diff --git a/lean/OAI/Combinatorics/Crossing/StraightChainIntersections.lean b/lean/OAI/Combinatorics/Crossing/StraightChainIntersections.lean new file mode 100644 index 0000000000000000000000000000000000000000..1e7fa54a15ffd1dd4e91847e691f1b6529947d85 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/StraightChainIntersections.lean @@ -0,0 +1,49 @@ +import OAI.Combinatorics.Crossing.DrawnEdgeChains + +namespace OAI + +noncomputable section +namespace Zarankiewicz.PolygonalChain +open scoped BigOperators +variable {O T : Set Plane} {a b c d : Plane} + +theorem intersection_single_right (P : PolygonalChain O a b) (hc : c ∈ T) (hcd : segment ℝ c d ⊆ T) : + polygonIntersection P.vertices (single T c d hc hcd).vertices P.pieces 1= + ∑ i ∈ Finset.range P.pieces, segmentCrossingSign (P.vertices i) (P.vertices (i+1)) c d := by + simp [polygonIntersection,single] + +theorem intersection_single_left (P : PolygonalChain O a b) (hc : c ∈ T) (hcd : segment ℝ c d ⊆ T) : + polygonIntersection (single T c d hc hcd).vertices P.vertices 1 P.pieces= + ∑ i ∈ Finset.range P.pieces, segmentCrossingSign c d (P.vertices i) (P.vertices (i+1)) := by + simp [polygonIntersection,single] + +theorem transverse_single_right (P : PolygonalChain O a b) (hc : c ∈ T) (hcd : segment ℝ c d ⊆ T) + (h : ∀ i : Fin P.pieces, SegmentPairTransverse (P.vertices i.val) (P.vertices (i.val+1)) c d) : + P.Transverse (single T c d hc hcd) := by + intro i j + have hj : j.val=0 := by have hj : j.val<1 := j.isLt; omega + simpa [single,hj] using h i + +theorem transverse_single_left (P : PolygonalChain O a b) (hc : c ∈ T) (hcd : segment ℝ c d ⊆ T) + (h : ∀ i : Fin P.pieces, SegmentPairTransverse c d (P.vertices i.val) (P.vertices (i.val+1))) : + (single T c d hc hcd).Transverse P := + P.transverse_swap _ (P.transverse_single_right hc hcd (fun i => segmentPairTransverse_swap _ _ _ _ (h i))) + +theorem intersection_single_right_zero (P : PolygonalChain O a b) (hc : c ∈ T) (hcd : segment ℝ c d ⊆ T) + (h : ∀ i : Fin P.pieces, ¬ ClosedSegmentsMeet (P.vertices i.val) (P.vertices (i.val+1)) c d) : + polygonIntersection P.vertices (single T c d hc hcd).vertices P.pieces 1=0 := by + rw [P.intersection_single_right] + apply Finset.sum_eq_zero + intro i hi + exact segmentCrossingSign_eq_zero_of_not_meet _ _ _ _ (h ⟨i,Finset.mem_range.mp hi⟩) + +theorem intersection_single_single (ha : a ∈ O) (hab : segment ℝ a b ⊆ O) + (hc : c ∈ T) (hcd : segment ℝ c d ⊆ T) : + polygonIntersection (single O a b ha hab).vertices (single T c d hc hcd).vertices 1 1= + segmentCrossingSign a b c d := by simp [polygonIntersection,single] + +end Zarankiewicz.PolygonalChain + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/StraightChainTransversality.lean b/lean/OAI/Combinatorics/Crossing/StraightChainTransversality.lean new file mode 100644 index 0000000000000000000000000000000000000000..f86e7105b91debf5f4cca4b7d61741b0445b7869 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/StraightChainTransversality.lean @@ -0,0 +1,30 @@ +import OAI.Combinatorics.Crossing.StraightChainIntersections + +namespace OAI + +noncomputable section +namespace Zarankiewicz.PolygonalChain +open scoped BigOperators +variable {O T : Set Plane} {a b c d : Plane} + +theorem transverse_single_single (ha : a ∈ O) (hab : segment ℝ a b ⊆ O) + (hc : c ∈ T) (hcd : segment ℝ c d ⊆ T) (h : SegmentPairTransverse a b c d) : + (single O a b ha hab).Transverse (single T c d hc hcd) := by + intro i j + have hi : i.val=0 := by have hh : i.val<1 := i.isLt; omega + have hj : j.val=0 := by have hh : j.val<1 := j.isLt; omega + simpa [single,hi,hj] using h + +theorem intersection_single_left_zero (P : PolygonalChain O a b) (hc : c ∈ T) (hcd : segment ℝ c d ⊆ T) + (h : ∀ i : Fin P.pieces, ¬ ClosedSegmentsMeet c d (P.vertices i.val) (P.vertices (i.val+1))) : + polygonIntersection (single T c d hc hcd).vertices P.vertices 1 P.pieces=0 := by + rw [P.intersection_single_left] + apply Finset.sum_eq_zero + intro i hi + exact segmentCrossingSign_eq_zero_of_not_meet _ _ _ _ (h ⟨i,Finset.mem_range.mp hi⟩) + +end Zarankiewicz.PolygonalChain + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/SubdivisionPointEndpoints.lean b/lean/OAI/Combinatorics/Crossing/SubdivisionPointEndpoints.lean new file mode 100644 index 0000000000000000000000000000000000000000..130f70dd5485f624815fd2977748811ae485d2b0 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/SubdivisionPointEndpoints.lean @@ -0,0 +1,34 @@ +import OAI.Combinatorics.Crossing.DrawingSubdivisionGraph + +namespace OAI + +noncomputable section +namespace Zarankiewicz +variable {m n : ℕ} {D : AdmissibleDrawing m n} + +theorem subdivision_point_endpoint (P : ∀ e, PolygonalParametrization (D.edge e)) + (x : Plane) (hpoint : ∀ e t, D.edge e t=x → t ∈ Set.range (P e).knot) + (e : BipartiteEdge m n) (i : Fin (P e).pieces) (hx : x ∈ (P e).pieceTrace i) : + x=D.edge e ((P e).knot i.castSucc) ∨ x=D.edge e ((P e).knot i.succ) := by + obtain ⟨t,ht⟩ := (P e).pieceTrace_subset_range i hx + obtain ⟨j,hj⟩ := hpoint e t ht + have he : D.edge e ((P e).knot j)=x := (congrArg (D.edge e) hj).trans ht + have hh := (P e).pieceTrace_knot_endpoint (D.edge_injective e) i j (he.symm ▸ hx) + simpa only [he] using hh + +theorem drawingSubdivisionGraph_point_endpoint (P : ∀ e, PolygonalParametrization (D.edge e)) + (x : Plane) (hpoint : ∀ e t, D.edge e t=x → t ∈ Set.range (P e).knot) + (a b : Plane) (hab : (drawingSubdivisionGraph P).Adj a b) (hx : x ∈ segment ℝ a b) : + x=a ∨ x=b := by + obtain ⟨hab,p,hp⟩ := hab + rcases hp with ⟨rfl,rfl⟩ | ⟨rfl,rfl⟩ + · exact subdivision_point_endpoint P x hpoint p.1 p.2 hx + · have hx' : x ∈ segment ℝ (drawingPieceStart P p) (drawingPieceEnd P p) := by + simpa only [segment_symm] using hx + exact (subdivision_point_endpoint P x hpoint p.1 p.2 hx').symm + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/SubdivisionSegments.lean b/lean/OAI/Combinatorics/Crossing/SubdivisionSegments.lean new file mode 100644 index 0000000000000000000000000000000000000000..011613ec775876894730faac8865591c716539b3 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/SubdivisionSegments.lean @@ -0,0 +1,91 @@ +import OAI.Combinatorics.Crossing.AffineSubdivisionRefinement + +namespace OAI + +noncomputable section +namespace Zarankiewicz.PolygonalParametrization +variable {a b : Plane} {γ : Path a b} + +def pieceTrace (P : PolygonalParametrization γ) (i : Fin P.pieces) : Set Plane := + segment ℝ (γ (P.knot i.castSucc)) (γ (P.knot i.succ)) + +theorem pieceTrace_parameter (P : PolygonalParametrization γ) (i : Fin P.pieces) + (x : Plane) (hx : x ∈ P.pieceTrace i) : + ∃ t : unitInterval, γ (intervalSegment (P.knot i.castSucc) (P.knot i.succ) t)=x := by + rw [pieceTrace,← Path.range_segment] at hx + obtain ⟨t,ht⟩ := hx + refine ⟨t,(P.affine i t).trans ?_⟩ + simpa only [Path.segment_apply,AffineMap.lineMap_apply_module,segmentPoint] using ht + +theorem pieceTrace_subset_range (P : PolygonalParametrization γ) (i : Fin P.pieces) : + P.pieceTrace i ⊆ Set.range γ := by + intro x hx + obtain ⟨t,ht⟩ := P.pieceTrace_parameter i x hx + exact ⟨intervalSegment (P.knot i.castSucc) (P.knot i.succ) t,ht⟩ + +theorem pieceTrace_knot_endpoint (P : PolygonalParametrization γ) (hγ : Function.Injective γ) + (i : Fin P.pieces) (j : Fin (P.pieces+1)) + (hx : γ (P.knot j) ∈ P.pieceTrace i) : + γ (P.knot j)=γ (P.knot i.castSucc) ∨ γ (P.knot j)=γ (P.knot i.succ) := by + obtain ⟨t,ht⟩ := P.pieceTrace_parameter i _ hx + by_cases ht0 : t=0 + · subst t + simpa [intervalSegment] using Or.inl ht.symm + by_cases ht1 : t=1 + · subst t + simpa [intervalSegment] using Or.inr ht.symm + have hmid := intervalSegment_strict_between (P.knot i.castSucc) (P.knot i.succ) t + (P.increasing (by change i.val < i.val+1; omega)) + ⟨lt_of_le_of_ne (show 0 ≤ t from t.property.1) (Ne.symm ht0), + lt_of_le_of_ne (show t ≤ 1 from t.property.2) ht1⟩ + have he := hγ ht + rw [he] at hmid + exact False.elim (strictMono_no_between_successors P.knot P.increasing i j hmid) + +theorem pieceTrace_other_piece_endpoint (P : PolygonalParametrization γ) (hγ : Function.Injective γ) + (i j : Fin P.pieces) (hij : i ≠ j) (x : Plane) + (hx : x ∈ P.pieceTrace i) (hy : x ∈ P.pieceTrace j) : + x=γ (P.knot i.castSucc) ∨ x=γ (P.knot i.succ) := by + obtain ⟨s,hs⟩ := P.pieceTrace_parameter i x hx + obtain ⟨t,ht⟩ := P.pieceTrace_parameter j x hy + by_cases hs0 : s=0 + · subst s + exact Or.inl (by simpa [intervalSegment] using hs.symm) + by_cases hs1 : s=1 + · subst s + exact Or.inr (by simpa [intervalSegment] using hs.symm) + have hsbetween := intervalSegment_strict_between (P.knot i.castSucc) (P.knot i.succ) s + (P.increasing (by change i.val < i.val+1; omega)) + ⟨lt_of_le_of_ne (show 0 ≤ s from s.property.1) (Ne.symm hs0), + lt_of_le_of_ne (show s ≤ 1 from s.property.2) hs1⟩ + have htbetween := intervalSegment_between (P.knot j.castSucc) (P.knot j.succ) t + (P.increasing.monotone (by change j.val ≤ j.val+1; omega)) + have he := hγ (hs.trans ht.symm) + rw [he] at hsbetween + rcases lt_or_gt_of_ne hij with hij | hji + · have hgap := P.increasing.monotone (show i.succ ≤ j.castSucc by change i.val+1 ≤ j.val; exact hij) + exact False.elim (hsbetween.2.not_ge (hgap.trans htbetween.1)) + · have hgap := P.increasing.monotone (show j.succ ≤ i.castSucc by change j.val+1 ≤ i.val; exact hji) + exact False.elim (hsbetween.1.not_ge (htbetween.2.trans hgap)) + +end Zarankiewicz.PolygonalParametrization +namespace Zarankiewicz +variable {m n : ℕ} + +theorem subdivision_mark_endpoint (D : AdmissibleDrawing m n) + (P : ∀ e, PolygonalParametrization (D.edge e)) + (hmark : ∀ e t, D.edge e t ∈ drawingMarks D.toFiniteIntersectionDrawing → t ∈ Set.range (P e).knot) + (e : BipartiteEdge m n) (i : Fin (P e).pieces) (x : Plane) + (hx : x ∈ (P e).pieceTrace i) (hm : x ∈ drawingMarks D.toFiniteIntersectionDrawing) : + x=D.edge e ((P e).knot i.castSucc) ∨ x=D.edge e ((P e).knot i.succ) := by + obtain ⟨t,ht⟩ := (P e).pieceTrace_subset_range i hx + obtain ⟨j,hj⟩ := hmark e t (ht.symm ▸ hm) + have he : D.edge e ((P e).knot j)=x := (congrArg (D.edge e) hj).trans ht + have hh := (P e).pieceTrace_knot_endpoint (D.edge_injective e) i j (he.symm ▸ hx) + simpa only [he] using hh + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/SublevelExtrema.lean b/lean/OAI/Combinatorics/Crossing/SublevelExtrema.lean new file mode 100644 index 0000000000000000000000000000000000000000..801cdfdeb185e0d8b528efc822282ac8b6031dfa --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/SublevelExtrema.lean @@ -0,0 +1,67 @@ +import OAI.Combinatorics.Crossing.FirstLastVisits + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +theorem sublevel_passage_extrema (f : ℝ → ℝ) (hf : Continuous f) (r τ : ℝ) + (hτ : τ ∈ Set.Icc (0 : ℝ) 1) (hvisit : f τ < r) : + ∃ a b : ℝ, a ∈ Set.Icc (0 : ℝ) 1 ∧ b ∈ Set.Icc (0 : ℝ) 1 ∧ + a ≤ τ ∧ τ ≤ b ∧ f a ≤ r ∧ f b ≤ r ∧ + (∀ t ∈ Set.Icc (0 : ℝ) 1, f t ≤ r → a ≤ t ∧ t ≤ b) ∧ + (0 < a → f a=r) ∧ (b < 1 → f b=r) ∧ + (0 < τ → a < τ) ∧ (τ < 1 → τ < b) := by + let S : Set ℝ := Set.Icc 0 1 ∩ {t | f t ≤ r} + have hS : IsCompact S := isCompact_Icc.inter_right (isClosed_le hf continuous_const) + have hτS : τ ∈ S := ⟨hτ,hvisit.le⟩ + obtain ⟨a,ha⟩ := hS.exists_isLeast ⟨τ,hτS⟩ + obtain ⟨b,hb⟩ := hS.exists_isGreatest ⟨τ,hτS⟩ + have hfa (ha0 : 0 < a) : f a=r := by + have hf0 : r < f 0 := by + apply lt_of_not_ge + intro h + have hh := ha.2 (show (0 : ℝ) ∈ S from ⟨⟨le_rfl,zero_le_one⟩,h⟩) + linarith + apply le_antisymm ha.1.2 + by_contra hn + have hlt : f a < r := lt_of_not_ge hn + obtain ⟨t,ht,he⟩ := intermediate_value_Icc' ha.1.1.1 hf.continuousOn ⟨hlt.le,hf0.le⟩ + have hmem : t ∈ S := ⟨⟨ht.1,ht.2.trans ha.1.1.2⟩,he.le⟩ + have hta : t=a := le_antisymm ht.2 (ha.2 hmem) + rw [hta] at he + exact hlt.ne he + have hfb (hb1 : b < 1) : f b=r := by + have hf1 : r < f 1 := by + apply lt_of_not_ge + intro h + have hh := hb.2 (show (1 : ℝ) ∈ S from ⟨⟨zero_le_one,le_rfl⟩,h⟩) + linarith + apply le_antisymm hb.1.2 + by_contra hn + have hlt : f b < r := lt_of_not_ge hn + obtain ⟨t,ht,he⟩ := intermediate_value_Icc hb.1.1.2 hf.continuousOn ⟨hlt.le,hf1.le⟩ + have hmem : t ∈ S := ⟨⟨hb.1.1.1.trans ht.1,ht.2⟩,he.le⟩ + have htb : t=b := le_antisymm (hb.2 hmem) ht.1 + rw [htb] at he + exact hlt.ne he + refine ⟨a,b,ha.1.1,hb.1.1,ha.2 hτS,hb.2 hτS,ha.1.2,hb.1.2, + fun t ht hh => ⟨ha.2 ⟨ht,hh⟩,hb.2 ⟨ht,hh⟩⟩,hfa,hfb,?_,?_⟩ + · intro ht0 + apply lt_of_le_of_ne (ha.2 hτS) + intro he + have h := hfa (he.symm ▸ ht0) + rw [he] at h + exact hvisit.ne h + · intro ht1 + apply lt_of_le_of_ne (hb.2 hτS) + intro he + have h := hfb (he ▸ ht1) + rw [← he] at h + exact hvisit.ne h + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/SubspaceIntersection.lean b/lean/OAI/Combinatorics/Crossing/SubspaceIntersection.lean new file mode 100644 index 0000000000000000000000000000000000000000..9da028062e4aaa7a003db158290e12e9f5458aad --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/SubspaceIntersection.lean @@ -0,0 +1,60 @@ +import OAI.Combinatorics.Crossing.StageDegreeBound +import OAI.Combinatorics.Crossing.DegreeCounting + +namespace OAI + +noncomputable section +namespace Zarankiewicz +open Module Submodule +open scoped BigOperators +variable {W : Type*} [AddCommGroup W] [Module ℝ W] [FiniteDimensional ℝ W] + +theorem subspace_intersection_bound (m : ℕ) (U V : Fin m → Submodule ℝ W) + (hUV : ∀ i, Disjoint (U i) (V i)) : + (∑ i, ∑ j, finrank ℝ ↥(U i ⊓ V j)) ≤ (m*m/4) * finrank ℝ W := by + let node : Fin m → ℝ := fun i => (i.val : ℝ) + have hn : Function.Injective node := by + intro i j hij + apply Fin.ext + dsimp only [node] at hij + exact_mod_cast hij + have ht : ∀ i, node i ≠ (-1 : ℝ) := by + intro i + have hnonneg : (0 : ℝ) ≤ node i := Nat.cast_nonneg i.val + linarith + let ell := columnIncrement U node ⊤ (-1) + have hsum : (∑ i, ∑ j, finrank ℝ ↥(U i ⊓ V j)) = + ∑ h ∈ Finset.range m, ∑ j, rankIncrement U node (V j) h := by + rw [Finset.sum_comm] + calc + (∑ j, ∑ i, finrank ℝ ↥(U i ⊓ V j)) = + ∑ j, ∑ h ∈ Finset.range m, rankIncrement U node (V j) h := by + apply Finset.sum_congr rfl + intro j hj + simpa only [Fintype.card_fin] using (interpolation_identity U node (V j) hn).symm + _ = _ := Finset.sum_comm + have hell : (∑ e ∈ Finset.range m, ell e) ≤ finrank ℝ W := by + change (∑ e ∈ Finset.range m, columnIncrement U node ⊤ (-1) e) ≤ _ + rw [sum_columnIncrement] + have he := Submodule.finrank_le (evaluationFiltration U node ⊤ (-1) m) + simpa using he + rw [hsum] + calc + (∑ h ∈ Finset.range m, ∑ j, rankIncrement U node (V j) h) ≤ + ∑ h ∈ Finset.range m, ∑ e ∈ Finset.range (h+1), e * ell e := by + apply Finset.sum_le_sum + intro h hh + exact stage_degree_bound U V node hn hUV (-1) ht h + _ ≤ (m*m/4) * finrank ℝ W := total_degree_cost_le ell m (finrank ℝ W) hell + +theorem lemma2_1 (m N : ℕ) (U V : Fin m → Submodule ℝ W) + (hN : finrank ℝ W = N) (hUV : ∀ i, U i ⊓ V i = ⊥) : + (∑ i, ∑ j, finrank ℝ ↥(U i ⊓ V j)) ≤ (m*m/4) * N := by + rw [← hN] + exact subspace_intersection_bound m U V (fun i => disjoint_iff.mpr (hUV i)) + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/SubspaceProjection.lean b/lean/OAI/Combinatorics/Crossing/SubspaceProjection.lean new file mode 100644 index 0000000000000000000000000000000000000000..fde3c43f1409231e4938d3d1f242bcc4abd17cf4 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/SubspaceProjection.lean @@ -0,0 +1,50 @@ +import Mathlib.LinearAlgebra.FiniteDimensional.Lemmas +import Mathlib.LinearAlgebra.Quotient.Basic +import Mathlib.Basic.Real.Basic +import Lean.Elab.Tactic.Omega + +namespace OAI + +noncomputable section +namespace Zarankiewicz +open Module Submodule +variable {W W' : Type*} [AddCommGroup W] [Module ℝ W] [FiniteDimensional ℝ W] +variable [AddCommGroup W'] [Module ℝ W'] + +theorem finrank_map_add_le (f : W →ₗ[ℝ] W') (E T : Submodule ℝ W) + (hTE : T ≤ E) (hTk : T ≤ LinearMap.ker f) : + finrank ℝ (E.map f) + finrank ℝ T ≤ finrank ℝ E := by + let g := f.comp E.subtype + have hk : T.comap E.subtype ≤ LinearMap.ker g := fun x hx => hTk hx + have hd := Submodule.finrank_mono hk + rw [(Submodule.comapSubtypeEquivOfLe hTE).finrank_eq] at hd + have hr := g.finrank_range_add_finrank_ker + have he : LinearMap.range g = E.map f := by + dsimp only [g] + rw [LinearMap.range_comp, Submodule.range_subtype] + rw [he] at hr + omega + +theorem finrank_map_of_disjoint + {W W' : Type*} [AddCommGroup W] [Module ℝ W] [FiniteDimensional ℝ W] + [AddCommGroup W'] [Module ℝ W'] + (f : W →ₗ[ℝ] W') (E : Submodule ℝ W) + (hE : Disjoint E (LinearMap.ker f)) : finrank ℝ (E.map f) = finrank ℝ E := by + let g := f.comp E.subtype + have hg : Function.Injective g := by + apply LinearMap.ker_eq_bot.mp + apply le_antisymm _ bot_le + intro x hx + have hm : x.val ∈ E ⊓ LinearMap.ker f := ⟨x.property, hx⟩ + rw [hE.eq_bot] at hm + exact (Submodule.mem_bot ℝ).mpr (Subtype.ext ((Submodule.mem_bot ℝ).mp hm)) + have hr := LinearMap.finrank_range_of_inj hg + change finrank ℝ (LinearMap.range (f.comp E.subtype)) = finrank ℝ E at hr + rw [LinearMap.range_comp, Submodule.range_subtype] at hr + exact hr + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/SurgeryCrossingContainment.lean b/lean/OAI/Combinatorics/Crossing/SurgeryCrossingContainment.lean new file mode 100644 index 0000000000000000000000000000000000000000..86b0ae53a26112f317caa099e3ae9ecfcf38ec2b --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/SurgeryCrossingContainment.lean @@ -0,0 +1,63 @@ +import OAI.Combinatorics.Crossing.SurgeryRouteIntersections +import OAI.Combinatorics.Crossing.ReplaceDrawingRangeCases +import OAI.Combinatorics.Crossing.DrawingRangeCrossings + +namespace OAI + +noncomputable section +namespace Zarankiewicz.PolygonalExterior +variable {m n : ℕ} {D : AdmissibleDrawing m n} {C : DrawingPassages D.toFiniteIntersectionDrawing} + (E : PolygonalExterior C) (v : BipartiteVertex m n → Plane) (hvinj : Function.Injective v) + (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) + (hdet : ∀ j (p q : C.PortsAt (C.vertexMark j)), p ≠ q → + det2 (C.portPoint p.val-v j) (C.portPoint q.val-v j) ≠ 0) + (P : ∀ e, PolygonalParametrization ((E.assembledAdmissible v hvinj hv hdet).edge e)) + {p q : C.InnerIndex} + +theorem adjacentSurgeryDrawing_crossings_subset + (Kp : ExteriorCrossingCut C P p) (Kq : ExteriorCrossingCut C P q) + (hpq : p ≠ q) (hm : C.innerMark p=C.innerMark q) (hadj : p.1.1=q.1.1 ∨ p.1.2=q.1.2) + (hcross : SegmentsCrossProperly (C.portPoint (C.incomingPort p)) (C.portPoint (C.outgoingPort p)) + (C.portPoint (C.incomingPort q)) (C.portPoint (C.outgoingPort q))) + (hemb : StraightEdgeEmbedding (crossingSurgeryGraph C P p q) id) : + crossingPoints (adjacentSurgeryDrawing Kp Kq hm hadj hv hemb) ⊆ + crossingPoints (E.assembledAdmissible v hvinj hv hdet).toContinuousDrawing := by + let B := (E.assembledAdmissible v hvinj hv hdet).toContinuousDrawing + let A := adjacentSurgeryDrawing Kp Kq hm hadj hv hemb + intro x hx + obtain ⟨e,f,hef,hxe,hxf⟩ := hx + have havoid : ∀ j, x ≠ B.vertex j := edgeInterior_not_vertex A e x hxe + have hpair (hx : x ∈ Set.range (adjacentSurgeryRouteP Kp Kq hm hadj)) + (hy : x ∈ Set.range (adjacentSurgeryRouteQ Kp Kq hm hadj)) : x ∈ crossingPoints B := by + have hh := E.adjacentSurgeryRoutes_meeting_each_other v hvinj hv hdet P Kp Kq hpq hm hadj hcross x hx hy + exact crossing_of_ranges_not_vertices B p.1 q.1 + (fun he => hpq (C.innerIndex_eq_of_edge_mark p q he hm)) x hh.1 hh.2 havoid + have hmixed (g : BipartiteEdge m n) (hgp : g ≠ p.1) (hgq : g ≠ q.1) + (hx : x ∈ Set.range (adjacentSurgeryRouteP Kp Kq hm hadj) ∨ + x ∈ Set.range (adjacentSurgeryRouteQ Kp Kq hm hadj)) + (hy : x ∈ Set.range (B.edge g)) : x ∈ crossingPoints B := by + rcases E.adjacentSurgeryRoutes_meeting_other v hvinj hv hdet P Kp Kq hpq hm hadj g hgp hgq x hx hy with h | h + · exact crossing_of_ranges_not_vertices B p.1 g (Ne.symm hgp) x h hy havoid + · exact crossing_of_ranges_not_vertices B q.1 g (Ne.symm hgq) x h hy havoid + have hcases (g : BipartiteEdge m n) (hg : x ∈ Set.range (A.edge g)) := + B.replaceTwoRoutes_range_cases p.1 q.1 (adjacentSurgeryRouteP Kp Kq hm hadj) + (adjacentSurgeryRouteQ Kp Kq hm hadj) g x hg + rcases hcases e (edgeInterior_subset_range A e hxe) with ⟨hep,hx⟩ | ⟨heq,hx⟩ | ⟨hep,heq,hx⟩ + · rcases hcases f (edgeInterior_subset_range A f hxf) with ⟨hfp,hy⟩ | ⟨hfq,hy⟩ | ⟨hfp,hfq,hy⟩ + · exact False.elim (hef (hep.trans hfp.symm)) + · exact hpair hx hy + · exact hmixed f hfp hfq (Or.inl hx) hy + · rcases hcases f (edgeInterior_subset_range A f hxf) with ⟨hfp,hy⟩ | ⟨hfq,hy⟩ | ⟨hfp,hfq,hy⟩ + · exact hpair hy hx + · exact False.elim (hef (heq.trans hfq.symm)) + · exact hmixed f hfp hfq (Or.inr hx) hy + · rcases hcases f (edgeInterior_subset_range A f hxf) with ⟨hfp,hy⟩ | ⟨hfq,hy⟩ | ⟨hfp,hfq,hy⟩ + · exact hmixed e hep heq (Or.inl hy) hx + · exact hmixed e hep heq (Or.inr hy) hx + · exact crossing_of_ranges_not_vertices B e f hef x hx hy havoid + +end Zarankiewicz.PolygonalExterior + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/SurgeryCutWalks.lean b/lean/OAI/Combinatorics/Crossing/SurgeryCutWalks.lean new file mode 100644 index 0000000000000000000000000000000000000000..bd724104b1afbdda7c420c6d8b9495169cd6c28e --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/SurgeryCutWalks.lean @@ -0,0 +1,47 @@ +import OAI.Combinatorics.Crossing.CrossingSurgeryGraph +import OAI.Combinatorics.Crossing.CrossingCutWalks +import OAI.Combinatorics.Crossing.GraphWalkRealizationLaws + +namespace OAI + +noncomputable section +namespace Zarankiewicz +variable {m n : ℕ} {D D' : AdmissibleDrawing m n} + +def surgeryPrefixWalk (C : DrawingPassages D.toFiniteIntersectionDrawing) + (P : ∀ e, PolygonalParametrization (D'.edge e)) (p q r : C.InnerIndex) + (i : ℕ) (hi : (drawingEdgeWalk P r.1).getVert i=C.portPoint (C.incomingPort r)) + (hout : Disjoint (Set.range (graphWalkPath id ((drawingEdgeWalk P r.1).take i))) (C.crossingDisk p)) : + (crossingSurgeryGraph C P p q).Walk (D'.vertex (.inl r.1.1)) (C.portPoint (C.incomingPort r)) := + ((exteriorGraphWalk ((drawingEdgeWalk P r.1).take i) (C.crossingDisk p) hout).mapLe + (exterior_le_crossingSurgeryGraph C P p q)).copy rfl hi + +def surgerySuffixWalk (C : DrawingPassages D.toFiniteIntersectionDrawing) + (P : ∀ e, PolygonalParametrization (D'.edge e)) (p q r : C.InnerIndex) + (j : ℕ) (hj : (drawingEdgeWalk P r.1).getVert j=C.portPoint (C.outgoingPort r)) + (hout : Disjoint (Set.range (graphWalkPath id ((drawingEdgeWalk P r.1).drop j))) (C.crossingDisk p)) : + (crossingSurgeryGraph C P p q).Walk (C.portPoint (C.outgoingPort r)) (D'.vertex (.inr r.1.2)) := + ((exteriorGraphWalk ((drawingEdgeWalk P r.1).drop j) (C.crossingDisk p) hout).mapLe + (exterior_le_crossingSurgeryGraph C P p q)).copy hj rfl + +theorem surgeryPrefixWalk_trace (C : DrawingPassages D.toFiniteIntersectionDrawing) + (P : ∀ e, PolygonalParametrization (D'.edge e)) (p q r : C.InnerIndex) + (i : ℕ) (hi : (drawingEdgeWalk P r.1).getVert i=C.portPoint (C.incomingPort r)) + (hout : Disjoint (Set.range (graphWalkPath id ((drawingEdgeWalk P r.1).take i))) (C.crossingDisk p)) : + Set.range (graphWalkPath id (surgeryPrefixWalk C P p q r i hi hout))= + Set.range (graphWalkPath id ((drawingEdgeWalk P r.1).take i)) := by + rw [surgeryPrefixWalk,graphWalkPath_copy_range,graphWalkPath_mapLe_range,exteriorGraphWalk_trace] + +theorem surgerySuffixWalk_trace (C : DrawingPassages D.toFiniteIntersectionDrawing) + (P : ∀ e, PolygonalParametrization (D'.edge e)) (p q r : C.InnerIndex) + (j : ℕ) (hj : (drawingEdgeWalk P r.1).getVert j=C.portPoint (C.outgoingPort r)) + (hout : Disjoint (Set.range (graphWalkPath id ((drawingEdgeWalk P r.1).drop j))) (C.crossingDisk p)) : + Set.range (graphWalkPath id (surgerySuffixWalk C P p q r j hj hout))= + Set.range (graphWalkPath id ((drawingEdgeWalk P r.1).drop j)) := by + rw [surgerySuffixWalk,graphWalkPath_copy_range,graphWalkPath_mapLe_range,exteriorGraphWalk_trace] + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/SurgeryFiniteDrawing.lean b/lean/OAI/Combinatorics/Crossing/SurgeryFiniteDrawing.lean new file mode 100644 index 0000000000000000000000000000000000000000..3c3d7bffb5688e59870d443cd77a31f78d116913 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/SurgeryFiniteDrawing.lean @@ -0,0 +1,42 @@ +import OAI.Combinatorics.Crossing.SurgeryNoTriples +import OAI.Combinatorics.Crossing.SurgeryStrictPointCount + +namespace OAI + +noncomputable section +namespace Zarankiewicz.PolygonalExterior +variable {m n : ℕ} {D : AdmissibleDrawing m n} {C : DrawingPassages D.toFiniteIntersectionDrawing} + (E : PolygonalExterior C) (v : BipartiteVertex m n → Plane) (hvinj : Function.Injective v) + (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) + (hdet : ∀ j (p q : C.PortsAt (C.vertexMark j)), p ≠ q → + det2 (C.portPoint p.val-v j) (C.portPoint q.val-v j) ≠ 0) + (P : ∀ e, PolygonalParametrization ((E.assembledAdmissible v hvinj hv hdet).edge e)) + {p q : C.InnerIndex} + +def adjacentSurgeryFiniteDrawing + (Kp : ExteriorCrossingCut C P p) (Kq : ExteriorCrossingCut C P q) + (hpq : p ≠ q) (hm : C.innerMark p=C.innerMark q) (hadj : p.1.1=q.1.1 ∨ p.1.2=q.1.2) + (hemb : StraightEdgeEmbedding (crossingSurgeryGraph C P p q) id) + (x : Plane) (hxp : x ∈ Set.range (C.crossingChord p)) (hxq : x ∈ Set.range (C.crossingChord q)) : + FiniteIntersectionDrawing m n where + toContinuousDrawing := adjacentSurgeryDrawing Kp Kq hm hadj hv hemb + crossings_finite := (E.adjacentSurgeryDrawing_strict_crossing_ncard v hvinj hv hdet P Kp Kq hpq hm hadj hemb x hxp hxq).1 + no_triples := E.adjacentSurgeryDrawing_no_triples v hvinj hv hdet P Kp Kq hpq hm hadj + (C.crossingChord_meeting_segmentsCrossProperly p q hpq x hxp hxq) hemb + +theorem adjacentSurgeryFiniteDrawing_count_lt + (Kp : ExteriorCrossingCut C P p) (Kq : ExteriorCrossingCut C P q) + (hpq : p ≠ q) (hm : C.innerMark p=C.innerMark q) (hadj : p.1.1=q.1.1 ∨ p.1.2=q.1.2) + (hemb : StraightEdgeEmbedding (crossingSurgeryGraph C P p q) id) + (x : Plane) (hxp : x ∈ Set.range (C.crossingChord p)) (hxq : x ∈ Set.range (C.crossingChord q)) : + finiteCrossingCount (E.adjacentSurgeryFiniteDrawing v hvinj hv hdet P Kp Kq hpq hm hadj hemb x hxp hxq) < + crossingCount (E.assembledAdmissible v hvinj hv hdet) := by + rw [finiteCrossingCount_eq_ncard] + have h := (E.adjacentSurgeryDrawing_strict_crossing_ncard v hvinj hv hdet P Kp Kq hpq hm hadj hemb x hxp hxq).2 + exact h.trans_eq (Set.ncard_eq_toFinset_card _ (E.assembledAdmissible v hvinj hv hdet).crossings_finite) + +end Zarankiewicz.PolygonalExterior + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/SurgeryNoTriples.lean b/lean/OAI/Combinatorics/Crossing/SurgeryNoTriples.lean new file mode 100644 index 0000000000000000000000000000000000000000..e7cc39caf19e20baed47c7e924406e56cef4d358 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/SurgeryNoTriples.lean @@ -0,0 +1,100 @@ +import OAI.Combinatorics.Crossing.SurgeryCrossingContainment + +namespace OAI + +noncomputable section +namespace Zarankiewicz.PolygonalExterior +variable {m n : ℕ} {D : AdmissibleDrawing m n} {C : DrawingPassages D.toFiniteIntersectionDrawing} + (E : PolygonalExterior C) (v : BipartiteVertex m n → Plane) (hvinj : Function.Injective v) + (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) + (hdet : ∀ j (p q : C.PortsAt (C.vertexMark j)), p ≠ q → + det2 (C.portPoint p.val-v j) (C.portPoint q.val-v j) ≠ 0) + (P : ∀ e, PolygonalParametrization ((E.assembledAdmissible v hvinj hv hdet).edge e)) + {p q : C.InnerIndex} + +theorem adjacentSurgeryDrawing_no_triples + (Kp : ExteriorCrossingCut C P p) (Kq : ExteriorCrossingCut C P q) + (hpq : p ≠ q) (hm : C.innerMark p=C.innerMark q) (hadj : p.1.1=q.1.1 ∨ p.1.2=q.1.2) + (hcross : SegmentsCrossProperly (C.portPoint (C.incomingPort p)) (C.portPoint (C.outgoingPort p)) + (C.portPoint (C.incomingPort q)) (C.portPoint (C.outgoingPort q))) + (hemb : StraightEdgeEmbedding (crossingSurgeryGraph C P p q) id) + (e f g : BipartiteEdge m n) (hef : e ≠ f) (heg : e ≠ g) (hfg : f ≠ g) : + edgeInterior (adjacentSurgeryDrawing Kp Kq hm hadj hv hemb) e ∩ + edgeInterior (adjacentSurgeryDrawing Kp Kq hm hadj hv hemb) f ∩ + edgeInterior (adjacentSurgeryDrawing Kp Kq hm hadj hv hemb) g = ∅ := by + let B := E.assembledAdmissible v hvinj hv hdet + let A := adjacentSurgeryDrawing Kp Kq hm hadj hv hemb + apply Set.eq_empty_iff_forall_notMem.mpr + intro x hx + obtain ⟨⟨hxe,hxf⟩,hxg⟩ := hx + have havoid : ∀ j, x ≠ B.vertex j := edgeInterior_not_vertex A e x hxe + have hthree (a b c : BipartiteEdge m n) (hab : a ≠ b) (hac : a ≠ c) (hbc : b ≠ c) + (ha : x ∈ Set.range (B.edge a)) (hb : x ∈ Set.range (B.edge b)) + (hc : x ∈ Set.range (B.edge c)) : False := by + have hmem : x ∈ edgeInterior B.toContinuousDrawing a ∩ edgeInterior B.toContinuousDrawing b ∩ + edgeInterior B.toContinuousDrawing c := + ⟨⟨edgeInterior_of_range_not_vertices _ a x ha havoid, + edgeInterior_of_range_not_vertices _ b x hb havoid⟩,edgeInterior_of_range_not_vertices _ c x hc havoid⟩ + rw [B.no_triples a b c hab hac hbc] at hmem + exact hmem + have htwo (a : BipartiteEdge m n) (hap : a ≠ p.1) (haq : a ≠ q.1) + (hp : x ∈ Set.range (adjacentSurgeryRouteP Kp Kq hm hadj)) + (hq : x ∈ Set.range (adjacentSurgeryRouteQ Kp Kq hm hadj)) + (ha : x ∈ Set.range (B.edge a)) : False := by + have hh := E.adjacentSurgeryRoutes_meeting_each_other v hvinj hv hdet P Kp Kq hpq hm hadj hcross x hp hq + exact hthree p.1 q.1 a (fun he => hpq (C.innerIndex_eq_of_edge_mark p q he hm)) + (Ne.symm hap) (Ne.symm haq) hh.1 hh.2 ha + have hone (a b : BipartiteEdge m n) (hab : a ≠ b) + (hap : a ≠ p.1) (haq : a ≠ q.1) (hbp : b ≠ p.1) (hbq : b ≠ q.1) + (hh : x ∈ Set.range (adjacentSurgeryRouteP Kp Kq hm hadj) ∨ + x ∈ Set.range (adjacentSurgeryRouteQ Kp Kq hm hadj)) + (ha : x ∈ Set.range (B.edge a)) (hb : x ∈ Set.range (B.edge b)) : False := by + rcases E.adjacentSurgeryRoutes_meeting_other v hvinj hv hdet P Kp Kq hpq hm hadj a hap haq x hh ha with hp | hq + · exact hthree p.1 a b (Ne.symm hap) (Ne.symm hbp) hab hp ha hb + · exact hthree q.1 a b (Ne.symm haq) (Ne.symm hbq) hab hq ha hb + have hcases (a : BipartiteEdge m n) (ha : x ∈ Set.range (A.edge a)) := + B.toContinuousDrawing.replaceTwoRoutes_range_cases p.1 q.1 (adjacentSurgeryRouteP Kp Kq hm hadj) + (adjacentSurgeryRouteQ Kp Kq hm hadj) a x ha + have hec := hcases e (edgeInterior_subset_range A e hxe) + have hfc := hcases f (edgeInterior_subset_range A f hxf) + have hgc := hcases g (edgeInterior_subset_range A g hxg) + rcases hec with ⟨hep,hx⟩ | ⟨heq,hx⟩ | ⟨hep,heq,hx⟩ + · rcases hfc with ⟨hfp,hy⟩ | ⟨hfq,hy⟩ | ⟨hfp,hfq,hy⟩ + · exact hef (hep.trans hfp.symm) + · rcases hgc with ⟨hgp,hz⟩ | ⟨hgq,hz⟩ | ⟨hgp,hgq,hz⟩ + · exact heg (hep.trans hgp.symm) + · exact hfg (hfq.trans hgq.symm) + · exact htwo g hgp hgq hx hy hz + · rcases hgc with ⟨hgp,hz⟩ | ⟨hgq,hz⟩ | ⟨hgp,hgq,hz⟩ + · exact heg (hep.trans hgp.symm) + · exact htwo f hfp hfq hx hz hy + · exact hone f g hfg hfp hfq hgp hgq (Or.inl hx) hy hz + · rcases hfc with ⟨hfp,hy⟩ | ⟨hfq,hy⟩ | ⟨hfp,hfq,hy⟩ + · rcases hgc with ⟨hgp,hz⟩ | ⟨hgq,hz⟩ | ⟨hgp,hgq,hz⟩ + · exact hfg (hfp.trans hgp.symm) + · exact heg (heq.trans hgq.symm) + · exact htwo g hgp hgq hy hx hz + · exact hef (heq.trans hfq.symm) + · rcases hgc with ⟨hgp,hz⟩ | ⟨hgq,hz⟩ | ⟨hgp,hgq,hz⟩ + · exact htwo f hfp hfq hz hx hy + · exact heg (heq.trans hgq.symm) + · exact hone f g hfg hfp hfq hgp hgq (Or.inr hx) hy hz + · rcases hfc with ⟨hfp,hy⟩ | ⟨hfq,hy⟩ | ⟨hfp,hfq,hy⟩ + · rcases hgc with ⟨hgp,hz⟩ | ⟨hgq,hz⟩ | ⟨hgp,hgq,hz⟩ + · exact hfg (hfp.trans hgp.symm) + · exact htwo e hep heq hy hz hx + · exact hone e g heg hep heq hgp hgq (Or.inl hy) hx hz + · rcases hgc with ⟨hgp,hz⟩ | ⟨hgq,hz⟩ | ⟨hgp,hgq,hz⟩ + · exact htwo e hep heq hz hy hx + · exact hfg (hfq.trans hgq.symm) + · exact hone e g heg hep heq hgp hgq (Or.inr hy) hx hz + · rcases hgc with ⟨hgp,hz⟩ | ⟨hgq,hz⟩ | ⟨hgp,hgq,hz⟩ + · exact hone e f hef hep heq hfp hfq (Or.inl hz) hx hy + · exact hone e f hef hep heq hfp hfq (Or.inr hz) hx hy + · exact hthree e f g hef heg hfg hx hy hz + +end Zarankiewicz.PolygonalExterior + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/SurgeryPathWitnesses.lean b/lean/OAI/Combinatorics/Crossing/SurgeryPathWitnesses.lean new file mode 100644 index 0000000000000000000000000000000000000000..1543d1a75655eabbbc58738f8e46e713048ab893 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/SurgeryPathWitnesses.lean @@ -0,0 +1,41 @@ +import OAI.Combinatorics.Crossing.SurgeryCutWalks + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +def walkThroughChord {G : SimpleGraph Plane} {a u v b : Plane} + (A : G.Walk a u) (h : G.Adj u v) (B : G.Walk v b) : G.Walk a b := + (A.append h.toWalk).append B + +theorem walkThroughChord_range {G : SimpleGraph Plane} {a u v b : Plane} + (A : G.Walk a u) (h : G.Adj u v) (B : G.Walk v b) : + Set.range (graphWalkPath id (walkThroughChord A h B))= + (Set.range (graphWalkPath id A) ∪ segment ℝ u v) ∪ Set.range (graphWalkPath id B) := by + rw [walkThroughChord,graphWalkPath_append_range,graphWalkPath_append_range,graphWalkPath_toWalk_range] + +theorem exists_simple_path_through_chord {G : SimpleGraph Plane} + (hemb : StraightEdgeEmbedding G id) {a u v b : Plane} (hab : a ≠ b) + (A : G.Walk a u) (h : G.Adj u v) (B : G.Walk v b) : + ∃ γ : Path a b, Function.Injective γ ∧ HasFiniteAffineCover γ ∧ + Set.range γ ⊆ (Set.range (graphWalkPath id A) ∪ segment ℝ u v) ∪ Set.range (graphWalkPath id B) := by + classical + let p := walkThroughChord A h B + refine ⟨graphWalkPath id p.bypass, + graphWalkPath_injective id hemb hab p.bypass p.bypass_isPath, + graphWalkPath_hasFiniteAffineCover id p.bypass,?_⟩ + exact (graphWalkPath_bypass_range_subset id p).trans (by rw [walkThroughChord_range]) + +variable {m n : ℕ} {D D' : AdmissibleDrawing m n} + +theorem surgery_mixed_endpoints_ne (C : DrawingPassages D.toFiniteIntersectionDrawing) + (p q : C.InnerIndex) : D'.vertex (.inl p.1.1) ≠ D'.vertex (.inr q.1.2) := by + intro h + cases D'.vertex_injective h + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/SurgeryRouteIntersections.lean b/lean/OAI/Combinatorics/Crossing/SurgeryRouteIntersections.lean new file mode 100644 index 0000000000000000000000000000000000000000..fb35b9b1ff6f29d1064880e8b3bc56a106401fb0 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/SurgeryRouteIntersections.lean @@ -0,0 +1,78 @@ +import OAI.Combinatorics.Crossing.ReconnectedIntersectionCases + +namespace OAI + +noncomputable section +namespace Zarankiewicz.PolygonalExterior +variable {m n : ℕ} {D : AdmissibleDrawing m n} {C : DrawingPassages D.toFiniteIntersectionDrawing} + (E : PolygonalExterior C) (v : BipartiteVertex m n → Plane) (hvinj : Function.Injective v) + (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) + (hdet : ∀ j (p q : C.PortsAt (C.vertexMark j)), p ≠ q → + det2 (C.portPoint p.val-v j) (C.portPoint q.val-v j) ≠ 0) + (P : ∀ e, PolygonalParametrization ((E.assembledAdmissible v hvinj hv hdet).edge e)) + {p q : C.InnerIndex} + +theorem reconnectedForwardPath_meeting_other + (Kp : ExteriorCrossingCut C P p) (Kq : ExteriorCrossingCut C P q) + (hpq : p ≠ q) (hm : C.innerMark p=C.innerMark q) + (e : BipartiteEdge m n) (hep : e ≠ p.1) (heq : e ≠ q.1) + (x : Plane) (hx : x ∈ Set.range (reconnectedForwardPath Kp Kq hm)) + (hy : x ∈ Set.range (E.assembledEdge v e)) : + x ∈ Set.range (E.assembledEdge v p.1) ∨ x ∈ Set.range (E.assembledEdge v q.1) := by + rcases reconnectedForwardPath_trace Kp Kq hm hx with (hx | hx) | hx + · exact Or.inl (Kp.prefix_subset_edge hx) + · exact False.elim (Set.disjoint_left.mp (E.reconnection_other_edge_disjoint v hv p q hpq hm true e hep heq) hx hy) + · exact Or.inr (Kq.suffix_subset_edge hx) + +theorem reconnectedBackwardPath_meeting_other + (Kp : ExteriorCrossingCut C P p) (Kq : ExteriorCrossingCut C P q) + (hpq : p ≠ q) (hm : C.innerMark p=C.innerMark q) + (e : BipartiteEdge m n) (hep : e ≠ p.1) (heq : e ≠ q.1) + (x : Plane) (hx : x ∈ Set.range (reconnectedBackwardPath Kp Kq hm)) + (hy : x ∈ Set.range (E.assembledEdge v e)) : + x ∈ Set.range (E.assembledEdge v p.1) ∨ x ∈ Set.range (E.assembledEdge v q.1) := by + rcases reconnectedBackwardPath_trace Kp Kq hm hx with (hx | hx) | hx + · exact Or.inr (Kq.prefix_subset_edge hx) + · exact False.elim (Set.disjoint_left.mp (E.reconnection_other_edge_disjoint v hv p q hpq hm false e hep heq) hx hy) + · exact Or.inl (Kp.suffix_subset_edge hx) + +theorem adjacentSurgeryRoutes_meeting_other + (Kp : ExteriorCrossingCut C P p) (Kq : ExteriorCrossingCut C P q) + (hpq : p ≠ q) (hm : C.innerMark p=C.innerMark q) (hadj : p.1.1=q.1.1 ∨ p.1.2=q.1.2) + (e : BipartiteEdge m n) (hep : e ≠ p.1) (heq : e ≠ q.1) + (x : Plane) (hx : x ∈ Set.range (adjacentSurgeryRouteP Kp Kq hm hadj) ∨ + x ∈ Set.range (adjacentSurgeryRouteQ Kp Kq hm hadj)) + (hy : x ∈ Set.range (E.assembledEdge v e)) : + x ∈ Set.range (E.assembledEdge v p.1) ∨ x ∈ Set.range (E.assembledEdge v q.1) := by + have hf := E.reconnectedForwardPath_meeting_other v hvinj hv hdet P Kp Kq hpq hm e hep heq x + have hb := E.reconnectedBackwardPath_meeting_other v hvinj hv hdet P Kp Kq hpq hm e hep heq x + rcases hx with hx | hx + · unfold adjacentSurgeryRouteP at hx + split at hx + · exact hb hx hy + · exact hf hx hy + · unfold adjacentSurgeryRouteQ at hx + split at hx + · exact hf hx hy + · exact hb hx hy + +theorem adjacentSurgeryRoutes_meeting_each_other + (Kp : ExteriorCrossingCut C P p) (Kq : ExteriorCrossingCut C P q) + (hpq : p ≠ q) (hm : C.innerMark p=C.innerMark q) (hadj : p.1.1=q.1.1 ∨ p.1.2=q.1.2) + (hcross : SegmentsCrossProperly (C.portPoint (C.incomingPort p)) (C.portPoint (C.outgoingPort p)) + (C.portPoint (C.incomingPort q)) (C.portPoint (C.outgoingPort q))) + (x : Plane) (hx : x ∈ Set.range (adjacentSurgeryRouteP Kp Kq hm hadj)) + (hy : x ∈ Set.range (adjacentSurgeryRouteQ Kp Kq hm hadj)) : + x ∈ Set.range (E.assembledEdge v p.1) ∧ x ∈ Set.range (E.assembledEdge v q.1) := by + have hh := E.reconnected_paths_meeting_old_edges v hvinj hv hdet P Kp Kq hpq hm hcross x + by_cases h : p.1.1=q.1.1 + · simp only [adjacentSurgeryRouteP,adjacentSurgeryRouteQ,dite_eq_left h] at hx hy + exact hh hy hx + · simp only [adjacentSurgeryRouteP,adjacentSurgeryRouteQ,dite_eq_right h] at hx hy + exact hh hx hy + +end Zarankiewicz.PolygonalExterior + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/SurgeryStrictPointCount.lean b/lean/OAI/Combinatorics/Crossing/SurgeryStrictPointCount.lean new file mode 100644 index 0000000000000000000000000000000000000000..15130ccfbdecbf19520f9029d39566a7b12a03ee --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/SurgeryStrictPointCount.lean @@ -0,0 +1,56 @@ +import OAI.Combinatorics.Crossing.SurgeryCrossingContainment +import Mathlib.Data.Set.Card + +namespace OAI + +noncomputable section +namespace Zarankiewicz.PolygonalExterior +variable {m n : ℕ} {D : AdmissibleDrawing m n} {C : DrawingPassages D.toFiniteIntersectionDrawing} + (E : PolygonalExterior C) (v : BipartiteVertex m n → Plane) (hvinj : Function.Injective v) + (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) + (hdet : ∀ j (p q : C.PortsAt (C.vertexMark j)), p ≠ q → + det2 (C.portPoint p.val-v j) (C.portPoint q.val-v j) ≠ 0) + {p q : C.InnerIndex} + +theorem crossingChord_meeting_is_assembled_crossing (hpq : p ≠ q) (x : Plane) + (hxp : x ∈ Set.range (C.crossingChord p)) (hxq : x ∈ Set.range (C.crossingChord q)) : + x ∈ crossingPoints (E.assembledAdmissible v hvinj hv hdet).toContinuousDrawing := by + have hm := C.chord_meeting_marks_eq p q hxp hxq + have hxin := (C.reconnection_avoids_chord_meeting p q hpq x hxp hxq).1 + have hxinq : x ∈ C.crossingDisk q := by + simpa only [DrawingPassages.crossingDisk,hm] using hxin + apply crossing_of_ranges_not_vertices (E.assembledAdmissible v hvinj hv hdet).toContinuousDrawing + p.1 q.1 (fun he => hpq (C.innerIndex_eq_of_edge_mark p q he hm)) x + ((E.assembled_range_in_crossingDisk v hv p x hxin).mpr hxp) + ((E.assembled_range_in_crossingDisk v hv q x hxinq).mpr hxq) + intro j he + exact Set.disjoint_left.mp (C.crossingDisk_disjoint_vertex_disk p j) hxin (he.symm ▸ (hv j).le) + +theorem adjacentSurgeryDrawing_strict_crossing_ncard + (P : ∀ e, PolygonalParametrization ((E.assembledAdmissible v hvinj hv hdet).edge e)) + (Kp : ExteriorCrossingCut C P p) (Kq : ExteriorCrossingCut C P q) + (hpq : p ≠ q) (hm : C.innerMark p=C.innerMark q) (hadj : p.1.1=q.1.1 ∨ p.1.2=q.1.2) + (hemb : StraightEdgeEmbedding (crossingSurgeryGraph C P p q) id) + (x : Plane) (hxp : x ∈ Set.range (C.crossingChord p)) (hxq : x ∈ Set.range (C.crossingChord q)) : + (crossingPoints (adjacentSurgeryDrawing Kp Kq hm hadj hv hemb)).Finite ∧ + (crossingPoints (adjacentSurgeryDrawing Kp Kq hm hadj hv hemb)).ncard < + (crossingPoints (E.assembledAdmissible v hvinj hv hdet).toContinuousDrawing).ncard := by + have hcross := C.crossingChord_meeting_segmentsCrossProperly p q hpq x hxp hxq + have hsub := E.adjacentSurgeryDrawing_crossings_subset v hvinj hv hdet P Kp Kq hpq hm hadj hcross hemb + have hfinite := (E.assembledAdmissible v hvinj hv hdet).crossings_finite + have hremoved := adjacentSurgeryDrawing_avoids_crossing Kp Kq hm hpq hadj hv hemb x hxp hxq (by + intro e hep heq hx + exact Set.disjoint_left.mp (E.assembled_other_edge_avoids_crossingDisk v hv p q hpq hm e hep heq) + hx (C.reconnection_avoids_chord_meeting p q hpq x hxp hxq).1) + have hnot : x ∉ crossingPoints (adjacentSurgeryDrawing Kp Kq hm hadj hv hemb) := by + rintro ⟨e,f,hef,hxe,hxf⟩ + exact hremoved e (edgeInterior_subset_range _ e hxe) + refine ⟨hfinite.subset hsub,Set.ncard_lt_ncard ⟨hsub,?_⟩ hfinite⟩ + intro hrev + exact hnot (hrev (E.crossingChord_meeting_is_assembled_crossing v hvinj hv hdet hpq x hxp hxq)) + +end Zarankiewicz.PolygonalExterior + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/TangentTrackIdentity.lean b/lean/OAI/Combinatorics/Crossing/TangentTrackIdentity.lean new file mode 100644 index 0000000000000000000000000000000000000000..37dad696f90c185aa6de88523040607667797933 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/TangentTrackIdentity.lean @@ -0,0 +1,66 @@ +import OAI.Combinatorics.Crossing.CircleOffsetLine +import OAI.Combinatorics.Crossing.CircleConnectors + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +theorem det2_rotateQuarter_self (d : Plane) : det2 d (rotateQuarter d)=squaredLength d := by + dsimp [det2,rotateQuarter,squaredLength] + ring + +theorem normalShift_eq_circleTrackScale (d w : Plane) (hd : d ≠ 0) (hw : w ≠ 0) + (hpar : det2 d w=0) : normalShift d=circleTrackScale d w • rotateQuarter w := by + let c := dot2 d w/squaredLength d + have hp : w=c • d := vector_parallel_of_det_zero d w hd hpar + have hc : c ≠ 0 := by + intro h + rw [h,zero_smul] at hp + exact hw hp + have hrot : rotateQuarter w=c • rotateQuarter d := by + rw [hp] + apply Prod.ext + · dsimp [rotateQuarter] + ring + · rfl + have hL := ne_of_gt (squaredLength_pos d hd) + unfold normalShift circleTrackScale + rw [hrot,det2_smul_right,det2_rotateQuarter_self,smul_smul] + congr 1 + field_simp + +theorem similarity_circleTangentOffset (o u v : Plane) (δ : ℝ) : + similarityPoint o u (circleTangentOffset v δ)= + similarityPoint o u v+δ • rotateQuarter (similarityPoint o u v-o) := by + apply Prod.ext <;> dsimp [similarityPoint,circleTangentOffset,rotateQuarter] <;> ring + +theorem tangentOffset_eq_normalShift (o u v d : Plane) (hd : d ≠ 0) + (hw : similarityPoint o u v-o ≠ 0) (hpar : det2 d (similarityPoint o u v-o)=0) + (ε : ℝ) : + similarityPoint o u (circleTangentOffset v (circleTrackScale d (similarityPoint o u v-o)*ε))= + similarityPoint o u v+ε • normalShift d := by + rw [similarity_circleTangentOffset,normalShift_eq_circleTrackScale d _ hd hw hpar,smul_smul] + congr 2 + ring + +theorem similarityPoint_squaredLength (o u x : Plane) : + squaredLength (similarityPoint o u x-o)=squaredLength u*squaredLength x := by + dsimp [similarityPoint,squaredLength] + ring + +theorem physical_circleConnector_strictly_outside (o u v : Plane) (hu : u ≠ 0) + (hv : squaredLength v=1) (δ : ℝ) (hδ : |δ|<1) (hne : δ ≠ 0) + (t : ℝ) (ht : 0 norm_num + filter_upwards [eventually_segmentCrossingSign_of_proper a b c d hc] with ab hab + apply segmentPairTransverse_of_proper + by_contra hn + have hz : segmentCrossingSign ab.1 ab.2 c d = 0 := by simp [segmentCrossingSign,hn] + exact hsign (hab.symm.trans hz) + · have hn : ¬ ClosedSegmentsMeet a b c d := by + rintro ⟨t,ht,u,hu,he⟩ + obtain ⟨hd,ht',hu'⟩ := h t ht u hu he + exact hc ⟨hd,t,ht',u,hu',he⟩ + have hevent := (isClosed_closedSegmentsMeet c d).isOpen_compl.mem_nhds + (show (a,b) ∈ {ab : Plane × Plane | ClosedSegmentsMeet ab.1 ab.2 c d}ᶜ from hn) + filter_upwards [hevent] with ab hab + intro t ht u hu he + exact False.elim (hab ⟨t,ht,u,hu,he⟩) + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/TransversePolygonIntersection.lean b/lean/OAI/Combinatorics/Crossing/TransversePolygonIntersection.lean new file mode 100644 index 0000000000000000000000000000000000000000..e15042d494da65bd6f4fd76ac5ea94a08b4f1959 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/TransversePolygonIntersection.lean @@ -0,0 +1,56 @@ +import OAI.Combinatorics.Crossing.GenericPolygonIntersection +import OAI.Combinatorics.Crossing.GenericPointFamily +import OAI.Combinatorics.Crossing.PolygonStability +import OAI.Combinatorics.Crossing.PeriodicPolygon + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +theorem segmentCrossingSign_self_left (a c d : Plane) : segmentCrossingSign a a c d = 0 := by + simp [segmentCrossingSign,SegmentsCrossProperly,det2] + +theorem polygon_intersection_zero_transverse (v w : ℕ → Plane) (n m : ℕ) + (hc : v n=v 0) (hd : w m=w 0) + (hw : ∀ j : Fin m, w (j.val+1) ≠ w j.val) + (ht : ∀ i : Fin n, ∀ j : Fin m, + SegmentPairTransverse (v i.val) (v (i.val+1)) (w j.val) (w (j.val+1))) : + polygonIntersection v w n m = 0 := by + by_cases hn : 1 w j.val) (fun j : Fin m => w j.val) + (fun j : Fin m => w (j.val+1)-w j.val) (fun j => sub_ne_zero.mpr (hw j)) + n (fun i => v i.val) (fun _ => ε) (fun _ => hε) + let v' := periodicPolygon n hn0 p + have hclose : v' n=v' 0 := periodicPolygon_closed n hn0 p + have hv' (i : Fin n) : v' (i.val+1) ≠ v' i.val := + hinj.ne (cyclicIndex_succ_ne n hn i) + have hpoint (i : Fin (n+1)) (j : Fin (m+1)) : w j.val ≠ v' i.val := hpq _ j + have hposition : PolygonLinePosition v' w n m := by + refine ⟨?_,?_,?_⟩ + · intro i j + exact hpar _ _ (Ne.symm (cyclicIndex_succ_ne n hn i)) j + · intro i j + change det2 (w (j.val+1)-w j.val) (p (cyclicIndex n hn0 i.val)-w j.val) ≠ 0 + rw [det2_swap] + exact neg_ne_zero.mpr (hline _ j) + · intro i j + exact hcorn _ _ (Ne.symm (cyclicIndex_succ_ne n hn i)) j + have hzero := polygon_intersection_zero_in_line_position v' w n m hclose hd hv' hw hpoint hposition + have heq := hstable v' (periodicPolygon_near n hn0 v hc p ε hnear) + rwa [heq] at hzero + · have hn' : n=0 ∨ n=1 := by omega + rcases hn' with rfl | rfl + · simp [polygonIntersection] + · simp only [polygonIntersection,Finset.sum_range_one] + rw [hc] + simp only [segmentCrossingSign_self_left,Finset.sum_const_zero] + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/TriangleEntryExit.lean b/lean/OAI/Combinatorics/Crossing/TriangleEntryExit.lean new file mode 100644 index 0000000000000000000000000000000000000000..366152c1abd69c04f7a318090a7f6075c9fd7b58 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/TriangleEntryExit.lean @@ -0,0 +1,71 @@ +import OAI.Combinatorics.Crossing.TriangleSideEvent +import OAI.Combinatorics.Crossing.SortedSideEvents +import OAI.Combinatorics.Crossing.PolygonalWalks +import Mathlib.Tactic.FinCases + +namespace OAI + +noncomputable section +namespace Zarankiewicz +open scoped BigOperators Classical + +def triangleStart (a b c : Plane) : Fin 3 → Plane := ![a,b,c] +def triangleEnd (a b c : Plane) : Fin 3 → Plane := ![b,c,a] +def triangleIndicator (a b c z : Plane) : ℝ := + ∏ i : Fin 3, positiveIndicator (orient2 (triangleStart a b c i) (triangleEnd a b c i) z) + +theorem triangle_area_cycle (a b c : Plane) : orient2 b c a = orient2 a b c := by + dsimp [orient2,det2] + ring + +theorem affine_side_factor (a b c d : Plane) (hn : det2 (b-a) (d-c) ≠ 0) (t : ℝ) : + orient2 a b (segmentPoint c d t) = + det2 (b-a) (d-c) * (t-secondIntersectionParameter a b c d) := by + rw [orient2_segment] + change (1-t)*orient2 a b c+t*orient2 a b d = + det2 (b-a) (d-c)*(t-(-orient2 a b c / det2 (b-a) (d-c))) + field_simp + linear_combination t * (orient2_difference a b c d) + +theorem triangle_segment_entry_exit (a b c d e : Plane) + (harea : 0 < orient2 a b c) + (hn : ∀ i : Fin 3, det2 (triangleEnd a b c i-triangleStart a b c i) (e-d) ≠ 0) + (hr : Function.Injective (fun i : Fin 3 => + secondIntersectionParameter (triangleStart a b c i) (triangleEnd a b c i) d e)) + (h0 : ∀ i : Fin 3, secondIntersectionParameter (triangleStart a b c i) (triangleEnd a b c i) d e ≠ 0) + (h1 : ∀ i : Fin 3, secondIntersectionParameter (triangleStart a b c i) (triangleEnd a b c i) d e ≠ 1) : + triangleSegmentIntersection a b c d e = triangleIndicator a b c e-triangleIndicator a b c d := by + let r := fun i : Fin 3 => secondIntersectionParameter (triangleStart a b c i) (triangleEnd a b c i) d e + let b' := fun i : Fin 3 => det2 (triangleEnd a b c i-triangleStart a b c i) (e-d) + have hf (i : Fin 3) (t : ℝ) : b' i*(t-r i) = + orient2 (triangleStart a b c i) (triangleEnd a b c i) (segmentPoint d e t) := + (affine_side_factor _ _ d e (hn i) t).symm + have hc1 : 0 < orient2 b c a := by rwa [triangle_area_cycle] + have hc2 : 0 < orient2 c a b := by rwa [triangle_area_cycle,triangle_area_cycle] + have hs (i : Fin 3) : + segmentCrossingSign (triangleStart a b c i) (triangleEnd a b c i) d e = + if 0 triangleCoefficient s p q) = + ∑ j : BiExponent s, + let pq := triangleNodePair s (triangleCoordEquiv s j) + triangleCoefficient s pq.1 pq.2 • detectorAtom s node pq.1 pq.2 := by + let f := fun pq : OrderedNode s × OrderedNode s => + triangleCoefficient s pq.1 pq.2 • detectorAtom s node pq.1 pq.2 + have hfull : rankDetector s node (fun p q => triangleCoefficient s p q) = ∑ pq, f pq := + (Fintype.sum_prod_type f).symm + have hfilter : (∑ pq ∈ orderedTriangle s, f pq) = ∑ pq, f pq := by + apply Finset.sum_subset (Finset.filter_subset _ _) + intro pq hpq hnot + have hm : (pq.1.val,pq.2.val) ∉ twoTriangle s := by simpa [orderedTriangle] using hnot + have hz : triangleCoefficient s pq.1 pq.2 = 0 := + not_ne_iff.mp (mt (triangleCoefficient_ne_zero_iff s pq.1 pq.2).mp hm) + simp only [f, hz, zero_smul] + rw [hfull, ← hfilter, ← Finset.sum_coe_sort] + exact ((triangleCoordEquiv s).trans (triangleNodeEquiv s)).sum_comp + (fun pq : ↥(orderedTriangle s) => f pq.val) |>.symm + +theorem rankDetector_triangle_factorization (s : ℕ) (node : OrderedNode s → ℝ) : + rankDetector s node (fun p q => triangleCoefficient s p q) = + triangleMatrix s (extendOrderedNode s node) * Matrix.diagonal (triangleDiagonalWeight s node) * + (triangleMatrix s (extendOrderedNode s node)).transpose := by + rw [rankDetector_triangle_sum, weightedGram_eq_sum] + apply Finset.sum_congr rfl + intro j hj + simp only [triangleDiagonalWeight, detectorAtom, smul_smul] + congr 2 + · funext ab + exact (triangleMatrix_ordered_entry s node ab j).symm + · funext ab + exact (triangleMatrix_ordered_entry s node ab j).symm + +theorem rankDetector_ordered_isUnit (s : ℕ) (node : OrderedNode s → ℝ) + (hn : Function.Injective node) : + IsUnit (rankDetector s node (halfOrderMatrix (OrderedNode s))) := by + rw [rankDetector_halfOrder_reduction s node hn] + apply IsUnit.neg + change IsUnit (rankDetector s node (fun p q => triangleCoefficient s p q)) + rw [rankDetector_triangle_factorization] + exact weightedGram_isUnit _ _ + (triangleMatrix_isUnit s (extendOrderedNode s node) (extendOrderedNode_injOn s node hn)) + (triangleDiagonalWeight_ne_zero s node hn) + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/TriangleOrientations.lean b/lean/OAI/Combinatorics/Crossing/TriangleOrientations.lean new file mode 100644 index 0000000000000000000000000000000000000000..1c698960b33cf310d74e21f83e7a50e76187d39b --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/TriangleOrientations.lean @@ -0,0 +1,90 @@ +import OAI.Combinatorics.Crossing.TriangleTransversality + +namespace OAI + +noncomputable section +namespace Zarankiewicz +open scoped BigOperators Classical + +theorem orient2_reverse_edge (a b c : Plane) : orient2 b a c = -orient2 a b c := by + dsimp [orient2,det2] + ring + +theorem det2_reverse_edge (a b c d : Plane) : det2 (a-b) (d-c) = -det2 (b-a) (d-c) := by + dsimp [det2] + ring + +theorem triangle_position_reverse (a b c d e : Plane) + (h : TriangleSegmentPosition a b c d e) : TriangleSegmentPosition a c b d e := by + refine ⟨?_,?_,?_⟩ + · intro i + fin_cases i + · change det2 (c-a) (e-d) ≠ 0 + rw [det2_reverse_edge c a d e] + exact neg_ne_zero.mpr (h.1 2) + · change det2 (b-c) (e-d) ≠ 0 + rw [det2_reverse_edge b c d e] + exact neg_ne_zero.mpr (h.1 1) + · change det2 (a-b) (e-d) ≠ 0 + rw [det2_reverse_edge a b d e] + exact neg_ne_zero.mpr (h.1 0) + · intro i + fin_cases i + · exact h.2.1 0 + · exact h.2.1 2 + · exact h.2.1 1 + · intro i + fin_cases i + · change orient2 a c d ≠ 0 ∧ orient2 a c e ≠ 0 + rw [orient2_reverse_edge c a d,orient2_reverse_edge c a e] + exact ⟨neg_ne_zero.mpr (h.2.2 2).1,neg_ne_zero.mpr (h.2.2 2).2⟩ + · change orient2 c b d ≠ 0 ∧ orient2 c b e ≠ 0 + rw [orient2_reverse_edge b c d,orient2_reverse_edge b c e] + exact ⟨neg_ne_zero.mpr (h.2.2 1).1,neg_ne_zero.mpr (h.2.2 1).2⟩ + · change orient2 b a d ≠ 0 ∧ orient2 b a e ≠ 0 + rw [orient2_reverse_edge a b d,orient2_reverse_edge a b e] + exact ⟨neg_ne_zero.mpr (h.2.2 0).1,neg_ne_zero.mpr (h.2.2 0).2⟩ + +theorem triangle_intersection_reverse (a b c d e : Plane) : + triangleSegmentIntersection a c b d e = -triangleSegmentIntersection a b c d e := by + unfold triangleSegmentIntersection + rw [segmentCrossingSign_reverse_left c a d e, + segmentCrossingSign_reverse_left b c d e,segmentCrossingSign_reverse_left a b d e] + ring + +def orientedTriangleIndicator (a b c z : Plane) : ℝ := + if 0 < orient2 a b c then triangleIndicator a b c z else -triangleIndicator a c b z + +theorem oriented_triangle_entry_exit (a b c d e : Plane) (ha : orient2 a b c ≠ 0) + (h : TriangleSegmentPosition a b c d e) : + triangleSegmentIntersection a b c d e = + orientedTriangleIndicator a b c e-orientedTriangleIndicator a b c d := by + rcases lt_or_gt_of_ne ha with ha | ha + · have hac : 0 < orient2 a c b := by + rw [triangle_area_cycle b a c,orient2_reverse_edge] + exact neg_pos.mpr ha + have hh := triangle_segment_entry_exit_of_position a c b d e hac (triangle_position_reverse a b c d e h) + rw [triangle_intersection_reverse] at hh + simp only [orientedTriangleIndicator,not_lt.mpr ha.le,ite_false] + linarith + · simpa only [orientedTriangleIndicator,ha,ite_true] using triangle_segment_entry_exit_of_position a b c d e ha h + +theorem triangle_closed_walk_intersection_zero (a b c : Plane) (ha : orient2 a b c ≠ 0) + (w : ℕ → Plane) (m : ℕ) (hw : w m = w 0) + (h : ∀ j ∈ Finset.range m, TriangleSegmentPosition a b c (w j) (w (j+1))) : + (∑ j ∈ Finset.range m, triangleSegmentIntersection a b c (w j) (w (j+1))) = 0 := by + have hs := telescoping_real_sum (fun j => orientedTriangleIndicator a b c (w j)) m + rw [hw,sub_self,Finset.sum_sub_distrib] at hs + calc + _ = ∑ j ∈ Finset.range m, + (orientedTriangleIndicator a b c (w (j+1))-orientedTriangleIndicator a b c (w j)) := by + apply Finset.sum_congr rfl + intro j hj + exact oriented_triangle_entry_exit a b c _ _ ha (h j hj) + _ = 0 := by rw [Finset.sum_sub_distrib]; linarith + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/TriangleSideEvent.lean b/lean/OAI/Combinatorics/Crossing/TriangleSideEvent.lean new file mode 100644 index 0000000000000000000000000000000000000000..d9076ece16624e7dce2824f54b38261db62cefcb --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/TriangleSideEvent.lean @@ -0,0 +1,54 @@ +import OAI.Combinatorics.Crossing.SegmentSides +import OAI.Combinatorics.Crossing.AffineSideEvents + +namespace OAI + +noncomputable section +namespace Zarankiewicz +open scoped Classical + +theorem triangle_side_at_first_edge (a b c : Plane) (t : ℝ) : + orient2 b c (segmentPoint a b t) = (1-t)*orient2 a b c := by + dsimp [orient2,det2,segmentPoint] + ring + +theorem triangle_other_side_at_first_edge (a b c : Plane) (t : ℝ) : + orient2 c a (segmentPoint a b t) = t*orient2 a b c := by + dsimp [orient2,det2,segmentPoint] + ring + +theorem triangle_edge_side_tests (a b c d e : Plane) + (harea : 0 < orient2 a b c) (hn : det2 (b-a) (e-d) ≠ 0) : + (0 < orient2 b c (segmentPoint d e (secondIntersectionParameter a b d e)) ↔ + firstIntersectionParameter a b d e < 1) ∧ + (0 < orient2 c a (segmentPoint d e (secondIntersectionParameter a b d e)) ↔ + 0 < firstIntersectionParameter a b d e) := by + rw [← intersection_parameters_eq a b d e hn, + triangle_side_at_first_edge, triangle_other_side_at_first_edge] + constructor + · rw [mul_pos_iff_of_pos_right harea] + constructor <;> intro h <;> linarith + · exact mul_pos_iff_of_pos_right harea + +theorem segmentCrossingSign_triangle_event (a b c d e : Plane) + (harea : 0 < orient2 a b c) (hn : det2 (b-a) (e-d) ≠ 0) : + segmentCrossingSign a b d e = + if 0 < secondIntersectionParameter a b d e ∧ secondIntersectionParameter a b d e < 1 then + slopeSign (det2 (b-a) (e-d)) * + (positiveIndicator (orient2 b c (segmentPoint d e (secondIntersectionParameter a b d e))) * + positiveIndicator (orient2 c a (segmentPoint d e (secondIntersectionParameter a b d e)))) + else 0 := by + obtain ⟨hleft,hright⟩ := triangle_edge_side_tests a b c d e harea hn + rw [segmentCrossingSign, segmentsCrossProperly_iff_parameters a b d e hn] + simp only [Set.mem_Ioo,positiveIndicator,hleft,hright] + by_cases hu : 0 < secondIntersectionParameter a b d e ∧ secondIntersectionParameter a b d e < 1 + · by_cases ht0 : 0 < firstIntersectionParameter a b d e <;> + by_cases ht1 : firstIntersectionParameter a b d e < 1 <;> + simp [hu,ht0,ht1,slopeSign] + · simp [hu] + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/TriangleTransversality.lean b/lean/OAI/Combinatorics/Crossing/TriangleTransversality.lean new file mode 100644 index 0000000000000000000000000000000000000000..e8b80c23436fda16d376898724bb79534b30f999 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/TriangleTransversality.lean @@ -0,0 +1,73 @@ +import OAI.Combinatorics.Crossing.TriangleEntryExit + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +def TriangleSegmentPosition (a b c d e : Plane) : Prop := + (∀ i : Fin 3, det2 (triangleEnd a b c i-triangleStart a b c i) (e-d) ≠ 0) ∧ + (∀ i : Fin 3, orient2 d e (triangleStart a b c i) ≠ 0) ∧ + (∀ i : Fin 3, orient2 (triangleStart a b c i) (triangleEnd a b c i) d ≠ 0 ∧ + orient2 (triangleStart a b c i) (triangleEnd a b c i) e ≠ 0) + +theorem triangle_consecutive_roots_ne (a b c d e : Plane) + (ha : orient2 a b c ≠ 0) (h₀ : det2 (b-a) (e-d) ≠ 0) + (h₁ : det2 (c-b) (e-d) ≠ 0) (hb : orient2 d e b ≠ 0) : + secondIntersectionParameter a b d e ≠ secondIntersectionParameter b c d e := by + intro heq + have hz : orient2 b c (segmentPoint a b (firstIntersectionParameter a b d e)) = 0 := by + rw [intersection_parameters_eq a b d e h₀,heq, + ← intersection_parameters_eq b c d e h₁,orient2_self_segment] + rw [triangle_side_at_first_edge] at hz + have ht : firstIntersectionParameter a b d e = 1 := by + have := (mul_eq_zero.mp hz).resolve_right ha + linarith + have hp := intersection_parameters_eq a b d e h₀ + rw [ht,segmentPoint_one] at hp + apply hb + rw [hp,orient2_self_segment] + +theorem second_parameter_ne_zero (a b c d : Plane) + (hn : det2 (b-a) (d-c) ≠ 0) (hc : orient2 a b c ≠ 0) : + secondIntersectionParameter a b c d ≠ 0 := by + intro h + have hh := affine_side_factor a b c d hn 0 + rw [h,segmentPoint_zero] at hh + apply hc + simpa using hh + +theorem second_parameter_ne_one (a b c d : Plane) + (hn : det2 (b-a) (d-c) ≠ 0) (hd : orient2 a b d ≠ 0) : + secondIntersectionParameter a b c d ≠ 1 := by + intro h + have hh := affine_side_factor a b c d hn 1 + rw [h,segmentPoint_one] at hh + apply hd + simpa using hh + +theorem triangle_roots_injective (a b c d e : Plane) (ha : orient2 a b c ≠ 0) + (h : TriangleSegmentPosition a b c d e) : + Function.Injective (fun i : Fin 3 => + secondIntersectionParameter (triangleStart a b c i) (triangleEnd a b c i) d e) := by + have h₀ := triangle_consecutive_roots_ne a b c d e ha (h.1 0) (h.1 1) (h.2.1 1) + have ha₁ : orient2 b c a ≠ 0 := by rwa [triangle_area_cycle] + have ha₂ : orient2 c a b ≠ 0 := by rwa [triangle_area_cycle,triangle_area_cycle] + have h₁ := triangle_consecutive_roots_ne b c a d e ha₁ (h.1 1) (h.1 2) (h.2.1 2) + have h₂ := triangle_consecutive_roots_ne c a b d e ha₂ (h.1 2) (h.1 0) (h.2.1 0) + intro i j hij + fin_cases i <;> fin_cases j <;> simp_all [triangleStart,triangleEnd] + +theorem triangle_segment_entry_exit_of_position (a b c d e : Plane) + (ha : 0 < orient2 a b c) (h : TriangleSegmentPosition a b c d e) : + triangleSegmentIntersection a b c d e = triangleIndicator a b c e-triangleIndicator a b c d := by + exact triangle_segment_entry_exit a b c d e ha h.1 + (triangle_roots_injective a b c d e (ne_of_gt ha) h) + (fun i => second_parameter_ne_zero _ _ _ _ (h.1 i) (h.2.2 i).1) + (fun i => second_parameter_ne_one _ _ _ _ (h.1 i) (h.2.2 i).2) + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/TruncatedChainDirections.lean b/lean/OAI/Combinatorics/Crossing/TruncatedChainDirections.lean new file mode 100644 index 0000000000000000000000000000000000000000..823df3b28a281a53e78401f2ede36a9ec4d14d02 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/TruncatedChainDirections.lean @@ -0,0 +1,59 @@ +import OAI.Combinatorics.Crossing.TruncatedChainVertices + +namespace OAI + +noncomputable section +namespace Zarankiewicz.PolygonalChain +variable {O : Set Plane} {a b : Plane} + +def truncatedScale (P : PolygonalChain O a b) (r : ℝ) (i : ℕ) : ℝ := + 1-(if i=0 then P.startFraction r else 0)-(if i+1=P.pieces then P.endFraction r else 0) + +theorem truncated_start_formula (P : PolygonalChain O a b) (r : ℝ) (i : ℕ) (hi : i < P.pieces) : + P.truncatedVertices r i=P.vertices i+(if i=0 then P.startFraction r else 0) • trackDirection P.vertices i := by + by_cases h : i=0 + · subst i + rw [truncatedVertices_first,startPort_eq_fraction] + rfl + · simp only [truncatedVertices,ite_eq_right h,ite_eq_right (show i ≠ P.pieces by omega),zero_smul,add_zero] + +theorem truncated_end_formula (P : PolygonalChain O a b) (r : ℝ) (i : ℕ) (_hi : i < P.pieces) : + P.truncatedVertices r (i+1)=P.vertices (i+1)-(if i+1=P.pieces then P.endFraction r else 0) • + trackDirection P.vertices i := by + by_cases h : i+1=P.pieces + · have hh : i=P.pieces-1 := by omega + rw [h,truncatedVertices_last P (by omega) r,endPort_eq_fraction,ite_eq_left rfl] + simp only [trackDirection,hh,show P.pieces-1+1=P.pieces by omega] + · simp only [truncatedVertices,ite_eq_right (show i+1 ≠ 0 by omega),ite_eq_right h,zero_smul,sub_zero] + +theorem truncated_direction (P : PolygonalChain O a b) (r : ℝ) (i : ℕ) (hi : i < P.pieces) : + trackDirection (P.truncatedVertices r) i=P.truncatedScale r i • trackDirection P.vertices i := by + change P.truncatedVertices r (i+1)-P.truncatedVertices r i=_ + rw [truncated_end_formula P r i hi,truncated_start_formula P r i hi] + apply Prod.ext <;> dsimp [trackDirection,truncatedScale] <;> ring + +theorem truncatedScale_pos (P : PolygonalChain O a b) (r : ℝ) (hr : 0 < r) + (hfirst : 4*r^2 < squaredLength (P.vertices 1-P.vertices 0)) + (hlast : 4*r^2 < squaredLength (P.vertices P.pieces-P.vertices (P.pieces-1))) (i : ℕ) : + 0 < P.truncatedScale r i := by + have hs := radialPort_parameter_half (P.vertices 0) (P.vertices 1) r hr hfirst + have he := radialPort_parameter_half (P.vertices (P.pieces-1)) (P.vertices P.pieces) r hr hlast + change 0 < P.startFraction r ∧ P.startFraction r < 1/2 at hs + change 0 < P.endFraction r ∧ P.endFraction r < 1/2 at he + unfold truncatedScale + split_ifs <;> linarith + +theorem truncated_direction_ne_zero (P : PolygonalChain O a b) + (hmin : ∀ Q : PolygonalChain O a b, P.pieces ≤ Q.pieces) + (r : ℝ) (hr : 0 < r) + (hfirst : 4*r^2 < squaredLength (P.vertices 1-P.vertices 0)) + (hlast : 4*r^2 < squaredLength (P.vertices P.pieces-P.vertices (P.pieces-1))) + (i : ℕ) (hi : i < P.pieces) : trackDirection (P.truncatedVertices r) i ≠ 0 := by + rw [P.truncated_direction r i hi] + exact smul_ne_zero (ne_of_gt (P.truncatedScale_pos r hr hfirst hlast i)) (P.minimum_piece_ne_zero hmin i hi) + +end Zarankiewicz.PolygonalChain + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/TruncatedChainPath.lean b/lean/OAI/Combinatorics/Crossing/TruncatedChainPath.lean new file mode 100644 index 0000000000000000000000000000000000000000..a2a1a7ad3aaf5051bed15191d9feac7c675d5e58 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/TruncatedChainPath.lean @@ -0,0 +1,56 @@ +import OAI.Combinatorics.Crossing.TruncatedTrackAvoidance + +namespace OAI + +noncomputable section +namespace Zarankiewicz.PolygonalChain +variable {O : Set Plane} {a b : Plane} + +def truncated (P : PolygonalChain O a b) (hp : 0 < P.pieces) (r : ℝ) (hr : 0 < r) + (hfirst : r^2 < squaredLength (P.vertices 1-P.vertices 0)) + (hlast : r^2 < squaredLength (P.vertices P.pieces-P.vertices (P.pieces-1))) : + PolygonalChain O (P.startPort r) (P.endPort r) where + pieces := P.pieces + vertices := P.truncatedVertices r + first := P.truncatedVertices_first r + last := P.truncatedVertices_last hp r + start_mem := P.inside 0 hp (openSegmentTrace_subset_segment _ _ (radialPort_mem_openSegment _ _ r hr hfirst)) + inside := fun i hi => (P.truncated_piece_subset r hr hfirst hlast i hi).trans (P.inside i hi) + +theorem truncated_segments_disjoint (P : PolygonalChain O a b) + (hmin : ∀ Q : PolygonalChain O a b, P.pieces ≤ Q.pieces) + (r : ℝ) (hr : 0 < r) + (hfirst : r^2 < squaredLength (P.vertices 1-P.vertices 0)) + (hlast : r^2 < squaredLength (P.vertices P.pieces-P.vertices (P.pieces-1))) + (i j : ℕ) (hij : i+1 < j) (hj : j < P.pieces) : + Disjoint (segment ℝ (P.truncatedVertices r i) (P.truncatedVertices r (i+1))) + (segment ℝ (P.truncatedVertices r j) (P.truncatedVertices r (j+1))) := + (P.minimum_nonadjacent_disjoint hmin i j hij hj).mono + (P.truncated_piece_subset r hr hfirst hlast i (by omega)) + (P.truncated_piece_subset r hr hfirst hlast j hj) + +theorem truncated_path_injective (P : PolygonalChain O a b) + (hmin : ∀ Q : PolygonalChain O a b, P.pieces ≤ Q.pieces) (hp : 0 < P.pieces) + (r : ℝ) (hr : 0 < r) + (hfirst : 4*r^2 < squaredLength (P.vertices 1-P.vertices 0)) + (hlast : 4*r^2 < squaredLength (P.vertices P.pieces-P.vertices (P.pieces-1))) : + Function.Injective (polygonalArcPath (P.truncatedVertices r) P.pieces) := by + have hs : r^2 < squaredLength (P.vertices 1-P.vertices 0) := by nlinarith [sq_nonneg r] + have ht : r^2 < squaredLength (P.vertices P.pieces-P.vertices (P.pieces-1)) := by nlinarith [sq_nonneg r] + apply polygonalArcPath_injective (P.truncatedVertices r) P.pieces hp + · intro i hi + exact Ne.symm (sub_ne_zero.mp (P.truncated_direction_ne_zero hmin r hr hfirst hlast i hi)) + · intro i j hij hj x hx hy + by_cases he : j=i+1 + · subst j + refine ⟨rfl,?_⟩ + have hb := P.truncated_bend_ne_zero hmin r hr hfirst hlast (i+1) (by omega) hj + apply adjacent_segments_meet_only_at_bend _ _ _ ?_ hx hy + simpa only [trackDirection,Nat.add_sub_cancel] using hb + · exact False.elim (Set.disjoint_left.mp (P.truncated_segments_disjoint hmin r hr hs ht i j (by omega) hj) hx hy) + +end Zarankiewicz.PolygonalChain + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/TruncatedChainVertices.lean b/lean/OAI/Combinatorics/Crossing/TruncatedChainVertices.lean new file mode 100644 index 0000000000000000000000000000000000000000..5c40a8d0a7d413b6d1010c981695e86329654907 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/TruncatedChainVertices.lean @@ -0,0 +1,72 @@ +import OAI.Combinatorics.Crossing.DrawingSpokePorts + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +theorem radialPort_parameter_half (a b : Plane) (r : ℝ) (hr : 0 < r) + (hshort : 4*r^2 < squaredLength (b-a)) : + 0 < r/Real.sqrt (squaredLength (b-a)) ∧ r/Real.sqrt (squaredLength (b-a)) < 1/2 := by + have hL : 0 < squaredLength (b-a) := by nlinarith [sq_nonneg r] + have hs := Real.sqrt_pos.mpr hL + have hs2 := Real.sq_sqrt hL.le + exact ⟨div_pos hr hs,(div_lt_iff₀ hs).mpr (by nlinarith)⟩ + +namespace PolygonalChain +variable {O : Set Plane} {a b : Plane} + +def startFraction (P : PolygonalChain O a b) (r : ℝ) : ℝ := + r/Real.sqrt (squaredLength (P.vertices 1-P.vertices 0)) + +def endFraction (P : PolygonalChain O a b) (r : ℝ) : ℝ := + r/Real.sqrt (squaredLength (P.vertices P.pieces-P.vertices (P.pieces-1))) + +def truncatedVertices (P : PolygonalChain O a b) (r : ℝ) (i : ℕ) : Plane := + if i=0 then P.startPort r else if i=P.pieces then P.endPort r else P.vertices i + +theorem startPort_eq_fraction (P : PolygonalChain O a b) (r : ℝ) : + P.startPort r=P.vertices 0+P.startFraction r • (P.vertices 1-P.vertices 0) := rfl + +theorem endPort_eq_fraction (P : PolygonalChain O a b) (r : ℝ) : + P.endPort r=P.vertices P.pieces-P.endFraction r • (P.vertices P.pieces-P.vertices (P.pieces-1)) := by + unfold endPort radialPort endFraction + rw [squaredLength_sub_comm (P.vertices (P.pieces-1)) (P.vertices P.pieces)] + apply Prod.ext <;> dsimp <;> ring + +theorem truncatedVertices_first (P : PolygonalChain O a b) (r : ℝ) : + P.truncatedVertices r 0=P.startPort r := by simp [truncatedVertices] + +theorem truncatedVertices_last (P : PolygonalChain O a b) (hp : 0 < P.pieces) (r : ℝ) : + P.truncatedVertices r P.pieces=P.endPort r := by simp [truncatedVertices,ne_of_gt hp] + +theorem truncated_piece_subset (P : PolygonalChain O a b) (r : ℝ) (hr : 0 < r) + (hfirst : r^2 < squaredLength (P.vertices 1-P.vertices 0)) + (hlast : r^2 < squaredLength (P.vertices P.pieces-P.vertices (P.pieces-1))) + (i : ℕ) (hi : i < P.pieces) : + segment ℝ (P.truncatedVertices r i) (P.truncatedVertices r (i+1)) ⊆ + segment ℝ (P.vertices i) (P.vertices (i+1)) := by + apply (convex_segment (𝕜 := ℝ) _ _).segment_subset + · by_cases h0 : i=0 + · subst i + rw [truncatedVertices_first] + exact openSegmentTrace_subset_segment _ _ (radialPort_mem_openSegment _ _ r hr hfirst) + · simp only [truncatedVertices,ite_eq_right h0,ite_eq_right (show i ≠ P.pieces by omega)] + exact left_mem_segment ℝ _ _ + · by_cases hn : i+1=P.pieces + · rw [show P.truncatedVertices r (i+1)=P.endPort r by rw [hn]; exact P.truncatedVertices_last (by omega) r] + have hh : i=P.pieces-1 := by omega + have hs : r^2 < squaredLength (P.vertices (P.pieces-1)-P.vertices P.pieces) := by + rwa [squaredLength_sub_comm] + have hx := openSegmentTrace_reverse_mem _ _ _ (radialPort_mem_openSegment _ _ r hr hs) + have hseg := openSegmentTrace_subset_segment _ _ hx + simpa only [endPort,hh,show P.pieces-1+1=P.pieces by omega] using hseg + · simp only [truncatedVertices,ite_eq_right (show i+1 ≠ 0 by omega),ite_eq_right hn] + exact right_mem_segment ℝ _ _ + +end PolygonalChain +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/TruncatedCrossingCorners.lean b/lean/OAI/Combinatorics/Crossing/TruncatedCrossingCorners.lean new file mode 100644 index 0000000000000000000000000000000000000000..ed4b6508a5c220caa4be9691dd272d35af2b3ef1 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/TruncatedCrossingCorners.lean @@ -0,0 +1,41 @@ +import OAI.Combinatorics.Crossing.TruncatedDrawingInteriors +import OAI.Combinatorics.Crossing.ReducedCrossingCorners + +namespace OAI + +noncomputable section +namespace Zarankiewicz +variable {m n : ℕ} + +theorem truncated_vertices_not_crossing (D : AdmissibleDrawing m n) + (hnorm : NoAdjacentCrossings D) (hstraight : LocallyStraightCrossings D) + (P : ∀ e : BipartiteEdge m n, PolygonalChain (Set.range (D.edge e)) + (D.vertex (.inl e.1)) (D.vertex (.inr e.2))) + (hmin : ∀ e, ∀ Q : PolygonalChain (Set.range (D.edge e)) + (D.vertex (.inl e.1)) (D.vertex (.inr e.2)), (P e).pieces ≤ Q.pieces) + (r : ℝ) + (hclear : ∀ j e (i : Fin (P e).pieces), + ¬ ((j=Sum.inl e.1 ∧ i.val=0) ∨ (j=Sum.inr e.2 ∧ i.val+1=(P e).pieces)) → + Disjoint (closedRoundDisk (D.vertex j) r) (segment ℝ ((P e).vertices i.val) ((P e).vertices (i.val+1)))) + (e : BipartiteEdge m n) (i : ℕ) (hi : i ≤ (P e).pieces) : + (P e).truncatedVertices r i ∉ crossingPoints D.toContinuousDrawing := by + by_cases h0 : i=0 + · subst i + rw [(P e).truncatedVertices_first] + intro hx + have hc := (drawing_chain_startPort_circle D.toContinuousDrawing e (P e) (hmin e) r).le + exact Set.disjoint_left.mp (vertex_disks_crossing_free D hnorm P r hclear (.inl e.1)) hc hx + by_cases hn : i=(P e).pieces + · subst i + rw [(P e).truncatedVertices_last (drawing_chain_pieces_pos D.toContinuousDrawing e (P e))] + intro hx + have hc := (drawing_chain_endPort_circle D.toContinuousDrawing e (P e) (hmin e) r).le + exact Set.disjoint_left.mp (vertex_disks_crossing_free D hnorm P r hclear (.inr e.2)) hc hx + · simp only [PolygonalChain.truncatedVertices,ite_eq_right h0,ite_eq_right hn] + exact minimum_vertices_not_crossing D hstraight e (P e) (hmin e) i hi + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/TruncatedCrossingRetention.lean b/lean/OAI/Combinatorics/Crossing/TruncatedCrossingRetention.lean new file mode 100644 index 0000000000000000000000000000000000000000..6c60d8a7611caf843ae96492045daf1793362713 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/TruncatedCrossingRetention.lean @@ -0,0 +1,41 @@ +import OAI.Combinatorics.Crossing.VertexDisksCrossingFree +import OAI.Combinatorics.Crossing.TruncatedTraceDecomposition + +namespace OAI + +noncomputable section +namespace Zarankiewicz +variable {m n : ℕ} + +theorem crossing_mem_truncated_edge (D : AdmissibleDrawing m n) (hnorm : NoAdjacentCrossings D) + (P : ∀ e : BipartiteEdge m n, PolygonalChain (Set.range (D.edge e)) + (D.vertex (.inl e.1)) (D.vertex (.inr e.2))) + (hmin : ∀ e, ∀ Q : PolygonalChain (Set.range (D.edge e)) + (D.vertex (.inl e.1)) (D.vertex (.inr e.2)), (P e).pieces ≤ Q.pieces) + (r : ℝ) (hr : 0 < r) + (hshort : ∀ e, r^2 < squaredLength ((P e).vertices 1-(P e).vertices 0) ∧ + r^2 < squaredLength ((P e).vertices (P e).pieces-(P e).vertices ((P e).pieces-1))) + (hclear : ∀ j e (i : Fin (P e).pieces), + ¬ ((j=Sum.inl e.1 ∧ i.val=0) ∨ (j=Sum.inr e.2 ∧ i.val+1=(P e).pieces)) → + Disjoint (closedRoundDisk (D.vertex j) r) (segment ℝ ((P e).vertices i.val) ((P e).vertices (i.val+1)))) + (e : BipartiteEdge m n) (x : Plane) (hx : x ∈ crossingPoints D.toContinuousDrawing) + (hxe : x ∈ edgeInterior D.toContinuousDrawing e) : + x ∈ Set.range (polygonalArcPath ((P e).truncatedVertices r) (P e).pieces) := by + have hh := edgeInterior_subset_range D.toContinuousDrawing e hxe + rw [drawing_edge_trace_decomposition D.toContinuousDrawing e (P e) r hr (hshort e).1 (hshort e).2] at hh + rcases hh with (hs | hm) | ht + · have hmem := center_segment_in_disk (D.vertex (.inl e.1)) ((P e).startPort r) r + (drawing_chain_startPort_circle D.toContinuousDrawing e (P e) (hmin e) r) hs + exact False.elim (Set.disjoint_left.mp (vertex_disks_crossing_free D hnorm P r hclear (.inl e.1)) hmem hx) + · exact hm + · have ht' : x ∈ segment ℝ (D.vertex (.inr e.2)) ((P e).endPort r) := by + simpa only [segment_symm ℝ ((P e).endPort r) (D.vertex (.inr e.2))] using ht + have hmem := center_segment_in_disk (D.vertex (.inr e.2)) ((P e).endPort r) r + (drawing_chain_endPort_circle D.toContinuousDrawing e (P e) (hmin e) r) ht' + exact False.elim (Set.disjoint_left.mp (vertex_disks_crossing_free D hnorm P r hclear (.inr e.2)) hmem hx) + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/TruncatedDrawingDisks.lean b/lean/OAI/Combinatorics/Crossing/TruncatedDrawingDisks.lean new file mode 100644 index 0000000000000000000000000000000000000000..a1fb154b65d561e93ea6d888f81f24e9fd574679 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/TruncatedDrawingDisks.lean @@ -0,0 +1,71 @@ +import OAI.Combinatorics.Crossing.TruncatedRadialEnds + +namespace OAI + +noncomputable section +namespace Zarankiewicz +variable {m n : ℕ} + +theorem truncated_piece_vertex_disk_cases (D : ContinuousDrawing m n) + (P : ∀ e : BipartiteEdge m n, PolygonalChain (Set.range (D.edge e)) + (D.vertex (.inl e.1)) (D.vertex (.inr e.2))) + (hmin : ∀ e, ∀ Q : PolygonalChain (Set.range (D.edge e)) + (D.vertex (.inl e.1)) (D.vertex (.inr e.2)), (P e).pieces ≤ Q.pieces) + (r : ℝ) (hr : 0 < r) + (hshort : ∀ e, 4*r^2 < squaredLength ((P e).vertices 1-(P e).vertices 0) ∧ + 4*r^2 < squaredLength ((P e).vertices (P e).pieces-(P e).vertices ((P e).pieces-1))) + (hclear : ∀ j e (i : Fin (P e).pieces), + ¬ ((j=Sum.inl e.1 ∧ i.val=0) ∨ (j=Sum.inr e.2 ∧ i.val+1=(P e).pieces)) → + Disjoint (closedRoundDisk (D.vertex j) r) (segment ℝ ((P e).vertices i.val) ((P e).vertices (i.val+1)))) + (j : BipartiteVertex m n) (e : BipartiteEdge m n) (i : Fin (P e).pieces) (x : Plane) + (hx : x ∈ segment ℝ ((P e).truncatedVertices r i.val) ((P e).truncatedVertices r (i.val+1))) : + (j=Sum.inl e.1 ∧ x=(P e).startPort r) ∨ + (j=Sum.inr e.2 ∧ x=(P e).endPort r) ∨ r^2 < squaredLength (x-D.vertex j) := by + have hp := drawing_chain_pieces_pos D e (P e) + by_cases hfirst : j=Sum.inl e.1 ∧ i.val=0 + · have hh := (P e).truncated_first_exterior (hmin e) hp r hr (hshort e).1 (hshort e).2 + (by simpa only [hfirst.2] using hx) + rcases Set.mem_insert_iff.mp hh with he | he + · exact Or.inl ⟨hfirst.1,he⟩ + · right; right + simpa only [Set.mem_ofPred_eq,(P e).first,hfirst.1] using he + by_cases hlast : j=Sum.inr e.2 ∧ i.val+1=(P e).pieces + · have hi : i.val=(P e).pieces-1 := by omega + have hh := (P e).truncated_last_exterior (hmin e) hp r hr (hshort e).1 (hshort e).2 + (by simpa only [hi,show (P e).pieces-1+1=(P e).pieces by omega] using hx) + rcases Set.mem_insert_iff.mp hh with he | he + · exact Or.inr (Or.inl ⟨hlast.1,he⟩) + · right; right + simpa only [Set.mem_ofPred_eq,(P e).last,hlast.1] using he + · right; right + have hs : r^2 < squaredLength ((P e).vertices 1-(P e).vertices 0) := by nlinarith [(hshort e).1,sq_nonneg r] + have ht : r^2 < squaredLength ((P e).vertices (P e).pieces-(P e).vertices ((P e).pieces-1)) := by + nlinarith [(hshort e).2,sq_nonneg r] + have hxi := (P e).truncated_piece_subset r hr hs ht i.val i.isLt hx + by_contra h + exact Set.disjoint_left.mp (hclear j e i (fun h => h.elim hfirst hlast)) (le_of_not_gt h) hxi + +theorem truncated_path_vertex_disk_cases (D : ContinuousDrawing m n) + (P : ∀ e : BipartiteEdge m n, PolygonalChain (Set.range (D.edge e)) + (D.vertex (.inl e.1)) (D.vertex (.inr e.2))) + (hmin : ∀ e, ∀ Q : PolygonalChain (Set.range (D.edge e)) + (D.vertex (.inl e.1)) (D.vertex (.inr e.2)), (P e).pieces ≤ Q.pieces) + (r : ℝ) (hr : 0 < r) + (hshort : ∀ e, 4*r^2 < squaredLength ((P e).vertices 1-(P e).vertices 0) ∧ + 4*r^2 < squaredLength ((P e).vertices (P e).pieces-(P e).vertices ((P e).pieces-1))) + (hclear : ∀ j e (i : Fin (P e).pieces), + ¬ ((j=Sum.inl e.1 ∧ i.val=0) ∨ (j=Sum.inr e.2 ∧ i.val+1=(P e).pieces)) → + Disjoint (closedRoundDisk (D.vertex j) r) (segment ℝ ((P e).vertices i.val) ((P e).vertices (i.val+1)))) + (j : BipartiteVertex m n) (e : BipartiteEdge m n) (x : Plane) + (hx : x ∈ Set.range (polygonalArcPath ((P e).truncatedVertices r) (P e).pieces)) : + (j=Sum.inl e.1 ∧ x=(P e).startPort r) ∨ + (j=Sum.inr e.2 ∧ x=(P e).endPort r) ∨ r^2 < squaredLength (x-D.vertex j) := by + obtain ⟨i,hi,hxi⟩ := polygonalArcPath_range_piece ((P e).truncatedVertices r) (P e).pieces + (drawing_chain_pieces_pos D e (P e)) x hx + exact truncated_piece_vertex_disk_cases D P hmin r hr hshort hclear j e ⟨i,hi⟩ x hxi + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/TruncatedDrawingInteriors.lean b/lean/OAI/Combinatorics/Crossing/TruncatedDrawingInteriors.lean new file mode 100644 index 0000000000000000000000000000000000000000..b0b95f5181e86c23d13e7227a063c3b4e73e0157 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/TruncatedDrawingInteriors.lean @@ -0,0 +1,72 @@ +import OAI.Combinatorics.Crossing.TruncatedCrossingRetention + +namespace OAI + +noncomputable section +namespace Zarankiewicz +variable {m n : ℕ} + +theorem truncated_range_subset_edgeInterior (D : ContinuousDrawing m n) + (P : ∀ e : BipartiteEdge m n, PolygonalChain (Set.range (D.edge e)) + (D.vertex (.inl e.1)) (D.vertex (.inr e.2))) + (hmin : ∀ e, ∀ Q : PolygonalChain (Set.range (D.edge e)) + (D.vertex (.inl e.1)) (D.vertex (.inr e.2)), (P e).pieces ≤ Q.pieces) + (r : ℝ) (hr : 0 < r) + (hshort : ∀ e, 4*r^2 < squaredLength ((P e).vertices 1-(P e).vertices 0) ∧ + 4*r^2 < squaredLength ((P e).vertices (P e).pieces-(P e).vertices ((P e).pieces-1))) + (hclear : ∀ j e (i : Fin (P e).pieces), + ¬ ((j=Sum.inl e.1 ∧ i.val=0) ∨ (j=Sum.inr e.2 ∧ i.val+1=(P e).pieces)) → + Disjoint (closedRoundDisk (D.vertex j) r) (segment ℝ ((P e).vertices i.val) ((P e).vertices (i.val+1)))) + (e : BipartiteEdge m n) : + Set.range (polygonalArcPath ((P e).truncatedVertices r) (P e).pieces) ⊆ edgeInterior D e := by + intro x hx + have hs : r^2 < squaredLength ((P e).vertices 1-(P e).vertices 0) := by nlinarith [(hshort e).1,sq_nonneg r] + have ht : r^2 < squaredLength ((P e).vertices (P e).pieces-(P e).vertices ((P e).pieces-1)) := by + nlinarith [(hshort e).2,sq_nonneg r] + apply edgeInterior_of_range_not_vertices D e x + · exact ((P e).truncated (drawing_chain_pieces_pos D e (P e)) r hr hs ht).path_range_subset hx + · intro j he + rcases truncated_path_vertex_disk_cases D P hmin r hr hshort hclear j e x hx with ⟨hj,hp⟩ | ⟨hj,hp⟩ | hout + · have hpi := drawing_chain_startPort_interior D e (P e) (hmin e) r hr hs + exact edgeInterior_not_vertex D e _ hpi j (hp.symm.trans he) + · have hpi := drawing_chain_endPort_interior D e (P e) (hmin e) r hr ht + exact edgeInterior_not_vertex D e _ hpi j (hp.symm.trans he) + · rw [he,sub_self] at hout + have hz : squaredLength (0 : Plane)=0 := by simp [squaredLength] + rw [hz] at hout + exact (sq_nonneg r).not_gt hout + +theorem truncated_edge_intersections_eq (D : AdmissibleDrawing m n) (hnorm : NoAdjacentCrossings D) + (P : ∀ e : BipartiteEdge m n, PolygonalChain (Set.range (D.edge e)) + (D.vertex (.inl e.1)) (D.vertex (.inr e.2))) + (hmin : ∀ e, ∀ Q : PolygonalChain (Set.range (D.edge e)) + (D.vertex (.inl e.1)) (D.vertex (.inr e.2)), (P e).pieces ≤ Q.pieces) + (r : ℝ) (hr : 0 < r) + (hshort : ∀ e, 4*r^2 < squaredLength ((P e).vertices 1-(P e).vertices 0) ∧ + 4*r^2 < squaredLength ((P e).vertices (P e).pieces-(P e).vertices ((P e).pieces-1))) + (hclear : ∀ j e (i : Fin (P e).pieces), + ¬ ((j=Sum.inl e.1 ∧ i.val=0) ∨ (j=Sum.inr e.2 ∧ i.val+1=(P e).pieces)) → + Disjoint (closedRoundDisk (D.vertex j) r) (segment ℝ ((P e).vertices i.val) ((P e).vertices (i.val+1)))) + (e f : BipartiteEdge m n) (hef : e ≠ f) : + Set.range (polygonalArcPath ((P e).truncatedVertices r) (P e).pieces) ∩ + Set.range (polygonalArcPath ((P f).truncatedVertices r) (P f).pieces) = + edgeInterior D.toContinuousDrawing e ∩ edgeInterior D.toContinuousDrawing f := by + have hweak (g : BipartiteEdge m n) : + r^2 < squaredLength ((P g).vertices 1-(P g).vertices 0) ∧ + r^2 < squaredLength ((P g).vertices (P g).pieces-(P g).vertices ((P g).pieces-1)) := by + constructor <;> nlinarith [(hshort g).1,(hshort g).2,sq_nonneg r] + ext x + constructor + · rintro ⟨hx,hy⟩ + exact ⟨truncated_range_subset_edgeInterior D.toContinuousDrawing P hmin r hr hshort hclear e hx, + truncated_range_subset_edgeInterior D.toContinuousDrawing P hmin r hr hshort hclear f hy⟩ + · rintro ⟨hx,hy⟩ + have hc : x ∈ crossingPoints D.toContinuousDrawing := ⟨e,f,hef,hx,hy⟩ + exact ⟨crossing_mem_truncated_edge D hnorm P hmin r hr hweak hclear e x hc hx, + crossing_mem_truncated_edge D hnorm P hmin r hr hweak hclear f x hc hy⟩ + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/TruncatedRadialDots.lean b/lean/OAI/Combinatorics/Crossing/TruncatedRadialDots.lean new file mode 100644 index 0000000000000000000000000000000000000000..15533175e1aba38828a5568666bad9fb8372af20 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/TruncatedRadialDots.lean @@ -0,0 +1,73 @@ +import OAI.Combinatorics.Crossing.TrackEndpointConnections +import OAI.Combinatorics.Crossing.NormalOffsetExterior + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +theorem dot2_scaled_self (v : Plane) (a b : ℝ) : dot2 (a • v) (b • v)=a*b*squaredLength v := by + dsimp [dot2,squaredLength] + ring + +namespace VertexTruncation +variable {m n : ℕ} {D : ContinuousDrawing m n} (V : VertexTruncation D) + +theorem start_radial_dot_pos (e : BipartiteEdge m n) : + 0 < dot2 (V.startPort e-D.vertex (Sum.inl e.1)) (trackDirection (V.vertices e) 0) := by + have hp := V.pieces_pos e + have hα := (radialPort_parameter_half ((V.chain e).vertices 0) ((V.chain e).vertices 1) + V.radius V.radius_pos (V.short e).1).1 + have hβ := (V.chain e).truncatedScale_pos V.radius V.radius_pos (V.short e).1 (V.short e).2 0 + have he : V.startPort e-D.vertex (Sum.inl e.1)= + (V.chain e).startFraction V.radius • trackDirection (V.chain e).vertices 0 := by + have hh := radialPort_sub ((V.chain e).vertices 0) ((V.chain e).vertices 1) V.radius + change (V.chain e).startPort V.radius-(V.chain e).vertices 0= + (V.chain e).startFraction V.radius • trackDirection (V.chain e).vertices 0 at hh + simpa only [startPort,(V.chain e).first] using hh + rw [he] + change 0 < dot2 _ (trackDirection ((V.chain e).truncatedVertices V.radius) 0) + rw [(V.chain e).truncated_direction V.radius 0 hp,dot2_scaled_self] + exact mul_pos (mul_pos hα hβ) + (squaredLength_pos _ ((V.chain e).minimum_piece_ne_zero (V.minimal e) 0 hp)) + +theorem end_radial_dot_neg (e : BipartiteEdge m n) : + dot2 (V.endPort e-D.vertex (Sum.inr e.2)) + (trackDirection (V.vertices e) (V.pieces e-1)) < 0 := by + have hp := V.pieces_pos e + have hp' : 0 < (V.chain e).pieces := hp + have hi : V.pieces e-1 < V.pieces e := by omega + have hα := (radialPort_parameter_half ((V.chain e).vertices ((V.chain e).pieces-1)) + ((V.chain e).vertices (V.chain e).pieces) V.radius V.radius_pos (V.short e).2).1 + have hβ := (V.chain e).truncatedScale_pos V.radius V.radius_pos (V.short e).1 (V.short e).2 (V.pieces e-1) + have he : V.endPort e-D.vertex (Sum.inr e.2)= + (-(V.chain e).endFraction V.radius) • trackDirection (V.chain e).vertices (V.pieces e-1) := by + have hh : (V.chain e).endPort V.radius-(V.chain e).vertices (V.chain e).pieces= + (-(V.chain e).endFraction V.radius) • trackDirection (V.chain e).vertices (V.pieces e-1) := by + rw [(V.chain e).endPort_eq_fraction] + simp only [trackDirection,pieces,show (V.chain e).pieces-1+1=(V.chain e).pieces by omega,neg_smul] + abel + simpa only [endPort,(V.chain e).last] using hh + rw [he] + change dot2 _ (trackDirection ((V.chain e).truncatedVertices V.radius) (V.pieces e-1)) < 0 + rw [(V.chain e).truncated_direction V.radius _ hi,dot2_scaled_self] + exact mul_neg_of_neg_of_pos (mul_neg_of_neg_of_pos (neg_neg_of_pos hα) hβ) + (squaredLength_pos _ ((V.chain e).minimum_piece_ne_zero (V.minimal e) _ hi)) + +theorem bend_ne_zero (e : BipartiteEdge m n) (i : ℕ) (hi0 : 0 < i) (hin : i < V.pieces e) : + det2 (trackDirection (V.vertices e) (i-1)) (trackDirection (V.vertices e) i) ≠ 0 := by + exact (V.chain e).truncated_bend_ne_zero (V.minimal e) V.radius V.radius_pos + (V.short e).1 (V.short e).2 i hi0 hin + +theorem exists_forward_radius (e : BipartiteEdge m n) : + ∃ δ : ℝ, 0<δ ∧ ∀ ε : ℝ, |ε|<δ → ∀ i : Fin (V.pieces e), + ∃ ℓ : ℝ, 0<ℓ ∧ shiftedTrack (V.vertices e) (V.pieces e) ε (i.val+1)- + shiftedTrack (V.vertices e) (V.pieces e) ε i.val=ℓ • trackDirection (V.vertices e) i.val := + exists_forward_shiftedTrack_radius (V.vertices e) (V.pieces e) (V.direction_ne_zero e) (V.bend_ne_zero e) + +end VertexTruncation +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/TruncatedRadialEnds.lean b/lean/OAI/Combinatorics/Crossing/TruncatedRadialEnds.lean new file mode 100644 index 0000000000000000000000000000000000000000..ac82ae120d3c7329643c806e6d750a5c6bd62412 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/TruncatedRadialEnds.lean @@ -0,0 +1,69 @@ +import OAI.Combinatorics.Crossing.TruncatedChainPath +import OAI.Combinatorics.Crossing.RadialExterior + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +theorem radial_segment_of_coefficients (o p q v : Plane) (r α β : ℝ) + (hr : 0 < r) (hα : 0 < α) (hβ : 0 < β) + (hp : p-o=α • v) (hq : q-p=β • v) (hc : squaredLength (p-o)=r^2) : + segment ℝ p q ⊆ insert p {x | r^2 < squaredLength (x-o)} := by + have he : q=p+(β/α) • (p-o) := by + rw [hp,smul_smul,div_mul_cancel₀ _ (ne_of_gt hα)] + rw [← hq] + abel + rw [he] + exact radial_spur_exterior o p r (β/α) hc hr (div_pos hβ hα) + +namespace PolygonalChain +variable {O : Set Plane} {a b : Plane} + +theorem truncated_first_exterior (P : PolygonalChain O a b) + (hmin : ∀ Q : PolygonalChain O a b, P.pieces ≤ Q.pieces) (hp : 0 < P.pieces) + (r : ℝ) (hr : 0 < r) + (hfirst : 4*r^2 < squaredLength (P.vertices 1-P.vertices 0)) + (hlast : 4*r^2 < squaredLength (P.vertices P.pieces-P.vertices (P.pieces-1))) : + segment ℝ (P.truncatedVertices r 0) (P.truncatedVertices r 1) ⊆ + insert (P.startPort r) {x | r^2 < squaredLength (x-P.vertices 0)} := by + have hα := (radialPort_parameter_half (P.vertices 0) (P.vertices 1) r hr hfirst).1 + have hβ := P.truncatedScale_pos r hr hfirst hlast 0 + rw [P.truncatedVertices_first] + apply radial_segment_of_coefficients (P.vertices 0) (P.startPort r) (P.truncatedVertices r 1) + (trackDirection P.vertices 0) r (P.startFraction r) (P.truncatedScale r 0) hr hα hβ + · exact radialPort_sub (P.vertices 0) (P.vertices 1) r + · simpa only [trackDirection,P.truncatedVertices_first] using P.truncated_direction r 0 hp + · exact radialPort_on_circle (P.vertices 0) (P.vertices 1) + (P.minimum_vertices_ne hmin 0 1 (by omega) hp) r + +theorem truncated_last_exterior (P : PolygonalChain O a b) + (hmin : ∀ Q : PolygonalChain O a b, P.pieces ≤ Q.pieces) (hp : 0 < P.pieces) + (r : ℝ) (hr : 0 < r) + (hfirst : 4*r^2 < squaredLength (P.vertices 1-P.vertices 0)) + (hlast : 4*r^2 < squaredLength (P.vertices P.pieces-P.vertices (P.pieces-1))) : + segment ℝ (P.truncatedVertices r (P.pieces-1)) (P.truncatedVertices r P.pieces) ⊆ + insert (P.endPort r) {x | r^2 < squaredLength (x-P.vertices P.pieces)} := by + have hi : P.pieces-1 < P.pieces := by omega + have hα := (radialPort_parameter_half (P.vertices (P.pieces-1)) (P.vertices P.pieces) r hr hlast).1 + have hβ := P.truncatedScale_pos r hr hfirst hlast (P.pieces-1) + rw [P.truncatedVertices_last hp,segment_symm] + apply radial_segment_of_coefficients (P.vertices P.pieces) (P.endPort r) + (P.truncatedVertices r (P.pieces-1)) (-(trackDirection P.vertices (P.pieces-1))) + r (P.endFraction r) (P.truncatedScale r (P.pieces-1)) hr hα hβ + · rw [P.endPort_eq_fraction] + simp only [trackDirection,show P.pieces-1+1=P.pieces by omega,smul_neg] + abel + · have h := P.truncated_direction r (P.pieces-1) hi + simp only [trackDirection,show P.pieces-1+1=P.pieces by omega,P.truncatedVertices_last hp] at h ⊢ + rw [smul_neg,← h] + abel + · have hn := Ne.symm (P.minimum_vertices_ne hmin (P.pieces-1) P.pieces hi (by omega)) + exact radialPort_on_circle (P.vertices P.pieces) (P.vertices (P.pieces-1)) hn r + +end PolygonalChain +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/TruncatedSegmentTransversality.lean b/lean/OAI/Combinatorics/Crossing/TruncatedSegmentTransversality.lean new file mode 100644 index 0000000000000000000000000000000000000000..d50a1682f15e7b727c9e4fda7770a1dc7443c350 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/TruncatedSegmentTransversality.lean @@ -0,0 +1,76 @@ +import OAI.Combinatorics.Crossing.TruncatedCrossingCorners +import OAI.Combinatorics.Crossing.ReducedCrossingTransversality + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +theorem segment_parameter_strict_of_avoids_endpoints (a b x : Plane) (S : Set Plane) + (hx : x ∈ S) (ha : a ∉ S) (hb : b ∉ S) (t : ℝ) (ht : t ∈ Set.Icc (0 : ℝ) 1) + (he : segmentPoint a b t=x) : t ∈ Set.Ioo (0 : ℝ) 1 := by + have ht0 : t ≠ 0 := by + intro h + rw [h,segmentPoint_zero] at he + exact ha (he.symm ▸ hx) + have ht1 : t ≠ 1 := by + intro h + rw [h,segmentPoint_one] at he + exact hb (he.symm ▸ hx) + exact ⟨lt_of_le_of_ne ht.1 ht0.symm,lt_of_le_of_ne ht.2 ht1⟩ + +theorem truncated_segment_pair_transverse {m n : ℕ} (D : AdmissibleDrawing m n) + (hnorm : NoAdjacentCrossings D) (hstraight : LocallyStraightCrossings D) + (htrans : LocallyTransverseCrossings D) + (P : ∀ e : BipartiteEdge m n, PolygonalChain (Set.range (D.edge e)) + (D.vertex (.inl e.1)) (D.vertex (.inr e.2))) + (hmin : ∀ e, ∀ Q : PolygonalChain (Set.range (D.edge e)) + (D.vertex (.inl e.1)) (D.vertex (.inr e.2)), (P e).pieces ≤ Q.pieces) + (r : ℝ) (hr : 0 < r) + (hshort : ∀ e, 4*r^2 < squaredLength ((P e).vertices 1-(P e).vertices 0) ∧ + 4*r^2 < squaredLength ((P e).vertices (P e).pieces-(P e).vertices ((P e).pieces-1))) + (hclear : ∀ j e (i : Fin (P e).pieces), + ¬ ((j=Sum.inl e.1 ∧ i.val=0) ∨ (j=Sum.inr e.2 ∧ i.val+1=(P e).pieces)) → + Disjoint (closedRoundDisk (D.vertex j) r) (segment ℝ ((P e).vertices i.val) ((P e).vertices (i.val+1)))) + (e f : BipartiteEdge m n) (hef : e ≠ f) (i : Fin (P e).pieces) (j : Fin (P f).pieces) : + SegmentPairTransverse ((P e).truncatedVertices r i.val) ((P e).truncatedVertices r (i.val+1)) + ((P f).truncatedVertices r j.val) ((P f).truncatedVertices r (j.val+1)) := by + intro s hs t ht he + let x := segmentPoint ((P e).truncatedVertices r i.val) ((P e).truncatedVertices r (i.val+1)) s + have hxe : x ∈ segment ℝ ((P e).truncatedVertices r i.val) ((P e).truncatedVertices r (i.val+1)) := by + rw [← Path.range_segment] + exact ⟨⟨s,hs⟩,by simp only [Path.segment_apply,AffineMap.lineMap_apply_module,segmentPoint,x]⟩ + have hxf : x ∈ segment ℝ ((P f).truncatedVertices r j.val) ((P f).truncatedVertices r (j.val+1)) := by + rw [← Path.range_segment] + refine ⟨⟨t,ht⟩,?_⟩ + simpa only [Path.segment_apply,AffineMap.lineMap_apply_module,x,segmentPoint] using he.symm + have hie := truncated_range_subset_edgeInterior D.toContinuousDrawing P hmin r hr hshort hclear e + (polygonalArcPath_piece_subset_range _ _ i.val i.isLt hxe) + have hif := truncated_range_subset_edgeInterior D.toContinuousDrawing P hmin r hr hshort hclear f + (polygonalArcPath_piece_subset_range _ _ j.val j.isLt hxf) + have hcross : x ∈ crossingPoints D.toContinuousDrawing := ⟨e,f,hef,hie,hif⟩ + have hcorner := truncated_vertices_not_crossing D hnorm hstraight P hmin r hclear + have hsi := segment_parameter_strict_of_avoids_endpoints _ _ x _ hcross + (hcorner e i.val (by omega)) (hcorner e (i.val+1) (by omega)) s hs rfl + have hti := segment_parameter_strict_of_avoids_endpoints _ _ x _ hcross + (hcorner f j.val (by omega)) (hcorner f (j.val+1) (by omega)) t ht he.symm + refine ⟨?_,hsi,hti⟩ + have hweak (g : BipartiteEdge m n) : + r^2 < squaredLength ((P g).vertices 1-(P g).vertices 0) ∧ + r^2 < squaredLength ((P g).vertices (P g).pieces-(P g).vertices ((P g).pieces-1)) := by + constructor <;> nlinarith [(hshort g).1,(hshort g).2,sq_nonneg r] + have hde := minimum_piece_det_at_crossing D hstraight htrans e f hef (P e) (P f) (hmin e) (hmin f) + i.val j.val i.isLt j.isLt x hie hif + ((P e).truncated_piece_subset r hr (hweak e).1 (hweak e).2 i.val i.isLt hxe) + ((P f).truncated_piece_subset r hr (hweak f).1 (hweak f).2 j.val j.isLt hxf) + change det2 (trackDirection ((P e).truncatedVertices r) i.val) (trackDirection ((P f).truncatedVertices r) j.val) ≠ 0 + rw [(P e).truncated_direction r i.val i.isLt,(P f).truncated_direction r j.val j.isLt, + det2_smul_left,det2_smul_right] + exact mul_ne_zero (ne_of_gt ((P e).truncatedScale_pos r hr (hshort e).1 (hshort e).2 i.val)) + (mul_ne_zero (ne_of_gt ((P f).truncatedScale_pos r hr (hshort f).1 (hshort f).2 j.val)) hde) + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/TruncatedSignedIntersections.lean b/lean/OAI/Combinatorics/Crossing/TruncatedSignedIntersections.lean new file mode 100644 index 0000000000000000000000000000000000000000..8d500c691e5bfb5211acfe58f679a3939ea13f2f --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/TruncatedSignedIntersections.lean @@ -0,0 +1,80 @@ +import OAI.Combinatorics.Crossing.UniformTrackPerturbation +import OAI.Combinatorics.Crossing.RowCrossingCount + +namespace OAI + +noncomputable section +namespace Zarankiewicz.VertexTruncation +open scoped BigOperators +variable {m n : ℕ} {D : ContinuousDrawing m n} (V : VertexTruncation D) + +theorem piece_subset_range (e : BipartiteEdge m n) (i : ℕ) (hi : i omega + +theorem spokeDirection_ne_zero (j : BipartiteVertex m n) (e : IncidentEdges j) : + V.spokeDirection j e ≠ 0 := V.direction_ne_zero e.val _ (V.spokeIndex_lt j e) + +theorem spokeDirection_eq_scale (j : BipartiteVertex m n) (e : IncidentEdges j) : + V.spokeDirection j e = + (V.chain e.val).truncatedScale V.radius (V.spokeIndex j e) • + drawingSpokeDirection D V.chain j e := by + change trackDirection ((V.chain e.val).truncatedVertices V.radius) (V.spokeIndex j e)=_ + rw [(V.chain e.val).truncated_direction V.radius _ (V.spokeIndex_lt j e)] + congr 1 + unfold spokeIndex drawingSpokeDirection + split_ifs <;> rfl + +theorem spokePort_circle (j : BipartiteVertex m n) (e : IncidentEdges j) : + squaredLength (V.spokePort j e-D.vertex j)=V.radius^2 := + drawingSpokePort_circle D V.chain V.minimal V.radius j e + +theorem spokePort_ne_center (j : BipartiteVertex m n) (e : IncidentEdges j) : + V.spokePort j e-D.vertex j ≠ 0 := by + intro h + have hc := V.spokePort_circle j e + rw [h] at hc + have hz : squaredLength (0 : Plane)=0 := by simp [squaredLength] + rw [hz] at hc + nlinarith [V.radius_pos] + +theorem spokeDirection_parallel (j : BipartiteVertex m n) (e : IncidentEdges j) : + det2 (V.spokeDirection j e) (V.spokePort j e-D.vertex j)=0 := by + rw [V.spokeDirection_eq_scale,det2_smul_left] + have hp := drawingSpokeDirection_port_parallel D V.chain V.radius j e (V.pieces_pos e.val) + change det2 (drawingSpokeDirection D V.chain j e) (V.spokePort j e-D.vertex j)=0 at hp + rw [hp,mul_zero] + +def spokeScale (j : BipartiteVertex m n) (e : IncidentEdges j) : ℝ := + circleTrackScale (V.spokeDirection j e) (V.spokePort j e-D.vertex j) + +theorem spokeScale_ne_zero (j : BipartiteVertex m n) (e : IncidentEdges j) : + V.spokeScale j e ≠ 0 := + circleTrackScale_ne_zero _ _ (V.spokeDirection_ne_zero j e) + (V.spokePort_ne_center j e) (V.spokeDirection_parallel j e) + +theorem spokePort_injective {A : AdmissibleDrawing m n} + (V : VertexTruncation A.toContinuousDrawing) (hnorm : NoAdjacentCrossings A) + (j : BipartiteVertex m n) : Function.Injective (V.spokePort j) := + drawingSpokePort_injective A hnorm V.chain V.minimal V.radius V.radius_pos V.weak_short j + +end Zarankiewicz.VertexTruncation + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/TruncatedTraceDecomposition.lean b/lean/OAI/Combinatorics/Crossing/TruncatedTraceDecomposition.lean new file mode 100644 index 0000000000000000000000000000000000000000..07cbed7fb343ce1496598c008a8699fdc798cd46 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/TruncatedTraceDecomposition.lean @@ -0,0 +1,67 @@ +import OAI.Combinatorics.Crossing.TruncatedChainPath + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +theorem center_segment_in_disk (o p : Plane) (r : ℝ) (hp : squaredLength (p-o)=r^2) : + segment ℝ o p ⊆ closedRoundDisk o r := by + intro x hx + rw [← Path.range_segment] at hx + obtain ⟨t,ht⟩ := hx + have he : squaredLength (segmentPoint o p t.val-o)=t.val^2*squaredLength (p-o) := by + dsimp [segmentPoint,squaredLength] + ring + have ht2 : t.val^2 ≤ 1 := by nlinarith [t.property.1,t.property.2] + have hh := mul_le_mul_of_nonneg_right ht2 (sq_nonneg r) + change squaredLength (x-o) ≤ r^2 + have ht' : segmentPoint o p t.val=x := by + simpa only [Path.segment_apply,AffineMap.lineMap_apply_module,segmentPoint] using ht + rw [← ht',he,hp] + simpa only [one_mul] using hh + +theorem drawing_edge_trace_decomposition {m n : ℕ} (D : ContinuousDrawing m n) + (e : BipartiteEdge m n) + (P : PolygonalChain (Set.range (D.edge e)) (D.vertex (.inl e.1)) (D.vertex (.inr e.2))) + (r : ℝ) (hr : 0 < r) + (hfirst : r^2 < squaredLength (P.vertices 1-P.vertices 0)) + (hlast : r^2 < squaredLength (P.vertices P.pieces-P.vertices (P.pieces-1))) : + Set.range (D.edge e)= + segment ℝ (D.vertex (.inl e.1)) (P.startPort r) ∪ + Set.range (polygonalArcPath (P.truncatedVertices r) P.pieces) ∪ + segment ℝ (P.endPort r) (D.vertex (.inr e.2)) := by + have hp := drawing_chain_pieces_pos D e P + have hs : segment ℝ (D.vertex (.inl e.1)) (P.startPort r) ⊆ Set.range (D.edge e) := by + have hx := openSegmentTrace_subset_segment _ _ (radialPort_mem_openSegment (P.vertices 0) (P.vertices 1) r hr hfirst) + have hh := ((convex_segment (𝕜 := ℝ) _ _).segment_subset (left_mem_segment ℝ _ _) hx).trans (P.inside 0 hp) + simpa only [PolygonalChain.startPort,P.first] using hh + have ht : segment ℝ (P.endPort r) (D.vertex (.inr e.2)) ⊆ Set.range (D.edge e) := by + have hlen : r^2 < squaredLength (P.vertices (P.pieces-1)-P.vertices P.pieces) := by + rwa [squaredLength_sub_comm] + have hx := openSegmentTrace_subset_segment _ _ + (openSegmentTrace_reverse_mem _ _ _ (radialPort_mem_openSegment _ _ r hr hlen)) + have hinside := P.inside (P.pieces-1) (by omega) + rw [show P.pieces-1+1=P.pieces by omega] at hinside + have hh := ((convex_segment (𝕜 := ℝ) _ _).segment_subset hx (right_mem_segment ℝ _ _)).trans hinside + simpa only [PolygonalChain.endPort,P.last] using hh + let T := P.truncated hp r hr hfirst hlast + let G := ((Path.segment (D.vertex (.inl e.1)) (P.startPort r)).trans T.path).trans + (Path.segment (P.endPort r) (D.vertex (.inr e.2))) + have hG : Set.range G ⊆ Set.range (D.edge e) := by + dsimp [G] + rw [Path.trans_range,Path.trans_range,Path.range_segment,Path.range_segment] + exact Set.union_subset (Set.union_subset hs T.path_range_subset) ht + have he := path_range_eq_of_subset (D.edge e) G (D.edge_injective e) hG + calc + Set.range (D.edge e) = Set.range G := he.symm + _ = _ := by + dsimp [G] + rw [Path.trans_range,Path.trans_range,Path.range_segment,Path.range_segment] + rfl + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/TruncatedTrackAvoidance.lean b/lean/OAI/Combinatorics/Crossing/TruncatedTrackAvoidance.lean new file mode 100644 index 0000000000000000000000000000000000000000..7653bc8c826e79b576eec15ab9e8369149f31d38 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/TruncatedTrackAvoidance.lean @@ -0,0 +1,52 @@ +import OAI.Combinatorics.Crossing.TruncatedChainDirections +import OAI.Combinatorics.Crossing.SegmentClosedIncidence +import OAI.Combinatorics.Crossing.SharedTrackAvoidance + +namespace OAI + +noncomputable section +namespace Zarankiewicz.PolygonalChain +variable {O : Set Plane} {a b : Plane} + +theorem truncated_bend_ne_zero (P : PolygonalChain O a b) + (hmin : ∀ Q : PolygonalChain O a b, P.pieces ≤ Q.pieces) + (r : ℝ) (hr : 0 < r) + (hfirst : 4*r^2 < squaredLength (P.vertices 1-P.vertices 0)) + (hlast : 4*r^2 < squaredLength (P.vertices P.pieces-P.vertices (P.pieces-1))) + (i : ℕ) (hi : 0 < i) (hi' : i < P.pieces) : + det2 (trackDirection (P.truncatedVertices r) (i-1)) (trackDirection (P.truncatedVertices r) i) ≠ 0 := by + rw [P.truncated_direction r (i-1) (by omega),P.truncated_direction r i hi',det2_smul_left,det2_smul_right] + apply mul_ne_zero (ne_of_gt (P.truncatedScale_pos r hr hfirst hlast (i-1))) + apply mul_ne_zero (ne_of_gt (P.truncatedScale_pos r hr hfirst hlast i)) + have h := P.minimum_bend_det_ne_zero hmin (i-1) (by omega) + simpa only [trackDirection,show i-1+1=i by omega,show i-1+2=i+1 by omega] using h + +theorem truncated_offset_avoidance (P : PolygonalChain O a b) + (hmin : ∀ Q : PolygonalChain O a b, P.pieces ≤ Q.pieces) + (r : ℝ) (hr : 0 < r) + (hfirst : 4*r^2 < squaredLength (P.vertices 1-P.vertices 0)) + (hlast : 4*r^2 < squaredLength (P.vertices P.pieces-P.vertices (P.pieces-1))) : + ∃ δ : ℝ, 0 < δ ∧ ∀ t : ℝ, t ≠ 0 → |t| < δ → ∀ i j : Fin P.pieces, + ¬ ClosedSegmentsMeet (P.truncatedVertices r i.val) (P.truncatedVertices r (i.val+1)) + (shiftedTrack (P.truncatedVertices r) P.pieces t j.val) + (shiftedTrack (P.truncatedVertices r) P.pieces t (j.val+1)) := by + apply exists_shared_track_avoidance_radius (P.truncatedVertices r) P.pieces + (P.truncated_direction_ne_zero hmin r hr hfirst hlast) + (P.truncated_bend_ne_zero hmin r hr hfirst hlast) + intro i j hij + have hdis : Disjoint (segment ℝ (P.vertices i.val) (P.vertices (i.val+1))) + (segment ℝ (P.vertices j.val) (P.vertices (j.val+1))) := by + rcases hij with h | h + · exact P.minimum_nonadjacent_disjoint hmin i.val j.val h j.isLt + · exact (P.minimum_nonadjacent_disjoint hmin j.val i.val h i.isLt).symm + have hfst : r^2 < squaredLength (P.vertices 1-P.vertices 0) := by nlinarith [sq_nonneg r] + have hlst : r^2 < squaredLength (P.vertices P.pieces-P.vertices (P.pieces-1)) := by nlinarith [sq_nonneg r] + exact not_closedSegmentsMeet_of_disjoint _ _ _ _ (hdis.mono + (P.truncated_piece_subset r hr hfst hlst i.val i.isLt) + (P.truncated_piece_subset r hr hfst hlst j.val j.isLt)) + +end Zarankiewicz.PolygonalChain + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/TruncatedTrackStability.lean b/lean/OAI/Combinatorics/Crossing/TruncatedTrackStability.lean new file mode 100644 index 0000000000000000000000000000000000000000..969f56f4917d9725d8e5a266322bbc22791ffa06 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/TruncatedTrackStability.lean @@ -0,0 +1,41 @@ +import OAI.Combinatorics.Crossing.VertexTruncationGeometry + +namespace OAI + +noncomputable section +namespace Zarankiewicz.VertexTruncation +variable {m n : ℕ} {D : AdmissibleDrawing m n} + +theorem exists_distinct_edge_shift_radius (V : VertexTruncation D.toContinuousDrawing) + (hnorm : NoAdjacentCrossings D) (hstraight : LocallyStraightCrossings D) (htrans : LocallyTransverseCrossings D) : + ∃ δ : ℝ, 0 < δ ∧ ∀ t : ℝ, |t| < δ → ∀ e f : BipartiteEdge m n, e ≠ f → + ∀ i : Fin (V.pieces e), ∀ j : Fin (V.pieces f), + SegmentPairTransverse (V.vertices e i.val) (V.vertices e (i.val+1)) + (shiftedTrack (V.vertices f) (V.pieces f) t j.val) + (shiftedTrack (V.vertices f) (V.pieces f) t (j.val+1)) ∧ + segmentCrossingSign (V.vertices e i.val) (V.vertices e (i.val+1)) + (shiftedTrack (V.vertices f) (V.pieces f) t j.val) + (shiftedTrack (V.vertices f) (V.pieces f) t (j.val+1)) = + segmentCrossingSign (V.vertices e i.val) (V.vertices e (i.val+1)) + (V.vertices f j.val) (V.vertices f (j.val+1)) := by + classical + let Pair := Σ e : BipartiteEdge m n, Σ f : {f : BipartiteEdge m n // e ≠ f}, + Fin (V.pieces e) × Fin (V.pieces f.val) + let a : Pair → Plane := fun k => V.vertices k.1 k.2.2.1.val + let b : Pair → Plane := fun k => V.vertices k.1 (k.2.2.1.val+1) + let c : Pair → Plane := fun k => V.vertices k.2.1.val k.2.2.2.val + let d : Pair → Plane := fun k => V.vertices k.2.1.val (k.2.2.2.val+1) + let qc : Pair → Plane := fun k => trackOffset (V.vertices k.2.1.val) (V.pieces k.2.1.val) k.2.2.2.val + let qd : Pair → Plane := fun k => trackOffset (V.vertices k.2.1.val) (V.pieces k.2.1.val) (k.2.2.2.val+1) + have hh (k : Pair) : SegmentPairTransverse (a k) (b k) (c k) (d k) := + V.pair_transverse hnorm hstraight htrans k.1 k.2.1.val k.2.1.property k.2.2.1 k.2.2.2 + obtain ⟨δ,hδ,hstable⟩ := exists_shifted_segment_pairs_radius a b c d qc qd hh + refine ⟨δ,hδ,?_⟩ + intro t ht e f hef i j + exact hstable t ht ⟨e,⟨f,hef⟩,i,j⟩ + +end Zarankiewicz.VertexTruncation + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/TwoTriangleBasis.lean b/lean/OAI/Combinatorics/Crossing/TwoTriangleBasis.lean new file mode 100644 index 0000000000000000000000000000000000000000..daf0cb59f232e916f34d312fbbad21cb76af0f64 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/TwoTriangleBasis.lean @@ -0,0 +1,65 @@ +import OAI.Combinatorics.Crossing.BivariateCoefficients + +namespace OAI + +noncomputable section +namespace Zarankiewicz +open Module +open scoped BigOperators + +abbrev TriangleIndex (s : ℕ) := ↥(twoTriangle s) + +def triangleCoordEquiv (s : ℕ) : BiExponent s ≃ TriangleIndex s := + Fintype.equivOfCardEq (by simp [BiExponent, TriangleIndex, card_twoTriangle]) + +def monomialVector (s : ℕ) (node : ℕ → ℝ) (p q : ℕ) : BiExponent s → ℝ := + fun ab => node p ^ ab.1.val * node q ^ ab.2.val + +def triangleMatrix (s : ℕ) (node : ℕ → ℝ) : Matrix (BiExponent s) (BiExponent s) ℝ := + fun ab j => monomialVector s node (triangleCoordEquiv s j).val.1 + (triangleCoordEquiv s j).val.2 ab + +theorem triangleMatrix_eval (s : ℕ) (node : ℕ → ℝ) (c : BiExponent s → ℝ) + (j : BiExponent s) : + (triangleMatrix s node).transpose.mulVec c j = + biEval (node (triangleCoordEquiv s j).val.1) (node (triangleCoordEquiv s j).val.2) + (biOfCoeffs s c) := by + rw [biEval_biOfCoeffs] + simp only [Matrix.mulVec, dotProduct, Matrix.transpose_apply, triangleMatrix, + monomialVector, Fintype.sum_prod_type] + +theorem triangleMatrix_isUnit (s : ℕ) (node : ℕ → ℝ) + (hn : Set.InjOn node (Set.Icc 1 (2*s+1))) : IsUnit (triangleMatrix s node) := by + rw [← Matrix.isUnit_transpose, ← Matrix.mulVec_injective_iff_isUnit] + intro c d hcd + apply biOfCoeffs_injective s + apply twoTriangle_evaluation_injective s node hn (biOfCoeffs s c) (biOfCoeffs s d) + (biOfCoeffs_bounded s c) (biOfCoeffs_bounded s d) + intro p q hpq + let j := (triangleCoordEquiv s).symm ⟨(p,q), hpq⟩ + have hh := congrFun hcd j + rw [triangleMatrix_eval, triangleMatrix_eval] at hh + simpa only [j, Equiv.apply_symm_apply] using hh + +def twoTriangleBasis (s : ℕ) (node : ℕ → ℝ) + (hn : Set.InjOn node (Set.Icc 1 (2*s+1))) : + Basis (BiExponent s) ℝ (BiExponent s → ℝ) := + (Pi.basisFun ℝ (BiExponent s)).map + (LinearEquiv.ofBijective (triangleMatrix s node).mulVecLin + ⟨Matrix.mulVec_injective_of_isUnit (triangleMatrix_isUnit s node hn), + Matrix.mulVec_surjective_iff_isUnit.mpr (triangleMatrix_isUnit s node hn)⟩) + +theorem twoTriangleBasis_apply (s : ℕ) (node : ℕ → ℝ) + (hn : Set.InjOn node (Set.Icc 1 (2*s+1))) (j : BiExponent s) : + twoTriangleBasis s node hn j = + monomialVector s node (triangleCoordEquiv s j).val.1 (triangleCoordEquiv s j).val.2 := by + simp only [twoTriangleBasis, Basis.map_apply, Pi.basisFun_apply] + change (triangleMatrix s node).mulVec (Pi.single j 1) = _ + funext i + simp [Matrix.mulVec_single, triangleMatrix] + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/TwoTriangleIndices.lean b/lean/OAI/Combinatorics/Crossing/TwoTriangleIndices.lean new file mode 100644 index 0000000000000000000000000000000000000000..ab30ca64563c8fe64ddfada85ddf94eaefad4358 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/TwoTriangleIndices.lean @@ -0,0 +1,101 @@ +import Mathlib.Data.Finset.Prod +import Mathlib.Order.Interval.Finset.Nat +import Mathlib.Data.Nat.Choose.Basic +import Mathlib.Tactic.Linarith +import Lean.Elab.Tactic.Omega + +namespace OAI + +namespace Zarankiewicz +open Finset + +def lowerTriangle (s : ℕ) : Finset (ℕ × ℕ) := + ((Icc 1 (s+1)) ×ˢ (Icc 1 (s+1))).filter (fun z => z.2 < z.1) + +def upperTriangle (s : ℕ) : Finset (ℕ × ℕ) := + ((Icc (s+2) (2*s+1)) ×ˢ (Icc (s+2) (2*s+1))).filter (fun z => z.1 < z.2) + +def twoTriangle (s : ℕ) : Finset (ℕ × ℕ) := lowerTriangle s ∪ upperTriangle s + +theorem mem_lowerTriangle (s p q : ℕ) : + (p,q) ∈ lowerTriangle s ↔ 1 ≤ q ∧ q < p ∧ p ≤ s+1 := by + simp only [lowerTriangle, mem_filter, mem_product, mem_Icc] + omega + +theorem mem_upperTriangle (s p q : ℕ) : + (p,q) ∈ upperTriangle s ↔ s+1 < p ∧ p < q ∧ q ≤ 2*s+1 := by + simp only [upperTriangle, mem_filter, mem_product, mem_Icc] + omega + +theorem mem_twoTriangle (s p q : ℕ) : + (p,q) ∈ twoTriangle s ↔ + (1 ≤ q ∧ q < p ∧ p ≤ s+1) ∨ (s+1 < p ∧ p < q ∧ q ≤ 2*s+1) := by + rw [twoTriangle, mem_union, mem_lowerTriangle, mem_upperTriangle] + +theorem disjoint_triangles (s : ℕ) : Disjoint (lowerTriangle s) (upperTriangle s) := by + apply Finset.disjoint_left.mpr + rintro ⟨p,q⟩ hp hq + rw [mem_lowerTriangle] at hp + rw [mem_upperTriangle] at hq + omega + +theorem card_lowerTriangle (s : ℕ) : (lowerTriangle s).card = (s+1).choose 2 := by + have hswap : (lowerTriangle s).card = + (((Icc 1 (s+1)) ×ˢ (Icc 1 (s+1))).filter (fun z => z.1 < z.2)).card := + Finset.card_equiv (Equiv.prodComm ℕ ℕ) (by + intro z + simp [lowerTriangle, and_comm, and_left_comm, and_assoc]) + rw [hswap, Finset.card_product_filter_lt] + simp + +theorem card_upperTriangle (s : ℕ) : (upperTriangle s).card = s.choose 2 := by + have h := Finset.card_product_filter_lt (s := Icc (s+2) (2*s+1)) + have hc : (Icc (s+2) (2*s+1)).card = s := by simp; omega + simpa [upperTriangle, hc] using h + +theorem adjacent_choose_two (s : ℕ) : (s+1).choose 2 + s.choose 2 = s*s := by + induction s with + | zero => simp + | succ s ih => + have ha : (s+2).choose 2 = (s+1).choose 2 + (s+1) := by + calc + (s+2).choose 2 = (s+1).choose 1 + (s+1).choose 2 := Nat.choose_succ_succ (s+1) 1 + _ = (s+1).choose 2 + (s+1) := by rw [Nat.choose_one_right]; omega + have hb : (s+1).choose 2 = s.choose 2 + s := by + simpa [Nat.choose_one_right, Nat.succ_eq_add_one, Nat.add_comm] using + (Nat.choose_succ_succ s 1) + have : s+1+1 = s+2 := by omega + rw [this, ha] + nlinarith + +theorem card_twoTriangle (s : ℕ) : (twoTriangle s).card = s*s := by + rw [twoTriangle, card_union_of_disjoint (disjoint_triangles s), card_lowerTriangle, + card_upperTriangle, adjacent_choose_two] + +def triangleRelabel (s k : ℕ) : ℕ := if k ≤ s then s+1+k else k-s+1 + +theorem triangleRelabel_injective_on (s : ℕ) : + Set.InjOn (triangleRelabel s) (Set.Icc 1 (2*s-1)) := by + intro p hp q hq he + simp only [Set.mem_Icc] at hp hq + unfold triangleRelabel at he + split_ifs at he <;> omega + +theorem triangleRelabel_range (s k : ℕ) (hk : k ∈ Icc 1 (2*s-1)) : + triangleRelabel s k ∈ Icc 1 (2*s+1) ∧ + triangleRelabel s k ≠ s+1 ∧ triangleRelabel s k ≠ 1 := by + simp only [mem_Icc] at hk ⊢ + unfold triangleRelabel + split_ifs <;> omega + +theorem relabel_twoTriangle (s : ℕ) (hs : 1 ≤ s) (p q : ℕ) + (hpq : (p,q) ∈ twoTriangle (s-1)) : + (triangleRelabel s q, triangleRelabel s p) ∈ twoTriangle s ∧ + triangleRelabel s q ≠ s+1 ∧ triangleRelabel s p ≠ 1 := by + rw [mem_twoTriangle] at hpq ⊢ + unfold triangleRelabel + split_ifs <;> omega + +end Zarankiewicz + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/TwoTriangleUnisolvence.lean b/lean/OAI/Combinatorics/Crossing/TwoTriangleUnisolvence.lean new file mode 100644 index 0000000000000000000000000000000000000000..9a91409e7bd57af85f03c32fd8f3047585ad49aa --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/TwoTriangleUnisolvence.lean @@ -0,0 +1,133 @@ +import OAI.Combinatorics.Crossing.Bivariate +import OAI.Combinatorics.Crossing.TwoTriangleIndices + +namespace OAI + +noncomputable section +namespace Zarankiewicz +open PolynomialModule +open Finset + +theorem eq_zero_of_roots_injOn {W : Type*} [AddCommGroup W] [Module ℝ W] + (node : ℕ → ℝ) (S : Finset ℕ) (hn : Set.InjOn node (S : Set ℕ)) + (p : PolynomialModule ℝ W) (hp : Bounded S.card p) + (he : ∀ i ∈ S, eval (node i) p = 0) : p = 0 := by + let x : S → ℝ := fun i => node i.val + have hx : Function.Injective x := by + intro i j hij + exact Subtype.ext (hn i.property j.property hij) + apply eq_zero_of_node_roots x hx Finset.univ p + · simpa using hp + · intro i hi + exact he i.val i.property + +theorem twoTriangle_unisolvent (s : ℕ) (node : ℕ → ℝ) + (hn : Set.InjOn node (Set.Icc 1 (2*s+1))) (p : BiPoly) + (hp : BiBounded s s p) + (hv : ∀ a b, (a,b) ∈ twoTriangle s → biEval (node a) (node b) p = 0) : p = 0 := by + induction s generalizing node p with + | zero => exact (bounded_zero_iff p).mp hp.1 + | succ k ih => + have node_ne : ∀ a b, a ∈ Icc 1 (2*(k+1)+1) → b ∈ Icc 1 (2*(k+1)+1) → + a ≠ b → node a ≠ node b := by + intro a b ha hb hab he + exact hab (hn (by simpa only [mem_Icc, Set.mem_Icc] using ha) + (by simpa only [mem_Icc, Set.mem_Icc] using hb) he) + + have hrow : eval (node (k+2)) p = 0 := by + apply eq_zero_of_roots_injOn node (Icc 1 (k+1)) + · intro a ha b hb he + apply hn _ _ he <;> simp only [mem_coe, mem_Icc, Set.mem_Icc] at * <;> omega + · simpa using bounded_eval_outer hp (node (k+2)) + · intro q hq + apply hv (k+2) q + rw [mem_twoTriangle] + simp only [mem_Icc] at hq + left + omega + obtain ⟨p₁, hp₁, he₁⟩ := bi_factor_row k (k+1) p hp (node (k+2)) hrow + + have hcol : eval (node 1) (swapBi p₁) = 0 := by + apply eq_zero_of_roots_injOn node (Icc 2 (k+1)) + · intro a ha b hb he + apply hn _ _ he <;> simp only [mem_coe, mem_Icc, Set.mem_Icc] at * <;> omega + · simpa using bounded_eval_outer (biBounded_swap hp₁) (node 1) + · intro a ha + change biEval (node 1) (node a) (swapBi p₁) = 0 + rw [biEval_swap] + have hpa : biEval (node a) (node 1) p = 0 := by + apply hv + rw [mem_twoTriangle] + simp only [mem_Icc] at ha + left + omega + rw [← he₁, biEval_mulRoot] at hpa + apply (mul_eq_zero.mp hpa).resolve_left + apply sub_ne_zero.mpr + apply node_ne a (k+2) <;> simp only [mem_Icc] at * <;> omega + obtain ⟨r, hr, her⟩ := bi_factor_row k k (swapBi p₁) (biBounded_swap hp₁) (node 1) hcol + + let y : ℕ → ℝ := fun i => node (triangleRelabel (k+1) i) + have hyrange : ∀ a, a ∈ Icc 1 (2*k+1) → + triangleRelabel (k+1) a ∈ Icc 1 (2*(k+1)+1) ∧ + triangleRelabel (k+1) a ≠ k+2 ∧ triangleRelabel (k+1) a ≠ 1 := by + intro a ha + simpa only [show k+1+1 = k+2 from rfl] using + triangleRelabel_range (k+1) a (by simp only [mem_Icc] at *; omega) + have hyn : Set.InjOn y (Set.Icc 1 (2*k+1)) := by + intro a ha b hb he + have ha' : a ∈ Icc 1 (2*k+1) := by simpa only [mem_Icc, Set.mem_Icc] using ha + have hb' : b ∈ Icc 1 (2*k+1) := by simpa only [mem_Icc, Set.mem_Icc] using hb + apply triangleRelabel_injective_on (k+1) + · simp only [Set.mem_Icc] at * + omega + · simp only [Set.mem_Icc] at * + omega + · exact hn (by simpa only [Set.mem_Icc, mem_Icc] using (hyrange a ha').1) + (by simpa only [Set.mem_Icc, mem_Icc] using (hyrange b hb').1) he + have hrv : ∀ a b, (a,b) ∈ twoTriangle k → biEval (y a) (y b) r = 0 := by + intro a b hab + have ha : a ∈ Icc 1 (2*k+1) := by + rw [mem_twoTriangle] at hab + simp only [mem_Icc] + omega + have hb : b ∈ Icc 1 (2*k+1) := by + rw [mem_twoTriangle] at hab + simp only [mem_Icc] + omega + have hpattern := relabel_twoTriangle (k+1) (by omega) a b (by simpa using hab) + have hval := hv (triangleRelabel (k+1) b) (triangleRelabel (k+1) a) hpattern.1 + rw [← he₁, biEval_mulRoot] at hval + have hfirst : node (triangleRelabel (k+1) b) - node (k+2) ≠ 0 := + sub_ne_zero.mpr (node_ne _ _ (hyrange b hb).1 (by simp) (hyrange b hb).2.1) + have hp₁val := (mul_eq_zero.mp hval).resolve_left hfirst + have hswap : p₁ = swapBi (mulRoot (node 1) r) := by rw [her, swapBi_swapBi] + rw [hswap, biEval_swap, biEval_mulRoot] at hp₁val + apply (mul_eq_zero.mp hp₁val).resolve_left + exact sub_ne_zero.mpr (node_ne _ _ (hyrange a ha).1 (by simp) (hyrange a ha).2.2) + have hr0 := ih y hyn r hr hrv + have hp₁0 : p₁ = 0 := by + apply swapBi.injective + rw [← her, hr0] + simp [mulRoot] + rw [← he₁, hp₁0] + simp [mulRoot] + +theorem twoTriangle_evaluation_injective (s : ℕ) (node : ℕ → ℝ) + (hn : Set.InjOn node (Set.Icc 1 (2*s+1))) (p q : BiPoly) + (hp : BiBounded s s p) (hq : BiBounded s s q) + (he : ∀ a b, (a,b) ∈ twoTriangle s → biEval (node a) (node b) p = biEval (node a) (node b) q) : + p = q := by + apply sub_eq_zero.mp + apply twoTriangle_unisolvent s node hn (p-q) + · refine ⟨bounded_sub hp.1 hq.1, ?_⟩ + intro a + exact bounded_sub (hp.2 a) (hq.2 a) + · intro a b hab + rw [map_sub, he a b hab, sub_self] + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/UniformCrossTypeGeometry.lean b/lean/OAI/Combinatorics/Crossing/UniformCrossTypeGeometry.lean new file mode 100644 index 0000000000000000000000000000000000000000..69dc0ea4888de7380a3d7380aea988d419fa55fd --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/UniformCrossTypeGeometry.lean @@ -0,0 +1,73 @@ +import OAI.Combinatorics.Crossing.ChordExteriorSeparation +import OAI.Combinatorics.Crossing.ConnectorTrackAvoidance +import OAI.Combinatorics.Crossing.SegmentTraversalReversal + +namespace OAI + +noncomputable section +namespace Zarankiewicz.TruncatedSpokeCoordinates +variable {m n : ℕ} {D : AdmissibleDrawing m n} {V : VertexTruncation D.toContinuousDrawing} + (C : TruncatedSpokeCoordinates V) + +theorem exists_cross_type_radius (hnorm : NoAdjacentCrossings D) : + ∃ δ : ℝ, 0<δ ∧ ∀ ε : ℝ, ε ≠ 0 → |ε|<δ → + (∀ j (f : IncidentEdges j) e (i : Fin (V.pieces e)), + ¬ ClosedSegmentsMeet (V.vertices e i.val) (V.vertices e (i.val+1)) + (C.shiftedPort j f ε) (C.tangentPort j f ε)) ∧ + (∀ j (c d : IncidentEdges j) e (i : Fin (V.pieces e)), + ¬ ClosedSegmentsMeet (V.vertices e i.val) (V.vertices e (i.val+1)) + (C.shiftedPort j c ε) (C.shiftedPort j d ε)) ∧ + (∀ j (a b : IncidentEdges j) e (i : Fin (V.pieces e)), + ¬ ClosedSegmentsMeet (V.spokePort j a) (V.spokePort j b) + (shiftedTrack (V.vertices e) (V.pieces e) ε i.val) + (shiftedTrack (V.vertices e) (V.pieces e) ε (i.val+1))) ∧ + (∀ j k (a b : IncidentEdges j) (f : IncidentEdges k), + ¬ ClosedSegmentsMeet (V.spokePort j a) (V.spokePort j b) + (C.shiftedPort k f ε) (C.tangentPort k f ε)) ∧ + (∀ j k (a b : IncidentEdges j) (c d : IncidentEdges k), a ≠ b → c ≠ d → + SegmentPairTransverse (V.spokePort j a) (V.spokePort j b) (C.shiftedPort k c ε) (C.shiftedPort k d ε)) ∧ + (∀ j k, j ≠ k → ∀ (a b : IncidentEdges j) (c d : IncidentEdges k), + ¬ ClosedSegmentsMeet (V.spokePort j a) (V.spokePort j b) (C.shiftedPort k c ε) (C.shiftedPort k d ε)) := by + obtain ⟨δ₀,hδ₀,htracks⟩ := V.exists_all_vertex_disk_radius + obtain ⟨δ₁,hδ₁,hconnectors⟩ := C.exists_all_connector_track_radius hnorm + obtain ⟨δ₂,hδ₂,hother⟩ := C.exists_connector_other_disks_radius + obtain ⟨δ₃,hδ₃,hseparate⟩ := C.exists_uniform_endpoint_radius + obtain ⟨δ₄,hδ₄,hscale⟩ := C.exists_uniform_scale_radius + let δ := min δ₀ (min δ₁ (min δ₂ (min δ₃ δ₄))) + have hδ : 0<δ := lt_min hδ₀ (lt_min hδ₁ (lt_min hδ₂ (lt_min hδ₃ hδ₄))) + have hb₀ : δ≤δ₀ := min_le_left _ _ + have hb₁ : δ≤δ₁ := (min_le_right _ _).trans (min_le_left _ _) + have hb₂ : δ≤δ₂ := (min_le_right _ _).trans ((min_le_right _ _).trans (min_le_left _ _)) + have hb₃ : δ≤δ₃ := (min_le_right _ _).trans ((min_le_right _ _).trans ((min_le_right _ _).trans (min_le_left _ _))) + have hb₄ : δ≤δ₄ := (min_le_right _ _).trans ((min_le_right _ _).trans ((min_le_right _ _).trans (min_le_right _ _))) + refine ⟨δ,hδ,?_⟩ + intro ε hε hsmall + have hs := hscale ε (hsmall.trans_le hb₄) + have hsep := hseparate ε hε (hsmall.trans_le hb₃) + refine ⟨hconnectors ε hε (hsmall.trans_le hb₁),?_,?_,?_,?_,?_⟩ + · intro j c d e i + exact C.track_shifted_chord_disjoint j c d ε (hs j c).le (hs j d).le (hsep j).1 e i + · intro j a b e i + exact round_chord_exterior_disjoint (D.vertex j) _ _ _ _ V.radius + (V.spokePort_circle j a) (V.spokePort_circle j b) (htracks ε hε (hsmall.trans_le hb₀) j e i) + · intro j k a b f + by_cases hjk : j=k + · subst k + exact C.chord_connector_disjoint_all_passages j a b f ε hε (hs j f) ((hsep j).1 a f) ((hsep j).1 b f) + · exact round_chord_exterior_disjoint (D.vertex j) _ _ _ _ V.radius + (V.spokePort_circle j a) (V.spokePort_circle j b) + (hother ε (hsmall.trans_le hb₂) k j (Ne.symm hjk) f) + · intro j k a b c d hab hcd + by_cases hjk : j=k + · subst k + exact C.shifted_chords_transverse j a b c d ε (fun e => (hs j e).le) (hsep j).1 (hsep j).2 hab hcd + · exact segmentPairTransverse_of_not_meet _ _ _ _ + (C.different_vertex_chords_disjoint j k hjk a b c d ε (hs k c).le (hs k d).le) + · intro j k hjk a b c d + exact C.different_vertex_chords_disjoint j k hjk a b c d ε (hs k c).le (hs k d).le + +end Zarankiewicz.TruncatedSpokeCoordinates + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/UniformSpokeRadii.lean b/lean/OAI/Combinatorics/Crossing/UniformSpokeRadii.lean new file mode 100644 index 0000000000000000000000000000000000000000..da651b5f059d3bcc78fb79d305d2dc87c61268a9 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/UniformSpokeRadii.lean @@ -0,0 +1,49 @@ +import OAI.Combinatorics.Crossing.SpokeEndpointSeparation +import OAI.Combinatorics.Crossing.FiniteScaledRadius + +namespace OAI + +noncomputable section +namespace Zarankiewicz.TruncatedSpokeCoordinates +variable {m n : ℕ} {D : ContinuousDrawing m n} {V : VertexTruncation D} + (C : TruncatedSpokeCoordinates V) + +theorem port_injective (C : TruncatedSpokeCoordinates V) (j : BipartiteVertex m n) : Function.Injective (V.spokePort j) := by + intro e f he + apply C.node_injective j + apply circlePoint_injective + apply similarityPoint_injective (D.vertex j) (C.frame j) (C.frame_ne_zero j) + simpa only [C.point_eq] using he + +theorem exists_uniform_endpoint_radius : + ∃ δ : ℝ, 0<δ ∧ ∀ ε : ℝ, ε ≠ 0 → |ε|<δ → ∀ j : BipartiteVertex m n, + (∀ e f : IncidentEdges j, V.spokePort j e ≠ C.shiftedPort j f ε) ∧ + Function.Injective (fun e : IncidentEdges j => C.shiftedPort j e ε) := by + classical + choose radius hpos hprop using C.exists_endpoint_separation_radius + obtain ⟨δ,hδ,hbound⟩ := finite_positive_lower_bound Finset.univ radius (fun j _ => hpos j) + exact ⟨δ,hδ,fun ε hε hsmall j => hprop j ε hε (hsmall.trans (hbound j (Finset.mem_univ _)))⟩ + +theorem exists_uniform_scale_radius (_C : TruncatedSpokeCoordinates V) : + ∃ δ : ℝ, 0<δ ∧ ∀ ε : ℝ, |ε|<δ → ∀ j (e : IncidentEdges j), |V.spokeScale j e*ε|<1 := by + let Spoke := Σ j : BipartiteVertex m n, IncidentEdges j + obtain ⟨δ,hδ,hbound⟩ := finite_scaled_radius + (fun s : Spoke => V.spokeScale s.1 s.2) (fun _ => (1 : ℝ)) (by intro s; norm_num) + exact ⟨δ,hδ,fun ε hε j e => hbound ε hε ⟨j,e⟩⟩ + +theorem exists_uniform_average_radius : + ∃ δ : ℝ, 0<δ ∧ ∀ t : ℝ, 0 hpos j) + exact ⟨δ,hδ,fun t ht hsmall j => hprop j t ht (hsmall.trans (hbound j (Finset.mem_univ _)))⟩ + +end Zarankiewicz.TruncatedSpokeCoordinates + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/UniformTrackPerturbation.lean b/lean/OAI/Combinatorics/Crossing/UniformTrackPerturbation.lean new file mode 100644 index 0000000000000000000000000000000000000000..ec9d0f0dd96c89006f939702efdfe7a9d890ff82 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/UniformTrackPerturbation.lean @@ -0,0 +1,74 @@ +import OAI.Combinatorics.Crossing.TruncatedTrackStability +import OAI.Combinatorics.Crossing.PolygonalWalks + +namespace OAI + +noncomputable section +namespace Zarankiewicz.VertexTruncation +open scoped BigOperators +variable {m n : ℕ} {D : AdmissibleDrawing m n} + +theorem exists_all_edge_shift_radius (V : VertexTruncation D.toContinuousDrawing) + (hnorm : NoAdjacentCrossings D) (hstraight : LocallyStraightCrossings D) (htrans : LocallyTransverseCrossings D) : + ∃ δ : ℝ, 0 < δ ∧ ∀ t : ℝ, t ≠ 0 → |t| < δ → ∀ e f : BipartiteEdge m n, + ∀ i : Fin (V.pieces e), ∀ j : Fin (V.pieces f), + SegmentPairTransverse (V.vertices e i.val) (V.vertices e (i.val+1)) + (shiftedTrack (V.vertices f) (V.pieces f) t j.val) + (shiftedTrack (V.vertices f) (V.pieces f) t (j.val+1)) ∧ + segmentCrossingSign (V.vertices e i.val) (V.vertices e (i.val+1)) + (shiftedTrack (V.vertices f) (V.pieces f) t j.val) + (shiftedTrack (V.vertices f) (V.pieces f) t (j.val+1)) = + if e=f then 0 else segmentCrossingSign (V.vertices e i.val) (V.vertices e (i.val+1)) + (V.vertices f j.val) (V.vertices f (j.val+1)) := by + classical + obtain ⟨δ₀,hδ₀,hother⟩ := V.exists_distinct_edge_shift_radius hnorm hstraight htrans + choose radius hpos hself using V.offset_avoidance + obtain ⟨δ₁,hδ₁,hbound⟩ := finite_positive_lower_bound Finset.univ radius (fun e _ => hpos e) + refine ⟨min δ₀ δ₁,lt_min hδ₀ hδ₁,?_⟩ + intro t ht hsmall e f i j + by_cases hef : e=f + · subst f + have hno := hself e t ht ((hsmall.trans_le (min_le_right _ _)).trans (hbound e (Finset.mem_univ _))) i j + refine ⟨?_,?_⟩ + · intro s hs u hu he + exact False.elim (hno ⟨s,hs,u,hu,he⟩) + · have hp : ¬ SegmentsCrossProperly (V.vertices e i.val) (V.vertices e (i.val+1)) + (shiftedTrack (V.vertices e) (V.pieces e) t j.val) + (shiftedTrack (V.vertices e) (V.pieces e) t (j.val+1)) := + fun h => hno (closedSegmentsMeet_of_proper _ _ _ _ h) + simp [segmentCrossingSign,hp] + · obtain ⟨hT,hS⟩ := hother t (hsmall.trans_le (min_le_left _ _)) e f hef i j + exact ⟨hT,by simpa only [ite_eq_right hef] using hS⟩ + +theorem exists_uniform_track_intersections (V : VertexTruncation D.toContinuousDrawing) + (hnorm : NoAdjacentCrossings D) (hstraight : LocallyStraightCrossings D) (htrans : LocallyTransverseCrossings D) : + ∃ δ : ℝ, 0 < δ ∧ ∀ t : ℝ, t ≠ 0 → |t| < δ → ∀ e f : BipartiteEdge m n, + polygonIntersection (V.vertices e) (shiftedTrack (V.vertices f) (V.pieces f) t) (V.pieces e) (V.pieces f) = + if e=f then 0 else polygonIntersection (V.vertices e) (V.vertices f) (V.pieces e) (V.pieces f) := by + classical + obtain ⟨δ,hδ,hh⟩ := V.exists_all_edge_shift_radius hnorm hstraight htrans + refine ⟨δ,hδ,?_⟩ + intro t ht hsmall e f + by_cases hef : e=f + · rw [ite_eq_left hef] + unfold polygonIntersection + apply Finset.sum_eq_zero + intro i hi + apply Finset.sum_eq_zero + intro j hj + simpa only [ite_eq_left hef] using + (hh t ht hsmall e f ⟨i,Finset.mem_range.mp hi⟩ ⟨j,Finset.mem_range.mp hj⟩).2 + · rw [ite_eq_right hef] + unfold polygonIntersection + apply Finset.sum_congr rfl + intro i hi + apply Finset.sum_congr rfl + intro j hj + simpa only [ite_eq_right hef] using + (hh t ht hsmall e f ⟨i,Finset.mem_range.mp hi⟩ ⟨j,Finset.mem_range.mp hj⟩).2 + +end Zarankiewicz.VertexTruncation + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/UniqueWalkPassage.lean b/lean/OAI/Combinatorics/Crossing/UniqueWalkPassage.lean new file mode 100644 index 0000000000000000000000000000000000000000..ecc5d073c7cff9bec5d581bfb4549343c118a54c --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/UniqueWalkPassage.lean @@ -0,0 +1,41 @@ +import Mathlib.Combinatorics.SimpleGraph.Paths + +namespace OAI + +namespace Zarankiewicz + +def UniqueWalkVisit {V : Type*} {G : SimpleGraph V} {a b : V} (p : G.Walk a b) (x : V) : Prop := + ∀ i j : ℕ, i ≤ p.length → j ≤ p.length → p.getVert i=x → p.getVert j=x → i=j + +theorem walk_dart_parameters {V : Type*} {G : SimpleGraph V} {a b : V} + (p : G.Walk a b) (d : G.Dart) (hd : d ∈ p.darts) : + ∃ i : ℕ, i < p.length ∧ d.fst=p.getVert i ∧ d.snd=p.getVert (i+1) := by + obtain ⟨i,hi⟩ := List.mem_iff_get.mp hd + have he := SimpleGraph.Walk.darts_getElem_eq_getVert (p:=p) i.val i.isLt + have hd' := hi.symm.trans he + refine ⟨i.val,by simpa only [p.length_darts] using i.isLt,?_,?_⟩ + · exact congrArg (fun r : G.Dart => r.fst) hd' + · exact congrArg (fun r : G.Dart => r.snd) hd' + +theorem unique_walk_visit_passage {V : Type*} {G : SimpleGraph V} {a b : V} + (p : G.Walk a b) (x : V) (hunique : UniqueWalkVisit p x) + (d e : G.Dart) (hd : d ∈ p.darts) (he : e ∈ p.darts) (hdx : d.snd=x) (hex : e.fst=x) : + ∃ i : ℕ, i+1 < p.length ∧ d.fst=p.getVert i ∧ + x=p.getVert (i+1) ∧ e.snd=p.getVert (i+2) := by + obtain ⟨i,hi,hdi,hdi'⟩ := walk_dart_parameters p d hd + obtain ⟨j,hj,hej,hej'⟩ := walk_dart_parameters p e he + have hij : i+1=j := hunique (i+1) j (by omega) (by omega) (hdi'.symm.trans hdx) (hej.symm.trans hex) + refine ⟨i,by omega,hdi,hdx.symm.trans hdi',?_⟩ + simpa only [← hij,Nat.add_assoc] using hej' + +theorem bypass_unique_walk_visit_passage {V : Type*} [DecidableEq V] {G : SimpleGraph V} {a b : V} + (p : G.Walk a b) (x : V) (hunique : UniqueWalkVisit p x) + (d e : G.Dart) (hd : d ∈ p.bypass.darts) (he : e ∈ p.bypass.darts) (hdx : d.snd=x) (hex : e.fst=x) : + ∃ i : ℕ, i+1 < p.length ∧ d.fst=p.getVert i ∧ + x=p.getVert (i+1) ∧ e.snd=p.getVert (i+2) := + unique_walk_visit_passage p x hunique d e (p.darts_bypass_subset_darts hd) + (p.darts_bypass_subset_darts he) hdx hex + +end Zarankiewicz + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/VertexChordIntersections.lean b/lean/OAI/Combinatorics/Crossing/VertexChordIntersections.lean new file mode 100644 index 0000000000000000000000000000000000000000..90b0679f7b014f9a7475f5c656c92234f60d8a14 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/VertexChordIntersections.lean @@ -0,0 +1,45 @@ +import OAI.Combinatorics.Crossing.StraightChainTransversality +import OAI.Combinatorics.Crossing.UniformCrossTypeGeometry + +namespace OAI + +noncomputable section +namespace Zarankiewicz.TruncatedSpokeCoordinates +variable {m n : ℕ} {D : AdmissibleDrawing m n} {V : VertexTruncation D.toContinuousDrawing} + (C : TruncatedSpokeCoordinates V) + +theorem chordChain_intersection (j k : BipartiteVertex m n) (a b : IncidentEdges j) + (c d : IncidentEdges k) (ε : ℝ) : + polygonIntersection (V.chordChain j a b).vertices (C.shiftedChordChain k c d ε).vertices 1 1= + segmentCrossingSign (V.spokePort j a) (V.spokePort j b) (C.shiftedPort k c ε) (C.shiftedPort k d ε) := by + rw [VertexTruncation.chordChain,shiftedChordChain,PolygonalChain.intersection_single_single] + +theorem exists_vertex_chord_chain_radius (hnorm : NoAdjacentCrossings D) : + ∃ δ : ℝ, 0<δ ∧ + (∀ ε : ℝ, ε ≠ 0 → |ε|<δ → ∀ j k (a b : IncidentEdges j) (c d : IncidentEdges k), + a ≠ b → c ≠ d → (V.chordChain j a b).Transverse (C.shiftedChordChain k c d ε)) ∧ + (∀ ε : ℝ, ε ≠ 0 → |ε|<δ → ∀ j k, j ≠ k → ∀ (a b : IncidentEdges j) (c d : IncidentEdges k), + polygonIntersection (V.chordChain j a b).vertices (C.shiftedChordChain k c d ε).vertices 1 1=0) ∧ + (∀ t : ℝ, 0 p ij.val.1) (fun ij : S => p ij.val.2-p ij.val.1) + (fun ij => sub_ne_zero.mpr (hp.ne (Ne.symm ij.property))) z (r/3) (by positivity) + have hinside : squaredLength (v-z) < r^2 := by + rw [Prod.dist_eq,Real.dist_eq,Real.dist_eq,max_lt_iff,abs_lt,abs_lt] at hv + have h₁ := mul_pos (sub_pos.mpr hv.1.2) (show 0 < r/3+(v.1-z.1) by linarith [hv.1.1]) + have h₂ := mul_pos (sub_pos.mpr hv.2.2) (show 0 < r/3+(v.2-z.2) by linarith [hv.2.1]) + change (v.1-z.1)^2+(v.2-z.2)^2 < r^2 + nlinarith [sq_pos_of_pos hr] + refine ⟨v,hinside,?_,?_⟩ + · intro i he + rw [he,hcircle i] at hinside + exact lt_irrefl _ hinside + · intro i j hij + have he : det2 (p i-v) (p j-v) = -det2 (v-p i) (p j-p i) := by dsimp [det2]; ring + rw [he] + exact neg_ne_zero.mpr (havoid ⟨(i,j),hij⟩) + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/VertexDisksCrossingFree.lean b/lean/OAI/Combinatorics/Crossing/VertexDisksCrossingFree.lean new file mode 100644 index 0000000000000000000000000000000000000000..66c2480841317eee0236112beb66939f6f9ea174 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/VertexDisksCrossingFree.lean @@ -0,0 +1,40 @@ +import OAI.Combinatorics.Crossing.TruncatedDrawingDisks +import OAI.Combinatorics.Crossing.IncidentSpokePorts + +namespace OAI + +noncomputable section +namespace Zarankiewicz +variable {m n : ℕ} + +theorem vertex_disks_crossing_free (D : AdmissibleDrawing m n) (hnorm : NoAdjacentCrossings D) + (P : ∀ e : BipartiteEdge m n, PolygonalChain (Set.range (D.edge e)) + (D.vertex (.inl e.1)) (D.vertex (.inr e.2))) + (r : ℝ) + (hclear : ∀ j e (i : Fin (P e).pieces), + ¬ ((j=Sum.inl e.1 ∧ i.val=0) ∨ (j=Sum.inr e.2 ∧ i.val+1=(P e).pieces)) → + Disjoint (closedRoundDisk (D.vertex j) r) (segment ℝ ((P e).vertices i.val) ((P e).vertices (i.val+1)))) + (j : BipartiteVertex m n) : + Disjoint (closedRoundDisk (D.vertex j) r) (crossingPoints D.toContinuousDrawing) := by + apply Set.disjoint_left.mpr + rintro x hxd ⟨e,f,hef,hxe,hxf⟩ + have hincident (g : BipartiteEdge m n) (hxg : x ∈ edgeInterior D.toContinuousDrawing g) : + j=Sum.inl g.1 ∨ j=Sum.inr g.2 := by + have hx := edgeInterior_subset_range D.toContinuousDrawing g hxg + rw [← drawing_chain_range_eq D.toContinuousDrawing g (P g)] at hx + obtain ⟨i,hi,hxi⟩ := polygonalArcPath_range_piece (P g).vertices (P g).pieces + (drawing_chain_pieces_pos D.toContinuousDrawing g (P g)) x hx + by_contra h + have hbad : ¬ ((j=Sum.inl g.1 ∧ i=0) ∨ (j=Sum.inr g.2 ∧ i+1=(P g).pieces)) := + fun hh => h (hh.elim (fun hh => Or.inl hh.1) (fun hh => Or.inr hh.1)) + exact Set.disjoint_left.mp (hclear j g ⟨i,hi⟩ hbad) hxd hxi + have hadj := incident_edges_adjacent j ⟨e,hincident e hxe⟩ ⟨f,hincident f hxf⟩ + have hh : x ∈ edgeInterior D.toContinuousDrawing e ∩ edgeInterior D.toContinuousDrawing f := ⟨hxe,hxf⟩ + rw [hnorm e f hef hadj] at hh + exact hh + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/VertexEndpointPorts.lean b/lean/OAI/Combinatorics/Crossing/VertexEndpointPorts.lean new file mode 100644 index 0000000000000000000000000000000000000000..6e74a596bd5366397e7b8a453da2295636a1a441 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/VertexEndpointPorts.lean @@ -0,0 +1,44 @@ +import OAI.Combinatorics.Crossing.DrawingVertexPlacement + +namespace OAI + +noncomputable section +namespace Zarankiewicz.DrawingPassages +variable {m n : ℕ} {D : FiniteIntersectionDrawing m n} + +def firstArc (C : DrawingPassages D) (e : BipartiteEdge m n) : C.ArcIndex := + ⟨e,⟨0,C.count_pos e⟩⟩ + +def lastArc (C : DrawingPassages D) (e : BipartiteEdge m n) : C.ArcIndex := + ⟨e,⟨C.count e-1,by have h := C.count_pos e; omega⟩⟩ + +theorem lastArc_node (C : DrawingPassages D) (e : BipartiteEdge m n) : + (C.lastArc e).2.succ=Fin.last (C.count e) := by + apply Fin.ext + have h := C.count_pos e + change C.count e-1+1=C.count e + omega + +theorem firstArc_mark (C : DrawingPassages D) (e : BipartiteEdge m n) : + C.arcStartMark (C.firstArc e)=C.vertexMark (.inl e.1) := by + apply Subtype.ext + change D.edge e (C.node e 0)=D.vertex (.inl e.1) + rw [C.first,Path.source] + +theorem lastArc_mark (C : DrawingPassages D) (e : BipartiteEdge m n) : + C.arcEndMark (C.lastArc e)=C.vertexMark (.inr e.2) := by + apply Subtype.ext + change D.edge e (C.node e (C.lastArc e).2.succ)=D.vertex (.inr e.2) + rw [C.lastArc_node,C.last,Path.target] + +def startPortAt (C : DrawingPassages D) (e : BipartiteEdge m n) : C.PortsAt (C.vertexMark (.inl e.1)) := + ⟨(C.firstArc e,false),C.firstArc_mark e⟩ + +def endPortAt (C : DrawingPassages D) (e : BipartiteEdge m n) : C.PortsAt (C.vertexMark (.inr e.2)) := + ⟨(C.lastArc e,true),C.lastArc_mark e⟩ + +end Zarankiewicz.DrawingPassages + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/VertexOrderDetector.lean b/lean/OAI/Combinatorics/Crossing/VertexOrderDetector.lean new file mode 100644 index 0000000000000000000000000000000000000000..d43c2e9095a66787b7c00bf7537fd70db5d2679d --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/VertexOrderDetector.lean @@ -0,0 +1,59 @@ +import OAI.Combinatorics.Crossing.CycleMatrixBlocks +import OAI.Combinatorics.Crossing.HalfOrderInvertibility + +namespace OAI + +noncomputable section +namespace Zarankiewicz.TruncatedSpokeCoordinates +variable {m n : ℕ} {D : AdmissibleDrawing m n} {V : VertexTruncation D.toContinuousDrawing} + (C : TruncatedSpokeCoordinates V) + +def leftNode (i : Fin m) (p : Fin n) : ℝ := C.node (Sum.inl i) (V.leftIncident (i,p)) + +theorem leftNode_injective (i : Fin m) : Function.Injective (C.leftNode i) := by + intro p q hpq + have he := C.node_injective (Sum.inl i) hpq + exact congrArg (fun e : IncidentEdges (Sum.inl i) => e.val.2) he + +@[instance_reducible] def leftOrder (i : Fin m) : LinearOrder (Fin n) := LinearOrder.lift' (C.leftNode i) (C.leftNode_injective i) + +theorem leftHalfOrder_eq_halfOrder (i : Fin m) : + C.leftHalfOrder i=@halfOrderMatrix (Fin n) (C.leftOrder i) := by + ext p q + change orderSign (C.leftNode i p) (C.leftNode i q)/2= + if C.leftNode i p norm_num + +theorem diagonal_detector_isUnit (hnorm : NoAdjacentCrossings D) + (s : ℕ) (hs : 0 < s) (node : Fin n → ℝ) (hn : Function.Injective node) + (hcard : n=2*s+1) (i : Fin m) : + IsUnit (rankDetector s node (edgeBlock C.cycleIntersectionMatrix i i)) := by + rw [C.cycleIntersectionMatrix_diagonal_block hnorm,C.leftHalfOrder_eq_halfOrder] + exact (lemma4_2 s hs node hn (by simpa only [Fintype.card_fin] using hcard)).2.2.2 (C.leftOrder i) + +theorem offDiagonal_detector (s : ℕ) (node : Fin n → ℝ) (i k : Fin m) (hik : i ≠ k) : + rankDetector s node (edgeBlock C.cycleIntersectionMatrix i k)= + rankDetector s node (V.intersectionBlock i k) := by + rw [C.cycleIntersectionMatrix_offDiagonal_block i k hik,map_add,rankDetector_diagonal,add_zero] + +theorem additive_detector_relation (hnorm : NoAdjacentCrossings D) + (hstraight : LocallyStraightCrossings D) (htrans : LocallyTransverseCrossings D) + (s : ℕ) (node : Fin n → ℝ) (hn : Function.Injective node) (hcard : n=2*s+1) + (i k i₀ : Fin m) : + rankDetector s node (edgeBlock C.cycleIntersectionMatrix i k)- + rankDetector s node (edgeBlock C.cycleIntersectionMatrix i i₀)- + rankDetector s node (edgeBlock C.cycleIntersectionMatrix i₀ k)+ + rankDetector s node (edgeBlock C.cycleIntersectionMatrix i₀ i₀)=0 := by + obtain ⟨r,c,hrc⟩ := C.lemma3_2 hnorm hstraight htrans i k i₀ + have he : blockRectangle C.cycleIntersectionMatrix i k i₀=(fun p q => r p+c q) := funext (fun p => funext (hrc p)) + have hz : rankDetector s node (blockRectangle C.cycleIntersectionMatrix i k i₀)=0 := by + rw [he] + exact rankDetector_additive s node hn (by simpa only [Fintype.card_fin] using hcard) r c + simpa only [blockRectangle,map_add,map_sub] using hz + +end Zarankiewicz.TruncatedSpokeCoordinates + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/VertexPassagePairing.lean b/lean/OAI/Combinatorics/Crossing/VertexPassagePairing.lean new file mode 100644 index 0000000000000000000000000000000000000000..a2760a7a0848f0204d78b230d69012f80c6324ad --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/VertexPassagePairing.lean @@ -0,0 +1,58 @@ +import OAI.Combinatorics.Crossing.GlobalCycleIntersection + +namespace OAI + +noncomputable section +namespace Zarankiewicz.TruncatedSpokeCoordinates +variable {m n : ℕ} {D : AdmissibleDrawing m n} {V : VertexTruncation D.toContinuousDrawing} + (C : TruncatedSpokeCoordinates V) + +def vertexChordPairing (j k : BipartiteVertex m n) (a b : IncidentEdges j) (c d : IncidentEdges k) : ℝ := + if h : k=j then chordEndpointPairing (C.node j a) (C.node j b) + (C.node j (incidentCast h c)) (C.node j (incidentCast h d)) else 0 + +def passagePairing (d f : ℕ → (completeBipartite m n).Dart) + (hd : ∀ i, (d i).snd=(d (i+1)).fst) (hf : ∀ j, (f j).snd=(f (j+1)).fst) + (i j : ℕ) : ℝ := + C.vertexChordPairing (d i).snd (f j).snd (dartTargetIncident (d i)) (dartPassageNext d hd i) + (dartTargetIncident (f j)) (dartPassageNext f hf j) + +theorem exists_vertex_pairing_radius (hnorm : NoAdjacentCrossings D) : + ∃ δ : ℝ, 0 < δ ∧ ∀ t : ℝ, 0 < t → t < δ → + ∀ j k (a b : IncidentEdges j) (c d : IncidentEdges k), a ≠ b → c ≠ d → + (polygonIntersection (V.chordChain j a b).vertices (C.shiftedChordChain k c d t).vertices 1 1+ + polygonIntersection (V.chordChain j a b).vertices (C.shiftedChordChain k c d (-t)).vertices 1 1)/2= + C.vertexChordPairing j k a b c d := by + obtain ⟨δ,hδ,-,hzero,havg⟩ := C.exists_vertex_chord_chain_radius hnorm + refine ⟨δ,hδ,?_⟩ + intro t ht hs j k a b c d hab hcd + by_cases h : k=j + · subst k + have hc : incidentCast (rfl : j=j) c=c := Subtype.ext rfl + have hd : incidentCast (rfl : j=j) d=d := Subtype.ext rfl + rw [vertexChordPairing,dite_eq_left rfl,hc,hd] + exact havg t ht hs j a b c d hab hcd + · have hzplus := hzero t (ne_of_gt ht) (by simpa only [abs_of_pos ht] using hs) j k (Ne.symm h) a b c d + have hzminus := hzero (-t) (neg_ne_zero.mpr (ne_of_gt ht)) (by simpa only [abs_neg,abs_of_pos ht] using hs) + j k (Ne.symm h) a b c d + rw [hzplus,hzminus,zero_add,zero_div] + simp only [vertexChordPairing,dite_eq_right h] + +theorem exists_passage_pairing_radius (hnorm : NoAdjacentCrossings D) : + ∃ δ : ℝ, 0 < δ ∧ ∀ t : ℝ, 0 < t → t < δ → + ∀ (d f : ℕ → (completeBipartite m n).Dart) + (hd : ∀ i, (d i).snd=(d (i+1)).fst) (hf : ∀ j, (f j).snd=(f (j+1)).fst) (i j : ℕ), + bipartiteDartEdge (d (i+1)) ≠ bipartiteDartEdge (d i) → + bipartiteDartEdge (f (j+1)) ≠ bipartiteDartEdge (f j) → + (C.passageIntersection d f hd hf i j t+C.passageIntersection d f hd hf i j (-t))/2= + C.passagePairing d f hd hf i j := by + obtain ⟨δ,hδ,hh⟩ := C.exists_vertex_pairing_radius hnorm + refine ⟨δ,hδ,?_⟩ + intro t ht hs d f hd hf i j hi hj + exact hh t ht hs _ _ _ _ _ _ (dartPassage_ne d hd i hi) (dartPassage_ne f hf j hj) + +end Zarankiewicz.TruncatedSpokeCoordinates + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/VertexPieceClearance.lean b/lean/OAI/Combinatorics/Crossing/VertexPieceClearance.lean new file mode 100644 index 0000000000000000000000000000000000000000..4f3713f8d448a553842cee794410817e0b12c5a2 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/VertexPieceClearance.lean @@ -0,0 +1,50 @@ +import OAI.Combinatorics.Crossing.MinimumChainVertexPieces +import OAI.Combinatorics.Crossing.MarkedCurveDisks + +namespace OAI + +noncomputable section +namespace Zarankiewicz +variable {m n : ℕ} + +theorem exists_vertex_piece_clearance (D : ContinuousDrawing m n) + (P : ∀ e : BipartiteEdge m n, PolygonalChain (Set.range (D.edge e)) + (D.vertex (.inl e.1)) (D.vertex (.inr e.2))) + (hmin : ∀ e, ∀ Q : PolygonalChain (Set.range (D.edge e)) + (D.vertex (.inl e.1)) (D.vertex (.inr e.2)), (P e).pieces ≤ Q.pieces) : + ∃ r : ℝ, 0 < r ∧ + (∀ j k, j ≠ k → Disjoint (closedRoundDisk (D.vertex j) r) (closedRoundDisk (D.vertex k) r)) ∧ + (∀ j e (i : Fin (P e).pieces), + ¬ ((j=Sum.inl e.1 ∧ i.val=0) ∨ (j=Sum.inr e.2 ∧ i.val+1=(P e).pieces)) → + Disjoint (closedRoundDisk (D.vertex j) r) + (segment ℝ ((P e).vertices i.val) ((P e).vertices (i.val+1)))) := by + classical + let Bad := Σ j : BipartiteVertex m n, Σ e : BipartiteEdge m n, + {i : Fin (P e).pieces // ¬ ((j=Sum.inl e.1 ∧ i.val=0) ∨ + (j=Sum.inr e.2 ∧ i.val+1=(P e).pieces))} + let K : Bad → Set Plane := fun t => + segment ℝ ((P t.2.1).vertices t.2.2.val.val) ((P t.2.1).vertices (t.2.2.val.val+1)) + have hK (t : Bad) : IsCompact (K t) := by + dsimp [K] + rw [← Path.range_segment] + exact isCompact_range (Path.segment _ _).continuous + have hnot (t : Bad) : D.vertex t.1 ∉ K t := by + intro hx + exact t.2.2.property (drawing_chain_piece_vertex D t.2.1 (P t.2.1) + (hmin t.2.1) t.2.2.val.val t.2.2.val.isLt t.1 hx) + obtain ⟨ρ,hρ,hclear⟩ := exists_round_disk_clearance (fun t : Bad => D.vertex t.1) K hK hnot + obtain ⟨σ,hσ,hdis⟩ := exists_disjoint_round_disks D.vertex D.vertex_injective + refine ⟨min ρ σ,lt_min hρ hσ,?_,?_⟩ + · intro j k hjk + exact (hdis j k hjk).mono + (closedRoundDisk_mono _ (le_of_lt (lt_min hρ hσ)) (min_le_right _ _)) + (closedRoundDisk_mono _ (le_of_lt (lt_min hρ hσ)) (min_le_right _ _)) + · intro j e i hi + exact (hclear ⟨j,e,⟨i,hi⟩⟩).mono_left + (closedRoundDisk_mono _ (le_of_lt (lt_min hρ hσ)) (min_le_left _ _)) + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/VertexSpokeBounds.lean b/lean/OAI/Combinatorics/Crossing/VertexSpokeBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..c03c46d24f2573cdb44d6317d55d9a5290ae0ae2 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/VertexSpokeBounds.lean @@ -0,0 +1,48 @@ +import OAI.Combinatorics.Crossing.VertexTraceDisks + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +theorem exists_small_squared_radius {ι : Type*} [Fintype ι] (ρ : ℝ) (hρ : 0 < ρ) + (L : ι → ℝ) (hL : ∀ i, 0 < L i) : + ∃ r : ℝ, 0 < r ∧ r ≤ ρ ∧ ∀ i, r^2 < L i := by + obtain ⟨δ,hδ,hbound⟩ := finite_positive_lower_bound Finset.univ (fun i => min 1 (L i)) + (fun i _ => lt_min (by norm_num) (hL i)) + refine ⟨min ρ δ,lt_min hρ hδ,min_le_left _ _,?_⟩ + intro i + have hh := (min_le_right ρ δ).trans_lt (hbound i (Finset.mem_univ _)) + have h1 := hh.trans_le (min_le_left 1 (L i)) + have hlen := hh.trans_le (min_le_right 1 (L i)) + have hpos := lt_min hρ hδ + have hm := mul_pos hpos (sub_pos.mpr h1) + nlinarith + +theorem exists_vertex_spoke_bound {m n : ℕ} (D : ContinuousDrawing m n) + (P : ∀ e : BipartiteEdge m n, PolygonalChain (Set.range (D.edge e)) + (D.vertex (.inl e.1)) (D.vertex (.inr e.2))) + (hmin : ∀ e, ∀ Q : PolygonalChain (Set.range (D.edge e)) + (D.vertex (.inl e.1)) (D.vertex (.inr e.2)), (P e).pieces ≤ Q.pieces) + (ρ : ℝ) (hρ : 0 < ρ) : + ∃ r : ℝ, 0 < r ∧ r ≤ ρ ∧ ∀ e, + r^2 < squaredLength ((P e).vertices 1-(P e).vertices 0) ∧ + r^2 < squaredLength ((P e).vertices (P e).pieces-(P e).vertices ((P e).pieces-1)) := by + let L : BipartiteEdge m n → ℝ := fun e => + min (squaredLength ((P e).vertices 1-(P e).vertices 0)) + (squaredLength ((P e).vertices (P e).pieces-(P e).vertices ((P e).pieces-1))) + have hL (e : BipartiteEdge m n) : 0 < L e := by + have hp := drawing_chain_pieces_pos D e (P e) + have hlast := (P e).minimum_piece_ne_zero (hmin e) ((P e).pieces-1) (by omega) + rw [show (P e).pieces-1+1=(P e).pieces by omega] at hlast + exact lt_min (squaredLength_pos _ ((P e).minimum_piece_ne_zero (hmin e) 0 hp)) + (squaredLength_pos _ hlast) + obtain ⟨r,hr,hrρ,hbound⟩ := exists_small_squared_radius ρ hρ L hL + exact ⟨r,hr,hrρ,fun e => ⟨(hbound e).trans_le (min_le_left _ _), + (hbound e).trans_le (min_le_right _ _)⟩⟩ + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/VertexTraceDisks.lean b/lean/OAI/Combinatorics/Crossing/VertexTraceDisks.lean new file mode 100644 index 0000000000000000000000000000000000000000..d6720c38f79cac59a59148f399b7dbf2c1d89529 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/VertexTraceDisks.lean @@ -0,0 +1,47 @@ +import OAI.Combinatorics.Crossing.VertexPieceClearance +import OAI.Combinatorics.Crossing.ChainTracePieces + +namespace OAI + +noncomputable section +namespace Zarankiewicz +variable {m n : ℕ} + +theorem exists_vertex_trace_disks (D : ContinuousDrawing m n) + (P : ∀ e : BipartiteEdge m n, PolygonalChain (Set.range (D.edge e)) + (D.vertex (.inl e.1)) (D.vertex (.inr e.2))) + (hmin : ∀ e, ∀ Q : PolygonalChain (Set.range (D.edge e)) + (D.vertex (.inl e.1)) (D.vertex (.inr e.2)), (P e).pieces ≤ Q.pieces) : + ∃ r : ℝ, 0 < r ∧ + (∀ j k, j ≠ k → Disjoint (closedRoundDisk (D.vertex j) r) (closedRoundDisk (D.vertex k) r)) ∧ + (∀ j e x, x ∈ closedRoundDisk (D.vertex j) r → + (x ∈ Set.range (D.edge e) ↔ + (j=Sum.inl e.1 ∧ x ∈ segment ℝ ((P e).vertices 0) ((P e).vertices 1)) ∨ + (j=Sum.inr e.2 ∧ x ∈ segment ℝ ((P e).vertices ((P e).pieces-1)) ((P e).vertices (P e).pieces)))) := by + classical + obtain ⟨r,hr,hdis,hclear⟩ := exists_vertex_piece_clearance D P hmin + refine ⟨r,hr,hdis,?_⟩ + intro j e x hxd + have hpos := drawing_chain_pieces_pos D e (P e) + constructor + · intro hx + rw [← drawing_chain_range_eq D e (P e)] at hx + obtain ⟨i,hi,hxi⟩ := polygonalArcPath_range_piece (P e).vertices (P e).pieces hpos x hx + have hinc : (j=Sum.inl e.1 ∧ i=0) ∨ (j=Sum.inr e.2 ∧ i+1=(P e).pieces) := by + by_contra h + exact Set.disjoint_left.mp (hclear j e ⟨i,hi⟩ h) hxd hxi + rcases hinc with ⟨hj,hii⟩ | ⟨hj,hii⟩ + · exact Or.inl ⟨hj,by simpa only [hii] using hxi⟩ + · have hlast : i=(P e).pieces-1 := by omega + exact Or.inr ⟨hj,by simpa only [hlast,show (P e).pieces-1+1=(P e).pieces by omega] using hxi⟩ + · rintro (⟨hj,hx⟩ | ⟨hj,hx⟩) + · exact (P e).inside 0 hpos hx + · have hi : (P e).pieces-1 < (P e).pieces := by omega + apply (P e).inside ((P e).pieces-1) hi + simpa only [show (P e).pieces-1+1=(P e).pieces by omega] using hx + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/VertexTruncation.lean b/lean/OAI/Combinatorics/Crossing/VertexTruncation.lean new file mode 100644 index 0000000000000000000000000000000000000000..420091d526ce8c71bd4ad9a169b5e3bf1535f5ca --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/VertexTruncation.lean @@ -0,0 +1,79 @@ +import OAI.Combinatorics.Crossing.TruncatedSegmentTransversality +import OAI.Combinatorics.Crossing.ShortVertexRadius + +namespace OAI + +noncomputable section +namespace Zarankiewicz +variable {m n : ℕ} + +structure VertexTruncation (D : ContinuousDrawing m n) where + chain : ∀ e : BipartiteEdge m n, PolygonalChain (Set.range (D.edge e)) + (D.vertex (.inl e.1)) (D.vertex (.inr e.2)) + minimal : ∀ e, ∀ Q : PolygonalChain (Set.range (D.edge e)) + (D.vertex (.inl e.1)) (D.vertex (.inr e.2)), (chain e).pieces ≤ Q.pieces + radius : ℝ + radius_pos : 0 < radius + short : ∀ e, 4*radius^2 < squaredLength ((chain e).vertices 1-(chain e).vertices 0) ∧ + 4*radius^2 < squaredLength ((chain e).vertices (chain e).pieces-(chain e).vertices ((chain e).pieces-1)) + disks_disjoint : ∀ j k, j ≠ k → + Disjoint (closedRoundDisk (D.vertex j) radius) (closedRoundDisk (D.vertex k) radius) + piece_clearance : ∀ j e (i : Fin (chain e).pieces), + ¬ ((j=Sum.inl e.1 ∧ i.val=0) ∨ (j=Sum.inr e.2 ∧ i.val+1=(chain e).pieces)) → + Disjoint (closedRoundDisk (D.vertex j) radius) + (segment ℝ ((chain e).vertices i.val) ((chain e).vertices (i.val+1))) + +theorem nonempty_vertexTruncation (D : ContinuousDrawing m n) + (hpoly : ∀ e, HasFiniteAffineCover (D.edge e)) : Nonempty (VertexTruncation D) := by + classical + have hex (e : BipartiteEdge m n) := exists_reduced_polygonalChain (D.edge e) (D.edge_injective e) (hpoly e) + choose P htrace hinj hpos hdir hbend hmin using hex + obtain ⟨ρ,hρ,hdis,hclear⟩ := exists_vertex_piece_clearance D P hmin + obtain ⟨r,hr,hrρ,hshort⟩ := exists_short_vertex_radius D P hmin ρ hρ + refine ⟨⟨P,hmin,r,hr,hshort,?_,?_⟩⟩ + · intro j k hjk + exact (hdis j k hjk).mono (closedRoundDisk_mono _ hr.le hrρ) (closedRoundDisk_mono _ hr.le hrρ) + · intro j e i hi + exact (hclear j e i hi).mono_left (closedRoundDisk_mono _ hr.le hrρ) + +namespace VertexTruncation +variable {D : ContinuousDrawing m n} (V : VertexTruncation D) + +def pieces (e : BipartiteEdge m n) : ℕ := (V.chain e).pieces + +def vertices (e : BipartiteEdge m n) : ℕ → Plane := (V.chain e).truncatedVertices V.radius + +def startPort (e : BipartiteEdge m n) : Plane := (V.chain e).startPort V.radius + +def endPort (e : BipartiteEdge m n) : Plane := (V.chain e).endPort V.radius + +theorem pieces_pos (e : BipartiteEdge m n) : 0 < V.pieces e := drawing_chain_pieces_pos D e (V.chain e) + +theorem weak_short (e : BipartiteEdge m n) : + V.radius^2 < squaredLength ((V.chain e).vertices 1-(V.chain e).vertices 0) ∧ + V.radius^2 < squaredLength ((V.chain e).vertices (V.chain e).pieces-(V.chain e).vertices ((V.chain e).pieces-1)) := by + constructor <;> nlinarith [(V.short e).1,(V.short e).2,sq_nonneg V.radius] + +def path (e : BipartiteEdge m n) : Path (V.startPort e) (V.endPort e) := + ((V.chain e).truncated (V.pieces_pos e) V.radius V.radius_pos (V.weak_short e).1 (V.weak_short e).2).path + +theorem path_injective (e : BipartiteEdge m n) : Function.Injective (V.path e) := + (V.chain e).truncated_path_injective (V.minimal e) (V.pieces_pos e) V.radius V.radius_pos + (V.short e).1 (V.short e).2 + +theorem path_hasFiniteAffineCover (e : BipartiteEdge m n) : HasFiniteAffineCover (V.path e) := + ((V.chain e).truncated (V.pieces_pos e) V.radius V.radius_pos (V.weak_short e).1 (V.weak_short e).2).hasFiniteAffineCover + +theorem range_subset_edgeInterior (e : BipartiteEdge m n) : Set.range (V.path e) ⊆ edgeInterior D e := + truncated_range_subset_edgeInterior D V.chain V.minimal V.radius V.radius_pos V.short V.piece_clearance e + +theorem direction_ne_zero (e : BipartiteEdge m n) (i : ℕ) (hi : i < V.pieces e) : + trackDirection (V.vertices e) i ≠ 0 := + (V.chain e).truncated_direction_ne_zero (V.minimal e) V.radius V.radius_pos (V.short e).1 (V.short e).2 i hi + +end VertexTruncation +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/VertexTruncationGeometry.lean b/lean/OAI/Combinatorics/Crossing/VertexTruncationGeometry.lean new file mode 100644 index 0000000000000000000000000000000000000000..9c81d8ff3a4638a1028626b9ddf37f0f22aa82eb --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/VertexTruncationGeometry.lean @@ -0,0 +1,49 @@ +import OAI.Combinatorics.Crossing.VertexTruncation + +namespace OAI + +noncomputable section +namespace Zarankiewicz.VertexTruncation +variable {m n : ℕ} + +theorem offset_avoidance {D : ContinuousDrawing m n} (V : VertexTruncation D) (e : BipartiteEdge m n) : + ∃ δ : ℝ, 0 < δ ∧ ∀ t : ℝ, t ≠ 0 → |t| < δ → ∀ i j : Fin (V.pieces e), + ¬ ClosedSegmentsMeet (V.vertices e i.val) (V.vertices e (i.val+1)) + (shiftedTrack (V.vertices e) (V.pieces e) t j.val) + (shiftedTrack (V.vertices e) (V.pieces e) t (j.val+1)) := + (V.chain e).truncated_offset_avoidance (V.minimal e) V.radius V.radius_pos (V.short e).1 (V.short e).2 + +theorem edge_intersections_eq {D : AdmissibleDrawing m n} (V : VertexTruncation D.toContinuousDrawing) + (hnorm : NoAdjacentCrossings D) (e f : BipartiteEdge m n) (hef : e ≠ f) : + Set.range (V.path e) ∩ Set.range (V.path f)=edgeInterior D.toContinuousDrawing e ∩ edgeInterior D.toContinuousDrawing f := + truncated_edge_intersections_eq D hnorm V.chain V.minimal V.radius V.radius_pos V.short V.piece_clearance e f hef + +theorem pair_transverse {D : AdmissibleDrawing m n} (V : VertexTruncation D.toContinuousDrawing) + (hnorm : NoAdjacentCrossings D) (hstraight : LocallyStraightCrossings D) (htrans : LocallyTransverseCrossings D) + (e f : BipartiteEdge m n) (hef : e ≠ f) (i : Fin (V.pieces e)) (j : Fin (V.pieces f)) : + SegmentPairTransverse (V.vertices e i.val) (V.vertices e (i.val+1)) + (V.vertices f j.val) (V.vertices f (j.val+1)) := + truncated_segment_pair_transverse D hnorm hstraight htrans V.chain V.minimal V.radius V.radius_pos + V.short V.piece_clearance e f hef i j + +theorem crossing_free_disks {D : AdmissibleDrawing m n} (V : VertexTruncation D.toContinuousDrawing) + (hnorm : NoAdjacentCrossings D) (j : BipartiteVertex m n) : + Disjoint (closedRoundDisk (D.vertex j) V.radius) (crossingPoints D.toContinuousDrawing) := + vertex_disks_crossing_free D hnorm V.chain V.radius V.piece_clearance j + +theorem vertices_not_crossing {D : AdmissibleDrawing m n} (V : VertexTruncation D.toContinuousDrawing) + (hnorm : NoAdjacentCrossings D) (hstraight : LocallyStraightCrossings D) + (e : BipartiteEdge m n) (i : ℕ) (hi : i ≤ V.pieces e) : V.vertices e i ∉ crossingPoints D.toContinuousDrawing := + truncated_vertices_not_crossing D hnorm hstraight V.chain V.minimal V.radius V.piece_clearance e i hi + +theorem vertex_disk_cases {D : ContinuousDrawing m n} (V : VertexTruncation D) + (j : BipartiteVertex m n) (e : BipartiteEdge m n) (x : Plane) (hx : x ∈ Set.range (V.path e)) : + (j=Sum.inl e.1 ∧ x=V.startPort e) ∨ (j=Sum.inr e.2 ∧ x=V.endPort e) ∨ + V.radius^2 < squaredLength (x-D.vertex j) := + truncated_path_vertex_disk_cases D V.chain V.minimal V.radius V.radius_pos V.short V.piece_clearance j e x hx + +end Zarankiewicz.VertexTruncation + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/WalkVectorSum.lean b/lean/OAI/Combinatorics/Crossing/WalkVectorSum.lean new file mode 100644 index 0000000000000000000000000000000000000000..76523a366f456c3ac7efae16787389c67a9be681 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/WalkVectorSum.lean @@ -0,0 +1,71 @@ +import OAI.Combinatorics.Crossing.CyclicWalkDarts +import OAI.Combinatorics.Crossing.RectangleAlgebra + +namespace OAI + +noncomputable section +namespace Zarankiewicz +open SimpleGraph +open scoped BigOperators +variable {m n : ℕ} {u v : BipartiteVertex m n} + +theorem walkEdgeChain_sum_steps (p : (completeBipartite m n).Walk u v) : + walkEdgeChain p=∑ i ∈ Finset.range p.length, orientedEdgeStep (p.getVert i) (p.getVert (i+1)) := by + induction p with + | nil => simp [walkEdgeChain] + | @cons u w v h p ih => + rw [walkEdgeChain,ih,Walk.length_cons,Finset.sum_range_succ'] + simp only [Walk.getVert_cons_succ,Walk.getVert_zero] + abel + +theorem walkEdgeChain_sum_cyclic_darts (p : (completeBipartite m n).Walk u u) (hp : 0 < p.length) : + walkEdgeChain p=∑ i ∈ Finset.range p.length, + bipartiteDartSign (cyclicWalkDart p hp i) • Pi.single (bipartiteDartEdge (cyclicWalkDart p hp i)) 1 := by + rw [walkEdgeChain_sum_steps] + apply Finset.sum_congr rfl + intro i hi + have hlt := Finset.mem_range.mp hi + rw [cyclicWalkDart,cyclicIndex_of_lt _ _ _ hlt] + exact orientedEdgeStep_dart (walkDart p ⟨i,hlt⟩) + +theorem edgePairing_sum_left {ι α : Type*} [Fintype ι] [DecidableEq ι] + (J : Matrix ι ι ℝ) (s : Finset α) (z : α → ι → ℝ) (y : ι → ℝ) : + edgePairing J (∑ a ∈ s, z a) y=∑ a ∈ s, edgePairing J (z a) y := by + classical + induction s using Finset.induction_on with + | empty => simp [edgePairing] + | @insert a s ha ih => rw [Finset.sum_insert ha,edgePairing_add_left,ih,Finset.sum_insert ha] + +theorem edgePairing_sum_right {ι α : Type*} [Fintype ι] [DecidableEq ι] + (J : Matrix ι ι ℝ) (s : Finset α) (z : ι → ℝ) (y : α → ι → ℝ) : + edgePairing J z (∑ a ∈ s, y a)=∑ a ∈ s, edgePairing J z (y a) := by + classical + induction s using Finset.induction_on with + | empty => simp [edgePairing] + | @insert a s ha ih => rw [Finset.sum_insert ha,edgePairing_add_right,ih,Finset.sum_insert ha] + +theorem edgePairing_smul_single {ι : Type*} [Fintype ι] [DecidableEq ι] + (J : Matrix ι ι ℝ) (e f : ι) (a b : ℝ) : + edgePairing J (a • Pi.single e 1) (b • Pi.single f 1)=a*b*J e f := by + simp [edgePairing,Pi.single_apply,mul_comm,mul_left_comm] + +theorem edgePairing_walk_dart_sum (J : Matrix (BipartiteEdge m n) (BipartiteEdge m n) ℝ) + (p : (completeBipartite m n).Walk u u) (q : (completeBipartite m n).Walk v v) + (hp : 0 < p.length) (hq : 0 < q.length) : + edgePairing J (walkEdgeChain p) (walkEdgeChain q)= + ∑ i ∈ Finset.range p.length, ∑ j ∈ Finset.range q.length, + bipartiteDartSign (cyclicWalkDart p hp i)*bipartiteDartSign (cyclicWalkDart q hq j)* + J (bipartiteDartEdge (cyclicWalkDart p hp i)) (bipartiteDartEdge (cyclicWalkDart q hq j)) := by + rw [walkEdgeChain_sum_cyclic_darts p hp,walkEdgeChain_sum_cyclic_darts q hq,edgePairing_sum_left] + apply Finset.sum_congr rfl + intro i hi + rw [edgePairing_sum_right] + apply Finset.sum_congr rfl + intro j hj + exact edgePairing_smul_single _ _ _ _ _ + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/WeightedGram.lean b/lean/OAI/Combinatorics/Crossing/WeightedGram.lean new file mode 100644 index 0000000000000000000000000000000000000000..be41e833ad169e566e05f2012b8021a28be7de92 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/WeightedGram.lean @@ -0,0 +1,36 @@ +import Mathlib.LinearAlgebra.Matrix.NonsingularInverse +import Mathlib.Basic.Real.Basic +import Mathlib.Tactic.Ring + +namespace OAI + +noncomputable section +namespace Zarankiewicz +open scoped BigOperators +variable {κ : Type*} [Fintype κ] [DecidableEq κ] + +theorem weightedGram_eq_sum (A : Matrix κ κ ℝ) (w : κ → ℝ) : + A * Matrix.diagonal w * A.transpose = + ∑ k, w k • Matrix.vecMulVec (fun i => A i k) (fun i => A i k) := by + funext i j + rw [Matrix.mul_apply, Matrix.sum_apply] + simp only [Matrix.mul_diagonal, Matrix.transpose_apply, + Matrix.smul_apply, smul_eq_mul, Matrix.vecMulVec_apply] + apply Finset.sum_congr rfl + intro k hk + ring + +theorem weightedGram_isUnit (A : Matrix κ κ ℝ) (w : κ → ℝ) + (hA : IsUnit A) (hw : ∀ k, w k ≠ 0) : IsUnit (A * Matrix.diagonal w * A.transpose) := by + have hD : IsUnit (Matrix.diagonal w) := by + apply (Matrix.isUnit_iff_isUnit_det _).mpr + apply isUnit_iff_ne_zero.mpr + rw [Matrix.det_diagonal] + exact Finset.prod_ne_zero_iff.mpr (fun k _ => hw k) + exact (hA.mul hD).mul ((Matrix.isUnit_transpose A).mpr hA) + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/CycleDecomposition/BatchEndpoints.lean b/lean/OAI/Combinatorics/CycleDecomposition/BatchEndpoints.lean new file mode 100644 index 0000000000000000000000000000000000000000..7cc8a9bb077f49d6f48d03436b7eb9ef6d305204 --- /dev/null +++ b/lean/OAI/Combinatorics/CycleDecomposition/BatchEndpoints.lean @@ -0,0 +1,275 @@ +import OAI.Combinatorics.CycleDecomposition.BatchPathDeletion + +namespace OAI + +universe cycleUniverse1 cycleUniverse2 cycleUniverse3 cycleUniverse4 cycleUniverse5 cycleUniverse6 cycleUniverse7 cycleUniverse8 cycleUniverse9 cycleUniverse10 cycleUniverse11 cycleUniverse12 cycleUniverse13 cycleUniverse14 + +section +open Filter Asymptotics Real +open scoped Topology +noncomputable section +open MeasureTheory ProbabilityTheory Finset +section +namespace ErdosGallai.Batch +noncomputable section +attribute [local instance] Classical.propDecidable +open scoped BigOperators + +theorem endpoint_partition_of_family {V : Type cycleUniverse1} {I : Type cycleUniverse2} [Fintype V] [Fintype I] + {G : SimpleGraph V} (P : I → PositiveSimplePath G) + (hd : Pairwise fun i j => Disjoint (P i).walk.edgeSet (P j).walk.edgeSet) + (hc : (⋃ i, (P i).walk.edgeSet) = G.edgeSet) + (hl : ∀ x : V, (Finset.univ.filter fun i => + (P i).start = x ∨ (P i).finish = x).card ≤ 2) : EndpointPathPartition G := by + classical + let e := (Fintype.equivFin I).symm + refine ⟨Fintype.card I,fun j => P (e j),?_,?_,?_,endpoint_path_count P hl⟩ + · intro i j hij + exact hd (fun he => hij (e.injective he)) + · rw [← hc] + ext z + simp only [Set.mem_iUnion] + constructor + · rintro ⟨i,hi⟩; exact ⟨e i,hi⟩ + · rintro ⟨i,hi⟩; exact ⟨e.symm i,by rw [e.apply_symm_apply]; exact hi⟩ + · intro x + have heq : (Finset.univ.filter fun j => (P (e j)).start = x ∨ (P (e j)).finish = x).card = + (Finset.univ.filter fun i => (P i).start = x ∨ (P i).finish = x).card := by + apply Finset.card_bij (fun j _ => e j) + · intro i hi; simpa only [Finset.mem_filter,Finset.mem_univ,true_and] using hi + · intro i hi j hj he; exact e.injective he + · intro i hi; exact ⟨e.symm i,by simpa using hi, by simp⟩ + rw [heq] + exact hl x + +def PositiveSimplePath.mapIso {V : Type cycleUniverse3} {W : Type cycleUniverse4} {G : SimpleGraph V} {H : SimpleGraph W} + (f : G ≃g H) (P : PositiveSimplePath G) : PositiveSimplePath H := + ⟨f P.start,f P.finish,P.walk.map f.toHom,P.isPath.map f.injective,by simpa using P.positive⟩ + +theorem endpoint_partition_mapIso {V : Type cycleUniverse5} {W : Type cycleUniverse6} [Fintype V] [Fintype W] + {G : SimpleGraph V} {H : SimpleGraph W} (f : G ≃g H) + (hp : EndpointPathPartition G) : EndpointPathPartition H := by + classical + obtain ⟨k,P,hd,hc,hl,hk⟩ := hp + apply endpoint_partition_of_family (fun i => (P i).mapIso f) + · intro i j hij + change Disjoint ((P i).walk.map f.toHom).edgeSet ((P j).walk.map f.toHom).edgeSet + simp only [SimpleGraph.Walk.edgeSet_map] + exact (Set.disjoint_image_iff (Sym2.map.injective f.injective)).mpr (hd hij) + · have hmap : Sym2.map f.toHom '' G.edgeSet = H.edgeSet := by + ext e + induction e using Sym2.inductionOn with | _ u v => + constructor + · rintro ⟨e,he,heq⟩ + induction e using Sym2.inductionOn with | _ a b => + have ha : H.Adj (f a) (f b) := f.toHom.map_adj he + exact heq ▸ ha + · intro huv + refine ⟨s(f.symm u, f.symm v), f.symm.toHom.map_adj huv,?_⟩ + simp + change (⋃ i, ((P i).walk.map f.toHom).edgeSet) = H.edgeSet + simp_rw [SimpleGraph.Walk.edgeSet_map] + rw [← Set.image_iUnion,hc,hmap] + · intro x + have heq : (Finset.univ.filter fun i => ((P i).mapIso f).start = x ∨ + ((P i).mapIso f).finish = x) = + (Finset.univ.filter fun i => (P i).start = f.symm x ∨ (P i).finish = f.symm x) := by + ext i + simp only [Finset.mem_filter,Finset.mem_univ,true_and] + change (f (P i).start = x ∨ f (P i).finish = x) ↔ _ + exact or_congr (f.toEquiv.eq_symm_apply.symm) (f.toEquiv.eq_symm_apply.symm) + rw [heq] + exact hl _ + +namespace SimplePathPiece +variable {V : Type cycleUniverse7} {I : Type cycleUniverse8} [Fintype V] [Fintype I] [DecidableEq V] {G : SimpleGraph V} + +lemma deletedInduced_map {V : Type cycleUniverse9} {I : Type cycleUniverse10} [_contextInstance2 : Fintype V] [_contextInstance3 : Fintype I] [_contextInstance4 : DecidableEq V] {G : SimpleGraph V} (p : I → SimplePathPiece G) (v : V) + (j : {j : DeleteIndex p v // 0 < (deleted p v j).walk.length}) : + (deletedInduced p v j).walk.map (SimpleGraph.Embedding.induce _).toHom = + (deleted p v j.val).walk := by + exact SimpleGraph.Walk.map_induce _ _ + +lemma deletedInduced_edges (p : I → SimplePathPiece G) (v : V) + (j : {j : DeleteIndex p v // 0 < (deleted p v j).walk.length}) : + Sym2.map (SimpleGraph.Embedding.induce (G := G) {x | x ≠ v}).toHom '' + (deletedInduced p v j).walk.edgeSet = (deleted p v j.val).walk.edgeSet := by + calc + _ = ((deletedInduced p v j).walk.map + (SimpleGraph.Embedding.induce {x | x ≠ v}).toHom).edgeSet := + (SimpleGraph.Walk.edgeSet_map _ _).symm + _ = _ := congrArg (fun q : G.Walk (deleted p v j.val).start + (deleted p v j.val).finish => q.edgeSet) (deletedInduced_map p v j) + +def deletedPositive (p : I → SimplePathPiece G) (v : V) + (j : {j : DeleteIndex p v // 0 < (deleted p v j).walk.length}) : + PositiveSimplePath (G.induce {x | x ≠ v}) := + { deletedInduced p v j with + positive := by + have h := congrArg SimpleGraph.Walk.length (deletedInduced_map p v j) + rw [SimpleGraph.Walk.length_map] at h + rw [h] + exact j.property } + +theorem endpoint_partition_after_deletion (p : I → SimplePathPiece G) (v : V) + (hne : ∀ i, (p i).start ≠ (p i).finish) + (hd : Pairwise fun i j => Disjoint (p i).walk.edgeSet (p j).walk.edgeSet) + (hc : (⋃ i, (p i).walk.edgeSet) = G.edgeSet) + (hl : ∀ x : V, x ≠ v → (Finset.univ.filter fun i => + (p i).start = x ∨ (p i).finish = x).card ≤ 1) : + EndpointPathPartition (G.induce {x | x ≠ v}) := by + classical + let A := {j : DeleteIndex p v // 0 < (deleted p v j).walk.length} + let f : G.induce {x | x ≠ v} →g G := (SimpleGraph.Embedding.induce _).toHom + have hf : Function.Injective f := Subtype.val_injective + apply endpoint_partition_of_family (fun j : A => deletedPositive p v j) + · intro j k hjk + have hdis := deleted_disjoint p v hd (fun he => hjk (Subtype.ext he)) + apply Set.disjoint_left.mpr + intro e hej hek + have he1 : Sym2.map f e ∈ (deleted p v j.val).walk.edgeSet := by + rw [← deletedInduced_edges p v j] + exact ⟨e,hej,rfl⟩ + have he2 : Sym2.map f e ∈ (deleted p v k.val).walk.edgeSet := by + rw [← deletedInduced_edges p v k] + exact ⟨e,hek,rfl⟩ + exact Set.disjoint_left.mp hdis he1 he2 + · apply Set.Subset.antisymm + · intro e he + obtain ⟨j,hj⟩ := Set.mem_iUnion.mp he + exact (deletedPositive p v j).walk.edges_subset_edgeSet hj + · intro e he + have he' : Sym2.map f e ∈ G.edgeSet ∧ v ∉ Sym2.map f e := by + induction e using Sym2.inductionOn with | _ a b => + refine ⟨he,?_⟩ + change v ∉ s(a.val,b.val) + simpa only [Sym2.map_mk,Sym2.mem_iff,eq_comm] using not_or.mpr ⟨a.property,b.property⟩ + have hmem : Sym2.map f e ∈ ⋃ j : A, (deleted p v j.val).walk.edgeSet := by + rw [deleted_positive_union] + refine ⟨?_,he'.2⟩ + exact Set.mem_iUnion.mp (hc.symm ▸ he'.1) + obtain ⟨j,hj⟩ := Set.mem_iUnion.mp hmem + rw [← deletedInduced_edges p v j] at hj + obtain ⟨e',he',heq⟩ := hj + have heq' : e' = e := Sym2.map.injective hf heq + subst e' + exact Set.mem_iUnion.mpr ⟨j,he'⟩ + · intro x + have hb := deleted_endpoint_load p v x.val hne hd (hl x.val x.property) + have hc' : (Finset.univ.filter fun j : A => + (deletedPositive p v j).start = x ∨ (deletedPositive p v j).finish = x).card ≤ + (Finset.univ.filter fun j : DeleteIndex p v => 0 < (deleted p v j).walk.length ∧ + ((deleted p v j).start = x.val ∨ (deleted p v j).finish = x.val)).card := by + apply Finset.card_le_card_of_injOn Subtype.val + · intro j hj + apply Finset.mem_filter.mpr + refine ⟨Finset.mem_univ _,j.property,?_⟩ + rcases (Finset.mem_filter.mp hj).2 with hs | ht + · exact Or.inl (congrArg Subtype.val hs) + · exact Or.inr (congrArg Subtype.val ht) + · exact fun _ _ _ _ he => Subtype.ext he + convert hc'.trans hb using 1 + + congr 1 + ext i + simp only [Finset.mem_filter,Finset.mem_univ,true_and] + +end SimplePathPiece + +def evenAugmentationOldIso {V : Type cycleUniverse11} [Fintype V] (G : SimpleGraph V) : + G ≃g (evenAugmentation G).induce {x | x ≠ none} where + toEquiv := Equiv.optionSubtype none ⟨Equiv.refl (Option V),rfl⟩ + map_rel_iff' := Iff.rfl + +theorem endpoint_partition_of_augmented_parts {V : Type cycleUniverse12} [Fintype V] + (G : SimpleGraph V) (hL : LovaszPathCyclePartition (evenAugmentation G)) : + EndpointPathPartition G := by + classical + obtain ⟨k,parts,hparts,hd,hc,hk⟩ := hL + have hw : ∀ i : Fin k, ∃ (a b : Option V) (p : (evenAugmentation G).Walk a b), + p.IsTrail ∧ (a ≠ b → p.IsPath) ∧ parts i = p.edgeSet := by + intro i + rcases hparts i with ⟨a,b,p,hp,_,he⟩ | ⟨a,p,hp,he⟩ + · exact ⟨a,b,p,hp.isTrail,fun _ => hp,he⟩ + · exact ⟨a,a,p,hp.isTrail,fun h => False.elim (h rfl),he⟩ + choose a b p ht hp he using hw + have hd' : Pairwise fun i j => Disjoint (p i).edgeSet (p j).edgeSet := by + simpa only [he] using hd + have hc' : (⋃ i, (p i).edgeSet) = (evenAugmentation G).edgeSet := by + simpa only [he] using hc + let S : Finset (Option V) := Finset.univ.image some + have hS : S.card = Fintype.card V := by + simp only [S,Finset.card_image_of_injective _ (Option.some_injective V),Finset.card_univ] + have ho : ∀ x ∈ S, Odd ((evenAugmentation G).degree x) := by + intro x hx + obtain ⟨y,_,rfl⟩ := Finset.mem_image.mp hx + exact evenAugmentation_old_odd G y + have hk' : 2 * Fintype.card (Fin k) ≤ S.card + 1 := by + simpa only [Fintype.card_fin,Fintype.card_option,hS] using hk + obtain ⟨hopen,hload⟩ := tight_odd_trail_partition (evenAugmentation G) S p ht hd' hc' ho hk' + let P : Fin k → SimplePathPiece (evenAugmentation G) := fun i => + ⟨a i,b i,p i,hp i (hopen i)⟩ + have hload' : ∀ x : Option V, x ≠ none → (Finset.univ.filter fun i => + (P i).start = x ∨ (P i).finish = x).card ≤ 1 := by + intro x hx + cases x with + | none => exact False.elim (hx rfl) + | some x => + have h := hload (some x) (Finset.mem_image.mpr ⟨x,Finset.mem_univ _,rfl⟩) + have hpred : (Finset.univ.filter fun i => a i ≠ b i ∧ + (some x = a i ∨ some x = b i)) = + (Finset.univ.filter fun i => (P i).start = some x ∨ (P i).finish = some x) := by + ext i + simp only [Finset.mem_filter,Finset.mem_univ,true_and,P] + constructor + · rintro ⟨_,hi⟩ + exact hi.elim (fun h => Or.inl h.symm) (fun h => Or.inr h.symm) + · intro hi + exact ⟨hopen i,hi.elim (fun h => Or.inl h.symm) (fun h => Or.inr h.symm)⟩ + apply le_of_eq + calc + _ = _ := congrArg Finset.card hpred.symm + _ = 1 := by + convert h using 1 + congr 1 + ext i + simp only [Finset.mem_filter,Finset.mem_univ,true_and] + + have hdel := SimplePathPiece.endpoint_partition_after_deletion P none hopen hd' hc' hload' + exact endpoint_partition_mapIso (evenAugmentationOldIso G).symm hdel + +end +end ErdosGallai.Batch + +namespace ErdosGallai.Batch +noncomputable section + +theorem lovasz_path_cycle_partition {V : Type cycleUniverse13} [Fintype V] (G : SimpleGraph V) : + LovaszPathCyclePartition G := by + classical + obtain ⟨k,P,hd,hc,hk⟩ := Lovasz.path_cycle_partition G + refine ⟨k,fun i => (P i).walk.edgeSet,?_,hd,hc,?_⟩ + · intro i + rcases (P i).simple with hp | ⟨h,hcy⟩ + · exact Or.inl ⟨(P i).start,(P i).finish,(P i).walk,hp.1,hp.2,rfl⟩ + · exact Or.inr ⟨(P i).start,(P i).walk.copy rfl h,hcy,by simp⟩ + · exact hk.trans (Finset.card_le_univ _) + +theorem lovasz_theorem : MissingLovaszTheorem := + fun _ G => lovasz_path_cycle_partition G + +theorem endpoint_path_partition {V : Type cycleUniverse14} [Fintype V] (G : SimpleGraph V) : + EndpointPathPartition G := + endpoint_partition_of_augmented_parts G (lovasz_path_cycle_partition (evenAugmentation G)) + +theorem endpoint_theorem : MissingEndpointTheorem := + fun _ G => endpoint_path_partition G + +end +end ErdosGallai.Batch + +end +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/CycleDecomposition/BatchIndexing.lean b/lean/OAI/Combinatorics/CycleDecomposition/BatchIndexing.lean new file mode 100644 index 0000000000000000000000000000000000000000..65ca258915fa1daea25cdc0564441298d32c6ffd --- /dev/null +++ b/lean/OAI/Combinatorics/CycleDecomposition/BatchIndexing.lean @@ -0,0 +1,498 @@ +import OAI.Combinatorics.CycleDecomposition.ScaleDecomposition + +namespace OAI + +universe cycleUniverse1 cycleUniverse2 cycleUniverse3 cycleUniverse4 cycleUniverse5 cycleUniverse6 cycleUniverse7 cycleUniverse8 cycleUniverse9 cycleUniverse10 cycleUniverse11 cycleUniverse12 cycleUniverse13 cycleUniverse14 cycleUniverse15 cycleUniverse16 + +section +open Filter Asymptotics Real +open scoped Topology +noncomputable section +open MeasureTheory ProbabilityTheory Finset +section + +namespace ErdosGallai.Indexing +noncomputable section +open Finset + +variable {I : Type cycleUniverse1} [DecidableEq I] + +def batchWeight (w : I → ℕ) (b : Finset I) : ℝ := ∑ i ∈ b, (w i : ℝ) + +lemma batchWeight_nonneg {I : Type cycleUniverse2} [_contextInstance1 : DecidableEq I] (w : I → ℕ) (b : Finset I) : 0 ≤ batchWeight w b := by + exact Finset.sum_nonneg (fun _ _ => Nat.cast_nonneg _) + +lemma indexed_batch_construction (w : I → ℕ) (A : Finset I) (B : ℝ) (hB : 0 < B) + (hw : ∀ i ∈ A, (w i : ℝ) ≤ B/2) : + ∃ P : List (Finset I), + P.Pairwise Disjoint ∧ + (∀ i, i ∈ A ↔ ∃ b ∈ P, i ∈ b) ∧ + (∀ b ∈ P, b.Nonempty ∧ batchWeight w b ≤ B) ∧ + (∀ b ∈ P.tail, B/2 < batchWeight w b) ∧ + (P.map (batchWeight w)).sum = batchWeight w A := by + induction A using Finset.induction_on with + | empty => + refine ⟨[], by simp, ?_, by simp, by simp, ?_⟩ + · simp + · simp [batchWeight] + | @insert a A ha ih => + obtain ⟨P, hdisj, hcover, hbins, hheavy, hmass⟩ := ih (fun i hi => hw i (by simp [hi])) + have hwa := hw a (by simp) + have haP : ∀ b ∈ P, a ∉ b := by + intro b hb hab + exact ha ((hcover a).mpr ⟨b,hb,hab⟩) + cases P with + | nil => + have hAz : A = ∅ := by + apply Finset.eq_empty_iff_forall_notMem.mpr + intro i hi + simpa using (hcover i).mp hi + subst A + refine ⟨[{a}], by simp, ?_, ?_, by simp, ?_⟩ + · intro i; simp + · intro b hb + simp only [List.mem_singleton] at hb + subst b + exact ⟨by simp, by simp [batchWeight]; linarith⟩ + · simp + | cons b bs => + have hab : a ∉ b := haP b (by simp) + obtain ⟨hbne,hbB⟩ := hbins b (by simp) + by_cases hlight : batchWeight w b ≤ B/2 + · refine ⟨insert a b :: bs, ?_, ?_, ?_, ?_, ?_⟩ + · rw [List.pairwise_cons] + refine ⟨?_, (List.pairwise_cons.mp hdisj).2⟩ + intro d hd + exact Finset.disjoint_insert_left.mpr ⟨haP d (by simp [hd]), + (List.pairwise_cons.mp hdisj).1 d hd⟩ + · intro i + constructor + · intro hia + rcases Finset.mem_insert.mp hia with hia | hi + · exact ⟨insert a b, by simp, by simp [hia]⟩ + · obtain ⟨d,hd,hid⟩ := (hcover i).mp hi + rcases List.mem_cons.mp hd with hd | hd + · subst d + exact ⟨insert a b, by simp, Finset.mem_insert_of_mem hid⟩ + · exact ⟨d, by simp [hd], hid⟩ + · rintro ⟨d,hd,hid⟩ + rcases List.mem_cons.mp hd with rfl | hd + · rcases Finset.mem_insert.mp hid with rfl | hib + · simp + · exact Finset.mem_insert_of_mem ((hcover i).mpr ⟨b, by simp, hib⟩) + · exact Finset.mem_insert_of_mem ((hcover i).mpr ⟨d, by simp [hd], hid⟩) + · intro d hd + rcases List.mem_cons.mp hd with rfl | hd + · refine ⟨by simp, ?_⟩ + simp only [batchWeight, Finset.sum_insert hab] + change (w a : ℝ) + batchWeight w b ≤ B + linarith + · exact hbins d (by simp [hd]) + · simpa using hheavy + · simp only [List.map_cons, List.sum_cons] at hmass ⊢ + rw [show batchWeight w (insert a b) = (w a:ℝ)+batchWeight w b by + simp [batchWeight, hab], show batchWeight w (insert a A) = (w a:ℝ)+batchWeight w A by + simp [batchWeight, ha]] + linarith + · refine ⟨{a} :: b :: bs, ?_, ?_, ?_, ?_, ?_⟩ + · rw [List.pairwise_cons] + exact ⟨fun d hd => Finset.disjoint_singleton_left.mpr (haP d hd), hdisj⟩ + · intro i + constructor + · intro hi + rcases Finset.mem_insert.mp hi with hia | hi + · exact ⟨{a}, by simp, by simp [hia]⟩ + · obtain ⟨d,hd,hid⟩ := (hcover i).mp hi + exact ⟨d, List.mem_cons_of_mem _ hd, hid⟩ + · rintro ⟨d,hd,hid⟩ + rcases List.mem_cons.mp hd with rfl | hd + · exact Finset.mem_insert.mpr (Or.inl (Finset.mem_singleton.mp hid)) + · exact Finset.mem_insert_of_mem ((hcover i).mpr ⟨d,hd,hid⟩) + · intro d hd + rcases List.mem_cons.mp hd with rfl | hd + · exact ⟨by simp, by simp [batchWeight]; linarith⟩ + · exact hbins d hd + · intro d hd + rcases List.mem_cons.mp hd with rfl | hd + · exact lt_of_not_ge hlight + · exact hheavy d hd + · simp only [List.map_cons, List.sum_cons] at hmass ⊢ + simp only [batchWeight, Finset.sum_singleton, Finset.sum_insert ha] at hmass ⊢ + linarith + +lemma batch_tail_mass {I : Type cycleUniverse3} [_contextInstance1 : DecidableEq I] (w : I → ℕ) (P : List (Finset I)) (t : ℝ) + (ht : ∀ b ∈ P, t ≤ batchWeight w b) : + (P.length : ℝ)*t ≤ (P.map (batchWeight w)).sum := by + induction P with + | nil => simp + | cons b bs ih => + have hb := ht b (by simp) + have hbs := ih (fun d hd => ht d (by simp [hd])) + simp only [List.length_cons, Nat.cast_add, Nat.cast_one, List.map_cons, List.sum_cons] + nlinarith + +theorem indexed_batch_partition (w : I → ℕ) (A : Finset I) (B : ℝ) (hB : 0 < B) + (hw : ∀ i ∈ A, (w i : ℝ) ≤ B/2) : + ∃ P : List (Finset I), + P.Pairwise Disjoint ∧ + (∀ i, i ∈ A ↔ ∃ b ∈ P, i ∈ b) ∧ + (∀ b ∈ P, b.Nonempty ∧ batchWeight w b ≤ B) ∧ + (P.map (batchWeight w)).sum = batchWeight w A ∧ + (P.length : ℝ) ≤ 1 + 2*batchWeight w A/B := by + obtain ⟨P,hd,hc,hb,ht,hm⟩ := indexed_batch_construction w A B hB hw + refine ⟨P,hd,hc,hb,hm,?_⟩ + have htail := batch_tail_mass w P.tail (B/2) (fun b hb => (ht b hb).le) + cases P with + | nil => + simp only [List.length_nil, Nat.cast_zero] + have hh := div_nonneg (mul_nonneg (by norm_num : (0:ℝ) ≤ 2) (batchWeight_nonneg w A)) hB.le + linarith + | cons b bs => + simp only [List.tail_cons, List.length_cons, Nat.cast_add, Nat.cast_one] at htail ⊢ + simp only [List.map_cons, List.sum_cons] at hm + have hb0 := batchWeight_nonneg w b + have hdv : (bs.length : ℝ) ≤ 2*batchWeight w A/B := by + apply (le_div_iff₀ hB).mpr + linarith + linarith + +end +end ErdosGallai.Indexing + +namespace ErdosGallai.Indexing +noncomputable section +open scoped BigOperators + +private theorem cover_card_le {V : Type cycleUniverse4} {I : Type cycleUniverse5} [DecidableEq V] [Fintype I] + (S : Finset V) (W : I → Finset V) + (h : S ⊆ Finset.univ.biUnion W) : + S.card ≤ ∑ i, (W i).card := + (Finset.card_le_card h).trans Finset.card_biUnion_le + +private theorem disjoint_piece_inter {V : Type cycleUniverse6} {J : Type cycleUniverse7} [DecidableEq V] [Fintype J] + (R : J → Finset V) (hR : Pairwise fun i j => Disjoint (R i) (R j)) + (S : Finset V) : + (S ∩ Finset.univ.biUnion R).card = ∑ j, (S ∩ R j).card := by + rw [Finset.inter_biUnion] + apply Finset.card_biUnion + intro i _ j _ hij + exact (hR hij).mono Finset.inter_subset_right Finset.inter_subset_right + +theorem active_occurrences {V : Type cycleUniverse8} {I : Type cycleUniverse9} {J : Type cycleUniverse10} [DecidableEq V] + [Fintype I] [Fintype J] + (Y good : Finset V) (W : I → Finset V) (R : J → Finset V) + (_hW : ∀ i, W i ⊆ Y) (hRsub : ∀ j, R j ⊆ Y) + (hcover : Y ⊆ Finset.univ.biUnion W) + (hR : Pairwise fun i j => Disjoint (R i) (R j)) + (keep : I → J → Prop) [∀ i j, Decidable (keep i j)] : + let active := ∑ i, ∑ j, if keep i j then (W i ∩ R j ∩ good).card else 0 + let skipped := ∑ i, ∑ j, if keep i j then 0 else (W i ∩ R j ∩ good).card + (∑ j, (R j).card) ≤ active + skipped + (Y \ good).card ∧ + active + Y.card ≤ (∑ j, (R j).card) + ∑ i, (W i).card := by + classical + dsimp only + let U := Finset.univ.biUnion R + have hU : U ⊆ Y := by + intro v hv + obtain ⟨j, _, hj⟩ := Finset.mem_biUnion.mp hv + exact hRsub j hj + have hcard : U.card = ∑ j, (R j).card := by + apply Finset.card_biUnion + intro i _ j _ hij + exact hR hij + let mass := ∑ i, ∑ j, (W i ∩ R j ∩ good).card + let whole := ∑ i, (W i ∩ U).card + have hsplit : + (∑ i, ∑ j, if keep i j then (W i ∩ R j ∩ good).card else 0) + + (∑ i, ∑ j, if keep i j then 0 else (W i ∩ R j ∩ good).card) = mass := by + dsimp [mass] + rw [← Finset.sum_add_distrib] + apply Finset.sum_congr rfl + intro i _ + rw [← Finset.sum_add_distrib] + apply Finset.sum_congr rfl + intro j _ + split_ifs <;> omega + have hgood : (U ∩ good).card ≤ mass := by + have hc : U ∩ good ⊆ Finset.univ.biUnion (fun i => W i ∩ U ∩ good) := by + intro v hv + obtain ⟨i, hi, hvi⟩ := Finset.mem_biUnion.mp (hcover (hU (Finset.mem_inter.mp hv).1)) + exact Finset.mem_biUnion.mpr ⟨i, hi, Finset.mem_inter.mpr + ⟨Finset.mem_inter.mpr ⟨hvi, (Finset.mem_inter.mp hv).1⟩, + (Finset.mem_inter.mp hv).2⟩⟩ + apply (cover_card_le (U ∩ good) _ hc).trans + apply le_of_eq + apply Finset.sum_congr rfl + intro i _ + have heq : W i ∩ U ∩ good = (W i ∩ good) ∩ U := by ext v; simp only [Finset.mem_inter]; tauto + rw [heq, disjoint_piece_inter R hR] + apply Finset.sum_congr rfl + intro j _ + congr 1 + ext v + simp only [Finset.mem_inter] + tauto + have hbad : (U \ good).card ≤ (Y \ good).card := by + apply Finset.card_le_card + intro v hv + exact Finset.mem_sdiff.mpr ⟨hU (Finset.mem_sdiff.mp hv).1, (Finset.mem_sdiff.mp hv).2⟩ + have hmass : mass ≤ whole := by + apply Finset.sum_le_sum + intro i _ + rw [disjoint_piece_inter R hR] + exact Finset.sum_le_sum fun j _ => Finset.card_le_card Finset.inter_subset_left + have houtside : (Y \ U).card ≤ ∑ i, (W i \ U).card := by + apply cover_card_le + intro v hv + obtain ⟨i, hi, hvi⟩ := Finset.mem_biUnion.mp (hcover (Finset.mem_sdiff.mp hv).1) + exact Finset.mem_biUnion.mpr ⟨i, hi, Finset.mem_sdiff.mpr ⟨hvi, (Finset.mem_sdiff.mp hv).2⟩⟩ + have hY : U.card + (Y \ U).card = Y.card := by + simpa only [Finset.inter_eq_right.mpr hU] using Finset.card_inter_add_card_sdiff Y U + have hWsum : whole + (∑ i, (W i \ U).card) = ∑ i, (W i).card := by + dsimp [whole] + rw [← Finset.sum_add_distrib] + exact Finset.sum_congr rfl fun i _ => Finset.card_inter_add_card_sdiff (W i) U + have hUgood := Finset.card_inter_add_card_sdiff U good + constructor <;> omega + +theorem skipped_occurrences_bound {V : Type cycleUniverse11} {I : Type cycleUniverse12} {J : Type cycleUniverse13} [DecidableEq V] + [Fintype I] [Fintype J] (W : I → Finset V) (R : J → Finset V) + (good : Finset V) (L : ℕ) : + (∑ i, ∑ j, if L ≤ (W i ∩ R j ∩ good).card then 0 + else (W i ∩ R j ∩ good).card) ≤ L * Fintype.card I * Fintype.card J := by + classical + calc + _ ≤ ∑ _i : I, ∑ _j : J, L := by + apply Finset.sum_le_sum + intro i _ + apply Finset.sum_le_sum + intro j _ + split_ifs <;> omega + _ = _ := by simp only [Finset.sum_const, Finset.card_univ, smul_eq_mul]; ring + +end +end ErdosGallai.Indexing + +namespace ErdosGallai.Indexing +noncomputable section +open Finset SimpleGraph +attribute [local instance] Classical.propDecidable + +lemma list_pairwise_get {A : Type cycleUniverse14} {R : A → A → Prop} {L : List A} + (h : L.Pairwise R) (hs : (∀ ⦃left right⦄, R left right → R right left)) : Pairwise fun i j : Fin L.length => R (L.get i) (L.get j) := by + intro i j hij + rcases lt_or_gt_of_ne (show i.val ≠ j.val from fun he => hij (Fin.ext he)) with hlt | hgt + · exact List.pairwise_iff_getElem.mp h i.val j.val i.isLt j.isLt hlt + · exact hs (List.pairwise_iff_getElem.mp h j.val i.val j.isLt i.isLt hgt) + +lemma list_sum_get {A : Type cycleUniverse15} {M : Type cycleUniverse16} [AddCommMonoid M] (L : List A) (f : A → M) : + (∑ i : Fin L.length, f (L.get i)) = (L.map f).sum := by + rw [← List.sum_ofFn] + calc + _ = (List.map f (List.ofFn L.get)).sum := by rw [List.map_ofFn]; rfl + _ = _ := by rw [List.ofFn_get] + +structure GraphBatches {V : Type} (F : SimpleGraph V) (Y : Finset V) (B T : ℝ) where + Index : Type + finite : Fintype Index + graph : Index → SimpleGraph V + vertices : Index → Finset V + graph_le : ∀ i, graph i ≤ F + disjoint : Pairwise fun i j => Disjoint (graph i).edgeSet (graph j).edgeSet + edge_cover : (⋃ i, (graph i).edgeSet) = F.edgeSet + supported : ∀ i, ∀ ⦃x y⦄, (graph i).Adj x y → x ∈ vertices i ∧ y ∈ vertices i + subset : ∀ i, vertices i ⊆ Y + vertex_cover : Y ⊆ univ.biUnion vertices + order_le : ∀ i, ((vertices i).card:ℝ) ≤ B + mass_le : (∑ i, ((vertices i).card:ℝ)) ≤ T + count_le : (Fintype.card Index:ℝ) ≤ 1+2*T/B +attribute [instance] GraphBatches.finite + +theorem materialize_batches {V I : Type} [Fintype I] + (F : SimpleGraph V) (Y : Finset V) (H : I → SimpleGraph V) (U : I → Finset V) + (hHH : Pairwise fun i j => Disjoint (H i).edgeSet (H j).edgeSet) + (hu : (⋃ i, (H i).edgeSet) = F.edgeSet) + (hU : ∀ i, ∀ ⦃x y⦄, (H i).Adj x y → x ∈ U i ∧ y ∈ U i) + (hUY : ∀ i, U i ⊆ Y) (hY : Y ⊆ univ.biUnion U) + (B : ℝ) (hB : 0 < B) (hsmall : ∀ i, ((U i).card:ℝ) ≤ B/2) : + Nonempty (GraphBatches F Y B (∑ i, ((U i).card:ℝ))) := by + classical + obtain ⟨L,hLd,hLc,hLn,hLm,hLnum⟩ := indexed_batch_partition (fun i => (U i).card) univ B hB (fun i _ => hsmall i) + let A := Fin L.length + let bag (a : A) : Finset I := L.get a + let W (a : A) := (bag a).biUnion U + let J (a : A) : SimpleGraph V := ⨆ i ∈ bag a, H i + have hbagd : Pairwise fun a b => Disjoint (bag a) (bag b) := list_pairwise_get hLd (fun _ _ h => h.symm) + have hbagcov (i : I) : ∃ a : A, i ∈ bag a := by + obtain ⟨b,hb,hi⟩ := (hLc i).mp (mem_univ _) + obtain ⟨k,hk⟩ := List.mem_iff_get.mp hb + exact ⟨k,by change i ∈ L.get k; rwa [hk]⟩ + have hJedge (a : A) : (J a).edgeSet = ⋃ i ∈ bag a, (H i).edgeSet := by + ext e + induction e using Sym2.ind with + | _ x y => simp [J,SimpleGraph.mem_edgeSet,SimpleGraph.iSup_adj] + have hJsub (a : A) : (J a).edgeSet ⊆ F.edgeSet := by + rw [hJedge,← hu] + exact Set.iUnion₂_subset fun i _ => Set.subset_iUnion (fun j : I => (H j).edgeSet) i + have hWweight (a : A) : ((W a).card:ℝ) ≤ batchWeight (fun i => (U i).card) (bag a) := by + have hh := Finset.card_biUnion_le (s := bag a) (t := U) + dsimp only [W,batchWeight] + exact_mod_cast hh + have hJd : Pairwise fun a b => Disjoint (J a).edgeSet (J b).edgeSet := by + intro a b hab + rw [hJedge,hJedge] + apply Set.disjoint_left.mpr + rintro e he he' + obtain ⟨i,hi,he⟩ := Set.mem_iUnion₂.mp he + obtain ⟨j,hj,he'⟩ := Set.mem_iUnion₂.mp he' + have hij : i ≠ j := by rintro rfl; exact Finset.disjoint_left.mp (hbagd hab) hi hj + exact Set.disjoint_left.mp (hHH hij) he he' + refine ⟨{ + Index := A + finite := inferInstance + graph := J + vertices := W + graph_le := fun a => SimpleGraph.edgeSet_subset_edgeSet.mp (hJsub a) + disjoint := hJd + edge_cover := ?_ + supported := ?_ + subset := ?_ + vertex_cover := ?_ + order_le := ?_ + mass_le := ?_ + count_le := ?_ }⟩ + · apply Set.Subset.antisymm (Set.iUnion_subset hJsub) + intro e he + rw [← hu] at he + obtain ⟨i,hi⟩ := Set.mem_iUnion.mp he + obtain ⟨a,hia⟩ := hbagcov i + exact Set.mem_iUnion.mpr ⟨a,by rw [hJedge]; exact Set.mem_iUnion₂.mpr ⟨i,hia,hi⟩⟩ + · intro a x y hxy + have he : s(x,y) ∈ (J a).edgeSet := hxy + rw [hJedge] at he + obtain ⟨i,hi,he⟩ := Set.mem_iUnion₂.mp he + exact ⟨Finset.mem_biUnion.mpr ⟨i,hi,(hU i he).1⟩,Finset.mem_biUnion.mpr ⟨i,hi,(hU i he).2⟩⟩ + · intro a v hv + obtain ⟨i,_,hi⟩ := Finset.mem_biUnion.mp hv + exact hUY i hi + · intro v hv + obtain ⟨i,_,hi⟩ := Finset.mem_biUnion.mp (hY hv) + obtain ⟨a,ha⟩ := hbagcov i + exact Finset.mem_biUnion.mpr ⟨a,mem_univ _,Finset.mem_biUnion.mpr ⟨i,ha,hi⟩⟩ + · intro a + exact (hWweight a).trans ((hLn (bag a) (L.get_mem a)).2) + · calc + _ ≤ ∑ a, batchWeight (fun i => (U i).card) (bag a) := Finset.sum_le_sum (fun a _ => hWweight a) + _ = _ := by rw [list_sum_get,hLm]; rfl + · simpa only [A,Fintype.card_fin,batchWeight] using hLnum + +end +end ErdosGallai.Indexing + +namespace ErdosGallai.Indexing +noncomputable section +open Finset SimpleGraph +attribute [local instance] Classical.propDecidable + +def goodVertices {V : Type} [Fintype V] (F : SimpleGraph V) (Y : Finset V) (a : ℝ) : Finset V := + Y.filter fun v => (F.degree v:ℝ) ≤ a + +lemma bad_vertices_degree_bound {V : Type} [Fintype V] (F : SimpleGraph V) (Y : Finset V) (a : ℝ) : + a * ((Y \ goodVertices F Y a).card:ℝ) ≤ 2 * (F.edgeFinset.card:ℝ) := by + classical + let bad := Y \ goodVertices F Y a + have hbad (v) (hv : v ∈ bad) : a ≤ (F.degree v:ℝ) := by + have hn := (Finset.mem_sdiff.mp hv).2 + exact le_of_lt (lt_of_not_ge (fun h => hn (Finset.mem_filter.mpr ⟨(Finset.mem_sdiff.mp hv).1,h⟩))) + calc + _ = ∑ v ∈ bad, a := by simp [bad,mul_comm] + _ ≤ ∑ v ∈ bad, (F.degree v:ℝ) := Finset.sum_le_sum hbad + _ ≤ ∑ v, (F.degree v:ℝ) := Finset.sum_le_sum_of_subset_of_nonneg (Finset.subset_univ _) (by intros; positivity) + _ = _ := by exact_mod_cast F.sum_degrees_eq_twice_card_edges + +structure ActiveFamily {V R B : Type} [Fintype V] [Fintype R] [Fintype B] + (F : SimpleGraph V) (Y : Finset V) (W : B → Finset V) (U : R → Finset V) (a L : ℝ) where + Index : B → Type + finite : ∀ b, Fintype (Index b) + vertices : ∀ b, Index b → Finset V + router : ∀ b, Index b → R + subset_batch : ∀ b i, vertices b i ⊆ W b + subset_router : ∀ b i, vertices b i ⊆ U (router b i) + disjoint : ∀ b, Pairwise fun i j => Disjoint (vertices b i) (vertices b j) + degree_le : ∀ b i v, v ∈ vertices b i → (F.degree v:ℝ) ≤ a + large : ∀ b i, L ≤ ((vertices b i).card:ℝ) + lower : (∑ r, ((U r).card:ℝ)) - ((Y \ goodVertices F Y a).card:ℝ) - + L * Fintype.card B * Fintype.card R ≤ ∑ b, ∑ i, ((vertices b i).card:ℝ) + upper : (∑ b, ∑ i, ((vertices b i).card:ℝ)) + Y.card ≤ + (∑ r, ((U r).card:ℝ)) + ∑ b, ((W b).card:ℝ) +attribute [instance] ActiveFamily.finite + +theorem choose_active_family {V R B : Type} [Fintype V] [Fintype R] [Fintype B] + (F : SimpleGraph V) (Y : Finset V) (W : B → Finset V) (U : R → Finset V) (a L : ℝ) + (hL : 0 ≤ L) (hW : ∀ b, W b ⊆ Y) (hU : ∀ r, U r ⊆ Y) + (hcov : Y ⊆ univ.biUnion W) (hUd : Pairwise fun r s => Disjoint (U r) (U s)) : + Nonempty (ActiveFamily F Y W U a L) := by + classical + let good := goodVertices F Y a + let S (b : B) (r : R) := W b ∩ U r ∩ good + let keep (b : B) (r : R) := L ≤ ((S b r).card:ℝ) + let I (b : B) := {r : R // keep b r} + let X (b : B) (i : I b) := S b i.val + have hsum (b : B) : (∑ i : I b, ((X b i).card:ℝ)) = + ∑ r, if keep b r then ((S b r).card:ℝ) else 0 := by + rw [← Finset.sum_filter] + simpa only [Finset.subtype_univ] using (Finset.sum_subtype_eq_sum_filter (s := univ) (p := keep b) (fun r => ((S b r).card:ℝ))) + have hadd := active_occurrences Y good W U hW hU hcov hUd keep + dsimp only at hadd + have hlow : (∑ r, ((U r).card:ℝ)) ≤ + (∑ b, ∑ r, if keep b r then ((S b r).card:ℝ) else 0) + + (∑ b, ∑ r, if keep b r then 0 else ((S b r).card:ℝ)) + ((Y \ good).card:ℝ) := by + exact_mod_cast hadd.1 + have hhigh : (∑ b, ∑ r, if keep b r then ((S b r).card:ℝ) else 0) + Y.card ≤ + (∑ r, ((U r).card:ℝ)) + ∑ b, ((W b).card:ℝ) := by exact_mod_cast hadd.2 + have hskip : (∑ b, ∑ r, if keep b r then 0 else ((S b r).card:ℝ)) ≤ + L * Fintype.card B * Fintype.card R := by + calc + _ ≤ ∑ _b : B, ∑ _r : R, L := by + apply Finset.sum_le_sum; intro b _ + apply Finset.sum_le_sum; intro r _ + split_ifs with hk + · exact hL + · exact le_of_lt (lt_of_not_ge hk) + _ = _ := by simp; ring + refine ⟨{ + Index := I + finite := fun _ => inferInstance + vertices := X + router := fun _ i => i.val + subset_batch := fun _ _ => Finset.inter_subset_left.trans Finset.inter_subset_left + subset_router := fun _ _ => Finset.inter_subset_left.trans Finset.inter_subset_right + disjoint := ?_ + degree_le := ?_ + large := fun _ i => i.property + lower := ?_ + upper := ?_ }⟩ + · intro b i j hij + exact (hUd (fun h => hij (Subtype.ext h))).mono + (Finset.inter_subset_left.trans Finset.inter_subset_right) + (Finset.inter_subset_left.trans Finset.inter_subset_right) + · intro b i v hv + exact (Finset.mem_filter.mp (Finset.mem_inter.mp hv).2).2 + · simp_rw [hsum] + dsimp only [good] at hlow hskip + linarith + · simpa only [hsum] using hhigh + +lemma thirds_le_halves {k : ℕ} (hk : 8 ≤ k) : (k:ℝ)/3 ≤ (k/2:ℕ) := by + have h : k ≤ 3*(k/2) := by omega + have h' : (k:ℝ) ≤ 3*(k/2:ℕ) := by exact_mod_cast h + linarith + +end +end ErdosGallai.Indexing + +end +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/CycleDecomposition/BatchLovasz.lean b/lean/OAI/Combinatorics/CycleDecomposition/BatchLovasz.lean new file mode 100644 index 0000000000000000000000000000000000000000..58a258ab78bd742e8e19956800a9969c42d0dbef --- /dev/null +++ b/lean/OAI/Combinatorics/CycleDecomposition/BatchLovasz.lean @@ -0,0 +1,1606 @@ +import OAI.Combinatorics.CycleDecomposition.Decomposition + +namespace OAI + +universe cycleUniverse1 cycleUniverse2 cycleUniverse3 cycleUniverse4 cycleUniverse5 cycleUniverse6 cycleUniverse7 cycleUniverse8 cycleUniverse9 cycleUniverse10 cycleUniverse11 cycleUniverse12 cycleUniverse13 cycleUniverse14 cycleUniverse15 cycleUniverse16 cycleUniverse17 cycleUniverse18 cycleUniverse19 cycleUniverse20 cycleUniverse21 cycleUniverse22 cycleUniverse23 cycleUniverse24 cycleUniverse25 cycleUniverse26 cycleUniverse27 cycleUniverse28 cycleUniverse29 cycleUniverse30 cycleUniverse31 cycleUniverse32 cycleUniverse33 cycleUniverse34 cycleUniverse35 cycleUniverse36 cycleUniverse37 cycleUniverse38 cycleUniverse39 cycleUniverse40 cycleUniverse41 cycleUniverse42 cycleUniverse43 cycleUniverse44 cycleUniverse45 cycleUniverse46 cycleUniverse47 cycleUniverse48 cycleUniverse49 cycleUniverse50 cycleUniverse51 cycleUniverse52 cycleUniverse53 cycleUniverse54 cycleUniverse55 cycleUniverse56 cycleUniverse57 cycleUniverse58 cycleUniverse59 cycleUniverse60 cycleUniverse61 cycleUniverse62 cycleUniverse63 cycleUniverse64 cycleUniverse65 cycleUniverse66 cycleUniverse67 cycleUniverse68 cycleUniverse69 cycleUniverse70 cycleUniverse71 cycleUniverse72 cycleUniverse73 cycleUniverse74 cycleUniverse75 cycleUniverse76 cycleUniverse77 cycleUniverse78 cycleUniverse79 cycleUniverse80 cycleUniverse81 cycleUniverse82 cycleUniverse83 cycleUniverse84 cycleUniverse85 + +section +open Filter Asymptotics Real +open scoped Topology +noncomputable section +open MeasureTheory ProbabilityTheory Finset +section + +namespace ErdosGallai.Batch.Lovasz +universe u +noncomputable section +open SimpleGraph +attribute [local instance] Classical.propDecidable + +def StarActive {V : Type cycleUniverse1} (S : Set V) (R : V → V → Prop) (v : V) : Prop := + ∃ a ∈ S, Relation.ReflTransGen R a v + +lemma starActive_source {V : Type cycleUniverse2} {S : Set V} {R : V → V → Prop} + {v : V} (hv : v ∈ S) : StarActive S R v := + ⟨v, hv, .refl⟩ + +lemma starActive_step {V : Type cycleUniverse3} {S : Set V} {R : V → V → Prop} + {v w : V} (hv : StarActive S R v) (h : R v w) : StarActive S R w := by + obtain ⟨a, ha, hr⟩ := hv + exact ⟨a, ha, hr.tail h⟩ + +lemma starActive_iff {V : Type cycleUniverse4} {S : Set V} {R : V → V → Prop} {v : V} : + StarActive S R v ↔ v ∈ S ∨ ∃ w, StarActive S R w ∧ R w v := by + constructor + · rintro ⟨a, ha, hr⟩ + rcases hr.cases_tail with rfl | ⟨w, hw, h⟩ + · exact Or.inl ha + · exact Or.inr ⟨w, ⟨a, ha, hw⟩, h⟩ + · rintro (h | ⟨w, hw, h⟩) + · exact starActive_source h + · exact starActive_step hw h + +lemma starActive_original_iff {V : Type cycleUniverse5} {S T : Set V} {R : V → V → Prop} + (hST : Disjoint S T) {v : V} (hv : v ∈ T) : + StarActive S R v ↔ ∃ w, StarActive S R w ∧ R w v := by + rw [starActive_iff] + have hs : v ∉ S := fun h => Set.disjoint_left.mp hST h hv + simp [hs] + +lemma starActive_subset {V : Type cycleUniverse6} {S T : Set V} {R : V → V → Prop} + (hS : S ⊆ T) (hR : ∀ a b, R a b → b ∈ T) : + {v | StarActive S R v} ⊆ T := by + rintro v ⟨a, ha, hr⟩ + rcases hr.cases_tail with rfl | ⟨w, _, h⟩ + · exact hS ha + · exact hR w v h + +lemma starActive_no_loop {V : Type cycleUniverse7} {S : Set V} {R : V → V → Prop} + (hinj : ∀ a b c, R a c → R b c → a = b) + (hsource : ∀ a b, a ∈ S → ¬ R b a) + {v : V} (hv : StarActive S R v) : ¬ R v v := by + obtain ⟨a, ha, hr⟩ := hv + induction hr with + | refl => exact hsource a a ha + | @tail b c hab hbc ih => + intro hcc + have he : b = c := hinj b c c hbc hcc + subst c + exact ih hbc + +lemma star_inj {V : Type cycleUniverse8} {x a b : V} : s(x,a) = s(x,b) ↔ a = b := by + rw [Sym2.eq_iff] + constructor + · rintro (⟨_, h⟩ | ⟨h, h'⟩) + · exact h + · exact h'.trans h + · intro h; exact Or.inl ⟨rfl, h⟩ + +structure PathPiece {V : Type cycleUniverse9} (G : SimpleGraph V) where + start : V + finish : V + walk : G.Walk start finish + isPath : walk.IsPath + positive : 0 < walk.length + +lemma PathPiece.ends_ne {V : Type cycleUniverse10} {G : SimpleGraph V} (P : PathPiece G) : + P.start ≠ P.finish := by + intro h + have hz := (P.isPath.nil_iff_eq.mpr h).length_eq_zero + have := P.positive + omega + +structure Piece {V : Type cycleUniverse11} (G : SimpleGraph V) where + start : V + finish : V + walk : G.Walk start finish + simple : (walk.IsPath ∧ 0 < walk.length) ∨ + ∃ h : finish = start, (walk.copy rfl h).IsCycle + +namespace Piece +variable {V : Type cycleUniverse12} {G : SimpleGraph V} + +def ofPath (p : PathPiece G) : Piece G := + ⟨p.start, p.finish, p.walk, Or.inl ⟨p.isPath, p.positive⟩⟩ + +def ofCycle {v : V} (p : G.Walk v v) (h : p.IsCycle) : Piece G := + ⟨v, v, p, Or.inr ⟨rfl, h⟩⟩ + +end Piece + +structure Arm {V : Type cycleUniverse13} (G : SimpleGraph V) (x : V) where + near : V + far : V + adj : G.Adj x near + walk : G.Walk near far + isPath : walk.IsPath + avoids : x ∉ walk.support + +namespace Arm +variable {V : Type cycleUniverse14} {G : SimpleGraph V} {x : V} + +def tip (A : Arm G x) : PathPiece G where + start := x + finish := A.far + walk := .cons A.adj A.walk + isPath := A.isPath.cons A.avoids + positive := by simp + +def flip (A : Arm G x) (h : G.Adj x A.far) : Arm G x where + near := A.far + far := A.near + adj := h + walk := A.walk.reverse + isPath := A.isPath.reverse + avoids := by simpa using A.avoids + +@[simp] lemma flip_edges (A : Arm G x) (h : G.Adj x A.far) : + (A.flip h).walk.edgeSet = A.walk.edgeSet := by simp [flip] + +@[simp] lemma mem_flip_support (A : Arm G x) (h : G.Adj x A.far) (v : V) : + v ∈ (A.flip h).walk.support ↔ v ∈ A.walk.support := by simp [flip] + +lemma two_arms_isPath (A B : Arm G x) + (hd : A.walk.support.Disjoint B.walk.support) : + ((Walk.cons A.adj A.walk).reverse.append (Walk.cons B.adj B.walk)).IsPath := by + apply Walk.IsPath.mk' + simp only [Walk.support_append, Walk.support_reverse, Walk.support_cons, + List.tail_cons, List.reverse_cons, List.append_assoc] + apply List.nodup_append'.mpr + refine ⟨List.nodup_reverse.mpr A.isPath.support_nodup, ?_, ?_⟩ + · exact List.nodup_cons.mpr ⟨B.avoids, B.isPath.support_nodup⟩ + · rw [List.disjoint_left] + intro v hv hq + have hav : v ∈ A.walk.support := List.mem_reverse.mp hv + rcases List.mem_cons.mp hq with rfl | hq + · exact A.avoids hav + · exact List.disjoint_left.mp hd hav hq + +def join (A B : Arm G x) (hd : A.walk.support.Disjoint B.walk.support) : PathPiece G where + start := A.far + finish := B.far + walk := (Walk.cons A.adj A.walk).reverse.append (Walk.cons B.adj B.walk) + isPath := two_arms_isPath A B hd + positive := by simp only [Walk.length_append, Walk.length_reverse, Walk.length_cons]; omega + +lemma join_edges (A B : Arm G x) (hd : A.walk.support.Disjoint B.walk.support) : + (A.join B hd).walk.edgeSet = + A.walk.edgeSet ∪ B.walk.edgeSet ∪ {s(x,A.near), s(x,B.near)} := by + simp only [join, Walk.edgeSet_append, Walk.edgeSet_reverse, Walk.edgeSet_cons] + ext e + simp only [Set.mem_union, Set.mem_insert_iff, Set.mem_singleton_iff] + tauto + +lemma near_ne (A B : Arm G x) (hd : A.walk.support.Disjoint B.walk.support) : + A.near ≠ B.near := by + intro h + exact List.disjoint_left.mp hd A.walk.start_mem_support (by simpa only [h] using B.walk.start_mem_support) + +lemma far_ne (A B : Arm G x) (hd : A.walk.support.Disjoint B.walk.support) : + A.far ≠ B.far := (A.join B hd).ends_ne + +lemma far_ne_center (A : Arm G x) : A.far ≠ x := by + intro h + apply A.avoids + simpa only [h] using A.walk.end_mem_support + +lemma star_not_mem (A : Arm G x) (v : V) : s(x,v) ∉ A.walk.edgeSet := by + intro he + exact A.avoids (Walk.mem_support_iff_exists_mem_edges.mpr + (Or.inr ⟨s(x,v), he, by simp⟩)) + +lemma flip_disjoint_left (A B : Arm G x) (h : G.Adj x A.far) + (hd : A.walk.support.Disjoint B.walk.support) : + (A.flip h).walk.support.Disjoint B.walk.support := by + rw [List.disjoint_left] at hd ⊢ + intro v hv hb + exact hd ((A.mem_flip_support h v).mp hv) hb + +lemma flip_disjoint_right (A B : Arm G x) (h : G.Adj x B.far) + (hd : A.walk.support.Disjoint B.walk.support) : + A.walk.support.Disjoint (B.flip h).walk.support := by + exact (flip_disjoint_left B A h hd.symm).symm + +def orient (A : Arm G x) (active : Prop) (h : active → G.Adj x A.far) : Arm G x := + if ha : active then A.flip (h ha) else A + +@[simp] lemma orient_edges (A : Arm G x) (active : Prop) (h : active → G.Adj x A.far) : + (A.orient active h).walk.edgeSet = A.walk.edgeSet := by + by_cases ha : active + · exact (congrArg (fun B : Arm G x => B.walk.edgeSet) + (show A.orient active h = A.flip (h ha) from dite_eq_left ha)).trans (A.flip_edges _) + · exact congrArg (fun B : Arm G x => B.walk.edgeSet) + (show A.orient active h = A from dite_eq_right ha) + +@[simp] lemma orient_near (A : Arm G x) (active : Prop) (h : active → G.Adj x A.far) : + (A.orient active h).near = if active then A.far else A.near := by + by_cases ha : active <;> simp [orient, flip, ha] + +@[simp] lemma mem_orient_support (A : Arm G x) (active : Prop) + (h : active → G.Adj x A.far) (v : V) : + v ∈ (A.orient active h).walk.support ↔ v ∈ A.walk.support := by + by_cases ha : active + · exact (congrArg (fun B : Arm G x => v ∈ B.walk.support) + (show A.orient active h = A.flip (h ha) from dite_eq_left ha)).to_iff.trans + (A.mem_flip_support _ v) + · exact (congrArg (fun B : Arm G x => v ∈ B.walk.support) + (show A.orient active h = A from dite_eq_right ha)).to_iff + +lemma orient_disjoint (A B : Arm G x) (p q : Prop) + (ha : p → G.Adj x A.far) (hb : q → G.Adj x B.far) + (hd : A.walk.support.Disjoint B.walk.support) : + (A.orient p ha).walk.support.Disjoint (B.orient q hb).walk.support := by + rw [List.disjoint_left] + intro v hv hw + exact List.disjoint_left.mp hd ((A.mem_orient_support p ha v).mp hv) + ((B.mem_orient_support q hb v).mp hw) + +end Arm + +inductive Frame {V : Type cycleUniverse15} (G : SimpleGraph V) (x : V) where + | away (p : PathPiece G) (avoid : x ∉ p.walk.support) + | tip (A : Arm G x) + | through (A B : Arm G x) (disjoint : A.walk.support.Disjoint B.walk.support) + +namespace Frame +variable {V : Type cycleUniverse16} {G : SimpleGraph V} {x : V} + +def path : Frame G x → PathPiece G + | .away p _ => p + | .tip A => A.tip + | .through A B hd => A.join B hd + +def Port : Frame G x → Type + | .away _ _ => Bool + | .tip _ => Unit + | .through _ _ _ => Bool + +def endpoint : (F : Frame G x) → F.Port → V + | .away p _, false => p.start + | .away p _, true => p.finish + | .tip A, _ => A.far + | .through A _ _, false => A.far + | .through _ B _, true => B.far + +def exit : (F : Frame G x) → F.Port → Option V + | .away _ _, _ => none + | .tip _, _ => none + | .through A _ _, false => some A.near + | .through _ B _, true => some B.near + +def inserted (F : Frame G x) (active : F.Port → Prop) : Set (Sym2 V) := + {e | ∃ p, active p ∧ e = s(x, F.endpoint p)} + +def removed (F : Frame G x) (active : F.Port → Prop) : Set (Sym2 V) := + {e | ∃ p, active p ∧ ∃ v, F.exit p = some v ∧ e = s(x,v)} + +lemma endpoint_ne_center (F : Frame G x) (p : F.Port) : F.endpoint p ≠ x := by + cases F with + | away P hx => + cases p + · change P.start ≠ x + intro h; apply hx; simpa only [← h] using P.walk.start_mem_support + · change P.finish ≠ x + intro h; apply hx; simpa only [← h] using P.walk.end_mem_support + | tip A => exact A.far_ne_center + | through A B hd => cases p <;> exact Arm.far_ne_center _ + +lemma endpoint_injective (F : Frame G x) : Function.Injective F.endpoint := by + cases F with + | away P hx => + intro a b hab + cases a <;> cases b <;> first | rfl | exact False.elim (P.ends_ne hab) | + exact False.elim (P.ends_ne hab.symm) + | tip A => + change Function.Injective (fun (_ : Unit) => A.far) + exact fun _ _ _ => Subsingleton.elim _ _ + | through A B hd => + intro a b hab + cases a <;> cases b <;> first | rfl | exact False.elim (A.far_ne B hd hab) | + exact False.elim (A.far_ne B hd hab.symm) + +lemma port_iff_endpoint (F : Frame G x) (v : V) : + (∃ p : F.Port, F.endpoint p = v) ↔ + (F.path.start = v ∨ F.path.finish = v) ∧ v ≠ x := by + constructor + · rintro ⟨p, rfl⟩ + refine ⟨?_, (F.endpoint_ne_center p)⟩ + cases F with + | away P hx => cases p <;> simp [endpoint, path] + | tip A => exact Or.inr rfl + | through A B hd => cases p <;> simp [endpoint, path, Arm.join] + · rintro ⟨he, hx⟩ + cases F with + | away P hp => + rcases he with he | he + · exact ⟨false, he⟩ + · exact ⟨true, he⟩ + | tip A => + rcases he with he | he + · exact (hx he.symm).elim + · exact ⟨(), he⟩ + | through A B hd => + rcases he with he | he + · exact ⟨false, he⟩ + · exact ⟨true, he⟩ + +lemma exit_edge (F : Frame G x) (p : F.Port) (v : V) (h : F.exit p = some v) : + s(x,v) ∈ F.path.walk.edgeSet := by + cases F with + | away P hx => cases h + | tip A => cases h + | through A B hd => + cases p + · cases h + rw [path, Arm.join_edges] + exact Or.inr (by simp) + · cases h + rw [path, Arm.join_edges] + exact Or.inr (by simp) + +lemma removed_subset (F : Frame G x) (active : F.Port → Prop) : + F.removed active ⊆ F.path.walk.edgeSet := by + rintro e ⟨p, hp, v, hv, rfl⟩ + exact F.exit_edge p v hv + +@[simp] lemma removed_away (P : PathPiece G) (hx : x ∉ P.walk.support) + (active : (Frame.away P hx).Port → Prop) : + (Frame.away P hx).removed active = ∅ := by + ext e; simp [removed, exit] + +@[simp] lemma removed_tip (A : Arm G x) (active : (Frame.tip A).Port → Prop) : + (Frame.tip A).removed active = ∅ := by + ext e; simp [removed, exit] + +lemma inserted_away (P : PathPiece G) (hx : x ∉ P.walk.support) + (active : (Frame.away P hx).Port → Prop) : + (Frame.away P hx).inserted active = + (if active false then {s(x,P.start)} else ∅) ∪ + (if active true then {s(x,P.finish)} else ∅) := by + ext e + by_cases h0 : active false <;> by_cases h1 : active true <;> + simp [inserted, endpoint, Port, Bool.exists_bool, h0, h1, or_comm] + +lemma inserted_tip (A : Arm G x) (active : (Frame.tip A).Port → Prop) : + (Frame.tip A).inserted active = if active () then {s(x,A.far)} else ∅ := by + ext e + by_cases h : active () <;> simp [inserted, endpoint, Port, h] + +lemma inserted_through (A B : Arm G x) (hd : A.walk.support.Disjoint B.walk.support) + (active : (Frame.through A B hd).Port → Prop) : + (Frame.through A B hd).inserted active = + (if active false then {s(x,A.far)} else ∅) ∪ + (if active true then {s(x,B.far)} else ∅) := by + ext e + by_cases h0 : active false <;> by_cases h1 : active true <;> + simp [inserted, endpoint, Port, Bool.exists_bool, h0, h1, or_comm] + +lemma removed_through (A B : Arm G x) (hd : A.walk.support.Disjoint B.walk.support) + (active : (Frame.through A B hd).Port → Prop) : + (Frame.through A B hd).removed active = + (if active false then {s(x,A.near)} else ∅) ∪ + (if active true then {s(x,B.near)} else ∅) := by + ext e + by_cases h0 : active false <;> by_cases h1 : active true <;> + simp [removed, exit, Port, Bool.exists_bool, h0, h1, or_comm] + +end Frame + +lemma replace_two_attachments {E : Type cycleUniverse17} (B : Set E) (e f a b : E) + (he : e ∉ B) (hf : f ∉ B) (hne : e ≠ f) (p q : Prop) [Decidable p] [Decidable q] : + ((B ∪ {e,f}) \ ((if p then {e} else ∅) ∪ (if q then {f} else ∅))) ∪ + ((if p then {a} else ∅) ∪ (if q then {b} else ∅)) = + B ∪ {if p then a else e, if q then b else f} := by + classical + ext z + by_cases hp : p <;> by_cases hq : q <;> + simp only [hp, hq, ↓reduceIte, Set.mem_union, Set.mem_sdiff, Set.mem_insert_iff, + Set.mem_singleton_iff, Set.mem_empty_iff_false] <;> aesop + +namespace Frame +variable {V : Type cycleUniverse18} {G : SimpleGraph V} {x : V} + +lemma modify_through (A B : Arm G x) (hd : A.walk.support.Disjoint B.walk.support) + (active : (Frame.through A B hd).Port → Prop) + (hadj : ∀ p, active p → G.Adj x ((Frame.through A B hd).endpoint p)) : + ∃ Q : Piece G, Q.walk.edgeSet = + ((Frame.through A B hd).path.walk.edgeSet \ (Frame.through A B hd).removed active) ∪ + (Frame.through A B hd).inserted active := by + have ha : active false → G.Adj x A.far := hadj false + have hb : active true → G.Adj x B.far := hadj true + let A' := A.orient (active false) ha + let B' := B.orient (active true) hb + have hd' : A'.walk.support.Disjoint B'.walk.support := + A.orient_disjoint B _ _ _ _ hd + refine ⟨Piece.ofPath (A'.join B' hd'), ?_⟩ + have he : s(x,A.near) ∉ A.walk.edgeSet ∪ B.walk.edgeSet := by + rintro (he | he) + · exact A.star_not_mem _ he + · exact B.star_not_mem _ he + have hf : s(x,B.near) ∉ A.walk.edgeSet ∪ B.walk.edgeSet := by + rintro (he | he) + · exact A.star_not_mem _ he + · exact B.star_not_mem _ he + have hne : s(x,A.near) ≠ s(x,B.near) := fun h => A.near_ne B hd (star_inj.mp h) + change (A'.join B' hd').walk.edgeSet = _ + rw [inserted_through, removed_through] + change (A'.join B' hd').walk.edgeSet = ((A.join B hd).walk.edgeSet \ _) ∪ _ + rw [Arm.join_edges, Arm.join_edges] + dsimp only [A', B'] + simp only [Arm.orient_edges, Arm.orient_near] + have hh := (replace_two_attachments _ _ _ s(x,A.far) s(x,B.far) he hf hne + (active false) (active true)).symm + by_cases h0 : active false <;> by_cases h1 : active true + · simpa [h0, h1] using hh + · simpa [h0, h1] using hh + · simpa [h0, h1] using hh + · simp [h0, h1] + +lemma modify_tip (A : Arm G x) (active : (Frame.tip A).Port → Prop) + (hadj : ∀ p, active p → G.Adj x ((Frame.tip A).endpoint p)) + (hnew : ∀ p, active p → s(x,(Frame.tip A).endpoint p) ∉ + (Frame.tip A).path.walk.edgeSet) : + ∃ Q : Piece G, Q.walk.edgeSet = + ((Frame.tip A).path.walk.edgeSet \ (Frame.tip A).removed active) ∪ + (Frame.tip A).inserted active := by + rw [removed_tip, inserted_tip, Set.sdiff_empty] + by_cases ha : active () + · have haG : G.Adj x A.far := hadj () ha + have he : s(A.far,x) ∉ A.tip.walk.edges := by + intro he + exact hnew () ha (Sym2.eq_swap ▸ he) + let c : G.Walk A.far A.far := Walk.cons haG.symm A.tip.walk + have hc : c.IsCycle := Path.cons_isCycle ⟨A.tip.walk,A.tip.isPath⟩ _ he + refine ⟨Piece.ofCycle c hc, ?_⟩ + change c.edgeSet = _ + dsimp only [c, Arm.tip, path] + simp only [Walk.edgeSet_cons, ha, ↓reduceIte] + rw [Sym2.eq_swap] + ext e + simp only [Set.mem_insert_iff, Set.mem_union, Set.mem_singleton_iff] + tauto + · refine ⟨Piece.ofPath A.tip, ?_⟩ + simp [Piece.ofPath, path, ha] + +lemma modify_away (P : PathPiece G) (hx : x ∉ P.walk.support) + (active : (Frame.away P hx).Port → Prop) + (hadj : ∀ p, active p → G.Adj x ((Frame.away P hx).endpoint p)) : + ∃ Q : Piece G, Q.walk.edgeSet = + ((Frame.away P hx).path.walk.edgeSet \ (Frame.away P hx).removed active) ∪ + (Frame.away P hx).inserted active := by + rw [removed_away, inserted_away, Set.sdiff_empty] + change ∃ Q : Piece G, Q.walk.edgeSet = P.walk.edgeSet ∪ _ + by_cases h0 : active false + · have h0G : G.Adj x P.start := hadj false h0 + let q : G.Walk x P.finish := Walk.cons h0G P.walk + have hq : q.IsPath := P.isPath.cons hx + by_cases h1 : active true + · have he : s(P.finish,x) ∉ q.edges := by + intro he + have hh := hq.length_eq_one_of_mem_edges (Sym2.eq_swap ▸ he) + have hp := P.positive + simp only [q, Walk.length_cons] at hh + omega + have h1G : G.Adj x P.finish := hadj true h1 + let c : G.Walk P.finish P.finish := Walk.cons h1G.symm q + have hc : c.IsCycle := Path.cons_isCycle ⟨q,hq⟩ _ he + refine ⟨Piece.ofCycle c hc, ?_⟩ + change c.edgeSet = _ + simp only [c, q, Walk.edgeSet_cons, h0, h1, ↓reduceIte] + rw [Sym2.eq_swap] + ext e + simp only [Set.mem_insert_iff, Set.mem_union, Set.mem_singleton_iff] + tauto + · let Q : PathPiece G := ⟨x, P.finish, q, hq, by simp [q]⟩ + refine ⟨Piece.ofPath Q, ?_⟩ + change q.edgeSet = _ + simp only [q, Walk.edgeSet_cons, h0, h1, ↓reduceIte, Set.union_empty] + ext e + simp only [Set.mem_insert_iff, Set.mem_union, Set.mem_singleton_iff] + tauto + · by_cases h1 : active true + · have h1G : G.Adj x P.finish := hadj true h1 + let q : G.Walk x P.start := Walk.cons h1G P.walk.reverse + have hq : q.IsPath := P.isPath.reverse.cons (by simpa using hx) + let Q : PathPiece G := ⟨x, P.start, q, hq, by simp [q]⟩ + refine ⟨Piece.ofPath Q, ?_⟩ + change q.edgeSet = _ + simp only [q, Walk.edgeSet_cons, Walk.edgeSet_reverse, h0, h1, ↓reduceIte, + Set.empty_union] + ext e + simp only [Set.mem_insert_iff, Set.mem_union, Set.mem_singleton_iff] + tauto + · refine ⟨Piece.ofPath P, ?_⟩ + simp [Piece.ofPath, h0, h1] + +theorem modify (F : Frame G x) (active : F.Port → Prop) + (hadj : ∀ p, active p → G.Adj x (F.endpoint p)) + (hnew : ∀ p, active p → F.exit p = none → s(x,F.endpoint p) ∉ F.path.walk.edgeSet) : + ∃ Q : Piece G, Q.walk.edgeSet = (F.path.walk.edgeSet \ F.removed active) ∪ + F.inserted active := by + cases F with + | away P hx => exact modify_away P hx active hadj + | through A B hd => exact modify_through A B hd active hadj + | tip A => exact modify_tip A active hadj (fun p hp => hnew p hp rfl) + +end Frame + +theorem rewire_partition {E : Type cycleUniverse19} {I : Type cycleUniverse20} (old remove add : I → Set E) (fresh : Set E) + (hsub : ∀ i, remove i ⊆ old i) + (hold : Pairwise fun i j => Disjoint (old i) (old j)) + (hadd : Pairwise fun i j => Disjoint (add i) (add j)) + (hfresh : Disjoint fresh (⋃ i, old i)) + (hbalance : (⋃ i, add i) = (⋃ i, remove i) ∪ fresh) : + Pairwise (fun i j => Disjoint ((old i \ remove i) ∪ add i) + ((old j \ remove j) ∪ add j)) ∧ + (⋃ i, ((old i \ remove i) ∪ add i)) = (⋃ i, old i) ∪ fresh := by + have hcross : ∀ i j, Disjoint (old i \ remove i) (add j) := by + intro i j + apply Set.disjoint_left.mpr + rintro e ⟨hei, hnot⟩ hej + have hh : e ∈ (⋃ l, remove l) ∪ fresh := by + rw [← hbalance] + exact Set.mem_iUnion.mpr ⟨j, hej⟩ + rcases hh with hh | hh + · obtain ⟨l, hel⟩ := Set.mem_iUnion.mp hh + by_cases hil : i = l + · subst l; exact hnot hel + · exact Set.disjoint_left.mp (hold hil) hei (hsub l hel) + · exact Set.disjoint_left.mp hfresh hh (Set.mem_iUnion.mpr ⟨i, hei⟩) + constructor + · intro i j hij + exact Disjoint.union_left + (Disjoint.union_right ((hold hij).mono Set.sdiff_subset Set.sdiff_subset) (hcross i j)) + (Disjoint.union_right (hcross j i).symm (hadd hij)) + · ext e + constructor + · intro he + obtain ⟨i, hi⟩ := Set.mem_iUnion.mp he + rcases hi with hi | hi + · exact Or.inl (Set.mem_iUnion.mpr ⟨i, hi.1⟩) + · have hh : e ∈ (⋃ l, remove l) ∪ fresh := by + rw [← hbalance] + exact Set.mem_iUnion.mpr ⟨i, hi⟩ + rcases hh with hh | hh + · obtain ⟨l, hl⟩ := Set.mem_iUnion.mp hh + exact Or.inl (Set.mem_iUnion.mpr ⟨l, hsub l hl⟩) + · exact Or.inr hh + · rintro (he | he) + · obtain ⟨i, hi⟩ := Set.mem_iUnion.mp he + by_cases hr : e ∈ remove i + · have hh : e ∈ ⋃ l, add l := by + rw [hbalance] + exact Or.inl (Set.mem_iUnion.mpr ⟨i, hr⟩) + obtain ⟨j, hj⟩ := Set.mem_iUnion.mp hh + exact Set.mem_iUnion.mpr ⟨j, Or.inr hj⟩ + · exact Set.mem_iUnion.mpr ⟨i, Or.inl ⟨hi, hr⟩⟩ + · have hh : e ∈ ⋃ l, add l := by rw [hbalance]; exact Or.inr he + obtain ⟨i, hi⟩ := Set.mem_iUnion.mp hh + exact Set.mem_iUnion.mpr ⟨i, Or.inr hi⟩ + +inductive Centered {V : Type cycleUniverse21} (G : SimpleGraph V) (x : V) where + | path (F : Frame G x) + | cycle {v : V} (c : G.Walk v v) (hc : c.IsCycle) + +namespace Centered +variable {V : Type cycleUniverse22} {G : SimpleGraph V} {x : V} + +def piece : Centered G x → Piece G + | .path F => .ofPath F.path + | .cycle c hc => .ofCycle c hc + +def Port : Centered G x → Type + | .path F => F.Port + | .cycle _ _ => Empty + +def endpoint : (K : Centered G x) → K.Port → V + | .path F, p => F.endpoint p + | .cycle _ _, p => nomatch p + +def exit : (K : Centered G x) → K.Port → Option V + | .path F, p => F.exit p + | .cycle _ _, p => nomatch p + +def inserted (K : Centered G x) (active : K.Port → Prop) : Set (Sym2 V) := + {e | ∃ p, active p ∧ e = s(x,K.endpoint p)} + +def removed (K : Centered G x) (active : K.Port → Prop) : Set (Sym2 V) := + {e | ∃ p, active p ∧ ∃ v, K.exit p = some v ∧ e = s(x,v)} + +lemma exit_edge (K : Centered G x) (p : K.Port) (v : V) (h : K.exit p = some v) : + s(x,v) ∈ K.piece.walk.edgeSet := by + cases K with + | path F => exact F.exit_edge p v h + | cycle c hc => exact p.elim + +lemma exit_adj (K : Centered G x) (p : K.Port) (v : V) (h : K.exit p = some v) : + G.Adj x v := by + exact G.mem_edgeSet.mp (K.piece.walk.edges_subset_edgeSet (K.exit_edge p v h)) + +lemma exit_none_all (K : Centered G x) (p : K.Port) (h : K.exit p = none) : + ∀ q, K.exit q = none := by + cases K with + | cycle c hc => exact p.elim + | path F => + cases F with + | away P hx => exact fun _ => rfl + | tip A => exact fun _ => rfl + | through A B hd => cases p <;> cases h + +lemma removed_subset (K : Centered G x) (active : K.Port → Prop) : + K.removed active ⊆ K.piece.walk.edgeSet := by + rintro e ⟨p, hp, v, hv, rfl⟩ + exact K.exit_edge p v hv + +lemma modify (K : Centered G x) (active : K.Port → Prop) + (hadj : ∀ p, active p → G.Adj x (K.endpoint p)) + (hnew : ∀ p, active p → K.exit p = none → + s(x,K.endpoint p) ∉ K.piece.walk.edgeSet) : + ∃ Q : Piece G, Q.walk.edgeSet = + (K.piece.walk.edgeSet \ K.removed active) ∪ K.inserted active := by + cases K with + | path F => exact F.modify active hadj hnew + | cycle c hc => + refine ⟨.ofCycle c hc, ?_⟩ + have hr : (Centered.cycle c hc).removed active = ∅ := by + ext e; simp only [removed, Set.mem_ofPred_eq, Set.mem_empty_iff_false] + exact ⟨fun ⟨p, _⟩ => p.elim, False.elim⟩ + have hi : (Centered.cycle c hc).inserted active = ∅ := by + ext e; simp only [inserted, Set.mem_ofPred_eq, Set.mem_empty_iff_false] + exact ⟨fun ⟨p, _⟩ => p.elim, False.elim⟩ + simp only [hr, hi, Set.sdiff_empty, Set.union_empty] + rfl + +end Centered + +theorem restore_selected {V : Type cycleUniverse23} {I : Type cycleUniverse24} (G : SimpleGraph V) (x : V) + (K : I → Centered G x) (S : Set V) + (hS : ∀ v ∈ S, G.Adj x v) + (hold : Pairwise fun i j => Disjoint (K i).piece.walk.edgeSet (K j).piece.walk.edgeSet) + (hfresh : Disjoint {e | ∃ v ∈ S, e = s(x,v)} (⋃ i, (K i).piece.walk.edgeSet)) + (selected : Set (Σ i, (K i).Port)) + (hinj : Set.InjOn (fun z : Σ i, (K i).Port => (K z.1).endpoint z.2) selected) + (hcov : ∀ v, G.Adj x v → ∃ z ∈ selected, (K z.1).endpoint z.2 = v) : + ∃ Q : I → Piece G, + (Pairwise fun i j => Disjoint (Q i).walk.edgeSet (Q j).walk.edgeSet) ∧ + (⋃ i, (Q i).walk.edgeSet) = + (⋃ i, (K i).piece.walk.edgeSet) ∪ {e | ∃ v ∈ S, e = s(x,v)} := by + let R : V → V → Prop := fun a b => ∃ z ∈ selected, + (K z.1).endpoint z.2 = a ∧ (K z.1).exit z.2 = some b + let active : (i : I) → (K i).Port → Prop := fun i p => + (⟨i,p⟩ : Σ j, (K j).Port) ∈ selected ∧ StarActive S R ((K i).endpoint p) + have hactive_adj : ∀ v, StarActive S R v → G.Adj x v := by + intro v hv + exact starActive_subset (T := {v | G.Adj x v}) hS + (by rintro a b ⟨z, _, _, hz⟩; exact (K z.1).exit_adj z.2 b hz) hv + have hbalance : (⋃ i, (K i).inserted (active i)) = + (⋃ i, (K i).removed (active i)) ∪ {e | ∃ v ∈ S, e = s(x,v)} := by + ext e + constructor + · intro he + obtain ⟨i, p, hp, rfl⟩ := Set.mem_iUnion.mp he + rcases (starActive_iff.mp hp.2) with hs | ⟨w, hw, z, hz, hzw, hzv⟩ + · exact Or.inr ⟨_, hs, rfl⟩ + · exact Or.inl (Set.mem_iUnion.mpr ⟨z.1, z.2, ⟨hz, hzw.symm ▸ hw⟩, + _, hzv, rfl⟩) + · rintro (he | ⟨v, hv, rfl⟩) + · obtain ⟨i, p, hp, v, hpv, rfl⟩ := Set.mem_iUnion.mp he + have hv : StarActive S R v := starActive_step hp.2 ⟨⟨i,p⟩, hp.1, rfl, hpv⟩ + obtain ⟨z, hz, hzv⟩ := hcov v (hactive_adj v hv) + exact Set.mem_iUnion.mpr ⟨z.1, z.2, ⟨hz, hzv.symm ▸ hv⟩, congrArg (s(x,·)) hzv.symm⟩ + · obtain ⟨z, hz, hzv⟩ := hcov v (hS v hv) + exact Set.mem_iUnion.mpr ⟨z.1, z.2, ⟨hz, hzv.symm ▸ starActive_source hv⟩, + congrArg (s(x,·)) hzv.symm⟩ + have hadd : Pairwise fun i j => + Disjoint ((K i).inserted (active i)) ((K j).inserted (active j)) := by + intro i j hij + apply Set.disjoint_left.mpr + rintro e ⟨p, hp, he⟩ ⟨q, hq, hf⟩ + have h : (⟨i,p⟩ : Σ l, (K l).Port) = ⟨j,q⟩ := + hinj hp.1 hq.1 (star_inj.mp (he.symm.trans hf)) + exact hij (congrArg Sigma.fst h) + have hnew : ∀ i p, active i p → (K i).exit p = none → + s(x,(K i).endpoint p) ∉ (K i).piece.walk.edgeSet := by + intro i p hp hn he + have ha : s(x,(K i).endpoint p) ∈ ⋃ j, (K j).inserted (active j) := + Set.mem_iUnion.mpr ⟨i, p, hp, rfl⟩ + rw [hbalance] at ha + rcases ha with ha | ha + · obtain ⟨j, q, hq, v, hqv, hev⟩ := Set.mem_iUnion.mp ha + have hej : s(x,(K i).endpoint p) ∈ (K j).piece.walk.edgeSet := + hev ▸ (K j).exit_edge q v hqv + have hij : i = j := by + by_contra h; exact Set.disjoint_left.mp (hold h) he hej + subst j + rw [(K i).exit_none_all p hn q] at hqv + cases hqv + · exact Set.disjoint_left.mp hfresh ha (Set.mem_iUnion.mpr ⟨i, he⟩) + choose Q hQ using fun i => (K i).modify (active i) + (fun p hp => hactive_adj _ hp.2) (hnew i) + have hh := rewire_partition (fun i => (K i).piece.walk.edgeSet) + (fun i => (K i).removed (active i)) (fun i => (K i).inserted (active i)) + {e | ∃ v ∈ S, e = s(x,v)} (fun i => (K i).removed_subset _) hold hadd hfresh hbalance + refine ⟨Q, ?_, ?_⟩ + · simpa only [hQ] using hh.1 + · simpa only [hQ] using hh.2 + +theorem restore_star {V : Type cycleUniverse25} {I : Type cycleUniverse26} (G : SimpleGraph V) (x : V) + (K : I → Centered G x) (S : Set V) + (hS : ∀ v ∈ S, G.Adj x v) + (hold : Pairwise fun i j => Disjoint (K i).piece.walk.edgeSet (K j).piece.walk.edgeSet) + (hfresh : Disjoint {e | ∃ v ∈ S, e = s(x,v)} (⋃ i, (K i).piece.walk.edgeSet)) + (hcov : ∀ v, G.Adj x v → ∃ i p, (K i).endpoint p = v) : + ∃ Q : I → Piece G, + (Pairwise fun i j => Disjoint (Q i).walk.edgeSet (Q j).walk.edgeSet) ∧ + (⋃ i, (Q i).walk.edgeSet) = + (⋃ i, (K i).piece.walk.edgeSet) ∪ {e | ∃ v ∈ S, e = s(x,v)} := by + let T := {v // G.Adj x v} + have hh : ∀ v : T, ∃ z : Σ i, (K i).Port, (K z.1).endpoint z.2 = v.val := by + intro v + obtain ⟨i,p,h⟩ := hcov v.val v.property + exact ⟨⟨i,p⟩,h⟩ + choose f hf using hh + apply restore_selected G x K S hS hold hfresh (Set.range f) + · rintro z ⟨v,rfl⟩ w ⟨u,rfl⟩ he + have hvu : v = u := Subtype.ext ((hf v).symm.trans (he.trans (hf u))) + exact congrArg f hvu + · intro v hv + exact ⟨f ⟨v,hv⟩, ⟨⟨v,hv⟩, rfl⟩, hf ⟨v,hv⟩⟩ + +namespace Arm +variable {V : Type cycleUniverse27} {G : SimpleGraph V} {x b : V} + +def fromWalk (w : G.Walk x b) (hp : w.IsPath) (hn : ¬w.Nil) : Arm G x := + match w with + | .nil => False.elim (hn .nil) + | @Walk.cons _ _ _ y _ h q => + ⟨y, b, h, q, (Walk.cons_isPath_iff h q).mp hp |>.1, + (Walk.cons_isPath_iff h q).mp hp |>.2⟩ + +@[simp] lemma fromWalk_far (w : G.Walk x b) (hp : w.IsPath) (hn : ¬w.Nil) : + (fromWalk w hp hn).far = b := by + cases w with + | nil => exact (hn .nil).elim + | cons h q => rfl + +@[simp] lemma fromWalk_support (w : G.Walk x b) (hp : w.IsPath) (hn : ¬w.Nil) : + (fromWalk w hp hn).walk.support = w.support.tail := by + cases w with + | nil => exact (hn .nil).elim + | cons h q => rfl + +@[simp] lemma fromWalk_tip_edges (w : G.Walk x b) (hp : w.IsPath) (hn : ¬w.Nil) : + (fromWalk w hp hn).tip.walk.edgeSet = w.edgeSet := by + cases w with + | nil => exact (hn .nil).elim + | cons h q => rfl +end Arm + +lemma PathPiece.exists_frame {V : Type cycleUniverse28} {G : SimpleGraph V} (P : PathPiece G) (x : V) : + ∃ F : Frame G x, F.path.walk.edgeSet = P.walk.edgeSet ∧ + ∀ v, (F.path.start = v ∨ F.path.finish = v) ↔ (P.start = v ∨ P.finish = v) := by + classical + by_cases hx : x ∈ P.walk.support + · obtain ⟨q,r,hq,hr,hqr⟩ := P.isPath.mem_support_iff_exists_append.mp hx + have hp : (q.append r).IsPath := hqr ▸ P.isPath + by_cases hqn : q.Nil + · have hx : P.start = x := hqn.eq + have hrn : ¬r.Nil := by + intro hn; exact P.ends_ne (hx.trans hn.eq) + let A := Arm.fromWalk r hr hrn + refine ⟨.tip A, ?_, ?_⟩ + · change A.tip.walk.edgeSet = P.walk.edgeSet + rw [Arm.fromWalk_tip_edges] + rw [hqr, Walk.edgeSet_append] + simp [Walk.edgeSet, Walk.edges_eq_nil.mpr hqn] + · intro v + change (x = v ∨ A.far = v) ↔ _ + simp only [A, Arm.fromWalk_far, hx] + · by_cases hrn : r.Nil + · have hx : x = P.finish := hrn.eq + have hqnr : ¬q.reverse.Nil := by simpa using hqn + let A := Arm.fromWalk q.reverse hq.reverse hqnr + refine ⟨.tip A, ?_, ?_⟩ + · change A.tip.walk.edgeSet = P.walk.edgeSet + rw [Arm.fromWalk_tip_edges, Walk.edgeSet_reverse] + rw [hqr, Walk.edgeSet_append] + simp [Walk.edgeSet, Walk.edges_eq_nil.mpr hrn] + · intro v + change (x = v ∨ A.far = v) ↔ _ + simp only [A, Arm.fromWalk_far, hx, or_comm] + · have hqnr : ¬q.reverse.Nil := by simpa using hqn + let A := Arm.fromWalk q.reverse hq.reverse hqnr + let B := Arm.fromWalk r hr hrn + have hd : A.walk.support.Disjoint B.walk.support := by + rw [Arm.fromWalk_support, Arm.fromWalk_support] + have hd := hp.disjoint_support_of_append hrn + rw [Walk.support_tail_of_not_nil r hrn] at hd + apply List.disjoint_left.mpr + intro v hv hw + exact List.disjoint_left.mp hd + (by simpa using (List.mem_of_mem_tail hv : v ∈ q.reverse.support)) hw + refine ⟨.through A B hd, ?_, ?_⟩ + · change ((Walk.cons A.adj A.walk).reverse.append (Walk.cons B.adj B.walk)).edgeSet = _ + rw [Walk.edgeSet_append, Walk.edgeSet_reverse] + change A.tip.walk.edgeSet ∪ B.tip.walk.edgeSet = _ + rw [Arm.fromWalk_tip_edges, Arm.fromWalk_tip_edges, Walk.edgeSet_reverse, + hqr, Walk.edgeSet_append] + · intro v + change (A.far = v ∨ B.far = v) ↔ _ + simp only [A, B, Arm.fromWalk_far] + · exact ⟨.away P hx, rfl, fun _ => Iff.rfl⟩ + +namespace Piece +variable {V : Type cycleUniverse29} {G H : SimpleGraph V} + +lemma isTrail (P : Piece G) : P.walk.IsTrail := by + rcases P.simple with hp | ⟨h,hc⟩ + · exact hp.1.isTrail + · exact (P.walk.isTrail_copy rfl h).mp hc.isTrail + +def mapLe (h : H ≤ G) (P : Piece H) : Piece G := by + rcases P with ⟨a,b,w,hs⟩ + refine ⟨a,b,w.mapLe h, ?_⟩ + rcases hs with hp | ⟨hb,hc⟩ + · exact Or.inl ⟨hp.1.mapLe h, by simpa using hp.2⟩ + · subst b + exact Or.inr ⟨rfl, by simpa using hc.mapLe h⟩ + +@[simp] lemma mapLe_edges (h : H ≤ G) (P : Piece H) : + (P.mapLe h).walk.edgeSet = P.walk.edgeSet := by + cases P + exact Walk.edgeSet_mapLe_eq_edgeSet _ _ + +@[simp] lemma mapLe_start (h : H ≤ G) (P : Piece H) : (P.mapLe h).start = P.start := by + cases P; rfl +@[simp] lemma mapLe_finish (h : H ≤ G) (P : Piece H) : (P.mapLe h).finish = P.finish := by + cases P; rfl + +lemma exists_centered (P : Piece G) (x : V) : + ∃ K : Centered G x, K.piece.walk.edgeSet = P.walk.edgeSet ∧ + ∀ v, P.start ≠ P.finish → (P.start = v ∨ P.finish = v) → v ≠ x → + ∃ p, K.endpoint p = v := by + rcases P with ⟨a,b,w,hs⟩ + rcases hs with hp | ⟨hb,hc⟩ + · let Q : PathPiece G := ⟨a,b,w,hp.1,hp.2⟩ + obtain ⟨F,he,hv⟩ := Q.exists_frame x + refine ⟨.path F, he, ?_⟩ + intro v _ he hx + exact (F.port_iff_endpoint v).mpr ⟨(hv v).mpr he, hx⟩ + · subst b + refine ⟨.cycle w (by simpa using hc), rfl, ?_⟩ + exact fun _ hn => (hn rfl).elim +end Piece + +theorem trail_partition_degree_sum {V : Type cycleUniverse30} {I : Type cycleUniverse31} [Fintype V] [Fintype I] + (G : SimpleGraph V) {a b : I → V} (p : ∀ i, G.Walk (a i) (b i)) + (ht : ∀ i, (p i).IsTrail) + (hd : Pairwise fun i j => Disjoint (p i).edgeSet (p j).edgeSet) + (hc : (⋃ i, (p i).edgeSet) = G.edgeSet) (v : V) : + G.degree v = ∑ i, (p i).edges.countP (fun e => decide (v ∈ e)) := by + classical + have he : G.edgeFinset = Finset.univ.biUnion (fun i => (p i).edges.toFinset) := by + ext e + simp only [SimpleGraph.mem_edgeFinset, ← hc, Set.mem_iUnion, + Finset.mem_biUnion, Finset.mem_univ, List.mem_toFinset, true_and, + SimpleGraph.Walk.mem_edgeSet] + rw [← G.card_incidenceFinset_eq_degree v, G.incidenceFinset_eq_filter, he, + Finset.filter_biUnion] + rw [Finset.card_biUnion] + · apply Finset.sum_congr rfl + intro i _ + have hfilter : ((p i).edges.filter (fun e => decide (v ∈ e))).toFinset = + ((p i).edges.toFinset.filter (fun e => v ∈ e)) := by + simp [List.toFinset_filter] + rw [← hfilter, List.toFinset_card_of_nodup ((ht i).edges_nodup.filter _), + List.countP_eq_length_filter] + · intro i _ j _ hij + apply Finset.disjoint_left.mpr + intro e hei hej + exact Set.disjoint_left.mp (hd hij) + (by simpa using (Finset.mem_filter.mp hei).1) + (by simpa using (Finset.mem_filter.mp hej).1) + +theorem trail_partition_even_degree_iff {V : Type cycleUniverse32} {I : Type cycleUniverse33} [Fintype V] [Fintype I] + (G : SimpleGraph V) {a b : I → V} (p : ∀ i, G.Walk (a i) (b i)) + (ht : ∀ i, (p i).IsTrail) + (hd : Pairwise fun i j => Disjoint (p i).edgeSet (p j).edgeSet) + (hc : (⋃ i, (p i).edgeSet) = G.edgeSet) (v : V) : + Even (G.degree v) ↔ Even (Finset.univ.filter + (fun i => a i ≠ b i ∧ (v = a i ∨ v = b i))).card := by + classical + rw [trail_partition_degree_sum G p ht hd hc v, Finset.even_sum_iff_even_card_odd] + have he : (Finset.univ.filter (fun i => Odd ((p i).edges.countP + (fun e => decide (v ∈ e))))) = (Finset.univ.filter + (fun i => a i ≠ b i ∧ (v = a i ∨ v = b i))) := by + ext i + simp only [Finset.mem_filter, Finset.mem_univ, true_and, + ← Nat.not_even_iff_odd, (ht i).even_countP_edges_iff] + tauto + rw [he] + +lemma endpoint_of_odd {V : Type cycleUniverse34} {I : Type cycleUniverse35} [Fintype V] [Fintype I] + (H : SimpleGraph V) (P : I → Piece H) + (hd : Pairwise fun i j => Disjoint (P i).walk.edgeSet (P j).walk.edgeSet) + (hc : (⋃ i, (P i).walk.edgeSet) = H.edgeSet) + (v : V) (hv : Odd (H.degree v)) : + ∃ i, (P i).start ≠ (P i).finish ∧ ((P i).start = v ∨ (P i).finish = v) := by + classical + have ho := (trail_partition_even_degree_iff H (fun i => (P i).walk) + (fun i => (P i).isTrail) hd hc v).not.mp (Nat.not_even_iff_odd.mpr hv) + have hp : 0 < (Finset.univ.filter + (fun i => (P i).start ≠ (P i).finish ∧ (v = (P i).start ∨ v = (P i).finish))).card := by + by_contra hn + have hz : (Finset.univ.filter + (fun i => (P i).start ≠ (P i).finish ∧ (v = (P i).start ∨ v = (P i).finish))).card = 0 := by omega + exact ho (hz ▸ ⟨0, rfl⟩) + obtain ⟨i,hi⟩ := Finset.card_pos.mp hp + exact ⟨i, (Finset.mem_filter.mp hi).2.1, by + simpa only [eq_comm] using (Finset.mem_filter.mp hi).2.2⟩ + +theorem restore_partition {V : Type cycleUniverse36} {I : Type cycleUniverse37} [Fintype V] [Fintype I] + (G H : SimpleGraph V) (hHG : H ≤ G) (x : V) (S : Set V) + (hS : ∀ v ∈ S, G.Adj x v) + (hedges : G.edgeSet = H.edgeSet ∪ {e | ∃ v ∈ S, e = s(x,v)}) + (hfresh : Disjoint {e | ∃ v ∈ S, e = s(x,v)} H.edgeSet) + (hodd : ∀ v, G.Adj x v → Odd (H.degree v)) + (P : I → Piece H) + (hd : Pairwise fun i j => Disjoint (P i).walk.edgeSet (P j).walk.edgeSet) + (hc : (⋃ i, (P i).walk.edgeSet) = H.edgeSet) : + ∃ Q : I → Piece G, + (Pairwise fun i j => Disjoint (Q i).walk.edgeSet (Q j).walk.edgeSet) ∧ + (⋃ i, (Q i).walk.edgeSet) = G.edgeSet := by + choose K hk hv using fun i => ((P i).mapLe hHG).exists_centered x + have he : ∀ i, (K i).piece.walk.edgeSet = (P i).walk.edgeSet := by + intro i; exact (hk i).trans ((P i).mapLe_edges hHG) + have hKC : (⋃ i, (K i).piece.walk.edgeSet) = H.edgeSet := by simpa only [he] using hc + obtain ⟨Q,hQ,hQC⟩ := restore_star G x K S hS + (by simpa only [he] using hd) (by rwa [hKC]) (by + intro v hxv + obtain ⟨i, hi, hiv⟩ := endpoint_of_odd H P hd hc v (hodd v hxv) + obtain ⟨p,hp⟩ := hv i v (by simpa using hi) (by simpa using hiv) hxv.ne.symm + exact ⟨i,p,hp⟩) + exact ⟨Q,hQ,by simpa only [hKC, ← hedges] using hQC⟩ + +def activeOrder {V : Type cycleUniverse38} [Fintype V] (G : SimpleGraph V) : ℕ := + G.support.toFinset.card + +lemma activeOrder_mono {V : Type cycleUniverse39} [Fintype V] {G H : SimpleGraph V} (h : H ≤ G) : + activeOrder H ≤ activeOrder G := by + apply Finset.card_le_card + intro v hv + exact Set.mem_toFinset.mpr (SimpleGraph.support_mono h (Set.mem_toFinset.mp hv)) + +def HasPartition {V : Type cycleUniverse40} [Fintype V] (G : SimpleGraph V) : Prop := + ∃ (k : ℕ) (P : Fin k → Piece G), + (Pairwise fun i j => Disjoint (P i).walk.edgeSet (P j).walk.edgeSet) ∧ + (⋃ i, (P i).walk.edgeSet) = G.edgeSet ∧ 2 * k ≤ activeOrder G + +def evenStarVertices {V : Type cycleUniverse41} [Fintype V] (G : SimpleGraph V) (x : V) : Set V := + {y | G.Adj x y ∧ Even (G.degree y)} + +def evenStarEdges {V : Type cycleUniverse42} [Fintype V] (G : SimpleGraph V) (x : V) : Set (Sym2 V) := + {e | ∃ y ∈ evenStarVertices G x, e = s(x,y)} + +def deleteEvenStar {V : Type cycleUniverse43} [Fintype V] (G : SimpleGraph V) (x : V) : SimpleGraph V := + G.deleteEdges (evenStarEdges G x) + +lemma evenStar_subset {V : Type cycleUniverse44} [Fintype V] (G : SimpleGraph V) (x : V) : + evenStarEdges G x ⊆ G.edgeSet := by + rintro e ⟨y,hy,rfl⟩; exact hy.1 + +lemma deleteEvenStar_neighbor_even {V : Type cycleUniverse45} [Fintype V] (G : SimpleGraph V) + (x v : V) (hxv : G.Adj x v) (he : Even (G.degree v)) : + (deleteEvenStar G x).neighborFinset v = (G.neighborFinset v).erase x := by + classical + ext w + rw [Finset.mem_erase, (deleteEvenStar G x).mem_neighborFinset, G.mem_neighborFinset] + rw [deleteEvenStar, SimpleGraph.deleteEdges_adj] + simp only [evenStarEdges, Set.mem_ofPred_eq, evenStarVertices, Sym2.eq_iff] + constructor + · rintro ⟨hvw, hn⟩ + refine ⟨?_,hvw⟩ + intro hw; subst w + exact hn ⟨v,⟨hxv,he⟩, Or.inr ⟨rfl,rfl⟩⟩ + · rintro ⟨hw,hvw⟩ + refine ⟨hvw, ?_⟩ + rintro ⟨y,_,h⟩ + rcases h with ⟨h,_⟩ | ⟨_,h⟩ + · exact hxv.ne h.symm + · exact hw h + +lemma deleteEvenStar_neighbor_odd {V : Type cycleUniverse46} [Fintype V] (G : SimpleGraph V) + (x v : V) (hxv : G.Adj x v) (he : ¬Even (G.degree v)) : + (deleteEvenStar G x).neighborFinset v = G.neighborFinset v := by + classical + ext w + rw [(deleteEvenStar G x).mem_neighborFinset, G.mem_neighborFinset] + rw [deleteEvenStar, SimpleGraph.deleteEdges_adj] + simp only [evenStarEdges, Set.mem_ofPred_eq, evenStarVertices, Sym2.eq_iff] + refine ⟨fun h => h.1, fun hw => ⟨hw, ?_⟩⟩ + rintro ⟨y,hy,h⟩ + rcases h with ⟨h,_⟩ | ⟨h,_⟩ + · exact hxv.ne h.symm + · subst y; exact he hy.2 + +lemma deleteEvenStar_neighbor_degree {V : Type cycleUniverse47} [Fintype V] (G : SimpleGraph V) + (x v : V) (hxv : G.Adj x v) : Odd ((deleteEvenStar G x).degree v) := by + classical + by_cases he : Even (G.degree v) + · have hcard := Finset.card_erase_add_one (s := G.neighborFinset v) + (a := x) (by simpa using hxv.symm) + rw [← deleteEvenStar_neighbor_even G x v hxv he, + G.card_neighborFinset_eq_degree, (deleteEvenStar G x).card_neighborFinset_eq_degree] at hcard + obtain ⟨k,hk⟩ := he + exact ⟨k-1, by omega⟩ + · rw [← (deleteEvenStar G x).card_neighborFinset_eq_degree v, + deleteEvenStar_neighbor_odd G x v hxv he, G.card_neighborFinset_eq_degree] + exact Nat.not_even_iff_odd.mp he + +lemma deleteEvenStar_edges {V : Type cycleUniverse48} [Fintype V] (G : SimpleGraph V) (x : V) : + G.edgeSet = (deleteEvenStar G x).edgeSet ∪ evenStarEdges G x := by + rw [deleteEvenStar, SimpleGraph.edgeSet_deleteEdges, + Set.sdiff_union_of_subset (evenStar_subset G x)] + +lemma deleteEvenStar_fresh {V : Type cycleUniverse49} [Fintype V] (G : SimpleGraph V) (x : V) : + Disjoint (evenStarEdges G x) (deleteEvenStar G x).edgeSet := by + rw [deleteEvenStar, SimpleGraph.edgeSet_deleteEdges] + exact Set.disjoint_sdiff_right + +lemma deleteEvenStar_lt {V : Type cycleUniverse50} [Fintype V] (G : SimpleGraph V) (x y : V) + (hxy : G.Adj x y) (he : Even (G.degree y)) : + (deleteEvenStar G x).edgeFinset.card < G.edgeFinset.card := by + classical + apply Finset.card_lt_card + apply Finset.ssubset_iff_subset_ne.mpr + refine ⟨?_, ?_⟩ + · intro e he + exact G.mem_edgeFinset.mpr (SimpleGraph.edgeSet_mono + (show deleteEvenStar G x ≤ G from G.deleteEdges_le _) + ((deleteEvenStar G x).mem_edgeFinset.mp he)) + · intro h + have hh : s(x,y) ∈ (deleteEvenStar G x).edgeFinset := h.symm ▸ G.mem_edgeFinset.mpr hxy + have hf : s(x,y) ∈ evenStarEdges G x := ⟨y,⟨hxy,he⟩,rfl⟩ + exact Set.disjoint_left.mp (deleteEvenStar_fresh G x) hf (SimpleGraph.mem_edgeFinset.mp hh) + +theorem even_vertex_step {V : Type cycleUniverse51} [Fintype V] (G : SimpleGraph V) + (hIH : ∀ H : SimpleGraph V, H.edgeFinset.card < G.edgeFinset.card → HasPartition H) + (hpos : ∃ y, 0 < G.degree y ∧ Even (G.degree y)) : HasPartition G := by + classical + obtain ⟨y,hy,he⟩ := hpos + obtain ⟨x,hxy⟩ := (G.degree_pos_iff_exists_adj y).mp hy + let H := deleteEvenStar G x + obtain ⟨k,P,hd,hc,hk⟩ := hIH H (deleteEvenStar_lt G x y hxy.symm he) + obtain ⟨Q,hQ,hQC⟩ := restore_partition G H (G.deleteEdges_le _) x + (evenStarVertices G x) (fun _ h => h.1) (deleteEvenStar_edges G x) + (deleteEvenStar_fresh G x) (deleteEvenStar_neighbor_degree G x) P hd hc + exact ⟨k,Q,hQ,hQC,hk.trans (activeOrder_mono (G.deleteEdges_le _))⟩ + +lemma single_edge_piece {V : Type cycleUniverse52} (G : SimpleGraph V) (e : Sym2 V) (he : e ∈ G.edgeSet) : + ∃ P : Piece G, P.walk.edgeSet = {e} := by + induction e using Sym2.ind with + | _ a b => + have hab : G.Adj a b := he + let P : PathPiece G := ⟨a,b,Walk.cons hab Walk.nil, + (Walk.IsPath.nil).cons (by simpa using hab.ne), by simp⟩ + exact ⟨.ofPath P, by simp [Piece.ofPath, P]⟩ + +lemma partition_single_edges {V : Type cycleUniverse53} [Fintype V] (G : SimpleGraph V) : + ∃ P : Fin G.edgeFinset.card → Piece G, + (Pairwise fun i j => Disjoint (P i).walk.edgeSet (P j).walk.edgeSet) ∧ + (⋃ i, (P i).walk.edgeSet) = G.edgeSet := by + classical + choose P hP using fun e : G.edgeSet => single_edge_piece G e.val e.property + let e : G.edgeSet ≃ Fin G.edgeFinset.card := (Fintype.equivFin G.edgeSet).trans + (finCongr (G.card_edgeSet)) + refine ⟨fun i => P (e.symm i), ?_, ?_⟩ + · intro i j hij + rw [hP, hP] + exact Set.disjoint_singleton.mpr (fun h => hij (e.symm.injective (Subtype.ext h))) + · ext z + simp only [Set.mem_iUnion,hP,Set.mem_singleton_iff] + constructor + · rintro ⟨i,rfl⟩; exact (e.symm i).property + · intro hz + exact ⟨e ⟨z,hz⟩, by simp⟩ + +lemma matching_partition {V : Type cycleUniverse54} [Fintype V] (G : SimpleGraph V) + (hdeg : ∀ v, G.degree v ≤ 1) : HasPartition G := by + classical + obtain ⟨P,hd,hc⟩ := partition_single_edges G + refine ⟨_,P,hd,hc,?_⟩ + rw [← G.sum_degrees_support_eq_twice_card_edges] + simpa [activeOrder] using Finset.sum_le_sum (s := G.support.toFinset) + (f := fun v => G.degree v) (g := fun _ => 1) (fun v _ => hdeg v) + +def subdivision {V : Type cycleUniverse55} (G : SimpleGraph V) (x y : V) : SimpleGraph (Option V) where + Adj a b := match a,b with + | some a, some b => G.Adj a b ∧ s(a,b) ≠ s(x,y) + | none, some b => b = x ∨ b = y + | some a, none => a = x ∨ a = y + | none, none => False + symm := ⟨by + intro a b h + cases a <;> cases b + · exact h + · exact h + · exact h + · exact ⟨h.1.symm, by simpa only [Sym2.eq_swap] using h.2⟩⟩ + loopless := ⟨by + intro a h + cases a + · exact h + · exact G.irrefl h.1⟩ + +@[simp] lemma subdivision_some {V : Type cycleUniverse56} (G : SimpleGraph V) (x y a b : V) : + (subdivision G x y).Adj (some a) (some b) ↔ G.Adj a b ∧ s(a,b) ≠ s(x,y) := Iff.rfl +@[simp] lemma subdivision_none_some {V : Type cycleUniverse57} (G : SimpleGraph V) (x y a : V) : + (subdivision G x y).Adj none (some a) ↔ a = x ∨ a = y := Iff.rfl +@[simp] lemma subdivision_some_none {V : Type cycleUniverse58} (G : SimpleGraph V) (x y a : V) : + (subdivision G x y).Adj (some a) none ↔ a = x ∨ a = y := Iff.rfl +@[simp] lemma subdivision_none_none {V : Type cycleUniverse59} (G : SimpleGraph V) (x y : V) : + ¬(subdivision G x y).Adj none none := id + +def halfSubdivision {V : Type cycleUniverse60} (G : SimpleGraph V) (x y : V) : SimpleGraph (Option V) := + (subdivision G x y).deleteEdges {s(none,some x)} + +@[simp] lemma half_some {V : Type cycleUniverse61} (G : SimpleGraph V) (x y a b : V) : + (halfSubdivision G x y).Adj (some a) (some b) ↔ G.Adj a b ∧ s(a,b) ≠ s(x,y) := by + rw [halfSubdivision, SimpleGraph.deleteEdges_adj] + simp [] + +@[simp] lemma half_none_some {V : Type cycleUniverse62} (G : SimpleGraph V) (x y a : V) (hxy : x ≠ y) : + (halfSubdivision G x y).Adj none (some a) ↔ a = y := by + rw [halfSubdivision, SimpleGraph.deleteEdges_adj] + simp only [subdivision_none_some, Set.mem_singleton_iff, star_inj, Option.some.injEq] + aesop + +@[simp] lemma half_some_none {V : Type cycleUniverse63} (G : SimpleGraph V) (x y a : V) (hxy : x ≠ y) : + (halfSubdivision G x y).Adj (some a) none ↔ a = y := by + rw [(halfSubdivision G x y).adj_comm, half_none_some G x y a hxy] + +lemma option_degree_some {V : Type cycleUniverse64} [Fintype V] (K : SimpleGraph (Option V)) (v : V) : + K.degree (some v) = (Finset.univ.filter (fun u : V => K.Adj (some v) (some u))).card + + if K.Adj (some v) none then 1 else 0 := by + classical + rw [← K.card_neighborFinset_eq_degree, K.neighborFinset_eq_filter, + Finset.card_eq_sum_ones, Finset.sum_filter, Fintype.sum_option] + rw [Finset.card_eq_sum_ones, Finset.sum_filter] + omega + +lemma option_degree_none {V : Type cycleUniverse65} [Fintype V] (K : SimpleGraph (Option V)) : + K.degree none = (Finset.univ.filter (fun u : V => K.Adj none (some u))).card := by + classical + rw [← K.card_neighborFinset_eq_degree, K.neighborFinset_eq_filter, + Finset.card_eq_sum_ones, Finset.sum_filter, Fintype.sum_option] + rw [Finset.card_eq_sum_ones, Finset.sum_filter] + simp + +lemma subdivision_old_neighbors {V : Type cycleUniverse66} [Fintype V] (G : SimpleGraph V) + (x y v : V) : + (Finset.univ.filter fun u : V => (subdivision G x y).Adj (some v) (some u)) = + if v = x then (G.neighborFinset v).erase y else + if v = y then (G.neighborFinset v).erase x else G.neighborFinset v := by + classical + ext u + by_cases hx : v = x + · subst v + simp [eq_comm, and_comm] + aesop + · by_cases hy : v = y + · subst v + simp [hx, eq_comm, and_comm] + tauto + · simp [hx, hy] + +lemma subdivision_degree {V : Type cycleUniverse67} [Fintype V] (G : SimpleGraph V) + (x y v : V) (hxy : G.Adj x y) : + (subdivision G x y).degree (some v) = G.degree v := by + classical + rw [option_degree_some, subdivision_old_neighbors] + by_cases hx : v = x + · subst v + simpa using Finset.card_erase_add_one (s := G.neighborFinset x) (a := y) + (by simpa using hxy) + · by_cases hy : v = y + · subst v + simpa [hx] using Finset.card_erase_add_one (s := G.neighborFinset y) (a := x) + (by simpa using hxy.symm) + · simp [hx,hy] + +lemma subdivision_degree_none {V : Type cycleUniverse68} [Fintype V] (G : SimpleGraph V) + (x y : V) (hxy : G.Adj x y) : (subdivision G x y).degree none = 2 := by + classical + rw [option_degree_none] + have he : (Finset.univ.filter fun u : V => (subdivision G x y).Adj none (some u)) = + {x,y} := by ext u; simp + rw [he] + simp [hxy.ne] + +lemma half_degree {V : Type cycleUniverse69} [Fintype V] (G : SimpleGraph V) + (x y v : V) (hxy : G.Adj x y) : + (halfSubdivision G x y).degree (some v) + (if v = x then 1 else 0) = G.degree v := by + classical + rw [option_degree_some] + have he : (Finset.univ.filter fun u : V => (halfSubdivision G x y).Adj (some v) (some u)) = + (Finset.univ.filter fun u : V => (subdivision G x y).Adj (some v) (some u)) := by + ext u; simp + rw [he, subdivision_old_neighbors] + by_cases hx : v = x + · subst v + simpa [hxy.ne] using Finset.card_erase_add_one (s := G.neighborFinset x) (a := y) + (by simpa using hxy) + · by_cases hy : v = y + · subst v + simpa [hx, hxy.ne] using Finset.card_erase_add_one (s := G.neighborFinset y) (a := x) + (by simpa using hxy.symm) + · simp [hx,hy,half_some_none G x y v hxy.ne] + +lemma half_degree_none {V : Type cycleUniverse70} [Fintype V] (G : SimpleGraph V) + (x y : V) (hxy : G.Adj x y) : (halfSubdivision G x y).degree none = 1 := by + classical + rw [option_degree_none] + have he : (Finset.univ.filter fun u : V => (halfSubdivision G x y).Adj none (some u)) = + {y} := by ext u; simp [half_none_some G x y u hxy.ne] + rw [he] + simp + +lemma subdivision_edge_count {V : Type cycleUniverse71} [Fintype V] (G : SimpleGraph V) + (x y : V) (hxy : G.Adj x y) : + (subdivision G x y).edgeFinset.card = G.edgeFinset.card + 1 := by + classical + have hd := (subdivision G x y).sum_degrees_eq_twice_card_edges + rw [Fintype.sum_option, subdivision_degree_none G x y hxy] at hd + simp_rw [subdivision_degree G x y _ hxy] at hd + rw [G.sum_degrees_eq_twice_card_edges] at hd + omega + +lemma half_edge_count {V : Type cycleUniverse72} [Fintype V] (G : SimpleGraph V) + (x y : V) (hxy : G.Adj x y) : + (halfSubdivision G x y).edgeFinset.card = G.edgeFinset.card := by + classical + have he : (halfSubdivision G x y).edgeFinset = + (subdivision G x y).edgeFinset.erase s(none,some x) := by + ext e + rw [(halfSubdivision G x y).mem_edgeFinset, Finset.mem_erase, + (subdivision G x y).mem_edgeFinset] + simp [halfSubdivision, SimpleGraph.edgeSet_deleteEdges, and_comm] + rw [he, Finset.card_erase_of_mem, subdivision_edge_count G x y hxy] + · omega + · exact (subdivision G x y).mem_edgeFinset.mpr (Or.inl rfl) + +lemma subdivision_activeOrder {V : Type cycleUniverse73} [Fintype V] (G : SimpleGraph V) + (x y : V) (hxy : G.Adj x y) : + activeOrder (subdivision G x y) = activeOrder G + 1 := by + classical + have he : (subdivision G x y).support.toFinset = + insert none (G.support.toFinset.image Option.some) := by + ext v + cases v with + | none => simp [← SimpleGraph.degree_pos_iff_mem_support, subdivision_degree_none G x y hxy] + | some v => + simp only [Set.mem_toFinset, Finset.mem_insert, Option.some_ne_none, Finset.mem_image, + Option.some.injEq, false_or, exists_eq_right] + rw [← (subdivision G x y).degree_pos_iff_mem_support, + subdivision_degree G x y v hxy, G.degree_pos_iff_mem_support] + dsimp [activeOrder] + rw [he, Finset.card_insert_of_notMem, Finset.card_image_of_injective] + · exact Option.some_injective V + · simp + +lemma suppress_path {V : Type cycleUniverse74} (G : SimpleGraph V) (x y : V) (hxy : G.Adj x y) + {a b : V} (p : (subdivision G x y).Walk (some a) (some b)) (hp : p.IsPath) : + ∃ q : G.Walk a b, q.IsPath ∧ q.support = p.support.filterMap id ∧ + ∀ e : Sym2 V, e ∈ q.edgeSet ↔ + e.map Option.some ∈ p.edgeSet ∨ (e = s(x,y) ∧ s(none,some x) ∈ p.edgeSet) := by + classical + generalize hn : p.length = n + induction n using Nat.strong_induction_on generalizing a b with + | h n ih => + cases p with + | nil => + refine ⟨.nil, by simp, by simp, ?_⟩ + intro e + simp + | @cons _ v _ h p => + have ht : p.IsPath := hp.of_cons + have ha : some a ∉ p.support := (Walk.cons_isPath_iff _ _ |>.mp hp).2 + cases v with + | some c => + obtain ⟨q,hq,hqs,hqe⟩ := ih p.length (by simp only [Walk.length_cons] at hn; omega) p ht rfl + have hac : G.Adj a c := (subdivision_some G x y a c).mp h |>.1 + refine ⟨.cons hac q, hq.cons ?_, ?_, ?_⟩ + · intro ha' + apply ha + rw [hqs] at ha' + simpa using ha' + · simp [hqs] + · intro e + have hinj : Function.Injective (Sym2.map (Option.some : V → Option V)) := + Sym2.map.injective (Option.some_injective V) + have he : e.map Option.some = s(some a,some c) ↔ e = s(a,c) := + by simpa only [Sym2.map_mk] using (hinj.eq_iff (a := e) (b := s(a,c))) + have hnedge : s(none,some x) ≠ s(some a,some c) := by simp [] + simp only [Walk.edgeSet_cons, Set.mem_insert_iff, he, hnedge, false_or, hqe] + tauto + | none => + cases p with + | @cons _ v _ h' p => + cases v with + | none => exact (h'.ne rfl).elim + | some c => + have hac : a ≠ c := by + intro he + apply ha + simp [he] + have hae : a = x ∨ a = y := (subdivision_some_none G x y a).mp h + have hce : c = x ∨ c = y := (subdivision_none_some G x y c).mp h' + have hexy : s(a,c) = s(x,y) := by + rcases hae with rfl | rfl <;> rcases hce with rfl | rfl + · exact (hac rfl).elim + · rfl + · exact Sym2.eq_swap + · exact (hac rfl).elim + have hacG : G.Adj a c := G.mem_edgeSet.mp (hexy.symm ▸ hxy) + obtain ⟨q,hq,hqs,hqe⟩ := ih p.length (by simp only [Walk.length_cons] at hn; omega) p ht.of_cons rfl + refine ⟨.cons hacG q, hq.cons ?_, ?_, ?_⟩ + · intro ha' + apply ha + have hh : some a ∈ p.support := by rw [hqs] at ha'; simpa using ha' + simp [hh] + · simp [hqs] + · intro e + have he1 : e.map Option.some ≠ s(some a,none) := by + induction e using Sym2.inductionOn with | _ u v => simp [] + have he2 : e.map Option.some ≠ s(none,some c) := by + induction e using Sym2.inductionOn with | _ u v => simp [] + have hn : s(none,some x) = s(some a,none) ∨ + s(none,some x) = s(none,some c) := by + rcases hae with rfl | hay + · exact Or.inl Sym2.eq_swap + · rcases hce with rfl | hcy + · exact Or.inr rfl + · exact (hac (hay.trans hcy.symm)).elim + simp only [Walk.edgeSet_cons, Set.mem_insert_iff, he1, he2, false_or, + hexy, hqe] + tauto + +lemma tight_partition_endpoints {V : Type cycleUniverse75} {I : Type cycleUniverse76} [Fintype V] [Fintype I] + (G : SimpleGraph V) (P : I → Piece G) (S : Finset V) + (hd : Pairwise fun i j => Disjoint (P i).walk.edgeSet (P j).walk.edgeSet) + (hc : (⋃ i, (P i).walk.edgeSet) = G.edgeSet) + (ho : ∀ v ∈ S, Odd (G.degree v)) (hk : 2 * Fintype.card I ≤ S.card) : + ∀ i, (P i).start ≠ (P i).finish ∧ (P i).start ∈ S ∧ (P i).finish ∈ S := by + classical + let endpoint : I × Bool → V := fun z => if z.2 then (P z.1).start else (P z.1).finish + have he : ∀ v : S, ∃ z : I × Bool, endpoint z = v := by + intro v + obtain ⟨i,_, h | h⟩ := endpoint_of_odd G P hd hc v (ho v v.property) + · exact ⟨(i,true),h⟩ + · exact ⟨(i,false),h⟩ + choose pick hpick using he + have hinj : Function.Injective pick := by + intro v w hvw + apply Subtype.ext + exact (hpick v).symm.trans ((congrArg endpoint hvw).trans (hpick w)) + have hsurj : Function.Surjective pick := by + by_contra hn + have hh := Fintype.card_lt_of_injective_not_surjective pick hinj hn + simp only [Fintype.card_coe, Fintype.card_prod, Fintype.card_bool] at hh + omega + have hendinj : Function.Injective endpoint := by + intro z t heq + obtain ⟨v,rfl⟩ := hsurj z + obtain ⟨w,rfl⟩ := hsurj t + have hvw : v = w := Subtype.ext (by simpa only [hpick] using heq) + exact congrArg pick hvw + have hmem : ∀ z, endpoint z ∈ S := by + intro z + obtain ⟨v,rfl⟩ := hsurj z + rw [hpick] + exact v.property + intro i + refine ⟨?_, hmem (i,true), hmem (i,false)⟩ + intro heq + have hh := hendinj (show endpoint (i,true) = endpoint (i,false) from heq) + have := congrArg Prod.snd hh + contradiction + +def subdivisionRepresentative {V : Type cycleUniverse77} (x y : V) (e : Sym2 V) : Sym2 (Option V) := + if e = s(x,y) then s(none,some x) else e.map Option.some + +lemma representative_mem {V : Type cycleUniverse78} (G : SimpleGraph V) (x y : V) (_hxy : G.Adj x y) + (e : Sym2 V) (he : e ∈ G.edgeSet) : + subdivisionRepresentative x y e ∈ (subdivision G x y).edgeSet := by + classical + by_cases h : e = s(x,y) + · simp [subdivisionRepresentative, h] + · rw [subdivisionRepresentative, ite_eq_right h] + induction e using Sym2.ind with + | _ a b => exact ⟨he,h⟩ + +lemma suppress_piece {V : Type cycleUniverse79} (G : SimpleGraph V) (x y : V) (hxy : G.Adj x y) + (P : Piece (subdivision G x y)) (hne : P.start ≠ P.finish) + (ha : P.start ≠ none) (hb : P.finish ≠ none) : + ∃ Q : Piece G, ∀ e, e ∈ Q.walk.edgeSet ↔ subdivisionRepresentative x y e ∈ P.walk.edgeSet := by + classical + rcases P with ⟨a,b,p,hp⟩ + cases a with + | none => exact (ha rfl).elim + | some a => + cases b with + | none => exact (hb rfl).elim + | some b => + have hab : a ≠ b := fun h => hne (congrArg some h) + have hpath : p.IsPath := by + rcases hp with h | ⟨h,_⟩ + · exact h.1 + · exact (hne h.symm).elim + obtain ⟨q,hq,_,hqe⟩ := suppress_path G x y hxy p hpath + have hpos : 0 < q.length := by + by_contra hn + exact hab (Walk.eq_of_length_eq_zero (by omega : q.length = 0)) + refine ⟨.ofPath ⟨a,b,q,hq,hpos⟩, ?_⟩ + intro e + change e ∈ q.edgeSet ↔ _ + rw [hqe] + by_cases he : e = s(x,y) + · subst e + have hn : (s(x,y) : Sym2 V).map some ∉ p.edgeSet := by + intro h + have hh := p.edges_subset_edgeSet h + exact hh.2 rfl + simp only [subdivisionRepresentative, ite_true, hn, false_or, true_and] + · simp [subdivisionRepresentative, he] + +lemma suppress_partition {V : Type cycleUniverse80} {I : Type cycleUniverse81} [Fintype I] + (G : SimpleGraph V) (x y : V) (hxy : G.Adj x y) + (P : I → Piece (subdivision G x y)) + (hd : Pairwise fun i j => Disjoint (P i).walk.edgeSet (P j).walk.edgeSet) + (hc : (⋃ i, (P i).walk.edgeSet) = (subdivision G x y).edgeSet) + (hp : ∀ i, (P i).start ≠ (P i).finish ∧ (P i).start ≠ none ∧ (P i).finish ≠ none) : + ∃ Q : I → Piece G, + (Pairwise fun i j => Disjoint (Q i).walk.edgeSet (Q j).walk.edgeSet) ∧ + (⋃ i, (Q i).walk.edgeSet) = G.edgeSet := by + classical + choose Q hQ using fun i => suppress_piece G x y hxy (P i) (hp i).1 (hp i).2.1 (hp i).2.2 + refine ⟨Q, ?_, ?_⟩ + · intro i j hij + exact Set.disjoint_left.mpr fun e hei hej => + Set.disjoint_left.mp (hd hij) ((hQ i e).mp hei) ((hQ j e).mp hej) + · apply Set.Subset.antisymm + · exact Set.iUnion_subset fun i => (Q i).walk.edges_subset_edgeSet + · intro e he + have hrep := representative_mem G x y hxy e he + rw [← hc] at hrep + obtain ⟨i,hi⟩ := Set.mem_iUnion.mp hrep + exact Set.mem_iUnion.mpr ⟨i,(hQ i e).mpr hi⟩ + +lemma even_activeOrder {V : Type cycleUniverse82} [Fintype V] (G : SimpleGraph V) + (ho : ∀ v, 0 < G.degree v → Odd (G.degree v)) : Even (activeOrder G) := by + classical + have he : G.support.toFinset = Finset.univ.filter (fun v => Odd (G.degree v)) := by + ext v + simp only [Set.mem_toFinset, Finset.mem_filter, Finset.mem_univ, true_and, + ← G.degree_pos_iff_mem_support] + refine ⟨ho v, ?_⟩ + rintro ⟨k,hk⟩ + omega + simpa only [activeOrder, he] using G.even_card_odd_degree_vertices + +lemma half_restore {V : Type cycleUniverse83} {I : Type cycleUniverse84} [Fintype V] [Fintype I] + (G : SimpleGraph V) (x y : V) (hxy : G.Adj x y) + (ho : ∀ v, 0 < G.degree v → Odd (G.degree v)) + (P : I → Piece (halfSubdivision G x y)) + (hd : Pairwise fun i j => Disjoint (P i).walk.edgeSet (P j).walk.edgeSet) + (hc : (⋃ i, (P i).walk.edgeSet) = (halfSubdivision G x y).edgeSet) : + ∃ Q : I → Piece (subdivision G x y), + (Pairwise fun i j => Disjoint (Q i).walk.edgeSet (Q j).walk.edgeSet) ∧ + (⋃ i, (Q i).walk.edgeSet) = (subdivision G x y).edgeSet := by + classical + have he : {e : Sym2 (Option V) | ∃ v ∈ ({none} : Set (Option V)), e = s(some x,v)} = + {s(none,some x)} := by + ext e + simp [Sym2.eq_swap] + apply restore_partition (subdivision G x y) (halfSubdivision G x y) + ((subdivision G x y).deleteEdges_le _) (some x) {none} + (by intro v hv; rcases hv with rfl; exact Or.inl rfl) ?_ ?_ ?_ P hd hc + · rw [he, halfSubdivision, SimpleGraph.edgeSet_deleteEdges] + symm + apply Set.sdiff_union_of_subset + intro e he + rcases he with rfl + exact Or.inl rfl + · rw [he, halfSubdivision, SimpleGraph.edgeSet_deleteEdges] + exact Set.disjoint_sdiff_right + · intro v hv + cases v with + | none => rw [half_degree_none G x y hxy]; exact ⟨0,rfl⟩ + | some v => + have hxv : G.Adj x v := hv.1 + have hh := half_degree G x y v hxy + rw [ite_eq_right hxv.ne.symm, add_zero] at hh + rw [hh] + exact ho v ((G.degree_pos_iff_exists_adj v).mpr ⟨x,hxv.symm⟩) + +theorem odd_vertex_step {V : Type cycleUniverse85} [Fintype V] (G : SimpleGraph V) + (hIH : ∀ H : SimpleGraph (Option V), H.edgeFinset.card < G.edgeFinset.card → HasPartition H) + (ho : ∀ v, 0 < G.degree v → Odd (G.degree v)) (x : V) (hx : 3 ≤ G.degree x) : + HasPartition G := by + classical + obtain ⟨y,hxy⟩ := (G.degree_pos_iff_exists_adj x).mp (by omega) + have hp : ∃ v, 0 < (halfSubdivision G x y).degree v ∧ + Even ((halfSubdivision G x y).degree v) := by + refine ⟨some x, ?_, ?_⟩ + · have hd := half_degree G x y x hxy + simp only [ite_true] at hd + omega + · have hd := half_degree G x y x hxy + simp only [ite_true] at hd + obtain ⟨k,hk⟩ := ho x (by omega) + exact ⟨k,by omega⟩ + obtain ⟨k,P,hd,hc,hk⟩ := even_vertex_step (halfSubdivision G x y) + (fun H hh => hIH H (by rwa [half_edge_count G x y hxy] at hh)) hp + have hbound : 2 * k ≤ activeOrder G + 1 := by + have hm := activeOrder_mono ((subdivision G x y).deleteEdges_le {s(none,some x)}) + rw [subdivision_activeOrder G x y hxy] at hm + exact hk.trans hm + have hk' : 2 * k ≤ activeOrder G := by + obtain ⟨a,ha⟩ := even_activeOrder G ho + omega + obtain ⟨Q,hQ,hQC⟩ := half_restore G x y hxy ho P hd hc + let S := G.support.toFinset.image Option.some + have hScard : S.card = activeOrder G := by + exact Finset.card_image_of_injective _ (Option.some_injective V) + have hSodd : ∀ v ∈ S, Odd ((subdivision G x y).degree v) := by + intro v hv + obtain ⟨w,hw,rfl⟩ := Finset.mem_image.mp hv + rw [subdivision_degree G x y w hxy] + exact ho w ((G.degree_pos_iff_mem_support w).mpr (Set.mem_toFinset.mp hw)) + have hends := tight_partition_endpoints (subdivision G x y) Q S hQ hQC hSodd + (by simpa only [Fintype.card_fin, hScard] using hk') + have hnon : ∀ i, (Q i).start ≠ (Q i).finish ∧ + (Q i).start ≠ none ∧ (Q i).finish ≠ none := by + intro i + refine ⟨(hends i).1, ?_, ?_⟩ + · intro h + have hh := (hends i).2.1 + simp only [h, S, Finset.mem_image, Option.some_ne_none, and_false, exists_false] at hh + · intro h + have hh := (hends i).2.2 + simp only [h, S, Finset.mem_image, Option.some_ne_none, and_false, exists_false] at hh + obtain ⟨R,hR,hRC⟩ := suppress_partition G x y hxy Q hQ hQC hnon + exact ⟨k,R,hR,hRC,hk'⟩ + +theorem path_cycle_partition {V : Type u} [Fintype V] (G : SimpleGraph V) : HasPartition G := by + classical + suffices ∀ (n : ℕ) (W : Type u) [Fintype W] (H : SimpleGraph W), + H.edgeFinset.card = n → HasPartition H by + exact this G.edgeFinset.card V G rfl + intro n + induction n using Nat.strong_induction_on with + | h n ih => + intro W _ H hcount + by_cases he : ∃ v, 0 < H.degree v ∧ Even (H.degree v) + · exact even_vertex_step H (fun K hk => ih K.edgeFinset.card (by omega) W K rfl) he + · have ho : ∀ v, 0 < H.degree v → Odd (H.degree v) := by + intro v hv + exact Nat.not_even_iff_odd.mp (fun hev => he ⟨v,hv,hev⟩) + by_cases hm : ∀ v, H.degree v ≤ 1 + · exact matching_partition H hm + · push Not at hm + obtain ⟨x,hx⟩ := hm + have hx3 : 3 ≤ H.degree x := by + obtain ⟨k,hk⟩ := ho x (by omega) + omega + exact odd_vertex_step H + (fun K hk => ih K.edgeFinset.card (by omega) (Option W) K rfl) ho x hx3 + +end +end ErdosGallai.Batch.Lovasz + +end +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/CycleDecomposition/BatchPathDeletion.lean b/lean/OAI/Combinatorics/CycleDecomposition/BatchPathDeletion.lean new file mode 100644 index 0000000000000000000000000000000000000000..29813e28574b1363640b811dac9d57b7736742fd --- /dev/null +++ b/lean/OAI/Combinatorics/CycleDecomposition/BatchPathDeletion.lean @@ -0,0 +1,735 @@ +import OAI.Combinatorics.CycleDecomposition.BatchLovasz + +namespace OAI + +universe cycleUniverse1 cycleUniverse2 cycleUniverse3 cycleUniverse4 cycleUniverse5 cycleUniverse6 cycleUniverse7 cycleUniverse8 cycleUniverse9 cycleUniverse10 cycleUniverse11 cycleUniverse12 cycleUniverse13 cycleUniverse14 cycleUniverse15 cycleUniverse16 cycleUniverse17 cycleUniverse18 cycleUniverse19 cycleUniverse20 cycleUniverse21 cycleUniverse22 cycleUniverse23 cycleUniverse24 cycleUniverse25 cycleUniverse26 cycleUniverse27 cycleUniverse28 cycleUniverse29 cycleUniverse30 cycleUniverse31 cycleUniverse32 cycleUniverse33 cycleUniverse34 cycleUniverse35 cycleUniverse36 cycleUniverse37 + +section +open Filter Asymptotics Real +open scoped Topology +noncomputable section +open MeasureTheory ProbabilityTheory Finset +section +namespace ErdosGallai.Batch +noncomputable section +attribute [local instance] Classical.propDecidable + +structure PositiveSimplePath {V : Type cycleUniverse1} (G : SimpleGraph V) where + start : V + finish : V + walk : G.Walk start finish + isPath : walk.IsPath + positive : 0 < walk.length + +lemma PositiveSimplePath.endpoints_ne {V : Type cycleUniverse2} {G : SimpleGraph V} + (P : PositiveSimplePath G) : P.start ≠ P.finish := by + intro he + have hz := P.isPath.nil_iff_eq.mpr he + have := hz.length_eq_zero + have := P.positive + omega + +theorem endpoint_path_count {V : Type cycleUniverse3} {I : Type cycleUniverse4} [Fintype V] [Fintype I] + {G : SimpleGraph V} (P : I → PositiveSimplePath G) + (hload : ∀ v : V, (Finset.univ.filter + (fun i => (P i).start = v ∨ (P i).finish = v)).card ≤ 2) : + Fintype.card I ≤ Fintype.card V := by + classical + have hsum : (∑ v : V, (Finset.univ.filter + (fun i => (P i).start = v ∨ (P i).finish = v)).card) = + 2 * Fintype.card I := by + simp only [Finset.card_eq_sum_ones, Finset.sum_filter] + rw [Finset.sum_comm] + have heq : ∀ i : I, + (∑ v : V, if (P i).start = v ∨ (P i).finish = v then 1 else 0) = 2 := by + intro i + have hf : (Finset.univ.filter fun v => + (P i).start = v ∨ (P i).finish = v) = {(P i).start, (P i).finish} := by + ext v; simp [eq_comm] + have hc : ({(P i).start, (P i).finish} : Finset V).card = 2 := by + simp [(P i).endpoints_ne] + rw [← hc, ← hf, Finset.card_eq_sum_ones, Finset.sum_filter] + simp only [heq, Finset.sum_const, Finset.card_univ, smul_eq_mul] + omega + have hbound := Finset.sum_le_sum (fun v (_ : v ∈ (Finset.univ : Finset V)) => hload v) + rw [hsum] at hbound + simp only [Finset.sum_const, Finset.card_univ, smul_eq_mul] at hbound + omega + +def EndpointPathPartition {V : Type cycleUniverse5} [Fintype V] (G : SimpleGraph V) : Prop := + ∃ (k : ℕ) (P : Fin k → PositiveSimplePath G), + Pairwise (fun i j => Disjoint (P i).walk.edgeSet (P j).walk.edgeSet) ∧ + (⋃ i, (P i).walk.edgeSet) = G.edgeSet ∧ + (∀ v : V, (Finset.univ.filter (fun i => (P i).start = v ∨ (P i).finish = v)).card ≤ 2) ∧ + k ≤ Fintype.card V + +def MissingEndpointTheorem : Prop := + ∀ (n : ℕ) (G : SimpleGraph (Fin n)), EndpointPathPartition G + +def PathOrCycleEdgeSet {V : Type cycleUniverse6} (G : SimpleGraph V) + (s : Set (Sym2 V)) : Prop := + (∃ (a b : V) (p : G.Walk a b), p.IsPath ∧ 0 < p.length ∧ s = p.edgeSet) ∨ + (∃ (a : V) (p : G.Walk a a), p.IsCycle ∧ s = p.edgeSet) + +def LovaszPathCyclePartition {V : Type cycleUniverse7} [Fintype V] (G : SimpleGraph V) : Prop := + ∃ (k : ℕ) (parts : Fin k → Set (Sym2 V)), + (∀ i, PathOrCycleEdgeSet G (parts i)) ∧ + Pairwise (fun i j => Disjoint (parts i) (parts j)) ∧ + (⋃ i, parts i) = G.edgeSet ∧ 2 * k ≤ Fintype.card V + +def MissingLovaszTheorem : Prop := + ∀ (n : ℕ) (G : SimpleGraph (Fin n)), LovaszPathCyclePartition G + +end +end ErdosGallai.Batch + +namespace ErdosGallai.Batch +noncomputable section +attribute [local instance] Classical.propDecidable +open scoped BigOperators + +def evenAugmentation {V : Type cycleUniverse8} [Fintype V] (G : SimpleGraph V) : + SimpleGraph (Option V) where + Adj x y := match x, y with + | some u, some v => G.Adj u v + | none, some v => Even (G.degree v) + | some u, none => Even (G.degree u) + | none, none => False + symm := ⟨by + intro x y h + cases x <;> cases y + · exact h + · exact h + · exact h + · exact G.adj_symm h⟩ + loopless := ⟨by + intro x h + cases x + · exact h + · exact G.irrefl h⟩ + +@[simp] theorem evenAugmentation_some_adj {V : Type cycleUniverse9} [Fintype V] + (G : SimpleGraph V) (u v : V) : + (evenAugmentation G).Adj (some u) (some v) ↔ G.Adj u v := Iff.rfl + +@[simp] theorem evenAugmentation_none_adj {V : Type cycleUniverse10} [Fintype V] + (G : SimpleGraph V) (v : V) : + (evenAugmentation G).Adj none (some v) ↔ Even (G.degree v) := Iff.rfl + +@[simp] theorem evenAugmentation_some_none {V : Type cycleUniverse11} [Fintype V] + (G : SimpleGraph V) (v : V) : + (evenAugmentation G).Adj (some v) none ↔ Even (G.degree v) := Iff.rfl + +theorem evenAugmentation_degree {V : Type cycleUniverse12} [Fintype V] + (G : SimpleGraph V) (v : V) : + (evenAugmentation G).degree (some v) = + G.degree v + if Even (G.degree v) then 1 else 0 := by + classical + rw [SimpleGraph.degree, SimpleGraph.neighborFinset_eq_filter, + Finset.card_eq_sum_ones, Finset.sum_filter, Fintype.sum_option] + simp only [evenAugmentation_some_adj, evenAugmentation_some_none] + have he : (∑ u : V, if G.Adj v u then 1 else 0) = G.degree v := by + rw [← G.card_neighborFinset_eq_degree v, G.neighborFinset_eq_filter, + Finset.card_eq_sum_ones, Finset.sum_filter] + rw [he] + omega + +theorem evenAugmentation_old_odd {V : Type cycleUniverse13} [Fintype V] + (G : SimpleGraph V) (v : V) : Odd ((evenAugmentation G).degree (some v)) := by + rw [evenAugmentation_degree] + by_cases h : Even (G.degree v) + · simp only [h, ↓reduceIte] + rcases h with ⟨k, hk⟩ + exact ⟨k, by omega⟩ + · simpa [h] using Nat.not_even_iff_odd.mp h + +end +end ErdosGallai.Batch + +namespace ErdosGallai.Batch +noncomputable section +open scoped BigOperators +attribute [local instance] Classical.propDecidable + +theorem trail_partition_degree_sum {V : Type cycleUniverse14} {I : Type cycleUniverse15} [Fintype V] [Fintype I] + (G : SimpleGraph V) {a b : I → V} (p : ∀ i, G.Walk (a i) (b i)) + (ht : ∀ i, (p i).IsTrail) + (hd : Pairwise fun i j => Disjoint (p i).edgeSet (p j).edgeSet) + (hc : (⋃ i, (p i).edgeSet) = G.edgeSet) (v : V) : + G.degree v = ∑ i, (p i).edges.countP (fun e => decide (v ∈ e)) := by + classical + have he : G.edgeFinset = Finset.univ.biUnion (fun i => (p i).edges.toFinset) := by + ext e + simp only [SimpleGraph.mem_edgeFinset, ← hc, Set.mem_iUnion, + Finset.mem_biUnion, Finset.mem_univ, List.mem_toFinset, true_and, + SimpleGraph.Walk.mem_edgeSet] + rw [← G.card_incidenceFinset_eq_degree v, G.incidenceFinset_eq_filter, he, + Finset.filter_biUnion] + rw [Finset.card_biUnion] + · apply Finset.sum_congr rfl + intro i _ + have hfilter : ((p i).edges.filter (fun e => decide (v ∈ e))).toFinset = + ((p i).edges.toFinset.filter (fun e => v ∈ e)) := by + simp [List.toFinset_filter] + rw [← hfilter, List.toFinset_card_of_nodup ((ht i).edges_nodup.filter _), + List.countP_eq_length_filter] + · intro i _ j _ hij + apply Finset.disjoint_left.mpr + intro e hei hej + exact Set.disjoint_left.mp (hd hij) + (by simpa using (Finset.mem_filter.mp hei).1) + (by simpa using (Finset.mem_filter.mp hej).1) + +theorem trail_partition_even_degree_iff {V : Type cycleUniverse16} {I : Type cycleUniverse17} [Fintype V] [Fintype I] + (G : SimpleGraph V) {a b : I → V} (p : ∀ i, G.Walk (a i) (b i)) + (ht : ∀ i, (p i).IsTrail) + (hd : Pairwise fun i j => Disjoint (p i).edgeSet (p j).edgeSet) + (hc : (⋃ i, (p i).edgeSet) = G.edgeSet) (v : V) : + Even (G.degree v) ↔ Even (Finset.univ.filter + (fun i => a i ≠ b i ∧ (v = a i ∨ v = b i))).card := by + classical + rw [trail_partition_degree_sum G p ht hd hc v, Finset.even_sum_iff_even_card_odd] + have he : (Finset.univ.filter (fun i => Odd ((p i).edges.countP + (fun e => decide (v ∈ e))))) = (Finset.univ.filter + (fun i => a i ≠ b i ∧ (v = a i ∨ v = b i))) := by + ext i + simp only [Finset.mem_filter, Finset.mem_univ, true_and, + ← Nat.not_even_iff_odd, (ht i).even_countP_edges_iff] + tauto + rw [he] + +private theorem odd_load_one {V : Type cycleUniverse18} [DecidableEq V] + (S : Finset V) (f : V → ℕ) (ho : ∀ v ∈ S, Odd (f v)) + (hs : ∑ v ∈ S, f v ≤ S.card + 1) : ∀ v ∈ S, f v = 1 := by + intro v hv + by_contra hn + have hv3 : 3 ≤ f v := by rcases ho v hv with ⟨k, hk⟩; omega + have hlow : ∑ x ∈ S, (1 + if x = v then 2 else 0) ≤ ∑ x ∈ S, f x := by + apply Finset.sum_le_sum + intro x hx + by_cases he : x = v + · subst x; simpa using hv3 + · simp only [he, ↓reduceIte, add_zero] + rcases ho x hx with ⟨k, hk⟩ + omega + have heq : (∑ x ∈ S, (1 + if x = v then 2 else 0)) = S.card + 2 := by + simp [Finset.sum_add_distrib, hv] + omega + +theorem tight_odd_trail_partition {V : Type cycleUniverse19} {I : Type cycleUniverse20} [Fintype V] [Fintype I] + (G : SimpleGraph V) (S : Finset V) {a b : I → V} + (p : ∀ i, G.Walk (a i) (b i)) (ht : ∀ i, (p i).IsTrail) + (hd : Pairwise fun i j => Disjoint (p i).edgeSet (p j).edgeSet) + (hc : (⋃ i, (p i).edgeSet) = G.edgeSet) + (ho : ∀ v ∈ S, Odd (G.degree v)) + (hsize : 2 * Fintype.card I ≤ S.card + 1) : + (∀ i, a i ≠ b i) ∧ (∀ v ∈ S, + (Finset.univ.filter (fun i => a i ≠ b i ∧ (v = a i ∨ v = b i))).card = 1) := by + classical + let load := fun v : V => (Finset.univ.filter + (fun i => a i ≠ b i ∧ (v = a i ∨ v = b i))).card + let openParts := Finset.univ.filter (fun i => a i ≠ b i) + have hlodd : ∀ v ∈ S, Odd (load v) := by + intro v hv + rw [← Nat.not_even_iff_odd, ← trail_partition_even_degree_iff G p ht hd hc v] + exact (Nat.not_even_iff_odd.mpr (ho v hv)) + have htotal : (∑ v : V, load v) = 2 * openParts.card := by + dsimp [load] + simp only [Finset.card_eq_sum_ones, Finset.sum_filter] + rw [Finset.sum_comm] + have he : ∀ i : I, (∑ v : V, if a i ≠ b i ∧ (v = a i ∨ v = b i) then 1 else 0) = + if a i ≠ b i then 2 else 0 := by + intro i + by_cases h : a i = b i + · simp [h] + · have hf : (Finset.univ.filter (fun v => a i ≠ b i ∧ (v = a i ∨ v = b i))) = + {a i, b i} := by ext v; simp [h] + have hcard : ({a i, b i} : Finset V).card = 2 := by simp [h] + rw [ite_eq_left h, ← hcard, ← hf, Finset.card_eq_sum_ones, Finset.sum_filter] + simp_rw [he] + rw [← Finset.sum_filter] + simp only [Finset.sum_const, smul_eq_mul, mul_one] + change openParts.card * 2 = 2 * openParts.card + omega + have hsub : (∑ v ∈ S, load v) ≤ ∑ v : V, load v := + Finset.sum_le_sum_of_subset (Finset.subset_univ S) + have hlow : S.card ≤ ∑ v ∈ S, load v := by + simpa using Finset.sum_le_sum (s := S) (f := fun _ => 1) (g := load) + (fun v hv => by rcases hlodd v hv with ⟨k, hk⟩; omega) + have hcount : openParts.card ≤ Fintype.card I := Finset.card_le_univ _ + have hpoint := odd_load_one S load hlodd (by omega) + refine ⟨?_, hpoint⟩ + intro i hi + have hproper : openParts ⊂ Finset.univ := by + apply Finset.ssubset_iff_subset_ne.mpr + refine ⟨Finset.subset_univ _, ?_⟩ + intro heq + have hh : i ∈ openParts := heq.symm ▸ Finset.mem_univ i + simp [openParts, hi] at hh + have hlt := Finset.card_lt_card hproper + simp only [Finset.card_univ] at hlt + omega + +end +end ErdosGallai.Batch + +namespace ErdosGallai.Batch +noncomputable section + +private theorem path_tail_delete_start {V : Type cycleUniverse21} {G : SimpleGraph V} + {a b : V} (p : G.Walk a b) (hp : p.IsPath) : + p.tail.edgeSet = {e | e ∈ p.edgeSet ∧ a ∉ e} := by + cases p with + | nil => ext e; simp + | @cons a c b h q => + have ha : a ∉ q.support := (List.nodup_cons.mp hp.support_nodup).1 + have hnot : ∀ e ∈ q.edgeSet, a ∉ e := by + intro e he hae + exact ha (SimpleGraph.Walk.mem_support_iff_exists_mem_edges.mpr + (Or.inr ⟨e, he, hae⟩)) + ext e + simp only [Set.mem_ofPred_eq, SimpleGraph.Walk.mem_edgeSet, + SimpleGraph.Walk.edges_tail, SimpleGraph.Walk.edges_cons, List.tail_cons, List.mem_cons] + constructor + · intro he + exact ⟨Or.inr he, hnot e he⟩ + · rintro ⟨he | he, hn⟩ + · subst e; exact (hn (by simp)).elim + · exact he + +private theorem path_dropLast_delete_end {V : Type cycleUniverse22} {G : SimpleGraph V} + {a b : V} (p : G.Walk a b) (hp : p.IsPath) : + p.dropLast.edgeSet = {e | e ∈ p.edgeSet ∧ b ∉ e} := by + have he : p.dropLast.edgeSet = p.reverse.tail.edgeSet := by + calc + _ = p.dropLast.reverse.edgeSet := (SimpleGraph.Walk.edgeSet_reverse _).symm + _ = _ := by rw [SimpleGraph.Walk.reverse_dropLast, SimpleGraph.Walk.edgeSet_copy] + rw [he, path_tail_delete_start p.reverse hp.reverse, SimpleGraph.Walk.edgeSet_reverse] + +private theorem positive_avoids_of_no_incidence {V : Type cycleUniverse23} {G : SimpleGraph V} + {a b v : V} (p : G.Walk a b) (hpos : 0 < p.length) + (he : ∀ e ∈ p.edgeSet, v ∉ e) : v ∉ p.support := by + have hn : ¬p.Nil := by intro hz; have := hz.length_eq_zero; omega + intro hv + obtain ⟨e, he', hve⟩ := SimpleGraph.Walk.mem_support_iff_exists_mem_edges_of_not_nil hn |>.mp hv + exact he e he' hve + +theorem delete_vertex_from_path {V : Type cycleUniverse24} [DecidableEq V] {G : SimpleGraph V} + {a b v : V} (p : G.Walk a b) (hp : p.IsPath) (hv : v ∈ p.support) : + let q := (p.takeUntil v hv).dropLast + let r := (p.dropUntil v hv).tail + q.IsPath ∧ r.IsPath ∧ Disjoint q.edgeSet r.edgeSet ∧ + q.edgeSet ∪ r.edgeSet = {e | e ∈ p.edgeSet ∧ v ∉ e} ∧ + (0 < q.length → v ∉ q.support) ∧ + (0 < r.length → v ∉ r.support) ∧ + (0 < q.length → G.Adj (p.takeUntil v hv).penultimate v) ∧ + (0 < r.length → G.Adj v (p.dropUntil v hv).snd) := by + dsimp only + let t := p.takeUntil v hv + let d := p.dropUntil v hv + have ht : t.IsPath := hp.takeUntil hv + have hd : d.IsPath := hp.dropUntil hv + have heq : t.append d = p := p.take_spec hv + have hqe : t.dropLast.edgeSet = {e | e ∈ t.edgeSet ∧ v ∉ e} := + path_dropLast_delete_end t ht + have hre : d.tail.edgeSet = {e | e ∈ d.edgeSet ∧ v ∉ e} := + path_tail_delete_start d hd + have hdis : Disjoint t.edgeSet d.edgeSet := by + have hn := hp.isTrail.edges_nodup + rw [← heq, SimpleGraph.Walk.edges_append] at hn + have hn' := (List.nodup_append.mp hn).2.2 + apply Set.disjoint_left.mpr + intro e het hed + exact hn' e het e hed rfl + refine ⟨ht.dropLast, hd.tail, ?_, ?_, ?_, ?_, ?_, ?_⟩ + · rw [hqe, hre] + exact hdis.mono (fun _ h => h.1) (fun _ h => h.1) + · have he : t.edgeSet ∪ d.edgeSet = p.edgeSet := by + rw [← SimpleGraph.Walk.edgeSet_append, heq] + rw [hqe, hre] + ext e + simp only [Set.mem_union, Set.mem_ofPred_eq] + rw [← he] + simp only [Set.mem_union] + tauto + · intro hpos + apply positive_avoids_of_no_incidence _ hpos + intro e he + exact (hqe ▸ he).2 + · intro hpos + apply positive_avoids_of_no_incidence _ hpos + intro e he + exact (hre ▸ he).2 + · intro hpos + apply t.adj_penultimate + intro hn + have hz := hn.length_eq_zero + change 0 < t.dropLast.length at hpos + rw [SimpleGraph.Walk.length_dropLast, hz] at hpos + omega + · intro hpos + apply d.adj_snd + intro hn + have hz := hn.length_eq_zero + change 0 < d.tail.length at hpos + rw [SimpleGraph.Walk.length_tail, hz] at hpos + omega + +theorem delete_vertex_boundary_edges {V : Type cycleUniverse25} [DecidableEq V] + {G : SimpleGraph V} {a b v : V} (p : G.Walk a b) (hv : v ∈ p.support) : + (0 < (p.takeUntil v hv).dropLast.length → + s((p.takeUntil v hv).penultimate, v) ∈ p.edgeSet) ∧ + (0 < (p.dropUntil v hv).tail.length → + s(v, (p.dropUntil v hv).snd) ∈ p.edgeSet) := by + let t := p.takeUntil v hv + let d := p.dropUntil v hv + have heq : t.append d = p := p.take_spec hv + constructor + · intro hpos + have hn : ¬ t.Nil := by + intro hz + change 0 < t.dropLast.length at hpos + rw [SimpleGraph.Walk.length_dropLast, hz.length_eq_zero] at hpos + omega + have hm := t.mk_penultimate_end_mem_edges hn + have hed : t.edgeSet ∪ d.edgeSet = p.edgeSet := by + rw [← SimpleGraph.Walk.edgeSet_append, heq] + exact hed ▸ Or.inl hm + · intro hpos + have hn : ¬ d.Nil := by + intro hz + change 0 < d.tail.length at hpos + rw [SimpleGraph.Walk.length_tail, hz.length_eq_zero] at hpos + omega + have hm := d.mk_start_snd_mem_edges hn + have hed : t.edgeSet ∪ d.edgeSet = p.edgeSet := by + rw [← SimpleGraph.Walk.edgeSet_append, heq] + exact hed ▸ Or.inr hm + +theorem delete_vertex_new_ends_ne {V : Type cycleUniverse26} [DecidableEq V] + {G : SimpleGraph V} {a b v : V} (p : G.Walk a b) (hp : p.IsPath) + (hv : v ∈ p.support) + (hl : 0 < (p.takeUntil v hv).dropLast.length) + (hr : 0 < (p.dropUntil v hv).tail.length) : + (p.takeUntil v hv).penultimate ≠ (p.dropUntil v hv).snd := by + let t := p.takeUntil v hv + let d := p.dropUntil v hv + have heq : t.append d = p := p.take_spec hv + have htn : ¬t.Nil := by + intro hz + change 0 < t.dropLast.length at hl + rw [SimpleGraph.Walk.length_dropLast, hz.length_eq_zero] at hl + omega + have hdn : ¬d.Nil := by + intro hz + change 0 < d.tail.length at hr + rw [SimpleGraph.Walk.length_tail, hz.length_eq_zero] at hr + omega + have hdj := hp.isTrail.edges_nodup + rw [← heq, SimpleGraph.Walk.edges_append] at hdj + have hdis := (List.nodup_append.mp hdj).2.2 + intro hsame + have ha := t.mk_penultimate_end_mem_edges htn + have hb := d.mk_start_snd_mem_edges hdn + apply hdis _ ha _ hb + + rw [show t.penultimate = d.snd from hsame, Sym2.eq_swap] + +theorem delete_vertex_new_endpoint_load {V : Type cycleUniverse27} {I : Type cycleUniverse28} [DecidableEq V] [Fintype I] + {G : SimpleGraph V} {a b : I → V} {v : V} + (p : ∀ i, G.Walk (a i) (b i)) (hp : ∀ i, (p i).IsPath) + (hv : ∀ i, v ∈ (p i).support) + (hd : Pairwise fun i j => Disjoint (p i).edgeSet (p j).edgeSet) (x : V) : + let live := fun z : I × Bool => if z.2 then + 0 < ((p z.1).takeUntil v (hv z.1)).dropLast.length else + 0 < ((p z.1).dropUntil v (hv z.1)).tail.length + let newEnd := fun z : I × Bool => if z.2 then + ((p z.1).takeUntil v (hv z.1)).penultimate else + ((p z.1).dropUntil v (hv z.1)).snd + (Finset.univ.filter fun z => live z ∧ newEnd z = x).card ≤ 1 := by + classical + dsimp only + apply Finset.card_le_one.mpr + intro z hz w hw + obtain ⟨i, bi⟩ := z + obtain ⟨j, bj⟩ := w + have hi := (Finset.mem_filter.mp hz).2 + have hj := (Finset.mem_filter.mp hw).2 + have hei : s(v,x) ∈ (p i).edgeSet := by + cases bi + · have hx : ((p i).dropUntil v (hv i)).snd = x := hi.2 + simpa only [hx] using (delete_vertex_boundary_edges (p i) (hv i)).2 hi.1 + · have hx : ((p i).takeUntil v (hv i)).penultimate = x := hi.2 + have he := (delete_vertex_boundary_edges (p i) (hv i)).1 hi.1 + simpa only [hx, Sym2.eq_swap] using he + have hej : s(v,x) ∈ (p j).edgeSet := by + cases bj + · have hx : ((p j).dropUntil v (hv j)).snd = x := hj.2 + simpa only [hx] using (delete_vertex_boundary_edges (p j) (hv j)).2 hj.1 + · have hx : ((p j).takeUntil v (hv j)).penultimate = x := hj.2 + have he := (delete_vertex_boundary_edges (p j) (hv j)).1 hj.1 + simpa only [hx, Sym2.eq_swap] using he + have hij : i = j := by + by_contra hn + exact Set.disjoint_left.mp (hd hn) hei hej + subst j + congr 1 + cases bi <;> cases bj + · rfl + · have he := delete_vertex_new_ends_ne (p i) (hp i) (hv i) hj.1 hi.1 + exact (he (hj.2.trans hi.2.symm)).elim + · have he := delete_vertex_new_ends_ne (p i) (hp i) (hv i) hi.1 hj.1 + exact (he (hi.2.trans hj.2.symm)).elim + · rfl + +structure SimplePathPiece {V : Type cycleUniverse29} (G : SimpleGraph V) where + start : V + finish : V + walk : G.Walk start finish + isPath : walk.IsPath + +namespace SimplePathPiece +attribute [local instance] Classical.propDecidable +variable {V : Type cycleUniverse30} {I : Type cycleUniverse31} [Fintype I] [DecidableEq V] {G : SimpleGraph V} + +def Avoiding (p : I → SimplePathPiece G) (v : V) := {i : I // v ∉ (p i).walk.support} +def Meeting (p : I → SimplePathPiece G) (v : V) := {i : I // v ∈ (p i).walk.support} +def DeleteIndex (p : I → SimplePathPiece G) (v : V) := + Avoiding p v ⊕ (Meeting p v × Bool) + +instance (p : I → SimplePathPiece G) (v : V) : Fintype (Avoiding p v) := by + classical + exact inferInstanceAs (Fintype {i : I // v ∉ (p i).walk.support}) +instance (p : I → SimplePathPiece G) (v : V) : Fintype (Meeting p v) := by + classical + exact inferInstanceAs (Fintype {i : I // v ∈ (p i).walk.support}) +instance (p : I → SimplePathPiece G) (v : V) : Fintype (DeleteIndex p v) := + inferInstanceAs (Fintype (Avoiding p v ⊕ (Meeting p v × Bool))) + +def deleted (p : I → SimplePathPiece G) (v : V) : DeleteIndex p v → SimplePathPiece G + | .inl i => p i.val + | .inr (i,true) => ⟨_,_,((p i.val).walk.takeUntil v i.property).dropLast, + ((p i.val).isPath.takeUntil i.property).dropLast⟩ + | .inr (i,false) => ⟨_,_,((p i.val).walk.dropUntil v i.property).tail, + ((p i.val).isPath.dropUntil i.property).tail⟩ + +def parent (p : I → SimplePathPiece G) (v : V) : DeleteIndex p v → I + | .inl i => i.val + | .inr (i,_) => i.val + +def oldEnd (p : I → SimplePathPiece G) (v x : V) : DeleteIndex p v → Prop + | .inl i => (p i.val).start = x ∨ (p i.val).finish = x + | .inr (i,true) => (p i.val).start = x + | .inr (i,false) => (p i.val).finish = x + +def newEnd (p : I → SimplePathPiece G) (v x : V) : DeleteIndex p v → Prop + | .inl _ => False + | .inr (i,true) => ((p i.val).walk.takeUntil v i.property).penultimate = x + | .inr (i,false) => ((p i.val).walk.dropUntil v i.property).snd = x + +lemma deleted_ends {V : Type cycleUniverse32} {I : Type cycleUniverse33} [_contextInstance2 : Fintype I] [_contextInstance3 : DecidableEq V] {G : SimpleGraph V} (p : I → SimplePathPiece G) (v x : V) (j : DeleteIndex p v) : + (deleted p v j).start = x ∨ (deleted p v j).finish = x ↔ + oldEnd p v x j ∨ newEnd p v x j := by + rcases j with i | ⟨i,b⟩ + · simp [deleted, oldEnd, newEnd] + · cases b <;> simp [deleted, oldEnd, newEnd, or_comm] + +lemma deleted_edges_subset {V : Type cycleUniverse34} {I : Type cycleUniverse35} [_contextInstance2 : Fintype I] [_contextInstance3 : DecidableEq V] {G : SimpleGraph V} (p : I → SimplePathPiece G) (v : V) (j : DeleteIndex p v) : + (deleted p v j).walk.edgeSet ⊆ (p (parent p v j)).walk.edgeSet := by + rcases j with i | ⟨i,b⟩ + · exact Set.Subset.rfl + · have h := (delete_vertex_from_path (p i.val).walk (p i.val).isPath i.property).2.2.2.1 + cases b + · intro e he + exact (show e ∈ {e | e ∈ (p i.val).walk.edgeSet ∧ v ∉ e} from + h ▸ Or.inr he).1 + · intro e he + exact (show e ∈ {e | e ∈ (p i.val).walk.edgeSet ∧ v ∉ e} from + h ▸ Or.inl he).1 + +lemma deleted_positive_avoids {V : Type cycleUniverse36} {I : Type cycleUniverse37} [_contextInstance2 : Fintype I] [_contextInstance3 : DecidableEq V] {G : SimpleGraph V} (p : I → SimplePathPiece G) (v : V) (j : DeleteIndex p v) + (hpos : 0 < (deleted p v j).walk.length) : v ∉ (deleted p v j).walk.support := by + rcases j with i | ⟨i,b⟩ + · exact i.property + · have h := delete_vertex_from_path (p i.val).walk (p i.val).isPath i.property + cases b + · exact h.2.2.2.2.2.1 hpos + · exact h.2.2.2.2.1 hpos + +lemma deleted_disjoint (p : I → SimplePathPiece G) (v : V) + (hd : Pairwise fun i j => Disjoint (p i).walk.edgeSet (p j).walk.edgeSet) : + Pairwise fun j k => Disjoint (deleted p v j).walk.edgeSet (deleted p v k).walk.edgeSet := by + intro j k hjk + by_cases he : parent p v j = parent p v k + · rcases j with i | ⟨i,b⟩ <;> rcases k with l | ⟨l,c⟩ + · exact (hjk (congrArg Sum.inl (Subtype.ext he))).elim + · exact (i.property (show v ∈ (p i.val).walk.support from (show i.val = l.val from he).symm ▸ l.property)).elim + · exact (l.property (show v ∈ (p l.val).walk.support from (show i.val = l.val from he) ▸ i.property)).elim + · have hil : i = l := Subtype.ext he + subst l + cases b <;> cases c + · exact (hjk rfl).elim + · exact (delete_vertex_from_path (p i.val).walk (p i.val).isPath i.property).2.2.1.symm + · exact (delete_vertex_from_path (p i.val).walk (p i.val).isPath i.property).2.2.1 + · exact (hjk rfl).elim + · exact (hd he).mono (deleted_edges_subset p v j) (deleted_edges_subset p v k) + +lemma deleted_old_load (p : I → SimplePathPiece G) (v x : V) + (hne : ∀ i, (p i).start ≠ (p i).finish) + (hload : (Finset.univ.filter fun i => (p i).start = x ∨ (p i).finish = x).card ≤ 1) : + (Finset.univ.filter fun j : DeleteIndex p v => oldEnd p v x j).card ≤ 1 := by + classical + apply Finset.card_le_one.mpr + intro j hj k hk + have hjp : (p (parent p v j)).start = x ∨ (p (parent p v j)).finish = x := by + have h := (Finset.mem_filter.mp hj).2 + rcases j with i | ⟨i,b⟩ + · exact h + · cases b + · exact Or.inr h + · exact Or.inl h + have hkp : (p (parent p v k)).start = x ∨ (p (parent p v k)).finish = x := by + have h := (Finset.mem_filter.mp hk).2 + rcases k with i | ⟨i,b⟩ + · exact h + · cases b + · exact Or.inr h + · exact Or.inl h + have he := Finset.card_le_one.mp hload (parent p v j) + (Finset.mem_filter.mpr ⟨Finset.mem_univ _,hjp⟩) (parent p v k) + (Finset.mem_filter.mpr ⟨Finset.mem_univ _,hkp⟩) + have hj' := (Finset.mem_filter.mp hj).2 + have hk' := (Finset.mem_filter.mp hk).2 + rcases j with i | ⟨i,b⟩ <;> rcases k with l | ⟨l,c⟩ + · exact congrArg Sum.inl (Subtype.ext he) + · exact (i.property (show v ∈ (p i.val).walk.support from (show i.val = l.val from he).symm ▸ l.property)).elim + · exact (l.property (show v ∈ (p l.val).walk.support from (show i.val = l.val from he) ▸ i.property)).elim + · have hil : i = l := Subtype.ext he + subst l + cases b <;> cases c + · rfl + · exact (hne _ (hk'.trans hj'.symm)).elim + · exact (hne _ (hj'.trans hk'.symm)).elim + · rfl + +lemma deleted_new_load (p : I → SimplePathPiece G) (v x : V) + (hd : Pairwise fun i j => Disjoint (p i).walk.edgeSet (p j).walk.edgeSet) : + (Finset.univ.filter fun j : DeleteIndex p v => + 0 < (deleted p v j).walk.length ∧ newEnd p v x j).card ≤ 1 := by + classical + have h := delete_vertex_new_endpoint_load + (fun i : Meeting p v => (p i.val).walk) (fun i => (p i.val).isPath) + (fun i => i.property) + (fun i j hij => hd (fun he => hij (Subtype.ext he))) x + apply Finset.card_le_one.mpr + intro j hj k hk + have hj' := (Finset.mem_filter.mp hj).2 + have hk' := (Finset.mem_filter.mp hk).2 + rcases j with i | ⟨i,b⟩ + · exact False.elim hj'.2 + rcases k with l | ⟨l,c⟩ + · exact False.elim hk'.2 + apply congrArg Sum.inr + apply Finset.card_le_one.mp h + · apply Finset.mem_filter.mpr + refine ⟨Finset.mem_univ _,?_⟩ + cases b <;> exact hj' + · apply Finset.mem_filter.mpr + refine ⟨Finset.mem_univ _,?_⟩ + cases c <;> exact hk' + +theorem deleted_endpoint_load (p : I → SimplePathPiece G) (v x : V) + (hne : ∀ i, (p i).start ≠ (p i).finish) + (hd : Pairwise fun i j => Disjoint (p i).walk.edgeSet (p j).walk.edgeSet) + (hload : (Finset.univ.filter fun i => (p i).start = x ∨ (p i).finish = x).card ≤ 1) : + (Finset.univ.filter fun j : DeleteIndex p v => 0 < (deleted p v j).walk.length ∧ + ((deleted p v j).start = x ∨ (deleted p v j).finish = x)).card ≤ 2 := by + classical + let A := Finset.univ.filter (fun j : DeleteIndex p v => oldEnd p v x j) + let B := Finset.univ.filter (fun j : DeleteIndex p v => + 0 < (deleted p v j).walk.length ∧ newEnd p v x j) + have hsub : (Finset.univ.filter fun j : DeleteIndex p v => + 0 < (deleted p v j).walk.length ∧ + ((deleted p v j).start = x ∨ (deleted p v j).finish = x)) ⊆ A ∪ B := by + intro j hj + obtain ⟨hpos,hend⟩ := (Finset.mem_filter.mp hj).2 + rcases (deleted_ends p v x j).mp hend with ho | hn + · exact Finset.mem_union_left _ (Finset.mem_filter.mpr ⟨Finset.mem_univ _,ho⟩) + · exact Finset.mem_union_right _ (Finset.mem_filter.mpr ⟨Finset.mem_univ _,hpos,hn⟩) + have ha := deleted_old_load p v x hne hload + have hb := deleted_new_load p v x hd + have hc := (Finset.card_le_card hsub).trans (Finset.card_union_le A B) + dsimp [A,B] at hc + omega + +theorem deleted_union (p : I → SimplePathPiece G) (v : V) : + (⋃ j : DeleteIndex p v, (deleted p v j).walk.edgeSet) = + {e | (∃ i, e ∈ (p i).walk.edgeSet) ∧ v ∉ e} := by + classical + ext e + constructor + · intro he + obtain ⟨j,hj⟩ := Set.mem_iUnion.mp he + refine ⟨⟨parent p v j, deleted_edges_subset p v j hj⟩,?_⟩ + rcases j with i | ⟨i,b⟩ + · intro hv + exact i.property (SimpleGraph.Walk.mem_support_iff_exists_mem_edges.mpr + (Or.inr ⟨e,hj,hv⟩)) + · have h := (delete_vertex_from_path (p i.val).walk (p i.val).isPath i.property).2.2.2.1 + cases b + · exact (show e ∈ {e | e ∈ (p i.val).walk.edgeSet ∧ v ∉ e} from + h ▸ Or.inr hj).2 + · exact (show e ∈ {e | e ∈ (p i.val).walk.edgeSet ∧ v ∉ e} from + h ▸ Or.inl hj).2 + · rintro ⟨⟨i,hi⟩,hv⟩ + by_cases hs : v ∈ (p i).walk.support + · have h := (delete_vertex_from_path (p i).walk (p i).isPath hs).2.2.2.1 + have he : e ∈ ((p i).walk.takeUntil v hs).dropLast.edgeSet ∪ + ((p i).walk.dropUntil v hs).tail.edgeSet := h.symm ▸ ⟨hi,hv⟩ + rcases he with hl | hr + · exact Set.mem_iUnion.mpr ⟨Sum.inr (⟨i,hs⟩,true),hl⟩ + · exact Set.mem_iUnion.mpr ⟨Sum.inr (⟨i,hs⟩,false),hr⟩ + · exact Set.mem_iUnion.mpr ⟨Sum.inl ⟨i,hs⟩,hi⟩ + +theorem deleted_positive_union (p : I → SimplePathPiece G) (v : V) : + (⋃ j : {j : DeleteIndex p v // 0 < (deleted p v j).walk.length}, + (deleted p v j.val).walk.edgeSet) = + {e | (∃ i, e ∈ (p i).walk.edgeSet) ∧ v ∉ e} := by + rw [← deleted_union p v] + ext e + constructor + · intro he + obtain ⟨j,hj⟩ := Set.mem_iUnion.mp he + exact Set.mem_iUnion.mpr ⟨j.val,hj⟩ + · intro he + obtain ⟨j,hj⟩ := Set.mem_iUnion.mp he + have hp : 0 < (deleted p v j).walk.length := by + by_contra hn + have hz : (deleted p v j).walk.length = 0 := by omega + have hn' := SimpleGraph.Walk.length_eq_zero_iff.mp hz + have he' := SimpleGraph.Walk.edges_eq_nil.mpr hn' + have hmem : e ∈ (deleted p v j).walk.edges := hj + exact List.not_mem_nil (he' ▸ hmem) + exact Set.mem_iUnion.mpr ⟨⟨j,hp⟩,hj⟩ + +def deletedInduced (p : I → SimplePathPiece G) (v : V) + (j : {j : DeleteIndex p v // 0 < (deleted p v j).walk.length}) : + SimplePathPiece (G.induce {x | x ≠ v}) := by + let q := deleted p v j.val + have havo : ∀ x ∈ q.walk.support, x ∈ ({x | x ≠ v} : Set V) := by + intro x hx he + subst x + exact deleted_positive_avoids p v j.val j.property hx + exact ⟨_,_, q.walk.induce _ havo, by + apply SimpleGraph.Walk.IsPath.of_map (f := (SimpleGraph.Embedding.induce _).toHom) + simpa using q.isPath⟩ + +end SimplePathPiece + +end +end ErdosGallai.Batch +end +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/CycleDecomposition/BatchPreparation.lean b/lean/OAI/Combinatorics/CycleDecomposition/BatchPreparation.lean new file mode 100644 index 0000000000000000000000000000000000000000..e62afbb34687e0576f16fe9535e1c3fa4049e3e7 --- /dev/null +++ b/lean/OAI/Combinatorics/CycleDecomposition/BatchPreparation.lean @@ -0,0 +1,1034 @@ +import OAI.Combinatorics.CycleDecomposition.CollisionEstimates + +namespace OAI + +universe cycleUniverse1 cycleUniverse2 cycleUniverse3 cycleUniverse4 cycleUniverse5 cycleUniverse6 cycleUniverse7 cycleUniverse8 cycleUniverse9 cycleUniverse10 cycleUniverse11 cycleUniverse12 cycleUniverse13 cycleUniverse14 cycleUniverse15 cycleUniverse16 cycleUniverse17 cycleUniverse18 cycleUniverse19 cycleUniverse20 cycleUniverse21 cycleUniverse22 cycleUniverse23 cycleUniverse24 cycleUniverse25 cycleUniverse26 cycleUniverse27 cycleUniverse28 cycleUniverse29 cycleUniverse30 cycleUniverse31 cycleUniverse32 cycleUniverse33 cycleUniverse34 + +section +open Filter Asymptotics Real +open scoped Topology +noncomputable section +open MeasureTheory ProbabilityTheory Finset +section +namespace ErdosGallai.Batch +open Finset +noncomputable section +attribute [local instance] Classical.propDecidable +variable {V : Type cycleUniverse1} {I : Type cycleUniverse2} [Fintype V] [Fintype I] (X : I → Finset V) + (hd : Pairwise (fun i j => Disjoint (X i) (X j))) + +lemma crossGraph_card (G : SimpleGraph V) (S T : Finset V) (hst : Disjoint S T) : + (crossGraph G S T).edgeFinset.card = betweenCount G S T := by + classical + have hdeg (v : V) : (crossGraph G S T).degree v = + (if v ∈ S then neighborsIn G T v else 0) + + (if v ∈ T then neighborsIn G S v else 0) := by + rw [← SimpleGraph.card_neighborFinset_eq_degree] + have hfin : (crossGraph G S T).neighborFinset v = + (if v ∈ S then T.filter (G.Adj v) else ∅) ∪ + (if v ∈ T then S.filter (G.Adj v) else ∅) := by + ext x + simp only [SimpleGraph.mem_neighborFinset,Finset.mem_union] + change (G.Adj v x ∧ ((v ∈ S ∧ x ∈ T) ∨ (v ∈ T ∧ x ∈ S))) ↔ _ + split_ifs <;> simp_all only [Finset.mem_filter,Finset.notMem_empty] <;> tauto + rw [hfin,Finset.card_union_of_disjoint] + · split_ifs <;> simp [neighborsIn] + · split_ifs with hs ht ht + · exact False.elim (Finset.disjoint_left.mp hst hs ht) + all_goals simp + have hh := (crossGraph G S T).sum_degrees_eq_twice_card_edges + simp_rw [hdeg] at hh + rw [Finset.sum_add_distrib] at hh + have hS : (∑ v, if v ∈ S then neighborsIn G T v else 0) = betweenCount G S T := by + simp [betweenCount] + have hT : (∑ v, if v ∈ T then neighborsIn G S v else 0) = betweenCount G T S := by + simp [betweenCount] + rw [hS,hT,betweenCount_comm G T S] at hh + omega + +def edgePairEvent (p : ∀ i, PairingSpace (X i)) (q : Finset (Sym2 V)) : Prop := + (q.image (Sym2.map (familyProject X hd p))).card = 1 + +lemma edgePairEvent_pair (p : ∀ i, PairingSpace (X i)) (e f : Sym2 V) : + edgePairEvent X hd p {e,f} ↔ + Sym2.map (familyProject X hd p) e = Sym2.map (familyProject X hd p) f := by + classical + by_cases h : Sym2.map (familyProject X hd p) e = Sym2.map (familyProject X hd p) f + · simp [edgePairEvent,h] + · simp [edgePairEvent,h,Finset.card_pair h] + +def DisjointEdgePair (q : Finset (Sym2 V)) : Prop := + ∃ u v x y : V, u ≠ v ∧ x ≠ y ∧ u ≠ x ∧ u ≠ y ∧ v ≠ x ∧ v ≠ y ∧ + q = {s(u,v),s(x,y)} + +def pairErrors (H : SimpleGraph V) (p : ∀ i, PairingSpace (X i)) := + ((H.edgeFinset.powersetCard 2).filter DisjointEdgePair).filter (edgePairEvent X hd p) + +def loopErrors (G : SimpleGraph V) (p : ∀ i, PairingSpace (X i)) (i : I) := + (internalGraph G (X i)).edgeFinset.filter + (fun e => (Sym2.map (familyProject X hd p) e).IsDiag) + +lemma loopErrors_average (G : SimpleGraph V) (i : I) (hm : 2 ≤ (X i).card) : + finiteAverage (fun p : ∀ j, PairingSpace (X j) => ((loopErrors X hd G p i).card : ℝ)) ≤ + ((internalGraph G (X i)).edgeFinset.card : ℝ) / ((X i).card-1:ℝ) := by + classical + change finiteAverage (fun p => (((internalGraph G (X i)).edgeFinset.filter _).card:ℝ)) ≤ _ + have hav := finiteAverage_filter_card (s:=(internalGraph G (X i)).edgeFinset) + (P:=fun (p : ∀ j, PairingSpace (X j)) e => (Sym2.map (familyProject X hd p) e).IsDiag) + calc + _ = ∑ e ∈ (internalGraph G (X i)).edgeFinset, + finiteAverage (fun p : ∀ j, PairingSpace (X j) => + if (Sym2.map (familyProject X hd p) e).IsDiag then 1 else 0) := by + convert hav using 1 <;> congr 4 + · funext p + congr 2 + ext e + simp only [Finset.mem_filter] + · funext e + congr 1 + funext p + split_ifs <;> rfl + _ ≤ _ := by + calc + _ ≤ ∑ _e ∈ (internalGraph G (X i)).edgeFinset, 1 / ((X i).card-1:ℝ) := by + apply Finset.sum_le_sum + intro e he + obtain ⟨u,v⟩ := e + obtain ⟨huv,hu,hv⟩ := mem_internalGraph.mp he + have heq (p : ∀ j, PairingSpace (X j)) : + (Sym2.map (familyProject X hd p) s(u,v)).IsDiag ↔ vertexPairEvent X p {u,v} := + (loop_iff_familyPaired X hd p huv.ne).trans (vertexPairEvent_pair X p u v huv.ne).symm + simp_rw [heq] + exact vertexPairEvent_average X hd i {u,v} (by intro z hz; rcases Finset.mem_insert.mp hz with rfl | hz; exact hu; exact Finset.mem_singleton.mp hz ▸ hv) + (by simp [huv.ne]) hm + _ = _ := by simp [div_eq_mul_inv] + +lemma internal_pairErrors_average (G : SimpleGraph V) (i : I) (hm : 4 ≤ (X i).card) : + finiteAverage (fun p : ∀ j, PairingSpace (X j) => + ((pairErrors X hd (internalGraph G (X i)) p).card : ℝ)) ≤ + ((internalGraph G (X i)).edgeFinset.card.choose 2 : ℝ) * + (2 / (((X i).card-1:ℝ)*((X i).card-3:ℝ))) := by + classical + change finiteAverage (fun p => (((((internalGraph G (X i)).edgeFinset.powersetCard 2).filter DisjointEdgePair).filter _).card:ℝ)) ≤ _ + rw [finiteAverage_filter_card] + calc + _ ≤ ∑ _q ∈ ((internalGraph G (X i)).edgeFinset.powersetCard 2).filter DisjointEdgePair, + 2 / (((X i).card-1:ℝ)*((X i).card-3:ℝ)) := by + apply Finset.sum_le_sum + intro q hq + obtain ⟨hq,hdis⟩ := Finset.mem_filter.mp hq + obtain ⟨u,v,x,y,huv,hxy,hux,huy,hvx,hvy,rfl⟩ := hdis + have hsub := (Finset.mem_powersetCard.mp hq).1 + obtain ⟨he,hu,hv⟩ := mem_internalGraph.mp (hsub (by simp : s(u,v) ∈ ({s(u,v),s(x,y)}:Finset (Sym2 V)))) + obtain ⟨hf,hx,hy⟩ := mem_internalGraph.mp (hsub (by simp : s(x,y) ∈ ({s(u,v),s(x,y)}:Finset (Sym2 V)))) + simp_rw [edgePairEvent_pair] + exact internal_collision_average X hd i hm ⟨u,hu⟩ ⟨v,hv⟩ ⟨x,hx⟩ ⟨y,hy⟩ + (fun h => huv (congrArg Subtype.val h)) (fun h => hux (congrArg Subtype.val h)) + (fun h => huy (congrArg Subtype.val h)) (fun h => hvx (congrArg Subtype.val h)) + (fun h => hvy (congrArg Subtype.val h)) (fun h => hxy (congrArg Subtype.val h)) + _ ≤ _ := by + simp only [Finset.sum_const, nsmul_eq_mul] + apply mul_le_mul_of_nonneg_right + · exact_mod_cast (Finset.card_filter_le _ _).trans_eq (Finset.card_powersetCard _ _) + · have : (4:ℝ) ≤ (X i).card := by exact_mod_cast hm + exact div_nonneg (by norm_num) (mul_nonneg (by linarith) (by linarith)) + +lemma cross_pair_orientation {V : Type cycleUniverse3} {I : Type cycleUniverse4} [_contextInstance2 : Fintype V] [_contextInstance3 : Fintype I] (X : I → Finset V) (G : SimpleGraph V) (i j : I) + (q : Finset (Sym2 V)) (hq : q ⊆ (crossGraph G (X i) (X j)).edgeFinset) + (hdis : DisjointEdgePair q) : + ∃ (u x : X i) (v y : X j), u ≠ x ∧ v ≠ y ∧ q = {s((u:V),(v:V)),s((x:V),(y:V))} := by + classical + obtain ⟨u,v,x,y,huv,hxy,hux,huy,hvx,hvy,rfl⟩ := hdis + have he := SimpleGraph.mem_edgeFinset.mp (hq (by simp : s(u,v) ∈ ({s(u,v),s(x,y)}:Finset (Sym2 V)))) + have hf := SimpleGraph.mem_edgeFinset.mp (hq (by simp : s(x,y) ∈ ({s(u,v),s(x,y)}:Finset (Sym2 V)))) + rcases he.2 with ⟨hui,hvj⟩ | ⟨huj,hvi⟩ <;> rcases hf.2 with ⟨hxi,hyj⟩ | ⟨hxj,hyi⟩ + · exact ⟨⟨u,hui⟩,⟨x,hxi⟩,⟨v,hvj⟩,⟨y,hyj⟩, + (fun h => hux (congrArg Subtype.val h)),(fun h => hvy (congrArg Subtype.val h)),rfl⟩ + · refine ⟨⟨u,hui⟩,⟨y,hyi⟩,⟨v,hvj⟩,⟨x,hxj⟩, + (fun h => huy (congrArg Subtype.val h)),(fun h => hvx (congrArg Subtype.val h)),?_⟩ + rw [Sym2.eq_swap (a:=y) (b:=x)] + · refine ⟨⟨v,hvi⟩,⟨x,hxi⟩,⟨u,huj⟩,⟨y,hyj⟩, + (fun h => hvx (congrArg Subtype.val h)),(fun h => huy (congrArg Subtype.val h)),?_⟩ + rw [Sym2.eq_swap (a:=v) (b:=u)] + · refine ⟨⟨v,hvi⟩,⟨y,hyi⟩,⟨u,huj⟩,⟨x,hxj⟩, + (fun h => hvy (congrArg Subtype.val h)),(fun h => hux (congrArg Subtype.val h)),?_⟩ + rw [Sym2.eq_swap (a:=v) (b:=u),Sym2.eq_swap (a:=y) (b:=x)] + +lemma cross_pairErrors_average (G : SimpleGraph V) (i j : I) (hij : i ≠ j) + (hi : 2 ≤ (X i).card) (hj : 2 ≤ (X j).card) : + finiteAverage (fun p : ∀ k, PairingSpace (X k) => + ((pairErrors X hd (crossGraph G (X i) (X j)) p).card : ℝ)) ≤ + ((betweenCount G (X i) (X j)).choose 2 : ℝ) * + (1 / (((X i).card-1:ℝ)*((X j).card-1:ℝ))) := by + classical + change finiteAverage (fun p => (((((crossGraph G (X i) (X j)).edgeFinset.powersetCard 2).filter DisjointEdgePair).filter _).card:ℝ)) ≤ _ + rw [finiteAverage_filter_card] + calc + _ ≤ ∑ _q ∈ ((crossGraph G (X i) (X j)).edgeFinset.powersetCard 2).filter DisjointEdgePair, + 1 / (((X i).card-1:ℝ)*((X j).card-1:ℝ)) := by + apply Finset.sum_le_sum + intro q hq + obtain ⟨hq,hdis⟩ := Finset.mem_filter.mp hq + obtain ⟨u,x,v,y,hux,hvy,rfl⟩ := cross_pair_orientation X G i j q + (Finset.mem_powersetCard.mp hq).1 hdis + simp_rw [edgePairEvent_pair] + exact cross_collision_average X hd i j hij hi hj u x v y hux hvy + _ ≤ _ := by + rw [← crossGraph_card G (X i) (X j) (hd hij)] + simp only [Finset.sum_const, nsmul_eq_mul] + apply mul_le_mul_of_nonneg_right + · exact_mod_cast (Finset.card_filter_le _ _).trans_eq (Finset.card_powersetCard _ _) + · have : (2:ℝ) ≤ (X i).card := by exact_mod_cast hi + have : (2:ℝ) ≤ (X j).card := by exact_mod_cast hj + exact div_nonneg (by norm_num) (mul_nonneg (by linarith) (by linarith)) + +end +end ErdosGallai.Batch + +namespace ErdosGallai.Batch +open Finset +noncomputable section +attribute [local instance] Classical.propDecidable +variable {V : Type cycleUniverse5} {I : Type cycleUniverse6} [Fintype V] [Fintype I] (X : I → Finset V) + (hd : Pairwise (fun i j => Disjoint (X i) (X j))) + +lemma mem_pairErrors (H : SimpleGraph V) (p : ∀ i, PairingSpace (X i)) + (q : Finset (Sym2 V)) : + q ∈ pairErrors X hd H p ↔ q ⊆ H.edgeFinset ∧ q.card = 2 ∧ + DisjointEdgePair q ∧ edgePairEvent X hd p q := by + classical + simp [pairErrors,and_assoc] + +lemma mem_crossGraph {G : SimpleGraph V} {S T : Finset V} {u v : V} : + s(u,v) ∈ (crossGraph G S T).edgeFinset ↔ + G.Adj u v ∧ ((u ∈ S ∧ v ∈ T) ∨ (u ∈ T ∧ v ∈ S)) := by + rw [SimpleGraph.mem_edgeFinset] + rfl + +lemma two_paired_edges_placement (G : SimpleGraph V) (p : ∀ i, PairingSpace (X i)) + {u v x y : V} (he : G.Adj u v) (hf : G.Adj x y) + (hux : familyPaired X p u x) (hvy : familyPaired X p v y) : + (∃ i, {s(u,v),s(x,y)} ⊆ (internalGraph G (X i)).edgeFinset) ∨ + (∃ i j, i ≠ j ∧ {s(u,v),s(x,y)} ⊆ (crossGraph G (X i) (X j)).edgeFinset) := by + classical + rcases paired_fibers_placement X p hux hvy with ⟨i,hu,hv,hx,hy⟩ | ⟨i,j,hij,hu,hx,hv,hy⟩ + · left + refine ⟨i,?_⟩ + intro e he' + rcases Finset.mem_insert.mp he' with rfl | he' + · exact mem_internalGraph.mpr ⟨he,hu,hv⟩ + · exact Finset.mem_singleton.mp he' ▸ mem_internalGraph.mpr ⟨hf,hx,hy⟩ + · right + refine ⟨i,j,hij,?_⟩ + intro e he' + rcases Finset.mem_insert.mp he' with rfl | he' + · exact mem_crossGraph.mpr ⟨he,Or.inl ⟨hu,hv⟩⟩ + · exact Finset.mem_singleton.mp he' ▸ mem_crossGraph.mpr ⟨hf,Or.inl ⟨hx,hy⟩⟩ + +def wedgeCover (G : SimpleGraph V) (p : ∀ i, PairingSpace (X i)) : Finset (Finset (Sym2 V)) := + Finset.univ.biUnion fun i => Finset.univ.biUnion fun v => + (wedgeErrors X G p i v).image (fun q => q.image (fun u => s(v,u))) + +def internalCover (G : SimpleGraph V) (p : ∀ i, PairingSpace (X i)) : Finset (Finset (Sym2 V)) := + Finset.univ.biUnion fun i => pairErrors X hd (internalGraph G (X i)) p + +def crossCover (G : SimpleGraph V) (p : ∀ i, PairingSpace (X i)) : Finset (Finset (Sym2 V)) := + Finset.univ.biUnion fun i => (Finset.univ.erase i).biUnion fun j => + pairErrors X hd (crossGraph G (X i) (X j)) p + +lemma all_collisions_covered (G : SimpleGraph V) (p : ∀ i, PairingSpace (X i)) : + CollisionPairs (Sym2.map (familyProject X hd p)) G.edgeFinset ⊆ + wedgeCover X G p ∪ internalCover X hd G p ∪ crossCover X hd G p := by + classical + intro q hq + obtain ⟨hsub,hcard,himage⟩ := (mem_collisionPairs _ _ _).mp hq + obtain ⟨e,f,hef,rfl⟩ := Finset.card_eq_two.mp hcard + have he := hsub (by simp : e ∈ ({e,f}:Finset (Sym2 V))) + have hf := hsub (by simp : f ∈ ({e,f}:Finset (Sym2 V))) + have hev : edgePairEvent X hd p {e,f} := himage + have heq := (edgePairEvent_pair X hd p e f).mp hev + rcases distinct_edge_cases G he hf hef with hshared | hdis + · obtain ⟨v,u,w,hvu,hvw,huw,rfl,rfl⟩ := hshared + have hpair := shared_endpoint_collision X hd p huw heq + obtain ⟨i,hu,hw,hpair'⟩ := hpair + apply Finset.mem_union_left + apply Finset.mem_union_left + apply Finset.mem_biUnion.mpr + refine ⟨i,Finset.mem_univ _,Finset.mem_biUnion.mpr ⟨v,Finset.mem_univ _,?_⟩⟩ + apply Finset.mem_image.mpr + refine ⟨{u,w},?_,by simp⟩ + apply Finset.mem_filter.mpr + refine ⟨Finset.mem_powersetCard.mpr ⟨?_,by simp [huw]⟩,?_⟩ + · intro z hz + rcases Finset.mem_insert.mp hz with rfl | hz + · exact Finset.mem_filter.mpr ⟨hu,SimpleGraph.mem_edgeFinset.mp he⟩ + · exact Finset.mem_singleton.mp hz ▸ Finset.mem_filter.mpr ⟨hw,SimpleGraph.mem_edgeFinset.mp hf⟩ + · exact (vertexPairEvent_pair X p u w huw).mpr ⟨i,hu,hw,hpair'⟩ + · obtain ⟨u,v,x,y,huv,hxy,hux,huy,hvx,hvy,rfl,rfl⟩ := hdis + have hdis : DisjointEdgePair ({s(u,v),s(x,y)}:Finset (Sym2 V)) := + ⟨u,v,x,y,huv,hxy,hux,huy,hvx,hvy,rfl⟩ + have hplace : (∃ i, {s(u,v),s(x,y)} ⊆ (internalGraph G (X i)).edgeFinset) ∨ + (∃ i j, i ≠ j ∧ {s(u,v),s(x,y)} ⊆ (crossGraph G (X i) (X j)).edgeFinset) := by + rcases four_endpoint_collision X hd p hux huy hvx hvy heq with hh | hh + · exact two_paired_edges_placement X G p (SimpleGraph.mem_edgeFinset.mp he) + (SimpleGraph.mem_edgeFinset.mp hf) hh.1 hh.2 + · have hh' := two_paired_edges_placement X G p (SimpleGraph.mem_edgeFinset.mp he) + (SimpleGraph.mem_edgeFinset.mp hf).symm hh.1 hh.2 + simpa only [Sym2.eq_swap (a:=y) (b:=x)] using hh' + rcases hplace with ⟨i,hi⟩ | ⟨i,j,hij,hij'⟩ + · apply Finset.mem_union_left + apply Finset.mem_union_right + exact Finset.mem_biUnion.mpr ⟨i,Finset.mem_univ _, + (mem_pairErrors X hd _ p _).mpr ⟨hi,by simp [hef],hdis,hev⟩⟩ + · apply Finset.mem_union_right + apply Finset.mem_biUnion.mpr + refine ⟨i,Finset.mem_univ _,Finset.mem_biUnion.mpr ⟨j,by simp [hij.symm],?_⟩⟩ + exact (mem_pairErrors X hd _ p _).mpr ⟨hij',by simp [hef],hdis,hev⟩ + +lemma all_loops_covered (G : SimpleGraph V) (p : ∀ i, PairingSpace (X i)) : + G.edgeFinset.filter (fun e => (Sym2.map (familyProject X hd p) e).IsDiag) ⊆ + Finset.univ.biUnion (fun i => loopErrors X hd G p i) := by + classical + intro e he + obtain ⟨he,hloop⟩ := Finset.mem_filter.mp he + obtain ⟨u,v⟩ := e + have huv := SimpleGraph.mem_edgeFinset.mp he + obtain ⟨i,hu,hv,hp⟩ := (loop_iff_familyPaired X hd p huv.ne).mp hloop + exact Finset.mem_biUnion.mpr ⟨i,Finset.mem_univ _, + Finset.mem_filter.mpr ⟨mem_internalGraph.mpr ⟨huv,hu,hv⟩,hloop⟩⟩ + +def foldErrorBudget (G : SimpleGraph V) (p : ∀ i, PairingSpace (X i)) : ℕ := + ∑ i, ((loopErrors X hd G p i).card + + (∑ v, (wedgeErrors X G p i v).card) + + (pairErrors X hd (internalGraph G (X i)) p).card + + ∑ j ∈ Finset.univ.erase i, (pairErrors X hd (crossGraph G (X i) (X j)) p).card) + +lemma quotientDefect_le_budget (G : SimpleGraph V) (p : ∀ i, PairingSpace (X i)) : + quotientDefect G (familyProject X hd p) ≤ foldErrorBudget X hd G p := by + classical + have hl := (Finset.card_le_card (all_loops_covered X hd G p)).trans + (Finset.card_biUnion_le) + have hc := (Finset.card_le_card (all_collisions_covered X hd G p)).trans + (Finset.card_union_le _ _) + have hw : (wedgeCover X G p).card ≤ ∑ i, ∑ v, (wedgeErrors X G p i v).card := by + apply Finset.card_biUnion_le.trans + apply Finset.sum_le_sum + intro i hi + apply Finset.card_biUnion_le.trans + exact Finset.sum_le_sum fun v hv => Finset.card_image_le + have hi : (internalCover X hd G p).card ≤ + ∑ i, (pairErrors X hd (internalGraph G (X i)) p).card := Finset.card_biUnion_le + have hx : (crossCover X hd G p).card ≤ ∑ i, ∑ j ∈ Finset.univ.erase i, + (pairErrors X hd (crossGraph G (X i) (X j)) p).card := by + apply Finset.card_biUnion_le.trans + exact Finset.sum_le_sum fun i hi => Finset.card_biUnion_le + have hc' := Finset.card_le_card (collisionPairs_mono (Sym2.map (familyProject X hd p)) + (Finset.filter_subset (fun e => ¬(Sym2.map (familyProject X hd p) e).IsDiag) G.edgeFinset)) + have hunion := Finset.card_union_le (wedgeCover X G p) (internalCover X hd G p) + unfold quotientDefect foldErrorBudget + simp only [Finset.sum_add_distrib] + omega + +end +end ErdosGallai.Batch + +namespace ErdosGallai.Batch +open Finset +noncomputable section +attribute [local instance] Classical.propDecidable +variable {V : Type cycleUniverse7} {I : Type cycleUniverse8} [Fintype V] [Fintype I] (X : I → Finset V) + (hd : Pairwise (fun i j => Disjoint (X i) (X j))) + +lemma fold_ratio_one (m : ℝ) (hm : 8 ≤ m) : m/(m-1) ≤ 8/7 := by + apply (div_le_iff₀ (show 0 < m-1 by linarith)).mpr + linarith +lemma fold_ratio_three (m : ℝ) (hm : 8 ≤ m) : m/(m-3) ≤ 8/5 := by + apply (div_le_iff₀ (show 0 < m-3 by linarith)).mpr + linarith +lemma choose_two_real_bound (n : ℕ) : (n.choose 2 : ℝ) ≤ (n:ℝ)^2/2 := by + rw [Nat.cast_choose_two] + have := Nat.cast_nonneg (α:=ℝ) n + nlinarith + +lemma first_error_numeric (m a e : ℝ) (hm : 8 ≤ m) (he : 2*e ≤ a*m) : + e/(m-1) + (a*(a-1)*m/2)/(m-1) ≤ (4/7)*a^2 := by + have hp : 0 < m-1 := by linarith + calc + _ = (e+a*(a-1)*m/2)/(m-1) := by ring + _ ≤ (a^2*m/2)/(m-1) := (div_le_div_iff_of_pos_right hp).mpr (by nlinarith) + _ = (a^2/2)*(m/(m-1)) := by ring + _ ≤ (a^2/2)*(8/7) := mul_le_mul_of_nonneg_left (fold_ratio_one m hm) (by positivity) + _ = _ := by ring + +lemma internal_error_numeric (m a : ℝ) (e : ℕ) (hm : 8 ≤ m) (ha : 0 ≤ a) + (he : 2*(e:ℝ) ≤ a*m) : + (e.choose 2 : ℝ)*(2/((m-1)*(m-3))) ≤ (16/35)*a^2 := by + have hp : 0 < m-1 := by linarith + have hp' : 0 < m-3 := by linarith + have he2 : (e:ℝ)^2 ≤ (a*m/2)^2 := by + apply sq_le_sq₀ (Nat.cast_nonneg _) (by positivity) |>.mpr + linarith + calc + _ ≤ ((e:ℝ)^2/2)*(2/((m-1)*(m-3))) := mul_le_mul_of_nonneg_right + (choose_two_real_bound e) (by positivity) + _ = (e:ℝ)^2/((m-1)*(m-3)) := by ring + _ ≤ (a*m/2)^2/((m-1)*(m-3)) := div_le_div_of_nonneg_right he2 (by positivity) + _ = (a^2/4)*((m/(m-1))*(m/(m-3))) := by field_simp ; ring + _ ≤ (a^2/4)*((8/7)*(8/5)) := mul_le_mul_of_nonneg_left + (mul_le_mul (fold_ratio_one m hm) (fold_ratio_three m hm) + (by positivity) (by norm_num)) (by positivity) + _ = _ := by ring + +lemma cross_error_numeric (m n : ℝ) (e : ℕ) (hm : 8 ≤ m) (hn : 8 ≤ n) : + (e.choose 2 : ℝ)*(1/((m-1)*(n-1))) ≤ (32/49)*((e:ℝ)^2/(m*n)) := by + have hp : 0 < m-1 := by linarith + have hq : 0 < n-1 := by linarith + have hm0 : 0 < m := by linarith + have hn0 : 0 < n := by linarith + calc + _ ≤ ((e:ℝ)^2/2)*(1/((m-1)*(n-1))) := mul_le_mul_of_nonneg_right + (choose_two_real_bound e) (by positivity) + _ = ((e:ℝ)^2/(2*m*n))*((m/(m-1))*(n/(n-1))) := by field_simp + _ ≤ ((e:ℝ)^2/(2*m*n))*((8/7)*(8/7)) := mul_le_mul_of_nonneg_left + (mul_le_mul (fold_ratio_one m hm) (fold_ratio_one n hn) + (by positivity) (by norm_num)) (by positivity) + _ = _ := by ring + +lemma first_errors_average (G : SimpleGraph V) (i : I) (a : ℝ) (ha : 1 ≤ a) + (hm : 8 ≤ (X i).card) + (hdegree : ∀ x ∈ X i, (G.degree x : ℝ) ≤ a) + (hneighbor : ∀ v, (neighborsIn G (X i) v : ℝ) ≤ a) : + finiteAverage (fun p : ∀ j, PairingSpace (X j) => + ((loopErrors X hd G p i).card : ℝ) + ∑ v, ((wedgeErrors X G p i v).card:ℝ)) ≤ + (4/7)*a^2 := by + classical + rw [finiteAverage_add,finiteAverage_sum] + have hp : 0 < ((X i).card:ℝ)-1 := by + have : (8:ℝ) ≤ (X i).card := by exact_mod_cast hm + linarith + calc + _ ≤ ((internalGraph G (X i)).edgeFinset.card:ℝ)/((X i).card-1:ℝ) + + ∑ v, ((neighborsIn G (X i) v).choose 2 : ℝ)/((X i).card-1:ℝ) := + add_le_add (loopErrors_average X hd G i (by omega)) + (Finset.sum_le_sum fun v _ => wedgeErrors_average X hd G i v (by omega)) + _ = ((internalGraph G (X i)).edgeFinset.card:ℝ)/((X i).card-1:ℝ) + + (∑ v, ((neighborsIn G (X i) v).choose 2 : ℝ))/((X i).card-1:ℝ) := by rw [Finset.sum_div] + _ ≤ ((internalGraph G (X i)).edgeFinset.card:ℝ)/((X i).card-1:ℝ) + + (a*(a-1)*(X i).card/2)/((X i).card-1:ℝ) := by + apply add_le_add_right + exact div_le_div_of_nonneg_right (by exact_mod_cast wedge_count_bound G (X i) a ha hdegree hneighbor) hp.le + _ ≤ _ := first_error_numeric _ _ _ (by exact_mod_cast hm) (internal_edge_bound G (X i) a hdegree) + +lemma internal_errors_average (G : SimpleGraph V) (i : I) (a : ℝ) (ha : 0 ≤ a) + (hm : 8 ≤ (X i).card) (hdegree : ∀ x ∈ X i, (G.degree x : ℝ) ≤ a) : + finiteAverage (fun p : ∀ j, PairingSpace (X j) => + ((pairErrors X hd (internalGraph G (X i)) p).card : ℝ)) ≤ (16/35)*a^2 := + (internal_pairErrors_average X hd G i (by omega)).trans + (internal_error_numeric _ _ _ (by exact_mod_cast hm) ha (internal_edge_bound G (X i) a hdegree)) + +lemma cross_errors_average (G : SimpleGraph V) (i : I) (a : ℝ) (ha : 0 ≤ a) + (hm : ∀ i, 8 ≤ (X i).card) + (hdegree : ∀ i x, x ∈ X i → (G.degree x : ℝ) ≤ a) : + finiteAverage (fun p : ∀ k, PairingSpace (X k) => + ∑ j ∈ Finset.univ.erase i, ((pairErrors X hd (crossGraph G (X i) (X j)) p).card : ℝ)) ≤ + (32/49)*a^2 := by + classical + rw [finiteAverage_sum] + calc + _ ≤ ∑ j ∈ Finset.univ.erase i, (32/49)*((betweenCount G (X i) (X j):ℝ)^2 / + ((X i).card*(X j).card)) := by + apply Finset.sum_le_sum + intro j hj + have hij := (Finset.mem_erase.mp hj).1.symm + exact (cross_pairErrors_average X hd G i j hij (by have := hm i; omega) (by have := hm j; omega)).trans + (cross_error_numeric _ _ _ (by exact_mod_cast hm i) (by exact_mod_cast hm j)) + _ ≤ ∑ j, (32/49)*((betweenCount G (X i) (X j):ℝ)^2 / + ((X i).card*(X j).card)) := by + apply Finset.sum_le_sum_of_subset_of_nonneg (Finset.erase_subset _ _) + intro j hj hj' + positivity + _ = (32/49)*∑ j, ((betweenCount G (X i) (X j):ℝ)^2 / + ((X i).card*(X j).card)) := by rw [Finset.mul_sum] + _ ≤ _ := mul_le_mul_of_nonneg_left (cross_error_row G X hd a ha (by intro i; have := hm i; omega) hdegree i) (by norm_num) + +end +end ErdosGallai.Batch + +namespace ErdosGallai.Batch +noncomputable section +open Finset +attribute [local instance] Classical.propDecidable +variable {V : Type cycleUniverse9} {I : Type cycleUniverse10} [Fintype V] [Fintype I] + +theorem folding_average_bound (G : SimpleGraph V) (X : I → Finset V) + (hd : Pairwise (fun i j => Disjoint (X i) (X j))) (a : ℝ) (ha : 1 ≤ a) + (hm : ∀ i, 8 ≤ (X i).card) (hma : ∀ i, a^2 ≤ (X i).card) + (hdegree : ∀ i x, x ∈ X i → (G.degree x : ℝ) ≤ a) + (hneighbor : ∀ i v, (neighborsIn G (X i) v : ℝ) ≤ a) : + finiteAverage (fun p : ∀ i, PairingSpace (X i) => + (foldErrorBudget X hd G p : ℝ)) ≤ 2 * ∑ i, ((X i).card : ℝ) := by + classical + simp only [foldErrorBudget,Nat.cast_sum,Nat.cast_add] + rw [finiteAverage_sum,Finset.mul_sum] + apply Finset.sum_le_sum + intro i hi + rw [finiteAverage_add,finiteAverage_add] + have hfirst := first_errors_average X hd G i a ha (hm i) (hdegree i) (hneighbor i) + have hint := internal_errors_average X hd G i a (by linarith) (hm i) (hdegree i) + have hcross := cross_errors_average X hd G i a (by linarith) hm hdegree + calc + _ ≤ (4/7)*a^2 + (16/35)*a^2 + (32/49)*a^2 := + add_le_add (add_le_add hfirst hint) hcross + _ ≤ 2 * ((X i).card : ℝ) := by nlinarith [hma i,sq_nonneg a] + +theorem pair_folding (G : SimpleGraph V) (X : I → Finset V) + (hd : Pairwise (fun i j => Disjoint (X i) (X j))) (a : ℝ) (ha : 1 ≤ a) + (hm : ∀ i, 8 ≤ (X i).card) (hma : ∀ i, a^2 ≤ (X i).card) + (hdegree : ∀ i x, x ∈ X i → (G.degree x : ℝ) ≤ a) + (hneighbor : ∀ i v, (neighborsIn G (X i) v : ℝ) ≤ a) : + ∃ (p : ∀ i, PairingSpace (X i)) (retained : Finset (Sym2 V)) + (Q : SimpleGraph (FamilyQuotient X p)), + retained ⊆ G.edgeFinset ∧ + (G.edgeFinset \ retained).card ≤ 2 * ∑ i, (X i).card ∧ + Q.edgeSet = ((retained.image (Sym2.map (familyProject X hd p)) : + Finset (Sym2 (FamilyQuotient X p))) : Set (Sym2 (FamilyQuotient X p))) ∧ + (∀ e ∈ Q.edgeSet, ∃! f, f ∈ retained ∧ Sym2.map (familyProject X hd p) f = e) ∧ + Fintype.card (FamilyQuotient X p) = Fintype.card V - ∑ i, (X i).card / 2 := by + classical + obtain ⟨p,hp⟩ := exists_le_finiteAverage (fun p : ∀ i, PairingSpace (X i) => + (foldErrorBudget X hd G p : ℝ)) + have hcostR := hp.trans (folding_average_bound G X hd a ha hm hma hdegree hneighbor) + have hcost : foldErrorBudget X hd G p ≤ 2 * ∑ i, (X i).card := by exact_mod_cast hcostR + obtain ⟨retained,Q,hsub,herr,hQ,hrep⟩ := simple_quotient_representatives G (familyProject X hd p) + exact ⟨p,retained,Q,hsub,herr.trans ((quotientDefect_le_budget X hd G p).trans hcost), + hQ,hrep,family_quotient_order X hd p⟩ + +end +end ErdosGallai.Batch + +namespace ErdosGallai.Batch +open Finset +noncomputable section +attribute [local instance] Classical.propDecidable +variable {V : Type cycleUniverse11} [Fintype V] (G : SimpleGraph V) + +def heavyNeighbors (X : Finset V) (a : ℝ) : Finset V := + Finset.univ.filter (fun v => a < (neighborsIn G X v : ℝ)) + +lemma mem_heavyNeighbors (X : Finset V) (a : ℝ) (v : V) : + v ∈ heavyNeighbors G X a ↔ a < (neighborsIn G X v : ℝ) := by simp [heavyNeighbors] + +lemma heavyNeighbors_disjoint_active (X Y : Finset V) (a : ℝ) + (hY : ∀ v ∈ Y, (G.degree v : ℝ) ≤ a) : + Disjoint (heavyNeighbors G X a) Y := by + apply Finset.disjoint_left.mpr + intro v hv hy + have h₁ := (mem_heavyNeighbors G X a v).mp hv + have h₂ : (neighborsIn G X v : ℝ) ≤ G.degree v := by + exact_mod_cast neighborsIn_le_degree G X v + exact (not_lt_of_ge (h₂.trans (hY v hy))) h₁ + +lemma heavyNeighbors_card_le (X : Finset V) (a : ℝ) (ha : 0 < a) + (hX : ∀ v ∈ X, (G.degree v : ℝ) ≤ a) : + (heavyNeighbors G X a).card ≤ X.card := by + have hsum : a * (heavyNeighbors G X a).card ≤ + ∑ v ∈ heavyNeighbors G X a, (neighborsIn G X v : ℝ) := by + calc + _ = ∑ _v ∈ heavyNeighbors G X a, a := by simp [mul_comm] + _ ≤ _ := Finset.sum_le_sum fun v hv => + ((mem_heavyNeighbors G X a v).mp hv).le + have hsub : (∑ v ∈ heavyNeighbors G X a, (neighborsIn G X v : ℝ)) ≤ + ∑ v, (neighborsIn G X v : ℝ) := + Finset.sum_le_sum_of_subset_of_nonneg (Finset.subset_univ _) (by intros; positivity) + have htotal : (∑ v, (neighborsIn G X v : ℝ)) ≤ a * X.card := by + rw [← Nat.cast_sum, sum_incidence_to_set G X, Nat.cast_sum] + simpa [mul_comm] using Finset.sum_le_sum (s := X) (fun v hv => hX v hv) + have hh := hsum.trans (hsub.trans htotal) + have := (mul_le_mul_iff_right₀ ha).mp hh + exact_mod_cast this + +variable {I : Type cycleUniverse12} [Fintype I] (X : I → Finset V) + +def heavyDesignated (a : ℝ) (i : I) : SimpleGraph V := + crossGraph G (X i) (heavyNeighbors G (X i) a) + +lemma heavyDesignated_le {V : Type cycleUniverse13} [_contextInstance1 : Fintype V] (G : SimpleGraph V) {I : Type cycleUniverse14} [_contextInstance4 : Fintype I] (X : I → Finset V) (a : ℝ) (i : I) : heavyDesignated G X a i ≤ G := + fun _ _ h => h.1 + +theorem heavyDesignated_pairwise {V : Type cycleUniverse15} [_contextInstance1 : Fintype V] (G : SimpleGraph V) {I : Type cycleUniverse16} [_contextInstance4 : Fintype I] (X : I → Finset V) (a : ℝ) + (hd : Pairwise (fun i j => Disjoint (X i) (X j))) + (hdegree : ∀ i v, v ∈ X i → (G.degree v : ℝ) ≤ a) : + Pairwise (fun i j => Disjoint (heavyDesignated G X a i).edgeSet + (heavyDesignated G X a j).edgeSet) := by + intro i j hij + apply Set.disjoint_left.mpr + intro e hei hej + induction e using Sym2.ind with + | _ u v => + change G.Adj u v ∧ ((u ∈ X i ∧ v ∈ heavyNeighbors G (X i) a) ∨ + (u ∈ heavyNeighbors G (X i) a ∧ v ∈ X i)) at hei + change G.Adj u v ∧ ((u ∈ X j ∧ v ∈ heavyNeighbors G (X j) a) ∨ + (u ∈ heavyNeighbors G (X j) a ∧ v ∈ X j)) at hej + rcases hei.2 with hi | hi <;> rcases hej.2 with hj | hj + · exact Finset.disjoint_left.mp (hd hij) hi.1 hj.1 + · exact Finset.disjoint_left.mp + (heavyNeighbors_disjoint_active G (X j) (X i) a (hdegree i)) hj.1 hi.1 + · exact Finset.disjoint_left.mp + (heavyNeighbors_disjoint_active G (X i) (X j) a (hdegree j)) hi.1 hj.1 + · exact Finset.disjoint_left.mp (hd hij) hi.2 hj.2 + +def trimHeavyGraph (a : ℝ) : SimpleGraph V where + Adj u v := G.Adj u v ∧ ∀ i, ¬ (heavyDesignated G X a i).Adj u v + symm := ⟨fun _ _ h => ⟨h.1.symm,fun i hi => h.2 i hi.symm⟩⟩ + loopless := ⟨fun _ h => G.irrefl h.1⟩ + +lemma trimHeavyGraph_le {V : Type cycleUniverse17} [_contextInstance1 : Fintype V] (G : SimpleGraph V) {I : Type cycleUniverse18} [_contextInstance4 : Fintype I] (X : I → Finset V) (a : ℝ) : trimHeavyGraph G X a ≤ G := fun _ _ h => h.1 + +theorem trimHeavyGraph_neighbors {V : Type cycleUniverse19} [_contextInstance1 : Fintype V] (G : SimpleGraph V) {I : Type cycleUniverse20} [_contextInstance4 : Fintype I] (X : I → Finset V) (a : ℝ) (ha : 0 ≤ a) (i : I) (v : V) : + (neighborsIn (trimHeavyGraph G X a) (X i) v : ℝ) ≤ a := by + by_cases hv : v ∈ heavyNeighbors G (X i) a + · have he : (X i).filter ((trimHeavyGraph G X a).Adj v) = ∅ := by + apply Finset.eq_empty_iff_forall_notMem.mpr + intro u hu + obtain ⟨hui,hvu⟩ := Finset.mem_filter.mp hu + exact hvu.2 i ⟨hvu.1,Or.inr ⟨hv,hui⟩⟩ + simpa [neighborsIn, he] using ha + · have hnon : (neighborsIn G (X i) v : ℝ) ≤ a := + le_of_not_gt (fun hh => hv ((mem_heavyNeighbors G (X i) a v).mpr hh)) + apply le_trans _ hnon + exact_mod_cast Finset.card_le_card (show + (X i).filter ((trimHeavyGraph G X a).Adj v) ⊆ (X i).filter (G.Adj v) from + fun u hu => Finset.mem_filter.mpr ⟨(Finset.mem_filter.mp hu).1, + (Finset.mem_filter.mp hu).2.1⟩) + +theorem trimHeavyGraph_degree (a : ℝ) (v : V) : + (trimHeavyGraph G X a).degree v ≤ G.degree v := by + classical + exact SimpleGraph.degree_le_of_le (trimHeavyGraph_le G X a) + +theorem trimHeavyGraph_ledger (a : ℝ) : + (trimHeavyGraph G X a).edgeSet ∪ + (⋃ i, (heavyDesignated G X a i).edgeSet) = G.edgeSet ∧ + Disjoint (trimHeavyGraph G X a).edgeSet + (⋃ i, (heavyDesignated G X a i).edgeSet) := by + constructor + · ext e + induction e using Sym2.ind with + | _ u v => + simp only [Set.mem_union, Set.mem_iUnion, SimpleGraph.mem_edgeSet] + change (G.Adj u v ∧ ∀ i, ¬ (heavyDesignated G X a i).Adj u v) ∨ + (∃ i, (heavyDesignated G X a i).Adj u v) ↔ G.Adj u v + constructor + · rintro (h | ⟨i,hi⟩) + · exact h.1 + · exact hi.1 + · intro h + by_cases he : ∃ i, (heavyDesignated G X a i).Adj u v + · exact Or.inr he + · exact Or.inl ⟨h,fun i hi => he ⟨i,hi⟩⟩ + · apply Set.disjoint_left.mpr + intro e he hf + induction e using Sym2.ind with + | _ u v => + obtain ⟨i,hi⟩ := Set.mem_iUnion.mp hf + exact he.2 i hi + +end +end ErdosGallai.Batch + +namespace ErdosGallai.Batch +noncomputable section +open SimpleGraph +attribute [local instance] Classical.propDecidable + +structure TrimmedPath {V : Type cycleUniverse21} (G : SimpleGraph V) where + start : V + finish : V + walk : G.Walk start finish + simple : walk.IsPath + +lemma alternating_endpoint_mem {V : Type cycleUniverse22} {G : SimpleGraph V} (X H : Set V) + (hbi : ∀ {u v}, G.Adj u v → (u ∈ X ∧ v ∈ H) ∨ (u ∈ H ∧ v ∈ X)) + {a b : V} (p : G.Walk a b) (hp : 0 < p.length) : + (a ∈ X ∨ a ∈ H) ∧ (b ∈ X ∨ b ∈ H) := by + have hn : ¬p.Nil := by intro h; have := h.length_eq_zero; omega + constructor + · exact (hbi (p.adj_snd hn)).elim (fun h => Or.inl h.1) (fun h => Or.inr h.1) + · exact (hbi (p.adj_penultimate hn)).elim (fun h => Or.inr h.2) (fun h => Or.inl h.2) + +lemma alternating_snd_mem {V : Type cycleUniverse23} {G : SimpleGraph V} (X H : Set V) + (hd : Disjoint X H) + (hbi : ∀ {u v}, G.Adj u v → (u ∈ X ∧ v ∈ H) ∨ (u ∈ H ∧ v ∈ X)) + {a b : V} (p : G.Walk a b) (hp : 0 < p.length) (ha : a ∈ H) : p.snd ∈ X := by + have hn : ¬p.Nil := by intro h; have := h.length_eq_zero; omega + rcases hbi (p.adj_snd hn) with h | h + · exact False.elim (Set.disjoint_left.mp hd h.1 ha) + · exact h.2 + +lemma alternating_penultimate_mem {V : Type cycleUniverse24} {G : SimpleGraph V} (X H : Set V) + (hd : Disjoint X H) + (hbi : ∀ {u v}, G.Adj u v → (u ∈ X ∧ v ∈ H) ∨ (u ∈ H ∧ v ∈ X)) + {a b : V} (p : G.Walk a b) (hp : 0 < p.length) (hb : b ∈ H) : + p.penultimate ∈ X := by + have hn : ¬p.Nil := by intro h; have := h.length_eq_zero; omega + rcases hbi (p.adj_penultimate hn) with h | h + · exact h.1 + · exact False.elim (Set.disjoint_left.mp hd h.2 hb) + +theorem trim_bipartite_path {V : Type cycleUniverse25} {G : SimpleGraph V} (X H : Set V) + (hd : Disjoint X H) + (hbi : ∀ {u v}, G.Adj u v → (u ∈ X ∧ v ∈ H) ∨ (u ∈ H ∧ v ∈ X)) + {a b : V} (p : G.Walk a b) (hs : p.IsPath) (hp : 0 < p.length) : + ∃ q : TrimmedPath G, + q.walk.edgeSet ⊆ p.edgeSet ∧ p.length ≤ q.walk.length + 2 ∧ + (0 < q.walk.length → q.start ∈ X ∧ q.finish ∈ X) := by + have hends := alternating_endpoint_mem X H hbi p hp + by_cases ha : a ∈ H + · have hsa := alternating_snd_mem X H hd hbi p hp ha + by_cases hb : b ∈ H + · refine ⟨⟨p.snd,p.tail.penultimate,p.tail.dropLast,hs.tail.dropLast⟩,?_,?_,?_⟩ + · intro e he + simp only [Walk.mem_edgeSet, Walk.edges_dropLast, Walk.edges_tail] at he ⊢ + exact List.mem_of_mem_tail (List.mem_of_mem_dropLast he) + · simp only [Walk.length_dropLast,Walk.length_tail] + omega + · intro hpos + have ht : 0 < p.tail.length := by + change 0 < p.tail.dropLast.length at hpos + rw [Walk.length_dropLast] at hpos + omega + exact ⟨hsa,alternating_penultimate_mem X H hd hbi p.tail ht hb⟩ + · refine ⟨⟨p.snd,b,p.tail,hs.tail⟩,?_,?_,?_⟩ + · intro e he + simp only [Walk.mem_edgeSet, Walk.edges_tail] at he ⊢ + exact List.mem_of_mem_tail he + · simp only [Walk.length_tail]; omega + · intro _ + exact ⟨hsa,hends.2.resolve_right hb⟩ + · by_cases hb : b ∈ H + · refine ⟨⟨a,p.penultimate,p.dropLast,hs.dropLast⟩,?_,?_,?_⟩ + · intro e he + simp only [Walk.mem_edgeSet, Walk.edges_dropLast] at he ⊢ + exact List.mem_of_mem_dropLast he + · simp only [Walk.length_dropLast]; omega + · intro _ + exact ⟨hends.1.resolve_right ha,alternating_penultimate_mem X H hd hbi p hp hb⟩ + · exact ⟨⟨a,b,p,hs⟩,Set.Subset.rfl,by change p.length ≤ p.length + 2; omega,fun _ => + ⟨hends.1.resolve_right ha,hends.2.resolve_right hb⟩⟩ + +lemma bipartite_path_length {V : Type cycleUniverse26} {G : SimpleGraph V} (X H : Set V) + (hd : Disjoint X H) + (hbi : ∀ {u v}, G.Adj u v → (u ∈ X ∧ v ∈ H) ∨ (u ∈ H ∧ v ∈ X)) + {a b : V} (p : G.Walk a b) (hp : 0 < p.length) (ha : a ∈ X) (hb : b ∈ X) : + 2 ≤ p.length := by + by_contra h + have hlen : p.length = 1 := by omega + rcases hbi (Walk.adj_of_length_eq_one hlen) with he | he + · exact Set.disjoint_left.mp hd hb he.2 + · exact Set.disjoint_left.mp hd ha he.1 + +lemma path_edgeFinset_card {V : Type cycleUniverse27} {G : SimpleGraph V} + {a b : V} (p : G.Walk a b) (hp : p.IsPath) : p.edges.toFinset.card = p.length := by + classical + rw [List.toFinset_card_of_nodup hp.isTrail.edges_nodup, Walk.length_edges] + +theorem trim_bipartite_path_ledger {V : Type cycleUniverse28} {G : SimpleGraph V} (X H : Set V) + (hd : Disjoint X H) + (hbi : ∀ {u v}, G.Adj u v → (u ∈ X ∧ v ∈ H) ∨ (u ∈ H ∧ v ∈ X)) + {a b : V} (p : G.Walk a b) (hs : p.IsPath) (hp : 0 < p.length) : + ∃ (q : TrimmedPath G) (discarded : Finset (Sym2 V)), + discarded.card ≤ 2 ∧ Disjoint (discarded : Set (Sym2 V)) q.walk.edgeSet ∧ + (discarded : Set (Sym2 V)) ∪ q.walk.edgeSet = p.edgeSet ∧ + (0 < q.walk.length → q.start ∈ X ∧ q.finish ∈ X ∧ 2 ≤ q.walk.length) := by + classical + obtain ⟨q,hsub,hlen,hends⟩ := trim_bipartite_path X H hd hbi p hs hp + have hfs : q.walk.edges.toFinset ⊆ p.edges.toFinset := by + intro e he + exact List.mem_toFinset.mpr (hsub (List.mem_toFinset.mp he)) + refine ⟨q,p.edges.toFinset \ q.walk.edges.toFinset,?_,?_,?_,?_⟩ + · rw [Finset.card_sdiff_of_subset hfs, path_edgeFinset_card p hs, + path_edgeFinset_card q.walk q.simple] + omega + · rw [Set.disjoint_left] + intro e he hq + exact (Finset.mem_sdiff.mp he).2 (List.mem_toFinset.mpr hq) + · ext e + simp only [Set.mem_union, Finset.mem_coe, Finset.mem_sdiff, List.mem_toFinset, + Walk.mem_edgeSet] + constructor + · rintro (h | h) + · exact h.1 + · exact hsub h + · intro h + by_cases he : e ∈ q.walk.edges + · exact Or.inr he + · exact Or.inl ⟨h,he⟩ + · intro hpos + obtain ⟨ha,hb⟩ := hends hpos + exact ⟨ha,hb,bipartite_path_length X H hd hbi q.walk hpos ha hb⟩ + +theorem close_trimmed_path {V : Type cycleUniverse29} {G : SimpleGraph V} {a b : V} + (p : G.Walk a b) (q : G.Walk b a) (hp : p.IsPath) (hq : q.IsPath) + (hlen : 2 ≤ p.length) + (havoid : ∀ v ∈ q.support, v ≠ a → v ≠ b → v ∉ p.support) : + (p.append q).IsCycle ∧ (p.append q).edgeSet = p.edgeSet ∪ q.edgeSet := by + refine ⟨hp.isCycle_append hq ?_ (Or.inl (by omega)), Walk.edgeSet_append p q⟩ + rw [List.disjoint_left] + intro v hvp hvq + have hva : v ≠ a := by + intro h; subst v + have hn := hp.support_nodup + rw [← p.cons_tail_support] at hn + exact hn.notMem hvp + have hvb : v ≠ b := by + intro h; subst v + have hn := hq.support_nodup + rw [← q.cons_tail_support] at hn + exact hn.notMem hvq + exact havoid v (List.mem_of_mem_tail hvq) hva hvb (List.mem_of_mem_tail hvp) + +end +end ErdosGallai.Batch + +namespace ErdosGallai.Batch +noncomputable section +open Finset SimpleGraph +attribute [local instance] Classical.propDecidable + +lemma endpoint_path_count_on {V : Type cycleUniverse30} {I : Type cycleUniverse31} [Fintype V] [Fintype I] + {G : SimpleGraph V} (P : I → PositiveSimplePath G) (S : Finset V) + (hends : ∀ i, (P i).start ∈ S ∧ (P i).finish ∈ S) + (hload : ∀ v, (univ.filter (fun i => (P i).start = v ∨ (P i).finish = v)).card ≤ 2) : + Fintype.card I ≤ S.card := by + classical + have heq : ∑ v ∈ S, (univ.filter (fun i => (P i).start = v ∨ (P i).finish = v)).card = + 2 * Fintype.card I := by + simp only [Finset.card_eq_sum_ones,Finset.sum_filter] + rw [Finset.sum_comm] + have hc : ∀ i : I, (∑ v ∈ S, if (P i).start = v ∨ (P i).finish = v then 1 else 0) = 2 := by + intro i + have hf : S.filter (fun v => (P i).start = v ∨ (P i).finish = v) = + {(P i).start,(P i).finish} := by + ext v + simp only [Finset.mem_filter,Finset.mem_insert,Finset.mem_singleton] + constructor + · intro h; simpa only [eq_comm] using h.2 + · intro h + rcases h with rfl | rfl + · exact ⟨(hends i).1,Or.inl rfl⟩ + · exact ⟨(hends i).2,Or.inr rfl⟩ + rw [← Finset.sum_filter,hf] + simp [(P i).endpoints_ne] + simp_rw [hc] + simp [mul_comm] + have hb := Finset.sum_le_sum (fun v (_ : v ∈ S) => hload v) + rw [heq] at hb + simp only [Finset.sum_const, smul_eq_mul] at hb + omega + +lemma heavy_paths {V : Type cycleUniverse32} [Fintype V] (G : SimpleGraph V) + (X : Finset V) (a : ℝ) (ha : 0 < a) + (hdeg : ∀ v ∈ X, (G.degree v:ℝ) ≤ a) : + let H := heavyNeighbors G X a + let B := crossGraph G X H + ∃ (k : ℕ) (P : Fin k → PositiveSimplePath B), + Pairwise (fun i j => Disjoint (P i).walk.edgeSet (P j).walk.edgeSet) ∧ + (⋃ i, (P i).walk.edgeSet) = B.edgeSet ∧ k ≤ 2 * X.card := by + classical + dsimp only + obtain ⟨k,P,hd,hu,hl,_⟩ := endpoint_path_partition (crossGraph G X (heavyNeighbors G X a)) + refine ⟨k,P,hd,hu,?_⟩ + have hend : ∀ i, (P i).start ∈ X ∪ heavyNeighbors G X a ∧ + (P i).finish ∈ X ∪ heavyNeighbors G X a := by + intro i + have h := alternating_endpoint_mem (X:Set V) (heavyNeighbors G X a : Set V) + (fun {_ _} (h : (crossGraph G X (heavyNeighbors G X a)).Adj _ _) => h.2) (P i).walk (P i).positive + exact ⟨Finset.mem_union.mpr h.1,Finset.mem_union.mpr h.2⟩ + have hk := endpoint_path_count_on P (X ∪ heavyNeighbors G X a) hend hl + rw [Fintype.card_fin] at hk + have hh := heavyNeighbors_card_le G X a ha hdeg + exact hk.trans ((Finset.card_union_le _ _).trans (by omega)) + +lemma folded_order_saving {V : Type cycleUniverse33} {I : Type cycleUniverse34} [Fintype V] [Fintype I] + (X : I → Finset V) (hd : Pairwise fun i j => Disjoint (X i) (X j)) + (p : ∀ i, PairingSpace (X i)) (hsize : ∀ i, 2 ≤ (X i).card) : + (Fintype.card (FamilyQuotient X p):ℝ) ≤ Fintype.card V - + (1/3:ℝ) * ∑ i, ((X i).card:ℝ) := by + have he := family_quotient_order_add X hd p + have hf : ∀ i, ((X i).card:ℝ)/3 ≤ ((X i).card/2:ℕ) := by + intro i + have h := Nat.mod_add_div (X i).card 2 + have hm := Nat.mod_lt (X i).card (by decide : 0<2) + have hs := hsize i + have hi : (X i).card ≤ 3 * ((X i).card/2) := by omega + exact (div_le_iff₀ (by norm_num : (0:ℝ)<3)).mpr (by simpa only [mul_comm] using (show ((X i).card:ℝ) ≤ 3*((X i).card/2:ℕ) by exact_mod_cast hi)) + have hb := Finset.sum_le_sum (fun i (_ : i ∈ (univ:Finset I)) => hf i) + have he' : (Fintype.card (FamilyQuotient X p):ℝ) + ∑ i, (((X i).card/2:ℕ):ℝ) = + Fintype.card V := by exact_mod_cast he + rw [← Finset.sum_div] at hb + linarith + +structure PreparedBatch {V I : Type} [Fintype V] [Fintype I] + (G : SimpleGraph V) (X : I → Finset V) + (hd : Pairwise fun i j => Disjoint (X i) (X j)) where + pairing : ∀ i, PairingSpace (X i) + quotient : SimpleGraph (FamilyQuotient X pairing) + retained : Finset (Sym2 V) + bad : Finset (Sym2 V) + count : I → ℕ + path : ∀ i, Fin (count i) → TrimmedPath G + count_le : ∀ i, count i ≤ 2 * (X i).card + bad_le : bad.card ≤ 6 * ∑ i, (X i).card + ends : ∀ i j, 0 < (path i j).walk.length → + (path i j).start ∈ X i ∧ (path i j).finish ∈ X i ∧ 2 ≤ (path i j).walk.length + paths_disjoint : Pairwise fun z w : Σ i, Fin (count i) => + Disjoint (path z.1 z.2).walk.edgeSet (path w.1 w.2).walk.edgeSet + bad_paths : ∀ i j, Disjoint (bad : Set (Sym2 V)) (path i j).walk.edgeSet + retained_paths : ∀ i j, Disjoint (retained : Set (Sym2 V)) (path i j).walk.edgeSet + bad_retained : Disjoint (bad : Set (Sym2 V)) (retained : Set (Sym2 V)) + cover : (bad : Set (Sym2 V)) ∪ (retained : Set (Sym2 V)) ∪ + (⋃ (i) (j), (path i j).walk.edgeSet) = G.edgeSet + quotient_edges : quotient.edgeSet = + (Sym2.map (familyProject X hd pairing)) '' (retained : Set (Sym2 V)) + representatives : ∀ e ∈ quotient.edgeSet, ∃! f, + f ∈ retained ∧ Sym2.map (familyProject X hd pairing) f = e + order : Fintype.card (FamilyQuotient X pairing) = + Fintype.card V - ∑ i, (X i).card / 2 + +lemma PreparedBatch.bad_subset {V I : Type} [Fintype V] [Fintype I] + {G : SimpleGraph V} {X : I → Finset V} {hd} + (b : PreparedBatch G X hd) : (b.bad : Set (Sym2 V)) ⊆ G.edgeSet := by + rw [← b.cover]; exact Set.subset_union_of_subset_left (Set.subset_union_left) _ + +lemma PreparedBatch.retained_subset {V I : Type} [Fintype V] [Fintype I] + {G : SimpleGraph V} {X : I → Finset V} {hd} + (b : PreparedBatch G X hd) : (b.retained : Set (Sym2 V)) ⊆ G.edgeSet := by + rw [← b.cover]; exact Set.subset_union_of_subset_left (Set.subset_union_right) _ + +theorem prepare_batch {V I : Type} [Fintype V] [Fintype I] + (G : SimpleGraph V) (X : I → Finset V) + (hd : Pairwise fun i j => Disjoint (X i) (X j)) + (a : ℝ) (ha : 1 ≤ a) (hm : ∀ i, 8 ≤ (X i).card) + (hma : ∀ i, a^2 ≤ (X i).card) + (hdeg : ∀ i v, v ∈ X i → (G.degree v:ℝ) ≤ a) : + Nonempty (PreparedBatch G X hd) := by + classical + let H := heavyDesignated G X a + let T := trimHeavyGraph G X a + have hHpair := heavyDesignated_pairwise G X a hd hdeg + have hT := trimHeavyGraph_ledger G X a + have hpaths : ∀ i, ∃ (k : ℕ) (P : Fin k → PositiveSimplePath (H i)), + Pairwise (fun j l => Disjoint (P j).walk.edgeSet (P l).walk.edgeSet) ∧ + (⋃ j, (P j).walk.edgeSet) = (H i).edgeSet ∧ k ≤ 2*(X i).card := + fun i => heavy_paths G (X i) a (by linarith) (hdeg i) + choose k P hPd hPu hk using hpaths + have htrim : ∀ i j, ∃ (q : TrimmedPath (H i)) (S : Finset (Sym2 V)), + S.card ≤ 2 ∧ Disjoint (S:Set _) q.walk.edgeSet ∧ + (S:Set _) ∪ q.walk.edgeSet = (P i j).walk.edgeSet ∧ + (0 < q.walk.length → q.start ∈ X i ∧ q.finish ∈ X i ∧ 2 ≤ q.walk.length) := by + intro i j + exact trim_bipartite_path_ledger (X i:Set V) (heavyNeighbors G (X i) a:Set V) + (by simpa only [Finset.disjoint_coe] using + (heavyNeighbors_disjoint_active G (X i) (X i) a (hdeg i)).symm) + (fun {_ _} (h : (H i).Adj _ _) => h.2) (P i j).walk (P i j).isPath (P i j).positive + choose q S hSnum hSq hScover hEnds using htrim + let Qpath : ∀ i, Fin (k i) → TrimmedPath G := fun i j => + ⟨(q i j).start,(q i j).finish,(q i j).walk.map (SimpleGraph.Hom.ofLE (heavyDesignated_le G X a i)), + (q i j).simple.map (Function.injective_id)⟩ + have hQedges : ∀ i j, (Qpath i j).walk.edgeSet = (q i j).walk.edgeSet := by + intro i j; simp [Qpath,Walk.edgeSet_map,SimpleGraph.Hom.ofLE] + have hQlen : ∀ i j, (Qpath i j).walk.length = (q i j).walk.length := + fun i j => Walk.length_map _ _ + have hSsub : ∀ i j, (S i j:Set _) ⊆ (P i j).walk.edgeSet := by + intro i j; rw [← hScover i j]; exact Set.subset_union_left + have hqsub : ∀ i j, (Qpath i j).walk.edgeSet ⊆ (P i j).walk.edgeSet := by + intro i j; rw [hQedges,← hScover i j]; exact Set.subset_union_right + have hPsub : ∀ i j, (P i j).walk.edgeSet ⊆ (H i).edgeSet := + fun i j => (P i j).walk.edges_subset_edgeSet + have hPdall : Pairwise fun z w : Σ i, Fin (k i) => + Disjoint (P z.1 z.2).walk.edgeSet (P w.1 w.2).walk.edgeSet := by + rintro ⟨i,j⟩ ⟨l,m⟩ hne + by_cases hi : i = l + · subst l + exact hPd i (fun he => hne (by cases he; rfl)) + · exact (hHpair hi).mono (hPsub _ _) (hPsub _ _) + let B := Finset.univ.biUnion fun z : Σ i, Fin (k i) => S z.1 z.2 + have hB : (B:Set (Sym2 V)) = ⋃ i, ⋃ j, (S i j : Set (Sym2 V)) := by + ext e; simp [B] + have hBnum : B.card ≤ 4 * ∑ i, (X i).card := by + have hc : B.card ≤ ∑ z : Σ i, Fin (k i), (S z.1 z.2).card := + Finset.card_biUnion_le + have hj : (∑ z : Σ i, Fin (k i), (S z.1 z.2).card) ≤ 2 * ∑ i, k i := by + calc + _ ≤ ∑ z : Σ i, Fin (k i), 2 := Finset.sum_le_sum (fun z _ => hSnum z.1 z.2) + _ = _ := by simp [Fintype.card_sigma,mul_comm] + have hk' := Finset.sum_le_sum (fun i (_:i∈(univ:Finset I)) => hk i) + rw [← Finset.mul_sum] at hk' + omega + have hBheavy : (B:Set (Sym2 V)) ⊆ ⋃ i, (H i).edgeSet := by + rw [hB]; exact Set.iUnion_subset (fun i => Set.iUnion_subset (fun j => + Set.subset_iUnion_of_subset i ((hSsub i j).trans (hPsub i j)))) + have hBhq : ∀ i j, Disjoint (B:Set (Sym2 V)) (Qpath i j).walk.edgeSet := by + intro i j + rw [hB,Set.disjoint_iUnion_left] + intro l + rw [Set.disjoint_iUnion_left] + intro m + by_cases he : (⟨l,m⟩ : Σ i, Fin (k i)) = ⟨i,j⟩ + · cases he + rw [hQedges]; exact hSq i j + · exact (hPdall he).mono (hSsub l m) (hqsub i j) + have hdegT : ∀ i v, v ∈ X i → (T.degree v:ℝ) ≤ a := by + intro i v hv + exact (show (T.degree v:ℝ) ≤ G.degree v by exact_mod_cast trimHeavyGraph_degree G X a v).trans (hdeg i v hv) + obtain ⟨p,R,Q,hR,hBad,hQ,hrep,horder⟩ := pair_folding T X hd a ha hm hma hdegT + (trimHeavyGraph_neighbors G X a (by linarith)) + let A := T.edgeFinset \ R + have hA : (A:Set (Sym2 V)) = T.edgeSet \ (R:Set (Sym2 V)) := by + simp [A,SimpleGraph.coe_edgeFinset] + have hR' : (R:Set (Sym2 V)) ⊆ T.edgeSet := by + intro e he; exact SimpleGraph.mem_edgeFinset.mp (hR he) + refine ⟨⟨p,Q,R,A ∪ B,k,Qpath,hk,?_,?_,?_,?_,?_,?_,?_,?_,hrep,horder⟩⟩ + · exact (Finset.card_union_le _ _).trans (by + have hn : A.card ≤ 2 * ∑ i, (X i).card := hBad + omega) + · intro i j hp + simpa only [Qpath,Walk.length_map] using hEnds i j (by rwa [hQlen] at hp) + · intro z w hzw + exact (hPdall hzw).mono (hqsub _ _) (hqsub _ _) + · intro i j + rw [Finset.coe_union,Set.disjoint_union_left] + refine ⟨?_,hBhq i j⟩ + apply hT.2.mono + · rw [hA]; exact Set.sdiff_subset + · exact (hqsub i j).trans ((hPsub i j).trans (Set.subset_iUnion (fun i => (H i).edgeSet) i)) + · intro i j + exact hT.2.mono hR' ((hqsub i j).trans ((hPsub i j).trans (Set.subset_iUnion (fun i => (H i).edgeSet) i))) + · rw [Finset.coe_union,Set.disjoint_union_left] + refine ⟨?_,hT.2.symm.mono hBheavy hR'⟩ + rw [hA]; exact Set.disjoint_sdiff_left + · have hheavy : (B:Set (Sym2 V)) ∪ (⋃ i, ⋃ j, (Qpath i j).walk.edgeSet) = + ⋃ i, (H i).edgeSet := by + rw [hB,← Set.iUnion_union_distrib] + congr 1 + funext i + rw [← Set.iUnion_union_distrib] + simp_rw [hQedges,hScover] + exact hPu i + rw [Finset.coe_union] + have hAR : (A:Set (Sym2 V)) ∪ (R:Set (Sym2 V)) = T.edgeSet := by + rw [hA]; exact Set.sdiff_union_of_subset hR' + calc + _ = ((A:Set _) ∪ (R:Set _)) ∪ ((B:Set _) ∪ ⋃ i, ⋃ j, (Qpath i j).walk.edgeSet) := by + ext e; simp only [Set.mem_union]; tauto + _ = T.edgeSet ∪ ⋃ i, (H i).edgeSet := by rw [hAR,hheavy] + _ = G.edgeSet := hT.1 + · simpa only [Finset.coe_image] using hQ + +end +end ErdosGallai.Batch +end +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/CycleDecomposition/BatchResolution.lean b/lean/OAI/Combinatorics/CycleDecomposition/BatchResolution.lean new file mode 100644 index 0000000000000000000000000000000000000000..f5fae69bb41e2d278c3371adcc86511a2e745563 --- /dev/null +++ b/lean/OAI/Combinatorics/CycleDecomposition/BatchResolution.lean @@ -0,0 +1,467 @@ +import OAI.Combinatorics.CycleDecomposition.Templates + +namespace OAI + +section +open Filter Asymptotics Real +open scoped Topology +noncomputable section +open MeasureTheory ProbabilityTheory Finset +section +namespace ErdosGallai.Batch +noncomputable section +open Finset SimpleGraph +attribute [local instance] Classical.propDecidable + +theorem cycle_template_of_representatives_bounded {V W : Type} [Fintype W] + {G : SimpleGraph V} {Q : SimpleGraph W} (projMap : V → W) + (S : Set (Sym2 V)) (hSG : S ⊆ G.edgeSet) + (hrep : ∀ e ∈ Q.edgeSet, ∃! f, f ∈ S ∧ Sym2.map projMap f = e) + {a : W} (p : Q.Walk a a) (hp : p.IsCycle) + (M : ℕ) (hM : p.dropLast.support.toFinset.card ≤ M) : + ∃ b : RoutingTemplate G, + b.edges = {e | e ∈ S ∧ Sym2.map projMap e ∈ p.edgeSet} ∧ + Fintype.card b.Arity ≤ M ∧ + b.vertices.card ≤ 2*M ∧ + ∀ i, projMap (b.x i) = projMap (b.y i) := by + classical + obtain ⟨R,hR⟩ := orient_edge_representatives projMap S hSG (fun e he => + (hrep e he).exists) + let v₀ := (R ⟨(a,p.snd),p.adj_snd hp.not_nil⟩).fst + obtain ⟨s,t,hports,hproj⟩ := choose_cycle_ports projMap R (fun d => (hR d).2) p hp v₀ + have hfst (d : Q.Dart) (hd : d ∈ p.darts) : d.fst ∈ p.dropLast.support := by + rw [p.support_dropLast hp.not_nil,← Walk.map_fst_darts] + exact List.mem_map.mpr ⟨d,hd,rfl⟩ + have hsnd (d : Q.Dart) (hd : d ∈ p.darts) : d.snd ∈ p.dropLast.support := by + rw [p.support_dropLast hp.not_nil] + apply p.tail_support_perm_dropLast_support.mem_iff.mp + rw [← Walk.map_snd_darts] + exact List.mem_map.mpr ⟨d,hd,rfl⟩ + let c : CycleOutline G := { + W := W, finiteW := inferInstance, Q := Q, base := a, cycle := p, isCycle := hp, + rep := R, start := fun z => if z ∈ p.dropLast.support then s z else v₀, + finish := fun z => if z ∈ p.dropLast.support then t z else v₀, + project := projMap, + ports := by intro d hd; simpa only [ite_eq_left (hfst d hd),ite_eq_left (hsnd d hd)] using hports d hd, + projects := by intro z hz; simpa only [ite_eq_left hz] using hproj z hz, + outside := by intro z hz; simp only [ite_eq_right hz] + } + have hmap (d : Q.Dart) : Sym2.map projMap (R d).edge = d.edge := by + change s(projMap (R d).fst,projMap (R d).snd) = s(d.fst,d.snd) + rw [(hR d).2.1,(hR d).2.2] + have he : c.edges = {e | e ∈ S ∧ Sym2.map projMap e ∈ p.edgeSet} := by + ext e + constructor + · rintro ⟨d,hd,rfl⟩ + refine ⟨(hR d).1,?_⟩ + rw [hmap] + change d.edge ∈ p.edges + rw [Walk.edges_eq_map_darts] + exact List.mem_map.mpr ⟨d,hd,rfl⟩ + · rintro ⟨hS,he⟩ + change Sym2.map projMap e ∈ p.edges at he + rw [Walk.edges_eq_map_darts] at he + obtain ⟨d,hd,hde⟩ := List.mem_map.mp he + refine ⟨d,hd,?_⟩ + exact (hrep d.edge d.edge_mem).unique ⟨hS,hde.symm⟩ ⟨(hR d).1,hmap d⟩ + refine ⟨RoutingTemplate.ofCycle c,he,?_,?_,?_⟩ + · change Fintype.card c.Switch ≤ M + apply le_trans _ hM + apply Finset.card_le_card_of_injOn (fun i : c.Switch => i.val) + · intro z hz; exact List.mem_toFinset.mpr z.property.1 + · intro z _ w _ h; exact Subtype.ext h + · exact c.vertices_card_support.trans (Nat.mul_le_mul_left _ hM) + · intro i + change c.Switch at i + exact (c.projects i i.property.1).1.trans (c.projects i i.property.1).2.symm + +theorem cycle_template_of_representatives {V W : Type} [Fintype W] + {G : SimpleGraph V} {Q : SimpleGraph W} (projMap : V → W) + (S : Set (Sym2 V)) (hSG : S ⊆ G.edgeSet) + (hrep : ∀ e ∈ Q.edgeSet, ∃! f, f ∈ S ∧ Sym2.map projMap f = e) + {a : W} (p : Q.Walk a a) (hp : p.IsCycle) : + ∃ b : RoutingTemplate G, + b.edges = {e | e ∈ S ∧ Sym2.map projMap e ∈ p.edgeSet} ∧ + Fintype.card b.Arity ≤ Fintype.card W ∧ + b.vertices.card ≤ 2*Fintype.card W ∧ + ∀ i, projMap (b.x i) = projMap (b.y i) := by + exact cycle_template_of_representatives_bounded projMap S hSG hrep p hp _ (Finset.card_le_univ _) + +theorem quotient_part_template {V W : Type} [Fintype W] + {G : SimpleGraph V} {Q : SimpleGraph W} (projMap : V → W) + (S : Set (Sym2 V)) (hSG : S ⊆ G.edgeSet) + (hrep : ∀ e ∈ Q.edgeSet, ∃! f, f ∈ S ∧ Sym2.map projMap f = e) + (s : Set (Sym2 W)) (hs : CycleOrSingleEdge Q s) : + ∃ b : RoutingTemplate G, + b.edges = {e | e ∈ S ∧ Sym2.map projMap e ∈ s} ∧ + Fintype.card b.Arity ≤ Fintype.card W ∧ + b.vertices.card ≤ 2*Fintype.card W ∧ + ∀ i, projMap (b.x i) = projMap (b.y i) := by + rcases hs with ⟨a,p,hp,rfl⟩ | ⟨e,he,rfl⟩ + · exact cycle_template_of_representatives projMap S hSG hrep p hp + · obtain ⟨f,hf,huniq⟩ := hrep e he + refine ⟨RoutingTemplate.ofSingle f (hSG hf.1),?_,by change Fintype.card Empty ≤ _; simp,by simp [RoutingTemplate.ofSingle],fun i => i.elim⟩ + ext g + change g = f ↔ g ∈ S ∧ Sym2.map projMap g ∈ ({e} : Set (Sym2 W)) + constructor + · intro h; subst g; exact ⟨hf.1,hf.2⟩ + · rintro ⟨hg,hge⟩; exact huniq g ⟨hg,hge⟩ + +theorem quotient_partition_templates {V W : Type} [Fintype W] + {G : SimpleGraph V} {Q : SimpleGraph W} (projMap : V → W) + (S : Set (Sym2 V)) (hSG : S ⊆ G.edgeSet) + (himage : Sym2.map projMap '' S = Q.edgeSet) + (hrep : ∀ e ∈ Q.edgeSet, ∃! f, f ∈ S ∧ Sym2.map projMap f = e) + {k : ℕ} (hQ : EdgeDecomposition Q k) : + ∃ b : Fin k → RoutingTemplate G, + Pairwise (fun i j => Disjoint (b i).edges (b j).edges) ∧ + (⋃ i, (b i).edges) = S ∧ + (∀ i, Fintype.card (b i).Arity ≤ Fintype.card W ∧ + (b i).vertices.card ≤ 2*Fintype.card W ∧ + ∀ j, projMap ((b i).x j) = projMap ((b i).y j)) := by + classical + obtain ⟨parts,hp,hd,hcover⟩ := hQ + choose b hb hnum hv hprojMap using fun i => quotient_part_template projMap S hSG hrep (parts i) (hp i) + refine ⟨b,?_,?_,fun i => ⟨hnum i,hv i,hprojMap i⟩⟩ + · intro i j hij + rw [hb i,hb j] + exact Set.disjoint_left.mpr (fun _ hi hj => Set.disjoint_left.mp (hd hij) hi.2 hj.2) + · ext e + simp only [Set.mem_iUnion] + constructor + · rintro ⟨i,hi⟩; rw [hb i] at hi; exact hi.1 + · intro he + have hq : Sym2.map projMap e ∈ Q.edgeSet := by rw [← himage]; exact Set.mem_image_of_mem _ he + rw [← hcover] at hq + obtain ⟨i,hi⟩ := Set.mem_iUnion.mp hq + exact ⟨i,by rw [hb i]; exact ⟨he,hi⟩⟩ + +theorem quotient_part_template_on {V W : Type} [Fintype W] + {G : SimpleGraph V} {Q : SimpleGraph W} (projMap : V → W) + (S : Set (Sym2 V)) (hSG : S ⊆ G.edgeSet) + (A : Finset W) (hA : ∀ ⦃x y⦄, Q.Adj x y → x ∈ A ∧ y ∈ A) + (hrep : ∀ e ∈ Q.edgeSet, ∃! f, f ∈ S ∧ Sym2.map projMap f = e) + (s : Set (Sym2 W)) (hs : CycleOrSingleEdge Q s) : + ∃ b : RoutingTemplate G, + b.edges = {e | e ∈ S ∧ Sym2.map projMap e ∈ s} ∧ + Fintype.card b.Arity ≤ A.card ∧ + b.vertices.card ≤ 2*A.card ∧ + ∀ i, projMap (b.x i) = projMap (b.y i) := by + rcases hs with ⟨a,p,hp,rfl⟩ | ⟨e,he,rfl⟩ + · exact cycle_template_of_representatives_bounded projMap S hSG hrep p hp A.card (by + apply Finset.card_le_card + intro z hz + rw [List.mem_toFinset,p.support_dropLast hp.not_nil,← Walk.map_fst_darts] at hz + obtain ⟨d,hd,rfl⟩ := List.mem_map.mp hz + exact (hA d.adj).1) + · obtain ⟨f,hf,huniq⟩ := hrep e he + refine ⟨RoutingTemplate.ofSingle f (hSG hf.1),?_,by change Fintype.card Empty ≤ _; simp,by simp [RoutingTemplate.ofSingle],fun i => i.elim⟩ + ext g + change g = f ↔ g ∈ S ∧ Sym2.map projMap g ∈ ({e} : Set (Sym2 W)) + constructor + · intro h; subst g; exact ⟨hf.1,hf.2⟩ + · rintro ⟨hg,hge⟩; exact huniq g ⟨hg,hge⟩ + +theorem quotient_partition_templates_on {V W : Type} [Fintype W] + {G : SimpleGraph V} {Q : SimpleGraph W} (projMap : V → W) + (S : Set (Sym2 V)) (hSG : S ⊆ G.edgeSet) + (A : Finset W) (hA : ∀ ⦃x y⦄, Q.Adj x y → x ∈ A ∧ y ∈ A) + (himage : Sym2.map projMap '' S = Q.edgeSet) + (hrep : ∀ e ∈ Q.edgeSet, ∃! f, f ∈ S ∧ Sym2.map projMap f = e) + {k : ℕ} (hQ : EdgeDecomposition Q k) : + ∃ b : Fin k → RoutingTemplate G, + Pairwise (fun i j => Disjoint (b i).edges (b j).edges) ∧ + (⋃ i, (b i).edges) = S ∧ + (∀ i, Fintype.card (b i).Arity ≤ A.card ∧ + (b i).vertices.card ≤ 2*A.card ∧ + ∀ j, projMap ((b i).x j) = projMap ((b i).y j)) := by + classical + obtain ⟨parts,hp,hd,hcover⟩ := hQ + choose b hb hnum hv hprojMap using fun i => quotient_part_template_on projMap S hSG A hA hrep (parts i) (hp i) + refine ⟨b,?_,?_,fun i => ⟨hnum i,hv i,hprojMap i⟩⟩ + · intro i j hij + rw [hb i,hb j] + exact Set.disjoint_left.mpr (fun _ hi hj => Set.disjoint_left.mp (hd hij) hi.2 hj.2) + · ext e + simp only [Set.mem_iUnion] + constructor + · rintro ⟨i,hi⟩; rw [hb i] at hi; exact hi.1 + · intro he + have hq : Sym2.map projMap e ∈ Q.edgeSet := by rw [← himage]; exact Set.mem_image_of_mem _ he + rw [← hcover] at hq + obtain ⟨i,hi⟩ := Set.mem_iUnion.mp hq + exact ⟨i,by rw [hb i]; exact ⟨he,hi⟩⟩ + +end +end ErdosGallai.Batch + +namespace ErdosGallai.Batch +noncomputable section +open Finset SimpleGraph +attribute [local instance] Classical.propDecidable + +lemma walk_support_on {V : Type} {G : SimpleGraph V} (W : Finset V) + (hW : ∀ ⦃x y⦄, G.Adj x y → x ∈ W ∧ y ∈ W) + {x y : V} (p : G.Walk x y) (hp : 0 < p.length) : p.support.toFinset ⊆ W := by + classical + intro v hv + obtain ⟨e,he,hv⟩ := Walk.mem_support_iff_exists_mem_edges_of_not_nil + (p := p) (by simpa only [Walk.length_eq_zero_iff.symm] using (Nat.ne_of_gt hp)) |>.mp (List.mem_toFinset.mp hv) + induction e using Sym2.ind with + | _ a b => + have hab : G.Adj a b := p.edges_subset_edgeSet he + rcases Sym2.mem_iff.mp hv with rfl | rfl + · exact (hW hab).1 + · exact (hW hab).2 + +structure BatchTemplateFamily {V I : Type} [Fintype I] + (G J : SimpleGraph V) (X : I → Finset V) (W : Finset V) (bad : Finset (Sym2 V)) (k : ℕ) where + Index : Type + finiteIndex : Fintype Index + block : Index → RoutingTemplate G + count : Fintype.card Index ≤ k + 2 * ∑ i, (X i).card + disjoint : Pairwise fun i j => Disjoint (block i).edges (block j).edges + bad_disjoint : ∀ i, Disjoint (bad : Set (Sym2 V)) (block i).edges + cover : (bad : Set (Sym2 V)) ∪ (⋃ i, (block i).edges) = J.edgeSet + arity : ∀ i, Fintype.card (block i).Arity ≤ W.card + vertices : ∀ i, (block i).vertices.card ≤ 2*W.card + owner : (i : Index) → (block i).Arity → I + ends : ∀ i j, (block i).x j ∈ X (owner i j) ∧ (block i).y j ∈ X (owner i j) +attribute [instance] BatchTemplateFamily.finiteIndex + +lemma BatchTemplateFamily.subset {V I : Type} [Fintype I] + {G J : SimpleGraph V} {X : I → Finset V} {W bad k} + (b : BatchTemplateFamily G J X W bad k) (i : b.Index) : (b.block i).edges ⊆ J.edgeSet := by + rw [← b.cover] + intro e he; exact Or.inr (Set.mem_iUnion.mpr ⟨i,he⟩) + +theorem prepare_templates {V I : Type} [Fintype V] [Fintype I] + (G J : SimpleGraph V) (hJG : J ≤ G) (W : Finset V) + (hW : ∀ ⦃x y⦄, J.Adj x y → x ∈ W ∧ y ∈ W) + (X : I → Finset V) (hd : Pairwise fun i j => Disjoint (X i) (X j)) + (hX : ∀ i, X i ⊆ W) (b : PreparedBatch J X hd) + {k : ℕ} (hk : EdgeDecomposition b.quotient k) : + Nonempty (BatchTemplateFamily G J X W b.bad k) := by + classical + let projMap := familyProject X hd b.pairing + let A := W.image projMap + have hAW : A.card ≤ W.card := Finset.card_image_le + obtain ⟨q,hqd,hqu,hqn⟩ := quotient_partition_templates_on projMap (b.retained:Set (Sym2 V)) + (b.retained_subset.trans (SimpleGraph.edgeSet_mono hJG)) A (b.quotient_supported W hW) + b.quotient_edges.symm (by simpa only [Finset.mem_coe] using b.representatives) hk + have hqsub (j) : (q j).edges ⊆ (b.retained : Set (Sym2 V)) := by + rw [← hqu]; intro e he; exact Set.mem_iUnion.mpr ⟨j,he⟩ + have hex (j) (i : (q j).Arity) : ∃ r, (q j).x i ∈ X r ∧ (q j).y i ∈ X r := by + obtain he | ⟨r,hx,hy,_⟩ := (familyProject_eq_iff X hd b.pairing _ _).mp ((hqn j).2.2 i) + · exact False.elim ((q j).ne i he) + · exact ⟨r,hx,hy⟩ + choose own hown using hex + let P := {z : Σ i, Fin (b.count i) // 0 < (b.path z.1 z.2).walk.length} + let path : ∀ z : P, G.Walk (b.path z.1.1 z.1.2).start (b.path z.1.1 z.1.2).finish := + fun z => (b.path z.1.1 z.1.2).walk.map (SimpleGraph.Hom.ofLE hJG) + have hpe (z : P) : (path z).edgeSet = (b.path z.1.1 z.1.2).walk.edgeSet := by + simp [path,Walk.edgeSet_map,SimpleGraph.Hom.ofLE] + have hps (z : P) : (path z).IsPath := (b.path z.1.1 z.1.2).simple.map Function.injective_id + have hpl (z : P) : 2 ≤ (path z).length := by + simpa only [path,Walk.length_map] using (b.ends z.1.1 z.1.2 z.property).2.2 + let t : P → RoutingTemplate G := fun z => RoutingTemplate.ofPath (path z) (hps z) (hpl z) + have hte (z : P) : (t z).edges = (b.path z.1.1 z.1.2).walk.edgeSet := hpe z + have htv (z : P) : (t z).vertices.card ≤ W.card := by + apply Finset.card_le_card + change (path z).support.toFinset ⊆ W + simpa [path,Walk.support_map,SimpleGraph.Hom.ofLE] using + walk_support_on W hW (b.path z.1.1 z.1.2).walk z.property + have hta (z : P) : Fintype.card (t z).Arity ≤ W.card := by + change Fintype.card Unit ≤ W.card + simpa using Finset.card_pos.mpr ⟨(b.path z.1.1 z.1.2).start, + hX z.1.1 (b.ends z.1.1 z.1.2 z.property).1⟩ + have htu : (⋃ z, (t z).edges) = ⋃ i, ⋃ j, (b.path i j).walk.edgeSet := by + ext e; simp only [Set.mem_iUnion] + constructor + · rintro ⟨z,hz⟩; exact ⟨z.1.1,z.1.2,(hte z) ▸ hz⟩ + · rintro ⟨i,j,hj⟩ + have hp : 0 < (b.path i j).walk.length := by + by_contra h + have hn := Walk.length_eq_zero_iff.mp (Nat.eq_zero_of_not_pos h) + have he := Walk.edges_eq_nil.mpr hn + change e ∈ (b.path i j).walk.edges at hj + rw [he] at hj; contradiction + exact ⟨⟨⟨i,j⟩,hp⟩,by rw [hte]; exact hj⟩ + refine ⟨{ + Index := Fin k ⊕ P, + finiteIndex := inferInstance, + block := Sum.elim q t, + count := ?_, + disjoint := ?_, + bad_disjoint := ?_, + cover := ?_, + arity := ?_, + vertices := ?_, + owner := fun j => match j with | Sum.inl j => own j | Sum.inr z => fun _ => z.1.1, + ends := ?_ + }⟩ + · have hp : Fintype.card P ≤ 2 * ∑ i, (X i).card := by + calc + _ ≤ Fintype.card (Σ i, Fin (b.count i)) := Fintype.card_subtype_le _ + _ = ∑ i, b.count i := by simp + _ ≤ ∑ i, 2*(X i).card := Finset.sum_le_sum (fun i _ => b.count_le i) + _ = _ := by rw [← Finset.mul_sum] + simpa only [Fintype.card_sum,Fintype.card_fin] using Nat.add_le_add_left hp k + · intro j l hne + rcases j with j | j <;> rcases l with l | l <;> dsimp only [Sum.elim_inl,Sum.elim_inr] + · exact hqd (fun h => hne (congrArg Sum.inl h)) + · exact (b.retained_paths l.1.1 l.1.2).mono (hqsub j) (by rw [hte]) + · exact ((b.retained_paths j.1.1 j.1.2).mono (hqsub l) (by rw [hte])).symm + · rw [hte,hte] + exact b.paths_disjoint (fun h => hne (congrArg Sum.inr (Subtype.ext h))) + · rintro (j | z) <;> dsimp only [Sum.elim_inl,Sum.elim_inr] + · exact b.bad_retained.mono_right (hqsub j) + · rw [hte]; exact b.bad_paths _ _ + · + simp only [Set.iUnion_sum,Sum.elim_inl,Sum.elim_inr] + rw [hqu,htu,← Set.union_assoc] + exact b.cover + · rintro (j | z) + · exact (hqn j).1.trans hAW + · exact hta z + · rintro (j | z) + · exact (hqn j).2.1.trans (Nat.mul_le_mul_left _ hAW) + · exact (htv z).trans (by omega) + · rintro (j | z) i + · exact hown j i + · exact ⟨(b.ends z.1.1 z.1.2 z.property).2.1,(b.ends z.1.1 z.1.2 z.property).1⟩ + +end +end ErdosGallai.Batch + +namespace ErdosGallai.Batch +noncomputable section +open Finset SimpleGraph +attribute [local instance] Classical.propDecidable + +theorem uniform_batch_resolution : + ∃ D₀ : ℝ, 1 < D₀ ∧ ∀ D ≥ D₀, + ∀ (V R B : Type) [Fintype V] [Fintype R] [Fintype B], + ∀ (G F : SimpleGraph V) (P : R → SimpleGraph V) (U : R → Finset V), + F ≤ G → (∀ r, P r ≤ G) → + Pairwise (fun r s => Disjoint (P r).edgeSet (P s).edgeSet) → + Pairwise (fun r s => Disjoint (U r) (U s)) → + (∀ r, Disjoint F.edgeSet (P r).edgeSet) → + (∀ r, CutExpansionOn (P r) (U r) (D^(9/10:ℝ)/4)) → + (∀ r, D^(9/10:ℝ) ≤ ((U r).card:ℝ) ∧ ((U r).card:ℝ) ≤ D^(51/50:ℝ)) → + ∀ (J : B → SimpleGraph V) (W : B → Finset V), + (∀ b, J b ≤ F) → Pairwise (fun b c => Disjoint (J b).edgeSet (J c).edgeSet) → + (⋃ b, (J b).edgeSet) = F.edgeSet → + (∀ b, ∀ ⦃x y⦄, (J b).Adj x y → x ∈ W b ∧ y ∈ W b) → + (∀ b, ((W b).card:ℝ) ≤ D^(3/10:ℝ)) → + ∀ (I : B → Type) [∀ b, Fintype (I b)] (X : ∀ b, I b → Finset V) + (hXd : ∀ b, Pairwise fun i j => Disjoint (X b i) (X b j)), + (∀ b i, X b i ⊆ W b) → + ∀ rX : ∀ b, I b → R, + (∀ b i, X b i ⊆ U (rX b i)) → + (∀ b i v, v ∈ X b i → (F.degree v:ℝ) ≤ D^(1/100:ℝ)) → + ∀ (prep : ∀ b, PreparedBatch (J b) (X b) (hXd b)) (k : B → ℕ), + (∀ b, EdgeDecomposition (prep b).quotient (k b)) → + ∃ (K : Type) (_ : Fintype K) (parts : K → Set (Sym2 V)) (used : Set (Sym2 V)), + Fintype.card K ≤ (∑ b, k b) + 8 * ∑ b, ∑ i, (X b i).card ∧ + (∀ j, CycleOrSingleEdge G (parts j)) ∧ + Pairwise (fun j l => Disjoint (parts j) (parts l)) ∧ + used ⊆ ⋃ r, (P r).edgeSet ∧ Disjoint F.edgeSet used ∧ + (⋃ j, parts j) = F.edgeSet ∪ used := by + classical + obtain ⟨D₀,hD₀,hresolve⟩ := uniform_resolve_templates + refine ⟨D₀,hD₀,?_⟩ + intro D hD V R B _ _ _ G F P U hFG hPG hPP hUU hFP he hr J W hJF hJJ hJu hW hWnum I _ X hXd hXW rX hXU hdeg prep k hk + have hT (b : B) := prepare_templates G (J b) ((hJF b).trans hFG) (W b) (hW b) + (X b) (hXd b) (hXW b) (prep b) (hk b) + let T : ∀ b, BatchTemplateFamily G (J b) (X b) (W b) (prep b).bad (k b) := + fun b => Classical.choice (hT b) + let Q := Σ b, (T b).Index + let q : Q → RoutingTemplate G := fun z => (T z.1).block z.2 + have hqsub (z : Q) : (q z).edges ⊆ F.edgeSet := + ((T z.1).subset z.2).trans (SimpleGraph.edgeSet_mono (hJF z.1)) + have hqd : Pairwise fun z w : Q => Disjoint (q z).edges (q w).edges := by + rintro ⟨b,i⟩ ⟨c,j⟩ hne + by_cases hh : b = c + · subst c; exact (T b).disjoint (fun h => hne (by cases h; rfl)) + · exact (hJJ hh).mono ((T b).subset i) ((T c).subset j) + let owner : (z : Q) → (q z).Arity → R := fun z i => rX z.1 ((T z.1).owner z.2 i) + obtain ⟨parts,used,hparts,hpartsd,hused,hFu,hcover⟩ := + hresolve D hD V R Q G F P U hFG hPG hPP hUU hFP he hr q hqsub hqd owner + (fun z i => ⟨hXU _ _ ((T z.1).ends z.2 i).1,hXU _ _ ((T z.1).ends z.2 i).2⟩) + (fun z i => ⟨hdeg _ _ _ ((T z.1).ends z.2 i).1,hdeg _ _ _ ((T z.1).ends z.2 i).2⟩) + (fun z => (Nat.cast_le.mpr ((T z.1).arity z.2)).trans (hWnum z.1)) + (fun z => (Nat.cast_le.mpr ((T z.1).vertices z.2)).trans (by + push_cast; exact mul_le_mul_of_nonneg_left (hWnum z.1) (by norm_num))) + let S := Σ b, (prep b).bad + let e : S → Sym2 V := fun z => z.2.val + have hSsub (z : S) : e z ∈ (J z.1).edgeSet := (prep z.1).bad_subset z.2.property + have hSF (z : S) : e z ∈ F.edgeSet := SimpleGraph.edgeSet_mono (hJF z.1) (hSsub z) + have hinj : Function.Injective e := by + rintro ⟨b,i⟩ ⟨c,j⟩ h + by_cases hh : b = c + · subst c; exact Sigma.ext rfl (heq_of_eq (Subtype.ext h)) + · exact False.elim (Set.disjoint_left.mp (hJJ hh) (hSsub ⟨b,i⟩) (h ▸ hSsub ⟨c,j⟩)) + have hbadq (z : S) (w : Q) : e z ∉ (q w).edges := by + intro hw + by_cases hh : z.1 = w.1 + · rcases z with ⟨b,z⟩; rcases w with ⟨c,w⟩ + dsimp only at hh; subst c + exact Set.disjoint_left.mp ((T b).bad_disjoint w) z.property hw + · exact Set.disjoint_left.mp (hJJ hh) (hSsub z) ((T w.1).subset w.2 hw) + have hbadpart (z : S) (w : Q) : e z ∉ parts w := by + intro hw + have hu : e z ∈ ⋃ w, parts w := Set.mem_iUnion.mpr ⟨w,hw⟩ + rw [hcover] at hu + rcases hu with hu | hu + · obtain ⟨w,hw⟩ := Set.mem_iUnion.mp hu; exact hbadq z w hw + · exact Set.disjoint_left.mp hFu (hSF z) hu + have horiginal : (⋃ z : S, {e z}) ∪ (⋃ w : Q, (q w).edges) = F.edgeSet := by + rw [← hJu] + ext f + simp only [Set.mem_union,Set.mem_iUnion,Set.mem_singleton_iff] + constructor + · rintro (⟨z,hz⟩ | ⟨w,hw⟩) + · exact ⟨z.1,hz ▸ hSsub z⟩ + · exact ⟨w.1,(T w.1).subset w.2 hw⟩ + · rintro ⟨b,hb⟩ + rw [← (T b).cover] at hb + rcases hb with hb | hb + · exact Or.inl ⟨⟨b,⟨f,hb⟩⟩,rfl⟩ + · obtain ⟨j,hj⟩ := Set.mem_iUnion.mp hb + exact Or.inr ⟨⟨b,j⟩,hj⟩ + refine ⟨Q ⊕ S,inferInstance,Sum.elim parts (fun z => {e z}),used,?_,?_,?_,hused,hFu,?_⟩ + · have hq : Fintype.card Q ≤ (∑ b, k b) + 2*∑ b, ∑ i, (X b i).card := by + calc + _ = ∑ b, Fintype.card (T b).Index := Fintype.card_sigma + _ ≤ ∑ b, (k b + 2 * ∑ i, (X b i).card) := Finset.sum_le_sum (fun b _ => (T b).count) + _ = _ := by rw [Finset.sum_add_distrib,← Finset.mul_sum] + have hs : Fintype.card S ≤ 6*∑ b, ∑ i, (X b i).card := by + calc + _ = ∑ b, (prep b).bad.card := by simp [S,Fintype.card_sigma] + _ ≤ ∑ b, 6*∑ i, (X b i).card := Finset.sum_le_sum (fun b _ => (prep b).bad_le) + _ = _ := by rw [← Finset.mul_sum] + rw [Fintype.card_sum]; omega + · rintro (j | z) + · exact hparts j + · exact Or.inr ⟨e z,SimpleGraph.edgeSet_mono hFG (hSF z),rfl⟩ + · rintro (i | i) (j | j) hij <;> dsimp only [Sum.elim_inl,Sum.elim_inr] + · exact hpartsd (fun h => hij (congrArg Sum.inl h)) + · exact (Set.disjoint_singleton_right).mpr (hbadpart j i) + · exact (Set.disjoint_singleton_left).mpr (hbadpart i j) + · exact Set.disjoint_singleton.mpr (fun h => hij (congrArg Sum.inr (hinj h))) + · simp only [Set.iUnion_sum,Sum.elim_inl,Sum.elim_inr] + rw [hcover] + calc + _ = ((⋃ z : S, {e z}) ∪ (⋃ w : Q, (q w).edges)) ∪ used := by + rw [Set.union_comm ((⋃ w : Q, (q w).edges) ∪ used), Set.union_assoc] + _ = _ := by rw [horiginal] + +end +end ErdosGallai.Batch + +end +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/CycleDecomposition/BatchRouting.lean b/lean/OAI/Combinatorics/CycleDecomposition/BatchRouting.lean new file mode 100644 index 0000000000000000000000000000000000000000..08052d8a25c96f5d18725a087a622db45675c2da --- /dev/null +++ b/lean/OAI/Combinatorics/CycleDecomposition/BatchRouting.lean @@ -0,0 +1,1100 @@ +import OAI.Combinatorics.CycleDecomposition.BatchPreparation + +namespace OAI + +section +open Filter Asymptotics Real +open scoped Topology +noncomputable section +open MeasureTheory ProbabilityTheory Finset +section +namespace ErdosGallai.Batch +noncomputable section +open Finset SimpleGraph +attribute [local instance] Classical.propDecidable + +lemma family_quotient_image_order {V I : Type} [Fintype V] [Fintype I] + (X : I → Finset V) (hd : Pairwise fun i j => Disjoint (X i) (X j)) + (p : ∀ i, PairingSpace (X i)) (W : Finset V) (hX : ∀ i, X i ⊆ W) : + (W.image (familyProject X hd p)).card + ∑ i, (X i).card / 2 = W.card := by + classical + let projMap := familyProject X hd p + have hi : Set.InjOn projMap (↑Wᶜ : Set V) := by + intro x hx y hy h + rcases (familyProject_eq_iff X hd p x y).mp h with he | ⟨i,hx',hy',_⟩ + · exact he + · exact False.elim (Finset.mem_compl.mp hx (hX i hx')) + have hd' : Disjoint (W.image projMap) (Wᶜ.image projMap) := by + apply Finset.disjoint_left.mpr + rintro z hz hz' + obtain ⟨x,hx,rfl⟩ := Finset.mem_image.mp hz + obtain ⟨y,hy,he⟩ := Finset.mem_image.mp hz' + rcases (familyProject_eq_iff X hd p y x).mp he with he | ⟨i,hy',hx',_⟩ + · subst y; exact Finset.mem_compl.mp hy hx + · exact Finset.mem_compl.mp hy (hX i hy') + have hu : W.image projMap ∪ Wᶜ.image projMap = univ := by + rw [← Finset.image_union,Finset.union_compl] + exact Finset.image_univ_of_surjective (familyProject_surjective X hd p) + have hc := Finset.card_union_of_disjoint hd' + rw [hu,Finset.card_univ,Finset.card_image_of_injOn hi] at hc + have hc' := Finset.card_compl W + have h := family_quotient_order_add X hd p + dsimp only [projMap] at hc + have hWcard := Finset.card_le_univ W + omega + +lemma PreparedBatch.quotient_supported {V I : Type} [Fintype V] [Fintype I] + {G : SimpleGraph V} {X : I → Finset V} {hd} + (b : PreparedBatch G X hd) (W : Finset V) + (hW : ∀ ⦃x y⦄, G.Adj x y → x ∈ W ∧ y ∈ W) : + ∀ ⦃x y⦄, b.quotient.Adj x y → + x ∈ W.image (familyProject X hd b.pairing) ∧ + y ∈ W.image (familyProject X hd b.pairing) := by + classical + intro x y hxy + have he : s(x,y) ∈ b.quotient.edgeSet := hxy + rw [b.quotient_edges] at he + obtain ⟨e,he,heq⟩ := he + induction e using Sym2.ind with + | _ u v => + have huv : G.Adj u v := b.retained_subset he + have hu := Finset.mem_image_of_mem (familyProject X hd b.pairing) (hW huv).1 + have hv := Finset.mem_image_of_mem (familyProject X hd b.pairing) (hW huv).2 + change s(familyProject X hd b.pairing u,familyProject X hd b.pairing v) = s(x,y) at heq + rcases Sym2.eq_iff.mp heq with ⟨rfl,rfl⟩ | ⟨rfl,rfl⟩ + · exact ⟨hu,hv⟩ + · exact ⟨hv,hu⟩ + +end +end ErdosGallai.Batch + +namespace ErdosGallai.Batch + +open Finset + +variable {V : Type} [Fintype V] [DecidableEq V] + +def CutExpansion (P : SimpleGraph V) [DecidableRel P.Adj] (h : ℝ) : Prop := + ∀ U : Finset V, h * min (U.card : ℝ) (Uᶜ.card : ℝ) ≤ + ((P.interedges U Uᶜ).card : ℝ) + +lemma boundary_sym2_injective (P : SimpleGraph V) [DecidableRel P.Adj] + (U : Finset V) : + Set.InjOn (fun e : V × V => s(e.1, e.2)) (P.interedges U Uᶜ : Set (V × V)) := by + intro e he f hf hef + rcases (Sym2.mk_eq_mk_iff.mp hef) with h | h + · exact h + · have he1 := (P.mem_interedges_iff.mp he).1 + have hf2 := (P.mem_interedges_iff.mp hf).2.1 + have hfirst : e.1 = f.2 := congrArg Prod.fst h + exact False.elim ((Finset.mem_compl.mp hf2) (hfirst ▸ he1)) + +lemma deleted_boundary_card_le (P : SimpleGraph V) [DecidableRel P.Adj] + (U : Finset V) (F : Finset (Sym2 V)) : + ((P.interedges U Uᶜ).filter (fun e => s(e.1, e.2) ∈ F)).card ≤ F.card := by + apply Finset.card_le_card_of_injOn (fun e : V × V => s(e.1, e.2)) + · intro e he + exact (Finset.mem_filter.mp he).2 + · exact (boundary_sym2_injective P U).mono (by + intro e he + exact (Finset.mem_filter.mp he).1) + +theorem routing_union_growth_step_of_boundary + (P : SimpleGraph V) [DecidableRel P.Adj] + (h : ℝ) (hexp : CutExpansion P h) + (hr : 0 < (Fintype.card V : ℝ)) + (F : Finset (Sym2 V)) (B Bnext : Finset V) + (W : V → Finset V) + (hmono : B ⊆ Bnext) + (hsmall : (B.card : ℝ) ≤ (Fintype.card V : ℝ) / 2) + (hF : (((P.interedges B Bᶜ).filter (fun e => s(e.1, e.2) ∈ F)).card : ℝ) ≤ + h * (B.card : ℝ) / 4) + (hW : ∀ v ∈ B, ((W v).card : ℝ) ≤ h / 4) + (hextend : ∀ v ∈ B, ∀ w ∉ B, P.Adj v w → s(v, w) ∉ F → + w ∉ W v → w ∈ Bnext) : + (1 + h / (2 * (Fintype.card V : ℝ))) * (B.card : ℝ) ≤ + (Bnext.card : ℝ) := by + let E := P.interedges B Bᶜ + let Ebad := E.filter (fun e => s(e.1, e.2) ∈ F) + let Vbad := B.biUnion (fun v => ({v} : Finset V) ×ˢ (W v)) + let Enew := (Finset.univ : Finset V) ×ˢ (Bnext \ B) + have hcover : E ⊆ Ebad ∪ Vbad ∪ Enew := by + intro e he + rcases P.mem_interedges_iff.mp he with ⟨hv, hw, hadj⟩ + have hnw : e.2 ∉ B := Finset.mem_compl.mp hw + by_cases hdel : s(e.1, e.2) ∈ F + · exact Finset.mem_union_left _ (Finset.mem_union_left _ + (Finset.mem_filter.mpr ⟨he, hdel⟩)) + by_cases hforbid : e.2 ∈ W e.1 + · apply Finset.mem_union_left + apply Finset.mem_union_right + apply Finset.mem_biUnion.mpr + exact ⟨e.1, hv, Finset.mem_product.mpr ⟨by simp, hforbid⟩⟩ + · apply Finset.mem_union_right + exact Finset.mem_product.mpr ⟨Finset.mem_univ _, Finset.mem_sdiff.mpr + ⟨hextend e.1 hv e.2 hnw hadj hdel hforbid, hnw⟩⟩ + have hcount : E.card ≤ Ebad.card + Vbad.card + Enew.card := + (Finset.card_le_card hcover).trans <| + (Finset.card_union_le _ _).trans <| + Nat.add_le_add_right (Finset.card_union_le _ _) _ + have hforbidden : Vbad.card ≤ ∑ v ∈ B, (W v).card := by + simpa [Vbad, Finset.card_product] using + (Finset.card_biUnion_le (s := B) (t := fun v => ({v} : Finset V) ×ˢ W v)) + have hnew : Enew.card = Fintype.card V * (Bnext \ B).card := by + simp [Enew] + have hraw : E.card ≤ Ebad.card + (∑ v ∈ B, (W v).card) + + Fintype.card V * (Bnext \ B).card := by omega + have hsum : (∑ v ∈ B, ((W v).card : ℝ)) ≤ (h / 4) * B.card := by + calc + _ ≤ ∑ _v ∈ B, h / 4 := Finset.sum_le_sum hW + _ = _ := by simp [mul_comm] + have hcomplN : B.card + Bᶜ.card = Fintype.card V := by + rw [Finset.card_compl] + exact Nat.add_sub_of_le (Finset.card_le_univ B) + have hcompl : (B.card : ℝ) + (Bᶜ.card : ℝ) = (Fintype.card V : ℝ) := by + exact_mod_cast hcomplN + have hlecompl : (B.card : ℝ) ≤ (Bᶜ.card : ℝ) := by linarith + have hcut : h * (B.card : ℝ) ≤ (E.card : ℝ) := by + simpa [min_eq_left hlecompl, E] using hexp B + have hdiffN : (Bnext \ B).card + B.card = Bnext.card := by + rw [Finset.card_sdiff_of_subset hmono] + exact Nat.sub_add_cancel (Finset.card_le_card hmono) + have hdiff : ((Bnext \ B).card : ℝ) + (B.card : ℝ) = (Bnext.card : ℝ) := by + exact_mod_cast hdiffN + have hrawR : (E.card : ℝ) ≤ (Ebad.card : ℝ) + + (∑ v ∈ B, ((W v).card : ℝ)) + + (Fintype.card V : ℝ) * ((Bnext \ B).card : ℝ) := by + exact_mod_cast hraw + have hreach : h * (B.card : ℝ) / 2 ≤ + (Fintype.card V : ℝ) * ((Bnext \ B).card : ℝ) := by + nlinarith [hcut, hrawR, hF, hsum] + have hdiv : h * (B.card : ℝ) / (2 * (Fintype.card V : ℝ)) ≤ + ((Bnext \ B).card : ℝ) := by + apply (div_le_iff₀ (by positivity : 0 < 2 * (Fintype.card V : ℝ))).mpr + nlinarith [hreach] + calc + (1 + h / (2 * (Fintype.card V : ℝ))) * (B.card : ℝ) + = (B.card : ℝ) + h * (B.card : ℝ) / (2 * (Fintype.card V : ℝ)) := by ring + _ ≤ (B.card : ℝ) + ((Bnext \ B).card : ℝ) := add_le_add (le_refl _) hdiv + _ = (Bnext.card : ℝ) := by linarith + +theorem routing_union_growth_step + (P : SimpleGraph V) [DecidableRel P.Adj] + (h : ℝ) (hexp : CutExpansion P h) + (hr : 0 < (Fintype.card V : ℝ)) + (F : Finset (Sym2 V)) (B Bnext : Finset V) + (W : V → Finset V) + (hmono : B ⊆ Bnext) + (hsmall : (B.card : ℝ) ≤ (Fintype.card V : ℝ) / 2) + (hF : (F.card : ℝ) ≤ h * (B.card : ℝ) / 4) + (hW : ∀ v ∈ B, ((W v).card : ℝ) ≤ h / 4) + (hextend : ∀ v ∈ B, ∀ w ∉ B, P.Adj v w → s(v, w) ∉ F → + w ∉ W v → w ∈ Bnext) : + (1 + h / (2 * (Fintype.card V : ℝ))) * (B.card : ℝ) ≤ + (Bnext.card : ℝ) := by + apply routing_union_growth_step_of_boundary P h hexp hr F B Bnext W hmono hsmall + · have hd : (((P.interedges B Bᶜ).filter (fun e => s(e.1, e.2) ∈ F)).card : ℝ) ≤ F.card := by + exact_mod_cast deleted_boundary_card_le P B F + exact hd.trans hF + · exact hW + · exact hextend + +def avoidGraph (P : SimpleGraph V) (F : Finset (Sym2 V)) (W : Finset V) : + SimpleGraph V where + Adj v w := P.Adj v w ∧ s(v, w) ∉ F ∧ v ∉ W ∧ w ∉ W + symm := ⟨by + intro v w h + exact ⟨h.1.symm, by simpa only [Sym2.eq_swap] using h.2.1, h.2.2.2, h.2.2.1⟩⟩ + loopless := ⟨by intro v h; exact P.irrefl h.1⟩ + +noncomputable def walkBall (G : SimpleGraph V) (s : V) (t : ℕ) : Finset V := by + classical + exact Finset.univ.filter (fun v => ∃ p : G.Walk s v, p.length ≤ t) + +@[simp] lemma mem_walkBall {V : Type} [_contextInstance1 : Fintype V] [_contextInstance2 : DecidableEq V] (G : SimpleGraph V) (s v : V) (t : ℕ) : + v ∈ walkBall G s t ↔ ∃ p : G.Walk s v, p.length ≤ t := by + classical + simp [walkBall] + +lemma root_mem_walkBall (G : SimpleGraph V) (s : V) (t : ℕ) : + s ∈ walkBall G s t := by + exact (mem_walkBall G s s t).mpr ⟨.nil, by simp⟩ + +lemma walkBall_mono (G : SimpleGraph V) (s : V) {t u : ℕ} (htu : t ≤ u) : + walkBall G s t ⊆ walkBall G s u := by + intro v hv + obtain ⟨p, hp⟩ := (mem_walkBall G s v t).mp hv + exact (mem_walkBall G s v u).mpr ⟨p, hp.trans htu⟩ + +lemma walk_avoids_end {V : Type} [_contextInstance1 : Fintype V] [_contextInstance2 : DecidableEq V] (P : SimpleGraph V) (F : Finset (Sym2 V)) (W : Finset V) + {s v : V} (p : (avoidGraph P F W).Walk s v) (hs : s ∉ W) : v ∉ W := by + induction p with + | nil => exact hs + | cons hadj p ih => exact ih hadj.2.2.2 + +lemma ball_avoids (P : SimpleGraph V) (F : Finset (Sym2 V)) (W : Finset V) + (s : V) (hs : s ∉ W) (t : ℕ) : Disjoint (walkBall (avoidGraph P F W) s t) W := by + apply Finset.disjoint_left.mpr + intro v hv + obtain ⟨p, _⟩ := (mem_walkBall _ _ _ _).mp hv + exact walk_avoids_end P F W p hs + +lemma walkBall_step (G : SimpleGraph V) (s v w : V) (t : ℕ) + (hv : v ∈ walkBall G s t) (hadj : G.Adj v w) : + w ∈ walkBall G s (t + 1) := by + obtain ⟨p, hp⟩ := (mem_walkBall _ _ _ _).mp hv + apply (mem_walkBall _ _ _ _).mpr + exact ⟨p.concat hadj, by simpa using Nat.add_le_add_right hp 1⟩ + +noncomputable def rootBallUnion (P : SimpleGraph V) (F : Finset (Sym2 V)) + (W : V → Finset V) (A : Finset V) (t : ℕ) : Finset V := + A.biUnion (fun s => walkBall (avoidGraph P F (W s)) s t) + +lemma rootBallUnion_mono_time (P : SimpleGraph V) (F : Finset (Sym2 V)) + (W : V → Finset V) (A : Finset V) {t u : ℕ} (htu : t ≤ u) : + rootBallUnion P F W A t ⊆ rootBallUnion P F W A u := + Finset.biUnion_mono (fun s _ => walkBall_mono _ s htu) + +lemma roots_subset_rootBallUnion (P : SimpleGraph V) (F : Finset (Sym2 V)) + (W : V → Finset V) (A : Finset V) (t : ℕ) : A ⊆ rootBallUnion P F W A t := by + intro s hs + exact Finset.mem_biUnion.mpr ⟨s, hs, root_mem_walkBall _ _ _⟩ + +theorem rootBallUnion_growth_step + (P : SimpleGraph V) [DecidableRel P.Adj] + (h : ℝ) (hexp : CutExpansion P h) + (hr : 0 < (Fintype.card V : ℝ)) + (F : Finset (Sym2 V)) (W : V → Finset V) (A : Finset V) (t : ℕ) + (hroots : ∀ s ∈ A, s ∉ W s) + (hW : ∀ s ∈ A, ((W s).card : ℝ) ≤ h / 4) + (hsmall : ((rootBallUnion P F W A t).card : ℝ) ≤ (Fintype.card V : ℝ) / 2) + (hF : (F.card : ℝ) ≤ h * (rootBallUnion P F W A t).card / 4) : + (1 + h / (2 * (Fintype.card V : ℝ))) * (rootBallUnion P F W A t).card ≤ + ((rootBallUnion P F W A (t + 1)).card : ℝ) := by + classical + let B := rootBallUnion P F W A t + have hchoose : ∀ v ∈ B, ∃ s ∈ A, v ∈ walkBall (avoidGraph P F (W s)) s t := by + intro v hv + exact Finset.mem_biUnion.mp hv + choose s hsA hreach using hchoose + let forbid : V → Finset V := fun v => if hv : v ∈ B then W (s v hv) else ∅ + apply routing_union_growth_step P h hexp hr F B (rootBallUnion P F W A (t + 1)) forbid + (rootBallUnion_mono_time P F W A (Nat.le_succ t)) hsmall hF + · intro v hv + simpa only [forbid, dite_eq_left hv] using hW (s v hv) (hsA v hv) + · intro v hv w _ hadj hdel hforbid + have hvs : v ∈ walkBall (avoidGraph P F (W (s v hv))) (s v hv) t := hreach v hv + have hnv : v ∉ W (s v hv) := + (Finset.disjoint_left.mp (ball_avoids P F (W (s v hv)) (s v hv) + (hroots (s v hv) (hsA v hv)) t)) hvs + have hnw : w ∉ W (s v hv) := by simpa only [forbid, dite_eq_left hv] using hforbid + exact Finset.mem_biUnion.mpr ⟨s v hv, hsA v hv, + walkBall_step _ _ v w t hvs ⟨hadj, hdel, hnv, hnw⟩⟩ + +theorem rootBallUnion_growth_block + (P : SimpleGraph V) [DecidableRel P.Adj] + (h : ℝ) (hh : 0 ≤ h) (hexp : CutExpansion P h) + (hr : 0 < (Fintype.card V : ℝ)) + (F : Finset (Sym2 V)) (W : V → Finset V) (A : Finset V) (t g : ℕ) + (hroots : ∀ s ∈ A, s ∉ W s) + (hW : ∀ s ∈ A, ((W s).card : ℝ) ≤ h / 4) + (hpos : 1 ≤ (rootBallUnion P F W A t).card) + (hF : (F.card : ℝ) ≤ h * (rootBallUnion P F W A t).card / 4) + (hg : (Fintype.card V : ℝ) / 2 < (1 + h / (2 * (Fintype.card V : ℝ))) ^ g) : + (Fintype.card V : ℝ) / 2 < (rootBallUnion P F W A (t + g)).card := by + by_contra hnot + have hend := le_of_not_gt hnot + let b : ℕ → ℝ := fun j => (rootBallUnion P F W A (t + j)).card + let c : ℝ := 1 + h / (2 * (Fintype.card V : ℝ)) + have hc : 0 ≤ c := by dsimp [c]; positivity + have hmono : Monotone b := by + intro j k hjk + dsimp [b] + exact_mod_cast Finset.card_le_card + (rootBallUnion_mono_time P F W A (Nat.add_le_add_left hjk t)) + have hbase : 1 ≤ b 0 := by dsimp [b]; simpa using (Nat.cast_le (α := ℝ)).mpr hpos + have hstep : ∀ j < g, c * b j ≤ b (j + 1) := by + intro j hj + have hsmall : b j ≤ (Fintype.card V : ℝ) / 2 := + (hmono (Nat.le_of_lt hj)).trans hend + have hFj : (F.card : ℝ) ≤ h * (rootBallUnion P F W A (t + j)).card / 4 := by + have hbj := hmono (Nat.zero_le j) + dsimp [b] at hbj + nlinarith + simpa only [c, b, Nat.add_assoc] using + rootBallUnion_growth_step P h hexp hr F W A (t + j) hroots hW hsmall hFj + have hpow : ∀ j ≤ g, c ^ j ≤ b j := by + intro j + induction j with + | zero => intro _; simpa using hbase + | succ j ih => + intro hjg + calc + c ^ (j + 1) = c * c ^ j := by rw [pow_succ]; ring + _ ≤ c * b j := mul_le_mul_of_nonneg_left (ih (by omega)) hc + _ ≤ b (j + 1) := hstep j (by omega) + exact (not_lt_of_ge ((hpow g le_rfl).trans hend)) hg + +lemma rootBallUnion_halve (P : SimpleGraph V) (F : Finset (Sym2 V)) + (W : V → Finset V) (A : Finset V) (t k : ℕ) (u : ℝ) + (hcard : A.card ≤ 2 * k) + (hlarge : 2 * u < (rootBallUnion P F W A t).card) : + ∃ A' ⊆ A, A'.card ≤ k ∧ u < (rootBallUnion P F W A' t).card := by + obtain ⟨A₁, hsub, hcard₁⟩ := Finset.exists_subset_card_eq (min_le_right k A.card) + let A₂ := A \ A₁ + have hcard₂ : A₂.card ≤ k := by + dsimp [A₂] + rw [Finset.card_sdiff_of_subset hsub, hcard₁] + omega + have hcover : A₁ ∪ A₂ = A := Finset.union_sdiff_of_subset hsub + have hcount : (rootBallUnion P F W A t).card ≤ + (rootBallUnion P F W A₁ t).card + (rootBallUnion P F W A₂ t).card := by + conv_lhs => rw [← hcover] + simp only [rootBallUnion, Finset.union_biUnion] + exact Finset.card_union_le _ _ + by_cases hfirst : u < (rootBallUnion P F W A₁ t).card + · exact ⟨A₁, hsub, hcard₁ ▸ min_le_left _ _, hfirst⟩ + · refine ⟨A₂, Finset.sdiff_subset, hcard₂, ?_⟩ + have hcR : ((rootBallUnion P F W A t).card : ℝ) ≤ + (rootBallUnion P F W A₁ t).card + (rootBallUnion P F W A₂ t).card := by + exact_mod_cast hcount + linarith + +theorem rootBallUnion_extract_root + (P : SimpleGraph V) [DecidableRel P.Adj] + (h : ℝ) (hh : 0 < h) (hexp : CutExpansion P h) + (hr : 0 < (Fintype.card V : ℝ)) + (F : Finset (Sym2 V)) (W : V → Finset V) (g N : ℕ) + (hFglobal : (F.card : ℝ) ≤ h * (Fintype.card V : ℝ) / 16) + (hg : (Fintype.card V : ℝ) / 2 < (1 + h / (2 * (Fintype.card V : ℝ))) ^ g) : + ∀ (A : Finset V) (t : ℕ), + (∀ s ∈ A, s ∉ W s) → + (∀ s ∈ A, ((W s).card : ℝ) ≤ h / 4) → + A.card ≤ 2 ^ N → + (Fintype.card V : ℝ) / 2 < (rootBallUnion P F W A t).card → + ∃ s ∈ A, (Fintype.card V : ℝ) / 2 < + (walkBall (avoidGraph P F (W s)) s (t + N * g)).card := by + induction N with + | zero => + intro A t hroots hW hcard hlarge + have hne : A.Nonempty := by + by_contra h + have he : A = ∅ := Finset.not_nonempty_iff_eq_empty.mp h + simp [he, rootBallUnion] at hlarge + linarith + obtain ⟨s, hs⟩ := hne + have he : A = {s} := Finset.eq_singleton_iff_unique_mem.mpr + ⟨hs, fun v hv => (Finset.card_le_one.mp (by simpa using hcard)) v hv s hs⟩ + refine ⟨s, hs, ?_⟩ + simpa [he, rootBallUnion] using hlarge + | succ N ih => + intro A t hroots hW hcard hlarge + have hcard' : A.card ≤ 2 * 2 ^ N := by simpa [pow_succ, Nat.mul_comm] using hcard + obtain ⟨A', hsub, hcard', hlarge'⟩ := rootBallUnion_halve P F W A t (2 ^ N) + ((Fintype.card V : ℝ) / 4) hcard' (by linarith) + have hF' : (F.card : ℝ) ≤ h * (rootBallUnion P F W A' t).card / 4 := by + nlinarith + have hpos : 1 ≤ (rootBallUnion P F W A' t).card := by + have : 0 < ((rootBallUnion P F W A' t).card : ℝ) := by linarith + exact_mod_cast this + have hroots' : ∀ s ∈ A', s ∉ W s := fun s hs => hroots s (hsub hs) + have hW' : ∀ s ∈ A', ((W s).card : ℝ) ≤ h / 4 := fun s hs => hW s (hsub hs) + have hnext := rootBallUnion_growth_block P h hh.le hexp hr F W A' t g + hroots' hW' hpos hF' hg + obtain ⟨s, hs, hb⟩ := ih A' (t + g) hroots' hW' hcard' hnext + refine ⟨s, hsub hs, ?_⟩ + have ht : t + (N + 1) * g = t + g + N * g := by ring + simpa only [Nat.succ_eq_add_one, ht] using hb + +lemma CutExpansion.le_order (P : SimpleGraph V) [DecidableRel P.Adj] + (h : ℝ) (hexp : CutExpansion P h) (hr : 2 ≤ Fintype.card V) : + h ≤ (Fintype.card V : ℝ) := by + obtain ⟨v⟩ := Fintype.card_pos_iff.mp (by omega : 0 < Fintype.card V) + have hcomplN : 1 ≤ ({v} : Finset V)ᶜ.card := by + simp only [Finset.card_compl, Finset.card_singleton] + omega + have hcompl : (1 : ℝ) ≤ (({v} : Finset V)ᶜ.card : ℝ) := by exact_mod_cast hcomplN + have hc := hexp {v} + simp only [Finset.card_singleton, Nat.cast_one, min_eq_left hcompl, mul_one] at hc + have hupper := P.card_interedges_le_mul ({v} : Finset V) ({v} : Finset V)ᶜ + simp only [Finset.card_singleton, one_mul] at hupper + have hle := (Finset.card_le_univ (({v} : Finset V)ᶜ)) + exact hc.trans (by exact_mod_cast hupper.trans hle) + +noncomputable def routingG (r h : ℝ) : ℕ := ⌈8 * (r / h) * Real.logb 2 (2 * r)⌉₊ + +noncomputable def routingDepth (r : ℝ) : ℕ := ⌈Real.logb 2 r⌉₊ + +noncomputable def routingLength (r h : ℝ) : ℕ := 2 * routingG r h * (1 + routingDepth r) + +lemma routingG_growth (r h : ℝ) (hr : 1 ≤ r) (hh : 0 < h) (hhr : h ≤ r) : + r / 2 < (1 + h / (2 * r)) ^ routingG r h := by + have hr0 : 0 < r := by linarith + let x := h / (2 * r) + have hx0 : 0 ≤ x := by dsimp [x]; positivity + have hxle : x ≤ 1 := by + dsimp [x] + apply (div_le_iff₀ (by positivity : 0 < 2 * r)).mpr + linarith + have hlog : h / (4 * r) ≤ Real.log (1 + h / (2 * r)) := by + have heq : h / (4 * r) = x / 2 := by dsimp [x]; ring + rw [heq] + calc + x / 2 ≤ 2 * x / (x + 2) := by + apply (le_div_iff₀ (by linarith : 0 < x + 2)).mpr + nlinarith [mul_nonneg hx0 (sub_nonneg.mpr hxle)] + _ ≤ Real.log (1 + x) := Real.le_log_one_add_of_nonneg hx0 + have hl2pos : 0 < Real.log 2 := Real.log_pos (by norm_num) + have hl2le : Real.log 2 ≤ 1 := by + have htwo := Real.log_le_sub_one_of_pos (by norm_num : (0 : ℝ) < 2) + norm_num at htwo ⊢ + exact htwo + have hlogpos : 0 < Real.log (2 * r) := Real.log_pos (by linarith) + have hbase : Real.log (2 * r) ≤ Real.logb 2 (2 * r) := by + rw [Real.logb] + apply (le_div_iff₀ hl2pos).mpr + nlinarith + have hg : 8 * (r / h) * Real.logb 2 (2 * r) ≤ (routingG r h : ℝ) := + Nat.le_ceil _ + have hlogpow : 2 * Real.log (2 * r) ≤ + Real.log ((1 + h / (2 * r)) ^ routingG r h) := by + rw [Real.log_pow] + calc + 2 * Real.log (2 * r) ≤ 2 * Real.logb 2 (2 * r) := by linarith + _ = (8 * (r / h) * Real.logb 2 (2 * r)) * (h / (4 * r)) := by + field_simp + ; ring + _ ≤ (routingG r h : ℝ) * (h / (4 * r)) := + mul_le_mul_of_nonneg_right hg (by positivity) + _ ≤ (routingG r h : ℝ) * Real.log (1 + h / (2 * r)) := + mul_le_mul_of_nonneg_left hlog (by positivity) + have hsmall : Real.log (r / 2) < 2 * Real.log (2 * r) := by + have := Real.log_le_log (by positivity : 0 < r / 2) (by linarith : r / 2 ≤ 2 * r) + linarith + apply (Real.log_lt_log_iff (by positivity : 0 < r / 2) (by positivity)).mp + exact hsmall.trans_le hlogpow + +lemma le_two_pow_routingDepth (r : ℕ) (hr : 0 < r) : r ≤ 2 ^ routingDepth r := by + have hrR : (0 : ℝ) < r := by exact_mod_cast hr + have hn := Nat.le_ceil (Real.logb 2 (r : ℝ)) + have hp := (Real.logb_le_iff_le_rpow (by norm_num : (1 : ℝ) < 2) hrR).mp hn + rw [Real.rpow_natCast] at hp + dsimp [routingDepth] + exact_mod_cast hp + +theorem routing_large_root_ball + (P : SimpleGraph V) [DecidableRel P.Adj] + (h : ℝ) (hh : 0 < h) (hexp : CutExpansion P h) (hr : 2 ≤ Fintype.card V) + (F : Finset (Sym2 V)) (W : V → Finset V) (S : Finset V) + (hne : S.Nonempty) + (hroots : ∀ s ∈ S, s ∉ W s) + (hW : ∀ s ∈ S, ((W s).card : ℝ) ≤ h / 4) + (hFstart : (F.card : ℝ) ≤ h * S.card / 4) + (hFglobal : (F.card : ℝ) ≤ h * (Fintype.card V : ℝ) / 16) : + ∃ s ∈ S, (Fintype.card V : ℝ) / 2 < + (walkBall (avoidGraph P F (W s)) s + (routingG (Fintype.card V) h * (1 + routingDepth (Fintype.card V)))).card := by + have hrpos : 0 < (Fintype.card V : ℝ) := by exact_mod_cast (by omega : 0 < Fintype.card V) + have hg := routingG_growth (Fintype.card V) h (by exact_mod_cast (by omega : 1 ≤ Fintype.card V)) + hh (hexp.le_order P h hr) + have hsub := roots_subset_rootBallUnion P F W S 0 + have hpos : 1 ≤ (rootBallUnion P F W S 0).card := + (Finset.card_pos.mpr hne).trans_le (Finset.card_le_card hsub) + have hF : (F.card : ℝ) ≤ h * (rootBallUnion P F W S 0).card / 4 := by + have hc : (S.card : ℝ) ≤ (rootBallUnion P F W S 0).card := by + exact_mod_cast Finset.card_le_card hsub + nlinarith + have hb := rootBallUnion_growth_block P h hh.le hexp hrpos F W S 0 + (routingG (Fintype.card V) h) hroots hW hpos hF hg + have hrootcard : S.card ≤ 2 ^ routingDepth (Fintype.card V) := + (Finset.card_le_univ S).trans (le_two_pow_routingDepth _ (by omega)) + obtain ⟨s, hs, hball⟩ := rootBallUnion_extract_root P h hh hexp hrpos F W + (routingG (Fintype.card V) h) (routingDepth (Fintype.card V)) + hFglobal hg S (routingG (Fintype.card V) h) hroots hW hrootcard (by simpa using hb) + refine ⟨s, hs, ?_⟩ + have ht : routingG (Fintype.card V) h * (1 + routingDepth (Fintype.card V)) = + routingG (Fintype.card V) h + routingDepth (Fintype.card V) * routingG (Fintype.card V) h := by ring + simpa only [ht] using hball + +def incidentEdges (F : Finset (Sym2 V)) (v : V) : Finset (Sym2 V) := + F.filter (fun e => v ∈ e) + +lemma incidentEdges_union {V : Type} [_contextInstance1 : Fintype V] [_contextInstance2 : DecidableEq V] (F E : Finset (Sym2 V)) (v : V) : + incidentEdges (F ∪ E) v = incidentEdges F v ∪ incidentEdges E v := by + simp [incidentEdges, Finset.filter_union] + +lemma incidentEdges_union_card_le (F E : Finset (Sym2 V)) (v : V) : + (incidentEdges (F ∪ E) v).card ≤ (incidentEdges F v).card + (incidentEdges E v).card := by + rw [incidentEdges_union] + exact Finset.card_union_le _ _ + +lemma incidentEdges_sum_le (F : Finset (Sym2 V)) : + ∑ v : V, (incidentEdges F v).card ≤ 2 * F.card := by + have heq : ∑ v : V, (incidentEdges F v).card = ∑ e ∈ F, e.toFinset.card := by + simp only [incidentEdges, Finset.card_eq_sum_ones, Finset.sum_filter] + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro e he + simp [← Sym2.mem_toFinset] + rw [heq] + calc + _ ≤ ∑ _e ∈ F, 2 := Finset.sum_le_sum (fun e _ => by + rw [Sym2.card_toFinset] + split <;> norm_num) + _ = 2 * F.card := by simp [mul_comm] + +lemma incidentEdges_path_start_le_one {V : Type} [_contextInstance1 : Fintype V] [_contextInstance2 : DecidableEq V] (G : SimpleGraph V) {s t : V} + (p : G.Walk s t) (hp : p.IsPath) : + (incidentEdges p.edges.toFinset s).card ≤ 1 := by + have hsub : incidentEdges p.edges.toFinset s ⊆ {s(s, p.snd)} := by + intro e he + obtain ⟨heP, hs⟩ := Finset.mem_filter.mp he + obtain ⟨v, hev⟩ := Sym2.mem_iff_exists.mp hs + subst e + have hv := hp.eq_snd_of_mem_edges (List.mem_toFinset.mp heP) + simp [hv] + exact (Finset.card_le_card hsub).trans (by simp) + +lemma incidentEdges_path_end_le_one (G : SimpleGraph V) {s t : V} + (p : G.Walk s t) (hp : p.IsPath) : + (incidentEdges p.edges.toFinset t).card ≤ 1 := by + simpa using incidentEdges_path_start_le_one G p.reverse hp.reverse + +lemma incidentEdges_walk_eq_empty_of_not_mem {V : Type} [_contextInstance1 : Fintype V] [_contextInstance2 : DecidableEq V] (G : SimpleGraph V) {s t v : V} + (p : G.Walk s t) (hv : v ∉ p.support) : incidentEdges p.edges.toFinset v = ∅ := by + apply Finset.eq_empty_iff_forall_notMem.mpr + intro e he + obtain ⟨heP, hve⟩ := Finset.mem_filter.mp he + have hm := p.mem_support_iff_exists_mem_edges.mpr (Or.inr ⟨e, List.mem_toFinset.mp heP, hve⟩) + exact hv hm + +lemma incidentEdges_path_le_two (G : SimpleGraph V) {s t : V} + (p : G.Walk s t) (hp : p.IsPath) (v : V) : + (incidentEdges p.edges.toFinset v).card ≤ 2 := by + by_cases hv : v ∈ p.support + · have htake := incidentEdges_path_end_le_one G (p.takeUntil v hv) (hp.takeUntil hv) + have hdrop := incidentEdges_path_start_le_one G (p.dropUntil v hv) (hp.dropUntil hv) + have heq : p.edges.toFinset = (p.takeUntil v hv).edges.toFinset ∪ (p.dropUntil v hv).edges.toFinset := by + have he := congrArg (fun q : G.Walk s t => q.edges.toFinset) (p.take_spec hv) + simpa only [SimpleGraph.Walk.edges_append, List.toFinset_append] using he.symm + rw [heq] + exact (incidentEdges_union_card_le _ _ v).trans (by omega) + · rw [incidentEdges_walk_eq_empty_of_not_mem G p hv] + simp + +lemma deleted_boundary_card_le_incidents (P : SimpleGraph V) [DecidableRel P.Adj] + (B : Finset V) (F : Finset (Sym2 V)) : + ((P.interedges B Bᶜ).filter (fun e => s(e.1, e.2) ∈ F)).card ≤ + ∑ v ∈ B, (incidentEdges F v).card := by + let T := B.biUnion (fun v => ({v} : Finset V) ×ˢ incidentEdges F v) + have hc : ((P.interedges B Bᶜ).filter (fun e => s(e.1, e.2) ∈ F)).card ≤ T.card := by + apply Finset.card_le_card_of_injOn (fun e : V × V => (e.1, s(e.1, e.2))) + · intro e he + obtain ⟨heP, heF⟩ := Finset.mem_filter.mp he + apply Finset.mem_biUnion.mpr + refine ⟨e.1, (P.mem_interedges_iff.mp heP).1, Finset.mem_product.mpr ⟨by simp, ?_⟩⟩ + exact Finset.mem_filter.mpr ⟨heF, by simp⟩ + · intro e he f hf heq + have hsym := congrArg Prod.snd heq + exact boundary_sym2_injective P B (Finset.mem_filter.mp he).1 + (Finset.mem_filter.mp hf).1 hsym + have hT : T.card ≤ ∑ v ∈ B, (incidentEdges F v).card := by + simpa [T] using Finset.card_biUnion_le (s := B) + (t := fun v => ({v} : Finset V) ×ˢ incidentEdges F v) + exact hc.trans hT + +lemma walkBall_growth_of_incidents (P : SimpleGraph V) [DecidableRel P.Adj] + (h : ℝ) (hexp : CutExpansion P h) (hr : 0 < (Fintype.card V : ℝ)) + (F : Finset (Sym2 V)) (W : Finset V) (s : V) (hs : s ∉ W) + (hF : ∀ v, ((incidentEdges F v).card : ℝ) ≤ h / 4) + (hW : (W.card : ℝ) ≤ h / 4) (t : ℕ) + (hsmall : ((walkBall (avoidGraph P F W) s t).card : ℝ) ≤ (Fintype.card V : ℝ) / 2) : + (1 + h / (2 * (Fintype.card V : ℝ))) * (walkBall (avoidGraph P F W) s t).card ≤ + ((walkBall (avoidGraph P F W) s (t + 1)).card : ℝ) := by + classical + apply routing_union_growth_step_of_boundary P h hexp hr F _ _ (fun _ => W) + (walkBall_mono _ s (Nat.le_succ t)) hsmall + · calc + _ ≤ ∑ v ∈ walkBall (avoidGraph P F W) s t, ((incidentEdges F v).card : ℝ) := by + exact_mod_cast deleted_boundary_card_le_incidents P (walkBall (avoidGraph P F W) s t) F + _ ≤ ∑ _v ∈ walkBall (avoidGraph P F W) s t, h / 4 := Finset.sum_le_sum (fun v _ => hF v) + _ = _ := by simp; ring + · exact fun _ _ => hW + · intro v hv w _ hadj hdel hw + have hnv := Finset.disjoint_left.mp (ball_avoids P F W s hs t) hv + exact walkBall_step _ s v w t hv ⟨hadj, hdel, hnv, hw⟩ + +lemma walkBall_large_of_incidents (P : SimpleGraph V) [DecidableRel P.Adj] + (h : ℝ) (hh : 0 < h) (hexp : CutExpansion P h) (hr : 2 ≤ Fintype.card V) + (F : Finset (Sym2 V)) (W : Finset V) (s : V) (hs : s ∉ W) + (hF : ∀ v, ((incidentEdges F v).card : ℝ) ≤ h / 4) + (hW : (W.card : ℝ) ≤ h / 4) : + (Fintype.card V : ℝ) / 2 < + (walkBall (avoidGraph P F W) s (routingG (Fintype.card V) h)).card := by + have hrR : (2 : ℝ) ≤ Fintype.card V := by exact_mod_cast hr + have hr0 : (0 : ℝ) < Fintype.card V := by linarith + let g := routingG (Fintype.card V) h + let c : ℝ := 1 + h / (2 * (Fintype.card V : ℝ)) + have hc : 0 ≤ c := by dsimp [c]; positivity + by_contra hnot + have hend := le_of_not_gt hnot + have hpow : ∀ j ≤ g, c ^ j ≤ (walkBall (avoidGraph P F W) s j).card := by + intro j + induction j with + | zero => + intro _ + have H := Finset.card_pos.mpr ⟨s, root_mem_walkBall (avoidGraph P F W) s 0⟩ + have H' : 1 ≤ (walkBall (avoidGraph P F W) s 0).card := H + simpa using (Nat.cast_le (α := ℝ)).mpr H' + | succ j ih => + intro hj + have hmono : ((walkBall (avoidGraph P F W) s j).card : ℝ) ≤ + (walkBall (avoidGraph P F W) s g).card := by + exact_mod_cast Finset.card_le_card (walkBall_mono (avoidGraph P F W) s (by omega : j ≤ g)) + have hsmall := hmono.trans hend + calc + c ^ (j + 1) = c * c ^ j := by rw [pow_succ]; ring + _ ≤ c * (walkBall (avoidGraph P F W) s j).card := mul_le_mul_of_nonneg_left (ih (by omega)) hc + _ ≤ (walkBall (avoidGraph P F W) s (j + 1)).card := + walkBall_growth_of_incidents P h hexp hr0 F W s hs hF hW j hsmall + have hg := routingG_growth (Fintype.card V) h (by linarith) hh (hexp.le_order P h hr) + exact (not_lt_of_ge ((hpow g le_rfl).trans hend)) hg + +lemma exists_short_avoiding_path (P : SimpleGraph V) [DecidableRel P.Adj] + (h : ℝ) (hh : 0 < h) (hexp : CutExpansion P h) (hr : 2 ≤ Fintype.card V) + (F : Finset (Sym2 V)) (W : Finset V) (s t : V) (hs : s ∉ W) (ht : t ∉ W) + (hF : ∀ v, ((incidentEdges F v).card : ℝ) ≤ h / 4) + (hW : (W.card : ℝ) ≤ h / 4) : + ∃ q : (avoidGraph P F W).Walk s t, q.IsPath ∧ + q.length ≤ 2 * routingG (Fintype.card V) h := by + classical + let g := routingG (Fintype.card V) h + let B₁ := walkBall (avoidGraph P F W) s g + let B₂ := walkBall (avoidGraph P F W) t g + have h₁ := walkBall_large_of_incidents P h hh hexp hr F W s hs hF hW + have h₂ := walkBall_large_of_incidents P h hh hexp hr F W t ht hF hW + have hmeet : (B₁ ∩ B₂).Nonempty := by + apply Finset.card_pos.mp + have hc := Finset.card_union_add_card_inter B₁ B₂ + have hu := Finset.card_le_univ (B₁ ∪ B₂) + have hsum : (Fintype.card V : ℝ) < (B₁.card : ℝ) + (B₂.card : ℝ) := by + dsimp [B₁, B₂, g]; linarith + have hsumN : Fintype.card V < B₁.card + B₂.card := by exact_mod_cast hsum + omega + obtain ⟨v, hv⟩ := hmeet + obtain ⟨p₁, hp₁⟩ := (mem_walkBall _ s v g).mp (Finset.mem_inter.mp hv).1 + obtain ⟨p₂, hp₂⟩ := (mem_walkBall _ t v g).mp (Finset.mem_inter.mp hv).2 + let w := p₁.append p₂.reverse + refine ⟨w.bypass, w.bypass_isPath, w.length_bypass_le_length.trans ?_⟩ + dsimp [w] + simp only [SimpleGraph.Walk.length_append, SimpleGraph.Walk.length_reverse] + omega + +lemma two_routingG_le_length (r h : ℝ) : 2 * routingG r h ≤ routingLength r h := by + dsimp [routingLength] + exact Nat.le_mul_of_pos_right _ (by omega) + +lemma routingLength_bounds (r h : ℝ) (hr : 1 ≤ r) (hh : 0 < h) : + 1 ≤ routingLength r h ∧ r ≤ (routingLength r h : ℝ) * h := by + have hl2 : 0 < Real.log 2 := Real.log_pos (by norm_num) + have hlog : 1 ≤ Real.logb 2 (2 * r) := by + rw [Real.logb] + apply (le_div_iff₀ hl2).mpr + simpa using Real.log_le_log (by norm_num : (0 : ℝ) < 2) (by linarith : 2 ≤ 2 * r) + have hg : 8 * (r / h) * Real.logb 2 (2 * r) ≤ (routingG r h : ℝ) := Nat.le_ceil _ + have hgh : 8 * r ≤ (routingG r h : ℝ) * h := by + calc + 8 * r = (8 * (r / h)) * h := by field_simp + _ ≤ (8 * (r / h) * Real.logb 2 (2 * r)) * h := by + apply mul_le_mul_of_nonneg_right _ hh.le + simpa using mul_le_mul_of_nonneg_left hlog (show 0 ≤ 8 * (r / h) by positivity) + _ ≤ (routingG r h : ℝ) * h := mul_le_mul_of_nonneg_right hg hh.le + have hgpos : 0 < routingG r h := by + have hgR : (0 : ℝ) < routingG r h := by nlinarith + exact_mod_cast hgR + have hgle : routingG r h ≤ routingLength r h := (by omega : routingG r h ≤ 2 * routingG r h).trans (two_routingG_le_length r h) + refine ⟨by omega, ?_⟩ + have hgleR : (routingG r h : ℝ) ≤ routingLength r h := by exact_mod_cast hgle + nlinarith + +lemma routing_budget (L k b z h r : ℝ) (hL : 1 ≤ L) (hk : 1 ≤ k) + (hb : 1 ≤ b) (hz : 0 ≤ z) (hh : 0 < h) (_hr : 0 ≤ r) + (hreach : r ≤ L * h) (hbudget : 64 * (L ^ 2 * (k + b) + z) ≤ h) : + h / 8 + 2 + k ≤ h / 4 ∧ z + b * L ≤ h / 8 ∧ 64 * L * k * r ≤ h ^ 2 := by + have hL0 : 0 ≤ L := by linarith + have hk0 : 0 ≤ k := by linarith + have hb0 : 0 ≤ b := by linarith + have hLs : 1 ≤ L ^ 2 := one_le_pow₀ hL + have hLLs : L ≤ L ^ 2 := by nlinarith + have hbig : 64 * (k + b) ≤ h := by + calc + _ ≤ 64 * (L ^ 2 * (k + b) + z) := by nlinarith [mul_le_mul_of_nonneg_right hLs (by linarith : 0 ≤ k + b)] + _ ≤ _ := hbudget + have hbL : 64 * (b * L + z) ≤ h := by + calc + _ ≤ 64 * (L ^ 2 * (k + b) + z) := by nlinarith [mul_le_mul_of_nonneg_left hLLs hb0, mul_nonneg (sq_nonneg L) hk0] + _ ≤ _ := hbudget + have hkL : 64 * L ^ 2 * k ≤ h := by nlinarith [mul_nonneg (sq_nonneg L) hb0] + refine ⟨by linarith, by linarith, ?_⟩ + calc + 64 * L * k * r ≤ 64 * L * k * (L * h) := mul_le_mul_of_nonneg_left hreach (by positivity) + _ = (64 * L ^ 2 * k) * h := by ring + _ ≤ h * h := mul_le_mul_of_nonneg_right hkL hh.le + _ = h ^ 2 := by ring + +noncomputable def saturated (F : Finset (Sym2 V)) (h : ℝ) : Finset V := by + classical + exact Finset.univ.filter (fun v => h / 8 ≤ ((incidentEdges F v).card : ℝ)) + +lemma saturated_card_le (F : Finset (Sym2 V)) (h : ℝ) (hh : 0 < h) + (hF : 128 * (F.card : ℝ) ≤ h ^ 2) : (saturated F h).card ≤ h / 8 := by + classical + have hs : h / 8 * (saturated F h).card ≤ ∑ v : V, ((incidentEdges F v).card : ℝ) := by + calc + _ = ∑ _v ∈ saturated F h, h / 8 := by simp [mul_comm] + _ ≤ ∑ v ∈ saturated F h, ((incidentEdges F v).card : ℝ) := Finset.sum_le_sum (fun v hv => (Finset.mem_filter.mp hv).2) + _ ≤ _ := Finset.sum_le_sum_of_subset_of_nonneg (Finset.subset_univ _) (by intros; positivity) + have hsum : (∑ v : V, ((incidentEdges F v).card : ℝ)) ≤ 2 * (F.card : ℝ) := by + exact_mod_cast incidentEdges_sum_le F + nlinarith + +def pathInterior {P : SimpleGraph V} {s t : V} (q : P.Walk s t) : Finset V := + q.support.toFinset \ {s, t} + +lemma pathInterior_card_le {V : Type} [_contextInstance1 : Fintype V] [_contextInstance2 : DecidableEq V] {P : SimpleGraph V} {s t : V} (q : P.Walk s t) : + (pathInterior q).card ≤ q.length := by + have hp := List.toFinset_card_le q.support + rw [q.length_support] at hp + have hstart : s ∈ q.support.toFinset ∩ ({s, t} : Finset V) := by simp + have hint := Finset.card_pos.mpr ⟨s, hstart⟩ + have hd := Finset.card_sdiff_add_card_inter q.support.toFinset ({s, t} : Finset V) + dsimp [pathInterior] + omega + +lemma avoidGraph_le {V : Type} [_contextInstance1 : Fintype V] [_contextInstance2 : DecidableEq V] (P : SimpleGraph V) (F : Finset (Sym2 V)) (W : Finset V) : + avoidGraph P F W ≤ P := fun _ _ h => h.1 + +lemma walk_avoids_support (P : SimpleGraph V) (F : Finset (Sym2 V)) (W : Finset V) + {s t : V} (q : (avoidGraph P F W).Walk s t) (hs : s ∉ W) : + Disjoint q.support.toFinset W := by + apply Finset.disjoint_left.mpr + intro v hv + exact walk_avoids_end P F W (q.takeUntil v (List.mem_toFinset.mp hv)) hs + +lemma walk_avoids_edges {V : Type} [_contextInstance1 : Fintype V] [_contextInstance2 : DecidableEq V] (P : SimpleGraph V) (F : Finset (Sym2 V)) (W : Finset V) + {s t : V} (q : (avoidGraph P F W).Walk s t) : + Disjoint q.edges.toFinset F := by + apply Finset.disjoint_left.mpr + intro e he + induction e using Sym2.inductionOn with + | hf v w => exact (q.adj_of_mem_edges (List.mem_toFinset.mp he)).2.1 + +lemma exists_short_path_with_avoidance (P : SimpleGraph V) [DecidableRel P.Adj] + (h : ℝ) (hh : 0 < h) (hexp : CutExpansion P h) (hr : 2 ≤ Fintype.card V) + (F : Finset (Sym2 V)) (W : Finset V) (s t : V) (hs : s ∉ W) (ht : t ∉ W) + (hF : ∀ v, ((incidentEdges F v).card : ℝ) ≤ h / 4) + (hW : (W.card : ℝ) ≤ h / 4) : + ∃ q : P.Walk s t, q.IsPath ∧ q.length ≤ routingLength (Fintype.card V) h ∧ + Disjoint q.edges.toFinset F ∧ Disjoint q.support.toFinset W := by + obtain ⟨q, hp, hl⟩ := exists_short_avoiding_path P h hh hexp hr F W s t hs ht hF hW + refine ⟨q.mapLe (avoidGraph_le P F W), hp.mapLe _, ?_, ?_, ?_⟩ + · simpa using hl.trans (two_routingG_le_length (Fintype.card V) h) + · simpa using walk_avoids_edges P F W q + · simpa using walk_avoids_support P F W q hs + +lemma route_degree_update {P : SimpleGraph V} {s t : V} (q : P.Walk s t) + (hp : q.IsPath) (F : Finset (Sym2 V)) (h : ℝ) (load : V → ℕ) + (hdegree : ∀ v, ((incidentEdges F v).card : ℝ) ≤ h / 8 + 2 + load v) + (havoid : Disjoint q.support.toFinset (saturated F h \ {s, t})) (v : V) : + ((incidentEdges (F ∪ q.edges.toFinset) v).card : ℝ) ≤ + h / 8 + 2 + load v + (if v = s ∨ v = t then 1 else 0) := by + classical + have hadd : ((incidentEdges (F ∪ q.edges.toFinset) v).card : ℝ) ≤ + (incidentEdges F v).card + (incidentEdges q.edges.toFinset v).card := by + exact_mod_cast incidentEdges_union_card_le F q.edges.toFinset v + by_cases hv : v = s ∨ v = t + · rw [ite_eq_left hv] + have hqN : (incidentEdges q.edges.toFinset v).card ≤ 1 := by + rcases hv with rfl | rfl + · exact incidentEdges_path_start_le_one P q hp + · exact incidentEdges_path_end_le_one P q hp + have hq : ((incidentEdges q.edges.toFinset v).card : ℝ) ≤ 1 := by exact_mod_cast hqN + linarith [hdegree v] + · rw [ite_eq_right hv] + by_cases hmem : v ∈ q.support + · have hns : v ∉ saturated F h := by + intro hsat + apply Finset.disjoint_left.mp havoid (List.mem_toFinset.mpr hmem) + exact Finset.mem_sdiff.mpr ⟨hsat, by simpa using hv⟩ + have hsmall : ((incidentEdges F v).card : ℝ) < h / 8 := by + simpa [saturated] using hns + have hq : ((incidentEdges q.edges.toFinset v).card : ℝ) ≤ 2 := by + exact_mod_cast incidentEdges_path_le_two P q hp v + have : (0 : ℝ) ≤ load v := by positivity + linarith + · rw [incidentEdges_walk_eq_empty_of_not_mem P q hmem] at hadd + simp only [Finset.card_empty, Nat.cast_zero, add_zero] at hadd + linarith [hdegree v] + +section Families +variable {I T : Type} [Fintype I] [DecidableEq I] [DecidableEq T] +variable {P : SimpleGraph V} {x y : I → V} + +def endpointLoad (A : Finset I) (x y : I → V) (v : V) : ℕ := + (A.filter (fun i => x i = v ∨ y i = v)).card + +lemma endpointLoad_mono {V : Type} [_contextInstance1 : Fintype V] [_contextInstance2 : DecidableEq V] {I : Type} [_contextInstance4 : Fintype I] [_contextInstance5 : DecidableEq I] {A B : Finset I} (hAB : A ⊆ B) (x y : I → V) (v : V) : + endpointLoad A x y v ≤ endpointLoad B x y v := + Finset.card_le_card (Finset.filter_subset_filter _ hAB) + +lemma endpointLoad_insert {V : Type} [_contextInstance1 : Fintype V] [_contextInstance2 : DecidableEq V] {I : Type} [_contextInstance4 : Fintype I] [_contextInstance5 : DecidableEq I] (A : Finset I) (i : I) (hi : i ∉ A) (x y : I → V) (v : V) : + endpointLoad (insert i A) x y v = endpointLoad A x y v + + (if v = x i ∨ v = y i then 1 else 0) := by + classical + by_cases hv : v = x i ∨ v = y i + · have hv' : x i = v ∨ y i = v := by simpa [eq_comm] using hv + simp [endpointLoad, Finset.filter_insert, hv, hv', hi] + · have hv' : ¬ (x i = v ∨ y i = v) := by simpa [eq_comm] using hv + simp [endpointLoad, Finset.filter_insert, hv, hv'] + +lemma endpointLoad_sum {V : Type} [_contextInstance1 : Fintype V] [_contextInstance2 : DecidableEq V] {I : Type} [_contextInstance4 : Fintype I] [_contextInstance5 : DecidableEq I] (A : Finset I) (x y : I → V) (hxy : ∀ i ∈ A, x i ≠ y i) : + ∑ v : V, endpointLoad A x y v = 2 * A.card := by + classical + simp only [endpointLoad, Finset.card_eq_sum_ones, Finset.sum_filter] + rw [Finset.sum_comm] + have heq : ∀ i ∈ A, (∑ v : V, if x i = v ∨ y i = v then 1 else 0) = 2 := by + intro i hi + have hf : (Finset.univ.filter fun v => x i = v ∨ y i = v) = ({x i, y i} : Finset V) := by + ext v + simp [eq_comm] + have hc : ({x i, y i} : Finset V).card = 2 := by simp [hxy i hi] + rw [← hc, ← hf, Finset.card_eq_sum_ones, Finset.sum_filter] + calc + _ = ∑ _i ∈ A, 2 := Finset.sum_congr rfl heq + _ = _ := by simp [mul_comm] + +noncomputable def usedEdges (A : Finset I) (q : ∀ i, P.Walk (x i) (y i)) : Finset (Sym2 V) := + A.biUnion (fun i => (q i).edges.toFinset) + +lemma usedEdges_card_le {V : Type} [_contextInstance1 : Fintype V] [_contextInstance2 : DecidableEq V] {I : Type} [_contextInstance4 : Fintype I] [_contextInstance5 : DecidableEq I] {P : SimpleGraph V} {x : I → V} {y : I → V} (A : Finset I) (q : ∀ i, P.Walk (x i) (y i)) (L : ℕ) + (hq : ∀ i ∈ A, (q i).length ≤ L) : (usedEdges A q).card ≤ L * A.card := by + calc + _ ≤ ∑ i ∈ A, (q i).edges.toFinset.card := Finset.card_biUnion_le + _ ≤ ∑ _i ∈ A, L := Finset.sum_le_sum (fun i hi => by + have hc := List.toFinset_card_le (q i).edges + simpa using hc.trans (by simpa using hq i hi)) + _ = _ := by simp [mul_comm] + +lemma usedEdges_update_insert {V : Type} [_contextInstance1 : Fintype V] [_contextInstance2 : DecidableEq V] {I : Type} [_contextInstance4 : Fintype I] [_contextInstance5 : DecidableEq I] {P : SimpleGraph V} {x : I → V} {y : I → V} (A : Finset I) (i : I) (hi : i ∉ A) + (q : ∀ j, P.Walk (x j) (y j)) (p : P.Walk (x i) (y i)) : + usedEdges (insert i A) (Function.update q i p) = usedEdges A q ∪ p.edges.toFinset := by + classical + rw [usedEdges, Finset.biUnion_insert] + simp only [Function.update_self] + rw [Finset.union_comm] + congr 1 + apply Finset.biUnion_congr rfl + intro j hj + have hji : j ≠ i := by intro h; exact hi (h ▸ hj) + rw [Function.update_of_ne hji] + +noncomputable def teamInterior (A : Finset I) (q : ∀ j, P.Walk (x j) (y j)) + (team : I → T) (i : I) : Finset V := + (A.filter (fun j => team j = team i)).biUnion (fun j => pathInterior (q j)) + +lemma teamInterior_card_le {V : Type} [_contextInstance1 : Fintype V] [_contextInstance2 : DecidableEq V] {I : Type} {T : Type} [_contextInstance5 : Fintype I] [_contextInstance6 : DecidableEq I] [_contextInstance7 : DecidableEq T] {P : SimpleGraph V} {x : I → V} {y : I → V} (A : Finset I) (q : ∀ j, P.Walk (x j) (y j)) + (team : I → T) (i : I) (L : ℕ) (b : ℝ) + (hq : ∀ j ∈ A, (q j).length ≤ L) + (hb : ((Finset.univ.filter (fun j => team j = team i)).card : ℝ) ≤ b) : + ((teamInterior A q team i).card : ℝ) ≤ b * L := by + have hc : (teamInterior A q team i).card ≤ L * (A.filter (fun j => team j = team i)).card := by + calc + _ ≤ ∑ j ∈ A.filter (fun j => team j = team i), (pathInterior (q j)).card := Finset.card_biUnion_le + _ ≤ ∑ _j ∈ A.filter (fun j => team j = team i), L := Finset.sum_le_sum (fun j hj => + (pathInterior_card_le (q j)).trans (hq j (Finset.mem_filter.mp hj).1)) + _ = _ := by simp [mul_comm] + have hcard : ((A.filter (fun j => team j = team i)).card : ℝ) ≤ b := by + apply le_trans _ hb + exact_mod_cast Finset.card_le_card (Finset.filter_subset_filter _ (Finset.subset_univ A)) + have hcR : ((teamInterior A q team i).card : ℝ) ≤ (L : ℝ) * (A.filter (fun j => team j = team i)).card := by exact_mod_cast hc + calc + _ ≤ (L : ℝ) * b := hcR.trans (mul_le_mul_of_nonneg_left hcard (by positivity)) + _ = _ := mul_comm _ _ + +structure PartialRoutes (P : SimpleGraph V) (x y : I → V) (team : I → T) + (Z : I → Finset V) (L : ℕ) (h : ℝ) (A : Finset I) + (q : ∀ i, P.Walk (x i) (y i)) : Prop where + simple : ∀ i ∈ A, (q i).IsPath + short : ∀ i ∈ A, (q i).length ≤ L + avoids : ∀ i ∈ A, Disjoint (pathInterior (q i)) (Z i) + edge_disjoint : ∀ i ∈ A, ∀ j ∈ A, i ≠ j → Disjoint (q i).edges.toFinset (q j).edges.toFinset + team_disjoint : ∀ i ∈ A, ∀ j ∈ A, i ≠ j → team i = team j → Disjoint (pathInterior (q i)) (pathInterior (q j)) + degree : ∀ v, ((incidentEdges (usedEdges A q) v).card : ℝ) ≤ h / 8 + 2 + endpointLoad A x y v + +theorem routing (P : SimpleGraph V) [DecidableRel P.Adj] + (h : ℝ) (hh : 0 < h) (hexp : CutExpansion P h) (hr : 2 ≤ Fintype.card V) + (x y : I → V) (hxy : ∀ i, x i ≠ y i) (team : I → T) (Z : I → Finset V) + (k b z : ℝ) (hk : 1 ≤ k) (hb : 1 ≤ b) (hz : 0 ≤ z) + (hload : ∀ v, (endpointLoad Finset.univ x y v : ℝ) ≤ k) + (hteam : ∀ i, ((Finset.univ.filter (fun j => team j = team i)).card : ℝ) ≤ b) + (hZ : ∀ i, ((Z i).card : ℝ) ≤ z) + (hbudget : 64 * ((routingLength (Fintype.card V) h : ℝ) ^ 2 * (k + b) + z) ≤ h) : + ∃ q : ∀ i, P.Walk (x i) (y i), + (∀ i, (q i).IsPath ∧ (q i).length ≤ routingLength (Fintype.card V) h ∧ + Disjoint (pathInterior (q i)) (Z i)) ∧ + (∀ i j, i ≠ j → Disjoint (q i).edges.toFinset (q j).edges.toFinset) ∧ + (∀ i j, i ≠ j → team i = team j → Disjoint (pathInterior (q i)) (pathInterior (q j))) := by + classical + let L := routingLength (Fintype.card V) h + have hrR : (2 : ℝ) ≤ Fintype.card V := by exact_mod_cast hr + obtain ⟨hL, hreach⟩ := routingLength_bounds (Fintype.card V) h (by linarith) hh + have hLR : (1 : ℝ) ≤ L := by exact_mod_cast hL + obtain ⟨hdegBudget, hforbidBudget, hnumBudget⟩ := routing_budget L k b z h (Fintype.card V) + hLR hk hb hz hh (by positivity) hreach hbudget + have hloadA : ∀ (A : Finset I) v, (endpointLoad A x y v : ℝ) ≤ k := by + intro A v + have hm : (endpointLoad A x y v : ℝ) ≤ endpointLoad Finset.univ x y v := by + exact_mod_cast endpointLoad_mono (Finset.subset_univ A) x y v + exact hm.trans (hload v) + have htotal : 2 * (Fintype.card I : ℝ) ≤ k * Fintype.card V := by + have heq := endpointLoad_sum Finset.univ x y (fun i _ => hxy i) + have heqR : (∑ v : V, (endpointLoad Finset.univ x y v : ℝ)) = 2 * Fintype.card I := by + exact_mod_cast heq + rw [← heqR] + calc + _ ≤ ∑ _v : V, k := Finset.sum_le_sum (fun v _ => hload v) + _ = _ := by simp [mul_comm] + have hdefault : ∀ i, ∃ p : P.Walk (x i) (y i), p.IsPath := by + intro i + obtain ⟨p, hp, _⟩ := exists_short_path_with_avoidance P h hh hexp hr ∅ ∅ (x i) (y i) + (by simp) (by simp) (by intro v; simp [incidentEdges]; positivity) (by simp; positivity) + exact ⟨p, hp⟩ + choose defaultPath hdefaultPath using hdefault + have hpartial : ∀ A : Finset I, ∃ q : ∀ i, P.Walk (x i) (y i), PartialRoutes P x y team Z L h A q := by + intro A + induction A using Finset.induction_on with + | empty => + refine ⟨defaultPath, ?_⟩ + constructor + · simp + · simp + · simp + · simp + · simp + · intro v + simp only [usedEdges, Finset.biUnion_empty, incidentEdges, Finset.filter_empty, + Finset.card_empty, Nat.cast_zero, endpointLoad, add_zero] + linarith + | @insert i A hi ih => + obtain ⟨q, hq⟩ := ih + let F := usedEdges A q + let S := saturated F h + let B := teamInterior A q team i + let W := (S ∪ Z i ∪ B) \ {x i, y i} + have hFcard : 128 * (F.card : ℝ) ≤ h ^ 2 := by + have hc : (F.card : ℝ) ≤ (L : ℝ) * A.card := by + exact_mod_cast usedEdges_card_le A q L hq.short + have ha : (A.card : ℝ) ≤ Fintype.card I := by exact_mod_cast Finset.card_le_univ A + have hsize : 2 * (A.card : ℝ) ≤ k * Fintype.card V := by linarith + have hmult := mul_le_mul_of_nonneg_left hsize (show 0 ≤ (L : ℝ) by positivity) + nlinarith [hnumBudget] + have hS : (S.card : ℝ) ≤ h / 8 := saturated_card_le F h hh hFcard + have hB : (B.card : ℝ) ≤ b * L := teamInterior_card_le A q team i L b hq.short (hteam i) + have hW : (W.card : ℝ) ≤ h / 4 := by + have hc : W.card ≤ S.card + (Z i).card + B.card := + (Finset.card_le_card Finset.sdiff_subset).trans ((Finset.card_union_le _ _).trans + (Nat.add_le_add_right (Finset.card_union_le _ _) _)) + have hcR : (W.card : ℝ) ≤ (S.card : ℝ) + (Z i).card + B.card := by exact_mod_cast hc + linarith [hZ i] + have hFdegree : ∀ v, ((incidentEdges F v).card : ℝ) ≤ h / 4 := by + intro v + have hd := hq.degree v + have hl := hloadA A v + dsimp [F] + linarith + obtain ⟨p, hp, hpL, hpF, hpW⟩ := exists_short_path_with_avoidance P h hh hexp hr F W (x i) (y i) + (by simp [W]) (by simp [W]) hFdegree hW + have hpZ : Disjoint (pathInterior p) (Z i) := by + apply Finset.disjoint_left.mpr + intro v hv hvZ + obtain ⟨hvp, hvends⟩ := Finset.mem_sdiff.mp hv + apply Finset.disjoint_left.mp hpW hvp + exact Finset.mem_sdiff.mpr ⟨Finset.mem_union_left _ (Finset.mem_union_right _ hvZ), hvends⟩ + have hpS : Disjoint p.support.toFinset (saturated F h \ {x i, y i}) := by + apply Finset.disjoint_left.mpr + intro v hv hvS + obtain ⟨hs, he⟩ := Finset.mem_sdiff.mp hvS + apply Finset.disjoint_left.mp hpW hv + exact Finset.mem_sdiff.mpr ⟨Finset.mem_union_left _ (Finset.mem_union_left _ hs), he⟩ + have hpEdge : ∀ j ∈ A, Disjoint p.edges.toFinset (q j).edges.toFinset := by + intro j hj + apply Finset.disjoint_left.mpr + intro e hep heq + exact Finset.disjoint_left.mp hpF hep (Finset.mem_biUnion.mpr ⟨j, hj, heq⟩) + have hpTeam : ∀ j ∈ A, team i = team j → Disjoint (pathInterior p) (pathInterior (q j)) := by + intro j hj htm + apply Finset.disjoint_left.mpr + intro v hvp hvq + obtain ⟨hvp', hvends⟩ := Finset.mem_sdiff.mp hvp + apply Finset.disjoint_left.mp hpW hvp' + apply Finset.mem_sdiff.mpr + refine ⟨Finset.mem_union_right _ ?_, hvends⟩ + exact Finset.mem_biUnion.mpr ⟨j, Finset.mem_filter.mpr ⟨hj, htm.symm⟩, hvq⟩ + let q' := Function.update q i p + have hsame : q' i = p := Function.update_self i p q + have hother : ∀ j ∈ A, q' j = q j := by + intro j hj + apply Function.update_of_ne + intro hji + exact hi (hji ▸ hj) + refine ⟨q', ?_⟩ + constructor + · intro j hj + rcases Finset.mem_insert.mp hj with rfl | hj + · simpa only [hsame] using hp + · simpa only [hother j hj] using hq.simple j hj + · intro j hj + rcases Finset.mem_insert.mp hj with rfl | hj + · simpa only [hsame] using hpL + · simpa only [hother j hj] using hq.short j hj + · intro j hj + rcases Finset.mem_insert.mp hj with rfl | hj + · simpa only [hsame] using hpZ + · simpa only [hother j hj] using hq.avoids j hj + · intro j hj k hk hjk + rcases Finset.mem_insert.mp hj with rfl | hjA + · have hkA : k ∈ A := (Finset.mem_insert.mp hk).resolve_left (Ne.symm hjk) + simpa only [hsame, hother k hkA] using hpEdge k hkA + · rcases Finset.mem_insert.mp hk with rfl | hkA + · simpa only [hsame, hother j hjA] using (hpEdge j hjA).symm + · simpa only [hother j hjA, hother k hkA] using hq.edge_disjoint j hjA k hkA hjk + · intro j hj k hk hjk htm + rcases Finset.mem_insert.mp hj with rfl | hjA + · have hkA : k ∈ A := (Finset.mem_insert.mp hk).resolve_left (Ne.symm hjk) + simpa only [hsame, hother k hkA] using hpTeam k hkA htm + · rcases Finset.mem_insert.mp hk with rfl | hkA + · simpa only [hsame, hother j hjA] using (hpTeam j hjA htm.symm).symm + · simpa only [hother j hjA, hother k hkA] using hq.team_disjoint j hjA k hkA hjk htm + · intro v + have heq : usedEdges (insert i A) q' = F ∪ p.edges.toFinset := usedEdges_update_insert A i hi q p + rw [heq] + have hu := route_degree_update p hp F h (endpointLoad A x y) hq.degree hpS v + have hloadEq : (endpointLoad (insert i A) x y v : ℝ) = + endpointLoad A x y v + (if v = x i ∨ v = y i then (1 : ℝ) else 0) := by + rw [endpointLoad_insert A i hi] + split_ifs <;> simp + rw [hloadEq] + simpa only [add_assoc] using hu + obtain ⟨q, hq⟩ := hpartial Finset.univ + exact ⟨q, fun i => ⟨hq.simple i (by simp), hq.short i (by simp), hq.avoids i (by simp)⟩, + fun i j hij => hq.edge_disjoint i (by simp) j (by simp) hij, + fun i j hij htm => hq.team_disjoint i (by simp) j (by simp) hij htm⟩ + +end Families +end ErdosGallai.Batch + +end +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/CycleDecomposition/CollisionEstimates.lean b/lean/OAI/Combinatorics/CycleDecomposition/CollisionEstimates.lean new file mode 100644 index 0000000000000000000000000000000000000000..eb42fb05e379adc0ca52acfaa9864f7171eb54cc --- /dev/null +++ b/lean/OAI/Combinatorics/CycleDecomposition/CollisionEstimates.lean @@ -0,0 +1,548 @@ +import OAI.Combinatorics.CycleDecomposition.Pairing + +namespace OAI + +universe cycleUniverse1 cycleUniverse2 cycleUniverse3 cycleUniverse4 cycleUniverse5 cycleUniverse6 cycleUniverse7 cycleUniverse8 cycleUniverse9 cycleUniverse10 cycleUniverse11 cycleUniverse12 cycleUniverse13 cycleUniverse14 cycleUniverse15 cycleUniverse16 cycleUniverse17 cycleUniverse18 cycleUniverse19 cycleUniverse20 cycleUniverse21 cycleUniverse22 cycleUniverse23 cycleUniverse24 cycleUniverse25 cycleUniverse26 cycleUniverse27 cycleUniverse28 cycleUniverse29 cycleUniverse30 cycleUniverse31 + +section +open Filter Asymptotics Real +open scoped Topology +noncomputable section +open MeasureTheory ProbabilityTheory Finset +section +namespace ErdosGallai.Batch +open Finset +noncomputable section +attribute [local instance] Classical.propDecidable +variable {V : Type cycleUniverse1} [Fintype V] (G : SimpleGraph V) + +def neighborsIn (X : Finset V) (v : V) : ℕ := + (X.filter (G.Adj v)).card + +def internalGraph (X : Finset V) : SimpleGraph V where + Adj u v := G.Adj u v ∧ u ∈ X ∧ v ∈ X + symm := ⟨fun _ _ h => ⟨h.1.symm,h.2.2,h.2.1⟩⟩ + loopless := ⟨fun _ h => G.irrefl h.1⟩ + +lemma neighborsIn_le_degree (X : Finset V) (v : V) : + neighborsIn G X v ≤ G.degree v := by + classical + rw [← G.card_neighborFinset_eq_degree] + apply Finset.card_le_card + intro x hx + exact (G.mem_neighborFinset v x).mpr (Finset.mem_filter.mp hx).2 + +lemma neighborsIn_eq_sum {V : Type cycleUniverse2} [_contextInstance1 : Fintype V] (G : SimpleGraph V) (X : Finset V) (v : V) : + neighborsIn G X v = ∑ x ∈ X, if G.Adj v x then 1 else 0 := by + classical + simp only [neighborsIn,Finset.card_eq_sum_ones,Finset.sum_filter] + +lemma sum_incidence_to_set (X : Finset V) : + ∑ v, neighborsIn G X v = ∑ x ∈ X, G.degree x := by + classical + simp_rw [neighborsIn_eq_sum] + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro x hx + simp_rw [G.adj_comm (v:=x)] + rw [← Finset.sum_filter] + have he : Finset.univ.filter (G.Adj x) = G.neighborFinset x := by + ext y + simp + simp [he] + +lemma internalGraph_degree (X : Finset V) (v : V) : + (internalGraph G X).degree v = if v ∈ X then neighborsIn G X v else 0 := by + classical + rw [← SimpleGraph.card_neighborFinset_eq_degree] + by_cases hv : v ∈ X + · simp only [hv,ite_true] + congr 1 + ext x + rw [SimpleGraph.mem_neighborFinset,Finset.mem_filter] + change (G.Adj v x ∧ v ∈ X ∧ x ∈ X) ↔ _ + tauto + · have he : (internalGraph G X).neighborFinset v = ∅ := by + ext x + simp only [SimpleGraph.mem_neighborFinset,Finset.notMem_empty] + change (G.Adj v x ∧ v ∈ X ∧ x ∈ X) ↔ False + tauto + simp [he,hv] + +lemma internalGraph_degree_sum (X : Finset V) : + 2 * (internalGraph G X).edgeFinset.card = ∑ x ∈ X, neighborsIn G X x := by + classical + rw [← SimpleGraph.sum_degrees_eq_twice_card_edges] + simp_rw [internalGraph_degree] + simp + +lemma internal_edge_bound (X : Finset V) (a : ℝ) + (ha : ∀ x ∈ X, (G.degree x : ℝ) ≤ a) : + 2 * ((internalGraph G X).edgeFinset.card : ℝ) ≤ a * X.card := by + have hid := congrArg (fun n : ℕ => (n:ℝ)) (internalGraph_degree_sum G X) + push_cast at hid + rw [hid] + calc + _ ≤ ∑ x ∈ X, a := Finset.sum_le_sum fun x hx => + (Nat.cast_le.mpr (neighborsIn_le_degree G X x)).trans (ha x hx) + _ = _ := by simp [mul_comm] + +lemma incidence_bound (X : Finset V) (a : ℝ) + (ha : ∀ x ∈ X, (G.degree x : ℝ) ≤ a) : + (∑ v, neighborsIn G X v : ℝ) ≤ a * X.card := by + have hid := congrArg (fun n : ℕ => (n:ℝ)) (sum_incidence_to_set G X) + push_cast at hid + rw [hid] + simpa [mul_comm] using Finset.sum_le_sum (s:=X) (fun x hx => ha x hx) + +lemma wedge_count_bound (X : Finset V) (a : ℝ) (ha : 1 ≤ a) + (hdegree : ∀ x ∈ X, (G.degree x : ℝ) ≤ a) + (hneighbor : ∀ v, (neighborsIn G X v : ℝ) ≤ a) : + ((∑ v, (neighborsIn G X v).choose 2 : ℕ) : ℝ) ≤ + a*(a-1)*X.card/2 := by + have hb (v : V) : ((neighborsIn G X v).choose 2 : ℝ) ≤ + (a-1)*(neighborsIn G X v)/2 := by + rw [Nat.cast_choose_two] + have hn : (0:ℝ) ≤ neighborsIn G X v := Nat.cast_nonneg _ + have hn' := hneighbor v + nlinarith + calc + _ = ∑ v, ((neighborsIn G X v).choose 2 : ℝ) := by push_cast; rfl + _ ≤ ∑ v, (a-1)*(neighborsIn G X v)/2 := Finset.sum_le_sum fun v _ => hb v + _ = (a-1)/2 * ∑ v, (neighborsIn G X v : ℝ) := by + rw [Finset.mul_sum] + apply Finset.sum_congr rfl + intro v hv + ring + _ ≤ (a-1)/2 * (a*X.card) := mul_le_mul_of_nonneg_left + (incidence_bound G X a hdegree) (by positivity) + _ = _ := by ring + +def betweenCount (X Y : Finset V) : ℕ := ∑ x ∈ X, neighborsIn G Y x + +lemma betweenCount_comm (X Y : Finset V) : + betweenCount G X Y = betweenCount G Y X := by + classical + simp only [betweenCount,neighborsIn_eq_sum] + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro y hy + apply Finset.sum_congr rfl + intro x hx + simp only [G.adj_comm] + +lemma betweenCount_bound (X Y : Finset V) (a : ℝ) + (hdegree : ∀ y ∈ Y, (G.degree y : ℝ) ≤ a) : + (betweenCount G X Y : ℝ) ≤ a*Y.card := by + rw [betweenCount_comm] + simp only [betweenCount,Nat.cast_sum] + calc + _ ≤ ∑ y ∈ Y, a := Finset.sum_le_sum fun y hy => + (Nat.cast_le.mpr (neighborsIn_le_degree G X y)).trans (hdegree y hy) + _ = _ := by simp [mul_comm] + +lemma disjoint_neighbor_sum_le {I : Type cycleUniverse3} [Fintype I] (X : I → Finset V) + (hd : Pairwise (fun i j => Disjoint (X i) (X j))) (v : V) : + ∑ i, neighborsIn G (X i) v ≤ G.degree v := by + classical + have hb : ((Finset.univ : Finset I) : Set I).PairwiseDisjoint + (fun i => (X i).filter (G.Adj v)) := by + intro i hi j hj hij + exact (hd hij).mono (Finset.filter_subset _ _) (Finset.filter_subset _ _) + simp only [neighborsIn] + rw [← Finset.card_biUnion hb,← G.card_neighborFinset_eq_degree] + apply Finset.card_le_card + intro x hx + obtain ⟨i,hi,hx⟩ := Finset.mem_biUnion.mp hx + exact (G.mem_neighborFinset v x).mpr (Finset.mem_filter.mp hx).2 + +lemma betweenCount_row_bound {I : Type cycleUniverse4} [Fintype I] (X : I → Finset V) + (hd : Pairwise (fun i j => Disjoint (X i) (X j))) (i : I) (a : ℝ) + (hdegree : ∀ x ∈ X i, (G.degree x : ℝ) ≤ a) : + (∑ j, betweenCount G (X i) (X j) : ℝ) ≤ a*(X i).card := by + simp only [betweenCount,Nat.cast_sum] + rw [Finset.sum_comm] + calc + _ ≤ ∑ x ∈ X i, a := by + apply Finset.sum_le_sum + intro x hx + have hn := disjoint_neighbor_sum_le G X hd x + have hn' : (∑ j, (neighborsIn G (X j) x : ℝ)) ≤ G.degree x := by + exact_mod_cast hn + exact hn'.trans (hdegree x hx) + _ = _ := by simp [mul_comm] + +lemma cross_error_row {I : Type cycleUniverse5} [Fintype I] (X : I → Finset V) + (hd : Pairwise (fun i j => Disjoint (X i) (X j))) (a : ℝ) (ha : 0 ≤ a) + (hsize : ∀ i, 0 < (X i).card) + (hdegree : ∀ i x, x ∈ X i → (G.degree x : ℝ) ≤ a) (i : I) : + (∑ j, ((betweenCount G (X i) (X j) : ℝ)^2 / + ((X i).card*(X j).card))) ≤ a^2 := by + have hmi : (0:ℝ) < (X i).card := by exact_mod_cast hsize i + calc + _ ≤ ∑ j, a/(X i).card * (betweenCount G (X i) (X j) : ℝ) := by + apply Finset.sum_le_sum + intro j hj + have hmj : (0:ℝ) < (X j).card := by exact_mod_cast hsize j + have he := betweenCount_bound G (X i) (X j) a (hdegree j) + have hn : (0:ℝ) ≤ betweenCount G (X i) (X j) := Nat.cast_nonneg _ + apply (div_le_iff₀ (mul_pos hmi hmj)).mpr + field_simp + nlinarith + _ = a/(X i).card * ∑ j, (betweenCount G (X i) (X j) : ℝ) := by + rw [Finset.mul_sum] + _ ≤ a/(X i).card * (a*(X i).card) := mul_le_mul_of_nonneg_left + (betweenCount_row_bound G X hd i a (hdegree i)) (by positivity) + _ = a^2 := by field_simp + +end +end ErdosGallai.Batch + +namespace ErdosGallai.Batch +open Finset +noncomputable section + +def CollisionPairs {α : Type cycleUniverse6} {β : Type cycleUniverse7} [DecidableEq α] [DecidableEq β] (f : α → β) (s : Finset α) : Finset (Finset α) := by + classical + exact (s.powersetCard 2).filter (fun p => (p.image f).card = 1) + +lemma mem_collisionPairs {α : Type cycleUniverse8} {β : Type cycleUniverse9} [DecidableEq α] [DecidableEq β] (f : α → β) (s : Finset α) (p : Finset α) : + p ∈ CollisionPairs f s ↔ p ⊆ s ∧ p.card = 2 ∧ (p.image f).card = 1 := by + classical + simp [CollisionPairs,and_assoc] + +lemma collisionPairs_mono {α : Type cycleUniverse10} {β : Type cycleUniverse11} [DecidableEq α] [DecidableEq β] (f : α → β) {s t : Finset α} (h : s ⊆ t) : + CollisionPairs f s ⊆ CollisionPairs f t := by + classical + intro p hp + rw [mem_collisionPairs] at hp ⊢ + exact ⟨hp.1.trans h,hp.2⟩ + +lemma pair_mem_collisionPairs {α : Type cycleUniverse12} {β : Type cycleUniverse13} [DecidableEq α] [DecidableEq β] (f : α → β) (s : Finset α) + {a b : α} (ha : a ∈ s) (hb : b ∈ s) (hne : a ≠ b) (heq : f a = f b) : + {a,b} ∈ CollisionPairs f s := by + classical + rw [mem_collisionPairs] + refine ⟨?_,by simp [hne],by simp [heq]⟩ + intro x hx + rcases Finset.mem_insert.mp hx with rfl | hx + · exact ha + · exact Finset.mem_singleton.mp hx ▸ hb + +theorem prune_collisions {α : Type cycleUniverse14} {β : Type cycleUniverse15} [DecidableEq α] [DecidableEq β] (f : α → β) (s : Finset α) : + ∃ t ⊆ s, Set.InjOn f (t : Set α) ∧ t.image f = s.image f ∧ + s.card - t.card ≤ (CollisionPairs f s).card := by + classical + refine Finset.strongInductionOn s ?_ + intro s ih + by_cases hinj : Set.InjOn f (s : Set α) + · exact ⟨s,Subset.rfl,hinj,rfl,by simp⟩ + simp only [Set.InjOn,Finset.mem_coe,not_forall] at hinj + obtain ⟨a,ha,b,hb,heq,hne⟩ := hinj + have hsub : s.erase a ⊂ s := Finset.erase_ssubset ha + obtain ⟨t,ht,hinj,himage,hcost⟩ := ih (s.erase a) hsub + have hpair := pair_mem_collisionPairs f s ha hb hne heq + have hnot : ({a,b}:Finset α) ∉ CollisionPairs f (s.erase a) := by + intro hp + have hh := (mem_collisionPairs f _ _).mp hp + have := hh.1 (show a ∈ ({a,b}:Finset α) by simp) + simp at this + have hlt : (CollisionPairs f (s.erase a)).card < (CollisionPairs f s).card := by + apply Finset.card_lt_card + exact Finset.ssubset_iff_subset_ne.mpr ⟨collisionPairs_mono f (Finset.erase_subset _ _), + fun he => hnot (he ▸ hpair)⟩ + have himage' : (s.erase a).image f = s.image f := by + apply le_antisymm + · exact Finset.image_subset_image (Finset.erase_subset _ _) + · intro y hy + obtain ⟨x,hx,rfl⟩ := Finset.mem_image.mp hy + by_cases hxa : x = a + · subst x + exact Finset.mem_image.mpr ⟨b,by simp [hb,Ne.symm hne],heq.symm⟩ + · exact Finset.mem_image.mpr ⟨x,by simp [hx,hxa],rfl⟩ + refine ⟨t,ht.trans (Finset.erase_subset _ _),hinj,himage.trans himage',?_⟩ + have hcard := Finset.card_erase_of_mem ha + have htt := Finset.card_le_card ht + omega + +theorem prune_bad_images {α : Type cycleUniverse16} {β : Type cycleUniverse17} [DecidableEq α] [DecidableEq β] (f : α → β) (s : Finset α) (bad : β → Prop) [DecidablePred bad] : + ∃ t ⊆ s, (∀ x ∈ t, ¬ bad (f x)) ∧ Set.InjOn f (t : Set α) ∧ + t.image f = (s.filter (fun x => ¬bad (f x))).image f ∧ + s.card-t.card ≤ (s.filter (fun x => bad (f x))).card + + (CollisionPairs f (s.filter (fun x => ¬bad (f x)))).card := by + classical + obtain ⟨t,ht,hinj,himage,hcost⟩ := prune_collisions f (s.filter (fun x => ¬bad (f x))) + refine ⟨t,ht.trans (Finset.filter_subset _ _),?_,hinj,himage,?_⟩ + · intro x hx + exact (Finset.mem_filter.mp (ht hx)).2 + · have hpart := Finset.card_filter_add_card_filter_not (s:=s) (p:=fun x => bad (f x)) + have hle := Finset.card_le_card ht + omega + +end +end ErdosGallai.Batch +namespace ErdosGallai.Batch +open Finset +noncomputable section +attribute [local instance] Classical.propDecidable + +def quotientDefect {V : Type cycleUniverse18} {W : Type cycleUniverse19} [Fintype V] (G : SimpleGraph V) (projMap : V → W) : ℕ := by + classical + let s := G.edgeFinset + exact (s.filter (fun e => (Sym2.map projMap e).IsDiag)).card + + (CollisionPairs (Sym2.map projMap) (s.filter (fun e => ¬(Sym2.map projMap e).IsDiag))).card + +theorem simple_quotient_representatives {V : Type cycleUniverse20} {W : Type cycleUniverse21} [Fintype V] + (G : SimpleGraph V) (projMap : V → W) : + ∃ (retained : Finset (Sym2 V)) (Q : SimpleGraph W), + retained ⊆ G.edgeFinset ∧ + (G.edgeFinset \ retained).card ≤ quotientDefect G projMap ∧ + Q.edgeSet = ((retained.image (Sym2.map projMap) : Finset (Sym2 W)) : Set (Sym2 W)) ∧ + (∀ e ∈ Q.edgeSet, ∃! f, f ∈ retained ∧ Sym2.map projMap f = e) := by + classical + obtain ⟨t,ht,hgood,hinj,himage,hcost⟩ := + prune_bad_images (Sym2.map projMap) G.edgeFinset Sym2.IsDiag + let Q : SimpleGraph W := SimpleGraph.fromEdgeSet (t.image (Sym2.map projMap) : Set (Sym2 W)) + have hQ : Q.edgeSet = (t.image (Sym2.map projMap) : Set (Sym2 W)) := by + rw [SimpleGraph.edgeSet_fromEdgeSet] + ext e + constructor + · exact fun h => h.1 + · intro he + refine ⟨he,?_⟩ + obtain ⟨f,hf,rfl⟩ := Finset.mem_image.mp he + exact hgood f hf + refine ⟨t,Q,ht,?_,hQ,?_⟩ + · rw [Finset.card_sdiff_of_subset ht] + exact hcost + · intro e he + rw [hQ] at he + obtain ⟨f,hf,hfe⟩ := Finset.mem_image.mp he + refine ⟨f,⟨hf,hfe⟩,?_⟩ + intro g hg + exact hinj hg.1 hf (hg.2.trans hfe.symm) + +end +end ErdosGallai.Batch +namespace ErdosGallai.Batch +open Finset +noncomputable section +attribute [local instance] Classical.propDecidable +variable {V : Type cycleUniverse22} {I : Type cycleUniverse23} [Fintype V] [Fintype I] (X : I → Finset V) + (hd : Pairwise (fun i j => Disjoint (X i) (X j))) + +lemma familyPaired_symm {V : Type cycleUniverse24} {I : Type cycleUniverse25} [_contextInstance2 : Fintype V] [_contextInstance3 : Fintype I] (X : I → Finset V) (p : ∀ i, PairingSpace (X i)) {u v : V} + (h : familyPaired X p u v) : familyPaired X p v u := by + obtain ⟨i,hu,hv,hp⟩ := h + exact ⟨i,hv,hu,paired_symm (p i) hp⟩ + +lemma familyPaired_local {V : Type cycleUniverse26} {I : Type cycleUniverse27} [_contextInstance2 : Fintype V] [_contextInstance3 : Fintype I] (X : I → Finset V) (hd : Pairwise fun i j => Disjoint (X i) (X j)) (p : ∀ i, PairingSpace (X i)) (i : I) + (u v : X i) : familyPaired X p u v ↔ paired (p i) u v := by + constructor + · rintro ⟨j,hu,hv,hp⟩ + have hij : i = j := by + by_contra hij + exact Finset.disjoint_left.mp (hd hij) u.property hu + subst j + exact hp + · intro hp + exact ⟨i,u.property,v.property,hp⟩ + +lemma familyPaired_same_set {V : Type cycleUniverse28} {I : Type cycleUniverse29} [_contextInstance2 : Fintype V] [_contextInstance3 : Fintype I] (X : I → Finset V) (hd : Pairwise fun i j => Disjoint (X i) (X j)) (p : ∀ i, PairingSpace (X i)) (i : I) + {u v : V} (hu : u ∈ X i) (hp : familyPaired X p u v) : v ∈ X i := by + obtain ⟨j,hu',hv,hp⟩ := hp + have hij : i = j := by + by_contra hij + exact Finset.disjoint_left.mp (hd hij) hu hu' + exact hij.symm ▸ hv + +def vertexPairEvent (p : ∀ i, PairingSpace (X i)) (s : Finset V) : Prop := + ∃ u ∈ s, ∃ v ∈ s, u ≠ v ∧ familyPaired X p u v + +lemma vertexPairEvent_pair (p : ∀ i, PairingSpace (X i)) (u v : V) (huv : u ≠ v) : + vertexPairEvent X p {u,v} ↔ familyPaired X p u v := by + constructor + · rintro ⟨a,ha,b,hb,hab,hp⟩ + simp only [Finset.mem_insert,Finset.mem_singleton] at ha hb + rcases ha with rfl | rfl <;> rcases hb with rfl | rfl + · exact False.elim (hab rfl) + · exact hp + · exact familyPaired_symm X p hp + · exact False.elim (hab rfl) + · intro hp + exact ⟨u,by simp,v,by simp,huv,hp⟩ + +lemma finiteAverage_filter_card {Ω : Type cycleUniverse30} {A : Type cycleUniverse31} [Fintype Ω] + (s : Finset A) (P : Ω → A → Prop) : + finiteAverage (fun ω => ((s.filter (P ω)).card : ℝ)) = + ∑ a ∈ s, finiteAverage (fun ω => if P ω a then 1 else 0) := by + have hf (ω : Ω) : ((s.filter (P ω)).card : ℝ) = + ∑ a ∈ s, if P ω a then 1 else 0 := by + rw [Finset.card_eq_sum_ones, Nat.cast_sum] + simp only [Nat.cast_one,Finset.sum_filter] + simp_rw [hf] + exact finiteAverage_sum s _ + +include hd in +lemma vertexPairEvent_average (i : I) (s : Finset V) + (hs : s ⊆ X i) (hc : s.card = 2) (hm : 2 ≤ (X i).card) : + finiteAverage (fun p : ∀ j, PairingSpace (X j) => + if vertexPairEvent X p s then 1 else 0) ≤ 1 / ((X i).card-1:ℝ) := by + classical + obtain ⟨u,v,huv,rfl⟩ := Finset.card_eq_two.mp hc + have hu := hs (show u ∈ ({u,v}:Finset V) by simp) + have hv := hs (show v ∈ ({u,v}:Finset V) by simp) + have he (p : ∀ j, PairingSpace (X j)) : + vertexPairEvent X p {u,v} ↔ paired (p i) ⟨u,hu⟩ ⟨v,hv⟩ := + (vertexPairEvent_pair X p u v huv).trans (familyPaired_local X hd p i ⟨u,hu⟩ ⟨v,hv⟩) + simp_rw [he] + rw [finiteAverage_pi_eval (Ω:=fun j => PairingSpace (X j)) i + (fun p => if paired p ⟨u,hu⟩ ⟨v,hv⟩ then 1 else 0)] + convert paired_first_bound (V:=(X i)) (by simpa using hm) ⟨u,hu⟩ ⟨v,hv⟩ + (fun h => huv (congrArg Subtype.val h)) using 1 ; simp + +def wedgeErrors (G : SimpleGraph V) (p : ∀ i, PairingSpace (X i)) (i : I) (v : V) := + (((X i).filter (G.Adj v)).powersetCard 2).filter (vertexPairEvent X p) + +include hd in +lemma wedgeErrors_average (G : SimpleGraph V) (i : I) (v : V) + (hm : 2 ≤ (X i).card) : + finiteAverage (fun p : ∀ j, PairingSpace (X j) => ((wedgeErrors X G p i v).card : ℝ)) ≤ + ((neighborsIn G (X i) v).choose 2 : ℝ) / ((X i).card-1:ℝ) := by + classical + change finiteAverage (fun p => (((((X i).filter (G.Adj v)).powersetCard 2).filter + (vertexPairEvent X p)).card : ℝ)) ≤ _ + rw [finiteAverage_filter_card] + calc + _ ≤ ∑ _s ∈ ((X i).filter (G.Adj v)).powersetCard 2, + 1 / ((X i).card-1:ℝ) := by + apply Finset.sum_le_sum + intro s hs + obtain ⟨hs,hc⟩ := Finset.mem_powersetCard.mp hs + exact vertexPairEvent_average X hd i s (hs.trans (Finset.filter_subset _ _)) hc hm + _ = _ := by simp [Finset.card_powersetCard,neighborsIn,div_eq_mul_inv] + +lemma mem_internalGraph {G : SimpleGraph V} {S : Finset V} {u v : V} : + s(u,v) ∈ (internalGraph G S).edgeFinset ↔ G.Adj u v ∧ u ∈ S ∧ v ∈ S := by + simp only [SimpleGraph.mem_edgeFinset,SimpleGraph.mem_edgeSet] + rfl + +def crossGraph (G : SimpleGraph V) (S T : Finset V) : SimpleGraph V where + Adj u v := G.Adj u v ∧ ((u ∈ S ∧ v ∈ T) ∨ (u ∈ T ∧ v ∈ S)) + symm := ⟨fun _ _ h => ⟨h.1.symm,h.2.elim (fun h => Or.inr ⟨h.2,h.1⟩) + (fun h => Or.inl ⟨h.2,h.1⟩)⟩⟩ + loopless := ⟨fun _ h => G.irrefl h.1⟩ + +lemma distinct_edge_cases (G : SimpleGraph V) {e f : Sym2 V} + (he : e ∈ G.edgeFinset) (hf : f ∈ G.edgeFinset) (hef : e ≠ f) : + (∃ v u w, v ≠ u ∧ v ≠ w ∧ u ≠ w ∧ e = s(v,u) ∧ f = s(v,w)) ∨ + (∃ u v x y, u ≠ v ∧ x ≠ y ∧ u ≠ x ∧ u ≠ y ∧ v ≠ x ∧ v ≠ y ∧ + e = s(u,v) ∧ f = s(x,y)) := by + obtain ⟨a,b⟩ := e + obtain ⟨c,d⟩ := f + have hab : a ≠ b := (SimpleGraph.mem_edgeFinset.mp he).ne + have hcd : c ≠ d := (SimpleGraph.mem_edgeFinset.mp hf).ne + by_cases hac : a = c + · subst c + refine Or.inl ⟨a,b,d,hab,hcd,?_,rfl,rfl⟩ + intro hbd + exact hef (hbd ▸ rfl) + by_cases had : a = d + · subst d + refine Or.inl ⟨a,b,c,hab,hcd.symm,?_,rfl,Sym2.eq_swap⟩ + intro hbc + subst c + exact hef Sym2.eq_swap + by_cases hbc : b = c + · subst c + refine Or.inl ⟨b,a,d,hab.symm,hcd,?_,Sym2.eq_swap,rfl⟩ + intro had + subst d + exact hef Sym2.eq_swap + by_cases hbd : b = d + · subst d + refine Or.inl ⟨b,a,c,hab.symm,hcd.symm,?_,Sym2.eq_swap,Sym2.eq_swap⟩ + intro hac + subst c + exact hef rfl + exact Or.inr ⟨a,b,c,d,hab,hcd,hac,had,hbc,hbd,rfl,rfl⟩ + +lemma internal_collision_average (i : I) (hm : 4 ≤ (X i).card) + (u v x y : X i) (huv : u ≠ v) (hux : u ≠ x) (huy : u ≠ y) + (hvx : v ≠ x) (hvy : v ≠ y) (hxy : x ≠ y) : + finiteAverage (fun p : ∀ j, PairingSpace (X j) => + if Sym2.map (familyProject X hd p) s((u:V),(v:V)) = + Sym2.map (familyProject X hd p) s((x:V),(y:V)) then 1 else 0) ≤ + 2 / (((X i).card-1:ℝ)*((X i).card-3:ℝ)) := by + classical + have hmono : finiteAverage (fun p : ∀ j, PairingSpace (X j) => + if Sym2.map (familyProject X hd p) s((u:V),(v:V)) = + Sym2.map (familyProject X hd p) s((x:V),(y:V)) then 1 else 0) ≤ + finiteAverage (fun p : ∀ j, PairingSpace (X j) => + if (paired (p i) u x ∧ paired (p i) v y) ∨ + (paired (p i) u y ∧ paired (p i) v x) then 1 else 0) := by + apply finiteAverage_mono + intro p + by_cases hc : Sym2.map (familyProject X hd p) s((u:V),(v:V)) = + Sym2.map (familyProject X hd p) s((x:V),(y:V)) + · have hh := four_endpoint_collision X hd p (fun h => hux (Subtype.ext h)) + (fun h => huy (Subtype.ext h)) (fun h => hvx (Subtype.ext h)) + (fun h => hvy (Subtype.ext h)) hc + have he : (paired (p i) u x ∧ paired (p i) v y) ∨ + (paired (p i) u y ∧ paired (p i) v x) := by + simpa only [familyPaired_local X hd p i] using hh + simp only [ite_eq_left hc,ite_eq_left he,le_refl] + · rw [ite_eq_right hc] + split_ifs <;> norm_num + apply hmono.trans + rw [finiteAverage_pi_eval (Ω:=fun j => PairingSpace (X j)) i + (fun p => if (paired p u x ∧ paired p v y) ∨ (paired p u y ∧ paired p v x) + then 1 else 0)] + simpa only [Fintype.card_coe] using pairing_patterns_internal + (V:=(X i)) (by simpa using hm) u v x y huv hux huy hvx hvy hxy + +lemma cross_collision_average (i j : I) (hij : i ≠ j) + (hi : 2 ≤ (X i).card) (hj : 2 ≤ (X j).card) + (u x : X i) (v y : X j) (hux : u ≠ x) (hvy : v ≠ y) : + finiteAverage (fun p : ∀ k, PairingSpace (X k) => + if Sym2.map (familyProject X hd p) s((u:V),(v:V)) = + Sym2.map (familyProject X hd p) s((x:V),(y:V)) then 1 else 0) ≤ + 1 / (((X i).card-1:ℝ)*((X j).card-1:ℝ)) := by + classical + have huy : (u:V) ≠ y := by + intro h + exact Finset.disjoint_left.mp (hd hij) u.property (h ▸ y.property) + have hvx : (v:V) ≠ x := by + intro h + exact Finset.disjoint_left.mp (hd hij) (h ▸ x.property) v.property + have hmono : finiteAverage (fun p : ∀ k, PairingSpace (X k) => + if Sym2.map (familyProject X hd p) s((u:V),(v:V)) = + Sym2.map (familyProject X hd p) s((x:V),(y:V)) then 1 else 0) ≤ + finiteAverage (fun p : ∀ k, PairingSpace (X k) => + if paired (p i) u x ∧ paired (p j) v y then 1 else 0) := by + apply finiteAverage_mono + intro p + by_cases hc : Sym2.map (familyProject X hd p) s((u:V),(v:V)) = + Sym2.map (familyProject X hd p) s((x:V),(y:V)) + · have hh := four_endpoint_collision X hd p (fun h => hux (Subtype.ext h)) + huy hvx (fun h => hvy (Subtype.ext h)) hc + have he : paired (p i) u x ∧ paired (p j) v y := by + rcases hh with hh | hh + · exact ⟨(familyPaired_local X hd p i u x).mp hh.1, + (familyPaired_local X hd p j v y).mp hh.2⟩ + · have hy := familyPaired_same_set X hd p i u.property hh.1 + exact False.elim (Finset.disjoint_left.mp (hd hij) hy y.property) + simp only [ite_eq_left hc,ite_eq_left he,le_refl] + · rw [ite_eq_right hc] + split_ifs <;> norm_num + apply hmono.trans + simpa only [Fintype.card_coe] using pairing_patterns_cross_bound + (V:=fun k => X k) i j hij (by simpa using hi) (by simpa using hj) u x hux v y hvy + +end +end ErdosGallai.Batch +end +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/CycleDecomposition/CostRegrouping.lean b/lean/OAI/Combinatorics/CycleDecomposition/CostRegrouping.lean new file mode 100644 index 0000000000000000000000000000000000000000..8664f8f053bc9f89aafbe1c34c8558c1e44cdf07 --- /dev/null +++ b/lean/OAI/Combinatorics/CycleDecomposition/CostRegrouping.lean @@ -0,0 +1,404 @@ +import OAI.Combinatorics.CycleDecomposition.PrefixSelection + +namespace OAI + +universe cycleUniverse1 cycleUniverse2 + +section +open Filter Asymptotics Real +open scoped Topology +noncomputable section +open MeasureTheory ProbabilityTheory Finset +section + +namespace ErdosGallai.Scale +noncomputable section +open Finset SimpleGraph Real +attribute [local instance] Classical.propDecidable +variable {V : Type} [Fintype V] [DecidableEq V] + +def StageSplit.rest {P : AssignedPiece V} (s : StageSplit P) (B : AssignedPiece V) : AssignedPiece V := + if h : B ∈ s.boxes then ⟨B.vertices,s.remainder B,s.remainder_supported B h⟩ else B + +@[simp] lemma StageSplit.rest_vertices {V : Type} [_contextInstance1 : Fintype V] [_contextInstance2 : DecidableEq V] {P : AssignedPiece V} (s : StageSplit P) (B) : + (s.rest B).vertices = B.vertices := by unfold StageSplit.rest; split_ifs <;> rfl +lemma StageSplit.rest_graph {V : Type} [_contextInstance1 : Fintype V] [_contextInstance2 : DecidableEq V] {P : AssignedPiece V} (s : StageSplit P) {B} (hB : B ∈ s.boxes) : + (s.rest B).graph = s.remainder B := by simp [StageSplit.rest,hB] +lemma StageSplit.children_eq_map_rest {V : Type} [_contextInstance1 : Fintype V] [_contextInstance2 : DecidableEq V] {P : AssignedPiece V} (s : StageSplit P) : + s.children = s.boxes.map s.rest := by + unfold StageSplit.children + rw [← List.pmap_eq_map (f := s.rest) (fun B (hB : B ∈ s.boxes) => hB)] + apply List.pmap_congr_left + intro B hB + simp [StageSplit.rest,hB] + +lemma pastPieces_flatMap (s : SplitSystem V) (j k) {I : Type cycleUniverse1} + (L : List I) (f : I → List (AssignedPiece V)) : + (pastPieces s j k (L.flatMap f)).Perm (L.flatMap (fun i => pastPieces s j k (f i))) := by + induction k with + | zero => simp [pastPieces] + | succ k ih => + simp only [pastPieces,advance_flatMap,levelPieces,List.flatMap_assoc] + apply (ih.append_right _).trans + exact List.flatMap_append_perm _ _ _ +lemma pastCycles_flatMap (s : SplitSystem V) (j k) {I : Type cycleUniverse2} + (L : List I) (f : I → List (AssignedPiece V)) : + (pastCycles s j k (L.flatMap f)).Perm (L.flatMap (fun i => pastCycles s j k (f i))) := by + induction k with + | zero => simp [pastCycles] + | succ k ih => + simp only [pastCycles,advance_flatMap,levelCycles,List.flatMap_assoc] + apply (ih.append_right _).trans + exact List.flatMap_append_perm _ _ _ + +lemma pastPieces_add (s : SplitSystem V) (j k l) (L : List (AssignedPiece V)) : + pastPieces s j (k+l) L = pastPieces s j k L ++ pastPieces s (j+k) l (advance s j k L) := by + induction l with + | zero => simp [pastPieces] + | succ l ih => simp [pastPieces,ih,advance_add,Nat.add_assoc,List.append_assoc] +lemma pastCycles_add (s : SplitSystem V) (j k l) (L : List (AssignedPiece V)) : + pastCycles s j (k+l) L = pastCycles s j k L ++ pastCycles s (j+k) l (advance s j k L) := by + induction l with + | zero => simp [pastCycles] + | succ l ih => simp [pastCycles,ih,advance_add,Nat.add_assoc,List.append_assoc] + +lemma advance_mem_mono (s : SplitSystem V) (j k) {L M : List (AssignedPiece V)} + (h : ∀ P ∈ L, P ∈ M) : ∀ Q ∈ advance s j k L, Q ∈ advance s j k M := by + induction k with + | zero => exact h + | succ k ih => + intro Q hQ + obtain ⟨P,hP,B,hB,hv,hg⟩ := (nextLayer_mem s (j+k) _ Q).mp hQ + exact (nextLayer_mem s (j+k) _ Q).mpr ⟨P,ih P hP,B,hB,hv,hg⟩ + +lemma advance_local_mem (s : SplitSystem V) (i k) (L : List (AssignedPiece V)) + {P B : AssignedPiece V} (hP : P ∈ advance s 0 i L) (hB : B ∈ (s i P).boxes) : + ∀ Q ∈ advance s (i+1) k [(s i P).rest B], Q ∈ advance s 0 (i+1+k) L := by + rw [advance_add, Nat.zero_add] + apply advance_mem_mono + intro Q hQ + simp only [List.mem_singleton] at hQ + subst Q + simp only [advance_succ,Nat.zero_add] + + apply (nextLayer_mem s i _ _).mpr + exact ⟨P,hP,B,hB,(s i P).rest_vertices B,(s i P).rest_graph hB⟩ + +lemma box_regroup {B R : AssignedPiece V} (A : List (AssignedPiece V)) + (hBR : GraphPartition B.graph (R.graph :: A.map AssignedPiece.graph)) + (s : SplitSystem V) (j k : ℕ) : + GraphPartition B.graph + (pastCycles s j k [R] ++ (pastPieces s j k [R]).map AssignedPiece.graph ++ + [graphUnion ((advance s j k [R]).map AssignedPiece.graph ++ A.map AssignedPiece.graph)]) := by + let L := (advance s j k [R]).map AssignedPiece.graph ++ A.map AssignedPiece.graph + have hL : GraphPartition (graphUnion L) L := by + apply graphPartition_of_le_one + intro x y + have hb := hBR x y + have hr := past_partition s j k R x y + simp only [edgeOccurrences_cons,edgeOccurrences_append] at hb hr ⊢ + dsimp only [L] + rw [edgeOccurrences_append] + split_ifs at hb hr <;> omega + intro x y + have hb := hBR x y + have hr := past_partition s j k R x y + have hl := hL x y + simp only [edgeOccurrences_cons,edgeOccurrences_append,edgeOccurrences_nil,Nat.add_zero] at hb hr hl ⊢ + dsimp only [L] at hl + rw [edgeOccurrences_append] at hl + omega + +lemma piece_list_cost (L : List (AssignedPiece V)) (c : ℝ) + (h : ∀ P ∈ L, (decompositionCost P.graph:ℝ) ≤ c*P.vertices.card) : + (L.map (fun P => (decompositionCost P.graph:ℝ))).sum ≤ c*vertexMass L := by + induction L with + | nil => simp + | cons P L ih => + have hp := h P (by simp) + have hl := ih (fun Q hQ => h Q (by simp [hQ])) + simp only [List.map_cons,List.sum_cons,vertexMass_cons] + nlinarith + +lemma box_cost_regroup {B R : AssignedPiece V} (A : List (AssignedPiece V)) + (hBR : GraphPartition B.graph (R.graph :: A.map AssignedPiece.graph)) + (s : SplitSystem V) (j k : ℕ) (c q : ℝ) + (hp : ∀ P ∈ pastPieces s j k [R], (decompositionCost P.graph:ℝ) ≤ c*P.vertices.card) + (hq : (decompositionCost (graphUnion ((advance s j k [R]).map AssignedPiece.graph ++ + A.map AssignedPiece.graph)):ℝ) ≤ q) : + (decompositionCost B.graph:ℝ) ≤ (pastCycles s j k [R]).length + + c*vertexMass (pastPieces s j k [R]) + q := by + have hh := decompositionCost_partition_real (box_regroup A hBR s j k) + have hc := decompositionCost_cycles (pastCycles s j k [R]) (pastCycles_good s j k [R]) + have hm := piece_list_cost (pastPieces s j k [R]) c hp + simp only [List.map_append,List.sum_append,List.map_cons,List.map_nil,List.sum_cons,List.sum_nil, + add_zero,List.map_map,Function.comp_def] at hh + linarith + +end +end ErdosGallai.Scale + +end + +section + +namespace ErdosGallai +noncomputable section +open Real Filter + +def mainP : ℝ := 804 +def mainEta : ℝ := 1/(100*mainP) +def mainH : ℝ := 80/(Scale.scaleTheta^200) +def mainA₁ : ℝ := mainH + 4/3 +def mainA₂ : ℝ := max (9*mainP+8) (9*mainH) +lemma mainP_pos : 0 < mainP := by norm_num [mainP] +lemma mainEta_pos : 0 < mainEta := by norm_num [mainEta,mainP] +lemma mainH_pos : 0 < mainH := by unfold mainH; exact div_pos (by norm_num) (pow_pos Scale.scaleTheta_pos _) +lemma mainA₁_nonneg : 0 ≤ mainA₁ := by unfold mainA₁; linarith [mainH_pos] +lemma mainA₂_nonneg : 0 ≤ mainA₂ := by unfold mainA₂; exact (by norm_num [mainP] : (0:ℝ) ≤ 9*mainP+8).trans (le_max_left _ _) +lemma mainEta_mul_P : mainEta*mainP = 1/100 := by norm_num [mainEta,mainP] +lemma mainP_eq : mainP = 4*(200+1:ℝ) := by norm_num [mainP] + +structure MainScaleReady (wmin D : ℝ) : Prop where + gt_one : 1 < D + log_large : wmin ≤ logb 2 D + cycle_power : 1/(D^(1/100:ℝ)) ≤ 1/logb 2 D + batch_power : D^(1/1000:ℝ) ≤ D^(3/10:ℝ)/2 + bad_power : 2*D^(-9/1000:ℝ) ≤ 1/logb 2 D + skip_power : D^(-87/100:ℝ)+4*D^(-3/20:ℝ) ≤ 1/logb 2 D + active_eight : 8 ≤ D^(3/100:ℝ) + +lemma eventually_inverse_power_log (C ε : ℝ) (hC : 0 ≤ C) (hε : 0 < ε) : + ∀ᶠ D : ℝ in atTop, C*D^(-ε) ≤ 1/logb 2 D := by + filter_upwards [Batch.eventually_logb_le_power (ε/2) (by positivity), + Batch.eventually_const_mul_power_le C (ε/2) ε (by linarith), + eventually_gt_atTop (1:ℝ)] with D hl hc hD + have hd : 0 < D := by linarith + have hw : 0 < logb 2 D := Real.logb_pos (by norm_num) hD + have hp : 0 < D^ε := Real.rpow_pos_of_pos hd _ + apply (le_div_iff₀ hw).mpr + calc + _ = (C*logb 2 D)/D^ε := by rw [Real.rpow_neg hd.le]; ring + _ ≤ 1 := (div_le_one hp).mpr ((mul_le_mul_of_nonneg_left hl hC).trans hc) + +lemma main_scale_ready_cutoff (wmin : ℝ) : ∃ D₀ : ℝ, 1 < D₀ ∧ ∀ D ≥ D₀, MainScaleReady wmin D := by + have hev : ∀ᶠ D : ℝ in atTop, MainScaleReady wmin D := by + filter_upwards [eventually_gt_atTop (1:ℝ), + (Real.tendsto_logb_atTop (by norm_num : (1:ℝ) < 2)).eventually (eventually_ge_atTop wmin), + eventually_inverse_power_log 1 (1/100) (by norm_num) (by norm_num), + Batch.eventually_const_mul_power_le 2 (1/1000) (3/10) (by norm_num), + eventually_inverse_power_log 2 (9/1000) (by norm_num) (by norm_num), + eventually_inverse_power_log 2 (87/100) (by norm_num) (by norm_num), + eventually_inverse_power_log 8 (3/20) (by norm_num) (by norm_num), + Batch.eventually_constant_le_power 8 (3/100) (by norm_num)] with D hD hw hc hb hbad hs₁ hs₂ h8 + refine ⟨hD,hw,?_,by linarith,by simpa only [neg_div] using hbad,?_,h8⟩ + · simpa only [one_mul,Real.rpow_neg (by linarith : 0 ≤ D),one_div] using hc + · simp only [neg_div] + linarith + obtain ⟨A,hA⟩ := eventually_atTop.mp hev + refine ⟨max A 2,lt_of_lt_of_le (by norm_num : (1:ℝ) < 2) (le_max_right _ _),?_⟩ + intro D hD + exact hA D ((le_max_left _ _).trans hD) + +lemma MainScaleReady.active_square {w D : ℝ} (h : MainScaleReady w D) : + (D^(1/100:ℝ))^2 ≤ D^(3/100:ℝ) := by + rw [← Real.rpow_mul_natCast (by linarith [h.gt_one] : 0 ≤ D)] + apply Real.rpow_le_rpow_of_exponent_le h.gt_one.le + norm_num + +lemma MainScaleReady.bad_count {w D y b : ℝ} (h : MainScaleReady w D) (hy : 0 ≤ y) + (hb : D^(1/100:ℝ)*b ≤ 2*y*D^(1/1000:ℝ)) : b ≤ y/logb 2 D := by + have hd : 0 < D := by linarith [h.gt_one] + have hp : 0 < D^(1/100:ℝ) := Real.rpow_pos_of_pos hd _ + calc + b ≤ 2*y*D^(1/1000:ℝ)/D^(1/100:ℝ) := (le_div_iff₀ hp).mpr (by simpa [mul_comm] using hb) + _ = y*(2*D^(-9/1000:ℝ)) := by + have he : D^(1/1000:ℝ)/D^(1/100:ℝ) = D^(-9/1000:ℝ) := by + rw [← Real.rpow_sub hd]; norm_num + rw [show 2*y*D^(1/1000:ℝ)/D^(1/100:ℝ) = (2*y)*(D^(1/1000:ℝ)/D^(1/100:ℝ)) by ring,he] + ring + _ ≤ y*(1/logb 2 D) := mul_le_mul_of_nonneg_left h.bad_power hy + _ = _ := by ring + +lemma MainScaleReady.skip_count {w D y T b r : ℝ} (h : MainScaleReady w D) + (hy : 0 ≤ y) (_hb : 0 ≤ b) (hr : 0 ≤ r) + (hyD : y ≤ D^(51/50:ℝ)) (hT : T ≤ 2*y) + (hbT : b ≤ 1+2*T/D^(3/10:ℝ)) (hrY : D^(9/10:ℝ)*r ≤ y) : + D^(3/100:ℝ)*b*r ≤ y/logb 2 D := by + have hd : 0 < D := by linarith [h.gt_one] + have hB : 0 < D^(3/10:ℝ) := Real.rpow_pos_of_pos hd _ + have hS : 0 < D^(9/10:ℝ) := Real.rpow_pos_of_pos hd _ + have hL : 0 ≤ D^(3/100:ℝ) := Real.rpow_nonneg hd.le _ + have hb' : b ≤ 1+4*y/D^(3/10:ℝ) := by + have ht := div_le_div_of_nonneg_right (by linarith : 2*T ≤ 4*y) hB.le + linarith + have hr' : r ≤ y/D^(9/10:ℝ) := (le_div_iff₀ hS).mpr (by simpa [mul_comm] using hrY) + have he₁ : D^(3/100:ℝ)/D^(9/10:ℝ) = D^(-87/100:ℝ) := by + rw [← Real.rpow_sub hd]; norm_num + have he₂ : D^(51/50:ℝ)*D^(3/100:ℝ)/(D^(3/10:ℝ)*D^(9/10:ℝ)) = D^(-3/20:ℝ) := by + rw [← Real.rpow_add hd,← Real.rpow_add hd,← Real.rpow_sub hd]; norm_num + calc + _ ≤ D^(3/100:ℝ)*(1+4*y/D^(3/10:ℝ))*(y/D^(9/10:ℝ)) := by gcongr + _ = y*(D^(3/100:ℝ)/D^(9/10:ℝ)+4*y*(D^(3/100:ℝ)/(D^(3/10:ℝ)*D^(9/10:ℝ)))) := by ring + _ ≤ y*(D^(3/100:ℝ)/D^(9/10:ℝ)+4*D^(51/50:ℝ)*(D^(3/100:ℝ)/(D^(3/10:ℝ)*D^(9/10:ℝ)))) := by gcongr + _ = y*(D^(-87/100:ℝ)+4*D^(-3/20:ℝ)) := by rw [he₁,← he₂]; ring + _ ≤ y*(1/logb 2 D) := mul_le_mul_of_nonneg_left h.skip_power hy + _ = _ := by ring + +end +end ErdosGallai + +end + +section + +namespace ErdosGallai.Scale +noncomputable section +open Finset SimpleGraph Real +attribute [local instance] Classical.propDecidable +variable {V : Type} [Fintype V] [DecidableEq V] + +def costMass (L : List (AssignedPiece V)) : ℝ := (L.map (fun Q => (decompositionCost Q.graph:ℝ))).sum + +lemma costMass_bound (L : List (AssignedPiece V)) (f : AssignedPiece V → ℝ) + (h : ∀ P ∈ L, (decompositionCost P.graph:ℝ) ≤ f P) : costMass L ≤ (L.map f).sum := + List.sum_le_sum h + +lemma past_cost (s : SplitSystem V) (j k) (P : AssignedPiece V) (c : ℝ) + (hp : ∀ Q ∈ pastPieces s j k [P], (decompositionCost Q.graph:ℝ) ≤ c*Q.vertices.card) : + (decompositionCost P.graph:ℝ) ≤ ((pastCycles s j k [P]).length:ℝ) + + c*vertexMass (pastPieces s j k [P]) + costMass (advance s j k [P]) := by + have hh := decompositionCost_partition_real (past_partition s j k P) + have hc := decompositionCost_cycles _ (pastCycles_good s j k [P]) + have hm := piece_list_cost _ c hp + simp only [List.map_append,List.sum_append,List.map_map,Function.comp_def] at hh + dsimp only [costMass] + linarith + +lemma stage_cost (s : SplitSystem V) (j) (P : AssignedPiece V) : + (decompositionCost P.graph:ℝ) ≤ ((s j P).cycles.length:ℝ) + costMass (s j P).boxes := by + have hh := decompositionCost_partition_real (s j P).partition + have hc := decompositionCost_cycles _ (s j P).cycles_good + simp only [List.map_append,List.sum_append,List.map_map,Function.comp_def] at hh + dsimp only [costMass] + linarith + +lemma vertexMass_perm {V : Type} [_contextInstance1 : Fintype V] [_contextInstance2 : DecidableEq V] {L M : List (AssignedPiece V)} (h : L.Perm M) : vertexMass L = vertexMass M := + (h.map _).sum_eq + +lemma pastCycles_sum (s : SplitSystem V) (j k) (L : List (AssignedPiece V)) : + (L.map (fun P => ((pastCycles s j k [P]).length:ℝ))).sum = ((pastCycles s j k L).length:ℝ) := by + have h := (pastCycles_flatMap s j k L (fun P => [P])).length_eq + simp only [List.flatMap_singleton'] at h + rw [h,List.length_flatMap] + simp [Function.comp_def] + +lemma pastPieces_sum (s : SplitSystem V) (j k) (L : List (AssignedPiece V)) : + (L.map (fun P => vertexMass (pastPieces s j k [P]))).sum = vertexMass (pastPieces s j k L) := by + have h := vertexMass_perm (pastPieces_flatMap s j k L (fun P => [P])) + simpa only [List.flatMap_singleton',vertexMass_flatMap] using h.symm + +lemma advance_sum (s : SplitSystem V) (j k) (L : List (AssignedPiece V)) : + (L.map (fun P => vertexMass (advance s j k [P]))).sum = vertexMass (advance s j k L) := by + have h := congrArg vertexMass (advance_flatMap s j k L (fun P => [P])) + simpa only [List.flatMap_singleton',vertexMass_flatMap] using h.symm + +lemma pastCycles_after_first (s : SplitSystem V) (j k) (P : AssignedPiece V) : + (pastCycles s j (k+1) [P]).Perm ((s j P).cycles ++ + (s j P).boxes.flatMap (fun B => pastCycles s (j+1) k [(s j P).rest B])) := by + rw [show k+1=1+k by omega,pastCycles_add] + simp only [pastCycles,advance_zero,List.nil_append,levelCycles,List.flatMap_singleton, + Nat.add_zero,advance_succ,nextLayer,Nat.add_zero,List.flatMap_singleton,StageSplit.children_eq_map_rest] + have hh := pastCycles_flatMap s (j+1) k (s j P).boxes (fun B => [(s j P).rest B]) + simp only [← List.map_eq_flatMap] at hh + exact hh.append_left _ + +lemma pastPieces_after_first (s : SplitSystem V) (j k) (P : AssignedPiece V) : + (pastPieces s j (k+1) [P]).Perm ((s j P).boxes.flatMap (s j P).pieces ++ + (s j P).boxes.flatMap (fun B => pastPieces s (j+1) k [(s j P).rest B])) := by + rw [show k+1=1+k by omega,pastPieces_add] + simp only [pastPieces,advance_zero,List.nil_append,levelPieces,List.flatMap_singleton, + Nat.add_zero,advance_succ,nextLayer,Nat.add_zero,List.flatMap_singleton,StageSplit.children_eq_map_rest] + have hh := pastPieces_flatMap s (j+1) k (s j P).boxes (fun B => [(s j P).rest B]) + simp only [← List.map_eq_flatMap] at hh + exact hh.append_left _ + +lemma advance_after_first (s : SplitSystem V) (j k) (P : AssignedPiece V) : + advance s j (k+1) [P] = (s j P).boxes.flatMap (fun B => advance s (j+1) k [(s j P).rest B]) := by + rw [show k+1=1+k by omega,advance_add] + simp only [advance_succ,advance_zero,Nat.add_zero,nextLayer,List.flatMap_singleton, + StageSplit.children_eq_map_rest] + simpa only [← List.map_eq_flatMap] using advance_flatMap s (j+1) k (s j P).boxes (fun B => [(s j P).rest B]) + +lemma selected_input_cost (s : SplitSystem V) (j k) (P : AssignedPiece V) (c α β γ : ℝ) + (hp : ∀ B ∈ (s j P).boxes, ∀ Q ∈ pastPieces s (j+1) k [(s j P).rest B], + (decompositionCost Q.graph:ℝ) ≤ c*Q.vertices.card) + (hq : ∀ B ∈ (s j P).boxes, + (decompositionCost (graphUnion ((advance s (j+1) k [(s j P).rest B]).map AssignedPiece.graph ++ + ((s j P).pieces B).map AssignedPiece.graph)):ℝ) ≤ + c*vertexMass ((s j P).pieces B) + α*vertexMass (advance s (j+1) k [(s j P).rest B]) + + β*vertexMass ((s j P).pieces B) + γ*B.vertices.card) : + (decompositionCost P.graph:ℝ) ≤ ((pastCycles s j (k+1) [P]).length:ℝ) + + c*vertexMass (pastPieces s j (k+1) [P]) + α*vertexMass (advance s j (k+1) [P]) + + β*vertexMass (levelPieces s j [P]) + γ*vertexMass (nextLayer s j [P]) := by + have hb (B) (hB : B ∈ (s j P).boxes) := box_cost_regroup ((s j P).pieces B) + (R := (s j P).rest B) (by simpa only [StageSplit.rest_graph _ hB] using (s j P).box_partition B hB) + s (j+1) k c _ (hp B hB) (hq B hB) + have hh := (stage_cost s j P).trans (add_le_add (le_refl _) (costMass_bound _ _ hb)) + have hc := (pastCycles_after_first s j k P).length_eq + have hm := vertexMass_perm (pastPieces_after_first s j k P) + rw [hc,List.length_append,Nat.cast_add,List.length_flatMap,hm,vertexMass_append, + vertexMass_flatMap,vertexMass_flatMap,advance_after_first,vertexMass_flatMap] + simp only [levelPieces,nextLayer,List.flatMap_singleton,StageSplit.children_mass,vertexMass_flatMap] + simp only [List.sum_map_add,List.sum_map_mul_left] at hh + simp only [Nat.cast_list_sum,List.map_map,Function.comp_def,vertexMass] at hh ⊢ + linarith + +lemma selected_prefix_cost (s : SplitSystem V) (i k) (P : AssignedPiece V) (c α β γ : ℝ) + (hp : ∀ Q ∈ pastPieces s 0 (i+(k+1)) [P], (decompositionCost Q.graph:ℝ) ≤ c*Q.vertices.card) + (hq : ∀ Q ∈ advance s 0 i [P], ∀ B ∈ (s i Q).boxes, + (decompositionCost (graphUnion ((advance s (i+1) k [(s i Q).rest B]).map AssignedPiece.graph ++ + ((s i Q).pieces B).map AssignedPiece.graph)):ℝ) ≤ + c*vertexMass ((s i Q).pieces B) + α*vertexMass (advance s (i+1) k [(s i Q).rest B]) + + β*vertexMass ((s i Q).pieces B) + γ*B.vertices.card) : + (decompositionCost P.graph:ℝ) ≤ ((pastCycles s 0 (i+(k+1)) [P]).length:ℝ) + + c*vertexMass (pastPieces s 0 (i+(k+1)) [P]) + α*vertexMass (advance s 0 (i+(k+1)) [P]) + + β*vertexMass (levelPieces s i (advance s 0 i [P])) + γ*vertexMass (advance s 0 (i+1) [P]) := by + have he : pastPieces s 0 (i+(k+1)) [P] = pastPieces s 0 i [P] ++ + pastPieces s i (k+1) (advance s 0 i [P]) := by rw [pastPieces_add,Nat.zero_add] + have hp₀ : ∀ Q ∈ pastPieces s 0 i [P], (decompositionCost Q.graph:ℝ) ≤ c*Q.vertices.card := by + intro Q hQ; apply hp; rw [he]; exact List.mem_append_left _ hQ + have hpp (Q) (hQ : Q ∈ advance s 0 i [P]) (B) (hB : B ∈ (s i Q).boxes) + (R) (hR : R ∈ pastPieces s (i+1) k [(s i Q).rest B]) : + (decompositionCost R.graph:ℝ) ≤ c*R.vertices.card := by + apply hp R + rw [he,List.mem_append] + right + have h₁ := pastPieces_flatMap s i (k+1) (advance s 0 i [P]) (fun Q => [Q]) + simp only [List.flatMap_singleton'] at h₁ + rw [h₁.mem_iff] + apply List.mem_flatMap.mpr + refine ⟨Q,hQ,?_⟩ + rw [(pastPieces_after_first s i k Q).mem_iff,List.mem_append] + exact Or.inr (List.mem_flatMap.mpr ⟨B,hB,hR⟩) + have hh := (past_cost s 0 i P c hp₀).trans (add_le_add (le_refl _) + (costMass_bound _ _ (fun Q hQ => selected_input_cost s i k Q c α β γ (hpp Q hQ) (hq Q hQ)))) + rw [pastCycles_add,pastPieces_add,advance_add,Nat.zero_add,List.length_append,Nat.cast_add,vertexMass_append] + simp only [List.sum_map_add,List.sum_map_mul_left,pastCycles_sum,pastPieces_sum,advance_sum] at hh + have hS : ((advance s 0 i [P]).map (fun Q => vertexMass (levelPieces s i [Q]))).sum = + vertexMass (levelPieces s i (advance s 0 i [P])) := by + simp only [levelPieces,List.flatMap_singleton,vertexMass_flatMap] + have hN : ((advance s 0 i [P]).map (fun Q => vertexMass (nextLayer s i [Q]))).sum = + vertexMass (advance s 0 (i+1) [P]) := by + simp only [nextLayer,List.flatMap_singleton,advance_succ,Nat.zero_add,vertexMass_flatMap] + rw [hS,hN] at hh + linarith + +end +end ErdosGallai.Scale + +end +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/CycleDecomposition/CoupledResolution.lean b/lean/OAI/Combinatorics/CycleDecomposition/CoupledResolution.lean new file mode 100644 index 0000000000000000000000000000000000000000..fff7340ad60520f0d4cc78736d5d1cc7c677b6af --- /dev/null +++ b/lean/OAI/Combinatorics/CycleDecomposition/CoupledResolution.lean @@ -0,0 +1,817 @@ +import OAI.Combinatorics.CycleDecomposition.BatchResolution + +namespace OAI + +universe cycleUniverse1 cycleUniverse2 cycleUniverse3 cycleUniverse4 cycleUniverse5 cycleUniverse6 cycleUniverse7 cycleUniverse8 + +section +open Filter Asymptotics Real +open scoped Topology +noncomputable section +open MeasureTheory ProbabilityTheory Finset +section +namespace ErdosGallai.Batch.Splitting +open MeasureTheory ProbabilityTheory Finset Real + +section BernoulliBounds +variable {Ω : Type cycleUniverse1} {I : Type cycleUniverse2} [MeasurableSpace Ω] {μ : Measure Ω} [IsProbabilityMeasure μ] + +lemma indicator_mem_Icc {Ω : Type cycleUniverse3} [_contextInstance1 : MeasurableSpace Ω] {X : Ω → ℝ} (hX : ∀ ω, X ω = 0 ∨ X ω = 1) (ω : Ω) : + X ω ∈ Set.Icc (0 : ℝ) 1 := by rcases hX ω with h | h <;> simp [h] + +lemma mgf_indicator {X : Ω → ℝ} (hm : Measurable X) + (hX : ∀ ω, X ω = 0 ∨ X ω = 1) (p t : ℝ) (hp : ∫ ω, X ω ∂μ = p) : + mgf X μ t = 1 + p * (exp t - 1) := by + have hXi : Integrable X μ := Integrable.of_mem_Icc 0 1 hm.aemeasurable + (ae_of_all _ (indicator_mem_Icc hX)) + have heq : (fun ω => exp (t * X ω)) = fun ω => (1 : ℝ) + (exp t - 1) * X ω := by + funext ω + rcases hX ω with h | h <;> simp [h] + rw [mgf, heq, integral_add (integrable_const _) (hXi.const_mul _), integral_const_mul, + hp, integral_const] + simp [mul_comm] + +lemma mgf_indicator_sum_bound {X : I → Ω → ℝ} (s : Finset I) + (hm : ∀ i, Measurable (X i)) (hi : iIndepFun X μ) + (hX : ∀ i ω, X i ω = 0 ∨ X i ω = 1) + (p t : ℝ) (hp : ∀ i, ∫ ω, X i ω ∂μ = p) : + mgf (∑ i ∈ s, X i) μ t ≤ exp ((s.card : ℝ) * p * (exp t - 1)) := by + by_cases hs : s.Nonempty + swap + · have he := Finset.not_nonempty_iff_eq_empty.mp hs + simp [he] + rw [hi.mgf_sum hm] + have heq : (∏ i ∈ s, mgf (X i) μ t) = (1 + p * (exp t - 1)) ^ s.card := by + simp_rw [mgf_indicator (hm _) (hX _) p t (hp _)] + simp + rw [heq] + have hn : 0 ≤ 1 + p * (exp t - 1) := by + obtain ⟨i, _⟩ := hs + rw [← mgf_indicator (hm i) (hX i) p t (hp i)] + exact mgf_nonneg + calc + (1 + p * (exp t - 1)) ^ s.card ≤ exp (p * (exp t - 1)) ^ s.card := + pow_le_pow_left₀ hn (by linarith [add_one_le_exp (p * (exp t - 1))]) _ + _ = _ := by rw [← exp_nat_mul]; congr 1; ring + +lemma exp_neg_half_bound : exp (-(1 / 2 : ℝ)) ≤ 5 / 8 := by + have he : exp (1 / 2 : ℝ) * exp (1 / 2 : ℝ) = exp 1 := by + rw [← exp_add]; norm_num + have hlow : (8 / 5 : ℝ) ≤ exp (1 / 2 : ℝ) := by + nlinarith [exp_one_gt_d9, exp_pos (1 / 2 : ℝ)] + rw [exp_neg] + exact (inv_le_comm₀ (exp_pos _) (by norm_num)).mpr (by norm_num at *; exact hlow) + +lemma exp_half_bound : exp (1 / 2 : ℝ) ≤ 5 / 3 := by + have he : exp (1 / 2 : ℝ) * exp (1 / 2 : ℝ) = exp 1 := by + rw [← exp_add]; norm_num + nlinarith [exp_one_lt_d9, exp_pos (1 / 2 : ℝ)] + +theorem bernoulli_sum_lower_tail {X : I → Ω → ℝ} (s : Finset I) + (hm : ∀ i, Measurable (X i)) (hi : iIndepFun X μ) + (hX : ∀ i ω, X i ω = 0 ∨ X i ω = 1) + (p : ℝ) (hp0 : 0 ≤ p) (hp : ∀ i, ∫ ω, X i ω ∂μ = p) : + μ.real {ω | (∑ i ∈ s, X i ω) ≤ p * s.card / 2} ≤ exp (-p * s.card / 8) := by + have hInt : Integrable (fun ω => exp (-(1 / 2 : ℝ) * (∑ i ∈ s, X i) ω)) μ := + hi.integrable_exp_mul_sum hm (fun i _ => integrable_exp_mul_of_mem_Icc + (hm i).aemeasurable (ae_of_all _ (indicator_mem_Icc (hX i)))) + have hb := measure_le_le_exp_mul_mgf (X := ∑ i ∈ s, X i) (p * s.card / 2) + (by norm_num : -(1 / 2 : ℝ) ≤ 0) hInt + simp only [Finset.sum_apply] at hb + apply hb.trans + calc + _ ≤ exp (-(-(1 / 2 : ℝ)) * (p * s.card / 2)) * + exp ((s.card : ℝ) * p * (exp (-(1 / 2 : ℝ)) - 1)) := by + exact mul_le_mul_of_nonneg_left (mgf_indicator_sum_bound s hm hi hX p _ hp) (exp_pos _).le + _ = exp (p * s.card / 4 + (s.card : ℝ) * p * (exp (-(1 / 2 : ℝ)) - 1)) := by + rw [← exp_add]; congr 1; ring + _ ≤ _ := by + apply exp_le_exp.mpr + nlinarith [mul_le_mul_of_nonneg_left exp_neg_half_bound + (mul_nonneg (Nat.cast_nonneg s.card) hp0)] + +theorem bernoulli_sum_upper_tail {X : I → Ω → ℝ} (s : Finset I) + (hm : ∀ i, Measurable (X i)) (hi : iIndepFun X μ) + (hX : ∀ i ω, X i ω = 0 ∨ X i ω = 1) + (p : ℝ) (hp0 : 0 ≤ p) (hp : ∀ i, ∫ ω, X i ω ∂μ = p) : + μ.real {ω | 2 * p * s.card ≤ ∑ i ∈ s, X i ω} ≤ exp (-p * s.card / 3) := by + have hInt : Integrable (fun ω => exp ((1 / 2 : ℝ) * (∑ i ∈ s, X i) ω)) μ := + hi.integrable_exp_mul_sum hm (fun i _ => integrable_exp_mul_of_mem_Icc + (hm i).aemeasurable (ae_of_all _ (indicator_mem_Icc (hX i)))) + have hb := measure_ge_le_exp_mul_mgf (X := ∑ i ∈ s, X i) (2 * p * s.card) + (by norm_num : (0 : ℝ) ≤ 1 / 2) hInt + simp only [Finset.sum_apply] at hb + apply hb.trans + calc + _ ≤ exp (-(1 / 2 : ℝ) * (2 * p * s.card)) * + exp ((s.card : ℝ) * p * (exp (1 / 2 : ℝ) - 1)) := by + exact mul_le_mul_of_nonneg_left (mgf_indicator_sum_bound s hm hi hX p _ hp) (exp_pos _).le + _ = exp (-p * s.card + (s.card : ℝ) * p * (exp (1 / 2 : ℝ) - 1)) := by + rw [← exp_add]; congr 1; ring + _ ≤ _ := by + apply exp_le_exp.mpr + nlinarith [mul_le_mul_of_nonneg_left exp_half_bound + (mul_nonneg (Nat.cast_nonneg s.card) hp0)] + +end BernoulliBounds + +noncomputable section +variable {V : Type cycleUniverse4} [Fintype V] [DecidableEq V] + +def CutExpansion (P : SimpleGraph V) [DecidableRel P.Adj] (h : ℝ) : Prop := + ∀ U : Finset V, h * min (U.card : ℝ) (Uᶜ.card : ℝ) ≤ + ((P.interedges U Uᶜ).card : ℝ) + +lemma boundary_sym2_injective (P : SimpleGraph V) [DecidableRel P.Adj] + (U : Finset V) : + Set.InjOn (fun e : V × V => s(e.1, e.2)) (P.interedges U Uᶜ : Set (V × V)) := by + intro e he f hf hef + rcases (Sym2.mk_eq_mk_iff.mp hef) with h | h + · exact h + · have he1 := (P.mem_interedges_iff.mp he).1 + have hf2 := (P.mem_interedges_iff.mp hf).2.1 + have hfirst : e.1 = f.2 := congrArg Prod.fst h + exact False.elim ((Finset.mem_compl.mp hf2) (hfirst ▸ he1)) + +def edgeColorMeasure (V : Type cycleUniverse5) [Fintype V] (l : ℕ) [NeZero l] : + Measure (Sym2 V → Fin l) := + Measure.pi (fun _ : Sym2 V => (PMF.uniformOfFintype (Fin l)).toMeasure) + +instance edgeColorMeasure_probability (l : ℕ) [NeZero l] : + IsProbabilityMeasure (edgeColorMeasure V l) := by + unfold edgeColorMeasure + infer_instance + +def colorIndicator {l : ℕ} (i : Fin l) (e : Sym2 V) (ω : Sym2 V → Fin l) : ℝ := + if ω e = i then 1 else 0 + +lemma colorIndicator_indep {V : Type cycleUniverse6} [_contextInstance1 : Fintype V] [_contextInstance2 : DecidableEq V] {l : ℕ} [NeZero l] (i : Fin l) : + iIndepFun (colorIndicator (V := V) i) (edgeColorMeasure V l) := by + exact iIndepFun_pi (X := fun _ : Sym2 V => fun j : Fin l => if j = i then (1 : ℝ) else 0) + (fun _ => (measurable_of_finite _).aemeasurable) + +lemma colorIndicator_integral {V : Type cycleUniverse7} [_contextInstance1 : Fintype V] [_contextInstance2 : DecidableEq V] {l : ℕ} [NeZero l] (i : Fin l) (e : Sym2 V) : + ∫ ω, colorIndicator i e ω ∂edgeColorMeasure V l = 1/(l : ℝ) := by + have hl := (measurePreserving_eval + (fun _ : Sym2 V => (PMF.uniformOfFintype (Fin l)).toMeasure) e).hasLaw + have hi := hl.integral_comp (f := fun j : Fin l => if j = i then (1 : ℝ) else 0) + (measurable_of_finite _).aestronglyMeasurable + rw [PMF.integral_eq_sum] at hi + simpa [edgeColorMeasure, colorIndicator, PMF.uniformOfFintype_apply] using hi + +def colorGraph (P : SimpleGraph V) {l : ℕ} (ω : Sym2 V → Fin l) (i : Fin l) : + SimpleGraph V where + Adj x y := P.Adj x y ∧ ω s(x,y) = i + symm := ⟨by intro x y h; exact ⟨h.1.symm, by simpa only [Sym2.eq_swap] using h.2⟩⟩ + loopless := ⟨by intro x h; exact P.irrefl h.1⟩ + +instance colorGraph_decidable (P : SimpleGraph V) [DecidableRel P.Adj] + {l : ℕ} (ω : Sym2 V → Fin l) (i : Fin l) : + DecidableRel (colorGraph P ω i).Adj := fun _ _ => inferInstanceAs (Decidable (_ ∧ _)) + +lemma colorGraph_interedges {V : Type cycleUniverse8} [_contextInstance1 : Fintype V] [_contextInstance2 : DecidableEq V] (P : SimpleGraph V) [DecidableRel P.Adj] + {l : ℕ} (ω : Sym2 V → Fin l) (i : Fin l) (S T : Finset V) : + (colorGraph P ω i).interedges S T = + (P.interedges S T).filter (fun e => ω s(e.1,e.2) = i) := by + ext ⟨x,y⟩ + simp only [SimpleGraph.mem_interedges_iff, Finset.mem_filter] + change (x ∈ S ∧ y ∈ T ∧ (P.Adj x y ∧ ω s(x,y) = i)) ↔ _ + tauto + +lemma color_cut_sum (P : SimpleGraph V) [DecidableRel P.Adj] + {l : ℕ} (ω : Sym2 V → Fin l) (i : Fin l) (S : Finset V) : + (∑ e ∈ (P.interedges S Sᶜ).image (fun e => s(e.1,e.2)), colorIndicator i e ω) = + (((colorGraph P ω i).interedges S Sᶜ).card : ℝ) := by + rw [Finset.sum_image (boundary_sym2_injective P S)] + simp only [colorIndicator, Finset.sum_boole, colorGraph_interedges] + +lemma color_cut_lower_tail (P : SimpleGraph V) [DecidableRel P.Adj] + {l : ℕ} [NeZero l] (i : Fin l) (S : Finset V) {h : ℝ} + (hexp : CutExpansion P h) (hS : S.card ≤ Sᶜ.card) : + (edgeColorMeasure V l).real {ω | + (((colorGraph P ω i).interedges S Sᶜ).card : ℝ) < h*S.card/(2*l)} ≤ + exp (-h*S.card/(8*l)) := by + let E := (P.interedges S Sᶜ).image (fun e => s(e.1,e.2)) + have hcard : E.card = (P.interedges S Sᶜ).card := + Finset.card_image_of_injOn (boundary_sym2_injective P S) + have hl : 0 < (l : ℝ) := by exact_mod_cast Nat.pos_of_ne_zero (NeZero.ne l) + have hcut : h * S.card ≤ (E.card : ℝ) := by + rw [hcard] + have he := hexp S + rwa [min_eq_left (by exact_mod_cast hS)] at he + have hb := bernoulli_sum_lower_tail (μ := edgeColorMeasure V l) E + (fun e => measurable_of_finite (colorIndicator i e)) (colorIndicator_indep i) + (fun e ω => by simp only [colorIndicator]; split <;> simp) + (1/(l : ℝ)) (by positivity) (colorIndicator_integral i) + apply (measureReal_mono (show {ω | + (((colorGraph P ω i).interedges S Sᶜ).card : ℝ) < h*S.card/(2*l)} ⊆ + {ω | (∑ e ∈ E, colorIndicator i e ω) ≤ (1/(l : ℝ))*E.card/2} from ?_)).trans + (hb.trans ?_) + · intro ω hω + change (∑ e ∈ E, colorIndicator i e ω) ≤ (1/(l : ℝ))*E.card/2 + rw [show (∑ e ∈ E, colorIndicator i e ω) = + (((colorGraph P ω i).interedges S Sᶜ).card : ℝ) from color_cut_sum P ω i S] + calc + _ ≤ h*S.card/(2*l) := le_of_lt hω + _ ≤ (E.card : ℝ)/(2*l) := div_le_div_of_nonneg_right hcut (by positivity) + _ = _ := by ring + · apply exp_le_exp.mpr + have he := div_le_div_of_nonneg_right hcut (show 0 ≤ 8*(l : ℝ) by positivity) + calc + _ = -((E.card : ℝ)/(8*l)) := by ring + _ ≤ -(h*S.card/(8*l)) := neg_le_neg he + _ = _ := by ring + +lemma cutExpansion_of_small_cuts (P : SimpleGraph V) [DecidableRel P.Adj] {h : ℝ} + (hcut : ∀ S : Finset V, S.Nonempty → S.card ≤ Sᶜ.card → + h*S.card ≤ ((P.interedges S Sᶜ).card : ℝ)) : CutExpansion P h := by + intro S + by_cases he : S = ∅ + · simp [he] + by_cases hc : Sᶜ = ∅ + · simp [hc] + by_cases hs : S.card ≤ Sᶜ.card + · rw [min_eq_left (by exact_mod_cast hs)] + exact hcut S (Finset.nonempty_iff_ne_empty.mpr he) hs + · rw [min_eq_right (by exact_mod_cast le_of_not_ge hs)] + have hi := hcut Sᶜ (Finset.nonempty_iff_ne_empty.mpr hc) (by simpa using le_of_not_ge hs) + have hcomm : (P.interedges Sᶜ S).card = (P.interedges S Sᶜ).card := by + have := P.symm + exact Rel.card_interedges_comm Sᶜ S + simpa only [compl_compl, hcomm] using hi + +lemma sum_nonempty_subsets_power (q : ℝ) : + (∑ S ∈ (Finset.univ : Finset (Finset V)).erase ∅, q^S.card) = + (1+q)^(Fintype.card V)-1 := by + have hs := Finset.sum_erase_add (s := Finset.univ) (fun S : Finset V => q^S.card) + (Finset.mem_univ (∅ : Finset V)) + have hp := Finset.prod_one_add (s := (Finset.univ : Finset V)) (f := fun _ => q) + simp only [Finset.prod_const, Finset.card_univ, Finset.powerset_univ] at hp + simp only [Finset.card_empty, pow_zero] at hs + linarith + +theorem edge_splitting_failure_bound (P : SimpleGraph V) [DecidableRel P.Adj] + {l : ℕ} [NeZero l] {h : ℝ} (hexp : CutExpansion P h) : + (edgeColorMeasure V l).real {ω | ∃ i, ¬CutExpansion (colorGraph P ω i) (h/(2*l))} ≤ + l * (exp ((Fintype.card V : ℝ)*exp (-h/(8*l)))-1) := by + let cuts : Finset (Finset V) := Finset.univ.erase ∅ + let B (i : Fin l) (S : Finset V) : Set (Sym2 V → Fin l) := + {ω | S.card ≤ Sᶜ.card ∧ + (((colorGraph P ω i).interedges S Sᶜ).card : ℝ) < h*S.card/(2*l)} + let q : ℝ := exp (-h/(8*l)) + have cover : {ω | ∃ i, ¬CutExpansion (colorGraph P ω i) (h/(2*l))} ⊆ + ⋃ i ∈ (Finset.univ : Finset (Fin l)), ⋃ S ∈ cuts, B i S := by + intro ω hω + rcases hω with ⟨i, hi⟩ + by_contra hn + apply hi + apply cutExpansion_of_small_cuts + intro S hS hs + have hb : ω ∉ B i S := by + intro hm + apply hn + exact Set.mem_iUnion.mpr ⟨i, Set.mem_iUnion.mpr ⟨Finset.mem_univ _, + Set.mem_iUnion.mpr ⟨S, Set.mem_iUnion.mpr + ⟨Finset.mem_erase.mpr ⟨hS.ne_empty, Finset.mem_univ _⟩, hm⟩⟩⟩⟩ + have hc : h*S.card/(2*l) ≤ (((colorGraph P ω i).interedges S Sᶜ).card : ℝ) := by + exact le_of_not_gt (fun hf => hb ⟨hs, hf⟩) + convert hc using 1 ; ring + have hbound (i : Fin l) (S : Finset V) : + (edgeColorMeasure V l).real (B i S) ≤ q^S.card := by + by_cases hs : S.card ≤ Sᶜ.card + · calc + _ ≤ (edgeColorMeasure V l).real {ω | + (((colorGraph P ω i).interedges S Sᶜ).card : ℝ) < h*S.card/(2*l)} := + measureReal_mono (fun _ hw => hw.2) + _ ≤ exp (-h*S.card/(8*l)) := color_cut_lower_tail P i S hexp hs + _ = q^S.card := by dsimp [q]; rw [← exp_nat_mul]; congr 1; ring + · have he : B i S = ∅ := by ext ω; simp [B,hs] + rw [he, measureReal_empty] + exact pow_nonneg (exp_pos _).le _ + calc + _ ≤ (edgeColorMeasure V l).real + (⋃ i ∈ (Finset.univ : Finset (Fin l)), ⋃ S ∈ cuts, B i S) := + measureReal_mono cover (measure_ne_top _ _) + _ ≤ ∑ i : Fin l, (edgeColorMeasure V l).real (⋃ S ∈ cuts, B i S) := + measureReal_biUnion_finset_le _ _ + _ ≤ ∑ i : Fin l, ∑ S ∈ cuts, (edgeColorMeasure V l).real (B i S) := + Finset.sum_le_sum (fun _ _ => measureReal_biUnion_finset_le _ _) + _ ≤ ∑ _i : Fin l, ∑ S ∈ cuts, q^S.card := by + apply Finset.sum_le_sum; intro i _; exact Finset.sum_le_sum (fun S _ => hbound i S) + _ = (l : ℝ)*((1+q)^(Fintype.card V)-1) := by + simp only [cuts, sum_nonempty_subsets_power, Finset.sum_const, Finset.card_univ, + Fintype.card_fin, nsmul_eq_mul] + _ ≤ l*(exp ((Fintype.card V : ℝ)*q)-1) := by + apply mul_le_mul_of_nonneg_left _ (Nat.cast_nonneg l) + apply sub_le_sub_right + calc + _ ≤ (exp q)^(Fintype.card V) := + pow_le_pow_left₀ (by dsimp [q]; positivity) (by linarith [add_one_le_exp q]) _ + _ = _ := (exp_nat_mul _ _).symm + +theorem edge_splitting_of_error_lt_one (P : SimpleGraph V) [DecidableRel P.Adj] + {l : ℕ} [NeZero l] {h : ℝ} (hexp : CutExpansion P h) + (herror : (l : ℝ)*(exp ((Fintype.card V : ℝ)*exp (-h/(8*l)))-1) < 1) : + ∃ ω : Sym2 V → Fin l, + (∀ i, CutExpansion (colorGraph P ω i) (h/(2*l))) ∧ + (∀ x y, P.Adj x y ↔ ∃ i, (colorGraph P ω i).Adj x y) ∧ + (∀ i j, i ≠ j → Disjoint (colorGraph P ω i).edgeSet (colorGraph P ω j).edgeSet) := by + have he := (edge_splitting_failure_bound P hexp).trans_lt herror + have hh : ∃ ω : Sym2 V → Fin l, ∀ i, CutExpansion (colorGraph P ω i) (h/(2*l)) := by + by_contra hn + push Not at hn + have hall : {ω : Sym2 V → Fin l | ∃ i, ¬CutExpansion (colorGraph P ω i) (h/(2*l))} = + Set.univ := Set.eq_univ_of_forall hn + simp only [hall, Measure.real, measure_univ, ENNReal.toReal_one] at he + exact (lt_irrefl _ he) + obtain ⟨ω, hω⟩ := hh + refine ⟨ω, hω, ?_, ?_⟩ + · intro x y + exact ⟨fun hxy => ⟨ω s(x,y), hxy, rfl⟩, fun ⟨_, hxy, _⟩ => hxy⟩ + · intro i j hij + apply Set.disjoint_left.mpr + intro e hei hej + induction e using Sym2.ind with | _ x y => + have hi : (colorGraph P ω i).Adj x y := by simpa using hei + have hj : (colorGraph P ω j).Adj x y := by simpa using hej + exact hij (hi.2.symm.trans hj.2) + +end + +open Filter Asymptotics +open scoped Topology + +lemma tendsto_monomial_exp_neg_power (a b c : ℝ) (hb : 0 < b) (hc : 0 < c) : + Tendsto (fun D : ℝ => D^a * exp (-c * D^b)) atTop (𝓝 0) := by + have ht := (tendsto_rpow_mul_exp_neg_mul_atTop_nhds_zero (a/b) c hc).comp + (tendsto_rpow_atTop hb) + apply ht.congr' + filter_upwards [eventually_gt_atTop (0 : ℝ)] with D hD + dsimp only [Function.comp_def] + rw [← Real.rpow_mul hD.le, mul_div_cancel₀ _ hb.ne'] + +noncomputable def edgeSplittingScaleError (c : ℝ) (l : ℕ) (D : ℝ) : ℝ := + (l : ℝ) * (Real.exp (D^(51/50 : ℝ) * Real.exp ((-(c / (8*l))) * D^(9/10 : ℝ))) - 1) + +lemma edgeSplittingScaleError_tendsto (c : ℝ) (hc : 0 < c) (l : ℕ) (hl : 0 < l) : + Tendsto (edgeSplittingScaleError c l) atTop (𝓝 0) := by + have hlR : 0 < (l : ℝ) := by exact_mod_cast hl + have ht := tendsto_monomial_exp_neg_power (51/50) (9/10) (c/(8*l)) + (by norm_num) (by positivity) + have hh := ((Real.continuous_exp.tendsto 0).comp ht).sub_const 1 |>.const_mul (l : ℝ) + unfold edgeSplittingScaleError + convert hh using 1 <;> norm_num + +universe u + +theorem edge_splitting_uniform (c : ℝ) (hc : 0 < c) (l : ℕ) (hl : 0 < l) : + ∃ D₀ : ℝ, ∀ D : ℝ, D₀ ≤ D → ∀ (V : Type u) [Fintype V] [DecidableEq V] + (P : SimpleGraph V) [DecidableRel P.Adj] (h : ℝ), + c*D^(9/10 : ℝ) ≤ h → D^(9/10 : ℝ) ≤ (Fintype.card V : ℝ) → + (Fintype.card V : ℝ) ≤ D^(51/50 : ℝ) → CutExpansion P h → + ∃ ω : Sym2 V → Fin l, + (∀ i, CutExpansion (colorGraph P ω i) (h/(2*l))) ∧ + (∀ x y, P.Adj x y ↔ ∃ i, (colorGraph P ω i).Adj x y) ∧ + (∀ i j, i ≠ j → Disjoint (colorGraph P ω i).edgeSet (colorGraph P ω j).edgeSet) := by + have : NeZero l := ⟨hl.ne'⟩ + have hlR : 0 < (l : ℝ) := by exact_mod_cast hl + have hevent := (edgeSplittingScaleError_tendsto c hc l hl).eventually_lt_const + (show (0 : ℝ) < 1 by norm_num) + obtain ⟨D₀,hD₀⟩ := hevent.exists_forall_of_atTop + refine ⟨D₀, ?_⟩ + intro D hD V _ _ P _ h hh _hrlo hrhi hexp + apply edge_splitting_of_error_lt_one P hexp + apply lt_of_le_of_lt _ (hD₀ D hD) + unfold edgeSplittingScaleError + apply mul_le_mul_of_nonneg_left _ hlR.le + apply sub_le_sub_right + apply exp_le_exp.mpr + apply mul_le_mul hrhi _ (exp_pos _).le ((Nat.cast_nonneg (Fintype.card V)).trans hrhi) + apply exp_le_exp.mpr + have he := div_le_div_of_nonneg_right hh (show 0 ≤ 8*(l : ℝ) by positivity) + calc + -h/(8*l) = -(h/(8*l)) := by ring + _ ≤ -(c*D^(9/10 : ℝ)/(8*l)) := neg_le_neg he + _ = -(c/(8*l))*D^(9/10 : ℝ) := by ring + +end ErdosGallai.Batch.Splitting + +namespace ErdosGallai.Batch +noncomputable section +open Real + +def inductionPhi (x : ℝ) : ℝ := + if x = 1 then 1/2 else max (1/2) (1 - 1 / sqrt (logb 2 x)) + +lemma inductionPhi_one : inductionPhi 1 = 1/2 := by simp [inductionPhi] + +lemma inductionPhi_bounds (x : ℝ) : 1/2 ≤ inductionPhi x ∧ inductionPhi x ≤ 1 := by + by_cases hx : x = 1 + · norm_num [inductionPhi, hx] + · simp only [inductionPhi, hx, ite_false] + exact ⟨le_max_left _ _, max_le (by norm_num) (by linarith [one_div_nonneg.mpr (Real.sqrt_nonneg (logb 2 x))])⟩ + +lemma inductionPhi_monotone : MonotoneOn inductionPhi (Set.Ici 1) := by + intro x hx y hy hxy + by_cases hx1 : x = 1 + · simpa [hx1, inductionPhi_one] using (inductionPhi_bounds y).1 + have hxgt : 1 < x := lt_of_le_of_ne hx (Ne.symm hx1) + have hygt : 1 < y := hxgt.trans_le hxy + have hlog : logb 2 x ≤ logb 2 y := Real.logb_le_logb_of_le (by norm_num) + (by linarith) hxy + have hxlog : 0 < logb 2 x := Real.logb_pos (by norm_num) hxgt + have hinv := one_div_le_one_div_of_le (Real.sqrt_pos.mpr hxlog) (Real.sqrt_le_sqrt hlog) + simp only [inductionPhi, hx1, ne_of_gt hygt, ite_false] + exact max_le_max le_rfl (by linarith) + +lemma inductionPhi_nonconstant (x : ℝ) (hlog : 4 ≤ logb 2 x) : + inductionPhi x = 1 - 1 / sqrt (logb 2 x) := by + have hx : x ≠ 1 := by intro hx; subst x; norm_num at hlog + have hsqrt : 2 ≤ sqrt (logb 2 x) := by + convert Real.sqrt_le_sqrt hlog using 1 ; norm_num + have hinv : 1 / sqrt (logb 2 x) ≤ 1/2 := + one_div_le_one_div_of_le (by norm_num) hsqrt + simp only [inductionPhi, hx, ite_false] + exact max_eq_right (by linarith) + +def inductionDelta : ℝ := 1 / sqrt (3/10) - 1 + +lemma inductionDelta_pos : 0 < inductionDelta := by + have hs : 0 < sqrt (3/10 : ℝ) := Real.sqrt_pos.mpr (by norm_num) + have hs1 : sqrt (3/10 : ℝ) < 1 := by + exact (Real.sqrt_lt' (by norm_num)).mpr (by norm_num) + dsimp [inductionDelta] + have hh := (one_lt_div hs).mpr hs1 + linarith + +theorem induction_potential_gain (D n : ℝ) (hD : 1 < D) (hn : D ≤ n) + (hw : 40/3 ≤ logb 2 D) : + inductionDelta / sqrt (logb 2 D) ≤ inductionPhi n - inductionPhi (D^(3/10:ℝ)) := by + have hD0 : 0 < D := by linarith + have hw0 : 0 < logb 2 D := by linarith + have hnlog : logb 2 D ≤ logb 2 n := + Real.logb_le_logb_of_le (by norm_num) hD0 hn + have hblog : logb 2 (D^(3/10:ℝ)) = (3/10)*logb 2 D := by + exact Real.logb_rpow_eq_mul_logb_of_pos hD0 + rw [inductionPhi_nonconstant n (by linarith), + inductionPhi_nonconstant (D^(3/10:ℝ)) (by rw [hblog]; linarith), hblog] + have hinv := one_div_le_one_div_of_le (Real.sqrt_pos.mpr hw0) + (Real.sqrt_le_sqrt hnlog) + have hid : 1 / sqrt ((3/10)*logb 2 D) - 1 / sqrt (logb 2 D) = + inductionDelta / sqrt (logb 2 D) := by + rw [Real.sqrt_mul (by norm_num : (0:ℝ) ≤ 3/10)] + dsimp [inductionDelta] + field_simp + rw [← hid] + linarith + +lemma induction_cutoff_absorption (A w : ℝ) (hA : 0 ≤ A) (hw0 : 0 < w) + (hw : ((A+1)/inductionDelta)^2 ≤ w) : + (A+1)/w ≤ inductionDelta / sqrt w := by + have hd := inductionDelta_pos + have hratio : 0 ≤ (A+1)/inductionDelta := by positivity + have hs : (A+1)/inductionDelta ≤ sqrt w := by + have hh := Real.sqrt_le_sqrt hw + simpa [Real.sqrt_sq hratio] using hh + have hm : A+1 ≤ inductionDelta * sqrt w := by + have := (div_le_iff₀ hd).mp hs + simpa [mul_comm] using this + apply (div_le_div_iff₀ hw0 (Real.sqrt_pos.mpr hw0)).mpr + have hmul := mul_le_mul_of_nonneg_right hm (Real.sqrt_nonneg w) + simpa [mul_assoc, Real.mul_self_sqrt hw0.le] using hmul + +theorem induction_cost_absorbed (D n S C A₁ A₂ : ℝ) + (hD : 1 < D) (hn : D ≤ n) (hS : 0 ≤ S) (hC : 0 ≤ C) + (hA₁ : 0 ≤ A₁) (_hA₂ : 0 ≤ A₂) (hCA : 7*A₂ ≤ C) + (hw : 40/3 ≤ logb 2 D) + (hcut : ((A₁+1)/inductionDelta)^2 ≤ logb 2 D) : + A₂*(S+n/logb 2 D) + (C/100)*S + + C*inductionPhi (D^(3/10:ℝ))*(n-S/3+A₁*n/logb 2 D) ≤ C*inductionPhi n*n := by + let f := inductionPhi (D^(3/10:ℝ)) + obtain ⟨hflo,hfhi⟩ := inductionPhi_bounds (D^(3/10:ℝ)) + have hw0 : 0 < logb 2 D := by linarith + have hn0 : 0 ≤ n := by linarith + have hnw : 0 ≤ n/logb 2 D := div_nonneg hn0 hw0.le + have hcoeff : A₂+C/100-C*f/3 ≤ 0 := by + dsimp [f] + nlinarith [mul_le_mul_of_nonneg_left hflo hC] + have hScost := mul_nonpos_of_nonpos_of_nonneg hcoeff hS + have hA₂C : A₂ ≤ C := by linarith + have hAprod : C*f*A₁ ≤ C*A₁ := by + exact mul_le_mul_of_nonneg_right (by + simpa [f] using mul_le_mul_of_nonneg_left hfhi hC) hA₁ + have how := mul_le_mul_of_nonneg_right (add_le_add hA₂C hAprod) hnw + have habs := induction_cutoff_absorption A₁ (logb 2 D) hA₁ hw0 hcut + have hgain := induction_potential_gain D n hD hn hw + have hpay := mul_le_mul_of_nonneg_left (habs.trans hgain) (mul_nonneg hC hn0) + change A₂*(S+n/logb 2 D) + (C/100)*S + C*f*(n-S/3+A₁*n/logb 2 D) ≤ _ + change C*n*((A₁+1)/logb 2 D) ≤ C*n*(inductionPhi n - f) at hpay + simp only [div_eq_mul_inv] at hScost how hpay ⊢ + nlinarith only [hScost, how, hpay] + +end +end ErdosGallai.Batch + +namespace ErdosGallai.Batch +noncomputable section +open Finset SimpleGraph Real +attribute [local instance] Classical.propDecidable +variable {V : Type} [Fintype V] [DecidableEq V] + +lemma cutExpansionOn_of_induce (P : SimpleGraph V) [DecidableRel P.Adj] + (W : Finset V) (h : ℝ) (he : CutExpansion (P.induce (W:Set V)) h) : CutExpansionOn P W h := by + intro A hA + let B : Finset (W:Set V) := univ.filter (fun x => x.val ∈ A) + have him : B.image Subtype.val = A := by + ext x + simp only [Finset.mem_image] + constructor + · rintro ⟨y,hy,rfl⟩; exact (Finset.mem_filter.mp hy).2 + · intro hx; exact ⟨⟨x,hA hx⟩,by simp [B,hx],rfl⟩ + have hcomp := subtype_image_compl W B + rw [him] at hcomp + have hh := he B + rw [induced_interedges_card,him] at hh + have hc : B.card = A.card := by rw [← him,Finset.card_image_of_injective _ Subtype.val_injective] + have hcc : Bᶜ.card = (W \ A).card := by rw [← hcomp,Finset.card_image_of_injective _ Subtype.val_injective] + simpa only [hc,hcc] using hh + +lemma cutExpansionOn_mono {V : Type} [_contextInstance1 : Fintype V] [_contextInstance2 : DecidableEq V] {P Q : SimpleGraph V} [DecidableRel P.Adj] [DecidableRel Q.Adj] + {W : Finset V} {h : ℝ} (he : CutExpansionOn P W h) (hPQ : P ≤ Q) : CutExpansionOn Q W h := by + intro A hA + exact (he A hA).trans (Nat.cast_le.mpr (Finset.card_le_card (by + intro e he + simp only [SimpleGraph.mem_interedges_iff] at he ⊢ + exact ⟨he.1,he.2.1,hPQ he.2.2⟩))) + +theorem uniform_two_routers_on : ∃ D₀ : ℝ, ∀ D ≥ D₀, + ∀ (V : Type) [Fintype V] [DecidableEq V] (R : SimpleGraph V) (W : Finset V), + (∀ ⦃x y⦄, R.Adj x y → x ∈ W ∧ y ∈ W) → + D^(9/10:ℝ) ≤ (W.card:ℝ) → (W.card:ℝ) ≤ D^(51/50:ℝ) → + CutExpansionOn R W (D^(9/10:ℝ)) → + ∃ P T : SimpleGraph V, P ≤ R ∧ T ≤ R ∧ Disjoint P.edgeSet T.edgeSet ∧ + P.edgeSet ∪ T.edgeSet = R.edgeSet ∧ + CutExpansionOn P W (D^(9/10:ℝ)/4) ∧ CutExpansionOn T W (D^(9/10:ℝ)/4) := by + obtain ⟨D₀,hsplit⟩ := Splitting.edge_splitting_uniform 1 (by norm_num) 2 (by norm_num) + refine ⟨D₀,?_⟩ + intro D hD V _ _ R W hW hlo hhi he + let R' := R.induce (W:Set V) + have he' : Splitting.CutExpansion R' (D^(9/10:ℝ)) := cutExpansion_induce R W _ he + obtain ⟨ω,hω,hcover,hdis⟩ := hsplit D hD (W:Set V) R' (D^(9/10:ℝ)) + (by simp) (by simpa using hlo) (by simpa using hhi) he' + let f : (W:Set V) ↪ V := ⟨Subtype.val,Subtype.val_injective⟩ + let Q (i : Fin 2) := (Splitting.colorGraph R' ω i).map f + have hQR (i : Fin 2) : Q i ≤ R := by + apply SimpleGraph.map_le_iff_le_comap.mpr + exact fun _ _ h => h.1 + have hind (i) : (Q i).induce (W:Set V) = Splitting.colorGraph R' ω i := + SimpleGraph.comap_map_eq f _ + have hexp (i) : @CutExpansionOn V _ (Q i) (fun _ _ => Classical.propDecidable _) W (D^(9/10:ℝ)/4) := by + apply @cutExpansionOn_of_induce V _ _ (Q i) (fun _ _ => Classical.propDecidable _) W + have hcol : CutExpansion (Splitting.colorGraph R' ω i) (D^(9/10:ℝ)/4) := by simpa only [CutExpansion, Splitting.CutExpansion, Nat.cast_ofNat, show (2:ℝ)*2=4 by norm_num] using hω i + convert hcol using 1 ; simp only [hind] + have hQedge (i) : (Q i).edgeSet = Sym2.map (Subtype.val : ↥(W:Set V) → V) '' + (Splitting.colorGraph R' ω i).edgeSet := SimpleGraph.edgeSet_map f _ + refine ⟨Q 0,Q 1,hQR 0,hQR 1,?_,?_,hexp 0,hexp 1⟩ + · rw [hQedge,hQedge] + apply Set.disjoint_left.mpr + rintro e ⟨a,ha,hae⟩ ⟨b,hb,hbe⟩ + have hab := Sym2.map.injective Subtype.val_injective (hae.trans hbe.symm) + subst b + exact Set.disjoint_left.mp (hdis 0 1 (by decide)) ha hb + · apply Set.Subset.antisymm + · exact Set.union_subset (SimpleGraph.edgeSet_mono (hQR 0)) (SimpleGraph.edgeSet_mono (hQR 1)) + · intro e heR + induction e using Sym2.ind with + | _ x y => + have hxy : R.Adj x y := heR + obtain ⟨i,hi⟩ := (hcover ⟨x,(hW hxy).1⟩ ⟨y,(hW hxy).2⟩).mp hxy + have hm : s(x,y) ∈ (Q i).edgeSet := by + rw [hQedge] + exact ⟨s(⟨x,(hW hxy).1⟩,⟨y,(hW hxy).2⟩),hi,rfl⟩ + fin_cases i + · exact Or.inl hm + · exact Or.inr hm + +end +end ErdosGallai.Batch + +namespace ErdosGallai.Batch +noncomputable section +open SimpleGraph Finset +attribute [local instance] Classical.propDecidable + +lemma decompositionCost_adjoin_same {V I J : Type} [Fintype V] [Fintype I] [Fintype J] + (G : SimpleGraph V) (parts : I → Set (Sym2 V)) + (hp : ∀ i, CycleOrSingleEdge G (parts i)) + (hd : Pairwise fun i j => Disjoint (parts i) (parts j)) + (H : J → SimpleGraph V) (hHG : ∀ j, H j ≤ G) + (hHH : Pairwise fun i j => Disjoint (H i).edgeSet (H j).edgeSet) + (hHP : ∀ j i, Disjoint (H j).edgeSet (parts i)) + (hu : (⋃ i, parts i) ∪ (⋃ j, (H j).edgeSet) = G.edgeSet) : + decompositionCost G ≤ Fintype.card I + ∑ j, decompositionCost (H j) := by + let f : ∀ j, H j →g G := fun j => ⟨id,fun h => hHG j h⟩ + have he (j) : Sym2.map (f j) '' (H j).edgeSet = (H j).edgeSet := by + have hf : (f j : V → V) = id := rfl + rw [hf, Sym2.map_id, Set.image_id] + apply decompositionCost_adjoin G parts hp hd (fun _ => V) H f (fun _ => Function.injective_id) + · simpa only [he] using hHH + · simpa only [he] using hHP + · simpa only [he] using hu + +lemma decompositionCost_assemble_same {V J : Type} [Fintype V] [Fintype J] + (G : SimpleGraph V) (H : J → SimpleGraph V) (hHG : ∀ j, H j ≤ G) + (hHH : Pairwise fun i j => Disjoint (H i).edgeSet (H j).edgeSet) + (hu : (⋃ j, (H j).edgeSet) = G.edgeSet) : + decompositionCost G ≤ ∑ j, decompositionCost (H j) := by + simpa using decompositionCost_adjoin_same (I := Empty) G Empty.elim (fun i => nomatch i) + (by intro i; exact i.elim) H hHG hHH (fun _ i => nomatch i) (by simpa using hu) + +end +end ErdosGallai.Batch + +namespace ErdosGallai.Batch +noncomputable section +open Finset SimpleGraph Real +attribute [local instance] Classical.propDecidable + +def routerRemainder {V : Type} (R : SimpleGraph V) (used : Set (Sym2 V)) : SimpleGraph V := + R \ SimpleGraph.fromEdgeSet used + +lemma routerRemainder_edges {V : Type} (R : SimpleGraph V) (used : Set (Sym2 V)) : + (routerRemainder R used).edgeSet = R.edgeSet \ used := by + simp [routerRemainder,SimpleGraph.edgeSet_sdiff] + +lemma routerRemainder_le {V : Type} (R : SimpleGraph V) (used : Set (Sym2 V)) : + routerRemainder R used ≤ R := fun _ _ h => h.1 + +lemma protected_le_remainder {V : Type} {R T : SimpleGraph V} {used : Set (Sym2 V)} + (hTR : T ≤ R) (htu : Disjoint T.edgeSet used) : T ≤ routerRemainder R used := by + apply SimpleGraph.edgeSet_subset_edgeSet.mp + rw [routerRemainder_edges] + exact fun _ he => ⟨SimpleGraph.edgeSet_mono hTR he,fun hu => Set.disjoint_left.mp htu he hu⟩ + +lemma protected_avoids_used {V A : Type} (R P T : A → SimpleGraph V) + (hRR : Pairwise fun i j => Disjoint (R i).edgeSet (R j).edgeSet) + (hPR : ∀ i, P i ≤ R i) (hTR : ∀ i, T i ≤ R i) + (hTP : ∀ i, Disjoint (T i).edgeSet (P i).edgeSet) + (used : Set (Sym2 V)) (hu : used ⊆ ⋃ i, (P i).edgeSet) : + ∀ i, Disjoint (T i).edgeSet used := by + intro i + apply Set.disjoint_left.mpr + intro e he heu + obtain ⟨j,hj⟩ := Set.mem_iUnion.mp (hu heu) + by_cases hij : i = j + · subst j; exact Set.disjoint_left.mp (hTP i) he hj + · exact Set.disjoint_left.mp (hRR hij) (SimpleGraph.edgeSet_mono (hTR i) he) + (SimpleGraph.edgeSet_mono (hPR j) hj) + +lemma batch_remainder_ledger {V A K : Type} [Fintype V] [Fintype A] [Fintype K] + (G F : SimpleGraph V) (R : A → SimpleGraph V) + (hRG : ∀ i, R i ≤ G) + (hRR : Pairwise fun i j => Disjoint (R i).edgeSet (R j).edgeSet) + (hFR : ∀ i, Disjoint F.edgeSet (R i).edgeSet) + (hcover : F.edgeSet ∪ (⋃ i, (R i).edgeSet) = G.edgeSet) + (parts : K → Set (Sym2 V)) (hp : ∀ k, CycleOrSingleEdge G (parts k)) + (hd : Pairwise fun j k => Disjoint (parts j) (parts k)) + (used : Set (Sym2 V)) (hu : used ⊆ ⋃ i, (R i).edgeSet) + (hparts : (⋃ k, parts k) = F.edgeSet ∪ used) : + decompositionCost G ≤ Fintype.card K + ∑ i, decompositionCost (routerRemainder (R i) used) := by + apply decompositionCost_adjoin_same G parts hp hd (fun i => routerRemainder (R i) used) + (fun i => (routerRemainder_le _ _).trans (hRG i)) + · intro i j hij + exact (hRR hij).mono (SimpleGraph.edgeSet_mono (routerRemainder_le _ _)) + (SimpleGraph.edgeSet_mono (routerRemainder_le _ _)) + · intro i k + rw [routerRemainder_edges] + apply Set.disjoint_left.mpr + intro e he hp + have hpe : e ∈ F.edgeSet ∪ used := hparts ▸ Set.mem_iUnion.mpr ⟨k,hp⟩ + rcases hpe with hpe | hpe + · exact Set.disjoint_left.mp (hFR i) hpe he.1 + · exact he.2 hpe + · rw [hparts,← hcover] + simp_rw [routerRemainder_edges] + ext e + simp only [Set.mem_union,Set.mem_iUnion,Set.mem_sdiff] + constructor + · rintro ((hf | hu') | ⟨i,hi,_⟩) + · exact Or.inl hf + · exact Or.inr (Set.mem_iUnion.mp (hu hu')) + · exact Or.inr ⟨i,hi⟩ + · rintro (hf | ⟨i,hi⟩) + · exact Or.inl (Or.inl hf) + · by_cases he : e ∈ used + · exact Or.inl (Or.inr he) + · exact Or.inr ⟨i,hi,he⟩ + +lemma prepared_quotient_cost {V I : Type} [Fintype V] [Fintype I] + (J : SimpleGraph V) (X : I → Finset V) (hd : Pairwise fun i j => Disjoint (X i) (X j)) + (p : PreparedBatch J X hd) (W : Finset V) + (hW : ∀ ⦃x y⦄, J.Adj x y → x ∈ W ∧ y ∈ W) + (hX : ∀ i, X i ⊆ W) (n : ℕ) (M t : ℝ) (_ht : 0 ≤ t) (hn : W.card < n) (hM : (W.card:ℝ) ≤ M) + (ih : ∀ (A : Type) [Fintype A] (H : SimpleGraph A), Fintype.card A < n → (Fintype.card A:ℝ) ≤ M → + (decompositionCost H:ℝ) ≤ t * Fintype.card A) : + ∃ k, EdgeDecomposition p.quotient k ∧ + (k:ℝ) ≤ t * ((W.card:ℝ) - ∑ i, ((X i).card / 2:ℕ)) := by + classical + let A := W.image (familyProject X hd p.pairing) + let H := p.quotient.induce (A:Set (FamilyQuotient X p.pairing)) + have ho : A.card + ∑ i, (X i).card / 2 = W.card := family_quotient_image_order X hd p.pairing W hX + have hn' : Fintype.card (A:Set (FamilyQuotient X p.pairing)) < n := by simp only [Finset.coe_sort_coe,Fintype.card_coe]; omega + refine ⟨decompositionCost H,edgeDecomposition_on _ A (p.quotient_supported W hW) (decompositionCost_spec H),?_⟩ + have hc := ih (A:Set (FamilyQuotient X p.pairing)) H hn' (by simp only [Finset.coe_sort_coe,Fintype.card_coe]; exact (Nat.cast_le.mpr (by omega : A.card ≤ W.card)).trans hM) + simp only [Finset.coe_sort_coe,Fintype.card_coe] at hc + have heq : (A.card:ℝ) = (W.card:ℝ) - ∑ i, ((X i).card / 2:ℕ) := by + have hh : (A.card:ℝ) + ∑ i, ((X i).card / 2:ℕ) = W.card := by exact_mod_cast ho + linarith + rwa [heq] at hc + +end +end ErdosGallai.Batch + +namespace ErdosGallai.Batch +noncomputable section +open Finset SimpleGraph Real +attribute [local instance] Classical.propDecidable + +theorem uniform_coupled_resolution_cost : ∃ D₀ : ℝ, 1 < D₀ ∧ ∀ D ≥ D₀, + ∀ (V A B : Type) [Fintype V] [Fintype A] [Fintype B], + ∀ (G F : SimpleGraph V) (R : A → SimpleGraph V) (U : A → Finset V), + F ≤ G → (∀ r, R r ≤ G) → + Pairwise (fun r s => Disjoint (R r).edgeSet (R s).edgeSet) → + Pairwise (fun r s => Disjoint (U r) (U s)) → + (∀ r, ∀ ⦃x y⦄, (R r).Adj x y → x ∈ U r ∧ y ∈ U r) → + (∀ r, Disjoint F.edgeSet (R r).edgeSet) → + F.edgeSet ∪ (⋃ r, (R r).edgeSet) = G.edgeSet → + (∀ r, CutExpansionOn (R r) (U r) (D^(9/10:ℝ))) → + (∀ r, D^(9/10:ℝ) ≤ ((U r).card:ℝ) ∧ ((U r).card:ℝ) ≤ D^(51/50:ℝ)) → + ∀ (J : B → SimpleGraph V) (W : B → Finset V), + (∀ b, J b ≤ F) → Pairwise (fun b c => Disjoint (J b).edgeSet (J c).edgeSet) → + (⋃ b, (J b).edgeSet) = F.edgeSet → + (∀ b, ∀ ⦃x y⦄, (J b).Adj x y → x ∈ W b ∧ y ∈ W b) → + (∀ b, ((W b).card:ℝ) ≤ D^(3/10:ℝ)) → + ∀ (I : B → Type) [∀ b, Fintype (I b)] (X : ∀ b, I b → Finset V) + (_hXd : ∀ b, Pairwise fun i j => Disjoint (X b i) (X b j)), + (∀ b i, X b i ⊆ W b) → + ∀ rX : ∀ b, I b → A, + (∀ b i, X b i ⊆ U (rX b i)) → + (∀ b i v, v ∈ X b i → (F.degree v:ℝ) ≤ D^(1/100:ℝ)) → + 1 ≤ D^(1/100:ℝ) → (∀ b i, 8 ≤ (X b i).card) → + (∀ b i, (D^(1/100:ℝ))^2 ≤ (X b i).card) → + ∀ (n : ℕ) (t : ℝ), 0 ≤ t → (∀ b, (W b).card < n) → + (∀ (Q : Type) [Fintype Q] (H : SimpleGraph Q), Fintype.card Q < n → + (Fintype.card Q:ℝ) ≤ D^(3/10:ℝ) → (decompositionCost H:ℝ) ≤ t * Fintype.card Q) → + ∃ H : A → SimpleGraph V, + (∀ r, H r ≤ R r) ∧ + (∀ r, CutExpansionOn (H r) (U r) (D^(9/10:ℝ)/4)) ∧ + (decompositionCost G:ℝ) ≤ + t * ((∑ b, ((W b).card:ℝ)) - ∑ b, ∑ i, ((X b i).card / 2:ℕ)) + + 8 * (∑ b, ∑ i, ((X b i).card:ℝ)) + ∑ r, (decompositionCost (H r):ℝ) := by + obtain ⟨D₁,hsplit⟩ := uniform_two_routers_on + obtain ⟨D₂,hD₂,hresolve⟩ := uniform_batch_resolution + refine ⟨max D₁ D₂,lt_of_lt_of_le hD₂ (le_max_right _ _),?_⟩ + intro D hD V A B _ _ _ G F R U hFG hRG hRR hUU hRU hFR hcover he hr + J W hJF hJJ hJu hW hWnum I _ X hXd hXW rX hXU hdeg ha hm hma n t ht hn ih + have hs (r : A) := hsplit D ((le_max_left _ _).trans hD) V (R r) (U r) + (hRU r) (hr r).1 (hr r).2 (he r) + choose P T hPR hTR hPT hPu hPe hTe using hs + have hPP : Pairwise fun r s => Disjoint (P r).edgeSet (P s).edgeSet := + fun _ _ h => (hRR h).mono (SimpleGraph.edgeSet_mono (hPR _)) (SimpleGraph.edgeSet_mono (hPR _)) + have hp (b : B) : Nonempty (PreparedBatch (J b) (X b) (hXd b)) := + prepare_batch (J b) (X b) (hXd b) (D^(1/100:ℝ)) ha (hm b) (hma b) + (fun i v hv => (Nat.cast_le.mpr (SimpleGraph.degree_le_of_le (hJF b))).trans (hdeg b i v hv)) + let prep (b : B) := Classical.choice (hp b) + have hq (b : B) := prepared_quotient_cost (J b) (X b) (hXd b) (prep b) (W b) + (hW b) (hXW b) n (D^(3/10:ℝ)) t ht (hn b) (hWnum b) ih + choose k hk hkc using hq + obtain ⟨K,hK,parts,used,hcount,hparts,hdis,hused,hFu,hpartscover⟩ := + hresolve D ((le_max_right _ _).trans hD) V A B G F P U hFG + (fun r => (hPR r).trans (hRG r)) hPP hUU + (fun r => (hFR r).mono_right (SimpleGraph.edgeSet_mono (hPR r))) hPe hr + J W hJF hJJ hJu hW hWnum I X hXd hXW rX hXU hdeg prep k hk + let : Fintype K := hK + have husedR : used ⊆ ⋃ r, (R r).edgeSet := hused.trans (Set.iUnion_mono fun r => SimpleGraph.edgeSet_mono (hPR r)) + have hTu := protected_avoids_used R P T hRR hPR hTR (fun r => (hPT r).symm) used hused + let H (r : A) := routerRemainder (R r) used + have hcost := batch_remainder_ledger G F R hRG hRR hFR hcover parts hparts hdis used husedR hpartscover + refine ⟨H,fun r => routerRemainder_le _ _,fun r => ?_,?_⟩ + · exact cutExpansionOn_mono (hTe r) (protected_le_remainder (hTR r) (hTu r)) + · have hkreal : (Fintype.card K:ℝ) ≤ (∑ b, (k b:ℝ)) + 8 * (∑ b, ∑ i, ((X b i).card:ℝ)) := by + exact_mod_cast hcount + have hqsum := Finset.sum_le_sum (s := univ) (fun b _ => hkc b) + have hqsum' : (∑ b, (k b:ℝ)) ≤ + t * ((∑ b, ((W b).card:ℝ)) - ∑ b, ∑ i, ((X b i).card / 2:ℕ)) := by + simpa only [Finset.mul_sum,Finset.sum_sub_distrib,mul_sub,Nat.cast_sum] using hqsum + have hc : (decompositionCost G:ℝ) ≤ (Fintype.card K:ℝ) + ∑ r, (decompositionCost (H r):ℝ) := by + exact_mod_cast hcost + linarith + +end +end ErdosGallai.Batch + +end +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/CycleDecomposition/CycleLifting.lean b/lean/OAI/Combinatorics/CycleDecomposition/CycleLifting.lean new file mode 100644 index 0000000000000000000000000000000000000000..9fbb004f764bf4e78b89c83370669667180c7ee0 --- /dev/null +++ b/lean/OAI/Combinatorics/CycleDecomposition/CycleLifting.lean @@ -0,0 +1,835 @@ +import OAI.Combinatorics.CycleDecomposition.BatchRouting + +namespace OAI + +universe cycleUniverse1 cycleUniverse2 cycleUniverse3 cycleUniverse4 cycleUniverse5 cycleUniverse6 cycleUniverse7 cycleUniverse8 cycleUniverse9 cycleUniverse10 cycleUniverse11 cycleUniverse12 cycleUniverse13 cycleUniverse14 cycleUniverse15 cycleUniverse16 cycleUniverse17 cycleUniverse18 cycleUniverse19 cycleUniverse20 + +section +open Filter Asymptotics Real +open scoped Topology +noncomputable section +open MeasureTheory ProbabilityTheory Finset +section +namespace ErdosGallai.Batch +noncomputable section +open Real Filter Asymptotics + +lemma routing_length_upper (r h : ℝ) (hr : 2 ≤ r) (hh : 0 < h) (hhr : h ≤ r) : + (routingLength r h : ℝ) ≤ 108*(r/h)*(logb 2 r)^2 := by + have hr0 : 0 < r := by linarith + have hl : 1 ≤ logb 2 r := by + simpa using Real.logb_le_logb_of_le (by norm_num : (1:ℝ) < 2) + (by norm_num : (0:ℝ) < 2) hr + have hR : 1 ≤ r/h := (le_div_iff₀ hh).mpr (by simpa using hhr) + have hlog : logb 2 (2*r) = 1 + logb 2 r := by + rw [Real.logb_mul (by norm_num) hr0.ne'] + norm_num + have hg := Nat.ceil_lt_add_one (show 0 ≤ 8*(r/h)*logb 2 (2*r) by rw [hlog]; positivity) + have hd := Nat.ceil_lt_add_one (show 0 ≤ logb 2 r by linarith) + change (routingG r h : ℝ) < 8*(r/h)*logb 2 (2*r)+1 at hg + change (routingDepth r : ℝ) < logb 2 r + 1 at hd + rw [hlog] at hg + have hprod : 1 ≤ (r/h)*logb 2 r := by + nlinarith [mul_nonneg (sub_nonneg.mpr hR) (sub_nonneg.mpr hl)] + have hg' : (routingG r h : ℝ) ≤ 18*(r/h)*logb 2 r := by nlinarith + have hd' : (1 + routingDepth r : ℝ) ≤ 3*logb 2 r := by linarith + have hm := mul_le_mul hg' hd' (by positivity) (by positivity) + dsimp [routingLength] + push_cast + nlinarith + +lemma eventually_logb_le_power (ε : ℝ) (hε : 0 < ε) : + ∀ᶠ D : ℝ in atTop, logb 2 D ≤ D^ε := by + have ho := (isLittleO_log_rpow_atTop hε).const_mul_left (1 / log 2) + filter_upwards [ho.eventuallyLE, eventually_ge_atTop (1:ℝ)] with D hD h1 + simpa [Real.logb, div_eq_mul_inv, mul_comm, Real.norm_eq_abs, + abs_of_nonneg (Real.log_nonneg h1), abs_of_nonneg (Real.rpow_nonneg (by linarith) ε), + abs_of_pos (show 0 < (log 2)⁻¹ by positivity), + abs_of_pos (Real.log_pos (by norm_num : (1:ℝ) < 2))] using hD + +lemma eventually_constant_le_power (C ε : ℝ) (hε : 0 < ε) : + ∀ᶠ D : ℝ in atTop, C ≤ D^ε := + (tendsto_rpow_atTop hε).eventually (eventually_ge_atTop C) + +lemma eventually_const_mul_power_le (C α β : ℝ) (hab : α < β) : + ∀ᶠ D : ℝ in atTop, C*D^α ≤ D^β := by + filter_upwards [eventually_constant_le_power C (β-α) (by linarith), + eventually_gt_atTop (0:ℝ)] with D hc hD + calc + C*D^α ≤ D^(β-α)*D^α := mul_le_mul_of_nonneg_right hc (Real.rpow_nonneg hD.le _) + _ = D^β := by rw [← Real.rpow_add hD]; congr 1; ring + +theorem eventually_routing_length (c β γ δ : ℝ) (hc : 0 < c) (hβ : 0 < β) + (hδ : 0 < δ) : + ∀ᶠ D : ℝ in atTop, ∀ r : ℝ, 2 ≤ r → r ≤ D^β → c*D^γ ≤ r → + (routingLength r (c*D^γ) : ℝ) ≤ D^(β-γ+δ) := by + filter_upwards [eventually_logb_le_power (δ/4) (by positivity), + eventually_constant_le_power (108*β^2/c) (δ/2) (by positivity), + eventually_gt_atTop (1:ℝ)] with D hlog hconst hD r hr hrD hhr + have hD0 : 0 < D := by linarith + have hpowγ : 0 < D^γ := Real.rpow_pos_of_pos hD0 _ + have hden : 0 < c*D^γ := mul_pos hc hpowγ + have hlog0 : 0 ≤ logb 2 r := (Real.logb_pos (by norm_num) (by linarith)).le + have hlogR : logb 2 r ≤ β*D^(δ/4) := by + have hh := Real.logb_le_logb_of_le (by norm_num : (1:ℝ) < 2) + (by linarith : 0 < r) hrD + rw [Real.logb_rpow_eq_mul_logb_of_pos hD0] at hh + exact hh.trans (mul_le_mul_of_nonneg_left hlog hβ.le) + have hratio : r/(c*D^γ) ≤ D^(β-γ)/c := by + calc + _ ≤ D^β/(c*D^γ) := div_le_div_of_nonneg_right hrD hden.le + _ = _ := by rw [Real.rpow_sub hD0]; ring + have hsq : (logb 2 r)^2 ≤ β^2*D^(δ/2) := by + calc + _ ≤ (β*D^(δ/4))^2 := pow_le_pow_left₀ hlog0 hlogR 2 + _ = _ := by rw [mul_pow, ← Real.rpow_mul_natCast hD0.le]; congr 2; ring + calc + (routingLength r (c*D^γ) : ℝ) ≤ 108*(r/(c*D^γ))*(logb 2 r)^2 := + routing_length_upper r (c*D^γ) hr hden hhr + _ ≤ 108*(D^(β-γ)/c)*(β^2*D^(δ/2)) := by gcongr + _ = (108*β^2/c)*D^(β-γ+δ/2) := by rw [Real.rpow_add hD0]; ring + _ ≤ D^(δ/2)*D^(β-γ+δ/2) := + mul_le_mul_of_nonneg_right hconst (Real.rpow_nonneg hD0.le _) + _ = D^(β-γ+δ) := by rw [← Real.rpow_add hD0]; congr 1; ring + +theorem batch_routing_margin : ∃ D₀ : ℝ, 1 < D₀ ∧ ∀ D ≥ D₀, + ∀ r : ℝ, D^(9/10:ℝ) ≤ r → r ≤ D^(51/50:ℝ) → + 2 ≤ r ∧ 64*((routingLength r (D^(9/10:ℝ)/4) : ℝ)^2* + (D^(1/100:ℝ)+D^(3/10:ℝ))+2*D^(3/10:ℝ)) ≤ D^(9/10:ℝ)/4 := by + have hev : ∀ᶠ D : ℝ in atTop, ∀ r : ℝ, D^(9/10:ℝ) ≤ r → r ≤ D^(51/50:ℝ) → + 2 ≤ r ∧ 64*((routingLength r (D^(9/10:ℝ)/4) : ℝ)^2* + (D^(1/100:ℝ)+D^(3/10:ℝ))+2*D^(3/10:ℝ)) ≤ D^(9/10:ℝ)/4 := by + filter_upwards [eventually_routing_length (1/4) (51/50) (9/10) (2/25) + (by norm_num) (by norm_num) (by norm_num), + eventually_const_mul_power_le 1024 (7/10) (9/10) (by norm_num), + eventually_constant_le_power 2 (9/10) (by norm_num), + eventually_gt_atTop (1:ℝ)] with D hlen hcost htwo hD r hr hrD + have hD0 : 0 < D := by linarith + have hr2 : 2 ≤ r := htwo.trans hr + have hh : (1/4)*D^(9/10:ℝ) ≤ r := by + have hh0 := Real.rpow_nonneg hD0.le (9/10:ℝ) + linarith + have hL := hlen r hr2 hrD hh + norm_num at hL + have hL' : (routingLength r (D^(9/10:ℝ)/4) : ℝ) ≤ D^(1/5:ℝ) := by + convert hL using 1 ; ring_nf + have hsmall : D^(1/100:ℝ) ≤ D^(3/10:ℝ) := Real.rpow_le_rpow_of_exponent_le hD.le (by norm_num) + have h37 : D^(3/10:ℝ) ≤ D^(7/10:ℝ) := Real.rpow_le_rpow_of_exponent_le hD.le (by norm_num) + have hprod : (routingLength r (D^(9/10:ℝ)/4) : ℝ)^2* + (D^(1/100:ℝ)+D^(3/10:ℝ)) ≤ 2*D^(7/10:ℝ) := by + calc + _ ≤ (D^(1/5:ℝ))^2 * (2*D^(3/10:ℝ)) := by gcongr; linarith + _ = _ := by + rw [← Real.rpow_mul_natCast hD0.le] + norm_num + rw [mul_left_comm, ← Real.rpow_add hD0] + norm_num + refine ⟨hr2, ?_⟩ + nlinarith only [hprod, h37, hcost] + obtain ⟨A,hA⟩ := eventually_atTop.mp hev + refine ⟨max A 2, lt_of_lt_of_le (by norm_num) (le_max_right _ _), ?_⟩ + intro D hD + exact hA D ((le_max_left _ _).trans hD) + +lemma eventually_reservoir_capacity (c p : ℝ) (hc : 0 < c) (hp : 0 < p) : + ∀ᶠ D : ℝ in atTop, ∀ r : ℝ, 0 ≤ r → r ≤ D^(51/50:ℝ) → + (⌈8*r/(p*(c*D^(9/10:ℝ)))⌉₊ : ℝ) ≤ D^(13/100:ℝ) := by + filter_upwards [eventually_const_mul_power_le (8/(p*c)+1) (3/25) (13/100) (by norm_num), + eventually_gt_atTop (1:ℝ)] with D hbound hD r hr hrD + have hD0 : 0 < D := by linarith + have hden : 0 < p*(c*D^(9/10:ℝ)) := by positivity + have hone : 1 ≤ D^(3/25:ℝ) := Real.one_le_rpow hD.le (by norm_num) + have hx : 8*r/(p*(c*D^(9/10:ℝ))) ≤ (8/(p*c))*D^(3/25:ℝ) := by + calc + _ ≤ 8*D^(51/50:ℝ)/(p*(c*D^(9/10:ℝ))) := by gcongr + _ = _ := by + have heq : D^(3/25:ℝ) = D^(51/50:ℝ)/D^(9/10:ℝ) := by + rw [← Real.rpow_sub hD0]; norm_num + rw [heq]; ring + have hceil := Nat.ceil_lt_add_one (show 0 ≤ 8*r/(p*(c*D^(9/10:ℝ))) by positivity) + nlinarith only [hx, hceil, hone, hbound] + +theorem residue_routing_margin (c p : ℝ) (hc : 0 < c) (hp : 0 < p) : + ∃ D₀ : ℝ, 1 < D₀ ∧ ∀ D ≥ D₀, ∀ r rᵢ : ℝ, + 0 ≤ r → r ≤ D^(51/50:ℝ) → 2 ≤ rᵢ → rᵢ ≤ r → D^(37/50:ℝ) ≤ rᵢ → + 64*((routingLength rᵢ (D^(37/50:ℝ)) : ℝ)^2* + ((⌈8*r/(p*(c*D^(9/10:ℝ)))⌉₊ : ℝ)+1)) ≤ D^(37/50:ℝ) := by + have hev : ∀ᶠ D : ℝ in atTop, ∀ r rᵢ : ℝ, + 0 ≤ r → r ≤ D^(51/50:ℝ) → 2 ≤ rᵢ → rᵢ ≤ r → D^(37/50:ℝ) ≤ rᵢ → + 64*((routingLength rᵢ (D^(37/50:ℝ)) : ℝ)^2* + ((⌈8*r/(p*(c*D^(9/10:ℝ)))⌉₊ : ℝ)+1)) ≤ D^(37/50:ℝ) := by + filter_upwards [eventually_routing_length 1 (51/50) (37/50) (1/100) + (by norm_num) (by norm_num) (by norm_num), + eventually_reservoir_capacity c p hc hp, + eventually_const_mul_power_le 128 (71/100) (37/50) (by norm_num), + eventually_gt_atTop (1:ℝ)] with D hlen hcap hcost hD r rᵢ hr hrD hri2 hrir htau + have hD0 : 0 < D := by linarith + have hL := hlen rᵢ hri2 (hrir.trans hrD) (by simpa using htau) + norm_num at hL + have hk := hcap r hr hrD + have hone : 1 ≤ D^(13/100:ℝ) := Real.one_le_rpow hD.le (by norm_num) + have hprod : (routingLength rᵢ (D^(37/50:ℝ)) : ℝ)^2* + ((⌈8*r/(p*(c*D^(9/10:ℝ)))⌉₊ : ℝ)+1) ≤ 2*D^(71/100:ℝ) := by + calc + _ ≤ (D^(29/100:ℝ))^2 * (2*D^(13/100:ℝ)) := by gcongr; linarith + _ = _ := by + rw [← Real.rpow_mul_natCast hD0.le] + norm_num + rw [mul_left_comm, ← Real.rpow_add hD0] + norm_num + nlinarith only [hprod, hcost] + obtain ⟨A,hA⟩ := eventually_atTop.mp hev + refine ⟨max A 2, lt_of_lt_of_le (by norm_num) (le_max_right _ _), ?_⟩ + intro D hD + exact hA D ((le_max_left _ _).trans hD) + +end +end ErdosGallai.Batch + +namespace ErdosGallai.Batch +noncomputable section +open Finset +attribute [local instance] Classical.propDecidable + +variable {V : Type} [Fintype V] [DecidableEq V] + +def CutExpansionOn (P : SimpleGraph V) [DecidableRel P.Adj] (W : Finset V) (h : ℝ) : Prop := + ∀ A : Finset V, A ⊆ W → h * min (A.card : ℝ) ((W \ A).card : ℝ) ≤ + ((P.interedges A (W \ A)).card : ℝ) + +lemma subtype_image_compl {V : Type} [_contextInstance1 : Fintype V] [_contextInstance2 : DecidableEq V] (W : Finset V) (U : Finset (W : Set V)) : + Uᶜ.image Subtype.val = W \ U.image Subtype.val := by + ext v + simp only [Finset.mem_image, Finset.mem_compl, Finset.mem_sdiff] + constructor + · rintro ⟨x,hx,rfl⟩ + refine ⟨x.property,?_⟩ + rintro ⟨y,hy,he⟩ + exact hx (Subtype.ext he ▸ hy) + · rintro ⟨hv,hvU⟩ + refine ⟨⟨v,hv⟩,?_,rfl⟩ + intro hx + exact hvU ⟨⟨v,hv⟩,hx,rfl⟩ + +lemma induced_interedges_card (P : SimpleGraph V) [DecidableRel P.Adj] + (W : Finset V) (U : Finset (W : Set V)) : + (((P.induce (W : Set V)).interedges U Uᶜ).card : ℝ) = + ((P.interedges (U.image Subtype.val) (W \ U.image Subtype.val)).card : ℝ) := by + classical + let f : ↥(W : Set V) × ↥(W : Set V) → V × V := fun e => (e.1.val,e.2.val) + have hf : Function.Injective f := by + intro a b h + apply Prod.ext <;> apply Subtype.ext + · exact congrArg Prod.fst h + · exact congrArg Prod.snd h + have heq : ((P.induce (W : Set V)).interedges U Uᶜ).image f = + P.interedges (U.image Subtype.val) (W \ U.image Subtype.val) := by + rw [← subtype_image_compl W U] + ext e + simp only [SimpleGraph.mem_interedges_iff, Finset.mem_image] + constructor + · rintro ⟨a,⟨ha,hb,hab⟩,rfl⟩ + exact ⟨⟨a.1,ha,rfl⟩,⟨a.2,hb,rfl⟩,hab⟩ + · rintro ⟨⟨x,hx,hxe⟩,⟨y,hy,hye⟩,he⟩ + refine ⟨(x,y),⟨hx,hy,?_⟩,Prod.ext hxe hye⟩ + change P.Adj x.val y.val + simpa only [hxe,hye] using he + rw [← heq, Finset.card_image_of_injective _ hf] + +lemma cutExpansion_induce (P : SimpleGraph V) [DecidableRel P.Adj] + (W : Finset V) (h : ℝ) (hexp : CutExpansionOn P W h) : + CutExpansion (P.induce (W : Set V)) h := by + classical + intro U + have hsub : U.image Subtype.val ⊆ W := by + rintro v hv + obtain ⟨a,ha,rfl⟩ := Finset.mem_image.mp hv + exact a.property + have h := hexp (U.image Subtype.val) hsub + have he : W \ U.image Subtype.val = Uᶜ.image Subtype.val := + (subtype_image_compl W U).symm + rw [he] at h + simp only [Finset.card_image_of_injective _ Subtype.val_injective] at h + rw [induced_interedges_card,he] + exact h + +lemma pathInterior_map {A B : Type} [DecidableEq A] [DecidableEq B] + {H : SimpleGraph A} {J : SimpleGraph B} (f : H →g J) + (hf : Function.Injective f) {a b : A} (p : H.Walk a b) : + pathInterior (p.map f) = (pathInterior p).image f := by + classical + simp only [pathInterior, SimpleGraph.Walk.support_map] + rw [Finset.image_sdiff _ _ hf] + have hm : (p.support.map f).toFinset = p.support.toFinset.image f := by + ext v; simp + rw [hm] + simp + +theorem team_routing_on_set {I T : Type} [Fintype I] + (G P : SimpleGraph V) [DecidableRel P.Adj] (hPG : P ≤ G) + (W : Finset V) (h : ℝ) (hh : 0 < h) + (hexp : CutExpansionOn P W h) (hr : 2 ≤ W.card) + (x y : I → V) (hx : ∀ i, x i ∈ W) (hy : ∀ i, y i ∈ W) + (hxy : ∀ i, x i ≠ y i) (team : I → T) (Z : I → Finset V) + (k b z : ℝ) (hk : 1 ≤ k) (hb : 1 ≤ b) (hz : 0 ≤ z) + (hload : ∀ v, (endpointLoad univ x y v : ℝ) ≤ k) + (hteam : ∀ i, ((univ.filter (fun j => team j = team i)).card : ℝ) ≤ b) + (hZ : ∀ i, ((Z i).card : ℝ) ≤ z) + (hbudget : 64 * ((routingLength W.card h : ℝ)^2 * (k+b) + z) ≤ h) : + ∃ q : ∀ i, G.Walk (x i) (y i), + (∀ i, (q i).IsPath ∧ (q i).length ≤ routingLength W.card h ∧ + (∀ v ∈ (q i).support, v ∈ W) ∧ (q i).edgeSet ⊆ P.edgeSet ∧ + Disjoint (pathInterior (q i)) (Z i)) ∧ + Pairwise (fun i j => Disjoint (q i).edgeSet (q j).edgeSet) ∧ + (∀ i j, i ≠ j → team i = team j → + Disjoint (pathInterior (q i)) (pathInterior (q j))) := by + classical + let X : I → (W : Set V) := fun i => ⟨x i,hx i⟩ + let Y : I → (W : Set V) := fun i => ⟨y i,hy i⟩ + let Z' : I → Finset (W : Set V) := fun i => univ.filter (fun v => v.val ∈ Z i) + have hl (v : (W : Set V)) : (endpointLoad univ X Y v : ℝ) ≤ k := by + simpa only [endpointLoad,X,Y,Subtype.ext_iff] using hload v.val + have hz' : ∀ i, ((Z' i).card : ℝ) ≤ z := by + intro i + apply le_trans _ (hZ i) + have hc : (Z' i).card ≤ (Z i).card := by + apply Finset.card_le_card_of_injOn Subtype.val + · intro v hv; exact (Finset.mem_filter.mp hv).2 + · exact Subtype.val_injective.injOn + exact_mod_cast hc + obtain ⟨q,hq,hd,ht⟩ := routing (P.induce (W : Set V)) h hh + (cutExpansion_induce P W h hexp) (by simpa using hr) X Y + (fun i he => hxy i (congrArg Subtype.val he)) team Z' k b z hk hb hz hl hteam hz' + (by simpa using hbudget) + let f : (P.induce (W : Set V)) →g G := + { toFun := Subtype.val, map_rel' := fun ha => hPG ha } + have hf : Function.Injective f := Subtype.val_injective + have hcard : Fintype.card ↥(W : Set V) = W.card := Fintype.card_coe W + let Q : ∀ i, G.Walk (x i) (y i) := fun i => (q i).map f + refine ⟨Q,?_,?_,?_⟩ + · intro i + refine ⟨(hq i).1.map hf,?_,?_,?_,?_⟩ + · simpa only [Q,SimpleGraph.Walk.length_map,hcard] using (hq i).2.1 + · intro v hv + have hv' : v ∈ (q i).support.map f := by simpa only [Q,SimpleGraph.Walk.support_map] using hv + obtain ⟨a,ha,rfl⟩ := List.mem_map.mp hv' + exact a.property + · intro e he + rw [SimpleGraph.Walk.edgeSet_map] at he + obtain ⟨d,hd,rfl⟩ := he + induction d using Sym2.ind with + | _ a b => exact (q i).adj_of_mem_edges hd + · rw [show Q i = (q i).map f from rfl, pathInterior_map f hf] + apply Finset.disjoint_left.mpr + intro v hv hzv + obtain ⟨a,ha,rfl⟩ := Finset.mem_image.mp hv + exact Finset.disjoint_left.mp (hq i).2.2 ha (by simpa [Z',f] using hzv) + · intro i j hij + change Disjoint ((q i).map f).edgeSet ((q j).map f).edgeSet + rw [SimpleGraph.Walk.edgeSet_map,SimpleGraph.Walk.edgeSet_map, + Set.disjoint_image_iff (Sym2.map.injective hf)] + apply Set.disjoint_left.mpr + intro e he he' + exact Finset.disjoint_left.mp (hd i j hij) (by simpa using he) (by simpa using he') + · intro i j hij hteam' + change Disjoint (pathInterior ((q i).map f)) (pathInterior ((q j).map f)) + rw [pathInterior_map f hf,pathInterior_map f hf,Finset.disjoint_image hf] + exact ht i j hij hteam' + +theorem uniform_batch_routing : + ∃ D₀ : ℝ, 1 < D₀ ∧ ∀ D ≥ D₀, + ∀ (A : Type) [Fintype A] [DecidableEq A], + ∀ (G P : SimpleGraph A) [DecidableRel P.Adj], P ≤ G → + ∀ W : Finset A, CutExpansionOn P W (D^(9/10:ℝ)/4) → + D^(9/10:ℝ) ≤ (W.card : ℝ) → (W.card : ℝ) ≤ D^(51/50:ℝ) → + ∀ (I T : Type) [Fintype I] (x y : I → A), + (∀ i, x i ∈ W) → (∀ i, y i ∈ W) → (∀ i, x i ≠ y i) → + ∀ (team : I → T) (Z : I → Finset A), + (∀ v, (endpointLoad univ x y v : ℝ) ≤ D^(1/100:ℝ)) → + (∀ i, ((univ.filter (fun j => team j = team i)).card : ℝ) ≤ D^(3/10:ℝ)) → + (∀ i, ((Z i).card : ℝ) ≤ 2*D^(3/10:ℝ)) → + ∃ q : ∀ i, G.Walk (x i) (y i), + (∀ i, (q i).IsPath ∧ (q i).length ≤ routingLength W.card (D^(9/10:ℝ)/4) ∧ + (∀ v ∈ (q i).support, v ∈ W) ∧ (q i).edgeSet ⊆ P.edgeSet ∧ + Disjoint (pathInterior (q i)) (Z i)) ∧ + Pairwise (fun i j => Disjoint (q i).edgeSet (q j).edgeSet) ∧ + (∀ i j, i ≠ j → team i = team j → + Disjoint (pathInterior (q i)) (pathInterior (q j))) := by + obtain ⟨D₀,hD₀,hm⟩ := batch_routing_margin + refine ⟨D₀,hD₀,?_⟩ + intro D hD A _ _ G P _ hPG W hexp hr₁ hr₂ I T _ x y hx hy hxy team Z hl ht hZ + have hD1 : 1 < D := hD₀.trans_le hD + have hD0 : 0 < D := lt_trans zero_lt_one hD1 + obtain ⟨hr,hbudget⟩ := hm D hD W.card hr₁ hr₂ + apply team_routing_on_set G P hPG W _ (by positivity) hexp (by exact_mod_cast hr) + x y hx hy hxy team Z _ _ _ _ _ (by positivity) hl ht hZ hbudget + · exact Real.one_le_rpow hD1.le (by norm_num) + · exact Real.one_le_rpow hD1.le (by norm_num) + +end +end ErdosGallai.Batch + +namespace ErdosGallai.Batch +open SimpleGraph + +variable {V : Type cycleUniverse1} {G : SimpleGraph V} + +structure CycleVisit (G : SimpleGraph V) where + start : V + finish : V + walk : G.Walk start finish + +inductive VisitChain (G : SimpleGraph V) : V → V → Type _ + | single {u v : V} (p : G.Walk u v) : VisitChain G u v + | cons {u v w z : V} (p : G.Walk u v) (h : G.Adj v w) + (q : VisitChain G w z) : VisitChain G u z + +namespace VisitChain + +variable {u v : V} + +def walk : {u v : V} → VisitChain G u v → G.Walk u v + | _, _, .single p => p + | _, _, .cons p h q => p.append (.cons h q.walk) + +def visits : {u v : V} → VisitChain G u v → List (CycleVisit G) + | u, v, .single p => [⟨u,v,p⟩] + | u, _, .cons (v := v) p _ q => ⟨u,v,p⟩ :: q.visits + +def links : {u v : V} → VisitChain G u v → Set (Sym2 V) + | _, _, .single _ => ∅ + | _, _, .cons (v := v) (w := w) _ _ q => {s(v,w)} ∪ q.links + +def switchEdges (q : VisitChain G u v) : Set (Sym2 V) := + ⋃ p ∈ q.visits, p.walk.edgeSet + +lemma mem_support_iff (q : VisitChain G u v) (x : V) : + x ∈ q.walk.support ↔ ∃ p ∈ q.visits, x ∈ p.walk.support := by + induction q with + | single p => simp [walk, visits] + | cons p h q ih => + simp only [walk, Walk.mem_support_append_iff, Walk.support_cons, List.mem_cons, + ih, visits, List.mem_cons] + constructor + · rintro (hp | rfl | ⟨r,hr,hx⟩) + · exact ⟨_, Or.inl rfl, hp⟩ + · exact ⟨_, Or.inl rfl, p.end_mem_support⟩ + · exact ⟨r, Or.inr hr, hx⟩ + · rintro ⟨r, rfl | hr, hx⟩ + · exact Or.inl hx + · exact Or.inr (Or.inr ⟨r,hr,hx⟩) + +lemma isPath_of_separated (q : VisitChain G u v) + (hp : ∀ p ∈ q.visits, p.walk.IsPath) + (hd : q.visits.Pairwise (fun p r => p.walk.support.Disjoint r.walk.support)) : + q.walk.IsPath := by + induction q with + | single p => exact hp ⟨_,_,p⟩ (by simp [visits]) + | cons p h q ih => + have hpd := (List.pairwise_cons.mp hd).1 + have hqt := ih (fun r hr => hp r (by simp [visits, hr])) + (List.pairwise_cons.mp hd).2 + have hpt := hp ⟨_,_,p⟩ (by simp [visits]) + have hdisj : p.support.Disjoint q.walk.support := by + rw [List.disjoint_left] + intro x hx hqx + obtain ⟨r,hr,hxr⟩ := q.mem_support_iff x |>.mp hqx + exact hpd r hr hx hxr + apply Walk.IsPath.mk' + simpa only [walk, Walk.support_append, Walk.support_cons, List.tail_cons] + using (List.nodup_append').mpr ⟨hpt.support_nodup, hqt.support_nodup, hdisj⟩ + +lemma length_visits_le (q : VisitChain G u v) : q.visits.length ≤ q.walk.length + 1 := by + induction q with + | single p => simp [visits, walk] + | cons p h q ih => simp only [visits, List.length_cons, walk, Walk.length_append, + Walk.length_cons]; omega + +lemma edgeSet_eq (q : VisitChain G u v) : + q.walk.edgeSet = q.links ∪ q.switchEdges := by + induction q with + | single p => simp [walk, links, switchEdges, visits] + | cons p h q ih => + simp only [walk, Walk.edgeSet_append, Walk.edgeSet_cons, ih, links, + switchEdges, visits] + ext e + simp only [Set.mem_union, Set.mem_singleton_iff, Set.mem_insert_iff, + Set.mem_iUnion, List.mem_cons, exists_prop, or_and_right, exists_or, exists_eq_left] + tauto + +theorem close_cycle (q : VisitChain G u v) (hc : G.Adj v u) + (hp : ∀ p ∈ q.visits, p.walk.IsPath) + (hd : q.visits.Pairwise (fun p r => p.walk.support.Disjoint r.walk.support)) + (hn : 3 ≤ q.visits.length) : + (Walk.cons hc q.walk).IsCycle ∧ + (Walk.cons hc q.walk).edgeSet = {s(v,u)} ∪ q.links ∪ q.switchEdges ∧ + 3 ≤ (Walk.cons hc q.walk).length := by + have hpath := q.isPath_of_separated hp hd + have hlength := q.length_visits_le + have he : s(v,u) ∉ q.walk.edges := by + intro he + have hh := hpath.length_eq_one_of_mem_edges (Sym2.eq_swap ▸ he) + omega + refine ⟨Path.cons_isCycle ⟨q.walk,hpath⟩ hc he, ?_, ?_⟩ + · rw [Walk.edgeSet_cons, q.edgeSet_eq] + ext e + simp only [Set.mem_union, Set.mem_insert_iff, Set.mem_singleton_iff] + tauto + · simp only [Walk.length_cons] + omega + +end VisitChain + +namespace CycleVisit + +def ends (p : CycleVisit G) : Set V := {p.start, p.finish} +def interior (p : CycleVisit G) : Set V := {x | x ∈ p.walk.support} \ p.ends + +lemma separated_of_interiors (p q : CycleVisit G) + (he : Disjoint p.ends q.ends) + (hpq : Disjoint p.interior q.ends) (hqp : Disjoint q.interior p.ends) + (hi : Disjoint p.interior q.interior) : + p.walk.support.Disjoint q.walk.support := by + rw [List.disjoint_left] + intro x hx hy + by_cases hpx : x ∈ p.ends + · by_cases hqx : x ∈ q.ends + · exact Set.disjoint_left.mp he hpx hqx + · exact Set.disjoint_left.mp hqp ⟨hy,hqx⟩ hpx + · by_cases hqx : x ∈ q.ends + · exact Set.disjoint_left.mp hpq ⟨hx,hpx⟩ hqx + · exact Set.disjoint_left.mp hi ⟨hx,hpx⟩ ⟨hy,hqx⟩ + +end CycleVisit + +theorem quotient_cycle_inflation {u v : V} (q : VisitChain G u v) (hc : G.Adj v u) + (hp : ∀ p ∈ q.visits, p.walk.IsPath) + (he : q.visits.Pairwise (fun p r => Disjoint p.ends r.ends)) + (hf : ∀ p ∈ q.visits, ∀ r ∈ q.visits, Disjoint p.interior r.ends) + (hi : q.visits.Pairwise (fun p r => Disjoint p.interior r.interior)) + (hn : 3 ≤ q.visits.length) : + (Walk.cons hc q.walk).IsCycle ∧ + (Walk.cons hc q.walk).edgeSet = {s(v,u)} ∪ q.links ∪ q.switchEdges ∧ + 3 ≤ (Walk.cons hc q.walk).length := by + apply q.close_cycle hc hp _ hn + have hh := he.and hi + apply hh.imp_of_mem + intro p r hpm hrm hpr + exact p.separated_of_interiors r hpr.1 (hf p hpm r hrm) (hf r hrm p hpm) hpr.2 + +namespace VisitChain +variable {W : Type cycleUniverse2} {Q : SimpleGraph W} + +def of_walk (s t : W → V) (q : ∀ z, G.Walk (s z) (t z)) : + {a b : W} → (p : Q.Walk a b) → + (∀ d ∈ p.darts, G.Adj (t d.fst) (s d.snd)) → VisitChain G (s a) (t b) + | _, _, .nil, _ => .single (q _) + | a, b, .cons (v := c) h p, hr => .cons (q a) + (hr ⟨(a,c),h⟩ (by simp)) + (of_walk s t q p (by intro d hd; exact hr d (by simp [hd]))) + +lemma of_walk_visits (s t : W → V) (q : ∀ z, G.Walk (s z) (t z)) + {a b : W} (p : Q.Walk a b) + (hr : ∀ d ∈ p.darts, G.Adj (t d.fst) (s d.snd)) : + (of_walk s t q p hr).visits = p.support.map (fun z => (⟨s z,t z,q z⟩ : CycleVisit G)) := by + induction p with + | nil => rfl + | cons h p ih => simp [of_walk, visits, ih] + +lemma of_walk_links (s t : W → V) (q : ∀ z, G.Walk (s z) (t z)) + {a b : W} (p : Q.Walk a b) + (hr : ∀ d ∈ p.darts, G.Adj (t d.fst) (s d.snd)) : + (of_walk s t q p hr).links = {e | ∃ d ∈ p.darts, e = s(t d.fst,s d.snd)} := by + induction p with + | nil => ext e; simp [of_walk, links] + | cons h p ih => + ext e + simp [of_walk, links, ih, ] + +lemma of_walk_switchEdges (s t : W → V) (q : ∀ z, G.Walk (s z) (t z)) + {a b : W} (p : Q.Walk a b) + (hr : ∀ d ∈ p.darts, G.Adj (t d.fst) (s d.snd)) : + (of_walk s t q p hr).switchEdges = ⋃ z ∈ p.support, (q z).edgeSet := by + rw [switchEdges, of_walk_visits] + ext e + simp only [Set.mem_iUnion, List.mem_map, exists_prop] + constructor + · rintro ⟨r,⟨z,hz,rfl⟩,he⟩ + exact ⟨z,hz,he⟩ + · rintro ⟨z,hz,he⟩ + exact ⟨⟨s z,t z,q z⟩,⟨z,hz,rfl⟩,he⟩ + +end VisitChain + +theorem lift_quotient_cycle {W : Type cycleUniverse3} {Q : SimpleGraph W} + (s t : W → V) (q : ∀ z, G.Walk (s z) (t z)) + {a : W} (p : Q.Walk a a) (hp : p.IsCycle) + (hr : ∀ d ∈ p.dropLast.darts, G.Adj (t d.fst) (s d.snd)) + (hc : G.Adj (t p.penultimate) (s a)) + (hq : ∀ z ∈ p.dropLast.support, (q z).IsPath) + (hsep : ∀ z ∈ p.dropLast.support, ∀ w ∈ p.dropLast.support, + z ≠ w → (q z).support.Disjoint (q w).support) : + ∃ c : G.Walk (t p.penultimate) (t p.penultimate), c.IsCycle ∧ + c.edgeSet = {s(t p.penultimate,s a)} ∪ + {e | ∃ d ∈ p.dropLast.darts, e = s(t d.fst,s d.snd)} ∪ + (⋃ z ∈ p.dropLast.support, (q z).edgeSet) := by + let chain := VisitChain.of_walk s t q p.dropLast hr + have hv : chain.visits = p.dropLast.support.map (fun z => (⟨s z,t z,q z⟩ : CycleVisit G)) := + VisitChain.of_walk_visits s t q p.dropLast hr + have hpaths : ∀ v ∈ chain.visits, v.walk.IsPath := by + intro v hvv + rw [hv] at hvv + obtain ⟨z,hz,rfl⟩ := List.mem_map.mp hvv + exact hq z hz + have hpair : chain.visits.Pairwise (fun v w => v.walk.support.Disjoint w.walk.support) := by + rw [hv, List.pairwise_map] + apply (List.pairwise_iff_getElem).mpr + intro i j hi hj hij + have hne : p.dropLast.support[i] ≠ p.dropLast.support[j] := by + intro he + have hij' := hp.isPath_dropLast.support_nodup.getElem_inj_iff.mp he + omega + exact hsep _ (List.getElem_mem _) _ (List.getElem_mem _) hne + have hn : 3 ≤ chain.visits.length := by + rw [hv, List.length_map, Walk.length_support, Walk.length_dropLast] + have := hp.three_le_length + omega + obtain ⟨hcycle,hedges,_⟩ := chain.close_cycle hc hpaths hpair hn + refine ⟨Walk.cons hc chain.walk,hcycle,?_⟩ + rw [hedges, VisitChain.of_walk_links, VisitChain.of_walk_switchEdges] + +noncomputable section +attribute [local instance] Classical.propDecidable + +theorem orient_edge_representatives {W : Type cycleUniverse4} {Q : SimpleGraph W} + (projMap : V → W) (S : Set (Sym2 V)) (hSG : S ⊆ G.edgeSet) + (hrep : ∀ e ∈ Q.edgeSet, ∃ f ∈ S, Sym2.map projMap f = e) : + ∃ R : Q.Dart → G.Dart, ∀ d, + (R d).edge ∈ S ∧ projMap (R d).fst = d.fst ∧ projMap (R d).snd = d.snd := by + have hex : ∀ d : Q.Dart, ∃ r : G.Dart, + r.edge ∈ S ∧ projMap r.fst = d.fst ∧ projMap r.snd = d.snd := by + intro d + obtain ⟨f,hf,hmap⟩ := hrep d.edge d.edge_mem + induction f using Sym2.ind with + | _ x y => + have hadj : G.Adj x y := hSG hf + change s(projMap x,projMap y) = s(d.fst,d.snd) at hmap + rcases Sym2.eq_iff.mp hmap with he | he + · exact ⟨⟨(x,y),hadj⟩,hf,he.1,he.2⟩ + · refine ⟨⟨(y,x),hadj.symm⟩,?_,he.2,he.1⟩ + change s(y,x) ∈ S + simpa only [Sym2.eq_swap] using hf + exact Classical.axiomOfChoice hex + +def portFrom {A : Type cycleUniverse5} {W : Type cycleUniverse6} (L : List A) (f : A → W) (g : A → V) + (v₀ : V) (z : W) : V := + if h : ∃ d ∈ L, f d = z then g h.choose else v₀ + +lemma portFrom_on {A : Type cycleUniverse7} {W : Type cycleUniverse8} (L : List A) (f : A → W) (g : A → V) + (v₀ : V) (hn : (L.map f).Nodup) {d : A} (hd : d ∈ L) : + portFrom L f g v₀ (f d) = g d := by + have hex : ∃ e ∈ L, f e = f d := ⟨d,hd,rfl⟩ + rw [portFrom, dite_eq_left hex] + congr 1 + exact List.inj_on_of_nodup_map hn hex.choose_spec.1 hd hex.choose_spec.2 + +theorem choose_cycle_ports {W : Type cycleUniverse9} {Q : SimpleGraph W} + (projMap : V → W) (R : Q.Dart → G.Dart) + (hprojMap : ∀ d, projMap (R d).fst = d.fst ∧ projMap (R d).snd = d.snd) + {a : W} (p : Q.Walk a a) (hp : p.IsCycle) (v₀ : V) : + ∃ s t : W → V, + (∀ d ∈ p.darts, t d.fst = (R d).fst ∧ s d.snd = (R d).snd) ∧ + (∀ z ∈ p.dropLast.support, projMap (s z) = z ∧ projMap (t z) = z) := by + let s := portFrom p.darts (fun d => d.snd) (fun d => (R d).snd) v₀ + let t := portFrom p.darts (fun d => d.fst) (fun d => (R d).fst) v₀ + have hnf : (p.darts.map (fun d => d.fst)).Nodup := by + rw [Walk.map_fst_darts] + exact hp.nodup_dropLast_support + have hns : (p.darts.map (fun d => d.snd)).Nodup := by + rw [Walk.map_snd_darts] + exact hp.support_nodup + have ht : ∀ d ∈ p.darts, t d.fst = (R d).fst := fun d hd => + portFrom_on _ _ _ _ hnf hd + have hs : ∀ d ∈ p.darts, s d.snd = (R d).snd := fun d hd => + portFrom_on _ _ _ _ hns hd + refine ⟨s,t,fun d hd => ⟨ht d hd,hs d hd⟩,?_⟩ + intro z hz + have hz' : z ∈ p.support.dropLast := by + rw [← p.support_dropLast hp.not_nil] + exact hz + have hzt : z ∈ p.support.tail := + p.tail_support_perm_dropLast_support.mem_iff.mpr hz' + have hzf : z ∈ p.darts.map (fun d => d.fst) := by rwa [Walk.map_fst_darts] + have hzs : z ∈ p.darts.map (fun d => d.snd) := by rwa [Walk.map_snd_darts] + obtain ⟨d,hd,he⟩ := List.mem_map.mp hzf + obtain ⟨e,he',hee⟩ := List.mem_map.mp hzs + exact ⟨by rw [← hee,hs e he']; exact (hprojMap e).2, + by rw [← he,ht d hd]; exact (hprojMap d).1⟩ + +lemma last_dart_mem {W : Type cycleUniverse10} {Q : SimpleGraph W} {a b : W} + (p : Q.Walk a b) (hp : ¬p.Nil) : + (⟨(p.penultimate,b),p.adj_penultimate hp⟩ : Q.Dart) ∈ p.darts := by + have he := congrArg Walk.darts (p.concat_dropLast (p.adj_penultimate hp)) + rw [Walk.darts_concat] at he + rw [← he] + simp + +lemma cycle_darts_split {W : Type cycleUniverse11} {Q : SimpleGraph W} {a b : W} + (p : Q.Walk a b) (hp : ¬p.Nil) : + p.darts = p.dropLast.darts ++ [⟨(p.penultimate,b),p.adj_penultimate hp⟩] := by + have he := congrArg Walk.darts (p.concat_dropLast (p.adj_penultimate hp)) + simpa only [Walk.darts_concat, List.concat_eq_append] using he.symm + +theorem inflate_represented_cycle {W : Type cycleUniverse12} {Q : SimpleGraph W} + (R : Q.Dart → G.Dart) (s t : W → V) + {a : W} (p : Q.Walk a a) (hp : p.IsCycle) + (hports : ∀ d ∈ p.darts, t d.fst = (R d).fst ∧ s d.snd = (R d).snd) + (q : ∀ z, G.Walk (s z) (t z)) + (hq : ∀ z ∈ p.dropLast.support, (q z).IsPath) + (hsep : ∀ z ∈ p.dropLast.support, ∀ w ∈ p.dropLast.support, + z ≠ w → (q z).support.Disjoint (q w).support) : + ∃ (v : V) (c : G.Walk v v), c.IsCycle ∧ + c.edgeSet = {e | ∃ d ∈ p.darts, e = (R d).edge} ∪ + (⋃ z ∈ p.dropLast.support, (q z).edgeSet) := by + let last : Q.Dart := ⟨(p.penultimate,a),p.adj_penultimate hp.not_nil⟩ + have hlast : last ∈ p.darts := last_dart_mem p hp.not_nil + have hsub : p.dropLast.darts ⊆ p.darts := by + rw [Walk.darts_dropLast]; exact List.dropLast_subset _ + have hed : ∀ d ∈ p.darts, s(t d.fst,s d.snd) = (R d).edge := by + intro d hd + rw [(hports d hd).1,(hports d hd).2] + rfl + have hadj : ∀ d ∈ p.darts, G.Adj (t d.fst) (s d.snd) := by + intro d hd + rw [(hports d hd).1,(hports d hd).2] + exact (R d).adj + obtain ⟨c,hc,he⟩ := lift_quotient_cycle s t q p hp + (fun d hd => hadj d (hsub hd)) (hadj last hlast) hq hsep + refine ⟨_,c,hc,?_⟩ + rw [he] + have hlinks : {s(t p.penultimate,s a)} ∪ + {e | ∃ d ∈ p.dropLast.darts, e = s(t d.fst,s d.snd)} = + {e | ∃ d ∈ p.darts, e = (R d).edge} := by + ext e + simp only [Set.mem_union, Set.mem_singleton_iff, Set.mem_ofPred_eq] + constructor + · rintro (rfl | ⟨d,hd,rfl⟩) + · exact ⟨last,hlast,hed last hlast⟩ + · exact ⟨d,hsub hd,hed d (hsub hd)⟩ + · rintro ⟨d,hd,rfl⟩ + rw [cycle_darts_split p hp.not_nil] at hd + simp only [List.mem_append,List.mem_singleton] at hd + rcases hd with hd | rfl + · exact Or.inr ⟨d,hd,(hed d (hsub hd)).symm⟩ + · exact Or.inl (hed last hlast).symm + rw [hlinks] + +theorem interiors_disjoint_across_routers {I : Type cycleUniverse13} {R : Type cycleUniverse14} + (U : R → Set V) (hi : Pairwise (fun r s => Disjoint (U r) (U s))) + (router : I → R) (A : I → Set V) + (hA : ∀ i, A i ⊆ U (router i)) + (hteam : ∀ i j, i ≠ j → router i = router j → Disjoint (A i) (A j)) : + Pairwise (fun i j => Disjoint (A i) (A j)) := by + intro i j hij + by_cases hr : router i = router j + · exact hteam i j hij hr + · exact (hi hr).mono (hA i) (hA j) + +def cyclePortSet {W : Type cycleUniverse15} (S : Set W) (s t : W → V) : Set V := + {v | ∃ z ∈ S, v = s z ∨ v = t z} + +def visitInterior {W : Type cycleUniverse16} (s t : W → V) (q : ∀ z, G.Walk (s z) (t z)) + (z : W) : Set V := {x | x ∈ (q z).support ∧ x ≠ s z ∧ x ≠ t z} + +theorem switch_supports_separated {W : Type cycleUniverse17} + (S : Set W) (projMap : V → W) (s t : W → V) + (q : ∀ z, G.Walk (s z) (t z)) + (hproj : ∀ z ∈ S, projMap (s z) = z ∧ projMap (t z) = z) + (havoid : ∀ z ∈ S, Disjoint (visitInterior s t q z) (cyclePortSet S s t)) + (hinter : ∀ z ∈ S, ∀ w ∈ S, z ≠ w → + Disjoint (visitInterior s t q z) (visitInterior s t q w)) : + ∀ z ∈ S, ∀ w ∈ S, z ≠ w → (q z).support.Disjoint (q w).support := by + intro z hz w hw hzw + rw [List.disjoint_left] + intro x hx hy + by_cases hxend : x = s z ∨ x = t z + · have hxZ : x ∈ cyclePortSet S s t := ⟨z,hz,hxend⟩ + by_cases hyend : x = s w ∨ x = t w + · have hxprojMap : projMap x = z := by rcases hxend with rfl | rfl <;> simp_all + have hyprojMap : projMap x = w := by rcases hyend with rfl | rfl <;> simp_all + exact hzw (hxprojMap.symm.trans hyprojMap) + · exact Set.disjoint_left.mp (havoid w hw) + ⟨hy,fun he => hyend (Or.inl he),fun he => hyend (Or.inr he)⟩ hxZ + · have hxI : x ∈ visitInterior s t q z := + ⟨hx,fun he => hxend (Or.inl he),fun he => hxend (Or.inr he)⟩ + by_cases hyend : x = s w ∨ x = t w + · exact Set.disjoint_left.mp (havoid z hz) hxI ⟨w,hw,hyend⟩ + · exact Set.disjoint_left.mp (hinter z hz w hw hzw) hxI + ⟨hy,fun he => hyend (Or.inl he),fun he => hyend (Or.inr he)⟩ + +theorem cyclePortSet_eq_representative_vertices {W : Type cycleUniverse18} {Q : SimpleGraph W} + (R : Q.Dart → G.Dart) (s t : W → V) + {a : W} (p : Q.Walk a a) (hp : p.IsCycle) + (hports : ∀ d ∈ p.darts, t d.fst = (R d).fst ∧ s d.snd = (R d).snd) : + cyclePortSet {z | z ∈ p.dropLast.support} s t = + {v | ∃ d ∈ p.darts, v = (R d).fst ∨ v = (R d).snd} := by + have hmF : p.darts.map (fun d => d.fst) = p.dropLast.support := by + rw [Walk.map_fst_darts, p.support_dropLast hp.not_nil] + have hmS : ∀ z, z ∈ p.darts.map (fun d => d.snd) ↔ z ∈ p.dropLast.support := by + intro z + rw [Walk.map_snd_darts, p.support_dropLast hp.not_nil] + exact p.tail_support_perm_dropLast_support.mem_iff + ext v + constructor + · rintro ⟨z,hz,hv | hv⟩ + · obtain ⟨d,hd,hds⟩ := List.mem_map.mp ((hmS z).mpr hz) + exact ⟨d,hd,Or.inr (hv.trans (by rw [← hds]; exact (hports d hd).2))⟩ + · have hz' : z ∈ p.darts.map (fun d => d.fst) := by rwa [hmF] + obtain ⟨d,hd,hdf⟩ := List.mem_map.mp hz' + exact ⟨d,hd,Or.inl (hv.trans (by rw [← hdf]; exact (hports d hd).1))⟩ + · rintro ⟨d,hd,hv | hv⟩ + · refine ⟨d.fst,?_,Or.inr (hv.trans (hports d hd).1.symm)⟩ + rw [← hmF] + exact List.mem_map.mpr ⟨d,hd,rfl⟩ + · exact ⟨d.snd,(hmS _).mp (List.mem_map.mpr ⟨d,hd,rfl⟩), + Or.inl (hv.trans (hports d hd).2.symm)⟩ + +theorem complete_batch_cycle {W : Type cycleUniverse19} {Ridx : Type cycleUniverse20} {Q : SimpleGraph W} + (projMap : V → W) (R : Q.Dart → G.Dart) + (_hprojMap : ∀ d, projMap (R d).fst = d.fst ∧ projMap (R d).snd = d.snd) + {a : W} (p : Q.Walk a a) (hp : p.IsCycle) + (s t : W → V) + (hports : ∀ d ∈ p.darts, t d.fst = (R d).fst ∧ s d.snd = (R d).snd) + (hproj : ∀ z ∈ p.dropLast.support, projMap (s z) = z ∧ projMap (t z) = z) + (q : ∀ z, G.Walk (s z) (t z)) + (hq : ∀ z ∈ p.dropLast.support, (q z).IsPath) + (U : Ridx → Set V) (hU : Pairwise (fun i j => Disjoint (U i) (U j))) + (router : {z // z ∈ p.dropLast.support} → Ridx) + (hroute : ∀ z : {z // z ∈ p.dropLast.support}, + visitInterior s t q z ⊆ U (router z)) + (hteam : ∀ z w : {z // z ∈ p.dropLast.support}, z ≠ w → + router z = router w → Disjoint (visitInterior s t q z) (visitInterior s t q w)) + (havoid : ∀ z ∈ p.dropLast.support, Disjoint (visitInterior s t q z) + {v | ∃ d ∈ p.darts, v = (R d).fst ∨ v = (R d).snd}) : + ∃ (v : V) (c : G.Walk v v), c.IsCycle ∧ + c.edgeSet = {e | ∃ d ∈ p.darts, e = (R d).edge} ∪ + (⋃ z ∈ p.dropLast.support, (q z).edgeSet) := by + have hinter := interiors_disjoint_across_routers U hU router + (fun z => visitInterior s t q z) hroute hteam + apply inflate_represented_cycle R s t p hp hports q hq + apply switch_supports_separated {z | z ∈ p.dropLast.support} projMap s t q hproj + · intro z hz + rw [cyclePortSet_eq_representative_vertices R s t p hp hports] + exact havoid z hz + · intro z hz w hw hzw + exact hinter (show (⟨z,hz⟩ : {z // z ∈ p.dropLast.support}) ≠ ⟨w,hw⟩ from + fun he => hzw (congrArg Subtype.val he)) + +end +end ErdosGallai.Batch + +end +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/CycleDecomposition/Decomposition.lean b/lean/OAI/Combinatorics/CycleDecomposition/Decomposition.lean new file mode 100644 index 0000000000000000000000000000000000000000..7f05c9565c9f57b8f46d51f6d8052e623ea11433 --- /dev/null +++ b/lean/OAI/Combinatorics/CycleDecomposition/Decomposition.lean @@ -0,0 +1,514 @@ +import OAI.Combinatorics.CycleDecomposition.EndpointPartition + +namespace OAI + +section +open Filter Asymptotics Real +open scoped Topology +noncomputable section +open MeasureTheory ProbabilityTheory Finset +noncomputable section +namespace ErdosGallai + +def CycleOrSingleEdge {V : Type} (G : SimpleGraph V) + (s : Set (Sym2 V)) : Prop := + (∃ (v : V) (p : G.Walk v v), p.IsCycle ∧ s = p.edgeSet) ∨ + ∃ e ∈ G.edgeSet, s = {e} + +def EdgeDecomposition {V : Type} (G : SimpleGraph V) (k : ℕ) : Prop := + ∃ parts : Fin k → Set (Sym2 V), + (∀ i, CycleOrSingleEdge G (parts i)) ∧ + Pairwise (fun i j => Disjoint (parts i) (parts j)) ∧ + (⋃ i, parts i) = G.edgeSet + +noncomputable section +open SimpleGraph + +lemma cycleOrSingleEdge_subset {V : Type} {G : SimpleGraph V} + {s : Set (Sym2 V)} (hs : CycleOrSingleEdge G s) : s ⊆ G.edgeSet := by + rcases hs with ⟨v,p,hp,rfl⟩ | ⟨e,he,rfl⟩ + · exact p.edges_subset_edgeSet + · simpa using he + +lemma cycleOrSingleEdge_map {V W : Type} {G : SimpleGraph V} {H : SimpleGraph W} + (f : G →g H) (hf : Function.Injective f) {s : Set (Sym2 V)} + (hs : CycleOrSingleEdge G s) : CycleOrSingleEdge H (Sym2.map f '' s) := by + rcases hs with ⟨v,p,hp,rfl⟩ | ⟨e,he,rfl⟩ + · exact Or.inl ⟨f v,p.map f,hp.map hf,(p.edgeSet_map f).symm⟩ + · refine Or.inr ⟨Sym2.map f e, ?_, by simp⟩ + induction e using Sym2.ind with | _ x y => + exact f.map_adj he + +lemma edgeDecomposition_of_indexed {V I : Type} [Fintype I] (G : SimpleGraph V) + (parts : I → Set (Sym2 V)) (hp : ∀ i, CycleOrSingleEdge G (parts i)) + (hd : Pairwise (fun i j => Disjoint (parts i) (parts j))) + (hu : (⋃ i, parts i) = G.edgeSet) : EdgeDecomposition G (Fintype.card I) := by + let e := Fintype.equivFin I + refine ⟨fun j => parts (e.symm j), fun j => hp _, ?_, ?_⟩ + · intro i j hij + exact hd (fun he => hij (e.symm.injective he)) + · ext x + simp only [Set.mem_iUnion] + rw [← hu] + simp only [Set.mem_iUnion] + constructor + · rintro ⟨i,hi⟩; exact ⟨e.symm i,hi⟩ + · rintro ⟨i,hi⟩; exact ⟨e i, by simpa using hi⟩ + +theorem edgeDecomposition_singleEdges {V : Type} [Fintype V] (G : SimpleGraph V) : + EdgeDecomposition G (Nat.card G.edgeSet) := by + classical + let : Fintype G.edgeSet := Fintype.ofFinite _ + rw [Nat.card_eq_fintype_card] + apply edgeDecomposition_of_indexed G (fun e : G.edgeSet => {e.1}) + · intro e; exact Or.inr ⟨e.1,e.2,rfl⟩ + · intro e d hed + exact Set.disjoint_singleton.mpr (fun h => hed (Subtype.ext h)) + · ext e; simp + +theorem edgeDecomposition_assemble {V I : Type} [Fintype I] (G : SimpleGraph V) + (W : I → Type) (H : ∀ i, SimpleGraph (W i)) + (f : ∀ i, H i →g G) (hf : ∀ i, Function.Injective (f i)) + (hdisj : Pairwise (fun i j => + Disjoint (Sym2.map (f i) '' (H i).edgeSet) (Sym2.map (f j) '' (H j).edgeSet))) + (hcover : (⋃ i, Sym2.map (f i) '' (H i).edgeSet) = G.edgeSet) + (k : I → ℕ) (hparts : ∀ i, EdgeDecomposition (H i) (k i)) : + EdgeDecomposition G (∑ i, k i) := by + classical + choose parts hp hd hu using hparts + let J := Σ i, Fin (k i) + let P : J → Set (Sym2 V) := fun j => Sym2.map (f j.1) '' parts j.1 j.2 + have hpart : ∀ j, CycleOrSingleEdge G (P j) := by + intro j; exact cycleOrSingleEdge_map (f j.1) (hf j.1) (hp j.1 j.2) + have hsub : ∀ i a, parts i a ⊆ (H i).edgeSet := by + intro i a; exact cycleOrSingleEdge_subset (hp i a) + have hdisjP : Pairwise (fun i j => Disjoint (P i) (P j)) := by + rintro ⟨i,a⟩ ⟨j,b⟩ hij + by_cases h : i = j + · subst j + have hab : a ≠ b := fun he => hij (by cases he; rfl) + apply Set.disjoint_left.mpr + rintro e ⟨x,hx,he⟩ ⟨y,hy,he'⟩ + have hxy : x = y := Sym2.map.injective (hf i) (he.trans he'.symm) + subst y + exact Set.disjoint_left.mp (hd i hab) hx hy + · exact (hdisj h).mono (Set.image_mono (hsub i a)) (Set.image_mono (hsub j b)) + have hcoverP : (⋃ j, P j) = G.edgeSet := by + rw [← hcover] + ext e + simp only [Set.mem_iUnion] + constructor + · rintro ⟨⟨i,a⟩,x,hx,he⟩ + exact ⟨i,x,hsub i a hx,he⟩ + · rintro ⟨i,x,hx,he⟩ + rw [← hu i] at hx + obtain ⟨a,ha⟩ := Set.mem_iUnion.mp hx + exact ⟨⟨i,a⟩,x,ha,he⟩ + have hc : Fintype.card J = ∑ i, k i := by simp [J, Fintype.card_sigma] + rw [← hc] + exact edgeDecomposition_of_indexed G P hpart hdisjP hcoverP + +end +end ErdosGallai + +namespace ErdosGallai +noncomputable section +open Finset SimpleGraph +attribute [local instance] Classical.propDecidable + +theorem small_residue (c η : ℝ) (hc : 0 < c) (hη : 0 < η) : + ∃ D₀ : ℝ, 1 < D₀ ∧ ∀ D ≥ D₀, + ∀ (V : Type) [Fintype V] [DecidableEq V] (G P : SimpleGraph V) + [DecidableRel P.Adj], P ≤ G → + D^(9/10:ℝ) ≤ (Fintype.card V:ℝ) → + (Fintype.card V:ℝ) ≤ D^(51/50:ℝ) → + Splitting.CutExpansion P (c*D^(9/10:ℝ)) → + ∃ (k : ℕ) (parts : Fin k → Set (Sym2 V)) + (W : Fin 3 → Finset V) (H : Fin 3 → SimpleGraph V), + (∀ i, CycleOrSingleEdge G (parts i)) ∧ + Pairwise (fun i j => Disjoint (parts i) (parts j)) ∧ + (∀ b, H b ≤ G ∧ (H b).support ⊆ (W b : Set V)) ∧ + (∀ b, (W b).card < Fintype.card V) ∧ + ((∑ b, (W b).card : ℕ):ℝ) ≤ η * Fintype.card V ∧ + Pairwise (fun b d => Disjoint (H b).edgeSet (H d).edgeSet) ∧ + (∀ b i, Disjoint (H b).edgeSet (parts i)) ∧ + ((⋃ i, parts i) ∪ (⋃ b, (H b).edgeSet)) = G.edgeSet ∧ + k ≤ 9 * Fintype.card V := by + classical + have ha : 0 < reservoirExpansionCoefficient c := by + unfold reservoirExpansionCoefficient + exact div_pos (lt_min hc (by norm_num)) (by norm_num) + have hp : 0 < reservoirProbability η := by + unfold reservoirProbability + exact lt_min (div_pos hη (by norm_num)) (by norm_num) + obtain ⟨D₁,hprep⟩ := reservoir_preparation c η hc hη + obtain ⟨D₂,hD₂,hclose⟩ := uniform_three_reservoir_completion + (reservoirExpansionCoefficient c) (reservoirProbability η) ha hp + refine ⟨max D₁ D₂, hD₂.trans_le (le_max_right _ _), ?_⟩ + intro D hD V _ _ G P _ hPG hlo hhi hexp + obtain ⟨ω,W,r,hPG',hPP,hPexp,hWW,hW2,hWsize,hWlt,hWsum,hWexp,hr,hrne,hcap⟩ := + hprep D ((le_max_left _ _).trans hD) V G P hPG hlo hhi hexp + let P' := fun b => Splitting.colorGraph P ω b + have hWW' : Pairwise fun b d => Disjoint (W b : Set V) (W d : Set V) := by + intro b d hbd + exact Finset.disjoint_coe.mpr (hWW b d hbd) + let R := fun b => reservoirInternal (P' b) (W b) + let T := fun b => R b ∪ (reservoirSpokes (W b) (r b) : Set (Sym2 V)) + let E : Set (Sym2 V) := ⋃ b, T b + have hres := reservoir_reservations G P' W r hPG' hPP + (fun b v hv t => (hr b v hv t).2) + have hE : E ⊆ G.edgeSet := Set.iUnion_subset fun b => + Set.union_subset (hres.1 b).1 (hres.1 b).2 + let K := fun b => complementaryReservoirGraph (G.deleteEdges E) + (fun b => (W b : Set V)) hWW' b + have hK := complementary_reservoir_graphs (G.deleteEdges E) + (fun b => (W b : Set V)) hWW' + have hKG : ∀ b, K b ≤ G := fun b => (hK.1 b).trans (G.deleteEdges_le E) + have hledger := complementary_reservation_ledger G (fun b => (W b : Set V)) hWW' E hE + have hKT : ∀ b d, Disjoint (K b).edgeSet (T d) := fun b d => + (hledger.2.1 b).mono_right (Set.subset_iUnion T d) + have hx : ∀ b : Fin 3, EndpointPathPartition (K b) := fun b => endpoint_path_partition (K b) + choose k Q hQQ hQc hQl hQn using hx + let x := fun b i => (Q b i).start + let y := fun b i => (Q b i).finish + let q : ∀ b i, G.Walk (x b i) (y b i) := fun b i => (Q b i).walk.mapLe (hKG b) + have hqp : ∀ b i, (q b i).IsPath := fun b i => (Q b i).isPath.mapLe _ + have hql : ∀ b i, 0 < (q b i).length := by + intro b i + simpa [q] using (Q b i).positive + have hqo : ∀ b i v, v ∈ (q b i).support → v ∉ W b := by + intro b i v hv + apply complementary_walk_outside (fun b => (W b : Set V)) hWW' b + (Q b i).walk (Q b i).positive v + simpa [q] using hv + have hqd : ∀ b, Pairwise fun i j => Disjoint (q b i).edgeSet (q b j).edgeSet := by + intro b i j hij + simpa [q] using hQQ b hij + have hqc : ∀ b, (⋃ i, (q b i).edgeSet) = (K b).edgeSet := by + intro b + simpa [q] using hQc b + obtain ⟨C,hCy,hCC,hCsub,hcover,hcount⟩ := hclose D ((le_max_right _ _).trans hD) + V G P' K hPG' hPP W r hWexp hW2 hhi hr hrne hcap + hledger.1 hKT (fun b => Fin (k b)) x y q hqp hql hqo hqd hqc + (by + intro b v + dsimp only [endpointLoad,x,y] + convert hQl b v using 2 + ext i + simp) + let I := Σ b, Fin (k b) + let CE : I → Set (Sym2 V) := fun z => (C z.1 z.2).edgeSet + have hCE : ∀ i, CE i ⊆ G.edgeSet := fun i => (C i.1 i.2).edges_subset_edgeSet + have hEeq : E = (⋃ b, R b) ∪ (allReservoirSpokes W r : Set _) := by + simp only [E,T,coe_allReservoirSpokes,Set.iUnion_union_distrib] + have hcov : G.edgeSet \ ((⋃ b, R b) ∪ (allReservoirSpokes W r : Set _)) ⊆ + completedEdges CE := by + rw [← hEeq, ← SimpleGraph.edgeSet_deleteEdges, ← hK.2.2.2] + exact hcover + obtain ⟨hsupp,hind,hHe,hHH,hHC,hHS,hCS,hu,hnum⟩ := + three_reservoir_remainder G P' W r hPG' hPP + (fun b v hv t => (hr b v hv t).2) CE hCE hCC hcount hcov + let H := residualInternalGraph G R CE + let S := unusedSpokes (↑(allReservoirSpokes W r)) CE + let J := I ⊕ S + let parts : J → Set (Sym2 V) := Sum.elim CE (fun e => {e.val}) + have hSsub : (S : Set (Sym2 V)) ⊆ G.edgeSet := by + intro e he + have hh : e ∈ (allReservoirSpokes W r : Set _) := by + have hh := he + simp only [Finset.mem_coe,S,unusedSpokes,Set.mem_toFinset,Set.mem_sdiff] at hh + exact hh.1 + exact hE (by rw [hEeq]; exact Or.inr hh) + have hpart : ∀ j, CycleOrSingleEdge G (parts j) := by + intro j + rcases j with i | e + · exact Or.inl ⟨x i.1 i.2,C i.1 i.2,hCy i.1 i.2,rfl⟩ + · exact Or.inr ⟨e.val,hSsub e.property,rfl⟩ + have hpd : Pairwise fun i j => Disjoint (parts i) (parts j) := by + intro i j hij + rcases i with i | e <;> rcases j with j | f + · exact hCC (fun h => hij (congrArg Sum.inl h)) + · exact (hCS i).mono_right (Set.singleton_subset_iff.mpr f.property) + · exact (hCS j).symm.mono_left (Set.singleton_subset_iff.mpr e.property) + · exact Set.disjoint_singleton.mpr (fun h => hij (congrArg Sum.inr (Subtype.ext h))) + have hpartU : (⋃ j, parts j) = completedEdges CE ∪ (S : Set (Sym2 V)) := by + ext e + simp only [Set.mem_iUnion, Set.mem_union, completedEdges, parts] + constructor + · rintro ⟨i,hi⟩ + rcases i with i | f + · exact Or.inl ⟨i,hi⟩ + · exact Or.inr ((Set.mem_singleton_iff.mp hi) ▸ f.property) + · rintro (⟨i,hi⟩ | he) + · exact ⟨Sum.inl i,hi⟩ + · exact ⟨Sum.inr ⟨e,he⟩,rfl⟩ + let equiv := Fintype.equivFin J + refine ⟨Fintype.card J,fun i => parts (equiv.symm i),W,H,?_,?_,?_,hWlt,hWsum, + hHH,?_,?_,?_⟩ + · exact fun i => hpart _ + · intro i j hij + exact hpd (fun h => hij (equiv.symm.injective h)) + · intro b + refine ⟨?_,hsupp b⟩ + exact edgeRestriction_le G _ + · intro b i + rcases hji : equiv.symm i with j | e + all_goals simp only [hji, parts, Sum.elim_inl, Sum.elim_inr] + · exact hHC b j + · exact (hHS b).mono_right (Set.singleton_subset_iff.mpr e.property) + · have he : (⋃ i, parts (equiv.symm i)) = ⋃ j, parts j := by + ext e + simp only [Set.mem_iUnion] + exact ⟨fun ⟨i,hi⟩ => ⟨equiv.symm i,hi⟩, + fun ⟨j,hj⟩ => ⟨equiv j,by simpa using hj⟩⟩ + rw [he,hpartU] + exact hu + · simpa only [J,Fintype.card_sum,Fintype.card_coe] using hnum + +end +end ErdosGallai + +namespace ErdosGallai +noncomputable section +open SimpleGraph Finset +attribute [local instance] Classical.propDecidable + +def decompositionCost {V : Type} [Fintype V] (G : SimpleGraph V) : ℕ := + Nat.find (show ∃ k, EdgeDecomposition G k from ⟨_,edgeDecomposition_singleEdges G⟩) + +lemma decompositionCost_spec {V : Type} [Fintype V] (G : SimpleGraph V) : + EdgeDecomposition G (decompositionCost G) := Nat.find_spec _ + +lemma decompositionCost_le {V : Type} [Fintype V] {G : SimpleGraph V} {k : ℕ} + (h : EdgeDecomposition G k) : decompositionCost G ≤ k := Nat.find_min' _ h + +lemma decompositionCost_singleEdges {V : Type} [Fintype V] (G : SimpleGraph V) : + decompositionCost G ≤ Nat.card G.edgeSet := decompositionCost_le (edgeDecomposition_singleEdges G) + +theorem edgeDecomposition_adjoin {V I J : Type} [Fintype I] [Fintype J] + (G : SimpleGraph V) (parts : I → Set (Sym2 V)) + (hp : ∀ i, CycleOrSingleEdge G (parts i)) + (hd : Pairwise fun i j => Disjoint (parts i) (parts j)) + (W : J → Type) (H : ∀ j, SimpleGraph (W j)) (f : ∀ j, H j →g G) + (hf : ∀ j, Function.Injective (f j)) + (hHH : Pairwise fun i j => Disjoint (Sym2.map (f i) '' (H i).edgeSet) + (Sym2.map (f j) '' (H j).edgeSet)) + (hHP : ∀ j i, Disjoint (Sym2.map (f j) '' (H j).edgeSet) (parts i)) + (hu : (⋃ i, parts i) ∪ (⋃ j, Sym2.map (f j) '' (H j).edgeSet) = G.edgeSet) + (k : J → ℕ) (hD : ∀ j, EdgeDecomposition (H j) (k j)) : + EdgeDecomposition G (Fintype.card I + ∑ j, k j) := by + classical + choose P hP hPd hPc using hD + let R : (I ⊕ Σ j, Fin (k j)) → Set (Sym2 V) := + Sum.elim parts (fun z => Sym2.map (f z.1) '' P z.1 z.2) + have hsub : ∀ j i, P j i ⊆ (H j).edgeSet := fun j i => cycleOrSingleEdge_subset (hP j i) + have hRp : ∀ z, CycleOrSingleEdge G (R z) := by + intro z + rcases z with z | ⟨j,i⟩ + · exact hp z + · exact cycleOrSingleEdge_map (f j) (hf j) (hP j i) + have hRd : Pairwise fun z t => Disjoint (R z) (R t) := by + intro z t hzt + rcases z with z | ⟨j,i⟩ <;> rcases t with t | ⟨l,a⟩ + · exact hd (fun h => hzt (congrArg Sum.inl h)) + · exact ((hHP l z).mono_left (Set.image_mono (hsub l a))).symm + · exact (hHP j t).mono_left (Set.image_mono (hsub j i)) + · by_cases hjl : j = l + · subst l + have hia : i ≠ a := fun h => hzt (by cases h; rfl) + apply Set.disjoint_left.mpr + rintro e ⟨x,hx,he⟩ ⟨y,hy,he'⟩ + have hxy := Sym2.map.injective (hf j) (he.trans he'.symm) + subst y + exact Set.disjoint_left.mp (hPd j hia) hx hy + · exact (hHH hjl).mono (Set.image_mono (hsub j i)) (Set.image_mono (hsub l a)) + have hRu : (⋃ z, R z) = G.edgeSet := by + rw [← hu] + ext e + simp only [Set.mem_iUnion, Set.mem_union] + constructor + · rintro ⟨z,hz⟩ + rcases z with z | ⟨j,i⟩ + · exact Or.inl ⟨z,hz⟩ + · obtain ⟨x,hx,he⟩ := hz + exact Or.inr ⟨j,x,hsub j i hx,he⟩ + · rintro (⟨i,hi⟩ | ⟨j,x,hx,he⟩) + · exact ⟨Sum.inl i,hi⟩ + · rw [← hPc j] at hx + obtain ⟨i,hi⟩ := Set.mem_iUnion.mp hx + exact ⟨Sum.inr ⟨j,i⟩,x,hi,he⟩ + simpa only [Fintype.card_sum,Fintype.card_sigma,Fintype.card_fin] using + edgeDecomposition_of_indexed G R hRp hRd hRu + +lemma decompositionCost_adjoin {V I J : Type} [Fintype V] [Fintype I] [Fintype J] + (G : SimpleGraph V) (parts : I → Set (Sym2 V)) + (hp : ∀ i, CycleOrSingleEdge G (parts i)) + (hd : Pairwise fun i j => Disjoint (parts i) (parts j)) + (W : J → Type) [∀ j, Fintype (W j)] (H : ∀ j, SimpleGraph (W j)) + (f : ∀ j, H j →g G) (hf : ∀ j, Function.Injective (f j)) + (hHH : Pairwise fun i j => Disjoint (Sym2.map (f i) '' (H i).edgeSet) + (Sym2.map (f j) '' (H j).edgeSet)) + (hHP : ∀ j i, Disjoint (Sym2.map (f j) '' (H j).edgeSet) (parts i)) + (hu : (⋃ i, parts i) ∪ (⋃ j, Sym2.map (f j) '' (H j).edgeSet) = G.edgeSet) : + decompositionCost G ≤ Fintype.card I + ∑ j, decompositionCost (H j) := + decompositionCost_le (edgeDecomposition_adjoin G parts hp hd W H f hf hHH hHP hu _ + (fun j => decompositionCost_spec (H j))) + +end +end ErdosGallai +namespace ErdosGallai +noncomputable section +open SimpleGraph Finset +attribute [local instance] Classical.propDecidable + +lemma edgeDecomposition_map {V W : Type} {G : SimpleGraph V} {H : SimpleGraph W} + (f : H →g G) (hf : Function.Injective f) + (hu : Sym2.map f '' H.edgeSet = G.edgeSet) {k : ℕ} (hk : EdgeDecomposition H k) : + EdgeDecomposition G k := by + have := edgeDecomposition_assemble (I := Unit) G (fun _ : Unit => W) (fun _ => H) (fun _ => f) + (fun _ => hf) (by intro i j hij; exact False.elim (hij (Subsingleton.elim _ _))) + (by rw [Set.iUnion_const]; exact hu) (fun _ => k) (fun _ => hk) + simpa using this + +lemma decompositionCost_on {V : Type} [Fintype V] (G : SimpleGraph V) + (A : Finset V) (hA : ∀ ⦃x y⦄, G.Adj x y → x ∈ A ∧ y ∈ A) : + decompositionCost G ≤ decompositionCost (G.induce (A:Set V)) := by + classical + let f : G.induce (A:Set V) →g G := ⟨Subtype.val,fun h => h⟩ + have hu : Sym2.map f '' (G.induce (A:Set V)).edgeSet = G.edgeSet := by + ext e + constructor + · rintro ⟨e,he,rfl⟩ + induction e using Sym2.ind with | _ x y => exact he + · intro he + induction e using Sym2.ind with + | _ x y => + exact ⟨s(⟨x,(hA he).1⟩,⟨y,(hA he).2⟩),he,rfl⟩ + exact decompositionCost_le (edgeDecomposition_map f Subtype.val_injective hu (decompositionCost_spec _)) + +lemma edgeDecomposition_on {V : Type} (G : SimpleGraph V) + (A : Finset V) (hA : ∀ ⦃x y⦄, G.Adj x y → x ∈ A ∧ y ∈ A) + {k : ℕ} (hk : EdgeDecomposition (G.induce (A:Set V)) k) : EdgeDecomposition G k := by + classical + let f : G.induce (A:Set V) →g G := ⟨Subtype.val,fun h => h⟩ + apply edgeDecomposition_map f Subtype.val_injective _ hk + ext e + constructor + · rintro ⟨e,he,rfl⟩ + induction e using Sym2.ind with | _ x y => exact he + · intro he + induction e using Sym2.ind with + | _ x y => exact ⟨s(⟨x,(hA he).1⟩,⟨y,(hA he).2⟩),he,rfl⟩ + +end +end ErdosGallai +namespace ErdosGallai +noncomputable section +open SimpleGraph Finset +attribute [local instance] Classical.propDecidable + +lemma decompositionCost_adjoin_same {V I J : Type} [Fintype V] [Fintype I] [Fintype J] + (G : SimpleGraph V) (parts : I → Set (Sym2 V)) + (hp : ∀ i, CycleOrSingleEdge G (parts i)) + (hd : Pairwise fun i j => Disjoint (parts i) (parts j)) + (H : J → SimpleGraph V) (hHG : ∀ j, H j ≤ G) + (hHH : Pairwise fun i j => Disjoint (H i).edgeSet (H j).edgeSet) + (hHP : ∀ j i, Disjoint (H j).edgeSet (parts i)) + (hu : (⋃ i, parts i) ∪ (⋃ j, (H j).edgeSet) = G.edgeSet) : + decompositionCost G ≤ Fintype.card I + ∑ j, decompositionCost (H j) := by + let f : ∀ j, H j →g G := fun j => ⟨id,fun h => hHG j h⟩ + have he (j) : Sym2.map (f j) '' (H j).edgeSet = (H j).edgeSet := by + have hf : (f j : V → V) = id := rfl + rw [hf, Sym2.map_id, Set.image_id] + apply decompositionCost_adjoin G parts hp hd (fun _ => V) H f (fun _ => Function.injective_id) + · simpa only [he] using hHH + · simpa only [he] using hHP + · simpa only [he] using hu + +lemma decompositionCost_assemble_same {V J : Type} [Fintype V] [Fintype J] + (G : SimpleGraph V) (H : J → SimpleGraph V) (hHG : ∀ j, H j ≤ G) + (hHH : Pairwise fun i j => Disjoint (H i).edgeSet (H j).edgeSet) + (hu : (⋃ j, (H j).edgeSet) = G.edgeSet) : + decompositionCost G ≤ ∑ j, decompositionCost (H j) := by + simpa using decompositionCost_adjoin_same (I := Empty) G Empty.elim (fun i => nomatch i) + (by intro i; exact i.elim) H hHG hHH (fun _ i => nomatch i) (by simpa using hu) + +end +end ErdosGallai + +namespace ErdosGallai +noncomputable section +open SimpleGraph Finset +attribute [local instance] Classical.propDecidable + +theorem uniform_piece_cost (c η : ℝ) (hc : 0 < c) (hη : 0 < η) : + ∃ D₀ : ℝ, 1 < D₀ ∧ ∀ D ≥ D₀, ∀ (n : ℕ) (C : ℝ), 0 ≤ C → + (∀ (W : Type) [Fintype W] (H : SimpleGraph W), Fintype.card W < n → + (decompositionCost H:ℝ) ≤ C * Fintype.card W) → + ∀ (V : Type) [Fintype V] [DecidableEq V] (G P : SimpleGraph V) + [DecidableRel P.Adj], P ≤ G → Fintype.card V ≤ n → + D^(9/10:ℝ) ≤ (Fintype.card V:ℝ) → + (Fintype.card V:ℝ) ≤ D^(51/50:ℝ) → + Splitting.CutExpansion P (c*D^(9/10:ℝ)) → + (decompositionCost G:ℝ) ≤ (9+C*η)*Fintype.card V := by + obtain ⟨D₀,hD₀,hres⟩ := small_residue c η hc hη + refine ⟨D₀,hD₀,?_⟩ + intro D hD n C hC ih V _ _ G P _ hPG hn hlo hhi he + obtain ⟨k,parts,W,H,hp,hd,hHG,hWlt,hWsum,hHH,hHP,hu,hk⟩ := + hres D hD V G P hPG hlo hhi he + have hcost (b : Fin 3) : (decompositionCost (H b):ℝ) ≤ C * (W b).card := by + have hA : ∀ ⦃x y⦄, (H b).Adj x y → x ∈ W b ∧ y ∈ W b := by + intro x y hxy + exact ⟨(hHG b).2 ⟨y,hxy⟩,(hHG b).2 ⟨x,hxy.symm⟩⟩ + calc + _ ≤ (decompositionCost ((H b).induce (W b:Set V)):ℝ) := + Nat.cast_le.mpr (decompositionCost_on _ _ hA) + _ ≤ C * Fintype.card (W b:Set V) := ih _ _ (by simpa using (hWlt b).trans_le hn) + _ = _ := by simp + have htot := decompositionCost_adjoin_same G parts hp hd H (fun b => (hHG b).1) hHH hHP hu + have hsum : (∑ b, (decompositionCost (H b):ℝ)) ≤ C * ∑ b, ((W b).card:ℝ) := by + rw [Finset.mul_sum] + exact Finset.sum_le_sum (fun b _ => hcost b) + have hsum' := mul_le_mul_of_nonneg_left hWsum hC + have hk' : (k:ℝ) ≤ 9 * Fintype.card V := by exact_mod_cast hk + have htot' : (decompositionCost G:ℝ) ≤ k + ∑ b, (decompositionCost (H b):ℝ) := by + simpa only [Fintype.card_fin, Nat.cast_add, Nat.cast_sum] using (Nat.cast_le.mpr htot : (decompositionCost G:ℝ) ≤ _) + push_cast at hsum' + nlinarith + +end +end ErdosGallai + +namespace ErdosGallai +noncomputable section +open SimpleGraph Finset +attribute [local instance] Classical.propDecidable + +theorem uniform_piece_cost_on (c η : ℝ) (hc : 0 < c) (hη : 0 < η) : + ∃ D₀ : ℝ, 1 < D₀ ∧ ∀ D ≥ D₀, ∀ (n : ℕ) (C : ℝ), 0 ≤ C → + (∀ (W : Type) [Fintype W] (H : SimpleGraph W), Fintype.card W < n → + (decompositionCost H:ℝ) ≤ C * Fintype.card W) → + ∀ (V : Type) [Fintype V] [DecidableEq V] (G P : SimpleGraph V) + [DecidableRel P.Adj] (A : Finset V), P ≤ G → A.card ≤ n → + (∀ ⦃x y⦄, G.Adj x y → x ∈ A ∧ y ∈ A) → + D^(9/10:ℝ) ≤ (A.card:ℝ) → (A.card:ℝ) ≤ D^(51/50:ℝ) → + CutExpansionOn P A (c*D^(9/10:ℝ)) → + (decompositionCost G:ℝ) ≤ (9+C*η)*A.card := by + obtain ⟨D₀,hD₀,hcost⟩ := uniform_piece_cost c η hc hη + refine ⟨D₀,hD₀,?_⟩ + intro D hD n C hC ih V _ _ G P _ A hPG hn hA hlo hhi he + have hcost' := hcost D hD n C hC ih (A:Set V) (G.induce (A:Set V)) + (P.induce (A:Set V)) (fun _ _ h => hPG h) (by simpa using hn) + (by simpa using hlo) (by simpa using hhi) (cutExpansion_induce P A _ he) + calc + _ ≤ (decompositionCost (G.induce (A:Set V)):ℝ) := Nat.cast_le.mpr (decompositionCost_on G A hA) + _ ≤ _ := by simpa using hcost' + +end +end ErdosGallai + +end +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/CycleDecomposition/DepthFirstSearch.lean b/lean/OAI/Combinatorics/CycleDecomposition/DepthFirstSearch.lean new file mode 100644 index 0000000000000000000000000000000000000000..fb34c026bca9834be90c03b0fae058ef5cfd6280 --- /dev/null +++ b/lean/OAI/Combinatorics/CycleDecomposition/DepthFirstSearch.lean @@ -0,0 +1,197 @@ +import OAI.Combinatorics.CycleDecomposition.CoupledResolution + +namespace OAI + +universe cycleUniverse1 cycleUniverse2 + +section +open Filter Asymptotics Real +open scoped Topology +noncomputable section +open MeasureTheory ProbabilityTheory Finset +section + +namespace ErdosGallai.Scale +universe u +open Finset SimpleGraph +variable {V : Type cycleUniverse1} [Fintype V] [DecidableEq V] + +structure DFSState (G : SimpleGraph V) where + stack : List V + finished : Finset V + unexplored : Finset V + nodup : stack.Nodup + chain : stack.IsChain G.Adj + f_s : Disjoint finished stack.toFinset + f_u : Disjoint finished unexplored + s_u : Disjoint stack.toFinset unexplored + cover : finished ∪ stack.toFinset ∪ unexplored = univ + separation : ∀ x ∈ finished, ∀ y ∈ unexplored, ¬ G.Adj x y + +namespace DFSState +variable {G : SimpleGraph V} + +lemma card_eq (s : DFSState G) : + Fintype.card V = s.finished.card + s.stack.length + s.unexplored.card := by + have hdis : Disjoint (s.finished ∪ s.stack.toFinset) s.unexplored := + Finset.disjoint_union_left.mpr ⟨s.f_u, s.s_u⟩ + have hc := congrArg Finset.card s.cover + rw [Finset.card_union_of_disjoint hdis, Finset.card_union_of_disjoint s.f_s, + List.toFinset_card_of_nodup s.nodup, Finset.card_univ] at hc + exact hc.symm + +lemma restart (s : DFSState G) (hs : s.stack = []) (v : V) (hv : v ∈ s.unexplored) : + ∃ t : DFSState G, t.finished = s.finished ∧ + t.unexplored.card + 1 = s.unexplored.card := by + have hvf : v ∉ s.finished := fun hf => Finset.disjoint_left.mp s.f_u hf hv + refine ⟨⟨[v], s.finished, s.unexplored.erase v, by simp, by simp, + ?_, ?_, ?_, ?_, ?_⟩, rfl, ?_⟩ + · simpa using hvf + · exact s.f_u.mono_right (Finset.erase_subset _ _) + · simp + · change s.finished ∪ {v} ∪ s.unexplored.erase v = univ + rw [Finset.union_assoc, Finset.singleton_union, Finset.insert_erase hv] + simpa only [hs, List.toFinset_nil, Finset.union_empty] using s.cover + · intro x hx y hy + exact s.separation x hx y (Finset.mem_of_mem_erase hy) + · exact Finset.card_erase_add_one hv + +lemma push (s : DFSState G) (v w : V) (L : List V) (hs : s.stack = v::L) + (hw : w ∈ s.unexplored) (hadj : G.Adj w v) : + ∃ t : DFSState G, t.finished = s.finished ∧ + t.unexplored.card + 1 = s.unexplored.card := by + have hws : w ∉ s.stack := fun h => Finset.disjoint_left.mp s.s_u + (List.mem_toFinset.mpr h) hw + have hwf : w ∉ s.finished := fun h => Finset.disjoint_left.mp s.f_u h hw + refine ⟨⟨w::s.stack, s.finished, s.unexplored.erase w, ?_, ?_, ?_, ?_, ?_, ?_, ?_⟩, + rfl, ?_⟩ + · exact List.nodup_cons.mpr ⟨hws,s.nodup⟩ + · rw [hs] + exact List.IsChain.cons_cons hadj (hs ▸ s.chain) + · simpa using And.intro hwf s.f_s + · exact s.f_u.mono_right (Finset.erase_subset _ _) + · rw [List.toFinset_cons, Finset.disjoint_insert_left] + exact ⟨(by simp), s.s_u.mono_right (Finset.erase_subset _ _)⟩ + · ext x + have hx : x ∈ s.finished ∪ s.stack.toFinset ∪ s.unexplored := by rw [s.cover]; simp + simp only [Finset.mem_union] at hx + simp only [List.toFinset_cons, Finset.mem_union, Finset.mem_insert, + Finset.mem_erase, Finset.mem_univ, iff_true] + by_cases hxw : x = w + · exact Or.inl (Or.inr (Or.inl hxw)) + · rcases hx with (h|h)|h + · exact Or.inl (Or.inl h) + · exact Or.inl (Or.inr (Or.inr h)) + · exact Or.inr ⟨hxw,h⟩ + · intro x hx y hy + exact s.separation x hx y (Finset.mem_of_mem_erase hy) + · exact Finset.card_erase_add_one hw + +lemma pop (s : DFSState G) (v : V) (L : List V) (hs : s.stack = v::L) + (hn : ∀ w ∈ s.unexplored, ¬G.Adj v w) : + ∃ t : DFSState G, t.finished.card = s.finished.card + 1 ∧ + t.unexplored = s.unexplored := by + have hvf : v ∉ s.finished := fun hv => Finset.disjoint_left.mp s.f_s hv (by simp [hs]) + have hvu : v ∉ s.unexplored := fun hv => Finset.disjoint_left.mp s.s_u (by simp [hs]) hv + have hL : L.toFinset ⊆ s.stack.toFinset := by rw [hs]; simp + have hnd : v ∉ L ∧ L.Nodup := by simpa only [hs, List.nodup_cons] using s.nodup + have hvL : v ∉ L := hnd.1 + refine ⟨⟨L, insert v s.finished, s.unexplored, ?_, ?_, ?_, ?_, ?_, ?_, ?_⟩, ?_, rfl⟩ + · exact hnd.2 + · exact (hs ▸ s.chain).of_cons + · exact Finset.disjoint_insert_left.mpr ⟨by simpa using hvL, s.f_s.mono_right hL⟩ + · exact Finset.disjoint_insert_left.mpr ⟨hvu,s.f_u⟩ + · exact s.s_u.mono_left hL + · simpa [hs, Finset.insert_union] using s.cover + · intro x hx y hy + rcases Finset.mem_insert.mp hx with rfl|hx + · exact hn y hy + · exact s.separation x hx y hy + · exact Finset.card_insert_of_notMem hvf + +lemma reaches_balance (s : DFSState G) (hs : s.finished.card ≤ s.unexplored.card) : + ∃ t : DFSState G, t.finished.card = t.unexplored.card := by + generalize hd : s.unexplored.card - s.finished.card = d + induction d using Nat.strong_induction_on generalizing s with + | h d ih => + by_cases heq : s.finished.card = s.unexplored.card + · exact ⟨s,heq⟩ + have hlt : s.finished.card < s.unexplored.card := lt_of_le_of_ne hs heq + have hdpos : 0 < d := by omega + cases hstack : s.stack with + | nil => + obtain ⟨v,hv⟩ := Finset.card_pos.mp (show 0 < s.unexplored.card by omega) + obtain ⟨t,htf,htu⟩ := s.restart hstack v hv + apply ih (t.unexplored.card-t.finished.card) (by rw [htf]; omega) t (by rw [htf]; omega) rfl + | cons v L => + by_cases hn : ∃ w ∈ s.unexplored, G.Adj v w + · obtain ⟨w,hw,hadj⟩ := hn + obtain ⟨t,htf,htu⟩ := s.push v w L hstack hw hadj.symm + apply ih (t.unexplored.card-t.finished.card) (by rw [htf]; omega) t (by rw [htf]; omega) rfl + · push Not at hn + obtain ⟨t,htf,htu⟩ := s.pop v L hstack hn + apply ih (t.unexplored.card-t.finished.card) (by rw [htf,htu]; omega) t (by rw [htf,htu]; omega) rfl + +end DFSState + +theorem exists_balanced_dfs_state (G : SimpleGraph V) : + ∃ s : DFSState G, s.finished.card = s.unexplored.card := by + let s : DFSState G := ⟨[], ∅, univ, by simp, by simp, by simp, by simp, by simp, + by simp, by simp⟩ + exact s.reaches_balance (by simp [s]) + +end ErdosGallai.Scale + +namespace ErdosGallai.Scale +open Finset SimpleGraph +variable {V : Type cycleUniverse2} [Fintype V] [DecidableEq V] + +def externalNeighbors (G : SimpleGraph V) [DecidableRel G.Adj] (U : Finset V) : Finset V := + univ.filter (fun v => v ∉ U ∧ ∃ u ∈ U, G.Adj u v) + +def VertexExpansion (G : SimpleGraph V) [DecidableRel G.Adj] (α : ℝ) : Prop := + ∀ U : Finset V, U.Nonempty → 2 * U.card ≤ Fintype.card V → + α * U.card ≤ ((externalNeighbors G U).card : ℝ) + +lemma DFSState.external_subset (G : SimpleGraph V) [DecidableRel G.Adj] (s : DFSState G) : + externalNeighbors G s.unexplored ⊆ s.stack.toFinset := by + intro v hv + obtain ⟨_,hvu,u,hu,hadj⟩ := Finset.mem_filter.mp hv + have hc : v ∈ s.finished ∪ s.stack.toFinset ∪ s.unexplored := by rw [s.cover]; simp + rcases Finset.mem_union.mp hc with h|h + · rcases Finset.mem_union.mp h with h|h + · exact (s.separation v h u hu hadj.symm).elim + · exact h + · exact (hvu h).elim + +theorem exists_long_stack (G : SimpleGraph V) [DecidableRel G.Adj] + (α : ℝ) (hα : α ≤ 1) (hexp : VertexExpansion G α) : + ∃ L : List V, L.Nodup ∧ L.IsChain G.Adj ∧ α * Fintype.card V / 3 ≤ (L.length : ℝ) := by + obtain ⟨s,heq⟩ := exists_balanced_dfs_state G + refine ⟨s.stack,s.nodup,s.chain,?_⟩ + have hc := s.card_eq + rw [heq] at hc + have hcR : (Fintype.card V : ℝ) = 2*(s.unexplored.card : ℝ)+(s.stack.length : ℝ) := by + exact_mod_cast (show Fintype.card V = 2*s.unexplored.card+s.stack.length by omega) + have hN : ((externalNeighbors G s.unexplored).card : ℝ) ≤ (s.stack.length : ℝ) := by + have ht := Finset.card_le_card (s.external_subset G) + rw [List.toFinset_card_of_nodup s.nodup] at ht + exact_mod_cast ht + by_cases hU : s.unexplored.Nonempty + · have hsmall : 2*s.unexplored.card ≤ Fintype.card V := by omega + have he := (hexp s.unexplored hU hsmall).trans hN + have ht : (0 : ℝ) ≤ s.stack.length := Nat.cast_nonneg _ + have ha := mul_le_mul_of_nonneg_right hα ht + nlinarith + · have hu : s.unexplored.card = 0 := by simp [Finset.not_nonempty_iff_eq_empty.mp hU] + rw [hu, Nat.cast_zero, mul_zero, zero_add] at hcR + + nlinarith [show (0 : ℝ) ≤ s.stack.length from Nat.cast_nonneg _, + mul_le_mul_of_nonneg_right hα (show (0 : ℝ) ≤ s.stack.length from Nat.cast_nonneg _)] + +end ErdosGallai.Scale +end +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/CycleDecomposition/EdgeSplitting.lean b/lean/OAI/Combinatorics/CycleDecomposition/EdgeSplitting.lean new file mode 100644 index 0000000000000000000000000000000000000000..e1a052bbe6e0cb522f47ae456871d3f3d2a967ca --- /dev/null +++ b/lean/OAI/Combinatorics/CycleDecomposition/EdgeSplitting.lean @@ -0,0 +1,403 @@ +import OAI.Combinatorics.CycleDecomposition.ReservoirSampling + +namespace OAI + +universe cycleUniverse1 cycleUniverse2 cycleUniverse3 cycleUniverse4 cycleUniverse5 cycleUniverse6 cycleUniverse7 cycleUniverse8 + +section +open Filter Asymptotics Real +open scoped Topology +noncomputable section +open MeasureTheory ProbabilityTheory Finset +noncomputable section +namespace ErdosGallai.Splitting +open MeasureTheory ProbabilityTheory Finset Real + +section BernoulliBounds +variable {Ω : Type cycleUniverse1} {I : Type cycleUniverse2} [MeasurableSpace Ω] {μ : Measure Ω} [IsProbabilityMeasure μ] + +lemma indicator_mem_Icc {Ω : Type cycleUniverse3} [_contextInstance1 : MeasurableSpace Ω] {X : Ω → ℝ} (hX : ∀ ω, X ω = 0 ∨ X ω = 1) (ω : Ω) : + X ω ∈ Set.Icc (0 : ℝ) 1 := by rcases hX ω with h | h <;> simp [h] + +lemma mgf_indicator {X : Ω → ℝ} (hm : Measurable X) + (hX : ∀ ω, X ω = 0 ∨ X ω = 1) (p t : ℝ) (hp : ∫ ω, X ω ∂μ = p) : + mgf X μ t = 1 + p * (exp t - 1) := by + have hXi : Integrable X μ := Integrable.of_mem_Icc 0 1 hm.aemeasurable + (ae_of_all _ (indicator_mem_Icc hX)) + have heq : (fun ω => exp (t * X ω)) = fun ω => (1 : ℝ) + (exp t - 1) * X ω := by + funext ω + rcases hX ω with h | h <;> simp [h] + rw [mgf, heq, integral_add (integrable_const _) (hXi.const_mul _), integral_const_mul, + hp, integral_const] + simp [mul_comm] + +lemma mgf_indicator_sum_bound {X : I → Ω → ℝ} (s : Finset I) + (hm : ∀ i, Measurable (X i)) (hi : iIndepFun X μ) + (hX : ∀ i ω, X i ω = 0 ∨ X i ω = 1) + (p t : ℝ) (hp : ∀ i, ∫ ω, X i ω ∂μ = p) : + mgf (∑ i ∈ s, X i) μ t ≤ exp ((s.card : ℝ) * p * (exp t - 1)) := by + by_cases hs : s.Nonempty + swap + · have he := Finset.not_nonempty_iff_eq_empty.mp hs + simp [he] + rw [hi.mgf_sum hm] + have heq : (∏ i ∈ s, mgf (X i) μ t) = (1 + p * (exp t - 1)) ^ s.card := by + simp_rw [mgf_indicator (hm _) (hX _) p t (hp _)] + simp + rw [heq] + have hn : 0 ≤ 1 + p * (exp t - 1) := by + obtain ⟨i, _⟩ := hs + rw [← mgf_indicator (hm i) (hX i) p t (hp i)] + exact mgf_nonneg + calc + (1 + p * (exp t - 1)) ^ s.card ≤ exp (p * (exp t - 1)) ^ s.card := + pow_le_pow_left₀ hn (by linarith [add_one_le_exp (p * (exp t - 1))]) _ + _ = _ := by rw [← exp_nat_mul]; congr 1; ring + +lemma exp_neg_half_bound : exp (-(1 / 2 : ℝ)) ≤ 5 / 8 := by + have he : exp (1 / 2 : ℝ) * exp (1 / 2 : ℝ) = exp 1 := by + rw [← exp_add]; norm_num + have hlow : (8 / 5 : ℝ) ≤ exp (1 / 2 : ℝ) := by + nlinarith [exp_one_gt_d9, exp_pos (1 / 2 : ℝ)] + rw [exp_neg] + exact (inv_le_comm₀ (exp_pos _) (by norm_num)).mpr (by norm_num at *; exact hlow) + +lemma exp_half_bound : exp (1 / 2 : ℝ) ≤ 5 / 3 := by + have he : exp (1 / 2 : ℝ) * exp (1 / 2 : ℝ) = exp 1 := by + rw [← exp_add]; norm_num + nlinarith [exp_one_lt_d9, exp_pos (1 / 2 : ℝ)] + +theorem bernoulli_sum_lower_tail {X : I → Ω → ℝ} (s : Finset I) + (hm : ∀ i, Measurable (X i)) (hi : iIndepFun X μ) + (hX : ∀ i ω, X i ω = 0 ∨ X i ω = 1) + (p : ℝ) (hp0 : 0 ≤ p) (hp : ∀ i, ∫ ω, X i ω ∂μ = p) : + μ.real {ω | (∑ i ∈ s, X i ω) ≤ p * s.card / 2} ≤ exp (-p * s.card / 8) := by + have hInt : Integrable (fun ω => exp (-(1 / 2 : ℝ) * (∑ i ∈ s, X i) ω)) μ := + hi.integrable_exp_mul_sum hm (fun i _ => integrable_exp_mul_of_mem_Icc + (hm i).aemeasurable (ae_of_all _ (indicator_mem_Icc (hX i)))) + have hb := measure_le_le_exp_mul_mgf (X := ∑ i ∈ s, X i) (p * s.card / 2) + (by norm_num : -(1 / 2 : ℝ) ≤ 0) hInt + simp only [Finset.sum_apply] at hb + apply hb.trans + calc + _ ≤ exp (-(-(1 / 2 : ℝ)) * (p * s.card / 2)) * + exp ((s.card : ℝ) * p * (exp (-(1 / 2 : ℝ)) - 1)) := by + exact mul_le_mul_of_nonneg_left (mgf_indicator_sum_bound s hm hi hX p _ hp) (exp_pos _).le + _ = exp (p * s.card / 4 + (s.card : ℝ) * p * (exp (-(1 / 2 : ℝ)) - 1)) := by + rw [← exp_add]; congr 1; ring + _ ≤ _ := by + apply exp_le_exp.mpr + nlinarith [mul_le_mul_of_nonneg_left exp_neg_half_bound + (mul_nonneg (Nat.cast_nonneg s.card) hp0)] + +theorem bernoulli_sum_upper_tail {X : I → Ω → ℝ} (s : Finset I) + (hm : ∀ i, Measurable (X i)) (hi : iIndepFun X μ) + (hX : ∀ i ω, X i ω = 0 ∨ X i ω = 1) + (p : ℝ) (hp0 : 0 ≤ p) (hp : ∀ i, ∫ ω, X i ω ∂μ = p) : + μ.real {ω | 2 * p * s.card ≤ ∑ i ∈ s, X i ω} ≤ exp (-p * s.card / 3) := by + have hInt : Integrable (fun ω => exp ((1 / 2 : ℝ) * (∑ i ∈ s, X i) ω)) μ := + hi.integrable_exp_mul_sum hm (fun i _ => integrable_exp_mul_of_mem_Icc + (hm i).aemeasurable (ae_of_all _ (indicator_mem_Icc (hX i)))) + have hb := measure_ge_le_exp_mul_mgf (X := ∑ i ∈ s, X i) (2 * p * s.card) + (by norm_num : (0 : ℝ) ≤ 1 / 2) hInt + simp only [Finset.sum_apply] at hb + apply hb.trans + calc + _ ≤ exp (-(1 / 2 : ℝ) * (2 * p * s.card)) * + exp ((s.card : ℝ) * p * (exp (1 / 2 : ℝ) - 1)) := by + exact mul_le_mul_of_nonneg_left (mgf_indicator_sum_bound s hm hi hX p _ hp) (exp_pos _).le + _ = exp (-p * s.card + (s.card : ℝ) * p * (exp (1 / 2 : ℝ) - 1)) := by + rw [← exp_add]; congr 1; ring + _ ≤ _ := by + apply exp_le_exp.mpr + nlinarith [mul_le_mul_of_nonneg_left exp_half_bound + (mul_nonneg (Nat.cast_nonneg s.card) hp0)] + +end BernoulliBounds + +noncomputable section +variable {V : Type cycleUniverse4} [Fintype V] [DecidableEq V] + +def CutExpansion (P : SimpleGraph V) [DecidableRel P.Adj] (h : ℝ) : Prop := + ∀ U : Finset V, h * min (U.card : ℝ) (Uᶜ.card : ℝ) ≤ + ((P.interedges U Uᶜ).card : ℝ) + +lemma boundary_sym2_injective (P : SimpleGraph V) [DecidableRel P.Adj] + (U : Finset V) : + Set.InjOn (fun e : V × V => s(e.1, e.2)) (P.interedges U Uᶜ : Set (V × V)) := by + intro e he f hf hef + rcases (Sym2.mk_eq_mk_iff.mp hef) with h | h + · exact h + · have he1 := (P.mem_interedges_iff.mp he).1 + have hf2 := (P.mem_interedges_iff.mp hf).2.1 + have hfirst : e.1 = f.2 := congrArg Prod.fst h + exact False.elim ((Finset.mem_compl.mp hf2) (hfirst ▸ he1)) + +def edgeColorMeasure (V : Type cycleUniverse5) [Fintype V] (l : ℕ) [NeZero l] : + Measure (Sym2 V → Fin l) := + Measure.pi (fun _ : Sym2 V => (PMF.uniformOfFintype (Fin l)).toMeasure) + +instance edgeColorMeasure_probability (l : ℕ) [NeZero l] : + IsProbabilityMeasure (edgeColorMeasure V l) := by + unfold edgeColorMeasure + infer_instance + +def colorIndicator {l : ℕ} (i : Fin l) (e : Sym2 V) (ω : Sym2 V → Fin l) : ℝ := + if ω e = i then 1 else 0 + +lemma colorIndicator_indep {V : Type cycleUniverse6} [_contextInstance1 : Fintype V] [_contextInstance2 : DecidableEq V] {l : ℕ} [NeZero l] (i : Fin l) : + iIndepFun (colorIndicator (V := V) i) (edgeColorMeasure V l) := by + exact iIndepFun_pi (X := fun _ : Sym2 V => fun j : Fin l => if j = i then (1 : ℝ) else 0) + (fun _ => (measurable_of_finite _).aemeasurable) + +lemma colorIndicator_integral {V : Type cycleUniverse7} [_contextInstance1 : Fintype V] [_contextInstance2 : DecidableEq V] {l : ℕ} [NeZero l] (i : Fin l) (e : Sym2 V) : + ∫ ω, colorIndicator i e ω ∂edgeColorMeasure V l = 1/(l : ℝ) := by + have hl := (measurePreserving_eval + (fun _ : Sym2 V => (PMF.uniformOfFintype (Fin l)).toMeasure) e).hasLaw + have hi := hl.integral_comp (f := fun j : Fin l => if j = i then (1 : ℝ) else 0) + (measurable_of_finite _).aestronglyMeasurable + rw [PMF.integral_eq_sum] at hi + simpa [edgeColorMeasure, colorIndicator, PMF.uniformOfFintype_apply] using hi + +def colorGraph (P : SimpleGraph V) {l : ℕ} (ω : Sym2 V → Fin l) (i : Fin l) : + SimpleGraph V where + Adj x y := P.Adj x y ∧ ω s(x,y) = i + symm := ⟨by intro x y h; exact ⟨h.1.symm, by simpa only [Sym2.eq_swap] using h.2⟩⟩ + loopless := ⟨by intro x h; exact P.irrefl h.1⟩ + +instance colorGraph_decidable (P : SimpleGraph V) [DecidableRel P.Adj] + {l : ℕ} (ω : Sym2 V → Fin l) (i : Fin l) : + DecidableRel (colorGraph P ω i).Adj := fun _ _ => inferInstanceAs (Decidable (_ ∧ _)) + +lemma colorGraph_interedges {V : Type cycleUniverse8} [_contextInstance1 : Fintype V] [_contextInstance2 : DecidableEq V] (P : SimpleGraph V) [DecidableRel P.Adj] + {l : ℕ} (ω : Sym2 V → Fin l) (i : Fin l) (S T : Finset V) : + (colorGraph P ω i).interedges S T = + (P.interedges S T).filter (fun e => ω s(e.1,e.2) = i) := by + ext ⟨x,y⟩ + simp only [SimpleGraph.mem_interedges_iff, Finset.mem_filter] + change (x ∈ S ∧ y ∈ T ∧ (P.Adj x y ∧ ω s(x,y) = i)) ↔ _ + tauto + +lemma color_cut_sum (P : SimpleGraph V) [DecidableRel P.Adj] + {l : ℕ} (ω : Sym2 V → Fin l) (i : Fin l) (S : Finset V) : + (∑ e ∈ (P.interedges S Sᶜ).image (fun e => s(e.1,e.2)), colorIndicator i e ω) = + (((colorGraph P ω i).interedges S Sᶜ).card : ℝ) := by + rw [Finset.sum_image (boundary_sym2_injective P S)] + simp only [colorIndicator, Finset.sum_boole, colorGraph_interedges] + +lemma color_cut_lower_tail (P : SimpleGraph V) [DecidableRel P.Adj] + {l : ℕ} [NeZero l] (i : Fin l) (S : Finset V) {h : ℝ} + (hexp : CutExpansion P h) (hS : S.card ≤ Sᶜ.card) : + (edgeColorMeasure V l).real {ω | + (((colorGraph P ω i).interedges S Sᶜ).card : ℝ) < h*S.card/(2*l)} ≤ + exp (-h*S.card/(8*l)) := by + let E := (P.interedges S Sᶜ).image (fun e => s(e.1,e.2)) + have hcard : E.card = (P.interedges S Sᶜ).card := + Finset.card_image_of_injOn (boundary_sym2_injective P S) + have hl : 0 < (l : ℝ) := by exact_mod_cast Nat.pos_of_ne_zero (NeZero.ne l) + have hcut : h * S.card ≤ (E.card : ℝ) := by + rw [hcard] + have he := hexp S + rwa [min_eq_left (by exact_mod_cast hS)] at he + have hb := bernoulli_sum_lower_tail (μ := edgeColorMeasure V l) E + (fun e => measurable_of_finite (colorIndicator i e)) (colorIndicator_indep i) + (fun e ω => by simp only [colorIndicator]; split <;> simp) + (1/(l : ℝ)) (by positivity) (colorIndicator_integral i) + apply (measureReal_mono (show {ω | + (((colorGraph P ω i).interedges S Sᶜ).card : ℝ) < h*S.card/(2*l)} ⊆ + {ω | (∑ e ∈ E, colorIndicator i e ω) ≤ (1/(l : ℝ))*E.card/2} from ?_)).trans + (hb.trans ?_) + · intro ω hω + change (∑ e ∈ E, colorIndicator i e ω) ≤ (1/(l : ℝ))*E.card/2 + rw [show (∑ e ∈ E, colorIndicator i e ω) = + (((colorGraph P ω i).interedges S Sᶜ).card : ℝ) from color_cut_sum P ω i S] + calc + _ ≤ h*S.card/(2*l) := le_of_lt hω + _ ≤ (E.card : ℝ)/(2*l) := div_le_div_of_nonneg_right hcut (by positivity) + _ = _ := by ring + · apply exp_le_exp.mpr + have he := div_le_div_of_nonneg_right hcut (show 0 ≤ 8*(l : ℝ) by positivity) + calc + _ = -((E.card : ℝ)/(8*l)) := by ring + _ ≤ -(h*S.card/(8*l)) := neg_le_neg he + _ = _ := by ring + +lemma cutExpansion_of_small_cuts (P : SimpleGraph V) [DecidableRel P.Adj] {h : ℝ} + (hcut : ∀ S : Finset V, S.Nonempty → S.card ≤ Sᶜ.card → + h*S.card ≤ ((P.interedges S Sᶜ).card : ℝ)) : CutExpansion P h := by + intro S + by_cases he : S = ∅ + · simp [he] + by_cases hc : Sᶜ = ∅ + · simp [hc] + by_cases hs : S.card ≤ Sᶜ.card + · rw [min_eq_left (by exact_mod_cast hs)] + exact hcut S (Finset.nonempty_iff_ne_empty.mpr he) hs + · rw [min_eq_right (by exact_mod_cast le_of_not_ge hs)] + have hi := hcut Sᶜ (Finset.nonempty_iff_ne_empty.mpr hc) (by simpa using le_of_not_ge hs) + have hcomm : (P.interedges Sᶜ S).card = (P.interedges S Sᶜ).card := by + have := P.symm + exact Rel.card_interedges_comm Sᶜ S + simpa only [compl_compl, hcomm] using hi + +lemma sum_nonempty_subsets_power (q : ℝ) : + (∑ S ∈ (Finset.univ : Finset (Finset V)).erase ∅, q^S.card) = + (1+q)^(Fintype.card V)-1 := by + have hs := Finset.sum_erase_add (s := Finset.univ) (fun S : Finset V => q^S.card) + (Finset.mem_univ (∅ : Finset V)) + have hp := Finset.prod_one_add (s := (Finset.univ : Finset V)) (f := fun _ => q) + simp only [Finset.prod_const, Finset.card_univ, Finset.powerset_univ] at hp + simp only [Finset.card_empty, pow_zero] at hs + linarith + +theorem edge_splitting_failure_bound (P : SimpleGraph V) [DecidableRel P.Adj] + {l : ℕ} [NeZero l] {h : ℝ} (hexp : CutExpansion P h) : + (edgeColorMeasure V l).real {ω | ∃ i, ¬CutExpansion (colorGraph P ω i) (h/(2*l))} ≤ + l * (exp ((Fintype.card V : ℝ)*exp (-h/(8*l)))-1) := by + let cuts : Finset (Finset V) := Finset.univ.erase ∅ + let B (i : Fin l) (S : Finset V) : Set (Sym2 V → Fin l) := + {ω | S.card ≤ Sᶜ.card ∧ + (((colorGraph P ω i).interedges S Sᶜ).card : ℝ) < h*S.card/(2*l)} + let q : ℝ := exp (-h/(8*l)) + have cover : {ω | ∃ i, ¬CutExpansion (colorGraph P ω i) (h/(2*l))} ⊆ + ⋃ i ∈ (Finset.univ : Finset (Fin l)), ⋃ S ∈ cuts, B i S := by + intro ω hω + rcases hω with ⟨i, hi⟩ + by_contra hn + apply hi + apply cutExpansion_of_small_cuts + intro S hS hs + have hb : ω ∉ B i S := by + intro hm + apply hn + exact Set.mem_iUnion.mpr ⟨i, Set.mem_iUnion.mpr ⟨Finset.mem_univ _, + Set.mem_iUnion.mpr ⟨S, Set.mem_iUnion.mpr + ⟨Finset.mem_erase.mpr ⟨hS.ne_empty, Finset.mem_univ _⟩, hm⟩⟩⟩⟩ + have hc : h*S.card/(2*l) ≤ (((colorGraph P ω i).interedges S Sᶜ).card : ℝ) := by + exact le_of_not_gt (fun hf => hb ⟨hs, hf⟩) + convert hc using 1 ; ring + have hbound (i : Fin l) (S : Finset V) : + (edgeColorMeasure V l).real (B i S) ≤ q^S.card := by + by_cases hs : S.card ≤ Sᶜ.card + · calc + _ ≤ (edgeColorMeasure V l).real {ω | + (((colorGraph P ω i).interedges S Sᶜ).card : ℝ) < h*S.card/(2*l)} := + measureReal_mono (fun _ hw => hw.2) + _ ≤ exp (-h*S.card/(8*l)) := color_cut_lower_tail P i S hexp hs + _ = q^S.card := by dsimp [q]; rw [← exp_nat_mul]; congr 1; ring + · have he : B i S = ∅ := by ext ω; simp [B,hs] + rw [he, measureReal_empty] + exact pow_nonneg (exp_pos _).le _ + calc + _ ≤ (edgeColorMeasure V l).real + (⋃ i ∈ (Finset.univ : Finset (Fin l)), ⋃ S ∈ cuts, B i S) := + measureReal_mono cover (measure_ne_top _ _) + _ ≤ ∑ i : Fin l, (edgeColorMeasure V l).real (⋃ S ∈ cuts, B i S) := + measureReal_biUnion_finset_le _ _ + _ ≤ ∑ i : Fin l, ∑ S ∈ cuts, (edgeColorMeasure V l).real (B i S) := + Finset.sum_le_sum (fun _ _ => measureReal_biUnion_finset_le _ _) + _ ≤ ∑ _i : Fin l, ∑ S ∈ cuts, q^S.card := by + apply Finset.sum_le_sum; intro i _; exact Finset.sum_le_sum (fun S _ => hbound i S) + _ = (l : ℝ)*((1+q)^(Fintype.card V)-1) := by + simp only [cuts, sum_nonempty_subsets_power, Finset.sum_const, Finset.card_univ, + Fintype.card_fin, nsmul_eq_mul] + _ ≤ l*(exp ((Fintype.card V : ℝ)*q)-1) := by + apply mul_le_mul_of_nonneg_left _ (Nat.cast_nonneg l) + apply sub_le_sub_right + calc + _ ≤ (exp q)^(Fintype.card V) := + pow_le_pow_left₀ (by dsimp [q]; positivity) (by linarith [add_one_le_exp q]) _ + _ = _ := (exp_nat_mul _ _).symm + +theorem edge_splitting_of_error_lt_one (P : SimpleGraph V) [DecidableRel P.Adj] + {l : ℕ} [NeZero l] {h : ℝ} (hexp : CutExpansion P h) + (herror : (l : ℝ)*(exp ((Fintype.card V : ℝ)*exp (-h/(8*l)))-1) < 1) : + ∃ ω : Sym2 V → Fin l, + (∀ i, CutExpansion (colorGraph P ω i) (h/(2*l))) ∧ + (∀ x y, P.Adj x y ↔ ∃ i, (colorGraph P ω i).Adj x y) ∧ + (∀ i j, i ≠ j → Disjoint (colorGraph P ω i).edgeSet (colorGraph P ω j).edgeSet) := by + have he := (edge_splitting_failure_bound P hexp).trans_lt herror + have hh : ∃ ω : Sym2 V → Fin l, ∀ i, CutExpansion (colorGraph P ω i) (h/(2*l)) := by + by_contra hn + push Not at hn + have hall : {ω : Sym2 V → Fin l | ∃ i, ¬CutExpansion (colorGraph P ω i) (h/(2*l))} = + Set.univ := Set.eq_univ_of_forall hn + simp only [hall, Measure.real, measure_univ, ENNReal.toReal_one] at he + exact (lt_irrefl _ he) + obtain ⟨ω, hω⟩ := hh + refine ⟨ω, hω, ?_, ?_⟩ + · intro x y + exact ⟨fun hxy => ⟨ω s(x,y), hxy, rfl⟩, fun ⟨_, hxy, _⟩ => hxy⟩ + · intro i j hij + apply Set.disjoint_left.mpr + intro e hei hej + induction e using Sym2.ind with | _ x y => + have hi : (colorGraph P ω i).Adj x y := by simpa using hei + have hj : (colorGraph P ω j).Adj x y := by simpa using hej + exact hij (hi.2.symm.trans hj.2) + +end + +open Filter Asymptotics +open scoped Topology + +lemma tendsto_monomial_exp_neg_power (a b c : ℝ) (hb : 0 < b) (hc : 0 < c) : + Tendsto (fun D : ℝ => D^a * exp (-c * D^b)) atTop (𝓝 0) := by + have ht := (tendsto_rpow_mul_exp_neg_mul_atTop_nhds_zero (a/b) c hc).comp + (tendsto_rpow_atTop hb) + apply ht.congr' + filter_upwards [eventually_gt_atTop (0 : ℝ)] with D hD + dsimp only [Function.comp_def] + rw [← Real.rpow_mul hD.le, mul_div_cancel₀ _ hb.ne'] + +noncomputable def edgeSplittingScaleError (c : ℝ) (l : ℕ) (D : ℝ) : ℝ := + (l : ℝ) * (Real.exp (D^(51/50 : ℝ) * Real.exp ((-(c / (8*l))) * D^(9/10 : ℝ))) - 1) + +lemma edgeSplittingScaleError_tendsto (c : ℝ) (hc : 0 < c) (l : ℕ) (hl : 0 < l) : + Tendsto (edgeSplittingScaleError c l) atTop (𝓝 0) := by + have hlR : 0 < (l : ℝ) := by exact_mod_cast hl + have ht := tendsto_monomial_exp_neg_power (51/50) (9/10) (c/(8*l)) + (by norm_num) (by positivity) + have hh := ((Real.continuous_exp.tendsto 0).comp ht).sub_const 1 |>.const_mul (l : ℝ) + unfold edgeSplittingScaleError + convert hh using 1 <;> norm_num + +universe u + +theorem edge_splitting_uniform (c : ℝ) (hc : 0 < c) (l : ℕ) (hl : 0 < l) : + ∃ D₀ : ℝ, ∀ D : ℝ, D₀ ≤ D → ∀ (V : Type u) [Fintype V] [DecidableEq V] + (P : SimpleGraph V) [DecidableRel P.Adj] (h : ℝ), + c*D^(9/10 : ℝ) ≤ h → D^(9/10 : ℝ) ≤ (Fintype.card V : ℝ) → + (Fintype.card V : ℝ) ≤ D^(51/50 : ℝ) → CutExpansion P h → + ∃ ω : Sym2 V → Fin l, + (∀ i, CutExpansion (colorGraph P ω i) (h/(2*l))) ∧ + (∀ x y, P.Adj x y ↔ ∃ i, (colorGraph P ω i).Adj x y) ∧ + (∀ i j, i ≠ j → Disjoint (colorGraph P ω i).edgeSet (colorGraph P ω j).edgeSet) := by + have : NeZero l := ⟨hl.ne'⟩ + have hlR : 0 < (l : ℝ) := by exact_mod_cast hl + have hevent := (edgeSplittingScaleError_tendsto c hc l hl).eventually_lt_const + (show (0 : ℝ) < 1 by norm_num) + obtain ⟨D₀,hD₀⟩ := hevent.exists_forall_of_atTop + refine ⟨D₀, ?_⟩ + intro D hD V _ _ P _ h hh _hrlo hrhi hexp + apply edge_splitting_of_error_lt_one P hexp + apply lt_of_le_of_lt _ (hD₀ D hD) + unfold edgeSplittingScaleError + apply mul_le_mul_of_nonneg_left _ hlR.le + apply sub_le_sub_right + apply exp_le_exp.mpr + apply mul_le_mul hrhi _ (exp_pos _).le ((Nat.cast_nonneg (Fintype.card V)).trans hrhi) + apply exp_le_exp.mpr + have he := div_le_div_of_nonneg_right hh (show 0 ≤ 8*(l : ℝ) by positivity) + calc + -h/(8*l) = -(h/(8*l)) := by ring + _ ≤ -(c*D^(9/10 : ℝ)/(8*l)) := neg_le_neg he + _ = -(c/(8*l))*D^(9/10 : ℝ) := by ring + +end ErdosGallai.Splitting + +end +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/CycleDecomposition/EndpointPartition.lean b/lean/OAI/Combinatorics/CycleDecomposition/EndpointPartition.lean new file mode 100644 index 0000000000000000000000000000000000000000..5d79d83d3c6f0ade6e0b8850e3ec73d5b8ce703e --- /dev/null +++ b/lean/OAI/Combinatorics/CycleDecomposition/EndpointPartition.lean @@ -0,0 +1,275 @@ +import OAI.Combinatorics.CycleDecomposition.PathDeletion + +namespace OAI + +universe cycleUniverse1 cycleUniverse2 cycleUniverse3 cycleUniverse4 cycleUniverse5 cycleUniverse6 cycleUniverse7 cycleUniverse8 cycleUniverse9 cycleUniverse10 cycleUniverse11 cycleUniverse12 cycleUniverse13 cycleUniverse14 + +section +open Filter Asymptotics Real +open scoped Topology +noncomputable section +open MeasureTheory ProbabilityTheory Finset +noncomputable section +namespace ErdosGallai +noncomputable section +attribute [local instance] Classical.propDecidable +open scoped BigOperators + +theorem endpoint_partition_of_family {V : Type cycleUniverse1} {I : Type cycleUniverse2} [Fintype V] [Fintype I] + {G : SimpleGraph V} (P : I → PositiveSimplePath G) + (hd : Pairwise fun i j => Disjoint (P i).walk.edgeSet (P j).walk.edgeSet) + (hc : (⋃ i, (P i).walk.edgeSet) = G.edgeSet) + (hl : ∀ x : V, (Finset.univ.filter fun i => + (P i).start = x ∨ (P i).finish = x).card ≤ 2) : EndpointPathPartition G := by + classical + let e := (Fintype.equivFin I).symm + refine ⟨Fintype.card I,fun j => P (e j),?_,?_,?_,endpoint_path_count P hl⟩ + · intro i j hij + exact hd (fun he => hij (e.injective he)) + · rw [← hc] + ext z + simp only [Set.mem_iUnion] + constructor + · rintro ⟨i,hi⟩; exact ⟨e i,hi⟩ + · rintro ⟨i,hi⟩; exact ⟨e.symm i,by rw [e.apply_symm_apply]; exact hi⟩ + · intro x + have heq : (Finset.univ.filter fun j => (P (e j)).start = x ∨ (P (e j)).finish = x).card = + (Finset.univ.filter fun i => (P i).start = x ∨ (P i).finish = x).card := by + apply Finset.card_bij (fun j _ => e j) + · intro i hi; simpa only [Finset.mem_filter,Finset.mem_univ,true_and] using hi + · intro i hi j hj he; exact e.injective he + · intro i hi; exact ⟨e.symm i,by simpa using hi, by simp⟩ + rw [heq] + exact hl x + +def PositiveSimplePath.mapIso {V : Type cycleUniverse3} {W : Type cycleUniverse4} {G : SimpleGraph V} {H : SimpleGraph W} + (f : G ≃g H) (P : PositiveSimplePath G) : PositiveSimplePath H := + ⟨f P.start,f P.finish,P.walk.map f.toHom,P.isPath.map f.injective,by simpa using P.positive⟩ + +theorem endpoint_partition_mapIso {V : Type cycleUniverse5} {W : Type cycleUniverse6} [Fintype V] [Fintype W] + {G : SimpleGraph V} {H : SimpleGraph W} (f : G ≃g H) + (hp : EndpointPathPartition G) : EndpointPathPartition H := by + classical + obtain ⟨k,P,hd,hc,hl,hk⟩ := hp + apply endpoint_partition_of_family (fun i => (P i).mapIso f) + · intro i j hij + change Disjoint ((P i).walk.map f.toHom).edgeSet ((P j).walk.map f.toHom).edgeSet + simp only [SimpleGraph.Walk.edgeSet_map] + exact (Set.disjoint_image_iff (Sym2.map.injective f.injective)).mpr (hd hij) + · have hmap : Sym2.map f.toHom '' G.edgeSet = H.edgeSet := by + ext e + induction e using Sym2.inductionOn with | _ u v => + constructor + · rintro ⟨e,he,heq⟩ + induction e using Sym2.inductionOn with | _ a b => + have ha : H.Adj (f a) (f b) := f.toHom.map_adj he + exact heq ▸ ha + · intro huv + refine ⟨s(f.symm u, f.symm v), f.symm.toHom.map_adj huv,?_⟩ + simp + change (⋃ i, ((P i).walk.map f.toHom).edgeSet) = H.edgeSet + simp_rw [SimpleGraph.Walk.edgeSet_map] + rw [← Set.image_iUnion,hc,hmap] + · intro x + have heq : (Finset.univ.filter fun i => ((P i).mapIso f).start = x ∨ + ((P i).mapIso f).finish = x) = + (Finset.univ.filter fun i => (P i).start = f.symm x ∨ (P i).finish = f.symm x) := by + ext i + simp only [Finset.mem_filter,Finset.mem_univ,true_and] + change (f (P i).start = x ∨ f (P i).finish = x) ↔ _ + exact or_congr (f.toEquiv.eq_symm_apply.symm) (f.toEquiv.eq_symm_apply.symm) + rw [heq] + exact hl _ + +namespace SimplePathPiece +variable {V : Type cycleUniverse7} {I : Type cycleUniverse8} [Fintype V] [Fintype I] [DecidableEq V] {G : SimpleGraph V} + +lemma deletedInduced_map {V : Type cycleUniverse9} {I : Type cycleUniverse10} [_contextInstance2 : Fintype V] [_contextInstance3 : Fintype I] [_contextInstance4 : DecidableEq V] {G : SimpleGraph V} (p : I → SimplePathPiece G) (v : V) + (j : {j : DeleteIndex p v // 0 < (deleted p v j).walk.length}) : + (deletedInduced p v j).walk.map (SimpleGraph.Embedding.induce _).toHom = + (deleted p v j.val).walk := by + exact SimpleGraph.Walk.map_induce _ _ + +lemma deletedInduced_edges (p : I → SimplePathPiece G) (v : V) + (j : {j : DeleteIndex p v // 0 < (deleted p v j).walk.length}) : + Sym2.map (SimpleGraph.Embedding.induce (G := G) {x | x ≠ v}).toHom '' + (deletedInduced p v j).walk.edgeSet = (deleted p v j.val).walk.edgeSet := by + calc + _ = ((deletedInduced p v j).walk.map + (SimpleGraph.Embedding.induce {x | x ≠ v}).toHom).edgeSet := + (SimpleGraph.Walk.edgeSet_map _ _).symm + _ = _ := congrArg (fun q : G.Walk (deleted p v j.val).start + (deleted p v j.val).finish => q.edgeSet) (deletedInduced_map p v j) + +def deletedPositive (p : I → SimplePathPiece G) (v : V) + (j : {j : DeleteIndex p v // 0 < (deleted p v j).walk.length}) : + PositiveSimplePath (G.induce {x | x ≠ v}) := + { deletedInduced p v j with + positive := by + have h := congrArg SimpleGraph.Walk.length (deletedInduced_map p v j) + rw [SimpleGraph.Walk.length_map] at h + rw [h] + exact j.property } + +theorem endpoint_partition_after_deletion (p : I → SimplePathPiece G) (v : V) + (hne : ∀ i, (p i).start ≠ (p i).finish) + (hd : Pairwise fun i j => Disjoint (p i).walk.edgeSet (p j).walk.edgeSet) + (hc : (⋃ i, (p i).walk.edgeSet) = G.edgeSet) + (hl : ∀ x : V, x ≠ v → (Finset.univ.filter fun i => + (p i).start = x ∨ (p i).finish = x).card ≤ 1) : + EndpointPathPartition (G.induce {x | x ≠ v}) := by + classical + let A := {j : DeleteIndex p v // 0 < (deleted p v j).walk.length} + let f : G.induce {x | x ≠ v} →g G := (SimpleGraph.Embedding.induce _).toHom + have hf : Function.Injective f := Subtype.val_injective + apply endpoint_partition_of_family (fun j : A => deletedPositive p v j) + · intro j k hjk + have hdis := deleted_disjoint p v hd (fun he => hjk (Subtype.ext he)) + apply Set.disjoint_left.mpr + intro e hej hek + have he1 : Sym2.map f e ∈ (deleted p v j.val).walk.edgeSet := by + rw [← deletedInduced_edges p v j] + exact ⟨e,hej,rfl⟩ + have he2 : Sym2.map f e ∈ (deleted p v k.val).walk.edgeSet := by + rw [← deletedInduced_edges p v k] + exact ⟨e,hek,rfl⟩ + exact Set.disjoint_left.mp hdis he1 he2 + · apply Set.Subset.antisymm + · intro e he + obtain ⟨j,hj⟩ := Set.mem_iUnion.mp he + exact (deletedPositive p v j).walk.edges_subset_edgeSet hj + · intro e he + have he' : Sym2.map f e ∈ G.edgeSet ∧ v ∉ Sym2.map f e := by + induction e using Sym2.inductionOn with | _ a b => + refine ⟨he,?_⟩ + change v ∉ s(a.val,b.val) + simpa only [Sym2.map_mk,Sym2.mem_iff,eq_comm] using not_or.mpr ⟨a.property,b.property⟩ + have hmem : Sym2.map f e ∈ ⋃ j : A, (deleted p v j.val).walk.edgeSet := by + rw [deleted_positive_union] + refine ⟨?_,he'.2⟩ + exact Set.mem_iUnion.mp (hc.symm ▸ he'.1) + obtain ⟨j,hj⟩ := Set.mem_iUnion.mp hmem + rw [← deletedInduced_edges p v j] at hj + obtain ⟨e',he',heq⟩ := hj + have heq' : e' = e := Sym2.map.injective hf heq + subst e' + exact Set.mem_iUnion.mpr ⟨j,he'⟩ + · intro x + have hb := deleted_endpoint_load p v x.val hne hd (hl x.val x.property) + have hc' : (Finset.univ.filter fun j : A => + (deletedPositive p v j).start = x ∨ (deletedPositive p v j).finish = x).card ≤ + (Finset.univ.filter fun j : DeleteIndex p v => 0 < (deleted p v j).walk.length ∧ + ((deleted p v j).start = x.val ∨ (deleted p v j).finish = x.val)).card := by + apply Finset.card_le_card_of_injOn Subtype.val + · intro j hj + apply Finset.mem_filter.mpr + refine ⟨Finset.mem_univ _,j.property,?_⟩ + rcases (Finset.mem_filter.mp hj).2 with hs | ht + · exact Or.inl (congrArg Subtype.val hs) + · exact Or.inr (congrArg Subtype.val ht) + · exact fun _ _ _ _ he => Subtype.ext he + convert hc'.trans hb using 1 + + congr 1 + ext i + simp only [Finset.mem_filter,Finset.mem_univ,true_and] + +end SimplePathPiece + +def evenAugmentationOldIso {V : Type cycleUniverse11} [Fintype V] (G : SimpleGraph V) : + G ≃g (evenAugmentation G).induce {x | x ≠ none} where + toEquiv := Equiv.optionSubtype none ⟨Equiv.refl (Option V),rfl⟩ + map_rel_iff' := Iff.rfl + +theorem endpoint_partition_of_augmented_parts {V : Type cycleUniverse12} [Fintype V] + (G : SimpleGraph V) (hL : LovaszPathCyclePartition (evenAugmentation G)) : + EndpointPathPartition G := by + classical + obtain ⟨k,parts,hparts,hd,hc,hk⟩ := hL + have hw : ∀ i : Fin k, ∃ (a b : Option V) (p : (evenAugmentation G).Walk a b), + p.IsTrail ∧ (a ≠ b → p.IsPath) ∧ parts i = p.edgeSet := by + intro i + rcases hparts i with ⟨a,b,p,hp,_,he⟩ | ⟨a,p,hp,he⟩ + · exact ⟨a,b,p,hp.isTrail,fun _ => hp,he⟩ + · exact ⟨a,a,p,hp.isTrail,fun h => False.elim (h rfl),he⟩ + choose a b p ht hp he using hw + have hd' : Pairwise fun i j => Disjoint (p i).edgeSet (p j).edgeSet := by + simpa only [he] using hd + have hc' : (⋃ i, (p i).edgeSet) = (evenAugmentation G).edgeSet := by + simpa only [he] using hc + let S : Finset (Option V) := Finset.univ.image some + have hS : S.card = Fintype.card V := by + simp only [S,Finset.card_image_of_injective _ (Option.some_injective V),Finset.card_univ] + have ho : ∀ x ∈ S, Odd ((evenAugmentation G).degree x) := by + intro x hx + obtain ⟨y,_,rfl⟩ := Finset.mem_image.mp hx + exact evenAugmentation_old_odd G y + have hk' : 2 * Fintype.card (Fin k) ≤ S.card + 1 := by + simpa only [Fintype.card_fin,Fintype.card_option,hS] using hk + obtain ⟨hopen,hload⟩ := tight_odd_trail_partition (evenAugmentation G) S p ht hd' hc' ho hk' + let P : Fin k → SimplePathPiece (evenAugmentation G) := fun i => + ⟨a i,b i,p i,hp i (hopen i)⟩ + have hload' : ∀ x : Option V, x ≠ none → (Finset.univ.filter fun i => + (P i).start = x ∨ (P i).finish = x).card ≤ 1 := by + intro x hx + cases x with + | none => exact False.elim (hx rfl) + | some x => + have h := hload (some x) (Finset.mem_image.mpr ⟨x,Finset.mem_univ _,rfl⟩) + have hpred : (Finset.univ.filter fun i => a i ≠ b i ∧ + (some x = a i ∨ some x = b i)) = + (Finset.univ.filter fun i => (P i).start = some x ∨ (P i).finish = some x) := by + ext i + simp only [Finset.mem_filter,Finset.mem_univ,true_and,P] + constructor + · rintro ⟨_,hi⟩ + exact hi.elim (fun h => Or.inl h.symm) (fun h => Or.inr h.symm) + · intro hi + exact ⟨hopen i,hi.elim (fun h => Or.inl h.symm) (fun h => Or.inr h.symm)⟩ + apply le_of_eq + calc + _ = _ := congrArg Finset.card hpred.symm + _ = 1 := by + convert h using 1 + congr 1 + ext i + simp only [Finset.mem_filter,Finset.mem_univ,true_and] + + have hdel := SimplePathPiece.endpoint_partition_after_deletion P none hopen hd' hc' hload' + exact endpoint_partition_mapIso (evenAugmentationOldIso G).symm hdel + +end +end ErdosGallai + +namespace ErdosGallai +noncomputable section + +theorem lovasz_path_cycle_partition {V : Type cycleUniverse13} [Fintype V] (G : SimpleGraph V) : + LovaszPathCyclePartition G := by + classical + obtain ⟨k,P,hd,hc,hk⟩ := Lovasz.path_cycle_partition G + refine ⟨k,fun i => (P i).walk.edgeSet,?_,hd,hc,?_⟩ + · intro i + rcases (P i).simple with hp | ⟨h,hcy⟩ + · exact Or.inl ⟨(P i).start,(P i).finish,(P i).walk,hp.1,hp.2,rfl⟩ + · exact Or.inr ⟨(P i).start,(P i).walk.copy rfl h,hcy,by simp⟩ + · exact hk.trans (Finset.card_le_univ _) + +theorem lovasz_theorem : MissingLovaszTheorem := + fun _ G => lovasz_path_cycle_partition G + +theorem endpoint_path_partition {V : Type cycleUniverse14} [Fintype V] (G : SimpleGraph V) : + EndpointPathPartition G := + endpoint_partition_of_augmented_parts G (lovasz_path_cycle_partition (evenAugmentation G)) + +theorem endpoint_theorem : MissingEndpointTheorem := + fun _ G => endpoint_path_partition G + +end +end ErdosGallai + +end +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/CycleDecomposition/ExpansionBoxes.lean b/lean/OAI/Combinatorics/CycleDecomposition/ExpansionBoxes.lean new file mode 100644 index 0000000000000000000000000000000000000000..e24f385bd6775336d3b9ad66497b73f739c1a2b3 --- /dev/null +++ b/lean/OAI/Combinatorics/CycleDecomposition/ExpansionBoxes.lean @@ -0,0 +1,658 @@ +import OAI.Combinatorics.CycleDecomposition.DepthFirstSearch + +namespace OAI + +universe cycleUniverse1 cycleUniverse2 cycleUniverse3 cycleUniverse4 cycleUniverse5 cycleUniverse6 cycleUniverse7 cycleUniverse8 cycleUniverse9 cycleUniverse10 cycleUniverse11 cycleUniverse12 cycleUniverse13 + +section +open Filter Asymptotics Real +open scoped Topology +noncomputable section +open MeasureTheory ProbabilityTheory Finset +section +namespace ErdosGallai.Scale +open Finset SimpleGraph +variable {V : Type cycleUniverse1} [Fintype V] [DecidableEq V] +def avoidGraph (G : SimpleGraph V) (J : Finset V) : SimpleGraph V where + Adj x y := G.Adj x y ∧ x ∉ J ∧ y ∉ J + symm := ⟨fun _x _y h => ⟨h.1.symm,h.2.2,h.2.1⟩⟩ + loopless := ⟨fun _x h => G.irrefl h.1⟩ + +lemma chain_reachable {V : Type cycleUniverse2} [_contextInstance1 : Fintype V] [_contextInstance2 : DecidableEq V] {H : SimpleGraph V} {L : List V} (hL : L.IsChain H.Adj) + {x y : V} (hx : x ∈ L) (hy : y ∈ L) : H.Reachable x y := by + let : Trans H.Reachable H.Reachable H.Reachable := ⟨fun h₁ h₂ => h₁.trans h₂⟩ + cases L with + | nil => simp at hx + | cons a L => + have hC : (a::L).IsChain H.Reachable := hL.imp (fun _ _ h => h.reachable) + have ha : ∀ b ∈ a::L, H.Reachable a b := by + intro b hb + rcases List.mem_cons.mp hb with rfl|hb + · exact .refl _ + · exact hC.rel_cons hb + exact (ha x hx).symm.trans (ha y hy) + +theorem connector_exists (G : SimpleGraph V) [DecidableRel G.Adj] + (α m : ℝ) (hα : 0 ≤ α) (hexp : VertexExpansion G α) + (X Z J : Finset V) (hX : X.Nonempty) (hZ : Z.Nonempty) + (hXJ : Disjoint X J) (hZJ : Disjoint Z J) + (hconnX : ∀ x ∈ X, ∀ y ∈ X, (avoidGraph G J).Reachable x y) + (_hconnZ : ∀ x ∈ Z, ∀ y ∈ Z, (avoidGraph G J).Reachable x y) + (hmX : m ≤ (X.card : ℝ)) (hmZ : m ≤ (Z.card : ℝ)) + (hJ : (J.card : ℝ) < α*m) : + ∃ x ∈ X, ∃ z ∈ Z, (avoidGraph G J).Reachable x z := by + classical + by_contra hn + obtain ⟨x,hx⟩ := hX + obtain ⟨z,hz⟩ := hZ + let H := avoidGraph G J + let A : Finset V := univ.filter (fun v => v ∉ J ∧ H.Reachable x v) + let B : Finset V := univ \ (J ∪ A) + have hXA : X ⊆ A := by + intro y hy + exact mem_filter.mpr ⟨mem_univ _, + (Finset.disjoint_left.mp hXJ hy), hconnX x hx y hy⟩ + have hZA : ∀ y ∈ Z, ¬ H.Reachable x y := by + intro y hy hr + exact hn ⟨x,hx,y,hy,hr⟩ + have hZB : Z ⊆ B := by + intro y hy + simp only [B, Finset.mem_sdiff, mem_univ, true_and, mem_union, not_or] + refine ⟨Finset.disjoint_left.mp hZJ hy, ?_⟩ + intro ha + exact hZA y hy (mem_filter.mp ha).2.2 + have hAB : Disjoint A B := by + apply Finset.disjoint_left.mpr + intro y ha hb + exact (mem_sdiff.mp hb).2 (mem_union_right J ha) + have hc : A.card + B.card ≤ Fintype.card V := by + rw [← card_union_of_disjoint hAB] + exact card_le_univ _ + have hboundaryA : externalNeighbors G A ⊆ J := by + intro v hv + obtain ⟨_,hva,u,hu,hadj⟩ := mem_filter.mp hv + by_contra hvj + obtain ⟨_,huj,hru⟩ := mem_filter.mp hu + have hadjH : H.Adj u v := ⟨hadj,huj,hvj⟩ + exact hva (mem_filter.mpr ⟨mem_univ _,hvj,hru.trans hadjH.reachable⟩) + have hboundaryB : externalNeighbors G B ⊆ J := by + intro v hv + obtain ⟨_,hvb,u,hu,hadj⟩ := mem_filter.mp hv + by_contra hvj + have hva : v ∈ A := by + by_contra hna + exact hvb (mem_sdiff.mpr ⟨mem_univ _, by simpa using And.intro hvj hna⟩) + obtain ⟨_,_,hrv⟩ := mem_filter.mp hva + have huj : u ∉ J := fun h => (mem_sdiff.mp hu).2 (mem_union_left A h) + have hadjH : H.Adj v u := ⟨hadj.symm,hvj,huj⟩ + have hua : u ∈ A := mem_filter.mpr ⟨mem_univ _,huj,hrv.trans hadjH.reachable⟩ + exact (mem_sdiff.mp hu).2 (mem_union_right J hua) + have hcontr (Q : Finset V) (hne : Q.Nonempty) (hsmall : 2*Q.card ≤ Fintype.card V) + (hm : m ≤ (Q.card : ℝ)) (hb : externalNeighbors G Q ⊆ J) : False := by + have he := hexp Q hne hsmall + have hc : ((externalNeighbors G Q).card : ℝ) ≤ J.card := by + exact_mod_cast card_le_card hb + have hh := mul_le_mul_of_nonneg_left hm hα + linarith + by_cases hsmall : 2*A.card ≤ Fintype.card V + · exact hcontr A ⟨x,hXA hx⟩ hsmall + (hmX.trans (by exact_mod_cast card_le_card hXA)) hboundaryA + · exact hcontr B ⟨z,hZB hz⟩ (by omega) + (hmZ.trans (by exact_mod_cast card_le_card hZB)) hboundaryB + +lemma avoid_support {V : Type cycleUniverse3} [_contextInstance1 : Fintype V] [_contextInstance2 : DecidableEq V] (G : SimpleGraph V) (J : Finset V) {x z : V} + (p : (avoidGraph G J).Walk x z) (hx : x ∉ J) : + ∀ w ∈ p.support, w ∉ J := by + induction p with + | nil => simpa using hx + | @cons u v z hadj p ih => + intro w hw + rcases List.mem_cons.mp hw with rfl|hw + · exact hx + · exact ih hadj.2.2 w hw + +theorem shortest_set_connector (G : SimpleGraph V) (X Z J : Finset V) + (hXJ : Disjoint X J) + (hr : ∃ x ∈ X, ∃ z ∈ Z, (avoidGraph G J).Reachable x z) : + ∃ x ∈ X, ∃ z ∈ Z, ∃ p : G.Walk x z, + p.IsPath ∧ ∀ w ∈ p.support, w ∉ J ∧ (w ∈ X → w = x) ∧ (w ∈ Z → w = z) := by + classical + let H := avoidGraph G J + let P : ℕ → Prop := fun k => ∃ x ∈ X, ∃ z ∈ Z, ∃ p : H.Walk x z, + p.IsPath ∧ p.length = k + have hP : ∃ k, P k := by + obtain ⟨x,hx,z,hz,hr⟩ := hr + obtain ⟨p,hp⟩ := hr.exists_isPath + exact ⟨p.length,x,hx,z,hz,p,hp,rfl⟩ + obtain ⟨x,hx,z,hz,p,hp,hplen⟩ := Nat.find_spec hP + have hmin : ∀ a ∈ X, ∀ b ∈ Z, ∀ q : H.Walk a b, q.IsPath → p.length ≤ q.length := by + intro a ha b hb q hq + rw [hplen] + exact Nat.find_min' hP ⟨a,ha,b,hb,q,hq,rfl⟩ + have hsub : H ≤ G := fun _ _ h => h.1 + refine ⟨x,hx,z,hz,p.mapLe hsub,(hp.mapLe hsub),?_⟩ + intro w hw + rw [Walk.support_mapLe_eq_support] at hw + refine ⟨avoid_support G J p (Finset.disjoint_left.mp hXJ hx) w hw,?_,?_⟩ + · intro hwX + by_contra hne + have hlt := Walk.length_dropUntil_lt_length hw hne + have hle := hmin w hwX z hz (p.dropUntil w hw) (hp.dropUntil hw) + omega + · intro hwZ + by_contra hne + have hlt := Walk.length_takeUntil_lt_length hw hne + have hle := hmin x hx w hwZ (p.takeUntil w hw) (hp.takeUntil hw) + omega + +lemma path_cons_append {V : Type cycleUniverse4} [_contextInstance1 : Fintype V] [_contextInstance2 : DecidableEq V] (G : SimpleGraph V) (x z : V) (B : List V) + (hC : (x :: (B ++ [z])).IsChain G.Adj) : + ∃ p : G.Walk x z, p.support = x :: (B ++ [z]) := by + let L := x :: (B ++ [z]) + have hn : L ≠ [] := by simp [L] + let p := Walk.ofSupport L hn hC + have hx : L.head hn = x := rfl + have hz : L.getLast hn = z := by simp [L] + exact ⟨p.copy hx hz, by + change ((Walk.ofSupport L hn hC).copy hx hz).support = L + rw [Walk.support_copy, Walk.support_ofSupport]⟩ + +theorem cycle_across_middle (G : SimpleGraph V) (X J Z : List V) + (hnd : (X ++ J ++ Z).Nodup) (hC : (X ++ J ++ Z).IsChain G.Adj) + (hj : 1 ≤ J.length) + (hc : ∃ x ∈ X, ∃ z ∈ Z, ∃ q : G.Walk x z, + q.IsPath ∧ ∀ w ∈ q.support, w ∉ J ∧ (w ∈ X → w = x) ∧ (w ∈ Z → w = z)) : + ∃ a : V, ∃ c : G.Walk a a, c.IsCycle ∧ J.length + 2 ≤ c.length := by + obtain ⟨x,hx,z,hz,q,hq,havoid⟩ := hc + obtain ⟨A,B,hX⟩ := List.mem_iff_append.mp hx + obtain ⟨C,D,hZ⟩ := List.mem_iff_append.mp hz + let M := x :: ((B ++ J ++ C) ++ [z]) + have heq : X ++ J ++ Z = A ++ (M ++ D) := by + simp [hX,hZ,M,List.append_assoc] + have hMC : M.IsChain G.Adj := by + rw [heq] at hC + exact hC.right_of_append.left_of_append + have hMN : M.Nodup := by + rw [heq] at hnd + exact (List.nodup_append.mp (List.nodup_append.mp hnd).2.1).1 + obtain ⟨p,hpS⟩ := path_cons_append G x z (B ++ J ++ C) hMC + have hp : p.IsPath := by + rw [Walk.isPath_def,hpS] + exact hMN + have hlen : J.length + 1 ≤ p.length := by + have ht := p.length_support + rw [hpS] at ht + simp only [List.length_cons,List.length_append] at ht + omega + have hxs : x ∉ p.support.tail := by + have hn := hp.support_nodup + rw [← p.cons_tail_support] at hn + exact (List.nodup_cons.mp hn).1 + have hzs : z ∉ q.reverse.support.tail := by + have hn := hq.reverse.support_nodup + rw [← q.reverse.cons_tail_support] at hn + exact (List.nodup_cons.mp hn).1 + have hdis : p.support.tail.Disjoint q.reverse.support.tail := by + apply List.disjoint_left.mpr + intro w hwP hwQ + have hwq : w ∈ q.support := by + simpa using List.mem_of_mem_tail hwQ + obtain ⟨hwJ,hwX,hwZ⟩ := havoid w hwq + have hwp : w ∈ X ++ J ++ Z := by + rw [heq] + have : w ∈ M := by + change w ∈ x :: ((B ++ J ++ C) ++ [z]) + rw [← hpS] + exact List.mem_of_mem_tail hwP + simp only [List.mem_append] + exact Or.inr (Or.inl this) + simp only [List.mem_append] at hwp + rcases hwp with (hw|hw)|hw + · exact hxs (hwX hw ▸ hwP) + · exact hwJ hw + · exact hzs (hwZ hw ▸ hwQ) + have hxz : x ≠ z := by + intro he + have hz : z ∈ p.support.tail := by simp [hpS] + exact hxs (he ▸ hz) + have hqlen : 1 ≤ q.length := by + by_contra hh + have : q.length = 0 := by omega + exact hxz (Walk.eq_of_length_eq_zero this) + refine ⟨x,p.append q.reverse,hp.isCycle_append hq.reverse hdis (Or.inl (by omega)),?_⟩ + simp only [Walk.length_append,Walk.length_reverse] + omega + +theorem long_cycle_of_vertex_expansion (G : SimpleGraph V) [DecidableRel G.Adj] + (α : ℝ) (hα : 0 < α) (hα1 : α ≤ 1) (hexp : VertexExpansion G α) + (hq : 1 ≤ α^2 * Fintype.card V / 100) : + ∃ a : V, ∃ c : G.Walk a a, c.IsCycle ∧ + α^2 * Fintype.card V / 100 < (c.length : ℝ) := by + classical + obtain ⟨L,hnd,hchain,hL⟩ := exists_long_stack G α hα1 hexp + let q := α^2 * Fintype.card V / 100 + let j := ⌊q⌋₊ + have hq0 : 0 ≤ q := by dsimp [q]; linarith + have hjle : (j : ℝ) ≤ q := Nat.floor_le hq0 + have hjlt : q < (j : ℝ)+1 := Nat.lt_floor_add_one q + have hj1 : 1 ≤ j := by exact (Nat.le_floor_iff hq0).mpr (by simpa [q] using hq) + have hL0 : (0 : ℝ) ≤ L.length := Nat.cast_nonneg _ + have hu0 : (0 : ℝ) ≤ Fintype.card V := Nat.cast_nonneg _ + have haa : α^2 ≤ α := by nlinarith + have hqq : 2*q ≤ α * Fintype.card V / 6 := by + have hh := mul_le_mul_of_nonneg_right haa hu0 + dsimp [q] + nlinarith [mul_nonneg (le_of_lt hα) hu0] + have hround : 2*(j+1) ≤ L.length := by + have hroundR : 2*((j:ℝ)+1) ≤ (L.length:ℝ) := by + have hq1 : 1 ≤ q := hq + linarith + exact_mod_cast hroundR + let k := (L.length-j)/2 + let X := L.take k + let J := (L.drop k).take j + let Z := (L.drop k).drop j + have heq : L = X ++ J ++ Z := by + dsimp [X,J,Z] + rw [List.append_assoc,List.take_append_drop,List.take_append_drop] + have hk : k ≤ L.length := by dsimp [k]; omega + have hjdrop : j ≤ (L.drop k).length := by simp only [List.length_drop]; dsimp [k]; omega + have hXlen : X.length = k := by simp [X,List.length_take, min_eq_left hk] + have hJlen : J.length = j := by dsimp [J]; rw [List.length_take, min_eq_left hjdrop] + have hZlen : Z.length = L.length-k-j := by simp only [Z,List.length_drop] + have houterX : L.length ≤ 4*X.length := by rw [hXlen]; dsimp [k]; omega + have houterZ : L.length ≤ 4*Z.length := by rw [hZlen]; dsimp [k]; omega + rw [heq] at hnd hchain + have hnX : X.Nodup := (List.nodup_append.mp (List.nodup_append.mp hnd).1).1 + have hnJ : J.Nodup := (List.nodup_append.mp (List.nodup_append.mp hnd).1).2.1 + have hnZ : Z.Nodup := (List.nodup_append.mp hnd).2.1 + have hXJ : X.Disjoint J := (List.nodup_append.mp hnd).1.disjoint + have hZJ : Z.Disjoint J := by + have hd := hnd.disjoint + exact List.disjoint_left.mpr (fun w hwz hwj => + List.disjoint_left.mp hd (List.mem_append_right X hwj) hwz) + have hXJf : Disjoint X.toFinset J.toFinset := by + apply Finset.disjoint_left.mpr + intro w hw hJw + exact List.disjoint_left.mp hXJ (List.mem_toFinset.mp hw) (List.mem_toFinset.mp hJw) + have hZJf : Disjoint Z.toFinset J.toFinset := by + apply Finset.disjoint_left.mpr + intro w hw hJw + exact List.disjoint_left.mp hZJ (List.mem_toFinset.mp hw) (List.mem_toFinset.mp hJw) + have hconnX : ∀ x ∈ X.toFinset, ∀ y ∈ X.toFinset, + (avoidGraph G J.toFinset).Reachable x y := by + intro x hx y hy + apply chain_reachable (L := X) _ (List.mem_toFinset.mp hx) (List.mem_toFinset.mp hy) + apply hchain.left_of_append.left_of_append.imp_of_mem_imp + intro a b ha hb hab + exact ⟨hab,fun hj => List.disjoint_left.mp hXJ ha (List.mem_toFinset.mp hj), + fun hj => List.disjoint_left.mp hXJ hb (List.mem_toFinset.mp hj)⟩ + have hconnZ : ∀ x ∈ Z.toFinset, ∀ y ∈ Z.toFinset, + (avoidGraph G J.toFinset).Reachable x y := by + intro x hx y hy + apply chain_reachable (L := Z) _ (List.mem_toFinset.mp hx) (List.mem_toFinset.mp hy) + apply hchain.right_of_append.imp_of_mem_imp + intro a b ha hb hab + exact ⟨hab,fun hj => List.disjoint_left.mp hZJ ha (List.mem_toFinset.mp hj), + fun hj => List.disjoint_left.mp hZJ hb (List.mem_toFinset.mp hj)⟩ + have hXne : X.toFinset.Nonempty := by + rw [← Finset.card_pos,List.toFinset_card_of_nodup hnX] + omega + have hZne : Z.toFinset.Nonempty := by + rw [← Finset.card_pos,List.toFinset_card_of_nodup hnZ] + omega + have hmX : (L.length : ℝ)/4 ≤ X.toFinset.card := by + rw [List.toFinset_card_of_nodup hnX] + have : (L.length : ℝ) ≤ 4*(X.length:ℝ) := by exact_mod_cast houterX + linarith + have hmZ : (L.length : ℝ)/4 ≤ Z.toFinset.card := by + rw [List.toFinset_card_of_nodup hnZ] + have : (L.length : ℝ) ≤ 4*(Z.length:ℝ) := by exact_mod_cast houterZ + linarith + have hsmallJ : (J.toFinset.card : ℝ) < α*((L.length:ℝ)/4) := by + rw [List.toFinset_card_of_nodup hnJ,hJlen] + have hmul := mul_le_mul_of_nonneg_left hL (le_of_lt hα) + dsimp [q] at hjle + nlinarith + obtain ⟨x,hx,z,hz,p,hp,hpavoid⟩ := shortest_set_connector G X.toFinset Z.toFinset J.toFinset hXJf + (connector_exists G α ((L.length:ℝ)/4) (le_of_lt hα) hexp + X.toFinset Z.toFinset J.toFinset hXne hZne hXJf hZJf hconnX hconnZ hmX hmZ hsmallJ) + obtain ⟨a,c,hc,hlen⟩ := cycle_across_middle G X J Z hnd hchain (by omega) + ⟨x,List.mem_toFinset.mp hx,z,List.mem_toFinset.mp hz,p,hp,by simpa using hpavoid⟩ + refine ⟨a,c,hc,?_⟩ + rw [hJlen] at hlen + have hlR : (j:ℝ)+2 ≤ c.length := by exact_mod_cast hlen + change q < (c.length:ℝ) + linarith + +end ErdosGallai.Scale + +namespace ErdosGallai.Scale +open Classical +end ErdosGallai.Scale +namespace ErdosGallai.Scale +open Finset SimpleGraph Classical +variable {V : Type cycleUniverse5} [Fintype V] [DecidableEq V] + +def SupportedOn (G : SimpleGraph V) (A : Finset V) : Prop := + ∀ ⦃x y⦄, G.Adj x y → x ∈ A ∧ y ∈ A + +structure AssignedPiece (V : Type cycleUniverse6) [DecidableEq V] where + vertices : Finset V + graph : SimpleGraph V + supported : SupportedOn graph vertices + +noncomputable def restrictGraph (G : SimpleGraph V) (A : Finset V) : SimpleGraph V where + Adj x y := G.Adj x y ∧ x ∈ A ∧ y ∈ A + symm := ⟨fun _ _ h => ⟨h.1.symm,h.2.2,h.2.1⟩⟩ + loopless := ⟨fun _ h => G.irrefl h.1⟩ + +noncomputable def crossingGraph (G : SimpleGraph V) (A B : Finset V) : SimpleGraph V where + Adj x y := G.Adj x y ∧ ((x ∈ A ∧ y ∈ B) ∨ (x ∈ B ∧ y ∈ A)) + symm := ⟨fun _ _ h => ⟨h.1.symm, h.2.elim (fun h => Or.inr ⟨h.2,h.1⟩) + (fun h => Or.inl ⟨h.2,h.1⟩)⟩⟩ + loopless := ⟨fun _ h => G.irrefl h.1⟩ + +noncomputable def edgeOccurrences (L : List (SimpleGraph V)) (x y : V) : ℕ := by + classical + exact L.countP (fun H => H.Adj x y) + +def GraphPartition (G : SimpleGraph V) (L : List (SimpleGraph V)) : Prop := + ∀ x y, edgeOccurrences L x y = if G.Adj x y then 1 else 0 + +noncomputable def edgeCount (G : SimpleGraph V) : ℕ := by + classical + exact G.edgeFinset.card + +noncomputable def cutCount (G : SimpleGraph V) (A B : Finset V) : ℕ := by + classical + exact (G.interedges A B).card + +def CutExpansionOn (G : SimpleGraph V) (A : Finset V) (h : ℝ) : Prop := + ∀ U ⊆ A, h * min (U.card : ℝ) ((A \ U).card : ℝ) ≤ cutCount G U (A \ U) + +@[simp] lemma edgeOccurrences_nil {V : Type cycleUniverse7} [_contextInstance1 : Fintype V] [_contextInstance2 : DecidableEq V] (x y : V) : edgeOccurrences [] x y = 0 := by + classical + simp [edgeOccurrences] +@[simp] lemma edgeOccurrences_cons {V : Type cycleUniverse8} [_contextInstance1 : Fintype V] [_contextInstance2 : DecidableEq V] (H : SimpleGraph V) (L) (x y : V) : + edgeOccurrences (H::L) x y = (if H.Adj x y then 1 else 0) + edgeOccurrences L x y := by + classical + simp [edgeOccurrences, List.countP_cons, Nat.add_comm] +@[simp] lemma edgeOccurrences_append {V : Type cycleUniverse9} [_contextInstance1 : Fintype V] [_contextInstance2 : DecidableEq V] (L M : List (SimpleGraph V)) (x y : V) : + edgeOccurrences (L++M) x y = edgeOccurrences L x y + edgeOccurrences M x y := by + classical + simp [edgeOccurrences] + +lemma restrictGraph_le {V : Type cycleUniverse10} [_contextInstance1 : Fintype V] [_contextInstance2 : DecidableEq V] (G : SimpleGraph V) (A : Finset V) : restrictGraph G A ≤ G := + fun _ _ h => h.1 +lemma restrictGraph_supported {V : Type cycleUniverse11} [_contextInstance1 : Fintype V] [_contextInstance2 : DecidableEq V] (G : SimpleGraph V) (A : Finset V) : + SupportedOn (restrictGraph G A) A := fun _ _ h => h.2 + +lemma partition_member_le {V : Type cycleUniverse12} [_contextInstance1 : Fintype V] [_contextInstance2 : DecidableEq V] {G : SimpleGraph V} {L : List (SimpleGraph V)} + (h : GraphPartition G L) {H : SimpleGraph V} (hH : H ∈ L) : H ≤ G := by + classical + intro x y hxy + by_contra hn + have hc := h x y + simp only [hn, ite_false] at hc + have hp : 0 < edgeOccurrences L x y := by + simpa [edgeOccurrences, List.countP_pos_iff] using (show ∃ K ∈ L, K.Adj x y from ⟨H,hH,hxy⟩) + omega + +@[simp] lemma edgeCount_bot {V : Type cycleUniverse13} [_contextInstance1 : Fintype V] [_contextInstance2 : DecidableEq V] : edgeCount (⊥ : SimpleGraph V) = 0 := by + classical + apply Finset.card_eq_zero.mpr + apply Finset.eq_empty_iff_forall_notMem.mpr + intro e he + simp only [SimpleGraph.mem_edgeFinset, SimpleGraph.edgeSet_bot, Set.mem_empty_iff_false] at he + +open Real + +noncomputable def splitPotential (T x : ℝ) : ℝ := + 1 + 1 / logb 2 (T/2) - 1 / logb 2 (max x (T/2)) + +lemma logb_four_thirds : (1/4:ℝ) ≤ logb 2 (4/3) := by + have h := Real.logb_le_logb_of_le (b:=2) (x:=2) (y:=(4/3:ℝ)^4) + (by norm_num) (by norm_num) (by norm_num) + rw [Real.logb_pow] at h + norm_num only [Real.logb_self_eq_one, Nat.cast_ofNat] at h + have hlog : 0 < Real.log 2 := Real.log_pos (by norm_num) + nlinarith + +lemma splitPotential_bounds (T x : ℝ) (hT : 4 ≤ T) : + 1 ≤ splitPotential T x ∧ splitPotential T x ≤ 2 := by + have hbase : 1 ≤ logb 2 (T/2) := by + have hh := Real.logb_le_logb_of_le (b:=2) (x:=2) (y:=T/2) + (by norm_num) (by norm_num) (by linarith) + norm_num [Real.logb] at hh + exact hh + have hlog := Real.logb_le_logb_of_le (b:=2) (x:=T/2) (y:=max x (T/2)) + (by norm_num) (by linarith) (le_max_right _ _) + have hsmall : 0 < logb 2 (T/2) := by linarith + have hbig : 0 < logb 2 (max x (T/2)) := by linarith + have hrecip : 1 / logb 2 (max x (T/2)) ≤ 1 / logb 2 (T/2) := + one_div_le_one_div_of_le hsmall hlog + have hrecipone : 1/logb 2 (T/2) ≤ 1 := (div_le_one hsmall).mpr hbase + dsimp [splitPotential] + constructor + · linarith + · linarith [one_div_pos.mpr hbig] + +lemma splitPotential_monotone (T : ℝ) (hT : 4 ≤ T) : Monotone (splitPotential T) := by + intro x y hxy + have hpos : 0 < T/2 := by linarith + have hlogx : 0 < logb 2 (max x (T/2)) := + Real.logb_pos (by norm_num) (lt_of_lt_of_le (by linarith : 1 < T/2) (le_max_right _ _)) + have hlog := Real.logb_le_logb_of_le (b:=2) (by norm_num) + (lt_of_lt_of_le hpos (le_max_right x (T/2))) (max_le_max hxy le_rfl) + have hi := one_div_le_one_div_of_le hlogx hlog + dsimp [splitPotential] + linarith + +lemma split_potential_decrement (T u u₁ : ℝ) (hT : 4 ≤ T) (hu : T < u) + (h₁ : u₁ ≤ 3*u/4) : + (1/4:ℝ)/(logb 2 u)^2 ≤ splitPotential T u - splitPotential T u₁ := by + let M := max u₁ (T/2) + have hu0 : 0 < u := by linarith + have hM0 : 0 < M := lt_of_lt_of_le (by linarith : 0 < T/2) (le_max_right _ _) + have hMu : M ≤ 3*u/4 := max_le h₁ (by linarith) + have hMlt : M ≤ u := by linarith + have hLu : 0 < logb 2 u := Real.logb_pos (by norm_num) (by linarith) + have hLM : 0 < logb 2 M := Real.logb_pos (by norm_num) + (lt_of_lt_of_le (by linarith : 1 < T/2) (le_max_right _ _)) + have hlle : logb 2 M ≤ logb 2 u := + Real.logb_le_logb_of_le (by norm_num) hM0 hMlt + have hquot : (4/3:ℝ) ≤ u/M := (le_div_iff₀ hM0).mpr (by linarith) + have hlogq := Real.logb_le_logb_of_le (b:=2) (x:=4/3) (y:=u/M) + (by norm_num) (by norm_num) hquot + rw [Real.logb_div hu0.ne' hM0.ne'] at hlogq + have hgap : (1/4:ℝ) ≤ logb 2 u - logb 2 M := logb_four_thirds.trans hlogq + have hmax : max u (T/2) = u := max_eq_left (by linarith) + dsimp [splitPotential] + rw [hmax] + change (1/4:ℝ)/(logb 2 u)^2 ≤ + (1+1/logb 2 (T/2)-1/logb 2 u) - (1+1/logb 2 (T/2)-1/logb 2 M) + have hid : (1+1/logb 2 (T/2)-1/logb 2 u) - (1+1/logb 2 (T/2)-1/logb 2 M) = + (logb 2 u-logb 2 M)/(logb 2 M*logb 2 u) := by field_simp; ring + rw [hid] + apply (div_le_div_iff₀ (sq_pos_of_pos hLu) (mul_pos hLM hLu)).mpr + have hm := mul_le_mul_of_nonneg_right hlle hLu.le + nlinarith [sq_nonneg (logb 2 u)] + +lemma split_potential_subadditive (T u u₁ u₂ : ℝ) (hT : 4 ≤ T) (hu : T < u) + (hu₁ : 0 ≤ u₁) (hu₂ : 0 ≤ u₂) (h₁ : u₁ ≤ 3*u/4) (h₂ : u₂ ≤ u) + (hsum : u₁+u₂ ≤ u+(1/32:ℝ)*u₁/(logb 2 u)^2) : + u₁*splitPotential T u₁ + u₂*splitPotential T u₂ ≤ u*splitPotential T u := by + have hdec := split_potential_decrement T u u₁ hT hu h₁ + have hmono := splitPotential_monotone T hT h₂ + obtain ⟨hfpos,hfhi⟩ := splitPotential_bounds T u hT + have h₁cost := mul_le_mul_of_nonneg_left hdec hu₁ + have h₂cost := mul_le_mul_of_nonneg_left hmono hu₂ + have hLu : 0 < logb 2 u := Real.logb_pos (by norm_num) (by linarith) + have hden : 0 < (logb 2 u)^2 := sq_pos_of_pos hLu + have hsumcost := mul_le_mul_of_nonneg_right hsum (by linarith : 0 ≤ splitPotential T u) + have hwt : 0 ≤ u₁/(logb 2 u)^2 := div_nonneg hu₁ hden.le + have hratio : u₁*((1/4:ℝ)/(logb 2 u)^2) = (1/4:ℝ)*(u₁/(logb 2 u)^2) := by ring + have hratio2 : ((1/32:ℝ)*u₁/(logb 2 u)^2)*splitPotential T u = + (1/32:ℝ)*(u₁/(logb 2 u)^2)*splitPotential T u := by ring + simp only [add_mul] at hsumcost + rw [hratio2] at hsumcost + rw [hratio] at h₁cost + nlinarith + +noncomputable def externalOn (G : SimpleGraph V) (U : Finset V) : Finset V := + univ.filter (fun v => v ∉ U ∧ ∃ u ∈ U, G.Adj u v) + +lemma externalOn_subset {G : SimpleGraph V} {A U : Finset V} (hG : SupportedOn G A) : + externalOn G U ⊆ A := by + intro x hx + obtain ⟨u,hu,hadj⟩ := (Finset.mem_filter.mp hx).2.2 + exact (hG hadj).2 + +lemma externalOn_disjoint (G : SimpleGraph V) (U : Finset V) : + Disjoint U (externalOn G U) := by + apply Finset.disjoint_left.mpr + intro x hx hn + exact (Finset.mem_filter.mp hn).2.1 hx + +lemma overlap_child_supported {G : SimpleGraph V} {A U : Finset V} + (hG : SupportedOn G A) (_hU : U ⊆ A) : + SupportedOn (G \ restrictGraph G (U ∪ externalOn G U)) (A\U) := by + intro x y hxy + obtain ⟨hx,hy⟩ := hG hxy.1 + have hb (x y : V) (hxy : G.Adj x y) (hx : x ∈ U) : y ∈ U ∪ externalOn G U := by + by_cases hy : y ∈ U + · exact Finset.mem_union_left _ hy + · exact Finset.mem_union_right _ (Finset.mem_filter.mpr ⟨Finset.mem_univ _,hy,x,hx,hxy⟩) + constructor + · refine Finset.mem_sdiff.mpr ⟨hx,fun hxU => ?_⟩ + exact hxy.2 ⟨hxy.1,Finset.mem_union_left _ hxU,hb x y hxy.1 hxU⟩ + · refine Finset.mem_sdiff.mpr ⟨hy,fun hyU => ?_⟩ + exact hxy.2 ⟨hxy.1,hb y x hxy.1.symm hyU,Finset.mem_union_left _ hyU⟩ + +lemma overlap_child_sizes {G : SimpleGraph V} {A U : Finset V} {T : ℝ} + (hT : 4 ≤ T) (hlarge : T < (A.card : ℝ)) (hU : U ⊆ A) + (hne : U.Nonempty) (hhalf : 2*U.card ≤ A.card) + (hsparse : ((externalOn G U).card : ℝ) < (1/32:ℝ)*U.card/(logb 2 A.card)^2) : + (U ∪ externalOn G U).Nonempty ∧ (A\U).Nonempty ∧ + ((U ∪ externalOn G U).card : ℝ) ≤ 3*A.card/4 ∧ + (A\U).card < A.card ∧ + ((U ∪ externalOn G U).card : ℝ) + (A\U).card ≤ + A.card+(1/32:ℝ)*(U ∪ externalOn G U).card/(logb 2 A.card)^2 := by + have hu : 0 < U.card := hne.card_pos + have hlog : 1 ≤ logb 2 (A.card : ℝ) := by + have h := Real.logb_le_logb_of_le (b:=2) (x:=2) (y:=A.card) + (by norm_num) (by norm_num) (by linarith) + norm_num [Real.logb] at h + exact h + have hd : 0 < (logb 2 (A.card : ℝ))^2 := by positivity + have hquot : (1/32:ℝ)/(logb 2 (A.card : ℝ))^2 ≤ 1/2 := by + apply (div_le_iff₀ hd).mpr + nlinarith [sq_nonneg (logb 2 (A.card : ℝ)-1)] + have hsmall : ((externalOn G U).card : ℝ) < (U.card : ℝ)/2 := by + have hm := mul_le_mul_of_nonneg_right hquot (Nat.cast_nonneg U.card) + have hid : (1/32:ℝ)/(logb 2 (A.card : ℝ))^2 * U.card = + (1/32:ℝ)*U.card/(logb 2 (A.card : ℝ))^2 := by ring + rw [hid] at hm + linarith + have hcard₁ := Finset.card_union_of_disjoint (externalOn_disjoint G U) + have hcard₂ := Finset.card_sdiff_add_card_eq_card hU + have hcard₁R : ((U ∪ externalOn G U).card : ℝ) = U.card+(externalOn G U).card := by + exact_mod_cast hcard₁ + have hcard₂R : ((A\U).card : ℝ) + U.card = A.card := by exact_mod_cast hcard₂ + have hhalfR : 2*(U.card : ℝ) ≤ A.card := by exact_mod_cast hhalf + have hmon : (1/32:ℝ)*U.card/(logb 2 A.card)^2 ≤ + (1/32:ℝ)*(U ∪ externalOn G U).card/(logb 2 A.card)^2 := by + gcongr + exact Finset.subset_union_left + refine ⟨hne.mono Finset.subset_union_left,?_,?_,?_,?_⟩ + · exact Finset.card_pos.mp (by omega) + · linarith + · omega + · linarith + +lemma partition_split_append {G K : SimpleGraph V} {L M : List (SimpleGraph V)} + (hle : K ≤ G) (hL : GraphPartition K L) (hM : GraphPartition (G\K) M) : + GraphPartition G (L++M) := by + intro x y + have h₁ := hL x y + have h₂ := hM x y + have hk := @hle x y + simp only [edgeOccurrences_append,SimpleGraph.sdiff_adj] at h₂ ⊢ + by_cases hK : K.Adj x y <;> by_cases hG : G.Adj x y <;> simp_all + +theorem box_recursion (G : SimpleGraph V) (A : Finset V) (T : ℝ) + (hT : 4 ≤ T) (hA : A.Nonempty) (hG : SupportedOn G A) + (hsplit : ∀ B ⊆ A, ∀ H : SimpleGraph V, H ≤ G → SupportedOn H B → T < (B.card : ℝ) → + ∃ U ⊆ B, U.Nonempty ∧ 2*U.card ≤ B.card ∧ + ((externalOn H U).card : ℝ) < (1/32:ℝ)*U.card/(logb 2 B.card)^2) : + ∃ L : List (AssignedPiece V), + (∀ P ∈ L, P.vertices ⊆ A ∧ P.vertices.Nonempty ∧ (P.vertices.card : ℝ) ≤ T) ∧ + (∀ x ∈ A, ∃ P ∈ L, x ∈ P.vertices) ∧ + GraphPartition G (L.map AssignedPiece.graph) ∧ + (L.map (fun P => (P.vertices.card : ℝ)*splitPotential T P.vertices.card)).sum ≤ + (A.card : ℝ)*splitPotential T A.card := by + classical + induction hn : A.card using Nat.strong_induction_on generalizing A G with + | h n ih => + by_cases hsmall : (A.card : ℝ) ≤ T + · let P : AssignedPiece V := ⟨A,G,hG⟩ + refine ⟨[P],?_,?_,?_,?_⟩ + · intro Q hQ; simp only [List.mem_singleton] at hQ; subst Q + exact ⟨Finset.Subset.refl _,hA,hsmall⟩ + · intro x hx; exact ⟨P,by simp,hx⟩ + · intro x y; simp [P] + · simp [P,← hn] + · have hlarge : T < (A.card : ℝ) := lt_of_not_ge hsmall + obtain ⟨U,hU,hne,hhalf,hsparse⟩ := hsplit A (Finset.Subset.refl _) G le_rfl hG hlarge + let B := externalOn G U + let A₁ := U ∪ B + let A₂ := A\U + let G₁ := restrictGraph G A₁ + let G₂ := G\G₁ + have hA₁ : A₁ ⊆ A := Finset.union_subset hU (externalOn_subset hG) + have hA₂ : A₂ ⊆ A := Finset.sdiff_subset + have hG₁ : G₁ ≤ G := restrictGraph_le G A₁ + have hG₂ : G₂ ≤ G := sdiff_le + have hs₁ : SupportedOn G₁ A₁ := restrictGraph_supported G A₁ + have hs₂ : SupportedOn G₂ A₂ := overlap_child_supported hG hU + obtain ⟨hn₁,hn₂,hsize₁,hsize₂,hsum⟩ := overlap_child_sizes hT hlarge hU hne hhalf hsparse + have hlt₁ : A₁.card < n := by + have hn0 : (0 : ℝ) < A.card := by linarith + have hlt : (A₁.card : ℝ) < A.card := lt_of_le_of_lt hsize₁ (by linarith) + exact hn ▸ (Nat.cast_lt.mp hlt) + have hlt₂ : A₂.card < n := hn ▸ hsize₂ + have subprem (D : Finset V) (hD : D ⊆ A) (K : SimpleGraph V) (hK : K ≤ G) : + ∀ C ⊆ D, ∀ H : SimpleGraph V, H ≤ K → SupportedOn H C → T < (C.card : ℝ) → + ∃ U ⊆ C, U.Nonempty ∧ 2*U.card ≤ C.card ∧ + ((externalOn H U).card : ℝ) < (1/32:ℝ)*U.card/(logb 2 C.card)^2 := by + intro C hC H hH hs hlarge + exact hsplit C (hC.trans hD) H (hH.trans hK) hs hlarge + obtain ⟨L,hL,hcovL,hpartL,hcostL⟩ := ih _ hlt₁ G₁ A₁ hn₁ hs₁ + (subprem A₁ hA₁ G₁ hG₁) rfl + obtain ⟨M,hM,hcovM,hpartM,hcostM⟩ := ih _ hlt₂ G₂ A₂ hn₂ hs₂ + (subprem A₂ hA₂ G₂ hG₂) rfl + refine ⟨L++M,?_,?_,?_,?_⟩ + · intro P hP + rcases List.mem_append.mp hP with hP | hP + · obtain ⟨hsub,hne,hbound⟩ := hL P hP; exact ⟨hsub.trans hA₁,hne,hbound⟩ + · obtain ⟨hsub,hne,hbound⟩ := hM P hP; exact ⟨hsub.trans hA₂,hne,hbound⟩ + · intro x hx + by_cases hxU : x ∈ U + · obtain ⟨P,hP,hxP⟩ := hcovL x (Finset.mem_union_left _ hxU) + exact ⟨P,List.mem_append_left _ hP,hxP⟩ + · obtain ⟨P,hP,hxP⟩ := hcovM x (Finset.mem_sdiff.mpr ⟨hx,hxU⟩) + exact ⟨P,List.mem_append_right _ hP,hxP⟩ + · simpa only [List.map_append] using partition_split_append hG₁ hpartL hpartM + · simp only [List.map_append,List.sum_append] + have hsub := split_potential_subadditive T A.card A₁.card A₂.card hT hlarge + (Nat.cast_nonneg _) (Nat.cast_nonneg _) hsize₁ (by exact_mod_cast hsize₂.le) hsum + rw [← hn] + linarith + +end ErdosGallai.Scale +end +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/CycleDecomposition/LayerCosts.lean b/lean/OAI/Combinatorics/CycleDecomposition/LayerCosts.lean new file mode 100644 index 0000000000000000000000000000000000000000..211e8cf318ab81e6a794ae1298d09de5293bbe43 --- /dev/null +++ b/lean/OAI/Combinatorics/CycleDecomposition/LayerCosts.lean @@ -0,0 +1,344 @@ +import OAI.Combinatorics.CycleDecomposition.UniformLayers + +namespace OAI + +section +open Filter Asymptotics Real +open scoped Topology +noncomputable section +open MeasureTheory ProbabilityTheory Finset +section + +namespace ErdosGallai.Scale +noncomputable section +open Finset SimpleGraph Real +attribute [local instance] Classical.propDecidable +variable {V : Type} [Fintype V] [DecidableEq V] + +lemma assigned_union_edges (L : List (AssignedPiece V)) : + (⋃ i : Fin L.length, (L.get i).graph.edgeSet) = (graphUnion (L.map AssignedPiece.graph)).edgeSet := by + ext e + induction e using Sym2.ind with + | _ x y => + simp only [Set.mem_iUnion,SimpleGraph.mem_edgeSet] + + rw [graphUnion_adj] + constructor + · rintro ⟨i,hi⟩ + exact ⟨_,List.mem_map.mpr ⟨_,L.get_mem i,rfl⟩,hi⟩ + · rintro ⟨G,hG,hxy⟩ + obtain ⟨Q,hQ,rfl⟩ := List.mem_map.mp hG + obtain ⟨i,rfl⟩ := List.mem_iff_get.mp hQ + exact ⟨i,hxy⟩ + +lemma box_coupled_partition {B R : AssignedPiece V} (A : List (AssignedPiece V)) + (hBR : GraphPartition B.graph (R.graph :: A.map AssignedPiece.graph)) + (s : SplitSystem V) (j k : ℕ) : + GraphPartition (graphUnion ((advance s j k [R]).map AssignedPiece.graph ++ A.map AssignedPiece.graph)) + ((advance s j k [R]).map AssignedPiece.graph ++ A.map AssignedPiece.graph) := by + apply graphPartition_of_le_one + intro x y + have hb := hBR x y + have hr := past_partition s j k R x y + simp only [edgeOccurrences_cons,edgeOccurrences_append] at hb hr ⊢ + split_ifs at hb hr <;> omega + +theorem uniform_local_box_cost : ∃ D₀ : ℝ, 1 < D₀ ∧ ∀ D ≥ D₀, ∀ wmin : ℝ, + ErdosGallai.MainScaleReady wmin D → + ∀ (V : Type) [Fintype V] (L A : List (AssignedPiece V)) (Y : Finset V), + GraphPartition (graphUnion (L.map AssignedPiece.graph ++ A.map AssignedPiece.graph)) + (L.map AssignedPiece.graph ++ A.map AssignedPiece.graph) → + A.Pairwise (fun R S => Disjoint R.vertices S.vertices) → + (∀ R ∈ A, R.vertices ⊆ Y) → + (∀ Q ∈ L, Q.vertices ⊆ Y) → + (∀ v ∈ Y, ∃ Q ∈ L, v ∈ Q.vertices) → + (∀ Q ∈ L, Q.vertices.Nonempty ∧ (Q.vertices.card:ℝ) ≤ D^(1/1000:ℝ) ∧ + 2*(edgeCount Q.graph:ℝ)/Q.vertices.card ≤ D^(1/1000:ℝ)) → + (∀ R ∈ A, D^(9/10:ℝ) ≤ (R.vertices.card:ℝ) ∧ (R.vertices.card:ℝ) ≤ D^(51/50:ℝ) ∧ + CutExpansionOn R.graph R.vertices (D^(9/10:ℝ))) → + (Y.card:ℝ) ≤ D^(51/50:ℝ) → vertexMass L ≤ 2*Y.card → + ∀ (n : ℕ) (C t : ℝ), 0 ≤ C → 0 ≤ t → Y.card ≤ n → D^(3/10:ℝ) < n → + (∀ (Q : Type) [Fintype Q] (H : SimpleGraph Q), Fintype.card Q < n → + (ErdosGallai.decompositionCost H:ℝ) ≤ C*Fintype.card Q) → + (∀ (Q : Type) [Fintype Q] (H : SimpleGraph Q), Fintype.card Q < n → + (Fintype.card Q:ℝ) ≤ D^(3/10:ℝ) → (Batch.decompositionCost H:ℝ) ≤ t*Fintype.card Q) → + (decompositionCost (graphUnion (L.map AssignedPiece.graph ++ A.map AssignedPiece.graph)):ℝ) ≤ + (9+C*ErdosGallai.mainEta)*vertexMass A + (t+8)*vertexMass L + + (8-t/3)*vertexMass A + ((2/3)*t/logb 2 D-8)*Y.card := by + obtain ⟨D₀,hD₀,hbox⟩ := ErdosGallai.uniform_box_cost + refine ⟨D₀,hD₀,?_⟩ + intro D hD wmin hready V _ L A Y hpart hAd hAY hLY hcover hL hA hY hmass + n C t hC ht hYn hsmall ih ihq + let F := graphUnion (L.map AssignedPiece.graph) + let G := graphUnion (L.map AssignedPiece.graph ++ A.map AssignedPiece.graph) + let R (r : Fin A.length) := (A.get r).graph + let U (r : Fin A.length) := (A.get r).vertices + have hp := List.pairwise_append.mp (graphPartition_pairwise hpart) + have hLL := list_pairwise_get (List.pairwise_map.mp hp.1) (fun _ _ h => h.symm) + have hRR : Pairwise (fun r s => Disjoint (R r).edgeSet (R s).edgeSet) := + list_pairwise_get (List.pairwise_map.mp hp.2.1) (fun _ _ h => h.symm) + have hUU : Pairwise (fun r s => Disjoint (U r) (U s)) := + list_pairwise_get hAd (fun _ _ h => h.symm) + have hFR (r) : Disjoint F.edgeSet (R r).edgeSet := by + rw [← assigned_union_edges] + exact Set.disjoint_iUnion_left.mpr (fun i => hp.2.2 _ (List.mem_map.mpr ⟨_,L.get_mem i,rfl⟩) + _ (List.mem_map.mpr ⟨_,A.get_mem r,rfl⟩)) + have hFG : F ≤ G := graphUnion_sublist (List.sublist_append_left _ _) + have hRG (r) : R r ≤ G := by + intro x y hxy + exact (graphUnion_adj _ _ _).mpr ⟨_,List.mem_append_right _ (List.mem_map.mpr ⟨_,A.get_mem r,rfl⟩),hxy⟩ + have hcov : F.edgeSet ∪ (⋃ r, (R r).edgeSet) = G.edgeSet := by + change F.edgeSet ∪ (⋃ r : Fin A.length, (A.get r).graph.edgeSet) = _ + rw [assigned_union_edges] + ext e + induction e using Sym2.ind with + | _ x y => simp only [Set.mem_union,SimpleGraph.mem_edgeSet,G,graphUnion_append,SimpleGraph.sup_adj,F] + have hB : 0 < D^(3/10:ℝ) := Real.rpow_pos_of_pos (by linarith [hready.gt_one]) _ + obtain ⟨b⟩ := Indexing.materialize_batches F Y (fun i : Fin L.length => (L.get i).graph) + (fun i => (L.get i).vertices) hLL (assigned_union_edges L) + (fun i x y hxy => (L.get i).supported hxy) (fun i => hLY _ (L.get_mem i)) + (by + intro v hv + obtain ⟨Q,hQ,hvQ⟩ := hcover v hv + obtain ⟨i,rfl⟩ := List.mem_iff_get.mp hQ + exact Finset.mem_biUnion.mpr ⟨i,mem_univ _,hvQ⟩) + (D^(3/10:ℝ)) hB (fun i => ((hL _ (L.get_mem i)).2.1).trans hready.batch_power) + have hsum : (∑ i : Fin L.length, ((L.get i).vertices.card:ℝ)) = vertexMass L := list_sum_get L (fun Q => (Q.vertices.card:ℝ)) + have hAsum : (∑ i : Fin A.length, ((U i).card:ℝ)) = vertexMass A := list_sum_get A (fun Q => (Q.vertices.card:ℝ)) + have hF : 2*(F.edgeFinset.card:ℝ) ≤ 2*Y.card*D^(1/1000:ℝ) := by + have hh := (Nat.cast_le.mpr (edgeCount_union_le (L.map AssignedPiece.graph)) : (_:ℝ) ≤ _) + have hdeg : (L.map (fun Q => 2*(edgeCount Q.graph:ℝ))).sum ≤ vertexMass L * D^(1/1000:ℝ) := by + unfold vertexMass + rw [← List.sum_map_mul_right] + apply List.sum_le_sum + intro Q hQ + have hc : (0:ℝ) < Q.vertices.card := by exact_mod_cast Finset.card_pos.mpr (hL Q hQ).1 + simpa only [mul_comm] using (div_le_iff₀ hc).mp (hL Q hQ).2.2 + simp only [Nat.cast_list_sum,List.map_map,Function.comp_def] at hh + rw [List.sum_map_mul_left] at hdeg + have hx := mul_le_mul_of_nonneg_right hmass (Real.rpow_nonneg (show (0:ℝ) ≤ D by linarith [hready.gt_one]) (1/1000:ℝ)) + change 2*(edgeCount F:ℝ) ≤ _ + linarith + have hcost := hbox D hD wmin hready V (Fin A.length) G F R U Y hFG hRG hRR hUU + (fun r => hAY _ (A.get_mem r)) (fun r x y hxy => (A.get r).supported hxy) hFR hcov + (fun r => (hA _ (A.get_mem r)).2.2) + (fun r => ⟨(hA _ (A.get_mem r)).1,(hA _ (A.get_mem r)).2.1⟩) + hY hF (∑ i : Fin L.length, ((L.get i).vertices.card:ℝ)) (by simpa only [hsum] using hmass) + b n C t hC ht hYn hsmall ih ihq + rw [hsum,hAsum] at hcost + change (decompositionCost G:ℝ) ≤ _ + convert hcost using 1 <;> first | rfl | ring + +end +end ErdosGallai.Scale + +end + +section + +namespace ErdosGallai.Scale +noncomputable section +open Finset SimpleGraph Real +attribute [local instance] Classical.propDecidable +variable {V : Type} [Fintype V] [DecidableEq V] + +lemma pastPieces_mem (s : SplitSystem V) (j k : ℕ) (L : List (AssignedPiece V)) + {R : AssignedPiece V} (hR : R ∈ pastPieces s j k L) : + ∃ l < k, R ∈ levelPieces s (j+l) (advance s j l L) := by + induction k with + | zero => simp [pastPieces] at hR + | succ k ih => + rcases List.mem_append.mp hR with h | h + · obtain ⟨l,hl,hR⟩ := ih h + exact ⟨l,by omega,hR⟩ + · exact ⟨k,by omega,h⟩ + +theorem uniform_committed_piece_cost : ∃ D₀ : ℝ, 1 < D₀ ∧ ∀ Dstar ≥ D₀, + ∀ (V : Type) [Fintype V] [DecidableEq V] (P : AssignedPiece V) (H : Layers P Dstar), + ∀ (C : ℝ), 0 ≤ C → + (∀ (Q : Type) [Fintype Q] (G : SimpleGraph Q), Fintype.card Q < P.vertices.card → + (ErdosGallai.decompositionCost G:ℝ) ≤ C*Fintype.card Q) → + ∀ k ≤ H.count, ∀ R ∈ pastPieces H.system 0 k [P], + (decompositionCost R.graph:ℝ) ≤ (9+C*ErdosGallai.mainEta)*R.vertices.card := by + obtain ⟨D₀,hD₀,hpc⟩ := ErdosGallai.uniform_piece_cost_on 1 ErdosGallai.mainEta (by norm_num) ErdosGallai.mainEta_pos + refine ⟨D₀,hD₀,?_⟩ + intro Dstar hD V _ _ P H C hC ih k hk R hR + obtain ⟨j,hjk,hR⟩ := pastPieces_mem H.system 0 k [P] hR + simp only [Nat.zero_add] at hR + obtain ⟨Q,hQ,B,hB,hR⟩ := (by simpa [levelPieces,List.mem_flatMap] using hR : + ∃ Q ∈ H.frontier j, ∃ B ∈ (H.system j Q).boxes, R ∈ (H.system j Q).pieces B) + have hj : j < H.count := by omega + have hb := (H.bounded j hj Q hQ).2.2.2.1 B hB R hR + have hsub := ((H.system j Q).piece_subset B hB R hR).trans (H.box_subset j hQ hB) + exact hpc (H.scale j) (hD.trans (H.cutoff j hj)) P.vertices.card C hC ih V R.graph R.graph R.vertices + le_rfl (Finset.card_le_card hsub) R.supported hb.1 hb.2.1 (by + simpa only [one_mul,ErdosGallai.CutExpansionOn,CutExpansionOn,cutCount,Layers.scale] using hb.2.2) + +theorem uniform_gap_prefix_cost : ∃ D₀ : ℝ, 1 < D₀ ∧ ∀ Dstar ≥ D₀, + ∀ (V : Type) [Fintype V] (P : AssignedPiece V) (H : Layers P Dstar), + 1 < (P.vertices.card:ℝ) → + (∀ j < H.count, ErdosGallai.MainScaleReady 80 (H.scale j)) → + ∀ i, i+200 < H.count → ∀ C t : ℝ, 0 ≤ C → 0 ≤ t → + (∀ (Q : Type) [Fintype Q] (G : SimpleGraph Q), Fintype.card Q < P.vertices.card → + (ErdosGallai.decompositionCost G:ℝ) ≤ C*Fintype.card Q) → + (∀ (Q : Type) [Fintype Q] (G : SimpleGraph Q), Fintype.card Q < P.vertices.card → + (Fintype.card Q:ℝ) ≤ (H.scale i)^(3/10:ℝ) → + (Batch.decompositionCost G:ℝ) ≤ t*Fintype.card Q) → + (∀ R ∈ pastPieces H.system 0 (i+201) [P], + (decompositionCost R.graph:ℝ) ≤ (9+C*ErdosGallai.mainEta)*R.vertices.card) → + (decompositionCost P.graph:ℝ) ≤ ((pastCycles H.system 0 (i+201) [P]).length:ℝ) + + (9+C*ErdosGallai.mainEta)*vertexMass (pastPieces H.system 0 (i+201) [P]) + + (t+8)*H.mass (i+201) + (8-t/3)*H.pieceMass i + + ((2/3)*t/logb 2 (H.scale i)-8)*H.mass (i+1) := by + obtain ⟨D₀,hD₀,hlocal⟩ := uniform_local_box_cost + refine ⟨D₀,hD₀,?_⟩ + intro Dstar hD V _ P H hn hready i hik C t hC ht ih ihq hp + have hi : i < H.count := by omega + have hne : P.vertices.Nonempty := Finset.card_pos.mp (by exact_mod_cast (by linarith : (0:ℝ) < P.vertices.card)) + have hsmall : (H.scale i)^(3/10:ℝ) < (P.vertices.card:ℝ) := by + apply lt_of_lt_of_le _ (inductionScale_le P.vertices.card hn.le i) + have hd := inductionScale_gt_one P.vertices.card hn i + simpa only [Real.rpow_one] using Real.rpow_lt_rpow_of_exponent_lt hd (by norm_num : (3/10:ℝ) < 1) + apply selected_prefix_cost H.system i 200 P (9+C*ErdosGallai.mainEta) + (t+8) (8-t/3) ((2/3)*t/logb 2 (H.scale i)-8) hp + intro Q hQ B hB + have hQne := advance_nonempty H.system 0 i [P] (by simpa using hne) Q hQ + have hBne := (H.system i Q).box_nonempty hQne B hB + have hrest : ((H.system i Q).rest B).vertices.Nonempty := by simpa only [StageSplit.rest_vertices] using hBne + exact hlocal (H.scale i) (hD.trans (H.cutoff i hi)) 80 (hready i hi) V + (advance H.system (i+1) 200 [(H.system i Q).rest B]) ((H.system i Q).pieces B) B.vertices + (box_coupled_partition _ (by simpa only [StageSplit.rest_graph _ hB] using (H.system i Q).box_partition B hB) _ _ _) + ((H.system i Q).piece_disjoint B hB) ((H.system i Q).piece_subset B hB) + (advance_subset H.system (i+1) 200 [(H.system i Q).rest B] B.vertices (by simp)) + (fun v hv => advance_cover H.system (i+1) 200 [(H.system i Q).rest B] ((H.system i Q).rest B) (by simp) v (by simpa only [StageSplit.rest_vertices] using hv)) + (fun R hR => ⟨advance_nonempty H.system (i+1) 200 [(H.system i Q).rest B] (by simpa using hrest) R hR, + H.gap_order hn i hik hQ hB hR⟩) + ((H.bounded i hi Q hQ).2.2.2.1 B hB) ((H.bounded i hi Q hQ).2.2.1 B hB) + (H.local_mass_two hn (fun j hj => (hready j hj).log_large) i 200 hik hQ hB) + P.vertices.card C t hC ht (Finset.card_le_card (H.box_subset i hQ hB)) hsmall ih ihq + +end +end ErdosGallai.Scale + +end + +section + +namespace ErdosGallai +noncomputable section +open Real + +lemma main_gap_scalar (q n S M L Nt Ni C t w : ℝ) + (hn : 0 ≤ n) (hS : 0 ≤ S) (hC : 0 ≤ C) (ht : 0 ≤ t) (hw : 0 < w) + (hM : M ≤ mainP*S) (hL : L ≤ mainH*n/w) + (hNt : Nt ≤ n+mainH*n/w) (hNilo : n ≤ Ni) (hNihi : Ni ≤ 2*n) + (hq : q ≤ L+(9+C*mainEta)*M+(t+8)*Nt+(8-t/3)*S+((2/3)*t/w-8)*Ni) : + q ≤ mainA₂*(S+n/w)+(C/100)*S+t*(n-S/3+mainA₁*n/w) := by + have hη := mainEta_pos + have hc := mul_le_mul_of_nonneg_left hM (by positivity : 0 ≤ 9+C*mainEta) + have hT := mul_le_mul_of_nonneg_left hNt (by linarith : 0 ≤ t+8) + have hI := mul_le_mul_of_nonneg_left hNihi (by positivity : 0 ≤ (2/3)*t/w) + have hI' : -8*Ni ≤ -8*n := by linarith + have hA := mul_le_mul_of_nonneg_right (le_max_left (9*mainP+8) (9*mainH)) hS + have hB := mul_le_mul_of_nonneg_right (le_max_right (9*mainP+8) (9*mainH)) (div_nonneg hn hw.le) + change (9*mainP+8)*S ≤ mainA₂*S at hA + change 9*mainH*(n/w) ≤ mainA₂*(n/w) at hB + simp only [mainEta,mainP,mainA₁,div_eq_mul_inv] at hc hT hI hI' hA hB hq hL ⊢ + nlinarith only [hc,hT,hI,hI',hA,hB,hq,hL] + +lemma main_terminal_scalar (q n M C Dstar : ℝ) (hn : 0 ≤ n) (hC : 0 ≤ C) + (hCbig : 4*(20+Dstar+18*mainP) ≤ C) (hM : M ≤ 2*mainP*n) + (hq : q ≤ (20+Dstar)*n+(9+C*mainEta)*M) : + q ≤ C*Batch.inductionPhi n*n := by + have hη := mainEta_pos + have hc := mul_le_mul_of_nonneg_left hM (by positivity : 0 ≤ 9+C*mainEta) + have hbig := mul_le_mul_of_nonneg_right hCbig hn + have hphi := mul_le_mul_of_nonneg_left (Batch.inductionPhi_bounds n).1 (mul_nonneg hC hn) + have hCn : 0 ≤ C*n := mul_nonneg hC hn + simp only [mainEta,mainP] at hc hbig hq + nlinarith only [hq,hc,hbig,hphi,hCn] + +end +end ErdosGallai + +namespace ErdosGallai.Scale +noncomputable section +open Finset SimpleGraph Real +attribute [local instance] Classical.propDecidable +variable {V : Type} [Fintype V] [DecidableEq V] {P : AssignedPiece V} {Dstar : ℝ} + +lemma Layers.gap_log (H : Layers P Dstar) (hn : 1 < (P.vertices.card:ℝ)) (i) : + logb 2 (H.scale (i+200)) = scaleTheta^200 * logb 2 (H.scale i) := by + dsimp only [Layers.scale] + rw [inductionScale_add _ (by positivity)] + exact Real.logb_rpow_eq_mul_logb_of_pos (inductionScale_pos _ (by linarith) _) + +lemma Layers.gap_mass (H : Layers P Dstar) (hn : 1 < (P.vertices.card:ℝ)) + (hready : ∀ j < H.count, ErdosGallai.MainScaleReady 80 (H.scale j)) (i) + (hik : i+200 < H.count) : + H.mass (i+201) ≤ (P.vertices.card:ℝ) + ErdosGallai.mainH*P.vertices.card/logb 2 (H.scale i) := by + have hh := H.mass_upper hn (fun j hj => (hready j hj).log_large) (i+200) hik + rw [H.gap_log hn] at hh + convert hh using 1 ; try omega + unfold ErdosGallai.mainH + simp only [div_eq_mul_inv,mul_inv_rev] + ring + +lemma Layers.gap_cycles (H : Layers P Dstar) (hn : 1 < (P.vertices.card:ℝ)) + (hready : ∀ j < H.count, ErdosGallai.MainScaleReady 80 (H.scale j)) (i) + (hik : i+200 < H.count) : + ((pastCycles H.system 0 (i+201) [P]).length:ℝ) ≤ + ErdosGallai.mainH*P.vertices.card/logb 2 (H.scale i) := by + have hh := H.cycles_bound hn hready (i+200) hik + rw [H.gap_log hn] at hh + have hw : 0 < logb 2 (H.scale i) := inductionScale_log_pos _ hn i + calc + _ ≤ 20*P.vertices.card/(scaleTheta^200*logb 2 (H.scale i)) := hh + _ ≤ 80*P.vertices.card/(scaleTheta^200*logb 2 (H.scale i)) := + div_le_div_of_nonneg_right (by nlinarith [(Nat.cast_nonneg P.vertices.card : (0:ℝ) ≤ _)]) (by positivity) + _ = _ := by unfold ErdosGallai.mainH; simp only [div_eq_mul_inv,mul_inv_rev]; ring + +lemma Layers.boundary_cost (H : Layers P Dstar) (hn : 1 < (P.vertices.card:ℝ)) + (hready : ∀ j < H.count, ErdosGallai.MainScaleReady 80 (H.scale j)) : + costMass (H.frontier H.count) ≤ Dstar*P.vertices.card := by + have hne : P.vertices.Nonempty := Finset.card_pos.mp (by exact_mod_cast (by linarith : (0:ℝ) < P.vertices.card)) + have hD : 0 ≤ Dstar := by + have hh := H.last_lt + have hd := inductionScale_pos P.vertices.card (by linarith) H.count + linarith + have hcost : ∀ Q ∈ H.frontier H.count, (decompositionCost Q.graph:ℝ) ≤ (Dstar/2)*Q.vertices.card := by + intro Q hQ + have hQne := advance_nonempty H.system 0 H.count [P] (by simpa using hne) Q hQ + have hc : (0:ℝ) < Q.vertices.card := by exact_mod_cast Finset.card_pos.mpr hQne + have hg := (div_le_iff₀ hc).mp (H.degree H.count le_rfl Q hQ) + have hh := mul_le_mul_of_nonneg_right H.last_lt.le hc.le + have he := (Nat.cast_le.mpr (decompositionCost_edgeCount Q.graph) : (_:ℝ) ≤ _) + nlinarith only [hg,hh,he] + have hh := piece_list_cost (H.frontier H.count) (Dstar/2) hcost + have hm := mul_le_mul_of_nonneg_left (H.mass_two hn (fun j hj => (hready j hj).log_large) H.count le_rfl) + (div_nonneg hD (by norm_num : (0:ℝ) ≤ 2)) + change costMass (H.frontier H.count) ≤ (Dstar/2)*H.mass H.count at hh + nlinarith only [hh,hm] + +lemma Layers.terminal_cost (H : Layers P Dstar) (hn : 1 < (P.vertices.card:ℝ)) + (hready : ∀ j < H.count, ErdosGallai.MainScaleReady 80 (H.scale j)) (c : ℝ) + (hp : ∀ R ∈ pastPieces H.system 0 H.count [P], (decompositionCost R.graph:ℝ) ≤ c*R.vertices.card) : + (decompositionCost P.graph:ℝ) ≤ (20+Dstar)*P.vertices.card + c*vertexMass (pastPieces H.system 0 H.count [P]) := by + have hcost := past_cost H.system 0 H.count P c hp + have he := H.boundary_cost hn hready + obtain ⟨j,hj⟩ := Nat.exists_eq_succ_of_ne_zero (Nat.ne_of_gt H.positive) + have hcy := H.cycles_bound hn hready j (by omega) + have hw := (hready j (by omega)).log_large + have hdiv : 20*(P.vertices.card:ℝ)/logb 2 (H.scale j) ≤ 20*P.vertices.card := + div_le_self (by positivity) (by linarith) + rw [hj] at hcost he ⊢ + nlinarith only [hcost,he,hcy,hdiv] + +end +end ErdosGallai.Scale + +end +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/CycleDecomposition/Lovasz.lean b/lean/OAI/Combinatorics/CycleDecomposition/Lovasz.lean new file mode 100644 index 0000000000000000000000000000000000000000..fbd9ce1b6ab357be009211d456cba647ff0ec482 --- /dev/null +++ b/lean/OAI/Combinatorics/CycleDecomposition/Lovasz.lean @@ -0,0 +1,1605 @@ +import OAI.Combinatorics.CycleDecomposition.ReservoirRemainder + +namespace OAI + +universe cycleUniverse1 cycleUniverse2 cycleUniverse3 cycleUniverse4 cycleUniverse5 cycleUniverse6 cycleUniverse7 cycleUniverse8 cycleUniverse9 cycleUniverse10 cycleUniverse11 cycleUniverse12 cycleUniverse13 cycleUniverse14 cycleUniverse15 cycleUniverse16 cycleUniverse17 cycleUniverse18 cycleUniverse19 cycleUniverse20 cycleUniverse21 cycleUniverse22 cycleUniverse23 cycleUniverse24 cycleUniverse25 cycleUniverse26 cycleUniverse27 cycleUniverse28 cycleUniverse29 cycleUniverse30 cycleUniverse31 cycleUniverse32 cycleUniverse33 cycleUniverse34 cycleUniverse35 cycleUniverse36 cycleUniverse37 cycleUniverse38 cycleUniverse39 cycleUniverse40 cycleUniverse41 cycleUniverse42 cycleUniverse43 cycleUniverse44 cycleUniverse45 cycleUniverse46 cycleUniverse47 cycleUniverse48 cycleUniverse49 cycleUniverse50 cycleUniverse51 cycleUniverse52 cycleUniverse53 cycleUniverse54 cycleUniverse55 cycleUniverse56 cycleUniverse57 cycleUniverse58 cycleUniverse59 cycleUniverse60 cycleUniverse61 cycleUniverse62 cycleUniverse63 cycleUniverse64 cycleUniverse65 cycleUniverse66 cycleUniverse67 cycleUniverse68 cycleUniverse69 cycleUniverse70 cycleUniverse71 cycleUniverse72 cycleUniverse73 cycleUniverse74 cycleUniverse75 cycleUniverse76 cycleUniverse77 cycleUniverse78 cycleUniverse79 cycleUniverse80 cycleUniverse81 cycleUniverse82 cycleUniverse83 cycleUniverse84 cycleUniverse85 + +section +open Filter Asymptotics Real +open scoped Topology +noncomputable section +open MeasureTheory ProbabilityTheory Finset +noncomputable section +namespace ErdosGallai.Lovasz +universe u +noncomputable section +open SimpleGraph +attribute [local instance] Classical.propDecidable + +def StarActive {V : Type cycleUniverse1} (S : Set V) (R : V → V → Prop) (v : V) : Prop := + ∃ a ∈ S, Relation.ReflTransGen R a v + +lemma starActive_source {V : Type cycleUniverse2} {S : Set V} {R : V → V → Prop} + {v : V} (hv : v ∈ S) : StarActive S R v := + ⟨v, hv, .refl⟩ + +lemma starActive_step {V : Type cycleUniverse3} {S : Set V} {R : V → V → Prop} + {v w : V} (hv : StarActive S R v) (h : R v w) : StarActive S R w := by + obtain ⟨a, ha, hr⟩ := hv + exact ⟨a, ha, hr.tail h⟩ + +lemma starActive_iff {V : Type cycleUniverse4} {S : Set V} {R : V → V → Prop} {v : V} : + StarActive S R v ↔ v ∈ S ∨ ∃ w, StarActive S R w ∧ R w v := by + constructor + · rintro ⟨a, ha, hr⟩ + rcases hr.cases_tail with rfl | ⟨w, hw, h⟩ + · exact Or.inl ha + · exact Or.inr ⟨w, ⟨a, ha, hw⟩, h⟩ + · rintro (h | ⟨w, hw, h⟩) + · exact starActive_source h + · exact starActive_step hw h + +lemma starActive_original_iff {V : Type cycleUniverse5} {S T : Set V} {R : V → V → Prop} + (hST : Disjoint S T) {v : V} (hv : v ∈ T) : + StarActive S R v ↔ ∃ w, StarActive S R w ∧ R w v := by + rw [starActive_iff] + have hs : v ∉ S := fun h => Set.disjoint_left.mp hST h hv + simp [hs] + +lemma starActive_subset {V : Type cycleUniverse6} {S T : Set V} {R : V → V → Prop} + (hS : S ⊆ T) (hR : ∀ a b, R a b → b ∈ T) : + {v | StarActive S R v} ⊆ T := by + rintro v ⟨a, ha, hr⟩ + rcases hr.cases_tail with rfl | ⟨w, _, h⟩ + · exact hS ha + · exact hR w v h + +lemma starActive_no_loop {V : Type cycleUniverse7} {S : Set V} {R : V → V → Prop} + (hinj : ∀ a b c, R a c → R b c → a = b) + (hsource : ∀ a b, a ∈ S → ¬ R b a) + {v : V} (hv : StarActive S R v) : ¬ R v v := by + obtain ⟨a, ha, hr⟩ := hv + induction hr with + | refl => exact hsource a a ha + | @tail b c hab hbc ih => + intro hcc + have he : b = c := hinj b c c hbc hcc + subst c + exact ih hbc + +lemma star_inj {V : Type cycleUniverse8} {x a b : V} : s(x,a) = s(x,b) ↔ a = b := by + rw [Sym2.eq_iff] + constructor + · rintro (⟨_, h⟩ | ⟨h, h'⟩) + · exact h + · exact h'.trans h + · intro h; exact Or.inl ⟨rfl, h⟩ + +structure PathPiece {V : Type cycleUniverse9} (G : SimpleGraph V) where + start : V + finish : V + walk : G.Walk start finish + isPath : walk.IsPath + positive : 0 < walk.length + +lemma PathPiece.ends_ne {V : Type cycleUniverse10} {G : SimpleGraph V} (P : PathPiece G) : + P.start ≠ P.finish := by + intro h + have hz := (P.isPath.nil_iff_eq.mpr h).length_eq_zero + have := P.positive + omega + +structure Piece {V : Type cycleUniverse11} (G : SimpleGraph V) where + start : V + finish : V + walk : G.Walk start finish + simple : (walk.IsPath ∧ 0 < walk.length) ∨ + ∃ h : finish = start, (walk.copy rfl h).IsCycle + +namespace Piece +variable {V : Type cycleUniverse12} {G : SimpleGraph V} + +def ofPath (p : PathPiece G) : Piece G := + ⟨p.start, p.finish, p.walk, Or.inl ⟨p.isPath, p.positive⟩⟩ + +def ofCycle {v : V} (p : G.Walk v v) (h : p.IsCycle) : Piece G := + ⟨v, v, p, Or.inr ⟨rfl, h⟩⟩ + +end Piece + +structure Arm {V : Type cycleUniverse13} (G : SimpleGraph V) (x : V) where + near : V + far : V + adj : G.Adj x near + walk : G.Walk near far + isPath : walk.IsPath + avoids : x ∉ walk.support + +namespace Arm +variable {V : Type cycleUniverse14} {G : SimpleGraph V} {x : V} + +def tip (A : Arm G x) : PathPiece G where + start := x + finish := A.far + walk := .cons A.adj A.walk + isPath := A.isPath.cons A.avoids + positive := by simp + +def flip (A : Arm G x) (h : G.Adj x A.far) : Arm G x where + near := A.far + far := A.near + adj := h + walk := A.walk.reverse + isPath := A.isPath.reverse + avoids := by simpa using A.avoids + +@[simp] lemma flip_edges (A : Arm G x) (h : G.Adj x A.far) : + (A.flip h).walk.edgeSet = A.walk.edgeSet := by simp [flip] + +@[simp] lemma mem_flip_support (A : Arm G x) (h : G.Adj x A.far) (v : V) : + v ∈ (A.flip h).walk.support ↔ v ∈ A.walk.support := by simp [flip] + +lemma two_arms_isPath (A B : Arm G x) + (hd : A.walk.support.Disjoint B.walk.support) : + ((Walk.cons A.adj A.walk).reverse.append (Walk.cons B.adj B.walk)).IsPath := by + apply Walk.IsPath.mk' + simp only [Walk.support_append, Walk.support_reverse, Walk.support_cons, + List.tail_cons, List.reverse_cons, List.append_assoc] + apply List.nodup_append'.mpr + refine ⟨List.nodup_reverse.mpr A.isPath.support_nodup, ?_, ?_⟩ + · exact List.nodup_cons.mpr ⟨B.avoids, B.isPath.support_nodup⟩ + · rw [List.disjoint_left] + intro v hv hq + have hav : v ∈ A.walk.support := List.mem_reverse.mp hv + rcases List.mem_cons.mp hq with rfl | hq + · exact A.avoids hav + · exact List.disjoint_left.mp hd hav hq + +def join (A B : Arm G x) (hd : A.walk.support.Disjoint B.walk.support) : PathPiece G where + start := A.far + finish := B.far + walk := (Walk.cons A.adj A.walk).reverse.append (Walk.cons B.adj B.walk) + isPath := two_arms_isPath A B hd + positive := by simp only [Walk.length_append, Walk.length_reverse, Walk.length_cons]; omega + +lemma join_edges (A B : Arm G x) (hd : A.walk.support.Disjoint B.walk.support) : + (A.join B hd).walk.edgeSet = + A.walk.edgeSet ∪ B.walk.edgeSet ∪ {s(x,A.near), s(x,B.near)} := by + simp only [join, Walk.edgeSet_append, Walk.edgeSet_reverse, Walk.edgeSet_cons] + ext e + simp only [Set.mem_union, Set.mem_insert_iff, Set.mem_singleton_iff] + tauto + +lemma near_ne (A B : Arm G x) (hd : A.walk.support.Disjoint B.walk.support) : + A.near ≠ B.near := by + intro h + exact List.disjoint_left.mp hd A.walk.start_mem_support (by simpa only [h] using B.walk.start_mem_support) + +lemma far_ne (A B : Arm G x) (hd : A.walk.support.Disjoint B.walk.support) : + A.far ≠ B.far := (A.join B hd).ends_ne + +lemma far_ne_center (A : Arm G x) : A.far ≠ x := by + intro h + apply A.avoids + simpa only [h] using A.walk.end_mem_support + +lemma star_not_mem (A : Arm G x) (v : V) : s(x,v) ∉ A.walk.edgeSet := by + intro he + exact A.avoids (Walk.mem_support_iff_exists_mem_edges.mpr + (Or.inr ⟨s(x,v), he, by simp⟩)) + +lemma flip_disjoint_left (A B : Arm G x) (h : G.Adj x A.far) + (hd : A.walk.support.Disjoint B.walk.support) : + (A.flip h).walk.support.Disjoint B.walk.support := by + rw [List.disjoint_left] at hd ⊢ + intro v hv hb + exact hd ((A.mem_flip_support h v).mp hv) hb + +lemma flip_disjoint_right (A B : Arm G x) (h : G.Adj x B.far) + (hd : A.walk.support.Disjoint B.walk.support) : + A.walk.support.Disjoint (B.flip h).walk.support := by + exact (flip_disjoint_left B A h hd.symm).symm + +def orient (A : Arm G x) (active : Prop) (h : active → G.Adj x A.far) : Arm G x := + if ha : active then A.flip (h ha) else A + +@[simp] lemma orient_edges (A : Arm G x) (active : Prop) (h : active → G.Adj x A.far) : + (A.orient active h).walk.edgeSet = A.walk.edgeSet := by + by_cases ha : active + · exact (congrArg (fun B : Arm G x => B.walk.edgeSet) + (show A.orient active h = A.flip (h ha) from dite_eq_left ha)).trans (A.flip_edges _) + · exact congrArg (fun B : Arm G x => B.walk.edgeSet) + (show A.orient active h = A from dite_eq_right ha) + +@[simp] lemma orient_near (A : Arm G x) (active : Prop) (h : active → G.Adj x A.far) : + (A.orient active h).near = if active then A.far else A.near := by + by_cases ha : active <;> simp [orient, flip, ha] + +@[simp] lemma mem_orient_support (A : Arm G x) (active : Prop) + (h : active → G.Adj x A.far) (v : V) : + v ∈ (A.orient active h).walk.support ↔ v ∈ A.walk.support := by + by_cases ha : active + · exact (congrArg (fun B : Arm G x => v ∈ B.walk.support) + (show A.orient active h = A.flip (h ha) from dite_eq_left ha)).to_iff.trans + (A.mem_flip_support _ v) + · exact (congrArg (fun B : Arm G x => v ∈ B.walk.support) + (show A.orient active h = A from dite_eq_right ha)).to_iff + +lemma orient_disjoint (A B : Arm G x) (p q : Prop) + (ha : p → G.Adj x A.far) (hb : q → G.Adj x B.far) + (hd : A.walk.support.Disjoint B.walk.support) : + (A.orient p ha).walk.support.Disjoint (B.orient q hb).walk.support := by + rw [List.disjoint_left] + intro v hv hw + exact List.disjoint_left.mp hd ((A.mem_orient_support p ha v).mp hv) + ((B.mem_orient_support q hb v).mp hw) + +end Arm + +inductive Frame {V : Type cycleUniverse15} (G : SimpleGraph V) (x : V) where + | away (p : PathPiece G) (avoid : x ∉ p.walk.support) + | tip (A : Arm G x) + | through (A B : Arm G x) (disjoint : A.walk.support.Disjoint B.walk.support) + +namespace Frame +variable {V : Type cycleUniverse16} {G : SimpleGraph V} {x : V} + +def path : Frame G x → PathPiece G + | .away p _ => p + | .tip A => A.tip + | .through A B hd => A.join B hd + +def Port : Frame G x → Type + | .away _ _ => Bool + | .tip _ => Unit + | .through _ _ _ => Bool + +def endpoint : (F : Frame G x) → F.Port → V + | .away p _, false => p.start + | .away p _, true => p.finish + | .tip A, _ => A.far + | .through A _ _, false => A.far + | .through _ B _, true => B.far + +def exit : (F : Frame G x) → F.Port → Option V + | .away _ _, _ => none + | .tip _, _ => none + | .through A _ _, false => some A.near + | .through _ B _, true => some B.near + +def inserted (F : Frame G x) (active : F.Port → Prop) : Set (Sym2 V) := + {e | ∃ p, active p ∧ e = s(x, F.endpoint p)} + +def removed (F : Frame G x) (active : F.Port → Prop) : Set (Sym2 V) := + {e | ∃ p, active p ∧ ∃ v, F.exit p = some v ∧ e = s(x,v)} + +lemma endpoint_ne_center (F : Frame G x) (p : F.Port) : F.endpoint p ≠ x := by + cases F with + | away P hx => + cases p + · change P.start ≠ x + intro h; apply hx; simpa only [← h] using P.walk.start_mem_support + · change P.finish ≠ x + intro h; apply hx; simpa only [← h] using P.walk.end_mem_support + | tip A => exact A.far_ne_center + | through A B hd => cases p <;> exact Arm.far_ne_center _ + +lemma endpoint_injective (F : Frame G x) : Function.Injective F.endpoint := by + cases F with + | away P hx => + intro a b hab + cases a <;> cases b <;> first | rfl | exact False.elim (P.ends_ne hab) | + exact False.elim (P.ends_ne hab.symm) + | tip A => + change Function.Injective (fun (_ : Unit) => A.far) + exact fun _ _ _ => Subsingleton.elim _ _ + | through A B hd => + intro a b hab + cases a <;> cases b <;> first | rfl | exact False.elim (A.far_ne B hd hab) | + exact False.elim (A.far_ne B hd hab.symm) + +lemma port_iff_endpoint (F : Frame G x) (v : V) : + (∃ p : F.Port, F.endpoint p = v) ↔ + (F.path.start = v ∨ F.path.finish = v) ∧ v ≠ x := by + constructor + · rintro ⟨p, rfl⟩ + refine ⟨?_, (F.endpoint_ne_center p)⟩ + cases F with + | away P hx => cases p <;> simp [endpoint, path] + | tip A => exact Or.inr rfl + | through A B hd => cases p <;> simp [endpoint, path, Arm.join] + · rintro ⟨he, hx⟩ + cases F with + | away P hp => + rcases he with he | he + · exact ⟨false, he⟩ + · exact ⟨true, he⟩ + | tip A => + rcases he with he | he + · exact (hx he.symm).elim + · exact ⟨(), he⟩ + | through A B hd => + rcases he with he | he + · exact ⟨false, he⟩ + · exact ⟨true, he⟩ + +lemma exit_edge (F : Frame G x) (p : F.Port) (v : V) (h : F.exit p = some v) : + s(x,v) ∈ F.path.walk.edgeSet := by + cases F with + | away P hx => cases h + | tip A => cases h + | through A B hd => + cases p + · cases h + rw [path, Arm.join_edges] + exact Or.inr (by simp) + · cases h + rw [path, Arm.join_edges] + exact Or.inr (by simp) + +lemma removed_subset (F : Frame G x) (active : F.Port → Prop) : + F.removed active ⊆ F.path.walk.edgeSet := by + rintro e ⟨p, hp, v, hv, rfl⟩ + exact F.exit_edge p v hv + +@[simp] lemma removed_away (P : PathPiece G) (hx : x ∉ P.walk.support) + (active : (Frame.away P hx).Port → Prop) : + (Frame.away P hx).removed active = ∅ := by + ext e; simp [removed, exit] + +@[simp] lemma removed_tip (A : Arm G x) (active : (Frame.tip A).Port → Prop) : + (Frame.tip A).removed active = ∅ := by + ext e; simp [removed, exit] + +lemma inserted_away (P : PathPiece G) (hx : x ∉ P.walk.support) + (active : (Frame.away P hx).Port → Prop) : + (Frame.away P hx).inserted active = + (if active false then {s(x,P.start)} else ∅) ∪ + (if active true then {s(x,P.finish)} else ∅) := by + ext e + by_cases h0 : active false <;> by_cases h1 : active true <;> + simp [inserted, endpoint, Port, Bool.exists_bool, h0, h1, or_comm] + +lemma inserted_tip (A : Arm G x) (active : (Frame.tip A).Port → Prop) : + (Frame.tip A).inserted active = if active () then {s(x,A.far)} else ∅ := by + ext e + by_cases h : active () <;> simp [inserted, endpoint, Port, h] + +lemma inserted_through (A B : Arm G x) (hd : A.walk.support.Disjoint B.walk.support) + (active : (Frame.through A B hd).Port → Prop) : + (Frame.through A B hd).inserted active = + (if active false then {s(x,A.far)} else ∅) ∪ + (if active true then {s(x,B.far)} else ∅) := by + ext e + by_cases h0 : active false <;> by_cases h1 : active true <;> + simp [inserted, endpoint, Port, Bool.exists_bool, h0, h1, or_comm] + +lemma removed_through (A B : Arm G x) (hd : A.walk.support.Disjoint B.walk.support) + (active : (Frame.through A B hd).Port → Prop) : + (Frame.through A B hd).removed active = + (if active false then {s(x,A.near)} else ∅) ∪ + (if active true then {s(x,B.near)} else ∅) := by + ext e + by_cases h0 : active false <;> by_cases h1 : active true <;> + simp [removed, exit, Port, Bool.exists_bool, h0, h1, or_comm] + +end Frame + +lemma replace_two_attachments {E : Type cycleUniverse17} (B : Set E) (e f a b : E) + (he : e ∉ B) (hf : f ∉ B) (hne : e ≠ f) (p q : Prop) [Decidable p] [Decidable q] : + ((B ∪ {e,f}) \ ((if p then {e} else ∅) ∪ (if q then {f} else ∅))) ∪ + ((if p then {a} else ∅) ∪ (if q then {b} else ∅)) = + B ∪ {if p then a else e, if q then b else f} := by + classical + ext z + by_cases hp : p <;> by_cases hq : q <;> + simp only [hp, hq, ↓reduceIte, Set.mem_union, Set.mem_sdiff, Set.mem_insert_iff, + Set.mem_singleton_iff, Set.mem_empty_iff_false] <;> aesop + +namespace Frame +variable {V : Type cycleUniverse18} {G : SimpleGraph V} {x : V} + +lemma modify_through (A B : Arm G x) (hd : A.walk.support.Disjoint B.walk.support) + (active : (Frame.through A B hd).Port → Prop) + (hadj : ∀ p, active p → G.Adj x ((Frame.through A B hd).endpoint p)) : + ∃ Q : Piece G, Q.walk.edgeSet = + ((Frame.through A B hd).path.walk.edgeSet \ (Frame.through A B hd).removed active) ∪ + (Frame.through A B hd).inserted active := by + have ha : active false → G.Adj x A.far := hadj false + have hb : active true → G.Adj x B.far := hadj true + let A' := A.orient (active false) ha + let B' := B.orient (active true) hb + have hd' : A'.walk.support.Disjoint B'.walk.support := + A.orient_disjoint B _ _ _ _ hd + refine ⟨Piece.ofPath (A'.join B' hd'), ?_⟩ + have he : s(x,A.near) ∉ A.walk.edgeSet ∪ B.walk.edgeSet := by + rintro (he | he) + · exact A.star_not_mem _ he + · exact B.star_not_mem _ he + have hf : s(x,B.near) ∉ A.walk.edgeSet ∪ B.walk.edgeSet := by + rintro (he | he) + · exact A.star_not_mem _ he + · exact B.star_not_mem _ he + have hne : s(x,A.near) ≠ s(x,B.near) := fun h => A.near_ne B hd (star_inj.mp h) + change (A'.join B' hd').walk.edgeSet = _ + rw [inserted_through, removed_through] + change (A'.join B' hd').walk.edgeSet = ((A.join B hd).walk.edgeSet \ _) ∪ _ + rw [Arm.join_edges, Arm.join_edges] + dsimp only [A', B'] + simp only [Arm.orient_edges, Arm.orient_near] + have hh := (replace_two_attachments _ _ _ s(x,A.far) s(x,B.far) he hf hne + (active false) (active true)).symm + by_cases h0 : active false <;> by_cases h1 : active true + · simpa [h0, h1] using hh + · simpa [h0, h1] using hh + · simpa [h0, h1] using hh + · simp [h0, h1] + +lemma modify_tip (A : Arm G x) (active : (Frame.tip A).Port → Prop) + (hadj : ∀ p, active p → G.Adj x ((Frame.tip A).endpoint p)) + (hnew : ∀ p, active p → s(x,(Frame.tip A).endpoint p) ∉ + (Frame.tip A).path.walk.edgeSet) : + ∃ Q : Piece G, Q.walk.edgeSet = + ((Frame.tip A).path.walk.edgeSet \ (Frame.tip A).removed active) ∪ + (Frame.tip A).inserted active := by + rw [removed_tip, inserted_tip, Set.sdiff_empty] + by_cases ha : active () + · have haG : G.Adj x A.far := hadj () ha + have he : s(A.far,x) ∉ A.tip.walk.edges := by + intro he + exact hnew () ha (Sym2.eq_swap ▸ he) + let c : G.Walk A.far A.far := Walk.cons haG.symm A.tip.walk + have hc : c.IsCycle := Path.cons_isCycle ⟨A.tip.walk,A.tip.isPath⟩ _ he + refine ⟨Piece.ofCycle c hc, ?_⟩ + change c.edgeSet = _ + dsimp only [c, Arm.tip, path] + simp only [Walk.edgeSet_cons, ha, ↓reduceIte] + rw [Sym2.eq_swap] + ext e + simp only [Set.mem_insert_iff, Set.mem_union, Set.mem_singleton_iff] + tauto + · refine ⟨Piece.ofPath A.tip, ?_⟩ + simp [Piece.ofPath, path, ha] + +lemma modify_away (P : PathPiece G) (hx : x ∉ P.walk.support) + (active : (Frame.away P hx).Port → Prop) + (hadj : ∀ p, active p → G.Adj x ((Frame.away P hx).endpoint p)) : + ∃ Q : Piece G, Q.walk.edgeSet = + ((Frame.away P hx).path.walk.edgeSet \ (Frame.away P hx).removed active) ∪ + (Frame.away P hx).inserted active := by + rw [removed_away, inserted_away, Set.sdiff_empty] + change ∃ Q : Piece G, Q.walk.edgeSet = P.walk.edgeSet ∪ _ + by_cases h0 : active false + · have h0G : G.Adj x P.start := hadj false h0 + let q : G.Walk x P.finish := Walk.cons h0G P.walk + have hq : q.IsPath := P.isPath.cons hx + by_cases h1 : active true + · have he : s(P.finish,x) ∉ q.edges := by + intro he + have hh := hq.length_eq_one_of_mem_edges (Sym2.eq_swap ▸ he) + have hp := P.positive + simp only [q, Walk.length_cons] at hh + omega + have h1G : G.Adj x P.finish := hadj true h1 + let c : G.Walk P.finish P.finish := Walk.cons h1G.symm q + have hc : c.IsCycle := Path.cons_isCycle ⟨q,hq⟩ _ he + refine ⟨Piece.ofCycle c hc, ?_⟩ + change c.edgeSet = _ + simp only [c, q, Walk.edgeSet_cons, h0, h1, ↓reduceIte] + rw [Sym2.eq_swap] + ext e + simp only [Set.mem_insert_iff, Set.mem_union, Set.mem_singleton_iff] + tauto + · let Q : PathPiece G := ⟨x, P.finish, q, hq, by simp [q]⟩ + refine ⟨Piece.ofPath Q, ?_⟩ + change q.edgeSet = _ + simp only [q, Walk.edgeSet_cons, h0, h1, ↓reduceIte, Set.union_empty] + ext e + simp only [Set.mem_insert_iff, Set.mem_union, Set.mem_singleton_iff] + tauto + · by_cases h1 : active true + · have h1G : G.Adj x P.finish := hadj true h1 + let q : G.Walk x P.start := Walk.cons h1G P.walk.reverse + have hq : q.IsPath := P.isPath.reverse.cons (by simpa using hx) + let Q : PathPiece G := ⟨x, P.start, q, hq, by simp [q]⟩ + refine ⟨Piece.ofPath Q, ?_⟩ + change q.edgeSet = _ + simp only [q, Walk.edgeSet_cons, Walk.edgeSet_reverse, h0, h1, ↓reduceIte, + Set.empty_union] + ext e + simp only [Set.mem_insert_iff, Set.mem_union, Set.mem_singleton_iff] + tauto + · refine ⟨Piece.ofPath P, ?_⟩ + simp [Piece.ofPath, h0, h1] + +theorem modify (F : Frame G x) (active : F.Port → Prop) + (hadj : ∀ p, active p → G.Adj x (F.endpoint p)) + (hnew : ∀ p, active p → F.exit p = none → s(x,F.endpoint p) ∉ F.path.walk.edgeSet) : + ∃ Q : Piece G, Q.walk.edgeSet = (F.path.walk.edgeSet \ F.removed active) ∪ + F.inserted active := by + cases F with + | away P hx => exact modify_away P hx active hadj + | through A B hd => exact modify_through A B hd active hadj + | tip A => exact modify_tip A active hadj (fun p hp => hnew p hp rfl) + +end Frame + +theorem rewire_partition {E : Type cycleUniverse19} {I : Type cycleUniverse20} (old remove add : I → Set E) (fresh : Set E) + (hsub : ∀ i, remove i ⊆ old i) + (hold : Pairwise fun i j => Disjoint (old i) (old j)) + (hadd : Pairwise fun i j => Disjoint (add i) (add j)) + (hfresh : Disjoint fresh (⋃ i, old i)) + (hbalance : (⋃ i, add i) = (⋃ i, remove i) ∪ fresh) : + Pairwise (fun i j => Disjoint ((old i \ remove i) ∪ add i) + ((old j \ remove j) ∪ add j)) ∧ + (⋃ i, ((old i \ remove i) ∪ add i)) = (⋃ i, old i) ∪ fresh := by + have hcross : ∀ i j, Disjoint (old i \ remove i) (add j) := by + intro i j + apply Set.disjoint_left.mpr + rintro e ⟨hei, hnot⟩ hej + have hh : e ∈ (⋃ l, remove l) ∪ fresh := by + rw [← hbalance] + exact Set.mem_iUnion.mpr ⟨j, hej⟩ + rcases hh with hh | hh + · obtain ⟨l, hel⟩ := Set.mem_iUnion.mp hh + by_cases hil : i = l + · subst l; exact hnot hel + · exact Set.disjoint_left.mp (hold hil) hei (hsub l hel) + · exact Set.disjoint_left.mp hfresh hh (Set.mem_iUnion.mpr ⟨i, hei⟩) + constructor + · intro i j hij + exact Disjoint.union_left + (Disjoint.union_right ((hold hij).mono Set.sdiff_subset Set.sdiff_subset) (hcross i j)) + (Disjoint.union_right (hcross j i).symm (hadd hij)) + · ext e + constructor + · intro he + obtain ⟨i, hi⟩ := Set.mem_iUnion.mp he + rcases hi with hi | hi + · exact Or.inl (Set.mem_iUnion.mpr ⟨i, hi.1⟩) + · have hh : e ∈ (⋃ l, remove l) ∪ fresh := by + rw [← hbalance] + exact Set.mem_iUnion.mpr ⟨i, hi⟩ + rcases hh with hh | hh + · obtain ⟨l, hl⟩ := Set.mem_iUnion.mp hh + exact Or.inl (Set.mem_iUnion.mpr ⟨l, hsub l hl⟩) + · exact Or.inr hh + · rintro (he | he) + · obtain ⟨i, hi⟩ := Set.mem_iUnion.mp he + by_cases hr : e ∈ remove i + · have hh : e ∈ ⋃ l, add l := by + rw [hbalance] + exact Or.inl (Set.mem_iUnion.mpr ⟨i, hr⟩) + obtain ⟨j, hj⟩ := Set.mem_iUnion.mp hh + exact Set.mem_iUnion.mpr ⟨j, Or.inr hj⟩ + · exact Set.mem_iUnion.mpr ⟨i, Or.inl ⟨hi, hr⟩⟩ + · have hh : e ∈ ⋃ l, add l := by rw [hbalance]; exact Or.inr he + obtain ⟨i, hi⟩ := Set.mem_iUnion.mp hh + exact Set.mem_iUnion.mpr ⟨i, Or.inr hi⟩ + +inductive Centered {V : Type cycleUniverse21} (G : SimpleGraph V) (x : V) where + | path (F : Frame G x) + | cycle {v : V} (c : G.Walk v v) (hc : c.IsCycle) + +namespace Centered +variable {V : Type cycleUniverse22} {G : SimpleGraph V} {x : V} + +def piece : Centered G x → Piece G + | .path F => .ofPath F.path + | .cycle c hc => .ofCycle c hc + +def Port : Centered G x → Type + | .path F => F.Port + | .cycle _ _ => Empty + +def endpoint : (K : Centered G x) → K.Port → V + | .path F, p => F.endpoint p + | .cycle _ _, p => nomatch p + +def exit : (K : Centered G x) → K.Port → Option V + | .path F, p => F.exit p + | .cycle _ _, p => nomatch p + +def inserted (K : Centered G x) (active : K.Port → Prop) : Set (Sym2 V) := + {e | ∃ p, active p ∧ e = s(x,K.endpoint p)} + +def removed (K : Centered G x) (active : K.Port → Prop) : Set (Sym2 V) := + {e | ∃ p, active p ∧ ∃ v, K.exit p = some v ∧ e = s(x,v)} + +lemma exit_edge (K : Centered G x) (p : K.Port) (v : V) (h : K.exit p = some v) : + s(x,v) ∈ K.piece.walk.edgeSet := by + cases K with + | path F => exact F.exit_edge p v h + | cycle c hc => exact p.elim + +lemma exit_adj (K : Centered G x) (p : K.Port) (v : V) (h : K.exit p = some v) : + G.Adj x v := by + exact G.mem_edgeSet.mp (K.piece.walk.edges_subset_edgeSet (K.exit_edge p v h)) + +lemma exit_none_all (K : Centered G x) (p : K.Port) (h : K.exit p = none) : + ∀ q, K.exit q = none := by + cases K with + | cycle c hc => exact p.elim + | path F => + cases F with + | away P hx => exact fun _ => rfl + | tip A => exact fun _ => rfl + | through A B hd => cases p <;> cases h + +lemma removed_subset (K : Centered G x) (active : K.Port → Prop) : + K.removed active ⊆ K.piece.walk.edgeSet := by + rintro e ⟨p, hp, v, hv, rfl⟩ + exact K.exit_edge p v hv + +lemma modify (K : Centered G x) (active : K.Port → Prop) + (hadj : ∀ p, active p → G.Adj x (K.endpoint p)) + (hnew : ∀ p, active p → K.exit p = none → + s(x,K.endpoint p) ∉ K.piece.walk.edgeSet) : + ∃ Q : Piece G, Q.walk.edgeSet = + (K.piece.walk.edgeSet \ K.removed active) ∪ K.inserted active := by + cases K with + | path F => exact F.modify active hadj hnew + | cycle c hc => + refine ⟨.ofCycle c hc, ?_⟩ + have hr : (Centered.cycle c hc).removed active = ∅ := by + ext e; simp only [removed, Set.mem_ofPred_eq, Set.mem_empty_iff_false] + exact ⟨fun ⟨p, _⟩ => p.elim, False.elim⟩ + have hi : (Centered.cycle c hc).inserted active = ∅ := by + ext e; simp only [inserted, Set.mem_ofPred_eq, Set.mem_empty_iff_false] + exact ⟨fun ⟨p, _⟩ => p.elim, False.elim⟩ + simp only [hr, hi, Set.sdiff_empty, Set.union_empty] + rfl + +end Centered + +theorem restore_selected {V : Type cycleUniverse23} {I : Type cycleUniverse24} (G : SimpleGraph V) (x : V) + (K : I → Centered G x) (S : Set V) + (hS : ∀ v ∈ S, G.Adj x v) + (hold : Pairwise fun i j => Disjoint (K i).piece.walk.edgeSet (K j).piece.walk.edgeSet) + (hfresh : Disjoint {e | ∃ v ∈ S, e = s(x,v)} (⋃ i, (K i).piece.walk.edgeSet)) + (selected : Set (Σ i, (K i).Port)) + (hinj : Set.InjOn (fun z : Σ i, (K i).Port => (K z.1).endpoint z.2) selected) + (hcov : ∀ v, G.Adj x v → ∃ z ∈ selected, (K z.1).endpoint z.2 = v) : + ∃ Q : I → Piece G, + (Pairwise fun i j => Disjoint (Q i).walk.edgeSet (Q j).walk.edgeSet) ∧ + (⋃ i, (Q i).walk.edgeSet) = + (⋃ i, (K i).piece.walk.edgeSet) ∪ {e | ∃ v ∈ S, e = s(x,v)} := by + let R : V → V → Prop := fun a b => ∃ z ∈ selected, + (K z.1).endpoint z.2 = a ∧ (K z.1).exit z.2 = some b + let active : (i : I) → (K i).Port → Prop := fun i p => + (⟨i,p⟩ : Σ j, (K j).Port) ∈ selected ∧ StarActive S R ((K i).endpoint p) + have hactive_adj : ∀ v, StarActive S R v → G.Adj x v := by + intro v hv + exact starActive_subset (T := {v | G.Adj x v}) hS + (by rintro a b ⟨z, _, _, hz⟩; exact (K z.1).exit_adj z.2 b hz) hv + have hbalance : (⋃ i, (K i).inserted (active i)) = + (⋃ i, (K i).removed (active i)) ∪ {e | ∃ v ∈ S, e = s(x,v)} := by + ext e + constructor + · intro he + obtain ⟨i, p, hp, rfl⟩ := Set.mem_iUnion.mp he + rcases (starActive_iff.mp hp.2) with hs | ⟨w, hw, z, hz, hzw, hzv⟩ + · exact Or.inr ⟨_, hs, rfl⟩ + · exact Or.inl (Set.mem_iUnion.mpr ⟨z.1, z.2, ⟨hz, hzw.symm ▸ hw⟩, + _, hzv, rfl⟩) + · rintro (he | ⟨v, hv, rfl⟩) + · obtain ⟨i, p, hp, v, hpv, rfl⟩ := Set.mem_iUnion.mp he + have hv : StarActive S R v := starActive_step hp.2 ⟨⟨i,p⟩, hp.1, rfl, hpv⟩ + obtain ⟨z, hz, hzv⟩ := hcov v (hactive_adj v hv) + exact Set.mem_iUnion.mpr ⟨z.1, z.2, ⟨hz, hzv.symm ▸ hv⟩, congrArg (s(x,·)) hzv.symm⟩ + · obtain ⟨z, hz, hzv⟩ := hcov v (hS v hv) + exact Set.mem_iUnion.mpr ⟨z.1, z.2, ⟨hz, hzv.symm ▸ starActive_source hv⟩, + congrArg (s(x,·)) hzv.symm⟩ + have hadd : Pairwise fun i j => + Disjoint ((K i).inserted (active i)) ((K j).inserted (active j)) := by + intro i j hij + apply Set.disjoint_left.mpr + rintro e ⟨p, hp, he⟩ ⟨q, hq, hf⟩ + have h : (⟨i,p⟩ : Σ l, (K l).Port) = ⟨j,q⟩ := + hinj hp.1 hq.1 (star_inj.mp (he.symm.trans hf)) + exact hij (congrArg Sigma.fst h) + have hnew : ∀ i p, active i p → (K i).exit p = none → + s(x,(K i).endpoint p) ∉ (K i).piece.walk.edgeSet := by + intro i p hp hn he + have ha : s(x,(K i).endpoint p) ∈ ⋃ j, (K j).inserted (active j) := + Set.mem_iUnion.mpr ⟨i, p, hp, rfl⟩ + rw [hbalance] at ha + rcases ha with ha | ha + · obtain ⟨j, q, hq, v, hqv, hev⟩ := Set.mem_iUnion.mp ha + have hej : s(x,(K i).endpoint p) ∈ (K j).piece.walk.edgeSet := + hev ▸ (K j).exit_edge q v hqv + have hij : i = j := by + by_contra h; exact Set.disjoint_left.mp (hold h) he hej + subst j + rw [(K i).exit_none_all p hn q] at hqv + cases hqv + · exact Set.disjoint_left.mp hfresh ha (Set.mem_iUnion.mpr ⟨i, he⟩) + choose Q hQ using fun i => (K i).modify (active i) + (fun p hp => hactive_adj _ hp.2) (hnew i) + have hh := rewire_partition (fun i => (K i).piece.walk.edgeSet) + (fun i => (K i).removed (active i)) (fun i => (K i).inserted (active i)) + {e | ∃ v ∈ S, e = s(x,v)} (fun i => (K i).removed_subset _) hold hadd hfresh hbalance + refine ⟨Q, ?_, ?_⟩ + · simpa only [hQ] using hh.1 + · simpa only [hQ] using hh.2 + +theorem restore_star {V : Type cycleUniverse25} {I : Type cycleUniverse26} (G : SimpleGraph V) (x : V) + (K : I → Centered G x) (S : Set V) + (hS : ∀ v ∈ S, G.Adj x v) + (hold : Pairwise fun i j => Disjoint (K i).piece.walk.edgeSet (K j).piece.walk.edgeSet) + (hfresh : Disjoint {e | ∃ v ∈ S, e = s(x,v)} (⋃ i, (K i).piece.walk.edgeSet)) + (hcov : ∀ v, G.Adj x v → ∃ i p, (K i).endpoint p = v) : + ∃ Q : I → Piece G, + (Pairwise fun i j => Disjoint (Q i).walk.edgeSet (Q j).walk.edgeSet) ∧ + (⋃ i, (Q i).walk.edgeSet) = + (⋃ i, (K i).piece.walk.edgeSet) ∪ {e | ∃ v ∈ S, e = s(x,v)} := by + let T := {v // G.Adj x v} + have hh : ∀ v : T, ∃ z : Σ i, (K i).Port, (K z.1).endpoint z.2 = v.val := by + intro v + obtain ⟨i,p,h⟩ := hcov v.val v.property + exact ⟨⟨i,p⟩,h⟩ + choose f hf using hh + apply restore_selected G x K S hS hold hfresh (Set.range f) + · rintro z ⟨v,rfl⟩ w ⟨u,rfl⟩ he + have hvu : v = u := Subtype.ext ((hf v).symm.trans (he.trans (hf u))) + exact congrArg f hvu + · intro v hv + exact ⟨f ⟨v,hv⟩, ⟨⟨v,hv⟩, rfl⟩, hf ⟨v,hv⟩⟩ + +namespace Arm +variable {V : Type cycleUniverse27} {G : SimpleGraph V} {x b : V} + +def fromWalk (w : G.Walk x b) (hp : w.IsPath) (hn : ¬w.Nil) : Arm G x := + match w with + | .nil => False.elim (hn .nil) + | @Walk.cons _ _ _ y _ h q => + ⟨y, b, h, q, (Walk.cons_isPath_iff h q).mp hp |>.1, + (Walk.cons_isPath_iff h q).mp hp |>.2⟩ + +@[simp] lemma fromWalk_far (w : G.Walk x b) (hp : w.IsPath) (hn : ¬w.Nil) : + (fromWalk w hp hn).far = b := by + cases w with + | nil => exact (hn .nil).elim + | cons h q => rfl + +@[simp] lemma fromWalk_support (w : G.Walk x b) (hp : w.IsPath) (hn : ¬w.Nil) : + (fromWalk w hp hn).walk.support = w.support.tail := by + cases w with + | nil => exact (hn .nil).elim + | cons h q => rfl + +@[simp] lemma fromWalk_tip_edges (w : G.Walk x b) (hp : w.IsPath) (hn : ¬w.Nil) : + (fromWalk w hp hn).tip.walk.edgeSet = w.edgeSet := by + cases w with + | nil => exact (hn .nil).elim + | cons h q => rfl +end Arm + +lemma PathPiece.exists_frame {V : Type cycleUniverse28} {G : SimpleGraph V} (P : PathPiece G) (x : V) : + ∃ F : Frame G x, F.path.walk.edgeSet = P.walk.edgeSet ∧ + ∀ v, (F.path.start = v ∨ F.path.finish = v) ↔ (P.start = v ∨ P.finish = v) := by + classical + by_cases hx : x ∈ P.walk.support + · obtain ⟨q,r,hq,hr,hqr⟩ := P.isPath.mem_support_iff_exists_append.mp hx + have hp : (q.append r).IsPath := hqr ▸ P.isPath + by_cases hqn : q.Nil + · have hx : P.start = x := hqn.eq + have hrn : ¬r.Nil := by + intro hn; exact P.ends_ne (hx.trans hn.eq) + let A := Arm.fromWalk r hr hrn + refine ⟨.tip A, ?_, ?_⟩ + · change A.tip.walk.edgeSet = P.walk.edgeSet + rw [Arm.fromWalk_tip_edges] + rw [hqr, Walk.edgeSet_append] + simp [Walk.edgeSet, Walk.edges_eq_nil.mpr hqn] + · intro v + change (x = v ∨ A.far = v) ↔ _ + simp only [A, Arm.fromWalk_far, hx] + · by_cases hrn : r.Nil + · have hx : x = P.finish := hrn.eq + have hqnr : ¬q.reverse.Nil := by simpa using hqn + let A := Arm.fromWalk q.reverse hq.reverse hqnr + refine ⟨.tip A, ?_, ?_⟩ + · change A.tip.walk.edgeSet = P.walk.edgeSet + rw [Arm.fromWalk_tip_edges, Walk.edgeSet_reverse] + rw [hqr, Walk.edgeSet_append] + simp [Walk.edgeSet, Walk.edges_eq_nil.mpr hrn] + · intro v + change (x = v ∨ A.far = v) ↔ _ + simp only [A, Arm.fromWalk_far, hx, or_comm] + · have hqnr : ¬q.reverse.Nil := by simpa using hqn + let A := Arm.fromWalk q.reverse hq.reverse hqnr + let B := Arm.fromWalk r hr hrn + have hd : A.walk.support.Disjoint B.walk.support := by + rw [Arm.fromWalk_support, Arm.fromWalk_support] + have hd := hp.disjoint_support_of_append hrn + rw [Walk.support_tail_of_not_nil r hrn] at hd + apply List.disjoint_left.mpr + intro v hv hw + exact List.disjoint_left.mp hd + (by simpa using (List.mem_of_mem_tail hv : v ∈ q.reverse.support)) hw + refine ⟨.through A B hd, ?_, ?_⟩ + · change ((Walk.cons A.adj A.walk).reverse.append (Walk.cons B.adj B.walk)).edgeSet = _ + rw [Walk.edgeSet_append, Walk.edgeSet_reverse] + change A.tip.walk.edgeSet ∪ B.tip.walk.edgeSet = _ + rw [Arm.fromWalk_tip_edges, Arm.fromWalk_tip_edges, Walk.edgeSet_reverse, + hqr, Walk.edgeSet_append] + · intro v + change (A.far = v ∨ B.far = v) ↔ _ + simp only [A, B, Arm.fromWalk_far] + · exact ⟨.away P hx, rfl, fun _ => Iff.rfl⟩ + +namespace Piece +variable {V : Type cycleUniverse29} {G H : SimpleGraph V} + +lemma isTrail (P : Piece G) : P.walk.IsTrail := by + rcases P.simple with hp | ⟨h,hc⟩ + · exact hp.1.isTrail + · exact (P.walk.isTrail_copy rfl h).mp hc.isTrail + +def mapLe (h : H ≤ G) (P : Piece H) : Piece G := by + rcases P with ⟨a,b,w,hs⟩ + refine ⟨a,b,w.mapLe h, ?_⟩ + rcases hs with hp | ⟨hb,hc⟩ + · exact Or.inl ⟨hp.1.mapLe h, by simpa using hp.2⟩ + · subst b + exact Or.inr ⟨rfl, by simpa using hc.mapLe h⟩ + +@[simp] lemma mapLe_edges (h : H ≤ G) (P : Piece H) : + (P.mapLe h).walk.edgeSet = P.walk.edgeSet := by + cases P + exact Walk.edgeSet_mapLe_eq_edgeSet _ _ + +@[simp] lemma mapLe_start (h : H ≤ G) (P : Piece H) : (P.mapLe h).start = P.start := by + cases P; rfl +@[simp] lemma mapLe_finish (h : H ≤ G) (P : Piece H) : (P.mapLe h).finish = P.finish := by + cases P; rfl + +lemma exists_centered (P : Piece G) (x : V) : + ∃ K : Centered G x, K.piece.walk.edgeSet = P.walk.edgeSet ∧ + ∀ v, P.start ≠ P.finish → (P.start = v ∨ P.finish = v) → v ≠ x → + ∃ p, K.endpoint p = v := by + rcases P with ⟨a,b,w,hs⟩ + rcases hs with hp | ⟨hb,hc⟩ + · let Q : PathPiece G := ⟨a,b,w,hp.1,hp.2⟩ + obtain ⟨F,he,hv⟩ := Q.exists_frame x + refine ⟨.path F, he, ?_⟩ + intro v _ he hx + exact (F.port_iff_endpoint v).mpr ⟨(hv v).mpr he, hx⟩ + · subst b + refine ⟨.cycle w (by simpa using hc), rfl, ?_⟩ + exact fun _ hn => (hn rfl).elim +end Piece + +theorem trail_partition_degree_sum {V : Type cycleUniverse30} {I : Type cycleUniverse31} [Fintype V] [Fintype I] + (G : SimpleGraph V) {a b : I → V} (p : ∀ i, G.Walk (a i) (b i)) + (ht : ∀ i, (p i).IsTrail) + (hd : Pairwise fun i j => Disjoint (p i).edgeSet (p j).edgeSet) + (hc : (⋃ i, (p i).edgeSet) = G.edgeSet) (v : V) : + G.degree v = ∑ i, (p i).edges.countP (fun e => decide (v ∈ e)) := by + classical + have he : G.edgeFinset = Finset.univ.biUnion (fun i => (p i).edges.toFinset) := by + ext e + simp only [SimpleGraph.mem_edgeFinset, ← hc, Set.mem_iUnion, + Finset.mem_biUnion, Finset.mem_univ, List.mem_toFinset, true_and, + SimpleGraph.Walk.mem_edgeSet] + rw [← G.card_incidenceFinset_eq_degree v, G.incidenceFinset_eq_filter, he, + Finset.filter_biUnion] + rw [Finset.card_biUnion] + · apply Finset.sum_congr rfl + intro i _ + have hfilter : ((p i).edges.filter (fun e => decide (v ∈ e))).toFinset = + ((p i).edges.toFinset.filter (fun e => v ∈ e)) := by + simp [List.toFinset_filter] + rw [← hfilter, List.toFinset_card_of_nodup ((ht i).edges_nodup.filter _), + List.countP_eq_length_filter] + · intro i _ j _ hij + apply Finset.disjoint_left.mpr + intro e hei hej + exact Set.disjoint_left.mp (hd hij) + (by simpa using (Finset.mem_filter.mp hei).1) + (by simpa using (Finset.mem_filter.mp hej).1) + +theorem trail_partition_even_degree_iff {V : Type cycleUniverse32} {I : Type cycleUniverse33} [Fintype V] [Fintype I] + (G : SimpleGraph V) {a b : I → V} (p : ∀ i, G.Walk (a i) (b i)) + (ht : ∀ i, (p i).IsTrail) + (hd : Pairwise fun i j => Disjoint (p i).edgeSet (p j).edgeSet) + (hc : (⋃ i, (p i).edgeSet) = G.edgeSet) (v : V) : + Even (G.degree v) ↔ Even (Finset.univ.filter + (fun i => a i ≠ b i ∧ (v = a i ∨ v = b i))).card := by + classical + rw [trail_partition_degree_sum G p ht hd hc v, Finset.even_sum_iff_even_card_odd] + have he : (Finset.univ.filter (fun i => Odd ((p i).edges.countP + (fun e => decide (v ∈ e))))) = (Finset.univ.filter + (fun i => a i ≠ b i ∧ (v = a i ∨ v = b i))) := by + ext i + simp only [Finset.mem_filter, Finset.mem_univ, true_and, + ← Nat.not_even_iff_odd, (ht i).even_countP_edges_iff] + tauto + rw [he] + +lemma endpoint_of_odd {V : Type cycleUniverse34} {I : Type cycleUniverse35} [Fintype V] [Fintype I] + (H : SimpleGraph V) (P : I → Piece H) + (hd : Pairwise fun i j => Disjoint (P i).walk.edgeSet (P j).walk.edgeSet) + (hc : (⋃ i, (P i).walk.edgeSet) = H.edgeSet) + (v : V) (hv : Odd (H.degree v)) : + ∃ i, (P i).start ≠ (P i).finish ∧ ((P i).start = v ∨ (P i).finish = v) := by + classical + have ho := (trail_partition_even_degree_iff H (fun i => (P i).walk) + (fun i => (P i).isTrail) hd hc v).not.mp (Nat.not_even_iff_odd.mpr hv) + have hp : 0 < (Finset.univ.filter + (fun i => (P i).start ≠ (P i).finish ∧ (v = (P i).start ∨ v = (P i).finish))).card := by + by_contra hn + have hz : (Finset.univ.filter + (fun i => (P i).start ≠ (P i).finish ∧ (v = (P i).start ∨ v = (P i).finish))).card = 0 := by omega + exact ho (hz ▸ ⟨0, rfl⟩) + obtain ⟨i,hi⟩ := Finset.card_pos.mp hp + exact ⟨i, (Finset.mem_filter.mp hi).2.1, by + simpa only [eq_comm] using (Finset.mem_filter.mp hi).2.2⟩ + +theorem restore_partition {V : Type cycleUniverse36} {I : Type cycleUniverse37} [Fintype V] [Fintype I] + (G H : SimpleGraph V) (hHG : H ≤ G) (x : V) (S : Set V) + (hS : ∀ v ∈ S, G.Adj x v) + (hedges : G.edgeSet = H.edgeSet ∪ {e | ∃ v ∈ S, e = s(x,v)}) + (hfresh : Disjoint {e | ∃ v ∈ S, e = s(x,v)} H.edgeSet) + (hodd : ∀ v, G.Adj x v → Odd (H.degree v)) + (P : I → Piece H) + (hd : Pairwise fun i j => Disjoint (P i).walk.edgeSet (P j).walk.edgeSet) + (hc : (⋃ i, (P i).walk.edgeSet) = H.edgeSet) : + ∃ Q : I → Piece G, + (Pairwise fun i j => Disjoint (Q i).walk.edgeSet (Q j).walk.edgeSet) ∧ + (⋃ i, (Q i).walk.edgeSet) = G.edgeSet := by + choose K hk hv using fun i => ((P i).mapLe hHG).exists_centered x + have he : ∀ i, (K i).piece.walk.edgeSet = (P i).walk.edgeSet := by + intro i; exact (hk i).trans ((P i).mapLe_edges hHG) + have hKC : (⋃ i, (K i).piece.walk.edgeSet) = H.edgeSet := by simpa only [he] using hc + obtain ⟨Q,hQ,hQC⟩ := restore_star G x K S hS + (by simpa only [he] using hd) (by rwa [hKC]) (by + intro v hxv + obtain ⟨i, hi, hiv⟩ := endpoint_of_odd H P hd hc v (hodd v hxv) + obtain ⟨p,hp⟩ := hv i v (by simpa using hi) (by simpa using hiv) hxv.ne.symm + exact ⟨i,p,hp⟩) + exact ⟨Q,hQ,by simpa only [hKC, ← hedges] using hQC⟩ + +def activeOrder {V : Type cycleUniverse38} [Fintype V] (G : SimpleGraph V) : ℕ := + G.support.toFinset.card + +lemma activeOrder_mono {V : Type cycleUniverse39} [Fintype V] {G H : SimpleGraph V} (h : H ≤ G) : + activeOrder H ≤ activeOrder G := by + apply Finset.card_le_card + intro v hv + exact Set.mem_toFinset.mpr (SimpleGraph.support_mono h (Set.mem_toFinset.mp hv)) + +def HasPartition {V : Type cycleUniverse40} [Fintype V] (G : SimpleGraph V) : Prop := + ∃ (k : ℕ) (P : Fin k → Piece G), + (Pairwise fun i j => Disjoint (P i).walk.edgeSet (P j).walk.edgeSet) ∧ + (⋃ i, (P i).walk.edgeSet) = G.edgeSet ∧ 2 * k ≤ activeOrder G + +def evenStarVertices {V : Type cycleUniverse41} [Fintype V] (G : SimpleGraph V) (x : V) : Set V := + {y | G.Adj x y ∧ Even (G.degree y)} + +def evenStarEdges {V : Type cycleUniverse42} [Fintype V] (G : SimpleGraph V) (x : V) : Set (Sym2 V) := + {e | ∃ y ∈ evenStarVertices G x, e = s(x,y)} + +def deleteEvenStar {V : Type cycleUniverse43} [Fintype V] (G : SimpleGraph V) (x : V) : SimpleGraph V := + G.deleteEdges (evenStarEdges G x) + +lemma evenStar_subset {V : Type cycleUniverse44} [Fintype V] (G : SimpleGraph V) (x : V) : + evenStarEdges G x ⊆ G.edgeSet := by + rintro e ⟨y,hy,rfl⟩; exact hy.1 + +lemma deleteEvenStar_neighbor_even {V : Type cycleUniverse45} [Fintype V] (G : SimpleGraph V) + (x v : V) (hxv : G.Adj x v) (he : Even (G.degree v)) : + (deleteEvenStar G x).neighborFinset v = (G.neighborFinset v).erase x := by + classical + ext w + rw [Finset.mem_erase, (deleteEvenStar G x).mem_neighborFinset, G.mem_neighborFinset] + rw [deleteEvenStar, SimpleGraph.deleteEdges_adj] + simp only [evenStarEdges, Set.mem_ofPred_eq, evenStarVertices, Sym2.eq_iff] + constructor + · rintro ⟨hvw, hn⟩ + refine ⟨?_,hvw⟩ + intro hw; subst w + exact hn ⟨v,⟨hxv,he⟩, Or.inr ⟨rfl,rfl⟩⟩ + · rintro ⟨hw,hvw⟩ + refine ⟨hvw, ?_⟩ + rintro ⟨y,_,h⟩ + rcases h with ⟨h,_⟩ | ⟨_,h⟩ + · exact hxv.ne h.symm + · exact hw h + +lemma deleteEvenStar_neighbor_odd {V : Type cycleUniverse46} [Fintype V] (G : SimpleGraph V) + (x v : V) (hxv : G.Adj x v) (he : ¬Even (G.degree v)) : + (deleteEvenStar G x).neighborFinset v = G.neighborFinset v := by + classical + ext w + rw [(deleteEvenStar G x).mem_neighborFinset, G.mem_neighborFinset] + rw [deleteEvenStar, SimpleGraph.deleteEdges_adj] + simp only [evenStarEdges, Set.mem_ofPred_eq, evenStarVertices, Sym2.eq_iff] + refine ⟨fun h => h.1, fun hw => ⟨hw, ?_⟩⟩ + rintro ⟨y,hy,h⟩ + rcases h with ⟨h,_⟩ | ⟨h,_⟩ + · exact hxv.ne h.symm + · subst y; exact he hy.2 + +lemma deleteEvenStar_neighbor_degree {V : Type cycleUniverse47} [Fintype V] (G : SimpleGraph V) + (x v : V) (hxv : G.Adj x v) : Odd ((deleteEvenStar G x).degree v) := by + classical + by_cases he : Even (G.degree v) + · have hcard := Finset.card_erase_add_one (s := G.neighborFinset v) + (a := x) (by simpa using hxv.symm) + rw [← deleteEvenStar_neighbor_even G x v hxv he, + G.card_neighborFinset_eq_degree, (deleteEvenStar G x).card_neighborFinset_eq_degree] at hcard + obtain ⟨k,hk⟩ := he + exact ⟨k-1, by omega⟩ + · rw [← (deleteEvenStar G x).card_neighborFinset_eq_degree v, + deleteEvenStar_neighbor_odd G x v hxv he, G.card_neighborFinset_eq_degree] + exact Nat.not_even_iff_odd.mp he + +lemma deleteEvenStar_edges {V : Type cycleUniverse48} [Fintype V] (G : SimpleGraph V) (x : V) : + G.edgeSet = (deleteEvenStar G x).edgeSet ∪ evenStarEdges G x := by + rw [deleteEvenStar, SimpleGraph.edgeSet_deleteEdges, + Set.sdiff_union_of_subset (evenStar_subset G x)] + +lemma deleteEvenStar_fresh {V : Type cycleUniverse49} [Fintype V] (G : SimpleGraph V) (x : V) : + Disjoint (evenStarEdges G x) (deleteEvenStar G x).edgeSet := by + rw [deleteEvenStar, SimpleGraph.edgeSet_deleteEdges] + exact Set.disjoint_sdiff_right + +lemma deleteEvenStar_lt {V : Type cycleUniverse50} [Fintype V] (G : SimpleGraph V) (x y : V) + (hxy : G.Adj x y) (he : Even (G.degree y)) : + (deleteEvenStar G x).edgeFinset.card < G.edgeFinset.card := by + classical + apply Finset.card_lt_card + apply Finset.ssubset_iff_subset_ne.mpr + refine ⟨?_, ?_⟩ + · intro e he + exact G.mem_edgeFinset.mpr (SimpleGraph.edgeSet_mono + (show deleteEvenStar G x ≤ G from G.deleteEdges_le _) + ((deleteEvenStar G x).mem_edgeFinset.mp he)) + · intro h + have hh : s(x,y) ∈ (deleteEvenStar G x).edgeFinset := h.symm ▸ G.mem_edgeFinset.mpr hxy + have hf : s(x,y) ∈ evenStarEdges G x := ⟨y,⟨hxy,he⟩,rfl⟩ + exact Set.disjoint_left.mp (deleteEvenStar_fresh G x) hf (SimpleGraph.mem_edgeFinset.mp hh) + +theorem even_vertex_step {V : Type cycleUniverse51} [Fintype V] (G : SimpleGraph V) + (hIH : ∀ H : SimpleGraph V, H.edgeFinset.card < G.edgeFinset.card → HasPartition H) + (hpos : ∃ y, 0 < G.degree y ∧ Even (G.degree y)) : HasPartition G := by + classical + obtain ⟨y,hy,he⟩ := hpos + obtain ⟨x,hxy⟩ := (G.degree_pos_iff_exists_adj y).mp hy + let H := deleteEvenStar G x + obtain ⟨k,P,hd,hc,hk⟩ := hIH H (deleteEvenStar_lt G x y hxy.symm he) + obtain ⟨Q,hQ,hQC⟩ := restore_partition G H (G.deleteEdges_le _) x + (evenStarVertices G x) (fun _ h => h.1) (deleteEvenStar_edges G x) + (deleteEvenStar_fresh G x) (deleteEvenStar_neighbor_degree G x) P hd hc + exact ⟨k,Q,hQ,hQC,hk.trans (activeOrder_mono (G.deleteEdges_le _))⟩ + +lemma single_edge_piece {V : Type cycleUniverse52} (G : SimpleGraph V) (e : Sym2 V) (he : e ∈ G.edgeSet) : + ∃ P : Piece G, P.walk.edgeSet = {e} := by + induction e using Sym2.ind with + | _ a b => + have hab : G.Adj a b := he + let P : PathPiece G := ⟨a,b,Walk.cons hab Walk.nil, + (Walk.IsPath.nil).cons (by simpa using hab.ne), by simp⟩ + exact ⟨.ofPath P, by simp [Piece.ofPath, P]⟩ + +lemma partition_single_edges {V : Type cycleUniverse53} [Fintype V] (G : SimpleGraph V) : + ∃ P : Fin G.edgeFinset.card → Piece G, + (Pairwise fun i j => Disjoint (P i).walk.edgeSet (P j).walk.edgeSet) ∧ + (⋃ i, (P i).walk.edgeSet) = G.edgeSet := by + classical + choose P hP using fun e : G.edgeSet => single_edge_piece G e.val e.property + let e : G.edgeSet ≃ Fin G.edgeFinset.card := (Fintype.equivFin G.edgeSet).trans + (finCongr (G.card_edgeSet)) + refine ⟨fun i => P (e.symm i), ?_, ?_⟩ + · intro i j hij + rw [hP, hP] + exact Set.disjoint_singleton.mpr (fun h => hij (e.symm.injective (Subtype.ext h))) + · ext z + simp only [Set.mem_iUnion,hP,Set.mem_singleton_iff] + constructor + · rintro ⟨i,rfl⟩; exact (e.symm i).property + · intro hz + exact ⟨e ⟨z,hz⟩, by simp⟩ + +lemma matching_partition {V : Type cycleUniverse54} [Fintype V] (G : SimpleGraph V) + (hdeg : ∀ v, G.degree v ≤ 1) : HasPartition G := by + classical + obtain ⟨P,hd,hc⟩ := partition_single_edges G + refine ⟨_,P,hd,hc,?_⟩ + rw [← G.sum_degrees_support_eq_twice_card_edges] + simpa [activeOrder] using Finset.sum_le_sum (s := G.support.toFinset) + (f := fun v => G.degree v) (g := fun _ => 1) (fun v _ => hdeg v) + +def subdivision {V : Type cycleUniverse55} (G : SimpleGraph V) (x y : V) : SimpleGraph (Option V) where + Adj a b := match a,b with + | some a, some b => G.Adj a b ∧ s(a,b) ≠ s(x,y) + | none, some b => b = x ∨ b = y + | some a, none => a = x ∨ a = y + | none, none => False + symm := ⟨by + intro a b h + cases a <;> cases b + · exact h + · exact h + · exact h + · exact ⟨h.1.symm, by simpa only [Sym2.eq_swap] using h.2⟩⟩ + loopless := ⟨by + intro a h + cases a + · exact h + · exact G.irrefl h.1⟩ + +@[simp] lemma subdivision_some {V : Type cycleUniverse56} (G : SimpleGraph V) (x y a b : V) : + (subdivision G x y).Adj (some a) (some b) ↔ G.Adj a b ∧ s(a,b) ≠ s(x,y) := Iff.rfl +@[simp] lemma subdivision_none_some {V : Type cycleUniverse57} (G : SimpleGraph V) (x y a : V) : + (subdivision G x y).Adj none (some a) ↔ a = x ∨ a = y := Iff.rfl +@[simp] lemma subdivision_some_none {V : Type cycleUniverse58} (G : SimpleGraph V) (x y a : V) : + (subdivision G x y).Adj (some a) none ↔ a = x ∨ a = y := Iff.rfl +@[simp] lemma subdivision_none_none {V : Type cycleUniverse59} (G : SimpleGraph V) (x y : V) : + ¬(subdivision G x y).Adj none none := id + +def halfSubdivision {V : Type cycleUniverse60} (G : SimpleGraph V) (x y : V) : SimpleGraph (Option V) := + (subdivision G x y).deleteEdges {s(none,some x)} + +@[simp] lemma half_some {V : Type cycleUniverse61} (G : SimpleGraph V) (x y a b : V) : + (halfSubdivision G x y).Adj (some a) (some b) ↔ G.Adj a b ∧ s(a,b) ≠ s(x,y) := by + rw [halfSubdivision, SimpleGraph.deleteEdges_adj] + simp [] + +@[simp] lemma half_none_some {V : Type cycleUniverse62} (G : SimpleGraph V) (x y a : V) (hxy : x ≠ y) : + (halfSubdivision G x y).Adj none (some a) ↔ a = y := by + rw [halfSubdivision, SimpleGraph.deleteEdges_adj] + simp only [subdivision_none_some, Set.mem_singleton_iff, star_inj, Option.some.injEq] + aesop + +@[simp] lemma half_some_none {V : Type cycleUniverse63} (G : SimpleGraph V) (x y a : V) (hxy : x ≠ y) : + (halfSubdivision G x y).Adj (some a) none ↔ a = y := by + rw [(halfSubdivision G x y).adj_comm, half_none_some G x y a hxy] + +lemma option_degree_some {V : Type cycleUniverse64} [Fintype V] (K : SimpleGraph (Option V)) (v : V) : + K.degree (some v) = (Finset.univ.filter (fun u : V => K.Adj (some v) (some u))).card + + if K.Adj (some v) none then 1 else 0 := by + classical + rw [← K.card_neighborFinset_eq_degree, K.neighborFinset_eq_filter, + Finset.card_eq_sum_ones, Finset.sum_filter, Fintype.sum_option] + rw [Finset.card_eq_sum_ones, Finset.sum_filter] + omega + +lemma option_degree_none {V : Type cycleUniverse65} [Fintype V] (K : SimpleGraph (Option V)) : + K.degree none = (Finset.univ.filter (fun u : V => K.Adj none (some u))).card := by + classical + rw [← K.card_neighborFinset_eq_degree, K.neighborFinset_eq_filter, + Finset.card_eq_sum_ones, Finset.sum_filter, Fintype.sum_option] + rw [Finset.card_eq_sum_ones, Finset.sum_filter] + simp + +lemma subdivision_old_neighbors {V : Type cycleUniverse66} [Fintype V] (G : SimpleGraph V) + (x y v : V) : + (Finset.univ.filter fun u : V => (subdivision G x y).Adj (some v) (some u)) = + if v = x then (G.neighborFinset v).erase y else + if v = y then (G.neighborFinset v).erase x else G.neighborFinset v := by + classical + ext u + by_cases hx : v = x + · subst v + simp [eq_comm, and_comm] + aesop + · by_cases hy : v = y + · subst v + simp [hx, eq_comm, and_comm] + tauto + · simp [hx, hy] + +lemma subdivision_degree {V : Type cycleUniverse67} [Fintype V] (G : SimpleGraph V) + (x y v : V) (hxy : G.Adj x y) : + (subdivision G x y).degree (some v) = G.degree v := by + classical + rw [option_degree_some, subdivision_old_neighbors] + by_cases hx : v = x + · subst v + simpa using Finset.card_erase_add_one (s := G.neighborFinset x) (a := y) + (by simpa using hxy) + · by_cases hy : v = y + · subst v + simpa [hx] using Finset.card_erase_add_one (s := G.neighborFinset y) (a := x) + (by simpa using hxy.symm) + · simp [hx,hy] + +lemma subdivision_degree_none {V : Type cycleUniverse68} [Fintype V] (G : SimpleGraph V) + (x y : V) (hxy : G.Adj x y) : (subdivision G x y).degree none = 2 := by + classical + rw [option_degree_none] + have he : (Finset.univ.filter fun u : V => (subdivision G x y).Adj none (some u)) = + {x,y} := by ext u; simp + rw [he] + simp [hxy.ne] + +lemma half_degree {V : Type cycleUniverse69} [Fintype V] (G : SimpleGraph V) + (x y v : V) (hxy : G.Adj x y) : + (halfSubdivision G x y).degree (some v) + (if v = x then 1 else 0) = G.degree v := by + classical + rw [option_degree_some] + have he : (Finset.univ.filter fun u : V => (halfSubdivision G x y).Adj (some v) (some u)) = + (Finset.univ.filter fun u : V => (subdivision G x y).Adj (some v) (some u)) := by + ext u; simp + rw [he, subdivision_old_neighbors] + by_cases hx : v = x + · subst v + simpa [hxy.ne] using Finset.card_erase_add_one (s := G.neighborFinset x) (a := y) + (by simpa using hxy) + · by_cases hy : v = y + · subst v + simpa [hx, hxy.ne] using Finset.card_erase_add_one (s := G.neighborFinset y) (a := x) + (by simpa using hxy.symm) + · simp [hx,hy,half_some_none G x y v hxy.ne] + +lemma half_degree_none {V : Type cycleUniverse70} [Fintype V] (G : SimpleGraph V) + (x y : V) (hxy : G.Adj x y) : (halfSubdivision G x y).degree none = 1 := by + classical + rw [option_degree_none] + have he : (Finset.univ.filter fun u : V => (halfSubdivision G x y).Adj none (some u)) = + {y} := by ext u; simp [half_none_some G x y u hxy.ne] + rw [he] + simp + +lemma subdivision_edge_count {V : Type cycleUniverse71} [Fintype V] (G : SimpleGraph V) + (x y : V) (hxy : G.Adj x y) : + (subdivision G x y).edgeFinset.card = G.edgeFinset.card + 1 := by + classical + have hd := (subdivision G x y).sum_degrees_eq_twice_card_edges + rw [Fintype.sum_option, subdivision_degree_none G x y hxy] at hd + simp_rw [subdivision_degree G x y _ hxy] at hd + rw [G.sum_degrees_eq_twice_card_edges] at hd + omega + +lemma half_edge_count {V : Type cycleUniverse72} [Fintype V] (G : SimpleGraph V) + (x y : V) (hxy : G.Adj x y) : + (halfSubdivision G x y).edgeFinset.card = G.edgeFinset.card := by + classical + have he : (halfSubdivision G x y).edgeFinset = + (subdivision G x y).edgeFinset.erase s(none,some x) := by + ext e + rw [(halfSubdivision G x y).mem_edgeFinset, Finset.mem_erase, + (subdivision G x y).mem_edgeFinset] + simp [halfSubdivision, SimpleGraph.edgeSet_deleteEdges, and_comm] + rw [he, Finset.card_erase_of_mem, subdivision_edge_count G x y hxy] + · omega + · exact (subdivision G x y).mem_edgeFinset.mpr (Or.inl rfl) + +lemma subdivision_activeOrder {V : Type cycleUniverse73} [Fintype V] (G : SimpleGraph V) + (x y : V) (hxy : G.Adj x y) : + activeOrder (subdivision G x y) = activeOrder G + 1 := by + classical + have he : (subdivision G x y).support.toFinset = + insert none (G.support.toFinset.image Option.some) := by + ext v + cases v with + | none => simp [← SimpleGraph.degree_pos_iff_mem_support, subdivision_degree_none G x y hxy] + | some v => + simp only [Set.mem_toFinset, Finset.mem_insert, Option.some_ne_none, Finset.mem_image, + Option.some.injEq, false_or, exists_eq_right] + rw [← (subdivision G x y).degree_pos_iff_mem_support, + subdivision_degree G x y v hxy, G.degree_pos_iff_mem_support] + dsimp [activeOrder] + rw [he, Finset.card_insert_of_notMem, Finset.card_image_of_injective] + · exact Option.some_injective V + · simp + +lemma suppress_path {V : Type cycleUniverse74} (G : SimpleGraph V) (x y : V) (hxy : G.Adj x y) + {a b : V} (p : (subdivision G x y).Walk (some a) (some b)) (hp : p.IsPath) : + ∃ q : G.Walk a b, q.IsPath ∧ q.support = p.support.filterMap id ∧ + ∀ e : Sym2 V, e ∈ q.edgeSet ↔ + e.map Option.some ∈ p.edgeSet ∨ (e = s(x,y) ∧ s(none,some x) ∈ p.edgeSet) := by + classical + generalize hn : p.length = n + induction n using Nat.strong_induction_on generalizing a b with + | h n ih => + cases p with + | nil => + refine ⟨.nil, by simp, by simp, ?_⟩ + intro e + simp + | @cons _ v _ h p => + have ht : p.IsPath := hp.of_cons + have ha : some a ∉ p.support := (Walk.cons_isPath_iff _ _ |>.mp hp).2 + cases v with + | some c => + obtain ⟨q,hq,hqs,hqe⟩ := ih p.length (by simp only [Walk.length_cons] at hn; omega) p ht rfl + have hac : G.Adj a c := (subdivision_some G x y a c).mp h |>.1 + refine ⟨.cons hac q, hq.cons ?_, ?_, ?_⟩ + · intro ha' + apply ha + rw [hqs] at ha' + simpa using ha' + · simp [hqs] + · intro e + have hinj : Function.Injective (Sym2.map (Option.some : V → Option V)) := + Sym2.map.injective (Option.some_injective V) + have he : e.map Option.some = s(some a,some c) ↔ e = s(a,c) := + by simpa only [Sym2.map_mk] using (hinj.eq_iff (a := e) (b := s(a,c))) + have hnedge : s(none,some x) ≠ s(some a,some c) := by simp [] + simp only [Walk.edgeSet_cons, Set.mem_insert_iff, he, hnedge, false_or, hqe] + tauto + | none => + cases p with + | @cons _ v _ h' p => + cases v with + | none => exact (h'.ne rfl).elim + | some c => + have hac : a ≠ c := by + intro he + apply ha + simp [he] + have hae : a = x ∨ a = y := (subdivision_some_none G x y a).mp h + have hce : c = x ∨ c = y := (subdivision_none_some G x y c).mp h' + have hexy : s(a,c) = s(x,y) := by + rcases hae with rfl | rfl <;> rcases hce with rfl | rfl + · exact (hac rfl).elim + · rfl + · exact Sym2.eq_swap + · exact (hac rfl).elim + have hacG : G.Adj a c := G.mem_edgeSet.mp (hexy.symm ▸ hxy) + obtain ⟨q,hq,hqs,hqe⟩ := ih p.length (by simp only [Walk.length_cons] at hn; omega) p ht.of_cons rfl + refine ⟨.cons hacG q, hq.cons ?_, ?_, ?_⟩ + · intro ha' + apply ha + have hh : some a ∈ p.support := by rw [hqs] at ha'; simpa using ha' + simp [hh] + · simp [hqs] + · intro e + have he1 : e.map Option.some ≠ s(some a,none) := by + induction e using Sym2.inductionOn with | _ u v => simp [] + have he2 : e.map Option.some ≠ s(none,some c) := by + induction e using Sym2.inductionOn with | _ u v => simp [] + have hn : s(none,some x) = s(some a,none) ∨ + s(none,some x) = s(none,some c) := by + rcases hae with rfl | hay + · exact Or.inl Sym2.eq_swap + · rcases hce with rfl | hcy + · exact Or.inr rfl + · exact (hac (hay.trans hcy.symm)).elim + simp only [Walk.edgeSet_cons, Set.mem_insert_iff, he1, he2, false_or, + hexy, hqe] + tauto + +lemma tight_partition_endpoints {V : Type cycleUniverse75} {I : Type cycleUniverse76} [Fintype V] [Fintype I] + (G : SimpleGraph V) (P : I → Piece G) (S : Finset V) + (hd : Pairwise fun i j => Disjoint (P i).walk.edgeSet (P j).walk.edgeSet) + (hc : (⋃ i, (P i).walk.edgeSet) = G.edgeSet) + (ho : ∀ v ∈ S, Odd (G.degree v)) (hk : 2 * Fintype.card I ≤ S.card) : + ∀ i, (P i).start ≠ (P i).finish ∧ (P i).start ∈ S ∧ (P i).finish ∈ S := by + classical + let endpoint : I × Bool → V := fun z => if z.2 then (P z.1).start else (P z.1).finish + have he : ∀ v : S, ∃ z : I × Bool, endpoint z = v := by + intro v + obtain ⟨i,_, h | h⟩ := endpoint_of_odd G P hd hc v (ho v v.property) + · exact ⟨(i,true),h⟩ + · exact ⟨(i,false),h⟩ + choose pick hpick using he + have hinj : Function.Injective pick := by + intro v w hvw + apply Subtype.ext + exact (hpick v).symm.trans ((congrArg endpoint hvw).trans (hpick w)) + have hsurj : Function.Surjective pick := by + by_contra hn + have hh := Fintype.card_lt_of_injective_not_surjective pick hinj hn + simp only [Fintype.card_coe, Fintype.card_prod, Fintype.card_bool] at hh + omega + have hendinj : Function.Injective endpoint := by + intro z t heq + obtain ⟨v,rfl⟩ := hsurj z + obtain ⟨w,rfl⟩ := hsurj t + have hvw : v = w := Subtype.ext (by simpa only [hpick] using heq) + exact congrArg pick hvw + have hmem : ∀ z, endpoint z ∈ S := by + intro z + obtain ⟨v,rfl⟩ := hsurj z + rw [hpick] + exact v.property + intro i + refine ⟨?_, hmem (i,true), hmem (i,false)⟩ + intro heq + have hh := hendinj (show endpoint (i,true) = endpoint (i,false) from heq) + have := congrArg Prod.snd hh + contradiction + +def subdivisionRepresentative {V : Type cycleUniverse77} (x y : V) (e : Sym2 V) : Sym2 (Option V) := + if e = s(x,y) then s(none,some x) else e.map Option.some + +lemma representative_mem {V : Type cycleUniverse78} (G : SimpleGraph V) (x y : V) (_hxy : G.Adj x y) + (e : Sym2 V) (he : e ∈ G.edgeSet) : + subdivisionRepresentative x y e ∈ (subdivision G x y).edgeSet := by + classical + by_cases h : e = s(x,y) + · simp [subdivisionRepresentative, h] + · rw [subdivisionRepresentative, ite_eq_right h] + induction e using Sym2.ind with + | _ a b => exact ⟨he,h⟩ + +lemma suppress_piece {V : Type cycleUniverse79} (G : SimpleGraph V) (x y : V) (hxy : G.Adj x y) + (P : Piece (subdivision G x y)) (hne : P.start ≠ P.finish) + (ha : P.start ≠ none) (hb : P.finish ≠ none) : + ∃ Q : Piece G, ∀ e, e ∈ Q.walk.edgeSet ↔ subdivisionRepresentative x y e ∈ P.walk.edgeSet := by + classical + rcases P with ⟨a,b,p,hp⟩ + cases a with + | none => exact (ha rfl).elim + | some a => + cases b with + | none => exact (hb rfl).elim + | some b => + have hab : a ≠ b := fun h => hne (congrArg some h) + have hpath : p.IsPath := by + rcases hp with h | ⟨h,_⟩ + · exact h.1 + · exact (hne h.symm).elim + obtain ⟨q,hq,_,hqe⟩ := suppress_path G x y hxy p hpath + have hpos : 0 < q.length := by + by_contra hn + exact hab (Walk.eq_of_length_eq_zero (by omega : q.length = 0)) + refine ⟨.ofPath ⟨a,b,q,hq,hpos⟩, ?_⟩ + intro e + change e ∈ q.edgeSet ↔ _ + rw [hqe] + by_cases he : e = s(x,y) + · subst e + have hn : (s(x,y) : Sym2 V).map some ∉ p.edgeSet := by + intro h + have hh := p.edges_subset_edgeSet h + exact hh.2 rfl + simp only [subdivisionRepresentative, ite_true, hn, false_or, true_and] + · simp [subdivisionRepresentative, he] + +lemma suppress_partition {V : Type cycleUniverse80} {I : Type cycleUniverse81} [Fintype I] + (G : SimpleGraph V) (x y : V) (hxy : G.Adj x y) + (P : I → Piece (subdivision G x y)) + (hd : Pairwise fun i j => Disjoint (P i).walk.edgeSet (P j).walk.edgeSet) + (hc : (⋃ i, (P i).walk.edgeSet) = (subdivision G x y).edgeSet) + (hp : ∀ i, (P i).start ≠ (P i).finish ∧ (P i).start ≠ none ∧ (P i).finish ≠ none) : + ∃ Q : I → Piece G, + (Pairwise fun i j => Disjoint (Q i).walk.edgeSet (Q j).walk.edgeSet) ∧ + (⋃ i, (Q i).walk.edgeSet) = G.edgeSet := by + classical + choose Q hQ using fun i => suppress_piece G x y hxy (P i) (hp i).1 (hp i).2.1 (hp i).2.2 + refine ⟨Q, ?_, ?_⟩ + · intro i j hij + exact Set.disjoint_left.mpr fun e hei hej => + Set.disjoint_left.mp (hd hij) ((hQ i e).mp hei) ((hQ j e).mp hej) + · apply Set.Subset.antisymm + · exact Set.iUnion_subset fun i => (Q i).walk.edges_subset_edgeSet + · intro e he + have hrep := representative_mem G x y hxy e he + rw [← hc] at hrep + obtain ⟨i,hi⟩ := Set.mem_iUnion.mp hrep + exact Set.mem_iUnion.mpr ⟨i,(hQ i e).mpr hi⟩ + +lemma even_activeOrder {V : Type cycleUniverse82} [Fintype V] (G : SimpleGraph V) + (ho : ∀ v, 0 < G.degree v → Odd (G.degree v)) : Even (activeOrder G) := by + classical + have he : G.support.toFinset = Finset.univ.filter (fun v => Odd (G.degree v)) := by + ext v + simp only [Set.mem_toFinset, Finset.mem_filter, Finset.mem_univ, true_and, + ← G.degree_pos_iff_mem_support] + refine ⟨ho v, ?_⟩ + rintro ⟨k,hk⟩ + omega + simpa only [activeOrder, he] using G.even_card_odd_degree_vertices + +lemma half_restore {V : Type cycleUniverse83} {I : Type cycleUniverse84} [Fintype V] [Fintype I] + (G : SimpleGraph V) (x y : V) (hxy : G.Adj x y) + (ho : ∀ v, 0 < G.degree v → Odd (G.degree v)) + (P : I → Piece (halfSubdivision G x y)) + (hd : Pairwise fun i j => Disjoint (P i).walk.edgeSet (P j).walk.edgeSet) + (hc : (⋃ i, (P i).walk.edgeSet) = (halfSubdivision G x y).edgeSet) : + ∃ Q : I → Piece (subdivision G x y), + (Pairwise fun i j => Disjoint (Q i).walk.edgeSet (Q j).walk.edgeSet) ∧ + (⋃ i, (Q i).walk.edgeSet) = (subdivision G x y).edgeSet := by + classical + have he : {e : Sym2 (Option V) | ∃ v ∈ ({none} : Set (Option V)), e = s(some x,v)} = + {s(none,some x)} := by + ext e + simp [Sym2.eq_swap] + apply restore_partition (subdivision G x y) (halfSubdivision G x y) + ((subdivision G x y).deleteEdges_le _) (some x) {none} + (by intro v hv; rcases hv with rfl; exact Or.inl rfl) ?_ ?_ ?_ P hd hc + · rw [he, halfSubdivision, SimpleGraph.edgeSet_deleteEdges] + symm + apply Set.sdiff_union_of_subset + intro e he + rcases he with rfl + exact Or.inl rfl + · rw [he, halfSubdivision, SimpleGraph.edgeSet_deleteEdges] + exact Set.disjoint_sdiff_right + · intro v hv + cases v with + | none => rw [half_degree_none G x y hxy]; exact ⟨0,rfl⟩ + | some v => + have hxv : G.Adj x v := hv.1 + have hh := half_degree G x y v hxy + rw [ite_eq_right hxv.ne.symm, add_zero] at hh + rw [hh] + exact ho v ((G.degree_pos_iff_exists_adj v).mpr ⟨x,hxv.symm⟩) + +theorem odd_vertex_step {V : Type cycleUniverse85} [Fintype V] (G : SimpleGraph V) + (hIH : ∀ H : SimpleGraph (Option V), H.edgeFinset.card < G.edgeFinset.card → HasPartition H) + (ho : ∀ v, 0 < G.degree v → Odd (G.degree v)) (x : V) (hx : 3 ≤ G.degree x) : + HasPartition G := by + classical + obtain ⟨y,hxy⟩ := (G.degree_pos_iff_exists_adj x).mp (by omega) + have hp : ∃ v, 0 < (halfSubdivision G x y).degree v ∧ + Even ((halfSubdivision G x y).degree v) := by + refine ⟨some x, ?_, ?_⟩ + · have hd := half_degree G x y x hxy + simp only [ite_true] at hd + omega + · have hd := half_degree G x y x hxy + simp only [ite_true] at hd + obtain ⟨k,hk⟩ := ho x (by omega) + exact ⟨k,by omega⟩ + obtain ⟨k,P,hd,hc,hk⟩ := even_vertex_step (halfSubdivision G x y) + (fun H hh => hIH H (by rwa [half_edge_count G x y hxy] at hh)) hp + have hbound : 2 * k ≤ activeOrder G + 1 := by + have hm := activeOrder_mono ((subdivision G x y).deleteEdges_le {s(none,some x)}) + rw [subdivision_activeOrder G x y hxy] at hm + exact hk.trans hm + have hk' : 2 * k ≤ activeOrder G := by + obtain ⟨a,ha⟩ := even_activeOrder G ho + omega + obtain ⟨Q,hQ,hQC⟩ := half_restore G x y hxy ho P hd hc + let S := G.support.toFinset.image Option.some + have hScard : S.card = activeOrder G := by + exact Finset.card_image_of_injective _ (Option.some_injective V) + have hSodd : ∀ v ∈ S, Odd ((subdivision G x y).degree v) := by + intro v hv + obtain ⟨w,hw,rfl⟩ := Finset.mem_image.mp hv + rw [subdivision_degree G x y w hxy] + exact ho w ((G.degree_pos_iff_mem_support w).mpr (Set.mem_toFinset.mp hw)) + have hends := tight_partition_endpoints (subdivision G x y) Q S hQ hQC hSodd + (by simpa only [Fintype.card_fin, hScard] using hk') + have hnon : ∀ i, (Q i).start ≠ (Q i).finish ∧ + (Q i).start ≠ none ∧ (Q i).finish ≠ none := by + intro i + refine ⟨(hends i).1, ?_, ?_⟩ + · intro h + have hh := (hends i).2.1 + simp only [h, S, Finset.mem_image, Option.some_ne_none, and_false, exists_false] at hh + · intro h + have hh := (hends i).2.2 + simp only [h, S, Finset.mem_image, Option.some_ne_none, and_false, exists_false] at hh + obtain ⟨R,hR,hRC⟩ := suppress_partition G x y hxy Q hQ hQC hnon + exact ⟨k,R,hR,hRC,hk'⟩ + +theorem path_cycle_partition {V : Type u} [Fintype V] (G : SimpleGraph V) : HasPartition G := by + classical + suffices ∀ (n : ℕ) (W : Type u) [Fintype W] (H : SimpleGraph W), + H.edgeFinset.card = n → HasPartition H by + exact this G.edgeFinset.card V G rfl + intro n + induction n using Nat.strong_induction_on with + | h n ih => + intro W _ H hcount + by_cases he : ∃ v, 0 < H.degree v ∧ Even (H.degree v) + · exact even_vertex_step H (fun K hk => ih K.edgeFinset.card (by omega) W K rfl) he + · have ho : ∀ v, 0 < H.degree v → Odd (H.degree v) := by + intro v hv + exact Nat.not_even_iff_odd.mp (fun hev => he ⟨v,hv,hev⟩) + by_cases hm : ∀ v, H.degree v ≤ 1 + · exact matching_partition H hm + · push Not at hm + obtain ⟨x,hx⟩ := hm + have hx3 : 3 ≤ H.degree x := by + obtain ⟨k,hk⟩ := ho x (by omega) + omega + exact odd_vertex_step H + (fun K hk => ih K.edgeFinset.card (by omega) (Option W) K rfl) ho x hx3 + +end +end ErdosGallai.Lovasz + +end +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/CycleDecomposition/Main.lean b/lean/OAI/Combinatorics/CycleDecomposition/Main.lean new file mode 100644 index 0000000000000000000000000000000000000000..a146a6edad4e9c89fcd4358cfb25141fe649c24f --- /dev/null +++ b/lean/OAI/Combinatorics/CycleDecomposition/Main.lean @@ -0,0 +1,226 @@ +import OAI.Combinatorics.CycleDecomposition.LayerCosts + +namespace OAI + +section +open Filter Asymptotics Real +open scoped Topology +noncomputable section +open MeasureTheory ProbabilityTheory Finset +section + +namespace ErdosGallai.Scale +noncomputable section +open Finset SimpleGraph Real +attribute [local instance] Classical.propDecidable +variable {V : Type} [Fintype V] [DecidableEq V] {P : AssignedPiece V} {Dstar : ℝ} + +def Layers.pieceSequence (H : Layers P Dstar) (j : ℕ) : ℝ := + if j < H.count then H.pieceMass j else 0 + +lemma Layers.pieceSequence_nonneg (H : Layers P Dstar) (j) : 0 ≤ H.pieceSequence j := by + unfold Layers.pieceSequence + split_ifs + · exact vertexMass_nonneg _ + · rfl + +lemma Layers.pieceSequence_zero (H : Layers P Dstar) (j) (hj : H.count ≤ j) : + H.pieceSequence j = 0 := by simp only [Layers.pieceSequence,ite_eq_right (by omega : ¬ j < H.count)] + +lemma Layers.past_mass_eq_sequence (H : Layers P Dstar) (k) (hk : k ≤ H.count) : + vertexMass (pastPieces H.system 0 k [P]) = ∑ j ∈ range k, H.pieceSequence j := by + rw [pastPieces_mass] + apply Finset.sum_congr rfl + intro j hj + simp only [Nat.zero_add,Layers.pieceSequence,ite_eq_left (by have := Finset.mem_range.mp hj; omega : j < H.count)] + +lemma Layers.prefix_choice (H : Layers P Dstar) : + vertexMass (pastPieces H.system 0 H.count [P]) = 0 ∨ + ∃ i < H.count, 0 < H.pieceMass i ∧ + ∀ k ≤ H.count, k ≤ i+201 → + vertexMass (pastPieces H.system 0 k [P]) ≤ ErdosGallai.mainP*H.pieceMass i := by + by_cases he : ∃ j, 0 < H.pieceSequence j + · right + obtain ⟨i,hi,hpref⟩ := ErdosGallai.prefix_selection H.pieceSequence H.pieceSequence_nonneg + 200 H.count H.pieceSequence_zero he + have hic : i < H.count := by + by_contra hi' + rw [H.pieceSequence_zero i (by omega)] at hi + linarith + simp only [Layers.pieceSequence,ite_eq_left hic] at hi + refine ⟨i,hic,hi,?_⟩ + intro k hk hki + rw [H.past_mass_eq_sequence k hk] + have hh : (∑ j ∈ range k, H.pieceSequence j) ≤ ∑ j ∈ range (i+200+1), H.pieceSequence j := + Finset.sum_le_sum_of_subset_of_nonneg (Finset.range_mono (by omega)) (fun j _ _ => H.pieceSequence_nonneg j) + apply hh.trans + norm_num only [Layers.pieceSequence,ite_eq_left hic,ErdosGallai.mainP,Nat.cast_ofNat] at hpref ⊢ + exact hpref + · left + rw [H.past_mass_eq_sequence H.count le_rfl] + apply Finset.sum_eq_zero + intro j _ + exact le_antisymm (le_of_not_gt (fun h => he ⟨j,h⟩)) (H.pieceSequence_nonneg j) + +end +end ErdosGallai.Scale + +end + +section + +namespace ErdosGallai +noncomputable section +open Finset SimpleGraph Real +attribute [local instance] Classical.propDecidable + +lemma main_edge_bound {V : Type} [Fintype V] (G : SimpleGraph V) : + 2*(Scale.edgeCount G:ℝ) ≤ (Fintype.card V:ℝ)^2 := by + classical + have h : (G.edgeFinset.card:ℝ) ≤ ((Fintype.card V).choose 2:ℝ) := + Nat.cast_le.mpr G.card_edgeFinset_le_card_choose_two + rw [Nat.cast_choose_two] at h + change 2*(G.edgeFinset.card:ℝ) ≤ _ + nlinarith [(Nat.cast_nonneg (Fintype.card V) : (0:ℝ) ≤ _)] + +lemma main_cost_eq_scale {V : Type} [Fintype V] (G : SimpleGraph V) : + decompositionCost G = Scale.decompositionCost G := by rfl +lemma main_cost_eq_batch {V : Type} [Fintype V] (G : SimpleGraph V) : + decompositionCost G = Batch.decompositionCost G := by rfl + +theorem main_cost_bound : ∃ C : ℝ, 0 < C ∧ ∀ (V : Type) [Fintype V] (G : SimpleGraph V), + (decompositionCost G:ℝ) ≤ C*Batch.inductionPhi (Fintype.card V)*Fintype.card V := by + classical + let wmin : ℝ := max 80 (((mainA₁+1)/Batch.inductionDelta)^2) + obtain ⟨Da,ha,hLayers⟩ := Scale.uniform_layers + obtain ⟨Db,hb,hPiece⟩ := Scale.uniform_committed_piece_cost + obtain ⟨Dc,hc,hGap⟩ := Scale.uniform_gap_prefix_cost + obtain ⟨Dr,hr,hReady⟩ := main_scale_ready_cutoff wmin + let Dstar : ℝ := max (max Da Db) (max Dc Dr) + have hDa : Da ≤ Dstar := (le_max_left Da Db).trans (le_max_left _ _) + have hDb : Db ≤ Dstar := (le_max_right Da Db).trans (le_max_left _ _) + have hDc : Dc ≤ Dstar := (le_max_left Dc Dr).trans (le_max_right _ _) + have hDr : Dr ≤ Dstar := (le_max_right Dc Dr).trans (le_max_right _ _) + have hDstar : 1 < Dstar := ha.trans_le hDa + let C : ℝ := max (4*(20+Dstar+18*mainP)) (7*mainA₂) + have hCbig : 4*(20+Dstar+18*mainP) ≤ C := le_max_left _ _ + have hCA : 7*mainA₂ ≤ C := le_max_right _ _ + have hCpos : 0 < C := lt_of_lt_of_le (by linarith [mainP_pos]) hCbig + have hC : 0 ≤ C := hCpos.le + refine ⟨C,hCpos,?_⟩ + have hmain : ∀ n : ℕ, ∀ (V : Type) [Fintype V], Fintype.card V = n → ∀ (G : SimpleGraph V), + (decompositionCost G:ℝ) ≤ C*Batch.inductionPhi (Fintype.card V)*Fintype.card V := by + intro n + induction n using Nat.strong_induction_on with + | h n ih => + intro V _ hn G + subst n + have hn0 : (0:ℝ) ≤ Fintype.card V := Nat.cast_nonneg _ + by_cases hsmall : (Fintype.card V:ℝ) < Dstar + · have he := main_edge_bound G + have hq : (decompositionCost G:ℝ) ≤ Scale.edgeCount G := + Nat.cast_le.mpr (Scale.decompositionCost_edgeCount G) + have hnD := mul_le_mul_of_nonneg_right hsmall.le hn0 + have hphi := mul_le_mul_of_nonneg_left (Batch.inductionPhi_bounds (Fintype.card V)).1 + (mul_nonneg hC hn0) + have hbig := mul_le_mul_of_nonneg_right hCbig hn0 + have hP := mul_nonneg mainP_pos.le hn0 + nlinarith only [he,hq,hnD,hphi,hbig,hP] + · have hnD : Dstar ≤ (Fintype.card V:ℝ) := le_of_not_gt hsmall + have hn1 : 1 < (Fintype.card V:ℝ) := hDstar.trans_le hnD + let P : Scale.AssignedPiece V := ⟨univ,G,fun _ _ _ => ⟨mem_univ _,mem_univ _⟩⟩ + have hpc : P.vertices.card = Fintype.card V := Finset.card_univ + have hp1 : 1 < (P.vertices.card:ℝ) := by simpa only [hpc] using hn1 + have hdeg : 2*(Scale.edgeCount P.graph:ℝ)/P.vertices.card ≤ P.vertices.card := by + apply (div_le_iff₀ (by linarith : (0:ℝ) < P.vertices.card)).mpr + simpa only [hpc,P,pow_two] using main_edge_bound G + obtain ⟨H⟩ := hLayers Dstar hDa V P (by simpa only [hpc] using hnD) hdeg + have hready' : ∀ j < H.count, MainScaleReady wmin (H.scale j) := by + intro j hj + exact hReady _ (hDr.trans (H.cutoff j hj)) + have hready : ∀ j < H.count, MainScaleReady 80 (H.scale j) := by + intro j hj + have hh := hready' j hj + exact ⟨hh.gt_one,(le_max_left _ _).trans hh.log_large,hh.cycle_power,hh.batch_power, + hh.bad_power,hh.skip_power,hh.active_eight⟩ + have ihw : ∀ (Q : Type) [Fintype Q] (F : SimpleGraph Q), Fintype.card Q < P.vertices.card → + (decompositionCost F:ℝ) ≤ C*Fintype.card Q := by + intro Q _ F hQ + have hh := ih (Fintype.card Q) (by simpa only [hpc] using hQ) Q rfl F + have hp := mul_le_mul_of_nonneg_left (Batch.inductionPhi_bounds (Fintype.card Q)).2 + (mul_nonneg hC (Nat.cast_nonneg (Fintype.card Q) : (0:ℝ) ≤ _)) + nlinarith only [hh,hp] + have hpieces := hPiece Dstar hDb V P H C hC ihw + have terminal (hm : Scale.vertexMass (Scale.pastPieces H.system 0 H.count [P]) ≤ + 2*mainP*P.vertices.card) : + (decompositionCost G:ℝ) ≤ C*Batch.inductionPhi (Fintype.card V)*Fintype.card V := by + have hh := H.terminal_cost hp1 hready (9+C*mainEta) (hpieces H.count le_rfl) + have ht := main_terminal_scalar _ P.vertices.card _ C Dstar (Nat.cast_nonneg _) hC hCbig hm hh + simpa only [hpc,P,← main_cost_eq_scale] using ht + rcases H.prefix_choice with hz | ⟨i,hic,hi,hprefix⟩ + · apply terminal + rw [hz] + exact mul_nonneg (mul_nonneg (by norm_num) mainP_pos.le) (Nat.cast_nonneg _) + · by_cases hgap : i+200 < H.count + · let t := C*Batch.inductionPhi ((H.scale i)^(3/10:ℝ)) + have ht : 0 ≤ t := mul_nonneg hC (by linarith [(Batch.inductionPhi_bounds ((H.scale i)^(3/10:ℝ))).1]) + have ihq : ∀ (Q : Type) [Fintype Q] (F : SimpleGraph Q), Fintype.card Q < P.vertices.card → + (Fintype.card Q:ℝ) ≤ (H.scale i)^(3/10:ℝ) → + (Batch.decompositionCost F:ℝ) ≤ t*Fintype.card Q := by + intro Q _ F hQ hQD + have hh := ih (Fintype.card Q) (by simpa only [hpc] using hQ) Q rfl F + by_cases h0 : Fintype.card Q = 0 + · simpa only [h0,Nat.cast_zero,mul_zero,← main_cost_eq_batch] using hh + · have h1 : (1:ℝ) ≤ Fintype.card Q := by exact_mod_cast (by omega : 1 ≤ Fintype.card Q) + have hp := Batch.inductionPhi_monotone h1 (h1.trans hQD) hQD + have hp' := mul_le_mul_of_nonneg_left hp + (mul_nonneg hC (Nat.cast_nonneg (Fintype.card Q) : (0:ℝ) ≤ _)) + change (decompositionCost F:ℝ) ≤ C*Batch.inductionPhi ((H.scale i)^(3/10:ℝ))*Fintype.card Q + nlinarith only [hh,hp'] + have hlocal := hGap Dstar hDc V P H hp1 hready i hgap C t hC ht ihw ihq + (hpieces (i+201) (by omega)) + have hscalar := main_gap_scalar _ P.vertices.card (H.pieceMass i) + (Scale.vertexMass (Scale.pastPieces H.system 0 (i+201) [P])) + ((Scale.pastCycles H.system 0 (i+201) [P]).length:ℝ) + (H.mass (i+201)) (H.mass (i+1)) C t (logb 2 (H.scale i)) + (Nat.cast_nonneg _) (Scale.vertexMass_nonneg _) hC ht + (by linarith [(hready i hic).log_large]) + (hprefix (i+201) (by omega) le_rfl) (H.gap_cycles hp1 hready i hgap) + (H.gap_mass hp1 hready i hgap) (H.mass_lower (i+1)) + (H.mass_two hp1 (fun j hj => (hready j hj).log_large) (i+1) (by omega)) hlocal + have habs := Batch.induction_cost_absorbed (H.scale i) P.vertices.card (H.pieceMass i) + C mainA₁ mainA₂ (hready i hic).gt_one (Scale.inductionScale_le _ hp1.le i) + (Scale.vertexMass_nonneg _) hC mainA₁_nonneg mainA₂_nonneg hCA + (by linarith [(hready i hic).log_large]) + ((le_max_right _ _).trans (hready' i hic).log_large) + have hfinal := hscalar.trans habs + simpa only [hpc,P,← main_cost_eq_scale] using hfinal + · apply terminal + calc + _ ≤ mainP*H.pieceMass i := hprefix H.count le_rfl (by omega) + _ ≤ mainP*(2*P.vertices.card) := mul_le_mul_of_nonneg_left + (H.pieceMass_two hp1 (fun j hj => (hready j hj).log_large) i hic) mainP_pos.le + _ = _ := by ring + intro V _ G + exact hmain (Fintype.card V) V rfl G + +theorem erdos_gallai : MainStatement := by + obtain ⟨C,hC,hcost⟩ := main_cost_bound + refine ⟨C,hC,?_⟩ + intro n G + refine ⟨decompositionCost G,decompositionCost_spec G,?_⟩ + have hh := hcost (Fin n) G + simp only [Fintype.card_fin] at hh + have hp := mul_le_mul_of_nonneg_left (Batch.inductionPhi_bounds n).2 + (mul_nonneg hC.le (Nat.cast_nonneg n : (0:ℝ) ≤ _)) + nlinarith only [hh,hp] + +end +end ErdosGallai + +end + +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/CycleDecomposition/Pairing.lean b/lean/OAI/Combinatorics/CycleDecomposition/Pairing.lean new file mode 100644 index 0000000000000000000000000000000000000000..955000e672d058274cddb037330bfe10e426fb5d --- /dev/null +++ b/lean/OAI/Combinatorics/CycleDecomposition/Pairing.lean @@ -0,0 +1,835 @@ +import OAI.Combinatorics.CycleDecomposition.BatchEndpoints + +namespace OAI + +universe cycleUniverse1 cycleUniverse2 cycleUniverse3 cycleUniverse4 cycleUniverse5 cycleUniverse6 cycleUniverse7 cycleUniverse8 cycleUniverse9 cycleUniverse10 cycleUniverse11 cycleUniverse12 cycleUniverse13 cycleUniverse14 cycleUniverse15 cycleUniverse16 cycleUniverse17 cycleUniverse18 cycleUniverse19 cycleUniverse20 cycleUniverse21 cycleUniverse22 cycleUniverse23 cycleUniverse24 cycleUniverse25 cycleUniverse26 cycleUniverse27 cycleUniverse28 cycleUniverse29 cycleUniverse30 cycleUniverse31 cycleUniverse32 cycleUniverse33 cycleUniverse34 cycleUniverse35 cycleUniverse36 cycleUniverse37 cycleUniverse38 cycleUniverse39 cycleUniverse40 cycleUniverse41 cycleUniverse42 cycleUniverse43 cycleUniverse44 cycleUniverse45 cycleUniverse46 cycleUniverse47 cycleUniverse48 cycleUniverse49 cycleUniverse50 cycleUniverse51 cycleUniverse52 cycleUniverse53 cycleUniverse54 cycleUniverse55 cycleUniverse56 cycleUniverse57 cycleUniverse58 cycleUniverse59 cycleUniverse60 cycleUniverse61 cycleUniverse62 cycleUniverse63 cycleUniverse64 + +section +open Filter Asymptotics Real +open scoped Topology +noncomputable section +open MeasureTheory ProbabilityTheory Finset +section +namespace ErdosGallai.Batch +open Finset +noncomputable section + +def Pairing (V : Type cycleUniverse1) := {f : V → V // Function.Involutive f ∧ ∀ x, f x ≠ x} + +namespace Pairing +variable {V : Type cycleUniverse2} {W : Type cycleUniverse3} +instance : CoeFun (Pairing V) (fun _ => V → V) := ⟨Subtype.val⟩ +instance [Fintype V] : Fintype (Pairing V) := by + classical + unfold Pairing + infer_instance +instance [Fintype V] : DecidableEq (Pairing V) := Classical.decEq _ + +@[simp] theorem apply_apply (p : Pairing V) (v : V) : p (p v) = v := p.property.1 v +@[simp] theorem apply_ne (p : Pairing V) (v : V) : p v ≠ v := p.property.2 v + +def transport (e : V ≃ W) : Pairing V ≃ Pairing W where + toFun p := ⟨fun x => e (p (e.symm x)), + (by intro x; simp), (by intro x h; have := congrArg e.symm h; simp at this)⟩ + invFun p := ⟨fun x => e.symm (p (e x)), + (by intro x; simp), (by intro x h; have := congrArg e h; simp at this)⟩ + left_inv p := by apply Subtype.ext; funext x; simp + right_inv p := by apply Subtype.ext; funext x; simp + +@[simp] theorem transport_apply (e : V ≃ W) (p : Pairing V) (x : W) : + transport e p x = e (p (e.symm x)) := rfl + +theorem nonempty_of_even [Fintype V] (h : Even (Fintype.card V)) : Nonempty (Pairing V) := by + classical + obtain ⟨k,hk⟩ := h + let q : Pairing (Fin k ⊕ Fin k) := ⟨fun x => x.swap, + (by intro x; cases x <;> rfl), (by intro x h; cases x <;> nomatch h)⟩ + let e : (Fin k ⊕ Fin k) ≃ V := Fintype.equivOfCardEq (by simpa using hk.symm) + exact ⟨transport e q⟩ + +variable [Fintype V] + +def oneCount (a b : V) : ℕ := by + classical + exact Fintype.card {p : Pairing V // p a = b} +def twoCount (a b c d : V) : ℕ := by + classical + exact Fintype.card {p : Pairing V // p a = b ∧ p c = d} + +@[simp] theorem oneCount_self (a : V) : oneCount a a = 0 := by + classical + unfold oneCount + apply Fintype.card_eq_zero_iff.mpr + exact ⟨fun p => p.val.apply_ne a p.property⟩ + +theorem oneCount_transport (e : V ≃ V) (a b : V) : + oneCount (e a) (e b) = oneCount a b := by + classical + symm + exact Fintype.card_congr ((transport e).subtypeEquiv (by intro p; simp)) + +theorem oneCount_eq (a b c : V) (hab : a ≠ b) (hac : a ≠ c) : + oneCount a b = oneCount a c := by + classical + have h := oneCount_transport (Equiv.swap b c) a b + simpa [Equiv.swap_apply_of_ne_of_ne hab hac] using h.symm + +theorem oneCount_balance (a b : V) (hab : a ≠ b) : + (Fintype.card V - 1) * oneCount a b = Fintype.card (Pairing V) := by + classical + have hsum : (∑ c : V, oneCount a c) = Fintype.card (Pairing V) := by + unfold oneCount + rw [← Fintype.card_sigma] + exact Fintype.card_congr (Equiv.sigmaFiberEquiv (fun p : Pairing V => p a)) + have heq : (∑ c : V, oneCount a c) = ∑ c ∈ (univ.erase a), oneCount a b := by + rw [← Finset.sum_erase_add _ _ (mem_univ a),oneCount_self,add_zero] + apply Finset.sum_congr rfl + intro c hc + exact oneCount_eq a c b (Finset.mem_erase.mp hc).1.symm hab + rw [heq,Finset.sum_const,Finset.card_erase_of_mem (mem_univ a)] at hsum + simpa using hsum + +theorem twoCount_transport (e : V ≃ V) (a b c d : V) : + twoCount (e a) (e b) (e c) (e d) = twoCount a b c d := by + classical + symm + exact Fintype.card_congr ((transport e).subtypeEquiv (by intro p; simp)) + +theorem twoCount_eq (a b c d e : V) + (had : a ≠ d) (hae : a ≠ e) (hbd : b ≠ d) (hbe : b ≠ e) + (hcd : c ≠ d) (hce : c ≠ e) : twoCount a b c d = twoCount a b c e := by + classical + have h := twoCount_transport (Equiv.swap d e) a b c d + simpa [Equiv.swap_apply_of_ne_of_ne had hae, + Equiv.swap_apply_of_ne_of_ne hbd hbe,Equiv.swap_apply_of_ne_of_ne hcd hce] using h.symm + +theorem twoCount_forbidden (a b c d : V) (hac : a ≠ c) (hbc : b ≠ c) + (hd : d = a ∨ d = b ∨ d = c) : twoCount a b c d = 0 := by + classical + unfold twoCount + apply Fintype.card_eq_zero_iff.mpr + refine ⟨fun p => ?_⟩ + rcases p.property with ⟨hab,hcd⟩ + rcases hd with rfl | rfl | rfl + · have h := congrArg p.val hcd + simp only [apply_apply,hab] at h + exact hbc h.symm + · have h := congrArg p.val hab + have h' := congrArg p.val hcd + simp only [apply_apply] at h h' + exact hac (h.trans h'.symm) + · exact p.val.apply_ne _ hcd + +theorem twoCount_balance (a b c d : V) + (hab : a ≠ b) (hac : a ≠ c) (had : a ≠ d) + (hbc : b ≠ c) (hbd : b ≠ d) (hcd : c ≠ d) : + (Fintype.card V - 3) * twoCount a b c d = oneCount a b := by + classical + let Q := {p : Pairing V // p a = b} + have hsum : (∑ e : V, twoCount a b c e) = oneCount a b := by + have hcard : ∀ e : V, Fintype.card {p : Q // p.val c = e} = twoCount a b c e := by + intro e + apply Fintype.card_congr + exact ⟨fun p => ⟨p.val.val,p.val.property,p.property⟩, + fun p => ⟨⟨p.val,p.property.1⟩,p.property.2⟩,fun _ => rfl,fun _ => rfl⟩ + calc + (∑ e : V, twoCount a b c e) = ∑ e : V, Fintype.card {p : Q // p.val c = e} := by simp_rw [hcard] + _ = Fintype.card Q := by + rw [← Fintype.card_sigma] + exact Fintype.card_congr (Equiv.sigmaFiberEquiv (fun p : Q => p.val c)) + _ = oneCount a b := rfl + let S : Finset V := {a,b,c} + have hScard : S.card = 3 := by simp [S,hab,hac,hbc] + have hsum' : (∑ e : V, twoCount a b c e) = ∑ e ∈ univ \ S, twoCount a b c d := by + rw [← Finset.sum_sdiff (s₁:=S) (s₂:=univ) (by simp)] + have hz : ∑ e ∈ S, twoCount a b c e = 0 := by + apply Finset.sum_eq_zero + intro e he + exact twoCount_forbidden a b c e hac hbc (by simpa [S] using he) + rw [hz,add_zero] + apply Finset.sum_congr rfl + intro e he + have he' : e ≠ a ∧ e ≠ b ∧ e ≠ c := by simpa [S] using (Finset.mem_sdiff.mp he).2 + exact twoCount_eq a b c e d he'.1.symm had he'.2.1.symm hbd he'.2.2.symm hcd + rw [hsum',Finset.sum_const,Finset.card_sdiff,Finset.inter_univ,hScard] at hsum + simpa using hsum + +theorem one_fraction (hV : Even (Fintype.card V)) (a b : V) (hab : a ≠ b) : + (oneCount a b : ℝ) / Fintype.card (Pairing V) = 1 / (Fintype.card V - 1 : ℝ) := by + classical + have hn : 2 ≤ Fintype.card V := Fintype.one_lt_card_iff_nontrivial.mpr ⟨a,b,hab⟩ + have hbal := oneCount_balance a b hab + have hbal' : ((Fintype.card V:ℝ)-1)*(oneCount a b:ℝ) = Fintype.card (Pairing V) := by + have h := congrArg (fun n : ℕ => (n:ℝ)) hbal + simpa only [Nat.cast_mul,Nat.cast_sub (show 1 ≤ Fintype.card V by omega),Nat.cast_one] using h + have : Nonempty (Pairing V) := nonempty_of_even hV + have hp : (0:ℝ) < Fintype.card (Pairing V) := by exact_mod_cast Fintype.card_pos + have hn' : (0:ℝ) < Fintype.card V-1 := by + have hnR : (2:ℝ) ≤ Fintype.card V := by exact_mod_cast hn + linarith + apply (div_eq_div_iff hp.ne' hn'.ne').mpr + nlinarith + +theorem two_fraction (hV : Even (Fintype.card V)) (a b c d : V) + (hab : a ≠ b) (hac : a ≠ c) (had : a ≠ d) + (hbc : b ≠ c) (hbd : b ≠ d) (hcd : c ≠ d) : + (twoCount a b c d : ℝ) / Fintype.card (Pairing V) = + 1 / ((Fintype.card V - 1 : ℝ)*(Fintype.card V - 3 : ℝ)) := by + classical + have hn : 4 ≤ Fintype.card V := by + have : ({a,b,c,d}:Finset V).card = 4 := by simp [hab,hac,had,hbc,hbd,hcd] + exact this.symm ▸ Finset.card_le_univ _ + have hone := oneCount_balance a b hab + have htwo := twoCount_balance a b c d hab hac had hbc hbd hcd + have hb : ((Fintype.card V:ℝ)-1)*((Fintype.card V:ℝ)-3)*(twoCount a b c d:ℝ) = + Fintype.card (Pairing V) := by + have h1 : ((Fintype.card V:ℝ)-1)*(oneCount a b:ℝ) = Fintype.card (Pairing V) := by + have h := congrArg (fun n : ℕ => (n:ℝ)) hone + simpa only [Nat.cast_mul,Nat.cast_sub (show 1 ≤ Fintype.card V by omega),Nat.cast_one] using h + have h2 : ((Fintype.card V:ℝ)-3)*(twoCount a b c d:ℝ) = oneCount a b := by + have h := congrArg (fun n : ℕ => (n:ℝ)) htwo + simpa only [Nat.cast_mul,Nat.cast_sub (show 3 ≤ Fintype.card V by omega),Nat.cast_ofNat] using h + nlinarith + have : Nonempty (Pairing V) := nonempty_of_even hV + have hp : (0:ℝ) < Fintype.card (Pairing V) := by exact_mod_cast Fintype.card_pos + have hn' : (0:ℝ) < Fintype.card V-3 := by + have hnR : (4:ℝ) ≤ Fintype.card V := by exact_mod_cast hn + linarith + have hn'' : (0:ℝ) < Fintype.card V-1 := by linarith + apply (div_eq_div_iff hp.ne' (mul_pos hn'' hn').ne').mpr + nlinarith + +end Pairing +end +end ErdosGallai.Batch + +namespace ErdosGallai.Batch +open Finset +noncomputable section + +def finiteAverage {α : Type cycleUniverse4} [Fintype α] (f : α → ℝ) : ℝ := + (∑ x, f x) / Fintype.card α + +lemma finiteAverage_equiv {α : Type cycleUniverse5} {β : Type cycleUniverse6} [Fintype α] [Fintype β] + (e : α ≃ β) (f : β → ℝ) : finiteAverage (fun x => f (e x)) = finiteAverage f := by + unfold finiteAverage + rw [e.sum_comp,Fintype.card_congr e] + +lemma finiteAverage_add {α : Type cycleUniverse7} [Fintype α] (f g : α → ℝ) : + finiteAverage (fun x => f x+g x) = finiteAverage f+finiteAverage g := by + simp [finiteAverage,Finset.sum_add_distrib,add_div] + +lemma finiteAverage_sum {α : Type cycleUniverse8} {ι : Type cycleUniverse9} [Fintype α] (s : Finset ι) (f : ι → α → ℝ) : + finiteAverage (fun x => ∑ i ∈ s, f i x) = ∑ i ∈ s, finiteAverage (f i) := by + unfold finiteAverage + rw [Finset.sum_comm,Finset.sum_div] + +lemma finiteAverage_mul_const {α : Type cycleUniverse10} [Fintype α] (f : α → ℝ) (r : ℝ) : + finiteAverage (fun x => f x*r) = finiteAverage f*r := by + simp only [finiteAverage,← Finset.sum_mul] + ring + +lemma finiteAverage_const {α : Type cycleUniverse11} [Fintype α] [Nonempty α] (r : ℝ) : + finiteAverage (fun _ : α => r) = r := by + have h : (Fintype.card α:ℝ) ≠ 0 := by exact_mod_cast Fintype.card_ne_zero + simp [finiteAverage,h] + +lemma finiteAverage_mono {α : Type cycleUniverse12} [Fintype α] {f g : α → ℝ} + (h : ∀ a, f a ≤ g a) : finiteAverage f ≤ finiteAverage g := by + apply div_le_div_of_nonneg_right _ (Nat.cast_nonneg _) + exact Finset.sum_le_sum (fun a _ => h a) + +lemma finiteAverage_prod {α : Type cycleUniverse13} {β : Type cycleUniverse14} [Fintype α] [Fintype β] + (f : α → ℝ) (g : β → ℝ) : + finiteAverage (fun x : α × β => f x.1*g x.2) = finiteAverage f*finiteAverage g := by + unfold finiteAverage + rw [Fintype.sum_prod_type,Fintype.card_prod,Nat.cast_mul] + simp_rw [← Finset.mul_sum] + rw [← Finset.sum_mul] + ring + +lemma exists_le_finiteAverage {α : Type cycleUniverse15} [Fintype α] [Nonempty α] (f : α → ℝ) : + ∃ a, f a ≤ finiteAverage f := by + have hp : (0:ℝ) < Fintype.card α := by exact_mod_cast Fintype.card_pos + have h : ∑ a, f a ≤ ∑ _a : α, finiteAverage f := by + simp only [Finset.sum_const,Finset.card_univ,nsmul_eq_mul,finiteAverage] + field_simp + rfl + obtain ⟨a,ha,h⟩ := Finset.exists_le_of_sum_le (Finset.univ_nonempty) h + exact ⟨a,h⟩ + +lemma finiteAverage_indicator {α : Type cycleUniverse16} [Fintype α] (P : α → Prop) [DecidablePred P] : + finiteAverage (fun a => if P a then 1 else 0) = (Fintype.card {a // P a} : ℝ)/Fintype.card α := by + unfold finiteAverage + congr 1 + simp [Fintype.card_subtype] + +lemma finiteAverage_pi_eval {ι : Type cycleUniverse17} [Fintype ι] [DecidableEq ι] {Ω : ι → Type cycleUniverse60} + [∀ i, Fintype (Ω i)] [∀ i, Nonempty (Ω i)] (i : ι) (f : Ω i → ℝ) : + finiteAverage (fun ω : ∀ j, Ω j => f (ω i)) = finiteAverage f := by + classical + let e := Equiv.piSplitAt i Ω + have he := finiteAverage_equiv e.symm (fun ω : ∀ j, Ω j => f (ω i)) + have he' : finiteAverage (fun x : Ω i × (∀ j : {j // j ≠ i}, Ω j.val) => f x.1) = + finiteAverage f := by + have h := finiteAverage_prod f (fun _ : (∀ j : {j // j ≠ i}, Ω j.val) => (1:ℝ)) + simpa only [mul_one,finiteAverage_const] using h + rw [← he] + simpa [e,Equiv.piSplitAt_symm_apply] using he' + +lemma finiteAverage_pi_pair {ι : Type cycleUniverse18} [Fintype ι] [DecidableEq ι] {Ω : ι → Type cycleUniverse61} + [∀ i, Fintype (Ω i)] [∀ i, Nonempty (Ω i)] (i j : ι) (hij : i ≠ j) + (f : Ω i → ℝ) (g : Ω j → ℝ) : + finiteAverage (fun ω : ∀ k, Ω k => f (ω i)*g (ω j)) = finiteAverage f*finiteAverage g := by + classical + let e := Equiv.piSplitAt i Ω + rw [← finiteAverage_equiv e.symm (fun ω : ∀ k, Ω k => f (ω i)*g (ω j))] + have hfun : (fun x => f (e.symm x i)*g (e.symm x j)) = + (fun x : Ω i × (∀ k : {k // k ≠ i}, Ω k.val) => f x.1*g (x.2 ⟨j,hij.symm⟩)) := by + funext x + simp [e,Equiv.piSplitAt_symm_apply,hij.symm] + rw [hfun,finiteAverage_prod f (fun x : (∀ k : {k // k ≠ i}, Ω k.val) => g (x ⟨j,hij.symm⟩)), + finiteAverage_pi_eval] + +end +end ErdosGallai.Batch +namespace ErdosGallai.Batch +open Finset +noncomputable section + +abbrev PairingSpace (V : Type cycleUniverse19) [Fintype V] := Pairing (V ⊕ Fin (Fintype.card V % 2)) + +lemma pairingSpace_even (V : Type cycleUniverse20) [Fintype V] : + Even (Fintype.card (V ⊕ Fin (Fintype.card V % 2))) := by + simp only [Fintype.card_sum,Fintype.card_fin,Nat.even_iff] + omega + +instance pairingSpace_nonempty (V : Type cycleUniverse21) [Fintype V] : Nonempty (PairingSpace V) := + Pairing.nonempty_of_even (pairingSpace_even V) + +def paired {V : Type cycleUniverse22} [Fintype V] (p : PairingSpace V) (u v : V) : Prop := + p (Sum.inl u) = Sum.inl v + +instance paired_decidable {V : Type cycleUniverse23} [Fintype V] (p : PairingSpace V) (u v : V) : + Decidable (paired p u v) := Classical.propDecidable _ + +lemma paired_ne {V : Type cycleUniverse24} [Fintype V] (p : PairingSpace V) {u v : V} + (h : paired p u v) : u ≠ v := by + rintro rfl + exact p.apply_ne _ h + +lemma paired_symm {V : Type cycleUniverse25} [Fintype V] (p : PairingSpace V) {u v : V} + (h : paired p u v) : paired p v u := by + have hh := congrArg p h + simpa only [paired,Pairing.apply_apply] using hh.symm + +lemma paired_unique {V : Type cycleUniverse26} [Fintype V] (p : PairingSpace V) {u v w : V} + (hv : paired p u v) (hw : paired p u w) : v = w := + Sum.inl_injective (hv.symm.trans hw) + +def pairingInvolution {V : Type cycleUniverse27} [Fintype V] (p : PairingSpace V) (u : V) : V := + match p (Sum.inl u) with + | Sum.inl v => v + | Sum.inr _ => u + +lemma pairingInvolution_eq_or_paired {V : Type cycleUniverse28} [Fintype V] (p : PairingSpace V) (u v : V) : + pairingInvolution p u = v → u = v ∨ paired p u v := by + unfold pairingInvolution paired + cases h : p (Sum.inl u) with + | inl w => simp only [Sum.inl.injEq]; exact Or.inr + | inr w => intro hh; exact Or.inl hh + +lemma pairingInvolution_involutive {V : Type cycleUniverse29} [Fintype V] (p : PairingSpace V) : + Function.Involutive (pairingInvolution p) := by + intro u + unfold pairingInvolution + cases h : p (Sum.inl u) with + | inl v => + have hh := congrArg p h + simp only [Pairing.apply_apply] at hh + rw [← hh] + | inr w => rw [h] + +lemma paired_first_moment {V : Type cycleUniverse30} [Fintype V] (u v : V) (huv : u ≠ v) : + finiteAverage (fun p : PairingSpace V => if paired p u v then 1 else 0) = + 1 / ((Fintype.card V:ℝ) + (Fintype.card V % 2 : ℕ) - 1) := by + classical + rw [finiteAverage_indicator] + have h := Pairing.one_fraction (pairingSpace_even V) (Sum.inl u) (Sum.inl v) + (by simpa using huv) + simp only [Fintype.card_sum,Fintype.card_fin,Nat.cast_add] at h + dsimp only [Pairing.oneCount,paired] at h ⊢ + convert h using 1 + congr 2 + +lemma paired_two_moment {V : Type cycleUniverse31} [Fintype V] (a b c d : V) + (hab : a ≠ b) (hac : a ≠ c) (had : a ≠ d) + (hbc : b ≠ c) (hbd : b ≠ d) (hcd : c ≠ d) : + finiteAverage (fun p : PairingSpace V => if paired p a b ∧ paired p c d then 1 else 0) = + 1 / (((Fintype.card V:ℝ)+(Fintype.card V%2:ℕ)-1)* + ((Fintype.card V:ℝ)+(Fintype.card V%2:ℕ)-3)) := by + classical + rw [finiteAverage_indicator] + have h := Pairing.two_fraction (pairingSpace_even V) + (Sum.inl a) (Sum.inl b) (Sum.inl c) (Sum.inl d) + (by simpa using hab) (by simpa using hac) (by simpa using had) + (by simpa using hbc) (by simpa using hbd) (by simpa using hcd) + simp only [Fintype.card_sum,Fintype.card_fin,Nat.cast_add] at h + dsimp only [Pairing.twoCount,paired] at h ⊢ + convert h using 1 + congr 2 + +lemma paired_first_bound {V : Type cycleUniverse32} [Fintype V] (hV : 2 ≤ Fintype.card V) + (u v : V) (huv : u ≠ v) : + finiteAverage (fun p : PairingSpace V => if paired p u v then 1 else 0) ≤ + 1 / ((Fintype.card V:ℝ)-1) := by + classical + rw [paired_first_moment u v huv] + have hn : (2:ℝ) ≤ Fintype.card V := by exact_mod_cast hV + have hm : (0:ℝ) ≤ (Fintype.card V%2:ℕ) := Nat.cast_nonneg _ + exact one_div_le_one_div_of_le (by linarith) (by linarith) + +lemma paired_two_bound {V : Type cycleUniverse33} [Fintype V] (hV : 4 ≤ Fintype.card V) + (a b c d : V) (hab : a ≠ b) (hac : a ≠ c) (had : a ≠ d) + (hbc : b ≠ c) (hbd : b ≠ d) (hcd : c ≠ d) : + finiteAverage (fun p : PairingSpace V => if paired p a b ∧ paired p c d then 1 else 0) ≤ + 1 / (((Fintype.card V:ℝ)-1)*((Fintype.card V:ℝ)-3)) := by + classical + rw [paired_two_moment a b c d hab hac had hbc hbd hcd] + have hn : (4:ℝ) ≤ Fintype.card V := by exact_mod_cast hV + have hm : (0:ℝ) ≤ (Fintype.card V%2:ℕ) := Nat.cast_nonneg _ + apply one_div_le_one_div_of_le (mul_pos (by linarith) (by linarith)) + exact mul_le_mul (by linarith) (by linarith) (by linarith) (by linarith) + +end +end ErdosGallai.Batch +namespace ErdosGallai.Batch +open Finset +noncomputable section +attribute [local instance] Classical.propDecidable + +lemma finiteAverage_or_le {Ω : Type cycleUniverse34} [Fintype Ω] (P Q : Ω → Prop) : + finiteAverage (fun ω => if P ω ∨ Q ω then 1 else 0) ≤ + finiteAverage (fun ω => if P ω then 1 else 0) + + finiteAverage (fun ω => if Q ω then 1 else 0) := by + rw [← finiteAverage_add] + apply finiteAverage_mono + intro ω + by_cases hp : P ω <;> by_cases hq : Q ω <;> simp [hp,hq] + +lemma paired_event_local {I : Type cycleUniverse35} [Fintype I] [DecidableEq I] + {V : I → Type cycleUniverse62} [∀ i, Fintype (V i)] (i : I) (a b : V i) (hab : a ≠ b) : + finiteAverage (fun p : ∀ j, PairingSpace (V j) => if paired (p i) a b then 1 else 0) = + 1 / ((Fintype.card (V i):ℝ)+(Fintype.card (V i)%2:ℕ)-1) := by + rw [finiteAverage_pi_eval (Ω:=fun j => PairingSpace (V j)) i + (fun p => if paired p a b then 1 else 0),paired_first_moment a b hab] + +lemma pairing_patterns_internal {V : Type cycleUniverse36} [Fintype V] (hV : 4 ≤ Fintype.card V) + (a b c d : V) (hab : a ≠ b) (hac : a ≠ c) (had : a ≠ d) + (hbc : b ≠ c) (hbd : b ≠ d) (hcd : c ≠ d) : + finiteAverage (fun p : PairingSpace V => + if (paired p a c ∧ paired p b d) ∨ (paired p a d ∧ paired p b c) then 1 else 0) ≤ + 2 / (((Fintype.card V:ℝ)-1)*((Fintype.card V:ℝ)-3)) := by + have h₁ := paired_two_bound hV a c b d hac hab had hbc.symm hcd hbd + have h₂ := paired_two_bound hV a d b c had hab hac hbd.symm hcd.symm hbc + have h := finiteAverage_or_le + (fun p : PairingSpace V => paired p a c ∧ paired p b d) + (fun p : PairingSpace V => paired p a d ∧ paired p b c) + calc + _ ≤ finiteAverage (fun p : PairingSpace V => if paired p a c ∧ paired p b d then 1 else 0) + + finiteAverage (fun p : PairingSpace V => if paired p a d ∧ paired p b c then 1 else 0) := by + convert h using 1 <;> congr 3 <;> funext p <;> split_ifs <;> rfl + _ ≤ 1 / (((Fintype.card V:ℝ)-1)*((Fintype.card V:ℝ)-3)) + + 1 / (((Fintype.card V:ℝ)-1)*((Fintype.card V:ℝ)-3)) := add_le_add h₁ h₂ + _ = _ := by ring + +lemma pairing_patterns_cross {I : Type cycleUniverse37} [Fintype I] [DecidableEq I] + {V : I → Type cycleUniverse63} [∀ i, Fintype (V i)] (i j : I) (hij : i ≠ j) + (a c : V i) (hac : a ≠ c) (b d : V j) (hbd : b ≠ d) : + finiteAverage (fun p : ∀ k, PairingSpace (V k) => + if paired (p i) a c ∧ paired (p j) b d then 1 else 0) = + (1 / ((Fintype.card (V i):ℝ)+(Fintype.card (V i)%2:ℕ)-1)) * + (1 / ((Fintype.card (V j):ℝ)+(Fintype.card (V j)%2:ℕ)-1)) := by + have hind : (fun p : ∀ k, PairingSpace (V k) => + if paired (p i) a c ∧ paired (p j) b d then (1:ℝ) else 0) = + (fun p => (if paired (p i) a c then 1 else 0)*(if paired (p j) b d then 1 else 0)) := by + funext p + split_ifs <;> simp_all + rw [hind,finiteAverage_pi_pair (Ω:=fun k => PairingSpace (V k)) i j hij + (fun p => if paired p a c then 1 else 0) (fun p => if paired p b d then 1 else 0),paired_first_moment a c hac,paired_first_moment b d hbd] + +lemma pairing_patterns_cross_bound {I : Type cycleUniverse38} [Fintype I] [DecidableEq I] + {V : I → Type cycleUniverse64} [∀ i, Fintype (V i)] (i j : I) (hij : i ≠ j) + (hi : 2 ≤ Fintype.card (V i)) (hj : 2 ≤ Fintype.card (V j)) + (a c : V i) (hac : a ≠ c) (b d : V j) (hbd : b ≠ d) : + finiteAverage (fun p : ∀ k, PairingSpace (V k) => + if paired (p i) a c ∧ paired (p j) b d then 1 else 0) ≤ + 1 / (((Fintype.card (V i):ℝ)-1)*((Fintype.card (V j):ℝ)-1)) := by + rw [pairing_patterns_cross i j hij a c hac b d hbd,one_div_mul_one_div] + have hi' : (2:ℝ) ≤ Fintype.card (V i) := by exact_mod_cast hi + have hj' : (2:ℝ) ≤ Fintype.card (V j) := by exact_mod_cast hj + have hmi : (0:ℝ) ≤ (Fintype.card (V i)%2:ℕ) := Nat.cast_nonneg _ + have hmj : (0:ℝ) ≤ (Fintype.card (V j)%2:ℕ) := Nat.cast_nonneg _ + apply one_div_le_one_div_of_le (mul_pos (by linarith) (by linarith)) + exact mul_le_mul (by linarith) (by linarith) (by linarith) (by linarith) + +end +end ErdosGallai.Batch +namespace ErdosGallai.Batch +open Finset +noncomputable section +namespace Pairing +variable {V : Type cycleUniverse39} + +def pairSetoid (p : Pairing V) : Setoid V where + r u v := u = v ∨ p u = v + iseqv := ⟨fun _ => Or.inl rfl, (by + intro u v h + rcases h with rfl | h + · exact Or.inl rfl + · exact Or.inr (by have hh := congrArg p h; simpa using hh.symm)), (by + intro u v w h1 h2 + rcases h1 with rfl | h1 + · exact h2 + rcases h2 with rfl | h2 + · exact Or.inr h1 + · left + have hh := congrArg p h1 + simpa only [apply_apply,h2] using hh)⟩ + +def PairQuotient (p : Pairing V) := Quotient (pairSetoid p) + +instance [Fintype V] (p : Pairing V) : Fintype (PairQuotient p) := by + classical + unfold PairQuotient + infer_instance + +instance (p : Pairing V) : DecidableEq (PairQuotient p) := Classical.decEq _ + +def project (p : Pairing V) (v : V) : PairQuotient p := Quotient.mk (pairSetoid p) v + +lemma project_eq_iff (p : Pairing V) (u v : V) : + project p u = project p v ↔ u = v ∨ p u = v := Quotient.eq + +lemma project_surjective (p : Pairing V) : Function.Surjective (project p) := by + intro q + exact Quotient.exists_rep q + +@[simp] lemma project_apply (p : Pairing V) (v : V) : project p (p v) = project p v := + (project_eq_iff p _ _).mpr (Or.inr (apply_apply p v)) + +lemma fiber_card [Fintype V] (p : Pairing V) (q : PairQuotient p) : + Fintype.card {v // project p v = q} = 2 := by + classical + obtain ⟨x,rfl⟩ := project_surjective p q + rw [Fintype.card_subtype] + have heq : (univ.filter (fun v => project p v = project p x)) = {x,p x} := by + ext v + simp only [Finset.mem_filter,Finset.mem_univ,true_and,Finset.mem_insert,Finset.mem_singleton] + rw [project_eq_iff] + constructor + · rintro (h | h) + · exact Or.inl h + · right + have hh := congrArg p h + simpa only [apply_apply] using hh + · rintro (h | h) + · exact Or.inl h + · right + subst v + simp + rw [heq] + simp [Ne.symm (apply_ne p x)] + +lemma card_pairQuotient [Fintype V] (p : Pairing V) : + 2 * Fintype.card (PairQuotient p) = Fintype.card V := by + classical + have h : (∑ q : PairQuotient p, Fintype.card {v // project p v = q}) = Fintype.card V := by + rw [← Fintype.card_sigma] + exact Fintype.card_congr (Equiv.sigmaFiberEquiv (project p)) + simpa only [fiber_card,Finset.sum_const,Finset.card_univ,smul_eq_mul,mul_comm] using h +end Pairing + +def oldProject {V : Type cycleUniverse40} [Fintype V] (p : PairingSpace V) (v : V) : Pairing.PairQuotient p := + p.project (Sum.inl v) + +lemma oldProject_eq_iff {V : Type cycleUniverse41} [Fintype V] (p : PairingSpace V) (u v : V) : + oldProject p u = oldProject p v ↔ u = v ∨ paired p u v := by + simp only [oldProject,Pairing.project_eq_iff,Sum.inl.injEq,paired] + +lemma dummy_partner_is_old {V : Type cycleUniverse42} [Fintype V] (p : PairingSpace V) + (d : Fin (Fintype.card V % 2)) : ∃ v : V, p (Sum.inr d) = Sum.inl v := by + cases h : p (Sum.inr d) with + | inl v => exact ⟨v,rfl⟩ + | inr e => + have he : e = d := by + apply Fin.ext + have hd := d.isLt + have he := e.isLt + have hh := Nat.mod_lt (Fintype.card V) (by omega : 0 < 2) + omega + subst e + exact False.elim (p.apply_ne _ h) + +lemma oldProject_surjective {V : Type cycleUniverse43} [Fintype V] (p : PairingSpace V) : + Function.Surjective (oldProject p) := by + intro q + obtain ⟨x,rfl⟩ := p.project_surjective q + cases x with + | inl v => exact ⟨v,rfl⟩ + | inr d => + obtain ⟨v,hv⟩ := dummy_partner_is_old p d + refine ⟨v,?_⟩ + change p.project (Sum.inl v) = p.project (Sum.inr d) + rw [← hv,p.project_apply] + +lemma old_quotient_order {V : Type cycleUniverse44} [Fintype V] (p : PairingSpace V) : + Fintype.card (Pairing.PairQuotient p) = Fintype.card V - Fintype.card V / 2 := by + have h := p.card_pairQuotient + simp only [Fintype.card_sum,Fintype.card_fin] at h + omega + +lemma old_fiber_card_le_two {V : Type cycleUniverse45} [Fintype V] (p : PairingSpace V) + (q : Pairing.PairQuotient p) : Fintype.card {v // oldProject p v = q} ≤ 2 := by + classical + calc + _ ≤ Fintype.card {v // p.project v = q} := ?_ + _ = 2 := p.fiber_card q + apply Fintype.card_le_of_injective (fun x : {v // oldProject p v = q} => + (⟨Sum.inl x.val,x.property⟩ : {v // p.project v = q})) + intro x y h + apply Subtype.ext + exact Sum.inl_injective (congrArg Subtype.val h) + +end +end ErdosGallai.Batch +namespace ErdosGallai.Batch +open Finset +noncomputable section + +variable {V : Type cycleUniverse46} {I : Type cycleUniverse47} [Fintype V] [Fintype I] (X : I → Finset V) + +abbrev Outside := {v : V // ∀ i, v ∉ X i} +abbrev FoldDomain := Outside X ⊕ (Σ i, X i) + +def unfoldVertex : FoldDomain X → V + | Sum.inl v => v.val + | Sum.inr v => v.2.val + +lemma unfoldVertex_bijective {V : Type cycleUniverse48} {I : Type cycleUniverse49} [_contextInstance2 : Fintype V] [_contextInstance3 : Fintype I] (X : I → Finset V) (hd : Pairwise (fun i j => Disjoint (X i) (X j))) : + Function.Bijective (unfoldVertex X) := by + classical + constructor + · rintro (u | ⟨i,u⟩) (v | ⟨j,v⟩) h + · exact congrArg Sum.inl (Subtype.ext h) + · change u.val = v.val at h + exact False.elim (u.property j (h.symm ▸ v.property)) + · change u.val = v.val at h + exact False.elim (v.property i (h ▸ u.property)) + · change u.val = v.val at h + have hij : i = j := by + by_contra hij + exact Finset.disjoint_left.mp (hd hij) u.property (h.symm ▸ v.property) + subst j + exact congrArg Sum.inr (Sigma.ext rfl (heq_of_eq (Subtype.ext h))) + · intro v + by_cases h : ∃ i, v ∈ X i + · obtain ⟨i,hi⟩ := h + exact ⟨Sum.inr ⟨i,⟨v,hi⟩⟩,rfl⟩ + · exact ⟨Sum.inl ⟨v,by simpa only [not_exists] using h⟩,rfl⟩ + +def splitEquiv (hd : Pairwise (fun i j => Disjoint (X i) (X j))) : FoldDomain X ≃ V := + Equiv.ofBijective (unfoldVertex X) (unfoldVertex_bijective X hd) + +abbrev FamilyQuotient (p : ∀ i, PairingSpace (X i)) := + Outside X ⊕ (Σ i, Pairing.PairQuotient (p i)) + +instance (p : ∀ i, PairingSpace (X i)) : Fintype (FamilyQuotient X p) := by + classical + unfold FamilyQuotient + infer_instance + +instance (p : ∀ i, PairingSpace (X i)) : DecidableEq (FamilyQuotient X p) := Classical.decEq _ + +def foldOnDomain (p : ∀ i, PairingSpace (X i)) : FoldDomain X → FamilyQuotient X p + | Sum.inl v => Sum.inl v + | Sum.inr ⟨i,v⟩ => Sum.inr ⟨i,oldProject (p i) v⟩ + +def familyProject (hd : Pairwise (fun i j => Disjoint (X i) (X j))) + (p : ∀ i, PairingSpace (X i)) : V → FamilyQuotient X p := + foldOnDomain X p ∘ (splitEquiv X hd).symm + +lemma familyProject_surjective (hd : Pairwise (fun i j => Disjoint (X i) (X j))) + (p : ∀ i, PairingSpace (X i)) : Function.Surjective (familyProject X hd p) := by + have h : Function.Surjective (foldOnDomain X p) := by + rintro (v | ⟨i,q⟩) + · exact ⟨Sum.inl v,rfl⟩ + · obtain ⟨v,hv⟩ := oldProject_surjective (p i) q + exact ⟨Sum.inr ⟨i,v⟩,by simp only [foldOnDomain,hv]⟩ + exact h.comp (splitEquiv X hd).symm.surjective + +lemma family_quotient_order_add (hd : Pairwise (fun i j => Disjoint (X i) (X j))) + (p : ∀ i, PairingSpace (X i)) : + Fintype.card (FamilyQuotient X p) + ∑ i, (X i).card / 2 = Fintype.card V := by + classical + have hV := Fintype.card_congr (splitEquiv X hd) + have hV' : Fintype.card (Outside X) + ∑ i, (X i).card = Fintype.card V := by + simpa only [FoldDomain,Fintype.card_sum,Fintype.card_sigma,Fintype.card_coe] using hV + rw [Fintype.card_sum,Fintype.card_sigma,add_assoc,← Finset.sum_add_distrib] + simp_rw [old_quotient_order,Fintype.card_coe,Nat.sub_add_cancel (Nat.div_le_self _ _)] + exact hV' + +theorem family_quotient_order (hd : Pairwise (fun i j => Disjoint (X i) (X j))) + (p : ∀ i, PairingSpace (X i)) : + Fintype.card (FamilyQuotient X p) = Fintype.card V - ∑ i, (X i).card / 2 := by + have h := family_quotient_order_add X hd p + omega + +lemma familyProject_eq_on_outside (hd : Pairwise (fun i j => Disjoint (X i) (X j))) + (p : ∀ i, PairingSpace (X i)) (v : Outside X) : + familyProject X hd p v.val = Sum.inl v := by + have hv : (splitEquiv X hd) (Sum.inl v) = v.val := rfl + rw [familyProject,Function.comp_apply,← hv,Equiv.symm_apply_apply] + rfl + +lemma familyProject_eq_on_inside (hd : Pairwise (fun i j => Disjoint (X i) (X j))) + (p : ∀ i, PairingSpace (X i)) (i : I) (v : X i) : + familyProject X hd p v.val = Sum.inr ⟨i,oldProject (p i) v⟩ := by + have hv : (splitEquiv X hd) (Sum.inr ⟨i,v⟩) = v.val := rfl + rw [familyProject,Function.comp_apply,← hv,Equiv.symm_apply_apply] + rfl + +end +end ErdosGallai.Batch +namespace ErdosGallai.Batch +open Finset +noncomputable section +attribute [local instance] Classical.propDecidable +variable {V : Type cycleUniverse50} {I : Type cycleUniverse51} [Fintype V] [Fintype I] (X : I → Finset V) + +def familyPaired (p : ∀ i, PairingSpace (X i)) (u v : V) : Prop := + ∃ (i : I) (hu : u ∈ X i) (hv : v ∈ X i), paired (p i) ⟨u,hu⟩ ⟨v,hv⟩ + +lemma familyProject_apply_split (hd : Pairwise (fun i j => Disjoint (X i) (X j))) + (p : ∀ i, PairingSpace (X i)) (x : FoldDomain X) : + familyProject X hd p ((splitEquiv X hd) x) = foldOnDomain X p x := by + simp only [familyProject,Function.comp_apply,Equiv.symm_apply_apply] + +lemma familyProject_eq_iff (hd : Pairwise (fun i j => Disjoint (X i) (X j))) + (p : ∀ i, PairingSpace (X i)) (u v : V) : + familyProject X hd p u = familyProject X hd p v ↔ u = v ∨ familyPaired X p u v := by + constructor + · intro h + obtain ⟨a,rfl⟩ := (splitEquiv X hd).surjective u + obtain ⟨b,rfl⟩ := (splitEquiv X hd).surjective v + rw [familyProject_apply_split,familyProject_apply_split] at h + rcases a with a | ⟨i,a⟩ <;> rcases b with b | ⟨j,b⟩ + · exact Or.inl (congrArg (splitEquiv X hd) (congrArg Sum.inl (Sum.inl.inj h))) + · simp only [foldOnDomain,Sum.inl_ne_inr] at h + · simp only [foldOnDomain,Sum.inr_ne_inl] at h + · have hh := Sum.inr.inj h + have hij := congrArg Sigma.fst hh + change i = j at hij + subst j + have hval : oldProject (p i) a = oldProject (p i) b := by + simpa only [Sigma.mk.inj_iff,heq_eq_eq,true_and] using hh + obtain hab | hab := (oldProject_eq_iff (p i) a b).mp hval + · subst b + exact Or.inl rfl + · exact Or.inr ⟨i,a.property,b.property,hab⟩ + · rintro (rfl | ⟨i,hu,hv,hp⟩) + · rfl + · rw [familyProject_eq_on_inside X hd p i ⟨u,hu⟩, + familyProject_eq_on_inside X hd p i ⟨v,hv⟩] + congr 2 + exact (oldProject_eq_iff (p i) ⟨u,hu⟩ ⟨v,hv⟩).mpr (Or.inr hp) + +lemma familyPaired_ne {V : Type cycleUniverse52} {I : Type cycleUniverse53} [_contextInstance2 : Fintype V] [_contextInstance3 : Fintype I] (X : I → Finset V) (p : ∀ i, PairingSpace (X i)) {u v : V} + (h : familyPaired X p u v) : u ≠ v := by + obtain ⟨i,hu,hv,hp⟩ := h + intro he + subst v + exact Pairing.apply_ne (p i) (Sum.inl ⟨u,hu⟩) hp + +lemma familyPaired_unique {V : Type cycleUniverse54} {I : Type cycleUniverse55} [_contextInstance2 : Fintype V] [_contextInstance3 : Fintype I] (X : I → Finset V) (hd : Pairwise (fun i j => Disjoint (X i) (X j))) + (p : ∀ i, PairingSpace (X i)) {u v w : V} + (hv : familyPaired X p u v) (hw : familyPaired X p u w) : v = w := by + obtain ⟨i,hu,hv,hpi⟩ := hv + obtain ⟨j,hu',hw,hpj⟩ := hw + have hij : i = j := by + by_contra hij + exact Finset.disjoint_left.mp (hd hij) hu hu' + subst j + exact congrArg Subtype.val (paired_unique (p i) hpi hpj) + +lemma familyProject_fiber_triple (hd : Pairwise (fun i j => Disjoint (X i) (X j))) + (p : ∀ i, PairingSpace (X i)) (u v w : V) + (huv : familyProject X hd p u = familyProject X hd p v) + (huw : familyProject X hd p u = familyProject X hd p w) : + u = v ∨ u = w ∨ v = w := by + obtain huv | huv := (familyProject_eq_iff X hd p u v).mp huv + · exact Or.inl huv + obtain huw | huw := (familyProject_eq_iff X hd p u w).mp huw + · exact Or.inr (Or.inl huw) + · exact Or.inr (Or.inr (familyPaired_unique X hd p huv huw)) + +end +end ErdosGallai.Batch +namespace ErdosGallai.Batch +open Finset +noncomputable section +attribute [local instance] Classical.propDecidable +variable {V : Type cycleUniverse56} {I : Type cycleUniverse57} [Fintype V] [Fintype I] (X : I → Finset V) + (hd : Pairwise (fun i j => Disjoint (X i) (X j))) (p : ∀ i, PairingSpace (X i)) + +lemma loop_iff_familyPaired {u v : V} (huv : u ≠ v) : + (Sym2.map (familyProject X hd p) s(u,v)).IsDiag ↔ familyPaired X p u v := by + simp only [Sym2.map_mk,Sym2.mk_isDiag_iff, + familyProject_eq_iff,huv,false_or] + +lemma shared_endpoint_collision {v u w : V} (huw : u ≠ w) + (h : Sym2.map (familyProject X hd p) s(v,u) = + Sym2.map (familyProject X hd p) s(v,w)) : familyPaired X p u w := by + have h := (Sym2.mk_eq_mk_iff (p := (familyProject X hd p v, familyProject X hd p u)) + (q := (familyProject X hd p v, familyProject X hd p w))).mp h + simp only [Prod.mk.injEq,Prod.swap_prod_mk] at h + have he : familyProject X hd p u = familyProject X hd p w := by + rcases h with h | h + · exact h.2 + · exact h.2.trans h.1 + exact ((familyProject_eq_iff X hd p u w).mp he).resolve_left huw + +lemma four_endpoint_collision {u v x y : V} + (hux : u ≠ x) (huy : u ≠ y) (hvx : v ≠ x) (hvy : v ≠ y) + (h : Sym2.map (familyProject X hd p) s(u,v) = + Sym2.map (familyProject X hd p) s(x,y)) : + (familyPaired X p u x ∧ familyPaired X p v y) ∨ + (familyPaired X p u y ∧ familyPaired X p v x) := by + have h := (Sym2.mk_eq_mk_iff (p := (familyProject X hd p u, familyProject X hd p v)) + (q := (familyProject X hd p x, familyProject X hd p y))).mp h + simp only [Prod.mk.injEq,Prod.swap_prod_mk] at h + rcases h with h | h + · exact Or.inl ⟨((familyProject_eq_iff X hd p u x).mp h.1).resolve_left hux, + ((familyProject_eq_iff X hd p v y).mp h.2).resolve_left hvy⟩ + · exact Or.inr ⟨((familyProject_eq_iff X hd p u y).mp h.1).resolve_left huy, + ((familyProject_eq_iff X hd p v x).mp h.2).resolve_left hvx⟩ + +lemma paired_fibers_placement {V : Type cycleUniverse58} {I : Type cycleUniverse59} [_contextInstance2 : Fintype V] [_contextInstance3 : Fintype I] (X : I → Finset V) (p : (i : I) → ErdosGallai.Batch.PairingSpace (Subtype fun x => x ∈ X i)) {u v x y : V} + (hux : familyPaired X p u x) (hvy : familyPaired X p v y) : + (∃ i, u ∈ X i ∧ v ∈ X i ∧ x ∈ X i ∧ y ∈ X i) ∨ + (∃ i j, i ≠ j ∧ u ∈ X i ∧ x ∈ X i ∧ v ∈ X j ∧ y ∈ X j) := by + obtain ⟨i,hu,hx,_⟩ := hux + obtain ⟨j,hv,hy,_⟩ := hvy + by_cases hij : i = j + · subst j + exact Or.inl ⟨i,hu,hv,hx,hy⟩ + · exact Or.inr ⟨i,j,hij,hu,hx,hv,hy⟩ + +end +end ErdosGallai.Batch + +end +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/CycleDecomposition/PathDeletion.lean b/lean/OAI/Combinatorics/CycleDecomposition/PathDeletion.lean new file mode 100644 index 0000000000000000000000000000000000000000..14013e0fb78e4ea2d708df402a6404afbbb7163e --- /dev/null +++ b/lean/OAI/Combinatorics/CycleDecomposition/PathDeletion.lean @@ -0,0 +1,735 @@ +import OAI.Combinatorics.CycleDecomposition.Lovasz + +namespace OAI + +universe cycleUniverse1 cycleUniverse2 cycleUniverse3 cycleUniverse4 cycleUniverse5 cycleUniverse6 cycleUniverse7 cycleUniverse8 cycleUniverse9 cycleUniverse10 cycleUniverse11 cycleUniverse12 cycleUniverse13 cycleUniverse14 cycleUniverse15 cycleUniverse16 cycleUniverse17 cycleUniverse18 cycleUniverse19 cycleUniverse20 cycleUniverse21 cycleUniverse22 cycleUniverse23 cycleUniverse24 cycleUniverse25 cycleUniverse26 cycleUniverse27 cycleUniverse28 cycleUniverse29 cycleUniverse30 cycleUniverse31 cycleUniverse32 cycleUniverse33 cycleUniverse34 cycleUniverse35 cycleUniverse36 cycleUniverse37 + +section +open Filter Asymptotics Real +open scoped Topology +noncomputable section +open MeasureTheory ProbabilityTheory Finset +noncomputable section +namespace ErdosGallai +noncomputable section +attribute [local instance] Classical.propDecidable + +structure PositiveSimplePath {V : Type cycleUniverse1} (G : SimpleGraph V) where + start : V + finish : V + walk : G.Walk start finish + isPath : walk.IsPath + positive : 0 < walk.length + +lemma PositiveSimplePath.endpoints_ne {V : Type cycleUniverse2} {G : SimpleGraph V} + (P : PositiveSimplePath G) : P.start ≠ P.finish := by + intro he + have hz := P.isPath.nil_iff_eq.mpr he + have := hz.length_eq_zero + have := P.positive + omega + +theorem endpoint_path_count {V : Type cycleUniverse3} {I : Type cycleUniverse4} [Fintype V] [Fintype I] + {G : SimpleGraph V} (P : I → PositiveSimplePath G) + (hload : ∀ v : V, (Finset.univ.filter + (fun i => (P i).start = v ∨ (P i).finish = v)).card ≤ 2) : + Fintype.card I ≤ Fintype.card V := by + classical + have hsum : (∑ v : V, (Finset.univ.filter + (fun i => (P i).start = v ∨ (P i).finish = v)).card) = + 2 * Fintype.card I := by + simp only [Finset.card_eq_sum_ones, Finset.sum_filter] + rw [Finset.sum_comm] + have heq : ∀ i : I, + (∑ v : V, if (P i).start = v ∨ (P i).finish = v then 1 else 0) = 2 := by + intro i + have hf : (Finset.univ.filter fun v => + (P i).start = v ∨ (P i).finish = v) = {(P i).start, (P i).finish} := by + ext v; simp [eq_comm] + have hc : ({(P i).start, (P i).finish} : Finset V).card = 2 := by + simp [(P i).endpoints_ne] + rw [← hc, ← hf, Finset.card_eq_sum_ones, Finset.sum_filter] + simp only [heq, Finset.sum_const, Finset.card_univ, smul_eq_mul] + omega + have hbound := Finset.sum_le_sum (fun v (_ : v ∈ (Finset.univ : Finset V)) => hload v) + rw [hsum] at hbound + simp only [Finset.sum_const, Finset.card_univ, smul_eq_mul] at hbound + omega + +def EndpointPathPartition {V : Type cycleUniverse5} [Fintype V] (G : SimpleGraph V) : Prop := + ∃ (k : ℕ) (P : Fin k → PositiveSimplePath G), + Pairwise (fun i j => Disjoint (P i).walk.edgeSet (P j).walk.edgeSet) ∧ + (⋃ i, (P i).walk.edgeSet) = G.edgeSet ∧ + (∀ v : V, (Finset.univ.filter (fun i => (P i).start = v ∨ (P i).finish = v)).card ≤ 2) ∧ + k ≤ Fintype.card V + +def MissingEndpointTheorem : Prop := + ∀ (n : ℕ) (G : SimpleGraph (Fin n)), EndpointPathPartition G + +def PathOrCycleEdgeSet {V : Type cycleUniverse6} (G : SimpleGraph V) + (s : Set (Sym2 V)) : Prop := + (∃ (a b : V) (p : G.Walk a b), p.IsPath ∧ 0 < p.length ∧ s = p.edgeSet) ∨ + (∃ (a : V) (p : G.Walk a a), p.IsCycle ∧ s = p.edgeSet) + +def LovaszPathCyclePartition {V : Type cycleUniverse7} [Fintype V] (G : SimpleGraph V) : Prop := + ∃ (k : ℕ) (parts : Fin k → Set (Sym2 V)), + (∀ i, PathOrCycleEdgeSet G (parts i)) ∧ + Pairwise (fun i j => Disjoint (parts i) (parts j)) ∧ + (⋃ i, parts i) = G.edgeSet ∧ 2 * k ≤ Fintype.card V + +def MissingLovaszTheorem : Prop := + ∀ (n : ℕ) (G : SimpleGraph (Fin n)), LovaszPathCyclePartition G + +end +end ErdosGallai + +namespace ErdosGallai +noncomputable section +attribute [local instance] Classical.propDecidable +open scoped BigOperators + +def evenAugmentation {V : Type cycleUniverse8} [Fintype V] (G : SimpleGraph V) : + SimpleGraph (Option V) where + Adj x y := match x, y with + | some u, some v => G.Adj u v + | none, some v => Even (G.degree v) + | some u, none => Even (G.degree u) + | none, none => False + symm := ⟨by + intro x y h + cases x <;> cases y + · exact h + · exact h + · exact h + · exact G.adj_symm h⟩ + loopless := ⟨by + intro x h + cases x + · exact h + · exact G.irrefl h⟩ + +@[simp] theorem evenAugmentation_some_adj {V : Type cycleUniverse9} [Fintype V] + (G : SimpleGraph V) (u v : V) : + (evenAugmentation G).Adj (some u) (some v) ↔ G.Adj u v := Iff.rfl + +@[simp] theorem evenAugmentation_none_adj {V : Type cycleUniverse10} [Fintype V] + (G : SimpleGraph V) (v : V) : + (evenAugmentation G).Adj none (some v) ↔ Even (G.degree v) := Iff.rfl + +@[simp] theorem evenAugmentation_some_none {V : Type cycleUniverse11} [Fintype V] + (G : SimpleGraph V) (v : V) : + (evenAugmentation G).Adj (some v) none ↔ Even (G.degree v) := Iff.rfl + +theorem evenAugmentation_degree {V : Type cycleUniverse12} [Fintype V] + (G : SimpleGraph V) (v : V) : + (evenAugmentation G).degree (some v) = + G.degree v + if Even (G.degree v) then 1 else 0 := by + classical + rw [SimpleGraph.degree, SimpleGraph.neighborFinset_eq_filter, + Finset.card_eq_sum_ones, Finset.sum_filter, Fintype.sum_option] + simp only [evenAugmentation_some_adj, evenAugmentation_some_none] + have he : (∑ u : V, if G.Adj v u then 1 else 0) = G.degree v := by + rw [← G.card_neighborFinset_eq_degree v, G.neighborFinset_eq_filter, + Finset.card_eq_sum_ones, Finset.sum_filter] + rw [he] + omega + +theorem evenAugmentation_old_odd {V : Type cycleUniverse13} [Fintype V] + (G : SimpleGraph V) (v : V) : Odd ((evenAugmentation G).degree (some v)) := by + rw [evenAugmentation_degree] + by_cases h : Even (G.degree v) + · simp only [h, ↓reduceIte] + rcases h with ⟨k, hk⟩ + exact ⟨k, by omega⟩ + · simpa [h] using Nat.not_even_iff_odd.mp h + +end +end ErdosGallai + +namespace ErdosGallai +noncomputable section +open scoped BigOperators +attribute [local instance] Classical.propDecidable + +theorem trail_partition_degree_sum {V : Type cycleUniverse14} {I : Type cycleUniverse15} [Fintype V] [Fintype I] + (G : SimpleGraph V) {a b : I → V} (p : ∀ i, G.Walk (a i) (b i)) + (ht : ∀ i, (p i).IsTrail) + (hd : Pairwise fun i j => Disjoint (p i).edgeSet (p j).edgeSet) + (hc : (⋃ i, (p i).edgeSet) = G.edgeSet) (v : V) : + G.degree v = ∑ i, (p i).edges.countP (fun e => decide (v ∈ e)) := by + classical + have he : G.edgeFinset = Finset.univ.biUnion (fun i => (p i).edges.toFinset) := by + ext e + simp only [SimpleGraph.mem_edgeFinset, ← hc, Set.mem_iUnion, + Finset.mem_biUnion, Finset.mem_univ, List.mem_toFinset, true_and, + SimpleGraph.Walk.mem_edgeSet] + rw [← G.card_incidenceFinset_eq_degree v, G.incidenceFinset_eq_filter, he, + Finset.filter_biUnion] + rw [Finset.card_biUnion] + · apply Finset.sum_congr rfl + intro i _ + have hfilter : ((p i).edges.filter (fun e => decide (v ∈ e))).toFinset = + ((p i).edges.toFinset.filter (fun e => v ∈ e)) := by + simp [List.toFinset_filter] + rw [← hfilter, List.toFinset_card_of_nodup ((ht i).edges_nodup.filter _), + List.countP_eq_length_filter] + · intro i _ j _ hij + apply Finset.disjoint_left.mpr + intro e hei hej + exact Set.disjoint_left.mp (hd hij) + (by simpa using (Finset.mem_filter.mp hei).1) + (by simpa using (Finset.mem_filter.mp hej).1) + +theorem trail_partition_even_degree_iff {V : Type cycleUniverse16} {I : Type cycleUniverse17} [Fintype V] [Fintype I] + (G : SimpleGraph V) {a b : I → V} (p : ∀ i, G.Walk (a i) (b i)) + (ht : ∀ i, (p i).IsTrail) + (hd : Pairwise fun i j => Disjoint (p i).edgeSet (p j).edgeSet) + (hc : (⋃ i, (p i).edgeSet) = G.edgeSet) (v : V) : + Even (G.degree v) ↔ Even (Finset.univ.filter + (fun i => a i ≠ b i ∧ (v = a i ∨ v = b i))).card := by + classical + rw [trail_partition_degree_sum G p ht hd hc v, Finset.even_sum_iff_even_card_odd] + have he : (Finset.univ.filter (fun i => Odd ((p i).edges.countP + (fun e => decide (v ∈ e))))) = (Finset.univ.filter + (fun i => a i ≠ b i ∧ (v = a i ∨ v = b i))) := by + ext i + simp only [Finset.mem_filter, Finset.mem_univ, true_and, + ← Nat.not_even_iff_odd, (ht i).even_countP_edges_iff] + tauto + rw [he] + +private theorem odd_load_one {V : Type cycleUniverse18} [DecidableEq V] + (S : Finset V) (f : V → ℕ) (ho : ∀ v ∈ S, Odd (f v)) + (hs : ∑ v ∈ S, f v ≤ S.card + 1) : ∀ v ∈ S, f v = 1 := by + intro v hv + by_contra hn + have hv3 : 3 ≤ f v := by rcases ho v hv with ⟨k, hk⟩; omega + have hlow : ∑ x ∈ S, (1 + if x = v then 2 else 0) ≤ ∑ x ∈ S, f x := by + apply Finset.sum_le_sum + intro x hx + by_cases he : x = v + · subst x; simpa using hv3 + · simp only [he, ↓reduceIte, add_zero] + rcases ho x hx with ⟨k, hk⟩ + omega + have heq : (∑ x ∈ S, (1 + if x = v then 2 else 0)) = S.card + 2 := by + simp [Finset.sum_add_distrib, hv] + omega + +theorem tight_odd_trail_partition {V : Type cycleUniverse19} {I : Type cycleUniverse20} [Fintype V] [Fintype I] + (G : SimpleGraph V) (S : Finset V) {a b : I → V} + (p : ∀ i, G.Walk (a i) (b i)) (ht : ∀ i, (p i).IsTrail) + (hd : Pairwise fun i j => Disjoint (p i).edgeSet (p j).edgeSet) + (hc : (⋃ i, (p i).edgeSet) = G.edgeSet) + (ho : ∀ v ∈ S, Odd (G.degree v)) + (hsize : 2 * Fintype.card I ≤ S.card + 1) : + (∀ i, a i ≠ b i) ∧ (∀ v ∈ S, + (Finset.univ.filter (fun i => a i ≠ b i ∧ (v = a i ∨ v = b i))).card = 1) := by + classical + let load := fun v : V => (Finset.univ.filter + (fun i => a i ≠ b i ∧ (v = a i ∨ v = b i))).card + let openParts := Finset.univ.filter (fun i => a i ≠ b i) + have hlodd : ∀ v ∈ S, Odd (load v) := by + intro v hv + rw [← Nat.not_even_iff_odd, ← trail_partition_even_degree_iff G p ht hd hc v] + exact (Nat.not_even_iff_odd.mpr (ho v hv)) + have htotal : (∑ v : V, load v) = 2 * openParts.card := by + dsimp [load] + simp only [Finset.card_eq_sum_ones, Finset.sum_filter] + rw [Finset.sum_comm] + have he : ∀ i : I, (∑ v : V, if a i ≠ b i ∧ (v = a i ∨ v = b i) then 1 else 0) = + if a i ≠ b i then 2 else 0 := by + intro i + by_cases h : a i = b i + · simp [h] + · have hf : (Finset.univ.filter (fun v => a i ≠ b i ∧ (v = a i ∨ v = b i))) = + {a i, b i} := by ext v; simp [h] + have hcard : ({a i, b i} : Finset V).card = 2 := by simp [h] + rw [ite_eq_left h, ← hcard, ← hf, Finset.card_eq_sum_ones, Finset.sum_filter] + simp_rw [he] + rw [← Finset.sum_filter] + simp only [Finset.sum_const, smul_eq_mul, mul_one] + change openParts.card * 2 = 2 * openParts.card + omega + have hsub : (∑ v ∈ S, load v) ≤ ∑ v : V, load v := + Finset.sum_le_sum_of_subset (Finset.subset_univ S) + have hlow : S.card ≤ ∑ v ∈ S, load v := by + simpa using Finset.sum_le_sum (s := S) (f := fun _ => 1) (g := load) + (fun v hv => by rcases hlodd v hv with ⟨k, hk⟩; omega) + have hcount : openParts.card ≤ Fintype.card I := Finset.card_le_univ _ + have hpoint := odd_load_one S load hlodd (by omega) + refine ⟨?_, hpoint⟩ + intro i hi + have hproper : openParts ⊂ Finset.univ := by + apply Finset.ssubset_iff_subset_ne.mpr + refine ⟨Finset.subset_univ _, ?_⟩ + intro heq + have hh : i ∈ openParts := heq.symm ▸ Finset.mem_univ i + simp [openParts, hi] at hh + have hlt := Finset.card_lt_card hproper + simp only [Finset.card_univ] at hlt + omega + +end +end ErdosGallai + +namespace ErdosGallai +noncomputable section + +private theorem path_tail_delete_start {V : Type cycleUniverse21} {G : SimpleGraph V} + {a b : V} (p : G.Walk a b) (hp : p.IsPath) : + p.tail.edgeSet = {e | e ∈ p.edgeSet ∧ a ∉ e} := by + cases p with + | nil => ext e; simp + | @cons a c b h q => + have ha : a ∉ q.support := (List.nodup_cons.mp hp.support_nodup).1 + have hnot : ∀ e ∈ q.edgeSet, a ∉ e := by + intro e he hae + exact ha (SimpleGraph.Walk.mem_support_iff_exists_mem_edges.mpr + (Or.inr ⟨e, he, hae⟩)) + ext e + simp only [Set.mem_ofPred_eq, SimpleGraph.Walk.mem_edgeSet, + SimpleGraph.Walk.edges_tail, SimpleGraph.Walk.edges_cons, List.tail_cons, List.mem_cons] + constructor + · intro he + exact ⟨Or.inr he, hnot e he⟩ + · rintro ⟨he | he, hn⟩ + · subst e; exact (hn (by simp)).elim + · exact he + +private theorem path_dropLast_delete_end {V : Type cycleUniverse22} {G : SimpleGraph V} + {a b : V} (p : G.Walk a b) (hp : p.IsPath) : + p.dropLast.edgeSet = {e | e ∈ p.edgeSet ∧ b ∉ e} := by + have he : p.dropLast.edgeSet = p.reverse.tail.edgeSet := by + calc + _ = p.dropLast.reverse.edgeSet := (SimpleGraph.Walk.edgeSet_reverse _).symm + _ = _ := by rw [SimpleGraph.Walk.reverse_dropLast, SimpleGraph.Walk.edgeSet_copy] + rw [he, path_tail_delete_start p.reverse hp.reverse, SimpleGraph.Walk.edgeSet_reverse] + +private theorem positive_avoids_of_no_incidence {V : Type cycleUniverse23} {G : SimpleGraph V} + {a b v : V} (p : G.Walk a b) (hpos : 0 < p.length) + (he : ∀ e ∈ p.edgeSet, v ∉ e) : v ∉ p.support := by + have hn : ¬p.Nil := by intro hz; have := hz.length_eq_zero; omega + intro hv + obtain ⟨e, he', hve⟩ := SimpleGraph.Walk.mem_support_iff_exists_mem_edges_of_not_nil hn |>.mp hv + exact he e he' hve + +theorem delete_vertex_from_path {V : Type cycleUniverse24} [DecidableEq V] {G : SimpleGraph V} + {a b v : V} (p : G.Walk a b) (hp : p.IsPath) (hv : v ∈ p.support) : + let q := (p.takeUntil v hv).dropLast + let r := (p.dropUntil v hv).tail + q.IsPath ∧ r.IsPath ∧ Disjoint q.edgeSet r.edgeSet ∧ + q.edgeSet ∪ r.edgeSet = {e | e ∈ p.edgeSet ∧ v ∉ e} ∧ + (0 < q.length → v ∉ q.support) ∧ + (0 < r.length → v ∉ r.support) ∧ + (0 < q.length → G.Adj (p.takeUntil v hv).penultimate v) ∧ + (0 < r.length → G.Adj v (p.dropUntil v hv).snd) := by + dsimp only + let t := p.takeUntil v hv + let d := p.dropUntil v hv + have ht : t.IsPath := hp.takeUntil hv + have hd : d.IsPath := hp.dropUntil hv + have heq : t.append d = p := p.take_spec hv + have hqe : t.dropLast.edgeSet = {e | e ∈ t.edgeSet ∧ v ∉ e} := + path_dropLast_delete_end t ht + have hre : d.tail.edgeSet = {e | e ∈ d.edgeSet ∧ v ∉ e} := + path_tail_delete_start d hd + have hdis : Disjoint t.edgeSet d.edgeSet := by + have hn := hp.isTrail.edges_nodup + rw [← heq, SimpleGraph.Walk.edges_append] at hn + have hn' := (List.nodup_append.mp hn).2.2 + apply Set.disjoint_left.mpr + intro e het hed + exact hn' e het e hed rfl + refine ⟨ht.dropLast, hd.tail, ?_, ?_, ?_, ?_, ?_, ?_⟩ + · rw [hqe, hre] + exact hdis.mono (fun _ h => h.1) (fun _ h => h.1) + · have he : t.edgeSet ∪ d.edgeSet = p.edgeSet := by + rw [← SimpleGraph.Walk.edgeSet_append, heq] + rw [hqe, hre] + ext e + simp only [Set.mem_union, Set.mem_ofPred_eq] + rw [← he] + simp only [Set.mem_union] + tauto + · intro hpos + apply positive_avoids_of_no_incidence _ hpos + intro e he + exact (hqe ▸ he).2 + · intro hpos + apply positive_avoids_of_no_incidence _ hpos + intro e he + exact (hre ▸ he).2 + · intro hpos + apply t.adj_penultimate + intro hn + have hz := hn.length_eq_zero + change 0 < t.dropLast.length at hpos + rw [SimpleGraph.Walk.length_dropLast, hz] at hpos + omega + · intro hpos + apply d.adj_snd + intro hn + have hz := hn.length_eq_zero + change 0 < d.tail.length at hpos + rw [SimpleGraph.Walk.length_tail, hz] at hpos + omega + +theorem delete_vertex_boundary_edges {V : Type cycleUniverse25} [DecidableEq V] + {G : SimpleGraph V} {a b v : V} (p : G.Walk a b) (hv : v ∈ p.support) : + (0 < (p.takeUntil v hv).dropLast.length → + s((p.takeUntil v hv).penultimate, v) ∈ p.edgeSet) ∧ + (0 < (p.dropUntil v hv).tail.length → + s(v, (p.dropUntil v hv).snd) ∈ p.edgeSet) := by + let t := p.takeUntil v hv + let d := p.dropUntil v hv + have heq : t.append d = p := p.take_spec hv + constructor + · intro hpos + have hn : ¬ t.Nil := by + intro hz + change 0 < t.dropLast.length at hpos + rw [SimpleGraph.Walk.length_dropLast, hz.length_eq_zero] at hpos + omega + have hm := t.mk_penultimate_end_mem_edges hn + have hed : t.edgeSet ∪ d.edgeSet = p.edgeSet := by + rw [← SimpleGraph.Walk.edgeSet_append, heq] + exact hed ▸ Or.inl hm + · intro hpos + have hn : ¬ d.Nil := by + intro hz + change 0 < d.tail.length at hpos + rw [SimpleGraph.Walk.length_tail, hz.length_eq_zero] at hpos + omega + have hm := d.mk_start_snd_mem_edges hn + have hed : t.edgeSet ∪ d.edgeSet = p.edgeSet := by + rw [← SimpleGraph.Walk.edgeSet_append, heq] + exact hed ▸ Or.inr hm + +theorem delete_vertex_new_ends_ne {V : Type cycleUniverse26} [DecidableEq V] + {G : SimpleGraph V} {a b v : V} (p : G.Walk a b) (hp : p.IsPath) + (hv : v ∈ p.support) + (hl : 0 < (p.takeUntil v hv).dropLast.length) + (hr : 0 < (p.dropUntil v hv).tail.length) : + (p.takeUntil v hv).penultimate ≠ (p.dropUntil v hv).snd := by + let t := p.takeUntil v hv + let d := p.dropUntil v hv + have heq : t.append d = p := p.take_spec hv + have htn : ¬t.Nil := by + intro hz + change 0 < t.dropLast.length at hl + rw [SimpleGraph.Walk.length_dropLast, hz.length_eq_zero] at hl + omega + have hdn : ¬d.Nil := by + intro hz + change 0 < d.tail.length at hr + rw [SimpleGraph.Walk.length_tail, hz.length_eq_zero] at hr + omega + have hdj := hp.isTrail.edges_nodup + rw [← heq, SimpleGraph.Walk.edges_append] at hdj + have hdis := (List.nodup_append.mp hdj).2.2 + intro hsame + have ha := t.mk_penultimate_end_mem_edges htn + have hb := d.mk_start_snd_mem_edges hdn + apply hdis _ ha _ hb + + rw [show t.penultimate = d.snd from hsame, Sym2.eq_swap] + +theorem delete_vertex_new_endpoint_load {V : Type cycleUniverse27} {I : Type cycleUniverse28} [DecidableEq V] [Fintype I] + {G : SimpleGraph V} {a b : I → V} {v : V} + (p : ∀ i, G.Walk (a i) (b i)) (hp : ∀ i, (p i).IsPath) + (hv : ∀ i, v ∈ (p i).support) + (hd : Pairwise fun i j => Disjoint (p i).edgeSet (p j).edgeSet) (x : V) : + let live := fun z : I × Bool => if z.2 then + 0 < ((p z.1).takeUntil v (hv z.1)).dropLast.length else + 0 < ((p z.1).dropUntil v (hv z.1)).tail.length + let newEnd := fun z : I × Bool => if z.2 then + ((p z.1).takeUntil v (hv z.1)).penultimate else + ((p z.1).dropUntil v (hv z.1)).snd + (Finset.univ.filter fun z => live z ∧ newEnd z = x).card ≤ 1 := by + classical + dsimp only + apply Finset.card_le_one.mpr + intro z hz w hw + obtain ⟨i, bi⟩ := z + obtain ⟨j, bj⟩ := w + have hi := (Finset.mem_filter.mp hz).2 + have hj := (Finset.mem_filter.mp hw).2 + have hei : s(v,x) ∈ (p i).edgeSet := by + cases bi + · have hx : ((p i).dropUntil v (hv i)).snd = x := hi.2 + simpa only [hx] using (delete_vertex_boundary_edges (p i) (hv i)).2 hi.1 + · have hx : ((p i).takeUntil v (hv i)).penultimate = x := hi.2 + have he := (delete_vertex_boundary_edges (p i) (hv i)).1 hi.1 + simpa only [hx, Sym2.eq_swap] using he + have hej : s(v,x) ∈ (p j).edgeSet := by + cases bj + · have hx : ((p j).dropUntil v (hv j)).snd = x := hj.2 + simpa only [hx] using (delete_vertex_boundary_edges (p j) (hv j)).2 hj.1 + · have hx : ((p j).takeUntil v (hv j)).penultimate = x := hj.2 + have he := (delete_vertex_boundary_edges (p j) (hv j)).1 hj.1 + simpa only [hx, Sym2.eq_swap] using he + have hij : i = j := by + by_contra hn + exact Set.disjoint_left.mp (hd hn) hei hej + subst j + congr 1 + cases bi <;> cases bj + · rfl + · have he := delete_vertex_new_ends_ne (p i) (hp i) (hv i) hj.1 hi.1 + exact (he (hj.2.trans hi.2.symm)).elim + · have he := delete_vertex_new_ends_ne (p i) (hp i) (hv i) hi.1 hj.1 + exact (he (hi.2.trans hj.2.symm)).elim + · rfl + +structure SimplePathPiece {V : Type cycleUniverse29} (G : SimpleGraph V) where + start : V + finish : V + walk : G.Walk start finish + isPath : walk.IsPath + +namespace SimplePathPiece +attribute [local instance] Classical.propDecidable +variable {V : Type cycleUniverse30} {I : Type cycleUniverse31} [Fintype I] [DecidableEq V] {G : SimpleGraph V} + +def Avoiding (p : I → SimplePathPiece G) (v : V) := {i : I // v ∉ (p i).walk.support} +def Meeting (p : I → SimplePathPiece G) (v : V) := {i : I // v ∈ (p i).walk.support} +def DeleteIndex (p : I → SimplePathPiece G) (v : V) := + Avoiding p v ⊕ (Meeting p v × Bool) + +instance (p : I → SimplePathPiece G) (v : V) : Fintype (Avoiding p v) := by + classical + exact inferInstanceAs (Fintype {i : I // v ∉ (p i).walk.support}) +instance (p : I → SimplePathPiece G) (v : V) : Fintype (Meeting p v) := by + classical + exact inferInstanceAs (Fintype {i : I // v ∈ (p i).walk.support}) +instance (p : I → SimplePathPiece G) (v : V) : Fintype (DeleteIndex p v) := + inferInstanceAs (Fintype (Avoiding p v ⊕ (Meeting p v × Bool))) + +def deleted (p : I → SimplePathPiece G) (v : V) : DeleteIndex p v → SimplePathPiece G + | .inl i => p i.val + | .inr (i,true) => ⟨_,_,((p i.val).walk.takeUntil v i.property).dropLast, + ((p i.val).isPath.takeUntil i.property).dropLast⟩ + | .inr (i,false) => ⟨_,_,((p i.val).walk.dropUntil v i.property).tail, + ((p i.val).isPath.dropUntil i.property).tail⟩ + +def parent (p : I → SimplePathPiece G) (v : V) : DeleteIndex p v → I + | .inl i => i.val + | .inr (i,_) => i.val + +def oldEnd (p : I → SimplePathPiece G) (v x : V) : DeleteIndex p v → Prop + | .inl i => (p i.val).start = x ∨ (p i.val).finish = x + | .inr (i,true) => (p i.val).start = x + | .inr (i,false) => (p i.val).finish = x + +def newEnd (p : I → SimplePathPiece G) (v x : V) : DeleteIndex p v → Prop + | .inl _ => False + | .inr (i,true) => ((p i.val).walk.takeUntil v i.property).penultimate = x + | .inr (i,false) => ((p i.val).walk.dropUntil v i.property).snd = x + +lemma deleted_ends {V : Type cycleUniverse32} {I : Type cycleUniverse33} [_contextInstance2 : Fintype I] [_contextInstance3 : DecidableEq V] {G : SimpleGraph V} (p : I → SimplePathPiece G) (v x : V) (j : DeleteIndex p v) : + (deleted p v j).start = x ∨ (deleted p v j).finish = x ↔ + oldEnd p v x j ∨ newEnd p v x j := by + rcases j with i | ⟨i,b⟩ + · simp [deleted, oldEnd, newEnd] + · cases b <;> simp [deleted, oldEnd, newEnd, or_comm] + +lemma deleted_edges_subset {V : Type cycleUniverse34} {I : Type cycleUniverse35} [_contextInstance2 : Fintype I] [_contextInstance3 : DecidableEq V] {G : SimpleGraph V} (p : I → SimplePathPiece G) (v : V) (j : DeleteIndex p v) : + (deleted p v j).walk.edgeSet ⊆ (p (parent p v j)).walk.edgeSet := by + rcases j with i | ⟨i,b⟩ + · exact Set.Subset.rfl + · have h := (delete_vertex_from_path (p i.val).walk (p i.val).isPath i.property).2.2.2.1 + cases b + · intro e he + exact (show e ∈ {e | e ∈ (p i.val).walk.edgeSet ∧ v ∉ e} from + h ▸ Or.inr he).1 + · intro e he + exact (show e ∈ {e | e ∈ (p i.val).walk.edgeSet ∧ v ∉ e} from + h ▸ Or.inl he).1 + +lemma deleted_positive_avoids {V : Type cycleUniverse36} {I : Type cycleUniverse37} [_contextInstance2 : Fintype I] [_contextInstance3 : DecidableEq V] {G : SimpleGraph V} (p : I → SimplePathPiece G) (v : V) (j : DeleteIndex p v) + (hpos : 0 < (deleted p v j).walk.length) : v ∉ (deleted p v j).walk.support := by + rcases j with i | ⟨i,b⟩ + · exact i.property + · have h := delete_vertex_from_path (p i.val).walk (p i.val).isPath i.property + cases b + · exact h.2.2.2.2.2.1 hpos + · exact h.2.2.2.2.1 hpos + +lemma deleted_disjoint (p : I → SimplePathPiece G) (v : V) + (hd : Pairwise fun i j => Disjoint (p i).walk.edgeSet (p j).walk.edgeSet) : + Pairwise fun j k => Disjoint (deleted p v j).walk.edgeSet (deleted p v k).walk.edgeSet := by + intro j k hjk + by_cases he : parent p v j = parent p v k + · rcases j with i | ⟨i,b⟩ <;> rcases k with l | ⟨l,c⟩ + · exact (hjk (congrArg Sum.inl (Subtype.ext he))).elim + · exact (i.property (show v ∈ (p i.val).walk.support from (show i.val = l.val from he).symm ▸ l.property)).elim + · exact (l.property (show v ∈ (p l.val).walk.support from (show i.val = l.val from he) ▸ i.property)).elim + · have hil : i = l := Subtype.ext he + subst l + cases b <;> cases c + · exact (hjk rfl).elim + · exact (delete_vertex_from_path (p i.val).walk (p i.val).isPath i.property).2.2.1.symm + · exact (delete_vertex_from_path (p i.val).walk (p i.val).isPath i.property).2.2.1 + · exact (hjk rfl).elim + · exact (hd he).mono (deleted_edges_subset p v j) (deleted_edges_subset p v k) + +lemma deleted_old_load (p : I → SimplePathPiece G) (v x : V) + (hne : ∀ i, (p i).start ≠ (p i).finish) + (hload : (Finset.univ.filter fun i => (p i).start = x ∨ (p i).finish = x).card ≤ 1) : + (Finset.univ.filter fun j : DeleteIndex p v => oldEnd p v x j).card ≤ 1 := by + classical + apply Finset.card_le_one.mpr + intro j hj k hk + have hjp : (p (parent p v j)).start = x ∨ (p (parent p v j)).finish = x := by + have h := (Finset.mem_filter.mp hj).2 + rcases j with i | ⟨i,b⟩ + · exact h + · cases b + · exact Or.inr h + · exact Or.inl h + have hkp : (p (parent p v k)).start = x ∨ (p (parent p v k)).finish = x := by + have h := (Finset.mem_filter.mp hk).2 + rcases k with i | ⟨i,b⟩ + · exact h + · cases b + · exact Or.inr h + · exact Or.inl h + have he := Finset.card_le_one.mp hload (parent p v j) + (Finset.mem_filter.mpr ⟨Finset.mem_univ _,hjp⟩) (parent p v k) + (Finset.mem_filter.mpr ⟨Finset.mem_univ _,hkp⟩) + have hj' := (Finset.mem_filter.mp hj).2 + have hk' := (Finset.mem_filter.mp hk).2 + rcases j with i | ⟨i,b⟩ <;> rcases k with l | ⟨l,c⟩ + · exact congrArg Sum.inl (Subtype.ext he) + · exact (i.property (show v ∈ (p i.val).walk.support from (show i.val = l.val from he).symm ▸ l.property)).elim + · exact (l.property (show v ∈ (p l.val).walk.support from (show i.val = l.val from he) ▸ i.property)).elim + · have hil : i = l := Subtype.ext he + subst l + cases b <;> cases c + · rfl + · exact (hne _ (hk'.trans hj'.symm)).elim + · exact (hne _ (hj'.trans hk'.symm)).elim + · rfl + +lemma deleted_new_load (p : I → SimplePathPiece G) (v x : V) + (hd : Pairwise fun i j => Disjoint (p i).walk.edgeSet (p j).walk.edgeSet) : + (Finset.univ.filter fun j : DeleteIndex p v => + 0 < (deleted p v j).walk.length ∧ newEnd p v x j).card ≤ 1 := by + classical + have h := delete_vertex_new_endpoint_load + (fun i : Meeting p v => (p i.val).walk) (fun i => (p i.val).isPath) + (fun i => i.property) + (fun i j hij => hd (fun he => hij (Subtype.ext he))) x + apply Finset.card_le_one.mpr + intro j hj k hk + have hj' := (Finset.mem_filter.mp hj).2 + have hk' := (Finset.mem_filter.mp hk).2 + rcases j with i | ⟨i,b⟩ + · exact False.elim hj'.2 + rcases k with l | ⟨l,c⟩ + · exact False.elim hk'.2 + apply congrArg Sum.inr + apply Finset.card_le_one.mp h + · apply Finset.mem_filter.mpr + refine ⟨Finset.mem_univ _,?_⟩ + cases b <;> exact hj' + · apply Finset.mem_filter.mpr + refine ⟨Finset.mem_univ _,?_⟩ + cases c <;> exact hk' + +theorem deleted_endpoint_load (p : I → SimplePathPiece G) (v x : V) + (hne : ∀ i, (p i).start ≠ (p i).finish) + (hd : Pairwise fun i j => Disjoint (p i).walk.edgeSet (p j).walk.edgeSet) + (hload : (Finset.univ.filter fun i => (p i).start = x ∨ (p i).finish = x).card ≤ 1) : + (Finset.univ.filter fun j : DeleteIndex p v => 0 < (deleted p v j).walk.length ∧ + ((deleted p v j).start = x ∨ (deleted p v j).finish = x)).card ≤ 2 := by + classical + let A := Finset.univ.filter (fun j : DeleteIndex p v => oldEnd p v x j) + let B := Finset.univ.filter (fun j : DeleteIndex p v => + 0 < (deleted p v j).walk.length ∧ newEnd p v x j) + have hsub : (Finset.univ.filter fun j : DeleteIndex p v => + 0 < (deleted p v j).walk.length ∧ + ((deleted p v j).start = x ∨ (deleted p v j).finish = x)) ⊆ A ∪ B := by + intro j hj + obtain ⟨hpos,hend⟩ := (Finset.mem_filter.mp hj).2 + rcases (deleted_ends p v x j).mp hend with ho | hn + · exact Finset.mem_union_left _ (Finset.mem_filter.mpr ⟨Finset.mem_univ _,ho⟩) + · exact Finset.mem_union_right _ (Finset.mem_filter.mpr ⟨Finset.mem_univ _,hpos,hn⟩) + have ha := deleted_old_load p v x hne hload + have hb := deleted_new_load p v x hd + have hc := (Finset.card_le_card hsub).trans (Finset.card_union_le A B) + dsimp [A,B] at hc + omega + +theorem deleted_union (p : I → SimplePathPiece G) (v : V) : + (⋃ j : DeleteIndex p v, (deleted p v j).walk.edgeSet) = + {e | (∃ i, e ∈ (p i).walk.edgeSet) ∧ v ∉ e} := by + classical + ext e + constructor + · intro he + obtain ⟨j,hj⟩ := Set.mem_iUnion.mp he + refine ⟨⟨parent p v j, deleted_edges_subset p v j hj⟩,?_⟩ + rcases j with i | ⟨i,b⟩ + · intro hv + exact i.property (SimpleGraph.Walk.mem_support_iff_exists_mem_edges.mpr + (Or.inr ⟨e,hj,hv⟩)) + · have h := (delete_vertex_from_path (p i.val).walk (p i.val).isPath i.property).2.2.2.1 + cases b + · exact (show e ∈ {e | e ∈ (p i.val).walk.edgeSet ∧ v ∉ e} from + h ▸ Or.inr hj).2 + · exact (show e ∈ {e | e ∈ (p i.val).walk.edgeSet ∧ v ∉ e} from + h ▸ Or.inl hj).2 + · rintro ⟨⟨i,hi⟩,hv⟩ + by_cases hs : v ∈ (p i).walk.support + · have h := (delete_vertex_from_path (p i).walk (p i).isPath hs).2.2.2.1 + have he : e ∈ ((p i).walk.takeUntil v hs).dropLast.edgeSet ∪ + ((p i).walk.dropUntil v hs).tail.edgeSet := h.symm ▸ ⟨hi,hv⟩ + rcases he with hl | hr + · exact Set.mem_iUnion.mpr ⟨Sum.inr (⟨i,hs⟩,true),hl⟩ + · exact Set.mem_iUnion.mpr ⟨Sum.inr (⟨i,hs⟩,false),hr⟩ + · exact Set.mem_iUnion.mpr ⟨Sum.inl ⟨i,hs⟩,hi⟩ + +theorem deleted_positive_union (p : I → SimplePathPiece G) (v : V) : + (⋃ j : {j : DeleteIndex p v // 0 < (deleted p v j).walk.length}, + (deleted p v j.val).walk.edgeSet) = + {e | (∃ i, e ∈ (p i).walk.edgeSet) ∧ v ∉ e} := by + rw [← deleted_union p v] + ext e + constructor + · intro he + obtain ⟨j,hj⟩ := Set.mem_iUnion.mp he + exact Set.mem_iUnion.mpr ⟨j.val,hj⟩ + · intro he + obtain ⟨j,hj⟩ := Set.mem_iUnion.mp he + have hp : 0 < (deleted p v j).walk.length := by + by_contra hn + have hz : (deleted p v j).walk.length = 0 := by omega + have hn' := SimpleGraph.Walk.length_eq_zero_iff.mp hz + have he' := SimpleGraph.Walk.edges_eq_nil.mpr hn' + have hmem : e ∈ (deleted p v j).walk.edges := hj + exact List.not_mem_nil (he' ▸ hmem) + exact Set.mem_iUnion.mpr ⟨⟨j,hp⟩,hj⟩ + +def deletedInduced (p : I → SimplePathPiece G) (v : V) + (j : {j : DeleteIndex p v // 0 < (deleted p v j).walk.length}) : + SimplePathPiece (G.induce {x | x ≠ v}) := by + let q := deleted p v j.val + have havo : ∀ x ∈ q.walk.support, x ∈ ({x | x ≠ v} : Set V) := by + intro x hx he + subst x + exact deleted_positive_avoids p v j.val j.property hx + exact ⟨_,_, q.walk.induce _ havo, by + apply SimpleGraph.Walk.IsPath.of_map (f := (SimpleGraph.Embedding.induce _).toHom) + simpa using q.isPath⟩ + +end SimplePathPiece + +end +end ErdosGallai +end +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/CycleDecomposition/PrefixSelection.lean b/lean/OAI/Combinatorics/CycleDecomposition/PrefixSelection.lean new file mode 100644 index 0000000000000000000000000000000000000000..693db2faeb17a920491a92184048a7ba489e96ae --- /dev/null +++ b/lean/OAI/Combinatorics/CycleDecomposition/PrefixSelection.lean @@ -0,0 +1,111 @@ +import OAI.Combinatorics.CycleDecomposition.BatchIndexing + +namespace OAI + +section +open Filter Asymptotics Real +open scoped Topology +noncomputable section +open MeasureTheory ProbabilityTheory Finset +section + +namespace ErdosGallai +noncomputable section +open Finset + +theorem prefix_selection (S : ℕ → ℝ) (hS : ∀ j, 0 ≤ S j) (K N : ℕ) + (hsupp : ∀ j, N ≤ j → S j = 0) (hne : ∃ j, 0 < S j) : + ∃ i, 0 < S i ∧ ∑ j ∈ range (i+K+1), S j ≤ 4*(K+1:ℝ)*S i := by + let A := (range N).filter (fun j => 0 < S j) + have hA : A.Nonempty := by + obtain ⟨j,hj⟩ := hne + exact ⟨j, by + simp only [A, mem_filter, mem_range] + exact ⟨by by_contra hn; rw [hsupp j (by omega)] at hj; linarith, hj⟩⟩ + let i₀ := A.min' hA + have hi₀A : i₀ ∈ A := A.min'_mem hA + have hi₀pos : 0 < S i₀ := (mem_filter.mp hi₀A).2 + have hstart : (∑ j ∈ range (i₀+1), S j) = S i₀ := by + apply sum_eq_single i₀ + · intro j hj hji + by_contra hjzero + have hjpos : 0 < S j := lt_of_le_of_ne (hS j) (Ne.symm hjzero) + have hjA : j ∈ A := by + simp only [A, mem_filter, mem_range] + refine ⟨?_, hjpos⟩ + have hiN := (mem_range.mp (mem_filter.mp hi₀A).1) + have hjle := mem_range.mp hj + omega + have hmin : i₀ ≤ j := A.min'_le j hjA + have hjle := mem_range.mp hj + omega + · intro hi + exact (hi (by simp)).elim + let B := A.filter (fun i => (∑ j ∈ range (i+1), S j) ≤ 2*(K+1:ℝ)*S i) + have hB : B.Nonempty := by + refine ⟨i₀, mem_filter.mpr ⟨hi₀A, ?_⟩⟩ + rw [hstart] + have hK : (0:ℝ) ≤ K := Nat.cast_nonneg K + nlinarith + let i := B.max' hB + have hiB : i ∈ B := B.max'_mem hB + have hiA : i ∈ A := (mem_filter.mp hiB).1 + have hipos : 0 < S i := (mem_filter.mp hiA).2 + have hinv : (∑ j ∈ range (i+1), S j) ≤ 2*(K+1:ℝ)*S i := (mem_filter.mp hiB).2 + refine ⟨i, hipos, ?_⟩ + by_contra hfail + have hfail' : 4*(K+1:ℝ)*S i < ∑ j ∈ range (i+K+1), S j := lt_of_not_ge hfail + have hwindow : 2*(K+1:ℝ)*S i < ∑ j ∈ Ico (i+1) (i+K+1), S j := by + have hsplit := Finset.sum_range_add_sum_Ico S (by omega : i+1 ≤ i+K+1) + linarith + have hwindow_nonempty : (Ico (i+1) (i+K+1)).Nonempty := by + by_contra hh + rw [Finset.not_nonempty_iff_eq_empty.mp hh] at hwindow + simp only [sum_empty] at hwindow + have hK : (0:ℝ) ≤ K := Nat.cast_nonneg K + nlinarith + obtain ⟨j,hjw,hmax⟩ := Finset.exists_max_image (Ico (i+1) (i+K+1)) S hwindow_nonempty + have hsum : (∑ l ∈ Ico (i+1) (i+K+1), S l) ≤ (K:ℝ)*S j := by + calc + _ ≤ ∑ _l ∈ Ico (i+1) (i+K+1), S j := sum_le_sum hmax + _ = _ := by simp [] + have hdouble : 2*S i < S j := by + have hK : (0:ℝ) ≤ K := Nat.cast_nonneg K + nlinarith + have hjpos : 0 < S j := by linarith + have hjA : j ∈ A := by + simp only [A, mem_filter, mem_range] + exact ⟨by by_contra hjN; rw [hsupp j (by omega)] at hjpos; linarith, hjpos⟩ + have hjbounds := Finset.mem_Ico.mp hjw + have hpartial : (∑ l ∈ Ico (i+1) (j+1), S l) ≤ (K:ℝ)*S j := by + calc + _ ≤ ∑ l ∈ Ico (i+1) (i+K+1), S l := by + apply sum_le_sum_of_subset_of_nonneg + · intro l hl + simp only [mem_Ico] at hl ⊢ + omega + · intro l _ _; exact hS l + _ ≤ _ := hsum + have hjinv : (∑ l ∈ range (j+1), S l) ≤ 2*(K+1:ℝ)*S j := by + have hsplit := Finset.sum_range_add_sum_Ico S (by omega : i+1 ≤ j+1) + have hK : (0:ℝ) ≤ K := Nat.cast_nonneg K + nlinarith + have hjB : j ∈ B := mem_filter.mpr ⟨hjA,hjinv⟩ + have hji : j ≤ i := B.le_max' j hjB + omega + +end +end ErdosGallai + +end + +namespace ErdosGallai + +def MainStatement : Prop := + ∃ C : ℝ, 0 < C ∧ ∀ (n : ℕ) (G : SimpleGraph (Fin n)), + ∃ k : ℕ, EdgeDecomposition G k ∧ (k : ℝ) ≤ C * n +end ErdosGallai +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/CycleDecomposition/Representatives.lean b/lean/OAI/Combinatorics/CycleDecomposition/Representatives.lean new file mode 100644 index 0000000000000000000000000000000000000000..2c54ea107a6e0e07556657af4b728a3baddd8eb3 --- /dev/null +++ b/lean/OAI/Combinatorics/CycleDecomposition/Representatives.lean @@ -0,0 +1,264 @@ +import OAI.Combinatorics.CycleDecomposition.EdgeSplitting + +namespace OAI + +universe cycleUniverse1 cycleUniverse2 + +section +open Filter Asymptotics Real +open scoped Topology +noncomputable section +open MeasureTheory ProbabilityTheory Finset +noncomputable section +namespace ErdosGallai.Representatives +noncomputable section +open Finset +variable {I : Type cycleUniverse1} {V : Type cycleUniverse2} [DecidableEq I] [DecidableEq V] [Nonempty V] + +lemma choose_with_mates (A : Finset I) (mate : I → I) + (hmate : Function.Involutive mate) (hfix : ∀ i, mate i ≠ i) + (N : I → Finset V) (k : ℕ) + (hroom : ∀ i ∈ A, A.card ≤ ((N i).card - 1) * k) : + ∃ f : I → V, (∀ i ∈ A, f i ∈ N i) ∧ + (∀ i ∈ A, mate i ∈ A → f i ≠ f (mate i)) ∧ + (∀ v, (A.filter (fun i => f i = v)).card ≤ k) := by + induction A using Finset.induction_on with + | empty => exact ⟨fun _ => Classical.choice inferInstance, by simp⟩ + | @insert i A hi ih => + obtain ⟨f,hf,hsep,hcap⟩ := ih (by + intro j hj + exact (Finset.card_le_card (Finset.subset_insert i A)).trans (hroom j (by simp [hj]))) + have hlt : A.card < ((N i).erase (f (mate i))).card * k := by + have h := hroom i (by simp) + have hcard := Finset.pred_card_le_card_erase (s := N i) (a := f (mate i)) + have hmul := Nat.mul_le_mul_right k hcard + rw [Finset.card_insert_of_notMem hi] at h + omega + obtain ⟨v,hv,hload⟩ := Finset.exists_card_fiber_lt_of_card_lt_mul (f := f) hlt + have hvN := (Finset.mem_erase.mp hv).2 + have hvne := (Finset.mem_erase.mp hv).1 + let g := Function.update f i v + have gi : g i = v := by simp [g] + have gold : ∀ j, j ≠ i → g j = f j := by + intro j hj + simp [g, hj] + refine ⟨g, ?_, ?_, ?_⟩ + · intro j hj + rcases Finset.mem_insert.mp hj with rfl | hj + · simpa only [gi] using hvN + · rw [gold j (ne_of_mem_of_not_mem hj hi)] + exact hf j hj + · intro j hj hmj + by_cases hji : j = i + · subst j + rw [gi, gold (mate i) (hfix i)] + exact hvne + · rw [gold j hji] + by_cases hmi : mate j = i + · rw [hmi, gi] + have hjm : j = mate i := by rw [← hmi, hmate] + simpa [hjm] using hvne.symm + · rw [gold (mate j) hmi] + exact hsep j (Finset.mem_of_mem_insert_of_ne hj hji) + (Finset.mem_of_mem_insert_of_ne hmj hmi) + · intro w + have hold : A.filter (fun j => g j = w) = A.filter (fun j => f j = w) := by + apply Finset.filter_congr + intro j hj + rw [gold j (ne_of_mem_of_not_mem hj hi)] + rw [Finset.filter_insert, hold] + by_cases hvw : v = w + · simp only [gi, hvw, ite_eq_left] + rw [Finset.card_insert_of_notMem (fun h => hi (Finset.mem_filter.mp h).1)] + simpa only [hvw] using Nat.succ_le_of_lt hload + · simp only [gi, hvw, ite_false] + exact hcap w + +theorem two_distinct_representatives (S : Finset I) (N : I → Finset V) (k : ℕ) + (hroom : ∀ i ∈ S, 2*S.card ≤ ((N i).card-1)*k) : + ∃ f : I × Fin 2 → V, + (∀ i ∈ S, ∀ t, f (i,t) ∈ N i) ∧ + (∀ i ∈ S, f (i,0) ≠ f (i,1)) ∧ + (∀ v, ((S ×ˢ Finset.univ).filter (fun i => f i = v)).card ≤ k) := by + let mate : I × Fin 2 → I × Fin 2 := fun i => (i.1, 1-i.2) + have hm : Function.Involutive mate := by + rintro ⟨i,t⟩ + fin_cases t <;> rfl + have hfix : ∀ i, mate i ≠ i := by + rintro ⟨i,t⟩ + fin_cases t <;> (intro h; have hh := congrArg Prod.snd h; norm_num [mate] at hh) + obtain ⟨f,hf,hsep,hcap⟩ := choose_with_mates (S ×ˢ Finset.univ) mate hm hfix + (fun i => N i.1) k (by + intro i hi + simpa [Finset.card_product, mul_comm] using hroom i.1 (Finset.mem_product.mp hi).1) + refine ⟨f, ?_, ?_, hcap⟩ + · intro i hi t + exact hf (i,t) (by simp [hi]) + · intro i hi + exact hsep (i,0) (by simp [hi]) (by simp [mate, hi]) + +theorem reservoir_representatives (S : Finset I) (N : I → Finset V) + (r d : ℝ) (hr : (S.card : ℝ) ≤ r) (hd : 4 ≤ d) + (hN : ∀ i ∈ S, d/2 ≤ ((N i).card : ℝ)) : + ∃ f : I × Fin 2 → V, + (∀ i ∈ S, ∀ t, f (i,t) ∈ N i) ∧ + (∀ i ∈ S, f (i,0) ≠ f (i,1)) ∧ + (∀ v, ((S ×ˢ Finset.univ).filter (fun i => f i = v)).card ≤ ⌈8*r/d⌉₊) := by + apply two_distinct_representatives + intro i hi + have hd0 : 0 < d := by linarith + have hr0 : 0 ≤ r := le_trans (Nat.cast_nonneg _) hr + have hNi := hN i hi + have hNi1 : 1 ≤ (N i).card := by exact_mod_cast (by linarith : (1 : ℝ) ≤ (N i).card) + have hn : d/4 ≤ (((N i).card - 1 : ℕ) : ℝ) := by + rw [Nat.cast_sub hNi1] + push_cast + linarith + have hk : 8*r/d ≤ (⌈8*r/d⌉₊ : ℝ) := Nat.le_ceil _ + have hk0 : 0 ≤ (⌈8*r/d⌉₊ : ℝ) := Nat.cast_nonneg _ + have hprod : 2*(S.card : ℝ) ≤ (((N i).card - 1 : ℕ) : ℝ)*(⌈8*r/d⌉₊ : ℝ) := by + calc + _ ≤ 2*r := by linarith + _ = (d/4)*(8*r/d) := by field_simp; ring + _ ≤ (d/4)*(⌈8*r/d⌉₊ : ℝ) := mul_le_mul_of_nonneg_left hk (by positivity) + _ ≤ _ := mul_le_mul_of_nonneg_right hn hk0 + exact_mod_cast hprod + +end +end ErdosGallai.Representatives + +namespace ErdosGallai +noncomputable section +open Finset Real Filter +attribute [local instance] Classical.propDecidable + +noncomputable def reservoirProbability (η : ℝ) : ℝ := min (η/12) (1/12) +noncomputable def reservoirExpansionCoefficient (c : ℝ) : ℝ := min c 1 / 6 + +universe u + +theorem reservoir_preparation (c η : ℝ) (hc : 0 < c) (hη : 0 < η) : + ∃ D₀ : ℝ, ∀ D : ℝ, D₀ ≤ D → ∀ (V : Type u) [Fintype V] [DecidableEq V] + (G P : SimpleGraph V) [DecidableRel P.Adj], P ≤ G → + D^(9/10 : ℝ) ≤ (Fintype.card V : ℝ) → + (Fintype.card V : ℝ) ≤ D^(51/50 : ℝ) → + Splitting.CutExpansion P (c*D^(9/10 : ℝ)) → + ∃ (ω : Sym2 V → Fin 3) (W : Fin 3 → Finset V) (f : Fin 3 → V × Fin 2 → V), + (∀ i, Splitting.colorGraph P ω i ≤ G) ∧ + (∀ i j, i ≠ j → Disjoint (Splitting.colorGraph P ω i).edgeSet + (Splitting.colorGraph P ω j).edgeSet) ∧ + (∀ i, Splitting.CutExpansion (Splitting.colorGraph P ω i) + (reservoirExpansionCoefficient c * D^(9/10 : ℝ))) ∧ + (∀ i j, i ≠ j → Disjoint (W i) (W j)) ∧ + (∀ i, 2 ≤ (W i).card) ∧ + (∀ i, ((W i).card : ℝ) ≤ 2*reservoirProbability η*Fintype.card V) ∧ + (∀ i, (W i).card < Fintype.card V) ∧ + ((∑ i, (W i).card : ℕ) : ℝ) ≤ η * Fintype.card V ∧ + (∀ i, Sampling.CutExpansionOn (Splitting.colorGraph P ω i) (W i) + (D^(37/50 : ℝ))) ∧ + (∀ i v, v ∉ W i → ∀ t, f i (v,t) ∈ W i ∧ + (Splitting.colorGraph P ω i).Adj v (f i (v,t))) ∧ + (∀ i v, v ∉ W i → f i (v,0) ≠ f i (v,1)) ∧ + (∀ i w, (((W i)ᶜ ×ˢ Finset.univ).filter (fun x => f i x = w)).card ≤ + ⌈8*(Fintype.card V : ℝ) / + (reservoirProbability η * (reservoirExpansionCoefficient c * D^(9/10 : ℝ)))⌉₊) := by + let c₀ := min c 1 + let a := reservoirExpansionCoefficient c + let q := reservoirProbability η + have hc₀ : 0 < c₀ := lt_min hc (by norm_num) + have ha : 0 < a := by dsimp [a, reservoirExpansionCoefficient]; positivity + have hq : 0 < q := by dsimp [q, reservoirProbability]; positivity + have hq12 : q ≤ 1/12 := min_le_right _ _ + have hqη : q ≤ η/12 := min_le_left _ _ + have hq3 : 3*q ≤ 1 := by linarith + have hq6 : 6*q ≤ η := by linarith + have hq2 : 2*q < 1 := by linarith + let p : unitInterval := ⟨q, hq.le, by linarith⟩ + obtain ⟨D₁,hD₁⟩ := Splitting.edge_splitting_uniform.{u} c₀ hc₀ 3 (by norm_num) + obtain ⟨D₂,hD₂⟩ := Sampling.three_reservoirs_uniform.{u} a ha p hq hq3 + have ht : ∀ᶠ D : ℝ in atTop, 4/(q*a) ≤ D^(9/10 : ℝ) := + (tendsto_rpow_atTop (by norm_num : (0 : ℝ) < 9/10)).eventually + (eventually_ge_atTop _) + obtain ⟨D₃,hD₃⟩ := ht.exists_forall_of_atTop + refine ⟨max 1 (max D₁ (max D₂ D₃)), ?_⟩ + intro D hD V _ _ G P _ hPG hlo hhi hexp + have hD1 : 1 ≤ D := (le_max_left _ _).trans hD + have hDsplit : D₁ ≤ D := (le_trans (le_max_left _ _) (le_max_right _ _)).trans hD + have hDsample : D₂ ≤ D := + (le_trans (le_max_left _ _) (le_trans (le_max_right _ _) (le_max_right _ _))).trans hD + have hDpower : D₃ ≤ D := + (le_trans (le_max_right _ _) (le_trans (le_max_right _ _) (le_max_right _ _))).trans hD + have hpow : 0 < D^(9/10 : ℝ) := Real.rpow_pos_of_pos (by linarith) _ + have hd : 4 ≤ q*(a*D^(9/10 : ℝ)) := by + have hh := (div_le_iff₀ (mul_pos hq ha)).mp (hD₃ D hDpower) + nlinarith + have hr : 0 < (Fintype.card V : ℝ) := hpow.trans_le hlo + have : Nonempty V := Fintype.card_pos_iff.mp (by exact_mod_cast hr) + have hexp₀ : Splitting.CutExpansion P (c₀*D^(9/10 : ℝ)) := by + intro U + exact (mul_le_mul_of_nonneg_right + (mul_le_mul_of_nonneg_right (min_le_left c 1) hpow.le) + (le_min (Nat.cast_nonneg _) (Nat.cast_nonneg _))).trans (hexp U) + obtain ⟨ω,hcut,hcover,hdisj⟩ := hD₁ D hDsplit V P + (c₀*D^(9/10 : ℝ)) le_rfl hlo hhi hexp₀ + have hcut' : ∀ i, Sampling.CutExpansion (Splitting.colorGraph P ω i) + (a*D^(9/10 : ℝ)) := by + intro i + have heq : a*D^(9/10 : ℝ) = c₀*D^(9/10 : ℝ)/(2*(3 : ℝ)) := by + dsimp [a, reservoirExpansionCoefficient, c₀] + ring + rw [heq] + exact hcut i + obtain ⟨W,hWdisj,hWsize,hWneigh,hWcut⟩ := hD₂ D hDsample V + (fun i => Splitting.colorGraph P ω i) hlo hhi hcut' + have hWtwo : ∀ i, 2 ≤ (W i).card := by + intro i + let v : V := Classical.choice inferInstance + have hn := hWneigh i v + have hsub : Sampling.neighborsIn (Splitting.colorGraph P ω i) v (W i) ⊆ W i := + Finset.filter_subset _ _ + have hh := Finset.card_le_card hsub + have hn' : (2 : ℝ) ≤ (Sampling.neighborsIn (Splitting.colorGraph P ω i) v (W i)).card := by + change q*(a*D^(9/10 : ℝ))/2 ≤ _ at hn + linarith + have hn'' : 2 ≤ (Sampling.neighborsIn (Splitting.colorGraph P ω i) v (W i)).card := by + exact_mod_cast hn' + omega + have hWlt : ∀ i, (W i).card < Fintype.card V := by + intro i + have hh := (hWsize i).trans_lt (mul_lt_of_lt_one_left hr hq2) + exact_mod_cast hh + have hWsum : ((∑ i, (W i).card : ℕ) : ℝ) ≤ η * Fintype.card V := by + have hh := Finset.sum_le_sum (fun i (_ : i ∈ (Finset.univ : Finset (Fin 3))) => hWsize i) + simp only [Finset.sum_const, Finset.card_univ, Fintype.card_fin, nsmul_eq_mul] at hh + rw [Nat.cast_sum] + exact hh.trans (by dsimp [p]; nlinarith [mul_le_mul_of_nonneg_right hq6 hr.le]) + have hrep : ∀ i, ∃ f : V × Fin 2 → V, + (∀ v ∈ (W i)ᶜ, ∀ t, f (v,t) ∈ Sampling.neighborsIn (Splitting.colorGraph P ω i) v (W i)) ∧ + (∀ v ∈ (W i)ᶜ, f (v,0) ≠ f (v,1)) ∧ + (∀ w, (((W i)ᶜ ×ˢ Finset.univ).filter (fun x => f x = w)).card ≤ + ⌈8*(Fintype.card V : ℝ)/(q*(a*D^(9/10 : ℝ)))⌉₊) := by + intro i + exact Representatives.reservoir_representatives (W i)ᶜ + (fun v => Sampling.neighborsIn (Splitting.colorGraph P ω i) v (W i)) + (Fintype.card V) (q*(a*D^(9/10 : ℝ))) + (by exact_mod_cast (Finset.card_le_univ ((W i)ᶜ))) hd + (fun v _ => hWneigh i v) + choose f hf hsep hcap using hrep + refine ⟨ω,W,f,?_,hdisj,?_,hWdisj,hWtwo,hWsize,hWlt,hWsum,hWcut,?_,?_,hcap⟩ + · intro i x y hxy + exact hPG hxy.1 + · exact hcut' + · intro i v hv t + exact Finset.mem_filter.mp (hf i v (Finset.mem_compl.mpr hv) t) + · intro i v hv + exact hsep i v (Finset.mem_compl.mpr hv) + +end +end ErdosGallai + +end +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/CycleDecomposition/ReservoirCycles.lean b/lean/OAI/Combinatorics/CycleDecomposition/ReservoirCycles.lean new file mode 100644 index 0000000000000000000000000000000000000000..6035f81a94659ed76f9c37ca47d50a7807dba5ae --- /dev/null +++ b/lean/OAI/Combinatorics/CycleDecomposition/ReservoirCycles.lean @@ -0,0 +1,775 @@ +import OAI.Combinatorics.CycleDecomposition.Routing + +namespace OAI + +universe cycleUniverse1 cycleUniverse2 cycleUniverse3 cycleUniverse4 cycleUniverse5 cycleUniverse6 cycleUniverse7 cycleUniverse8 cycleUniverse9 cycleUniverse10 cycleUniverse11 cycleUniverse12 cycleUniverse13 cycleUniverse14 cycleUniverse15 cycleUniverse16 cycleUniverse17 cycleUniverse18 cycleUniverse19 + +section +open Filter Asymptotics Real +open scoped Topology +noncomputable section +open MeasureTheory ProbabilityTheory Finset +noncomputable section +namespace ErdosGallai +noncomputable section +open Real Filter Asymptotics + +lemma routing_length_upper (r h : ℝ) (hr : 2 ≤ r) (hh : 0 < h) (hhr : h ≤ r) : + (routingLength r h : ℝ) ≤ 108*(r/h)*(logb 2 r)^2 := by + have hr0 : 0 < r := by linarith + have hl : 1 ≤ logb 2 r := by + simpa using Real.logb_le_logb_of_le (by norm_num : (1:ℝ) < 2) + (by norm_num : (0:ℝ) < 2) hr + have hR : 1 ≤ r/h := (le_div_iff₀ hh).mpr (by simpa using hhr) + have hlog : logb 2 (2*r) = 1 + logb 2 r := by + rw [Real.logb_mul (by norm_num) hr0.ne'] + norm_num + have hg := Nat.ceil_lt_add_one (show 0 ≤ 8*(r/h)*logb 2 (2*r) by rw [hlog]; positivity) + have hd := Nat.ceil_lt_add_one (show 0 ≤ logb 2 r by linarith) + change (routingG r h : ℝ) < 8*(r/h)*logb 2 (2*r)+1 at hg + change (routingDepth r : ℝ) < logb 2 r + 1 at hd + rw [hlog] at hg + have hprod : 1 ≤ (r/h)*logb 2 r := by + nlinarith [mul_nonneg (sub_nonneg.mpr hR) (sub_nonneg.mpr hl)] + have hg' : (routingG r h : ℝ) ≤ 18*(r/h)*logb 2 r := by nlinarith + have hd' : (1 + routingDepth r : ℝ) ≤ 3*logb 2 r := by linarith + have hm := mul_le_mul hg' hd' (by positivity) (by positivity) + dsimp [routingLength] + push_cast + nlinarith + +lemma eventually_logb_le_power (ε : ℝ) (hε : 0 < ε) : + ∀ᶠ D : ℝ in atTop, logb 2 D ≤ D^ε := by + have ho := (isLittleO_log_rpow_atTop hε).const_mul_left (1 / log 2) + filter_upwards [ho.eventuallyLE, eventually_ge_atTop (1:ℝ)] with D hD h1 + simpa [Real.logb, div_eq_mul_inv, mul_comm, Real.norm_eq_abs, + abs_of_nonneg (Real.log_nonneg h1), abs_of_nonneg (Real.rpow_nonneg (by linarith) ε), + abs_of_pos (show 0 < (log 2)⁻¹ by positivity), + abs_of_pos (Real.log_pos (by norm_num : (1:ℝ) < 2))] using hD + +lemma eventually_constant_le_power (C ε : ℝ) (hε : 0 < ε) : + ∀ᶠ D : ℝ in atTop, C ≤ D^ε := + (tendsto_rpow_atTop hε).eventually (eventually_ge_atTop C) + +lemma eventually_const_mul_power_le (C α β : ℝ) (hab : α < β) : + ∀ᶠ D : ℝ in atTop, C*D^α ≤ D^β := by + filter_upwards [eventually_constant_le_power C (β-α) (by linarith), + eventually_gt_atTop (0:ℝ)] with D hc hD + calc + C*D^α ≤ D^(β-α)*D^α := mul_le_mul_of_nonneg_right hc (Real.rpow_nonneg hD.le _) + _ = D^β := by rw [← Real.rpow_add hD]; congr 1; ring + +theorem eventually_routing_length (c β γ δ : ℝ) (hc : 0 < c) (hβ : 0 < β) + (hδ : 0 < δ) : + ∀ᶠ D : ℝ in atTop, ∀ r : ℝ, 2 ≤ r → r ≤ D^β → c*D^γ ≤ r → + (routingLength r (c*D^γ) : ℝ) ≤ D^(β-γ+δ) := by + filter_upwards [eventually_logb_le_power (δ/4) (by positivity), + eventually_constant_le_power (108*β^2/c) (δ/2) (by positivity), + eventually_gt_atTop (1:ℝ)] with D hlog hconst hD r hr hrD hhr + have hD0 : 0 < D := by linarith + have hpowγ : 0 < D^γ := Real.rpow_pos_of_pos hD0 _ + have hden : 0 < c*D^γ := mul_pos hc hpowγ + have hlog0 : 0 ≤ logb 2 r := (Real.logb_pos (by norm_num) (by linarith)).le + have hlogR : logb 2 r ≤ β*D^(δ/4) := by + have hh := Real.logb_le_logb_of_le (by norm_num : (1:ℝ) < 2) + (by linarith : 0 < r) hrD + rw [Real.logb_rpow_eq_mul_logb_of_pos hD0] at hh + exact hh.trans (mul_le_mul_of_nonneg_left hlog hβ.le) + have hratio : r/(c*D^γ) ≤ D^(β-γ)/c := by + calc + _ ≤ D^β/(c*D^γ) := div_le_div_of_nonneg_right hrD hden.le + _ = _ := by rw [Real.rpow_sub hD0]; ring + have hsq : (logb 2 r)^2 ≤ β^2*D^(δ/2) := by + calc + _ ≤ (β*D^(δ/4))^2 := pow_le_pow_left₀ hlog0 hlogR 2 + _ = _ := by rw [mul_pow, ← Real.rpow_mul_natCast hD0.le]; congr 2; ring + calc + (routingLength r (c*D^γ) : ℝ) ≤ 108*(r/(c*D^γ))*(logb 2 r)^2 := + routing_length_upper r (c*D^γ) hr hden hhr + _ ≤ 108*(D^(β-γ)/c)*(β^2*D^(δ/2)) := by gcongr + _ = (108*β^2/c)*D^(β-γ+δ/2) := by rw [Real.rpow_add hD0]; ring + _ ≤ D^(δ/2)*D^(β-γ+δ/2) := + mul_le_mul_of_nonneg_right hconst (Real.rpow_nonneg hD0.le _) + _ = D^(β-γ+δ) := by rw [← Real.rpow_add hD0]; congr 1; ring + +theorem batch_routing_margin : ∃ D₀ : ℝ, 1 < D₀ ∧ ∀ D ≥ D₀, + ∀ r : ℝ, D^(9/10:ℝ) ≤ r → r ≤ D^(51/50:ℝ) → + 2 ≤ r ∧ 64*((routingLength r (D^(9/10:ℝ)/4) : ℝ)^2* + (D^(1/100:ℝ)+D^(3/10:ℝ))+2*D^(3/10:ℝ)) ≤ D^(9/10:ℝ)/4 := by + have hev : ∀ᶠ D : ℝ in atTop, ∀ r : ℝ, D^(9/10:ℝ) ≤ r → r ≤ D^(51/50:ℝ) → + 2 ≤ r ∧ 64*((routingLength r (D^(9/10:ℝ)/4) : ℝ)^2* + (D^(1/100:ℝ)+D^(3/10:ℝ))+2*D^(3/10:ℝ)) ≤ D^(9/10:ℝ)/4 := by + filter_upwards [eventually_routing_length (1/4) (51/50) (9/10) (2/25) + (by norm_num) (by norm_num) (by norm_num), + eventually_const_mul_power_le 1024 (7/10) (9/10) (by norm_num), + eventually_constant_le_power 2 (9/10) (by norm_num), + eventually_gt_atTop (1:ℝ)] with D hlen hcost htwo hD r hr hrD + have hD0 : 0 < D := by linarith + have hr2 : 2 ≤ r := htwo.trans hr + have hh : (1/4)*D^(9/10:ℝ) ≤ r := by + have hh0 := Real.rpow_nonneg hD0.le (9/10:ℝ) + linarith + have hL := hlen r hr2 hrD hh + norm_num at hL + have hL' : (routingLength r (D^(9/10:ℝ)/4) : ℝ) ≤ D^(1/5:ℝ) := by + convert hL using 1 ; ring_nf + have hsmall : D^(1/100:ℝ) ≤ D^(3/10:ℝ) := Real.rpow_le_rpow_of_exponent_le hD.le (by norm_num) + have h37 : D^(3/10:ℝ) ≤ D^(7/10:ℝ) := Real.rpow_le_rpow_of_exponent_le hD.le (by norm_num) + have hprod : (routingLength r (D^(9/10:ℝ)/4) : ℝ)^2* + (D^(1/100:ℝ)+D^(3/10:ℝ)) ≤ 2*D^(7/10:ℝ) := by + calc + _ ≤ (D^(1/5:ℝ))^2 * (2*D^(3/10:ℝ)) := by gcongr; linarith + _ = _ := by + rw [← Real.rpow_mul_natCast hD0.le] + norm_num + rw [mul_left_comm, ← Real.rpow_add hD0] + norm_num + refine ⟨hr2, ?_⟩ + nlinarith only [hprod, h37, hcost] + obtain ⟨A,hA⟩ := eventually_atTop.mp hev + refine ⟨max A 2, lt_of_lt_of_le (by norm_num) (le_max_right _ _), ?_⟩ + intro D hD + exact hA D ((le_max_left _ _).trans hD) + +lemma eventually_reservoir_capacity (c p : ℝ) (hc : 0 < c) (hp : 0 < p) : + ∀ᶠ D : ℝ in atTop, ∀ r : ℝ, 0 ≤ r → r ≤ D^(51/50:ℝ) → + (⌈8*r/(p*(c*D^(9/10:ℝ)))⌉₊ : ℝ) ≤ D^(13/100:ℝ) := by + filter_upwards [eventually_const_mul_power_le (8/(p*c)+1) (3/25) (13/100) (by norm_num), + eventually_gt_atTop (1:ℝ)] with D hbound hD r hr hrD + have hD0 : 0 < D := by linarith + have hden : 0 < p*(c*D^(9/10:ℝ)) := by positivity + have hone : 1 ≤ D^(3/25:ℝ) := Real.one_le_rpow hD.le (by norm_num) + have hx : 8*r/(p*(c*D^(9/10:ℝ))) ≤ (8/(p*c))*D^(3/25:ℝ) := by + calc + _ ≤ 8*D^(51/50:ℝ)/(p*(c*D^(9/10:ℝ))) := by gcongr + _ = _ := by + have heq : D^(3/25:ℝ) = D^(51/50:ℝ)/D^(9/10:ℝ) := by + rw [← Real.rpow_sub hD0]; norm_num + rw [heq]; ring + have hceil := Nat.ceil_lt_add_one (show 0 ≤ 8*r/(p*(c*D^(9/10:ℝ))) by positivity) + nlinarith only [hx, hceil, hone, hbound] + +theorem residue_routing_margin (c p : ℝ) (hc : 0 < c) (hp : 0 < p) : + ∃ D₀ : ℝ, 1 < D₀ ∧ ∀ D ≥ D₀, ∀ r rᵢ : ℝ, + 0 ≤ r → r ≤ D^(51/50:ℝ) → 2 ≤ rᵢ → rᵢ ≤ r → D^(37/50:ℝ) ≤ rᵢ → + 64*((routingLength rᵢ (D^(37/50:ℝ)) : ℝ)^2* + ((⌈8*r/(p*(c*D^(9/10:ℝ)))⌉₊ : ℝ)+1)) ≤ D^(37/50:ℝ) := by + have hev : ∀ᶠ D : ℝ in atTop, ∀ r rᵢ : ℝ, + 0 ≤ r → r ≤ D^(51/50:ℝ) → 2 ≤ rᵢ → rᵢ ≤ r → D^(37/50:ℝ) ≤ rᵢ → + 64*((routingLength rᵢ (D^(37/50:ℝ)) : ℝ)^2* + ((⌈8*r/(p*(c*D^(9/10:ℝ)))⌉₊ : ℝ)+1)) ≤ D^(37/50:ℝ) := by + filter_upwards [eventually_routing_length 1 (51/50) (37/50) (1/100) + (by norm_num) (by norm_num) (by norm_num), + eventually_reservoir_capacity c p hc hp, + eventually_const_mul_power_le 128 (71/100) (37/50) (by norm_num), + eventually_gt_atTop (1:ℝ)] with D hlen hcap hcost hD r rᵢ hr hrD hri2 hrir htau + have hD0 : 0 < D := by linarith + have hL := hlen rᵢ hri2 (hrir.trans hrD) (by simpa using htau) + norm_num at hL + have hk := hcap r hr hrD + have hone : 1 ≤ D^(13/100:ℝ) := Real.one_le_rpow hD.le (by norm_num) + have hprod : (routingLength rᵢ (D^(37/50:ℝ)) : ℝ)^2* + ((⌈8*r/(p*(c*D^(9/10:ℝ)))⌉₊ : ℝ)+1) ≤ 2*D^(71/100:ℝ) := by + calc + _ ≤ (D^(29/100:ℝ))^2 * (2*D^(13/100:ℝ)) := by gcongr; linarith + _ = _ := by + rw [← Real.rpow_mul_natCast hD0.le] + norm_num + rw [mul_left_comm, ← Real.rpow_add hD0] + norm_num + nlinarith only [hprod, hcost] + obtain ⟨A,hA⟩ := eventually_atTop.mp hev + refine ⟨max A 2, lt_of_lt_of_le (by norm_num) (le_max_right _ _), ?_⟩ + intro D hD + exact hA D ((le_max_left _ _).trans hD) + +end +end ErdosGallai + +namespace ErdosGallai +noncomputable section +open Finset +attribute [local instance] Classical.propDecidable + +variable {V : Type} [Fintype V] [DecidableEq V] + +def CutExpansionOn (P : SimpleGraph V) [DecidableRel P.Adj] (W : Finset V) (h : ℝ) : Prop := + ∀ A : Finset V, A ⊆ W → h * min (A.card : ℝ) ((W \ A).card : ℝ) ≤ + ((P.interedges A (W \ A)).card : ℝ) + +lemma subtype_image_compl {V : Type} [_contextInstance1 : Fintype V] [_contextInstance2 : DecidableEq V] (W : Finset V) (U : Finset (W : Set V)) : + Uᶜ.image Subtype.val = W \ U.image Subtype.val := by + ext v + simp only [Finset.mem_image, Finset.mem_compl, Finset.mem_sdiff] + constructor + · rintro ⟨x,hx,rfl⟩ + refine ⟨x.property,?_⟩ + rintro ⟨y,hy,he⟩ + exact hx (Subtype.ext he ▸ hy) + · rintro ⟨hv,hvU⟩ + refine ⟨⟨v,hv⟩,?_,rfl⟩ + intro hx + exact hvU ⟨⟨v,hv⟩,hx,rfl⟩ + +lemma induced_interedges_card (P : SimpleGraph V) [DecidableRel P.Adj] + (W : Finset V) (U : Finset (W : Set V)) : + (((P.induce (W : Set V)).interedges U Uᶜ).card : ℝ) = + ((P.interedges (U.image Subtype.val) (W \ U.image Subtype.val)).card : ℝ) := by + classical + let f : ↥(W : Set V) × ↥(W : Set V) → V × V := fun e => (e.1.val,e.2.val) + have hf : Function.Injective f := by + intro a b h + apply Prod.ext <;> apply Subtype.ext + · exact congrArg Prod.fst h + · exact congrArg Prod.snd h + have heq : ((P.induce (W : Set V)).interedges U Uᶜ).image f = + P.interedges (U.image Subtype.val) (W \ U.image Subtype.val) := by + rw [← subtype_image_compl W U] + ext e + simp only [SimpleGraph.mem_interedges_iff, Finset.mem_image] + constructor + · rintro ⟨a,⟨ha,hb,hab⟩,rfl⟩ + exact ⟨⟨a.1,ha,rfl⟩,⟨a.2,hb,rfl⟩,hab⟩ + · rintro ⟨⟨x,hx,hxe⟩,⟨y,hy,hye⟩,he⟩ + refine ⟨(x,y),⟨hx,hy,?_⟩,Prod.ext hxe hye⟩ + change P.Adj x.val y.val + simpa only [hxe,hye] using he + rw [← heq, Finset.card_image_of_injective _ hf] + +lemma cutExpansion_induce (P : SimpleGraph V) [DecidableRel P.Adj] + (W : Finset V) (h : ℝ) (hexp : CutExpansionOn P W h) : + CutExpansion (P.induce (W : Set V)) h := by + classical + intro U + have hsub : U.image Subtype.val ⊆ W := by + rintro v hv + obtain ⟨a,ha,rfl⟩ := Finset.mem_image.mp hv + exact a.property + have h := hexp (U.image Subtype.val) hsub + have he : W \ U.image Subtype.val = Uᶜ.image Subtype.val := + (subtype_image_compl W U).symm + rw [he] at h + simp only [Finset.card_image_of_injective _ Subtype.val_injective] at h + rw [induced_interedges_card,he] + exact h + +theorem routing_allow_equal {I : Type} [Fintype I] + (P : SimpleGraph V) [DecidableRel P.Adj] + (h : ℝ) (hh : 0 < h) (hexp : CutExpansion P h) (hr : 2 ≤ Fintype.card V) + (x y : I → V) (k : ℝ) (hk : 1 ≤ k) + (hload : ∀ v, (endpointLoad Finset.univ x y v : ℝ) ≤ k) + (hbudget : 64 * ((routingLength (Fintype.card V) h : ℝ)^2 * (k+1)) ≤ h) : + ∃ q : ∀ i, P.Walk (x i) (y i), + (∀ i, (q i).IsPath ∧ (q i).length ≤ routingLength (Fintype.card V) h) ∧ + (∀ i j, i ≠ j → Disjoint (q i).edges.toFinset (q j).edges.toFinset) := by + classical + let J := {i : I // x i ≠ y i} + have hjload (v : V) : + (endpointLoad Finset.univ (fun i : J => x i.val) (fun i : J => y i.val) v : ℝ) ≤ k := by + apply le_trans _ (hload v) + exact_mod_cast (show endpointLoad Finset.univ (fun i : J => x i.val) + (fun i : J => y i.val) v ≤ endpointLoad Finset.univ x y v from by + apply Finset.card_le_card_of_injOn Subtype.val + · intro a ha + exact Finset.mem_filter.mpr ⟨Finset.mem_univ _,(Finset.mem_filter.mp ha).2⟩ + · intro a _ b _ hab + exact Subtype.ext hab) + obtain ⟨q,hq,hd,_⟩ := routing P h hh hexp hr + (fun i : J => x i.val) (fun i : J => y i.val) (fun i => i.property) + (fun i : J => i) (fun _ => ∅) k 1 0 hk (by norm_num) (by norm_num) hjload + (by + intro i + have he : (univ.filter (fun j : J => j = i)) = {i} := by ext j; simp + rw [he]; simp) (by intro i; simp) (by simpa only [add_zero] using hbudget) + let Q : ∀ i, P.Walk (x i) (y i) := fun i => + if hi : x i = y i then (SimpleGraph.Walk.nil : P.Walk (x i) (x i)).copy rfl hi + else q ⟨i,hi⟩ + refine ⟨Q,?_,?_⟩ + · intro i + by_cases hi : x i = y i + · simp [Q,hi] + · simpa only [Q,dite_eq_right hi] using ⟨(hq ⟨i,hi⟩).1,(hq ⟨i,hi⟩).2.1⟩ + · intro i j hij + by_cases hi : x i = y i + · simp [Q,hi] + by_cases hj : x j = y j + · simp [Q,hj] + simp only [Q,dite_eq_right hi,dite_eq_right hj] + exact hd ⟨i,hi⟩ ⟨j,hj⟩ (fun he => hij (congrArg Subtype.val he)) + +theorem routing_in_reservoir {I : Type} [Fintype I] + (G P : SimpleGraph V) [DecidableRel P.Adj] (hPG : P ≤ G) + (W : Finset V) (h : ℝ) (hh : 0 < h) + (hexp : CutExpansionOn P W h) (hr : 2 ≤ W.card) + (x y : I → V) (hx : ∀ i, x i ∈ W) (hy : ∀ i, y i ∈ W) + (k : ℝ) (hk : 1 ≤ k) + (hload : ∀ v, (endpointLoad Finset.univ x y v : ℝ) ≤ k) + (hbudget : 64 * ((routingLength W.card h : ℝ)^2 * (k+1)) ≤ h) : + ∃ q : ∀ i, G.Walk (x i) (y i), + (∀ i, (q i).IsPath ∧ (q i).length ≤ routingLength W.card h ∧ + ∀ v ∈ (q i).support, v ∈ W) ∧ + Pairwise (fun i j => Disjoint (q i).edgeSet (q j).edgeSet) := by + classical + let X : I → (W : Set V) := fun i => ⟨x i,hx i⟩ + let Y : I → (W : Set V) := fun i => ⟨y i,hy i⟩ + have hl (v : (W : Set V)) : (endpointLoad univ X Y v : ℝ) ≤ k := by + simpa only [endpointLoad,X,Y,Subtype.ext_iff] using hload v.val + obtain ⟨q,hq,hd⟩ := routing_allow_equal (P.induce (W : Set V)) h hh + (cutExpansion_induce P W h hexp) (by simpa using hr) X Y k hk hl + (by simpa using hbudget) + let f : (P.induce (W : Set V)) →g G := + { toFun := Subtype.val, map_rel' := fun ha => hPG ha } + have hf : Function.Injective f := Subtype.val_injective + have hcard : Fintype.card ↥(W : Set V) = W.card := Fintype.card_coe W + let Q : ∀ i, G.Walk (x i) (y i) := fun i => (q i).map f + refine ⟨Q,?_,?_⟩ + · intro i + refine ⟨(hq i).1.map hf,?_,?_⟩ + · simpa only [Q,SimpleGraph.Walk.length_map, hcard] using (hq i).2 + · intro v hv + have hv' : v ∈ (q i).support.map f := by simpa only [Q,SimpleGraph.Walk.support_map] using hv + obtain ⟨a,ha,rfl⟩ := List.mem_map.mp hv' + exact a.property + · intro i j hij + change Disjoint ((q i).map f).edgeSet ((q j).map f).edgeSet + rw [SimpleGraph.Walk.edgeSet_map,SimpleGraph.Walk.edgeSet_map] + rw [Set.disjoint_image_iff (Sym2.map.injective hf)] + apply Set.disjoint_left.mpr + intro e he he' + exact Finset.disjoint_left.mp (hd i j hij) + (by simpa using he) (by simpa using he') + +theorem uniform_reservoir_routing (c p : ℝ) (hc : 0 < c) (hp : 0 < p) : + ∃ D₀ : ℝ, 1 < D₀ ∧ ∀ D ≥ D₀, + ∀ (V : Type) [Fintype V] [DecidableEq V], + ∀ (G P : SimpleGraph V) [DecidableRel P.Adj], P ≤ G → + ∀ W : Finset V, CutExpansionOn P W (D^(37/50:ℝ)) → 2 ≤ W.card → + (Fintype.card V : ℝ) ≤ D^(51/50:ℝ) → + ∀ (I : Type) [Fintype I] (x y : I → V), + (∀ i, x i ∈ W) → (∀ i, y i ∈ W) → + (∀ v, endpointLoad univ x y v ≤ + ⌈8*(Fintype.card V:ℝ)/(p*(c*D^(9/10:ℝ)))⌉₊) → + ∃ q : ∀ i, G.Walk (x i) (y i), + (∀ i, (q i).IsPath ∧ (q i).length ≤ routingLength W.card (D^(37/50:ℝ)) ∧ + ∀ v ∈ (q i).support, v ∈ W) ∧ + Pairwise (fun i j => Disjoint (q i).edgeSet (q j).edgeSet) := by + obtain ⟨D₀,hD₀,hmargin⟩ := residue_routing_margin c p hc hp + refine ⟨D₀,hD₀,?_⟩ + intro D hD V _ _ G P _ hPG W hexp hW hr I _ x y hx hy hl + have hDpos : 0 < D := lt_trans (by norm_num) (hD₀.trans_le hD) + have horder : (D^(37/50:ℝ)) ≤ (W.card : ℝ) := by + simpa using (cutExpansion_induce P W _ hexp).le_order (P.induce (W:Set V)) _ + (by simpa using hW) + have hWupper : (W.card : ℝ) ≤ (Fintype.card V : ℝ) := by + exact_mod_cast W.card_le_univ + have hrpos : 0 < (Fintype.card V : ℝ) := by + have hWreal : (2:ℝ) ≤ W.card := by exact_mod_cast hW + linarith + have hk : 1 ≤ (⌈8*(Fintype.card V:ℝ)/(p*(c*D^(9/10:ℝ)))⌉₊ : ℝ) := by + have hceil : 0 < ⌈8*(Fintype.card V:ℝ)/(p*(c*D^(9/10:ℝ)))⌉₊ := + Nat.ceil_pos.mpr (by positivity) + exact_mod_cast hceil + apply routing_in_reservoir G P hPG W (D^(37/50:ℝ)) (by positivity) hexp hW + x y hx hy _ hk (by intro v; exact_mod_cast hl v) + exact hmargin D hD _ _ hrpos.le hr (by exact_mod_cast hW) hWupper horder + +end +end ErdosGallai + +namespace ErdosGallai +noncomputable section +open Finset +attribute [local instance] Classical.propDecidable + +theorem occurrence_slots {A : Type cycleUniverse1} {V : Type cycleUniverse2} [Fintype A] (f : A → V) (k : ℕ) + (h : ∀ v, Fintype.card {a // f a = v} ≤ k) : + ∃ slot : A → Fin k, Function.Injective (fun a => (f a, slot a)) := by + classical + have he : ∀ v, Nonempty ({a // f a = v} ↪ Fin k) := by + intro v + exact Function.Embedding.nonempty_of_card_le (by simpa using h v) + let e := fun v => Classical.choice (he v) + refine ⟨fun a => e (f a) ⟨a,rfl⟩, ?_⟩ + intro a b hab + have hf : f a = f b := congrArg Prod.fst hab + have hs : e (f a) ⟨a,rfl⟩ = e (f b) ⟨b,rfl⟩ := congrArg Prod.snd hab + have hσ : (⟨f a, e (f a) ⟨a,rfl⟩⟩ : Σ _ : V, Fin k) = + ⟨f b, e (f b) ⟨b,rfl⟩⟩ := Sigma.ext hf (heq_of_eq hs) + let E : (Σ v, {a // f a = v}) ↪ (Σ _ : V, Fin k) := + Function.Embedding.sigmaMap (Function.Embedding.refl V) e + have heq : (⟨f a, ⟨a,rfl⟩⟩ : Σ v, {a // f a = v}) = ⟨f b, ⟨b,rfl⟩⟩ := + E.injective hσ + exact congrArg (fun z : Σ v, {a // f a = v} => z.2.val) heq + +def endpointOccurrence {I : Type cycleUniverse3} {V : Type cycleUniverse4} (x y : I → V) (a : I × Fin 2) : V := + if a.2 = 0 then x a.1 else y a.1 + +theorem endpoint_occurrence_slots {I : Type cycleUniverse5} {V : Type cycleUniverse6} [Fintype I] + (x y : I → V) (hne : ∀ i, x i ≠ y i) + (hload : ∀ v, (univ.filter (fun i => x i = v ∨ y i = v)).card ≤ 2) : + ∃ slot : I × Fin 2 → Fin 2, + Function.Injective (fun a => (endpointOccurrence x y a, slot a)) := by + classical + apply occurrence_slots + intro v + let f : {a : I × Fin 2 // endpointOccurrence x y a = v} → + {i : I // x i = v ∨ y i = v} := fun a => + ⟨a.val.1, by + by_cases h0 : a.val.2 = 0 + · exact Or.inl (by simpa [endpointOccurrence,h0] using a.property) + · exact Or.inr (by simpa [endpointOccurrence,h0] using a.property)⟩ + have hf : Function.Injective f := by + intro a b hab + apply Subtype.ext + have hi : a.val.1 = b.val.1 := congrArg Subtype.val hab + apply Prod.ext hi + by_contra ht + have hcases : (a.val.2 = 0 ∧ b.val.2 ≠ 0) ∨ (a.val.2 ≠ 0 ∧ b.val.2 = 0) := by + have ha := (a.val.2).isLt + have hb := (b.val.2).isLt + have hne : (a.val.2).val ≠ (b.val.2).val := fun h => ht (Fin.ext h) + simp only [Fin.ext_iff, Fin.val_zero] + omega + rcases hcases with h | h + · have ha : x a.val.1 = v := by simpa [endpointOccurrence,h.1] using a.property + have hb : y b.val.1 = v := by simpa [endpointOccurrence,h.2] using b.property + exact hne _ (ha.trans (hi ▸ hb).symm) + · have ha : y a.val.1 = v := by simpa [endpointOccurrence,h.1] using a.property + have hb : x b.val.1 = v := by simpa [endpointOccurrence,h.2] using b.property + exact hne _ ((hi ▸ hb).trans ha.symm) + exact (Fintype.card_le_of_injective f hf).trans (by simpa only [Fintype.card_subtype] using hload v) + +theorem reserved_edges_injective {A : Type cycleUniverse7} {V : Type cycleUniverse8} (S W : Set V) + (f : A → V) (slot : A → Fin 2) (r : V × Fin 2 → V) + (hslots : Function.Injective (fun a => (f a,slot a))) + (hout : ∀ a, f a ∈ S) (hin : ∀ v ∈ S, ∀ t, r (v,t) ∈ W) + (hdisj : Disjoint S W) (hr : ∀ v ∈ S, r (v,0) ≠ r (v,1)) : + Function.Injective (fun a => s(f a,r (f a,slot a))) := by + intro a b hab + rcases Sym2.eq_iff.mp hab with he | he + · have hf : f a = f b := he.1 + have hh : r (f a,slot a) = r (f b,slot b) := he.2 + apply hslots + apply Prod.ext hf + have hrinj : Function.Injective (fun t : Fin 2 => r (f a,t)) := by + intro i j hij + have h0 := hr (f a) (hout a) + fin_cases i <;> fin_cases j + · rfl + · exact (h0 hij).elim + · exact (h0 hij.symm).elim + · rfl + exact hrinj (by simpa only [hf] using hh) + · have hf : f a = r (f b,slot b) := he.1 + exact False.elim (Set.disjoint_left.mp hdisj (hout a) + (hf.symm ▸ hin (f b) (hout b) (slot b))) + +theorem assigned_representative_load {A : Type cycleUniverse9} {V : Type cycleUniverse10} [Fintype A] [DecidableEq V] + (S : Finset V) (f : A → V) (slot : A → Fin 2) (r : V × Fin 2 → V) + (hslots : Function.Injective (fun a => (f a,slot a))) + (hout : ∀ a, f a ∈ S) (k : ℕ) + (hcap : ∀ v, ((S ×ˢ univ).filter (fun a => r a = v)).card ≤ k) : + ∀ v, (univ.filter (fun a => r (f a,slot a) = v)).card ≤ k := by + classical + intro v + apply le_trans (Finset.card_le_card_of_injOn (fun a => (f a,slot a)) ?_ ?_) (hcap v) + · intro a ha + exact mem_filter.mpr ⟨mem_product.mpr ⟨hout a,mem_univ _⟩, (mem_filter.mp ha).2⟩ + · intro a _ b _ hab + exact hslots hab + +end +end ErdosGallai + +namespace ErdosGallai +noncomputable section +open Finset +attribute [local instance] Classical.propDecidable + +theorem choose_reservoir_endpoints {V I : Type} [Fintype V] [Fintype I] + [DecidableEq V] (P : SimpleGraph V) (W : Finset V) + (x y : I → V) (hne : ∀ i, x i ≠ y i) + (houtx : ∀ i, x i ∉ W) (houty : ∀ i, y i ∉ W) + (hload : ∀ v, endpointLoad univ x y v ≤ 2) + (r : V × Fin 2 → V) + (hr : ∀ v, v ∉ W → ∀ t, r (v,t) ∈ W ∧ P.Adj v (r (v,t))) + (hrne : ∀ v, v ∉ W → r (v,0) ≠ r (v,1)) + (k : ℕ) (hcap : ∀ v, ((Wᶜ ×ˢ univ).filter (fun z => r z = v)).card ≤ k) : + ∃ a b : I → V, + (∀ i, a i ∈ W ∧ P.Adj (x i) (a i)) ∧ + (∀ i, b i ∈ W ∧ P.Adj (y i) (b i)) ∧ + Function.Injective (fun z : I × Fin 2 => + if z.2 = 0 then s(x z.1,a z.1) else s(y z.1,b z.1)) ∧ + (∀ v, endpointLoad univ a b v ≤ k) ∧ + (∀ i, ∃ t, a i = r (x i,t)) ∧ (∀ i, ∃ t, b i = r (y i,t)) := by + classical + obtain ⟨slot,hslot⟩ := endpoint_occurrence_slots x y hne (fun v => by + convert hload v using 1 + congr 1 + ext i + simp only [ Finset.mem_filter, Finset.mem_univ, true_and]) + let occ := endpointOccurrence x y + have ho : ∀ z : I × Fin 2, occ z ∉ W := by + rintro ⟨i,t⟩ + by_cases h : t = 0 + · simpa [occ,endpointOccurrence,h] using houtx i + · simpa [occ,endpointOccurrence,h] using houty i + let a := fun i => r (x i,slot (i,0)) + let b := fun i => r (y i,slot (i,1)) + have hsp := reserved_edges_injective (Wᶜ : Finset V) W occ slot r hslot + (fun z => Finset.mem_compl.mpr (ho z)) + (fun v hv t => (hr v (Finset.mem_compl.mp hv) t).1) + (Set.disjoint_left.mpr (fun _ hv hw => (Finset.mem_compl.mp hv) hw)) + (fun v hv => hrne v (Finset.mem_compl.mp hv)) + have hcap' := assigned_representative_load Wᶜ occ slot r hslot + (fun z => Finset.mem_compl.mpr (ho z)) k hcap + refine ⟨a,b,(fun i => hr _ (houtx i) _),(fun i => hr _ (houty i) _),?_,?_,?_,?_⟩ + · have heq : (fun z : I × Fin 2 => + if z.2 = 0 then s(x z.1,a z.1) else s(y z.1,b z.1)) = + (fun z => s(occ z,r (occ z,slot z))) := by + funext z + rcases z with ⟨i,t⟩ + fin_cases t <;> simp [occ,endpointOccurrence,a,b] + rw [heq] + exact hsp + · intro v + apply le_trans (Finset.card_le_card_of_injOn + (fun i => (i,if a i = v then (0 : Fin 2) else 1)) ?_ ?_) (hcap' v) + · intro i hi + have hi' := (Finset.mem_filter.mp hi).2 + apply Finset.mem_filter.mpr + refine ⟨Finset.mem_univ _,?_⟩ + by_cases hi0 : a i = v + · simp [hi0,occ,endpointOccurrence,a] + · have hi1 : b i = v := hi'.resolve_left hi0 + simpa [hi0,occ,endpointOccurrence,b] using hi1 + · intro i hi j hj he + exact congrArg Prod.fst he + · intro i; exact ⟨slot (i,0),rfl⟩ + · intro i; exact ⟨slot (i,1),rfl⟩ + +theorem uniform_assigned_reservoir_routing (c p : ℝ) (hc : 0 < c) (hp : 0 < p) : + ∃ D₀ : ℝ, 1 < D₀ ∧ ∀ D ≥ D₀, + ∀ (V : Type) [Fintype V] [DecidableEq V], + ∀ (G P : SimpleGraph V) [DecidableRel P.Adj], P ≤ G → + ∀ W : Finset V, CutExpansionOn P W (D^(37/50:ℝ)) → 2 ≤ W.card → + (Fintype.card V : ℝ) ≤ D^(51/50:ℝ) → + ∀ (I : Type) [Fintype I] (x y : I → V), + (∀ i, x i ≠ y i) → (∀ i, x i ∉ W) → (∀ i, y i ∉ W) → + (∀ v, endpointLoad univ x y v ≤ 2) → + ∀ r : V × Fin 2 → V, + (∀ v, v ∉ W → ∀ t, r (v,t) ∈ W ∧ P.Adj v (r (v,t))) → + (∀ v, v ∉ W → r (v,0) ≠ r (v,1)) → + (∀ v, ((Wᶜ ×ˢ univ).filter (fun z => r z = v)).card ≤ + ⌈8*(Fintype.card V:ℝ)/(p*(c*D^(9/10:ℝ)))⌉₊) → + ∃ (a b : I → V) (q : ∀ i, G.Walk (a i) (b i)), + (∀ i, G.Adj (x i) (a i) ∧ G.Adj (y i) (b i)) ∧ + Function.Injective (fun z : I × Fin 2 => + if z.2 = 0 then s(x z.1,a z.1) else s(y z.1,b z.1)) ∧ + (∀ i, (q i).IsPath ∧ (q i).length ≤ routingLength W.card (D^(37/50:ℝ)) ∧ + ∀ v ∈ (q i).support, v ∈ W) ∧ + Pairwise (fun i j => Disjoint (q i).edgeSet (q j).edgeSet) ∧ + (∀ i, ∃ t, a i = r (x i,t)) ∧ (∀ i, ∃ t, b i = r (y i,t)) ∧ + (∀ i, (q i).edgeSet ⊆ P.edgeSet) := by + obtain ⟨D₀,hD₀,hroute⟩ := uniform_reservoir_routing c p hc hp + refine ⟨D₀,hD₀,?_⟩ + intro D hD V _ _ G P _ hPG W hexp hW hr I _ x y hne hx hy hl r hrep hrepne hcap + obtain ⟨a,b,ha,hb,hs,hl',ha',hb'⟩ := + choose_reservoir_endpoints P W x y hne hx hy hl r hrep hrepne _ hcap + obtain ⟨q,hq,hd⟩ := hroute D hD V P P le_rfl W hexp hW hr I a b + (fun i => (ha i).1) (fun i => (hb i).1) hl' + let Q : ∀ i, G.Walk (a i) (b i) := fun i => (q i).mapLe hPG + refine ⟨a,b,Q,(fun i => ⟨hPG (ha i).2,hPG (hb i).2⟩),hs,?_,?_,ha',hb',?_⟩ + · intro i + refine ⟨(hq i).1.mapLe hPG,?_,?_⟩ + · simpa only [Q, SimpleGraph.Walk.length_mapLe] using (hq i).2.1 + · simpa only [Q, SimpleGraph.Walk.support_mapLe_eq_support] using (hq i).2.2 + · intro i j hij + simpa only [Q, SimpleGraph.Walk.edgeSet_mapLe_eq_edgeSet] using hd hij + · intro i + rw [show (Q i).edgeSet = (q i).edgeSet from (q i).edgeSet_mapLe_eq_edgeSet hPG] + intro e he + exact (q i).edges_subset_edgeSet he + +end +end ErdosGallai + +namespace ErdosGallai +open SimpleGraph + +variable {V : Type cycleUniverse11} {G : SimpleGraph V} {x y a b : V} + +def reservoirReturn (P : G.Walk a b) (hx : G.Adj x a) (hy : G.Adj y b) : + G.Walk y x := .cons hy (P.reverse.concat hx.symm) + +lemma reservoirReturn_isPath (Q : G.Walk x y) (P : G.Walk a b) + (hQ : Q.IsPath) (hQpos : 0 < Q.length) (hP : P.IsPath) + (hdisj : Q.support.Disjoint P.support) (hx : G.Adj x a) (hy : G.Adj y b) : + (reservoirReturn P hx hy).IsPath := by + have hxy : x ≠ y := by + intro h + subst y + have := hQ.nil_iff_eq.mpr rfl + have hz : Q.length = 0 := this.length_eq_zero + omega + have hxP : x ∉ P.reverse.support := by + simpa using hdisj Q.start_mem_support + have hyP : y ∉ P.reverse.support := by + simpa using hdisj Q.end_mem_support + exact (hP.reverse.concat hxP hx.symm).cons (by simpa using And.intro hyP hxy.symm) + +theorem reservoir_path_closure (Q : G.Walk x y) (P : G.Walk a b) + (hQ : Q.IsPath) (hQpos : 0 < Q.length) (hP : P.IsPath) + (hdisj : Q.support.Disjoint P.support) (hx : G.Adj x a) (hy : G.Adj y b) : + (Q.append (reservoirReturn P hx hy)).IsCycle ∧ + (Q.append (reservoirReturn P hx hy)).edgeSet = + Q.edgeSet ∪ P.edgeSet ∪ {s(x,a), s(y,b)} ∧ + 3 ≤ (Q.append (reservoirReturn P hx hy)).length := by + have hreturn := reservoirReturn_isPath Q P hQ hQpos hP hdisj hx hy + have htail : Q.support.tail.Disjoint (reservoirReturn P hx hy).support.tail := by + rw [List.disjoint_left] + intro v hv + have hvQ := List.mem_of_mem_tail hv + have hvP : v ∉ P.support := hdisj hvQ + have hvx : v ≠ x := by + have hn := hQ.support_nodup + rw [← Q.cons_tail_support, List.nodup_cons] at hn + exact fun heq => hn.1 (heq ▸ hv) + simpa [reservoirReturn] using And.intro hvP hvx + have hcycle := hQ.isCycle_append hreturn htail (Or.inr (by simp [reservoirReturn])) + refine ⟨hcycle, ?_, ?_⟩ + · ext e + simp only [Walk.edgeSet_append, reservoirReturn, Walk.edgeSet_cons, + Walk.edgeSet_concat, Walk.edgeSet_reverse, Set.mem_union, Set.mem_insert_iff, + Set.mem_singleton_iff] + rw [Sym2.eq_swap (a := x) (b := a)] + tauto + · simpa [reservoirReturn] using (by omega : 3 ≤ Q.length + (P.length + 1 + 1)) + +end ErdosGallai + +namespace ErdosGallai +noncomputable section +open SimpleGraph +attribute [local instance] Classical.propDecidable + +lemma spoke_sets_pairwise {I : Type cycleUniverse12} {E : Type cycleUniverse13} (e : I × Fin 2 → E) + (he : Function.Injective e) : + Pairwise (fun i j => Disjoint ({e (i,0), e (i,1)} : Set E) {e (j,0), e (j,1)}) := by + intro i j hij + apply Set.disjoint_left.mpr + intro a hai haj + simp only [Set.mem_insert_iff, Set.mem_singleton_iff] at hai haj + rcases hai with hai | hai <;> rcases haj with haj | haj + all_goals exact hij (congrArg Prod.fst (he (hai.symm.trans haj))) + +lemma pairwise_union_three {I : Type cycleUniverse14} {E : Type cycleUniverse15} (A B S : I → Set E) + (hA : Pairwise fun i j => Disjoint (A i) (A j)) + (hB : Pairwise fun i j => Disjoint (B i) (B j)) + (hS : Pairwise fun i j => Disjoint (S i) (S j)) + (hAB : ∀ i j, Disjoint (A i) (B j)) + (hAS : ∀ i j, Disjoint (A i) (S j)) + (hBS : ∀ i j, Disjoint (B i) (S j)) : + Pairwise (fun i j => Disjoint (A i ∪ B i ∪ S i) (A j ∪ B j ∪ S j)) := by + intro i j hij + apply Set.disjoint_left.mpr + rintro e ((ha | hb) | hs) ((ha' | hb') | hs') + all_goals first + | exact Set.disjoint_left.mp (hA hij) ha ha' + | exact Set.disjoint_left.mp (hB hij) hb hb' + | exact Set.disjoint_left.mp (hS hij) hs hs' + | exact Set.disjoint_left.mp (hAB i j) ha hb' + | exact Set.disjoint_left.mp (hAS i j) ha hs' + | exact Set.disjoint_left.mp (hBS i j) hb hs' + | exact Set.disjoint_left.mp (hAB j i) ha' hb + | exact Set.disjoint_left.mp (hAS j i) ha' hs + | exact Set.disjoint_left.mp (hBS j i) hb' hs + +theorem reservoir_cycle_family {V : Type cycleUniverse16} {I : Type cycleUniverse17} {G : SimpleGraph V} + {x y a b : I → V} (Q : ∀ i, G.Walk (x i) (y i)) + (P : ∀ i, G.Walk (a i) (b i)) + (hx : ∀ i, G.Adj (x i) (a i)) (hy : ∀ i, G.Adj (y i) (b i)) + (hQ : ∀ i, (Q i).IsPath) (hQpos : ∀ i, 0 < (Q i).length) + (hP : ∀ i, (P i).IsPath) + (hsep : ∀ i, (Q i).support.Disjoint (P i).support) + (hQQ : Pairwise fun i j => Disjoint (Q i).edgeSet (Q j).edgeSet) + (hPP : Pairwise fun i j => Disjoint (P i).edgeSet (P j).edgeSet) + (hspoke : Function.Injective (fun z : I × Fin 2 => + if z.2 = 0 then s(x z.1,a z.1) else s(y z.1,b z.1))) + (hQP : ∀ i j, Disjoint (Q i).edgeSet (P j).edgeSet) + (hQS : ∀ i j, Disjoint (Q i).edgeSet {s(x j,a j),s(y j,b j)}) + (hPS : ∀ i j, Disjoint (P i).edgeSet {s(x j,a j),s(y j,b j)}) : + let C := fun i => (Q i).append (reservoirReturn (P i) (hx i) (hy i)) + (∀ i, (C i).IsCycle) ∧ + Pairwise (fun i j => Disjoint (C i).edgeSet (C j).edgeSet) ∧ + (⋃ i, (C i).edgeSet) = + (⋃ i, (Q i).edgeSet) ∪ (⋃ i, (P i).edgeSet) ∪ + (⋃ i, ({s(x i,a i),s(y i,b i)} : Set (Sym2 V))) := by + dsimp only + have hC := fun i => reservoir_path_closure (Q i) (P i) (hQ i) (hQpos i) + (hP i) (hsep i) (hx i) (hy i) + refine ⟨fun i => (hC i).1, ?_, ?_⟩ + · have hSS : Pairwise (fun i j => Disjoint + ({s(x i,a i),s(y i,b i)} : Set (Sym2 V)) {s(x j,a j),s(y j,b j)}) := by + simpa using spoke_sets_pairwise _ hspoke + simpa only [fun i => (hC i).2.1] using + pairwise_union_three (fun i => (Q i).edgeSet) (fun i => (P i).edgeSet) + (fun i => ({s(x i,a i),s(y i,b i)} : Set (Sym2 V))) + hQQ hPP hSS hQP hQS hPS + · simp only [fun i => (hC i).2.1, Set.iUnion_union_distrib] + +lemma reservoir_edge_ledger {E : Type cycleUniverse18} {I : Type cycleUniverse19} (G O R : Set E) + (A B S C : I → Set E) + (hcover : (⋃ i, A i) ∪ O ∪ R = G) + (hAO : Disjoint (⋃ i, A i) O) (hAR : Disjoint (⋃ i, A i) R) + (hOR : Disjoint O R) + (hB : (⋃ i, B i) ⊆ R) (hS : (⋃ i, S i) ⊆ O) + (hC : (⋃ i, C i) = (⋃ i, A i) ∪ (⋃ i, B i) ∪ (⋃ i, S i)) : + let unusedSpokes := O \ (⋃ i, S i) + let remaining := R \ (⋃ i, B i) + Disjoint (⋃ i, C i) unusedSpokes ∧ + Disjoint (⋃ i, C i) remaining ∧ + Disjoint unusedSpokes remaining ∧ + (⋃ i, C i) ∪ unusedSpokes ∪ remaining = G := by + dsimp only + rw [hC] + have hBO := hOR.symm.mono_left hB + have hSR := hOR.mono_left hS + refine ⟨?_,?_,hOR.mono Set.sdiff_subset Set.sdiff_subset,?_⟩ + · apply Set.disjoint_left.mpr + rintro e ((he | he) | he) ⟨ho,hs⟩ + · exact Set.disjoint_left.mp hAO he ho + · exact Set.disjoint_left.mp hBO he ho + · exact hs he + · apply Set.disjoint_left.mpr + rintro e ((he | he) | he) ⟨hr,hb⟩ + · exact Set.disjoint_left.mp hAR he hr + · exact hb he + · exact Set.disjoint_left.mp hSR he hr + · rw [← hcover] + ext e + simp only [Set.mem_union, Set.mem_sdiff] + constructor + · rintro ((((ha | hb) | hs) | ho) | hr) + · exact Or.inl (Or.inl ha) + · exact Or.inr (hB hb) + · exact Or.inl (Or.inr (hS hs)) + · exact Or.inl (Or.inr ho.1) + · exact Or.inr hr.1 + · rintro ((ha | ho) | hr) + · exact Or.inl (Or.inl (Or.inl (Or.inl ha))) + · by_cases hs : e ∈ ⋃ i, S i + · exact Or.inl (Or.inl (Or.inr hs)) + · exact Or.inl (Or.inr ⟨ho,hs⟩) + · by_cases hb : e ∈ ⋃ i, B i + · exact Or.inl (Or.inl (Or.inl (Or.inr hb))) + · exact Or.inr ⟨hr,hb⟩ + +end +end ErdosGallai + +end +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/CycleDecomposition/ReservoirRemainder.lean b/lean/OAI/Combinatorics/CycleDecomposition/ReservoirRemainder.lean new file mode 100644 index 0000000000000000000000000000000000000000..f33b43114fd014e7842b49cc1a6a1ae368d4c609 --- /dev/null +++ b/lean/OAI/Combinatorics/CycleDecomposition/ReservoirRemainder.lean @@ -0,0 +1,741 @@ +import OAI.Combinatorics.CycleDecomposition.ReservoirCycles + +namespace OAI + +universe cycleUniverse1 cycleUniverse2 cycleUniverse3 cycleUniverse4 cycleUniverse5 cycleUniverse6 cycleUniverse7 cycleUniverse8 cycleUniverse9 cycleUniverse10 cycleUniverse11 cycleUniverse12 cycleUniverse13 cycleUniverse14 cycleUniverse15 cycleUniverse16 cycleUniverse17 cycleUniverse18 cycleUniverse19 cycleUniverse20 cycleUniverse21 cycleUniverse22 cycleUniverse23 cycleUniverse24 cycleUniverse25 cycleUniverse26 cycleUniverse27 cycleUniverse28 cycleUniverse29 cycleUniverse30 cycleUniverse31 cycleUniverse32 cycleUniverse33 cycleUniverse34 cycleUniverse35 cycleUniverse36 cycleUniverse37 cycleUniverse38 cycleUniverse39 cycleUniverse40 cycleUniverse41 cycleUniverse42 cycleUniverse43 cycleUniverse44 cycleUniverse45 cycleUniverse46 cycleUniverse47 cycleUniverse48 cycleUniverse49 cycleUniverse50 cycleUniverse51 cycleUniverse52 cycleUniverse53 cycleUniverse54 cycleUniverse55 cycleUniverse56 + +section +open Filter Asymptotics Real +open scoped Topology +noncomputable section +open MeasureTheory ProbabilityTheory Finset +noncomputable section +namespace ErdosGallai +noncomputable section +open Finset SimpleGraph +attribute [local instance] Classical.propDecidable + +lemma walks_edges_disjoint_of_support {V : Type cycleUniverse1} {G H : SimpleGraph V} + {x y a b : V} (p : G.Walk x y) (q : H.Walk a b) + (h : p.support.Disjoint q.support) : Disjoint p.edgeSet q.edgeSet := by + apply Set.disjoint_left.mpr + intro e he he' + induction e using Sym2.ind with + | _ u v => + exact h (p.fst_mem_support_of_mem_edges he) (q.fst_mem_support_of_mem_edges he') + +lemma walk_edges_disjoint_spokes_of_outside {V : Type cycleUniverse2} {I : Type cycleUniverse3} {G : SimpleGraph V} + {u v : V} (Q : G.Walk u v) (W : Set V) (x y a b : I → V) + (hQ : ∀ z ∈ Q.support, z ∉ W) (ha : ∀ i, a i ∈ W) (hb : ∀ i, b i ∈ W) : + ∀ i, Disjoint Q.edgeSet ({s(x i,a i), s(y i,b i)} : Set (Sym2 V)) := by + intro i + apply Set.disjoint_left.mpr + intro e he he' + rcases he' with rfl | he' + · exact hQ _ (Q.snd_mem_support_of_mem_edges he) (ha i) + · have heq : e = s(y i,b i) := he' + subst e + exact hQ _ (Q.snd_mem_support_of_mem_edges he) (hb i) + +lemma walk_edges_disjoint_spokes_of_inside {V : Type cycleUniverse4} {I : Type cycleUniverse5} {G : SimpleGraph V} + {u v : V} (Q : G.Walk u v) (W : Set V) (x y a b : I → V) + (hQ : ∀ z ∈ Q.support, z ∈ W) (hx : ∀ i, x i ∉ W) (hy : ∀ i, y i ∉ W) : + ∀ i, Disjoint Q.edgeSet ({s(x i,a i), s(y i,b i)} : Set (Sym2 V)) := by + intro i + apply Set.disjoint_left.mpr + intro e he he' + rcases he' with rfl | he' + · exact hx i (hQ _ (Q.fst_mem_support_of_mem_edges he)) + · have heq : e = s(y i,b i) := he' + subst e + exact hy i (hQ _ (Q.fst_mem_support_of_mem_edges he)) + +theorem uniform_reservoir_completion (c p : ℝ) (hc : 0 < c) (hp : 0 < p) : + ∃ D₀ : ℝ, 1 < D₀ ∧ ∀ D ≥ D₀, + ∀ (V : Type) [Fintype V] [DecidableEq V], + ∀ (G P : SimpleGraph V) [DecidableRel P.Adj], P ≤ G → + ∀ W : Finset V, CutExpansionOn P W (D^(37/50:ℝ)) → 2 ≤ W.card → + (Fintype.card V : ℝ) ≤ D^(51/50:ℝ) → + ∀ (I : Type) [Fintype I] (x y : I → V) (Q : ∀ i, G.Walk (x i) (y i)), + (∀ i, (Q i).IsPath) → (∀ i, 0 < (Q i).length) → + (∀ i v, v ∈ (Q i).support → v ∉ W) → + Pairwise (fun i j => Disjoint (Q i).edgeSet (Q j).edgeSet) → + (∀ v, endpointLoad univ x y v ≤ 2) → + ∀ r : V × Fin 2 → V, + (∀ v, v ∉ W → ∀ t, r (v,t) ∈ W ∧ P.Adj v (r (v,t))) → + (∀ v, v ∉ W → r (v,0) ≠ r (v,1)) → + (∀ v, ((Wᶜ ×ˢ univ).filter (fun z => r z = v)).card ≤ + ⌈8*(Fintype.card V:ℝ)/(p*(c*D^(9/10:ℝ)))⌉₊) → + ∃ (a b : I → V) (q : ∀ i, G.Walk (a i) (b i)) + (C : ∀ i, G.Walk (x i) (x i)), + (∀ i, (C i).IsCycle) ∧ + Pairwise (fun i j => Disjoint (C i).edgeSet (C j).edgeSet) ∧ + (∀ i, (C i).edgeSet = (Q i).edgeSet ∪ (q i).edgeSet ∪ + {s(x i,a i),s(y i,b i)}) ∧ + (∀ i, (q i).edgeSet ⊆ P.edgeSet ∧ ∀ v ∈ (q i).support, v ∈ W) ∧ + Function.Injective (fun z : I × Fin 2 => + if z.2 = 0 then s(x z.1,a z.1) else s(y z.1,b z.1)) ∧ + (∀ i, ∃ t, a i = r (x i,t)) ∧ (∀ i, ∃ t, b i = r (y i,t)) := by + obtain ⟨D₀,hD₀,hrouting⟩ := uniform_assigned_reservoir_routing c p hc hp + refine ⟨D₀,hD₀,?_⟩ + intro D hD V _ _ G P _ hPG W hexp hW hr I _ x y Q hQ hpos hout hQQ hl r hrep hrepne hcap + have hne : ∀ i, x i ≠ y i := by + intro i hi + have hz := ((hQ i).nil_iff_eq.mpr hi).length_eq_zero + have := hpos i + omega + have hx : ∀ i, x i ∉ W := fun i => hout i _ (Q i).start_mem_support + have hy : ∀ i, y i ∉ W := fun i => hout i _ (Q i).end_mem_support + obtain ⟨a,b,q,hab,hsp,hq,hdd,ha',hb',hPedge⟩ := + hrouting D hD V G P hPG W hexp hW hr I x y hne hx hy hl r hrep hrepne hcap + have ha : ∀ i, a i ∈ W := fun i => (hq i).2.2 _ (q i).start_mem_support + have hb : ∀ i, b i ∈ W := fun i => (hq i).2.2 _ (q i).end_mem_support + have hdisj : ∀ i j, (Q i).support.Disjoint (q j).support := by + intro i j + exact List.disjoint_left.mpr (fun v hv hv' => hout i v hv ((hq j).2.2 v hv')) + let C := fun i => (Q i).append (reservoirReturn (q i) (hab i).1 (hab i).2) + have hfamily := reservoir_cycle_family Q q (fun i => (hab i).1) (fun i => (hab i).2) + hQ hpos (fun i => (hq i).1) (fun i => hdisj i i) hQQ hdd hsp + (fun i j => walks_edges_disjoint_of_support _ _ (hdisj i j)) + (fun i => walk_edges_disjoint_spokes_of_outside (Q i) W x y a b (hout i) ha hb) + (fun i => walk_edges_disjoint_spokes_of_inside (q i) W x y a b (hq i).2.2 hx hy) + refine ⟨a,b,q,C,hfamily.1,hfamily.2.1,?_,?_,hsp,ha',hb'⟩ + · intro i + exact (reservoir_path_closure (Q i) (q i) (hQ i) (hpos i) (hq i).1 + (hdisj i i) (hab i).1 (hab i).2).2.1 + · intro i + exact ⟨hPedge i,(hq i).2.2⟩ + +end +end ErdosGallai + +namespace ErdosGallai +noncomputable section +open SimpleGraph +attribute [local instance] Classical.propDecidable + +lemma exists_reservoir_avoided {V : Type cycleUniverse6} (W : Fin 3 → Set V) + (hW : Pairwise fun i j => Disjoint (W i) (W j)) (x y : V) : + ∃ i, x ∉ W i ∧ y ∉ W i := by + by_contra hno + have h : ∀ i, x ∈ W i ∨ y ∈ W i := by + intro i + by_contra! hi + exact hno ⟨i,hi⟩ + have h01 := Set.disjoint_left.mp (hW (show (0 : Fin 3) ≠ 1 by decide)) + have h02 := Set.disjoint_left.mp (hW (show (0 : Fin 3) ≠ 2 by decide)) + have h12 := Set.disjoint_left.mp (hW (show (1 : Fin 3) ≠ 2 by decide)) + rcases h 0 with hx0 | hy0 <;> + rcases h 1 with hx1 | hy1 <;> + rcases h 2 with hx2 | hy2 + all_goals first + | exact h01 hx0 hx1 + | exact h02 hx0 hx2 + | exact h12 hx1 hx2 + | exact h01 hy0 hy1 + | exact h02 hy0 hy2 + | exact h12 hy1 hy2 + +lemma exists_edge_reservoir_avoided {V : Type cycleUniverse7} (W : Fin 3 → Set V) + (hW : Pairwise fun i j => Disjoint (W i) (W j)) (e : Sym2 V) : + ∃ i, ∀ v ∈ e, v ∉ W i := by + induction e using Sym2.ind with + | _ x y => + obtain ⟨i,hx,hy⟩ := exists_reservoir_avoided W hW x y + refine ⟨i,?_⟩ + intro v hv + rcases Sym2.mem_iff.mp hv with rfl | rfl + · exact hx + · exact hy + +noncomputable def reservoirColor {V : Type cycleUniverse8} (W : Fin 3 → Set V) + (hW : Pairwise fun i j => Disjoint (W i) (W j)) (e : Sym2 V) : Fin 3 := + (exists_edge_reservoir_avoided W hW e).choose + +lemma reservoirColor_avoids {V : Type cycleUniverse9} (W : Fin 3 → Set V) + (hW : Pairwise fun i j => Disjoint (W i) (W j)) (e : Sym2 V) : + ∀ v ∈ e, v ∉ W (reservoirColor W hW e) := + (exists_edge_reservoir_avoided W hW e).choose_spec + +def complementaryReservoirGraph {V : Type cycleUniverse10} (G : SimpleGraph V) + (W : Fin 3 → Set V) (hW : Pairwise fun i j => Disjoint (W i) (W j)) + (i : Fin 3) : SimpleGraph V where + Adj x y := G.Adj x y ∧ reservoirColor W hW s(x,y) = i + symm := ⟨by + intro x y h + exact ⟨h.1.symm, by simpa only [Sym2.eq_swap] using h.2⟩⟩ + loopless := ⟨by intro x h; exact G.loopless.irrefl x h.1⟩ + +lemma complementaryReservoirGraph_edges {V : Type cycleUniverse11} (G : SimpleGraph V) + (W : Fin 3 → Set V) (hW : Pairwise fun i j => Disjoint (W i) (W j)) + (i : Fin 3) : + (complementaryReservoirGraph G W hW i).edgeSet = + {e | e ∈ G.edgeSet ∧ reservoirColor W hW e = i} := by + ext e + induction e using Sym2.ind with + | _ x y => rfl + +theorem complementary_reservoir_graphs {V : Type cycleUniverse12} (G : SimpleGraph V) + (W : Fin 3 → Set V) (hW : Pairwise fun i j => Disjoint (W i) (W j)) : + (∀ i, complementaryReservoirGraph G W hW i ≤ G) ∧ + (∀ i x y, (complementaryReservoirGraph G W hW i).Adj x y → + x ∉ W i ∧ y ∉ W i) ∧ + Pairwise (fun i j => Disjoint (complementaryReservoirGraph G W hW i).edgeSet + (complementaryReservoirGraph G W hW j).edgeSet) ∧ + (⋃ i, (complementaryReservoirGraph G W hW i).edgeSet) = G.edgeSet := by + refine ⟨fun _ _ _ h => h.1, ?_, ?_, ?_⟩ + · intro i x y h + have hx := reservoirColor_avoids W hW s(x,y) x (Sym2.mem_mk_left x y) + have hy := reservoirColor_avoids W hW s(x,y) y (Sym2.mem_mk_right x y) + rw [h.2] at hx hy + exact ⟨hx,hy⟩ + · intro i j hij + rw [complementaryReservoirGraph_edges, complementaryReservoirGraph_edges] + exact Set.disjoint_left.mpr fun _ he hj => hij (he.2.symm.trans hj.2) + · ext e + simp only [Set.mem_iUnion, complementaryReservoirGraph_edges, Set.mem_ofPred] + constructor + · rintro ⟨i,he,_⟩; exact he + · intro he; exact ⟨reservoirColor W hW e, he, rfl⟩ + +end +end ErdosGallai + +namespace ErdosGallai +noncomputable section +open Finset SimpleGraph +attribute [local instance] Classical.propDecidable + +def reservoirInternal {V : Type cycleUniverse13} (P : SimpleGraph V) (W : Set V) : Set (Sym2 V) := + {e | e ∈ P.edgeSet ∧ ∀ v ∈ e, v ∈ W} + +noncomputable def reservoirSpokes {V : Type cycleUniverse14} [Fintype V] [DecidableEq V] + (W : Finset V) (r : V × Fin 2 → V) : Finset (Sym2 V) := + (Wᶜ ×ˢ univ).image (fun z => s(z.1,r z)) + +lemma mem_reservoirSpokes {V : Type cycleUniverse15} [Fintype V] [DecidableEq V] + (W : Finset V) (r : V × Fin 2 → V) (e : Sym2 V) : + e ∈ reservoirSpokes W r ↔ ∃ v ∉ W, ∃ t : Fin 2, e = s(v,r (v,t)) := by + simp only [reservoirSpokes, Finset.mem_image, Finset.mem_product, + Finset.mem_compl, Finset.mem_univ, and_true, Prod.exists] + constructor + · rintro ⟨v,t,hv,he⟩ + exact ⟨v,hv,t,he.symm⟩ + · rintro ⟨v,hv,t,he⟩ + exact ⟨v,t,hv,he.symm⟩ + +lemma reservoirSpokes_card_le {V : Type cycleUniverse16} [Fintype V] [DecidableEq V] + (W : Finset V) (r : V × Fin 2 → V) : + (reservoirSpokes W r).card ≤ 2 * Fintype.card V := by + apply (Finset.card_image_le).trans + rw [Finset.card_product, Finset.card_univ, Fintype.card_fin] + have := Finset.card_le_univ Wᶜ + omega + +lemma reservoirSpokes_subset {V : Type cycleUniverse17} [Fintype V] [DecidableEq V] + (P : SimpleGraph V) (W : Finset V) (r : V × Fin 2 → V) + (hr : ∀ v, v ∉ W → ∀ t, P.Adj v (r (v,t))) : + (reservoirSpokes W r : Set (Sym2 V)) ⊆ P.edgeSet := by + intro e he + obtain ⟨v,hv,t,rfl⟩ := (mem_reservoirSpokes W r e).mp he + exact hr v hv t + +lemma reservoirInternal_spokes_disjoint {V : Type cycleUniverse18} [Fintype V] [DecidableEq V] + (P : SimpleGraph V) (W : Finset V) (r : V × Fin 2 → V) : + Disjoint (reservoirInternal P W) (reservoirSpokes W r : Set (Sym2 V)) := by + apply Set.disjoint_left.mpr + intro e he he' + obtain ⟨v,hv,t,rfl⟩ := (mem_reservoirSpokes W r e).mp he' + exact hv (he.2 _ (Sym2.mem_mk_left _ _)) + +theorem reservoir_reservations {V : Type cycleUniverse19} [Fintype V] [DecidableEq V] + (G : SimpleGraph V) (P : Fin 3 → SimpleGraph V) (W : Fin 3 → Finset V) + (r : Fin 3 → V × Fin 2 → V) + (hPG : ∀ i, P i ≤ G) + (hPP : Pairwise fun i j => Disjoint (P i).edgeSet (P j).edgeSet) + (hr : ∀ i v, v ∉ W i → ∀ t, (P i).Adj v (r i (v,t))) : + let R := fun i => reservoirInternal (P i) (W i) + let O := fun i => (reservoirSpokes (W i) (r i) : Set (Sym2 V)) + (∀ i, R i ⊆ G.edgeSet ∧ O i ⊆ G.edgeSet) ∧ + Pairwise (fun i j => Disjoint (R i ∪ O i) (R j ∪ O j)) ∧ + (∀ i, Disjoint (R i) (O i)) ∧ + Disjoint (⋃ i, R i) (⋃ i, O i) ∧ + (∑ i, (reservoirSpokes (W i) (r i)).card) ≤ 6 * Fintype.card V := by + dsimp only + have hR : ∀ i, reservoirInternal (P i) (W i) ⊆ (P i).edgeSet := fun _ _ he => he.1 + have hO := fun i => reservoirSpokes_subset (P i) (W i) (r i) (hr i) + have hU : ∀ i, reservoirInternal (P i) (W i) ∪ + (reservoirSpokes (W i) (r i) : Set (Sym2 V)) ⊆ (P i).edgeSet := + fun i => Set.union_subset (hR i) (hO i) + refine ⟨?_,?_,?_,?_,?_⟩ + · intro i + exact ⟨(hR i).trans (SimpleGraph.edgeSet_mono (hPG i)), + (hO i).trans (SimpleGraph.edgeSet_mono (hPG i))⟩ + · intro i j hij + exact (hPP hij).mono (hU i) (hU j) + · exact fun i => reservoirInternal_spokes_disjoint (P i) (W i) (r i) + · rw [Set.disjoint_iUnion_left] + intro i + rw [Set.disjoint_iUnion_right] + intro j + by_cases hij : i = j + · subst j + exact reservoirInternal_spokes_disjoint (P i) (W i) (r i) + · exact (hPP hij).mono (hR i) (hO j) + · calc + _ ≤ ∑ _i : Fin 3, 2 * Fintype.card V := + Finset.sum_le_sum (fun i _ => reservoirSpokes_card_le (W i) (r i)) + _ = _ := by simp; omega + +lemma complementary_walk_outside {V : Type cycleUniverse20} {G : SimpleGraph V} + (W : Fin 3 → Set V) (hW : Pairwise fun i j => Disjoint (W i) (W j)) + (i : Fin 3) {x y : V} (q : (complementaryReservoirGraph G W hW i).Walk x y) + (hq : 0 < q.length) : ∀ v ∈ q.support, v ∉ W i := by + have hn : ¬ q.Nil := by + intro h + have hz := h.length_eq_zero + omega + intro v hv + obtain ⟨e,he,hve⟩ := SimpleGraph.Walk.mem_support_iff_exists_mem_edges_of_not_nil hn |>.mp hv + have heG := q.edges_subset_edgeSet he + have hecol : reservoirColor W hW e = i := by + rw [complementaryReservoirGraph_edges] at heG + exact heG.2 + exact hecol ▸ reservoirColor_avoids W hW e v hve + +theorem complementary_reservation_ledger {V : Type cycleUniverse21} (G : SimpleGraph V) + (W : Fin 3 → Set V) (hW : Pairwise fun i j => Disjoint (W i) (W j)) + (E : Set (Sym2 V)) (hE : E ⊆ G.edgeSet) : + let H := G.deleteEdges E + let K := fun i => complementaryReservoirGraph H W hW i + Pairwise (fun i j => Disjoint (K i).edgeSet (K j).edgeSet) ∧ + (∀ i, Disjoint (K i).edgeSet E) ∧ + ((⋃ i, (K i).edgeSet) ∪ E = G.edgeSet) := by + dsimp only + have hh := complementary_reservoir_graphs (G.deleteEdges E) W hW + refine ⟨hh.2.2.1,?_,?_⟩ + · intro i + apply Set.disjoint_left.mpr + intro e he he' + have h := SimpleGraph.edgeSet_mono (hh.1 i) he + rw [SimpleGraph.edgeSet_deleteEdges] at h + exact h.2 he' + · rw [hh.2.2.2, SimpleGraph.edgeSet_deleteEdges] + exact Set.sdiff_union_of_subset hE + +end +end ErdosGallai + +namespace ErdosGallai +noncomputable section +open Finset SimpleGraph +attribute [local instance] Classical.propDecidable + +def edgeRestriction {V : Type cycleUniverse22} (G : SimpleGraph V) (E : Set (Sym2 V)) : SimpleGraph V where + Adj x y := G.Adj x y ∧ s(x,y) ∈ E + symm := ⟨by intro x y h; exact ⟨h.1.symm, by simpa only [Sym2.eq_swap] using h.2⟩⟩ + loopless := ⟨by intro x h; exact G.loopless.irrefl x h.1⟩ + +lemma edgeRestriction_le {V : Type cycleUniverse23} (G : SimpleGraph V) (E : Set (Sym2 V)) : + edgeRestriction G E ≤ G := fun _ _ h => h.1 + +lemma edgeRestriction_edges {V : Type cycleUniverse24} (G : SimpleGraph V) (E : Set (Sym2 V)) : + (edgeRestriction G E).edgeSet = G.edgeSet ∩ E := by + ext e + induction e using Sym2.ind with | _ x y => rfl + +lemma edgeRestriction_edges_of_subset {V : Type cycleUniverse25} (G : SimpleGraph V) (E : Set (Sym2 V)) + (hE : E ⊆ G.edgeSet) : (edgeRestriction G E).edgeSet = E := by + rw [edgeRestriction_edges, Set.inter_eq_right.mpr hE] + +def completedEdges {V : Type cycleUniverse26} {I : Type cycleUniverse27} (C : I → Set (Sym2 V)) : Set (Sym2 V) := ⋃ i, C i + +def residualInternalGraph {V : Type cycleUniverse28} {B : Type cycleUniverse29} {I : Type cycleUniverse30} (G : SimpleGraph V) + (R : B → Set (Sym2 V)) (C : I → Set (Sym2 V)) (b : B) : SimpleGraph V := + edgeRestriction G (R b \ completedEdges C) + +def unusedSpokes {V : Type cycleUniverse31} {I : Type cycleUniverse32} [Fintype V] (S : Set (Sym2 V)) + (C : I → Set (Sym2 V)) : Finset (Sym2 V) := (S \ completedEdges C).toFinset + +lemma unusedSpokes_card_le {V : Type cycleUniverse33} {I : Type cycleUniverse34} [Fintype V] (S : Finset (Sym2 V)) + (C : I → Set (Sym2 V)) : (unusedSpokes (↑S) C).card ≤ S.card := by + apply Finset.card_le_card + intro e he + simp only [unusedSpokes, Set.mem_toFinset, Finset.mem_coe, Set.mem_sdiff] at he + exact he.1 + +theorem residue_edge_ledger {V : Type cycleUniverse35} {B : Type cycleUniverse36} {I : Type cycleUniverse37} [Fintype V] + (G : SimpleGraph V) (R : B → Set (Sym2 V)) (S : Set (Sym2 V)) + (C : I → Set (Sym2 V)) + (hR : ∀ b, R b ⊆ G.edgeSet) (hS : S ⊆ G.edgeSet) + (hRR : Pairwise fun b c => Disjoint (R b) (R c)) + (hRS : ∀ b, Disjoint (R b) S) + (hC : ∀ i, C i ⊆ G.edgeSet) + (_hCC : Pairwise fun i j => Disjoint (C i) (C j)) + (hcover : G.edgeSet \ ((⋃ b, R b) ∪ S) ⊆ completedEdges C) : + (∀ b, (residualInternalGraph G R C b).edgeSet = R b \ completedEdges C) ∧ + Pairwise (fun b c => Disjoint (residualInternalGraph G R C b).edgeSet + (residualInternalGraph G R C c).edgeSet) ∧ + (∀ b i, Disjoint (residualInternalGraph G R C b).edgeSet (C i)) ∧ + (∀ b, Disjoint (residualInternalGraph G R C b).edgeSet (↑(unusedSpokes S C) : Set _)) ∧ + (∀ i, Disjoint (C i) (↑(unusedSpokes S C) : Set _)) ∧ + (completedEdges C ∪ (↑(unusedSpokes S C) : Set _) ∪ + (⋃ b, (residualInternalGraph G R C b).edgeSet)) = G.edgeSet := by + classical + have hrem (b : B) : (residualInternalGraph G R C b).edgeSet = R b \ completedEdges C := by + apply edgeRestriction_edges_of_subset + exact fun e he => hR b he.1 + have hsingle : (↑(unusedSpokes S C) : Set _) = S \ completedEdges C := by + simp only [unusedSpokes, Set.coe_toFinset] + have hsub : completedEdges C ⊆ G.edgeSet := by + rintro e he + obtain ⟨i,hi⟩ := Set.mem_iUnion.mp he + exact hC i hi + refine ⟨hrem,?_,?_,?_,?_,?_⟩ + · intro b c hbc + rw [hrem b,hrem c] + exact (hRR hbc).mono Set.sdiff_subset Set.sdiff_subset + · intro b i + rw [hrem b] + apply Set.disjoint_left.mpr + intro e he hi + exact he.2 (Set.mem_iUnion.mpr ⟨i,hi⟩) + · intro b + rw [hrem b,hsingle] + exact (hRS b).mono Set.sdiff_subset Set.sdiff_subset + · intro i + rw [hsingle] + apply Set.disjoint_left.mpr + intro e hi he + exact he.2 (Set.mem_iUnion.mpr ⟨i,hi⟩) + · rw [hsingle] + ext e + constructor + · rintro ((he | he) | he) + · exact hsub he + · exact hS he.1 + · obtain ⟨b,hb⟩ := Set.mem_iUnion.mp he + rw [hrem b] at hb + exact hR b hb.1 + · intro he + by_cases hc : e ∈ completedEdges C + · exact Or.inl (Or.inl hc) + by_cases hs : e ∈ S + · exact Or.inl (Or.inr ⟨hs,hc⟩) + have hr : e ∈ ⋃ b, R b := by + by_contra hr + exact hc (hcover ⟨he,by intro hu; exact hu.elim hr hs⟩) + obtain ⟨b,hb⟩ := Set.mem_iUnion.mp hr + exact Or.inr (Set.mem_iUnion.mpr ⟨b,by rw [hrem b]; exact ⟨hb,hc⟩⟩) + +theorem residue_part_count {V : Type cycleUniverse38} {I : Type cycleUniverse39} [Fintype V] [Fintype I] + (S : Finset (Sym2 V)) (C : I → Set (Sym2 V)) + (hI : Fintype.card I ≤ 3 * Fintype.card V) + (hS : S.card ≤ 6 * Fintype.card V) : + Fintype.card I + (unusedSpokes (↑S) C).card ≤ 9 * Fintype.card V := by + have := unusedSpokes_card_le S C + omega + +lemma induce_edge_image_of_support_subset {V : Type cycleUniverse40} (H : SimpleGraph V) + (W : Set V) (hW : H.support ⊆ W) : + Sym2.map Subtype.val '' (H.induce W).edgeSet = H.edgeSet := by + ext e + constructor + · rintro ⟨d,hd,rfl⟩ + induction d using Sym2.ind with + | _ x y => exact hd + · intro he + induction e using Sym2.ind with + | _ x y => + have hx : x ∈ W := hW ⟨y,he⟩ + have hy : y ∈ W := hW ⟨x,he.symm⟩ + exact ⟨s(⟨x,hx⟩,⟨y,hy⟩),he,rfl⟩ + +theorem residual_induce_exact {V : Type cycleUniverse41} {B : Type cycleUniverse42} {I : Type cycleUniverse43} (G : SimpleGraph V) + (R : B → Set (Sym2 V)) (C : I → Set (Sym2 V)) (b : B) (W : Set V) + (hR : R b ⊆ G.edgeSet) (hinside : ∀ e ∈ R b, ∀ v ∈ e, v ∈ W) : + Sym2.map Subtype.val '' ((residualInternalGraph G R C b).induce W).edgeSet = + R b \ completedEdges C := by + have hsupport : (residualInternalGraph G R C b).support ⊆ W := by + rintro v ⟨w,hw⟩ + exact hinside s(v,w) hw.2.1 v (by simp) + rw [induce_edge_image_of_support_subset _ W hsupport] + exact edgeRestriction_edges_of_subset G _ (fun e he => hR he.1) + +end +end ErdosGallai + +namespace ErdosGallai +noncomputable section +open Finset SimpleGraph +attribute [local instance] Classical.propDecidable + +lemma walk_edges_internal {V : Type cycleUniverse44} {G P : SimpleGraph V} {a b : V} + (W : Set V) (q : G.Walk a b) (he : q.edgeSet ⊆ P.edgeSet) + (hv : ∀ v ∈ q.support, v ∈ W) : + q.edgeSet ⊆ reservoirInternal P W := by + intro e h + refine ⟨he h,?_⟩ + induction e using Sym2.ind with + | _ x y => + intro v hmem + rcases (Sym2.mem_iff.mp hmem) with rfl | rfl + · exact hv _ (q.fst_mem_support_of_mem_edges h) + · exact hv _ (q.snd_mem_support_of_mem_edges h) + +lemma completion_edges_subset {V : Type cycleUniverse45} [Fintype V] [DecidableEq V] + {G P : SimpleGraph V} (W : Finset V) (r : V × Fin 2 → V) + {x y a b : V} (Q : G.Walk x y) (q : G.Walk a b) (C : G.Walk x x) + (K : Set (Sym2 V)) (hQ : Q.edgeSet ⊆ K) + (hC : C.edgeSet = Q.edgeSet ∪ q.edgeSet ∪ {s(x,a),s(y,b)}) + (hq : q.edgeSet ⊆ P.edgeSet ∧ ∀ v ∈ q.support, v ∈ W) + (hx : x ∉ W) (hy : y ∉ W) + (ha : ∃ t, a = r (x,t)) (hb : ∃ t, b = r (y,t)) : + C.edgeSet ⊆ K ∪ (reservoirInternal P W ∪ (reservoirSpokes W r : Set _)) := by + rw [hC] + have hqi := walk_edges_internal (W : Set V) q hq.1 hq.2 + intro e he + rcases he with (he | he) | he + · exact Or.inl (hQ he) + · exact Or.inr (Or.inl (hqi he)) + · apply Or.inr ∘ Or.inr + rcases (show e = s(x,a) ∨ e = s(y,b) by simpa using he) with rfl | rfl + · obtain ⟨t,rfl⟩ := ha + exact (mem_reservoirSpokes W r _).mpr ⟨x,hx,t,rfl⟩ + · obtain ⟨t,rfl⟩ := hb + exact (mem_reservoirSpokes W r _).mpr ⟨y,hy,t,rfl⟩ + +lemma completed_subfamilies_disjoint {E : Type cycleUniverse46} {B : Type cycleUniverse47} {I : B → Type cycleUniverse55} + (K R : B → Set E) (C : ∀ b, I b → Set E) + (hKK : Pairwise fun b c => Disjoint (K b) (K c)) + (hRR : Pairwise fun b c => Disjoint (R b) (R c)) + (hKR : ∀ b c, Disjoint (K b) (R c)) + (hC : ∀ b i, C b i ⊆ K b ∪ R b) + (hCC : ∀ b, Pairwise fun i j => Disjoint (C b i) (C b j)) : + Pairwise (fun s t : Sigma I => Disjoint (C s.1 s.2) (C t.1 t.2)) := by + rintro ⟨b,i⟩ ⟨c,j⟩ hne + by_cases hbc : b = c + · subst c + apply hCC b + intro hij + exact hne (by cases hij; rfl) + · apply Disjoint.mono (hC b i) (hC c j) + rw [Set.disjoint_union_left,Set.disjoint_union_right,Set.disjoint_union_right] + exact ⟨⟨hKK hbc,hKR b c⟩,⟨(hKR c b).symm,hRR hbc⟩⟩ + +lemma completed_subfamilies_cover {E : Type cycleUniverse48} {B : Type cycleUniverse49} {I : B → Type cycleUniverse56} + (K : B → Set E) (Q C : ∀ b, I b → Set E) + (hQ : ∀ b, (⋃ i, Q b i) = K b) + (hQC : ∀ b i, Q b i ⊆ C b i) : + (⋃ b, K b) ⊆ ⋃ s : Sigma I, C s.1 s.2 := by + intro e he + obtain ⟨b,hb⟩ := Set.mem_iUnion.mp he + rw [← hQ b] at hb + obtain ⟨i,hi⟩ := Set.mem_iUnion.mp hb + exact Set.mem_iUnion.mpr ⟨⟨b,i⟩,hQC b i hi⟩ + +lemma endpointLoad_family_card {V I : Type} [Fintype V] [DecidableEq V] [Fintype I] + (x y : I → V) (hne : ∀ i, x i ≠ y i) + (hload : ∀ v, endpointLoad univ x y v ≤ 2) : + Fintype.card I ≤ Fintype.card V := by + classical + have hs := endpointLoad_sum (univ : Finset I) x y (fun i _ => hne i) + have hb := Finset.sum_le_sum (fun v (_ : v ∈ (univ : Finset V)) => hload v) + simp only [Finset.card_univ] at hs + rw [hs] at hb + simp only [Finset.sum_const,Finset.card_univ,smul_eq_mul] at hb + omega + +lemma sigma_three_card_le {V : Type} [Fintype V] + (I : Fin 3 → Type) [∀ b, Fintype (I b)] + (hI : ∀ b, Fintype.card (I b) ≤ Fintype.card V) : + Fintype.card (Sigma I) ≤ 3 * Fintype.card V := by + rw [Fintype.card_sigma] + calc + _ ≤ ∑ _b : Fin 3, Fintype.card V := Finset.sum_le_sum (fun b _ => hI b) + _ = _ := by simp [mul_comm] + +end +end ErdosGallai + +namespace ErdosGallai +noncomputable section +open Finset SimpleGraph +attribute [local instance] Classical.propDecidable + +theorem uniform_three_reservoir_completion (c p : ℝ) (hc : 0 < c) (hp : 0 < p) : + ∃ D₀ : ℝ, 1 < D₀ ∧ ∀ D ≥ D₀, + ∀ (V : Type) [Fintype V] [DecidableEq V], + ∀ (G : SimpleGraph V) (P K : Fin 3 → SimpleGraph V) + [∀ b, DecidableRel (P b).Adj], + (∀ b, P b ≤ G) → + Pairwise (fun b d => Disjoint (P b).edgeSet (P d).edgeSet) → + ∀ (W : Fin 3 → Finset V) (r : Fin 3 → V × Fin 2 → V), + (∀ b, CutExpansionOn (P b) (W b) (D^(37/50:ℝ))) → + (∀ b, 2 ≤ (W b).card) → (Fintype.card V : ℝ) ≤ D^(51/50:ℝ) → + (∀ b v, v ∉ W b → ∀ t, r b (v,t) ∈ W b ∧ (P b).Adj v (r b (v,t))) → + (∀ b v, v ∉ W b → r b (v,0) ≠ r b (v,1)) → + (∀ b v, (((W b)ᶜ ×ˢ univ).filter (fun z => r b z = v)).card ≤ + ⌈8*(Fintype.card V:ℝ)/(p*(c*D^(9/10:ℝ)))⌉₊) → + let T := fun b => reservoirInternal (P b) (W b) ∪ + (reservoirSpokes (W b) (r b) : Set (Sym2 V)) + Pairwise (fun b d => Disjoint (K b).edgeSet (K d).edgeSet) → + (∀ b d, Disjoint (K b).edgeSet (T d)) → + ∀ (I : Fin 3 → Type) [∀ b, Fintype (I b)] + (x y : ∀ b, I b → V) (Q : ∀ b i, G.Walk (x b i) (y b i)), + (∀ b i, (Q b i).IsPath) → (∀ b i, 0 < (Q b i).length) → + (∀ b i v, v ∈ (Q b i).support → v ∉ W b) → + (∀ b, Pairwise fun i j => Disjoint (Q b i).edgeSet (Q b j).edgeSet) → + (∀ b, (⋃ i, (Q b i).edgeSet) = (K b).edgeSet) → + (∀ b v, endpointLoad univ (x b) (y b) v ≤ 2) → + ∃ C : ∀ b i, G.Walk (x b i) (x b i), + (∀ b i, (C b i).IsCycle) ∧ + Pairwise (fun s t : Sigma I => + Disjoint (C s.1 s.2).edgeSet (C t.1 t.2).edgeSet) ∧ + (∀ b i, (C b i).edgeSet ⊆ (K b).edgeSet ∪ T b) ∧ + (⋃ b, (K b).edgeSet) ⊆ (⋃ s : Sigma I, (C s.1 s.2).edgeSet) ∧ + Fintype.card (Sigma I) ≤ 3 * Fintype.card V := by + classical + obtain ⟨D₀,hD₀,hclose⟩ := uniform_reservoir_completion c p hc hp + refine ⟨D₀,hD₀,?_⟩ + intro D hD V _ _ G P K _ hPG hPP W r hexp hW hn hr hrne hcap + dsimp only + intro hKK hKT I _ x y Q hQ hpos hout hQQ hcover hl + have hex : ∀ b : Fin 3, + ∃ (a z : I b → V) (q : ∀ i, G.Walk (a i) (z i)) + (C : ∀ i, G.Walk (x b i) (x b i)), + (∀ i, (C i).IsCycle) ∧ + Pairwise (fun i j => Disjoint (C i).edgeSet (C j).edgeSet) ∧ + (∀ i, (C i).edgeSet = (Q b i).edgeSet ∪ (q i).edgeSet ∪ + {s(x b i,a i),s(y b i,z i)}) ∧ + (∀ i, (q i).edgeSet ⊆ (P b).edgeSet ∧ ∀ v ∈ (q i).support, v ∈ W b) ∧ + Function.Injective (fun z' : I b × Fin 2 => + if z'.2 = 0 then s(x b z'.1,a z'.1) else s(y b z'.1,z z'.1)) ∧ + (∀ i, ∃ t, a i = r b (x b i,t)) ∧ + (∀ i, ∃ t, z i = r b (y b i,t)) := by + intro b + exact hclose D hD V G (P b) (hPG b) (W b) (hexp b) (hW b) hn + (I b) (x b) (y b) (Q b) (hQ b) (hpos b) (hout b) (hQQ b) (hl b) + (r b) (hr b) (hrne b) (hcap b) + choose a z q C hCy hCC hCe hqe _hsp ha hz using hex + have hsub : ∀ b i, (C b i).edgeSet ⊆ (K b).edgeSet ∪ + (reservoirInternal (P b) (W b) ∪ (reservoirSpokes (W b) (r b) : Set _)) := by + intro b i + apply completion_edges_subset (W b) (r b) (Q b i) (q b i) (C b i) + (K b).edgeSet _ (hCe b i) (hqe b i) + (hout b i _ (Q b i).start_mem_support) + (hout b i _ (Q b i).end_mem_support) (ha b i) (hz b i) + intro e he + rw [← hcover b] + exact Set.mem_iUnion.mpr ⟨i,he⟩ + have hreserv := reservoir_reservations G P W r hPG hPP + (fun b v hv t => (hr b v hv t).2) + refine ⟨C,hCy,?_,hsub,?_,?_⟩ + · exact completed_subfamilies_disjoint (fun b => (K b).edgeSet) + (fun b => reservoirInternal (P b) (W b) ∪ + (reservoirSpokes (W b) (r b) : Set _)) + (fun b i => (C b i).edgeSet) hKK hreserv.2.1 hKT hsub hCC + · apply completed_subfamilies_cover (fun b => (K b).edgeSet) + (fun b i => (Q b i).edgeSet) (fun b i => (C b i).edgeSet) hcover + intro b i e he + rw [hCe b i] + exact Or.inl (Or.inl he) + · apply sigma_three_card_le I + intro b + apply endpointLoad_family_card (x b) (y b) _ (hl b) + intro i hi + have hz := ((hQ b i).nil_iff_eq.mpr hi).length_eq_zero + have hp := hpos b i + omega + +end +end ErdosGallai + +namespace ErdosGallai +noncomputable section +open Finset SimpleGraph +attribute [local instance] Classical.propDecidable + +noncomputable def allReservoirSpokes {V : Type cycleUniverse50} [Fintype V] [DecidableEq V] + (W : Fin 3 → Finset V) (r : Fin 3 → V × Fin 2 → V) : Finset (Sym2 V) := + univ.biUnion (fun b => reservoirSpokes (W b) (r b)) + +lemma coe_allReservoirSpokes {V : Type cycleUniverse51} [Fintype V] [DecidableEq V] + (W : Fin 3 → Finset V) (r : Fin 3 → V × Fin 2 → V) : + (allReservoirSpokes W r : Set (Sym2 V)) = + ⋃ b, (reservoirSpokes (W b) (r b) : Set (Sym2 V)) := by + ext e + simp [allReservoirSpokes] + +lemma allReservoirSpokes_card_le {V : Type cycleUniverse52} [Fintype V] [DecidableEq V] + (W : Fin 3 → Finset V) (r : Fin 3 → V × Fin 2 → V) : + (allReservoirSpokes W r).card ≤ 6 * Fintype.card V := by + apply (Finset.card_biUnion_le).trans + calc + (∑ b : Fin 3, (reservoirSpokes (W b) (r b)).card) ≤ + ∑ _b : Fin 3, 2 * Fintype.card V := + Finset.sum_le_sum (fun b _ => reservoirSpokes_card_le (W b) (r b)) + _ = _ := by simp; omega + +theorem three_reservoir_remainder {V : Type cycleUniverse53} {I : Type cycleUniverse54} [Fintype V] [DecidableEq V] [Fintype I] + (G : SimpleGraph V) (P : Fin 3 → SimpleGraph V) + (W : Fin 3 → Finset V) (r : Fin 3 → V × Fin 2 → V) + (hPG : ∀ b, P b ≤ G) + (hPP : Pairwise fun b d => Disjoint (P b).edgeSet (P d).edgeSet) + (hr : ∀ b v, v ∉ W b → ∀ t, (P b).Adj v (r b (v,t))) + (C : I → Set (Sym2 V)) (hC : ∀ i, C i ⊆ G.edgeSet) + (hCC : Pairwise fun i j => Disjoint (C i) (C j)) + (hI : Fintype.card I ≤ 3 * Fintype.card V) + (hcover : G.edgeSet \ ((⋃ b, reservoirInternal (P b) (W b)) ∪ + (allReservoirSpokes W r : Set _)) ⊆ completedEdges C) : + let R := fun b => reservoirInternal (P b) (W b) + let H := residualInternalGraph G R C + let S := unusedSpokes (↑(allReservoirSpokes W r)) C + (∀ b, (H b).support ⊆ (W b : Set V)) ∧ + (∀ b, Sym2.map Subtype.val '' ((H b).induce (W b : Set V)).edgeSet = (H b).edgeSet) ∧ + (∀ b, (H b).edgeSet = R b \ completedEdges C) ∧ + Pairwise (fun b d => Disjoint (H b).edgeSet (H d).edgeSet) ∧ + (∀ b i, Disjoint (H b).edgeSet (C i)) ∧ + (∀ b, Disjoint (H b).edgeSet (S : Set _)) ∧ + (∀ i, Disjoint (C i) (S : Set _)) ∧ + (completedEdges C ∪ (S : Set _) ∪ (⋃ b, (H b).edgeSet)) = G.edgeSet ∧ + Fintype.card I + S.card ≤ 9 * Fintype.card V := by + classical + dsimp only + obtain ⟨hsub,hTT,_hown,hRS,_hcount⟩ := reservoir_reservations G P W r hPG hPP hr + have hS : (allReservoirSpokes W r : Set (Sym2 V)) ⊆ G.edgeSet := by + rw [coe_allReservoirSpokes] + exact Set.iUnion_subset (fun b => (hsub b).2) + have hRR : Pairwise fun b d => + Disjoint (reservoirInternal (P b) (W b)) (reservoirInternal (P d) (W d)) := by + intro b d hbd + exact (hTT hbd).mono Set.subset_union_left Set.subset_union_left + have hRO : ∀ b, Disjoint (reservoirInternal (P b) (W b)) + (allReservoirSpokes W r : Set (Sym2 V)) := by + intro b + rw [coe_allReservoirSpokes] + exact hRS.mono_left (Set.subset_iUnion (fun d => reservoirInternal (P d) (W d)) b) + let R := fun b => reservoirInternal (P b) (W b) + let H := residualInternalGraph G R C + have hledger := residue_edge_ledger G R (↑(allReservoirSpokes W r)) C + (fun b => (hsub b).1) hS hRR hRO hC hCC hcover + have hsupp : ∀ b, (H b).support ⊆ (W b : Set V) := by + intro b v hv + obtain ⟨w,hw⟩ := (H b).mem_support.mp hv + have he : s(v,w) ∈ (H b).edgeSet := hw + rw [hledger.1 b] at he + exact he.1.2 _ (Sym2.mem_mk_left _ _) + refine ⟨hsupp,?_,hledger.1,hledger.2.1,hledger.2.2.1, + hledger.2.2.2.1,hledger.2.2.2.2.1,hledger.2.2.2.2.2,?_⟩ + · intro b + exact induce_edge_image_of_support_subset (H b) (W b) (hsupp b) + · exact residue_part_count (allReservoirSpokes W r) C hI (allReservoirSpokes_card_le W r) + +end +end ErdosGallai + +end +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/CycleDecomposition/ReservoirSampling.lean b/lean/OAI/Combinatorics/CycleDecomposition/ReservoirSampling.lean new file mode 100644 index 0000000000000000000000000000000000000000..885fe927826ac8155256d9520f84e3da703fd23e --- /dev/null +++ b/lean/OAI/Combinatorics/CycleDecomposition/ReservoirSampling.lean @@ -0,0 +1,398 @@ +import OAI.Combinatorics.CycleDecomposition.SamplingCuts + +namespace OAI + +universe cycleUniverse1 cycleUniverse2 cycleUniverse3 cycleUniverse4 + +section +open Filter Asymptotics Real +open scoped Topology +noncomputable section +namespace ErdosGallai.Sampling + +lemma eventually_monomial_lt (K c a b : ℝ) (hc : 0 < c) (hab : a < b) : + ∀ᶠ D : ℝ in atTop, K * D^a < c * D^b := by + have ht : Tendsto (fun D : ℝ => K * D^(a-b)) atTop (𝓝 0) := by + have hh := (tendsto_rpow_neg_atTop (sub_pos.mpr hab)).const_mul K + simpa only [neg_sub, mul_zero] using hh + filter_upwards [eventually_gt_atTop (0 : ℝ), ht.eventually_lt_const hc] with D hD htD + have hb : 0 < D^b := Real.rpow_pos_of_pos hD b + have heq : D^a = D^(a-b) * D^b := by rw [← Real.rpow_add hD]; congr 1; ring + rw [heq, ← mul_assoc] + exact mul_lt_mul_of_pos_right htD hb + +lemma tendsto_monomial_exp_neg_power (a b c : ℝ) (hb : 0 < b) (hc : 0 < c) : + Tendsto (fun D : ℝ => D^a * exp (-c * D^b)) atTop (𝓝 0) := by + have ht := (tendsto_rpow_mul_exp_neg_mul_atTop_nhds_zero (a/b) c hc).comp + (tendsto_rpow_atTop hb) + apply ht.congr' + filter_upwards [eventually_gt_atTop (0 : ℝ)] with D hD + dsimp only [Function.comp_def] + rw [← Real.rpow_mul hD.le, mul_div_cancel₀ _ hb.ne'] + +lemma eventually_log_le_small_power : ∀ᶠ D : ℝ in atTop, log D ≤ D^(1/10 : ℝ) := by + filter_upwards [(isLittleO_log_rpow_atTop (show (0 : ℝ) < 1/10 by norm_num)).eventuallyLE, + eventually_ge_atTop (1 : ℝ)] with D hD h1 + simpa only [Real.norm_eq_abs, abs_of_nonneg (Real.log_nonneg h1), + abs_of_nonneg (Real.rpow_nonneg (by linarith) _)] using hD + +def samplingScaleError (c p D : ℝ) : ℝ := + exp (-p/3 * D^(9/10 : ℝ)) + + D^(51/50 : ℝ) * exp (-(p*c/8) * D^(9/10 : ℝ)) + + (2*(4/c+2)) * (D^(23/20 : ℝ) * exp (-(p^3*c^2/512) * D^(39/50 : ℝ))) + +lemma samplingScaleError_tendsto (c p : ℝ) (hc : 0 < c) (hp : 0 < p) : + Tendsto (samplingScaleError c p) atTop (𝓝 0) := by + have h0 := tendsto_monomial_exp_neg_power 0 (9/10) (p/3) (by norm_num) (by positivity) + have h1 := tendsto_monomial_exp_neg_power (51/50) (9/10) (p*c/8) (by norm_num) (by positivity) + have h2 := (tendsto_monomial_exp_neg_power (23/20) (39/50) (p^3*c^2/512) + (by norm_num) (by positivity)).const_mul (2*(4/c+2)) + unfold samplingScaleError + simpa [neg_div, Real.rpow_zero] using (h0.add h1).add h2 + +def SamplingScaleReady (c p D : ℝ) (r : ℕ) : Prop := + let h := c*D^(9/10 : ℝ) + let τ := D^(37/50 : ℝ) + let M := D^(1/100 : ℝ) + 2 ≤ r ∧ τ < p*h/4 ∧ M ≤ h ∧ (r : ℝ)*exp (-p*M/4) < 1/2 ∧ + 4*τ/(p*h)+4*τ*M/h ≤ 1/2 ∧ + τ+r*(4*τ/(p*h)+4*τ*M/h) ≤ p^2*h/8 ∧ + exp (-p*r/3) + r*exp (-p*h/8) + + 2*r*((⌈4*r*M/h⌉₊+1 : ℕ) : ℝ) * (r : ℝ)^⌈4*r*M/h⌉₊ * + exp (-p^3*h^2/(256*r)) ≤ samplingScaleError c p D + +lemma sampling_witness_error_le (c p D : ℝ) (r : ℕ) (hc : 0 < c) (hp : 0 < p) + (hD : 1 ≤ D) (hrpos : 0 < (r : ℝ)) (hrhi : (r : ℝ) ≤ D^(51/50 : ℝ)) + (hlog : log D ≤ D^(1/10 : ℝ)) + (hcost : ((51/50)*(4/c+2))*D^(23/100 : ℝ) ≤ + (p^3*c^2/512)*D^(39/50 : ℝ)) : + let h := c*D^(9/10 : ℝ) + let M := D^(1/100 : ℝ) + 2*r*((⌈4*r*M/h⌉₊+1 : ℕ) : ℝ)*(r : ℝ)^⌈4*r*M/h⌉₊* + exp (-p^3*h^2/(256*r)) ≤ + (2*(4/c+2))*(D^(23/20 : ℝ)*exp (-(p^3*c^2/512)*D^(39/50 : ℝ))) := by + let h := c*D^(9/10 : ℝ) + let M := D^(1/100 : ℝ) + let K := 4/c+2 + have hK : 0 < K := by dsimp [K]; positivity + have hDpos : 0 < D := by linarith + have hh : 0 < h := by dsimp [h]; positivity + have hMpos : 0 < M := Real.rpow_pos_of_pos hDpos _ + have hrNat : 0 < r := by exact_mod_cast hrpos + have hs : ((⌈4*r*M/h⌉₊+1 : ℕ) : ℝ) ≤ K*D^(13/100 : ℝ) := by + have hnorm : 4*D^(51/50 : ℝ)*M/h = (4/c)*D^(13/100 : ℝ) := by + dsimp [M,h] + rw [show (13/100 : ℝ) = (51/50+1/100)-9/10 by norm_num, + Real.rpow_sub hDpos, Real.rpow_add hDpos] + field_simp + calc + _ ≤ 4*r*M/h+2 := by + have hs := (Nat.ceil_lt_add_one (show 0 ≤ 4*(r : ℝ)*M/h by positivity)).le + push_cast + linarith + _ ≤ 4*D^(51/50 : ℝ)*M/h+2 := by gcongr + _ = (4/c)*D^(13/100 : ℝ)+2 := by rw [hnorm] + _ ≤ K*D^(13/100 : ℝ) := by + have hd := Real.one_le_rpow hD (show (0 : ℝ) ≤ 13/100 by norm_num) + dsimp [K] + nlinarith + have hln : log (r : ℝ) ≤ (51/50)*log D := by + simpa only [Real.log_rpow hDpos] using Real.log_le_log hrpos hrhi + have hecost : (⌈4*r*M/h⌉₊ : ℝ)*log (r : ℝ) ≤ + (p^3*c^2/512)*D^(39/50 : ℝ) := by + have hs' : (⌈4*r*M/h⌉₊ : ℝ) ≤ K*D^(13/100 : ℝ) := by push_cast at hs; linarith + calc + _ ≤ K*D^(13/100 : ℝ)*((51/50)*log D) := by + apply mul_le_mul hs' hln + · exact Real.log_nonneg (by exact_mod_cast (show 1 ≤ r by omega)) + · positivity + _ ≤ K*D^(13/100 : ℝ)*((51/50)*D^(1/10 : ℝ)) := by gcongr + _ = ((51/50)*K)*D^(23/100 : ℝ) := by + have he := Real.rpow_add hDpos (13/100 : ℝ) (1/10) + norm_num at he + rw [he] + ring + _ ≤ _ := hcost + have hratio : c^2*D^(39/50 : ℝ) ≤ h^2/(r : ℝ) := by + have he : c^2*D^(39/50 : ℝ) = h^2/D^(51/50 : ℝ) := by + dsimp [h] + rw [show (39/50 : ℝ) = (9/10)*2-51/50 by norm_num, + Real.rpow_sub hDpos] + have he2 := Real.rpow_mul_natCast hDpos.le (9/10 : ℝ) 2 + norm_num only [Nat.cast_ofNat] at he2 + rw [show (9/10 : ℝ)*2=9/5 by norm_num, he2] + ring + rw [he] + exact div_le_div_of_nonneg_left (sq_nonneg h) hrpos hrhi + have hexpcost : exp ((⌈4*r*M/h⌉₊ : ℝ)*log (r : ℝ) - p^3*h^2/(256*r)) ≤ + exp (-(p^3*c^2/512)*D^(39/50 : ℝ)) := by + apply Real.exp_le_exp.mpr + have hn := mul_le_mul_of_nonneg_left hratio (show 0 ≤ p^3/256 by positivity) + have hid : (p^3/256)*(h^2/(r : ℝ)) =p^3*h^2/(256*r) := by ring + rw [hid] at hn + nlinarith + have hpoly : 2*(r : ℝ)*((⌈4*r*M/h⌉₊+1 : ℕ) : ℝ) ≤ + 2*K*D^(23/20 : ℝ) := by + calc + _ ≤ 2*D^(51/50 : ℝ)*(K*D^(13/100 : ℝ)) := by gcongr + _ = _ := by + have he := Real.rpow_add hDpos (51/50 : ℝ) (13/100) + norm_num at he + rw [he] + ring + have hwitness : 2*r*((⌈4*r*M/h⌉₊+1 : ℕ) : ℝ)*(r : ℝ)^⌈4*r*M/h⌉₊* + exp (-p^3*h^2/(256*r)) ≤ + (2*K)*(D^(23/20 : ℝ)*exp (-(p^3*c^2/512)*D^(39/50 : ℝ))) := by + have heq : (r : ℝ)^⌈4*r*M/h⌉₊*exp (-p^3*h^2/(256*r)) = + exp ((⌈4*r*M/h⌉₊ : ℝ)*log (r : ℝ)-p^3*h^2/(256*r)) := by + rw [Real.exp_sub, Real.exp_nat_mul, Real.exp_log hrpos] + simp only [neg_mul, Real.exp_neg, div_eq_mul_inv] + rw [mul_assoc (2*(r : ℝ)*_) _ _, heq] + exact (mul_le_mul hpoly hexpcost (exp_pos _).le (by positivity)).trans_eq (by ring) + exact hwitness + +lemma eventually_samplingScaleReady (c p : ℝ) (hc : 0 < c) (hp : 0 < p) : + ∀ᶠ D : ℝ in atTop, ∀ r : ℕ, + D^(9/10 : ℝ) ≤ r → (r : ℝ) ≤ D^(51/50 : ℝ) → SamplingScaleReady c p D r := by + let K := 4/c+2 + have hK : 0 < K := by dsimp [K]; positivity + have hmiss : Tendsto (fun D : ℝ => D^(51/50 : ℝ) * exp (-p/4*D^(1/100 : ℝ))) + atTop (𝓝 0) := by + convert tendsto_monomial_exp_neg_power (51/50) (1/100) (p/4) + (by norm_num) (by positivity) using 1 ; simp [neg_div] + filter_upwards [eventually_ge_atTop (1 : ℝ), + (tendsto_rpow_atTop (show (0 : ℝ) < 9/10 by norm_num)).eventually_ge_atTop 2, + eventually_monomial_lt 1 (p*c/4) (37/50) (9/10) (by positivity) (by norm_num), + eventually_monomial_lt 1 c (1/100) (9/10) hc (by norm_num), + hmiss.eventually_lt_const (show (0 : ℝ) < 1/2 by norm_num), + eventually_monomial_lt (4/(p*c)) (1/4) (-4/25) 0 (by norm_num) (by norm_num), + eventually_monomial_lt (4/c) (1/4) (-3/20) 0 (by norm_num) (by norm_num), + eventually_monomial_lt 1 (p^2*c/24) (37/50) (9/10) (by positivity) (by norm_num), + eventually_monomial_lt (4/(p*c)) (p^2*c/24) (43/50) (9/10) (by positivity) (by norm_num), + eventually_monomial_lt (4/c) (p^2*c/24) (87/100) (9/10) (by positivity) (by norm_num), + eventually_log_le_small_power, + eventually_monomial_lt ((51/50)*K) (p^3*c^2/512) (23/100) (39/50) + (by positivity) (by norm_num)] with D hD h2 hτ hM hm hε₁ hε₂ ht₀ ht₁ ht₂ hlog hcost + intro r hrlo hrhi + have hDpos : 0 < D := by linarith + have hr2 : 2 ≤ r := by exact_mod_cast h2.trans hrlo + have hrpos : 0 < (r : ℝ) := by exact_mod_cast (show 0 < r by omega) + let h := c*D^(9/10 : ℝ) + let τ := D^(37/50 : ℝ) + let M := D^(1/100 : ℝ) + have hh : 0 < h := by dsimp [h]; positivity + have hτpos : 0 < τ := Real.rpow_pos_of_pos hDpos _ + have hMpos : 0 < M := Real.rpow_pos_of_pos hDpos _ + have he₁ : 4*τ/(p*h) = (4/(p*c))*D^(-4/25 : ℝ) := by + dsimp [τ,h] + rw [show (-4/25 : ℝ) =37/50-9/10 by norm_num, Real.rpow_sub hDpos] + field_simp + have he₂ : 4*τ*M/h = (4/c)*D^(-3/20 : ℝ) := by + dsimp [τ,M,h] + rw [show (-3/20 : ℝ) =(37/50+1/100)-9/10 by norm_num, + Real.rpow_sub hDpos, Real.rpow_add hDpos] + field_simp + have hm₁ : D^(51/50 : ℝ)*((4/(p*c))*D^(-4/25 : ℝ)) = + (4/(p*c))*D^(43/50 : ℝ) := by + rw [mul_left_comm, ← Real.rpow_add hDpos] + norm_num + have hm₂ : D^(51/50 : ℝ)*((4/c)*D^(-3/20 : ℝ)) = + (4/c)*D^(87/100 : ℝ) := by + rw [mul_left_comm, ← Real.rpow_add hDpos] + norm_num + refine ⟨hr2, ?_, (by simpa only [one_mul] using hM.le), ?_, ?_, ?_, ?_⟩ + · change τ < p*h/4 + dsimp [τ,h] + simpa only [one_mul, div_mul_eq_mul_div, mul_assoc] using hτ + · change (r : ℝ)*exp (-p*M/4) < 1/2 + calc + _ ≤ D^(51/50 : ℝ)*exp (-p*M/4) := mul_le_mul_of_nonneg_right hrhi (exp_pos _).le + _ < _ := by simpa [M, div_mul_eq_mul_div] using hm + · change 4*τ/(p*h)+4*τ*M/h ≤ 1/2 + rw [he₁, he₂] + simp only [Real.rpow_zero, mul_one] at hε₁ hε₂ + linarith + · change τ+(r : ℝ)*(4*τ/(p*h)+4*τ*M/h) ≤ p^2*h/8 + rw [he₁,he₂] + have ht : (r : ℝ)*((4/(p*c))*D^(-4/25 : ℝ)+(4/c)*D^(-3/20 : ℝ)) ≤ + (4/(p*c))*D^(43/50 : ℝ)+(4/c)*D^(87/100 : ℝ) := by + calc + _ ≤ D^(51/50 : ℝ)*((4/(p*c))*D^(-4/25 : ℝ)+(4/c)*D^(-3/20 : ℝ)) := by + apply mul_le_mul_of_nonneg_right hrhi; positivity + _ = _ := by rw [mul_add, hm₁, hm₂] + dsimp [τ,h] + nlinarith + · change exp (-p*r/3)+r*exp (-p*h/8)+ + 2*r*((⌈4*r*M/h⌉₊+1 : ℕ) : ℝ)*(r : ℝ)^⌈4*r*M/h⌉₊* + exp (-p^3*h^2/(256*r)) ≤ samplingScaleError c p D + have hwitness := sampling_witness_error_le c p D r hc hp hD hrpos hrhi hlog hcost.le + have hsize : exp (-p*r/3) ≤ exp (-p/3*D^(9/10 : ℝ)) := by + apply exp_le_exp.mpr + have ht := mul_le_mul_of_nonneg_left hrlo hp.le + nlinarith + have hdegree : (r : ℝ)*exp (-p*h/8) ≤ + D^(51/50 : ℝ)*exp (-(p*c/8)*D^(9/10 : ℝ)) := by + have heq : -p*h/8=-(p*c/8)*D^(9/10 : ℝ) := by dsimp [h]; ring + rw [heq] + exact mul_le_mul_of_nonneg_right hrhi (exp_pos _).le + exact add_le_add (add_le_add hsize hdegree) hwitness + +end ErdosGallai.Sampling + +namespace ErdosGallai.Sampling +open Filter MeasureTheory Real + +universe u + +theorem vertex_sampling_uniform (c : ℝ) (hc : 0 < c) (p : unitInterval) + (hp : 0 < (p : ℝ)) (_hp1 : (p : ℝ) < 1) (ε : ℝ) (hε : 0 < ε) : + ∃ D₀ : ℝ, ∀ D : ℝ, D₀ ≤ D → ∀ (V : Type u) [Fintype V] [DecidableEq V] + (P : SimpleGraph V) [DecidableRel P.Adj], + D^(9/10 : ℝ) ≤ (Fintype.card V : ℝ) → + (Fintype.card V : ℝ) ≤ D^(51/50 : ℝ) → + CutExpansion P (c*D^(9/10 : ℝ)) → + (sampleMeasure V p).real {ω | ¬SampleGood P (p : ℝ) (c*D^(9/10 : ℝ)) + (D^(37/50 : ℝ)) ω} ≤ ε := by + have hevent : ∀ᶠ D : ℝ in atTop, + 1 ≤ D ∧ + (∀ r : ℕ, D^(9/10 : ℝ) ≤ r → (r : ℝ) ≤ D^(51/50 : ℝ) → + SamplingScaleReady c (p : ℝ) D r) ∧ + samplingScaleError c (p : ℝ) D ≤ ε := by + filter_upwards [eventually_ge_atTop (1 : ℝ), eventually_samplingScaleReady c (p : ℝ) hc hp, + (samplingScaleError_tendsto c (p : ℝ) hc hp).eventually_le_const hε] with D h1 h2 h3 + exact ⟨h1,h2,h3⟩ + obtain ⟨D₀,hD₀⟩ := hevent.exists_forall_of_atTop + refine ⟨D₀, ?_⟩ + intro D hD V _ _ P _ hrlo hrhi hexp + obtain ⟨h1, hready, herr⟩ := hD₀ D hD + have hDpos : 0 < D := by linarith + obtain ⟨hr,hτ,hM,hmiss,he,hperturb,hbound⟩ := hready (Fintype.card V) hrlo hrhi + exact (vertex_sampling_failure_bound P p hp (by positivity) (by positivity) + hτ (by positivity) hM hr hmiss he hperturb hexp).trans (hbound.trans herr) + +end ErdosGallai.Sampling + +open MeasureTheory ProbabilityTheory Finset +noncomputable section +namespace ErdosGallai.Sampling + +def reservoirLabelPMF (p : unitInterval) (hp : 3*(p : ℝ) ≤ 1) : PMF (Fin 4) := + PMF.ofFintype (fun i => ENNReal.ofReal (if i = 3 then 1-3*(p : ℝ) else (p : ℝ))) (by + rw [Fin.sum_univ_four] + simp only [show (0 : Fin 4) ≠ 3 by decide, show (1 : Fin 4) ≠ 3 by decide, + show (2 : Fin 4) ≠ 3 by decide, ↓reduceIte, ] + rw [← ENNReal.ofReal_add p.property.1 p.property.1, + ← ENNReal.ofReal_add (by linarith [p.property.1]) p.property.1, + ← ENNReal.ofReal_add (by linarith [p.property.1]) (by linarith)] + norm_num [show (p : ℝ)+(p : ℝ)+(p : ℝ)+(1-3*(p : ℝ)) = 1 by ring]) + +def labelIs (i : Fin 3) (j : Fin 4) : Bool := decide (j = i.castSucc) + +lemma ofReal_unitInterval (p : unitInterval) : + ENNReal.ofReal (p : ℝ) = (unitInterval.toNNReal p : ENNReal) := by + unfold ENNReal.ofReal + apply congrArg (fun x : NNReal => (x : ENNReal)) + apply Subtype.ext + exact Real.coe_toNNReal _ p.property.1 + +lemma labelIs_preserving (p : unitInterval) (hp : 3*(p : ℝ) ≤ 1) (i : Fin 3) : + MeasurePreserving (labelIs i) (reservoirLabelPMF p hp).toMeasure + (bernoulliMeasure true false p) := by + have hnon : 0 ≤ (p : ℝ) := p.property.1 + have hnon' : 0 ≤ 1-3*(p : ℝ) := by linarith + refine ⟨measurable_of_finite _, ?_⟩ + apply Measure.ext_iff_singleton.mpr + intro b + rw [Measure.map_apply (measurable_of_finite _) (measurableSet_singleton _)] + rw [PMF.toMeasure_apply_fintype] + simp only [reservoirLabelPMF] + cases b <;> fin_cases i <;> + simp [labelIs, Fin.sum_univ_four, PMF.ofFintype_apply] + all_goals + first + | exact ofReal_unitInterval p + | rw [← ENNReal.ofReal_add hnon hnon, + ← ENNReal.ofReal_add (by linarith : 0 ≤ (p : ℝ)+(p : ℝ)) hnon'] + convert ofReal_unitInterval (unitInterval.symm p) using 1 + congr 1 + change (p : ℝ)+(p : ℝ)+(1-3*(p : ℝ)) = 1-(p : ℝ) + ring + +end ErdosGallai.Sampling + +namespace ErdosGallai.Sampling +open Finset MeasureTheory ProbabilityTheory +noncomputable section +variable {V : Type cycleUniverse1} [Fintype V] [DecidableEq V] + +def reservoirSample (i : Fin 3) (ω : V → Fin 4) : V → Bool := fun v => labelIs i (ω v) + +def reservoirMeasure (V : Type cycleUniverse2) [Fintype V] (p : unitInterval) (hp : 3*(p : ℝ) ≤ 1) : + Measure (V → Fin 4) := Measure.pi (fun _ : V => (reservoirLabelPMF p hp).toMeasure) + +instance reservoirMeasure_probability (p : unitInterval) (hp : 3*(p : ℝ) ≤ 1) : + IsProbabilityMeasure (reservoirMeasure V p hp) := by unfold reservoirMeasure; infer_instance + +lemma reservoirSample_preserving {V : Type cycleUniverse3} [_contextInstance1 : Fintype V] [_contextInstance2 : DecidableEq V] (p : unitInterval) (hp : 3*(p : ℝ) ≤ 1) (i : Fin 3) : + MeasurePreserving (reservoirSample i) (reservoirMeasure V p hp) (sampleMeasure V p) := by + exact measurePreserving_pi _ _ (fun _ => labelIs_preserving p hp i) + +lemma reservoirSamples_disjoint {V : Type cycleUniverse4} [_contextInstance1 : Fintype V] [_contextInstance2 : DecidableEq V] (ω : V → Fin 4) (i j : Fin 3) (hij : i ≠ j) : + Disjoint (sampleVertices (reservoirSample i ω)) (sampleVertices (reservoirSample j ω)) := by + apply Finset.disjoint_left.mpr + intro v hi hj + simp only [sampleVertices, Finset.mem_filter, Finset.mem_univ, true_and, + reservoirSample, labelIs, decide_eq_true_eq] at hi hj + exact hij (Fin.castSucc_injective 3 (hi.symm.trans hj)) + +universe u + +theorem three_reservoirs_uniform (c : ℝ) (hc : 0 < c) (p : unitInterval) + (hp : 0 < (p : ℝ)) (hp3 : 3*(p : ℝ) ≤ 1) : + ∃ D₀ : ℝ, ∀ D : ℝ, D₀ ≤ D → ∀ (V : Type u) [Fintype V] [DecidableEq V] + (P : Fin 3 → SimpleGraph V) [∀ i, DecidableRel (P i).Adj], + D^(9/10 : ℝ) ≤ (Fintype.card V : ℝ) → + (Fintype.card V : ℝ) ≤ D^(51/50 : ℝ) → + (∀ i, CutExpansion (P i) (c*D^(9/10 : ℝ))) → + ∃ W : Fin 3 → Finset V, + (∀ i j, i ≠ j → Disjoint (W i) (W j)) ∧ + (∀ i, ((W i).card : ℝ) ≤ 2*(p : ℝ)*Fintype.card V) ∧ + (∀ i v, (p : ℝ)*(c*D^(9/10 : ℝ))/2 ≤ ((neighborsIn (P i) v (W i)).card : ℝ)) ∧ + (∀ i, CutExpansionOn (P i) (W i) (D^(37/50 : ℝ))) := by + have hp1 : (p : ℝ) < 1 := by linarith + obtain ⟨D₀,hD₀⟩ := vertex_sampling_uniform.{u} c hc p hp hp1 (1/4) (by norm_num) + refine ⟨D₀, ?_⟩ + intro D hD V _ _ P _ hlo hhi hcut + let μ := reservoirMeasure V p hp3 + let B : Fin 3 → Set (V → Fin 4) := fun i => + {ω | ¬SampleGood (P i) (p : ℝ) (c*D^(9/10 : ℝ)) (D^(37/50 : ℝ)) (reservoirSample i ω)} + have hB : ∀ i, μ.real (B i) ≤ 1/4 := by + intro i + have hm := (reservoirSample_preserving (V := V) p hp3 i).measure_preimage + ((Set.Finite.measurableSet (Set.toFinite {ω | ¬SampleGood (P i) (p : ℝ) (c*D^(9/10 : ℝ)) + (D^(37/50 : ℝ)) ω})).nullMeasurableSet) + change (μ (B i)).toReal ≤ 1/4 + rw [show μ (B i) = (sampleMeasure V p) {ω | ¬SampleGood (P i) (p : ℝ) + (c*D^(9/10 : ℝ)) (D^(37/50 : ℝ)) ω} from hm] + exact hD₀ D hD V (P i) hlo hhi (hcut i) + have hi : ∑ i ∈ (Finset.univ : Finset (Fin 3)), μ.real (B i) < 1 := by + calc + _ ≤ ∑ i ∈ (Finset.univ : Finset (Fin 3)), (1/4 : ℝ) := by + exact Finset.sum_le_sum (fun i _ => hB i) + _ < 1 := by norm_num + obtain ⟨ω,hω⟩ := exists_avoiding_finite_events (μ := μ) Finset.univ B hi + have hgood : ∀ i, SampleGood (P i) (p : ℝ) (c*D^(9/10 : ℝ)) (D^(37/50 : ℝ)) + (reservoirSample i ω) := by + intro i + exact not_not.mp (hω i (Finset.mem_univ i)) + refine ⟨fun i => sampleVertices (reservoirSample i ω), reservoirSamples_disjoint ω, + fun i => (hgood i).1, fun i => (hgood i).2.1, fun i => (hgood i).2.2⟩ + +end +end ErdosGallai.Sampling + +end +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/CycleDecomposition/Routing.lean b/lean/OAI/Combinatorics/CycleDecomposition/Routing.lean new file mode 100644 index 0000000000000000000000000000000000000000..d67e4e04bf5a1e575e5f1c39cdcb05f43a0805fe --- /dev/null +++ b/lean/OAI/Combinatorics/CycleDecomposition/Routing.lean @@ -0,0 +1,1040 @@ +import OAI.Combinatorics.CycleDecomposition.Representatives + +namespace OAI + +section +open Filter Asymptotics Real +open scoped Topology +noncomputable section +open MeasureTheory ProbabilityTheory Finset +noncomputable section +namespace ErdosGallai + +open Finset + +variable {V : Type} [Fintype V] [DecidableEq V] + +def CutExpansion (P : SimpleGraph V) [DecidableRel P.Adj] (h : ℝ) : Prop := + ∀ U : Finset V, h * min (U.card : ℝ) (Uᶜ.card : ℝ) ≤ + ((P.interedges U Uᶜ).card : ℝ) + +lemma boundary_sym2_injective (P : SimpleGraph V) [DecidableRel P.Adj] + (U : Finset V) : + Set.InjOn (fun e : V × V => s(e.1, e.2)) (P.interedges U Uᶜ : Set (V × V)) := by + intro e he f hf hef + rcases (Sym2.mk_eq_mk_iff.mp hef) with h | h + · exact h + · have he1 := (P.mem_interedges_iff.mp he).1 + have hf2 := (P.mem_interedges_iff.mp hf).2.1 + have hfirst : e.1 = f.2 := congrArg Prod.fst h + exact False.elim ((Finset.mem_compl.mp hf2) (hfirst ▸ he1)) + +lemma deleted_boundary_card_le (P : SimpleGraph V) [DecidableRel P.Adj] + (U : Finset V) (F : Finset (Sym2 V)) : + ((P.interedges U Uᶜ).filter (fun e => s(e.1, e.2) ∈ F)).card ≤ F.card := by + apply Finset.card_le_card_of_injOn (fun e : V × V => s(e.1, e.2)) + · intro e he + exact (Finset.mem_filter.mp he).2 + · exact (boundary_sym2_injective P U).mono (by + intro e he + exact (Finset.mem_filter.mp he).1) + +theorem routing_union_growth_step_of_boundary + (P : SimpleGraph V) [DecidableRel P.Adj] + (h : ℝ) (hexp : CutExpansion P h) + (hr : 0 < (Fintype.card V : ℝ)) + (F : Finset (Sym2 V)) (B Bnext : Finset V) + (W : V → Finset V) + (hmono : B ⊆ Bnext) + (hsmall : (B.card : ℝ) ≤ (Fintype.card V : ℝ) / 2) + (hF : (((P.interedges B Bᶜ).filter (fun e => s(e.1, e.2) ∈ F)).card : ℝ) ≤ + h * (B.card : ℝ) / 4) + (hW : ∀ v ∈ B, ((W v).card : ℝ) ≤ h / 4) + (hextend : ∀ v ∈ B, ∀ w ∉ B, P.Adj v w → s(v, w) ∉ F → + w ∉ W v → w ∈ Bnext) : + (1 + h / (2 * (Fintype.card V : ℝ))) * (B.card : ℝ) ≤ + (Bnext.card : ℝ) := by + let E := P.interedges B Bᶜ + let Ebad := E.filter (fun e => s(e.1, e.2) ∈ F) + let Vbad := B.biUnion (fun v => ({v} : Finset V) ×ˢ (W v)) + let Enew := (Finset.univ : Finset V) ×ˢ (Bnext \ B) + have hcover : E ⊆ Ebad ∪ Vbad ∪ Enew := by + intro e he + rcases P.mem_interedges_iff.mp he with ⟨hv, hw, hadj⟩ + have hnw : e.2 ∉ B := Finset.mem_compl.mp hw + by_cases hdel : s(e.1, e.2) ∈ F + · exact Finset.mem_union_left _ (Finset.mem_union_left _ + (Finset.mem_filter.mpr ⟨he, hdel⟩)) + by_cases hforbid : e.2 ∈ W e.1 + · apply Finset.mem_union_left + apply Finset.mem_union_right + apply Finset.mem_biUnion.mpr + exact ⟨e.1, hv, Finset.mem_product.mpr ⟨by simp, hforbid⟩⟩ + · apply Finset.mem_union_right + exact Finset.mem_product.mpr ⟨Finset.mem_univ _, Finset.mem_sdiff.mpr + ⟨hextend e.1 hv e.2 hnw hadj hdel hforbid, hnw⟩⟩ + have hcount : E.card ≤ Ebad.card + Vbad.card + Enew.card := + (Finset.card_le_card hcover).trans <| + (Finset.card_union_le _ _).trans <| + Nat.add_le_add_right (Finset.card_union_le _ _) _ + have hforbidden : Vbad.card ≤ ∑ v ∈ B, (W v).card := by + simpa [Vbad, Finset.card_product] using + (Finset.card_biUnion_le (s := B) (t := fun v => ({v} : Finset V) ×ˢ W v)) + have hnew : Enew.card = Fintype.card V * (Bnext \ B).card := by + simp [Enew] + have hraw : E.card ≤ Ebad.card + (∑ v ∈ B, (W v).card) + + Fintype.card V * (Bnext \ B).card := by omega + have hsum : (∑ v ∈ B, ((W v).card : ℝ)) ≤ (h / 4) * B.card := by + calc + _ ≤ ∑ _v ∈ B, h / 4 := Finset.sum_le_sum hW + _ = _ := by simp [mul_comm] + have hcomplN : B.card + Bᶜ.card = Fintype.card V := by + rw [Finset.card_compl] + exact Nat.add_sub_of_le (Finset.card_le_univ B) + have hcompl : (B.card : ℝ) + (Bᶜ.card : ℝ) = (Fintype.card V : ℝ) := by + exact_mod_cast hcomplN + have hlecompl : (B.card : ℝ) ≤ (Bᶜ.card : ℝ) := by linarith + have hcut : h * (B.card : ℝ) ≤ (E.card : ℝ) := by + simpa [min_eq_left hlecompl, E] using hexp B + have hdiffN : (Bnext \ B).card + B.card = Bnext.card := by + rw [Finset.card_sdiff_of_subset hmono] + exact Nat.sub_add_cancel (Finset.card_le_card hmono) + have hdiff : ((Bnext \ B).card : ℝ) + (B.card : ℝ) = (Bnext.card : ℝ) := by + exact_mod_cast hdiffN + have hrawR : (E.card : ℝ) ≤ (Ebad.card : ℝ) + + (∑ v ∈ B, ((W v).card : ℝ)) + + (Fintype.card V : ℝ) * ((Bnext \ B).card : ℝ) := by + exact_mod_cast hraw + have hreach : h * (B.card : ℝ) / 2 ≤ + (Fintype.card V : ℝ) * ((Bnext \ B).card : ℝ) := by + nlinarith [hcut, hrawR, hF, hsum] + have hdiv : h * (B.card : ℝ) / (2 * (Fintype.card V : ℝ)) ≤ + ((Bnext \ B).card : ℝ) := by + apply (div_le_iff₀ (by positivity : 0 < 2 * (Fintype.card V : ℝ))).mpr + nlinarith [hreach] + calc + (1 + h / (2 * (Fintype.card V : ℝ))) * (B.card : ℝ) + = (B.card : ℝ) + h * (B.card : ℝ) / (2 * (Fintype.card V : ℝ)) := by ring + _ ≤ (B.card : ℝ) + ((Bnext \ B).card : ℝ) := add_le_add (le_refl _) hdiv + _ = (Bnext.card : ℝ) := by linarith + +theorem routing_union_growth_step + (P : SimpleGraph V) [DecidableRel P.Adj] + (h : ℝ) (hexp : CutExpansion P h) + (hr : 0 < (Fintype.card V : ℝ)) + (F : Finset (Sym2 V)) (B Bnext : Finset V) + (W : V → Finset V) + (hmono : B ⊆ Bnext) + (hsmall : (B.card : ℝ) ≤ (Fintype.card V : ℝ) / 2) + (hF : (F.card : ℝ) ≤ h * (B.card : ℝ) / 4) + (hW : ∀ v ∈ B, ((W v).card : ℝ) ≤ h / 4) + (hextend : ∀ v ∈ B, ∀ w ∉ B, P.Adj v w → s(v, w) ∉ F → + w ∉ W v → w ∈ Bnext) : + (1 + h / (2 * (Fintype.card V : ℝ))) * (B.card : ℝ) ≤ + (Bnext.card : ℝ) := by + apply routing_union_growth_step_of_boundary P h hexp hr F B Bnext W hmono hsmall + · have hd : (((P.interedges B Bᶜ).filter (fun e => s(e.1, e.2) ∈ F)).card : ℝ) ≤ F.card := by + exact_mod_cast deleted_boundary_card_le P B F + exact hd.trans hF + · exact hW + · exact hextend + +def avoidGraph (P : SimpleGraph V) (F : Finset (Sym2 V)) (W : Finset V) : + SimpleGraph V where + Adj v w := P.Adj v w ∧ s(v, w) ∉ F ∧ v ∉ W ∧ w ∉ W + symm := ⟨by + intro v w h + exact ⟨h.1.symm, by simpa only [Sym2.eq_swap] using h.2.1, h.2.2.2, h.2.2.1⟩⟩ + loopless := ⟨by intro v h; exact P.irrefl h.1⟩ + +noncomputable def walkBall (G : SimpleGraph V) (s : V) (t : ℕ) : Finset V := by + classical + exact Finset.univ.filter (fun v => ∃ p : G.Walk s v, p.length ≤ t) + +@[simp] lemma mem_walkBall {V : Type} [_contextInstance1 : Fintype V] [_contextInstance2 : DecidableEq V] (G : SimpleGraph V) (s v : V) (t : ℕ) : + v ∈ walkBall G s t ↔ ∃ p : G.Walk s v, p.length ≤ t := by + classical + simp [walkBall] + +lemma root_mem_walkBall (G : SimpleGraph V) (s : V) (t : ℕ) : + s ∈ walkBall G s t := by + exact (mem_walkBall G s s t).mpr ⟨.nil, by simp⟩ + +lemma walkBall_mono (G : SimpleGraph V) (s : V) {t u : ℕ} (htu : t ≤ u) : + walkBall G s t ⊆ walkBall G s u := by + intro v hv + obtain ⟨p, hp⟩ := (mem_walkBall G s v t).mp hv + exact (mem_walkBall G s v u).mpr ⟨p, hp.trans htu⟩ + +lemma walk_avoids_end {V : Type} [_contextInstance1 : Fintype V] [_contextInstance2 : DecidableEq V] (P : SimpleGraph V) (F : Finset (Sym2 V)) (W : Finset V) + {s v : V} (p : (avoidGraph P F W).Walk s v) (hs : s ∉ W) : v ∉ W := by + induction p with + | nil => exact hs + | cons hadj p ih => exact ih hadj.2.2.2 + +lemma ball_avoids (P : SimpleGraph V) (F : Finset (Sym2 V)) (W : Finset V) + (s : V) (hs : s ∉ W) (t : ℕ) : Disjoint (walkBall (avoidGraph P F W) s t) W := by + apply Finset.disjoint_left.mpr + intro v hv + obtain ⟨p, _⟩ := (mem_walkBall _ _ _ _).mp hv + exact walk_avoids_end P F W p hs + +lemma walkBall_step (G : SimpleGraph V) (s v w : V) (t : ℕ) + (hv : v ∈ walkBall G s t) (hadj : G.Adj v w) : + w ∈ walkBall G s (t + 1) := by + obtain ⟨p, hp⟩ := (mem_walkBall _ _ _ _).mp hv + apply (mem_walkBall _ _ _ _).mpr + exact ⟨p.concat hadj, by simpa using Nat.add_le_add_right hp 1⟩ + +noncomputable def rootBallUnion (P : SimpleGraph V) (F : Finset (Sym2 V)) + (W : V → Finset V) (A : Finset V) (t : ℕ) : Finset V := + A.biUnion (fun s => walkBall (avoidGraph P F (W s)) s t) + +lemma rootBallUnion_mono_time (P : SimpleGraph V) (F : Finset (Sym2 V)) + (W : V → Finset V) (A : Finset V) {t u : ℕ} (htu : t ≤ u) : + rootBallUnion P F W A t ⊆ rootBallUnion P F W A u := + Finset.biUnion_mono (fun s _ => walkBall_mono _ s htu) + +lemma roots_subset_rootBallUnion (P : SimpleGraph V) (F : Finset (Sym2 V)) + (W : V → Finset V) (A : Finset V) (t : ℕ) : A ⊆ rootBallUnion P F W A t := by + intro s hs + exact Finset.mem_biUnion.mpr ⟨s, hs, root_mem_walkBall _ _ _⟩ + +theorem rootBallUnion_growth_step + (P : SimpleGraph V) [DecidableRel P.Adj] + (h : ℝ) (hexp : CutExpansion P h) + (hr : 0 < (Fintype.card V : ℝ)) + (F : Finset (Sym2 V)) (W : V → Finset V) (A : Finset V) (t : ℕ) + (hroots : ∀ s ∈ A, s ∉ W s) + (hW : ∀ s ∈ A, ((W s).card : ℝ) ≤ h / 4) + (hsmall : ((rootBallUnion P F W A t).card : ℝ) ≤ (Fintype.card V : ℝ) / 2) + (hF : (F.card : ℝ) ≤ h * (rootBallUnion P F W A t).card / 4) : + (1 + h / (2 * (Fintype.card V : ℝ))) * (rootBallUnion P F W A t).card ≤ + ((rootBallUnion P F W A (t + 1)).card : ℝ) := by + classical + let B := rootBallUnion P F W A t + have hchoose : ∀ v ∈ B, ∃ s ∈ A, v ∈ walkBall (avoidGraph P F (W s)) s t := by + intro v hv + exact Finset.mem_biUnion.mp hv + choose s hsA hreach using hchoose + let forbid : V → Finset V := fun v => if hv : v ∈ B then W (s v hv) else ∅ + apply routing_union_growth_step P h hexp hr F B (rootBallUnion P F W A (t + 1)) forbid + (rootBallUnion_mono_time P F W A (Nat.le_succ t)) hsmall hF + · intro v hv + simpa only [forbid, dite_eq_left hv] using hW (s v hv) (hsA v hv) + · intro v hv w _ hadj hdel hforbid + have hvs : v ∈ walkBall (avoidGraph P F (W (s v hv))) (s v hv) t := hreach v hv + have hnv : v ∉ W (s v hv) := + (Finset.disjoint_left.mp (ball_avoids P F (W (s v hv)) (s v hv) + (hroots (s v hv) (hsA v hv)) t)) hvs + have hnw : w ∉ W (s v hv) := by simpa only [forbid, dite_eq_left hv] using hforbid + exact Finset.mem_biUnion.mpr ⟨s v hv, hsA v hv, + walkBall_step _ _ v w t hvs ⟨hadj, hdel, hnv, hnw⟩⟩ + +theorem rootBallUnion_growth_block + (P : SimpleGraph V) [DecidableRel P.Adj] + (h : ℝ) (hh : 0 ≤ h) (hexp : CutExpansion P h) + (hr : 0 < (Fintype.card V : ℝ)) + (F : Finset (Sym2 V)) (W : V → Finset V) (A : Finset V) (t g : ℕ) + (hroots : ∀ s ∈ A, s ∉ W s) + (hW : ∀ s ∈ A, ((W s).card : ℝ) ≤ h / 4) + (hpos : 1 ≤ (rootBallUnion P F W A t).card) + (hF : (F.card : ℝ) ≤ h * (rootBallUnion P F W A t).card / 4) + (hg : (Fintype.card V : ℝ) / 2 < (1 + h / (2 * (Fintype.card V : ℝ))) ^ g) : + (Fintype.card V : ℝ) / 2 < (rootBallUnion P F W A (t + g)).card := by + by_contra hnot + have hend := le_of_not_gt hnot + let b : ℕ → ℝ := fun j => (rootBallUnion P F W A (t + j)).card + let c : ℝ := 1 + h / (2 * (Fintype.card V : ℝ)) + have hc : 0 ≤ c := by dsimp [c]; positivity + have hmono : Monotone b := by + intro j k hjk + dsimp [b] + exact_mod_cast Finset.card_le_card + (rootBallUnion_mono_time P F W A (Nat.add_le_add_left hjk t)) + have hbase : 1 ≤ b 0 := by dsimp [b]; simpa using (Nat.cast_le (α := ℝ)).mpr hpos + have hstep : ∀ j < g, c * b j ≤ b (j + 1) := by + intro j hj + have hsmall : b j ≤ (Fintype.card V : ℝ) / 2 := + (hmono (Nat.le_of_lt hj)).trans hend + have hFj : (F.card : ℝ) ≤ h * (rootBallUnion P F W A (t + j)).card / 4 := by + have hbj := hmono (Nat.zero_le j) + dsimp [b] at hbj + nlinarith + simpa only [c, b, Nat.add_assoc] using + rootBallUnion_growth_step P h hexp hr F W A (t + j) hroots hW hsmall hFj + have hpow : ∀ j ≤ g, c ^ j ≤ b j := by + intro j + induction j with + | zero => intro _; simpa using hbase + | succ j ih => + intro hjg + calc + c ^ (j + 1) = c * c ^ j := by rw [pow_succ]; ring + _ ≤ c * b j := mul_le_mul_of_nonneg_left (ih (by omega)) hc + _ ≤ b (j + 1) := hstep j (by omega) + exact (not_lt_of_ge ((hpow g le_rfl).trans hend)) hg + +lemma rootBallUnion_halve (P : SimpleGraph V) (F : Finset (Sym2 V)) + (W : V → Finset V) (A : Finset V) (t k : ℕ) (u : ℝ) + (hcard : A.card ≤ 2 * k) + (hlarge : 2 * u < (rootBallUnion P F W A t).card) : + ∃ A' ⊆ A, A'.card ≤ k ∧ u < (rootBallUnion P F W A' t).card := by + obtain ⟨A₁, hsub, hcard₁⟩ := Finset.exists_subset_card_eq (min_le_right k A.card) + let A₂ := A \ A₁ + have hcard₂ : A₂.card ≤ k := by + dsimp [A₂] + rw [Finset.card_sdiff_of_subset hsub, hcard₁] + omega + have hcover : A₁ ∪ A₂ = A := Finset.union_sdiff_of_subset hsub + have hcount : (rootBallUnion P F W A t).card ≤ + (rootBallUnion P F W A₁ t).card + (rootBallUnion P F W A₂ t).card := by + conv_lhs => rw [← hcover] + simp only [rootBallUnion, Finset.union_biUnion] + exact Finset.card_union_le _ _ + by_cases hfirst : u < (rootBallUnion P F W A₁ t).card + · exact ⟨A₁, hsub, hcard₁ ▸ min_le_left _ _, hfirst⟩ + · refine ⟨A₂, Finset.sdiff_subset, hcard₂, ?_⟩ + have hcR : ((rootBallUnion P F W A t).card : ℝ) ≤ + (rootBallUnion P F W A₁ t).card + (rootBallUnion P F W A₂ t).card := by + exact_mod_cast hcount + linarith + +theorem rootBallUnion_extract_root + (P : SimpleGraph V) [DecidableRel P.Adj] + (h : ℝ) (hh : 0 < h) (hexp : CutExpansion P h) + (hr : 0 < (Fintype.card V : ℝ)) + (F : Finset (Sym2 V)) (W : V → Finset V) (g N : ℕ) + (hFglobal : (F.card : ℝ) ≤ h * (Fintype.card V : ℝ) / 16) + (hg : (Fintype.card V : ℝ) / 2 < (1 + h / (2 * (Fintype.card V : ℝ))) ^ g) : + ∀ (A : Finset V) (t : ℕ), + (∀ s ∈ A, s ∉ W s) → + (∀ s ∈ A, ((W s).card : ℝ) ≤ h / 4) → + A.card ≤ 2 ^ N → + (Fintype.card V : ℝ) / 2 < (rootBallUnion P F W A t).card → + ∃ s ∈ A, (Fintype.card V : ℝ) / 2 < + (walkBall (avoidGraph P F (W s)) s (t + N * g)).card := by + induction N with + | zero => + intro A t hroots hW hcard hlarge + have hne : A.Nonempty := by + by_contra h + have he : A = ∅ := Finset.not_nonempty_iff_eq_empty.mp h + simp [he, rootBallUnion] at hlarge + linarith + obtain ⟨s, hs⟩ := hne + have he : A = {s} := Finset.eq_singleton_iff_unique_mem.mpr + ⟨hs, fun v hv => (Finset.card_le_one.mp (by simpa using hcard)) v hv s hs⟩ + refine ⟨s, hs, ?_⟩ + simpa [he, rootBallUnion] using hlarge + | succ N ih => + intro A t hroots hW hcard hlarge + have hcard' : A.card ≤ 2 * 2 ^ N := by simpa [pow_succ, Nat.mul_comm] using hcard + obtain ⟨A', hsub, hcard', hlarge'⟩ := rootBallUnion_halve P F W A t (2 ^ N) + ((Fintype.card V : ℝ) / 4) hcard' (by linarith) + have hF' : (F.card : ℝ) ≤ h * (rootBallUnion P F W A' t).card / 4 := by + nlinarith + have hpos : 1 ≤ (rootBallUnion P F W A' t).card := by + have : 0 < ((rootBallUnion P F W A' t).card : ℝ) := by linarith + exact_mod_cast this + have hroots' : ∀ s ∈ A', s ∉ W s := fun s hs => hroots s (hsub hs) + have hW' : ∀ s ∈ A', ((W s).card : ℝ) ≤ h / 4 := fun s hs => hW s (hsub hs) + have hnext := rootBallUnion_growth_block P h hh.le hexp hr F W A' t g + hroots' hW' hpos hF' hg + obtain ⟨s, hs, hb⟩ := ih A' (t + g) hroots' hW' hcard' hnext + refine ⟨s, hsub hs, ?_⟩ + have ht : t + (N + 1) * g = t + g + N * g := by ring + simpa only [Nat.succ_eq_add_one, ht] using hb + +lemma CutExpansion.le_order (P : SimpleGraph V) [DecidableRel P.Adj] + (h : ℝ) (hexp : CutExpansion P h) (hr : 2 ≤ Fintype.card V) : + h ≤ (Fintype.card V : ℝ) := by + obtain ⟨v⟩ := Fintype.card_pos_iff.mp (by omega : 0 < Fintype.card V) + have hcomplN : 1 ≤ ({v} : Finset V)ᶜ.card := by + simp only [Finset.card_compl, Finset.card_singleton] + omega + have hcompl : (1 : ℝ) ≤ (({v} : Finset V)ᶜ.card : ℝ) := by exact_mod_cast hcomplN + have hc := hexp {v} + simp only [Finset.card_singleton, Nat.cast_one, min_eq_left hcompl, mul_one] at hc + have hupper := P.card_interedges_le_mul ({v} : Finset V) ({v} : Finset V)ᶜ + simp only [Finset.card_singleton, one_mul] at hupper + have hle := (Finset.card_le_univ (({v} : Finset V)ᶜ)) + exact hc.trans (by exact_mod_cast hupper.trans hle) + +noncomputable def routingG (r h : ℝ) : ℕ := ⌈8 * (r / h) * Real.logb 2 (2 * r)⌉₊ + +noncomputable def routingDepth (r : ℝ) : ℕ := ⌈Real.logb 2 r⌉₊ + +noncomputable def routingLength (r h : ℝ) : ℕ := 2 * routingG r h * (1 + routingDepth r) + +lemma routingG_growth (r h : ℝ) (hr : 1 ≤ r) (hh : 0 < h) (hhr : h ≤ r) : + r / 2 < (1 + h / (2 * r)) ^ routingG r h := by + have hr0 : 0 < r := by linarith + let x := h / (2 * r) + have hx0 : 0 ≤ x := by dsimp [x]; positivity + have hxle : x ≤ 1 := by + dsimp [x] + apply (div_le_iff₀ (by positivity : 0 < 2 * r)).mpr + linarith + have hlog : h / (4 * r) ≤ Real.log (1 + h / (2 * r)) := by + have heq : h / (4 * r) = x / 2 := by dsimp [x]; ring + rw [heq] + calc + x / 2 ≤ 2 * x / (x + 2) := by + apply (le_div_iff₀ (by linarith : 0 < x + 2)).mpr + nlinarith [mul_nonneg hx0 (sub_nonneg.mpr hxle)] + _ ≤ Real.log (1 + x) := Real.le_log_one_add_of_nonneg hx0 + have hl2pos : 0 < Real.log 2 := Real.log_pos (by norm_num) + have hl2le : Real.log 2 ≤ 1 := by + have htwo := Real.log_le_sub_one_of_pos (by norm_num : (0 : ℝ) < 2) + norm_num at htwo ⊢ + exact htwo + have hlogpos : 0 < Real.log (2 * r) := Real.log_pos (by linarith) + have hbase : Real.log (2 * r) ≤ Real.logb 2 (2 * r) := by + rw [Real.logb] + apply (le_div_iff₀ hl2pos).mpr + nlinarith + have hg : 8 * (r / h) * Real.logb 2 (2 * r) ≤ (routingG r h : ℝ) := + Nat.le_ceil _ + have hlogpow : 2 * Real.log (2 * r) ≤ + Real.log ((1 + h / (2 * r)) ^ routingG r h) := by + rw [Real.log_pow] + calc + 2 * Real.log (2 * r) ≤ 2 * Real.logb 2 (2 * r) := by linarith + _ = (8 * (r / h) * Real.logb 2 (2 * r)) * (h / (4 * r)) := by + field_simp + ; ring + _ ≤ (routingG r h : ℝ) * (h / (4 * r)) := + mul_le_mul_of_nonneg_right hg (by positivity) + _ ≤ (routingG r h : ℝ) * Real.log (1 + h / (2 * r)) := + mul_le_mul_of_nonneg_left hlog (by positivity) + have hsmall : Real.log (r / 2) < 2 * Real.log (2 * r) := by + have := Real.log_le_log (by positivity : 0 < r / 2) (by linarith : r / 2 ≤ 2 * r) + linarith + apply (Real.log_lt_log_iff (by positivity : 0 < r / 2) (by positivity)).mp + exact hsmall.trans_le hlogpow + +lemma le_two_pow_routingDepth (r : ℕ) (hr : 0 < r) : r ≤ 2 ^ routingDepth r := by + have hrR : (0 : ℝ) < r := by exact_mod_cast hr + have hn := Nat.le_ceil (Real.logb 2 (r : ℝ)) + have hp := (Real.logb_le_iff_le_rpow (by norm_num : (1 : ℝ) < 2) hrR).mp hn + rw [Real.rpow_natCast] at hp + dsimp [routingDepth] + exact_mod_cast hp + +theorem routing_large_root_ball + (P : SimpleGraph V) [DecidableRel P.Adj] + (h : ℝ) (hh : 0 < h) (hexp : CutExpansion P h) (hr : 2 ≤ Fintype.card V) + (F : Finset (Sym2 V)) (W : V → Finset V) (S : Finset V) + (hne : S.Nonempty) + (hroots : ∀ s ∈ S, s ∉ W s) + (hW : ∀ s ∈ S, ((W s).card : ℝ) ≤ h / 4) + (hFstart : (F.card : ℝ) ≤ h * S.card / 4) + (hFglobal : (F.card : ℝ) ≤ h * (Fintype.card V : ℝ) / 16) : + ∃ s ∈ S, (Fintype.card V : ℝ) / 2 < + (walkBall (avoidGraph P F (W s)) s + (routingG (Fintype.card V) h * (1 + routingDepth (Fintype.card V)))).card := by + have hrpos : 0 < (Fintype.card V : ℝ) := by exact_mod_cast (by omega : 0 < Fintype.card V) + have hg := routingG_growth (Fintype.card V) h (by exact_mod_cast (by omega : 1 ≤ Fintype.card V)) + hh (hexp.le_order P h hr) + have hsub := roots_subset_rootBallUnion P F W S 0 + have hpos : 1 ≤ (rootBallUnion P F W S 0).card := + (Finset.card_pos.mpr hne).trans_le (Finset.card_le_card hsub) + have hF : (F.card : ℝ) ≤ h * (rootBallUnion P F W S 0).card / 4 := by + have hc : (S.card : ℝ) ≤ (rootBallUnion P F W S 0).card := by + exact_mod_cast Finset.card_le_card hsub + nlinarith + have hb := rootBallUnion_growth_block P h hh.le hexp hrpos F W S 0 + (routingG (Fintype.card V) h) hroots hW hpos hF hg + have hrootcard : S.card ≤ 2 ^ routingDepth (Fintype.card V) := + (Finset.card_le_univ S).trans (le_two_pow_routingDepth _ (by omega)) + obtain ⟨s, hs, hball⟩ := rootBallUnion_extract_root P h hh hexp hrpos F W + (routingG (Fintype.card V) h) (routingDepth (Fintype.card V)) + hFglobal hg S (routingG (Fintype.card V) h) hroots hW hrootcard (by simpa using hb) + refine ⟨s, hs, ?_⟩ + have ht : routingG (Fintype.card V) h * (1 + routingDepth (Fintype.card V)) = + routingG (Fintype.card V) h + routingDepth (Fintype.card V) * routingG (Fintype.card V) h := by ring + simpa only [ht] using hball + +def incidentEdges (F : Finset (Sym2 V)) (v : V) : Finset (Sym2 V) := + F.filter (fun e => v ∈ e) + +lemma incidentEdges_union {V : Type} [_contextInstance1 : Fintype V] [_contextInstance2 : DecidableEq V] (F E : Finset (Sym2 V)) (v : V) : + incidentEdges (F ∪ E) v = incidentEdges F v ∪ incidentEdges E v := by + simp [incidentEdges, Finset.filter_union] + +lemma incidentEdges_union_card_le (F E : Finset (Sym2 V)) (v : V) : + (incidentEdges (F ∪ E) v).card ≤ (incidentEdges F v).card + (incidentEdges E v).card := by + rw [incidentEdges_union] + exact Finset.card_union_le _ _ + +lemma incidentEdges_sum_le (F : Finset (Sym2 V)) : + ∑ v : V, (incidentEdges F v).card ≤ 2 * F.card := by + have heq : ∑ v : V, (incidentEdges F v).card = ∑ e ∈ F, e.toFinset.card := by + simp only [incidentEdges, Finset.card_eq_sum_ones, Finset.sum_filter] + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro e he + simp [← Sym2.mem_toFinset] + rw [heq] + calc + _ ≤ ∑ _e ∈ F, 2 := Finset.sum_le_sum (fun e _ => by + rw [Sym2.card_toFinset] + split <;> norm_num) + _ = 2 * F.card := by simp [mul_comm] + +lemma incidentEdges_path_start_le_one {V : Type} [_contextInstance1 : Fintype V] [_contextInstance2 : DecidableEq V] (G : SimpleGraph V) {s t : V} + (p : G.Walk s t) (hp : p.IsPath) : + (incidentEdges p.edges.toFinset s).card ≤ 1 := by + have hsub : incidentEdges p.edges.toFinset s ⊆ {s(s, p.snd)} := by + intro e he + obtain ⟨heP, hs⟩ := Finset.mem_filter.mp he + obtain ⟨v, hev⟩ := Sym2.mem_iff_exists.mp hs + subst e + have hv := hp.eq_snd_of_mem_edges (List.mem_toFinset.mp heP) + simp [hv] + exact (Finset.card_le_card hsub).trans (by simp) + +lemma incidentEdges_path_end_le_one (G : SimpleGraph V) {s t : V} + (p : G.Walk s t) (hp : p.IsPath) : + (incidentEdges p.edges.toFinset t).card ≤ 1 := by + simpa using incidentEdges_path_start_le_one G p.reverse hp.reverse + +lemma incidentEdges_walk_eq_empty_of_not_mem {V : Type} [_contextInstance1 : Fintype V] [_contextInstance2 : DecidableEq V] (G : SimpleGraph V) {s t v : V} + (p : G.Walk s t) (hv : v ∉ p.support) : incidentEdges p.edges.toFinset v = ∅ := by + apply Finset.eq_empty_iff_forall_notMem.mpr + intro e he + obtain ⟨heP, hve⟩ := Finset.mem_filter.mp he + have hm := p.mem_support_iff_exists_mem_edges.mpr (Or.inr ⟨e, List.mem_toFinset.mp heP, hve⟩) + exact hv hm + +lemma incidentEdges_path_le_two (G : SimpleGraph V) {s t : V} + (p : G.Walk s t) (hp : p.IsPath) (v : V) : + (incidentEdges p.edges.toFinset v).card ≤ 2 := by + by_cases hv : v ∈ p.support + · have htake := incidentEdges_path_end_le_one G (p.takeUntil v hv) (hp.takeUntil hv) + have hdrop := incidentEdges_path_start_le_one G (p.dropUntil v hv) (hp.dropUntil hv) + have heq : p.edges.toFinset = (p.takeUntil v hv).edges.toFinset ∪ (p.dropUntil v hv).edges.toFinset := by + have he := congrArg (fun q : G.Walk s t => q.edges.toFinset) (p.take_spec hv) + simpa only [SimpleGraph.Walk.edges_append, List.toFinset_append] using he.symm + rw [heq] + exact (incidentEdges_union_card_le _ _ v).trans (by omega) + · rw [incidentEdges_walk_eq_empty_of_not_mem G p hv] + simp + +lemma deleted_boundary_card_le_incidents (P : SimpleGraph V) [DecidableRel P.Adj] + (B : Finset V) (F : Finset (Sym2 V)) : + ((P.interedges B Bᶜ).filter (fun e => s(e.1, e.2) ∈ F)).card ≤ + ∑ v ∈ B, (incidentEdges F v).card := by + let T := B.biUnion (fun v => ({v} : Finset V) ×ˢ incidentEdges F v) + have hc : ((P.interedges B Bᶜ).filter (fun e => s(e.1, e.2) ∈ F)).card ≤ T.card := by + apply Finset.card_le_card_of_injOn (fun e : V × V => (e.1, s(e.1, e.2))) + · intro e he + obtain ⟨heP, heF⟩ := Finset.mem_filter.mp he + apply Finset.mem_biUnion.mpr + refine ⟨e.1, (P.mem_interedges_iff.mp heP).1, Finset.mem_product.mpr ⟨by simp, ?_⟩⟩ + exact Finset.mem_filter.mpr ⟨heF, by simp⟩ + · intro e he f hf heq + have hsym := congrArg Prod.snd heq + exact boundary_sym2_injective P B (Finset.mem_filter.mp he).1 + (Finset.mem_filter.mp hf).1 hsym + have hT : T.card ≤ ∑ v ∈ B, (incidentEdges F v).card := by + simpa [T] using Finset.card_biUnion_le (s := B) + (t := fun v => ({v} : Finset V) ×ˢ incidentEdges F v) + exact hc.trans hT + +lemma walkBall_growth_of_incidents (P : SimpleGraph V) [DecidableRel P.Adj] + (h : ℝ) (hexp : CutExpansion P h) (hr : 0 < (Fintype.card V : ℝ)) + (F : Finset (Sym2 V)) (W : Finset V) (s : V) (hs : s ∉ W) + (hF : ∀ v, ((incidentEdges F v).card : ℝ) ≤ h / 4) + (hW : (W.card : ℝ) ≤ h / 4) (t : ℕ) + (hsmall : ((walkBall (avoidGraph P F W) s t).card : ℝ) ≤ (Fintype.card V : ℝ) / 2) : + (1 + h / (2 * (Fintype.card V : ℝ))) * (walkBall (avoidGraph P F W) s t).card ≤ + ((walkBall (avoidGraph P F W) s (t + 1)).card : ℝ) := by + classical + apply routing_union_growth_step_of_boundary P h hexp hr F _ _ (fun _ => W) + (walkBall_mono _ s (Nat.le_succ t)) hsmall + · calc + _ ≤ ∑ v ∈ walkBall (avoidGraph P F W) s t, ((incidentEdges F v).card : ℝ) := by + exact_mod_cast deleted_boundary_card_le_incidents P (walkBall (avoidGraph P F W) s t) F + _ ≤ ∑ _v ∈ walkBall (avoidGraph P F W) s t, h / 4 := Finset.sum_le_sum (fun v _ => hF v) + _ = _ := by simp; ring + · exact fun _ _ => hW + · intro v hv w _ hadj hdel hw + have hnv := Finset.disjoint_left.mp (ball_avoids P F W s hs t) hv + exact walkBall_step _ s v w t hv ⟨hadj, hdel, hnv, hw⟩ + +lemma walkBall_large_of_incidents (P : SimpleGraph V) [DecidableRel P.Adj] + (h : ℝ) (hh : 0 < h) (hexp : CutExpansion P h) (hr : 2 ≤ Fintype.card V) + (F : Finset (Sym2 V)) (W : Finset V) (s : V) (hs : s ∉ W) + (hF : ∀ v, ((incidentEdges F v).card : ℝ) ≤ h / 4) + (hW : (W.card : ℝ) ≤ h / 4) : + (Fintype.card V : ℝ) / 2 < + (walkBall (avoidGraph P F W) s (routingG (Fintype.card V) h)).card := by + have hrR : (2 : ℝ) ≤ Fintype.card V := by exact_mod_cast hr + have hr0 : (0 : ℝ) < Fintype.card V := by linarith + let g := routingG (Fintype.card V) h + let c : ℝ := 1 + h / (2 * (Fintype.card V : ℝ)) + have hc : 0 ≤ c := by dsimp [c]; positivity + by_contra hnot + have hend := le_of_not_gt hnot + have hpow : ∀ j ≤ g, c ^ j ≤ (walkBall (avoidGraph P F W) s j).card := by + intro j + induction j with + | zero => + intro _ + have H := Finset.card_pos.mpr ⟨s, root_mem_walkBall (avoidGraph P F W) s 0⟩ + have H' : 1 ≤ (walkBall (avoidGraph P F W) s 0).card := H + simpa using (Nat.cast_le (α := ℝ)).mpr H' + | succ j ih => + intro hj + have hmono : ((walkBall (avoidGraph P F W) s j).card : ℝ) ≤ + (walkBall (avoidGraph P F W) s g).card := by + exact_mod_cast Finset.card_le_card (walkBall_mono (avoidGraph P F W) s (by omega : j ≤ g)) + have hsmall := hmono.trans hend + calc + c ^ (j + 1) = c * c ^ j := by rw [pow_succ]; ring + _ ≤ c * (walkBall (avoidGraph P F W) s j).card := mul_le_mul_of_nonneg_left (ih (by omega)) hc + _ ≤ (walkBall (avoidGraph P F W) s (j + 1)).card := + walkBall_growth_of_incidents P h hexp hr0 F W s hs hF hW j hsmall + have hg := routingG_growth (Fintype.card V) h (by linarith) hh (hexp.le_order P h hr) + exact (not_lt_of_ge ((hpow g le_rfl).trans hend)) hg + +lemma exists_short_avoiding_path (P : SimpleGraph V) [DecidableRel P.Adj] + (h : ℝ) (hh : 0 < h) (hexp : CutExpansion P h) (hr : 2 ≤ Fintype.card V) + (F : Finset (Sym2 V)) (W : Finset V) (s t : V) (hs : s ∉ W) (ht : t ∉ W) + (hF : ∀ v, ((incidentEdges F v).card : ℝ) ≤ h / 4) + (hW : (W.card : ℝ) ≤ h / 4) : + ∃ q : (avoidGraph P F W).Walk s t, q.IsPath ∧ + q.length ≤ 2 * routingG (Fintype.card V) h := by + classical + let g := routingG (Fintype.card V) h + let B₁ := walkBall (avoidGraph P F W) s g + let B₂ := walkBall (avoidGraph P F W) t g + have h₁ := walkBall_large_of_incidents P h hh hexp hr F W s hs hF hW + have h₂ := walkBall_large_of_incidents P h hh hexp hr F W t ht hF hW + have hmeet : (B₁ ∩ B₂).Nonempty := by + apply Finset.card_pos.mp + have hc := Finset.card_union_add_card_inter B₁ B₂ + have hu := Finset.card_le_univ (B₁ ∪ B₂) + have hsum : (Fintype.card V : ℝ) < (B₁.card : ℝ) + (B₂.card : ℝ) := by + dsimp [B₁, B₂, g]; linarith + have hsumN : Fintype.card V < B₁.card + B₂.card := by exact_mod_cast hsum + omega + obtain ⟨v, hv⟩ := hmeet + obtain ⟨p₁, hp₁⟩ := (mem_walkBall _ s v g).mp (Finset.mem_inter.mp hv).1 + obtain ⟨p₂, hp₂⟩ := (mem_walkBall _ t v g).mp (Finset.mem_inter.mp hv).2 + let w := p₁.append p₂.reverse + refine ⟨w.bypass, w.bypass_isPath, w.length_bypass_le_length.trans ?_⟩ + dsimp [w] + simp only [SimpleGraph.Walk.length_append, SimpleGraph.Walk.length_reverse] + omega + +lemma two_routingG_le_length (r h : ℝ) : 2 * routingG r h ≤ routingLength r h := by + dsimp [routingLength] + exact Nat.le_mul_of_pos_right _ (by omega) + +lemma routingLength_bounds (r h : ℝ) (hr : 1 ≤ r) (hh : 0 < h) : + 1 ≤ routingLength r h ∧ r ≤ (routingLength r h : ℝ) * h := by + have hl2 : 0 < Real.log 2 := Real.log_pos (by norm_num) + have hlog : 1 ≤ Real.logb 2 (2 * r) := by + rw [Real.logb] + apply (le_div_iff₀ hl2).mpr + simpa using Real.log_le_log (by norm_num : (0 : ℝ) < 2) (by linarith : 2 ≤ 2 * r) + have hg : 8 * (r / h) * Real.logb 2 (2 * r) ≤ (routingG r h : ℝ) := Nat.le_ceil _ + have hgh : 8 * r ≤ (routingG r h : ℝ) * h := by + calc + 8 * r = (8 * (r / h)) * h := by field_simp + _ ≤ (8 * (r / h) * Real.logb 2 (2 * r)) * h := by + apply mul_le_mul_of_nonneg_right _ hh.le + simpa using mul_le_mul_of_nonneg_left hlog (show 0 ≤ 8 * (r / h) by positivity) + _ ≤ (routingG r h : ℝ) * h := mul_le_mul_of_nonneg_right hg hh.le + have hgpos : 0 < routingG r h := by + have hgR : (0 : ℝ) < routingG r h := by nlinarith + exact_mod_cast hgR + have hgle : routingG r h ≤ routingLength r h := (by omega : routingG r h ≤ 2 * routingG r h).trans (two_routingG_le_length r h) + refine ⟨by omega, ?_⟩ + have hgleR : (routingG r h : ℝ) ≤ routingLength r h := by exact_mod_cast hgle + nlinarith + +lemma routing_budget (L k b z h r : ℝ) (hL : 1 ≤ L) (hk : 1 ≤ k) + (hb : 1 ≤ b) (hz : 0 ≤ z) (hh : 0 < h) (_hr : 0 ≤ r) + (hreach : r ≤ L * h) (hbudget : 64 * (L ^ 2 * (k + b) + z) ≤ h) : + h / 8 + 2 + k ≤ h / 4 ∧ z + b * L ≤ h / 8 ∧ 64 * L * k * r ≤ h ^ 2 := by + have hL0 : 0 ≤ L := by linarith + have hk0 : 0 ≤ k := by linarith + have hb0 : 0 ≤ b := by linarith + have hLs : 1 ≤ L ^ 2 := one_le_pow₀ hL + have hLLs : L ≤ L ^ 2 := by nlinarith + have hbig : 64 * (k + b) ≤ h := by + calc + _ ≤ 64 * (L ^ 2 * (k + b) + z) := by nlinarith [mul_le_mul_of_nonneg_right hLs (by linarith : 0 ≤ k + b)] + _ ≤ _ := hbudget + have hbL : 64 * (b * L + z) ≤ h := by + calc + _ ≤ 64 * (L ^ 2 * (k + b) + z) := by nlinarith [mul_le_mul_of_nonneg_left hLLs hb0, mul_nonneg (sq_nonneg L) hk0] + _ ≤ _ := hbudget + have hkL : 64 * L ^ 2 * k ≤ h := by nlinarith [mul_nonneg (sq_nonneg L) hb0] + refine ⟨by linarith, by linarith, ?_⟩ + calc + 64 * L * k * r ≤ 64 * L * k * (L * h) := mul_le_mul_of_nonneg_left hreach (by positivity) + _ = (64 * L ^ 2 * k) * h := by ring + _ ≤ h * h := mul_le_mul_of_nonneg_right hkL hh.le + _ = h ^ 2 := by ring + +noncomputable def saturated (F : Finset (Sym2 V)) (h : ℝ) : Finset V := by + classical + exact Finset.univ.filter (fun v => h / 8 ≤ ((incidentEdges F v).card : ℝ)) + +lemma saturated_card_le (F : Finset (Sym2 V)) (h : ℝ) (hh : 0 < h) + (hF : 128 * (F.card : ℝ) ≤ h ^ 2) : (saturated F h).card ≤ h / 8 := by + classical + have hs : h / 8 * (saturated F h).card ≤ ∑ v : V, ((incidentEdges F v).card : ℝ) := by + calc + _ = ∑ _v ∈ saturated F h, h / 8 := by simp [mul_comm] + _ ≤ ∑ v ∈ saturated F h, ((incidentEdges F v).card : ℝ) := Finset.sum_le_sum (fun v hv => (Finset.mem_filter.mp hv).2) + _ ≤ _ := Finset.sum_le_sum_of_subset_of_nonneg (Finset.subset_univ _) (by intros; positivity) + have hsum : (∑ v : V, ((incidentEdges F v).card : ℝ)) ≤ 2 * (F.card : ℝ) := by + exact_mod_cast incidentEdges_sum_le F + nlinarith + +def pathInterior {P : SimpleGraph V} {s t : V} (q : P.Walk s t) : Finset V := + q.support.toFinset \ {s, t} + +lemma pathInterior_card_le {V : Type} [_contextInstance1 : Fintype V] [_contextInstance2 : DecidableEq V] {P : SimpleGraph V} {s t : V} (q : P.Walk s t) : + (pathInterior q).card ≤ q.length := by + have hp := List.toFinset_card_le q.support + rw [q.length_support] at hp + have hstart : s ∈ q.support.toFinset ∩ ({s, t} : Finset V) := by simp + have hint := Finset.card_pos.mpr ⟨s, hstart⟩ + have hd := Finset.card_sdiff_add_card_inter q.support.toFinset ({s, t} : Finset V) + dsimp [pathInterior] + omega + +lemma avoidGraph_le {V : Type} [_contextInstance1 : Fintype V] [_contextInstance2 : DecidableEq V] (P : SimpleGraph V) (F : Finset (Sym2 V)) (W : Finset V) : + avoidGraph P F W ≤ P := fun _ _ h => h.1 + +lemma walk_avoids_support (P : SimpleGraph V) (F : Finset (Sym2 V)) (W : Finset V) + {s t : V} (q : (avoidGraph P F W).Walk s t) (hs : s ∉ W) : + Disjoint q.support.toFinset W := by + apply Finset.disjoint_left.mpr + intro v hv + exact walk_avoids_end P F W (q.takeUntil v (List.mem_toFinset.mp hv)) hs + +lemma walk_avoids_edges {V : Type} [_contextInstance1 : Fintype V] [_contextInstance2 : DecidableEq V] (P : SimpleGraph V) (F : Finset (Sym2 V)) (W : Finset V) + {s t : V} (q : (avoidGraph P F W).Walk s t) : + Disjoint q.edges.toFinset F := by + apply Finset.disjoint_left.mpr + intro e he + induction e using Sym2.inductionOn with + | hf v w => exact (q.adj_of_mem_edges (List.mem_toFinset.mp he)).2.1 + +lemma exists_short_path_with_avoidance (P : SimpleGraph V) [DecidableRel P.Adj] + (h : ℝ) (hh : 0 < h) (hexp : CutExpansion P h) (hr : 2 ≤ Fintype.card V) + (F : Finset (Sym2 V)) (W : Finset V) (s t : V) (hs : s ∉ W) (ht : t ∉ W) + (hF : ∀ v, ((incidentEdges F v).card : ℝ) ≤ h / 4) + (hW : (W.card : ℝ) ≤ h / 4) : + ∃ q : P.Walk s t, q.IsPath ∧ q.length ≤ routingLength (Fintype.card V) h ∧ + Disjoint q.edges.toFinset F ∧ Disjoint q.support.toFinset W := by + obtain ⟨q, hp, hl⟩ := exists_short_avoiding_path P h hh hexp hr F W s t hs ht hF hW + refine ⟨q.mapLe (avoidGraph_le P F W), hp.mapLe _, ?_, ?_, ?_⟩ + · simpa using hl.trans (two_routingG_le_length (Fintype.card V) h) + · simpa using walk_avoids_edges P F W q + · simpa using walk_avoids_support P F W q hs + +lemma route_degree_update {P : SimpleGraph V} {s t : V} (q : P.Walk s t) + (hp : q.IsPath) (F : Finset (Sym2 V)) (h : ℝ) (load : V → ℕ) + (hdegree : ∀ v, ((incidentEdges F v).card : ℝ) ≤ h / 8 + 2 + load v) + (havoid : Disjoint q.support.toFinset (saturated F h \ {s, t})) (v : V) : + ((incidentEdges (F ∪ q.edges.toFinset) v).card : ℝ) ≤ + h / 8 + 2 + load v + (if v = s ∨ v = t then 1 else 0) := by + classical + have hadd : ((incidentEdges (F ∪ q.edges.toFinset) v).card : ℝ) ≤ + (incidentEdges F v).card + (incidentEdges q.edges.toFinset v).card := by + exact_mod_cast incidentEdges_union_card_le F q.edges.toFinset v + by_cases hv : v = s ∨ v = t + · rw [ite_eq_left hv] + have hqN : (incidentEdges q.edges.toFinset v).card ≤ 1 := by + rcases hv with rfl | rfl + · exact incidentEdges_path_start_le_one P q hp + · exact incidentEdges_path_end_le_one P q hp + have hq : ((incidentEdges q.edges.toFinset v).card : ℝ) ≤ 1 := by exact_mod_cast hqN + linarith [hdegree v] + · rw [ite_eq_right hv] + by_cases hmem : v ∈ q.support + · have hns : v ∉ saturated F h := by + intro hsat + apply Finset.disjoint_left.mp havoid (List.mem_toFinset.mpr hmem) + exact Finset.mem_sdiff.mpr ⟨hsat, by simpa using hv⟩ + have hsmall : ((incidentEdges F v).card : ℝ) < h / 8 := by + simpa [saturated] using hns + have hq : ((incidentEdges q.edges.toFinset v).card : ℝ) ≤ 2 := by + exact_mod_cast incidentEdges_path_le_two P q hp v + have : (0 : ℝ) ≤ load v := by positivity + linarith + · rw [incidentEdges_walk_eq_empty_of_not_mem P q hmem] at hadd + simp only [Finset.card_empty, Nat.cast_zero, add_zero] at hadd + linarith [hdegree v] + +section Families +variable {I T : Type} [Fintype I] [DecidableEq I] [DecidableEq T] +variable {P : SimpleGraph V} {x y : I → V} + +def endpointLoad (A : Finset I) (x y : I → V) (v : V) : ℕ := + (A.filter (fun i => x i = v ∨ y i = v)).card + +lemma endpointLoad_mono {V : Type} [_contextInstance1 : Fintype V] [_contextInstance2 : DecidableEq V] {I : Type} [_contextInstance4 : Fintype I] [_contextInstance5 : DecidableEq I] {A B : Finset I} (hAB : A ⊆ B) (x y : I → V) (v : V) : + endpointLoad A x y v ≤ endpointLoad B x y v := + Finset.card_le_card (Finset.filter_subset_filter _ hAB) + +lemma endpointLoad_insert {V : Type} [_contextInstance1 : Fintype V] [_contextInstance2 : DecidableEq V] {I : Type} [_contextInstance4 : Fintype I] [_contextInstance5 : DecidableEq I] (A : Finset I) (i : I) (hi : i ∉ A) (x y : I → V) (v : V) : + endpointLoad (insert i A) x y v = endpointLoad A x y v + + (if v = x i ∨ v = y i then 1 else 0) := by + classical + by_cases hv : v = x i ∨ v = y i + · have hv' : x i = v ∨ y i = v := by simpa [eq_comm] using hv + simp [endpointLoad, Finset.filter_insert, hv, hv', hi] + · have hv' : ¬ (x i = v ∨ y i = v) := by simpa [eq_comm] using hv + simp [endpointLoad, Finset.filter_insert, hv, hv'] + +lemma endpointLoad_sum {V : Type} [_contextInstance1 : Fintype V] [_contextInstance2 : DecidableEq V] {I : Type} [_contextInstance4 : Fintype I] [_contextInstance5 : DecidableEq I] (A : Finset I) (x y : I → V) (hxy : ∀ i ∈ A, x i ≠ y i) : + ∑ v : V, endpointLoad A x y v = 2 * A.card := by + classical + simp only [endpointLoad, Finset.card_eq_sum_ones, Finset.sum_filter] + rw [Finset.sum_comm] + have heq : ∀ i ∈ A, (∑ v : V, if x i = v ∨ y i = v then 1 else 0) = 2 := by + intro i hi + have hf : (Finset.univ.filter fun v => x i = v ∨ y i = v) = ({x i, y i} : Finset V) := by + ext v + simp [eq_comm] + have hc : ({x i, y i} : Finset V).card = 2 := by simp [hxy i hi] + rw [← hc, ← hf, Finset.card_eq_sum_ones, Finset.sum_filter] + calc + _ = ∑ _i ∈ A, 2 := Finset.sum_congr rfl heq + _ = _ := by simp [mul_comm] + +noncomputable def usedEdges (A : Finset I) (q : ∀ i, P.Walk (x i) (y i)) : Finset (Sym2 V) := + A.biUnion (fun i => (q i).edges.toFinset) + +lemma usedEdges_card_le {V : Type} [_contextInstance1 : Fintype V] [_contextInstance2 : DecidableEq V] {I : Type} [_contextInstance4 : Fintype I] [_contextInstance5 : DecidableEq I] {P : SimpleGraph V} {x : I → V} {y : I → V} (A : Finset I) (q : ∀ i, P.Walk (x i) (y i)) (L : ℕ) + (hq : ∀ i ∈ A, (q i).length ≤ L) : (usedEdges A q).card ≤ L * A.card := by + calc + _ ≤ ∑ i ∈ A, (q i).edges.toFinset.card := Finset.card_biUnion_le + _ ≤ ∑ _i ∈ A, L := Finset.sum_le_sum (fun i hi => by + have hc := List.toFinset_card_le (q i).edges + simpa using hc.trans (by simpa using hq i hi)) + _ = _ := by simp [mul_comm] + +lemma usedEdges_update_insert {V : Type} [_contextInstance1 : Fintype V] [_contextInstance2 : DecidableEq V] {I : Type} [_contextInstance4 : Fintype I] [_contextInstance5 : DecidableEq I] {P : SimpleGraph V} {x : I → V} {y : I → V} (A : Finset I) (i : I) (hi : i ∉ A) + (q : ∀ j, P.Walk (x j) (y j)) (p : P.Walk (x i) (y i)) : + usedEdges (insert i A) (Function.update q i p) = usedEdges A q ∪ p.edges.toFinset := by + classical + rw [usedEdges, Finset.biUnion_insert] + simp only [Function.update_self] + rw [Finset.union_comm] + congr 1 + apply Finset.biUnion_congr rfl + intro j hj + have hji : j ≠ i := by intro h; exact hi (h ▸ hj) + rw [Function.update_of_ne hji] + +noncomputable def teamInterior (A : Finset I) (q : ∀ j, P.Walk (x j) (y j)) + (team : I → T) (i : I) : Finset V := + (A.filter (fun j => team j = team i)).biUnion (fun j => pathInterior (q j)) + +lemma teamInterior_card_le {V : Type} [_contextInstance1 : Fintype V] [_contextInstance2 : DecidableEq V] {I : Type} {T : Type} [_contextInstance5 : Fintype I] [_contextInstance6 : DecidableEq I] [_contextInstance7 : DecidableEq T] {P : SimpleGraph V} {x : I → V} {y : I → V} (A : Finset I) (q : ∀ j, P.Walk (x j) (y j)) + (team : I → T) (i : I) (L : ℕ) (b : ℝ) + (hq : ∀ j ∈ A, (q j).length ≤ L) + (hb : ((Finset.univ.filter (fun j => team j = team i)).card : ℝ) ≤ b) : + ((teamInterior A q team i).card : ℝ) ≤ b * L := by + have hc : (teamInterior A q team i).card ≤ L * (A.filter (fun j => team j = team i)).card := by + calc + _ ≤ ∑ j ∈ A.filter (fun j => team j = team i), (pathInterior (q j)).card := Finset.card_biUnion_le + _ ≤ ∑ _j ∈ A.filter (fun j => team j = team i), L := Finset.sum_le_sum (fun j hj => + (pathInterior_card_le (q j)).trans (hq j (Finset.mem_filter.mp hj).1)) + _ = _ := by simp [mul_comm] + have hcard : ((A.filter (fun j => team j = team i)).card : ℝ) ≤ b := by + apply le_trans _ hb + exact_mod_cast Finset.card_le_card (Finset.filter_subset_filter _ (Finset.subset_univ A)) + have hcR : ((teamInterior A q team i).card : ℝ) ≤ (L : ℝ) * (A.filter (fun j => team j = team i)).card := by exact_mod_cast hc + calc + _ ≤ (L : ℝ) * b := hcR.trans (mul_le_mul_of_nonneg_left hcard (by positivity)) + _ = _ := mul_comm _ _ + +structure PartialRoutes (P : SimpleGraph V) (x y : I → V) (team : I → T) + (Z : I → Finset V) (L : ℕ) (h : ℝ) (A : Finset I) + (q : ∀ i, P.Walk (x i) (y i)) : Prop where + simple : ∀ i ∈ A, (q i).IsPath + short : ∀ i ∈ A, (q i).length ≤ L + avoids : ∀ i ∈ A, Disjoint (pathInterior (q i)) (Z i) + edge_disjoint : ∀ i ∈ A, ∀ j ∈ A, i ≠ j → Disjoint (q i).edges.toFinset (q j).edges.toFinset + team_disjoint : ∀ i ∈ A, ∀ j ∈ A, i ≠ j → team i = team j → Disjoint (pathInterior (q i)) (pathInterior (q j)) + degree : ∀ v, ((incidentEdges (usedEdges A q) v).card : ℝ) ≤ h / 8 + 2 + endpointLoad A x y v + +theorem routing (P : SimpleGraph V) [DecidableRel P.Adj] + (h : ℝ) (hh : 0 < h) (hexp : CutExpansion P h) (hr : 2 ≤ Fintype.card V) + (x y : I → V) (hxy : ∀ i, x i ≠ y i) (team : I → T) (Z : I → Finset V) + (k b z : ℝ) (hk : 1 ≤ k) (hb : 1 ≤ b) (hz : 0 ≤ z) + (hload : ∀ v, (endpointLoad Finset.univ x y v : ℝ) ≤ k) + (hteam : ∀ i, ((Finset.univ.filter (fun j => team j = team i)).card : ℝ) ≤ b) + (hZ : ∀ i, ((Z i).card : ℝ) ≤ z) + (hbudget : 64 * ((routingLength (Fintype.card V) h : ℝ) ^ 2 * (k + b) + z) ≤ h) : + ∃ q : ∀ i, P.Walk (x i) (y i), + (∀ i, (q i).IsPath ∧ (q i).length ≤ routingLength (Fintype.card V) h ∧ + Disjoint (pathInterior (q i)) (Z i)) ∧ + (∀ i j, i ≠ j → Disjoint (q i).edges.toFinset (q j).edges.toFinset) ∧ + (∀ i j, i ≠ j → team i = team j → Disjoint (pathInterior (q i)) (pathInterior (q j))) := by + classical + let L := routingLength (Fintype.card V) h + have hrR : (2 : ℝ) ≤ Fintype.card V := by exact_mod_cast hr + obtain ⟨hL, hreach⟩ := routingLength_bounds (Fintype.card V) h (by linarith) hh + have hLR : (1 : ℝ) ≤ L := by exact_mod_cast hL + obtain ⟨hdegBudget, hforbidBudget, hnumBudget⟩ := routing_budget L k b z h (Fintype.card V) + hLR hk hb hz hh (by positivity) hreach hbudget + have hloadA : ∀ (A : Finset I) v, (endpointLoad A x y v : ℝ) ≤ k := by + intro A v + have hm : (endpointLoad A x y v : ℝ) ≤ endpointLoad Finset.univ x y v := by + exact_mod_cast endpointLoad_mono (Finset.subset_univ A) x y v + exact hm.trans (hload v) + have htotal : 2 * (Fintype.card I : ℝ) ≤ k * Fintype.card V := by + have heq := endpointLoad_sum Finset.univ x y (fun i _ => hxy i) + have heqR : (∑ v : V, (endpointLoad Finset.univ x y v : ℝ)) = 2 * Fintype.card I := by + exact_mod_cast heq + rw [← heqR] + calc + _ ≤ ∑ _v : V, k := Finset.sum_le_sum (fun v _ => hload v) + _ = _ := by simp [mul_comm] + have hdefault : ∀ i, ∃ p : P.Walk (x i) (y i), p.IsPath := by + intro i + obtain ⟨p, hp, _⟩ := exists_short_path_with_avoidance P h hh hexp hr ∅ ∅ (x i) (y i) + (by simp) (by simp) (by intro v; simp [incidentEdges]; positivity) (by simp; positivity) + exact ⟨p, hp⟩ + choose defaultPath hdefaultPath using hdefault + have hpartial : ∀ A : Finset I, ∃ q : ∀ i, P.Walk (x i) (y i), PartialRoutes P x y team Z L h A q := by + intro A + induction A using Finset.induction_on with + | empty => + refine ⟨defaultPath, ?_⟩ + constructor + · simp + · simp + · simp + · simp + · simp + · intro v + simp only [usedEdges, Finset.biUnion_empty, incidentEdges, Finset.filter_empty, + Finset.card_empty, Nat.cast_zero, endpointLoad, add_zero] + linarith + | @insert i A hi ih => + obtain ⟨q, hq⟩ := ih + let F := usedEdges A q + let S := saturated F h + let B := teamInterior A q team i + let W := (S ∪ Z i ∪ B) \ {x i, y i} + have hFcard : 128 * (F.card : ℝ) ≤ h ^ 2 := by + have hc : (F.card : ℝ) ≤ (L : ℝ) * A.card := by + exact_mod_cast usedEdges_card_le A q L hq.short + have ha : (A.card : ℝ) ≤ Fintype.card I := by exact_mod_cast Finset.card_le_univ A + have hsize : 2 * (A.card : ℝ) ≤ k * Fintype.card V := by linarith + have hmult := mul_le_mul_of_nonneg_left hsize (show 0 ≤ (L : ℝ) by positivity) + nlinarith [hnumBudget] + have hS : (S.card : ℝ) ≤ h / 8 := saturated_card_le F h hh hFcard + have hB : (B.card : ℝ) ≤ b * L := teamInterior_card_le A q team i L b hq.short (hteam i) + have hW : (W.card : ℝ) ≤ h / 4 := by + have hc : W.card ≤ S.card + (Z i).card + B.card := + (Finset.card_le_card Finset.sdiff_subset).trans ((Finset.card_union_le _ _).trans + (Nat.add_le_add_right (Finset.card_union_le _ _) _)) + have hcR : (W.card : ℝ) ≤ (S.card : ℝ) + (Z i).card + B.card := by exact_mod_cast hc + linarith [hZ i] + have hFdegree : ∀ v, ((incidentEdges F v).card : ℝ) ≤ h / 4 := by + intro v + have hd := hq.degree v + have hl := hloadA A v + dsimp [F] + linarith + obtain ⟨p, hp, hpL, hpF, hpW⟩ := exists_short_path_with_avoidance P h hh hexp hr F W (x i) (y i) + (by simp [W]) (by simp [W]) hFdegree hW + have hpZ : Disjoint (pathInterior p) (Z i) := by + apply Finset.disjoint_left.mpr + intro v hv hvZ + obtain ⟨hvp, hvends⟩ := Finset.mem_sdiff.mp hv + apply Finset.disjoint_left.mp hpW hvp + exact Finset.mem_sdiff.mpr ⟨Finset.mem_union_left _ (Finset.mem_union_right _ hvZ), hvends⟩ + have hpS : Disjoint p.support.toFinset (saturated F h \ {x i, y i}) := by + apply Finset.disjoint_left.mpr + intro v hv hvS + obtain ⟨hs, he⟩ := Finset.mem_sdiff.mp hvS + apply Finset.disjoint_left.mp hpW hv + exact Finset.mem_sdiff.mpr ⟨Finset.mem_union_left _ (Finset.mem_union_left _ hs), he⟩ + have hpEdge : ∀ j ∈ A, Disjoint p.edges.toFinset (q j).edges.toFinset := by + intro j hj + apply Finset.disjoint_left.mpr + intro e hep heq + exact Finset.disjoint_left.mp hpF hep (Finset.mem_biUnion.mpr ⟨j, hj, heq⟩) + have hpTeam : ∀ j ∈ A, team i = team j → Disjoint (pathInterior p) (pathInterior (q j)) := by + intro j hj htm + apply Finset.disjoint_left.mpr + intro v hvp hvq + obtain ⟨hvp', hvends⟩ := Finset.mem_sdiff.mp hvp + apply Finset.disjoint_left.mp hpW hvp' + apply Finset.mem_sdiff.mpr + refine ⟨Finset.mem_union_right _ ?_, hvends⟩ + exact Finset.mem_biUnion.mpr ⟨j, Finset.mem_filter.mpr ⟨hj, htm.symm⟩, hvq⟩ + let q' := Function.update q i p + have hsame : q' i = p := Function.update_self i p q + have hother : ∀ j ∈ A, q' j = q j := by + intro j hj + apply Function.update_of_ne + intro hji + exact hi (hji ▸ hj) + refine ⟨q', ?_⟩ + constructor + · intro j hj + rcases Finset.mem_insert.mp hj with rfl | hj + · simpa only [hsame] using hp + · simpa only [hother j hj] using hq.simple j hj + · intro j hj + rcases Finset.mem_insert.mp hj with rfl | hj + · simpa only [hsame] using hpL + · simpa only [hother j hj] using hq.short j hj + · intro j hj + rcases Finset.mem_insert.mp hj with rfl | hj + · simpa only [hsame] using hpZ + · simpa only [hother j hj] using hq.avoids j hj + · intro j hj k hk hjk + rcases Finset.mem_insert.mp hj with rfl | hjA + · have hkA : k ∈ A := (Finset.mem_insert.mp hk).resolve_left (Ne.symm hjk) + simpa only [hsame, hother k hkA] using hpEdge k hkA + · rcases Finset.mem_insert.mp hk with rfl | hkA + · simpa only [hsame, hother j hjA] using (hpEdge j hjA).symm + · simpa only [hother j hjA, hother k hkA] using hq.edge_disjoint j hjA k hkA hjk + · intro j hj k hk hjk htm + rcases Finset.mem_insert.mp hj with rfl | hjA + · have hkA : k ∈ A := (Finset.mem_insert.mp hk).resolve_left (Ne.symm hjk) + simpa only [hsame, hother k hkA] using hpTeam k hkA htm + · rcases Finset.mem_insert.mp hk with rfl | hkA + · simpa only [hsame, hother j hjA] using (hpTeam j hjA htm.symm).symm + · simpa only [hother j hjA, hother k hkA] using hq.team_disjoint j hjA k hkA hjk htm + · intro v + have heq : usedEdges (insert i A) q' = F ∪ p.edges.toFinset := usedEdges_update_insert A i hi q p + rw [heq] + have hu := route_degree_update p hp F h (endpointLoad A x y) hq.degree hpS v + have hloadEq : (endpointLoad (insert i A) x y v : ℝ) = + endpointLoad A x y v + (if v = x i ∨ v = y i then (1 : ℝ) else 0) := by + rw [endpointLoad_insert A i hi] + split_ifs <;> simp + rw [hloadEq] + simpa only [add_assoc] using hu + obtain ⟨q, hq⟩ := hpartial Finset.univ + exact ⟨q, fun i => ⟨hq.simple i (by simp), hq.short i (by simp), hq.avoids i (by simp)⟩, + fun i j hij => hq.edge_disjoint i (by simp) j (by simp) hij, + fun i j hij htm => hq.team_disjoint i (by simp) j (by simp) hij htm⟩ + +end Families +end ErdosGallai + +end +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/CycleDecomposition/Sampling.lean b/lean/OAI/Combinatorics/CycleDecomposition/Sampling.lean new file mode 100644 index 0000000000000000000000000000000000000000..60fd93a4f96c69b005d41640354fe826e3ed0b09 --- /dev/null +++ b/lean/OAI/Combinatorics/CycleDecomposition/Sampling.lean @@ -0,0 +1,388 @@ +import Mathlib + +namespace OAI + +universe cycleUniverse1 cycleUniverse2 cycleUniverse3 cycleUniverse4 cycleUniverse5 cycleUniverse6 cycleUniverse7 cycleUniverse8 cycleUniverse9 cycleUniverse10 cycleUniverse11 cycleUniverse12 cycleUniverse13 cycleUniverse14 cycleUniverse15 + +section + +namespace ErdosGallai.Sampling +open MeasureTheory ProbabilityTheory Finset Real + +section BernoulliBounds +variable {Ω : Type cycleUniverse1} {I : Type cycleUniverse2} [MeasurableSpace Ω] {μ : Measure Ω} [IsProbabilityMeasure μ] + +lemma indicator_mem_Icc {Ω : Type cycleUniverse3} [_contextInstance1 : MeasurableSpace Ω] {X : Ω → ℝ} (hX : ∀ ω, X ω = 0 ∨ X ω = 1) (ω : Ω) : + X ω ∈ Set.Icc (0 : ℝ) 1 := by rcases hX ω with h | h <;> simp [h] + +lemma mgf_indicator {X : Ω → ℝ} (hm : Measurable X) + (hX : ∀ ω, X ω = 0 ∨ X ω = 1) (p t : ℝ) (hp : ∫ ω, X ω ∂μ = p) : + mgf X μ t = 1 + p * (exp t - 1) := by + have hXi : Integrable X μ := Integrable.of_mem_Icc 0 1 hm.aemeasurable + (ae_of_all _ (indicator_mem_Icc hX)) + have heq : (fun ω => exp (t * X ω)) = fun ω => (1 : ℝ) + (exp t - 1) * X ω := by + funext ω + rcases hX ω with h | h <;> simp [h] + rw [mgf, heq, integral_add (integrable_const _) (hXi.const_mul _), integral_const_mul, + hp, integral_const] + simp [mul_comm] + +lemma mgf_indicator_sum_bound {X : I → Ω → ℝ} (s : Finset I) + (hm : ∀ i, Measurable (X i)) (hi : iIndepFun X μ) + (hX : ∀ i ω, X i ω = 0 ∨ X i ω = 1) + (p t : ℝ) (hp : ∀ i, ∫ ω, X i ω ∂μ = p) : + mgf (∑ i ∈ s, X i) μ t ≤ exp ((s.card : ℝ) * p * (exp t - 1)) := by + by_cases hs : s.Nonempty + swap + · have he := Finset.not_nonempty_iff_eq_empty.mp hs + simp [he] + rw [hi.mgf_sum hm] + have heq : (∏ i ∈ s, mgf (X i) μ t) = (1 + p * (exp t - 1)) ^ s.card := by + simp_rw [mgf_indicator (hm _) (hX _) p t (hp _)] + simp + rw [heq] + have hn : 0 ≤ 1 + p * (exp t - 1) := by + obtain ⟨i, _⟩ := hs + rw [← mgf_indicator (hm i) (hX i) p t (hp i)] + exact mgf_nonneg + calc + (1 + p * (exp t - 1)) ^ s.card ≤ exp (p * (exp t - 1)) ^ s.card := + pow_le_pow_left₀ hn (by linarith [add_one_le_exp (p * (exp t - 1))]) _ + _ = _ := by rw [← exp_nat_mul]; congr 1; ring + +lemma exp_neg_half_bound : exp (-(1 / 2 : ℝ)) ≤ 5 / 8 := by + have he : exp (1 / 2 : ℝ) * exp (1 / 2 : ℝ) = exp 1 := by + rw [← exp_add]; norm_num + have hlow : (8 / 5 : ℝ) ≤ exp (1 / 2 : ℝ) := by + nlinarith [exp_one_gt_d9, exp_pos (1 / 2 : ℝ)] + rw [exp_neg] + exact (inv_le_comm₀ (exp_pos _) (by norm_num)).mpr (by norm_num at *; exact hlow) + +lemma exp_half_bound : exp (1 / 2 : ℝ) ≤ 5 / 3 := by + have he : exp (1 / 2 : ℝ) * exp (1 / 2 : ℝ) = exp 1 := by + rw [← exp_add]; norm_num + nlinarith [exp_one_lt_d9, exp_pos (1 / 2 : ℝ)] + +theorem bernoulli_sum_lower_tail {X : I → Ω → ℝ} (s : Finset I) + (hm : ∀ i, Measurable (X i)) (hi : iIndepFun X μ) + (hX : ∀ i ω, X i ω = 0 ∨ X i ω = 1) + (p : ℝ) (hp0 : 0 ≤ p) (hp : ∀ i, ∫ ω, X i ω ∂μ = p) : + μ.real {ω | (∑ i ∈ s, X i ω) ≤ p * s.card / 2} ≤ exp (-p * s.card / 8) := by + have hInt : Integrable (fun ω => exp (-(1 / 2 : ℝ) * (∑ i ∈ s, X i) ω)) μ := + hi.integrable_exp_mul_sum hm (fun i _ => integrable_exp_mul_of_mem_Icc + (hm i).aemeasurable (ae_of_all _ (indicator_mem_Icc (hX i)))) + have hb := measure_le_le_exp_mul_mgf (X := ∑ i ∈ s, X i) (p * s.card / 2) + (by norm_num : -(1 / 2 : ℝ) ≤ 0) hInt + simp only [Finset.sum_apply] at hb + apply hb.trans + calc + _ ≤ exp (-(-(1 / 2 : ℝ)) * (p * s.card / 2)) * + exp ((s.card : ℝ) * p * (exp (-(1 / 2 : ℝ)) - 1)) := by + exact mul_le_mul_of_nonneg_left (mgf_indicator_sum_bound s hm hi hX p _ hp) (exp_pos _).le + _ = exp (p * s.card / 4 + (s.card : ℝ) * p * (exp (-(1 / 2 : ℝ)) - 1)) := by + rw [← exp_add]; congr 1; ring + _ ≤ _ := by + apply exp_le_exp.mpr + nlinarith [mul_le_mul_of_nonneg_left exp_neg_half_bound + (mul_nonneg (Nat.cast_nonneg s.card) hp0)] + +theorem bernoulli_sum_upper_tail {X : I → Ω → ℝ} (s : Finset I) + (hm : ∀ i, Measurable (X i)) (hi : iIndepFun X μ) + (hX : ∀ i ω, X i ω = 0 ∨ X i ω = 1) + (p : ℝ) (hp0 : 0 ≤ p) (hp : ∀ i, ∫ ω, X i ω ∂μ = p) : + μ.real {ω | 2 * p * s.card ≤ ∑ i ∈ s, X i ω} ≤ exp (-p * s.card / 3) := by + have hInt : Integrable (fun ω => exp ((1 / 2 : ℝ) * (∑ i ∈ s, X i) ω)) μ := + hi.integrable_exp_mul_sum hm (fun i _ => integrable_exp_mul_of_mem_Icc + (hm i).aemeasurable (ae_of_all _ (indicator_mem_Icc (hX i)))) + have hb := measure_ge_le_exp_mul_mgf (X := ∑ i ∈ s, X i) (2 * p * s.card) + (by norm_num : (0 : ℝ) ≤ 1 / 2) hInt + simp only [Finset.sum_apply] at hb + apply hb.trans + calc + _ ≤ exp (-(1 / 2 : ℝ) * (2 * p * s.card)) * + exp ((s.card : ℝ) * p * (exp (1 / 2 : ℝ) - 1)) := by + exact mul_le_mul_of_nonneg_left (mgf_indicator_sum_bound s hm hi hX p _ hp) (exp_pos _).le + _ = exp (-p * s.card + (s.card : ℝ) * p * (exp (1 / 2 : ℝ) - 1)) := by + rw [← exp_add]; congr 1; ring + _ ≤ _ := by + apply exp_le_exp.mpr + nlinarith [mul_le_mul_of_nonneg_left exp_half_bound + (mul_nonneg (Nat.cast_nonneg s.card) hp0)] + +end BernoulliBounds + +section ProductSamples +variable {V : Type cycleUniverse4} [Fintype V] [DecidableEq V] + +noncomputable def sampleMeasure (V : Type cycleUniverse5) [Fintype V] (p : unitInterval) : Measure (V → Bool) := + Measure.pi (fun _ : V => bernoulliMeasure true false p) + +instance sampleMeasure_probability (p : unitInterval) : IsProbabilityMeasure (sampleMeasure V p) := by + unfold sampleMeasure + infer_instance + +def sampleVertices (ω : V → Bool) : Finset V := Finset.univ.filter (fun v => ω v = true) + +def sampleIndicator (v : V) (ω : V → Bool) : ℝ := if ω v then 1 else 0 + +lemma sampleIndicator_measurable {V : Type cycleUniverse6} [_contextInstance1 : Fintype V] [_contextInstance2 : DecidableEq V] (v : V) : Measurable (sampleIndicator v) := + measurable_of_finite _ + +lemma sampleIndicator_values {V : Type cycleUniverse7} [_contextInstance1 : Fintype V] [_contextInstance2 : DecidableEq V] (v : V) (ω : V → Bool) : + sampleIndicator v ω = 0 ∨ sampleIndicator v ω = 1 := by + simp only [sampleIndicator]; split <;> simp + +lemma sampleIndicator_indep {V : Type cycleUniverse8} [_contextInstance1 : Fintype V] [_contextInstance2 : DecidableEq V] (p : unitInterval) : + iIndepFun (sampleIndicator (V := V)) (sampleMeasure V p) := by + exact iIndepFun_pi (X := fun _ : V => fun b : Bool => if b then (1 : ℝ) else 0) + (fun _ => (measurable_of_finite _).aemeasurable) + +lemma sampleIndicator_integral {V : Type cycleUniverse9} [_contextInstance1 : Fintype V] [_contextInstance2 : DecidableEq V] (p : unitInterval) (v : V) : + ∫ ω, sampleIndicator v ω ∂sampleMeasure V p = (p : ℝ) := by + have hl := (measurePreserving_eval (fun _ : V => bernoulliMeasure true false p) v).hasLaw + have hi := hl.integral_comp (f := fun b : Bool => if b then (1 : ℝ) else 0) + (measurable_of_finite _).aestronglyMeasurable + simpa [sampleMeasure, sampleIndicator, integral_bernoulliMeasure] using hi + +lemma sampleIndicator_sum (S : Finset V) (ω : V → Bool) : + (∑ v ∈ S, sampleIndicator v ω) = ((S ∩ sampleVertices ω).card : ℝ) := by + simp only [sampleIndicator, Finset.sum_boole] + congr 2 + ext v + simp [sampleVertices] + +lemma sample_card_lower_tail (p : unitInterval) (S : Finset V) : + (sampleMeasure V p).real {ω | ((S ∩ sampleVertices ω).card : ℝ) ≤ (p : ℝ) * S.card / 2} ≤ + exp (-(p : ℝ) * S.card / 8) := by + simpa only [sampleIndicator_sum] using bernoulli_sum_lower_tail S + sampleIndicator_measurable (sampleIndicator_indep p) sampleIndicator_values + (p : ℝ) p.property.1 (sampleIndicator_integral p) + +lemma sample_card_upper_tail (p : unitInterval) (S : Finset V) : + (sampleMeasure V p).real {ω | 2 * (p : ℝ) * S.card ≤ ((S ∩ sampleVertices ω).card : ℝ)} ≤ + exp (-(p : ℝ) * S.card / 3) := by + simpa only [sampleIndicator_sum] using bernoulli_sum_upper_tail S + sampleIndicator_measurable (sampleIndicator_indep p) sampleIndicator_values + (p : ℝ) p.property.1 (sampleIndicator_integral p) + +lemma sample_miss_probability (p : unitInterval) (S : Finset V) : + (sampleMeasure V p).real {ω | Disjoint S (sampleVertices ω)} = (1 - (p : ℝ)) ^ S.card := by + have heq : {ω | Disjoint S (sampleVertices ω)} = + Set.univ.pi (fun v : V => if v ∈ S then {false} else Set.univ) := by + ext ω + simp only [Set.mem_ofPred_eq, Set.mem_pi, Set.mem_univ, forall_true_left] + simp only [Finset.disjoint_left, sampleVertices, Finset.mem_filter, Finset.mem_univ, true_and] + constructor + · intro h v + by_cases hv : v ∈ S + · simp only [hv, ↓reduceIte, Set.mem_singleton_iff] + cases hi : ω v <;> simp_all + · simp [hv] + · intro h v hv ht + have := h v + simp_all + rw [heq, Measure.real, sampleMeasure, Measure.pi_pi, ENNReal.toReal_prod] + have hpv (v : V) : + ((bernoulliMeasure true false p) (if v ∈ S then {false} else Set.univ)).toReal = + if v ∈ S then 1 - (p : ℝ) else 1 := by + by_cases hv : v ∈ S + · simp only [hv, ↓reduceIte] + change (bernoulliMeasure true false p).real {false} = _ + exact bernoulliMeasure_real_apply_of_notMem_of_mem p (by simp) (by simp) (by simp) + · simp [hv] + simp_rw [hpv] + simp + +lemma sample_miss_bound (p : unitInterval) (S : Finset V) : + (sampleMeasure V p).real {ω | Disjoint S (sampleVertices ω)} ≤ exp (-(p : ℝ) * S.card) := by + rw [sample_miss_probability] + calc + (1 - (p : ℝ)) ^ S.card ≤ exp (-(p : ℝ)) ^ S.card := by + apply pow_le_pow_left₀ (sub_nonneg.mpr p.property.2) + linarith [add_one_le_exp (-(p : ℝ))] + _ = _ := by rw [← exp_nat_mul]; congr 1; ring + +lemma sample_contains_probability (p : unitInterval) (S : Finset V) : + (sampleMeasure V p) {ω | S ⊆ sampleVertices ω} = ENNReal.ofReal (p : ℝ) ^ S.card := by + have heq : {ω | S ⊆ sampleVertices ω} = + Set.univ.pi (fun v : V => if v ∈ S then {true} else Set.univ) := by + ext ω + simp only [Set.mem_ofPred_eq, Set.mem_pi, Set.mem_univ, forall_true_left] + simp only [Finset.subset_iff, sampleVertices, Finset.mem_filter, Finset.mem_univ, true_and] + constructor + · intro h v + by_cases hv : v ∈ S <;> simp_all + · intro h v hv + simpa [hv] using h v + rw [heq, sampleMeasure, Measure.pi_pi] + have hpv (v : V) : + bernoulliMeasure true false p (if v ∈ S then {true} else Set.univ) = + if v ∈ S then ENNReal.ofReal (p : ℝ) else 1 := by + by_cases hv : v ∈ S + · simp only [hv, ↓reduceIte] + rw [bernoulliMeasure_apply_of_mem_of_notMem p (by simp) (by simp) (by simp)] + exact ENNReal.ofReal_coe_nnreal.symm + · simp [hv] + simp_rw [hpv] + simp + +lemma sample_contains_real_probability (p : unitInterval) (S : Finset V) : + (sampleMeasure V p).real {ω | S ⊆ sampleVertices ω} = (p : ℝ) ^ S.card := by + rw [Measure.real, sample_contains_probability, ENNReal.toReal_pow, + ENNReal.toReal_ofReal p.property.1] + +lemma sample_blocks_independent {I : Type cycleUniverse10} (p : unitInterval) (S : I → Finset V) + (hS : Pairwise fun i j => Disjoint (S i) (S j)) : + iIndepSet (fun i => {ω | S i ⊆ sampleVertices ω}) (sampleMeasure V p) := by + classical + rw [iIndepSet_iff_meas_biInter (fun _ => MeasurableSet.of_discrete)] + intro t + have heq : (⋂ i ∈ t, {ω | S i ⊆ sampleVertices ω}) = + {ω | t.biUnion S ⊆ sampleVertices ω} := by + ext ω + simp only [Set.mem_iInter, Set.mem_ofPred_eq, Finset.biUnion_subset] + rw [heq, sample_contains_probability, Finset.card_biUnion] + · simp_rw [sample_contains_probability] + exact (Finset.prod_pow_eq_pow_sum t (fun i => (S i).card) _).symm + · intro i _ j _ hij + exact hS hij + +noncomputable def blockIndicator (S : Finset V) : (V → Bool) → ℝ := + {ω | S ⊆ sampleVertices ω}.indicator (fun _ => 1) + +lemma blockIndicator_values (S : Finset V) (ω : V → Bool) : + blockIndicator S ω = 0 ∨ blockIndicator S ω = 1 := by + classical + by_cases h : S ⊆ sampleVertices ω <;> simp [blockIndicator, h] + +lemma blockIndicator_integral (p : unitInterval) (S : Finset V) : + ∫ ω, blockIndicator S ω ∂sampleMeasure V p = (p : ℝ) ^ S.card := by + rw [blockIndicator, integral_indicator_const _ MeasurableSet.of_discrete, + sample_contains_real_probability] + simp + +lemma sample_blocks_lower_tail {I : Type cycleUniverse11} (p : unitInterval) (S : I → Finset V) + (hS : Pairwise fun i j => Disjoint (S i) (S j)) (d : ℕ) + (hd : ∀ i, (S i).card = d) (t : Finset I) : + (sampleMeasure V p).real {ω | (∑ i ∈ t, blockIndicator (S i) ω) ≤ + (p : ℝ) ^ d * t.card / 2} ≤ exp (-(p : ℝ) ^ d * t.card / 8) := by + apply bernoulli_sum_lower_tail t (fun _ => measurable_of_finite _) + (sample_blocks_independent p S hS).iIndepFun_indicator + (fun i => blockIndicator_values (S i)) ((p : ℝ) ^ d) (pow_nonneg p.property.1 _) + intro i + change (∫ ω, blockIndicator (S i) ω ∂sampleMeasure V p) = _ + rw [blockIndicator_integral, hd] + +lemma sample_weight_sum (A : Finset V) (w : V → ℝ) (ω : V → Bool) : + (∑ v ∈ A ∩ sampleVertices ω, w v) = ∑ v ∈ A, w v * sampleIndicator v ω := by + rw [← Finset.sum_ite_mem] + apply Finset.sum_congr rfl + intro v _ + simp only [sampleVertices, Finset.mem_filter, Finset.mem_univ, true_and, sampleIndicator] + split <;> simp_all + +lemma sample_weight_integral (p : unitInterval) (A : Finset V) (w : V → ℝ) : + ∫ ω, (∑ v ∈ A ∩ sampleVertices ω, w v) ∂sampleMeasure V p = + (p : ℝ) * ∑ v ∈ A, w v := by + simp_rw [sample_weight_sum] + rw [integral_finsetSum A (fun _ _ => Integrable.of_finite)] + simp_rw [integral_const_mul, sampleIndicator_integral] + rw [← Finset.sum_mul, mul_comm] + +lemma nonnegative_markov_quarter {Ω : Type cycleUniverse12} [MeasurableSpace Ω] + {μ : Measure Ω} [IsProbabilityMeasure μ] {X : Ω → ℝ} + (hi : Integrable X μ) (hn : ∀ ω, 0 ≤ X ω) {B : ℝ} (hB : 0 < B) + (he : ∫ ω, X ω ∂μ ≤ B) : μ.real {ω | 4 * B < X ω} ≤ 1 / 4 := by + have hb := mul_meas_ge_le_integral_of_nonneg (ae_of_all _ hn) hi (4 * B) + have hm : μ.real {ω | 4 * B < X ω} ≤ μ.real {ω | 4 * B ≤ X ω} := + measureReal_mono (fun ω (h : 4 * B < X ω) => h.le) + nlinarith [mul_le_mul_of_nonneg_left hm (by positivity : 0 ≤ 4 * B)] + +lemma sample_weight_markov (p : unitInterval) (hp : 0 < (p : ℝ)) + (A : Finset V) (w : V → ℝ) (hw : ∀ v ∈ A, 0 ≤ w v) + {B : ℝ} (hB : 0 < B) (hs : ∑ v ∈ A, w v ≤ B) : + (sampleMeasure V p).real {ω | 4 * (p : ℝ) * B < ∑ v ∈ A ∩ sampleVertices ω, w v} ≤ + 1 / 4 := by + have ht := nonnegative_markov_quarter (μ := sampleMeasure V p) + (X := fun ω => ∑ v ∈ A ∩ sampleVertices ω, w v) Integrable.of_finite + (fun ω => Finset.sum_nonneg (fun v hv => hw v (Finset.mem_inter.mp hv).1)) + (mul_pos hp hB) (by rw [sample_weight_integral]; exact mul_le_mul_of_nonneg_left hs hp.le) + simpa only [mul_assoc] using ht + +theorem exists_small_weighted_hitting_set {I : Type cycleUniverse13} (A : Finset V) (hA : A.Nonempty) + (good : Finset I) (K : I → Finset V) (hKA : ∀ i ∈ good, K i ⊆ A) + (w : V → ℝ) (hw : ∀ v ∈ A, 0 ≤ w v) {B d : ℝ} + (hB : 0 < B) (hs : ∑ v ∈ A, w v ≤ B) + (hd : ∀ i ∈ good, d ≤ (K i).card) + (q : unitInterval) (hq : 0 < (q : ℝ)) + (hmiss : (good.card : ℝ) * exp (-(q : ℝ) * d) < 1 / 2) : + ∃ S : Finset V, S ⊆ A ∧ (S.card : ℝ) ≤ 4 * (q : ℝ) * A.card ∧ + (∑ v ∈ S, w v) ≤ 4 * (q : ℝ) * B ∧ ∀ i ∈ good, ¬Disjoint (K i) S := by + classical + let μ := sampleMeasure V q + let E₁ : Set (V → Bool) := {ω | 4 * (q : ℝ) * A.card < ((A ∩ sampleVertices ω).card : ℝ)} + let E₂ : Set (V → Bool) := {ω | 4 * (q : ℝ) * B < ∑ v ∈ A ∩ sampleVertices ω, w v} + let E₃ : Set (V → Bool) := ⋃ i ∈ good, {ω | Disjoint (K i) (sampleVertices ω)} + have h₁ : μ.real E₁ ≤ 1 / 4 := by + have ht := sample_weight_markov q hq A (fun _ => (1 : ℝ)) (by simp) + (show (0 : ℝ) < A.card by exact_mod_cast hA.card_pos) (by simp) + simpa [μ, E₁] using ht + have h₂ : μ.real E₂ ≤ 1 / 4 := sample_weight_markov q hq A w hw hB hs + have h₃ : μ.real E₃ < 1 / 2 := by + calc + μ.real E₃ ≤ ∑ i ∈ good, μ.real {ω | Disjoint (K i) (sampleVertices ω)} := + measureReal_biUnion_finset_le good _ + _ ≤ ∑ i ∈ good, exp (-(q : ℝ) * d) := by + apply Finset.sum_le_sum + intro i hi + exact (sample_miss_bound q (K i)).trans (exp_le_exp.mpr + (mul_le_mul_of_nonpos_left (hd i hi) (neg_nonpos.mpr hq.le))) + _ = (good.card : ℝ) * exp (-(q : ℝ) * d) := by simp + _ < _ := hmiss + have hf : μ.real (E₁ ∪ E₂ ∪ E₃) < 1 := by + have ha := measureReal_union_le (μ := μ) (E₁ ∪ E₂) E₃ + have hb := measureReal_union_le (μ := μ) E₁ E₂ + linarith + have hne : E₁ ∪ E₂ ∪ E₃ ≠ Set.univ := by + intro h + rw [h] at hf + have hu : μ.real Set.univ = 1 := by simp [μ, Measure.real] + linarith + obtain ⟨ω, hω⟩ := (Set.ne_univ_iff_exists_notMem _).mp hne + have hn := hω + simp only [Set.mem_union, not_or] at hn + refine ⟨A ∩ sampleVertices ω, Finset.inter_subset_left, le_of_not_gt hn.1.1, + le_of_not_gt hn.1.2, ?_⟩ + intro i hi hdj + apply hn.2 + simp only [E₃, Set.mem_iUnion, Set.mem_ofPred_eq] + refine ⟨i, hi, ?_⟩ + apply Finset.disjoint_left.mpr + intro v hv hvs + exact Finset.disjoint_left.mp hdj hv (Finset.mem_inter.mpr ⟨hKA i hi hv, hvs⟩) + +end ProductSamples + +section FiniteUnion +variable {Ω : Type cycleUniverse14} {I : Type cycleUniverse15} [MeasurableSpace Ω] {μ : Measure Ω} [IsProbabilityMeasure μ] + +lemma exists_avoiding_finite_events (s : Finset I) (E : I → Set Ω) + (h : ∑ i ∈ s, μ.real (E i) < 1) : ∃ ω, ∀ i ∈ s, ω ∉ E i := by + by_contra hn + push Not at hn + have cover : (⋃ i ∈ s, E i) = Set.univ := by + ext ω + simp only [Set.mem_iUnion, Set.mem_univ, iff_true] + obtain ⟨i, hi, he⟩ := hn ω + exact ⟨i, hi, he⟩ + have hu := measureReal_biUnion_finset_le (μ := μ) s E + rw [cover] at hu + have : μ.real Set.univ = 1 := by simp [Measure.real] + rw [this] at hu + linarith + +end FiniteUnion +end ErdosGallai.Sampling +end + +end OAI diff --git a/lean/OAI/Combinatorics/CycleDecomposition/SamplingCuts.lean b/lean/OAI/Combinatorics/CycleDecomposition/SamplingCuts.lean new file mode 100644 index 0000000000000000000000000000000000000000..0ee1c3ddf34787b3bbd42ef023d5f1231687738c --- /dev/null +++ b/lean/OAI/Combinatorics/CycleDecomposition/SamplingCuts.lean @@ -0,0 +1,713 @@ +import OAI.Combinatorics.CycleDecomposition.Sampling + +namespace OAI + +universe cycleUniverse1 cycleUniverse2 cycleUniverse3 cycleUniverse4 cycleUniverse5 cycleUniverse6 cycleUniverse7 + +section +namespace ErdosGallai.Sampling +open Finset MeasureTheory ProbabilityTheory Real +open scoped symmDiff +variable {V : Type cycleUniverse1} [Fintype V] [DecidableEq V] + +noncomputable def cutColor (e : V × V) : ℕ := + (Fintype.equivFin V e.1).val + (Fintype.equivFin V e.2).val + +lemma cutColor_lt {V : Type cycleUniverse2} [_contextInstance1 : Fintype V] [_contextInstance2 : DecidableEq V] (e : V × V) : cutColor e < 2 * Fintype.card V := by + have h₁ := (Fintype.equivFin V e.1).isLt + have h₂ := (Fintype.equivFin V e.2).isLt + dsimp [cutColor] + omega + +lemma same_cutColor_blocks_disjoint (A B : Finset V) (hAB : Disjoint A B) + {e f : V × V} (he₁ : e.1 ∈ A) (he₂ : e.2 ∈ B) + (hf₁ : f.1 ∈ A) (hf₂ : f.2 ∈ B) (hc : cutColor e = cutColor f) (hef : e ≠ f) : + Disjoint ({e.1, e.2} : Finset V) {f.1, f.2} := by + have h₁ : e.1 ≠ f.1 := by + intro h + have ht : e.2 = f.2 := (Fintype.equivFin V).injective (Fin.ext (by + dsimp [cutColor] at hc + rw [h] at hc + omega)) + exact hef (Prod.ext h ht) + have h₂ : e.2 ≠ f.2 := by + intro h + have ht : e.1 = f.1 := (Fintype.equivFin V).injective (Fin.ext (by + dsimp [cutColor] at hc + rw [h] at hc + omega)) + exact hef (Prod.ext ht h) + have h₃ : e.1 ≠ f.2 := fun h => Finset.disjoint_left.mp hAB he₁ (h ▸ hf₂) + have h₄ : e.2 ≠ f.1 := fun h => Finset.disjoint_left.mp hAB hf₁ (h ▸ he₂) + simp [Finset.disjoint_left, h₁, h₂, h₃, h₄] + +lemma blockIndicator_sum_card (E : Finset (V × V)) (ω : V → Bool) : + (∑ e ∈ E, blockIndicator ({e.1, e.2} : Finset V) ω) = + ((E.filter (fun e => e.1 ∈ sampleVertices ω ∧ e.2 ∈ sampleVertices ω)).card : ℝ) := by + classical + simp only [blockIndicator, Set.indicator_apply, Set.mem_ofPred_eq, + Finset.insert_subset_iff, Finset.singleton_subset_iff] + exact Finset.sum_boole _ _ + +lemma sampled_matching_lower_tail (p : unitInterval) (A B : Finset V) (hAB : Disjoint A B) + (E : Finset (V × V)) (hE : ∀ e ∈ E, e.1 ∈ A ∧ e.2 ∈ B) + (c : ℕ) (hc : ∀ e ∈ E, cutColor e = c) : + (sampleMeasure V p).real {ω | + ((E.filter (fun e => e.1 ∈ sampleVertices ω ∧ e.2 ∈ sampleVertices ω)).card : ℝ) ≤ + (p : ℝ) ^ 2 * E.card / 2} ≤ exp (-(p : ℝ) ^ 2 * E.card / 8) := by + classical + let S : E → Finset V := fun e => {e.val.1, e.val.2} + have hS : Pairwise fun e f : E => Disjoint (S e) (S f) := by + intro e f hef + exact same_cutColor_blocks_disjoint A B hAB (hE e e.property).1 (hE e e.property).2 + (hE f f.property).1 (hE f f.property).2 ((hc e e.property).trans (hc f f.property).symm) + (fun h => hef (Subtype.ext h)) + have hd : ∀ e : E, (S e).card = 2 := by + intro e + apply Finset.card_pair + intro h + exact Finset.disjoint_left.mp hAB (hE e e.property).1 (h ▸ (hE e e.property).2) + have ht := sample_blocks_lower_tail p S hS 2 hd Finset.univ + have heq (ω : V → Bool) : (∑ e : E, blockIndicator (S e) ω) = + (∑ e ∈ E, blockIndicator ({e.1, e.2} : Finset V) ω) := by + exact Finset.sum_attach E (fun e => blockIndicator ({e.1, e.2} : Finset V) ω) + simp_rw [heq, blockIndicator_sum_card] at ht + simpa using ht + +lemma sum_cutColor_class_card (E : Finset (V × V)) : + (∑ i ∈ Finset.range (2 * Fintype.card V), (E.filter (fun e => cutColor e = i)).card) = + E.card := by + rw [Finset.sum_card_fiberwise_eq_card_filter] + congr 1 + apply Finset.filter_true_of_mem + intro e _ + exact Finset.mem_range.mpr (cutColor_lt e) + +theorem sampled_bipartite_cut_lower_tail (p : unitInterval) + (hr : 0 < Fintype.card V) (A B : Finset V) (hAB : Disjoint A B) + (E : Finset (V × V)) (hE : ∀ e ∈ E, e.1 ∈ A ∧ e.2 ∈ B) : + (sampleMeasure V p).real {ω | + ((E.filter (fun e => e.1 ∈ sampleVertices ω ∧ e.2 ∈ sampleVertices ω)).card : ℝ) < + (p : ℝ) ^ 2 * E.card / 4} ≤ + 2 * (Fintype.card V : ℝ) * exp (-(p : ℝ) ^ 2 * E.card / (32 * Fintype.card V)) := by + classical + let r : ℝ := Fintype.card V + have hrR : 0 < r := by + change 0 < (Fintype.card V : ℝ) + exact_mod_cast hr + let colors := Finset.range (2 * Fintype.card V) + let C (i : ℕ) := E.filter (fun e => cutColor e = i) + let m (i : ℕ) : ℝ := (C i).card + let L := colors.filter (fun i => (E.card : ℝ) / (4 * r) ≤ m i) + let retained (i : ℕ) (ω : V → Bool) : ℝ := + ((C i |>.filter (fun e => e.1 ∈ sampleVertices ω ∧ e.2 ∈ sampleVertices ω)).card : ℝ) + have hsum : ∑ i ∈ colors, m i = (E.card : ℝ) := by + dsimp [colors, m, C] + exact_mod_cast sum_cutColor_class_card E + have hretain (ω : V → Bool) : ∑ i ∈ colors, retained i ω = + ((E.filter (fun e => e.1 ∈ sampleVertices ω ∧ e.2 ∈ sampleVertices ω)).card : ℝ) := by + have ht := sum_cutColor_class_card + (E.filter (fun e => e.1 ∈ sampleVertices ω ∧ e.2 ∈ sampleVertices ω)) + simpa only [retained, C, colors, Finset.filter_filter, and_comm, Nat.cast_sum] using + (show (∑ i ∈ Finset.range (2 * Fintype.card V), + (((E.filter (fun e => e.1 ∈ sampleVertices ω ∧ e.2 ∈ sampleVertices ω)).filter + (fun e => cutColor e = i)).card : ℝ)) = _ by exact_mod_cast ht) + have hlarge : (E.card : ℝ) / 2 ≤ ∑ i ∈ L, m i := by + have hb : ∑ i ∈ colors, m i ≤ + ∑ i ∈ colors, ((if i ∈ L then m i else 0) + (E.card : ℝ) / (4 * r)) := by + apply Finset.sum_le_sum + intro i hi + by_cases hiL : i ∈ L + · simp only [hiL, ↓reduceIte] + have : 0 ≤ (E.card : ℝ) / (4 * r) := by positivity + linarith + · have hiM : m i < (E.card : ℝ) / (4 * r) := by + simpa only [L, Finset.mem_filter, hi, true_and, not_le] using hiL + simp only [hiL, ↓reduceIte, zero_add] + exact hiM.le + rw [hsum, Finset.sum_add_distrib, Finset.sum_ite_mem] at hb + have hsub : colors ∩ L = L := Finset.inter_eq_right.mpr (Finset.filter_subset _ _) + rw [hsub] at hb + have hconst : ∑ _i ∈ colors, (E.card : ℝ) / (4 * r) = (E.card : ℝ) / 2 := by + simp only [Finset.sum_const, nsmul_eq_mul, colors, Finset.card_range, Nat.cast_mul, + Nat.cast_ofNat] + dsimp [r] at * + field_simp + ; ring + rw [hconst] at hb + linarith + let Bad (i : ℕ) : Set (V → Bool) := + {ω | retained i ω ≤ (p : ℝ) ^ 2 * m i / 2} + have hcover : {ω | + ((E.filter (fun e => e.1 ∈ sampleVertices ω ∧ e.2 ∈ sampleVertices ω)).card : ℝ) < + (p : ℝ) ^ 2 * E.card / 4} ⊆ ⋃ i ∈ L, Bad i := by + intro ω hfail + by_contra hnot + have hiok : ∀ i ∈ L, (p : ℝ) ^ 2 * m i / 2 ≤ retained i ω := by + intro i hi + have hn : ω ∉ Bad i := fun h => hnot (Set.mem_iUnion.mpr ⟨i, + Set.mem_iUnion.mpr ⟨hi, h⟩⟩) + exact (lt_of_not_ge hn).le + have hs₁ : (p : ℝ) ^ 2 / 2 * (∑ i ∈ L, m i) ≤ ∑ i ∈ L, retained i ω := by + rw [Finset.mul_sum] + apply Finset.sum_le_sum + intro i hi + calc + _ = (p : ℝ) ^ 2 * m i / 2 := by ring + _ ≤ retained i ω := hiok i hi + have hs₂ : (∑ i ∈ L, retained i ω) ≤ ∑ i ∈ colors, retained i ω := + Finset.sum_le_sum_of_subset_of_nonneg (Finset.filter_subset _ _) + (fun i _ _ => Nat.cast_nonneg _) + rw [hretain] at hs₂ + have hs₃ := mul_le_mul_of_nonneg_left hlarge (by positivity : 0 ≤ (p : ℝ) ^ 2 / 2) + change ((E.filter (fun e => e.1 ∈ sampleVertices ω ∧ e.2 ∈ sampleVertices ω)).card : ℝ) < + (p : ℝ) ^ 2 * E.card / 4 at hfail + nlinarith + have hbad (i : ℕ) (hi : i ∈ L) : (sampleMeasure V p).real (Bad i) ≤ + exp (-(p : ℝ) ^ 2 * E.card / (32 * r)) := by + have ht := sampled_matching_lower_tail p A B hAB (C i) + (fun e he => hE e (Finset.mem_filter.mp he).1) i + (fun e he => (Finset.mem_filter.mp he).2) + have hm : (E.card : ℝ) / (4 * r) ≤ m i := (Finset.mem_filter.mp hi).2 + have he : -(p : ℝ) ^ 2 * m i / 8 ≤ -(p : ℝ) ^ 2 * E.card / (32 * r) := by + have ht := mul_le_mul_of_nonpos_left hm (neg_nonpos.mpr (sq_nonneg (p : ℝ))) + calc + _ ≤ (-(p : ℝ) ^ 2 * ((E.card : ℝ) / (4 * r))) / 8 := by linarith + _ = _ := by ring + exact ht.trans (exp_le_exp.mpr he) + calc + _ ≤ (sampleMeasure V p).real (⋃ i ∈ L, Bad i) := measureReal_mono hcover (measure_ne_top _ _) + _ ≤ ∑ i ∈ L, (sampleMeasure V p).real (Bad i) := measureReal_biUnion_finset_le L Bad + _ ≤ ∑ i ∈ L, exp (-(p : ℝ) ^ 2 * E.card / (32 * r)) := Finset.sum_le_sum hbad + _ = (L.card : ℝ) * exp (-(p : ℝ) ^ 2 * E.card / (32 * r)) := by simp + _ ≤ 2 * r * exp (-(p : ℝ) ^ 2 * E.card / (32 * r)) := by + apply mul_le_mul_of_nonneg_right _ (exp_pos _).le + have ht := Finset.card_le_card (Finset.filter_subset (fun i => (E.card : ℝ) / (4 * r) ≤ m i) colors) + have ht' : L.card ≤ 2 * Fintype.card V := by + simpa only [colors, Finset.card_range] using ht + change (L.card : ℝ) ≤ 2 * (Fintype.card V : ℝ) + exact_mod_cast ht' + +def neighborsIn (P : SimpleGraph V) [DecidableRel P.Adj] (v : V) (A : Finset V) := + A.filter (P.Adj v) + +lemma card_interedges_eq_sum_neighborsIn {V : Type cycleUniverse3} [_contextInstance1 : Fintype V] [_contextInstance2 : DecidableEq V] (P : SimpleGraph V) [DecidableRel P.Adj] + (A B : Finset V) : (P.interedges A B).card = ∑ v ∈ A, (neighborsIn P v B).card := by + simp only [SimpleGraph.interedges, Rel.interedges, neighborsIn, Finset.card_filter] + rw [Finset.sum_product] + +lemma neighborsIn_partition_card {V : Type cycleUniverse4} [_contextInstance1 : Fintype V] [_contextInstance2 : DecidableEq V] (P : SimpleGraph V) [DecidableRel P.Adj] + (v : V) (A W : Finset V) (hAW : A ⊆ W) : + (neighborsIn P v W).card = (neighborsIn P v A).card + (neighborsIn P v (W \ A)).card := by + have hu : neighborsIn P v W = neighborsIn P v A ∪ neighborsIn P v (W \ A) := by + ext x; simp only [neighborsIn, Finset.mem_union, Finset.mem_filter, Finset.mem_sdiff] + constructor + · intro ⟨hx, ha⟩ + by_cases hxA : x ∈ A + · exact Or.inl ⟨hxA, ha⟩ + · exact Or.inr ⟨⟨hx, hxA⟩, ha⟩ + · rintro (⟨hx, ha⟩ | ⟨⟨hx, _⟩, ha⟩) + · exact ⟨hAW hx, ha⟩ + · exact ⟨hx, ha⟩ + rw [hu, Finset.card_union_of_disjoint] + apply Finset.disjoint_left.mpr + intro x hx hy + exact (Finset.mem_sdiff.mp (Finset.mem_filter.mp hy).1).2 (Finset.mem_filter.mp hx).1 + +lemma interedges_sym2_injective {V : Type cycleUniverse5} [_contextInstance1 : Fintype V] [_contextInstance2 : DecidableEq V] (P : SimpleGraph V) [DecidableRel P.Adj] + (A B : Finset V) (hAB : Disjoint A B) : + Set.InjOn (fun e : V × V => s(e.1, e.2)) (P.interedges A B : Set (V × V)) := by + intro e he f hf hef + rcases Sym2.mk_eq_mk_iff.mp hef with h | h + · exact h + · exact False.elim <| Finset.disjoint_left.mp hAB (P.mem_interedges_iff.mp he).1 + ((congrArg Prod.fst h).symm ▸ (P.mem_interedges_iff.mp hf).2.1) + +lemma cut_perturbation_card (P : SimpleGraph V) [DecidableRel P.Adj] + (W A T : Finset V) (_hAW : A ⊆ W) (_hTW : T ⊆ W) : + (P.interedges T (W \ T)).card ≤ (P.interedges A (W \ A)).card + + Fintype.card V * (A ∆ T).card := by + classical + let f := fun e : V × V => s(e.1, e.2) + let E := (P.interedges A (W \ A)).image f + let D := (((A ∆ T) ×ˢ (Finset.univ : Finset V)).image f) + have hinj := interedges_sym2_injective P T (W \ T) (Finset.disjoint_left.mpr (by + intro x hx hy + exact (Finset.mem_sdiff.mp hy).2 hx)) + have hsub : (P.interedges T (W \ T)).image f ⊆ E ∪ D := by + intro e he + obtain ⟨⟨x,y⟩, hxy, rfl⟩ := Finset.mem_image.mp he + rcases P.mem_interedges_iff.mp hxy with ⟨hxT, hyWT, hxy⟩ + obtain ⟨hyW, hyT⟩ := Finset.mem_sdiff.mp hyWT + by_cases hxA : x ∈ A + · by_cases hyA : y ∈ A + · apply Finset.mem_union_right + apply Finset.mem_image.mpr + refine ⟨(y,x), Finset.mem_product.mpr ⟨?_, Finset.mem_univ _⟩, ?_⟩ + · exact Finset.mem_symmDiff.mpr (Or.inl ⟨hyA, hyT⟩) + · exact Sym2.eq_swap + · apply Finset.mem_union_left + exact Finset.mem_image.mpr ⟨(x,y), P.mem_interedges_iff.mpr + ⟨hxA, Finset.mem_sdiff.mpr ⟨hyW, hyA⟩, hxy⟩, rfl⟩ + · apply Finset.mem_union_right + exact Finset.mem_image.mpr ⟨(x,y), Finset.mem_product.mpr + ⟨Finset.mem_symmDiff.mpr (Or.inr ⟨hxT, hxA⟩), Finset.mem_univ _⟩, rfl⟩ + calc + _ = ((P.interedges T (W \ T)).image f).card := (Finset.card_image_of_injOn hinj).symm + _ ≤ (E ∪ D).card := Finset.card_le_card hsub + _ ≤ E.card + D.card := Finset.card_union_le _ _ + _ ≤ (P.interedges A (W \ A)).card + (((A ∆ T) ×ˢ (Finset.univ : Finset V))).card := + Nat.add_le_add (Finset.card_image_le) Finset.card_image_le + _ = _ := by simp [mul_comm] + +lemma card_le_add_symmDiff {V : Type cycleUniverse6} [_contextInstance1 : Fintype V] [_contextInstance2 : DecidableEq V] (A T : Finset V) : A.card ≤ T.card + (A ∆ T).card := by + have hs : A ⊆ T ∪ (A ∆ T) := by + intro x hx + by_cases hxT : x ∈ T + · exact Finset.mem_union_left _ hxT + · exact Finset.mem_union_right _ (Finset.mem_symmDiff.mpr (Or.inl ⟨hx,hxT⟩)) + exact (Finset.card_le_card hs).trans (Finset.card_union_le _ _) + +lemma sdiff_card_le_add_symmDiff {V : Type cycleUniverse7} [_contextInstance1 : Fintype V] [_contextInstance2 : DecidableEq V] (W A T : Finset V) : + (W \ A).card ≤ (W \ T).card + (A ∆ T).card := by + have hs : W \ A ⊆ (W \ T) ∪ (A ∆ T) := by + intro x hx + obtain ⟨hxW,hxA⟩ := Finset.mem_sdiff.mp hx + by_cases hxT : x ∈ T + · exact Finset.mem_union_right _ (Finset.mem_symmDiff.mpr (Or.inr ⟨hxT,hxA⟩)) + · exact Finset.mem_union_left _ (Finset.mem_sdiff.mpr ⟨hxW,hxT⟩) + exact (Finset.card_le_card hs).trans (Finset.card_union_le _ _) + +lemma cut_card_lower_of_neighbors (P : SimpleGraph V) [DecidableRel P.Adj] + (A B Q : Finset V) (hQA : Q ⊆ A) (c : ℝ) + (hc : ∀ v ∈ Q, c ≤ (neighborsIn P v B).card) : + c * Q.card ≤ ((P.interedges A B).card : ℝ) := by + rw [card_interedges_eq_sum_neighborsIn, Nat.cast_sum] + calc + _ = ∑ v ∈ Q, c := by simp [mul_comm] + _ ≤ ∑ v ∈ Q, ((neighborsIn P v B).card : ℝ) := Finset.sum_le_sum hc + _ ≤ ∑ v ∈ A, ((neighborsIn P v B).card : ℝ) := + Finset.sum_le_sum_of_subset_of_nonneg hQA (fun _ _ _ => Nat.cast_nonneg _) + +lemma bad_sampled_cut_size_and_exceptional (P : SimpleGraph V) [DecidableRel P.Adj] + (W A : Finset V) (hAW : A ⊆ W) (_ha : 0 < (A.card : ℝ)) + {p h τ : ℝ} (hp : 0 < p) (hh : 0 < h) (hτ : τ < p*h/4) + (hdeg : ∀ v, p*h/2 ≤ ((neighborsIn P v W).card : ℝ)) + (hbad : ((P.interedges A (W \ A)).card : ℝ) < τ * A.card) : + p*h/4 < (A.card : ℝ) ∧ + ((A \ A.filter (fun v => p*h/4 ≤ ((neighborsIn P v A).card : ℝ))).card : ℝ) ≤ + 4*τ*A.card/(p*h) := by + have hpart (v : V) : ((neighborsIn P v W).card : ℝ) = + ((neighborsIn P v A).card : ℝ) + ((neighborsIn P v (W \ A)).card : ℝ) := by + exact_mod_cast neighborsIn_partition_card P v A W hAW + constructor + · by_contra hn + have ha' : (A.card : ℝ) ≤ p*h/4 := le_of_not_gt hn + have hlo : p*h/4 * A.card ≤ ((P.interedges A (W \ A)).card : ℝ) := by + apply cut_card_lower_of_neighbors P A (W \ A) A (Finset.Subset.refl _) (p*h/4) + intro v _ + have hc : ((neighborsIn P v A).card : ℝ) ≤ A.card := by + exact_mod_cast Finset.card_le_card (Finset.filter_subset (P.Adj v) A) + have hd := hdeg v + have he := hpart v + linarith + nlinarith + · let Q := A \ A.filter (fun v => p*h/4 ≤ ((neighborsIn P v A).card : ℝ)) + have hl : p*h/4 * Q.card ≤ ((P.interedges A (W \ A)).card : ℝ) := by + apply cut_card_lower_of_neighbors P A (W \ A) Q Finset.sdiff_subset (p*h/4) + intro v hv + obtain ⟨hvA,hvG⟩ := Finset.mem_sdiff.mp hv + have hn : ((neighborsIn P v A).card : ℝ) < p*h/4 := by + simpa only [Finset.mem_filter, hvA, true_and, not_le] using hvG + have hd := hdeg v + have he := hpart v + linarith + change (Q.card : ℝ) ≤ _ + apply (le_div_iff₀ (mul_pos hp hh)).mpr + nlinarith + +def neighborhoodUnion (P : SimpleGraph V) [DecidableRel P.Adj] (S : Finset V) : Finset V := + S.biUnion (fun v => neighborsIn P v Finset.univ) + +lemma neighborhoodUnion_leakage (P : SimpleGraph V) [DecidableRel P.Adj] + (S W A : Finset V) : + (((neighborhoodUnion P S ∩ W) \ A).card : ℝ) ≤ + ∑ v ∈ S, ((neighborsIn P v (W \ A)).card : ℝ) := by + have heq : (neighborhoodUnion P S ∩ W) \ A = + S.biUnion (fun v => neighborsIn P v (W \ A)) := by + ext x + simp only [neighborhoodUnion, neighborsIn, Finset.mem_sdiff, Finset.mem_inter, + Finset.mem_biUnion, Finset.mem_filter, Finset.mem_univ, true_and] + aesop + rw [heq] + exact_mod_cast Finset.card_biUnion_le + +lemma hitting_neighborhoodUnion (P : SimpleGraph V) [DecidableRel P.Adj] + (good S A : Finset V) (hhit : ∀ v ∈ good, ¬Disjoint (neighborsIn P v A) S) : + good ⊆ neighborhoodUnion P S := by + intro v hv + obtain ⟨x,hxK,hxS⟩ := Finset.not_disjoint_iff.mp (hhit v hv) + apply Finset.mem_biUnion.mpr + refine ⟨x,hxS,?_⟩ + exact Finset.mem_filter.mpr ⟨Finset.mem_univ _, P.adj_symm (Finset.mem_filter.mp hxK).2⟩ + +theorem exists_approximating_witness (P : SimpleGraph V) [DecidableRel P.Adj] + (W A : Finset V) (hAW : A ⊆ W) (ha : 0 < (A.card : ℝ)) + {p h τ M : ℝ} (hp : 0 < p) (hh : 0 < h) (hτ0 : 0 < τ) + (hτ : τ < p*h/4) (hM : 0 < M) (hMh : M ≤ h) + (hmiss : (Fintype.card V : ℝ) * exp (-p*M/4) < 1/2) + (hdeg : ∀ v, p*h/2 ≤ ((neighborsIn P v W).card : ℝ)) + (hbad : ((P.interedges A (W \ A)).card : ℝ) < τ * A.card) : + p*h/4 < (A.card : ℝ) ∧ ∃ S : Finset V, S ⊆ A ∧ + (S.card : ℝ) ≤ 4 * A.card * M / h ∧ + ((A ∆ (neighborhoodUnion P S ∩ W)).card : ℝ) ≤ + (4*τ/(p*h) + 4*τ*M/h) * A.card := by + classical + obtain ⟨hlarge, hexc⟩ := bad_sampled_cut_size_and_exceptional P W A hAW ha hp hh hτ hdeg hbad + refine ⟨hlarge, ?_⟩ + let good := A.filter (fun v => p*h/4 ≤ ((neighborsIn P v A).card : ℝ)) + let w : V → ℝ := fun v => ((neighborsIn P v (W \ A)).card : ℝ) + let q : unitInterval := ⟨M/h, div_nonneg hM.le hh.le, (div_le_one hh).mpr hMh⟩ + have hq : 0 < (q : ℝ) := div_pos hM hh + have hm : (good.card : ℝ) * exp (-(q : ℝ) * (p*h/4)) < 1/2 := by + have heq : -(q : ℝ) * (p*h/4) = -p*M/4 := by + dsimp [q] + field_simp [hh.ne'] + rw [heq] + have hg : (good.card : ℝ) ≤ Fintype.card V := by exact_mod_cast Finset.card_le_univ good + exact (mul_le_mul_of_nonneg_right hg (exp_pos _).le).trans_lt hmiss + have hsum : ∑ v ∈ A, w v ≤ τ * A.card := by + dsimp [w] + rw [← Nat.cast_sum, ← card_interedges_eq_sum_neighborsIn] + exact hbad.le + obtain ⟨S,hSA,hSc,hSw,hSh⟩ := exists_small_weighted_hitting_set A + (Finset.card_pos.mp (by exact_mod_cast ha)) good (fun v => neighborsIn P v A) + (fun v _ => Finset.filter_subset _ _) w (fun _ _ => Nat.cast_nonneg _) + (mul_pos hτ0 ha) hsum + (fun v hv => (Finset.mem_filter.mp hv).2) q hq hm + refine ⟨S,hSA,?_,?_⟩ + · convert hSc using 1 ; dsimp [q] ; ring + · let T := neighborhoodUnion P S ∩ W + have hgood : good ⊆ neighborhoodUnion P S := hitting_neighborhoodUnion P good S A hSh + have hsub : A ∆ T ⊆ (A \ good) ∪ (T \ A) := by + intro v hv + rcases Finset.mem_symmDiff.mp hv with ⟨hvA,hvT⟩ | ⟨hvT,hvA⟩ + · apply Finset.mem_union_left + apply Finset.mem_sdiff.mpr + refine ⟨hvA,?_⟩ + intro hvG + exact hvT (Finset.mem_inter.mpr ⟨hgood hvG, hAW hvA⟩) + · exact Finset.mem_union_right _ (Finset.mem_sdiff.mpr ⟨hvT,hvA⟩) + have hδ : ((A ∆ T).card : ℝ) ≤ ((A \ good).card : ℝ) + ((T \ A).card : ℝ) := by + exact_mod_cast (Finset.card_le_card hsub).trans (Finset.card_union_le _ _) + have hleak : ((T \ A).card : ℝ) ≤ 4*(q : ℝ)*(τ*A.card) := + (neighborhoodUnion_leakage P S W A).trans hSw + change ((A ∆ T).card : ℝ) ≤ _ + change ((A \ good).card : ℝ) ≤ _ at hexc + calc + _ ≤ 4*τ*A.card/(p*h) + 4*(q : ℝ)*(τ*A.card) := add_le_add hexc hleak |>.trans' hδ + _ = _ := by dsimp [q]; ring + +def CutExpansion (P : SimpleGraph V) [DecidableRel P.Adj] (h : ℝ) : Prop := + ∀ U : Finset V, h * min (U.card : ℝ) (Uᶜ.card : ℝ) ≤ + ((P.interedges U Uᶜ).card : ℝ) + +def CutExpansionOn (P : SimpleGraph V) [DecidableRel P.Adj] (W : Finset V) (h : ℝ) : Prop := + ∀ A : Finset V, A ⊆ W → h * min (A.card : ℝ) ((W \ A).card : ℝ) ≤ + ((P.interedges A (W \ A)).card : ℝ) + +theorem cutExpansionOn_of_witnesses (P : SimpleGraph V) [DecidableRel P.Adj] + (W : Finset V) {p h τ M : ℝ} (hp : 0 < p) (hh : 0 < h) (hτ0 : 0 < τ) + (hτ : τ < p*h/4) (hM : 0 < M) (hMh : M ≤ h) + (hmiss : (Fintype.card V : ℝ) * exp (-p*M/4) < 1/2) + (hε : 4*τ/(p*h) + 4*τ*M/h ≤ 1/2) + (hperturb : τ + Fintype.card V * (4*τ/(p*h) + 4*τ*M/h) ≤ p^2*h/8) + (hexp : CutExpansion P h) + (hdeg : ∀ v, p*h/2 ≤ ((neighborsIn P v W).card : ℝ)) + (hwitness : ∀ S : Finset V, (S.card : ℝ) ≤ 4*Fintype.card V*M/h → + let U := neighborhoodUnion P S + p*h/8 ≤ min (U.card : ℝ) (Uᶜ.card : ℝ) → + (p^2/4) * ((P.interedges U Uᶜ).card : ℝ) ≤ + ((P.interedges (U ∩ W) (W \ (U ∩ W))).card : ℝ)) : + CutExpansionOn P W τ := by + classical + have hsmall (A : Finset V) (hAW : A ⊆ W) + (hsize : (A.card : ℝ) ≤ (W \ A).card) : + τ * A.card ≤ ((P.interedges A (W \ A)).card : ℝ) := by + by_contra hn + have hbad := lt_of_not_ge hn + have ha : 0 < (A.card : ℝ) := by + by_contra hn + have hz : (A.card : ℝ) = 0 := (le_of_not_gt hn).antisymm (Nat.cast_nonneg _) + rw [hz, mul_zero] at hbad + exact (Nat.cast_nonneg _).not_gt hbad + obtain ⟨hlarge,S,hSA,hSc,hδ⟩ := exists_approximating_witness P W A hAW ha + hp hh hτ0 hτ hM hMh hmiss hdeg hbad + let U := neighborhoodUnion P S + let T := U ∩ W + let δ : ℝ := (A ∆ T).card + have hδ' : δ ≤ (A.card : ℝ)/2 := by + have ht := mul_le_mul_of_nonneg_right hε ha.le + dsimp [δ,T,U] + linarith + have hmin : (A.card : ℝ)/2 ≤ min (U.card : ℝ) (Uᶜ.card : ℝ) := by + apply le_min + · have ht : (A.card : ℝ) ≤ (T.card : ℝ) + δ := by + dsimp [δ] + exact_mod_cast card_le_add_symmDiff A T + have hTU : (T.card : ℝ) ≤ U.card := by + exact_mod_cast Finset.card_le_card (Finset.inter_subset_left : T ⊆ U) + linarith + · have ht : ((W \ A).card : ℝ) ≤ ((W \ T).card : ℝ) + δ := by + dsimp [δ] + exact_mod_cast sdiff_card_le_add_symmDiff W A T + have hs : W \ T ⊆ Uᶜ := by + intro v hv + obtain ⟨hvW,hvT⟩ := Finset.mem_sdiff.mp hv + apply Finset.mem_compl.mpr + intro hvU + exact hvT (Finset.mem_inter.mpr ⟨hvU,hvW⟩) + have hh' : ((W \ T).card : ℝ) ≤ Uᶜ.card := by exact_mod_cast Finset.card_le_card hs + linarith + have hsbound : (S.card : ℝ) ≤ 4*Fintype.card V*M/h := by + apply hSc.trans + have hac : (A.card : ℝ) ≤ Fintype.card V := by exact_mod_cast Finset.card_le_univ A + gcongr + have hw := hwitness S hsbound (by dsimp [U] at hmin; linarith) + have he := hexp U + have hlo : p^2*h*A.card/8 ≤ ((P.interedges T (W \ T)).card : ℝ) := by + have hm := mul_le_mul_of_nonneg_left hmin hh.le + have ht := mul_le_mul_of_nonneg_left (hm.trans he) (by positivity : 0 ≤ p^2/4) + change p^2/4 * ((P.interedges U Uᶜ).card : ℝ) ≤ _ at hw + nlinarith + have hupper : ((P.interedges T (W \ T)).card : ℝ) ≤ + ((P.interedges A (W \ A)).card : ℝ) + Fintype.card V * δ := by + dsimp [δ] + exact_mod_cast cut_perturbation_card P W A T hAW Finset.inter_subset_right + have hd := mul_le_mul_of_nonneg_left hδ (by positivity : 0 ≤ (Fintype.card V : ℝ)) + have hp' := mul_le_mul_of_nonneg_right hperturb ha.le + change (Fintype.card V : ℝ) * δ ≤ _ at hd + nlinarith + intro A hAW + by_cases hs : (A.card : ℝ) ≤ (W \ A).card + · rw [min_eq_left hs] + exact hsmall A hAW hs + · have hs' : ((W \ A).card : ℝ) ≤ A.card := (lt_of_not_ge hs).le + rw [min_eq_right hs'] + have heq : W \ (W \ A) = A := Finset.sdiff_sdiff_eq_self hAW + have ht := hsmall (W \ A) Finset.sdiff_subset (by simpa only [heq] using hs') + rw [heq] at ht + let : Std.Symm P.Adj := P.symm + have hcomm : (P.interedges (W \ A) A).card = (P.interedges A (W \ A)).card := + Rel.card_interedges_comm (W \ A) A + rwa [hcomm] at ht + +lemma cutExpansion_minDegree (P : SimpleGraph V) [DecidableRel P.Adj] + {h : ℝ} (hexp : CutExpansion P h) (hr : 2 ≤ Fintype.card V) (v : V) : + h ≤ ((neighborsIn P v Finset.univ).card : ℝ) := by + have ht := hexp {v} + have hc : (1 : ℝ) ≤ ((({v} : Finset V)ᶜ).card : ℝ) := by + have : 1 ≤ (({v} : Finset V)ᶜ).card := by + rw [Finset.card_compl, Finset.card_singleton] + omega + exact_mod_cast this + simp only [Finset.card_singleton, Nat.cast_one, min_eq_left hc, mul_one] at ht + rw [card_interedges_eq_sum_neighborsIn, Finset.sum_singleton] at ht + have heq : neighborsIn P v ({v} : Finset V)ᶜ = neighborsIn P v Finset.univ := by + ext x + simp only [neighborsIn, Finset.mem_filter, Finset.mem_compl, Finset.mem_singleton, + Finset.mem_univ, true_and] + exact ⟨fun h => h.2, fun h => ⟨fun he => P.irrefl (he ▸ h), h⟩⟩ + rwa [heq] at ht + +lemma sample_neighbors_lower_tail (P : SimpleGraph V) [DecidableRel P.Adj] + (p : unitInterval) {h : ℝ} (hdeg : ∀ v, h ≤ ((neighborsIn P v Finset.univ).card : ℝ)) + (v : V) : + (sampleMeasure V p).real {ω | ((neighborsIn P v (sampleVertices ω)).card : ℝ) < (p : ℝ)*h/2} ≤ + exp (-(p : ℝ)*h/8) := by + have heq (ω : V → Bool) : neighborsIn P v (sampleVertices ω) = + neighborsIn P v Finset.univ ∩ sampleVertices ω := by + ext x; simp [neighborsIn, and_comm] + simp_rw [heq] + have hs : {ω | (((neighborsIn P v Finset.univ) ∩ sampleVertices ω).card : ℝ) < (p : ℝ)*h/2} ⊆ + {ω | (((neighborsIn P v Finset.univ) ∩ sampleVertices ω).card : ℝ) ≤ + (p : ℝ)*(neighborsIn P v Finset.univ).card/2} := by + intro ω hω + change (((neighborsIn P v Finset.univ) ∩ sampleVertices ω).card : ℝ) < (p : ℝ)*h/2 at hω + exact hω.le.trans (div_le_div_of_nonneg_right + (mul_le_mul_of_nonneg_left (hdeg v) p.property.1) (by norm_num)) + have he : -(p : ℝ)*(neighborsIn P v Finset.univ).card/8 ≤ -(p : ℝ)*h/8 := by + have ht := mul_le_mul_of_nonneg_left (hdeg v) p.property.1 + linarith + exact (measureReal_mono hs (measure_ne_top _ _)).trans + ((sample_card_lower_tail p _).trans (exp_le_exp.mpr he)) + +lemma card_small_subsets_le (s : ℕ) (hr : 0 < Fintype.card V) : + (((Finset.univ : Finset V).powerset).filter (fun S => S.card ≤ s)).card ≤ + (s+1) * Fintype.card V ^ s := by + classical + have heq : (((Finset.univ : Finset V).powerset).filter (fun S => S.card ≤ s)) = + (Finset.range (s+1)).biUnion (fun t => (Finset.univ : Finset V).powersetCard t) := by + ext S + simp only [Finset.mem_filter, Finset.mem_powerset, Finset.subset_univ, true_and, + Finset.mem_biUnion, Finset.mem_range, Finset.mem_powersetCard] + exact ⟨fun h => ⟨S.card, by omega, rfl⟩, + fun ⟨t,ht,he⟩ => by omega⟩ + rw [heq] + calc + _ ≤ ∑ t ∈ Finset.range (s+1), ((Finset.univ : Finset V).powersetCard t).card := + Finset.card_biUnion_le + _ ≤ ∑ t ∈ Finset.range (s+1), Fintype.card V ^ s := by + apply Finset.sum_le_sum + intro t ht + rw [Finset.card_powersetCard, Finset.card_univ] + exact (Nat.choose_le_pow _ _).trans (Nat.pow_le_pow_right hr (by simpa using ht)) + _ = _ := by simp [mul_comm] + +def witnessFamily (P : SimpleGraph V) [DecidableRel P.Adj] (s : ℕ) : Finset (Finset V) := + ((((Finset.univ : Finset V).powerset).filter (fun S => S.card ≤ s))).image (neighborhoodUnion P) + +lemma card_witnessFamily_le (P : SimpleGraph V) [DecidableRel P.Adj] + (s : ℕ) (hr : 0 < Fintype.card V) : + (witnessFamily P s).card ≤ (s+1) * Fintype.card V ^ s := + Finset.card_image_le.trans (card_small_subsets_le s hr) + +lemma sampled_witness_cut_lower_tail (P : SimpleGraph V) [DecidableRel P.Adj] + (p : unitInterval) {h : ℝ} (hh : 0 ≤ h) (hexp : CutExpansion P h) + (hr : 0 < Fintype.card V) (U : Finset V) + (hU : (p : ℝ)*h/8 ≤ min (U.card : ℝ) (Uᶜ.card : ℝ)) : + (sampleMeasure V p).real {ω | + ((P.interedges (U ∩ sampleVertices ω) (sampleVertices ω \ (U ∩ sampleVertices ω))).card : ℝ) < + (p : ℝ)^2/4 * (P.interedges U Uᶜ).card} ≤ + 2 * (Fintype.card V : ℝ) * exp (-(p : ℝ)^3*h^2/(256*Fintype.card V)) := by + have hAB : Disjoint U Uᶜ := Finset.disjoint_left.mpr (fun _ hx hy => (Finset.mem_compl.mp hy) hx) + have heq (ω : V → Bool) : + P.interedges (U ∩ sampleVertices ω) (sampleVertices ω \ (U ∩ sampleVertices ω)) = + (P.interedges U Uᶜ).filter (fun e => e.1 ∈ sampleVertices ω ∧ e.2 ∈ sampleVertices ω) := by + ext ⟨x,y⟩ + simp only [SimpleGraph.mem_interedges_iff, Finset.mem_inter, Finset.mem_sdiff, + Finset.mem_filter, Finset.mem_compl] + aesop + have ht := sampled_bipartite_cut_lower_tail p hr U Uᶜ hAB (P.interedges U Uᶜ) + (fun e he => ⟨(P.mem_interedges_iff.mp he).1, (P.mem_interedges_iff.mp he).2.1⟩) + have hl : (p : ℝ)*h^2/8 ≤ ((P.interedges U Uᶜ).card : ℝ) := by + have ht := mul_le_mul_of_nonneg_left hU hh + have hu := hexp U + nlinarith + have he : -(p : ℝ)^2 * (P.interedges U Uᶜ).card/(32*Fintype.card V) ≤ + -(p : ℝ)^3*h^2/(256*Fintype.card V) := by + have hrR : 0 < (Fintype.card V : ℝ) := by exact_mod_cast hr + apply (div_le_div_iff₀ (by positivity) (by positivity)).mpr + have hs := mul_le_mul_of_nonneg_left hl (by positivity : 0 ≤ (p : ℝ)^2) + nlinarith + simp_rw [heq] + have hc : (p : ℝ)^2/4 * (P.interedges U Uᶜ).card = (p : ℝ)^2 * (P.interedges U Uᶜ).card/4 := by ring + rw [hc] + exact ht.trans (mul_le_mul_of_nonneg_left (exp_le_exp.mpr he) (by positivity)) + +def SampleGood (P : SimpleGraph V) [DecidableRel P.Adj] (p h τ : ℝ) (ω : V → Bool) : Prop := + ((sampleVertices ω).card : ℝ) ≤ 2*p*Fintype.card V ∧ + (∀ v, p*h/2 ≤ ((neighborsIn P v (sampleVertices ω)).card : ℝ)) ∧ + CutExpansionOn P (sampleVertices ω) τ + +theorem vertex_sampling_failure_bound (P : SimpleGraph V) [DecidableRel P.Adj] + (p : unitInterval) {h τ M : ℝ} (hp : 0 < (p : ℝ)) (hh : 0 < h) (hτ0 : 0 < τ) + (hτ : τ < (p : ℝ)*h/4) (hM : 0 < M) (hMh : M ≤ h) + (hr : 2 ≤ Fintype.card V) + (hmiss : (Fintype.card V : ℝ) * exp (-(p : ℝ)*M/4) < 1/2) + (hε : 4*τ/((p : ℝ)*h) + 4*τ*M/h ≤ 1/2) + (hperturb : τ + Fintype.card V * (4*τ/((p : ℝ)*h) + 4*τ*M/h) ≤ (p : ℝ)^2*h/8) + (hexp : CutExpansion P h) : + (sampleMeasure V p).real {ω | ¬SampleGood P (p : ℝ) h τ ω} ≤ + exp (-(p : ℝ)*Fintype.card V/3) + + Fintype.card V * exp (-(p : ℝ)*h/8) + + 2*Fintype.card V * ((⌈4*Fintype.card V*M/h⌉₊+1 : ℕ) : ℝ) * + (Fintype.card V : ℝ)^⌈4*Fintype.card V*M/h⌉₊ * + exp (-(p : ℝ)^3*h^2/(256*Fintype.card V)) := by + classical + let μ := sampleMeasure V p + let s := ⌈4*(Fintype.card V : ℝ)*M/h⌉₊ + let large := (witnessFamily P s).filter + (fun U => (p : ℝ)*h/8 ≤ min (U.card : ℝ) (Uᶜ.card : ℝ)) + let B₀ : Set (V → Bool) := {ω | 2*(p : ℝ)*Fintype.card V < ((sampleVertices ω).card : ℝ)} + let B₁ (v : V) : Set (V → Bool) := + {ω | ((neighborsIn P v (sampleVertices ω)).card : ℝ) < (p : ℝ)*h/2} + let B₂ (U : Finset V) : Set (V → Bool) := {ω | + ((P.interedges (U ∩ sampleVertices ω) (sampleVertices ω \ (U ∩ sampleVertices ω))).card : ℝ) < + (p : ℝ)^2/4 * (P.interedges U Uᶜ).card} + have h₀ : μ.real B₀ ≤ exp (-(p : ℝ)*Fintype.card V/3) := by + have hs : B₀ ⊆ {ω | 2*(p : ℝ)*Fintype.card V ≤ ((sampleVertices ω).card : ℝ)} := by + intro ω hω + change 2*(p : ℝ)*Fintype.card V < ((sampleVertices ω).card : ℝ) at hω + exact hω.le + have ht := sample_card_upper_tail p (Finset.univ : Finset V) + simp only [Finset.card_univ, Finset.univ_inter] at ht + exact (measureReal_mono hs (measure_ne_top _ _)).trans ht + have h₁ : μ.real (⋃ v ∈ (Finset.univ : Finset V), B₁ v) ≤ + Fintype.card V * exp (-(p : ℝ)*h/8) := by + calc + _ ≤ ∑ v : V, μ.real (B₁ v) := measureReal_biUnion_finset_le _ _ + _ ≤ ∑ _v : V, exp (-(p : ℝ)*h/8) := Finset.sum_le_sum (fun v _ => + sample_neighbors_lower_tail P p (cutExpansion_minDegree P hexp hr) v) + _ = _ := by simp + have h₂ : μ.real (⋃ U ∈ large, B₂ U) ≤ + 2*Fintype.card V * ((s+1 : ℕ) : ℝ) * (Fintype.card V : ℝ)^s * + exp (-(p : ℝ)^3*h^2/(256*Fintype.card V)) := by + calc + _ ≤ ∑ U ∈ large, μ.real (B₂ U) := measureReal_biUnion_finset_le _ _ + _ ≤ ∑ _U ∈ large, 2*(Fintype.card V : ℝ)*exp (-(p : ℝ)^3*h^2/(256*Fintype.card V)) := by + apply Finset.sum_le_sum + intro U hU + exact sampled_witness_cut_lower_tail P p hh.le hexp (by omega) U (Finset.mem_filter.mp hU).2 + _ = (large.card : ℝ) * (2*Fintype.card V * exp (-(p : ℝ)^3*h^2/(256*Fintype.card V))) := by simp + _ ≤ (((s+1 : ℕ) : ℝ) * (Fintype.card V : ℝ)^s) * + (2*Fintype.card V * exp (-(p : ℝ)^3*h^2/(256*Fintype.card V))) := by + apply mul_le_mul_of_nonneg_right _ (by positivity) + have ht : large.card ≤ (s+1)*Fintype.card V^s := + (Finset.card_le_card (Finset.filter_subset _ _)).trans + (card_witnessFamily_le P s (by omega)) + exact_mod_cast ht + _ = _ := by ring + have hcover : {ω | ¬SampleGood P (p : ℝ) h τ ω} ⊆ + (B₀ ∪ (⋃ v ∈ (Finset.univ : Finset V), B₁ v)) ∪ (⋃ U ∈ large, B₂ U) := by + intro ω hω + by_contra hn + have hn₀ : ω ∉ B₀ := fun h => hn (Or.inl (Or.inl h)) + have hn₁ (v : V) : ω ∉ B₁ v := fun h => hn (Or.inl (Or.inr + (Set.mem_iUnion.mpr ⟨v, Set.mem_iUnion.mpr ⟨Finset.mem_univ _, h⟩⟩))) + have hn₂ (U : Finset V) (hU : U ∈ large) : ω ∉ B₂ U := fun h => hn (Or.inr + (Set.mem_iUnion.mpr ⟨U, Set.mem_iUnion.mpr ⟨hU,h⟩⟩)) + apply hω + have hd (v : V) : (p : ℝ)*h/2 ≤ ((neighborsIn P v (sampleVertices ω)).card : ℝ) := + le_of_not_gt (hn₁ v) + refine ⟨le_of_not_gt hn₀, hd, ?_⟩ + apply cutExpansionOn_of_witnesses P (sampleVertices ω) hp hh hτ0 hτ hM hMh + hmiss hε hperturb hexp hd + intro S hS + dsimp only + intro hU + let U := neighborhoodUnion P S + have hSc : S.card ≤ s := by + have ht := hS.trans (Nat.le_ceil (4*(Fintype.card V : ℝ)*M/h)) + dsimp [s] + exact_mod_cast ht + have hmem : U ∈ large := by + apply Finset.mem_filter.mpr + refine ⟨?_, hU⟩ + apply Finset.mem_image.mpr + exact ⟨S, Finset.mem_filter.mpr ⟨Finset.mem_powerset.mpr (Finset.subset_univ _), hSc⟩, rfl⟩ + exact le_of_not_gt (hn₂ U hmem) + calc + _ ≤ μ.real ((B₀ ∪ (⋃ v ∈ (Finset.univ : Finset V), B₁ v)) ∪ (⋃ U ∈ large, B₂ U)) := + measureReal_mono hcover (measure_ne_top _ _) + _ ≤ μ.real (B₀ ∪ (⋃ v ∈ (Finset.univ : Finset V), B₁ v)) + μ.real (⋃ U ∈ large, B₂ U) := + measureReal_union_le _ _ + _ ≤ μ.real B₀ + μ.real (⋃ v ∈ (Finset.univ : Finset V), B₁ v) + μ.real (⋃ U ∈ large, B₂ U) := + add_le_add (measureReal_union_le _ _) le_rfl + _ ≤ _ := add_le_add (add_le_add h₀ h₁) h₂ + +end ErdosGallai.Sampling + +end + +end OAI diff --git a/lean/OAI/Combinatorics/CycleDecomposition/ScaleDecomposition.lean b/lean/OAI/Combinatorics/CycleDecomposition/ScaleDecomposition.lean new file mode 100644 index 0000000000000000000000000000000000000000..68f4795ea18eec026215e1c7f9d3a25b4d5da87f --- /dev/null +++ b/lean/OAI/Combinatorics/CycleDecomposition/ScaleDecomposition.lean @@ -0,0 +1,632 @@ +import OAI.Combinatorics.CycleDecomposition.ScaleHierarchy + +namespace OAI + +universe cycleUniverse1 cycleUniverse2 cycleUniverse3 + +section +open Filter Asymptotics Real +open scoped Topology +noncomputable section +open MeasureTheory ProbabilityTheory Finset +section +namespace ErdosGallai.Scale +noncomputable section +open Finset SimpleGraph Real +attribute [local instance] Classical.propDecidable +variable {V : Type} [Fintype V] [DecidableEq V] + +def graphUnion (L : List (SimpleGraph V)) : SimpleGraph V := L.foldr (· ⊔ ·) ⊥ + +@[simp] lemma graphUnion_nil {V : Type} [_contextInstance1 : Fintype V] [_contextInstance2 : DecidableEq V] : graphUnion ([] : List (SimpleGraph V)) = ⊥ := rfl +@[simp] lemma graphUnion_cons {V : Type} [_contextInstance1 : Fintype V] [_contextInstance2 : DecidableEq V] (G : SimpleGraph V) (L) : graphUnion (G::L) = G ⊔ graphUnion L := rfl +lemma graphUnion_adj {V : Type} [_contextInstance1 : Fintype V] [_contextInstance2 : DecidableEq V] (L : List (SimpleGraph V)) (x y : V) : + (graphUnion L).Adj x y ↔ ∃ G ∈ L, G.Adj x y := by + induction L with + | nil => simp + | cons G L ih => simp only [graphUnion_cons,SimpleGraph.sup_adj,ih,List.mem_cons]; aesop + +lemma edgeOccurrences_pos (L : List (SimpleGraph V)) (x y : V) : + 0 < edgeOccurrences L x y ↔ (graphUnion L).Adj x y := by + simp [edgeOccurrences,List.countP_pos_iff,graphUnion_adj] + +lemma graphPartition_union {G : SimpleGraph V} {L : List (SimpleGraph V)} + (h : GraphPartition G L) : graphUnion L = G := by + ext x y + rw [← edgeOccurrences_pos,h x y] + split_ifs <;> simp_all + +lemma graphPartition_of_le_one (L : List (SimpleGraph V)) + (h : ∀ x y, edgeOccurrences L x y ≤ 1) : GraphPartition (graphUnion L) L := by + intro x y + have hh := h x y + rw [← edgeOccurrences_pos] + split_ifs <;> omega + +lemma edgeOccurrences_sublist {V : Type} [_contextInstance1 : Fintype V] [_contextInstance2 : DecidableEq V] {L M : List (SimpleGraph V)} (h : L.Sublist M) (x y : V) : + edgeOccurrences L x y ≤ edgeOccurrences M x y := by + exact List.Sublist.countP_le h + +lemma graphPartition_sublist {G : SimpleGraph V} {L M : List (SimpleGraph V)} + (hp : GraphPartition G M) (h : L.Sublist M) : GraphPartition (graphUnion L) L := by + apply graphPartition_of_le_one + intro x y + have hh := edgeOccurrences_sublist h x y + rw [hp x y] at hh + split_ifs at hh <;> omega + +lemma graphUnion_sublist {L M : List (SimpleGraph V)} (h : L.Sublist M) : graphUnion L ≤ graphUnion M := by + intro x y hxy + obtain ⟨G,hG,hxy⟩ := (graphUnion_adj _ _ _).mp hxy + exact (graphUnion_adj _ _ _).mpr ⟨G,h.subset hG,hxy⟩ + +lemma graphUnion_append (L M : List (SimpleGraph V)) : graphUnion (L++M) = graphUnion L ⊔ graphUnion M := by + ext x y + simp only [graphUnion_adj,List.mem_append,SimpleGraph.sup_adj] + aesop + +lemma edgeOccurrences_perm {V : Type} [_contextInstance1 : Fintype V] [_contextInstance2 : DecidableEq V] {L M : List (SimpleGraph V)} (h : L.Perm M) (x y : V) : + edgeOccurrences L x y = edgeOccurrences M x y := List.Perm.countP_eq _ h + +lemma graphPartition_perm {G : SimpleGraph V} {L M : List (SimpleGraph V)} + (h : GraphPartition G L) (hp : L.Perm M) : GraphPartition G M := by + intro x y + rw [← edgeOccurrences_perm hp] + exact h x y + +lemma graphUnion_supported (L : List (AssignedPiece V)) (A : Finset V) + (h : ∀ P ∈ L, P.vertices ⊆ A) : SupportedOn (graphUnion (L.map AssignedPiece.graph)) A := by + intro x y hxy + obtain ⟨G,hG,hxy⟩ := (graphUnion_adj _ _ _).mp hxy + obtain ⟨P,hP,rfl⟩ := List.mem_map.mp hG + exact ⟨h P hP (P.supported hxy).1,h P hP (P.supported hxy).2⟩ + +lemma edgeCount_union_le (L : List (SimpleGraph V)) : + edgeCount (graphUnion L) ≤ (L.map edgeCount).sum := by + induction L with + | nil => simp + | cons G L ih => + simp only [graphUnion_cons,List.map_cons,List.sum_cons] + exact (edgeCount_sup_le G (graphUnion L)).trans (Nat.add_le_add_left ih _) + +def levelCycles (s : SplitSystem V) (j : ℕ) (L : List (AssignedPiece V)) : List (SimpleGraph V) := + L.flatMap fun P => (s j P).cycles + +def levelPieces (s : SplitSystem V) (j : ℕ) (L : List (AssignedPiece V)) : List (AssignedPiece V) := + L.flatMap fun P => (s j P).boxes.flatMap (s j P).pieces + +lemma StageSplit.ledger {P : AssignedPiece V} (s : StageSplit P) (x y : V) : + edgeOccurrences (s.cycles ++ (s.boxes.flatMap s.pieces).map AssignedPiece.graph ++ + s.children.map AssignedPiece.graph) x y = if P.graph.Adj x y then 1 else 0 := by + have h := s.partition x y + rw [edgeOccurrences_append] at h + rw [← edgeOccurrences_refine s.boxes AssignedPiece.graph + (fun B => s.remainder B :: (s.pieces B).map AssignedPiece.graph) s.box_partition] at h + have he : edgeOccurrences (s.boxes.flatMap (fun B => s.remainder B :: + (s.pieces B).map AssignedPiece.graph)) x y = + edgeOccurrences ((s.boxes.flatMap s.pieces).map AssignedPiece.graph) x y + + edgeOccurrences (s.children.map AssignedPiece.graph) x y := by + rw [s.children_map (fun _ G => G)] + induction s.boxes with + | nil => simp + | cons B L ih => + simp only [List.flatMap_cons,List.map_append,List.map_cons,edgeOccurrences_append, + edgeOccurrences_cons] at * + omega + rw [he] at h + simpa only [edgeOccurrences_append,Nat.add_assoc] using h + +lemma level_ledger (s : SplitSystem V) (j) (L : List (AssignedPiece V)) (x y : V) : + edgeOccurrences (levelCycles s j L ++ (levelPieces s j L).map AssignedPiece.graph ++ + (nextLayer s j L).map AssignedPiece.graph) x y = edgeOccurrences (L.map AssignedPiece.graph) x y := by + induction L with + | nil => simp [levelCycles,levelPieces,nextLayer] + | cons P L ih => + have hp := (s j P).ledger x y + simp only [levelCycles,levelPieces,nextLayer,List.flatMap_cons,List.map_append, + List.map_cons,edgeOccurrences_append,edgeOccurrences_cons] at ih hp ⊢ + omega + +def pastCycles (s : SplitSystem V) (j : ℕ) : ℕ → List (AssignedPiece V) → List (SimpleGraph V) + | 0,_ => [] + | k+1,L => pastCycles s j k L ++ levelCycles s (j+k) (advance s j k L) + +def pastPieces (s : SplitSystem V) (j : ℕ) : ℕ → List (AssignedPiece V) → List (AssignedPiece V) + | 0,_ => [] + | k+1,L => pastPieces s j k L ++ levelPieces s (j+k) (advance s j k L) + +lemma past_ledger (s : SplitSystem V) (j k) (L : List (AssignedPiece V)) (x y : V) : + edgeOccurrences (pastCycles s j k L ++ (pastPieces s j k L).map AssignedPiece.graph ++ + (advance s j k L).map AssignedPiece.graph) x y = edgeOccurrences (L.map AssignedPiece.graph) x y := by + induction k with + | zero => simp [pastCycles,pastPieces] + | succ k ih => + have h := level_ledger s (j+k) (advance s j k L) x y + simp only [pastCycles,pastPieces,advance_succ,List.map_append,edgeOccurrences_append] at ih h ⊢ + omega + +lemma past_partition (s : SplitSystem V) (j k) (P : AssignedPiece V) : + GraphPartition P.graph (pastCycles s j k [P] ++ (pastPieces s j k [P]).map AssignedPiece.graph ++ + (advance s j k [P]).map AssignedPiece.graph) := by + intro x y + rw [past_ledger] + simp + +lemma levelCycles_good (s : SplitSystem V) (j) (L : List (AssignedPiece V)) : + ∀ G ∈ levelCycles s j L, IsCycleGraph G := by + intro G hG + obtain ⟨P,_,hG⟩ := List.mem_flatMap.mp hG + exact (s j P).cycles_good G hG + +lemma pastCycles_good (s : SplitSystem V) (j k) (L : List (AssignedPiece V)) : + ∀ G ∈ pastCycles s j k L, IsCycleGraph G := by + induction k with + | zero => simp [pastCycles] + | succ k ih => + intro G hG + rcases List.mem_append.mp hG with h | h + · exact ih G h + · exact levelCycles_good s (j+k) _ G h + +lemma levelPieces_subset (s : SplitSystem V) (j) (L : List (AssignedPiece V)) (A : Finset V) + (hL : ∀ P ∈ L, P.vertices ⊆ A) : ∀ Q ∈ levelPieces s j L, Q.vertices ⊆ A := by + intro Q hQ + obtain ⟨P,hP,B,hB,hQ⟩ := (by simpa [levelPieces,List.mem_flatMap] using hQ : + ∃ P ∈ L, ∃ B ∈ (s j P).boxes, Q ∈ (s j P).pieces B) + exact ((s j P).piece_subset B hB Q hQ).trans (((s j P).box_subset B hB).trans (hL P hP)) + +lemma levelPieces_mass (s : SplitSystem V) (j) (L : List (AssignedPiece V)) : + vertexMass (levelPieces s j L) ≤ vertexMass (nextLayer s j L) := by + induction L with + | nil => simp [levelPieces,nextLayer] + | cons P L ih => + have hs : vertexMass ((s j P).boxes.flatMap (s j P).pieces) ≤ vertexMass (s j P).boxes := by + rw [vertexMass_flatMap] + unfold vertexMass + exact List.sum_le_sum (fun B hB => (s j P).pieces_mass hB) + simp only [levelPieces,nextLayer,List.flatMap_cons,vertexMass_append, + StageSplit.children_mass] at ih ⊢ + linarith + +lemma levelCycles_length (s : SplitSystem V) (j) (L : List (AssignedPiece V)) (D : ℝ) + (hb : ∀ P ∈ L, (s j P).Bounded D) : + ((levelCycles s j L).length:ℝ) ≤ vertexMass L / (2*D^(1/100:ℝ)) := by + induction L with + | nil => simp [levelCycles] + | cons P L ih => + have hp := (hb P (by simp)).1 + have hl := ih (fun Q hQ => hb Q (by simp [hQ])) + simp only [levelCycles,List.flatMap_cons,List.length_append,Nat.cast_add,vertexMass_cons] + rw [add_div] + exact add_le_add hp hl + +lemma pastPieces_mass (s : SplitSystem V) (j k) (L : List (AssignedPiece V)) : + vertexMass (pastPieces s j k L) = ∑ l ∈ Finset.range k, + vertexMass (levelPieces s (j+l) (advance s j l L)) := by + induction k with + | zero => simp [pastPieces] + | succ k ih => simp [pastPieces,ih,Finset.sum_range_succ] + +lemma pastCycles_length (s : SplitSystem V) (j k) (L : List (AssignedPiece V)) : + ((pastCycles s j k L).length:ℝ) = ∑ l ∈ Finset.range k, + ((levelCycles s (j+l) (advance s j l L)).length:ℝ) := by + induction k with + | zero => simp [pastCycles] + | succ k ih => simp [pastCycles,ih,Finset.sum_range_succ] + +end +end ErdosGallai.Scale + +namespace ErdosGallai.Scale + +def CycleOrSingleEdge {V : Type} (G : SimpleGraph V) + (s : Set (Sym2 V)) : Prop := + (∃ (v : V) (p : G.Walk v v), p.IsCycle ∧ s = p.edgeSet) ∨ + ∃ e ∈ G.edgeSet, s = {e} + +def EdgeDecomposition {V : Type} (G : SimpleGraph V) (k : ℕ) : Prop := + ∃ parts : Fin k → Set (Sym2 V), + (∀ i, CycleOrSingleEdge G (parts i)) ∧ + Pairwise (fun i j => Disjoint (parts i) (parts j)) ∧ + (⋃ i, parts i) = G.edgeSet + +noncomputable section +open SimpleGraph + +lemma cycleOrSingleEdge_subset {V : Type} {G : SimpleGraph V} + {s : Set (Sym2 V)} (hs : CycleOrSingleEdge G s) : s ⊆ G.edgeSet := by + rcases hs with ⟨v,p,hp,rfl⟩ | ⟨e,he,rfl⟩ + · exact p.edges_subset_edgeSet + · simpa using he + +lemma cycleOrSingleEdge_map {V W : Type} {G : SimpleGraph V} {H : SimpleGraph W} + (f : G →g H) (hf : Function.Injective f) {s : Set (Sym2 V)} + (hs : CycleOrSingleEdge G s) : CycleOrSingleEdge H (Sym2.map f '' s) := by + rcases hs with ⟨v,p,hp,rfl⟩ | ⟨e,he,rfl⟩ + · exact Or.inl ⟨f v,p.map f,hp.map hf,(p.edgeSet_map f).symm⟩ + · refine Or.inr ⟨Sym2.map f e, ?_, by simp⟩ + induction e using Sym2.ind with | _ x y => + exact f.map_adj he + +lemma edgeDecomposition_of_indexed {V I : Type} [Fintype I] (G : SimpleGraph V) + (parts : I → Set (Sym2 V)) (hp : ∀ i, CycleOrSingleEdge G (parts i)) + (hd : Pairwise (fun i j => Disjoint (parts i) (parts j))) + (hu : (⋃ i, parts i) = G.edgeSet) : EdgeDecomposition G (Fintype.card I) := by + let e := Fintype.equivFin I + refine ⟨fun j => parts (e.symm j), fun j => hp _, ?_, ?_⟩ + · intro i j hij + exact hd (fun he => hij (e.symm.injective he)) + · ext x + simp only [Set.mem_iUnion] + rw [← hu] + simp only [Set.mem_iUnion] + constructor + · rintro ⟨i,hi⟩; exact ⟨e.symm i,hi⟩ + · rintro ⟨i,hi⟩; exact ⟨e i, by simpa using hi⟩ + +theorem edgeDecomposition_singleEdges {V : Type} [Fintype V] (G : SimpleGraph V) : + EdgeDecomposition G (Nat.card G.edgeSet) := by + classical + let : Fintype G.edgeSet := Fintype.ofFinite _ + rw [Nat.card_eq_fintype_card] + apply edgeDecomposition_of_indexed G (fun e : G.edgeSet => {e.1}) + · intro e; exact Or.inr ⟨e.1,e.2,rfl⟩ + · intro e d hed + exact Set.disjoint_singleton.mpr (fun h => hed (Subtype.ext h)) + · ext e; simp + +theorem edgeDecomposition_assemble {V I : Type} [Fintype I] (G : SimpleGraph V) + (W : I → Type) (H : ∀ i, SimpleGraph (W i)) + (f : ∀ i, H i →g G) (hf : ∀ i, Function.Injective (f i)) + (hdisj : Pairwise (fun i j => + Disjoint (Sym2.map (f i) '' (H i).edgeSet) (Sym2.map (f j) '' (H j).edgeSet))) + (hcover : (⋃ i, Sym2.map (f i) '' (H i).edgeSet) = G.edgeSet) + (k : I → ℕ) (hparts : ∀ i, EdgeDecomposition (H i) (k i)) : + EdgeDecomposition G (∑ i, k i) := by + classical + choose parts hp hd hu using hparts + let J := Σ i, Fin (k i) + let P : J → Set (Sym2 V) := fun j => Sym2.map (f j.1) '' parts j.1 j.2 + have hpart : ∀ j, CycleOrSingleEdge G (P j) := by + intro j; exact cycleOrSingleEdge_map (f j.1) (hf j.1) (hp j.1 j.2) + have hsub : ∀ i a, parts i a ⊆ (H i).edgeSet := by + intro i a; exact cycleOrSingleEdge_subset (hp i a) + have hdisjP : Pairwise (fun i j => Disjoint (P i) (P j)) := by + rintro ⟨i,a⟩ ⟨j,b⟩ hij + by_cases h : i = j + · subst j + have hab : a ≠ b := fun he => hij (by cases he; rfl) + apply Set.disjoint_left.mpr + rintro e ⟨x,hx,he⟩ ⟨y,hy,he'⟩ + have hxy : x = y := Sym2.map.injective (hf i) (he.trans he'.symm) + subst y + exact Set.disjoint_left.mp (hd i hab) hx hy + · exact (hdisj h).mono (Set.image_mono (hsub i a)) (Set.image_mono (hsub j b)) + have hcoverP : (⋃ j, P j) = G.edgeSet := by + rw [← hcover] + ext e + simp only [Set.mem_iUnion] + constructor + · rintro ⟨⟨i,a⟩,x,hx,he⟩ + exact ⟨i,x,hsub i a hx,he⟩ + · rintro ⟨i,x,hx,he⟩ + rw [← hu i] at hx + obtain ⟨a,ha⟩ := Set.mem_iUnion.mp hx + exact ⟨⟨i,a⟩,x,ha,he⟩ + have hc : Fintype.card J = ∑ i, k i := by simp [J, Fintype.card_sigma] + rw [← hc] + exact edgeDecomposition_of_indexed G P hpart hdisjP hcoverP + +end +end ErdosGallai.Scale + +namespace ErdosGallai.Scale +noncomputable section +open SimpleGraph Finset +attribute [local instance] Classical.propDecidable + +def decompositionCost {V : Type} [Fintype V] (G : SimpleGraph V) : ℕ := + Nat.find (show ∃ k, EdgeDecomposition G k from ⟨_,edgeDecomposition_singleEdges G⟩) + +lemma decompositionCost_spec {V : Type} [Fintype V] (G : SimpleGraph V) : + EdgeDecomposition G (decompositionCost G) := Nat.find_spec _ + +lemma decompositionCost_le {V : Type} [Fintype V] {G : SimpleGraph V} {k : ℕ} + (h : EdgeDecomposition G k) : decompositionCost G ≤ k := Nat.find_min' _ h + +lemma decompositionCost_singleEdges {V : Type} [Fintype V] (G : SimpleGraph V) : + decompositionCost G ≤ Nat.card G.edgeSet := decompositionCost_le (edgeDecomposition_singleEdges G) + +theorem edgeDecomposition_adjoin {V I J : Type} [Fintype I] [Fintype J] + (G : SimpleGraph V) (parts : I → Set (Sym2 V)) + (hp : ∀ i, CycleOrSingleEdge G (parts i)) + (hd : Pairwise fun i j => Disjoint (parts i) (parts j)) + (W : J → Type) (H : ∀ j, SimpleGraph (W j)) (f : ∀ j, H j →g G) + (hf : ∀ j, Function.Injective (f j)) + (hHH : Pairwise fun i j => Disjoint (Sym2.map (f i) '' (H i).edgeSet) + (Sym2.map (f j) '' (H j).edgeSet)) + (hHP : ∀ j i, Disjoint (Sym2.map (f j) '' (H j).edgeSet) (parts i)) + (hu : (⋃ i, parts i) ∪ (⋃ j, Sym2.map (f j) '' (H j).edgeSet) = G.edgeSet) + (k : J → ℕ) (hD : ∀ j, EdgeDecomposition (H j) (k j)) : + EdgeDecomposition G (Fintype.card I + ∑ j, k j) := by + classical + choose P hP hPd hPc using hD + let R : (I ⊕ Σ j, Fin (k j)) → Set (Sym2 V) := + Sum.elim parts (fun z => Sym2.map (f z.1) '' P z.1 z.2) + have hsub : ∀ j i, P j i ⊆ (H j).edgeSet := fun j i => cycleOrSingleEdge_subset (hP j i) + have hRp : ∀ z, CycleOrSingleEdge G (R z) := by + intro z + rcases z with z | ⟨j,i⟩ + · exact hp z + · exact cycleOrSingleEdge_map (f j) (hf j) (hP j i) + have hRd : Pairwise fun z t => Disjoint (R z) (R t) := by + intro z t hzt + rcases z with z | ⟨j,i⟩ <;> rcases t with t | ⟨l,a⟩ + · exact hd (fun h => hzt (congrArg Sum.inl h)) + · exact ((hHP l z).mono_left (Set.image_mono (hsub l a))).symm + · exact (hHP j t).mono_left (Set.image_mono (hsub j i)) + · by_cases hjl : j = l + · subst l + have hia : i ≠ a := fun h => hzt (by cases h; rfl) + apply Set.disjoint_left.mpr + rintro e ⟨x,hx,he⟩ ⟨y,hy,he'⟩ + have hxy := Sym2.map.injective (hf j) (he.trans he'.symm) + subst y + exact Set.disjoint_left.mp (hPd j hia) hx hy + · exact (hHH hjl).mono (Set.image_mono (hsub j i)) (Set.image_mono (hsub l a)) + have hRu : (⋃ z, R z) = G.edgeSet := by + rw [← hu] + ext e + simp only [Set.mem_iUnion, Set.mem_union] + constructor + · rintro ⟨z,hz⟩ + rcases z with z | ⟨j,i⟩ + · exact Or.inl ⟨z,hz⟩ + · obtain ⟨x,hx,he⟩ := hz + exact Or.inr ⟨j,x,hsub j i hx,he⟩ + · rintro (⟨i,hi⟩ | ⟨j,x,hx,he⟩) + · exact ⟨Sum.inl i,hi⟩ + · rw [← hPc j] at hx + obtain ⟨i,hi⟩ := Set.mem_iUnion.mp hx + exact ⟨Sum.inr ⟨j,i⟩,x,hi,he⟩ + simpa only [Fintype.card_sum,Fintype.card_sigma,Fintype.card_fin] using + edgeDecomposition_of_indexed G R hRp hRd hRu + +lemma decompositionCost_adjoin {V I J : Type} [Fintype V] [Fintype I] [Fintype J] + (G : SimpleGraph V) (parts : I → Set (Sym2 V)) + (hp : ∀ i, CycleOrSingleEdge G (parts i)) + (hd : Pairwise fun i j => Disjoint (parts i) (parts j)) + (W : J → Type) [∀ j, Fintype (W j)] (H : ∀ j, SimpleGraph (W j)) + (f : ∀ j, H j →g G) (hf : ∀ j, Function.Injective (f j)) + (hHH : Pairwise fun i j => Disjoint (Sym2.map (f i) '' (H i).edgeSet) + (Sym2.map (f j) '' (H j).edgeSet)) + (hHP : ∀ j i, Disjoint (Sym2.map (f j) '' (H j).edgeSet) (parts i)) + (hu : (⋃ i, parts i) ∪ (⋃ j, Sym2.map (f j) '' (H j).edgeSet) = G.edgeSet) : + decompositionCost G ≤ Fintype.card I + ∑ j, decompositionCost (H j) := + decompositionCost_le (edgeDecomposition_adjoin G parts hp hd W H f hf hHH hHP hu _ + (fun j => decompositionCost_spec (H j))) + +end +end ErdosGallai.Scale +namespace ErdosGallai.Scale +noncomputable section +open SimpleGraph Finset +attribute [local instance] Classical.propDecidable + +lemma edgeDecomposition_map {V W : Type} {G : SimpleGraph V} {H : SimpleGraph W} + (f : H →g G) (hf : Function.Injective f) + (hu : Sym2.map f '' H.edgeSet = G.edgeSet) {k : ℕ} (hk : EdgeDecomposition H k) : + EdgeDecomposition G k := by + have := edgeDecomposition_assemble (I := Unit) G (fun _ : Unit => W) (fun _ => H) (fun _ => f) + (fun _ => hf) (by intro i j hij; exact False.elim (hij (Subsingleton.elim _ _))) + (by rw [Set.iUnion_const]; exact hu) (fun _ => k) (fun _ => hk) + simpa using this + +lemma decompositionCost_on {V : Type} [Fintype V] (G : SimpleGraph V) + (A : Finset V) (hA : ∀ ⦃x y⦄, G.Adj x y → x ∈ A ∧ y ∈ A) : + decompositionCost G ≤ decompositionCost (G.induce (A:Set V)) := by + classical + let f : G.induce (A:Set V) →g G := ⟨Subtype.val,fun h => h⟩ + have hu : Sym2.map f '' (G.induce (A:Set V)).edgeSet = G.edgeSet := by + ext e + constructor + · rintro ⟨e,he,rfl⟩ + induction e using Sym2.ind with | _ x y => exact he + · intro he + induction e using Sym2.ind with + | _ x y => + exact ⟨s(⟨x,(hA he).1⟩,⟨y,(hA he).2⟩),he,rfl⟩ + exact decompositionCost_le (edgeDecomposition_map f Subtype.val_injective hu (decompositionCost_spec _)) + +lemma edgeDecomposition_on {V : Type} (G : SimpleGraph V) + (A : Finset V) (hA : ∀ ⦃x y⦄, G.Adj x y → x ∈ A ∧ y ∈ A) + {k : ℕ} (hk : EdgeDecomposition (G.induce (A:Set V)) k) : EdgeDecomposition G k := by + classical + let f : G.induce (A:Set V) →g G := ⟨Subtype.val,fun h => h⟩ + apply edgeDecomposition_map f Subtype.val_injective _ hk + ext e + constructor + · rintro ⟨e,he,rfl⟩ + induction e using Sym2.ind with | _ x y => exact he + · intro he + induction e using Sym2.ind with + | _ x y => exact ⟨s(⟨x,(hA he).1⟩,⟨y,(hA he).2⟩),he,rfl⟩ + +end +end ErdosGallai.Scale +namespace ErdosGallai.Scale +noncomputable section +open SimpleGraph Finset +attribute [local instance] Classical.propDecidable + +lemma decompositionCost_adjoin_same {V I J : Type} [Fintype V] [Fintype I] [Fintype J] + (G : SimpleGraph V) (parts : I → Set (Sym2 V)) + (hp : ∀ i, CycleOrSingleEdge G (parts i)) + (hd : Pairwise fun i j => Disjoint (parts i) (parts j)) + (H : J → SimpleGraph V) (hHG : ∀ j, H j ≤ G) + (hHH : Pairwise fun i j => Disjoint (H i).edgeSet (H j).edgeSet) + (hHP : ∀ j i, Disjoint (H j).edgeSet (parts i)) + (hu : (⋃ i, parts i) ∪ (⋃ j, (H j).edgeSet) = G.edgeSet) : + decompositionCost G ≤ Fintype.card I + ∑ j, decompositionCost (H j) := by + let f : ∀ j, H j →g G := fun j => ⟨id,fun h => hHG j h⟩ + have he (j) : Sym2.map (f j) '' (H j).edgeSet = (H j).edgeSet := by + have hf : (f j : V → V) = id := rfl + rw [hf, Sym2.map_id, Set.image_id] + apply decompositionCost_adjoin G parts hp hd (fun _ => V) H f (fun _ => Function.injective_id) + · simpa only [he] using hHH + · simpa only [he] using hHP + · simpa only [he] using hu + +lemma decompositionCost_assemble_same {V J : Type} [Fintype V] [Fintype J] + (G : SimpleGraph V) (H : J → SimpleGraph V) (hHG : ∀ j, H j ≤ G) + (hHH : Pairwise fun i j => Disjoint (H i).edgeSet (H j).edgeSet) + (hu : (⋃ j, (H j).edgeSet) = G.edgeSet) : + decompositionCost G ≤ ∑ j, decompositionCost (H j) := by + simpa using decompositionCost_adjoin_same (I := Empty) G Empty.elim (fun i => nomatch i) + (by intro i; exact i.elim) H hHG hHH (fun _ i => nomatch i) (by simpa using hu) + +end +end ErdosGallai.Scale + +namespace ErdosGallai.Scale +noncomputable section +open Finset SimpleGraph +attribute [local instance] Classical.propDecidable +variable {V : Type} [Fintype V] [DecidableEq V] + +lemma list_pairwise_get {A : Type cycleUniverse1} {R : A → A → Prop} {L : List A} + (h : L.Pairwise R) (hs : (∀ ⦃left right⦄, R left right → R right left)) : Pairwise fun i j : Fin L.length => R (L.get i) (L.get j) := by + intro i j hij + rcases lt_or_gt_of_ne (show i.val ≠ j.val from fun he => hij (Fin.ext he)) with hlt | hgt + · exact List.pairwise_iff_getElem.mp h i.val j.val i.isLt j.isLt hlt + · exact hs (List.pairwise_iff_getElem.mp h j.val i.val j.isLt i.isLt hgt) + +lemma list_sum_get {A : Type cycleUniverse2} {M : Type cycleUniverse3} [AddCommMonoid M] (L : List A) (f : A → M) : + (∑ i : Fin L.length, f (L.get i)) = (L.map f).sum := by + rw [← List.sum_ofFn] + calc + _ = (List.map f (List.ofFn L.get)).sum := by rw [List.map_ofFn]; rfl + _ = _ := by rw [List.ofFn_get] + +lemma graphPartition_pairwise {G : SimpleGraph V} {L : List (SimpleGraph V)} + (h : GraphPartition G L) : L.Pairwise fun H K => Disjoint H.edgeSet K.edgeSet := by + induction L generalizing G with + | nil => simp + | cons H L ih => + apply List.pairwise_cons.mpr + refine ⟨?_,ih (graphPartition_sublist h (List.sublist_cons_self _ _))⟩ + intro K hK + apply Set.disjoint_left.mpr + intro e he he' + induction e using Sym2.ind with + | _ x y => + have hc := h x y + have hp : 0 < edgeOccurrences L x y := by + rw [edgeOccurrences_pos,graphUnion_adj] + exact ⟨K,hK,he'⟩ + have hxy : H.Adj x y := he + simp only [edgeOccurrences_cons,hxy,ite_true] at hc + split_ifs at hc <;> omega + +lemma graphUnion_edges (L : List (SimpleGraph V)) : + (⋃ i : Fin L.length, (L.get i).edgeSet) = (graphUnion L).edgeSet := by + ext e + induction e using Sym2.ind with + | _ x y => + simp only [Set.mem_iUnion,SimpleGraph.mem_edgeSet] + + rw [graphUnion_adj] + constructor + · rintro ⟨i,h⟩; exact ⟨_,L.get_mem i,h⟩ + · rintro ⟨H,hH,h⟩ + obtain ⟨i,rfl⟩ := List.mem_iff_get.mp hH + exact ⟨i,h⟩ + +lemma decompositionCost_partition {G : SimpleGraph V} {L : List (SimpleGraph V)} + (h : GraphPartition G L) : decompositionCost G ≤ (L.map decompositionCost).sum := by + rw [← list_sum_get L decompositionCost] + apply decompositionCost_assemble_same G (fun i : Fin L.length => L.get i) + · intro i; exact partition_member_le h (L.get_mem i) + · exact list_pairwise_get (graphPartition_pairwise h) (fun _ _ h => h.symm) + · rw [graphUnion_edges,graphPartition_union h] + +lemma decompositionCost_cycle {V : Type} [_contextInstance1 : Fintype V] [_contextInstance2 : DecidableEq V] {G : SimpleGraph V} (h : IsCycleGraph G) : + decompositionCost G ≤ 1 := by + apply decompositionCost_le + have hp : CycleOrSingleEdge G G.edgeSet := by + obtain ⟨a,p,hp,he⟩ := h + exact Or.inl ⟨a,p,hp,he⟩ + refine ⟨fun _ => G.edgeSet,fun _ => hp,?_,?_⟩ + · intro i j hij; exact False.elim (hij (Subsingleton.elim i j)) + · ext e + simp only [Set.mem_iUnion] + exact ⟨fun ⟨_,h⟩ => h,fun h => ⟨(0 : Fin 1),h⟩⟩ + +lemma decompositionCost_edgeCount {V : Type} [_contextInstance1 : Fintype V] [_contextInstance2 : DecidableEq V] (G : SimpleGraph V) : decompositionCost G ≤ edgeCount G := by + have h := decompositionCost_singleEdges G + rw [Nat.card_eq_fintype_card,SimpleGraph.card_edgeSet] at h + exact h + +lemma decompositionCost_bot : decompositionCost (⊥ : SimpleGraph V) = 0 := by + have h := decompositionCost_edgeCount (⊥ : SimpleGraph V) + simp only [edgeCount_bot] at h + omega + +lemma decompositionCost_partition_real {G : SimpleGraph V} {L : List (SimpleGraph V)} + (h : GraphPartition G L) : (decompositionCost G:ℝ) ≤ + (L.map (fun H => (decompositionCost H:ℝ))).sum := by + have hh : (decompositionCost G:ℝ) ≤ ((L.map decompositionCost).sum:ℕ) := + Nat.cast_le.mpr (decompositionCost_partition h) + simpa [List.map_map,Function.comp_def] using hh + +lemma decompositionCost_cycles (L : List (SimpleGraph V)) + (h : ∀ G ∈ L, IsCycleGraph G) : + (L.map (fun H => (decompositionCost H:ℝ))).sum ≤ L.length := by + calc + _ ≤ (L.map (fun _ => (1:ℝ))).sum := List.sum_le_sum (fun G hG => by exact_mod_cast decompositionCost_cycle (h G hG)) + _ = _ := by simp + +lemma partition_recombine {G : SimpleGraph V} {L M : List (SimpleGraph V)} + (h : GraphPartition G (L++M)) : GraphPartition G (L++[graphUnion M]) := by + have hm := graphPartition_sublist h (List.sublist_append_right L M) + intro x y + have hh := h x y + simp only [edgeOccurrences_append] at hh ⊢ + rw [hm x y] at hh + simpa using hh + +lemma cost_recombine {G : SimpleGraph V} {L M : List (SimpleGraph V)} + (h : GraphPartition G (L++M)) : + (decompositionCost G:ℝ) ≤ (L.map (fun H => (decompositionCost H:ℝ))).sum + + decompositionCost (graphUnion M) := by + simpa using decompositionCost_partition_real (partition_recombine h) + +lemma graphUnion_le_of_members {L : List (SimpleGraph V)} {G : SimpleGraph V} + (h : ∀ H ∈ L, H ≤ G) : graphUnion L ≤ G := by + intro x y hxy + obtain ⟨H,hH,hxy⟩ := (graphUnion_adj _ _ _).mp hxy + exact h H hH hxy + +lemma graphPartition_of_pairwise (L : List (SimpleGraph V)) + (hd : L.Pairwise fun H K => Disjoint H.edgeSet K.edgeSet) : GraphPartition (graphUnion L) L := by + induction L with + | nil => intro x y; simp + | cons G L ih => + obtain ⟨hG,hd⟩ := List.pairwise_cons.mp hd + intro x y + have hi := ih hd x y + have hdis : ¬ (G.Adj x y ∧ (graphUnion L).Adj x y) := by + rintro ⟨hg,hL⟩ + obtain ⟨H,hH,hxy⟩ := (graphUnion_adj _ _ _).mp hL + exact Set.disjoint_left.mp (hG H hH) (show s(x,y) ∈ G.edgeSet from hg) hxy + simp only [edgeOccurrences_cons,hi,graphUnion_cons,SimpleGraph.sup_adj] + by_cases hg : G.Adj x y <;> by_cases hl : (graphUnion L).Adj x y <;> simp_all + +end +end ErdosGallai.Scale + +end +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/CycleDecomposition/ScaleExtraction.lean b/lean/OAI/Combinatorics/CycleDecomposition/ScaleExtraction.lean new file mode 100644 index 0000000000000000000000000000000000000000..6a22e68f47fc0218c32587fd7e6c8f1142e81e4c --- /dev/null +++ b/lean/OAI/Combinatorics/CycleDecomposition/ScaleExtraction.lean @@ -0,0 +1,622 @@ +import OAI.Combinatorics.CycleDecomposition.ExpansionBoxes + +namespace OAI + +universe u + +universe cycleUniverse1 cycleUniverse2 cycleUniverse3 cycleUniverse4 cycleUniverse5 cycleUniverse6 cycleUniverse7 + +section +open Filter Asymptotics Real +open scoped Topology +noncomputable section +open MeasureTheory ProbabilityTheory Finset +section +namespace ErdosGallai.Scale +open Finset SimpleGraph Classical +variable {V : Type cycleUniverse1} [Fintype V] [DecidableEq V] +lemma edgeCount_eq_card {V : Type cycleUniverse2} [_contextInstance1 : Fintype V] [_contextInstance2 : DecidableEq V] (G : SimpleGraph V) (S : Finset (Sym2 V)) + (hS : ∀ e, e ∈ S ↔ e ∈ G.edgeSet) : edgeCount G = S.card := by + unfold edgeCount + congr 1 + ext e + simp only [SimpleGraph.mem_edgeFinset] + exact (hS e).symm + +def IsCycleGraph (K : SimpleGraph V) : Prop := + ∃ a : V, ∃ p : K.Walk a a, p.IsCycle ∧ K.edgeSet = p.edgeSet + +def NoLongCycle (G : SimpleGraph V) (ℓ : ℝ) : Prop := + ∀ a : V, ∀ p : G.Walk a a, p.IsCycle → (p.length : ℝ) < ℓ + +lemma NoLongCycle.mono {V : Type cycleUniverse3} [_contextInstance1 : Fintype V] [_contextInstance2 : DecidableEq V] {G H : SimpleGraph V} {ℓ : ℝ} + (h : NoLongCycle G ℓ) (hle : H ≤ G) : NoLongCycle H ℓ := by + intro a p hp + simpa using h a (p.mapLe hle) (hp.mapLe hle) + +lemma cycle_graph_of_walk (G : SimpleGraph V) {a : V} (p : G.Walk a a) (hp : p.IsCycle) : + ∃ K : SimpleGraph V, K ≤ G ∧ IsCycleGraph K ∧ edgeCount K = p.length := by + classical + let K := SimpleGraph.fromEdgeSet p.edgeSet + have he : K.edgeSet = p.edgeSet := by + rw [SimpleGraph.edgeSet_fromEdgeSet,sdiff_eq_left] + exact Set.disjoint_left.mpr (fun e he hd => + G.not_isDiag_of_mem_edgeSet (p.edges_subset_edgeSet he) hd) + have hle : K ≤ G := SimpleGraph.edgeSet_subset_edgeSet.mp (he ▸ p.edges_subset_edgeSet) + have htransfer : ∀ e ∈ p.edges, e ∈ K.edgeSet := by + intro e he'; rw [he]; exact he' + refine ⟨K,hle,⟨a,p.transfer K htransfer,hp.transfer htransfer,?_⟩,?_⟩ + · simpa using he + · rw [edgeCount_eq_card K p.edges.toFinset (by + intro e; simp only [List.mem_toFinset,he]; rfl)] + exact (List.toFinset_card_of_nodup hp.isTrail.edges_nodup).trans p.length_edges + +lemma edgeCount_sdiff_add {G K : SimpleGraph V} (hle : K ≤ G) : + edgeCount (G \ K) + edgeCount K = edgeCount G := by + classical + rw [edgeCount_eq_card (G \ K) (G.edgeFinset \ K.edgeFinset) (by + intro e; simp only [Finset.mem_sdiff,SimpleGraph.mem_edgeFinset,SimpleGraph.edgeSet_sdiff, + Set.mem_sdiff]), + edgeCount_eq_card K K.edgeFinset (by intro e; simp), + edgeCount_eq_card G G.edgeFinset (by intro e; simp)] + exact Finset.card_sdiff_add_card_eq_card (SimpleGraph.edgeFinset_mono hle) + +lemma edgeCount_cycle_pos {K : SimpleGraph V} (h : IsCycleGraph K) : 0 < edgeCount K := by + classical + obtain ⟨a,p,hp,he⟩ := h + have hf : K.edgeFinset = p.edges.toFinset := by + ext e + simp only [SimpleGraph.mem_edgeFinset,he,List.mem_toFinset] + rfl + simp only [edgeCount,hf,List.toFinset_card_of_nodup hp.isTrail.edges_nodup, + SimpleGraph.Walk.length_edges] + exact hp.three_le_length.trans_lt' (by omega) + +theorem remove_long_cycles (G : SimpleGraph V) (ℓ : ℝ) : + ∃ (H : SimpleGraph V) (L : List (SimpleGraph V)), + H ≤ G ∧ NoLongCycle H ℓ ∧ + (∀ K ∈ L, IsCycleGraph K ∧ ℓ ≤ (edgeCount K : ℝ)) ∧ + GraphPartition G (H::L) ∧ + (L.length : ℝ)*ℓ + edgeCount H ≤ edgeCount G := by + classical + induction hn : edgeCount G using Nat.strong_induction_on generalizing G with + | h n ih => + by_cases hstop : NoLongCycle G ℓ + · refine ⟨G,[],le_rfl,hstop,by simp,?_,?_⟩ + · intro x y; simp + · simp [← hn] + · obtain ⟨a,p,hp,hplen⟩ : ∃ a, ∃ p : G.Walk a a, p.IsCycle ∧ ℓ ≤ (p.length : ℝ) := by + by_contra hh + apply hstop + intro a p hp + by_contra hlen + exact hh ⟨a,p,hp,le_of_not_gt hlen⟩ + obtain ⟨K,hle,hK,hKlen⟩ := cycle_graph_of_walk G p hp + have heq := edgeCount_sdiff_add hle + have hpos := edgeCount_cycle_pos hK + have hlt : edgeCount (G \ K) < n := by omega + obtain ⟨H,L,hH,hNL,hL,hpart,hbudget⟩ := ih _ hlt (G \ K) rfl + refine ⟨H,K::L,hH.trans sdiff_le,hNL,?_,?_,?_⟩ + · intro J hJ + rcases List.mem_cons.mp hJ with rfl | hJ + · exact ⟨hK,by simpa [hKlen] using hplen⟩ + · exact hL J hJ + · intro x y + have hh := @hH x y + have hk := @hle x y + have he := hpart x y + simp only [edgeOccurrences_cons,SimpleGraph.sdiff_adj] at he ⊢ + by_cases hG : G.Adj x y <;> by_cases hK : K.Adj x y <;> + by_cases hH : H.Adj x y <;> simp_all + · have heqR : (edgeCount (G \ K) : ℝ) + edgeCount K = edgeCount G := by exact_mod_cast heq + have hKbound : ℓ ≤ (edgeCount K : ℝ) := by simpa [hKlen] using hplen + simp only [List.length_cons,Nat.cast_add,Nat.cast_one] + rw [← hn] + nlinarith + +open Real Filter Asymptotics + +lemma longCycle_power_margin : ∀ᶠ u : ℝ in atTop, + 4 ≤ u ∧ u^(199/200:ℝ) ≤ ((1/32:ℝ)/(logb 2 u)^2)^2*u/100 := by + have hlog := (isLittleO_log_rpow_rpow_atTop (4:ℝ) + (s:=1/200) (by norm_num)).const_mul_left ((102400:ℝ)/(log 2)^4) + filter_upwards [eventually_ge_atTop (4:ℝ),hlog.eventuallyLE] with u hu hh + have hu0 : 0 < u := by linarith + have hln : 0 ≤ log u := log_nonneg (by linarith) + have hln2 : 0 < log 2 := log_pos (by norm_num) + have hLu : 0 < logb 2 u := logb_pos (by norm_num) (by linarith) + have hr0 : 0 ≤ u^(1/200:ℝ) := rpow_nonneg hu0.le _ + have hnum0 : 0 ≤ (102400:ℝ)/(log 2)^4 * (log u)^(4:ℝ) := by positivity + simp only [Real.norm_eq_abs,abs_of_nonneg hnum0,abs_of_nonneg hr0] at hh + have hden : (102400:ℝ)*(logb 2 u)^4 ≤ u^(1/200:ℝ) := by + calc + (102400:ℝ)*(logb 2 u)^4 = (102400:ℝ)/(log 2)^(4:ℕ) * (log u)^(4:ℕ) := by + simp only [Real.logb,div_pow]; ring + _ ≤ u^(1/200:ℝ) := by simpa only [show (4:ℝ) = ((4:ℕ):ℝ) by norm_num, Real.rpow_natCast] using hh + have hm := mul_le_mul_of_nonneg_left hden (rpow_nonneg hu0.le (199/200:ℝ)) + have he : u^(199/200:ℝ)*u^(1/200:ℝ) = u := by + rw [← Real.rpow_add hu0]; norm_num + rw [he] at hm + refine ⟨hu,?_⟩ + have hid : ((1/32:ℝ)/(logb 2 u)^2)^2*u/100 = u/(102400*(logb 2 u)^4) := by + field_simp + ; ring + rw [hid] + exact (le_div_iff₀ (by positivity : (0:ℝ) < 102400*(logb 2 u)^4)).mpr (by nlinarith) + +lemma longCycle_scale_ready : ∃ Dsp : ℝ, ∀ D ≥ Dsp, + 4 ≤ D ∧ 4 ≤ D^(51/50:ℝ) ∧ + ∀ u : ℝ, D^(51/50:ℝ) < u → + 0 < (1/32:ℝ)/(logb 2 u)^2 ∧ (1/32:ℝ)/(logb 2 u)^2 ≤ 1 ∧ + 1 ≤ ((1/32:ℝ)/(logb 2 u)^2)^2*u/100 ∧ + D^(101/100:ℝ) < ((1/32:ℝ)/(logb 2 u)^2)^2*u/100 := by + obtain ⟨Q,hQ⟩ := eventually_atTop.mp longCycle_power_margin + refine ⟨max 4 Q,?_⟩ + intro D hD + have hD4 : 4 ≤ D := (le_max_left _ _).trans hD + have hD1 : 1 ≤ D := by linarith + have hDp : 0 < D := by linarith + have hTD : D ≤ D^(51/50:ℝ) := by + simpa only [Real.rpow_one] using Real.rpow_le_rpow_of_exponent_le hD1 + (by norm_num : (1:ℝ) ≤ 51/50) + refine ⟨hD4,hD4.trans hTD,?_⟩ + intro u hu + have huQ : Q ≤ u := (le_max_right 4 Q).trans (hD.trans (hTD.trans hu.le)) + obtain ⟨hu4,hq⟩ := hQ u huQ + have hlog : 1 ≤ logb 2 u := by + have h := Real.logb_le_logb_of_le (b:=2) (x:=2) (y:=u) + (by norm_num) (by norm_num) (by linarith) + norm_num [Real.logb] at h + exact h + have hd : 0 < (logb 2 u)^2 := by positivity + have hα : 0 < (1/32:ℝ)/(logb 2 u)^2 := by positivity + have hα1 : (1/32:ℝ)/(logb 2 u)^2 ≤ 1 := by + apply (div_le_one hd).mpr + nlinarith [sq_nonneg (logb 2 u-1)] + have hmargin : D^(101/100:ℝ) < u^(199/200:ℝ) := by + have hstrict := Real.rpow_lt_rpow (Real.rpow_nonneg hDp.le (51/50:ℝ)) hu + (by norm_num : (0:ℝ) < 199/200) + rw [← Real.rpow_mul hDp.le] at hstrict + have hle := Real.rpow_le_rpow_of_exponent_le hD1 + (by norm_num : (101/100:ℝ) ≤ (51/50)*(199/200)) + exact hle.trans_lt hstrict + have hpow1 : 1 ≤ D^(101/100:ℝ) := Real.one_le_rpow hD1 (by norm_num) + exact ⟨hα,hα1,hpow1.trans (hmargin.le.trans hq),hmargin.trans_le hq⟩ + +lemma external_induce_image (G : SimpleGraph V) (A : Finset V) (hG : SupportedOn G A) + (U : Finset {x // x ∈ A}) : + externalOn G (U.image Subtype.val) = + (externalOn (G.induce (A : Set V)) U).image Subtype.val := by + classical + ext y + constructor + · intro hy + obtain ⟨_,hyU,x,hx,hxy⟩ := Finset.mem_filter.mp hy + have hyA := (hG hxy).2 + obtain ⟨x',hx',heq⟩ := Finset.mem_image.mp hx + refine Finset.mem_image.mpr ⟨⟨y,hyA⟩,Finset.mem_filter.mpr ⟨Finset.mem_univ _,?_,?_⟩,rfl⟩ + · intro hy' + exact hyU (Finset.mem_image.mpr ⟨⟨y,hyA⟩,hy',rfl⟩) + · exact ⟨x',hx',by simpa only [SimpleGraph.induce_adj,heq] using hxy⟩ + · intro hy + obtain ⟨y',hy',rfl⟩ := Finset.mem_image.mp hy + obtain ⟨_,hyU,x,hx,hxy⟩ := Finset.mem_filter.mp hy' + refine Finset.mem_filter.mpr ⟨Finset.mem_univ _,?_,?_⟩ + · intro hy + obtain ⟨z,hz,heq⟩ := Finset.mem_image.mp hy + have heq' : z = y' := Subtype.ext heq + exact hyU (heq' ▸ hz) + · exact ⟨x,Finset.mem_image.mpr ⟨x,hx,rfl⟩,hxy⟩ + +lemma sparse_neighborhood_from_cycle_exclusion (G : SimpleGraph V) (A : Finset V) + (hG : SupportedOn G A) (ℓ : ℝ) (hNL : NoLongCycle G ℓ) + (hα : 0 < (1/32:ℝ)/(logb 2 A.card)^2) + (hα1 : (1/32:ℝ)/(logb 2 A.card)^2 ≤ 1) + (hq : 1 ≤ ((1/32:ℝ)/(logb 2 A.card)^2)^2*A.card/100) + (hmargin : ℓ < ((1/32:ℝ)/(logb 2 A.card)^2)^2*A.card/100) : + ∃ U ⊆ A, U.Nonempty ∧ 2*U.card ≤ A.card ∧ + ((externalOn G U).card : ℝ) < (1/32:ℝ)*U.card/(logb 2 A.card)^2 := by + classical + by_contra hno + let H := G.induce (A : Set V) + let α := (1/32:ℝ)/(logb 2 A.card)^2 + have hexp : VertexExpansion H α := by + intro U hU hhalf + let W := U.image Subtype.val + have hW : W ⊆ A := by + intro x hx + obtain ⟨x',hx',rfl⟩ := Finset.mem_image.mp hx + exact x'.property + have hcard : W.card = U.card := Finset.card_image_of_injective _ Subtype.val_injective + have hWne : W.Nonempty := hU.image _ + have hWhalf : 2*W.card ≤ A.card := by simpa [hcard] using hhalf + have hs : ¬ ((externalOn G W).card : ℝ) < (1/32:ℝ)*W.card/(logb 2 A.card)^2 := + fun hs => hno ⟨W,hW,hWne,hWhalf,hs⟩ + have hbound := le_of_not_gt hs + have heq := external_induce_image G A hG U + have hcardext := congrArg Finset.card heq + rw [Finset.card_image_of_injective _ Subtype.val_injective] at hcardext + have hext : externalNeighbors H U = externalOn H U := by rfl + rw [hext] + change α*(U.card:ℝ) ≤ (externalOn H U).card + rw [← hcardext] + dsimp [α] + rw [← hcard] + calc + (1/32:ℝ)/(logb 2 A.card)^2 * (W.card:ℝ) = (1/32:ℝ)*(W.card:ℝ)/(logb 2 A.card)^2 := by ring + _ ≤ ((externalOn G W).card:ℝ) := hbound + have hq' : 1 ≤ α^2*(Fintype.card {x // x ∈ A})/100 := by simpa [α] using hq + obtain ⟨a,p,hp,hplen⟩ := long_cycle_of_vertex_expansion H α hα hα1 hexp hq' + let f : H →g G := ⟨Subtype.val,fun h => h⟩ + have hc := hp.map (f:=f) (by exact Subtype.val_injective) + have hlen := hNL a.val (p.map f) hc + simp only [SimpleGraph.Walk.length_map] at hlen + have hplen' : α^2*(A.card:ℝ)/100 < (p.length:ℝ) := by simpa using hplen + dsimp [α] at hplen' + linarith + +lemma splitPotential_scale_bound (D x : ℝ) (hD : 4 ≤ D) : + splitPotential (D^(51/50:ℝ)) x ≤ 1+2/logb 2 D := by + have hD1 : 1 ≤ D := by linarith + have hDp : 0 < D := by linarith + have hLD : 2 ≤ logb 2 D := by + have h := Real.logb_le_logb_of_le (b:=2) (x:=4) (y:=D) + (by norm_num) (by norm_num) hD + have h4 : logb 2 (4:ℝ) = 2 := by + rw [show (4:ℝ) = 2^(2:ℕ) by norm_num,Real.logb_pow] + norm_num + rw [h4] at h + exact h + have hLD0 : 0 < logb 2 D := by linarith + have hlogT : logb 2 (D^(51/50:ℝ)/2) = (51/50:ℝ)*logb 2 D-1 := by + rw [Real.logb_div (Real.rpow_pos_of_pos hDp _).ne' (by norm_num), + Real.logb_rpow_eq_mul_logb_of_pos hDp] + norm_num + have hT0 : 0 < logb 2 (D^(51/50:ℝ)/2) := by rw [hlogT]; linarith + have hrecip : 1/logb 2 (D^(51/50:ℝ)/2) ≤ 2/logb 2 D := by + apply (div_le_div_iff₀ hT0 hLD0).mpr + rw [hlogT] + linarith + have hbasepos : 0 < D^(51/50:ℝ)/2 := by positivity + have hmaxlog := Real.logb_le_logb_of_le (b:=2) (by norm_num) hbasepos + (le_max_right x (D^(51/50:ℝ)/2)) + have hmax0 : 0 < logb 2 (max x (D^(51/50:ℝ)/2)) := lt_of_lt_of_le hT0 hmaxlog + have hinv := one_div_pos.mpr hmax0 + dsimp [splitPotential] + linarith + +lemma partition_replace_head {G H : SimpleGraph V} {C L : List (SimpleGraph V)} + (hG : GraphPartition G (H::C)) (hH : GraphPartition H L) : + GraphPartition G (C++L) := by + intro x y + have h := hG x y + simp only [edgeOccurrences_cons] at h + rw [edgeOccurrences_append,hH x y] + omega + +theorem scale_boxes : ∃ Dsp : ℝ, ∀ D ≥ Dsp, + ∀ (V : Type u) [Fintype V] [DecidableEq V] + (G : SimpleGraph V) (A : Finset V), A.Nonempty → SupportedOn G A → + 2*(edgeCount G : ℝ)/A.card ≤ D → + ∃ (C : List (SimpleGraph V)) (L : List (AssignedPiece V)), + (∀ K ∈ C, IsCycleGraph K ∧ D^(101/100:ℝ) ≤ (edgeCount K : ℝ)) ∧ + (C.length : ℝ) ≤ A.card/(2*D^(1/100:ℝ)) ∧ + (∀ P ∈ L, P.vertices ⊆ A ∧ P.vertices.Nonempty ∧ (P.vertices.card : ℝ) ≤ D^(51/50:ℝ)) ∧ + (∀ x ∈ A, ∃ P ∈ L, x ∈ P.vertices) ∧ + GraphPartition G (C++L.map AssignedPiece.graph) ∧ + (L.map (fun P => (P.vertices.card : ℝ))).sum ≤ (1+2/logb 2 D)*A.card := by + classical + obtain ⟨Dsp,hsp⟩ := longCycle_scale_ready + refine ⟨Dsp,?_⟩ + intro D hD V _ _ G A hA hG hdeg + obtain ⟨hD4,hT4,hnum⟩ := hsp D hD + have hDp : 0 < D := by linarith + have hA0 : (0:ℝ) < A.card := by exact_mod_cast hA.card_pos + obtain ⟨H,C,hHG,hNL,hC,hpartC,hbudget⟩ := remove_long_cycles G (D^(101/100:ℝ)) + have hHA : SupportedOn H A := fun _ _ h => hG (hHG h) + have hsplit : ∀ B ⊆ A, ∀ K : SimpleGraph V, K ≤ H → SupportedOn K B → D^(51/50:ℝ) < (B.card:ℝ) → + ∃ U ⊆ B, U.Nonempty ∧ 2*U.card ≤ B.card ∧ + ((externalOn K U).card : ℝ) < (1/32:ℝ)*U.card/(logb 2 B.card)^2 := by + intro B hB K hK hs hlarge + obtain ⟨ha,ha1,hq,hm⟩ := hnum B.card hlarge + exact sparse_neighborhood_from_cycle_exclusion K B hs _ (hNL.mono hK) ha ha1 hq hm + obtain ⟨L,hL,hcov,hpartL,hcost⟩ := box_recursion H A (D^(51/50:ℝ)) hT4 hA hHA hsplit + refine ⟨C,L,hC,?_,hL,hcov,partition_replace_head hpartC hpartL,?_⟩ + · have hdeg' := (div_le_iff₀ hA0).mp hdeg + have he : D^(101/100:ℝ) = D*D^(1/100:ℝ) := by + rw [show (101/100:ℝ) = 1+1/100 by norm_num,Real.rpow_add hDp,Real.rpow_one] + rw [he] at hbudget + apply (le_div_iff₀ (by positivity : (0:ℝ) < 2*D^(1/100:ℝ))).mpr + have hnonneg : (0:ℝ) ≤ edgeCount H := Nat.cast_nonneg _ + nlinarith + · have hfbound := splitPotential_scale_bound D A.card hD4 + have hplain : (L.map (fun P => (P.vertices.card:ℝ))).sum ≤ + (L.map (fun P => (P.vertices.card:ℝ)*splitPotential (D^(51/50:ℝ)) P.vertices.card)).sum := by + apply List.sum_le_sum + intro P hP + have hb := (splitPotential_bounds (D^(51/50:ℝ)) P.vertices.card hT4).1 + have hm := mul_le_mul_of_nonneg_left hb (Nat.cast_nonneg P.vertices.card) + simpa using hm + have hmul := mul_le_mul_of_nonneg_left hfbound hA0.le + nlinarith + +end ErdosGallai.Scale + +namespace ErdosGallai.Scale +open Finset SimpleGraph Classical Real +variable {V : Type cycleUniverse4} [Fintype V] [DecidableEq V] + +lemma edgeCount_sup_le (G H : SimpleGraph V) : edgeCount (G ⊔ H) ≤ edgeCount G + edgeCount H := by + classical + simpa [edgeCount, SimpleGraph.edgeFinset_sup] using Finset.card_union_le G.edgeFinset H.edgeFinset + +lemma crossing_count (G : SimpleGraph V) (A B : Finset V) (hd : Disjoint A B) : + edgeCount (crossingGraph G A B) = cutCount G A B := by + classical + have hinj : Set.InjOn (fun e : V × V => s(e.1,e.2)) (G.interedges A B : Set (V×V)) := by + intro e he f hf hh + rcases Sym2.mk_eq_mk_iff.mp hh with hh | hh + · exact hh + · have heA := (G.mem_interedges_iff.mp he).1 + have hfB := (G.mem_interedges_iff.mp hf).2.1 + have heq : e.1 = f.2 := congrArg Prod.fst hh + exact False.elim (Finset.disjoint_left.mp hd heA (heq.symm ▸ hfB)) + have heq : (crossingGraph G A B).edgeFinset = + (G.interedges A B).image (fun e : V×V => s(e.1,e.2)) := by + ext e + induction e using Sym2.inductionOn with | _ x y => + simp only [SimpleGraph.mem_edgeFinset, SimpleGraph.mem_edgeSet] + constructor + · rintro ⟨hxy,(⟨hx,hy⟩|⟨hx,hy⟩)⟩ + · exact Finset.mem_image.mpr ⟨(x,y),G.mem_interedges_iff.mpr ⟨hx,hy,hxy⟩,rfl⟩ + · exact Finset.mem_image.mpr ⟨(y,x),G.mem_interedges_iff.mpr ⟨hy,hx,hxy.symm⟩, + Sym2.eq_swap⟩ + · rintro h + obtain ⟨⟨a,b⟩,hab,he⟩ := Finset.mem_image.mp h + obtain ⟨ha,hb,hg⟩ := G.mem_interedges_iff.mp hab + rcases (Sym2.mk_eq_mk_iff (p := (a,b)) (q := (x,y))).mp he with he | he + · cases he; exact ⟨hg,Or.inl ⟨ha,hb⟩⟩ + · cases he; exact ⟨hg.symm,Or.inr ⟨hb,ha⟩⟩ + simp only [edgeCount,heq,Finset.card_image_of_injOn hinj,cutCount] + +lemma log2_split_budget {a b : ℕ} (ha : 0 < a) (hb : 0 < b) : + min a b + a*a.log2 + b*b.log2 ≤ (a+b)*(a+b).log2 := by + have hm : Monotone Nat.log2 := by + intro m n h + simpa only [Nat.log2_eq_log_two] using (Nat.log_mono_right (b:=2) h) + have hla := hm (show a ≤ a+b by omega) + have hlb := hm (show b ≤ a+b by omega) + rcases le_total a b with hab | hba + · have hhalf := hm (show 2*a ≤ a+b by omega) + rw [Nat.log2_two_mul (by omega)] at hhalf + rw [min_eq_left hab] + nlinarith + · have hhalf := hm (show 2*b ≤ a+b by omega) + rw [Nat.log2_two_mul (by omega)] at hhalf + rw [min_eq_right hba] + nlinarith + +lemma partition_combine {G K G₁ G₂ H₁ H₂ : SimpleGraph V} + {L₁ L₂ : List (SimpleGraph V)} + (hp₁ : GraphPartition G₁ (H₁::L₁)) (hp₂ : GraphPartition G₂ (H₂::L₂)) + (hcover : ∀ x y, G.Adj x y ↔ K.Adj x y ∨ G₁.Adj x y ∨ G₂.Adj x y) + (hd₁ : Disjoint K G₁) (hd₂ : Disjoint K G₂) (hd₃ : Disjoint G₁ G₂) : + GraphPartition G ((K ⊔ H₁ ⊔ H₂)::(L₁++L₂)) := by + classical + have hle₁ : H₁ ≤ G₁ := partition_member_le hp₁ (by simp) + have hle₂ : H₂ ≤ G₂ := partition_member_le hp₂ (by simp) + intro x y + have h₁ := hp₁ x y + have h₂ := hp₂ x y + have hd₁ := SimpleGraph.disjoint_left.mp hd₁ x y + have hd₂ := SimpleGraph.disjoint_left.mp hd₂ x y + have hd₃ := SimpleGraph.disjoint_left.mp hd₃ x y + have hh₁ := @hle₁ x y + have hh₂ := @hle₂ x y + have hc := hcover x y + simp only [edgeOccurrences_cons,edgeOccurrences_append,SimpleGraph.sup_adj] at * + by_cases hK : K.Adj x y <;> by_cases hG₁ : G₁.Adj x y <;> + by_cases hG₂ : G₂.Adj x y <;> by_cases hH₁ : H₁.Adj x y <;> + by_cases hH₂ : H₂.Adj x y <;> simp_all + +lemma cut_split_properties {V : Type cycleUniverse5} [_contextInstance1 : Fintype V] [_contextInstance2 : DecidableEq V] (G : SimpleGraph V) (A U : Finset V) + (hG : SupportedOn G A) (_hU : U ⊆ A) : + (∀ x y, G.Adj x y ↔ (crossingGraph G U (A\U)).Adj x y ∨ + (restrictGraph G U).Adj x y ∨ (restrictGraph G (A\U)).Adj x y) ∧ + Disjoint (crossingGraph G U (A\U)) (restrictGraph G U) ∧ + Disjoint (crossingGraph G U (A\U)) (restrictGraph G (A\U)) ∧ + Disjoint (restrictGraph G U) (restrictGraph G (A\U)) := by + constructor + · intro x y + change G.Adj x y ↔ (G.Adj x y ∧ _) ∨ (G.Adj x y ∧ _) ∨ (G.Adj x y ∧ _) + have hs := @hG x y + simp only [Finset.mem_sdiff] + tauto + · simp only [SimpleGraph.disjoint_left, crossingGraph, restrictGraph,Finset.mem_sdiff] + tauto + +lemma empty_supported_graph {V : Type cycleUniverse6} [_contextInstance1 : Fintype V] [_contextInstance2 : DecidableEq V] {G : SimpleGraph V} {A : Finset V} + (hG : SupportedOn G A) (hA : A.card ≤ 1) : G = ⊥ := by + ext x y + constructor + · intro h + obtain ⟨hx,hy⟩ := hG h + have hxy := Finset.card_le_one.mp hA x hx y hy + exact False.elim (G.ne_of_adj h hxy) + · simp + +theorem cut_extraction (G : SimpleGraph V) (A : Finset V) + (hG : SupportedOn G A) (σ : ℝ) (hσ : 0 ≤ σ) : + ∃ (R : List (AssignedPiece V)) (H : SimpleGraph V), + (∀ P ∈ R, P.vertices ⊆ A ∧ 2 ≤ P.vertices.card ∧ + CutExpansionOn P.graph P.vertices σ) ∧ + R.Pairwise (fun P Q => Disjoint P.vertices Q.vertices) ∧ + GraphPartition G (H :: R.map AssignedPiece.graph) ∧ + SupportedOn H A ∧ + (edgeCount H : ℝ) ≤ σ * A.card * A.card.log2 := by + classical + induction hcard : A.card using Nat.strong_induction_on generalizing A G with + | h n ih => + by_cases hsmall : A.card ≤ 1 + · have he := empty_supported_graph hG hsmall + refine ⟨[],⊥,by simp,by simp,?_,?_,?_⟩ + · subst G + intro x y + simp + · intro x y h; exact False.elim h + · simp only [edgeCount_bot,Nat.cast_zero] + positivity + by_cases hexp : CutExpansionOn G A σ + · refine ⟨[⟨A,G,hG⟩],⊥,?_,by simp,?_,?_,?_⟩ + · intro P hP + have he := List.mem_singleton.mp hP + subst P + exact ⟨fun _ h => h,by change 2 ≤ A.card; omega,hexp⟩ + · intro x y; simp + · intro x y h; exact False.elim h + · simp only [edgeCount_bot,Nat.cast_zero] + positivity + unfold CutExpansionOn at hexp + push Not at hexp + obtain ⟨U,hU,hcut⟩ := hexp + have hdisUB : Disjoint U (A\U) := Finset.disjoint_left.mpr + (fun _ hu hb => (Finset.mem_sdiff.mp hb).2 hu) + have hcnt : (0 : ℝ) ≤ cutCount G U (A\U) := Nat.cast_nonneg _ + have hσpos : 0 < σ := by + by_contra h + have : σ = 0 := le_antisymm (le_of_not_gt h) hσ + rw [this,zero_mul] at hcut + linarith + have hUpos : 0 < U.card := by + by_contra h + have hz : U.card = 0 := by omega + simp [hz] at hcut + linarith [min_le_left (0:ℝ) ((A\U).card:ℝ)] + have hBpos : 0 < (A\U).card := by + by_contra h + have hz : (A\U).card = 0 := by omega + simp [hz] at hcut + linarith [min_le_right (U.card:ℝ) (0:ℝ)] + have hcardSum := Finset.card_sdiff_add_card_eq_card hU + have hUlt : U.card < n := by omega + have hBlt : (A\U).card < n := by omega + obtain ⟨R₁,H₁,hR₁,hd₁,hp₁,hs₁,hc₁⟩ := ih U.card hUlt (restrictGraph G U) U + (restrictGraph_supported G U) rfl + obtain ⟨R₂,H₂,hR₂,hd₂,hp₂,hs₂,hc₂⟩ := ih (A\U).card hBlt (restrictGraph G (A\U)) (A\U) + (restrictGraph_supported G (A\U)) rfl + let K := crossingGraph G U (A\U) + obtain ⟨hcover,hdis₁,hdis₂,hdis₃⟩ := cut_split_properties G A U hG hU + refine ⟨R₁++R₂,K ⊔ H₁ ⊔ H₂,?_,?_,?_,?_,?_⟩ + · intro P hP + rcases List.mem_append.mp hP with hP | hP + · obtain ⟨hPA,hPc,hPe⟩ := hR₁ P hP + exact ⟨hPA.trans hU,hPc,hPe⟩ + · obtain ⟨hPA,hPc,hPe⟩ := hR₂ P hP + exact ⟨hPA.trans Finset.sdiff_subset,hPc,hPe⟩ + · apply List.pairwise_append.mpr + refine ⟨hd₁,hd₂,?_⟩ + intro P hP Q hQ + exact hdisUB.mono + (hR₁ P hP).1 (hR₂ Q hQ).1 + · simpa only [List.map_append] using partition_combine hp₁ hp₂ hcover hdis₁ hdis₂ hdis₃ + · intro x y h + rcases h with (h|h)|h + · exact hG h.1 + · exact ⟨hU (hs₁ h).1,hU (hs₁ h).2⟩ + · exact ⟨(Finset.mem_sdiff.mp (hs₂ h).1).1,(Finset.mem_sdiff.mp (hs₂ h).2).1⟩ + · have hcardK : edgeCount K = cutCount G U (A\U) := + crossing_count G U (A\U) hdisUB + have hcost : (edgeCount (K⊔H₁⊔H₂) : ℝ) ≤ + edgeCount K + edgeCount H₁ + edgeCount H₂ := by + exact_mod_cast (edgeCount_sup_le (K⊔H₁) H₂).trans + (Nat.add_le_add_right (edgeCount_sup_le K H₁) _) + have hpot := log2_split_budget hUpos hBpos + have hpotR : min (U.card:ℝ) ((A\U).card:ℝ) + U.card*U.card.log2 + + (A\U).card*(A\U).card.log2 ≤ (A.card:ℝ) * A.card.log2 := by + have he : U.card+(A\U).card = A.card := by omega + rw [he] at hpot + exact_mod_cast hpot + have hpay := mul_le_mul_of_nonneg_left hpotR hσ + rw [hcardK] at hcost + rw [← hcard] + nlinarith + +lemma cast_log2_le_logb {n : ℕ} (hn : 0 < n) : (n.log2 : ℝ) ≤ Real.logb 2 n := by + apply (Real.le_logb_iff_rpow_le (by norm_num : (1:ℝ)<2) (by exact_mod_cast hn)).mpr + rw [Real.rpow_natCast, Nat.log2_eq_log_two] + exact_mod_cast Nat.pow_log_le_self 2 hn.ne' + +lemma expansion_order_lower {V : Type cycleUniverse7} [_contextInstance1 : Fintype V] [_contextInstance2 : DecidableEq V] {G : SimpleGraph V} {A : Finset V} {σ : ℝ} + (hA : 2 ≤ A.card) (he : CutExpansionOn G A σ) : σ+1 ≤ A.card := by + classical + obtain ⟨x,hx⟩ := Finset.card_pos.mp (show 0 < A.card by omega) + have hsub : {x} ⊆ A := Finset.singleton_subset_iff.mpr hx + have hcard := Finset.card_sdiff_add_card_eq_card hsub + simp only [Finset.card_singleton] at hcard + have hB : (1:ℝ) ≤ (A\{x}).card := by exact_mod_cast (show 1 ≤ (A\{x}).card by omega) + have hc := he {x} hsub + simp only [Finset.card_singleton,Nat.cast_one,min_eq_left hB,mul_one] at hc + have hbound : cutCount G {x} (A\{x}) ≤ (A\{x}).card := by + simpa only [cutCount,Finset.card_singleton,one_mul] using G.card_interedges_le_mul {x} (A\{x}) + have hboundR : (cutCount G {x} (A\{x}) : ℝ) ≤ (A\{x}).card := by exact_mod_cast hbound + have heqR : ((A\{x}).card:ℝ)+1 = A.card := by exact_mod_cast hcard + linarith + +open Filter Asymptotics Real in +lemma cut_scale_ready : ∀ᶠ D : ℝ in atTop, + 1 ≤ D ∧ 2*D^(9/10:ℝ)*logb 2 (D^(51/50:ℝ)) ≤ D^(19/20:ℝ) := by + have hlog2 : 0 < log 2 := log_pos (by norm_num) + have he := ((isLittleO_log_rpow_atTop (by norm_num : (0:ℝ)<1/20)).const_mul_left + ((51/25:ℝ)/log 2)).eventuallyLE + filter_upwards [eventually_ge_atTop (1:ℝ),he] with D hD h + have hDp : 0 < D := by linarith + have hn : 0 ≤ (51/25:ℝ)/log 2 * log D := mul_nonneg (by positivity) (Real.log_nonneg hD) + have hh : (51/25:ℝ)/log 2 * log D ≤ D^(1/20:ℝ) := by + simpa only [Real.norm_eq_abs,abs_of_nonneg hn,abs_of_nonneg (Real.rpow_nonneg hDp.le _)] using h + refine ⟨hD,?_⟩ + calc + 2*D^(9/10:ℝ)*logb 2 (D^(51/50:ℝ)) = D^(9/10:ℝ)*((51/25:ℝ)/log 2*log D) := by + rw [Real.logb_rpow_eq_mul_logb_of_pos hDp] + simp only [Real.logb] + ring + _ ≤ D^(9/10:ℝ)*D^(1/20:ℝ) := mul_le_mul_of_nonneg_left hh (by positivity) + _ = D^(19/20:ℝ) := by rw [← Real.rpow_add hDp]; norm_num + +theorem scale_cut_extraction : ∃ Dcut : ℝ, ∀ D ≥ Dcut, + ∀ (V : Type u) [Fintype V] [DecidableEq V] + (G : SimpleGraph V) (A : Finset V), A.Nonempty → SupportedOn G A → + (A.card : ℝ) ≤ D^(51/50:ℝ) → + ∃ (R : List (AssignedPiece V)) (H : SimpleGraph V), + (∀ P ∈ R, P.vertices ⊆ A ∧ D^(9/10:ℝ) ≤ P.vertices.card ∧ + (P.vertices.card:ℝ) ≤ D^(51/50:ℝ) ∧ CutExpansionOn P.graph P.vertices (D^(9/10:ℝ))) ∧ + R.Pairwise (fun P Q => Disjoint P.vertices Q.vertices) ∧ + GraphPartition G (H :: R.map AssignedPiece.graph) ∧ SupportedOn H A ∧ + 2*(edgeCount H : ℝ)/A.card ≤ D^(19/20:ℝ) := by + classical + obtain ⟨Dcut,hready⟩ := Filter.eventually_atTop.mp cut_scale_ready + refine ⟨Dcut,?_⟩ + intro D hD V _ _ G A hA hG hhi + obtain ⟨hD₁,hscale⟩ := hready D hD + have hDp : 0 < D := by linarith + have hAp : 0 < A.card := Finset.card_pos.mpr hA + have hAr : (0:ℝ) < A.card := by exact_mod_cast hAp + obtain ⟨R,H,hR,hd,hp,hs,hcost⟩ := cut_extraction G A hG (D^(9/10:ℝ)) (by positivity) + refine ⟨R,H,?_,hd,hp,hs,?_⟩ + · intro P hP + obtain ⟨hsub,hsize,hexp⟩ := hR P hP + have hlo := expansion_order_lower hsize hexp + have hle : (P.vertices.card:ℝ) ≤ A.card := by exact_mod_cast Finset.card_le_card hsub + exact ⟨hsub,by linarith,hle.trans hhi,hexp⟩ + · have hlog := (cast_log2_le_logb hAp).trans + (Real.logb_le_logb_of_le (by norm_num : (1:ℝ)<2) hAr hhi) + have hmul := mul_le_mul_of_nonneg_left hlog (show 0 ≤ D^(9/10:ℝ)*(A.card:ℝ) by positivity) + have hscaleA := mul_le_mul_of_nonneg_right hscale hAr.le + apply (div_le_iff₀ hAr).mpr + nlinarith + +end ErdosGallai.Scale +end +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/CycleDecomposition/ScaleHierarchy.lean b/lean/OAI/Combinatorics/CycleDecomposition/ScaleHierarchy.lean new file mode 100644 index 0000000000000000000000000000000000000000..4a43fb8552258b71497f10eab8b81b9393ea420f --- /dev/null +++ b/lean/OAI/Combinatorics/CycleDecomposition/ScaleHierarchy.lean @@ -0,0 +1,575 @@ +import OAI.Combinatorics.CycleDecomposition.ScaleExtraction + +namespace OAI + +universe u + +universe cycleUniverse1 cycleUniverse2 cycleUniverse3 cycleUniverse4 cycleUniverse5 cycleUniverse6 + +section +open Filter Asymptotics Real +open scoped Topology +noncomputable section +open MeasureTheory ProbabilityTheory Finset +section +namespace ErdosGallai.Scale +open Finset SimpleGraph Classical Real +variable {V : Type cycleUniverse1} [Fintype V] [DecidableEq V] + +lemma edgeOccurrences_refine {I : Type cycleUniverse2} (L : List I) + (g : I → SimpleGraph V) (f : I → List (SimpleGraph V)) + (h : ∀ i ∈ L, GraphPartition (g i) (f i)) (x y : V) : + edgeOccurrences (L.flatMap f) x y = edgeOccurrences (L.map g) x y := by + induction L with + | nil => simp + | cons i L ih => + simp only [List.flatMap_cons, edgeOccurrences_append, List.map_cons, + edgeOccurrences_cons] + rw [h i (by simp), ih (fun j hj => h j (by simp [hj]))] + +lemma graphPartition_refine {I : Type cycleUniverse3} {G : SimpleGraph V} + {C : List (SimpleGraph V)} {L : List I} + {g : I → SimpleGraph V} {f : I → List (SimpleGraph V)} + (hp : GraphPartition G (C ++ L.map g)) + (h : ∀ i ∈ L, GraphPartition (g i) (f i)) : + GraphPartition G (C ++ L.flatMap f) := by + intro x y + simpa only [edgeOccurrences_append, edgeOccurrences_refine L g f h] using hp x y + +theorem scale_split : ∃ Dsp : ℝ, ∀ D ≥ Dsp, + ∀ (V : Type u) [Fintype V] [DecidableEq V] + (G : SimpleGraph V) (A : Finset V), A.Nonempty → SupportedOn G A → + 2*(edgeCount G : ℝ)/A.card ≤ D → + ∃ (C : List (SimpleGraph V)) (L : List (AssignedPiece V)) + (R : AssignedPiece V → List (AssignedPiece V)) + (H : AssignedPiece V → SimpleGraph V), + (∀ K ∈ C, IsCycleGraph K ∧ D^(101/100:ℝ) ≤ (edgeCount K : ℝ)) ∧ + (C.length : ℝ) ≤ A.card/(2*D^(1/100:ℝ)) ∧ + (∀ P ∈ L, P.vertices ⊆ A ∧ P.vertices.Nonempty ∧ + (P.vertices.card : ℝ) ≤ D^(51/50:ℝ)) ∧ + (∀ x ∈ A, ∃ P ∈ L, x ∈ P.vertices) ∧ + (L.map (fun P => (P.vertices.card : ℝ))).sum ≤ (1+2/logb 2 D)*A.card ∧ + (∀ P ∈ L, + (∀ Q ∈ R P, Q.vertices ⊆ P.vertices ∧ + D^(9/10:ℝ) ≤ Q.vertices.card ∧ + (Q.vertices.card:ℝ) ≤ D^(51/50:ℝ) ∧ + CutExpansionOn Q.graph Q.vertices (D^(9/10:ℝ))) ∧ + (R P).Pairwise (fun Q T => Disjoint Q.vertices T.vertices) ∧ + GraphPartition P.graph (H P :: (R P).map AssignedPiece.graph) ∧ + SupportedOn (H P) P.vertices ∧ + 2*(edgeCount (H P) : ℝ)/P.vertices.card ≤ D^(19/20:ℝ)) ∧ + GraphPartition G (C ++ L.flatMap (fun P => H P :: (R P).map AssignedPiece.graph)) := by + classical + obtain ⟨D₁,h₁⟩ := scale_boxes.{u} + obtain ⟨D₂,h₂⟩ := scale_cut_extraction.{u} + refine ⟨max D₁ D₂, ?_⟩ + intro D hD V _ _ G A hA hs hd + obtain ⟨C,L,hC,hCN,hL,hcover,hp,hcost⟩ := + h₁ D ((le_max_left _ _).trans hD) V G A hA hs hd + have hres : ∀ P : AssignedPiece V, + ∃ (R : List (AssignedPiece V)) (H : SimpleGraph V), P ∈ L → + (∀ Q ∈ R, Q.vertices ⊆ P.vertices ∧ + D^(9/10:ℝ) ≤ Q.vertices.card ∧ + (Q.vertices.card:ℝ) ≤ D^(51/50:ℝ) ∧ + CutExpansionOn Q.graph Q.vertices (D^(9/10:ℝ))) ∧ + R.Pairwise (fun Q T => Disjoint Q.vertices T.vertices) ∧ + GraphPartition P.graph (H :: R.map AssignedPiece.graph) ∧ + SupportedOn H P.vertices ∧ + 2*(edgeCount H : ℝ)/P.vertices.card ≤ D^(19/20:ℝ) := by + intro P + by_cases hP : P ∈ L + · obtain ⟨R,H,hgood⟩ := h₂ D ((le_max_right _ _).trans hD) V + P.graph P.vertices (hL P hP).2.1 P.supported (hL P hP).2.2 + exact ⟨R,H,fun _ => hgood⟩ + · exact ⟨[],⊥,fun hp => False.elim (hP hp)⟩ + choose R H hR using hres + refine ⟨C,L,R,H,hC,hCN,hL,hcover,hcost,hR,?_⟩ + exact graphPartition_refine hp (fun P hP => (hR P hP).2.2.1) + +end ErdosGallai.Scale + +namespace ErdosGallai.Scale +noncomputable section +open Real Filter Finset +open scoped Topology + +def scaleTheta : ℝ := 19/20 +def inductionScale (n : ℝ) (j : ℕ) : ℝ := n ^ (scaleTheta ^ j) + +lemma scaleTheta_pos : 0 < scaleTheta := by norm_num [scaleTheta] +lemma scaleTheta_lt_one : scaleTheta < 1 := by norm_num [scaleTheta] + +lemma inductionScale_zero (n : ℝ) : inductionScale n 0 = n := by + simp [inductionScale] + +lemma inductionScale_pos (n : ℝ) (hn : 0 < n) (j : ℕ) : + 0 < inductionScale n j := Real.rpow_pos_of_pos hn _ + +lemma inductionScale_succ (n : ℝ) (hn : 0 ≤ n) (j : ℕ) : + inductionScale n (j+1) = (inductionScale n j) ^ scaleTheta := by + simp only [inductionScale, pow_succ, Real.rpow_mul hn] + +lemma inductionScale_gt_one (n : ℝ) (hn : 1 < n) (j : ℕ) : + 1 < inductionScale n j := by + simpa [inductionScale] using Real.rpow_lt_rpow_of_exponent_lt hn + (pow_pos scaleTheta_pos j) + +lemma inductionScale_le (n : ℝ) (hn : 1 ≤ n) (j : ℕ) : + inductionScale n j ≤ n := by + have hp : scaleTheta ^ j ≤ 1 := pow_le_one₀ scaleTheta_pos.le scaleTheta_lt_one.le + simpa [inductionScale] using Real.rpow_le_rpow_of_exponent_le hn hp + +lemma inductionScale_log (n : ℝ) (hn : 0 < n) (j : ℕ) : + logb 2 (inductionScale n j) = scaleTheta ^ j * logb 2 n := by + exact Real.logb_rpow_eq_mul_logb_of_pos hn + +lemma inductionScale_log_pos (n : ℝ) (hn : 1 < n) (j : ℕ) : + 0 < logb 2 (inductionScale n j) := by + exact Real.logb_pos (by norm_num) (inductionScale_gt_one n hn j) + +lemma inductionScale_log_succ (n : ℝ) (hn : 0 < n) (j : ℕ) : + logb 2 (inductionScale n (j+1)) = scaleTheta * logb 2 (inductionScale n j) := by + rw [inductionScale_log n hn, inductionScale_log n hn, pow_succ] + ring + +lemma inductionScale_add (n : ℝ) (hn : 0 ≤ n) (i K : ℕ) : + inductionScale n (i+K) = (inductionScale n i) ^ (scaleTheta ^ K) := by + simp only [inductionScale, pow_add, Real.rpow_mul hn] + +lemma inductionScale_window : (51/50 : ℝ) * scaleTheta ^ 200 < 1/1000 ∧ + scaleTheta ^ 201 < 1/1000 := by + norm_num [scaleTheta] + +lemma inductionScale_tendsto (n : ℝ) (hn : 0 < n) : + Tendsto (inductionScale n) atTop (𝓝 1) := by + have ht := (Real.continuous_const_rpow (ne_of_gt hn)).tendsto 0 + change Tendsto (fun j : ℕ => n ^ (scaleTheta ^ j)) atTop (𝓝 1) + simpa only [Function.comp_def, Real.rpow_zero] using + ht.comp (tendsto_pow_atTop_nhds_zero_of_lt_one scaleTheta_pos.le scaleTheta_lt_one) + +theorem inductionScale_first_cutoff (n Dstar : ℝ) (hD : 1 < Dstar) (hn : Dstar ≤ n) : + ∃ m : ℕ, 0 < m ∧ inductionScale n m < Dstar ∧ + ∀ j < m, Dstar ≤ inductionScale n j := by + have hn0 : 0 < n := lt_trans (by norm_num) (hD.trans_le hn) + have he : ∀ᶠ j in atTop, inductionScale n j < Dstar := + (inductionScale_tendsto n hn0).eventually (gt_mem_nhds hD) + have hex : ∃ j, inductionScale n j < Dstar := he.exists + refine ⟨Nat.find hex, ?_, Nat.find_spec hex, ?_⟩ + · by_contra hm + have hz : Nat.find hex = 0 := by omega + have := Nat.find_spec hex + rw [hz, inductionScale_zero] at this + linarith + · intro j hj + exact le_of_not_gt (Nat.find_min hex hj) + +theorem scale_reciprocal_log_sum (n : ℝ) (hn : 1 < n) (j : ℕ) : + (∑ l ∈ Finset.range (j+1), 1 / logb 2 (inductionScale n l)) ≤ + 20 / logb 2 (inductionScale n j) := by + induction j with + | zero => + simp only [zero_add, Finset.sum_range_succ, Finset.sum_range_zero, zero_add] + exact div_le_div_of_nonneg_right (by norm_num) (inductionScale_log_pos n hn 0).le + | succ j ih => + rw [Finset.sum_range_succ] + have hb : (∑ x ∈ range (j + 1), 1 / logb 2 (inductionScale n x)) + + 1 / logb 2 (inductionScale n (j+1)) ≤ + 20 / logb 2 (inductionScale n j) + 1 / logb 2 (inductionScale n (j+1)) := by + linarith [ih] + apply hb.trans_eq + rw [inductionScale_log_succ n (by linarith)] + have hz : logb 2 (inductionScale n j) ≠ 0 := ne_of_gt (inductionScale_log_pos n hn j) + dsimp [scaleTheta] + field_simp + ; ring + +lemma exp_le_one_add_twice {x : ℝ} (hx : 0 ≤ x) (hxhalf : x ≤ 1/2) : + exp x ≤ 1+2*x := by + apply (Real.exp_bound_div_one_sub_of_interval hx (by linarith)).trans + apply (div_le_iff₀ (by linarith : 0 < 1-x)).mpr + nlinarith + +theorem scale_overlap_product (n C₀ : ℝ) (hn : 1 < n) (hC : 0 ≤ C₀) (j : ℕ) + (hcut : 40*C₀ ≤ logb 2 (inductionScale n j)) : + (∏ l ∈ Finset.range (j+1), (1 + C₀ / logb 2 (inductionScale n l))) ≤ + 1 + 40*C₀ / logb 2 (inductionScale n j) := by + have hL := inductionScale_log_pos n hn j + have hsum : (∑ l ∈ Finset.range (j+1), C₀ / logb 2 (inductionScale n l)) ≤ + 20*C₀ / logb 2 (inductionScale n j) := by + have hh := mul_le_mul_of_nonneg_left (scale_reciprocal_log_sum n hn j) hC + calc + _ ≤ C₀ * (20 / logb 2 (inductionScale n j)) := by + simpa only [Finset.mul_sum, mul_one_div] using hh + _ = _ := by ring + calc + _ ≤ ∏ l ∈ Finset.range (j+1), exp (C₀ / logb 2 (inductionScale n l)) := by + apply Finset.prod_le_prod₀ + · intro l hl + have := div_nonneg hC (inductionScale_log_pos n hn l).le + linarith + · intro l hl + simpa [add_comm] using Real.add_one_le_exp (C₀ / logb 2 (inductionScale n l)) + _ = exp (∑ l ∈ Finset.range (j+1), C₀ / logb 2 (inductionScale n l)) := + (Real.exp_sum _ _).symm + _ ≤ exp (20*C₀ / logb 2 (inductionScale n j)) := Real.exp_le_exp.mpr hsum + _ ≤ 1 + 2*(20*C₀ / logb 2 (inductionScale n j)) := by + apply exp_le_one_add_twice (div_nonneg (by positivity) hL.le) + apply (div_le_iff₀ hL).mpr + linarith + _ = _ := by ring + +theorem scale_prefix_cycle_cost (n : ℝ) (hn : 1 < n) (j : ℕ) (A : ℕ → ℝ) + (hA : ∀ l ∈ Finset.range (j+1), A l ≤ 2*n) + (hscale : ∀ l ∈ Finset.range (j+1), + 1 / (inductionScale n l) ^ (1/100 : ℝ) ≤ 1 / logb 2 (inductionScale n l)) : + (∑ l ∈ Finset.range (j+1), A l / (2*(inductionScale n l) ^ (1/100 : ℝ))) ≤ + 20*n / logb 2 (inductionScale n j) := by + have hn0 : 0 < n := by linarith + calc + _ ≤ ∑ l ∈ Finset.range (j+1), n * (1 / logb 2 (inductionScale n l)) := by + apply Finset.sum_le_sum + intro l hl + have hp : 0 < (inductionScale n l) ^ (1/100 : ℝ) := + Real.rpow_pos_of_pos (inductionScale_pos n hn0 l) _ + calc + _ ≤ 2*n / (2*(inductionScale n l) ^ (1/100 : ℝ)) := + div_le_div_of_nonneg_right (hA l hl) (by positivity) + _ = n * (1 / (inductionScale n l) ^ (1/100 : ℝ)) := by ring + _ ≤ _ := mul_le_mul_of_nonneg_left (hscale l hl) hn0.le + _ = n * (∑ l ∈ Finset.range (j+1), 1 / logb 2 (inductionScale n l)) := + (Finset.mul_sum _ _ _).symm + _ ≤ n * (20 / logb 2 (inductionScale n j)) := + mul_le_mul_of_nonneg_left (scale_reciprocal_log_sum n hn j) hn0.le + _ = _ := by ring + +end +end ErdosGallai.Scale + +namespace ErdosGallai.Scale +noncomputable section +open Finset SimpleGraph Real +attribute [local instance] Classical.propDecidable + +variable {V : Type} [Fintype V] [DecidableEq V] + +structure StageSplit (P : AssignedPiece V) where + cycles : List (SimpleGraph V) + boxes : List (AssignedPiece V) + pieces : AssignedPiece V → List (AssignedPiece V) + remainder : AssignedPiece V → SimpleGraph V + cycles_good : ∀ K ∈ cycles, IsCycleGraph K + box_subset : ∀ B ∈ boxes, B.vertices ⊆ P.vertices + box_nonempty : P.vertices.Nonempty → ∀ B ∈ boxes, B.vertices.Nonempty + box_cover : ∀ v ∈ P.vertices, ∃ B ∈ boxes, v ∈ B.vertices + piece_subset : ∀ B ∈ boxes, ∀ R ∈ pieces B, R.vertices ⊆ B.vertices + piece_disjoint : ∀ B ∈ boxes, (pieces B).Pairwise fun R S => Disjoint R.vertices S.vertices + remainder_supported : ∀ B ∈ boxes, SupportedOn (remainder B) B.vertices + box_partition : ∀ B ∈ boxes, GraphPartition B.graph (remainder B :: (pieces B).map AssignedPiece.graph) + partition : GraphPartition P.graph (cycles ++ boxes.map AssignedPiece.graph) + +def StageSplit.Bounded {P : AssignedPiece V} (s : StageSplit P) (D : ℝ) : Prop := + (s.cycles.length:ℝ) ≤ P.vertices.card / (2*D^(1/100:ℝ)) ∧ + (s.boxes.map (fun B => (B.vertices.card:ℝ))).sum ≤ (1+2/logb 2 D)*P.vertices.card ∧ + (∀ B ∈ s.boxes, (B.vertices.card:ℝ) ≤ D^(51/50:ℝ)) ∧ + (∀ B ∈ s.boxes, ∀ R ∈ s.pieces B, + D^(9/10:ℝ) ≤ (R.vertices.card:ℝ) ∧ (R.vertices.card:ℝ) ≤ D^(51/50:ℝ) ∧ + CutExpansionOn R.graph R.vertices (D^(9/10:ℝ))) ∧ + (∀ B ∈ s.boxes, 2*(edgeCount (s.remainder B):ℝ)/B.vertices.card ≤ D^(19/20:ℝ)) + +def StageSplit.trivial (P : AssignedPiece V) : StageSplit P where + cycles := [] + boxes := [P] + pieces := fun _ => [] + remainder := AssignedPiece.graph + cycles_good := by simp + box_subset := by simp + box_nonempty := by simp + box_cover := by intro v hv; exact ⟨P,by simp,hv⟩ + piece_subset := by simp + piece_disjoint := by simp + remainder_supported := fun B _ => B.supported + box_partition := by intro B _ x y; simp + partition := by intro x y; simp + +theorem scale_splitter : ∃ Dsp : ℝ, ∀ (V : Type) [Fintype V] [DecidableEq V], + ∃ split : ∀ (_D : ℝ) (P : AssignedPiece V), StageSplit P, + ∀ D ≥ Dsp, ∀ P, P.vertices.Nonempty → + 2*(edgeCount P.graph:ℝ)/P.vertices.card ≤ D → (split D P).Bounded D := by + obtain ⟨Dsp,hsp⟩ := scale_split + refine ⟨Dsp,?_⟩ + intro V _ _ + have hex (D : ℝ) (P : AssignedPiece V) : ∃ s : StageSplit P, + Dsp ≤ D → P.vertices.Nonempty → 2*(edgeCount P.graph:ℝ)/P.vertices.card ≤ D → s.Bounded D := by + by_cases h : Dsp ≤ D ∧ P.vertices.Nonempty ∧ 2*(edgeCount P.graph:ℝ)/P.vertices.card ≤ D + · obtain ⟨C,L,R,H,hC,hCl,hL,hcover,horder,hR,hpart⟩ := + hsp D h.1 V P.graph P.vertices h.2.1 P.supported h.2.2 + have hpart' : GraphPartition P.graph (C ++ L.map AssignedPiece.graph) := by + intro x y + rw [edgeOccurrences_append, ← edgeOccurrences_refine L AssignedPiece.graph + (fun B => H B :: (R B).map AssignedPiece.graph) (fun B hB => (hR B hB).2.2.1)] + simpa only [edgeOccurrences_append] using hpart x y + let s : StageSplit P := { + cycles := C, boxes := L, pieces := R, remainder := H + cycles_good := fun K hK => (hC K hK).1 + box_subset := fun B hB => (hL B hB).1 + box_nonempty := fun _ B hB => (hL B hB).2.1 + box_cover := hcover + piece_subset := fun B hB Q hQ => (hR B hB).1 Q hQ |>.1 + piece_disjoint := fun B hB => (hR B hB).2.1 + remainder_supported := fun B hB => (hR B hB).2.2.2.1 + box_partition := fun B hB => (hR B hB).2.2.1 + partition := hpart' } + refine ⟨s,fun _ _ _ => ⟨hCl,horder,fun B hB => (hL B hB).2.2,?_,?_⟩⟩ + · exact fun B hB Q hQ => (hR B hB).1 Q hQ |>.2 + · exact fun B hB => (hR B hB).2.2.2.2 + · exact ⟨StageSplit.trivial P,fun hD hP hdeg => False.elim (h ⟨hD,hP,hdeg⟩)⟩ + choose s hs using hex + exact ⟨s,fun D hD P hP hdeg => hs D P hD hP hdeg⟩ + +def StageSplit.children {P : AssignedPiece V} (s : StageSplit P) : List (AssignedPiece V) := + s.boxes.pmap (fun B hB => ⟨B.vertices,s.remainder B,s.remainder_supported B hB⟩) (fun _ h => h) + +lemma StageSplit.mem_children {V : Type} [_contextInstance1 : Fintype V] [_contextInstance2 : DecidableEq V] {P : AssignedPiece V} (s : StageSplit P) (Q : AssignedPiece V) : + Q ∈ s.children ↔ ∃ B ∈ s.boxes, Q.vertices = B.vertices ∧ Q.graph = s.remainder B := by + simp only [StageSplit.children, List.mem_pmap] + constructor + · rintro ⟨B,hB,rfl⟩; exact ⟨B,hB,rfl,rfl⟩ + · rintro ⟨B,hB,hv,hg⟩ + refine ⟨B,hB,?_⟩ + cases Q; cases B; simp_all + +lemma StageSplit.children_map {V : Type} [_contextInstance1 : Fintype V] [_contextInstance2 : DecidableEq V] {P : AssignedPiece V} (s : StageSplit P) + {α : Type cycleUniverse4} (f : Finset V → SimpleGraph V → α) : + s.children.map (fun Q => f Q.vertices Q.graph) = + s.boxes.map (fun B => f B.vertices (s.remainder B)) := by + unfold StageSplit.children + rw [List.map_pmap] + change List.pmap (fun B (_ : B ∈ s.boxes) => f B.vertices (s.remainder B)) s.boxes _ = _ + exact List.pmap_eq_map (fun B (h : B ∈ s.boxes) => h) + +lemma list_disjoint_card_le {V : Type} [_contextInstance1 : Fintype V] [_contextInstance2 : DecidableEq V] (L : List (Finset V)) (A : Finset V) + (hd : L.Pairwise Disjoint) (hA : ∀ B ∈ L, B ⊆ A) : + (L.map Finset.card).sum ≤ A.card := by + induction L generalizing A with + | nil => simp + | cons B L ih => + obtain ⟨hBL,hd⟩ := List.pairwise_cons.mp hd + have hBA := hA B (by simp) + have hLA : ∀ C ∈ L, C ⊆ A \ B := by + intro C hC v hv + exact Finset.mem_sdiff.mpr ⟨hA C (by simp [hC]) hv, + fun hb => Finset.disjoint_left.mp (hBL C hC) hb hv⟩ + have hh := ih (A \ B) hd hLA + have hc := Finset.card_sdiff_of_subset hBA + have hBAcard := Finset.card_le_card hBA + simp only [List.map_cons,List.sum_cons] + omega + +def vertexMass (L : List (AssignedPiece V)) : ℝ := + (L.map (fun P => (P.vertices.card:ℝ))).sum + +lemma vertexMass_nonneg {V : Type} [_contextInstance1 : Fintype V] [_contextInstance2 : DecidableEq V] (L : List (AssignedPiece V)) : 0 ≤ vertexMass L := + List.sum_nonneg (fun x hx => by obtain ⟨P,_,rfl⟩ := List.mem_map.mp hx; positivity) + +@[simp] lemma vertexMass_nil {V : Type} [_contextInstance1 : Fintype V] [_contextInstance2 : DecidableEq V] : vertexMass ([] : List (AssignedPiece V)) = 0 := rfl +@[simp] lemma vertexMass_cons {V : Type} [_contextInstance1 : Fintype V] [_contextInstance2 : DecidableEq V] (P : AssignedPiece V) (L) : + vertexMass (P::L) = P.vertices.card + vertexMass L := rfl +@[simp] lemma vertexMass_append {V : Type} [_contextInstance1 : Fintype V] [_contextInstance2 : DecidableEq V] (L M : List (AssignedPiece V)) : + vertexMass (L++M) = vertexMass L + vertexMass M := by simp [vertexMass] +lemma vertexMass_flatMap {I : Type cycleUniverse5} (L : List I) (f : I → List (AssignedPiece V)) : + vertexMass (L.flatMap f) = (L.map (fun i => vertexMass (f i))).sum := by + induction L with + | nil => simp + | cons i L ih => simp [ih] + +lemma StageSplit.children_mass {P : AssignedPiece V} (s : StageSplit P) : + vertexMass s.children = vertexMass s.boxes := by + unfold vertexMass + rw [s.children_map (fun A _ => (A.card:ℝ))] + +lemma StageSplit.pieces_mass {P : AssignedPiece V} (s : StageSplit P) {B : AssignedPiece V} + (hB : B ∈ s.boxes) : vertexMass (s.pieces B) ≤ B.vertices.card := by + have hh := list_disjoint_card_le ((s.pieces B).map AssignedPiece.vertices) B.vertices + (List.pairwise_map.mpr (s.piece_disjoint B hB)) (by + intro A hA; obtain ⟨Q,hQ,rfl⟩ := List.mem_map.mp hA + exact s.piece_subset B hB Q hQ) + simpa [vertexMass,List.map_map,Function.comp_def] using (Nat.cast_le.mpr hh : (_:ℝ) ≤ _) + +end +end ErdosGallai.Scale + +namespace ErdosGallai.Scale +noncomputable section +open Finset SimpleGraph Real +attribute [local instance] Classical.propDecidable +variable {V : Type} [Fintype V] [DecidableEq V] + +abbrev SplitSystem (V : Type) [Fintype V] [DecidableEq V] := + ℕ → (P : AssignedPiece V) → StageSplit P + +def nextLayer (s : SplitSystem V) (j : ℕ) (L : List (AssignedPiece V)) : List (AssignedPiece V) := + L.flatMap fun P => (s j P).children + +def advance (s : SplitSystem V) (j : ℕ) : ℕ → List (AssignedPiece V) → List (AssignedPiece V) + | 0,L => L + | k+1,L => nextLayer s (j+k) (advance s j k L) + +@[simp] lemma advance_zero (s : SplitSystem V) (j) (L) : advance s j 0 L = L := rfl +@[simp] lemma advance_succ (s : SplitSystem V) (j k) (L) : + advance s j (k+1) L = nextLayer s (j+k) (advance s j k L) := rfl + +lemma advance_add (s : SplitSystem V) (j k l) (L) : + advance s j (k+l) L = advance s (j+k) l (advance s j k L) := by + induction l with + | zero => simp + | succ l ih => simp only [Nat.add_succ,advance_succ,ih,Nat.add_assoc] + +lemma advance_flatMap (s : SplitSystem V) (j k) {I : Type cycleUniverse6} + (L : List I) (f : I → List (AssignedPiece V)) : + advance s j k (L.flatMap f) = L.flatMap (fun i => advance s j k (f i)) := by + induction k with + | zero => rfl + | succ k ih => simp only [advance_succ,nextLayer,ih,List.flatMap_assoc] + +lemma nextLayer_mem (s : SplitSystem V) (j) (L) (Q : AssignedPiece V) : + Q ∈ nextLayer s j L ↔ ∃ P ∈ L, ∃ B ∈ (s j P).boxes, + Q.vertices = B.vertices ∧ Q.graph = (s j P).remainder B := by + simp only [nextLayer,List.mem_flatMap,StageSplit.mem_children] + +lemma advance_subset (s : SplitSystem V) (j k) (L) (A : Finset V) + (hA : ∀ P ∈ L, P.vertices ⊆ A) : + ∀ Q ∈ advance s j k L, Q.vertices ⊆ A := by + induction k with + | zero => exact hA + | succ k ih => + intro Q hQ + obtain ⟨P,hP,B,hB,hv,_⟩ := (nextLayer_mem s (j+k) _ Q).mp hQ + rw [hv] + exact ((s (j+k) P).box_subset B hB).trans (ih P hP) + +lemma advance_nonempty (s : SplitSystem V) (j k) (L) + (hL : ∀ P ∈ L, P.vertices.Nonempty) : + ∀ Q ∈ advance s j k L, Q.vertices.Nonempty := by + induction k with + | zero => exact hL + | succ k ih => + intro Q hQ + obtain ⟨P,hP,B,hB,hv,_⟩ := (nextLayer_mem s (j+k) _ Q).mp hQ + rw [hv] + exact (s (j+k) P).box_nonempty (ih P hP) B hB + +lemma advance_cover (s : SplitSystem V) (j k) (L) (P : AssignedPiece V) (hP : P ∈ L) + (v : V) (hv : v ∈ P.vertices) : ∃ Q ∈ advance s j k L, v ∈ Q.vertices := by + induction k with + | zero => exact ⟨P,hP,hv⟩ + | succ k ih => + obtain ⟨Q,hQ,hvQ⟩ := ih + obtain ⟨B,hB,hvB⟩ := (s (j+k) Q).box_cover v hvQ + let T : AssignedPiece V := ⟨B.vertices,(s (j+k) Q).remainder B, + (s (j+k) Q).remainder_supported B hB⟩ + exact ⟨T,(nextLayer_mem s (j+k) _ T).mpr ⟨Q,hQ,B,hB,rfl,rfl⟩,hvB⟩ + +lemma list_union_mem {V : Type} [_contextInstance1 : Fintype V] [_contextInstance2 : DecidableEq V] (L : List (AssignedPiece V)) (v : V) : + v ∈ L.foldr (fun (P : AssignedPiece V) (U : Finset V) => P.vertices ∪ U) ∅ ↔ ∃ P ∈ L, v ∈ P.vertices := by + induction L with + | nil => simp + | cons P L ih => + simp only [List.foldr_cons,Finset.mem_union,ih,List.mem_cons] + aesop + +lemma list_union_card {V : Type} [_contextInstance1 : Fintype V] [_contextInstance2 : DecidableEq V] (L : List (AssignedPiece V)) : + ((L.foldr (fun (P : AssignedPiece V) (U : Finset V) => P.vertices ∪ U) ∅).card:ℝ) ≤ vertexMass L := by + induction L with + | nil => simp + | cons P L ih => + simp only [List.foldr_cons,vertexMass_cons] + have hc := Finset.card_union_le P.vertices (L.foldr (fun (P : AssignedPiece V) (U : Finset V) => P.vertices ∪ U) ∅) + have hc' : ((P.vertices ∪ L.foldr (fun (P : AssignedPiece V) (U : Finset V) => P.vertices ∪ U) ∅).card:ℝ) ≤ + P.vertices.card + (L.foldr (fun (P : AssignedPiece V) (U : Finset V) => P.vertices ∪ U) ∅).card := by exact_mod_cast hc + linarith + +lemma list_cover_card_le (L : List (AssignedPiece V)) (A : Finset V) + (hcover : ∀ v ∈ A, ∃ P ∈ L, v ∈ P.vertices) : (A.card:ℝ) ≤ vertexMass L := by + have hsub : A ⊆ L.foldr (fun (P : AssignedPiece V) (U : Finset V) => P.vertices ∪ U) ∅ := + fun v hv => (list_union_mem L v).mpr (hcover v hv) + exact (Nat.cast_le.mpr (Finset.card_le_card hsub)).trans (list_union_card L) + +lemma advance_mass_lower (s : SplitSystem V) (j k) (P : AssignedPiece V) : + (P.vertices.card:ℝ) ≤ vertexMass (advance s j k [P]) := + list_cover_card_le _ _ (fun v hv => advance_cover s j k [P] P (by simp) v hv) + +lemma nextLayer_mass_bound (s : SplitSystem V) (j) (L : List (AssignedPiece V)) (D : ℝ) + (hb : ∀ P ∈ L, (s j P).Bounded D) : + vertexMass (nextLayer s j L) ≤ (1+2/logb 2 D)*vertexMass L := by + induction L with + | nil => simp [nextLayer] + | cons P L ih => + have hP := (hb P (by simp)).2.1 + have hL := ih (fun Q hQ => hb Q (by simp [hQ])) + simp only [nextLayer,List.flatMap_cons,vertexMass_append,StageSplit.children_mass, + vertexMass_cons] at hL ⊢ + change vertexMass (s j P).boxes ≤ _ at hP + nlinarith + +lemma advance_valid (s : SplitSystem V) (n Dstar : ℝ) (hn : 0 ≤ n) + (hs : ∀ l P, Dstar ≤ inductionScale n l → P.vertices.Nonempty → + 2*(edgeCount P.graph:ℝ)/P.vertices.card ≤ inductionScale n l → + (s l P).Bounded (inductionScale n l)) + (j k : ℕ) (L : List (AssignedPiece V)) + (hL : ∀ P ∈ L, P.vertices.Nonempty) + (hdeg : ∀ P ∈ L, 2*(edgeCount P.graph:ℝ)/P.vertices.card ≤ inductionScale n j) + (hcut : ∀ l, j ≤ l → l < j+k → Dstar ≤ inductionScale n l) : + ∀ P ∈ advance s j k L, + 2*(edgeCount P.graph:ℝ)/P.vertices.card ≤ inductionScale n (j+k) := by + induction k with + | zero => simpa using hdeg + | succ k ih => + intro Q hQ + obtain ⟨P,hP,B,hB,hv,hg⟩ := (nextLayer_mem s (j+k) _ Q).mp hQ + have hPdeg := ih (fun l hlj hl => hcut l hlj (by omega)) P hP + have hb := hs (j+k) P (hcut (j+k) (by omega) (by omega)) + (advance_nonempty s j k L hL P hP) hPdeg + rw [hv,hg,show j+(k+1) = (j+k)+1 by omega,inductionScale_succ n hn] + exact hb.2.2.2.2 B hB + +lemma advance_bounded (s : SplitSystem V) (n Dstar : ℝ) (hn : 0 ≤ n) + (hs : ∀ l P, Dstar ≤ inductionScale n l → P.vertices.Nonempty → + 2*(edgeCount P.graph:ℝ)/P.vertices.card ≤ inductionScale n l → + (s l P).Bounded (inductionScale n l)) + (j k : ℕ) (L : List (AssignedPiece V)) + (hL : ∀ P ∈ L, P.vertices.Nonempty) + (hdeg : ∀ P ∈ L, 2*(edgeCount P.graph:ℝ)/P.vertices.card ≤ inductionScale n j) + (hcut : ∀ l, j ≤ l → l ≤ j+k → Dstar ≤ inductionScale n l) : + ∀ P ∈ advance s j k L, (s (j+k) P).Bounded (inductionScale n (j+k)) := by + intro P hP + exact hs (j+k) P (hcut _ (by omega) (by omega)) (advance_nonempty s j k L hL P hP) + (advance_valid s n Dstar hn hs j k L hL hdeg (fun l hlj hl => hcut l hlj (by omega)) P hP) + +lemma advance_mass_global_product (s : SplitSystem V) (n : ℝ) (hn : 1 < n) + (j k : ℕ) (L : List (AssignedPiece V)) + (hb : ∀ l < k, ∀ P ∈ advance s j l L, (s (j+l) P).Bounded (inductionScale n (j+l))) : + vertexMass (advance s j k L) ≤ vertexMass L * + ∏ l ∈ Finset.range (j+k), (1+2/logb 2 (inductionScale n l)) := by + have hfac (l) : 1 ≤ 1+2/logb 2 (inductionScale n l) := by + have := div_nonneg (by norm_num : (0:ℝ) ≤ 2) (inductionScale_log_pos n hn l).le + linarith + induction k with + | zero => + simp only [advance_zero,Nat.add_zero] + exact le_mul_of_one_le_right (vertexMass_nonneg L) (Finset.one_le_prod₀ (fun l _ => hfac l)) + | succ k ih => + have hm := nextLayer_mass_bound s (j+k) (advance s j k L) (inductionScale n (j+k)) + (hb k (by omega)) + have hi := mul_le_mul_of_nonneg_left (ih (fun l hl => hb l (by omega))) ((hfac (j+k)).trans' (by norm_num : (0:ℝ) ≤ 1)) + rw [advance_succ,show j+(k+1) = (j+k)+1 by omega,Finset.prod_range_succ] + calc + _ ≤ (1+2/logb 2 (inductionScale n (j+k))) * vertexMass (advance s j k L) := hm + _ ≤ _ := by nlinarith only [hi] + +end +end ErdosGallai.Scale +end +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/CycleDecomposition/Templates.lean b/lean/OAI/Combinatorics/CycleDecomposition/Templates.lean new file mode 100644 index 0000000000000000000000000000000000000000..353ecbd1374cf7610667f876c8f071d78ffa9578 --- /dev/null +++ b/lean/OAI/Combinatorics/CycleDecomposition/Templates.lean @@ -0,0 +1,784 @@ +import OAI.Combinatorics.CycleDecomposition.CycleLifting + +namespace OAI + +universe cycleUniverse1 cycleUniverse2 cycleUniverse3 cycleUniverse4 cycleUniverse5 cycleUniverse6 cycleUniverse7 cycleUniverse8 cycleUniverse9 cycleUniverse10 cycleUniverse11 cycleUniverse12 + +section +open Filter Asymptotics Real +open scoped Topology +noncomputable section +open MeasureTheory ProbabilityTheory Finset +section +namespace ErdosGallai.Batch +noncomputable section +open Finset SimpleGraph +attribute [local instance] Classical.propDecidable + +def demandLoad {I : Type cycleUniverse1} {V : Type cycleUniverse2} [Fintype I] (x y : I → V) (v : V) : ℕ := + (univ.filter fun i => x i = v ∨ y i = v).card + +theorem demand_load_le_degree {V : Type cycleUniverse3} {I : Type cycleUniverse4} {B : Type cycleUniverse5} [Fintype V] [Fintype I] + [DecidableEq V] (G : SimpleGraph V) [DecidableRel G.Adj] + (E : B → Set (Sym2 V)) + (hE : Pairwise fun b c => Disjoint (E b) (E c)) + (owner : I → B) (x y : I → V) + (hunique : ∀ i j v, owner i = owner j → + (x i = v ∨ y i = v) → (x j = v ∨ y j = v) → i = j) + (hedge : ∀ i v, x i = v ∨ y i = v → + ∃ w, G.Adj v w ∧ s(v,w) ∈ E (owner i)) (v : V) : + demandLoad x y v ≤ G.degree v := by + classical + let S := {i : I // x i = v ∨ y i = v} + have hs (i : S) := hedge i.val v i.property + let f : S → G.neighborFinset v := fun i => + ⟨(hs i).choose, by simpa using (hs i).choose_spec.1⟩ + have hf : Function.Injective f := by + intro i j hij + have he : (hs i).choose = (hs j).choose := congrArg Subtype.val hij + apply Subtype.ext + by_cases ho : owner i.val = owner j.val + · exact hunique i.val j.val v ho i.property j.property + · exact False.elim (Set.disjoint_left.mp (hE ho) + (hs i).choose_spec.2 (by rw [he]; exact (hs j).choose_spec.2)) + have hc := Fintype.card_le_of_injective f hf + have hn : Fintype.card (G.neighborFinset v) = G.degree v := by + rw [Fintype.card_coe, SimpleGraph.card_neighborFinset_eq_degree] + rw [hn] at hc + have hcS : Fintype.card S = demandLoad x y v := by + simp only [S, Fintype.card_subtype, demandLoad] + congr 1 + ext i + simp + rw [hcS] at hc + exact hc + +lemma start_has_incident_edge {V : Type cycleUniverse6} {G : SimpleGraph V} {a b : V} + (p : G.Walk a b) (hp : ¬p.Nil) : + ∃ w, G.Adj a w ∧ s(a,w) ∈ p.edgeSet := by + exact ⟨p.snd,p.adj_snd hp,p.mk_start_snd_mem_edges hp⟩ + +lemma finish_has_incident_edge {V : Type cycleUniverse7} {G : SimpleGraph V} {a b : V} + (p : G.Walk a b) (hp : ¬p.Nil) : + ∃ w, G.Adj b w ∧ s(b,w) ∈ p.edgeSet := by + refine ⟨p.penultimate,(p.adj_penultimate hp).symm,?_⟩ + change s(b,p.penultimate) ∈ p.edges + simpa only [Sym2.eq_swap] using p.mk_penultimate_end_mem_edges hp + +theorem path_demands_load_le_degree {V : Type cycleUniverse8} {I : Type cycleUniverse9} [Fintype V] [Fintype I] + [DecidableEq V] (G : SimpleGraph V) [DecidableRel G.Adj] + (x y : I → V) (p : ∀ i, G.Walk (x i) (y i)) + (hpos : ∀ i, ¬(p i).Nil) + (hd : Pairwise fun i j => Disjoint (p i).edgeSet (p j).edgeSet) (v : V) : + demandLoad x y v ≤ G.degree v := by + apply demand_load_le_degree G (fun i => (p i).edgeSet) hd id x y + · intro i j _ hij _ _; exact hij + · intro i w hw + rcases hw with rfl | rfl + · exact start_has_incident_edge (p i) (hpos i) + · exact finish_has_incident_edge (p i) (hpos i) + +lemma disjoint_sum_blocks {α : Type cycleUniverse10} {B : Type cycleUniverse11} {C : Type cycleUniverse12} (E : B → Set α) (F : C → Set α) + (hE : Pairwise fun b c => Disjoint (E b) (E c)) + (hF : Pairwise fun b c => Disjoint (F b) (F c)) + (hEF : ∀ b c, Disjoint (E b) (F c)) : + Pairwise (fun i j : B ⊕ C => Disjoint (Sum.elim E F i) (Sum.elim E F j)) := by + intro i j hij + cases i with + | inl b => + cases j with + | inl c => exact hE (fun he => hij (congrArg Sum.inl he)) + | inr c => exact hEF b c + | inr b => + cases j with + | inl c => exact (hEF c b).symm + | inr c => exact hF (fun he => hij (congrArg Sum.inr he)) + +end +end ErdosGallai.Batch + +namespace ErdosGallai.Batch + +def CycleOrSingleEdge {V : Type} (G : SimpleGraph V) + (s : Set (Sym2 V)) : Prop := + (∃ (v : V) (p : G.Walk v v), p.IsCycle ∧ s = p.edgeSet) ∨ + ∃ e ∈ G.edgeSet, s = {e} + +def EdgeDecomposition {V : Type} (G : SimpleGraph V) (k : ℕ) : Prop := + ∃ parts : Fin k → Set (Sym2 V), + (∀ i, CycleOrSingleEdge G (parts i)) ∧ + Pairwise (fun i j => Disjoint (parts i) (parts j)) ∧ + (⋃ i, parts i) = G.edgeSet + +noncomputable section +open SimpleGraph + +lemma cycleOrSingleEdge_subset {V : Type} {G : SimpleGraph V} + {s : Set (Sym2 V)} (hs : CycleOrSingleEdge G s) : s ⊆ G.edgeSet := by + rcases hs with ⟨v,p,hp,rfl⟩ | ⟨e,he,rfl⟩ + · exact p.edges_subset_edgeSet + · simpa using he + +lemma cycleOrSingleEdge_map {V W : Type} {G : SimpleGraph V} {H : SimpleGraph W} + (f : G →g H) (hf : Function.Injective f) {s : Set (Sym2 V)} + (hs : CycleOrSingleEdge G s) : CycleOrSingleEdge H (Sym2.map f '' s) := by + rcases hs with ⟨v,p,hp,rfl⟩ | ⟨e,he,rfl⟩ + · exact Or.inl ⟨f v,p.map f,hp.map hf,(p.edgeSet_map f).symm⟩ + · refine Or.inr ⟨Sym2.map f e, ?_, by simp⟩ + induction e using Sym2.ind with | _ x y => + exact f.map_adj he + +lemma edgeDecomposition_of_indexed {V I : Type} [Fintype I] (G : SimpleGraph V) + (parts : I → Set (Sym2 V)) (hp : ∀ i, CycleOrSingleEdge G (parts i)) + (hd : Pairwise (fun i j => Disjoint (parts i) (parts j))) + (hu : (⋃ i, parts i) = G.edgeSet) : EdgeDecomposition G (Fintype.card I) := by + let e := Fintype.equivFin I + refine ⟨fun j => parts (e.symm j), fun j => hp _, ?_, ?_⟩ + · intro i j hij + exact hd (fun he => hij (e.symm.injective he)) + · ext x + simp only [Set.mem_iUnion] + rw [← hu] + simp only [Set.mem_iUnion] + constructor + · rintro ⟨i,hi⟩; exact ⟨e.symm i,hi⟩ + · rintro ⟨i,hi⟩; exact ⟨e i, by simpa using hi⟩ + +theorem edgeDecomposition_singleEdges {V : Type} [Fintype V] (G : SimpleGraph V) : + EdgeDecomposition G (Nat.card G.edgeSet) := by + classical + let : Fintype G.edgeSet := Fintype.ofFinite _ + rw [Nat.card_eq_fintype_card] + apply edgeDecomposition_of_indexed G (fun e : G.edgeSet => {e.1}) + · intro e; exact Or.inr ⟨e.1,e.2,rfl⟩ + · intro e d hed + exact Set.disjoint_singleton.mpr (fun h => hed (Subtype.ext h)) + · ext e; simp + +theorem edgeDecomposition_assemble {V I : Type} [Fintype I] (G : SimpleGraph V) + (W : I → Type) (H : ∀ i, SimpleGraph (W i)) + (f : ∀ i, H i →g G) (hf : ∀ i, Function.Injective (f i)) + (hdisj : Pairwise (fun i j => + Disjoint (Sym2.map (f i) '' (H i).edgeSet) (Sym2.map (f j) '' (H j).edgeSet))) + (hcover : (⋃ i, Sym2.map (f i) '' (H i).edgeSet) = G.edgeSet) + (k : I → ℕ) (hparts : ∀ i, EdgeDecomposition (H i) (k i)) : + EdgeDecomposition G (∑ i, k i) := by + classical + choose parts hp hd hu using hparts + let J := Σ i, Fin (k i) + let P : J → Set (Sym2 V) := fun j => Sym2.map (f j.1) '' parts j.1 j.2 + have hpart : ∀ j, CycleOrSingleEdge G (P j) := by + intro j; exact cycleOrSingleEdge_map (f j.1) (hf j.1) (hp j.1 j.2) + have hsub : ∀ i a, parts i a ⊆ (H i).edgeSet := by + intro i a; exact cycleOrSingleEdge_subset (hp i a) + have hdisjP : Pairwise (fun i j => Disjoint (P i) (P j)) := by + rintro ⟨i,a⟩ ⟨j,b⟩ hij + by_cases h : i = j + · subst j + have hab : a ≠ b := fun he => hij (by cases he; rfl) + apply Set.disjoint_left.mpr + rintro e ⟨x,hx,he⟩ ⟨y,hy,he'⟩ + have hxy : x = y := Sym2.map.injective (hf i) (he.trans he'.symm) + subst y + exact Set.disjoint_left.mp (hd i hab) hx hy + · exact (hdisj h).mono (Set.image_mono (hsub i a)) (Set.image_mono (hsub j b)) + have hcoverP : (⋃ j, P j) = G.edgeSet := by + rw [← hcover] + ext e + simp only [Set.mem_iUnion] + constructor + · rintro ⟨⟨i,a⟩,x,hx,he⟩ + exact ⟨i,x,hsub i a hx,he⟩ + · rintro ⟨i,x,hx,he⟩ + rw [← hu i] at hx + obtain ⟨a,ha⟩ := Set.mem_iUnion.mp hx + exact ⟨⟨i,a⟩,x,ha,he⟩ + have hc : Fintype.card J = ∑ i, k i := by simp [J, Fintype.card_sigma] + rw [← hc] + exact edgeDecomposition_of_indexed G P hpart hdisjP hcoverP + +end +end ErdosGallai.Batch + +namespace ErdosGallai.Batch +noncomputable section +open SimpleGraph Finset +attribute [local instance] Classical.propDecidable + +def decompositionCost {V : Type} [Fintype V] (G : SimpleGraph V) : ℕ := + Nat.find (show ∃ k, EdgeDecomposition G k from ⟨_,edgeDecomposition_singleEdges G⟩) + +lemma decompositionCost_spec {V : Type} [Fintype V] (G : SimpleGraph V) : + EdgeDecomposition G (decompositionCost G) := Nat.find_spec _ + +lemma decompositionCost_le {V : Type} [Fintype V] {G : SimpleGraph V} {k : ℕ} + (h : EdgeDecomposition G k) : decompositionCost G ≤ k := Nat.find_min' _ h + +lemma decompositionCost_singleEdges {V : Type} [Fintype V] (G : SimpleGraph V) : + decompositionCost G ≤ Nat.card G.edgeSet := decompositionCost_le (edgeDecomposition_singleEdges G) + +theorem edgeDecomposition_adjoin {V I J : Type} [Fintype I] [Fintype J] + (G : SimpleGraph V) (parts : I → Set (Sym2 V)) + (hp : ∀ i, CycleOrSingleEdge G (parts i)) + (hd : Pairwise fun i j => Disjoint (parts i) (parts j)) + (W : J → Type) (H : ∀ j, SimpleGraph (W j)) (f : ∀ j, H j →g G) + (hf : ∀ j, Function.Injective (f j)) + (hHH : Pairwise fun i j => Disjoint (Sym2.map (f i) '' (H i).edgeSet) + (Sym2.map (f j) '' (H j).edgeSet)) + (hHP : ∀ j i, Disjoint (Sym2.map (f j) '' (H j).edgeSet) (parts i)) + (hu : (⋃ i, parts i) ∪ (⋃ j, Sym2.map (f j) '' (H j).edgeSet) = G.edgeSet) + (k : J → ℕ) (hD : ∀ j, EdgeDecomposition (H j) (k j)) : + EdgeDecomposition G (Fintype.card I + ∑ j, k j) := by + classical + choose P hP hPd hPc using hD + let R : (I ⊕ Σ j, Fin (k j)) → Set (Sym2 V) := + Sum.elim parts (fun z => Sym2.map (f z.1) '' P z.1 z.2) + have hsub : ∀ j i, P j i ⊆ (H j).edgeSet := fun j i => cycleOrSingleEdge_subset (hP j i) + have hRp : ∀ z, CycleOrSingleEdge G (R z) := by + intro z + rcases z with z | ⟨j,i⟩ + · exact hp z + · exact cycleOrSingleEdge_map (f j) (hf j) (hP j i) + have hRd : Pairwise fun z t => Disjoint (R z) (R t) := by + intro z t hzt + rcases z with z | ⟨j,i⟩ <;> rcases t with t | ⟨l,a⟩ + · exact hd (fun h => hzt (congrArg Sum.inl h)) + · exact ((hHP l z).mono_left (Set.image_mono (hsub l a))).symm + · exact (hHP j t).mono_left (Set.image_mono (hsub j i)) + · by_cases hjl : j = l + · subst l + have hia : i ≠ a := fun h => hzt (by cases h; rfl) + apply Set.disjoint_left.mpr + rintro e ⟨x,hx,he⟩ ⟨y,hy,he'⟩ + have hxy := Sym2.map.injective (hf j) (he.trans he'.symm) + subst y + exact Set.disjoint_left.mp (hPd j hia) hx hy + · exact (hHH hjl).mono (Set.image_mono (hsub j i)) (Set.image_mono (hsub l a)) + have hRu : (⋃ z, R z) = G.edgeSet := by + rw [← hu] + ext e + simp only [Set.mem_iUnion, Set.mem_union] + constructor + · rintro ⟨z,hz⟩ + rcases z with z | ⟨j,i⟩ + · exact Or.inl ⟨z,hz⟩ + · obtain ⟨x,hx,he⟩ := hz + exact Or.inr ⟨j,x,hsub j i hx,he⟩ + · rintro (⟨i,hi⟩ | ⟨j,x,hx,he⟩) + · exact ⟨Sum.inl i,hi⟩ + · rw [← hPc j] at hx + obtain ⟨i,hi⟩ := Set.mem_iUnion.mp hx + exact ⟨Sum.inr ⟨j,i⟩,x,hi,he⟩ + simpa only [Fintype.card_sum,Fintype.card_sigma,Fintype.card_fin] using + edgeDecomposition_of_indexed G R hRp hRd hRu + +lemma decompositionCost_adjoin {V I J : Type} [Fintype V] [Fintype I] [Fintype J] + (G : SimpleGraph V) (parts : I → Set (Sym2 V)) + (hp : ∀ i, CycleOrSingleEdge G (parts i)) + (hd : Pairwise fun i j => Disjoint (parts i) (parts j)) + (W : J → Type) [∀ j, Fintype (W j)] (H : ∀ j, SimpleGraph (W j)) + (f : ∀ j, H j →g G) (hf : ∀ j, Function.Injective (f j)) + (hHH : Pairwise fun i j => Disjoint (Sym2.map (f i) '' (H i).edgeSet) + (Sym2.map (f j) '' (H j).edgeSet)) + (hHP : ∀ j i, Disjoint (Sym2.map (f j) '' (H j).edgeSet) (parts i)) + (hu : (⋃ i, parts i) ∪ (⋃ j, Sym2.map (f j) '' (H j).edgeSet) = G.edgeSet) : + decompositionCost G ≤ Fintype.card I + ∑ j, decompositionCost (H j) := + decompositionCost_le (edgeDecomposition_adjoin G parts hp hd W H f hf hHH hHP hu _ + (fun j => decompositionCost_spec (H j))) + +end +end ErdosGallai.Batch +namespace ErdosGallai.Batch +noncomputable section +open SimpleGraph Finset +attribute [local instance] Classical.propDecidable + +lemma edgeDecomposition_map {V W : Type} {G : SimpleGraph V} {H : SimpleGraph W} + (f : H →g G) (hf : Function.Injective f) + (hu : Sym2.map f '' H.edgeSet = G.edgeSet) {k : ℕ} (hk : EdgeDecomposition H k) : + EdgeDecomposition G k := by + have := edgeDecomposition_assemble (I := Unit) G (fun _ : Unit => W) (fun _ => H) (fun _ => f) + (fun _ => hf) (by intro i j hij; exact False.elim (hij (Subsingleton.elim _ _))) + (by rw [Set.iUnion_const]; exact hu) (fun _ => k) (fun _ => hk) + simpa using this + +lemma decompositionCost_on {V : Type} [Fintype V] (G : SimpleGraph V) + (A : Finset V) (hA : ∀ ⦃x y⦄, G.Adj x y → x ∈ A ∧ y ∈ A) : + decompositionCost G ≤ decompositionCost (G.induce (A:Set V)) := by + classical + let f : G.induce (A:Set V) →g G := ⟨Subtype.val,fun h => h⟩ + have hu : Sym2.map f '' (G.induce (A:Set V)).edgeSet = G.edgeSet := by + ext e + constructor + · rintro ⟨e,he,rfl⟩ + induction e using Sym2.ind with | _ x y => exact he + · intro he + induction e using Sym2.ind with + | _ x y => + exact ⟨s(⟨x,(hA he).1⟩,⟨y,(hA he).2⟩),he,rfl⟩ + exact decompositionCost_le (edgeDecomposition_map f Subtype.val_injective hu (decompositionCost_spec _)) + +lemma edgeDecomposition_on {V : Type} (G : SimpleGraph V) + (A : Finset V) (hA : ∀ ⦃x y⦄, G.Adj x y → x ∈ A ∧ y ∈ A) + {k : ℕ} (hk : EdgeDecomposition (G.induce (A:Set V)) k) : EdgeDecomposition G k := by + classical + let f : G.induce (A:Set V) →g G := ⟨Subtype.val,fun h => h⟩ + apply edgeDecomposition_map f Subtype.val_injective _ hk + ext e + constructor + · rintro ⟨e,he,rfl⟩ + induction e using Sym2.ind with | _ x y => exact he + · intro he + induction e using Sym2.ind with + | _ x y => exact ⟨s(⟨x,(hA he).1⟩,⟨y,(hA he).2⟩),he,rfl⟩ + +end +end ErdosGallai.Batch + +namespace ErdosGallai.Batch +noncomputable section +open Finset SimpleGraph +attribute [local instance] Classical.propDecidable + +lemma endpointLoad_subtype_le {V I : Type} [Fintype I] + (x y : I → V) (s : I → Prop) (v : V) : + endpointLoad univ (fun i : {i // s i} => x i) (fun i => y i) v ≤ endpointLoad univ x y v := by + classical + simp only [endpointLoad] + apply Finset.card_le_card_of_injOn (fun i : {i // s i} => i.val) + · intro i hi; simpa using hi + · intro i _ j _ h; exact Subtype.ext h + +theorem uniform_multi_batch_routing : + ∃ D₀ : ℝ, 1 < D₀ ∧ ∀ D ≥ D₀, + ∀ (V R I T : Type) [Fintype V] [Fintype R] [Fintype I], + ∀ (G : SimpleGraph V) (P : R → SimpleGraph V) (U : R → Finset V), + (∀ r, P r ≤ G) → Pairwise (fun r s => Disjoint (P r).edgeSet (P s).edgeSet) → + Pairwise (fun r s => Disjoint (U r) (U s)) → + (∀ r, CutExpansionOn (P r) (U r) (D^(9/10:ℝ)/4)) → + (∀ r, D^(9/10:ℝ) ≤ ((U r).card:ℝ) ∧ ((U r).card:ℝ) ≤ D^(51/50:ℝ)) → + ∀ (owner : I → R) (x y : I → V), + (∀ i, x i ∈ U (owner i) ∧ y i ∈ U (owner i) ∧ x i ≠ y i) → + ∀ (team : I → T) (Z : I → Finset V), + (∀ v, (endpointLoad univ x y v:ℝ) ≤ D^(1/100:ℝ)) → + (∀ i, ((univ.filter (fun j => team j = team i)).card:ℝ) ≤ D^(3/10:ℝ)) → + (∀ i, ((Z i).card:ℝ) ≤ 2*D^(3/10:ℝ)) → + ∃ q : ∀ i, G.Walk (x i) (y i), + (∀ i, (q i).IsPath ∧ (∀ v ∈ (q i).support, v ∈ U (owner i)) ∧ + (q i).edgeSet ⊆ (P (owner i)).edgeSet ∧ Disjoint (pathInterior (q i)) (Z i)) ∧ + Pairwise (fun i j => Disjoint (q i).edgeSet (q j).edgeSet) ∧ + (∀ i j, i ≠ j → team i = team j → Disjoint (pathInterior (q i)) (pathInterior (q j))) := by + classical + obtain ⟨D₀,hD₀,hroute⟩ := uniform_batch_routing + refine ⟨D₀,hD₀,?_⟩ + intro D hD V R I T _ _ _ G P U hPG hPP hUU he hr owner x y hxy team Z hl ht hZ + let J := fun r => {i // owner i = r} + have hex : ∀ r, ∃ q : ∀ i : J r, G.Walk (x i) (y i), + (∀ i, (q i).IsPath ∧ (∀ v ∈ (q i).support, v ∈ U r) ∧ + (q i).edgeSet ⊆ (P r).edgeSet ∧ Disjoint (pathInterior (q i)) (Z i)) ∧ + Pairwise (fun i j => Disjoint (q i).edgeSet (q j).edgeSet) ∧ + (∀ i j : J r, i ≠ j → team i = team j → Disjoint (pathInterior (q i)) (pathInterior (q j))) := by + intro r + obtain ⟨q,hq,hd,hi⟩ := hroute D hD V G (P r) (hPG r) (U r) (he r) (hr r).1 (hr r).2 + (J r) T (fun i => x i) (fun i => y i) + (fun i => by simpa only [← i.property] using (hxy i).1) + (fun i => by simpa only [← i.property] using (hxy i).2.1) + (fun i => (hxy i).2.2) (fun i => team i) (fun i => Z i) + (fun v => (show (endpointLoad univ (fun i : J r => x i) (fun i => y i) v:ℝ) ≤ + endpointLoad univ x y v by exact_mod_cast endpointLoad_subtype_le x y (fun i => owner i = r) v).trans (hl v)) + (fun i => le_trans (by + apply Nat.cast_le.mpr + apply Finset.card_le_card_of_injOn (fun i : J r => i.val) + · intro j hj; simpa using hj + · intro j _ l _ h; exact Subtype.ext h) (ht i)) (fun i => hZ i) + exact ⟨q,fun i => ⟨(hq i).1,(hq i).2.2⟩,hd,hi⟩ + choose q hq hd hi using hex + let f : ∀ i, G.Walk (x i) (y i) := fun i => q (owner i) ⟨i,rfl⟩ + have hf (i : I) (r : R) (h : owner i = r) : f i = q r ⟨i,h⟩ := by + subst r; rfl + refine ⟨f,fun i => hq _ _,?_,?_⟩ + · intro i j hij + by_cases hh : owner i = owner j + · have h := hd (owner i) (show (⟨i,rfl⟩:J (owner i)) ≠ ⟨j,hh.symm⟩ from + fun h => hij (congrArg Subtype.val h)) + rw [hf j (owner i) hh.symm] + exact h + · exact (hPP hh).mono (hq _ _).2.2.1 (hq _ _).2.2.1 + · intro i j hij hteam + by_cases hh : owner i = owner j + · have h := hi (owner i) ⟨i,rfl⟩ ⟨j,hh.symm⟩ + (fun h => hij (congrArg Subtype.val h)) hteam + rw [hf j (owner i) hh.symm] + exact h + · apply (hUU hh).mono + · intro v hv; exact (hq (owner i) ⟨i,rfl⟩).2.1 v (List.mem_toFinset.mp (Finset.mem_sdiff.mp hv).1) + · intro v hv; exact (hq (owner j) ⟨j,rfl⟩).2.1 v (List.mem_toFinset.mp (Finset.mem_sdiff.mp hv).1) + +structure CycleOutline {V : Type} (G : SimpleGraph V) where + W : Type + finiteW : Fintype W + Q : SimpleGraph W + base : W + cycle : Q.Walk base base + isCycle : cycle.IsCycle + rep : Q.Dart → G.Dart + start : W → V + finish : W → V + project : V → W + ports : ∀ d ∈ cycle.darts, finish d.fst = (rep d).fst ∧ start d.snd = (rep d).snd + projects : ∀ z ∈ cycle.dropLast.support, project (start z) = z ∧ project (finish z) = z + outside : ∀ z, z ∉ cycle.dropLast.support → start z = finish z +attribute [instance] CycleOutline.finiteW + +namespace CycleOutline +variable {V : Type} {G : SimpleGraph V} (c : CycleOutline G) + +def edges : Set (Sym2 V) := {e | ∃ d ∈ c.cycle.darts, e = (c.rep d).edge} +def vertices : Finset V := c.cycle.darts.toFinset.biUnion fun d => {(c.rep d).fst,(c.rep d).snd} +abbrev Switch := {z : c.W // z ∈ c.cycle.dropLast.support ∧ c.start z ≠ c.finish z} +instance : Fintype c.Switch := inferInstanceAs (Fintype {_z : c.W // _}) + +lemma edges_subset : c.edges ⊆ G.edgeSet := by + rintro e ⟨d,hd,rfl⟩; exact (c.rep d).edge_mem + +lemma fst_mem {d : c.Q.Dart} (hd : d ∈ c.cycle.darts) : d.fst ∈ c.cycle.dropLast.support := by + rw [c.cycle.support_dropLast c.isCycle.not_nil,← Walk.map_fst_darts] + exact List.mem_map.mpr ⟨d,hd,rfl⟩ + +lemma snd_mem {d : c.Q.Dart} (hd : d ∈ c.cycle.darts) : d.snd ∈ c.cycle.dropLast.support := by + rw [c.cycle.support_dropLast c.isCycle.not_nil] + apply c.cycle.tail_support_perm_dropLast_support.mem_iff.mp + rw [← Walk.map_snd_darts] + exact List.mem_map.mpr ⟨d,hd,rfl⟩ + +lemma outgoing (z : c.W) (hz : z ∈ c.cycle.dropLast.support) : + ∃ d ∈ c.cycle.darts, d.fst = z := by + have h : z ∈ c.cycle.darts.map (fun d => d.fst) := by + rw [Walk.map_fst_darts,← c.cycle.support_dropLast c.isCycle.not_nil]; exact hz + exact List.mem_map.mp h + +lemma incoming (z : c.W) (hz : z ∈ c.cycle.dropLast.support) : + ∃ d ∈ c.cycle.darts, d.snd = z := by + have h : z ∈ c.cycle.darts.map (fun d => d.snd) := by + rw [Walk.map_snd_darts] + apply c.cycle.tail_support_perm_dropLast_support.mem_iff.mpr + rw [← c.cycle.support_dropLast c.isCycle.not_nil]; exact hz + exact List.mem_map.mp h + +lemma endpoint_incident (z : c.Switch) (v : V) (hv : c.start z = v ∨ c.finish z = v) : + ∃ w, G.Adj v w ∧ s(v,w) ∈ c.edges := by + rcases hv with rfl | rfl + · obtain ⟨d,hd,he⟩ := c.incoming z z.property.1 + have hh := (c.ports d hd).2 + rw [he] at hh + refine ⟨(c.rep d).fst,?_,?_⟩ + · rw [hh]; exact (c.rep d).adj.symm + · refine ⟨d,hd,?_⟩ + rw [hh]; exact Sym2.eq_swap + · obtain ⟨d,hd,he⟩ := c.outgoing z z.property.1 + have hh := (c.ports d hd).1 + rw [he] at hh + refine ⟨(c.rep d).snd,?_,?_⟩ + · rw [hh]; exact (c.rep d).adj + · refine ⟨d,hd,?_⟩; rw [hh]; rfl + +lemma endpoint_unique (z w : c.Switch) (v : V) + (hz : c.start z = v ∨ c.finish z = v) (hw : c.start w = v ∨ c.finish w = v) : z = w := by + apply Subtype.ext + have hf : ∀ (z : c.Switch), c.start z = v ∨ c.finish z = v → c.project v = z := by + intro z hz + rcases hz with h | h + · rw [← h]; exact (c.projects z z.property.1).1 + · rw [← h]; exact (c.projects z z.property.1).2 + exact (hf z hz).symm.trans (hf w hw) + +lemma vertices_card_support : c.vertices.card ≤ 2 * c.cycle.dropLast.support.toFinset.card := by + have hfirst : c.vertices.card ≤ 2*c.cycle.darts.toFinset.card := by + calc + _ ≤ ∑ d ∈ c.cycle.darts.toFinset, ({(c.rep d).fst,(c.rep d).snd}:Finset V).card := Finset.card_biUnion_le + _ ≤ ∑ d ∈ c.cycle.darts.toFinset, 2 := Finset.sum_le_sum (fun d _ => Finset.card_le_two) + _ = _ := by simp [mul_comm] + have hd : c.cycle.darts.toFinset.card ≤ c.cycle.dropLast.support.toFinset.card := by + calc + _ ≤ c.cycle.darts.length := List.toFinset_card_le _ + _ = c.cycle.dropLast.support.length := by + rw [Walk.length_darts,Walk.length_support,Walk.length_dropLast] + have := c.isCycle.three_le_length; omega + _ = c.cycle.dropLast.support.toFinset.card := (List.toFinset_card_of_nodup c.isCycle.isPath_dropLast.support_nodup).symm + omega + +lemma vertices_card : c.vertices.card ≤ 2 * Fintype.card c.W := + c.vertices_card_support.trans (Nat.mul_le_mul_left _ (Finset.card_le_univ _)) + +lemma mem_vertices (v : V) : v ∈ c.vertices ↔ ∃ d ∈ c.cycle.darts, v = (c.rep d).fst ∨ v = (c.rep d).snd := by + simp [vertices] + +theorem complete [DecidableEq V] + (route : ∀ z : c.Switch, G.Walk (c.start z) (c.finish z)) + (hs : ∀ z, (route z).IsPath) + (ha : ∀ z, Disjoint (pathInterior (route z)) c.vertices) + (hd : Pairwise fun z w => Disjoint (pathInterior (route z)) (pathInterior (route w))) : + ∃ (v : V) (p : G.Walk v v), p.IsCycle ∧ + p.edgeSet = c.edges ∪ ⋃ z, (route z).edgeSet := by + classical + let visits : ∀ z, G.Walk (c.start z) (c.finish z) := fun z => + if h : z ∈ c.cycle.dropLast.support ∧ c.start z ≠ c.finish z then route ⟨z,h⟩ + else (Walk.nil : G.Walk (c.start z) (c.start z)).copy rfl (by + by_cases hz : z ∈ c.cycle.dropLast.support + · exact not_not.mp (fun hn => h ⟨hz,hn⟩) + · exact c.outside z hz) + have hv (z : c.Switch) : visits z = route z := by simp only [visits,dite_eq_left z.property] + have hnil (z : c.W) (hz : ¬(z ∈ c.cycle.dropLast.support ∧ c.start z ≠ c.finish z)) : + (visits z).Nil := by simp only [visits,dite_eq_right hz,Walk.nil_copy,Walk.nil_nil] + have hpath : ∀ z, (visits z).IsPath := by + intro z + by_cases hz : z ∈ c.cycle.dropLast.support ∧ c.start z ≠ c.finish z + · simpa only [visits,dite_eq_left hz] using hs ⟨z,hz⟩ + · simp [visits,dite_eq_right hz] + have hinter (z : c.W) : visitInterior c.start c.finish visits z = (pathInterior (visits z):Set V) := by + ext v; simp [visitInterior,pathInterior] + have h_avoid : ∀ z ∈ c.cycle.dropLast.support, Disjoint + (visitInterior c.start c.finish visits z) {v | ∃ d ∈ c.cycle.darts, v = (c.rep d).fst ∨ v = (c.rep d).snd} := by + intro z hz + rw [hinter] + have he : {v | ∃ d ∈ c.cycle.darts, v = (c.rep d).fst ∨ v = (c.rep d).snd} = (c.vertices:Set V) := by + ext v; exact (c.mem_vertices v).symm + rw [he,Finset.disjoint_coe] + by_cases hne : c.start z ≠ c.finish z + · rw [hv ⟨z,hz,hne⟩]; exact ha _ + · have hn := hnil z (by tauto) + simp [Finset.disjoint_left,pathInterior,Walk.nil_iff_support_eq.mp hn] + have h_dis : Pairwise fun z w : {z // z ∈ c.cycle.dropLast.support} => + Disjoint (visitInterior c.start c.finish visits z) (visitInterior c.start c.finish visits w) := by + intro z w hzw + rw [hinter,hinter,Finset.disjoint_coe] + by_cases hz : c.start z ≠ c.finish z + · by_cases hw : c.start w ≠ c.finish w + · rw [hv ⟨z,z.property,hz⟩,hv ⟨w,w.property,hw⟩] + exact hd (fun h => hzw (Subtype.ext (congrArg (fun t : c.Switch => (t:c.W)) h))) + · have hn := hnil w (by tauto); simp [Finset.disjoint_left,pathInterior,Walk.nil_iff_support_eq.mp hn] ; tauto + · have hn := hnil z (by tauto); simp [Finset.disjoint_left,pathInterior,Walk.nil_iff_support_eq.mp hn] + obtain ⟨v,p,hp,hedge⟩ := inflate_represented_cycle c.rep c.start c.finish c.cycle c.isCycle c.ports visits + (fun z _ => hpath z) (switch_supports_separated {z | z ∈ c.cycle.dropLast.support} + c.project c.start c.finish visits c.projects + (by + intro z hz + rw [cyclePortSet_eq_representative_vertices c.rep c.start c.finish c.cycle c.isCycle c.ports] + exact h_avoid z hz) + (fun z hz w hw hzw => h_dis (show (⟨z,hz⟩:{z // z ∈ c.cycle.dropLast.support}) ≠ ⟨w,hw⟩ from + fun h => hzw (congrArg Subtype.val h)))) + refine ⟨v,p,hp,hedge.trans ?_⟩ + congr 1 + ext e + simp only [Set.mem_iUnion] + constructor + · rintro ⟨z,hz,he⟩ + by_cases hne : c.start z ≠ c.finish z + · exact ⟨⟨z,hz,hne⟩,by rwa [hv ⟨z,hz,hne⟩] at he⟩ + · have hn := hnil z (by tauto) + have hh := he + simp [Walk.edgeSet,Walk.edges_eq_nil.mpr hn] at hh + · rintro ⟨z,he⟩; exact ⟨z,z.property.1,by rwa [hv]⟩ + +end CycleOutline +end +end ErdosGallai.Batch + +namespace ErdosGallai.Batch +noncomputable section +open Finset SimpleGraph +attribute [local instance] Classical.propDecidable + +structure RoutingTemplate {V : Type} (G : SimpleGraph V) where + Arity : Type + finiteArity : Fintype Arity + x : Arity → V + y : Arity → V + ne : ∀ i, x i ≠ y i + edges : Set (Sym2 V) + subset : edges ⊆ G.edgeSet + vertices : Finset V + incident : ∀ i v, x i = v ∨ y i = v → ∃ w, s(v,w) ∈ edges + unique : ∀ i j v, (x i = v ∨ y i = v) → (x j = v ∨ y j = v) → i = j + complete : ∀ q : ∀ i, G.Walk (x i) (y i), + (∀ i, (q i).IsPath) → + (∀ i, Disjoint (pathInterior (q i)) vertices) → + Pairwise (fun i j => Disjoint (pathInterior (q i)) (pathInterior (q j))) → + CycleOrSingleEdge G (edges ∪ ⋃ i, (q i).edgeSet) +attribute [instance] RoutingTemplate.finiteArity + +namespace RoutingTemplate +variable {V : Type} {G : SimpleGraph V} + +def ofCycle (c : CycleOutline G) : RoutingTemplate G where + Arity := c.Switch + finiteArity := inferInstance + x := fun i => c.start i + y := fun i => c.finish i + ne := fun i => i.property.2 + edges := c.edges + subset := c.edges_subset + vertices := c.vertices + incident := fun i v h => by obtain ⟨w,_,he⟩ := c.endpoint_incident i v h; exact ⟨w,he⟩ + unique := c.endpoint_unique + complete := by + intro q hs ha hd + obtain ⟨v,p,hp,he⟩ := c.complete q hs ha hd + exact Or.inl ⟨v,p,hp,he.symm⟩ + +def ofSingle (e : Sym2 V) (he : e ∈ G.edgeSet) : RoutingTemplate G where + Arity := Empty + finiteArity := inferInstance + x := Empty.elim + y := Empty.elim + ne := fun i => i.elim + edges := {e} + subset := Set.singleton_subset_iff.mpr he + vertices := ∅ + incident := fun i => i.elim + unique := fun i => i.elim + complete := by intro q _ _ _; exact Or.inr ⟨e,he,by simp⟩ + +def ofPath {x y : V} (p : G.Walk x y) (hp : p.IsPath) (hl : 2 ≤ p.length) : RoutingTemplate G where + Arity := Unit + finiteArity := inferInstance + x := fun _ => y + y := fun _ => x + ne := fun _ he => by + have hn : p.Nil := hp.nil_iff_eq.mpr he.symm + have := Walk.length_eq_zero_iff.mpr hn + omega + edges := p.edgeSet + subset := p.edges_subset_edgeSet + vertices := p.support.toFinset + incident := by + intro i v hv + have hn : ¬p.Nil := fun h => by have := Walk.length_eq_zero_iff.mpr h; omega + rcases hv with rfl | rfl + · obtain ⟨w,_,he⟩ := finish_has_incident_edge p hn; exact ⟨w,he⟩ + · obtain ⟨w,_,he⟩ := start_has_incident_edge p hn; exact ⟨w,he⟩ + unique := fun _ _ _ _ _ => Subsingleton.elim _ _ + complete := by + intro q hs ha hd + obtain ⟨hc,he⟩ := close_trimmed_path p (q ()) hp (hs ()) hl (by + intro v hv hxa hxb hpv + exact Finset.disjoint_left.mp (ha ()) + (by simp [pathInterior,hv,hxa,hxb]) (List.mem_toFinset.mpr hpv)) + refine Or.inl ⟨x,p.append (q ()),hc,?_⟩ + have hh : ∀ i : Unit, q i = q () := fun i => by cases i; rfl + simp_rw [hh,Set.iUnion_const] + exact he.symm + +lemma ofCycle_arity_card (c : CycleOutline G) : + Fintype.card (ofCycle c).Arity ≤ Fintype.card c.W := Fintype.card_subtype_le _ + +lemma ofPath_vertices_card [Fintype V] {x y : V} (p : G.Walk x y) (hp : p.IsPath) (hl : 2 ≤ p.length) : + (ofPath p hp hl).vertices.card ≤ Fintype.card V := Finset.card_le_univ _ + +end RoutingTemplate + +theorem uniform_resolve_templates : + ∃ D₀ : ℝ, 1 < D₀ ∧ ∀ D ≥ D₀, + ∀ (V R B : Type) [Fintype V] [Fintype R] [Fintype B], + ∀ (G F : SimpleGraph V) (P : R → SimpleGraph V) (U : R → Finset V), + F ≤ G → (∀ r, P r ≤ G) → + Pairwise (fun r s => Disjoint (P r).edgeSet (P s).edgeSet) → + Pairwise (fun r s => Disjoint (U r) (U s)) → + (∀ r, Disjoint F.edgeSet (P r).edgeSet) → + (∀ r, CutExpansionOn (P r) (U r) (D^(9/10:ℝ)/4)) → + (∀ r, D^(9/10:ℝ) ≤ ((U r).card:ℝ) ∧ ((U r).card:ℝ) ≤ D^(51/50:ℝ)) → + ∀ (b : B → RoutingTemplate G), + (∀ j, (b j).edges ⊆ F.edgeSet) → + Pairwise (fun j k => Disjoint (b j).edges (b k).edges) → + ∀ owner : (j : B) → (b j).Arity → R, + (∀ j i, (b j).x i ∈ U (owner j i) ∧ (b j).y i ∈ U (owner j i)) → + (∀ j i, (F.degree ((b j).x i):ℝ) ≤ D^(1/100:ℝ) ∧ + (F.degree ((b j).y i):ℝ) ≤ D^(1/100:ℝ)) → + (∀ j, (Fintype.card (b j).Arity:ℝ) ≤ D^(3/10:ℝ)) → + (∀ j, ((b j).vertices.card:ℝ) ≤ 2*D^(3/10:ℝ)) → + ∃ (parts : B → Set (Sym2 V)) (used : Set (Sym2 V)), + (∀ j, CycleOrSingleEdge G (parts j)) ∧ + Pairwise (fun j k => Disjoint (parts j) (parts k)) ∧ + used ⊆ ⋃ r, (P r).edgeSet ∧ Disjoint F.edgeSet used ∧ + (⋃ j, parts j) = (⋃ j, (b j).edges) ∪ used := by + classical + obtain ⟨D₀,hD₀,hr⟩ := uniform_multi_batch_routing + refine ⟨D₀,hD₀,?_⟩ + intro D hD V R B _ _ _ G F P U hFG hPG hPP hUU hFP he hsize b hsub hdis owner hends hdeg hnum hvertices + let I := Σ j, (b j).Arity + let x : I → V := fun i => (b i.1).x i.2 + let y : I → V := fun i => (b i.1).y i.2 + have hl (v : V) : (endpointLoad univ x y v:ℝ) ≤ D^(1/100:ℝ) := by + have hload : endpointLoad univ x y v ≤ F.degree v := by + have hh := demand_load_le_degree F (fun j => (b j).edges) hdis + Sigma.fst x y (by + rintro ⟨j,i⟩ ⟨k,l⟩ v h h₁ h₂ + dsimp only at h; subst k + congr 1; exact (b j).unique i l v h₁ h₂) (by + rintro ⟨j,i⟩ v h + obtain ⟨w,hw⟩ := (b j).incident i v h + exact ⟨w,hsub j hw,hw⟩) v + simpa [demandLoad,endpointLoad] using hh + by_cases hz : endpointLoad univ x y v = 0 + · rw [hz,Nat.cast_zero]; exact Real.rpow_nonneg (by linarith) _ + · have hp : 0 < (univ.filter fun i => x i = v ∨ y i = v).card := by + change 0 < endpointLoad univ x y v; omega + obtain ⟨⟨j,i⟩,hi⟩ := Finset.card_pos.mp hp + have hv : (b j).x i = v ∨ (b j).y i = v := (Finset.mem_filter.mp hi).2 + have hh : (F.degree v:ℝ) ≤ D^(1/100:ℝ) := by + rcases hv with rfl | rfl + · exact (hdeg j i).1 + · exact (hdeg j i).2 + exact (Nat.cast_le.mpr hload).trans hh + have hteam (i : I) : ((univ.filter fun j : I => j.1 = i.1).card:ℝ) ≤ D^(3/10:ℝ) := by + have hc : (univ.filter fun j : I => j.1 = i.1).card = Fintype.card (b i.1).Arity := by + rw [Finset.card_eq_sum_ones,Finset.sum_filter,Fintype.sum_sigma] + calc + _ = ∑ j : B, if j = i.1 then Fintype.card (b j).Arity else 0 := by + apply Finset.sum_congr rfl; intro j _ + by_cases hh : j = i.1 <;> simp [hh] + _ = _ := by simp + rw [hc]; exact hnum i.1 + obtain ⟨q,hq,hqd,hqi⟩ := hr D hD V R I B G P U hPG hPP hUU he hsize + (fun i => owner i.1 i.2) x y (fun i => ⟨(hends i.1 i.2).1,(hends i.1 i.2).2,(b i.1).ne i.2⟩) + Sigma.fst (fun i => (b i.1).vertices) hl hteam (fun i => hvertices i.1) + let used := ⋃ i, (q i).edgeSet + let parts := fun j => (b j).edges ∪ ⋃ i, (q ⟨j,i⟩).edgeSet + have hu : used ⊆ ⋃ r, (P r).edgeSet := by + apply Set.iUnion_subset; intro i + exact Set.subset_iUnion_of_subset (owner i.1 i.2) (hq i).2.2.1 + have hFu : Disjoint F.edgeSet used := by + refine Set.disjoint_iUnion_right.mpr (fun i => ?_) + exact (hFP _).mono_right (hq i).2.2.1 + have hbu : ∀ j, Disjoint (b j).edges used := fun j => hFu.mono_left (hsub j) + refine ⟨parts,used,?_,?_,hu,hFu,?_⟩ + · intro j + exact (b j).complete (fun i => q ⟨j,i⟩) (fun i => (hq _).1) (fun i => (hq _).2.2.2) + (fun i l hil => hqi _ _ (fun h => hil (eq_of_heq (Sigma.mk.inj_iff.mp h).2)) rfl) + · intro j k hjk + apply Set.disjoint_union_left.mpr; constructor + · apply Set.disjoint_union_right.mpr; constructor + · exact hdis hjk + · exact (hbu j).mono_right (Set.iUnion_subset (fun i => Set.subset_iUnion (fun z : I => (q z).edgeSet) ⟨k,i⟩)) + · apply Set.disjoint_union_right.mpr; constructor + · exact ((hbu k).mono_right (Set.iUnion_subset (fun i => Set.subset_iUnion (fun z : I => (q z).edgeSet) ⟨j,i⟩))).symm + · apply Set.disjoint_iUnion_left.mpr; intro i + apply Set.disjoint_iUnion_right.mpr; intro l + exact hqd (fun h => hjk (congrArg Sigma.fst h)) + · ext e + simp only [parts,used,Set.mem_iUnion,Set.mem_union] + constructor + · rintro ⟨j,he|⟨i,hi⟩⟩ + · exact Or.inl ⟨j,he⟩ + · exact Or.inr ⟨⟨j,i⟩,hi⟩ + · rintro (⟨j,he⟩|⟨⟨j,i⟩,he⟩) + · exact ⟨j,Or.inl he⟩ + · exact ⟨j,Or.inr ⟨i,he⟩⟩ + +end +end ErdosGallai.Batch +end +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/CycleDecomposition/UniformLayers.lean b/lean/OAI/Combinatorics/CycleDecomposition/UniformLayers.lean new file mode 100644 index 0000000000000000000000000000000000000000..9682d1b28622171b605cef94ccda310413c008c8 --- /dev/null +++ b/lean/OAI/Combinatorics/CycleDecomposition/UniformLayers.lean @@ -0,0 +1,297 @@ +import OAI.Combinatorics.CycleDecomposition.CostRegrouping + +namespace OAI + +section +open Filter Asymptotics Real +open scoped Topology +noncomputable section +open MeasureTheory ProbabilityTheory Finset +section + +namespace ErdosGallai.Scale +noncomputable section +open Finset SimpleGraph Real +attribute [local instance] Classical.propDecidable +variable {V : Type} [Fintype V] [DecidableEq V] + +structure Layers (P : AssignedPiece V) (Dstar : ℝ) where + system : SplitSystem V + count : ℕ + positive : 0 < count + cutoff : ∀ j < count, Dstar ≤ inductionScale P.vertices.card j + last_lt : inductionScale P.vertices.card count < Dstar + bounded : ∀ j < count, ∀ Q ∈ advance system 0 j [P], + (system j Q).Bounded (inductionScale P.vertices.card j) + degree : ∀ j ≤ count, ∀ Q ∈ advance system 0 j [P], + 2*(edgeCount Q.graph:ℝ)/Q.vertices.card ≤ inductionScale P.vertices.card j + +theorem uniform_layers : ∃ D₀ : ℝ, 1 < D₀ ∧ ∀ Dstar ≥ D₀, + ∀ (V : Type) [Fintype V] [DecidableEq V] (P : AssignedPiece V), + Dstar ≤ (P.vertices.card:ℝ) → 2*(edgeCount P.graph:ℝ)/P.vertices.card ≤ P.vertices.card → + Nonempty (Layers P Dstar) := by + obtain ⟨Dsp,hsp⟩ := scale_splitter + refine ⟨max Dsp 2,lt_of_lt_of_le (by norm_num : (1:ℝ) < 2) (le_max_right _ _),?_⟩ + intro Dstar hD V _ _ P hn hdeg + have hD1 : 1 < Dstar := lt_of_lt_of_le (by norm_num : (1:ℝ) < 2) ((le_max_right _ _).trans hD) + have hn1 : 1 < (P.vertices.card:ℝ) := hD1.trans_le hn + have hne : P.vertices.Nonempty := Finset.card_pos.mp (by exact_mod_cast (by linarith : (0:ℝ) < P.vertices.card)) + obtain ⟨split,hsplit⟩ := hsp V + let s : SplitSystem V := fun j Q => split (inductionScale P.vertices.card j) Q + have hs : ∀ j Q, Dstar ≤ inductionScale P.vertices.card j → Q.vertices.Nonempty → + 2*(edgeCount Q.graph:ℝ)/Q.vertices.card ≤ inductionScale P.vertices.card j → + (s j Q).Bounded (inductionScale P.vertices.card j) := by + intro j Q hj hQ hd + exact hsplit _ ((le_max_left _ _).trans (hD.trans hj)) Q hQ hd + obtain ⟨m,hm,hlast,hcut⟩ := inductionScale_first_cutoff P.vertices.card Dstar hD1 hn + have hL : ∀ Q ∈ [P], Q.vertices.Nonempty := by simpa using hne + have hLd : ∀ Q ∈ [P], 2*(edgeCount Q.graph:ℝ)/Q.vertices.card ≤ inductionScale P.vertices.card 0 := by + simpa only [List.mem_singleton,forall_eq,inductionScale_zero] using hdeg + refine ⟨{ system := s, count := m, positive := hm, cutoff := hcut, last_lt := hlast, bounded := ?_, degree := ?_ }⟩ + · intro j hj + simpa only [Nat.zero_add] using advance_bounded s P.vertices.card Dstar (Nat.cast_nonneg _) hs + 0 j [P] hL hLd (fun l _ hl => hcut l (by omega)) + · intro j hj + simpa only [Nat.zero_add] using advance_valid s P.vertices.card Dstar (Nat.cast_nonneg _) hs + 0 j [P] hL hLd (fun l _ hl => hcut l (by omega)) + +variable {P : AssignedPiece V} {Dstar : ℝ} + +abbrev Layers.frontier (H : Layers P Dstar) (j : ℕ) := advance H.system 0 j [P] +abbrev Layers.scale (_H : Layers P Dstar) (j : ℕ) := inductionScale (P.vertices.card:ℝ) j +abbrev Layers.mass (H : Layers P Dstar) (j : ℕ) := vertexMass (H.frontier j) +abbrev Layers.pieceMass (H : Layers P Dstar) (j : ℕ) := vertexMass (levelPieces H.system j (H.frontier j)) + +lemma Layers.mass_lower (H : Layers P Dstar) (j) : (P.vertices.card:ℝ) ≤ H.mass j := + advance_mass_lower H.system 0 j P + +lemma Layers.mass_upper (H : Layers P Dstar) (hn : 1 < (P.vertices.card:ℝ)) + (hlog : ∀ j < H.count, 80 ≤ logb 2 (H.scale j)) (j) (hj : j < H.count) : + H.mass (j+1) ≤ (1+80/logb 2 (H.scale j))*P.vertices.card := by + have hh := advance_mass_global_product H.system P.vertices.card hn 0 (j+1) [P] + (fun l hl => by simpa only [Nat.zero_add] using H.bounded l (by omega)) + have hx := scale_overlap_product P.vertices.card 2 hn (by norm_num) j (by norm_num; exact hlog j hj) + simp only [Nat.zero_add,vertexMass_cons,vertexMass_nil,add_zero] at hh + have hx' := mul_le_mul_of_nonneg_left hx (Nat.cast_nonneg P.vertices.card : (0:ℝ) ≤ _) + norm_num only [show (40:ℝ)*2=80 by norm_num] at hx' + dsimp only [Layers.mass,Layers.frontier,Layers.scale] at * + nlinarith + +lemma Layers.mass_two (H : Layers P Dstar) (hn : 1 < (P.vertices.card:ℝ)) + (hlog : ∀ j < H.count, 80 ≤ logb 2 (H.scale j)) (k) (hk : k ≤ H.count) : + H.mass k ≤ 2*P.vertices.card := by + cases k with + | zero => simp only [Layers.mass,Layers.frontier,advance_zero,vertexMass_cons,vertexMass_nil,add_zero]; nlinarith [(Nat.cast_nonneg P.vertices.card : (0:ℝ) ≤ _)] + | succ j => + have hj : j < H.count := by omega + have hh := H.mass_upper hn hlog j hj + have hl := hlog j hj + have hd : 80/logb 2 (H.scale j) ≤ 1 := (div_le_one (by linarith)).mpr hl + have hc : (0:ℝ) ≤ P.vertices.card := Nat.cast_nonneg _ + nlinarith + +lemma Layers.pieceMass_two (H : Layers P Dstar) (hn : 1 < (P.vertices.card:ℝ)) + (hlog : ∀ j < H.count, 80 ≤ logb 2 (H.scale j)) (j) (hj : j < H.count) : + H.pieceMass j ≤ 2*P.vertices.card := + (levelPieces_mass H.system j (H.frontier j)).trans (by + simpa only [Layers.mass,Layers.frontier,advance_succ,Nat.zero_add] using H.mass_two hn hlog (j+1) (by omega)) + +lemma Layers.cycles_bound (H : Layers P Dstar) (hn : 1 < (P.vertices.card:ℝ)) + (hready : ∀ j < H.count, ErdosGallai.MainScaleReady 80 (H.scale j)) (j) (hj : j < H.count) : + ((pastCycles H.system 0 (j+1) [P]).length:ℝ) ≤ 20*P.vertices.card/logb 2 (H.scale j) := by + rw [pastCycles_length] + apply (Finset.sum_le_sum (fun l hl => ?_)).trans + (scale_prefix_cycle_cost P.vertices.card hn j (fun l => H.mass l) + (fun l hl => H.mass_two hn (fun a ha => (hready a ha).log_large) l (by have := Finset.mem_range.mp hl; omega)) + (fun l hl => (hready l (by have := Finset.mem_range.mp hl; omega)).cycle_power)) + simpa only [Nat.zero_add] using levelCycles_length H.system l (H.frontier l) (H.scale l) + (H.bounded l (by have := Finset.mem_range.mp hl; omega)) + +lemma Layers.subset (H : Layers P Dstar) (j) : ∀ Q ∈ H.frontier j, Q.vertices ⊆ P.vertices := + advance_subset H.system 0 j [P] P.vertices (by simp) + +lemma Layers.box_subset (H : Layers P Dstar) (j) {Q B : AssignedPiece V} + (hQ : Q ∈ H.frontier j) (hB : B ∈ (H.system j Q).boxes) : B.vertices ⊆ P.vertices := + ((H.system j Q).box_subset B hB).trans (H.subset j Q hQ) + +lemma Layers.boundary_order (H : Layers P Dstar) (j) (hj : j < H.count) + {Q : AssignedPiece V} (hQ : Q ∈ H.frontier (j+1)) : + (Q.vertices.card:ℝ) ≤ (H.scale j)^(51/50:ℝ) := by + simp only [Layers.frontier,advance_succ,Nat.zero_add] at hQ + obtain ⟨T,hT,B,hB,hv,_⟩ := (nextLayer_mem H.system j _ Q).mp hQ + rw [hv] + exact (H.bounded j hj T hT).2.2.1 B hB + +lemma Layers.local_mass (H : Layers P Dstar) (hn : 1 < (P.vertices.card:ℝ)) + (hlog : ∀ j < H.count, 80 ≤ logb 2 (H.scale j)) (i k) + (hik : i+k < H.count) {Q B : AssignedPiece V} + (hQ : Q ∈ H.frontier i) (hB : B ∈ (H.system i Q).boxes) : + vertexMass (advance H.system (i+1) k [(H.system i Q).rest B]) ≤ + (1+80/logb 2 (H.scale (i+k)))*B.vertices.card := by + have hh := advance_mass_global_product H.system P.vertices.card hn (i+1) k [(H.system i Q).rest B] + (fun l hl R hR => by + have hr := advance_local_mem H.system i l [P] hQ hB R hR + have he : i+1+l = (i+l)+1 := by omega + exact H.bounded (i+1+l) (by omega) R hr) + have hx := scale_overlap_product P.vertices.card 2 hn (by norm_num) (i+k) + (by norm_num; exact hlog (i+k) hik) + simp only [vertexMass_cons,vertexMass_nil,add_zero,StageSplit.rest_vertices] at hh + rw [show i+1+k=(i+k)+1 by omega] at hh + have hx' := mul_le_mul_of_nonneg_left hx (Nat.cast_nonneg B.vertices.card : (0:ℝ) ≤ _) + norm_num only [show (40:ℝ)*2=80 by norm_num] at hx' + dsimp only [Layers.scale] at * + nlinarith + +lemma Layers.local_mass_two (H : Layers P Dstar) (hn : 1 < (P.vertices.card:ℝ)) + (hlog : ∀ j < H.count, 80 ≤ logb 2 (H.scale j)) (i k) + (hik : i+k < H.count) {Q B : AssignedPiece V} + (hQ : Q ∈ H.frontier i) (hB : B ∈ (H.system i Q).boxes) : + vertexMass (advance H.system (i+1) k [(H.system i Q).rest B]) ≤ 2*B.vertices.card := by + have hh := H.local_mass hn hlog i k hik hQ hB + have hl := hlog (i+k) hik + have hd : 80/logb 2 (H.scale (i+k)) ≤ 1 := (div_le_one (by linarith)).mpr hl + have hc : (0:ℝ) ≤ B.vertices.card := Nat.cast_nonneg _ + nlinarith + +lemma Layers.gap_order (H : Layers P Dstar) (hn : 1 < (P.vertices.card:ℝ)) (i) + (hik : i+200 < H.count) {Q B R : AssignedPiece V} + (hQ : Q ∈ H.frontier i) (hB : B ∈ (H.system i Q).boxes) + (hR : R ∈ advance H.system (i+1) 200 [(H.system i Q).rest B]) : + (R.vertices.card:ℝ) ≤ (H.scale i)^(1/1000:ℝ) ∧ + 2*(edgeCount R.graph:ℝ)/R.vertices.card ≤ (H.scale i)^(1/1000:ℝ) := by + have hr := advance_local_mem H.system i 200 [P] hQ hB R hR + have hr' : R ∈ H.frontier ((i+200)+1) := by convert hr using 1 + have hd : 1 < H.scale i := inductionScale_gt_one P.vertices.card hn i + constructor + · have hh := H.boundary_order (i+200) hik hr' + apply hh.trans + dsimp only [Layers.scale] + rw [inductionScale_add _ (by positivity),← Real.rpow_mul (by linarith : 0 ≤ inductionScale P.vertices.card i)] + apply Real.rpow_le_rpow_of_exponent_le hd.le + nlinarith [inductionScale_window.1] + · have hh := H.degree ((i+200)+1) (by omega) R hr' + apply hh.trans + rw [show i+200+1=i+201 by omega] + dsimp only [Layers.scale] + rw [inductionScale_add _ (by positivity)] + exact Real.rpow_le_rpow_of_exponent_le hd.le inductionScale_window.2.le + +end +end ErdosGallai.Scale + +end + +section + +namespace ErdosGallai +noncomputable section +open Finset SimpleGraph Real +attribute [local instance] Classical.propDecidable + +lemma disjoint_subset_mass {V A : Type} [Fintype A] [DecidableEq V] + (U : A → Finset V) (Y : Finset V) (hd : Pairwise fun r s => Disjoint (U r) (U s)) + (hu : ∀ r, U r ⊆ Y) : (∑ r, ((U r).card:ℝ)) ≤ Y.card := by + have hc : (univ.biUnion U).card = ∑ r, (U r).card := Finset.card_biUnion (fun i _ j _ hij => hd hij) + have hs : univ.biUnion U ⊆ Y := by + intro v hv + obtain ⟨r,_,hv⟩ := Finset.mem_biUnion.mp hv + exact hu r hv + have hh := Finset.card_le_card hs + rw [hc] at hh + exact_mod_cast hh + +theorem uniform_box_cost : ∃ D₀ : ℝ, 1 < D₀ ∧ ∀ D ≥ D₀, ∀ wmin : ℝ, + MainScaleReady wmin D → + ∀ (V A : Type) [Fintype V] [Fintype A], + ∀ (G F : SimpleGraph V) (R : A → SimpleGraph V) (U : A → Finset V) (Y : Finset V), + F ≤ G → (∀ r, R r ≤ G) → + Pairwise (fun r s => Disjoint (R r).edgeSet (R s).edgeSet) → + Pairwise (fun r s => Disjoint (U r) (U s)) → + (∀ r, U r ⊆ Y) → + (∀ r, ∀ ⦃x y⦄, (R r).Adj x y → x ∈ U r ∧ y ∈ U r) → + (∀ r, Disjoint F.edgeSet (R r).edgeSet) → + F.edgeSet ∪ (⋃ r, (R r).edgeSet) = G.edgeSet → + (∀ r, Batch.CutExpansionOn (R r) (U r) (D^(9/10:ℝ))) → + (∀ r, D^(9/10:ℝ) ≤ ((U r).card:ℝ) ∧ ((U r).card:ℝ) ≤ D^(51/50:ℝ)) → + ((Y.card:ℝ) ≤ D^(51/50:ℝ)) → + 2*(F.edgeFinset.card:ℝ) ≤ 2*Y.card*D^(1/1000:ℝ) → + ∀ T : ℝ, T ≤ 2*Y.card → + ∀ _b : Indexing.GraphBatches F Y (D^(3/10:ℝ)) T, + ∀ (n : ℕ) (C t : ℝ), 0 ≤ C → 0 ≤ t → Y.card ≤ n → D^(3/10:ℝ) < n → + (∀ (Q : Type) [Fintype Q] (H : SimpleGraph Q), Fintype.card Q < n → + (decompositionCost H:ℝ) ≤ C*Fintype.card Q) → + (∀ (Q : Type) [Fintype Q] (H : SimpleGraph Q), Fintype.card Q < n → + (Fintype.card Q:ℝ) ≤ D^(3/10:ℝ) → (Batch.decompositionCost H:ℝ) ≤ t*Fintype.card Q) → + (Batch.decompositionCost G:ℝ) ≤ + t*(T-(∑ r, ((U r).card:ℝ))/3+(2/3)*Y.card/logb 2 D) + + 8*((∑ r, ((U r).card:ℝ))+T-Y.card) + (9+C*mainEta)*(∑ r, ((U r).card:ℝ)) := by + obtain ⟨D₁,hD₁,hresolve⟩ := Batch.uniform_coupled_resolution_cost + obtain ⟨D₂,hD₂,hpiece⟩ := uniform_piece_cost_on (1/4) mainEta (by norm_num) mainEta_pos + refine ⟨max D₁ D₂,lt_of_lt_of_le hD₁ (le_max_left _ _),?_⟩ + intro D hD wmin hready V A _ _ G F R U Y hFG hRG hRR hUU hUY hRU hFR hcov hexp horder + hY hF T hT b n C t hC ht hYn hsmall ih ihq + have hD0 : 0 < D := by linarith [hready.gt_one] + have ha : 1 ≤ D^(1/100:ℝ) := Real.one_le_rpow hready.gt_one.le (by norm_num) + obtain ⟨a⟩ := Indexing.choose_active_family F Y b.vertices U (D^(1/100:ℝ)) (D^(3/100:ℝ)) + (Real.rpow_nonneg hD0.le _) b.subset hUY b.vertex_cover hUU + let := a.finite + have h8 (j) (i : a.Index j) : 8 ≤ (a.vertices j i).card := by + have hh := hready.active_eight.trans (a.large j i) + exact_mod_cast hh + have hsquare (j) (i : a.Index j) : (D^(1/100:ℝ))^2 ≤ (a.vertices j i).card := + hready.active_square.trans (a.large j i) + have hn (j) : (b.vertices j).card < n := by + exact_mod_cast (b.order_le j).trans_lt hsmall + obtain ⟨H,hHR,hHexp,hcost⟩ := hresolve D ((le_max_left _ _).trans hD) V A b.Index G F R U + hFG hRG hRR hUU hRU hFR hcov hexp horder b.graph b.vertices b.graph_le b.disjoint b.edge_cover + b.supported b.order_le a.Index a.vertices a.disjoint a.subset_batch a.router a.subset_router + a.degree_le ha h8 hsquare n t ht hn ihq + have hp (r : A) : (Batch.decompositionCost (H r):ℝ) ≤ (9+C*mainEta)*(U r).card := by + have hh := hpiece D ((le_max_right _ _).trans hD) n C hC ih V (H r) (H r) (U r) le_rfl + ((Finset.card_le_card (hUY r)).trans hYn) (fun x y h => hRU r (hHR r h)) (horder r).1 (horder r).2 + (by + + simpa only [CutExpansionOn,Batch.CutExpansionOn,show (1/4:ℝ)*D^(9/10:ℝ) = D^(9/10:ℝ)/4 by ring] using hHexp r) + exact hh + have hpsum : (∑ r, (Batch.decompositionCost (H r):ℝ)) ≤ (9+C*mainEta)*(∑ r, ((U r).card:ℝ)) := by + simpa only [Finset.mul_sum] using Finset.sum_le_sum (s := univ) (fun r _ => hp r) + have hbad : ((Y \ Indexing.goodVertices F Y (D^(1/100:ℝ))).card:ℝ) ≤ Y.card/logb 2 D := + hready.bad_count (Nat.cast_nonneg _) ((Indexing.bad_vertices_degree_bound F Y (D^(1/100:ℝ))).trans hF) + have hrcount : D^(9/10:ℝ)*(Fintype.card A:ℝ) ≤ Y.card := by + calc + _ = ∑ _r : A, D^(9/10:ℝ) := by simp [mul_comm] + _ ≤ ∑ r, ((U r).card:ℝ) := Finset.sum_le_sum (fun r _ => (horder r).1) + _ ≤ _ := disjoint_subset_mass U Y hUU hUY + have hskip := hready.skip_count (Nat.cast_nonneg Y.card) (Nat.cast_nonneg (Fintype.card b.Index)) + (Nat.cast_nonneg (Fintype.card A)) hY hT b.count_le hrcount + have hlow : (∑ r, ((U r).card:ℝ))-2*Y.card/logb 2 D ≤ ∑ j, ∑ i, ((a.vertices j i).card:ℝ) := by + have hh := a.lower + simp only [div_eq_mul_inv] at hbad hskip hh ⊢ + linarith only [hh,hbad,hskip] + have hhigh : (∑ j, ∑ i, ((a.vertices j i).card:ℝ)) ≤ (∑ r, ((U r).card:ℝ))+T-Y.card := by + have hh := a.upper + have hm := b.mass_le + linarith + have hhalf : (∑ j, ∑ i, ((a.vertices j i).card:ℝ))/3 ≤ + ∑ j, ∑ i, (((a.vertices j i).card / 2:ℕ):ℝ) := by + simp only [Finset.sum_div] + apply Finset.sum_le_sum; intro j _ + apply Finset.sum_le_sum; intro i _ + exact Indexing.thirds_le_halves (h8 j i) + have hq : (∑ j, ((b.vertices j).card:ℝ)) - ∑ j, ∑ i, (((a.vertices j i).card / 2:ℕ):ℝ) ≤ + T-(∑ r, ((U r).card:ℝ))/3+(2/3)*Y.card/logb 2 D := by + have hm := b.mass_le + simp only [div_eq_mul_inv] at hm hlow hhalf ⊢ + linarith only [hm,hlow,hhalf] + have hqm := mul_le_mul_of_nonneg_left hq ht + push_cast at hcost + linarith + +end +end ErdosGallai + +end +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/DiscreteConvexity/Basic.lean b/lean/OAI/Combinatorics/DiscreteConvexity/Basic.lean new file mode 100644 index 0000000000000000000000000000000000000000..c5830b958c929fd405a20c659b1b2d2c82ef16bc --- /dev/null +++ b/lean/OAI/Combinatorics/DiscreteConvexity/Basic.lean @@ -0,0 +1,195 @@ +import OAI.Combinatorics.DiscreteConvexity.Model + +namespace OAI + +namespace TalagrandDiscreteConvexity + +open scoped BigOperators + +variable {α : Type*} [Fintype α] [DecidableEq α] + +noncomputable section + +theorem bernoulliMass_nonneg {p : ℝ} (hp0 : 0 ≤ p) (hp1 : p ≤ 1) + (s : Finset α) : 0 ≤ bernoulliMass p s := + mul_nonneg (pow_nonneg hp0 _) (pow_nonneg (sub_nonneg.mpr hp1) _) + +theorem familyMeasure_nonneg {p : ℝ} (hp0 : 0 ≤ p) (hp1 : p ≤ 1) + (D : Family α) : 0 ≤ familyMeasure p D := + Finset.sum_nonneg (fun s _ => bernoulliMass_nonneg hp0 hp1 s) + +@[simp] theorem familyMeasure_empty (p : ℝ) : + familyMeasure p (∅ : Family α) = 0 := by simp [familyMeasure] + +theorem familyMeasure_mono {p : ℝ} (hp0 : 0 ≤ p) (hp1 : p ≤ 1) + {D E : Family α} (h : D ⊆ E) : familyMeasure p D ≤ familyMeasure p E := by + exact Finset.sum_le_sum_of_subset_of_nonneg h + (fun s _ _ => bernoulliMass_nonneg hp0 hp1 s) + +omit [Fintype α] [DecidableEq α] in +@[simp] theorem cost_empty (p : ℝ) : cost p (∅ : Family α) = 0 := by + simp [cost] + +omit [Fintype α] [DecidableEq α] in +@[simp] theorem cost_singleton (p : ℝ) (I : Finset α) : + cost p {I} = p ^ I.card := by simp [cost] + +omit [Fintype α] [DecidableEq α] in +theorem cost_nonneg {p : ℝ} (hp : 0 ≤ p) (G : Family α) : 0 ≤ cost p G := + Finset.sum_nonneg (fun generator _ => pow_nonneg hp generator.card) + +omit [Fintype α] [DecidableEq α] in +theorem cost_mono {p : ℝ} (hp : 0 ≤ p) {G H : Family α} (h : G ⊆ H) : + cost p G ≤ cost p H := + Finset.sum_le_sum_of_subset_of_nonneg h (fun generator _ _ => pow_nonneg hp generator.card) + +omit [Fintype α] in +theorem cost_union_le {p : ℝ} (hp : 0 ≤ p) (G H : Family α) : + cost p (G ∪ H) ≤ cost p G + cost p H := by + calc + cost p (G ∪ H) ≤ cost p (G ∪ H) + cost p (G ∩ H) := + le_add_of_nonneg_right (cost_nonneg hp _) + _ = cost p G + cost p H := by + exact Finset.sum_union_inter + +omit [Fintype α] in +theorem cost_biUnion_le {ι : Type*} [DecidableEq ι] {p : ℝ} (hp : 0 ≤ p) + (T : Finset ι) (G : ι → Family α) : + cost p (T.biUnion G) ≤ ∑ i ∈ T, cost p (G i) := by + induction T using Finset.induction_on with + | empty => simp + | @insert a T ha ih => + rw [Finset.biUnion_insert, Finset.sum_insert ha] + exact (cost_union_le hp _ _).trans (add_le_add le_rfl ih) + +omit [Fintype α] in +theorem cost_image_le {ι : Type*} [DecidableEq ι] {p : ℝ} (hp : 0 ≤ p) + (T : Finset ι) (G : ι → Finset α) : + cost p (T.image G) ≤ ∑ i ∈ T, p ^ (G i).card := by + exact Finset.sum_image_le_of_nonneg (fun I _ => pow_nonneg hp I.card) + +omit [Fintype α] [DecidableEq α] in +theorem covers_self (A : Family α) : Covers A A := + fun S hS => ⟨S, hS, Finset.Subset.refl S⟩ + +omit [Fintype α] [DecidableEq α] in +@[simp] theorem covers_empty (G : Family α) : Covers G ∅ := by + intro S hS + exact False.elim (Finset.notMem_empty S hS) + +omit [Fintype α] [DecidableEq α] in +theorem Covers.mono_target {G A B : Family α} (h : Covers G A) (hBA : B ⊆ A) : + Covers G B := fun S hS => h S (hBA hS) + +omit [Fintype α] [DecidableEq α] in +theorem Covers.mono_cover {G H A : Family α} (h : Covers G A) (hGH : G ⊆ H) : + Covers H A := by + intro S hS + obtain ⟨I, hI, hIS⟩ := h S hS + exact ⟨I, hGH hI, hIS⟩ + +omit [Fintype α] in +theorem Covers.union {G H A B : Family α} (hGA : Covers G A) (hHB : Covers H B) : + Covers (G ∪ H) (A ∪ B) := by + intro S hS + rcases Finset.mem_union.mp hS with hS | hS + · obtain ⟨I, hI, hIS⟩ := hGA S hS + exact ⟨I, Finset.mem_union_left H hI, hIS⟩ + · obtain ⟨I, hI, hIS⟩ := hHB S hS + exact ⟨I, Finset.mem_union_right G hI, hIS⟩ + +omit [Fintype α] [DecidableEq α] in +theorem small_empty (p : ℝ) : Small p (∅ : Family α) := by + refine ⟨∅, covers_empty _, ?_⟩ + simp + +omit [Fintype α] in +@[simp] theorem mem_unionTuple {k : ℕ} {f : Fin k → Finset α} {a : α} : + a ∈ unionTuple f ↔ ∃ j, a ∈ f j := by + simp [unionTuple] + +omit [Fintype α] in +theorem subset_unionTuple {k : ℕ} (f : Fin k → Finset α) (j : Fin k) : + f j ⊆ unionTuple f := fun _ ha => mem_unionTuple.mpr ⟨j, ha⟩ + +omit [Fintype α] in +theorem unionTuple_subset_iff {k : ℕ} (f : Fin k → Finset α) (S : Finset α) : + unionTuple f ⊆ S ↔ ∀ j, f j ⊆ S := by + constructor + · intro h j + exact (subset_unionTuple f j).trans h + · intro h a ha + obtain ⟨j, hj⟩ := mem_unionTuple.mp ha + exact h j hj + +@[simp] theorem mem_unionFamily {k : ℕ} {D : Family α} {S : Finset α} : + S ∈ unionFamily k D ↔ + ∃ f : Fin k → Finset α, (∀ j, f j ∈ D) ∧ unionTuple f = S := by + classical + simp [unionFamily] + +@[simp] theorem mem_exceptional {k : ℕ} {D : Family α} {S : Finset α} : + S ∈ exceptional k D ↔ + ∀ f : Fin k → Finset α, (∀ j, f j ∈ D) → ¬ S ⊆ unionTuple f := by + classical + simp [exceptional] + +theorem mem_exceptional_iff_unionFamily {k : ℕ} {D : Family α} {S : Finset α} : + S ∈ exceptional k D ↔ ∀ T ∈ unionFamily k D, ¬ S ⊆ T := by + constructor + · intro h T hT + obtain ⟨f, hf, rfl⟩ := mem_unionFamily.mp hT + exact mem_exceptional.mp h f hf + · intro h + apply mem_exceptional.mpr + intro f hf + exact h (unionTuple f) (mem_unionFamily.mpr ⟨f, hf, rfl⟩) + +theorem exceptional_tuple_misses {k : ℕ} {D : Family α} {S : Finset α} + (hS : S ∈ exceptional k D) (f : Fin k → Finset α) (hf : ∀ j, f j ∈ D) : + ∃ a ∈ S, ∀ j, a ∉ f j := by + obtain ⟨a, ha, hmiss⟩ := Finset.not_subset.mp (mem_exceptional.mp hS f hf) + exact ⟨a, ha, fun j hj => hmiss (mem_unionTuple.mpr ⟨j, hj⟩)⟩ + +theorem exceptional_antitone {k : ℕ} {D E : Family α} (hDE : D ⊆ E) : + exceptional k E ⊆ exceptional k D := by + intro S hS + apply mem_exceptional.mpr + intro f hf + exact mem_exceptional.mp hS f (fun j => hDE (hf j)) + +theorem exceptional_eq_empty_of_full_union {k : ℕ} {D : Family α} + (f : Fin k → Finset α) (hf : ∀ j, f j ∈ D) (hfull : unionTuple f = Finset.univ) : + exceptional k D = ∅ := by + apply Finset.eq_empty_iff_forall_notMem.mpr + intro S hS + exact mem_exceptional.mp hS f hf (hfull.symm ▸ Finset.subset_univ S) + +omit [DecidableEq α] in +@[simp] theorem mem_cubeSet {x : α → Bool} {a : α} : + a ∈ cubeSet x ↔ x a = true := by simp [cubeSet] + +@[simp] theorem cubeSet_decide (S : Finset α) : + cubeSet (fun a => decide (a ∈ S)) = S := by + ext a + simp + +theorem familyIndicator_nonneg (D : Family α) (x : α → Bool) : + 0 ≤ familyIndicator D x := by + unfold familyIndicator + split_ifs <;> simp + +theorem familyIndicator_le_one (D : Family α) (x : α → Bool) : + familyIndicator D x ≤ 1 := by + unfold familyIndicator + split_ifs <;> simp + +theorem familyIndicator_sq (D : Family α) (x : α → Bool) : + familyIndicator D x ^ 2 = familyIndicator D x := by + unfold familyIndicator + split_ifs <;> simp + +end +end TalagrandDiscreteConvexity + +end OAI diff --git a/lean/OAI/Combinatorics/DiscreteConvexity/Bernoulli.lean b/lean/OAI/Combinatorics/DiscreteConvexity/Bernoulli.lean new file mode 100644 index 0000000000000000000000000000000000000000..ec1c8668b7e8efee203976fae5d9a29ef80e0842 --- /dev/null +++ b/lean/OAI/Combinatorics/DiscreteConvexity/Bernoulli.lean @@ -0,0 +1,299 @@ +import OAI.Combinatorics.DiscreteConvexity.Basic +import OAI.Combinatorics.DiscreteConvexity.FiniteProbability +import Mathlib.Algebra.BigOperators.Group.Finset.Piecewise +import Mathlib.Algebra.BigOperators.GroupWithZero.Finset +import Mathlib.Tactic.Ring + +namespace OAI + +/-! +# Bernoulli product laws and Boolean cubes + +The algebraic identities hold for every real parameter. Nonnegative normalized +laws additionally require a parameter in the closed unit interval. +-/ + +open scoped BigOperators +noncomputable section +attribute [local instance] Classical.propDecidable + +namespace TalagrandDiscreteConvexity + +/-- The mass of a Bernoulli bit. -/ +def bitWeight (p : ℝ) (b : Bool) : ℝ := if b then p else 1 - p + +@[simp] theorem bitWeight_true (p : ℝ) : bitWeight p true = p := rfl +@[simp] theorem bitWeight_false (p : ℝ) : bitWeight p false = 1 - p := rfl + +theorem bitWeight_nonneg {p : ℝ} (hp0 : 0 ≤ p) (hp1 : p ≤ 1) (b : Bool) : + 0 ≤ bitWeight p b := by + cases b + · exact sub_nonneg.mpr hp1 + · exact hp0 + +def bitLaw (p : ℝ) (hp0 : 0 ≤ p) (hp1 : p ≤ 1) : FiniteLaw Bool where + weight := bitWeight p + nonneg := bitWeight_nonneg hp0 hp1 + total := by simp [bitWeight] + +@[simp] theorem bitLaw_weight (p : ℝ) (hp0 : 0 ≤ p) (hp1 : p ≤ 1) (b : Bool) : + (bitLaw p hp0 hp1).weight b = bitWeight p b := rfl + +@[simp] theorem bitLaw_prob_true (p : ℝ) (hp0 : 0 ≤ p) (hp1 : p ≤ 1) : + (bitLaw p hp0 hp1).prob (fun b => b = true) = p := by + simp [FiniteLaw.prob, bitLaw, bitWeight] + +@[simp] theorem bitLaw_prob_false (p : ℝ) (hp0 : 0 ≤ p) (hp1 : p ≤ 1) : + (bitLaw p hp0 hp1).prob (fun b => b = false) = 1 - p := by + simp [FiniteLaw.prob, bitLaw, bitWeight] + +variable {α : Type*} [Fintype α] [DecidableEq α] + +/-- Product mass on the Boolean cube, including signed parameters. -/ +def cubeWeight (p : ℝ) (x : α → Bool) : ℝ := ∏ i, bitWeight p (x i) + +def cubeExpectation (p : ℝ) (f : (α → Bool) → ℝ) : ℝ := + ∑ x, cubeWeight p x * f x + +def bernoulliWeight (p : ℝ) (s : Finset α) : ℝ := + ∏ i, if i ∈ s then p else 1 - p + +def bernoulliExpectation (p : ℝ) (f : Finset α → ℝ) : ℝ := + ∑ s, bernoulliWeight p s * f s + +def bernoulliProbability (p : ℝ) (P : Finset α → Prop) : ℝ := + ∑ s, if P s then bernoulliWeight p s else 0 + +def finsetBoolEquiv : Finset α ≃ (α → Bool) where + toFun W x := decide (x ∈ W) + invFun b := Finset.univ.filter fun x => b x = true + left_inv W := by ext x; simp + right_inv b := by + funext x + cases hb : b x <;> simp [hb] + +theorem sum_finset_product (f : α → Bool → ℝ) : + (∑ W : Finset α, ∏ x, f x (decide (x ∈ W))) = + ∏ x, (f x true + f x false) := by + calc + (∑ W : Finset α, ∏ x, f x (decide (x ∈ W))) = + ∑ b : α → Bool, ∏ x, f x (b x) := + (finsetBoolEquiv (α := α)).sum_comp (fun b => ∏ x, f x (b x)) + _ = _ := by rw [← Fintype.prod_sum f]; simp only [Fintype.sum_bool] + +theorem bernoulliExpectation_product (p : ℝ) (f : α → Bool → ℝ) : + bernoulliExpectation p (fun W => ∏ x, f x (decide (x ∈ W))) = + ∏ x, (p * f x true + (1 - p) * f x false) := by + unfold bernoulliExpectation bernoulliWeight + simp_rw [← Finset.prod_mul_distrib] + simpa using sum_finset_product (fun x b => (if b then p else 1 - p) * f x b) + +theorem bernoulliWeight_nonneg {p : ℝ} (hp0 : 0 ≤ p) (hp1 : p ≤ 1) (W : Finset α) : + 0 ≤ bernoulliWeight p W := by + apply Finset.prod_nonneg + intro x _ + split_ifs <;> linarith + +theorem bernoulliWeight_pos {p : ℝ} (hp0 : 0 < p) (hp1 : p < 1) (W : Finset α) : + 0 < bernoulliWeight p W := by + apply Finset.prod_pos + intro x _ + split_ifs <;> linarith + +theorem bernoulliWeight_sum (p : ℝ) : ∑ W : Finset α, bernoulliWeight p W = 1 := by + have hp : p + (1 - p) = 1 := by ring + simpa [bernoulliExpectation, hp] using + bernoulliExpectation_product p (fun (_ : α) (_ : Bool) => 1) + +def bernoulliLaw (p : ℝ) (hp0 : 0 ≤ p) (hp1 : p ≤ 1) : FiniteLaw (Finset α) where + weight := bernoulliWeight p + nonneg := bernoulliWeight_nonneg hp0 hp1 + total := bernoulliWeight_sum p + +@[simp] theorem bernoulliLaw_weight (p : ℝ) (hp0 : 0 ≤ p) (hp1 : p ≤ 1) (W : Finset α) : + (bernoulliLaw p hp0 hp1).weight W = bernoulliWeight p W := rfl + +@[simp] theorem bernoulliLaw_expectation (p : ℝ) (hp0 : 0 ≤ p) (hp1 : p ≤ 1) + (f : Finset α → ℝ) : + (bernoulliLaw p hp0 hp1).expectation f = bernoulliExpectation p f := rfl + +@[simp] theorem bernoulliLaw_prob (p : ℝ) (hp0 : 0 ≤ p) (hp1 : p ≤ 1) + (P : Finset α → Prop) : (bernoulliLaw p hp0 hp1).prob P = bernoulliProbability p P := rfl + +theorem bernoulliProbability_eq_expectation (p : ℝ) (P : Finset α → Prop) : + bernoulliProbability p P = bernoulliExpectation p (fun W => if P W then 1 else 0) := by + classical + simp [bernoulliProbability, bernoulliExpectation, mul_ite] + +theorem subset_indicator_product (A W : Finset α) : + (if A ⊆ W then (1 : ℝ) else 0) = + ∏ x, (if x ∈ A then (if x ∈ W then (1 : ℝ) else 0) else 1) := by + rw [Fintype.prod_ite_mem, Finset.prod_boole] + rfl + +theorem bernoulliProbability_subset (p : ℝ) (A : Finset α) : + bernoulliProbability p (fun W => A ⊆ W) = p ^ A.card := by + trans bernoulliExpectation p (fun W => + ∏ x, (if x ∈ A then (if x ∈ W then (1 : ℝ) else 0) else 1)) + · unfold bernoulliProbability bernoulliExpectation + apply Finset.sum_congr rfl + intro W _ + dsimp only + by_cases hs : A ⊆ W + · have hh := (subset_indicator_product A W).symm + simp only [ite_eq_left hs] at hh + rw [hh] + simp [hs] + · have hh := (subset_indicator_product A W).symm + simp only [ite_eq_right hs] at hh + rw [hh] + simp [hs] + calc + bernoulliExpectation p (fun W => + ∏ x, (if x ∈ A then (if x ∈ W then (1 : ℝ) else 0) else 1)) = + ∏ x, (p * (if x ∈ A then (1 : ℝ) else 1) + + (1 - p) * (if x ∈ A then (0 : ℝ) else 1)) := by + simpa only [decide_eq_true_eq, Bool.true_eq, ite_true, Bool.false_eq_true, ite_false] using + bernoulliExpectation_product p + (fun x b => if x ∈ A then (if b then (1 : ℝ) else 0) else 1) + _ = ∏ x, (if x ∈ A then p else 1) := by + apply Finset.prod_congr rfl + intro x _ + by_cases hx : x ∈ A <;> simp [hx] + _ = p ^ A.card := by rw [Fintype.prod_ite_mem]; simp + +theorem bernoulliWeight_eq_mass (p : ℝ) (s : Finset α) : + bernoulliWeight p s = bernoulliMass p s := by + simp only [bernoulliWeight, bernoulliMass, Finset.prod_ite, + Finset.filter_mem_eq_inter, Finset.univ_inter, + Finset.filter_notMem_eq_sdiff, Finset.prod_const] + +@[simp] theorem cubeSet_finsetBoolEquiv (s : Finset α) : + cubeSet (finsetBoolEquiv s) = s := cubeSet_decide s + +@[simp] theorem cubeWeight_finsetBoolEquiv (p : ℝ) (s : Finset α) : + cubeWeight p (finsetBoolEquiv s) = bernoulliWeight p s := by + simp [cubeWeight, bitWeight, finsetBoolEquiv, bernoulliWeight] + +omit [DecidableEq α] in +theorem cubeWeight_nonneg {p : ℝ} (hp0 : 0 ≤ p) (hp1 : p ≤ 1) (x : α → Bool) : + 0 ≤ cubeWeight p x := + Finset.prod_nonneg (fun i _ => bitWeight_nonneg hp0 hp1 (x i)) + +theorem cubeWeight_sum (p : ℝ) : ∑ x : α → Bool, cubeWeight p x = 1 := by + rw [← (finsetBoolEquiv (α := α)).sum_comp (cubeWeight p)] + simpa only [cubeWeight_finsetBoolEquiv] using bernoulliWeight_sum (α := α) p + +theorem cubeExpectation_eq_bernoulliExpectation (p : ℝ) (f : (α → Bool) → ℝ) : + cubeExpectation p f = bernoulliExpectation p (fun s => f (finsetBoolEquiv s)) := by + unfold cubeExpectation bernoulliExpectation + rw [← (finsetBoolEquiv (α := α)).sum_comp (fun x => cubeWeight p x * f x)] + simp only [cubeWeight_finsetBoolEquiv] + +theorem cubeExpectation_product (p : ℝ) (f : α → Bool → ℝ) : + cubeExpectation p (fun x => ∏ i, f i (x i)) = + ∏ i, (p * f i true + (1 - p) * f i false) := by + rw [cubeExpectation_eq_bernoulliExpectation] + exact bernoulliExpectation_product p f + +theorem cubeExpectation_familyIndicator (p : ℝ) (D : Family α) : + cubeExpectation p (familyIndicator D) = familyMeasure p D := by + rw [cubeExpectation_eq_bernoulliExpectation] + simp only [bernoulliExpectation, familyIndicator, cubeSet_finsetBoolEquiv, + mul_ite, mul_one, mul_zero, bernoulliWeight_eq_mass] + rw [← Finset.sum_filter, Finset.filter_mem_eq_inter, Finset.univ_inter] + rfl + +theorem bernoulliLaw_prob_subset (p : ℝ) (hp0 : 0 ≤ p) (hp1 : p ≤ 1) + (A : Finset α) : + (bernoulliLaw p hp0 hp1).prob (fun s => A ⊆ s) = p ^ A.card := + bernoulliProbability_subset p A + +theorem bernoulliLaw_prob_mem (p : ℝ) (hp0 : 0 ≤ p) (hp1 : p ≤ 1) (a : α) : + (bernoulliLaw p hp0 hp1).prob (fun s => a ∈ s) = p := by + simpa using bernoulliLaw_prob_subset p hp0 hp1 ({a} : Finset α) + +theorem disjoint_indicator_product (A W : Finset α) : + (if Disjoint W A then (1 : ℝ) else 0) = + ∏ x, (if x ∈ A then (if x ∈ W then (0 : ℝ) else 1) else 1) := by + simp only [Finset.disjoint_right] + rw [Fintype.prod_ite_mem] + have h (x : α) : (if x ∈ W then (0 : ℝ) else 1) = + if x ∉ W then 1 else 0 := by + by_cases hx : x ∈ W <;> simp [hx] + simp_rw [h] + rw [Finset.prod_boole] + by_cases hexp : ∀ i ∈ A, i ∉ W + · have himp : ∀ ⦃i : α⦄, i ∈ A → i ∉ W := by + intro i hi + exact hexp i hi + simp only [ite_eq_left himp] + · have himp : ¬ (∀ ⦃i : α⦄, i ∈ A → i ∉ W) := by + intro hi + exact hexp (fun i hai => hi hai) + simp only [ite_eq_right himp] + +theorem bernoulliProbability_disjoint (p : ℝ) (A : Finset α) : + bernoulliProbability p (fun W => Disjoint W A) = (1 - p) ^ A.card := by + rw [bernoulliProbability_eq_expectation] + trans bernoulliExpectation p (fun W => + ∏ x, (if x ∈ A then (if x ∈ W then (0 : ℝ) else 1) else 1)) + · congr 1 + funext W + by_cases h : Disjoint W A <;> + simpa [h] using disjoint_indicator_product A W + calc + bernoulliExpectation p (fun W => + ∏ x, (if x ∈ A then (if x ∈ W then (0 : ℝ) else 1) else 1)) = + ∏ x, (p * (if x ∈ A then (0 : ℝ) else 1) + + (1 - p) * (if x ∈ A then (1 : ℝ) else 1)) := by + simpa only [decide_eq_true_eq, Bool.true_eq, ite_true, Bool.false_eq_true, ite_false] using + bernoulliExpectation_product p + (fun x b => if x ∈ A then (if b then (0 : ℝ) else 1) else 1) + _ = ∏ x, (if x ∈ A then 1 - p else 1) := by + apply Finset.prod_congr rfl + intro x _ + by_cases hx : x ∈ A <;> simp [hx] + _ = (1 - p) ^ A.card := by rw [Fintype.prod_ite_mem]; simp + +theorem bernoulliLaw_prob_disjoint (p : ℝ) (hp0 : 0 ≤ p) (hp1 : p ≤ 1) + (A : Finset α) : + (bernoulliLaw p hp0 hp1).prob (fun W => Disjoint W A) = (1 - p) ^ A.card := + bernoulliProbability_disjoint p A + +theorem bernoulliLaw_expect_sum_mem (p : ℝ) (hp0 : 0 ≤ p) (hp1 : p ≤ 1) + (f : α → ℝ) : + (bernoulliLaw p hp0 hp1).expectation (fun W => ∑ x ∈ W, f x) = p * ∑ x, f x := by + classical + let μ : FiniteLaw (Finset α) := bernoulliLaw p hp0 hp1 + have hsum (W : Finset α) : + (∑ x ∈ W, f x) = ∑ x, if x ∈ W then f x else 0 := by + rw [← Finset.sum_filter, Finset.filter_mem_eq_inter, Finset.univ_inter] + have hx (x : α) : + μ.expectation (fun W => if x ∈ W then f x else 0) = p * f x := by + calc + _ = μ.expectation (fun W => f x * (if x ∈ W then 1 else 0)) := by + congr 1 + funext W + by_cases h : x ∈ W <;> simp [h] + _ = f x * μ.prob (fun W => x ∈ W) := by + rw [FiniteLaw.expectation_smul] + apply congrArg (fun z : ℝ => f x * z) + rw [FiniteLaw.prob_eq_expectation] + apply congrArg μ.expectation + funext W + by_cases h : x ∈ W <;> simp [h] + _ = p * f x := by + rw [show μ.prob (fun W => x ∈ W) = p from bernoulliLaw_prob_mem p hp0 hp1 x] + exact mul_comm _ _ + change μ.expectation (fun W => ∑ x ∈ W, f x) = p * ∑ x, f x + simp_rw [hsum] + rw [FiniteLaw.expectation_sum] + simp_rw [hx] + simpa only [Finset.mem_univ, ite_true] using (Finset.mul_sum Finset.univ f p).symm + +end TalagrandDiscreteConvexity + +end + +end OAI diff --git a/lean/OAI/Combinatorics/DiscreteConvexity/BinNumerics.lean b/lean/OAI/Combinatorics/DiscreteConvexity/BinNumerics.lean new file mode 100644 index 0000000000000000000000000000000000000000..3fc751321b76674211e5017957baafe7e8836476 --- /dev/null +++ b/lean/OAI/Combinatorics/DiscreteConvexity/BinNumerics.lean @@ -0,0 +1,178 @@ +import Mathlib.Basic.Real.Basic +import Mathlib.Data.Finset.Lattice.Fold +import Mathlib.Algebra.BigOperators.Group.Finset.Sigma +import Mathlib.Algebra.BigOperators.Ring.Finset +import Mathlib.Algebra.Order.BigOperators.Group.Finset +import Mathlib.Tactic.Linarith +import Mathlib.Tactic.NormNum +import Lean.Elab.Tactic.Omega +import Mathlib.Tactic.Positivity +import Mathlib.Tactic.Ring + +namespace OAI + +namespace TalagrandDiscreteConvexity + +open scoped BigOperators + +private theorem half_range_sum (n : ℕ) : + (∑ i ∈ Finset.range n, (1 / 2 : ℝ) ^ i) + 2 * (1 / 2 : ℝ) ^ n = 2 := by + induction n with + | zero => norm_num + | succ n ih => + rw [Finset.sum_range_succ, pow_succ] + nlinarith [ih] + +private theorem finite_half_sum_le_two (s : Finset ℕ) : + (∑ i ∈ s, (1 / 2 : ℝ) ^ i) ≤ 2 := by + have hsub : s ⊆ Finset.range (s.sup id + 1) := by + intro i hi + exact Finset.mem_range.mpr (Nat.lt_succ_of_le (Finset.le_sup (f := id) hi)) + have hle : (∑ i ∈ s, (1 / 2 : ℝ) ^ i) ≤ + ∑ i ∈ Finset.range (s.sup id + 1), (1 / 2 : ℝ) ^ i := + Finset.sum_le_sum_of_subset_of_nonneg hsub (by + intro i hi hnot + positivity) + have hgeom := half_range_sum (s.sup id + 1) + have hp : 0 ≤ (1 / 2 : ℝ) ^ (s.sup id + 1) := by positivity + linarith + +private theorem finite_small_base_sum_le_two (s : Finset ℕ) {a : ℝ} + (ha : 0 ≤ a) (ha' : a ≤ 1 / 2) : (∑ i ∈ s, a ^ i) ≤ 2 := by + calc + (∑ i ∈ s, a ^ i) ≤ ∑ i ∈ s, (1 / 2 : ℝ) ^ i := + Finset.sum_le_sum (fun i _ => pow_le_pow_left₀ ha ha' i) + _ ≤ 2 := finite_half_sum_le_two s + +private theorem finite_quadrant_sum_le_four (T : Finset (ℕ × ℕ)) {a : ℝ} + (ha : 0 ≤ a) (ha' : a ≤ 1 / 2) : + (∑ c ∈ T, a ^ c.1 * a ^ c.2) ≤ 4 := by + have hsub : T ⊆ (T.image Prod.fst) ×ˢ (T.image Prod.snd) := by + intro c hc + exact Finset.mem_product.mpr + ⟨Finset.mem_image_of_mem _ hc, Finset.mem_image_of_mem _ hc⟩ + calc + (∑ c ∈ T, a ^ c.1 * a ^ c.2) ≤ + ∑ c ∈ (T.image Prod.fst) ×ˢ (T.image Prod.snd), a ^ c.1 * a ^ c.2 := + Finset.sum_le_sum_of_subset_of_nonneg hsub (by + intro c hc hnot + exact mul_nonneg (pow_nonneg ha _) (pow_nonneg ha _)) + _ = (∑ i ∈ T.image Prod.fst, a ^ i) * (∑ j ∈ T.image Prod.snd, a ^ j) := by + rw [Finset.sum_product, Finset.sum_mul_sum] + _ ≤ 2 * 2 := + mul_le_mul (finite_small_base_sum_le_two _ ha ha') + (finite_small_base_sum_le_two _ ha ha') + (Finset.sum_nonneg fun _ _ => pow_nonneg ha _) (by norm_num) + _ = 4 := by norm_num + +/-- A finite occupied-bin estimate, with no infinite-series premise. -/ +theorem finite_bin_geometric_bound (B : Finset (ℕ × ℕ)) + (hB : ∀ b ∈ B, 1 ≤ b.1 ∧ 64 * b.1 ≤ b.2) {a : ℝ} + (ha : 0 ≤ a) (ha' : a ≤ 1 / 2) : + (∑ b ∈ B, a ^ b.2) ≤ 4 * a ^ 64 := by + let shift : ℕ × ℕ → ℕ × ℕ := fun b => (b.1 - 1, b.2 - b.1 - 63) + have hinj : Set.InjOn shift B := by + intro b hb c hc heq + have hb' := hB b hb + have hc' := hB c hc + have heq₁ : b.1 - 1 = c.1 - 1 := congrArg Prod.fst heq + have heq₂ : b.2 - b.1 - 63 = c.2 - c.1 - 63 := congrArg Prod.snd heq + apply Prod.ext <;> omega + have heq : (∑ b ∈ B, a ^ b.2) = + a ^ 64 * ∑ c ∈ B.image shift, a ^ c.1 * a ^ c.2 := by + rw [Finset.mul_sum, Finset.sum_image hinj] + apply Finset.sum_congr rfl + intro b hb + have hb' := hB b hb + have hexp : b.2 = 64 + (b.1 - 1) + (b.2 - b.1 - 63) := by omega + change a ^ b.2 = a ^ 64 * (a ^ (b.1 - 1) * a ^ (b.2 - b.1 - 63)) + calc + a ^ b.2 = a ^ (64 + (b.1 - 1) + (b.2 - b.1 - 63)) := congrArg (a ^ ·) hexp + _ = a ^ 64 * (a ^ (b.1 - 1) * a ^ (b.2 - b.1 - 63)) := by + simp only [pow_add, mul_assoc] + rw [heq] + calc + a ^ 64 * (∑ c ∈ B.image shift, a ^ c.1 * a ^ c.2) ≤ a ^ 64 * 4 := + mul_le_mul_of_nonneg_left (finite_quadrant_sum_le_four _ ha ha') + (pow_nonneg ha _) + _ = 4 * a ^ 64 := mul_comm _ _ + +/-- The total bin-cover cost is strictly below one quarter. -/ +theorem finite_bin_cost_lt_quarter (B : Finset (ℕ × ℕ)) + (hB : ∀ b ∈ B, 1 ≤ b.1 ∧ 64 * b.1 ≤ b.2) : + (∑ b ∈ B, 3 * (1 / 2 : ℝ) ^ b.2) < 1 / 4 := by + rw [← Finset.mul_sum] + have h := finite_bin_geometric_bound B hB (a := (1 / 2 : ℝ)) + (by norm_num) (by norm_num) + have hn : (3 : ℝ) * (4 * (1 / 2 : ℝ) ^ 64) < 1 / 4 := by norm_num + exact lt_of_le_of_lt (mul_le_mul_of_nonneg_left h (by norm_num)) hn + +/-- The total contribution of uncovered bins is below the exceptional threshold. -/ +theorem finite_bin_power_lt_threshold (B : Finset (ℕ × ℕ)) + (hB : ∀ b ∈ B, 1 ≤ b.1 ∧ 64 * b.1 ≤ b.2) : + (∑ b ∈ B, (1 / 2 : ℝ) ^ (4 * b.2)) < (1 / 2 : ℝ) ^ 32 := by + have h := finite_bin_geometric_bound B hB (a := (1 / 2 : ℝ) ^ 4) + (by norm_num) (by norm_num) + have heq : (∑ b ∈ B, (1 / 2 : ℝ) ^ (4 * b.2)) = + ∑ b ∈ B, ((1 / 2 : ℝ) ^ 4) ^ b.2 := by + simp only [pow_mul] + rw [heq] + exact lt_of_le_of_lt h (by norm_num) + +/-- Large weights can be bought outright at a total factor of at most `1/64`. -/ +theorem outright_weight_le {r : ℕ} {q w : ℝ} (hr : 1 ≤ r) (hq : 0 ≤ q) + (hw : (1 / 2 : ℝ) ^ (64 * r) ≤ w) : + (q / (2 : ℝ) ^ 70) ^ r ≤ (1 / 64 : ℝ) * q ^ r * w := by + have hsmall : (1 / 2 : ℝ) ^ (6 * r) ≤ (1 / 64 : ℝ) := by + have h := pow_le_pow_of_le_one (by norm_num : (0 : ℝ) ≤ 1 / 2) + (by norm_num : (1 / 2 : ℝ) ≤ 1) (show 6 ≤ 6 * r by omega) + norm_num at h ⊢ + exact h + have hqpow : 0 ≤ q ^ r := pow_nonneg hq _ + calc + (q / (2 : ℝ) ^ 70) ^ r = q ^ r * (1 / 2 : ℝ) ^ (70 * r) := by + simp only [div_eq_mul_inv, mul_pow, one_mul, pow_mul, inv_pow] + _ = q ^ r * ((1 / 2 : ℝ) ^ (6 * r) * (1 / 2 : ℝ) ^ (64 * r)) := by + rw [← pow_add, show 6 * r + 64 * r = 70 * r by omega] + _ ≤ q ^ r * ((1 / 64 : ℝ) * w) := by + apply mul_le_mul_of_nonneg_left _ hqpow + exact mul_le_mul hsmall hw (by positivity) (by norm_num) + _ = (1 / 64 : ℝ) * q ^ r * w := by ring + +/-- The lower edge of a bin bounds its cardinality at the reduced density. -/ +theorem bin_card_cost_bound {n r h : ℕ} {q : ℝ} (hq : 0 < q) + (hw : (n : ℝ) * q ^ r * (1 / 2 : ℝ) ^ (h + 1) ≤ 1) : + (n : ℝ) * (q / (2 : ℝ) ^ 70) ^ r ≤ (2 : ℝ) ^ (h + 1) := by + have hrho : q / (2 : ℝ) ^ 70 ≤ q := div_le_self hq.le (by norm_num) + have hden : (1 / 2 : ℝ) ^ (h + 1) * (2 : ℝ) ^ (h + 1) = 1 := by + rw [← mul_pow] + norm_num + calc + (n : ℝ) * (q / (2 : ℝ) ^ 70) ^ r ≤ (n : ℝ) * q ^ r := + mul_le_mul_of_nonneg_left (pow_le_pow_left₀ (by positivity) hrho r) (by positivity) + _ = ((n : ℝ) * q ^ r * (1 / 2 : ℝ) ^ (h + 1)) * (2 : ℝ) ^ (h + 1) := by + calc + (n : ℝ) * q ^ r = ((n : ℝ) * q ^ r) * + ((1 / 2 : ℝ) ^ (h + 1) * (2 : ℝ) ^ (h + 1)) := by rw [hden, mul_one] + _ = _ := by ring + _ ≤ 1 * (2 : ℝ) ^ (h + 1) := + mul_le_mul_of_nonneg_right hw (by positivity) + _ = (2 : ℝ) ^ (h + 1) := one_mul _ + +/-- Fewer than `2^(12h)` weights at most `2⁻ʰ` have small sixteenth-power sum. -/ +theorem bin_power_bound {m h : ℕ} (hm : m ≤ 2 ^ (12 * h)) : + (m : ℝ) * ((1 / 2 : ℝ) ^ h) ^ 16 ≤ (1 / 2 : ℝ) ^ (4 * h) := by + have hm' : (m : ℝ) ≤ (2 : ℝ) ^ (12 * h) := by + simpa only [Nat.cast_pow, Nat.cast_ofNat] using (Nat.cast_le (α := ℝ)).mpr hm + calc + (m : ℝ) * ((1 / 2 : ℝ) ^ h) ^ 16 ≤ + (2 : ℝ) ^ (12 * h) * ((1 / 2 : ℝ) ^ h) ^ 16 := + mul_le_mul_of_nonneg_right hm' (by positivity) + _ = (1 / 2 : ℝ) ^ (4 * h) := by + rw [← pow_mul, show h * 16 = 12 * h + 4 * h by omega, + pow_add, ← mul_assoc, ← mul_pow] + norm_num + +end TalagrandDiscreteConvexity + +end OAI diff --git a/lean/OAI/Combinatorics/DiscreteConvexity/Bins.lean b/lean/OAI/Combinatorics/DiscreteConvexity/Bins.lean new file mode 100644 index 0000000000000000000000000000000000000000..d6c303172ddcf437bf2187618048dadeebd7c86c --- /dev/null +++ b/lean/OAI/Combinatorics/DiscreteConvexity/Bins.lean @@ -0,0 +1,167 @@ +import OAI.Combinatorics.DiscreteConvexity.Basic +import OAI.Combinatorics.DiscreteConvexity.DyadicBins +import OAI.Combinatorics.DiscreteConvexity.FiniteFibers +import OAI.Combinatorics.DiscreteConvexity.BinNumerics + +namespace OAI + +open scoped BigOperators + +namespace TalagrandDiscreteConvexity + +variable {α : Type*} [Fintype α] [DecidableEq α] + +/-- The generators whose weights pay directly for their cost. -/ +noncomputable def largeWeightFamily (W : Finset α → ℝ) : Family α := by + classical + exact Finset.univ.filter fun U => U ≠ ∅ ∧ (1 / 2 : ℝ) ^ (64 * U.card) ≤ W U + +/-- The remaining nonzero weights; this finite family is partitioned into bins. -/ +noncomputable def smallWeightFamily (W : Finset α → ℝ) : Family α := by + classical + exact Finset.univ.filter fun U => + U ≠ ∅ ∧ 0 < W U ∧ W U < (1 / 2 : ℝ) ^ (64 * U.card) + +noncomputable def weightBinKey (W : Finset α → ℝ) (U : Finset α) : ℕ × ℕ := + (U.card, binExponent (W U)) + +noncomputable def occupiedWeightBins (W : Finset α → ℝ) : Finset (ℕ × ℕ) := + FiniteFibers.keys (smallWeightFamily W) (weightBinKey W) + +noncomputable def weightBin (W : Finset α → ℝ) (b : ℕ × ℕ) : Family α := + FiniteFibers.fiber (smallWeightFamily W) (weightBinKey W) b + +@[simp] theorem mem_largeWeightFamily {W : Finset α → ℝ} {U : Finset α} : + U ∈ largeWeightFamily W ↔ + U ≠ ∅ ∧ (1 / 2 : ℝ) ^ (64 * U.card) ≤ W U := by + classical + simp [largeWeightFamily] + +@[simp] theorem mem_smallWeightFamily {W : Finset α → ℝ} {U : Finset α} : + U ∈ smallWeightFamily W ↔ + U ≠ ∅ ∧ 0 < W U ∧ W U < (1 / 2 : ℝ) ^ (64 * U.card) := by + classical + simp [smallWeightFamily] + +theorem mem_weightBin {W : Finset α → ℝ} {U : Finset α} {b : ℕ × ℕ} : + U ∈ weightBin W b ↔ U ∈ smallWeightFamily W ∧ weightBinKey W U = b := by + classical + simp [weightBin, FiniteFibers.fiber] + +theorem weightBin_card {W : Finset α → ℝ} {U : Finset α} {b : ℕ × ℕ} + (hU : U ∈ weightBin W b) : U.card = b.1 := by + exact congrArg Prod.fst (mem_weightBin.mp hU).2 + +theorem weightBin_bounds {W : Finset α → ℝ} {U : Finset α} {b : ℕ × ℕ} + (hU : U ∈ weightBin W b) : + (1 / 2 : ℝ) ^ (b.2 + 1) < W U ∧ W U ≤ (1 / 2 : ℝ) ^ b.2 := by + have hmem := mem_weightBin.mp hU + have hw := mem_smallWeightFamily.mp hmem.1 + have hle : W U ≤ 1 := hw.2.2.le.trans (pow_le_one₀ (by norm_num) (by norm_num)) + have hbin := binExponent_spec hw.2.1 hle + have he : binExponent (W U) = b.2 := congrArg Prod.snd hmem.2 + simpa only [he] using hbin + +theorem occupiedWeightBins_bounds {W : Finset α → ℝ} {b : ℕ × ℕ} + (hb : b ∈ occupiedWeightBins W) : 1 ≤ b.1 ∧ 64 * b.1 ≤ b.2 := by + classical + obtain ⟨U, hU, rfl⟩ := Finset.mem_image.mp hb + have hw := mem_smallWeightFamily.mp hU + exact ⟨Finset.one_le_card.mpr (Finset.nonempty_iff_ne_empty.mpr hw.1), + le_binExponent_of_lt_pow hw.2.1 hw.2.2⟩ + +omit [DecidableEq α] in +theorem subfamily_weight_sum_le {q : ℝ} {W : Finset α → ℝ} + (hq : 0 ≤ q) (hW : ∀ U, 0 ≤ W U) + (hglobal : (∑ U : Finset α, q ^ U.card * W U) ≤ 1) (A : Family α) : + (∑ U ∈ A, q ^ U.card * W U) ≤ 1 := by + exact (Finset.sum_le_univ_sum_of_nonneg + (fun U => mul_nonneg (pow_nonneg hq _) (hW U))).trans hglobal + +/-- Each occupied bin satisfies the size hypothesis of the covering lemma. -/ +theorem weightBin_cost_bound {q : ℝ} {W : Finset α → ℝ} + (hq : 0 < q) (hW : ∀ U, 0 ≤ W U) + (hglobal : (∑ U : Finset α, q ^ U.card * W U) ≤ 1) (b : ℕ × ℕ) : + ((weightBin W b).card : ℝ) * (q / (2 : ℝ) ^ 70) ^ b.1 ≤ + (2 : ℝ) ^ (b.2 + 1) := by + have hlo : ((weightBin W b).card : ℝ) * q ^ b.1 * + (1 / 2 : ℝ) ^ (b.2 + 1) ≤ 1 := by + calc + _ = ∑ U ∈ weightBin W b, q ^ b.1 * (1 / 2 : ℝ) ^ (b.2 + 1) := by + simp [Finset.sum_const, nsmul_eq_mul, mul_assoc] + _ ≤ ∑ U ∈ weightBin W b, q ^ U.card * W U := by + apply Finset.sum_le_sum + intro U hU + rw [weightBin_card hU] + exact mul_le_mul_of_nonneg_left (weightBin_bounds hU).1.le (pow_nonneg hq.le _) + _ ≤ 1 := subfamily_weight_sum_le hq.le hW hglobal _ + exact bin_card_cost_bound hq hlo + +/-- All large weights together have cost at most one sixty-fourth. -/ +theorem largeWeightFamily_cost_le {q : ℝ} {W : Finset α → ℝ} + (hq : 0 ≤ q) (hW : ∀ U, 0 ≤ W U) + (hglobal : (∑ U : Finset α, q ^ U.card * W U) ≤ 1) : + cost (q / (2 : ℝ) ^ 70) (largeWeightFamily W) ≤ 1 / 64 := by + calc + _ ≤ ∑ U ∈ largeWeightFamily W, (1 / 64 : ℝ) * (q ^ U.card * W U) := by + apply Finset.sum_le_sum + intro U hU + have hw := mem_largeWeightFamily.mp hU + simpa only [mul_assoc] using outright_weight_le + (Finset.one_le_card.mpr (Finset.nonempty_iff_ne_empty.mpr hw.1)) hq hw.2 + _ = (1 / 64 : ℝ) * ∑ U ∈ largeWeightFamily W, q ^ U.card * W U := by + rw [Finset.mul_sum] + _ ≤ (1 / 64 : ℝ) * 1 := mul_le_mul_of_nonneg_left + (subfamily_weight_sum_le hq hW hglobal _) (by norm_num) + _ = 1 / 64 := by ring + +/-- In an uncovered bin, the sixteenth powers have the required geometric bound. -/ +theorem weightBin_power_sum_le {W : Finset α → ℝ} (hW : ∀ U, 0 ≤ W U) + (S : Finset α) (b : ℕ × ℕ) + (hcount : ((weightBin W b).filter (fun U => U ⊆ S)).card ≤ 2 ^ (12 * b.2)) : + (∑ U ∈ (weightBin W b).filter (fun U => U ⊆ S), (W U) ^ 16) ≤ + (1 / 2 : ℝ) ^ (4 * b.2) := by + calc + _ ≤ ∑ U ∈ (weightBin W b).filter (fun U => U ⊆ S), + ((1 / 2 : ℝ) ^ b.2) ^ 16 := by + apply Finset.sum_le_sum + intro U hU + exact pow_le_pow_left₀ (hW U) (weightBin_bounds (Finset.mem_filter.mp hU).1).2 _ + _ = (((weightBin W b).filter (fun U => U ⊆ S)).card : ℝ) * + ((1 / 2 : ℝ) ^ b.2) ^ 16 := by simp [Finset.sum_const, nsmul_eq_mul] + _ ≤ (1 / 2 : ℝ) ^ (4 * b.2) := bin_power_bound hcount + +/-- Removing zero weights and partitioning the remainder is a finite identity. -/ +theorem subset_power_sum_le_bins {W : Finset α → ℝ} (hW : ∀ U, 0 ≤ W U) + (S : Finset α) (hlarge : ∀ U ∈ largeWeightFamily W, ¬ U ⊆ S) : + (∑ U ∈ S.powerset.erase ∅, (W U) ^ 16) ≤ + ∑ b ∈ occupiedWeightBins W, + ∑ U ∈ (weightBin W b).filter (fun U => U ⊆ S), (W U) ^ 16 := by + classical + let A := S.powerset.erase ∅ + have hzero : (∑ U ∈ A, (W U) ^ 16) = + ∑ U ∈ A.filter (fun U => 0 < W U), (W U) ^ 16 := by + symm + apply Finset.sum_subset (Finset.filter_subset _ _) + intro U hU hnot + have hn : ¬ 0 < W U := fun h => hnot (Finset.mem_filter.mpr ⟨hU, h⟩) + have hz : W U = 0 := le_antisymm (le_of_not_gt hn) (hW U) + simp [hz] + have hsub : A.filter (fun U => 0 < W U) ⊆ + (smallWeightFamily W).filter (fun U => U ⊆ S) := by + intro U hU + obtain ⟨hUA, hpos⟩ := Finset.mem_filter.mp hU + obtain ⟨hne, hUS⟩ := Finset.mem_erase.mp hUA + have hsubset : U ⊆ S := Finset.mem_powerset.mp hUS + refine Finset.mem_filter.mpr ⟨mem_smallWeightFamily.mpr ⟨hne, hpos, ?_⟩, hsubset⟩ + by_contra hlt + exact hlarge U (mem_largeWeightFamily.mpr ⟨hne, le_of_not_gt hlt⟩) hsubset + calc + _ = ∑ U ∈ A.filter (fun U => 0 < W U), (W U) ^ 16 := hzero + _ ≤ ∑ U ∈ (smallWeightFamily W).filter (fun U => U ⊆ S), (W U) ^ 16 := + Finset.sum_le_sum_of_subset_of_nonneg hsub (fun U _ _ => pow_nonneg (hW U) _) + _ = _ := FiniteFibers.sum_filter_eq_sum_fibers _ _ _ _ + +end TalagrandDiscreteConvexity + +end OAI diff --git a/lean/OAI/Combinatorics/DiscreteConvexity/ColumnExpansion.lean b/lean/OAI/Combinatorics/DiscreteConvexity/ColumnExpansion.lean new file mode 100644 index 0000000000000000000000000000000000000000..0455e5eba88b472ba9b196dbaadc0349a5a3c487 --- /dev/null +++ b/lean/OAI/Combinatorics/DiscreteConvexity/ColumnExpansion.lean @@ -0,0 +1,66 @@ +import Mathlib.Algebra.BigOperators.Ring.Finset +import Mathlib.Basic.Real.Basic + +namespace OAI + +/-! +# A product expansion on a prescribed set of coordinates + +Only coordinates in `S` contribute correction terms. Expanding their product +therefore gives a sum indexed by `S.powerset`, with the factors outside `S` +left unchanged. +-/ + +namespace TalagrandDiscreteConvexity + +open scoped BigOperators + +variable {V : Type*} [Fintype V] [DecidableEq V] + +private theorem prod_ite_split (S U : Finset V) (P C : V → ℝ) (hU : U ⊆ S) : + (∏ i, if i ∈ U then C i else P i) = + ((∏ i ∈ U, C i) * ∏ i ∈ S \ U, P i) * ∏ i ∈ Sᶜ, P i := by + calc + (∏ i, if i ∈ U then C i else P i) = + (∏ i ∈ S, if i ∈ U then C i else P i) * + ∏ i ∈ Sᶜ, if i ∈ U then C i else P i := + (Finset.prod_mul_prod_compl S _).symm + _ = ((∏ i ∈ U, C i) * ∏ i ∈ S \ U, P i) * ∏ i ∈ Sᶜ, P i := by + congr 1 + · simpa only [Finset.piecewise, Finset.inter_eq_right.mpr hU] using + Finset.prod_piecewise S U C P + · apply Finset.prod_congr rfl + intro i hi + have hiU : i ∉ U := fun h => (Finset.mem_compl.mp hi) (hU h) + simp only [ite_eq_right hiU] + +/-- Expand a product with correction terms restricted to `S`. -/ +theorem prod_sub_ite_eq_sum_powerset (S : Finset V) (P C : V → ℝ) : + (∏ i, (P i - if i ∈ S then C i else 0)) = + ∑ U ∈ S.powerset, (-1 : ℝ) ^ U.card * ∏ i, if i ∈ U then C i else P i := by + have hsplit : + (∏ i, (P i - if i ∈ S then C i else 0)) = + (∏ i ∈ S, (P i - C i)) * ∏ i ∈ Sᶜ, P i := by + calc + (∏ i, (P i - if i ∈ S then C i else 0)) = + (∏ i ∈ S, (P i - if i ∈ S then C i else 0)) * + ∏ i ∈ Sᶜ, (P i - if i ∈ S then C i else 0) := + (Finset.prod_mul_prod_compl S _).symm + _ = (∏ i ∈ S, (P i - C i)) * ∏ i ∈ Sᶜ, P i := by + congr 1 + · apply Finset.prod_congr rfl + intro i hi + simp only [ite_eq_left hi] + · apply Finset.prod_congr rfl + intro i hi + simp only [ite_eq_right (Finset.mem_compl.mp hi), sub_zero] + rw [hsplit, Finset.prod_sub, Finset.sum_mul] + apply Finset.sum_congr rfl + intro U hU + rw [prod_ite_split S U P C (Finset.mem_powerset.mp hU)] + simp only [mul_assoc] + rw [mul_left_comm (∏ i ∈ S \ U, P i) (∏ i ∈ U, C i)] + +end TalagrandDiscreteConvexity + +end OAI diff --git a/lean/OAI/Combinatorics/DiscreteConvexity/CoordinateObservations.lean b/lean/OAI/Combinatorics/DiscreteConvexity/CoordinateObservations.lean new file mode 100644 index 0000000000000000000000000000000000000000..ffe71d78b780f2ec4cd33bb8d5bd8ebda227d3f4 --- /dev/null +++ b/lean/OAI/Combinatorics/DiscreteConvexity/CoordinateObservations.lean @@ -0,0 +1,81 @@ +import OAI.Combinatorics.DiscreteConvexity.Bernoulli +import OAI.Combinatorics.DiscreteConvexity.ProductProbability + +namespace OAI + +/-! +# Boolean observations of finite product laws + +Independent Boolean observations with common success probability have the +Bernoulli law on subsets, both on individual atoms and on arbitrary families. +-/ + +open scoped BigOperators +noncomputable section + +namespace TalagrandDiscreteConvexity + +variable {α : Type*} [Fintype α] [DecidableEq α] + {Ω : α → Type*} [∀ i, Fintype (Ω i)] + +/-- A specified set of successful coordinate observations has its Bernoulli mass. -/ +theorem prob_pi_cubeSet_eq_mass (μ : ∀ i, FiniteLaw (Ω i)) + (obs : ∀ i, Ω i → Bool) (p : ℝ) + (hobs : ∀ i, (μ i).prob (fun w => obs i w = true) = p) (s : Finset α) : + (FiniteLaw.pi μ).prob (fun ω => cubeSet (fun i => obs i (ω i)) = s) = + bernoulliMass p s := by + classical + have hcoord (i : α) : + (μ i).prob (fun w => (obs i w = true ↔ i ∈ s)) = + if i ∈ s then p else 1 - p := by + by_cases hi : i ∈ s + · simpa [hi] using hobs i + · simpa [hi, hobs i] using (μ i).prob_compl (fun w => obs i w = true) + calc + (FiniteLaw.pi μ).prob (fun ω => cubeSet (fun i => obs i (ω i)) = s) = + (FiniteLaw.pi μ).prob (fun ω => ∀ i, obs i (ω i) = true ↔ i ∈ s) := by + congr 1 + funext ω + apply propext + simp only [Finset.ext_iff, mem_cubeSet] + _ = ∏ i, (μ i).prob (fun w => (obs i w = true ↔ i ∈ s)) := + FiniteLaw.prob_pi μ (fun i w => (obs i w = true ↔ i ∈ s)) + _ = ∏ i, if i ∈ s then p else 1 - p := by + apply Finset.prod_congr rfl + intro i _ + exact hcoord i + _ = bernoulliMass p s := bernoulliWeight_eq_mass p s + +/-- Membership of the observed set in a family has exactly its Bernoulli measure. -/ +theorem prob_pi_cubeSet_mem_family (μ : ∀ i, FiniteLaw (Ω i)) + (obs : ∀ i, Ω i → Bool) (p : ℝ) + (hobs : ∀ i, (μ i).prob (fun w => obs i w = true) = p) (D : Family α) : + (FiniteLaw.pi μ).prob (fun ω => cubeSet (fun i => obs i (ω i)) ∈ D) = + familyMeasure p D := by + classical + let f : (∀ i, Ω i) → Finset α := fun ω => cubeSet (fun i => obs i (ω i)) + calc + (FiniteLaw.pi μ).prob (fun ω => cubeSet (fun i => obs i (ω i)) ∈ D) = + ((FiniteLaw.pi μ).map f).prob (fun s => s ∈ D) := + (FiniteLaw.prob_map (FiniteLaw.pi μ) f (fun s => s ∈ D)).symm + _ = ∑ s ∈ D, ((FiniteLaw.pi μ).map f).weight s := by + calc + ((FiniteLaw.pi μ).map f).prob (fun s => s ∈ D) = + ∑ s : Finset α, if s ∈ D then ((FiniteLaw.pi μ).map f).weight s else 0 := by + unfold FiniteLaw.prob + apply Finset.sum_congr rfl + intro s _ + by_cases hs : s ∈ D <;> simp [hs] + _ = _ := Finset.sum_ite_mem_eq D ((FiniteLaw.pi μ).map f).weight + _ = ∑ s ∈ D, bernoulliMass p s := by + apply Finset.sum_congr rfl + intro s _ + rw [FiniteLaw.map_weight_eq_prob] + exact prob_pi_cubeSet_eq_mass μ obs p hobs s + _ = familyMeasure p D := rfl + +end TalagrandDiscreteConvexity + +end + +end OAI diff --git a/lean/OAI/Combinatorics/DiscreteConvexity/CoveringBasic.lean b/lean/OAI/Combinatorics/DiscreteConvexity/CoveringBasic.lean new file mode 100644 index 0000000000000000000000000000000000000000..ef60fb1185ba82804b19554e48a0affe531eade9 --- /dev/null +++ b/lean/OAI/Combinatorics/DiscreteConvexity/CoveringBasic.lean @@ -0,0 +1,118 @@ +import OAI.Combinatorics.DiscreteConvexity.Basic +import Mathlib.Data.Fintype.Pi +import Mathlib.Data.Fintype.Prod +import Mathlib.Data.Fintype.Powerset +import Mathlib.Data.Finset.Union + +namespace OAI + +/-! +# Finite objects in the elementary covering argument + +Sampling is indexed by ordered pairs of edges, including diagonal pairs. +Different pairs remain different indices even if their unions coincide. +Residual generators are indexed by injective ordered tuples. +-/ + +namespace TalagrandDiscreteConvexity.Covering + +variable {V : Type*} [DecidableEq V] + +/-- An ordered tuple of distinct members of a finite edge family. -/ +def EdgeTuple (H : Family V) (t : ℕ) := + {f : Fin t → ↥H // Function.Injective f} + +noncomputable instance edgeTupleFintype (H : Family V) (t : ℕ) : + Fintype (EdgeTuple H t) := by + classical + exact Subtype.fintype _ + +/-- All independent ordered-pair sampling indices. -/ +abbrev PairIndex (H : Family V) := ↥H × ↥H + +/-- A sampling outcome specifies precisely the pairs selected. -/ +abbrev Sample (H : Family V) := Finset (PairIndex H) + +def tupleUnion {H : Family V} {t : ℕ} (f : EdgeTuple H t) : Finset V := + Finset.univ.biUnion (fun i => (f.val i).val) + +noncomputable def tuplePairs {H : Family V} {t : ℕ} + (f : EdgeTuple H t) : Finset (PairIndex H) := by + classical + exact Finset.univ.image (fun ij : Fin t × Fin t => (f.val ij.1, f.val ij.2)) + +@[simp] theorem mem_tupleUnion {H : Family V} {t : ℕ} + {f : EdgeTuple H t} {v : V} : + v ∈ tupleUnion f ↔ ∃ i, v ∈ (f.val i).val := by + simp [tupleUnion] + +@[simp] theorem mem_tuplePairs {H : Family V} {t : ℕ} + {f : EdgeTuple H t} {p : PairIndex H} : + p ∈ tuplePairs f ↔ ∃ i j, (f.val i, f.val j) = p := by + classical + simp [tuplePairs, Prod.exists] + +/-- The weighted number of edges containing a prescribed vertex set. -/ +noncomputable def weightedDegree (H : Family V) (rho : ℝ) (r : ℕ) + (I : Finset V) : ℝ := by + classical + exact ((H.filter (fun e => I ⊆ e)).card : ℝ) * rho ^ (r - I.card) + +/-- Edges avoiding all prescribed initial generators. -/ +noncomputable def regularFamily (H C0 : Family V) : Family V := by + classical + exact H.filter (fun e => ∀ I ∈ C0, ¬ I ⊆ e) + +@[simp] theorem mem_regularFamily {H C0 : Family V} {e : Finset V} : + e ∈ regularFamily H C0 ↔ e ∈ H ∧ ∀ I ∈ C0, ¬ I ⊆ e := by + classical + simp [regularFamily] + +theorem regularFamily_subset (H C0 : Family V) : regularFamily H C0 ⊆ H := by + intro e he + exact (mem_regularFamily.mp he).1 + +section FiniteGround + +variable [Fintype V] + +/-- The high weighted-degree sets used as the initial generators. -/ +noncomputable def initialFamily (H : Family V) (rho : ℝ) (r : ℕ) + (T : ℝ) : Family V := by + classical + exact Finset.univ.filter (fun I => I.card ≤ r ∧ T < weightedDegree H rho r I) + +/-- The regular edges for the actual high-degree initial family. -/ +noncomputable def regularEdges (H : Family V) (rho : ℝ) (r : ℕ) + (T : ℝ) : Family V := regularFamily H (initialFamily H rho r T) + +/-- Sets containing at least `m` distinct edges of the original family. -/ +noncomputable def denseFamily (H : Family V) (m : ℕ) : Family V := by + classical + exact Finset.univ.filter (fun S => m ≤ (H.filter (fun e => e ⊆ S)).card) + +@[simp] theorem mem_initialFamily {H : Family V} {rho T : ℝ} + {r : ℕ} {I : Finset V} : + I ∈ initialFamily H rho r T ↔ I.card ≤ r ∧ T < weightedDegree H rho r I := by + classical + simp [initialFamily] + +@[simp] theorem mem_regularEdges {H : Family V} {rho T : ℝ} + {r : ℕ} {e : Finset V} : + e ∈ regularEdges H rho r T ↔ + e ∈ H ∧ ∀ I ∈ initialFamily H rho r T, ¬ I ⊆ e := by + exact mem_regularFamily + +@[simp] theorem mem_denseFamily {H : Family V} {m : ℕ} {S : Finset V} : + S ∈ denseFamily H m ↔ m ≤ (H.filter (fun e => e ⊆ S)).card := by + classical + simp [denseFamily] + +theorem regularEdges_subset (H : Family V) (rho : ℝ) (r : ℕ) (T : ℝ) : + regularEdges H rho r T ⊆ H := regularFamily_subset _ _ + +end FiniteGround + +end TalagrandDiscreteConvexity.Covering + +end OAI diff --git a/lean/OAI/Combinatorics/DiscreteConvexity/CoveringBinomialBounds.lean b/lean/OAI/Combinatorics/DiscreteConvexity/CoveringBinomialBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..d636e0cea118a3313509758ad6b09deb2cfc1aac --- /dev/null +++ b/lean/OAI/Combinatorics/DiscreteConvexity/CoveringBinomialBounds.lean @@ -0,0 +1,53 @@ +import Mathlib.Data.Finset.Powerset +import Mathlib.Data.Nat.Choose.Bounds +import Mathlib.Data.Nat.Choose.Sum + +namespace OAI + +/-! +# Counting bounded-size subsets + +Subsets of cardinality at most `r` are counted by a partial binomial sum. +The elementary bound by `(1 + B.card)^r` includes `r = 0` and empty `B`. +-/ + +namespace TalagrandDiscreteConvexity.Covering + +open scoped BigOperators + +/-- Partition the subsets of `B` of size at most `r` by their cardinality. -/ +theorem card_subsets_card_le {V : Type*} [DecidableEq V] (B : Finset V) (r : ℕ) : + (B.powerset.filter (fun I => I.card ≤ r)).card = + ∑ i ∈ Finset.range (r + 1), Nat.choose B.card i := by + simpa only [Finset.mem_range, Nat.lt_succ_iff, + ← Finset.powersetCard_eq_filter, Finset.card_powersetCard] using + (Finset.sum_card_fiberwise_eq_card_filter B.powerset + (Finset.range (r + 1)) Finset.card).symm + +/-- A partial binomial sum is bounded by the number of length-`r` words +over an alphabet with `n + 1` letters. -/ +theorem sum_choose_range_le_pow (n r : ℕ) : + (∑ i ∈ Finset.range (r + 1), Nat.choose n i) ≤ (1 + n) ^ r := by + calc + (∑ i ∈ Finset.range (r + 1), Nat.choose n i) + ≤ ∑ i ∈ Finset.range (r + 1), n ^ i * Nat.choose r i := by + apply Finset.sum_le_sum + intro i hi + have hc : 1 ≤ Nat.choose r i := + Nat.choose_pos (Nat.le_of_lt_succ (Finset.mem_range.mp hi)) + exact (Nat.choose_le_pow n i).trans (by + simpa only [Nat.mul_one] using Nat.mul_le_mul_left (n ^ i) hc) + _ = (n + 1) ^ r := by + simpa using (add_pow n 1 r).symm + _ = (1 + n) ^ r := by rw [Nat.add_comm] + +/-- The number of subsets of `B` of size at most `r` is at most `(1 + B.card)^r`. -/ +theorem card_subsets_card_le_pow {V : Type*} [DecidableEq V] + (B : Finset V) (r : ℕ) : + (B.powerset.filter (fun I => I.card ≤ r)).card ≤ (1 + B.card) ^ r := by + rw [card_subsets_card_le] + exact sum_choose_range_le_pow B.card r + +end TalagrandDiscreteConvexity.Covering + +end OAI diff --git a/lean/OAI/Combinatorics/DiscreteConvexity/CoveringNumericalBounds.lean b/lean/OAI/Combinatorics/DiscreteConvexity/CoveringNumericalBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..c80b4aa8230eeaab84b36ea7745df5db3630b37a --- /dev/null +++ b/lean/OAI/Combinatorics/DiscreteConvexity/CoveringNumericalBounds.lean @@ -0,0 +1,240 @@ +import Mathlib.Analysis.Complex.Exponential +import Mathlib.Tactic.Linarith +import Mathlib.Tactic.Positivity +import Mathlib.Tactic.Ring + +namespace OAI + +namespace TalagrandDiscreteConvexity.Covering.NumericalBounds + +/-- Number of distinct edges in a residual tuple. -/ +def m (h : ℕ) : ℕ := 2 ^ (12 * h) + +/-- Threshold for a large weighted degree. -/ +def T (h : ℕ) : ℝ := 2 ^ (4 * h) + +/-- Independent sampling probability for each ordered pair. -/ +noncomputable def p (h : ℕ) : ℝ := (2 ^ (8 * h))⁻¹ + +/-- Exponent bounding one regular extension factor. -/ +def A (r h : ℕ) : ℕ := 4 * h + 13 * r * h + +theorem m_pos (h : ℕ) : 0 < m h := by + unfold m + positivity + +theorem T_pos (h : ℕ) : 0 < T h := by + unfold T + positivity + +theorem T_nonneg (h : ℕ) : 0 ≤ T h := (T_pos h).le + +theorem p_pos (h : ℕ) : 0 < p h := by + unfold p + positivity + +theorem p_nonneg (h : ℕ) : 0 ≤ p h := (p_pos h).le + +theorem p_le_one (h : ℕ) : p h ≤ 1 := by + unfold p + exact inv_le_one_of_one_le₀ (one_le_pow₀ (by norm_num : (1 : ℝ) ≤ 2)) + +/-- The count of possible padded extensions has this dyadic upper bound. -/ +theorem extension_base_le_pow (r h : ℕ) (hrh : r ≤ h) : + 1 + r * m h ≤ 2 ^ (13 * h) := by + have hm : 1 ≤ m h := m_pos h + have hpow : h + 1 ≤ 2 ^ h := Nat.lt_two_pow_self + calc + 1 + r * m h ≤ m h + h * m h := + Nat.add_le_add hm (Nat.mul_le_mul_right (m h) hrh) + _ = (h + 1) * m h := by ring + _ ≤ 2 ^ h * m h := Nat.mul_le_mul_right (m h) hpow + _ = 2 ^ (13 * h) := by + rw [m, ← pow_add] + congr 1 + omega + +/-- The extension factor from the weighted-degree estimate is at most +the stated natural power of two. -/ +theorem extension_factor_le_pow (r h : ℕ) (hrh : r ≤ h) : + T h * (1 + (r : ℝ) * (m h : ℝ)) ^ r ≤ (2 : ℝ) ^ A r h := by + have hbase : 1 + (r : ℝ) * (m h : ℝ) ≤ (2 : ℝ) ^ (13 * h) := by + exact_mod_cast extension_base_le_pow r h hrh + calc + T h * (1 + (r : ℝ) * (m h : ℝ)) ^ r ≤ + T h * ((2 : ℝ) ^ (13 * h)) ^ r := + mul_le_mul_of_nonneg_left (pow_le_pow_left₀ (by positivity) hbase r) (T_nonneg h) + _ = (2 : ℝ) ^ A r h := by + rw [T, ← pow_mul, ← pow_add] + congr 1 + unfold A + ring + +/-- The quadratic polynomial exponent is dominated by the sampling budget. -/ +theorem exponent_budget_nat (r h : ℕ) (hrh : r ≤ h) (hh : 64 ≤ h) : + A r h + 1 ≤ 2 ^ (4 * h) := by + have hh1 : 1 ≤ h := by omega + have hrh' : r * h ≤ h * h := Nat.mul_le_mul_right h hrh + have hh' : h ≤ h * h := by + simpa only [Nat.mul_one] using Nat.mul_le_mul_left h hh1 + have hquadratic : A r h + 1 ≤ 18 * h ^ 2 := by + unfold A + nlinarith + have hpow : h ≤ 2 ^ h := Nat.le_of_lt Nat.lt_two_pow_self + have hsquare : h ^ 2 ≤ 2 ^ (2 * h) := by + calc + h ^ 2 ≤ (2 ^ h) ^ 2 := Nat.pow_le_pow_left hpow 2 + _ = 2 ^ (2 * h) := by rw [← pow_mul, Nat.mul_comm h 2] + have h18 : 18 ≤ 2 ^ (2 * h) := by + calc + 18 ≤ (2 : ℕ) ^ 5 := by norm_num + _ ≤ 2 ^ (2 * h) := + pow_le_pow_right₀ (by norm_num : (1 : ℕ) ≤ 2) (by omega) + calc + A r h + 1 ≤ 18 * h ^ 2 := hquadratic + _ ≤ 18 * 2 ^ (2 * h) := Nat.mul_le_mul_left 18 hsquare + _ ≤ 2 ^ (2 * h) * 2 ^ (2 * h) := Nat.mul_le_mul_right _ h18 + _ = 2 ^ (4 * h) := by + rw [← pow_add] + congr 1 + omega + +/-- The chosen pair probability times the tuple length is exactly the +weighted-degree threshold. -/ +theorem p_mul_m (h : ℕ) : p h * (m h : ℝ) = T h := by + simp only [p, m, T, Nat.cast_pow, Nat.cast_ofNat] + rw [show 12 * h = 8 * h + 4 * h by omega, pow_add, ← mul_assoc, + inv_mul_cancel₀ (pow_ne_zero _ (by norm_num : (2 : ℝ) ≠ 0)), one_mul] + +theorem exponent_budget (r h : ℕ) (hrh : r ≤ h) (hh : 64 ≤ h) : + (A r h : ℝ) + 1 ≤ p h * (m h : ℝ) := by + rw [p_mul_m] + unfold T + exact_mod_cast exponent_budget_nat r h hrh hh + +/-- A dyadic growth factor is dominated by independent avoidance when each +block has one additional unit of exponential sampling budget. -/ +theorem dyadic_residual_bound (a n : ℕ) (prob : ℝ) + (hprob : prob ≤ 1) + (hbudget : (a : ℝ) + 1 ≤ prob * (n : ℝ)) : + ((2 : ℝ) ^ a) ^ n * (1 - prob) ^ (n * n) ≤ ((2 : ℝ) ^ n)⁻¹ := by + have hnonneg : 0 ≤ 1 - prob := sub_nonneg.mpr hprob + have htwo : (2 : ℝ) ≤ Real.exp 1 := by + linarith [Real.add_one_le_exp (1 : ℝ)] + have hpow : (2 : ℝ) ^ a ≤ Real.exp (a : ℝ) := by + calc + (2 : ℝ) ^ a ≤ (Real.exp 1) ^ a := + pow_le_pow_left₀ (by norm_num) htwo a + _ = Real.exp (a : ℝ) := by rw [← Real.exp_nat_mul, mul_one] + have hexponent : (a : ℝ) + (n : ℝ) * (-prob) ≤ -1 := by + calc + (a : ℝ) + (n : ℝ) * (-prob) = (a : ℝ) - prob * (n : ℝ) := by ring + _ ≤ -1 := by linarith + have hhalf : Real.exp (-1 : ℝ) ≤ (2 : ℝ)⁻¹ := by + rw [Real.exp_neg] + exact (inv_le_inv₀ (Real.exp_pos 1) (by norm_num)).mpr htwo + have hbase : (2 : ℝ) ^ a * (1 - prob) ^ n ≤ (2 : ℝ)⁻¹ := by + calc + (2 : ℝ) ^ a * (1 - prob) ^ n ≤ + Real.exp (a : ℝ) * (Real.exp (-prob)) ^ n := + mul_le_mul hpow + (pow_le_pow_left₀ hnonneg (Real.one_sub_le_exp_neg prob) n) + (pow_nonneg hnonneg n) (Real.exp_nonneg _) + _ = Real.exp ((a : ℝ) + (n : ℝ) * (-prob)) := by + rw [← Real.exp_nat_mul, ← Real.exp_add] + _ ≤ Real.exp (-1) := Real.exp_le_exp.mpr hexponent + _ ≤ (2 : ℝ)⁻¹ := hhalf + simpa only [mul_pow, ← pow_mul, inv_pow] using + pow_le_pow_left₀ + (mul_nonneg (pow_nonneg (by norm_num : (0 : ℝ) ≤ 2) a) + (pow_nonneg hnonneg n)) hbase n + +/-- The actual residual tuple-growth factor times its exact avoidance +probability is at most the reciprocal dyadic tuple-length power. -/ +theorem residual_cost_le_inv_pow (r h : ℕ) (hrh : r ≤ h) (hh : 64 ≤ h) : + (T h * (1 + (r : ℝ) * (m h : ℝ)) ^ r) ^ m h * + (1 - p h) ^ (m h * m h) ≤ ((2 : ℝ) ^ m h)⁻¹ := by + have hfactor : 0 ≤ T h * (1 + (r : ℝ) * (m h : ℝ)) ^ r := + mul_nonneg (T_nonneg h) (pow_nonneg (by positivity) r) + calc + (T h * (1 + (r : ℝ) * (m h : ℝ)) ^ r) ^ m h * + (1 - p h) ^ (m h * m h) ≤ + ((2 : ℝ) ^ A r h) ^ m h * (1 - p h) ^ (m h * m h) := + mul_le_mul_of_nonneg_right + (pow_le_pow_left₀ hfactor (extension_factor_le_pow r h hrh) (m h)) + (pow_nonneg (sub_nonneg.mpr (p_le_one h)) _) + _ ≤ ((2 : ℝ) ^ m h)⁻¹ := + dyadic_residual_bound (A r h) (m h) (p h) (p_le_one h) + (exponent_budget r h hrh hh) + +/-- The initial weighted-degree generators have the required numerical cost +after inserting the assumed upper bound on the total edge mass. -/ +theorem initial_cost_le (r h : ℕ) (hrh : r ≤ h) : + (T h)⁻¹ * (2 : ℝ) ^ r * (2 : ℝ) ^ (h + 1) ≤ + 2 * ((2 : ℝ) ^ (2 * h))⁻¹ := by + change ((2 : ℝ) ^ (4 * h))⁻¹ * (2 : ℝ) ^ r * (2 : ℝ) ^ (h + 1) ≤ _ + have hpos : 0 < (2 : ℝ) ^ (4 * h) := pow_pos (by norm_num) _ + have hcancel : + (2 : ℝ) ^ (4 * h) * (2 * ((2 : ℝ) ^ (2 * h))⁻¹) = + 2 * (2 : ℝ) ^ (2 * h) := by + rw [show 4 * h = 2 * h + 2 * h by omega, pow_add] + calc + _ = 2 * ((2 : ℝ) ^ (2 * h) * (2 : ℝ) ^ (2 * h) * + ((2 : ℝ) ^ (2 * h))⁻¹) := by ring + _ = 2 * (2 : ℝ) ^ (2 * h) := by rw [mul_self_mul_inv] + rw [mul_assoc, inv_mul_le_iff₀ hpos, hcancel] + calc + (2 : ℝ) ^ r * (2 : ℝ) ^ (h + 1) = (2 : ℝ) ^ (r + (h + 1)) := + (pow_add _ _ _).symm + _ ≤ (2 : ℝ) ^ (2 * h + 1) := + pow_le_pow_right₀ (by norm_num) (by omega) + _ = 2 * (2 : ℝ) ^ (2 * h) := by rw [pow_succ, mul_comm] + +/-- The sampled-pair numerical cost has the same bound as the initial cost. -/ +theorem pair_cost_le (r h : ℕ) (hrh : r ≤ h) : + p h * (2 : ℝ) ^ (h + 1) * (2 : ℝ) ^ r * T h ≤ + 2 * ((2 : ℝ) ^ (2 * h))⁻¹ := by + have hcancel : p h * T h = (T h)⁻¹ := by + change ((2 : ℝ) ^ (8 * h))⁻¹ * (2 : ℝ) ^ (4 * h) = + ((2 : ℝ) ^ (4 * h))⁻¹ + rw [show 8 * h = 4 * h + 4 * h by omega, pow_add, mul_inv_rev, + mul_assoc, inv_mul_cancel₀ (pow_ne_zero _ (by norm_num : (2 : ℝ) ≠ 0)), + mul_one] + calc + p h * (2 : ℝ) ^ (h + 1) * (2 : ℝ) ^ r * T h = + (p h * T h) * (2 : ℝ) ^ r * (2 : ℝ) ^ (h + 1) := by ring + _ = (T h)⁻¹ * (2 : ℝ) ^ r * (2 : ℝ) ^ (h + 1) := by rw [hcancel] + _ ≤ 2 * ((2 : ℝ) ^ (2 * h))⁻¹ := initial_cost_le r h hrh + +theorem h_le_m (h : ℕ) : h ≤ m h := by + calc + h ≤ 2 ^ h := Nat.le_of_lt Nat.lt_two_pow_self + _ ≤ 2 ^ (12 * h) := + pow_le_pow_right₀ (by norm_num : (1 : ℕ) ≤ 2) (by omega) + +/-- The sum of the two initial-scale costs and the residual dyadic cost +is at most the final covering budget. -/ +theorem final_cost_le (h : ℕ) (hh : 64 ≤ h) : + 4 * ((2 : ℝ) ^ (2 * h))⁻¹ + ((2 : ℝ) ^ m h)⁻¹ ≤ + 3 * ((2 : ℝ) ^ h)⁻¹ := by + have hpos : 0 < (2 : ℝ) ^ h := pow_pos (by norm_num) _ + have hfour : (4 : ℝ) ≤ (2 : ℝ) ^ h := by + calc + (4 : ℝ) = (2 : ℝ) ^ 2 := by norm_num + _ ≤ (2 : ℝ) ^ h := pow_le_pow_right₀ (by norm_num) (by omega) + have hfirst : 4 * ((2 : ℝ) ^ (2 * h))⁻¹ ≤ ((2 : ℝ) ^ h)⁻¹ := by + apply (mul_inv_le_iff₀ (pow_pos (by norm_num : (0 : ℝ) < 2) (2 * h))).2 + rw [show 2 * h = h + h by omega, pow_add, inv_mul_cancel_left₀ hpos.ne'] + exact hfour + have hlast : ((2 : ℝ) ^ m h)⁻¹ ≤ ((2 : ℝ) ^ h)⁻¹ := + inv_anti₀ hpos (pow_le_pow_right₀ (by norm_num) (h_le_m h)) + calc + 4 * ((2 : ℝ) ^ (2 * h))⁻¹ + ((2 : ℝ) ^ m h)⁻¹ ≤ + ((2 : ℝ) ^ h)⁻¹ + ((2 : ℝ) ^ h)⁻¹ := add_le_add hfirst hlast + _ = 2 * ((2 : ℝ) ^ h)⁻¹ := by ring + _ ≤ 3 * ((2 : ℝ) ^ h)⁻¹ := + mul_le_mul_of_nonneg_right (by norm_num) (inv_nonneg.mpr hpos.le) + +end TalagrandDiscreteConvexity.Covering.NumericalBounds + +end OAI diff --git a/lean/OAI/Combinatorics/DiscreteConvexity/CoveringPairCost.lean b/lean/OAI/Combinatorics/DiscreteConvexity/CoveringPairCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..7d4793730bea5ebb0ab80138e88f1121cd31ca0a --- /dev/null +++ b/lean/OAI/Combinatorics/DiscreteConvexity/CoveringPairCost.lean @@ -0,0 +1,82 @@ +import OAI.Combinatorics.DiscreteConvexity.CoveringRegularization +import OAI.Combinatorics.DiscreteConvexity.CoveringSampledFamilies +import OAI.Combinatorics.DiscreteConvexity.Bernoulli + +namespace OAI + +/-! +# The cost of sampled ordered pairs + +The expectation is bounded by counting pair unions with multiplicity. Its +deterministic bound uses the actual regularized edge family and the sharp +`2^r` extension estimate, rather than the coarser tuple-extension estimate. +-/ + +namespace TalagrandDiscreteConvexity.Covering + +open scoped BigOperators + +variable {V : Type*} [Fintype V] [DecidableEq V] + +theorem regular_pair_weight_sum_le {H : Family V} {rho T : ℝ} {r : ℕ} + (hrho : 0 ≤ rho) (hT : 0 ≤ T) (hH : ∀ e ∈ H, e.card = r) : + (∑ p : PairIndex (regularEdges H rho r T), rho ^ (pairUnion p).card) ≤ + (H.card : ℝ) * rho ^ r * (2 : ℝ) ^ r * T := by + classical + let K := regularEdges H rho r T + have hK : K ⊆ H := regularEdges_subset H rho r T + have hinner (a : K) : + (∑ b : K, rho ^ (a.val ∪ b.val).card) ≤ rho ^ r * ((2 : ℝ) ^ r * T) := by + have ha : a.val.card = r := hH a.val (hK a.property) + have hext : (∑ b : K, rho ^ (b.val \ a.val).card) ≤ (2 : ℝ) ^ r * T := by + rw [Finset.sum_coe_sort K (fun b : Finset V => rho ^ (b \ a.val).card)] + exact regular_extension_le_two_pow hrho hT hH ha + calc + (∑ b : K, rho ^ (a.val ∪ b.val).card) = + ∑ b : K, rho ^ r * rho ^ (b.val \ a.val).card := by + apply Finset.sum_congr rfl + intro b _ + rw [Finset.union_comm, ← Finset.card_sdiff_add_card, pow_add, ha] + exact mul_comm _ _ + _ = rho ^ r * ∑ b : K, rho ^ (b.val \ a.val).card := + (Finset.mul_sum _ _ _).symm + _ ≤ rho ^ r * ((2 : ℝ) ^ r * T) := + mul_le_mul_of_nonneg_left hext (pow_nonneg hrho _) + have hcard : (K.card : ℝ) ≤ (H.card : ℝ) := by + exact_mod_cast Finset.card_le_card hK + have hfactor : 0 ≤ rho ^ r * ((2 : ℝ) ^ r * T) := + mul_nonneg (pow_nonneg hrho _) (mul_nonneg (pow_nonneg (by norm_num) _) hT) + calc + (∑ p : PairIndex K, rho ^ (pairUnion p).card) = + ∑ a : K, ∑ b : K, rho ^ (a.val ∪ b.val).card := by + simp only [PairIndex, Fintype.sum_prod_type, pairUnion] + _ ≤ ∑ _a : K, rho ^ r * ((2 : ℝ) ^ r * T) := + Finset.sum_le_sum (fun a _ => hinner a) + _ = (K.card : ℝ) * (rho ^ r * ((2 : ℝ) ^ r * T)) := by simp + _ ≤ (H.card : ℝ) * (rho ^ r * ((2 : ℝ) ^ r * T)) := + mul_le_mul_of_nonneg_right hcard hfactor + _ = (H.card : ℝ) * rho ^ r * (2 : ℝ) ^ r * T := by ring + +/-- The actual independent pair sample has small expected generator cost. +No identification of equal unions is made at the probability-index level. -/ +theorem expectation_sampledFamily_le {H : Family V} {rho T p : ℝ} {r : ℕ} + (hrho : 0 ≤ rho) (hT : 0 ≤ T) (hH : ∀ e ∈ H, e.card = r) + (hp0 : 0 ≤ p) (hp1 : p ≤ 1) : + (bernoulliLaw (α := PairIndex (regularEdges H rho r T)) p hp0 hp1).expectation + (fun sample => cost rho (sampledFamily (regularEdges H rho r T) sample)) ≤ + p * ((H.card : ℝ) * rho ^ r * (2 : ℝ) ^ r * T) := by + classical + let K := regularEdges H rho r T + let μ := bernoulliLaw (α := PairIndex K) p hp0 hp1 + calc + μ.expectation (fun sample => cost rho (sampledFamily K sample)) ≤ + μ.expectation (fun sample => ∑ pair ∈ sample, rho ^ (pairUnion pair).card) := + μ.expectation_mono (fun sample => cost_sampledFamily_le K sample hrho) + _ = p * ∑ pair : PairIndex K, rho ^ (pairUnion pair).card := + bernoulliLaw_expect_sum_mem p hp0 hp1 (fun pair => rho ^ (pairUnion pair).card) + _ ≤ p * ((H.card : ℝ) * rho ^ r * (2 : ℝ) ^ r * T) := + mul_le_mul_of_nonneg_left (regular_pair_weight_sum_le hrho hT hH) hp0 + +end TalagrandDiscreteConvexity.Covering + +end OAI diff --git a/lean/OAI/Combinatorics/DiscreteConvexity/CoveringRegularization.lean b/lean/OAI/Combinatorics/DiscreteConvexity/CoveringRegularization.lean new file mode 100644 index 0000000000000000000000000000000000000000..3657efe92cd8540e4aa42f5d2955c92b7807a284 --- /dev/null +++ b/lean/OAI/Combinatorics/DiscreteConvexity/CoveringRegularization.lean @@ -0,0 +1,232 @@ +import OAI.Combinatorics.DiscreteConvexity.CoveringBasic +import OAI.Combinatorics.DiscreteConvexity.CoveringBinomialBounds +import Mathlib.Combinatorics.Enumerative.DoubleCounting + +namespace OAI + +/-! +# Weighted-degree regularization + +The initial family is the actual family of high weighted-degree subsets. +Double counting bounds its cost. An edge surviving this deletion has bounded +weighted degree at every one of its subsets. Grouping surviving edges by their +intersection with `B` gives the extension estimates used for pair sampling and +for residual tuples. No regularity property is assumed separately. +-/ + +namespace TalagrandDiscreteConvexity.Covering + +open scoped BigOperators + +variable {V : Type*} [Fintype V] [DecidableEq V] + +/-- Count incidences between edges and subsets of cardinality at most `r`. -/ +theorem incidence_count (H : Family V) (r : ℕ) + (hH : ∀ e ∈ H, e.card = r) : + (∑ I ∈ Finset.univ.filter (fun I : Finset V => I.card ≤ r), + (H.filter (fun e => I ⊆ e)).card) = H.card * 2 ^ r := by + classical + let K : Finset (Finset V) := Finset.univ.filter (fun I => I.card ≤ r) + have hbelow (e : Finset V) (he : e ∈ H) : + K.filter (fun I => I ⊆ e) = e.powerset := by + apply Finset.ext + intro I + simp only [K, Finset.mem_filter, Finset.mem_univ, true_and, Finset.mem_powerset] + constructor + · exact fun h => h.2 + · intro hIe + exact ⟨(Finset.card_le_card hIe).trans_eq (hH e he), hIe⟩ + calc + (∑ I ∈ K, (H.filter (fun e => I ⊆ e)).card) = + ∑ e ∈ H, (K.filter (fun I => I ⊆ e)).card := by + exact Finset.sum_card_bipartiteAbove_eq_sum_card_bipartiteBelow + (fun I e : Finset V => I ⊆ e) + _ = ∑ _e ∈ H, 2 ^ r := by + apply Finset.sum_congr rfl + intro e he + rw [hbelow e he, Finset.card_powerset, hH e he] + _ = H.card * 2 ^ r := by simp + +omit [Fintype V] in +theorem weightedDegree_nonneg {H : Family V} {rho : ℝ} {r : ℕ} {I : Finset V} + (hρ : 0 ≤ rho) : 0 ≤ weightedDegree H rho r I := by + classical + exact mul_nonneg (Nat.cast_nonneg _) (pow_nonneg hρ _) + +/-- The weighted incidence identity is valid even at `rho = 0`. -/ +theorem weighted_incidence_count (H : Family V) (rho : ℝ) (r : ℕ) + (hH : ∀ e ∈ H, e.card = r) : + (∑ I ∈ Finset.univ.filter (fun I : Finset V => I.card ≤ r), + weightedDegree H rho r I * rho ^ I.card) = + (2 : ℝ) ^ r * (H.card : ℝ) * rho ^ r := by + classical + let K : Finset (Finset V) := Finset.univ.filter (fun I => I.card ≤ r) + have hcast : (∑ I ∈ K, ((H.filter (fun e => I ⊆ e)).card : ℝ)) = + (H.card : ℝ) * (2 : ℝ) ^ r := by + simpa only [Nat.cast_sum, Nat.cast_mul, Nat.cast_pow, Nat.cast_ofNat] using + congrArg (fun n : ℕ => (n : ℝ)) (incidence_count H r hH) + calc + (∑ I ∈ K, weightedDegree H rho r I * rho ^ I.card) = + (∑ I ∈ K, ((H.filter (fun e => I ⊆ e)).card : ℝ)) * rho ^ r := by + rw [Finset.sum_mul] + apply Finset.sum_congr rfl + intro I hI + have hIr : I.card ≤ r := (Finset.mem_filter.mp hI).2 + rw [weightedDegree, mul_assoc, ← pow_add, Nat.sub_add_cancel hIr] + _ = ((H.card : ℝ) * (2 : ℝ) ^ r) * rho ^ r := by rw [hcast] + _ = (2 : ℝ) ^ r * (H.card : ℝ) * rho ^ r := by + rw [mul_comm (H.card : ℝ) ((2 : ℝ) ^ r)] + +/-- The initial generators cost at most their weighted-incidence budget divided +by the high-degree threshold. -/ +theorem initial_cost_le {H : Family V} {rho T : ℝ} {r : ℕ} + (hρ : 0 ≤ rho) (hT : 0 < T) (hH : ∀ e ∈ H, e.card = r) : + cost rho (initialFamily H rho r T) ≤ + T⁻¹ * (2 : ℝ) ^ r * (H.card : ℝ) * rho ^ r := by + classical + let K : Finset (Finset V) := Finset.univ.filter (fun I => I.card ≤ r) + have hsub : initialFamily H rho r T ⊆ K := by + intro I hI + exact Finset.mem_filter.mpr ⟨Finset.mem_univ _, (mem_initialFamily.mp hI).1⟩ + have hbudget : T * cost rho (initialFamily H rho r T) ≤ + (2 : ℝ) ^ r * (H.card : ℝ) * rho ^ r := by + calc + T * cost rho (initialFamily H rho r T) = + ∑ I ∈ initialFamily H rho r T, T * rho ^ I.card := by + rw [cost, Finset.mul_sum] + _ ≤ ∑ I ∈ initialFamily H rho r T, + weightedDegree H rho r I * rho ^ I.card := by + apply Finset.sum_le_sum + intro I hI + exact mul_le_mul_of_nonneg_right (mem_initialFamily.mp hI).2.le + (pow_nonneg hρ _) + _ ≤ ∑ I ∈ K, weightedDegree H rho r I * rho ^ I.card := by + apply Finset.sum_le_sum_of_subset_of_nonneg hsub + intro I _ _ + exact mul_nonneg (weightedDegree_nonneg hρ) (pow_nonneg hρ _) + _ = (2 : ℝ) ^ r * (H.card : ℝ) * rho ^ r := + weighted_incidence_count H rho r hH + calc + cost rho (initialFamily H rho r T) ≤ + ((2 : ℝ) ^ r * (H.card : ℝ) * rho ^ r) / T := by + apply (le_div_iff₀ hT).mpr + simpa only [mul_comm] using hbudget + _ = T⁻¹ * (2 : ℝ) ^ r * (H.card : ℝ) * rho ^ r := by + rw [div_eq_mul_inv] + ac_rfl + +/-- Actual survival implies the weighted-degree bound at every subset of the +surviving edge. -/ +theorem regular_weightedDegree_le {H : Family V} {rho T : ℝ} {r : ℕ} + (hH : ∀ e ∈ H, e.card = r) {e I : Finset V} + (he : e ∈ regularEdges H rho r T) (hIe : I ⊆ e) : + weightedDegree H rho r I ≤ T := by + have heH : e ∈ H := (mem_regularEdges.mp he).1 + have hIr : I.card ≤ r := (Finset.card_le_card hIe).trans_eq (hH e heH) + apply le_of_not_gt + intro hlarge + exact (mem_regularEdges.mp he).2 I (mem_initialFamily.mpr ⟨hIr, hlarge⟩) hIe + +/-- Each nonempty intersection class contributes at most `T`, and the empty +classes contribute zero. -/ +private theorem regular_intersection_sum_le {H : Family V} {rho T : ℝ} {r : ℕ} + (hρ : 0 ≤ rho) (hT : 0 ≤ T) (hH : ∀ e ∈ H, e.card = r) + (B I : Finset V) : + (∑ e ∈ (regularEdges H rho r T).filter (fun e => e ∩ B = I), + rho ^ (e \ B).card) ≤ T := by + classical + let F := (regularEdges H rho r T).filter (fun e => e ∩ B = I) + by_cases hne : F.Nonempty + · obtain ⟨e₀, he₀⟩ := hne + have he₀reg := (Finset.mem_filter.mp he₀).1 + have he₀I : e₀ ∩ B = I := (Finset.mem_filter.mp he₀).2 + have hIe₀ : I ⊆ e₀ := by rw [← he₀I]; exact Finset.inter_subset_left + have hdegree := regular_weightedDegree_le hH he₀reg hIe₀ + have hsub : F ⊆ H.filter (fun e => I ⊆ e) := by + intro e he + obtain ⟨hereg, heI⟩ := Finset.mem_filter.mp he + refine Finset.mem_filter.mpr ⟨(mem_regularEdges.mp hereg).1, ?_⟩ + rw [← heI] + exact Finset.inter_subset_left + have hcards : (F.card : ℝ) ≤ ((H.filter (fun e => I ⊆ e)).card : ℝ) := + Nat.cast_le.mpr (Finset.card_le_card hsub) + calc + (∑ e ∈ F, rho ^ (e \ B).card) = (F.card : ℝ) * rho ^ (r - I.card) := by + calc + (∑ e ∈ F, rho ^ (e \ B).card) = ∑ _e ∈ F, rho ^ (r - I.card) := by + apply Finset.sum_congr rfl + intro e he + obtain ⟨hereg, heI⟩ := Finset.mem_filter.mp he + have hecard := hH e (mem_regularEdges.mp hereg).1 + have hpartition := Finset.card_sdiff_add_card_inter e B + rw [heI, hecard] at hpartition + have hdiff : (e \ B).card = r - I.card := by omega + rw [hdiff] + _ = (F.card : ℝ) * rho ^ (r - I.card) := by simp + _ ≤ weightedDegree H rho r I := + mul_le_mul_of_nonneg_right hcards (pow_nonneg hρ _) + _ ≤ T := hdegree + · have hF : F = ∅ := Finset.not_nonempty_iff_eq_empty.mp hne + change (∑ e ∈ F, rho ^ (e \ B).card) ≤ T + rw [hF, Finset.sum_empty] + exact hT + +/-- Extension cost for actual regular edges, with the exact number of possible +intersections with `B`. -/ +theorem regular_extension_le_card {H : Family V} {rho T : ℝ} {r : ℕ} + (hρ : 0 ≤ rho) (hT : 0 ≤ T) (hH : ∀ e ∈ H, e.card = r) (B : Finset V) : + (∑ e ∈ regularEdges H rho r T, rho ^ (e \ B).card) ≤ + T * ((B.powerset.filter (fun I => I.card ≤ r)).card : ℝ) := by + classical + let D := B.powerset.filter (fun I => I.card ≤ r) + have hmap : ∀ e ∈ regularEdges H rho r T, e ∩ B ∈ D := by + intro e he + refine Finset.mem_filter.mpr ⟨Finset.mem_powerset.mpr Finset.inter_subset_right, ?_⟩ + exact (Finset.card_le_card Finset.inter_subset_left).trans_eq + (hH e (mem_regularEdges.mp he).1) + calc + (∑ e ∈ regularEdges H rho r T, rho ^ (e \ B).card) = + ∑ I ∈ D, ∑ e ∈ (regularEdges H rho r T).filter (fun e => e ∩ B = I), + rho ^ (e \ B).card := + (Finset.sum_fiberwise_of_maps_to hmap (fun e => rho ^ (e \ B).card)).symm + _ ≤ ∑ _I ∈ D, T := by + apply Finset.sum_le_sum + intro I _ + exact regular_intersection_sum_le hρ hT hH B I + _ = T * (D.card : ℝ) := by simp [mul_comm] + +/-- The exact binomial extension bound from the covering lemma. -/ +theorem regular_extension_le_choose {H : Family V} {rho T : ℝ} {r : ℕ} + (hρ : 0 ≤ rho) (hT : 0 ≤ T) (hH : ∀ e ∈ H, e.card = r) (B : Finset V) : + (∑ e ∈ regularEdges H rho r T, rho ^ (e \ B).card) ≤ + T * (∑ i ∈ Finset.range (r + 1), (Nat.choose B.card i : ℝ)) := by + calc + _ ≤ T * ((B.powerset.filter (fun I => I.card ≤ r)).card : ℝ) := + regular_extension_le_card hρ hT hH B + _ = _ := by rw [card_subsets_card_le, Nat.cast_sum] + +/-- The polynomial version used for extending a residual tuple prefix. -/ +theorem regular_extension_le_pow {H : Family V} {rho T : ℝ} {r : ℕ} + (hρ : 0 ≤ rho) (hT : 0 ≤ T) (hH : ∀ e ∈ H, e.card = r) (B : Finset V) : + (∑ e ∈ regularEdges H rho r T, rho ^ (e \ B).card) ≤ + T * (1 + (B.card : ℝ)) ^ r := by + have hc : ((B.powerset.filter (fun I => I.card ≤ r)).card : ℝ) ≤ + (((1 + B.card) ^ r : ℕ) : ℝ) := + Nat.cast_le.mpr (card_subsets_card_le_pow B r) + have hc' : ((B.powerset.filter (fun I => I.card ≤ r)).card : ℝ) ≤ + (1 + (B.card : ℝ)) ^ r := by + simpa only [Nat.cast_pow, Nat.cast_add, Nat.cast_one] using hc + exact (regular_extension_le_card hρ hT hH B).trans (mul_le_mul_of_nonneg_left hc' hT) + +/-- An `r`-element prefix gives the sharper factor `2^r`, used for pairs. -/ +theorem regular_extension_le_two_pow {H : Family V} {rho T : ℝ} {r : ℕ} + (hρ : 0 ≤ rho) (hT : 0 ≤ T) (hH : ∀ e ∈ H, e.card = r) + {B : Finset V} (hB : B.card = r) : + (∑ e ∈ regularEdges H rho r T, rho ^ (e \ B).card) ≤ (2 : ℝ) ^ r * T := by + have h := regular_extension_le_choose hρ hT hH B + rw [hB, ← Nat.cast_sum, Nat.sum_range_choose, Nat.cast_pow, Nat.cast_ofNat] at h + simpa only [mul_comm] using h + +end TalagrandDiscreteConvexity.Covering + +end OAI diff --git a/lean/OAI/Combinatorics/DiscreteConvexity/CoveringResidualCost.lean b/lean/OAI/Combinatorics/DiscreteConvexity/CoveringResidualCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..498110490f0ae5163b4fb0562b3bcb27dfaa8bc6 --- /dev/null +++ b/lean/OAI/Combinatorics/DiscreteConvexity/CoveringResidualCost.lean @@ -0,0 +1,97 @@ +import OAI.Combinatorics.DiscreteConvexity.CoveringSampledFamilies +import OAI.Combinatorics.DiscreteConvexity.CoveringResidualProbability +import OAI.Combinatorics.DiscreteConvexity.CoveringResidualTuples +import OAI.Combinatorics.DiscreteConvexity.CoveringNumericalBounds + +namespace OAI + +/-! +# Expected cost of the actual residual generators + +Repeated unions are first counted with multiplicity. Each injective tuple +avoids exactly its distinct ordered-pair indices under the product Bernoulli +law. Finite linearity then separates this common survival probability from +the weighted tuple sum. +-/ + +namespace TalagrandDiscreteConvexity.Covering + +open scoped BigOperators Classical + +variable {V : Type*} [DecidableEq V] + +/-- The expected residual cost is bounded by the actual weighted tuple sum +times the exact probability of avoiding all ordered pairs of one tuple. -/ +theorem expectation_residualFamily_le (H : Family V) (rho : ℝ) + (hrho : 0 ≤ rho) (m : ℕ) (p : ℝ) (hp0 : 0 ≤ p) (hp1 : p ≤ 1) : + (bernoulliLaw (α := PairIndex H) p hp0 hp1).expectation + (fun sample => cost rho (residualFamily H m sample)) ≤ + tupleWeightSum H rho m * (1 - p) ^ (m * m) := by + classical + let μ := bernoulliLaw (α := PairIndex H) p hp0 hp1 + calc + μ.expectation (fun sample => cost rho (residualFamily H m sample)) ≤ + μ.expectation (fun sample => ∑ f : EdgeTuple H m, + if Disjoint sample (tuplePairs f) then rho ^ (tupleUnion f).card else 0) := + μ.expectation_mono (fun sample => cost_residualFamily_le H m sample hrho) + _ = ∑ f : EdgeTuple H m, μ.expectation (fun sample => + if Disjoint sample (tuplePairs f) then rho ^ (tupleUnion f).card else 0) := + μ.expectation_sum _ + _ = ∑ f : EdgeTuple H m, (1 - p) ^ (m * m) * rho ^ (tupleUnion f).card := by + apply Finset.sum_congr rfl + intro f _ + calc + μ.expectation (fun sample => if Disjoint sample (tuplePairs f) + then rho ^ (tupleUnion f).card else 0) = + μ.prob (fun sample => Disjoint sample (tuplePairs f)) * + rho ^ (tupleUnion f).card := by + simp only [FiniteLaw.expectation, FiniteLaw.prob, Finset.sum_mul] + apply Finset.sum_congr rfl + intro sample _ + by_cases hs : Disjoint sample (tuplePairs f) + · simp only [ite_eq_left hs] + · simp only [ite_eq_right hs, mul_zero, zero_mul] + _ = _ := congrArg (fun q : ℝ => q * rho ^ (tupleUnion f).card) + (tuple_survival_probability f p hp0 hp1) + _ = tupleWeightSum H rho m * (1 - p) ^ (m * m) := by + unfold tupleWeightSum tupleWeight + rw [← Finset.mul_sum] + exact mul_comm _ _ + +/-- Applying the proved tuple recurrence bounds the expected residual cost +using only the actual extension estimate for the edge family. -/ +theorem expectation_residualFamily_le_extension (H : Family V) + {rho T : ℝ} {r m : ℕ} (hrho : 0 ≤ rho) (hT : 0 ≤ T) + (uniform : ∀ e ∈ H, (e : Finset V).card = r) + (extension : ∀ B : Finset V, + (∑ e ∈ H, rho ^ (e \ B).card) ≤ T * (1 + (B.card : ℝ)) ^ r) + (p : ℝ) (hp0 : 0 ≤ p) (hp1 : p ≤ 1) : + (bernoulliLaw (α := PairIndex H) p hp0 hp1).expectation + (fun sample => cost rho (residualFamily H m sample)) ≤ + (T * (1 + ((r * m : ℕ) : ℝ)) ^ r) ^ m * (1 - p) ^ (m * m) := by + exact (expectation_residualFamily_le H rho hrho m p hp0 hp1).trans + (mul_le_mul_of_nonneg_right + (tupleWeightSum_le H (rho := rho) (T := T) (r := r) (m := m) + hrho hT uniform extension) + (pow_nonneg (sub_nonneg.mpr hp1) _)) + +theorem expectation_residualFamily_le_inv_pow (H : Family V) + {rho : ℝ} {r h : ℕ} (hrho : 0 ≤ rho) + (uniform : ∀ e ∈ H, (e : Finset V).card = r) + (extension : ∀ B : Finset V, (∑ e ∈ H, rho ^ (e \ B).card) ≤ + NumericalBounds.T h * (1 + (B.card : ℝ)) ^ r) + (hrh : r ≤ h) (hh : 64 ≤ h) : + (bernoulliLaw (α := PairIndex H) (NumericalBounds.p h) + (NumericalBounds.p_nonneg h) (NumericalBounds.p_le_one h)).expectation + (fun sample => cost rho (residualFamily H (NumericalBounds.m h) sample)) ≤ + ((2 : ℝ) ^ NumericalBounds.m h)⁻¹ := by + have hbound := expectation_residualFamily_le_extension H + (rho := rho) (r := r) (m := NumericalBounds.m h) hrho + (NumericalBounds.T_nonneg h) uniform extension (NumericalBounds.p h) + (NumericalBounds.p_nonneg h) (NumericalBounds.p_le_one h) + apply hbound.trans + simpa only [Nat.cast_mul] using NumericalBounds.residual_cost_le_inv_pow r h hrh hh + +end TalagrandDiscreteConvexity.Covering + +end OAI diff --git a/lean/OAI/Combinatorics/DiscreteConvexity/CoveringResidualProbability.lean b/lean/OAI/Combinatorics/DiscreteConvexity/CoveringResidualProbability.lean new file mode 100644 index 0000000000000000000000000000000000000000..09718aaa1c0c92fdfd165063a4534bf2a1394666 --- /dev/null +++ b/lean/OAI/Combinatorics/DiscreteConvexity/CoveringResidualProbability.lean @@ -0,0 +1,66 @@ +import OAI.Combinatorics.DiscreteConvexity.CoveringBasic +import OAI.Combinatorics.DiscreteConvexity.Bernoulli + +namespace OAI + +/-! +# Exact survival probability of a tuple of distinct edges + +The sampling coordinates are ordered pairs of edges, not their unions. Every +ordered pair of positions contributes a distinct coordinate, including each +diagonal position. The product Bernoulli law therefore assigns exactly +`(1 - p) ^ (m * m)` to the event that all these coordinates are absent. +-/ + +namespace TalagrandDiscreteConvexity.Covering + +/-- Applying an injection in both coordinates preserves ordered pairs. -/ +theorem orderedPairMap_injective {I E : Type*} {e : I → E} + (he : Function.Injective e) : + Function.Injective (fun ij : I × I => (e ij.1, e ij.2)) := by + intro ij kl h + apply Prod.ext + · exact he (congrArg Prod.fst h) + · exact he (congrArg Prod.snd h) + +variable {X : Type*} [DecidableEq X] + +noncomputable section + +/-- The tuple uses all `m * m` ordered pair coordinates, including the diagonal. -/ +theorem tuplePairs_card {H : Family X} {m : ℕ} (f : EdgeTuple H m) : + (tuplePairs f).card = m * m := by + classical + rw [tuplePairs, Finset.card_image_of_injective _ + (orderedPairMap_injective f.property)] + simp only [Finset.card_univ, Fintype.card_prod, Fintype.card_fin] + +/-- A diagonal edge pair is one of the sampled coordinates used by the tuple. -/ +theorem diagonal_mem_tuplePairs {H : Family X} {m : ℕ} + (f : EdgeTuple H m) (i : Fin m) : (f.val i, f.val i) ∈ tuplePairs f := by + exact mem_tuplePairs.mpr ⟨i, i, rfl⟩ + +/-- Avoiding the pair set means that none of the ordered tuple pairs was sampled. -/ +theorem disjoint_tuplePairs_iff {H : Family X} {m : ℕ} + (f : EdgeTuple H m) (sample : Sample H) : + Disjoint sample (tuplePairs f) ↔ ∀ i j, (f.val i, f.val j) ∉ sample := by + constructor + · intro h i j hij + exact Finset.disjoint_left.mp h hij (mem_tuplePairs.mpr ⟨i, j, rfl⟩) + · intro h + apply Finset.disjoint_left.mpr + intro pair hsample htuple + obtain ⟨i, j, rfl⟩ := mem_tuplePairs.mp htuple + exact h i j hsample + +/-- Exact residual probability under the actual finite product Bernoulli law. -/ +theorem tuple_survival_probability {H : Family X} {m : ℕ} + (f : EdgeTuple H m) (p : ℝ) (hp0 : 0 ≤ p) (hp1 : p ≤ 1) : + (bernoulliLaw (α := ↥H × ↥H) p hp0 hp1).prob + (fun sample => Disjoint sample (tuplePairs f)) = (1 - p) ^ (m * m) := by + rw [bernoulliLaw_prob_disjoint, tuplePairs_card] + +end +end TalagrandDiscreteConvexity.Covering + +end OAI diff --git a/lean/OAI/Combinatorics/DiscreteConvexity/CoveringResidualTuples.lean b/lean/OAI/Combinatorics/DiscreteConvexity/CoveringResidualTuples.lean new file mode 100644 index 0000000000000000000000000000000000000000..03bd2b3308a19a24e27964ed43ac598b0292815c --- /dev/null +++ b/lean/OAI/Combinatorics/DiscreteConvexity/CoveringResidualTuples.lean @@ -0,0 +1,200 @@ +import OAI.Combinatorics.DiscreteConvexity.CoveringBasic +import Mathlib.Data.Fin.Tuple.Basic +import Mathlib.Data.Fintype.BigOperators +import Mathlib.Algebra.Order.BigOperators.Group.Finset +import Mathlib.Algebra.BigOperators.Ring.Finset + +namespace OAI + +/-! +# The total weight of residual tuples + +We bound the sum over injective edge tuples by the sum over all edge tuples. +Splitting an unrestricted tuple into its first edge and its tail gives an +exact weighted recurrence. The per-union extension bound then controls every +step. No nonemptiness assumption on the edge family is needed. +-/ + +namespace TalagrandDiscreteConvexity.Covering + +open scoped BigOperators + +variable {V : Type*} [DecidableEq V] + +noncomputable section + +/-- The union of an unrestricted ordered edge tuple. -/ +def allTupleUnion {H : Family V} {t : ℕ} (f : Fin t → ↥H) : Finset V := + Finset.univ.biUnion (fun i => (f i).val) + +/-- Weight of the union of an injective tuple. -/ +def tupleWeight {H : Family V} {t : ℕ} (rho : ℝ) (f : EdgeTuple H t) : ℝ := + rho ^ (tupleUnion f).card + +def tupleWeightSum (H : Family V) (rho : ℝ) (t : ℕ) : ℝ := + ∑ f : EdgeTuple H t, tupleWeight rho f + +/-- The larger sum in which repeated edges are allowed. -/ +def allTupleWeightSum (H : Family V) (rho : ℝ) (t : ℕ) : ℝ := + ∑ f : Fin t → ↥H, rho ^ (allTupleUnion f).card + +theorem tupleWeight_nonneg {H : Family V} {t : ℕ} {rho : ℝ} + (hrho : 0 ≤ rho) (f : EdgeTuple H t) : 0 ≤ tupleWeight rho f := + pow_nonneg hrho _ + +@[simp] theorem allTupleUnion_zero {H : Family V} (f : Fin 0 → ↥H) : + allTupleUnion f = ∅ := by + simp [allTupleUnion] + +@[simp] theorem allTupleWeightSum_zero (H : Family V) (rho : ℝ) : + allTupleWeightSum H rho 0 = 1 := by + classical + simp [allTupleWeightSum] + +@[simp] theorem tupleWeightSum_zero (H : Family V) (rho : ℝ) : + tupleWeightSum H rho 0 = 1 := by + classical + let : Unique (EdgeTuple H 0) := + { default := ⟨Fin.elim0, fun i => Fin.elim0 i⟩ + uniq := fun f => Subtype.ext (funext fun i => Fin.elim0 i) } + simp [tupleWeightSum, tupleWeight, tupleUnion] + +/-- An unrestricted `t`-tuple of `r`-element edges uses at most `r * t` vertices. -/ +theorem allTupleUnion_card_le {H : Family V} {r t : ℕ} + (uniform : ∀ e ∈ H, (e : Finset V).card = r) (f : Fin t → ↥H) : + (allTupleUnion f).card ≤ r * t := by + classical + calc + (allTupleUnion f).card ≤ ∑ i : Fin t, (f i).val.card := + Finset.card_biUnion_le + _ = ∑ _i : Fin t, r := + Finset.sum_congr rfl (fun i _ => uniform (f i).val (f i).property) + _ = r * t := by simp [Nat.mul_comm] + +theorem tupleUnion_card_le {H : Family V} {r t : ℕ} + (uniform : ∀ e ∈ H, (e : Finset V).card = r) (f : EdgeTuple H t) : + (tupleUnion f).card ≤ r * t := + allTupleUnion_card_le uniform f.val + +/-- Splitting a tuple separates its old union from the newly chosen edge. -/ +theorem allTupleUnion_cons {H : Family V} {t : ℕ} + (e : ↥H) (f : Fin t → ↥H) : + allTupleUnion (Fin.cons e f) = allTupleUnion f ∪ e.val := by + ext v + simp [allTupleUnion, Fin.exists_fin_succ, or_comm] + +/-- Union weight factors exactly into the prefix weight and its extension cost. -/ +theorem allTupleWeight_cons {H : Family V} {t : ℕ} (rho : ℝ) + (e : ↥H) (f : Fin t → ↥H) : + rho ^ (allTupleUnion (Fin.cons e f)).card = + rho ^ (allTupleUnion f).card * rho ^ (e.val \ allTupleUnion f).card := by + rw [allTupleUnion_cons, Finset.union_comm, + ← Finset.card_sdiff_add_card, pow_add, mul_comm] + +/-- Exact recurrence for the unrestricted sum, obtained by reindexing with `Fin.cons`. -/ +theorem allTupleWeightSum_succ (H : Family V) (rho : ℝ) (t : ℕ) : + allTupleWeightSum H rho (t + 1) = + ∑ f : Fin t → ↥H, rho ^ (allTupleUnion f).card * + (∑ e ∈ H, rho ^ (e \ allTupleUnion f).card) := by + classical + calc + allTupleWeightSum H rho (t + 1) = + ∑ p : ↥H × (Fin t → ↥H), + rho ^ (allTupleUnion (Fin.cons p.1 p.2)).card := by + exact ((Fin.consEquiv (fun _ : Fin (t + 1) => ↥H)).sum_comp + (fun f => rho ^ (allTupleUnion f).card)).symm + _ = ∑ f : Fin t → ↥H, ∑ e : ↥H, + rho ^ (allTupleUnion (Fin.cons e f)).card := + Fintype.sum_prod_type_right _ + _ = ∑ f : Fin t → ↥H, rho ^ (allTupleUnion f).card * + (∑ e ∈ H, rho ^ (e \ allTupleUnion f).card) := by + apply Finset.sum_congr rfl + intro f _ + simp_rw [allTupleWeight_cons] + rw [← Finset.mul_sum, Finset.sum_coe_sort H + (fun e : Finset V => rho ^ (e \ allTupleUnion f).card)] + +/-- Discarding the injectivity restriction increases the sum of nonnegative weights. -/ +theorem tupleWeightSum_le_allTupleWeightSum (H : Family V) {rho : ℝ} + (hrho : 0 ≤ rho) (t : ℕ) : + tupleWeightSum H rho t ≤ allTupleWeightSum H rho t := by + classical + calc + tupleWeightSum H rho t = + ∑ f ∈ Finset.univ.filter (fun f : Fin t → ↥H => Function.Injective f), + rho ^ (allTupleUnion f).card := by + exact (Finset.sum_subtype + (p := fun f : Fin t → ↥H => Function.Injective f) + (Finset.univ.filter (fun f : Fin t → ↥H => Function.Injective f)) + (fun f => by simp) (fun f => rho ^ (allTupleUnion f).card)).symm + _ ≤ allTupleWeightSum H rho t := by + exact Finset.sum_le_sum_of_subset_of_nonneg (Finset.filter_subset _ _) + (fun f _ _ => pow_nonneg hrho _) + +/-- The extension estimate yields the unrestricted recurrence up to a fixed length. -/ +theorem allTupleWeightSum_succ_le (H : Family V) {rho T : ℝ} {r m t : ℕ} + (hrho : 0 ≤ rho) (hT : 0 ≤ T) + (uniform : ∀ e ∈ H, (e : Finset V).card = r) + (extension : ∀ B : Finset V, + (∑ e ∈ H, rho ^ (e \ B).card) ≤ T * (1 + (B.card : ℝ)) ^ r) + (ht : t ≤ m) : + allTupleWeightSum H rho (t + 1) ≤ + (T * (1 + ((r * m : ℕ) : ℝ)) ^ r) * allTupleWeightSum H rho t := by + classical + rw [allTupleWeightSum_succ, allTupleWeightSum, Finset.mul_sum] + apply Finset.sum_le_sum + intro f _ + have hcard : (allTupleUnion f).card ≤ r * m := + (allTupleUnion_card_le uniform f).trans (Nat.mul_le_mul_left r ht) + have hcast : ((allTupleUnion f).card : ℝ) ≤ ((r * m : ℕ) : ℝ) := + Nat.cast_le.mpr hcard + have hpower : (1 + ((allTupleUnion f).card : ℝ)) ^ r ≤ + (1 + ((r * m : ℕ) : ℝ)) ^ r := + pow_le_pow_left₀ (add_nonneg zero_le_one (Nat.cast_nonneg _)) + (add_le_add (le_refl (1 : ℝ)) hcast) r + have hext : (∑ e ∈ H, rho ^ (e \ allTupleUnion f).card) ≤ + T * (1 + ((r * m : ℕ) : ℝ)) ^ r := + (extension (allTupleUnion f)).trans (mul_le_mul_of_nonneg_left hpower hT) + simpa only [mul_comm] using + mul_le_mul_of_nonneg_left hext (pow_nonneg hrho (allTupleUnion f).card) + +/-- Iteration of the actual recurrence bounds every unrestricted sum up to `m`. -/ +theorem allTupleWeightSum_le (H : Family V) {rho T : ℝ} {r m : ℕ} + (hrho : 0 ≤ rho) (hT : 0 ≤ T) + (uniform : ∀ e ∈ H, (e : Finset V).card = r) + (extension : ∀ B : Finset V, + (∑ e ∈ H, rho ^ (e \ B).card) ≤ T * (1 + (B.card : ℝ)) ^ r) + (t : ℕ) (ht : t ≤ m) : + allTupleWeightSum H rho t ≤ (T * (1 + ((r * m : ℕ) : ℝ)) ^ r) ^ t := by + have hfactor : 0 ≤ T * (1 + ((r * m : ℕ) : ℝ)) ^ r := + mul_nonneg hT (pow_nonneg (add_nonneg zero_le_one (Nat.cast_nonneg _)) r) + revert ht + induction t with + | zero => intro ht; simp + | succ t ih => + intro ht + have htm : t ≤ m := Nat.le_of_succ_le ht + calc + allTupleWeightSum H rho (t + 1) ≤ + (T * (1 + ((r * m : ℕ) : ℝ)) ^ r) * allTupleWeightSum H rho t := + allTupleWeightSum_succ_le H hrho hT uniform extension htm + _ ≤ (T * (1 + ((r * m : ℕ) : ℝ)) ^ r) * + (T * (1 + ((r * m : ℕ) : ℝ)) ^ r) ^ t := + mul_le_mul_of_nonneg_left (ih htm) hfactor + _ = (T * (1 + ((r * m : ℕ) : ℝ)) ^ r) ^ (t + 1) := by + rw [pow_succ, mul_comm] + +theorem tupleWeightSum_le (H : Family V) {rho T : ℝ} {r m : ℕ} + (hrho : 0 ≤ rho) (hT : 0 ≤ T) + (uniform : ∀ e ∈ H, (e : Finset V).card = r) + (extension : ∀ B : Finset V, + (∑ e ∈ H, rho ^ (e \ B).card) ≤ T * (1 + (B.card : ℝ)) ^ r) : + tupleWeightSum H rho m ≤ (T * (1 + ((r * m : ℕ) : ℝ)) ^ r) ^ m := + (tupleWeightSum_le_allTupleWeightSum H hrho m).trans + (allTupleWeightSum_le H hrho hT uniform extension m le_rfl) + +end + +end TalagrandDiscreteConvexity.Covering + +end OAI diff --git a/lean/OAI/Combinatorics/DiscreteConvexity/CoveringSampledFamilies.lean b/lean/OAI/Combinatorics/DiscreteConvexity/CoveringSampledFamilies.lean new file mode 100644 index 0000000000000000000000000000000000000000..f9b2787f4c22568d53d9de28a41420fafe3374bb --- /dev/null +++ b/lean/OAI/Combinatorics/DiscreteConvexity/CoveringSampledFamilies.lean @@ -0,0 +1,131 @@ +import OAI.Combinatorics.DiscreteConvexity.CoveringBasic +import Mathlib.Algebra.Order.BigOperators.Group.Finset +import Mathlib.Data.Fintype.EquivFin + +namespace OAI + +/-! +# Deterministic covers from a pair-sampling outcome + +Every sampling outcome gives a cover. The cost bounds count generators +with multiplicity, indexed by ordered pairs or injective ordered tuples. +No independence or probability estimate is needed for these pointwise +statements. +-/ + +namespace TalagrandDiscreteConvexity.Covering + +open scoped BigOperators + +variable {V : Type*} [DecidableEq V] + +/-- The generator produced by a sampled ordered pair. -/ +def pairUnion {H : Family V} (p : PairIndex H) : Finset V := p.1.val ∪ p.2.val + +/-- Duplicate unions are identified in the family of sampled generators. -/ +noncomputable def sampledFamily (H : Family V) (sample : Sample H) : Family V := + sample.image pairUnion + +/-- An injective tuple contributes a residual generator exactly when all +of its ordered pair indices were avoided. -/ +noncomputable def residualFamily (H : Family V) (m : ℕ) (sample : Sample H) : + Family V := by + classical + exact (Finset.univ.filter + (fun f : EdgeTuple H m => Disjoint sample (tuplePairs f))).image tupleUnion + +@[simp] theorem mem_sampledFamily {H : Family V} {sample : Sample H} {I : Finset V} : + I ∈ sampledFamily H sample ↔ ∃ p ∈ sample, pairUnion p = I := by + classical + simp [sampledFamily] + +@[simp] theorem mem_residualFamily {H : Family V} {m : ℕ} + {sample : Sample H} {I : Finset V} : + I ∈ residualFamily H m sample ↔ + ∃ f : EdgeTuple H m, Disjoint sample (tuplePairs f) ∧ tupleUnion f = I := by + classical + simp [residualFamily] + +/-- Counting each sampled ordered pair separately bounds the family cost. -/ +theorem cost_sampledFamily_le (H : Family V) (sample : Sample H) + {rho : ℝ} (hrho : 0 ≤ rho) : + cost rho (sampledFamily H sample) ≤ + ∑ p ∈ sample, rho ^ (pairUnion p).card := by + classical + unfold cost sampledFamily + exact Finset.sum_image_le_of_nonneg + (fun I _ => pow_nonneg hrho I.card) + +/-- Counting each avoiding tuple separately bounds the residual cost. +The indicator has the same argument order as the sampling law. -/ +theorem cost_residualFamily_le (H : Family V) (m : ℕ) (sample : Sample H) + {rho : ℝ} (hrho : 0 ≤ rho) : + cost rho (residualFamily H m sample) ≤ + ∑ f : EdgeTuple H m, + if Disjoint sample (tuplePairs f) then rho ^ (tupleUnion f).card else 0 := by + classical + calc + cost rho (residualFamily H m sample) ≤ + ∑ f ∈ Finset.univ.filter + (fun f : EdgeTuple H m => Disjoint sample (tuplePairs f)), + rho ^ (tupleUnion f).card := by + unfold cost residualFamily + exact Finset.sum_image_le_of_nonneg + (fun I _ => pow_nonneg hrho I.card) + _ = _ := Finset.sum_filter _ _ + +/-- A large contained-edge family can be enumerated injectively inside +the regular edges, provided the set avoids the initial generators. -/ +theorem exists_regular_tuple {H C0 : Family V} {m : ℕ} {S : Finset V} + (hm : m ≤ (H.filter (fun e => e ⊆ S)).card) + (h0 : ¬∃ I ∈ C0, I ⊆ S) : + ∃ f : EdgeTuple (regularFamily H C0) m, ∀ i, (f.val i).val ⊆ S := by + classical + let K := H.filter (fun e => e ⊆ S) + have hKregular : K ⊆ regularFamily H C0 := by + intro e he + obtain ⟨heH, heS⟩ := Finset.mem_filter.mp he + refine mem_regularFamily.mpr ⟨heH, ?_⟩ + intro I hI hIe + exact h0 ⟨I, hI, Finset.Subset.trans hIe heS⟩ + have hcard : Fintype.card (Fin m) ≤ Fintype.card ↥K := by + simpa only [Fintype.card_fin, Fintype.card_coe] using hm + obtain ⟨g⟩ := Function.Embedding.nonempty_of_card_le hcard + let f : EdgeTuple (regularFamily H C0) m := + ⟨fun i => ⟨(g i).val, hKregular (g i).property⟩, by + intro i j hij + apply g.injective + apply Subtype.ext + exact congrArg (Subtype.val : ↥(regularFamily H C0) → Finset V) hij⟩ + refine ⟨f, ?_⟩ + intro i + exact (Finset.mem_filter.mp (g i).property).2 + +/-- Every pair-sampling outcome covers each set containing sufficiently +many original edges. This includes `m = 0` and empty edge families. -/ +theorem covers_sampled_residual [Fintype V] (H C0 : Family V) (m : ℕ) + (sample : Sample (regularFamily H C0)) : + Covers (C0 ∪ sampledFamily (regularFamily H C0) sample ∪ + residualFamily (regularFamily H C0) m sample) (denseFamily H m) := by + classical + intro S hS + by_cases h0 : ∃ I ∈ C0, I ⊆ S + · obtain ⟨I, hI, hIS⟩ := h0 + exact ⟨I, Finset.mem_union_left _ (Finset.mem_union_left _ hI), hIS⟩ + · obtain ⟨f, hf⟩ := exists_regular_tuple (mem_denseFamily.mp hS) h0 + by_cases havoid : Disjoint sample (tuplePairs f) + · refine ⟨tupleUnion f, + Finset.mem_union_right _ (mem_residualFamily.mpr ⟨f, havoid, rfl⟩), ?_⟩ + intro v hv + obtain ⟨i, hi⟩ := mem_tupleUnion.mp hv + exact hf i hi + · obtain ⟨p, hp, hpf⟩ := Finset.not_disjoint_iff.mp havoid + obtain ⟨i, j, rfl⟩ := mem_tuplePairs.mp hpf + refine ⟨pairUnion (f.val i, f.val j), ?_, ?_⟩ + · exact Finset.mem_union_left _ + (Finset.mem_union_right _ (mem_sampledFamily.mpr ⟨_, hp, rfl⟩)) + · exact Finset.union_subset (hf i) (hf j) + +end TalagrandDiscreteConvexity.Covering + +end OAI diff --git a/lean/OAI/Combinatorics/DiscreteConvexity/DensityConstants.lean b/lean/OAI/Combinatorics/DiscreteConvexity/DensityConstants.lean new file mode 100644 index 0000000000000000000000000000000000000000..096909792e2bf00083c28a04842a5f732872dc91 --- /dev/null +++ b/lean/OAI/Combinatorics/DiscreteConvexity/DensityConstants.lean @@ -0,0 +1,45 @@ +import OAI.Combinatorics.DiscreteConvexity.Basic +import Mathlib.Algebra.Order.Field.Basic +import Mathlib.Algebra.Order.Monoid.Unbundled.Pow +import Mathlib.Tactic.FieldSimp +import Mathlib.Tactic.Linarith +import Mathlib.Tactic.NormNum +import Mathlib.Tactic.Ring + +namespace OAI + +/-! +# Symbolic constants for the original-density argument + +Only the small factor `32 = 2^5` is evaluated. The number of rows and the +final tuple length remain symbolic powers throughout the construction. +-/ + +namespace TalagrandDiscreteConvexity + +theorem density_rows_gt_one : 1 < (2 : ℕ) ^ 70 := + one_lt_pow' (by decide : (1 : ℕ) < 2) (by decide : (70 : ℕ) ≠ 0) + +theorem density_rows_pos : 0 < (2 : ℕ) ^ 70 := + lt_trans Nat.zero_lt_one density_rows_gt_one + +theorem density_tuple_count : 32 * (2 : ℕ) ^ 70 = 2 ^ 75 := by + rw [show (32 : ℕ) = 2 ^ 5 by decide, ← pow_add] + +theorem density_tuple_count_real : (2 : ℝ) ^ 75 = 32 * (2 : ℝ) ^ 70 := by + calc + (2 : ℝ) ^ 75 = 2 ^ 5 * 2 ^ 70 := by rw [← pow_add] + _ = 32 * 2 ^ 70 := by rw [show (2 : ℝ) ^ 5 = 32 by norm_num] + +/-- A density loss of at most `1 / (32 L)` spends at most `1 / 32` across rows. -/ +theorem density_failure_budget {L a : ℝ} (hL : 0 < L) + (ha : 1 - 1 / (32 * L) ≤ a) : L * (1 - a) ≤ 1 / 32 := by + have hbound : 1 - a ≤ 1 / (32 * L) := by linarith + calc + L * (1 - a) ≤ L * (1 / (32 * L)) := + mul_le_mul_of_nonneg_left hbound hL.le + _ = 1 / 32 := by field_simp [ne_of_gt hL] + +end TalagrandDiscreteConvexity + +end OAI diff --git a/lean/OAI/Combinatorics/DiscreteConvexity/DyadicBins.lean b/lean/OAI/Combinatorics/DiscreteConvexity/DyadicBins.lean new file mode 100644 index 0000000000000000000000000000000000000000..4069dfd1c2969e336de8c60e4185350d4b92fa4d --- /dev/null +++ b/lean/OAI/Combinatorics/DiscreteConvexity/DyadicBins.lean @@ -0,0 +1,95 @@ +import OAI.Combinatorics.DiscreteConvexity.Basic +import Mathlib.Algebra.Order.Archimedean.Basic +import Mathlib.Algebra.Order.Archimedean.Real.Basic +import Mathlib.Tactic.NormNum + +namespace OAI + +/-! +# Dyadic bins for positive weights + +The exponent of a weight is determined by the first power of `1 / 2` +strictly below it. In particular, a weight equal to a dyadic endpoint +belongs to the bin whose upper endpoint it equals. +-/ + +namespace TalagrandDiscreteConvexity + +/-- The dyadic exponent of a positive weight. Its value at a nonpositive +weight is irrelevant to the bin partition and is fixed to zero. -/ +noncomputable def binExponent (w : ℝ) : ℕ := by + classical + exact if hw : 0 < w then + Nat.find (exists_pow_lt_of_lt_one hw (by norm_num : (1 / 2 : ℝ) < 1)) - 1 + else 0 + +/-- Every positive weight at most one lies in its specified dyadic bin. -/ +theorem binExponent_spec {w : ℝ} (hwpos : 0 < w) (hwle : w ≤ 1) : + (1 / 2 : ℝ) ^ (binExponent w + 1) < w ∧ + w ≤ (1 / 2 : ℝ) ^ binExponent w := by + classical + let ex : ∃ h : ℕ, (1 / 2 : ℝ) ^ h < w := + exists_pow_lt_of_lt_one hwpos (by norm_num : (1 / 2 : ℝ) < 1) + have hcross : (1 / 2 : ℝ) ^ Nat.find ex < w := Nat.find_spec ex + have hne : Nat.find ex ≠ 0 := by + intro hz + have : (1 : ℝ) < w := by simpa only [hz, pow_zero] using hcross + exact (not_lt_of_ge hwle) this + have hexp : binExponent w = Nat.find ex - 1 := by + simp only [binExponent, dite_eq_left hwpos] + rw [hexp] + constructor + · simpa only [Nat.sub_add_cancel (Nat.one_le_iff_ne_zero.mpr hne)] using hcross + · exact le_of_not_gt (Nat.find_min ex (Nat.sub_one_lt hne)) + +theorem binExponent_lower {w : ℝ} (hwpos : 0 < w) (hwle : w ≤ 1) : + (1 / 2 : ℝ) ^ (binExponent w + 1) < w := + (binExponent_spec hwpos hwle).1 + +theorem binExponent_upper {w : ℝ} (hwpos : 0 < w) (hwle : w ≤ 1) : + w ≤ (1 / 2 : ℝ) ^ binExponent w := + (binExponent_spec hwpos hwle).2 + +/-- A dyadic upper bound on a weight gives a lower bound on its bin index. -/ +theorem le_binExponent_of_le_pow {w : ℝ} {n : ℕ} (hwpos : 0 < w) + (hwn : w ≤ (1 / 2 : ℝ) ^ n) : n ≤ binExponent w := by + have hwle : w ≤ 1 := + hwn.trans (pow_le_one₀ (by norm_num : (0 : ℝ) ≤ 1 / 2) (by norm_num)) + have hpow : (1 / 2 : ℝ) ^ (binExponent w + 1) < (1 / 2 : ℝ) ^ n := + (binExponent_lower hwpos hwle).trans_le hwn + have hn : n < binExponent w + 1 := + (pow_lt_pow_iff_right_of_lt_one₀ + (by norm_num : (0 : ℝ) < 1 / 2) (by norm_num)).mp hpow + exact Nat.lt_succ_iff.mp hn + +theorem le_binExponent_of_lt_pow {w : ℝ} {n : ℕ} (hwpos : 0 < w) + (hwn : w < (1 / 2 : ℝ) ^ n) : n ≤ binExponent w := + le_binExponent_of_le_pow hwpos hwn.le + +/-- The half-open bins are disjoint, including at their dyadic endpoints. -/ +theorem binExponent_eq_of_bounds {w : ℝ} {h : ℕ} + (hlo : (1 / 2 : ℝ) ^ (h + 1) < w) + (hhi : w ≤ (1 / 2 : ℝ) ^ h) : binExponent w = h := by + have hwpos : 0 < w := (pow_pos (by norm_num : (0 : ℝ) < 1 / 2) _).trans hlo + have hwle : w ≤ 1 := + hhi.trans (pow_le_one₀ (by norm_num : (0 : ℝ) ≤ 1 / 2) (by norm_num)) + have hpow : (1 / 2 : ℝ) ^ (h + 1) < (1 / 2 : ℝ) ^ binExponent w := + hlo.trans_le (binExponent_upper hwpos hwle) + have hh : binExponent w < h + 1 := + (pow_lt_pow_iff_right_of_lt_one₀ + (by norm_num : (0 : ℝ) < 1 / 2) (by norm_num)).mp hpow + exact Nat.le_antisymm (Nat.lt_succ_iff.mp hh) (le_binExponent_of_le_pow hwpos hhi) + +/-- The form used when assigning all residual weights to bins of index at +least their support size. -/ +theorem exists_dyadic_bin {w : ℝ} {n : ℕ} (hwpos : 0 < w) + (hwn : w < (1 / 2 : ℝ) ^ n) : + ∃ h : ℕ, n ≤ h ∧ (1 / 2 : ℝ) ^ (h + 1) < w ∧ w ≤ (1 / 2 : ℝ) ^ h := by + have hwle : w ≤ 1 := + hwn.le.trans (pow_le_one₀ (by norm_num : (0 : ℝ) ≤ 1 / 2) (by norm_num)) + exact ⟨binExponent w, le_binExponent_of_lt_pow hwpos hwn, + binExponent_spec hwpos hwle⟩ + +end TalagrandDiscreteConvexity + +end OAI diff --git a/lean/OAI/Combinatorics/DiscreteConvexity/ElementaryCovering.lean b/lean/OAI/Combinatorics/DiscreteConvexity/ElementaryCovering.lean new file mode 100644 index 0000000000000000000000000000000000000000..6ab59e4561fb168247b9420f32e308e31ae80ee5 --- /dev/null +++ b/lean/OAI/Combinatorics/DiscreteConvexity/ElementaryCovering.lean @@ -0,0 +1,94 @@ +import OAI.Combinatorics.DiscreteConvexity.CoveringPairCost +import OAI.Combinatorics.DiscreteConvexity.CoveringResidualCost +import OAI.Combinatorics.DiscreteConvexity.ProbabilisticExistence + +namespace OAI + +/-! +# The elementary covering lemma + +The initial generators and regular edges are constructed from weighted +degrees. The remaining generators come from an actual finite Bernoulli +sample of ordered pairs. Every outcome is a containment cover, and finite +averaging selects an outcome meeting the claimed cost budget. +-/ + +namespace TalagrandDiscreteConvexity.Covering + +open scoped BigOperators + +variable {V : Type*} [Fintype V] [DecidableEq V] + +theorem elementary_covering (H : Family V) (rho : ℝ) (r h : ℕ) + (hrho0 : 0 < rho) (_hrho1 : rho < 1) + (uniform : ∀ e ∈ H, e.card = r) + (_hr : 1 ≤ r) (hrh : r ≤ h) (hh : 64 ≤ h) + (hweight : (H.card : ℝ) * rho ^ r ≤ (2 : ℝ) ^ (h + 1)) : + ∃ G : Family V, Covers G (denseFamily H (2 ^ (12 * h))) ∧ + cost rho G ≤ 3 * ((2 : ℝ) ^ h)⁻¹ := by + classical + let T := NumericalBounds.T h + let m := NumericalBounds.m h + let p := NumericalBounds.p h + let C0 := initialFamily H rho r T + let K := regularEdges H rho r T + let μ := bernoulliLaw (α := PairIndex K) p + (NumericalBounds.p_nonneg h) (NumericalBounds.p_le_one h) + let G : Sample K → Family V := fun sample => + C0 ∪ sampledFamily K sample ∪ residualFamily K m sample + have hrho : 0 ≤ rho := hrho0.le + have hT : 0 ≤ T := NumericalBounds.T_nonneg h + have hK : K ⊆ H := regularEdges_subset H rho r T + have hKuniform : ∀ e ∈ K, e.card = r := fun e he => uniform e (hK he) + have hcover (sample : Sample K) : Covers (G sample) (denseFamily H m) := + covers_sampled_residual H C0 m sample + have hC0 : cost rho C0 ≤ 2 * ((2 : ℝ) ^ (2 * h))⁻¹ := by + calc + cost rho C0 ≤ T⁻¹ * (2 : ℝ) ^ r * (H.card : ℝ) * rho ^ r := + initial_cost_le hrho (NumericalBounds.T_pos h) uniform + _ = (T⁻¹ * (2 : ℝ) ^ r) * ((H.card : ℝ) * rho ^ r) := by ring + _ ≤ (T⁻¹ * (2 : ℝ) ^ r) * (2 : ℝ) ^ (h + 1) := + mul_le_mul_of_nonneg_left hweight + (mul_nonneg (inv_nonneg.mpr hT) (pow_nonneg (by norm_num) _)) + _ ≤ 2 * ((2 : ℝ) ^ (2 * h))⁻¹ := NumericalBounds.initial_cost_le r h hrh + have hC1 : μ.expectation (fun sample => cost rho (sampledFamily K sample)) ≤ + 2 * ((2 : ℝ) ^ (2 * h))⁻¹ := by + calc + μ.expectation (fun sample => cost rho (sampledFamily K sample)) ≤ + p * ((H.card : ℝ) * rho ^ r * (2 : ℝ) ^ r * T) := + expectation_sampledFamily_le hrho hT uniform + (NumericalBounds.p_nonneg h) (NumericalBounds.p_le_one h) + _ = (p * (2 : ℝ) ^ r * T) * ((H.card : ℝ) * rho ^ r) := by ring + _ ≤ (p * (2 : ℝ) ^ r * T) * (2 : ℝ) ^ (h + 1) := + mul_le_mul_of_nonneg_left hweight + (mul_nonneg (mul_nonneg (NumericalBounds.p_nonneg h) + (pow_nonneg (by norm_num) _)) hT) + _ = p * (2 : ℝ) ^ (h + 1) * (2 : ℝ) ^ r * T := by ring + _ ≤ 2 * ((2 : ℝ) ^ (2 * h))⁻¹ := NumericalBounds.pair_cost_le r h hrh + have hC2 : μ.expectation (fun sample => cost rho (residualFamily K m sample)) ≤ + ((2 : ℝ) ^ m)⁻¹ := + expectation_residualFamily_le_inv_pow K hrho hKuniform + (fun B => regular_extension_le_pow hrho hT uniform B) hrh hh + have hmean : μ.expectation (fun sample => cost rho (G sample)) ≤ + 3 * ((2 : ℝ) ^ h)⁻¹ := by + calc + μ.expectation (fun sample => cost rho (G sample)) ≤ + μ.expectation (fun sample => cost rho C0 + + cost rho (sampledFamily K sample) + cost rho (residualFamily K m sample)) := by + apply μ.expectation_mono + intro sample + exact (cost_union_le hrho (C0 ∪ sampledFamily K sample) + (residualFamily K m sample)).trans + (add_le_add (cost_union_le hrho C0 (sampledFamily K sample)) le_rfl) + _ = cost rho C0 + μ.expectation (fun sample => cost rho (sampledFamily K sample)) + + μ.expectation (fun sample => cost rho (residualFamily K m sample)) := by + rw [μ.expectation_add, μ.expectation_add, μ.expectation_const] + _ ≤ 4 * ((2 : ℝ) ^ (2 * h))⁻¹ + ((2 : ℝ) ^ m)⁻¹ := by + linarith + _ ≤ 3 * ((2 : ℝ) ^ h)⁻¹ := NumericalBounds.final_cost_le h hh + obtain ⟨sample, hsample⟩ := μ.exists_le_expectation (fun sample => cost rho (G sample)) + exact ⟨G sample, hcover sample, hsample.trans hmean⟩ + +end TalagrandDiscreteConvexity.Covering + +end OAI diff --git a/lean/OAI/Combinatorics/DiscreteConvexity/ExceptionalWeightBound.lean b/lean/OAI/Combinatorics/DiscreteConvexity/ExceptionalWeightBound.lean new file mode 100644 index 0000000000000000000000000000000000000000..9c7a44043ef94111d31b25427ce5a3f3eadc4519 --- /dev/null +++ b/lean/OAI/Combinatorics/DiscreteConvexity/ExceptionalWeightBound.lean @@ -0,0 +1,57 @@ +import Mathlib.Basic.Real.Basic +import Mathlib.Data.Finset.Powerset +import Mathlib.Algebra.Order.BigOperators.Group.Finset +import Mathlib.Algebra.Order.Ring.Abs +import Mathlib.Algebra.Order.Field.Basic + +namespace OAI + +/-! +# An exceptional-weight lower bound from a signed identity + +Separating the empty subset in a vanishing signed sum bounds its weight by +the total unsigned weight of the nonempty subsets. This scalar argument does +not depend on how the weights or their signed identity were constructed. +-/ + +namespace TalagrandDiscreteConvexity + +open scoped BigOperators + +/-- A vanishing signed 32nd-power sum and an empty-subset value at least one +half force a lower bound on the sum of the nonempty squared weights. -/ +theorem exceptional_lower_bound_of_signed_sum {V : Type*} [DecidableEq V] + (S : Finset V) (b : Finset V → ℝ) + (hsum : ∑ U ∈ S.powerset, (-1 : ℝ) ^ U.card * b U ^ 32 = 0) + (hb0 : (1 / 2 : ℝ) ≤ b ∅) : + (1 / 2 : ℝ) ^ 32 ≤ ∑ U ∈ S.powerset.erase ∅, (b U ^ 2) ^ 16 := by + have hpower (U : Finset V) : b U ^ 32 = (b U ^ 2) ^ 16 := by + rw [← pow_mul] + have hnonneg (U : Finset V) : 0 ≤ b U ^ 32 := by + rw [hpower] + exact pow_nonneg (sq_nonneg (b U)) 16 + have hsplit : + (∑ U ∈ S.powerset.erase ∅, (-1 : ℝ) ^ U.card * b U ^ 32) + + b ∅ ^ 32 = 0 := by + simpa only [Finset.card_empty, pow_zero, one_mul] using + (Finset.sum_erase_add S.powerset + (fun U => (-1 : ℝ) ^ U.card * b U ^ 32) + (Finset.empty_mem_powerset S)).trans hsum + have hrest : + (∑ U ∈ S.powerset.erase ∅, (-1 : ℝ) ^ U.card * b U ^ 32) = + -(b ∅ ^ 32) := eq_neg_of_add_eq_zero_left hsplit + calc + (1 / 2 : ℝ) ^ 32 ≤ b ∅ ^ 32 := + pow_le_pow_left₀ (div_nonneg zero_le_one zero_le_two) hb0 32 + _ = |∑ U ∈ S.powerset.erase ∅, (-1 : ℝ) ^ U.card * b U ^ 32| := by + rw [hrest, abs_neg, abs_of_nonneg (hnonneg ∅)] + _ ≤ ∑ U ∈ S.powerset.erase ∅, |(-1 : ℝ) ^ U.card * b U ^ 32| := + Finset.abs_sum_le_sum_abs _ _ + _ = ∑ U ∈ S.powerset.erase ∅, (b U ^ 2) ^ 16 := by + apply Finset.sum_congr rfl + intro U hU + rw [abs_mul, abs_neg_one_pow, one_mul, abs_of_nonneg (hnonneg U), hpower] + +end TalagrandDiscreteConvexity + +end OAI diff --git a/lean/OAI/Combinatorics/DiscreteConvexity/FiniteFibers.lean b/lean/OAI/Combinatorics/DiscreteConvexity/FiniteFibers.lean new file mode 100644 index 0000000000000000000000000000000000000000..3f10cdb071583c633299fccffa4294aca67ac005 --- /dev/null +++ b/lean/OAI/Combinatorics/DiscreteConvexity/FiniteFibers.lean @@ -0,0 +1,86 @@ +import Mathlib.Algebra.BigOperators.Group.Finset.Basic + +namespace OAI + +/-! +# Finite partitions by a key + +The fibers indexed by the image of a finite source partition that source. +Filtering the source commutes with taking fibers, so the same partition +identities apply to restrictions of a weighted sum. +-/ + +namespace TalagrandDiscreteConvexity.FiniteFibers + +open scoped BigOperators + +variable {α β M : Type*} [DecidableEq β] + +/-- The elements of `A` with the specified key. -/ +def fiber (A : Finset α) (key : α → β) (b : β) : Finset α := + A.filter (fun a => key a = b) + +/-- Exactly the keys attained by the finite source. -/ +def keys (A : Finset α) (key : α → β) : Finset β := + A.image key + +@[simp] +theorem mem_fiber {A : Finset α} {key : α → β} {b : β} {a : α} : + a ∈ fiber A key b ↔ a ∈ A ∧ key a = b := + Finset.mem_filter + +@[simp] +theorem mem_keys {A : Finset α} {key : α → β} {b : β} : + b ∈ keys A key ↔ ∃ a ∈ A, key a = b := + Finset.mem_image + +theorem fiber_subset (A : Finset α) (key : α → β) (b : β) : + fiber A key b ⊆ A := + Finset.filter_subset _ _ + +theorem key_eq_of_mem_fiber {A : Finset α} {key : α → β} {b : β} {a : α} + (ha : a ∈ fiber A key b) : key a = b := + (mem_fiber.mp ha).2 + +@[simp] +theorem fiber_nonempty_iff (A : Finset α) (key : α → β) (b : β) : + (fiber A key b).Nonempty ↔ b ∈ keys A key := by + simp only [fiber, Finset.filter_nonempty_iff, mem_keys] + +/-- Restricting the source commutes with taking a fiber. -/ +theorem filter_fiber (A : Finset α) (key : α → β) (b : β) + (P : α → Prop) [DecidablePred P] : + fiber (A.filter P) key b = (fiber A key b).filter P := + Finset.filter_comm P (fun a => key a = b) A + +variable [AddCommMonoid M] + +/-- Summing the fibers over the attained keys counts each source element once. -/ +theorem sum_fibers (A : Finset α) (key : α → β) (f : α → M) : + (∑ b ∈ keys A key, ∑ a ∈ fiber A key b, f a) = ∑ a ∈ A, f a := by + exact Finset.sum_fiberwise_of_maps_to + (fun a ha => Finset.mem_image_of_mem key ha) f + +/-- The same partition identity after restricting every fiber by a predicate. -/ +theorem sum_filter_fibers (A : Finset α) (key : α → β) + (P : α → Prop) [DecidablePred P] (f : α → M) : + (∑ b ∈ keys A key, ∑ a ∈ (fiber A key b).filter P, f a) = + ∑ a ∈ A.filter P, f a := by + calc + (∑ b ∈ keys A key, ∑ a ∈ (fiber A key b).filter P, f a) = + ∑ b ∈ keys A key, ∑ a ∈ fiber (A.filter P) key b, f a := by + simp only [filter_fiber] + _ = ∑ a ∈ A.filter P, f a := by + exact Finset.sum_fiberwise_of_maps_to + (fun a ha => Finset.mem_image_of_mem key (Finset.mem_filter.mp ha).1) f + +/-- A restricted sum decomposed into the bins of the original source. -/ +theorem sum_filter_eq_sum_fibers (A : Finset α) (key : α → β) + (P : α → Prop) [DecidablePred P] (f : α → M) : + (∑ a ∈ A.filter P, f a) = + ∑ b ∈ keys A key, ∑ a ∈ (fiber A key b).filter P, f a := + (sum_filter_fibers A key P f).symm + +end TalagrandDiscreteConvexity.FiniteFibers + +end OAI diff --git a/lean/OAI/Combinatorics/DiscreteConvexity/FiniteParseval.lean b/lean/OAI/Combinatorics/DiscreteConvexity/FiniteParseval.lean new file mode 100644 index 0000000000000000000000000000000000000000..53f8f2c3bcd0a88b80109251d2c2031939057496 --- /dev/null +++ b/lean/OAI/Combinatorics/DiscreteConvexity/FiniteParseval.lean @@ -0,0 +1,80 @@ +import Mathlib.Algebra.BigOperators.Ring.Finset +import Mathlib.Data.Fintype.BigOperators +import Mathlib.Basic.Real.Basic +import Mathlib.Tactic.Ring + +namespace OAI + +/-! +# Finite Parseval identities from a weighted kernel + +The algebraic statement below separates finite-sum rearrangement from the +concrete kernel identity. Neither the expansion nor the Parseval identity +requires nonnegative weights. +-/ + +namespace TalagrandDiscreteConvexity + +open scoped BigOperators + +variable {I J : Type*} [Fintype I] [Fintype J] + +/-- Expanding a weighted product of transforms gives the associated kernel. -/ +theorem weighted_transform_bilinear_expansion + (K : I → J → ℝ) (r : I → ℝ) (f g : J → ℝ) : + (∑ u, r u * (∑ x, f x * K u x) * (∑ y, g y * K u y)) = + ∑ x, ∑ y, f x * g y * (∑ u, r u * K u x * K u y) := by + calc + _ = ∑ u, ∑ x, ∑ y, f x * g y * (r u * K u x * K u y) := by + apply Finset.sum_congr rfl + intro u _ + rw [mul_assoc, Fintype.sum_mul_sum] + simp only [Finset.mul_sum] + apply Finset.sum_congr rfl + intro x _ + apply Finset.sum_congr rfl + intro y _ + ring + _ = ∑ x, ∑ y, ∑ u, f x * g y * (r u * K u x * K u y) := by + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro x _ + rw [Finset.sum_comm] + _ = ∑ x, ∑ y, f x * g y * (∑ u, r u * K u x * K u y) := by + simp only [Finset.mul_sum] + +variable [DecidableEq J] + +/-- A diagonal weighted kernel preserves the corresponding bilinear form. -/ +theorem weighted_kernel_bilinear + (K : I → J → ℝ) (r : I → ℝ) (μ : J → ℝ) + (hkernel : ∀ x y, (∑ u, r u * K u x * K u y) = + if x = y then μ x else 0) (f g : J → ℝ) : + (∑ u, r u * (∑ x, f x * K u x) * (∑ y, g y * K u y)) = + ∑ x, μ x * f x * g x := by + rw [weighted_transform_bilinear_expansion] + apply Finset.sum_congr rfl + intro x _ + simp_rw [hkernel] + calc + (∑ y, f x * g y * (if x = y then μ x else 0)) = + f x * g x * (if x = x then μ x else 0) := by + apply Finset.sum_eq_single_of_mem x (Finset.mem_univ x) + intro y _ hy + rw [ite_eq_right (Ne.symm hy), mul_zero] + _ = μ x * f x * g x := by + rw [ite_eq_left rfl] + ring + +/-- Finite Parseval follows from the weighted kernel identity. -/ +theorem weighted_kernel_parseval + (K : I → J → ℝ) (r : I → ℝ) (μ : J → ℝ) + (hkernel : ∀ x y, (∑ u, r u * K u x * K u y) = + if x = y then μ x else 0) (f : J → ℝ) : + (∑ u, r u * (∑ x, f x * K u x) ^ 2) = + ∑ x, μ x * (f x) ^ 2 := by + simpa only [pow_two, mul_assoc] using weighted_kernel_bilinear K r μ hkernel f f + +end TalagrandDiscreteConvexity + +end OAI diff --git a/lean/OAI/Combinatorics/DiscreteConvexity/FiniteProbability.lean b/lean/OAI/Combinatorics/DiscreteConvexity/FiniteProbability.lean new file mode 100644 index 0000000000000000000000000000000000000000..557ccde0da6221b4d465362bb1b86ba28127446c --- /dev/null +++ b/lean/OAI/Combinatorics/DiscreteConvexity/FiniteProbability.lean @@ -0,0 +1,195 @@ +import Mathlib.Basic.Real.Basic +import Mathlib.Algebra.BigOperators.Ring.Finset +import Mathlib.Algebra.Order.BigOperators.Group.Finset +import Mathlib.Algebra.Order.BigOperators.GroupWithZero.Finset +import Mathlib.Data.Fintype.BigOperators +import Mathlib.Data.Fintype.Pi +import Mathlib.Tactic.Linarith +import Mathlib.Tactic.SplitIfs + +namespace OAI + +/-! +# Finite probability laws + +All probabilities and expectations are finite real sums. Finite laws admit +elementary probability inequalities, product laws, independent samples, and +uniform distributions. +-/ + +open scoped BigOperators +noncomputable section +attribute [local instance] Classical.propDecidable + +namespace TalagrandDiscreteConvexity + +structure FiniteLaw (Ω : Type*) [Fintype Ω] where + weight : Ω → ℝ + nonneg : ∀ ω, 0 ≤ weight ω + total : ∑ ω, weight ω = 1 + +namespace FiniteLaw + +def expectation {Ω : Type*} [Fintype Ω] (μ : FiniteLaw Ω) (f : Ω → ℝ) : ℝ := + ∑ ω, μ.weight ω * f ω + +def prob {Ω : Type*} [Fintype Ω] (μ : FiniteLaw Ω) (P : Ω → Prop) : ℝ := by + classical + exact ∑ ω, if P ω then μ.weight ω else 0 + +def IsPositive {Ω : Type*} [Fintype Ω] (μ : FiniteLaw Ω) : Prop := + ∀ ω, 0 < μ.weight ω + +variable {Ω Γ : Type*} [Fintype Ω] [Fintype Γ] + +@[simp] theorem expectation_const (μ : FiniteLaw Ω) (c : ℝ) : + μ.expectation (fun _ => c) = c := by + rw [expectation, ← Finset.sum_mul, μ.total, one_mul] + +theorem expectation_add (μ : FiniteLaw Ω) (f g : Ω → ℝ) : + μ.expectation (fun ω => f ω + g ω) = μ.expectation f + μ.expectation g := by + simp [expectation, mul_add, Finset.sum_add_distrib] + +theorem expectation_sub (μ : FiniteLaw Ω) (f g : Ω → ℝ) : + μ.expectation (fun ω => f ω - g ω) = μ.expectation f - μ.expectation g := by + simp [expectation, mul_sub, Finset.sum_sub_distrib] + +theorem expectation_smul (μ : FiniteLaw Ω) (c : ℝ) (f : Ω → ℝ) : + μ.expectation (fun ω => c * f ω) = c * μ.expectation f := by + simp [expectation, Finset.mul_sum, mul_left_comm] + +theorem expectation_sum {ι : Type*} [Fintype ι] (μ : FiniteLaw Ω) (f : ι → Ω → ℝ) : + μ.expectation (fun ω => ∑ i, f i ω) = ∑ i, μ.expectation (f i) := by + simp only [expectation, Finset.mul_sum] + exact Finset.sum_comm + +theorem expectation_nonneg (μ : FiniteLaw Ω) {f : Ω → ℝ} (hf : ∀ ω, 0 ≤ f ω) : + 0 ≤ μ.expectation f := + Finset.sum_nonneg fun ω _ => mul_nonneg (μ.nonneg ω) (hf ω) + +theorem expectation_mono (μ : FiniteLaw Ω) {f g : Ω → ℝ} (hfg : ∀ ω, f ω ≤ g ω) : + μ.expectation f ≤ μ.expectation g := + Finset.sum_le_sum fun ω _ => mul_le_mul_of_nonneg_left (hfg ω) (μ.nonneg ω) + +theorem prob_eq_expectation (μ : FiniteLaw Ω) (P : Ω → Prop) : + μ.prob P = μ.expectation (fun ω => if P ω then 1 else 0) := by + classical + simp [prob, expectation, mul_ite] + +@[simp] theorem prob_true (μ : FiniteLaw Ω) : μ.prob (fun _ => True) = 1 := by + simp [prob, μ.total] + +@[simp] theorem prob_false (μ : FiniteLaw Ω) : μ.prob (fun _ => False) = 0 := by + simp [prob] + +theorem prob_nonneg (μ : FiniteLaw Ω) (P : Ω → Prop) : 0 ≤ μ.prob P := by + classical + exact Finset.sum_nonneg fun ω _ => by split_ifs <;> simp [μ.nonneg] + +theorem prob_mono (μ : FiniteLaw Ω) {P Q : Ω → Prop} (hPQ : ∀ ω, P ω → Q ω) : + μ.prob P ≤ μ.prob Q := by + classical + apply Finset.sum_le_sum + intro ω _ + by_cases hp : P ω + · simp [hp, hPQ ω hp] + · by_cases hq : Q ω <;> simp [hp, hq, μ.nonneg ω] + +theorem prob_le_one (μ : FiniteLaw Ω) (P : Ω → Prop) : μ.prob P ≤ 1 := by + simpa using μ.prob_mono (Q := fun _ => True) (fun _ _ => trivial) + +theorem prob_compl (μ : FiniteLaw Ω) (P : Ω → Prop) : + μ.prob (fun ω => ¬ P ω) = 1 - μ.prob P := by + classical + have h : μ.prob P + μ.prob (fun ω => ¬ P ω) = 1 := by + rw [prob, prob, ← Finset.sum_add_distrib, ← μ.total] + apply Finset.sum_congr rfl + intro ω _ + by_cases hp : P ω <;> simp [hp] + linarith + +theorem prob_union_le (μ : FiniteLaw Ω) (P Q : Ω → Prop) : + μ.prob (fun ω => P ω ∨ Q ω) ≤ μ.prob P + μ.prob Q := by + classical + rw [prob, prob, prob, ← Finset.sum_add_distrib] + apply Finset.sum_le_sum + intro ω _ + by_cases hp : P ω <;> by_cases hq : Q ω <;> simp [hp, hq, μ.nonneg] + +theorem prob_le_expectation (μ : FiniteLaw Ω) (P : Ω → Prop) (f : Ω → ℝ) + (hf : ∀ ω, 0 ≤ f ω) (hP : ∀ ω, P ω → 1 ≤ f ω) : μ.prob P ≤ μ.expectation f := by + classical + rw [prob_eq_expectation] + apply μ.expectation_mono + intro ω + by_cases hp : P ω + · simpa [hp] using hP ω hp + · simpa [hp] using hf ω + +theorem prob_ge_le_expectation_div (μ : FiniteLaw Ω) (f : Ω → ℝ) + (hf : ∀ ω, 0 ≤ f ω) {t : ℝ} (ht : 0 < t) : + μ.prob (fun ω => t ≤ f ω) ≤ μ.expectation f / t := by + have h := μ.prob_le_expectation (fun ω => t ≤ f ω) (fun ω => t⁻¹ * f ω) + (fun ω => mul_nonneg (inv_nonneg.mpr ht.le) (hf ω)) + (fun ω hω => by simpa [ht.ne'] using mul_le_mul_of_nonneg_left hω (inv_nonneg.mpr ht.le)) + rw [expectation_smul] at h + simpa [div_eq_mul_inv, mul_comm] using h + +def prod (μ : FiniteLaw Ω) (ν : FiniteLaw Γ) : FiniteLaw (Ω × Γ) where + weight ω := μ.weight ω.1 * ν.weight ω.2 + nonneg ω := mul_nonneg (μ.nonneg _) (ν.nonneg _) + total := by + simp only [Fintype.sum_prod_type, ← Finset.mul_sum, ν.total, mul_one, μ.total] + +@[simp] theorem prod_weight (μ : FiniteLaw Ω) (ν : FiniteLaw Γ) (ω : Ω) (γ : Γ) : + (μ.prod ν).weight (ω, γ) = μ.weight ω * ν.weight γ := rfl + +theorem expectation_prod (μ : FiniteLaw Ω) (ν : FiniteLaw Γ) (f : Ω × Γ → ℝ) : + (μ.prod ν).expectation f = μ.expectation (fun ω => ν.expectation (fun γ => f (ω, γ))) := by + simp [expectation, prod, Fintype.sum_prod_type, Finset.mul_sum, mul_assoc] + +theorem prod_isPositive (μ : FiniteLaw Ω) (ν : FiniteLaw Γ) + (hμ : μ.IsPositive) (hν : ν.IsPositive) : (μ.prod ν).IsPositive := + fun outcome => mul_pos (hμ outcome.1) (hν outcome.2) + +def pi {ι : Type*} [Fintype ι] [DecidableEq ι] {A : ι → Type*} [∀ i, Fintype (A i)] + (μ : ∀ i, FiniteLaw (A i)) : FiniteLaw (∀ i, A i) := by + classical + exact { + weight := fun ω => ∏ i, (μ i).weight (ω i) + nonneg := fun ω => Finset.prod_nonneg fun i _ => (μ i).nonneg (ω i) + total := by + rw [← Fintype.prod_sum (fun i a => (μ i).weight a)] + simp_rw [(μ _).total] + simp } + +@[simp] theorem pi_weight {ι : Type*} [Fintype ι] [DecidableEq ι] {A : ι → Type*} [∀ i, Fintype (A i)] + (μ : ∀ i, FiniteLaw (A i)) (ω : ∀ i, A i) : + (pi μ).weight ω = ∏ i, (μ i).weight (ω i) := rfl + +def iid (μ : FiniteLaw Ω) (n : ℕ) : FiniteLaw (Fin n → Ω) := pi (fun _ : Fin n => μ) + +@[simp] theorem iid_weight (μ : FiniteLaw Ω) (n : ℕ) (ω : Fin n → Ω) : + (iid μ n).weight ω = ∏ i, μ.weight (ω i) := rfl + +def uniform (Ω : Type*) [Fintype Ω] [Nonempty Ω] : FiniteLaw Ω where + weight _ := (Fintype.card Ω : ℝ)⁻¹ + nonneg _ := inv_nonneg.mpr (Nat.cast_nonneg _) + total := by + have hN : (Fintype.card Ω : ℝ) ≠ 0 := Nat.cast_ne_zero.mpr Fintype.card_ne_zero + simp [hN] + +theorem uniform_isPositive (Ω : Type*) [Fintype Ω] [Nonempty Ω] : + (uniform Ω).IsPositive := fun _ => inv_pos.mpr (Nat.cast_pos.mpr Fintype.card_pos) + +theorem uniform_prob (Ω : Type*) [Fintype Ω] [Nonempty Ω] (P : Ω → Prop) : + (uniform Ω).prob P = ((Finset.univ.filter P).card : ℝ) / Fintype.card Ω := by + simp [prob, uniform, ← Finset.sum_filter, div_eq_mul_inv] + +end FiniteLaw + +end TalagrandDiscreteConvexity + +end + +end OAI diff --git a/lean/OAI/Combinatorics/DiscreteConvexity/FourierGlobalBound.lean b/lean/OAI/Combinatorics/DiscreteConvexity/FourierGlobalBound.lean new file mode 100644 index 0000000000000000000000000000000000000000..015103cb8186211e0ba6209f550de859d54f4a6f --- /dev/null +++ b/lean/OAI/Combinatorics/DiscreteConvexity/FourierGlobalBound.lean @@ -0,0 +1,76 @@ +import OAI.Combinatorics.DiscreteConvexity.FourierProductKernel +import OAI.Combinatorics.DiscreteConvexity.FiniteParseval +import Mathlib.Algebra.Order.BigOperators.Ring.Finset +import Mathlib.Tactic.Linarith + +namespace OAI + +/-! +# Biased Parseval and the global weight bound + +The exact Parseval multiplier for the unnormalized coefficients is +`(q / (1-q))^|U|`. The desired multiplier `q^|U|` is smaller for `0 < q < 1`. +The actual product-kernel identity proves Parseval here; it is not a hypothesis +of the global bound or its family-indicator specialization. +-/ + +noncomputable section +open scoped BigOperators + +namespace TalagrandDiscreteConvexity + +variable {V : Type*} [Fintype V] [DecidableEq V] + +/-- Square-root-free biased Parseval for the actual alternating coefficients. -/ +theorem biased_parseval (q : ℝ) (hq0 : 0 < q) (hq1 : q < 1) + (f : (V → Bool) → ℝ) : + (∑ U : Finset V, (q / (1 - q)) ^ U.card * w q f U) = + cubeExpectation q (fun x => (f x) ^ 2) := by + simpa only [b, w, cubeExpectation] using + weighted_kernel_parseval (rowKernel q) + (fun U : Finset V => (q / (1 - q)) ^ U.card) + (cubeWeight q) (rowKernel_gram q hq0 hq1) f + +theorem weight_sum_le_second_moment (q : ℝ) (hq0 : 0 < q) (hq1 : q < 1) + (f : (V → Bool) → ℝ) : + (∑ U : Finset V, q ^ U.card * w q f U) ≤ + cubeExpectation q (fun x => (f x) ^ 2) := by + rw [← biased_parseval q hq0 hq1 f] + have hratio : q ≤ q / (1 - q) := by + apply (le_div_iff₀ (sub_pos.mpr hq1)).mpr + nlinarith [sq_nonneg q] + apply Finset.sum_le_sum + intro U _ + exact mul_le_mul_of_nonneg_right + (pow_le_pow_left₀ hq0.le hratio U.card) (w_nonneg q f U) + +/-- A bounded-square function has global weight sum at most one. -/ +theorem global_weight_bound (q : ℝ) (hq0 : 0 < q) (hq1 : q < 1) + (f : (V → Bool) → ℝ) (hf : ∀ x, (f x) ^ 2 ≤ 1) : + (∑ U : Finset V, q ^ U.card * w q f U) ≤ 1 := by + apply (weight_sum_le_second_moment q hq0 hq1 f).trans + calc + cubeExpectation q (fun x => (f x) ^ 2) ≤ + ∑ x : V → Bool, cubeWeight q x := by + unfold cubeExpectation + apply Finset.sum_le_sum + intro x _ + simpa only [mul_one] using + mul_le_mul_of_nonneg_left (hf x) (cubeWeight_nonneg hq0.le hq1.le x) + _ = 1 := cubeWeight_sum q + +/-- The global weight bound for the actual indicator of an arbitrary family. +No monotonicity or density assumption on the family is needed. -/ +theorem indicator_global_weight_bound (q : ℝ) (hq0 : 0 < q) (hq1 : q < 1) + (D : Family V) : + (∑ U : Finset V, q ^ U.card * w q (familyIndicator D) U) ≤ 1 := by + apply global_weight_bound q hq0 hq1 (familyIndicator D) + intro x + rw [familyIndicator_sq] + exact familyIndicator_le_one D x + +end TalagrandDiscreteConvexity + +end + +end OAI diff --git a/lean/OAI/Combinatorics/DiscreteConvexity/FourierProductKernel.lean b/lean/OAI/Combinatorics/DiscreteConvexity/FourierProductKernel.lean new file mode 100644 index 0000000000000000000000000000000000000000..f34f348d9904006fb1fc55ed3d8f266c4238db03 --- /dev/null +++ b/lean/OAI/Combinatorics/DiscreteConvexity/FourierProductKernel.lean @@ -0,0 +1,89 @@ +import OAI.Combinatorics.DiscreteConvexity.FourierWeights +import Mathlib.Algebra.BigOperators.GroupWithZero.Finset +import Mathlib.Tactic.FieldSimp +import Mathlib.Tactic.Ring + +namespace OAI + +/-! +# Orthogonality of the biased product kernel + +The two possible choices at one coordinate give its Bernoulli diagonal +matrix. Summing over all subsets tensors this identity, with no square roots +or choice of a normalized Fourier basis. +-/ + +noncomputable section +open scoped BigOperators + +namespace TalagrandDiscreteConvexity + +/-- The one-coordinate Gram identity for the mass and alternating factors. -/ +theorem bitWeight_correction_gram (q : ℝ) (hq1 : q < 1) (x y : Bool) : + bitWeight q x * bitWeight q y + + (q / (1 - q)) * correction q x * correction q y = + if x = y then bitWeight q x else 0 := by + have hden : (1 : ℝ) - q ≠ 0 := ne_of_gt (sub_pos.mpr hq1) + cases x <;> cases y <;> + simp [bitWeight, correction] <;> field_simp [hden] <;> ring + +variable {V : Type*} [Fintype V] [DecidableEq V] + +/-- Move the subset weight into the coordinate product. -/ +theorem rowKernel_weighted_product (q : ℝ) (U : Finset V) (x y : V → Bool) : + (q / (1 - q)) ^ U.card * rowKernel q U x * rowKernel q U y = + ∏ i, if i ∈ U then + (q / (1 - q)) * correction q (x i) * correction q (y i) + else bitWeight q (x i) * bitWeight q (y i) := by + have hp : (q / (1 - q)) ^ U.card = + ∏ i : V, if i ∈ U then q / (1 - q) else 1 := by + symm + rw [Finset.prod_ite_mem_eq, Finset.prod_const] + rw [hp] + simp only [rowKernel] + rw [← Finset.prod_mul_distrib, ← Finset.prod_mul_distrib] + apply Finset.prod_congr rfl + intro i _ + by_cases hi : i ∈ U <;> simp [hi] + +/-- Summing the weighted kernel products over all subsets gives the original +Bernoulli mass on the diagonal and zero away from the diagonal. -/ +theorem rowKernel_gram (q : ℝ) (_hq0 : 0 < q) (hq1 : q < 1) (x y : V → Bool) : + (∑ U : Finset V, + (q / (1 - q)) ^ U.card * rowKernel q U x * rowKernel q U y) = + if x = y then cubeWeight q x else 0 := by + classical + calc + (∑ U : Finset V, + (q / (1 - q)) ^ U.card * rowKernel q U x * rowKernel q U y) = + ∑ U : Finset V, ∏ i, if i ∈ U then + (q / (1 - q)) * correction q (x i) * correction q (y i) + else bitWeight q (x i) * bitWeight q (y i) := by + apply Finset.sum_congr rfl + intro U _ + exact rowKernel_weighted_product q U x y + _ = ∏ i, + ((q / (1 - q)) * correction q (x i) * correction q (y i) + + bitWeight q (x i) * bitWeight q (y i)) := by + simpa using (sum_finset_product (fun (i : V) (flag : Bool) => + if flag then + (q / (1 - q)) * correction q (x i) * correction q (y i) + else bitWeight q (x i) * bitWeight q (y i))) + _ = ∏ i, if x i = y i then bitWeight q (x i) else 0 := by + apply Finset.prod_congr rfl + intro i _ + rw [add_comm] + exact bitWeight_correction_gram q hq1 (x i) (y i) + _ = if x = y then cubeWeight q x else 0 := by + rw [Fintype.prod_ite_zero] + by_cases hxy : x = y + · have hpoint : ∀ i, x i = y i := fun i => congrFun hxy i + simp only [ite_eq_left hpoint, ite_eq_left hxy, cubeWeight] + · have hpoint : ¬ ∀ i, x i = y i := fun h => hxy (funext h) + simp only [ite_eq_right hpoint, ite_eq_right hxy] + +end TalagrandDiscreteConvexity + +end + +end OAI diff --git a/lean/OAI/Combinatorics/DiscreteConvexity/FourierWeights.lean b/lean/OAI/Combinatorics/DiscreteConvexity/FourierWeights.lean new file mode 100644 index 0000000000000000000000000000000000000000..6171fed6f0195e38b53b091bbf7a763471c7c9b1 --- /dev/null +++ b/lean/OAI/Combinatorics/DiscreteConvexity/FourierWeights.lean @@ -0,0 +1,85 @@ +import OAI.Combinatorics.DiscreteConvexity.Bernoulli +import Mathlib.Algebra.BigOperators.Group.Finset.Piecewise + +namespace OAI + +noncomputable section +open scoped BigOperators + +namespace TalagrandDiscreteConvexity + +/-- The alternating factor for a coordinate inside the differentiated set. -/ +def correction (q : ℝ) (bit : Bool) : ℝ := + if bit then -(1 - q) else 1 - q + +@[simp] theorem correction_false (q : ℝ) : correction q false = 1 - q := rfl + +@[simp] theorem correction_true (q : ℝ) : correction q true = -(1 - q) := rfl + +variable {V : Type*} [Fintype V] [DecidableEq V] + +/-- Coordinate product defining the alternating partial expectation. -/ +def rowKernel (q : ℝ) (U : Finset V) (x : V → Bool) : ℝ := + ∏ i, if i ∈ U then correction q (x i) else bitWeight q (x i) + +/-- Exactly `(1-q)^|U|` times the alternating sum over the coordinates in `U`, +with independent Bernoulli expectation on its complement. -/ +def b (q : ℝ) (f : (V → Bool) → ℝ) (U : Finset V) : ℝ := + ∑ x, f x * rowKernel q U x + +/-- The nonnegative weights used by both global and exceptional-set bounds. -/ +def w (q : ℝ) (f : (V → Bool) → ℝ) (U : Finset V) : ℝ := + (b q f U) ^ 2 + +/-- Separate the alternating coordinates from the independent outside mass. -/ +theorem rowKernel_eq_alternating_product (q : ℝ) (U : Finset V) (x : V → Bool) : + rowKernel q U x = (1 - q) ^ U.card * + (∏ i ∈ U, if x i then (-1 : ℝ) else 1) * + ∏ i ∈ Finset.univ \ U, bitWeight q (x i) := by + have hsplit : rowKernel q U x = + (∏ i ∈ U, correction q (x i)) * + ∏ i ∈ Finset.univ \ U, bitWeight q (x i) := by + simpa only [rowKernel, Finset.piecewise, Finset.univ_inter] using + (Finset.prod_piecewise Finset.univ U + (fun i => correction q (x i)) (fun i => bitWeight q (x i))) + have hc : (∏ i ∈ U, correction q (x i)) = + (1 - q) ^ U.card * ∏ i ∈ U, if x i then (-1 : ℝ) else 1 := by + calc + (∏ i ∈ U, correction q (x i)) = + ∏ i ∈ U, (1 - q) * (if x i then (-1 : ℝ) else 1) := by + apply Finset.prod_congr rfl + intro i _ + cases x i <;> simp [correction] + _ = _ := by rw [Finset.prod_mul_distrib, Finset.prod_const] + rw [hsplit, hc] + +/-- The explicit alternating partial-expectation formula for the coefficient. -/ +theorem b_eq_alternating_sum (q : ℝ) (f : (V → Bool) → ℝ) (U : Finset V) : + b q f U = (1 - q) ^ U.card * + ∑ x, f x * (∏ i ∈ U, if x i then (-1 : ℝ) else 1) * + ∏ i ∈ Finset.univ \ U, bitWeight q (x i) := by + simp only [b, rowKernel_eq_alternating_product, Finset.mul_sum] + apply Finset.sum_congr rfl + intro x _ + ac_rfl + +@[simp] theorem rowKernel_empty (q : ℝ) (x : V → Bool) : + rowKernel q ∅ x = cubeWeight q x := by + simp [rowKernel, cubeWeight] + +/-- The empty coefficient is the original biased expectation. -/ +@[simp] theorem b_empty (q : ℝ) (f : (V → Bool) → ℝ) : + b q f ∅ = cubeExpectation q f := by + simp only [b, rowKernel_empty, cubeExpectation] + apply Finset.sum_congr rfl + intro x _ + exact mul_comm _ _ + +theorem w_nonneg (q : ℝ) (f : (V → Bool) → ℝ) (U : Finset V) : + 0 ≤ w q f U := sq_nonneg _ + +end TalagrandDiscreteConvexity + +end + +end OAI diff --git a/lean/OAI/Combinatorics/DiscreteConvexity/HalfDensity.lean b/lean/OAI/Combinatorics/DiscreteConvexity/HalfDensity.lean new file mode 100644 index 0000000000000000000000000000000000000000..83261fd7e3f71447d0b2acd4f86e381c5154e0ff --- /dev/null +++ b/lean/OAI/Combinatorics/DiscreteConvexity/HalfDensity.lean @@ -0,0 +1,27 @@ +import OAI.Combinatorics.DiscreteConvexity.WeightedCover +import OAI.Combinatorics.DiscreteConvexity.FourierGlobalBound +import OAI.Combinatorics.DiscreteConvexity.SignedArrays + +namespace OAI + +/-! +# Small exceptional families at a fixed fraction of the density + +The actual biased Fourier weights satisfy both estimates needed by the finite +bin construction. No monotonicity of the given family is assumed. +-/ + +namespace TalagrandDiscreteConvexity + +variable {α : Type*} [Fintype α] [DecidableEq α] + +theorem halfDensity_small {q : ℝ} (hq0 : 0 < q) (hq1 : q < 1) + (F : Family α) (hF : (1 / 2 : ℝ) ≤ familyMeasure q F) : + Small (q / (2 : ℝ) ^ 70) (exceptional 32 F) := by + exact weights_small hq0 hq1 (exceptional 32 F) (w q (familyIndicator F)) + (w_nonneg q (familyIndicator F)) (indicator_global_weight_bound q hq0 hq1 F) + (fun _ hS => exceptional_weight_lower_bound q hF hS) + +end TalagrandDiscreteConvexity + +end OAI diff --git a/lean/OAI/Combinatorics/DiscreteConvexity/LabelCoupling.lean b/lean/OAI/Combinatorics/DiscreteConvexity/LabelCoupling.lean new file mode 100644 index 0000000000000000000000000000000000000000..a911eb313fa941589c4773ee7e1fa2a2c18a65e4 --- /dev/null +++ b/lean/OAI/Combinatorics/DiscreteConvexity/LabelCoupling.lean @@ -0,0 +1,171 @@ +import OAI.Combinatorics.DiscreteConvexity.Basic +import OAI.Combinatorics.DiscreteConvexity.CoordinateObservations +import OAI.Combinatorics.DiscreteConvexity.UnionBound +import Mathlib.Algebra.BigOperators.Fin +import Mathlib.Algebra.BigOperators.Group.Finset.Piecewise +import Mathlib.Tactic.Ring + +namespace OAI + +namespace TalagrandDiscreteConvexity + +open scoped BigOperators + +noncomputable section + +/-- One coordinate receives label zero with the residual mass, and each of the +`L` row labels with mass `p`. This does not assert independence of the rows. -/ +def labelLaw (L : ℕ) (p : ℝ) (hp : 0 ≤ p) (hLp : (L : ℝ) * p ≤ 1) : + FiniteLaw (Fin (L + 1)) := by + classical + exact { + weight := fun j => if j = 0 then 1 - (L : ℝ) * p else p + nonneg := fun j => by + split_ifs + · exact sub_nonneg.mpr hLp + · exact hp + total := by + rw [Fin.sum_univ_succ] + simp [nsmul_eq_mul] } + +@[simp] theorem labelLaw_weight_zero (L : ℕ) (p : ℝ) + (hp : 0 ≤ p) (hLp : (L : ℝ) * p ≤ 1) : + (labelLaw L p hp hLp).weight 0 = 1 - (L : ℝ) * p := by + simp [labelLaw] + +@[simp] theorem labelLaw_weight_succ (L : ℕ) (p : ℝ) + (hp : 0 ≤ p) (hLp : (L : ℝ) * p ≤ 1) (j : Fin L) : + (labelLaw L p hp hLp).weight j.succ = p := by + simp [labelLaw] + +@[simp] theorem labelLaw_prob_zero (L : ℕ) (p : ℝ) + (hp : 0 ≤ p) (hLp : (L : ℝ) * p ≤ 1) : + (labelLaw L p hp hLp).prob (fun j => j = 0) = 1 - (L : ℝ) * p := by + classical + unfold FiniteLaw.prob + refine (Finset.sum_eq_single (0 : Fin (L + 1)) ?_ ?_).trans ?_ + · intro k _ hk + exact ite_eq_right hk + · simp + · simp only [ite_true, labelLaw_weight_zero] + +@[simp] theorem labelLaw_prob_succ (L : ℕ) (p : ℝ) + (hp : 0 ≤ p) (hLp : (L : ℝ) * p ≤ 1) (j : Fin L) : + (labelLaw L p hp hLp).prob (fun k => k = j.succ) = p := by + classical + unfold FiniteLaw.prob + refine (Finset.sum_eq_single j.succ ?_ ?_).trans ?_ + · intro k _ hk + exact ite_eq_right hk + · simp + · simp only [ite_true, labelLaw_weight_succ] + +@[simp] theorem labelLaw_prob_nonzero (L : ℕ) (p : ℝ) + (hp : 0 ≤ p) (hLp : (L : ℝ) * p ≤ 1) : + (labelLaw L p hp hLp).prob (fun j => j ≠ 0) = (L : ℝ) * p := by + have h := (labelLaw L p hp hLp).prob_compl (fun j => j = 0) + simpa only [labelLaw_prob_zero, sub_sub_cancel] using h + +variable {α : Type*} [Fintype α] [DecidableEq α] + +/-- Independent coordinate labels; the row membership events may be dependent. -/ +def labelSamples (L : ℕ) (p : ℝ) (hp : 0 ≤ p) (hLp : (L : ℝ) * p ≤ 1) : + FiniteLaw (α → Fin (L + 1)) := + FiniteLaw.pi (fun _ : α => labelLaw L p hp hLp) + +/-- Row `j` contains exactly the coordinates labeled by its successor label. -/ +def labelRow {L : ℕ} (ω : α → Fin (L + 1)) (j : Fin L) : Finset α := by + classical + exact cubeSet (fun i => decide (ω i = j.succ)) + +omit [DecidableEq α] in +@[simp] theorem mem_labelRow {L : ℕ} {ω : α → Fin (L + 1)} + {j : Fin L} {i : α} : i ∈ labelRow ω j ↔ ω i = j.succ := by + classical + simp [labelRow] + +theorem labelUnion_eq_cubeSet_nonzero {L : ℕ} (ω : α → Fin (L + 1)) : + unionTuple (labelRow ω) = cubeSet (fun i => decide (ω i ≠ 0)) := by + classical + ext i + simp only [mem_unionTuple, mem_labelRow, mem_cubeSet, decide_eq_true_eq] + constructor + · rintro ⟨j, hj⟩ + rw [hj] + exact Fin.succ_ne_zero j + · intro hi + exact Fin.eq_succ_of_ne_zero hi + +/-- Every row has the full Bernoulli law, proved from independent coordinates. -/ +theorem labelRow_prob_eq_mass (L : ℕ) (p : ℝ) (hp : 0 ≤ p) + (hLp : (L : ℝ) * p ≤ 1) (j : Fin L) (s : Finset α) : + (labelSamples L p hp hLp).prob (fun ω => labelRow ω j = s) = + bernoulliMass p s := by + classical + have hobs (i : α) : + (labelLaw L p hp hLp).prob (fun k => decide (k = j.succ) = true) = p := by + simpa only [decide_eq_true_eq] using labelLaw_prob_succ L p hp hLp j + simpa only [labelSamples, labelRow] using + prob_pi_cubeSet_eq_mass (fun _ : α => labelLaw L p hp hLp) + (fun _ k => decide (k = j.succ)) p hobs s + +theorem labelRow_prob_mem_family (L : ℕ) (p : ℝ) (hp : 0 ≤ p) + (hLp : (L : ℝ) * p ≤ 1) (j : Fin L) (D : Family α) : + (labelSamples L p hp hLp).prob (fun ω => labelRow ω j ∈ D) = + familyMeasure p D := by + classical + have hobs (i : α) : + (labelLaw L p hp hLp).prob (fun k => decide (k = j.succ) = true) = p := by + simpa only [decide_eq_true_eq] using labelLaw_prob_succ L p hp hLp j + simpa only [labelSamples, labelRow] using + prob_pi_cubeSet_mem_family (fun _ : α => labelLaw L p hp hLp) + (fun _ k => decide (k = j.succ)) p hobs D + +/-- The row union has the full Bernoulli law at the amplified density `L * p`. -/ +theorem labelUnion_prob_eq_mass (L : ℕ) (p : ℝ) (hp : 0 ≤ p) + (hLp : (L : ℝ) * p ≤ 1) (s : Finset α) : + (labelSamples L p hp hLp).prob (fun ω => unionTuple (labelRow ω) = s) = + bernoulliMass ((L : ℝ) * p) s := by + classical + have hobs (i : α) : + (labelLaw L p hp hLp).prob (fun k => decide (k ≠ 0) = true) = (L : ℝ) * p := by + simpa only [decide_eq_true_eq] using labelLaw_prob_nonzero L p hp hLp + simpa only [labelSamples, labelUnion_eq_cubeSet_nonzero] using + prob_pi_cubeSet_eq_mass (fun _ : α => labelLaw L p hp hLp) + (fun _ k => decide (k ≠ 0)) ((L : ℝ) * p) hobs s + +theorem labelUnion_prob_mem_family (L : ℕ) (p : ℝ) (hp : 0 ≤ p) + (hLp : (L : ℝ) * p ≤ 1) (D : Family α) : + (labelSamples L p hp hLp).prob (fun ω => unionTuple (labelRow ω) ∈ D) = + familyMeasure ((L : ℝ) * p) D := by + classical + have hobs (i : α) : + (labelLaw L p hp hLp).prob (fun k => decide (k ≠ 0) = true) = (L : ℝ) * p := by + simpa only [decide_eq_true_eq] using labelLaw_prob_nonzero L p hp hLp + simpa only [labelSamples, labelUnion_eq_cubeSet_nonzero] using + prob_pi_cubeSet_mem_family (fun _ : α => labelLaw L p hp hLp) + (fun _ k => decide (k ≠ 0)) ((L : ℝ) * p) hobs D + +/-- Dependent rows give the density bound using only a union bound on failures. +The law of the rows and of their union is supplied by the explicit label coupling. -/ +theorem familyMeasure_unionFamily_label_lower (L : ℕ) (p : ℝ) (hp : 0 ≤ p) + (hLp : (L : ℝ) * p ≤ 1) (D : Family α) : + 1 - (L : ℝ) * (1 - familyMeasure p D) ≤ + familyMeasure ((L : ℝ) * p) (unionFamily L D) := by + classical + have hgood := FiniteLaw.prob_forall_ge_of_const + (labelSamples (α := α) L p hp hLp) + (fun (j : Fin L) ω => labelRow ω j ∈ D) (familyMeasure p D) + (fun j => labelRow_prob_mem_family L p hp hLp j D) + have hinclusion := (labelSamples (α := α) L p hp hLp).prob_mono + (P := fun ω => ∀ j : Fin L, labelRow ω j ∈ D) + (Q := fun ω => unionTuple (labelRow ω) ∈ unionFamily L D) + (fun ω hω => mem_unionFamily.mpr ⟨labelRow ω, hω, rfl⟩) + rw [labelUnion_prob_mem_family] at hinclusion + simpa only [Fintype.card_fin] using hgood.trans hinclusion + +end + +end TalagrandDiscreteConvexity + +end OAI diff --git a/lean/OAI/Combinatorics/DiscreteConvexity/Main.lean b/lean/OAI/Combinatorics/DiscreteConvexity/Main.lean new file mode 100644 index 0000000000000000000000000000000000000000..9dc92872ef4727dab6ab1a6ffb35e27a8905b490 --- /dev/null +++ b/lean/OAI/Combinatorics/DiscreteConvexity/Main.lean @@ -0,0 +1,69 @@ +import OAI.Combinatorics.DiscreteConvexity.HalfDensity +import OAI.Combinatorics.DiscreteConvexity.DensityConstants +import OAI.Combinatorics.DiscreteConvexity.LabelCoupling +import OAI.Combinatorics.DiscreteConvexity.MandatoryCoupling +import OAI.Combinatorics.DiscreteConvexity.UnionTuples + +namespace OAI + +/-! +# Talagrand discrete convexity at the original density + +Independent coordinate choices produce dependent rows with full Bernoulli +subset laws. The label construction raises the union density when `L p < 1`; +the mandatory-row construction covers every coordinate when `1 ≤ L p`. +Both cases use the same row-failure budget, without independence between rows. +-/ + +namespace TalagrandDiscreteConvexity + +variable {α : Type*} [Fintype α] [DecidableEq α] + +/-- The density reduction works on any finite ground set. -/ +theorem original_density_small (p : ℝ) (hp0 : 0 < p) (hp1 : p < 1) + (D : Family α) (hD : 1 - 1 / (2 : ℝ) ^ 75 ≤ familyMeasure p D) : + Small p (exceptional ((2 : ℕ) ^ 75) D) := by + let L : ℕ := 2 ^ 70 + have hL : 1 < L := density_rows_gt_one + have hLpos : (0 : ℝ) < (L : ℝ) := by + exact_mod_cast density_rows_pos + have hLcast : (L : ℝ) = (2 : ℝ) ^ 70 := by + simp only [L, Nat.cast_pow, Nat.cast_ofNat] + have hcount : 32 * L = (2 : ℕ) ^ 75 := density_tuple_count + have hD' : 1 - 1 / (32 * (L : ℝ)) ≤ familyMeasure p D := by + rw [hLcast, ← density_tuple_count_real] + exact hD + have hbudget : (L : ℝ) * (1 - familyMeasure p D) ≤ 1 / 32 := + density_failure_budget hLpos hD' + by_cases hlow : (L : ℝ) * p < 1 + · have hq0 : 0 < (L : ℝ) * p := mul_pos hLpos hp0 + have hmeasure := familyMeasure_unionFamily_label_lower L p hp0.le hlow.le D + have hhalf : (1 / 2 : ℝ) ≤ familyMeasure ((L : ℝ) * p) (unionFamily L D) := by + calc + (1 / 2 : ℝ) ≤ 1 - 1 / 32 := by norm_num + _ ≤ 1 - (L : ℝ) * (1 - familyMeasure p D) := sub_le_sub_left hbudget 1 + _ ≤ familyMeasure ((L : ℝ) * p) (unionFamily L D) := hmeasure + have hsmall := halfDensity_small hq0 hlow (unionFamily L D) hhalf + have hquot : ((L : ℝ) * p) / (2 : ℝ) ^ 70 = p := by + rw [← hLcast] + exact mul_div_cancel_left₀ p hLpos.ne' + rw [hquot, exceptional_unionFamily, hcount] at hsmall + exact hsmall + · have hhigh : 1 ≤ (L : ℝ) * p := le_of_not_gt hlow + obtain ⟨rows, hrows, hfull⟩ := exists_mandatory_cover hL p hp1 hhigh D + (hbudget.trans_lt (by norm_num : (1 / 32 : ℝ) < 1)) + have hempty := exceptional_mul_eq_empty_of_full_union + (a := 32) (by decide : 0 < 32) rows hrows hfull + rw [hcount] at hempty + rw [hempty] + exact small_empty p + +theorem talagrand_discrete_convexity (N : ℕ) (_hN : 1 ≤ N) + (p : ℝ) (hp0 : 0 < p) (hp1 : p < 1) (D : Family (Fin N)) + (hD : 1 - 1 / (2 : ℝ) ^ 75 ≤ familyMeasure p D) : + Small p (exceptional ((2 : ℕ) ^ 75) D) := + original_density_small p hp0 hp1 D hD + +end TalagrandDiscreteConvexity + +end OAI diff --git a/lean/OAI/Combinatorics/DiscreteConvexity/MandatoryCoupling.lean b/lean/OAI/Combinatorics/DiscreteConvexity/MandatoryCoupling.lean new file mode 100644 index 0000000000000000000000000000000000000000..4b9c248e35564a0c181ce81bf89fb6ca66b88707 --- /dev/null +++ b/lean/OAI/Combinatorics/DiscreteConvexity/MandatoryCoupling.lean @@ -0,0 +1,187 @@ +import OAI.Combinatorics.DiscreteConvexity.Basic +import OAI.Combinatorics.DiscreteConvexity.CoordinateObservations +import OAI.Combinatorics.DiscreteConvexity.UnionBound +import Mathlib.Algebra.Order.Field.Basic +import Mathlib.Tactic.NormNum +import Mathlib.Tactic.Ring + +namespace OAI + +/-! +# The mandatory-row coupling at high density + +The auxiliary inclusion probability is valid throughout the closed high-density +regime `1 ≤ L * p`, including equality, when it is zero. + +At each coordinate the mandatory label is uniform and independent of the +independent Bernoulli marks. Taking a product of these laws across coordinates +gives each row its full Bernoulli subset law. The union is full in every outcome; +only marginal probabilities are used to obtain simultaneous family membership. +-/ + +noncomputable section + +namespace TalagrandDiscreteConvexity + +/-- The extra inclusion probability after the uniformly chosen mandatory row. -/ +def mandatoryParameter (L : ℕ) (p : ℝ) : ℝ := + (p - 1 / (L : ℝ)) / (1 - 1 / (L : ℝ)) + +theorem mandatoryParameter_den_pos {L : ℕ} (hL : 1 < L) : + 0 < 1 - 1 / (L : ℝ) := by + have hLreal : (1 : ℝ) < (L : ℝ) := by exact_mod_cast hL + have hLpos : (0 : ℝ) < (L : ℝ) := lt_trans zero_lt_one hLreal + exact sub_pos.mpr ((div_lt_one hLpos).mpr hLreal) + +theorem mandatoryParameter_nonneg {L : ℕ} {p : ℝ} + (hL : 1 < L) (hLp : 1 ≤ (L : ℝ) * p) : + 0 ≤ mandatoryParameter L p := by + have hLreal : (1 : ℝ) < (L : ℝ) := by exact_mod_cast hL + have hLpos : (0 : ℝ) < (L : ℝ) := lt_trans zero_lt_one hLreal + have hbase : 1 / (L : ℝ) ≤ p := + (div_le_iff₀ hLpos).mpr (by simpa only [mul_comm] using hLp) + exact div_nonneg (sub_nonneg.mpr hbase) (mandatoryParameter_den_pos hL).le + +theorem mandatoryParameter_lt_one {L : ℕ} {p : ℝ} + (hL : 1 < L) (hp : p < 1) : mandatoryParameter L p < 1 := by + exact (div_lt_one (mandatoryParameter_den_pos hL)).mpr + (sub_lt_sub_right hp (1 / (L : ℝ))) + +theorem mandatoryParameter_marginal {L : ℕ} (hL : 1 < L) (p : ℝ) : + 1 / (L : ℝ) + (1 - 1 / (L : ℝ)) * mandatoryParameter L p = p := by + unfold mandatoryParameter + rw [mul_div_cancel₀ _ (mandatoryParameter_den_pos hL).ne'] + ring + +theorem mandatoryParameter_boundary {L : ℕ} {p : ℝ} + (hL : 1 < L) (hLp : (L : ℝ) * p = 1) : mandatoryParameter L p = 0 := by + have hLreal : (1 : ℝ) < (L : ℝ) := by exact_mod_cast hL + have hLpos : (0 : ℝ) < (L : ℝ) := lt_trans zero_lt_one hLreal + have hpbase : p = 1 / (L : ℝ) := + (eq_div_iff hLpos.ne').mpr (by simpa only [mul_comm] using hLp) + unfold mandatoryParameter + rw [hpbase, sub_self, zero_div] + +/-- A coordinate chooses one compulsory row, together with independent marks. +The mark in the compulsory row may be sampled and then ignored. -/ +abbrev MandatoryColumn (L : ℕ) := Fin L × (Fin L → Bool) + +def mandatoryBit {L : ℕ} (j : Fin L) (z : MandatoryColumn L) : Bool := + decide (z.1 = j ∨ z.2 j = true) + +@[simp] theorem mandatoryBit_mandatory {L : ℕ} (z : MandatoryColumn L) : + mandatoryBit z.1 z = true := by + simp [mandatoryBit] + +private theorem mandatory_prob_prod_or {Ω Γ : Type*} [Fintype Ω] [Fintype Γ] + (μ : FiniteLaw Ω) (ν : FiniteLaw Γ) (P : Ω → Prop) (Q : Γ → Prop) : + (μ.prod ν).prob (fun z => P z.1 ∨ Q z.2) = + μ.prob P + (1 - μ.prob P) * ν.prob Q := by + classical + have h := (μ.prod ν).prob_compl (fun z => P z.1 ∨ Q z.2) + simp only [not_or] at h + rw [FiniteLaw.prob_prod μ ν (fun ω => ¬ P ω) (fun γ => ¬ Q γ), + μ.prob_compl P, ν.prob_compl Q] at h + nlinarith only [h] + +/-- Uniform mandatory label, independent of all the extra row marks. -/ +def mandatoryColumnLaw {L : ℕ} (hL : 1 < L) (p : ℝ) (hp : p < 1) + (hLp : 1 ≤ (L : ℝ) * p) : FiniteLaw (MandatoryColumn L) := by + let : Nonempty (Fin L) := ⟨⟨0, lt_trans Nat.zero_lt_one hL⟩⟩ + exact (FiniteLaw.uniform (Fin L)).prod + (FiniteLaw.iid (bitLaw (mandatoryParameter L p) + (mandatoryParameter_nonneg hL hLp) (mandatoryParameter_lt_one hL hp).le) L) + +theorem mandatoryColumnLaw_marginal {L : ℕ} (hL : 1 < L) (p : ℝ) + (hp : p < 1) (hLp : 1 ≤ (L : ℝ) * p) (j : Fin L) : + (mandatoryColumnLaw hL p hp hLp).prob (fun z => mandatoryBit j z = true) = p := by + classical + let : Nonempty (Fin L) := ⟨⟨0, lt_trans Nat.zero_lt_one hL⟩⟩ + have hmandatory : (FiniteLaw.uniform (Fin L)).prob (fun k => k = j) = + 1 / (L : ℝ) := by + rw [FiniteLaw.uniform_prob] + simp only [Fintype.card_fin] + congr 1 + norm_cast + apply Finset.card_eq_one.mpr + refine ⟨j, ?_⟩ + ext k + simp + have hmarks : + (FiniteLaw.iid (bitLaw (mandatoryParameter L p) + (mandatoryParameter_nonneg hL hLp) (mandatoryParameter_lt_one hL hp).le) L).prob + (fun marks => marks j = true) = mandatoryParameter L p := by + unfold FiniteLaw.iid + rw [FiniteLaw.prob_pi_coordinate + (fun _ : Fin L => bitLaw (mandatoryParameter L p) + (mandatoryParameter_nonneg hL hLp) (mandatoryParameter_lt_one hL hp).le) + j (fun b : Bool => b = true)] + exact bitLaw_prob_true _ _ _ + unfold mandatoryColumnLaw + simp only [mandatoryBit, decide_eq_true_eq] + rw [mandatory_prob_prod_or (FiniteLaw.uniform (Fin L)) + (FiniteLaw.iid (bitLaw (mandatoryParameter L p) + (mandatoryParameter_nonneg hL hLp) (mandatoryParameter_lt_one hL hp).le) L) + (fun k : Fin L => k = j) (fun marks : Fin L → Bool => marks j = true), + hmandatory, hmarks] + exact mandatoryParameter_marginal hL p + +variable {α : Type*} [Fintype α] [DecidableEq α] + +/-- Read the sets in all rows of a coordinate array. -/ +def mandatoryRows {L : ℕ} (ω : α → MandatoryColumn L) (j : Fin L) : Finset α := + cubeSet (fun i => mandatoryBit j (ω i)) + +/-- The coordinate choices are independent; the rows need not be independent. -/ +def mandatoryArrayLaw {L : ℕ} (hL : 1 < L) (p : ℝ) (hp : p < 1) + (hLp : 1 ≤ (L : ℝ) * p) : FiniteLaw (α → MandatoryColumn L) := + FiniteLaw.pi (fun _ : α => mandatoryColumnLaw hL p hp hLp) + +/-- Every atom of each row has its exact Bernoulli subset mass. -/ +theorem mandatoryRows_prob_eq_mass {L : ℕ} (hL : 1 < L) (p : ℝ) + (hp : p < 1) (hLp : 1 ≤ (L : ℝ) * p) (j : Fin L) (s : Finset α) : + (mandatoryArrayLaw (α := α) hL p hp hLp).prob + (fun ω => mandatoryRows ω j = s) = bernoulliMass p s := by + exact prob_pi_cubeSet_eq_mass (fun _ : α => mandatoryColumnLaw hL p hp hLp) + (fun _ => mandatoryBit j) p (fun _ => mandatoryColumnLaw_marginal hL p hp hLp j) s + +/-- The row distribution agrees on arbitrary, potentially nonmonotone families. -/ +theorem mandatoryRows_prob_mem_family {L : ℕ} (hL : 1 < L) (p : ℝ) + (hp : p < 1) (hLp : 1 ≤ (L : ℝ) * p) (j : Fin L) (D : Family α) : + (mandatoryArrayLaw (α := α) hL p hp hLp).prob + (fun ω => mandatoryRows ω j ∈ D) = familyMeasure p D := by + exact prob_pi_cubeSet_mem_family (fun _ : α => mandatoryColumnLaw hL p hp hLp) + (fun _ => mandatoryBit j) p (fun _ => mandatoryColumnLaw_marginal hL p hp hLp j) D + +/-- The selected mandatory row contains each coordinate in every outcome. -/ +theorem mandatoryRows_union {L : ℕ} (ω : α → MandatoryColumn L) : + unionTuple (mandatoryRows ω) = Finset.univ := by + ext i + simp only [Finset.mem_univ, iff_true] + apply mem_unionTuple.mpr + refine ⟨(ω i).1, ?_⟩ + exact mem_cubeSet.mpr (mandatoryBit_mandatory (ω i)) + +/-- Marginal success probabilities and the union bound give a covering tuple. +There is no independence assumption between the rows. -/ +theorem exists_mandatory_cover {L : ℕ} (hL : 1 < L) (p : ℝ) + (hp : p < 1) (hLp : 1 ≤ (L : ℝ) * p) (D : Family α) + (hbudget : (L : ℝ) * (1 - familyMeasure p D) < 1) : + ∃ rows : Fin L → Finset α, + (∀ j, rows j ∈ D) ∧ unionTuple rows = Finset.univ := by + have hmarginal (j : Fin L) : + (mandatoryArrayLaw (α := α) hL p hp hLp).prob + (fun ω => mandatoryRows ω j ∈ D) = familyMeasure p D := + mandatoryRows_prob_mem_family hL p hp hLp j D + have hbudget' : (Fintype.card (Fin L) : ℝ) * (1 - familyMeasure p D) < 1 := by + simpa only [Fintype.card_fin] using hbudget + obtain ⟨ω, hω⟩ := FiniteLaw.exists_forall_of_const + (mandatoryArrayLaw (α := α) hL p hp hLp) + (fun j ω => mandatoryRows ω j ∈ D) (familyMeasure p D) hmarginal hbudget' + exact ⟨mandatoryRows ω, hω, mandatoryRows_union ω⟩ + +end TalagrandDiscreteConvexity + +end + +end OAI diff --git a/lean/OAI/Combinatorics/DiscreteConvexity/Model.lean b/lean/OAI/Combinatorics/DiscreteConvexity/Model.lean new file mode 100644 index 0000000000000000000000000000000000000000..6f82265099eafabeaf710668e9eb37855ffe1687 --- /dev/null +++ b/lean/OAI/Combinatorics/DiscreteConvexity/Model.lean @@ -0,0 +1,71 @@ +import Mathlib.Data.Fintype.Powerset +import Mathlib.Data.Finset.Union +import Mathlib.Basic.Real.Basic +import Mathlib.Algebra.Order.BigOperators.Group.Finset + +namespace OAI + +/-! +# Finite families, containment covers, and exceptional sets + +All families are ordinary finite sets: repeated generators carry no extra cost. +In contrast, the members of a union tuple may repeat. The exceptional family +uses containment in a union, without any monotonicity assumption on the input. +-/ + +namespace TalagrandDiscreteConvexity + +open scoped BigOperators + +abbrev Family (α : Type*) := Finset (Finset α) + +variable {α : Type*} [Fintype α] [DecidableEq α] + +noncomputable section + +/-- The mass of a subset under independent Bernoulli coordinates. -/ +def bernoulliMass (p : ℝ) (s : Finset α) : ℝ := + p ^ s.card * (1 - p) ^ (Finset.univ \ s).card + +/-- The Bernoulli measure of an arbitrary finite family. -/ +def familyMeasure (p : ℝ) (D : Family α) : ℝ := + ∑ s ∈ D, bernoulliMass p s + +/-- Cost at the specified density, counting each generator once. -/ +def cost (p : ℝ) (G : Family α) : ℝ := ∑ I ∈ G, p ^ I.card + +/-- A cover supplies a contained generator for every target set. -/ +def Covers (G A : Family α) : Prop := ∀ S ∈ A, ∃ I ∈ G, I ⊆ S + +/-- Smallness is witnessed by an actual containment cover of cost at most one half. -/ +def Small (p : ℝ) (A : Family α) : Prop := + ∃ G : Family α, Covers G A ∧ cost p G ≤ 1 / 2 + +/-- A union of exactly `k` entries; repetitions are allowed. -/ +def unionTuple {k : ℕ} (f : Fin k → Finset α) : Finset α := + Finset.univ.biUnion f + +/-- All unions of `k` members of a family. -/ +def unionFamily (k : ℕ) (D : Family α) : Family α := by + classical + exact Finset.univ.filter (fun S => + ∃ f : Fin k → Finset α, (∀ j, f j ∈ D) ∧ unionTuple f = S) + +/-- Sets contained in no union of `k` members of `D`. -/ +def exceptional (k : ℕ) (D : Family α) : Family α := by + classical + exact Finset.univ.filter (fun S => + ∀ f : Fin k → Finset α, (∀ j, f j ∈ D) → ¬ S ⊆ unionTuple f) + +/-- The subset represented by a Boolean coordinate vector. -/ +def cubeSet (x : α → Bool) : Finset α := + Finset.univ.filter (fun i => x i = true) + +/-- The indicator of a family on the Boolean cube. -/ +def familyIndicator (D : Family α) (x : α → Bool) : ℝ := + if cubeSet x ∈ D then 1 else 0 + +end +end TalagrandDiscreteConvexity + +end OAI diff --git a/lean/OAI/Combinatorics/DiscreteConvexity/ProbabilisticExistence.lean b/lean/OAI/Combinatorics/DiscreteConvexity/ProbabilisticExistence.lean new file mode 100644 index 0000000000000000000000000000000000000000..69fbf39dadf929004093d33b791bd11bdb892823 --- /dev/null +++ b/lean/OAI/Combinatorics/DiscreteConvexity/ProbabilisticExistence.lean @@ -0,0 +1,57 @@ +import OAI.Combinatorics.DiscreteConvexity.FiniteProbability + +namespace OAI + +/-! +# Extracting outcomes from a finite probability law + +Normalization guarantees a positive-weight outcome. It also guarantees an +outcome below the expectation and a witness to every positive-probability +event; strict positivity of every individual mass is not required. +-/ + +namespace TalagrandDiscreteConvexity.FiniteLaw + +open scoped BigOperators + +variable {Ω : Type*} [Fintype Ω] + +theorem exists_weight_pos (μ : FiniteLaw Ω) : ∃ ω, 0 < μ.weight ω := by + classical + by_contra h + have hz (ω : Ω) : μ.weight ω = 0 := + le_antisymm (le_of_not_gt (fun hp => h ⟨ω, hp⟩)) (μ.nonneg ω) + have htotal : (∑ ω, μ.weight ω) = 0 := by simp [hz] + rw [μ.total] at htotal + exact one_ne_zero htotal + +theorem exists_le_expectation (μ : FiniteLaw Ω) (f : Ω → ℝ) : + ∃ ω, f ω ≤ μ.expectation f := by + classical + obtain ⟨ω₀, hω₀⟩ := μ.exists_weight_pos + by_contra h + have hlt (ω : Ω) : μ.expectation f < f ω := + lt_of_not_ge (fun hle => h ⟨ω, hle⟩) + have hsum : μ.expectation (fun _ => μ.expectation f) < μ.expectation f := by + apply Finset.sum_lt_sum + · intro ω _ + exact mul_le_mul_of_nonneg_left (hlt ω).le (μ.nonneg ω) + · exact ⟨ω₀, Finset.mem_univ ω₀, + mul_lt_mul_of_pos_left (hlt ω₀) hω₀⟩ + rw [expectation_const] at hsum + exact (lt_irrefl _) hsum + +theorem exists_of_prob_pos (μ : FiniteLaw Ω) {P : Ω → Prop} + (hP : 0 < μ.prob P) : ∃ ω, P ω := by + classical + by_contra h + have hz : μ.prob P = 0 := by + unfold prob + apply Finset.sum_eq_zero + intro ω _ + exact ite_eq_right (fun hp => h ⟨ω, hp⟩) + exact (ne_of_gt hP) hz + +end TalagrandDiscreteConvexity.FiniteLaw + +end OAI diff --git a/lean/OAI/Combinatorics/DiscreteConvexity/ProductProbability.lean b/lean/OAI/Combinatorics/DiscreteConvexity/ProductProbability.lean new file mode 100644 index 0000000000000000000000000000000000000000..26cd7d30418e1e476ed13ded56598f1ec04b910d --- /dev/null +++ b/lean/OAI/Combinatorics/DiscreteConvexity/ProductProbability.lean @@ -0,0 +1,142 @@ +import OAI.Combinatorics.DiscreteConvexity.FiniteProbability +import Mathlib.Algebra.BigOperators.Group.Finset.Piecewise +import Mathlib.Algebra.BigOperators.GroupWithZero.Finset + +namespace OAI + +/-! +# Marginals and pushforwards of finite product laws + +All identities below follow from the weights of the actual finite laws. +-/ + +open scoped BigOperators +noncomputable section +attribute [local instance] Classical.propDecidable + +namespace TalagrandDiscreteConvexity.FiniteLaw + +section ProductCoordinates + +variable {I : Type*} [Fintype I] [DecidableEq I] + {A : I → Type*} [∀ i, Fintype (A i)] + +/-- Product observables factor under the product of the given finite laws. -/ +theorem expectation_pi_product (μ : ∀ i, FiniteLaw (A i)) + (f : ∀ i, A i → ℝ) : + (pi μ).expectation (fun ω => ∏ i, f i (ω i)) = + ∏ i, (μ i).expectation (f i) := by + classical + simp only [expectation, pi_weight] + simp_rw [← Finset.prod_mul_distrib] + exact (Fintype.prod_sum (fun i a => (μ i).weight a * f i a)).symm + +/-- A coordinate of the product law has exactly its prescribed marginal. -/ +theorem expectation_pi_coordinate (μ : ∀ i, FiniteLaw (A i)) + (i : I) (f : A i → ℝ) : + (pi μ).expectation (fun ω => f (ω i)) = (μ i).expectation f := by + classical + let g : ∀ j, A j → ℝ := fun j a => if h : j = i then f (h ▸ a) else 1 + have hg (ω : ∀ j, A j) : (∏ j, g j (ω j)) = f (ω i) := by + dsimp only [g] + simp only [Fintype.prod_dite_eq'] + have he (j : I) : (μ j).expectation (g j) = + if h : j = i then (μ i).expectation f else 1 := by + by_cases h : j = i + · subst j + simp [g] + · simp [g, h, expectation_const] + calc + _ = (pi μ).expectation (fun ω => ∏ j, g j (ω j)) := by + congr 1 + funext ω + exact (hg ω).symm + _ = ∏ j, (μ j).expectation (g j) := expectation_pi_product μ g + _ = _ := by simp_rw [he]; simp + +/-- Events depending on one coordinate have their original probabilities. -/ +theorem prob_pi_coordinate (μ : ∀ i, FiniteLaw (A i)) + (i : I) (P : A i → Prop) : + (pi μ).prob (fun ω => P (ω i)) = (μ i).prob P := by + classical + rw [prob_eq_expectation, prob_eq_expectation] + exact expectation_pi_coordinate μ i (fun a => if P a then 1 else 0) + +/-- A cylinder event has the product of its coordinate probabilities. -/ +theorem prob_pi (μ : ∀ i, FiniteLaw (A i)) (P : ∀ i, A i → Prop) : + (pi μ).prob (fun ω => ∀ i, P i (ω i)) = ∏ i, (μ i).prob (P i) := by + classical + rw [prob_eq_expectation] + calc + _ = (pi μ).expectation (fun ω => ∏ i, if P i (ω i) then 1 else 0) := by + congr 1 + funext ω + symm + by_cases h : ∀ i, P i (ω i) + · simpa only [ite_eq_left h] using + (Fintype.prod_boole (p := fun i => P i (ω i)) (M₀ := ℝ)) + · simpa only [ite_eq_right h] using + (Fintype.prod_boole (p := fun i => P i (ω i)) (M₀ := ℝ)) + _ = ∏ i, (μ i).expectation (fun a => if P i a then 1 else 0) := + expectation_pi_product μ (fun i a => if P i a then 1 else 0) + _ = _ := by simp_rw [prob_eq_expectation] + +end ProductCoordinates + +variable {Ω Γ : Type*} [Fintype Ω] [Fintype Γ] + +/-- Rectangle events factor under the binary product law. -/ +theorem prob_prod (μ : FiniteLaw Ω) (ν : FiniteLaw Γ) + (P : Ω → Prop) (Q : Γ → Prop) : + (μ.prod ν).prob (fun z => P z.1 ∧ Q z.2) = μ.prob P * ν.prob Q := by + classical + simp only [prob, prod, Fintype.sum_prod_type] + calc + _ = ∑ ω, ∑ γ, + (if P ω then μ.weight ω else 0) * (if Q γ then ν.weight γ else 0) := by + apply Finset.sum_congr rfl + intro ω _ + apply Finset.sum_congr rfl + intro γ _ + by_cases hp : P ω <;> by_cases hq : Q γ <;> simp [hp, hq] + _ = _ := by + simp_rw [← Finset.mul_sum] + rw [← Finset.sum_mul] + +/-- Pushforward by summing the source weights in each fiber. -/ +def map (μ : FiniteLaw Ω) (f : Ω → Γ) : FiniteLaw Γ where + weight γ := ∑ ω, if f ω = γ then μ.weight ω else 0 + nonneg γ := Finset.sum_nonneg fun ω _ => by + split_ifs + · exact μ.nonneg ω + · exact le_rfl + total := by + rw [Finset.sum_comm] + simpa using μ.total + +@[simp] theorem map_weight (μ : FiniteLaw Ω) (f : Ω → Γ) (γ : Γ) : + (map μ f).weight γ = ∑ ω, if f ω = γ then μ.weight ω else 0 := rfl + +theorem map_weight_eq_prob (μ : FiniteLaw Ω) (f : Ω → Γ) (γ : Γ) : + (map μ f).weight γ = μ.prob (fun ω => f ω = γ) := rfl + +/-- Observables of a pushed law are evaluated along the defining map. -/ +theorem expectation_map (μ : FiniteLaw Ω) (f : Ω → Γ) (g : Γ → ℝ) : + (map μ f).expectation g = μ.expectation (fun ω => g (f ω)) := by + unfold expectation + simp only [map_weight, Finset.sum_mul] + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro ω _ + simp [ite_mul] + +/-- The probability of an event under a pushed law is its preimage probability. -/ +theorem prob_map (μ : FiniteLaw Ω) (f : Ω → Γ) (P : Γ → Prop) : + (map μ f).prob P = μ.prob (fun ω => P (f ω)) := by + rw [prob_eq_expectation, expectation_map, prob_eq_expectation] + +end TalagrandDiscreteConvexity.FiniteLaw + +end + +end OAI diff --git a/lean/OAI/Combinatorics/DiscreteConvexity/SignedArrays.lean b/lean/OAI/Combinatorics/DiscreteConvexity/SignedArrays.lean new file mode 100644 index 0000000000000000000000000000000000000000..fedae2336e388fb6465baddce8bcc9de1809c952 --- /dev/null +++ b/lean/OAI/Combinatorics/DiscreteConvexity/SignedArrays.lean @@ -0,0 +1,143 @@ +import OAI.Combinatorics.DiscreteConvexity.Basic +import OAI.Combinatorics.DiscreteConvexity.FourierWeights +import OAI.Combinatorics.DiscreteConvexity.ColumnExpansion +import OAI.Combinatorics.DiscreteConvexity.ExceptionalWeightBound + +namespace OAI + +/-! +# Signed arrays force weight on every exceptional set + +The arrays have one common set of rows. Each column in `S` receives the +Bernoulli product mass minus the product of the alternating corrections. +All-zero columns in `S` have zero signed mass. This gives pointwise vanishing +for exceptional sets, without any nonnegativity assumption on these masses. +Expanding the column products and summing independently over the rows gives +the exact signed coefficient identity. +-/ + +noncomputable section + +open scoped BigOperators + +namespace TalagrandDiscreteConvexity + +variable {V : Type*} [Fintype V] [DecidableEq V] + +def signedArrayMass (q : ℝ) {k : ℕ} (S : Finset V) + (X : Fin k → V → Bool) : ℝ := + ∏ i, ((∏ j, bitWeight q (X j i)) - + if i ∈ S then ∏ j, correction q (X j i) else 0) + +/-- Choosing the correction columns factors into the same coefficient kernel +in every row. -/ +theorem columnKernel_eq_rowKernel (q : ℝ) {k : ℕ} (U : Finset V) + (X : Fin k → V → Bool) : + (∏ i, if i ∈ U then ∏ j, correction q (X j i) + else ∏ j, bitWeight q (X j i)) = + ∏ j, rowKernel q U (X j) := by + unfold rowKernel + rw [Finset.prod_comm] + apply Finset.prod_congr rfl + intro i _ + by_cases hi : i ∈ U <;> simp only [hi, ite_true, ite_false] + +/-- The finite product expansion, followed by exact row factorization. +It is valid for every real q and every real-valued row function. -/ +theorem signed_array_identity (q : ℝ) (k : ℕ) + (f : (V → Bool) → ℝ) (S : Finset V) : + (∑ X : Fin k → V → Bool, (∏ j, f (X j)) * signedArrayMass q S X) = + ∑ U ∈ S.powerset, (-1 : ℝ) ^ U.card * b q f U ^ k := by + classical + calc + (∑ X : Fin k → V → Bool, (∏ j, f (X j)) * signedArrayMass q S X) = + ∑ X : Fin k → V → Bool, ∑ U ∈ S.powerset, + (-1 : ℝ) ^ U.card * ∏ j, (f (X j) * rowKernel q U (X j)) := by + apply Finset.sum_congr rfl + intro X _ + rw [signedArrayMass, prod_sub_ite_eq_sum_powerset, Finset.mul_sum] + apply Finset.sum_congr rfl + intro U _ + rw [columnKernel_eq_rowKernel, Finset.prod_mul_distrib] + exact mul_left_comm _ _ _ + _ = ∑ U ∈ S.powerset, (-1 : ℝ) ^ U.card * + ∑ X : Fin k → V → Bool, ∏ j, (f (X j) * rowKernel q U (X j)) := by + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro U _ + rw [Finset.mul_sum] + _ = ∑ U ∈ S.powerset, (-1 : ℝ) ^ U.card * b q f U ^ k := by + apply Finset.sum_congr rfl + intro U _ + congr 1 + rw [← Fintype.prod_sum (fun (_ : Fin k) (x : V → Bool) => + f x * rowKernel q U x)] + simp only [b, Finset.prod_const, Finset.card_univ, Fintype.card_fin] + +/-- An all-zero column in S cancels exactly; the masses may be signed. -/ +theorem signedArrayMass_eq_zero_of_zero_column (q : ℝ) {k : ℕ} + {S : Finset V} {X : Fin k → V → Bool} {i : V} + (hi : i ∈ S) (hzero : ∀ j, X j i = false) : + signedArrayMass q S X = 0 := by + apply Finset.prod_eq_zero (Finset.mem_univ i) + simp [hi, hzero, bitWeight, correction] + +/-- On an exceptional set, either one row leaves the family or some column +of S is all zero. In either case the signed summand vanishes. -/ +theorem exceptional_signed_summand_eq_zero (q : ℝ) {k : ℕ} + {D : Family V} {S : Finset V} (hS : S ∈ exceptional k D) + (X : Fin k → V → Bool) : + (∏ j, familyIndicator D (X j)) * signedArrayMass q S X = 0 := by + classical + by_cases hrows : ∀ j, cubeSet (X j) ∈ D + · obtain ⟨i, hi, hmissing⟩ := + exceptional_tuple_misses hS (fun j => cubeSet (X j)) hrows + have hzero (j : Fin k) : X j i = false := by + cases hbit : X j i with + | false => rfl + | true => + exact False.elim (hmissing j (by simp [cubeSet, hbit])) + rw [signedArrayMass_eq_zero_of_zero_column q hi hzero, mul_zero] + · obtain ⟨j, hj⟩ := not_forall.mp hrows + have hprod : (∏ j, familyIndicator D (X j)) = 0 := by + apply Finset.prod_eq_zero (Finset.mem_univ j) + simp only [familyIndicator, ite_eq_right hj] + rw [hprod, zero_mul] + +/-- The exact vanishing signed expansion on an exceptional set. -/ +theorem exceptional_signed_sum_eq_zero (q : ℝ) {k : ℕ} + {D : Family V} {S : Finset V} (hS : S ∈ exceptional k D) : + (∑ U ∈ S.powerset, (-1 : ℝ) ^ U.card * b q (familyIndicator D) U ^ k) = 0 := by + rw [← signed_array_identity] + apply Finset.sum_eq_zero + intro X _ + exact exceptional_signed_summand_eq_zero q hS X + +theorem exceptional_signed_identity (q : ℝ) + {D : Family V} {S : Finset V} (hS : S ∈ exceptional 32 D) : + 0 = ∑ U ∈ S.powerset, (-1 : ℝ) ^ U.card * b q (familyIndicator D) U ^ 32 := + (exceptional_signed_sum_eq_zero q hS).symm + +/-- The actual exceptional-weight bound, at the original family density. -/ +theorem exceptional_weight_lower_bound (q : ℝ) + {D : Family V} (hD : (1 / 2 : ℝ) ≤ familyMeasure q D) + {S : Finset V} (hS : S ∈ exceptional 32 D) : + (1 / 2 : ℝ) ^ 32 ≤ + ∑ U ∈ S.powerset.erase ∅, w q (familyIndicator D) U ^ 16 := by + apply exceptional_lower_bound_of_signed_sum S (b q (familyIndicator D)) + (exceptional_signed_sum_eq_zero q hS) + simpa only [b_empty, cubeExpectation_familyIndicator] using hD + +/-- The filter form used to combine the exceptional bound with weight bins. -/ +theorem exceptional_weight_lower_bound_filter (q : ℝ) + {D : Family V} (hD : (1 / 2 : ℝ) ≤ familyMeasure q D) + {S : Finset V} (hS : S ∈ exceptional 32 D) : + (1 / 2 : ℝ) ^ 32 ≤ + ∑ U ∈ S.powerset.filter (fun U => U ≠ ∅), w q (familyIndicator D) U ^ 16 := by + simpa only [Finset.filter_ne'] using exceptional_weight_lower_bound q hD hS + +end TalagrandDiscreteConvexity + +end + +end OAI diff --git a/lean/OAI/Combinatorics/DiscreteConvexity/UnionBound.lean b/lean/OAI/Combinatorics/DiscreteConvexity/UnionBound.lean new file mode 100644 index 0000000000000000000000000000000000000000..4601bc6dfc0cccbc3e210bad03eb99e717eb2078 --- /dev/null +++ b/lean/OAI/Combinatorics/DiscreteConvexity/UnionBound.lean @@ -0,0 +1,66 @@ +import OAI.Combinatorics.DiscreteConvexity.ProbabilisticExistence + +namespace OAI + +open scoped BigOperators + +namespace TalagrandDiscreteConvexity.FiniteLaw + +variable {Ω ι : Type*} [Fintype Ω] [Fintype ι] + +/-- The indexed union bound uses no independence among the events. -/ +theorem prob_exists_le (μ : FiniteLaw Ω) (P : ι → Ω → Prop) : + μ.prob (fun ω => ∃ i, P i ω) ≤ ∑ i, μ.prob (P i) := by + classical + calc + μ.prob (fun ω => ∃ i, P i ω) ≤ + μ.expectation (fun ω => ∑ i, if P i ω then (1 : ℝ) else 0) := by + apply μ.prob_le_expectation + · intro ω + exact Finset.sum_nonneg fun i _ => by + by_cases h : P i ω <;> simp [h] + · intro ω hω + obtain ⟨i, hi⟩ := hω + have hsum : (if P i ω then (1 : ℝ) else 0) ≤ + ∑ j, if P j ω then (1 : ℝ) else 0 := by + apply Finset.single_le_sum (a := i) + (f := fun j => if P j ω then (1 : ℝ) else 0) + · intro j _ + by_cases h : P j ω <;> simp [h] + · exact Finset.mem_univ i + simpa only [ite_eq_left hi] using hsum + _ = ∑ i, μ.prob (P i) := by + rw [μ.expectation_sum] + apply Finset.sum_congr rfl + intro i _ + exact (μ.prob_eq_expectation (P i)).symm + +/-- Simultaneous success is bounded using only the individual marginals. -/ +theorem prob_forall_ge (μ : FiniteLaw Ω) (P : ι → Ω → Prop) : + 1 - ∑ i, (1 - μ.prob (P i)) ≤ μ.prob (fun ω => ∀ i, P i ω) := by + classical + have hbad := prob_exists_le μ (fun i ω => ¬ P i ω) + have hcompl : μ.prob (fun ω => ¬ ∀ i, P i ω) ≤ + ∑ i, μ.prob (fun ω => ¬ P i ω) := by + simpa only [not_forall] using hbad + rw [μ.prob_compl] at hcompl + simp_rw [μ.prob_compl] at hcompl + linarith + +theorem prob_forall_ge_of_const (μ : FiniteLaw Ω) (P : ι → Ω → Prop) + (a : ℝ) (hmarginal : ∀ i, μ.prob (P i) = a) : + 1 - (Fintype.card ι : ℝ) * (1 - a) ≤ μ.prob (fun ω => ∀ i, P i ω) := by + have h := prob_forall_ge μ P + simpa only [hmarginal, Finset.sum_const, Finset.card_univ, nsmul_eq_mul] using h + +theorem exists_forall_of_const (μ : FiniteLaw Ω) (P : ι → Ω → Prop) + (a : ℝ) (hmarginal : ∀ i, μ.prob (P i) = a) + (hbudget : (Fintype.card ι : ℝ) * (1 - a) < 1) : + ∃ ω, ∀ i, P i ω := by + apply exists_of_prob_pos μ (P := fun ω => ∀ i, P i ω) + have h := prob_forall_ge_of_const μ P a hmarginal + linarith + +end TalagrandDiscreteConvexity.FiniteLaw + +end OAI diff --git a/lean/OAI/Combinatorics/DiscreteConvexity/UnionTuples.lean b/lean/OAI/Combinatorics/DiscreteConvexity/UnionTuples.lean new file mode 100644 index 0000000000000000000000000000000000000000..faf3ef6e491cbe0dfcb55da4030e68dc9d96275f --- /dev/null +++ b/lean/OAI/Combinatorics/DiscreteConvexity/UnionTuples.lean @@ -0,0 +1,125 @@ +import OAI.Combinatorics.DiscreteConvexity.Basic +import Mathlib.Logic.Equiv.Fin.Basic + +namespace OAI + +/-! +# Grouping and repeating union tuples + +Grouping `a * b` entries into `a` rows of length `b` preserves exactly the +possible unions. Repetition is allowed throughout, as in the definition of +the exceptional family. No positivity assumption is needed for grouping. +-/ + +namespace TalagrandDiscreteConvexity + +variable {α : Type*} [Fintype α] [DecidableEq α] + +/-- Flatten a rectangular array using the standard finite product equivalence. -/ +def flattenTuple {a b : ℕ} (f : Fin a → Fin b → Finset α) : + Fin (a * b) → Finset α := + fun t => f (finProdFinEquiv.symm t).1 (finProdFinEquiv.symm t).2 + +omit [Fintype α] in +theorem unionTuple_flatten {a b : ℕ} (f : Fin a → Fin b → Finset α) : + unionTuple (flattenTuple f) = unionTuple (fun i => unionTuple (f i)) := by + ext x + simp only [mem_unionTuple] + constructor + · rintro ⟨t, ht⟩ + exact ⟨(finProdFinEquiv.symm t).1, (finProdFinEquiv.symm t).2, ht⟩ + · rintro ⟨i, j, hij⟩ + refine ⟨finProdFinEquiv (i, j), ?_⟩ + simpa only [flattenTuple, Equiv.symm_apply_apply] using hij + +omit [Fintype α] in +theorem unionTuple_rows {a b : ℕ} (f : Fin (a * b) → Finset α) : + unionTuple (fun i : Fin a => unionTuple (fun j : Fin b => f (finProdFinEquiv (i, j)))) = + unionTuple f := by + rw [← unionTuple_flatten] + apply congrArg (fun g : Fin (a * b) → Finset α => unionTuple g) + funext t + exact congrArg f (finProdFinEquiv.apply_symm_apply t) + +/-- Iterated unions are exactly unions of the product number of entries. -/ +theorem unionFamily_mul (a b : ℕ) (D : Family α) : + unionFamily a (unionFamily b D) = unionFamily (a * b) D := by + classical + ext S + constructor + · intro hS + obtain ⟨f, hf, hfS⟩ := mem_unionFamily.mp hS + have hrows : ∀ i : Fin a, ∃ g : Fin b → Finset α, + (∀ j, g j ∈ D) ∧ unionTuple g = f i := + fun i => mem_unionFamily.mp (hf i) + choose g hg hgUnion using hrows + apply mem_unionFamily.mpr + refine ⟨flattenTuple g, ?_, ?_⟩ + · intro t + exact hg (finProdFinEquiv.symm t).1 (finProdFinEquiv.symm t).2 + · rw [unionTuple_flatten] + have hfun : (fun i => unionTuple (g i)) = f := funext hgUnion + rw [hfun] + exact hfS + · intro hS + obtain ⟨f, hf, hfS⟩ := mem_unionFamily.mp hS + apply mem_unionFamily.mpr + refine ⟨fun i : Fin a => unionTuple (fun j : Fin b => f (finProdFinEquiv (i, j))), + ?_, ?_⟩ + · intro i + exact mem_unionFamily.mpr + ⟨fun j => f (finProdFinEquiv (i, j)), fun j => hf _, rfl⟩ + · rw [unionTuple_rows] + exact hfS + +/-- Grouping tuples preserves failure of containment in every possible union. -/ +theorem exceptional_unionFamily (a b : ℕ) (D : Family α) : + exceptional a (unionFamily b D) = exceptional (a * b) D := by + ext S + simp only [mem_exceptional_iff_unionFamily, unionFamily_mul] + +/-- Repeat the same row tuple `a` times. -/ +def repeatTuple (a : ℕ) {b : ℕ} (f : Fin b → Finset α) : + Fin (a * b) → Finset α := + flattenTuple (fun _ : Fin a => f) + +omit [Fintype α] [DecidableEq α] in +theorem repeatTuple_mem {a b : ℕ} {D : Family α} (f : Fin b → Finset α) + (hf : ∀ j, f j ∈ D) (t : Fin (a * b)) : repeatTuple a f t ∈ D := + hf (finProdFinEquiv.symm t).2 + +omit [Fintype α] in +theorem unionTuple_repeat {a b : ℕ} (ha : 0 < a) (f : Fin b → Finset α) : + unionTuple (repeatTuple a f) = unionTuple f := by + rw [repeatTuple, unionTuple_flatten] + ext x + simp only [mem_unionTuple] + constructor + · rintro ⟨_, j, hj⟩ + exact ⟨j, hj⟩ + · rintro ⟨j, hj⟩ + exact ⟨⟨0, ha⟩, j, hj⟩ + +theorem exists_unionTuple_mul_eq_univ {a b : ℕ} (ha : 0 < a) {D : Family α} + (f : Fin b → Finset α) (hf : ∀ j, f j ∈ D) + (hfull : unionTuple f = Finset.univ) : + ∃ g : Fin (a * b) → Finset α, (∀ j, g j ∈ D) ∧ unionTuple g = Finset.univ := by + refine ⟨repeatTuple a f, repeatTuple_mem f hf, ?_⟩ + rw [unionTuple_repeat ha, hfull] + +theorem exceptional_mul_eq_empty_of_full_union {a b : ℕ} (ha : 0 < a) {D : Family α} + (f : Fin b → Finset α) (hf : ∀ j, f j ∈ D) + (hfull : unionTuple f = Finset.univ) : exceptional (a * b) D = ∅ := by + obtain ⟨g, hg, hgfull⟩ := exists_unionTuple_mul_eq_univ ha f hf hfull + exact exceptional_eq_empty_of_full_union g hg hgfull + +/-- The repetition used in the full-union branch of the density argument. -/ +theorem exists_unionTuple_thirtytwo_mul_eq_univ {L : ℕ} {D : Family α} + (f : Fin L → Finset α) (hf : ∀ j, f j ∈ D) + (hfull : unionTuple f = Finset.univ) : + ∃ g : Fin (32 * L) → Finset α, (∀ j, g j ∈ D) ∧ unionTuple g = Finset.univ := + exists_unionTuple_mul_eq_univ (by decide : 0 < 32) f hf hfull + +end TalagrandDiscreteConvexity + +end OAI diff --git a/lean/OAI/Combinatorics/DiscreteConvexity/WeightedCover.lean b/lean/OAI/Combinatorics/DiscreteConvexity/WeightedCover.lean new file mode 100644 index 0000000000000000000000000000000000000000..3fe75e70e5811a0fdcc3faf4a46f5b9004b75389 --- /dev/null +++ b/lean/OAI/Combinatorics/DiscreteConvexity/WeightedCover.lean @@ -0,0 +1,94 @@ +import OAI.Combinatorics.DiscreteConvexity.Bins +import OAI.Combinatorics.DiscreteConvexity.ElementaryCovering +import Lean.Elab.Tactic.Omega +import Mathlib.Tactic.Linarith + +namespace OAI + +/-! +# From actual dyadic weights to a containment cover + +The only inputs are the two weight inequalities. All bins, their finite +index set, their covers, and the final union are constructed in the proof. +-/ + +open scoped BigOperators + +namespace TalagrandDiscreteConvexity + +variable {α : Type*} [Fintype α] [DecidableEq α] + +theorem weights_small {q : ℝ} (hq0 : 0 < q) (hq1 : q < 1) + (A : Family α) (W : Finset α → ℝ) (hW : ∀ U, 0 ≤ W U) + (hglobal : (∑ U : Finset α, q ^ U.card * W U) ≤ 1) + (hlower : ∀ S ∈ A, + (1 / 2 : ℝ) ^ 32 ≤ ∑ U ∈ S.powerset.erase ∅, (W U) ^ 16) : + Small (q / (2 : ℝ) ^ 70) A := by + classical + let ρ : ℝ := q / (2 : ℝ) ^ 70 + let B := occupiedWeightBins W + have hρ0 : 0 < ρ := div_pos hq0 (pow_pos (by norm_num) _) + have hρq : ρ ≤ q := div_le_self hq0.le (one_le_pow₀ (by norm_num)) + have hρ1 : ρ < 1 := hρq.trans_lt hq1 + have hB : ∀ b ∈ B, 1 ≤ b.1 ∧ 64 * b.1 ≤ b.2 := + fun _ hb => occupiedWeightBins_bounds hb + have each : ∀ b : ℕ × ℕ, ∃ G : Family α, b ∈ B → + Covers G (Covering.denseFamily (weightBin W b) (2 ^ (12 * b.2))) ∧ + cost ρ G ≤ 3 * (1 / 2 : ℝ) ^ b.2 := by + intro b + by_cases hb : b ∈ B + · have hbnd := hB b hb + obtain ⟨G, hcover, hcost⟩ := Covering.elementary_covering + (weightBin W b) ρ b.1 b.2 hρ0 hρ1 + (fun U hU => weightBin_card hU) hbnd.1 + (by omega) (by omega) (weightBin_cost_bound hq0 hW hglobal b) + refine ⟨G, fun _ => ⟨hcover, ?_⟩⟩ + simpa only [one_div, inv_pow] using hcost + · exact ⟨∅, fun h => False.elim (hb h)⟩ + let G : (ℕ × ℕ) → Family α := fun b => Classical.choose (each b) + have hG : ∀ b ∈ B, + Covers (G b) (Covering.denseFamily (weightBin W b) (2 ^ (12 * b.2))) ∧ + cost ρ (G b) ≤ 3 * (1 / 2 : ℝ) ^ b.2 := + fun b hb => Classical.choose_spec (each b) hb + let C : Family α := largeWeightFamily W ∪ B.biUnion G + have hcost : cost ρ C ≤ 1 / 2 := by + have hsum : (∑ b ∈ B, cost ρ (G b)) < 1 / 4 := + (Finset.sum_le_sum (fun b hb => (hG b hb).2)).trans_lt + (finite_bin_cost_lt_quarter B hB) + have hlarge : cost ρ (largeWeightFamily W) ≤ 1 / 64 := + largeWeightFamily_cost_le hq0.le hW hglobal + have htotal := (cost_union_le hρ0.le (largeWeightFamily W) (B.biUnion G)).trans + (add_le_add le_rfl (cost_biUnion_le hρ0.le B G)) + change cost ρ (largeWeightFamily W ∪ B.biUnion G) ≤ 1 / 2 + linarith + refine ⟨C, ?_, hcost⟩ + intro S hS + by_contra hcovered + have hnone : ∀ I ∈ C, ¬ I ⊆ S := by + intro I hI hIS + exact hcovered ⟨I, hI, hIS⟩ + have hlarge : ∀ U ∈ largeWeightFamily W, ¬ U ⊆ S := by + intro U hU + exact hnone U (Finset.mem_union_left _ hU) + have hcount : ∀ b ∈ B, + ((weightBin W b).filter (fun U => U ⊆ S)).card ≤ 2 ^ (12 * b.2) := by + intro b hb + have hnot : ¬ S ∈ Covering.denseFamily (weightBin W b) (2 ^ (12 * b.2)) := by + intro hdense + obtain ⟨I, hI, hIS⟩ := (hG b hb).1 S hdense + exact hnone I (Finset.mem_union_right _ (Finset.mem_biUnion.mpr ⟨b, hb, hI⟩)) hIS + have hlt : ((weightBin W b).filter (fun U => U ⊆ S)).card < 2 ^ (12 * b.2) := + lt_of_not_ge (fun h => hnot (Covering.mem_denseFamily.mpr h)) + exact hlt.le + have hupper : (∑ U ∈ S.powerset.erase ∅, (W U) ^ 16) < (1 / 2 : ℝ) ^ 32 := by + calc + _ ≤ ∑ b ∈ B, ∑ U ∈ (weightBin W b).filter (fun U => U ⊆ S), (W U) ^ 16 := + subset_power_sum_le_bins hW S hlarge + _ ≤ ∑ b ∈ B, (1 / 2 : ℝ) ^ (4 * b.2) := + Finset.sum_le_sum (fun b hb => weightBin_power_sum_le hW S b (hcount b hb)) + _ < (1 / 2 : ℝ) ^ 32 := finite_bin_power_lt_threshold B hB + exact (not_lt_of_ge (hlower S hS)) hupper + +end TalagrandDiscreteConvexity + +end OAI diff --git a/lean/OAI/Combinatorics/Distances/PolynomialIsolation.lean b/lean/OAI/Combinatorics/Distances/PolynomialIsolation.lean new file mode 100644 index 0000000000000000000000000000000000000000..180c7a8dac5ad9a3f62fc28eb14c805dc28f2952 --- /dev/null +++ b/lean/OAI/Combinatorics/Distances/PolynomialIsolation.lean @@ -0,0 +1,392 @@ +import Mathlib + +namespace OAI + +/-! Polynomial separators, finite-point isolation and elementary bounds for distinct Euclidean distances. -/ + +noncomputable section + +open scoped BigOperators Topology + +namespace ErdosDistinctDistances + +abbrev Point (d : ℕ) := EuclideanSpace ℝ (Fin d) + +def distances {d : ℕ} (P : Finset (Point d)) : Finset ℝ := by + classical + exact P.offDiag.image (fun pq => dist pq.1 pq.2) + +variable {d : ℕ} {P Q : Finset (Point d)} + +@[simp] theorem mem_distances {r : ℝ} : + r ∈ distances P ↔ ∃ p ∈ P, ∃ q ∈ P, p ≠ q ∧ dist p q = r := by + classical + simp only [distances, Finset.mem_image, Finset.mem_offDiag] + constructor + · rintro ⟨⟨p, q⟩, ⟨hp, hq, hpq⟩, hr⟩ + exact ⟨p, hp, q, hq, hpq, hr⟩ + · rintro ⟨p, hp, q, hq, hpq, hr⟩ + exact ⟨(p, q), ⟨hp, hq, hpq⟩, hr⟩ + +theorem coe_distances (P : Finset (Point d)) : + (distances P : Set ℝ) = + {r | ∃ p ∈ P, ∃ q ∈ P, p ≠ q ∧ ‖p - q‖ = r} := by + ext r + simp [mem_distances, dist_eq_norm] + +theorem distance_pos {r : ℝ} (hr : r ∈ distances P) : 0 < r := by + obtain ⟨p, _, q, _, hpq, rfl⟩ := mem_distances.mp hr + exact dist_pos.mpr hpq + +@[simp] theorem zero_not_mem_distances (P : Finset (Point d)) : + (0 : ℝ) ∉ distances P := by + intro h + exact (lt_irrefl (0 : ℝ)) (distance_pos h) + +theorem distances_mono (h : P ⊆ Q) : distances P ⊆ distances Q := by + intro r hr + obtain ⟨p, hp, q, hq, hpq, rfl⟩ := mem_distances.mp hr + exact mem_distances.mpr ⟨p, h hp, q, h hq, hpq, rfl⟩ + +theorem distances_nonempty (hP : 2 ≤ P.card) : (distances P).Nonempty := by + classical + obtain ⟨p, hp, q, hq, hpq⟩ := Finset.one_lt_card.mp hP + exact ⟨dist p q, mem_distances.mpr ⟨p, hp, q, hq, hpq, rfl⟩⟩ + +theorem one_le_card_distances (hP : 2 ≤ P.card) : 1 ≤ (distances P).card := + (distances_nonempty hP).card_pos + +theorem failure_gives_regime (hd : 3 ≤ d) + (hfail : ¬ ∃ c : ℝ, 0 < c ∧ + ∀ P : Finset (Point d), 2 ≤ P.card → + c * (P.card : ℝ) ^ (2 / (d : ℝ)) ≤ (distances P).card) : + ∃ P : ℕ → Finset (Point d), + (∀ k, 2 ≤ (P k).card) ∧ + Filter.Tendsto (fun k => (P k).card) Filter.atTop Filter.atTop ∧ + Filter.Tendsto + (fun k => (1 + ((distances (P k)).card : ℝ)) / + ((P k).card : ℝ) ^ (2 / (d : ℝ))) + Filter.atTop (𝓝 0) := by + classical + have hf : ∀ c : ℝ, 0 < c → ∃ P : Finset (Point d), + 2 ≤ P.card ∧ (distances P).card < c * (P.card : ℝ) ^ (2 / (d : ℝ)) := by + push Not at hfail + exact hfail + have hchoice : ∀ k : ℕ, ∃ P : Finset (Point d), 2 ≤ P.card ∧ + (distances P).card < (1 / ((k : ℝ) + 1)) * + (P.card : ℝ) ^ (2 / (d : ℝ)) := by + intro k + exact hf _ (by positivity) + choose P hP hm using hchoice + have hn (k : ℕ) : (2 : ℝ) ≤ (P k).card := by exact_mod_cast hP k + have hA (k : ℕ) : 0 < ((P k).card : ℝ) ^ (2 / (d : ℝ)) := + Real.rpow_pos_of_pos (by linarith [hn k]) _ + have hM (k : ℕ) : (1 : ℝ) ≤ (distances (P k)).card := by + exact_mod_cast one_le_card_distances (hP k) + have he : 2 / (d : ℝ) ≤ 1 := by + have hd' : (3 : ℝ) ≤ d := by exact_mod_cast hd + apply (div_le_one (by linarith : (0 : ℝ) < d)).mpr + linarith + have hkA (k : ℕ) : (k : ℝ) + 1 < ((P k).card : ℝ) ^ (2 / (d : ℝ)) := by + have h : (1 : ℝ) < ((P k).card : ℝ) ^ (2 / (d : ℝ)) / ((k : ℝ) + 1) := by + simpa [div_eq_mul_inv, mul_comm] using lt_of_le_of_lt (hM k) (hm k) + simpa using (lt_div_iff₀ (by positivity : (0 : ℝ) < (k : ℝ) + 1)).mp h + have hkn (k : ℕ) : k ≤ (P k).card := by + have hpow := Real.rpow_le_self_of_one_le (by linarith [hn k] : (1 : ℝ) ≤ (P k).card) he + have : (k : ℝ) ≤ (P k).card := by linarith [hkA k] + exact_mod_cast this + refine ⟨P, hP, Filter.tendsto_atTop_mono hkn Filter.tendsto_id, ?_⟩ + apply squeeze_zero + · intro k + exact div_nonneg (by positivity) (hA k).le + · intro k + apply le_of_lt + apply (div_lt_iff₀ (hA k)).mpr + calc + 1 + ((distances (P k)).card : ℝ) ≤ 2 * (distances (P k)).card := by + linarith [hM k] + _ < 2 * ((1 / ((k : ℝ) + 1)) * ((P k).card : ℝ) ^ (2 / (d : ℝ))) := + mul_lt_mul_of_pos_left (hm k) (by norm_num) + _ = (2 / ((k : ℝ) + 1)) * ((P k).card : ℝ) ^ (2 / (d : ℝ)) := by ring + · convert tendsto_one_div_add_atTop_nhds_zero_nat.const_mul (2 : ℝ) using 1 <;> + simp [div_eq_mul_inv] + +theorem regime_precludes_bound (P : ℕ → Finset (Point d)) + (hP : ∀ k, 2 ≤ (P k).card) + (hlim : Filter.Tendsto + (fun k => (1 + ((distances (P k)).card : ℝ)) / + ((P k).card : ℝ) ^ (2 / (d : ℝ))) Filter.atTop (𝓝 0)) : + ¬ ∃ c : ℝ, 0 < c ∧ + ∀ Q : Finset (Point d), 2 ≤ Q.card → + c * (Q.card : ℝ) ^ (2 / (d : ℝ)) ≤ (distances Q).card := by + rintro ⟨c, hc, hb⟩ + have hcle : c ≤ 0 := ge_of_tendsto' hlim fun k => by + have hn : (0 : ℝ) < (P k).card := by + exact_mod_cast lt_of_lt_of_le (by decide : 0 < 2) (hP k) + apply (le_div_iff₀ (Real.rpow_pos_of_pos hn _)).mpr + linarith [hb (P k) (hP k)] + exact (not_le_of_gt hc) hcle + +def complexPoint (p : Point d) : Fin d → ℂ := fun i => (p i : ℂ) + +def squaredDistancePolynomial (p : Point d) : MvPolynomial (Fin d) ℂ := + ∑ i : Fin d, (MvPolynomial.X i - MvPolynomial.C ((p i : ℝ) : ℂ)) ^ 2 + +theorem eval_squaredDistancePolynomial (p q : Point d) : + MvPolynomial.eval (complexPoint q) (squaredDistancePolynomial p) = + (dist p q : ℂ) ^ 2 := by + simp only [squaredDistancePolynomial, map_sum, map_pow, map_sub, + MvPolynomial.eval_X, MvPolynomial.eval_C, complexPoint] + norm_cast + simp [EuclideanSpace.dist_sq_eq, Real.dist_eq, sub_sq_comm] + +theorem degree_squaredDistancePolynomial (p : Point d) : + (squaredDistancePolynomial p).totalDegree ≤ 2 := by + apply MvPolynomial.totalDegree_finsetSum_le + intro i _ + have h : (MvPolynomial.X i - MvPolynomial.C ((p i : ℝ) : ℂ)).totalDegree ≤ 1 := by + simpa using MvPolynomial.totalDegree_sub + (MvPolynomial.X i) (MvPolynomial.C ((p i : ℝ) : ℂ)) + calc + _ ≤ 2 * (MvPolynomial.X i - MvPolynomial.C ((p i : ℝ) : ℂ)).totalDegree := + MvPolynomial.totalDegree_pow _ _ + _ ≤ 2 * 1 := Nat.mul_le_mul_left _ h + _ = 2 := rfl + +def separatorFactor (p : Point d) (r : ℝ) : MvPolynomial (Fin d) ℂ := + (squaredDistancePolynomial p - MvPolynomial.C ((r : ℂ) ^ 2)) * + MvPolynomial.C ((-((r : ℂ) ^ 2))⁻¹) + +def physicalSeparator (P : Finset (Point d)) (p : Point d) : MvPolynomial (Fin d) ℂ := + ∏ r ∈ distances P, separatorFactor p r + +theorem degree_separatorFactor (p : Point d) (r : ℝ) : + (separatorFactor p r).totalDegree ≤ 2 := by + have h := MvPolynomial.totalDegree_sub (squaredDistancePolynomial p) + (MvPolynomial.C ((r : ℂ) ^ 2)) + simp only [MvPolynomial.totalDegree_C, max_eq_left (Nat.zero_le _)] at h + calc + _ ≤ (squaredDistancePolynomial p - MvPolynomial.C ((r : ℂ) ^ 2)).totalDegree + + (MvPolynomial.C ((-((r : ℂ) ^ 2))⁻¹)).totalDegree := + MvPolynomial.totalDegree_mul _ _ + _ = (squaredDistancePolynomial p - MvPolynomial.C ((r : ℂ) ^ 2)).totalDegree := by + simp + _ ≤ (squaredDistancePolynomial p).totalDegree := h + _ ≤ 2 := degree_squaredDistancePolynomial p + +theorem degree_physicalSeparator (P : Finset (Point d)) (p : Point d) : + (physicalSeparator P p).totalDegree ≤ 2 * (distances P).card := by + calc + _ ≤ ∑ r ∈ distances P, (separatorFactor p r).totalDegree := + MvPolynomial.totalDegree_finsetProd _ _ + _ ≤ ∑ _ ∈ distances P, 2 := Finset.sum_le_sum fun r _ => degree_separatorFactor p r + _ = 2 * (distances P).card := by simp [Nat.mul_comm] + +theorem eval_physicalSeparator_self (P : Finset (Point d)) (p : Point d) : + MvPolynomial.eval (complexPoint p) (physicalSeparator P p) = 1 := by + classical + rw [physicalSeparator, map_prod] + apply Finset.prod_eq_one + intro r hr + have hr0 : (r : ℂ) ≠ 0 := by exact_mod_cast ne_of_gt (distance_pos hr) + simp [separatorFactor, eval_squaredDistancePolynomial, hr0] + +theorem eval_physicalSeparator_ne {p q : Point d} (hp : p ∈ P) (hq : q ∈ P) (hpq : p ≠ q) : + MvPolynomial.eval (complexPoint q) (physicalSeparator P p) = 0 := by + classical + rw [physicalSeparator, map_prod] + apply Finset.prod_eq_zero (mem_distances.mpr ⟨p, hp, q, hq, hpq, rfl⟩) + simp [separatorFactor, eval_squaredDistancePolynomial] + +theorem eval_physicalSeparator {p q : Point d} (hp : p ∈ P) (hq : q ∈ P) : + MvPolynomial.eval (complexPoint q) (physicalSeparator P p) = if p = q then 1 else 0 := by + classical + by_cases h : p = q + · subst q + simp [eval_physicalSeparator_self] + · simp [h, eval_physicalSeparator_ne hp hq h] + +def isolationPolynomials (P : Finset (Point d)) : Finset (MvPolynomial (Fin d) ℂ) := by + classical + exact insert (1 - ∑ p ∈ P, physicalSeparator P p) + ((P.product Finset.univ).image (fun pj => + (MvPolynomial.X pj.2 - MvPolynomial.C (complexPoint pj.1 pj.2)) * + physicalSeparator P pj.1)) + +theorem degree_isolationPolynomials {f : MvPolynomial (Fin d) ℂ} + (hf : f ∈ isolationPolynomials P) : + f.totalDegree ≤ 2 * (distances P).card + 1 := by + classical + rcases Finset.mem_insert.mp hf with rfl | hf + · have hs : (∑ p ∈ P, physicalSeparator P p).totalDegree ≤ 2 * (distances P).card := + MvPolynomial.totalDegree_finsetSum_le fun p _ => degree_physicalSeparator P p + have ht := MvPolynomial.totalDegree_sub (1 : MvPolynomial (Fin d) ℂ) + (∑ p ∈ P, physicalSeparator P p) + simp only [MvPolynomial.totalDegree_one, zero_le, max_eq_right] at ht + exact (ht.trans hs).trans (Nat.le_add_right _ _) + · obtain ⟨⟨p, j⟩, _, rfl⟩ := Finset.mem_image.mp hf + have hl : (MvPolynomial.X j - MvPolynomial.C (complexPoint p j)).totalDegree ≤ 1 := by + simpa using MvPolynomial.totalDegree_sub (MvPolynomial.X j) + (MvPolynomial.C (complexPoint p j)) + calc + _ ≤ (MvPolynomial.X j - MvPolynomial.C (complexPoint p j)).totalDegree + + (physicalSeparator P p).totalDegree := MvPolynomial.totalDegree_mul _ _ + _ ≤ 1 + 2 * (distances P).card := Nat.add_le_add hl (degree_physicalSeparator P p) + _ = 2 * (distances P).card + 1 := Nat.add_comm _ _ + +theorem isolation_zero_iff (P : Finset (Point d)) (z : Fin d → ℂ) : + (∀ f ∈ isolationPolynomials P, MvPolynomial.eval z f = 0) ↔ + ∃ p ∈ P, complexPoint p = z := by + classical + constructor + · intro hzero + have hsum : ∑ p ∈ P, MvPolynomial.eval z (physicalSeparator P p) = 1 := by + have hz := hzero _ (Finset.mem_insert_self _ _) + simp only [map_sub, map_one, map_sum] at hz + exact (sub_eq_zero.mp hz).symm + have hsum0 : ∑ p ∈ P, MvPolynomial.eval z (physicalSeparator P p) ≠ 0 := by + rw [hsum] + exact one_ne_zero + obtain ⟨p, hp, hs⟩ := Finset.exists_ne_zero_of_sum_ne_zero hsum0 + refine ⟨p, hp, ?_⟩ + funext j + have hj : (MvPolynomial.X j - MvPolynomial.C (complexPoint p j)) * + physicalSeparator P p ∈ isolationPolynomials P := by + apply Finset.mem_insert_of_mem + apply Finset.mem_image.mpr + exact ⟨(p, j), Finset.mem_product.mpr ⟨hp, Finset.mem_univ j⟩, rfl⟩ + have hz := hzero _ hj + simp only [map_mul, map_sub, MvPolynomial.eval_X, MvPolynomial.eval_C] at hz + exact (sub_eq_zero.mp ((mul_eq_zero.mp hz).resolve_right hs)).symm + · rintro ⟨p, hp, rfl⟩ f hf + rcases Finset.mem_insert.mp hf with rfl | hf + · rw [map_sub, map_one, map_sum] + have hsum : ∑ q ∈ P, MvPolynomial.eval (complexPoint p) (physicalSeparator P q) = 1 := by + rw [Finset.sum_eq_single p] + · exact eval_physicalSeparator_self P p + · intro q hq hqp + exact eval_physicalSeparator_ne hq hp hqp + · exact fun h => (h hp).elim + simp [hsum] + · obtain ⟨⟨q, j⟩, hqj, rfl⟩ := Finset.mem_image.mp hf + have hq : q ∈ P := (Finset.mem_product.mp hqj).1 + by_cases hqp : q = p + · subst q + simp + · simp [eval_physicalSeparator_ne hq hp hqp] + +theorem linearIndependent_physicalSeparator (P : Finset (Point d)) : + LinearIndependent ℂ (fun p : P => physicalSeparator P p) := by + classical + rw [linearIndependent_iff'] + intro s a hs p hp + have h := congrArg (MvPolynomial.eval (complexPoint (p : Point d))) hs + simp only [map_sum, MvPolynomial.smul_eval, map_zero] at h + have heq : ∑ q ∈ s, a q * + MvPolynomial.eval (complexPoint (p : Point d)) (physicalSeparator P q) = a p := by + rw [Finset.sum_eq_single p] + · simp [eval_physicalSeparator_self] + · intro q _ hqp + have hqp' : (q : Point d) ≠ (p : Point d) := fun h => hqp (Subtype.ext h) + simp [eval_physicalSeparator_ne q.property p.property hqp'] + · exact fun h => (h hp).elim + exact heq.symm.trans h + +theorem finrank_restrictDegree (d L : ℕ) : + Module.finrank ℂ (MvPolynomial.restrictDegree (Fin d) ℂ L) = (L + 1) ^ d := by + classical + let e : {n : Fin d →₀ ℕ // ∀ i, n i ≤ L} ≃ (Fin d → Fin (L + 1)) := + { toFun := fun n i => ⟨n.1 i, Nat.lt_succ_iff.mpr (n.2 i)⟩ + invFun := fun n => ⟨Finsupp.equivFunOnFinite.symm (fun i => (n i).val), + fun i => by simpa using Nat.lt_succ_iff.mp (n i).isLt⟩ + left_inv := fun n => by + apply Subtype.ext + ext i + simp + right_inv := fun n => by + funext i + apply Fin.ext + simp } + let : Fintype {n : Fin d →₀ ℕ // ∀ i, n i ≤ L} := Fintype.ofEquiv _ e.symm + calc + _ = Fintype.card {n : Fin d →₀ ℕ // ∀ i, n i ≤ L} := + Module.finrank_eq_card_basis (MvPolynomial.basisRestrictSupport ℂ _) + _ = Fintype.card (Fin d → Fin (L + 1)) := Fintype.card_congr e + _ = (L + 1) ^ d := by simp + +theorem elementary_card_bound (P : Finset (Point d)) : + P.card ≤ (2 * (distances P).card + 1) ^ d := by + classical + let V := MvPolynomial.restrictDegree (Fin d) ℂ (2 * (distances P).card) + have hv (p : P) : physicalSeparator P p ∈ V := + MvPolynomial.restrictTotalDegree_le_restrictDegree _ _ _ + ((MvPolynomial.mem_restrictTotalDegree _ _ _).mpr (degree_physicalSeparator P p)) + let v : P → V := fun p => ⟨physicalSeparator P p, hv p⟩ + have hlin : LinearIndependent ℂ v := + LinearIndependent.of_comp V.subtype (linearIndependent_physicalSeparator P) + have hcard := hlin.fintype_card_le_finrank + simpa [V, finrank_restrictDegree] using hcard + +def lengthFiber (S : Finset (Point d × Point d)) (r : ℝ) : Finset (Point d × Point d) := by + classical + exact S.filter (fun pq => dist pq.1 pq.2 = r) + +def equalLengthPairs (S : Finset (Point d × Point d)) : + Finset ((Point d × Point d) × (Point d × Point d)) := by + classical + exact (S.product S).filter (fun ab => dist ab.1.1 ab.1.2 = dist ab.2.1 ab.2.2) + +theorem sum_lengthFiber_card (S : Finset (Point d × Point d)) (hS : S ⊆ P.offDiag) : + ∑ r ∈ distances P, (lengthFiber S r).card = S.card := by + classical + change ∑ r ∈ distances P, (S.filter (fun pq => dist pq.1 pq.2 = r)).card = S.card + rw [Finset.sum_card_fiberwise_eq_card_filter] + congr 1 + apply Finset.filter_eq_self.mpr + intro pq hpq + exact Finset.mem_image.mpr ⟨pq, hS hpq, rfl⟩ + +theorem equalLengthPairs_card (S : Finset (Point d × Point d)) (hS : S ⊆ P.offDiag) : + (equalLengthPairs S).card = ∑ r ∈ distances P, (lengthFiber S r).card ^ 2 := by + classical + have hfib (r : ℝ) : + ((equalLengthPairs S).filter (fun ab => dist ab.1.1 ab.1.2 = r)) = + (lengthFiber S r).product (lengthFiber S r) := by + ext ab + simp only [equalLengthPairs, lengthFiber, Finset.mem_filter] + aesop + have hcover : ((equalLengthPairs S).filter + (fun ab => dist ab.1.1 ab.1.2 ∈ distances P)) = equalLengthPairs S := by + apply Finset.filter_eq_self.mpr + intro ab hab + have ha : ab.1 ∈ S := (Finset.mem_product.mp (Finset.mem_filter.mp hab).1).1 + exact Finset.mem_image.mpr ⟨ab.1, hS ha, rfl⟩ + have hsum := Finset.sum_card_fiberwise_eq_card_filter (equalLengthPairs S) + (distances P) (fun ab => dist ab.1.1 ab.1.2) + rw [hcover] at hsum + rw [← hsum] + apply Finset.sum_congr rfl + intro r _ + rw [hfib r] + exact (Finset.card_product _ _).trans (pow_two _).symm + +theorem equalLengthPairs_lower_bound (S : Finset (Point d × Point d)) (hS : S ⊆ P.offDiag) : + S.card ^ 2 ≤ (distances P).card * (equalLengthPairs S).card := by + classical + have h := Finset.sum_mul_sq_le_sq_mul_sq (distances P) + (fun _ => (1 : ℕ)) (fun r => (lengthFiber S r).card) + simpa only [one_mul, one_pow, Finset.sum_const, smul_eq_mul, mul_one, + sum_lengthFiber_card S hS, ← equalLengthPairs_card S hS] using h + +theorem equalLengthPairs_lower_bound_real (S : Finset (Point d × Point d)) (hS : S ⊆ P.offDiag) : + (S.card : ℝ) ^ 2 / (1 + ((distances P).card : ℝ)) ≤ (equalLengthPairs S).card := by + have h : (S.card : ℝ) ^ 2 ≤ (distances P).card * (equalLengthPairs S).card := by + exact_mod_cast equalLengthPairs_lower_bound S hS + apply (div_le_iff₀ (by positivity : (0 : ℝ) < 1 + ((distances P).card : ℝ))).mpr + nlinarith [Nat.cast_nonneg (α := ℝ) (equalLengthPairs S).card] + +end ErdosDistinctDistances + +end + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/AlmostLinear.lean b/lean/OAI/Combinatorics/EditApproximation/AlmostLinear.lean new file mode 100644 index 0000000000000000000000000000000000000000..e66e936986052264904fdf5c8f4fa26c146967da --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/AlmostLinear.lean @@ -0,0 +1,46 @@ +import OAI.Combinatorics.EditApproximation.AlmostLinearConditional +import OAI.Combinatorics.EditApproximation.Probability.BernsteinFinite + +namespace OAI + +/-! A uniform binary approximation scheme for edit distance. +The finite Bernstein inequality supplies the concentration bounds for the +initial estimator and the refinement samples. -/ + +namespace EditApproximation +open MeasureTheory Filter + +/-- Finite product-measure concentration for the initial estimator and refinement. -/ +theorem computedBernsteinInputs (N : ℕ) : ComputedBernsteinInputs N := by + constructor + · exact finiteBernsteinInput _ + · intro b h + exact finiteBernsteinInput _ + +/-- A uniform almost-linear approximation scheme. The same binary algorithm +satisfies the approximation, equality, expected-work and space bounds. -/ +theorem almostLinearEditDistance (epsilon : BinaryFraction) + (hepsilon : 0 < epsilon.value) (_hepsilonOne : epsilon.value < 1) + : + (∀ (source target : List ℤ) (N : ℕ), source.length + target.length ≤ N → + (2 / 3 : ℝ) ≤ (computedFullLaw (source.map integerSymbolCode) (target.map integerSymbolCode) N epsilon).real + {outcome | EditDistortion.edit source target ≤ integerBinaryAnswer source target N epsilon outcome ∧ + (integerBinaryAnswer source target N epsilon outcome : ℝ) ≤ + (1 + (epsilon.value : ℝ)) * EditDistortion.edit source target}) ∧ + (∀ (source target : List ℤ) (N : ℕ), source = target → ∀ outcome, + integerBinaryAnswer source target N epsilon outcome = 0) ∧ + (∀ (C : ℕ) (eta : ℝ), 0 < eta → ∀ᶠ N : ℕ in atTop, + ∀ source target : List ℤ, source.length + target.length ≤ N → + (∀ z ∈ source ++ target, z.natAbs ≤ (N + 2) ^ C) → + (∫ outcome, integerBinaryWork source target N epsilon outcome + ∂computedFullLaw (source.map integerSymbolCode) (target.map integerSymbolCode) N epsilon) ≤ + (N + 2 : ℝ) ^ (1 + eta)) ∧ + (∀ C : ℕ, ∀ᶠ N : ℕ in atTop, ∀ source target : List ℤ, + source.length + target.length ≤ N → + (∀ z ∈ source ++ target, z.natAbs ≤ (N + 2) ^ C) → + ∀ outcome, integerBinarySpace source target N epsilon outcome ≤ (N + 2) ^ (C + 65564)) := by + exact almostLinearEditDistance_conditional epsilon hepsilon _hepsilonOne computedBernsteinInputs + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/AlmostLinearConditional.lean b/lean/OAI/Combinatorics/EditApproximation/AlmostLinearConditional.lean new file mode 100644 index 0000000000000000000000000000000000000000..50c9bc84f65f8de2263cc4c7bdadc41a41892131 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/AlmostLinearConditional.lean @@ -0,0 +1,57 @@ +import OAI.Combinatorics.EditApproximation.Binary.IntegerBinaryAccuracy +import OAI.Combinatorics.EditApproximation.Binary.IntegerBinarySpace + +namespace OAI + +/-! An edit-distance approximation scheme conditional on finite scalar +Bernstein concentration (Tropp, ACM217, corrected 2023, Theorem 4.16). +The same uniform binary algorithm is used in all four clauses. -/ + +namespace EditApproximation +open MeasureTheory Filter + +/-- For each fixed binary accuracy in `(0,1)`, the concrete uniform algorithm +has success probability at least `2/3`, deterministic zero on equal inputs, +worst-case expected almost-linear time including preprocessing and sampling, +and polynomial space on every outcome. Alphabet bounds are analysis parameters, +not inputs to the algorithm. The finite initial range uses exact suffix DP. -/ +theorem almostLinearEditDistance_conditional (epsilon : BinaryFraction) + (hepsilon : 0 < epsilon.value) (_hepsilonOne : epsilon.value < 1) + (bernstein : ∀ N, ComputedBernsteinInputs N) : + (∀ (source target : List ℤ) (N : ℕ), source.length + target.length ≤ N → + (2 / 3 : ℝ) ≤ (computedFullLaw (source.map integerSymbolCode) (target.map integerSymbolCode) N epsilon).real + {outcome | EditDistortion.edit source target ≤ integerBinaryAnswer source target N epsilon outcome ∧ + (integerBinaryAnswer source target N epsilon outcome : ℝ) ≤ + (1 + (epsilon.value : ℝ)) * EditDistortion.edit source target}) ∧ + (∀ (source target : List ℤ) (N : ℕ), source = target → ∀ outcome, + integerBinaryAnswer source target N epsilon outcome = 0) ∧ + (∀ (C : ℕ) (eta : ℝ), 0 < eta → ∀ᶠ N : ℕ in atTop, + ∀ source target : List ℤ, source.length + target.length ≤ N → + (∀ z ∈ source ++ target, z.natAbs ≤ (N + 2) ^ C) → + (∫ outcome, integerBinaryWork source target N epsilon outcome + ∂computedFullLaw (source.map integerSymbolCode) (target.map integerSymbolCode) N epsilon) ≤ + (N + 2 : ℝ) ^ (1 + eta)) ∧ + (∀ C : ℕ, ∀ᶠ N : ℕ in atTop, ∀ source target : List ℤ, + source.length + target.length ≤ N → + (∀ z ∈ source ++ target, z.natAbs ≤ (N + 2) ^ C) → + ∀ outcome, integerBinarySpace source target N epsilon outcome ≤ (N + 2) ^ (C + 65564)) := by + refine ⟨?_, ?_, ?_, ?_⟩ + · intro source target N hsize + exact integerBinaryAnswer_conditional_accuracy source target N epsilon hepsilon hsize (bernstein N) + · intro source target N heq outcome + exact integerBinaryAnswer_equal source target N epsilon heq outcome + · intro C eta heta + exact integerBinaryWork_expected_near_linear C epsilon hepsilon eta heta + · intro C + exact integerBinarySpace_polynomial C epsilon hepsilon + +/-- The cutoff selects an exact answer, rather than leaving the small-input +regime outside the uniform algorithm's correctness statement. -/ +theorem integerBinaryAnswer_fallback (source target : List ℤ) (N : ℕ) (epsilon : BinaryFraction) + (hsmall : ¬ physicalLargeInput N epsilon) (outcome) : + integerBinaryAnswer source target N epsilon outcome = EditDistortion.edit source target := by + simp only [integerBinaryAnswer, hsmall, ite_false, exactSuffixAnswer_eq_edit, integerSymbols_edit] + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/BasicResults.lean b/lean/OAI/Combinatorics/EditApproximation/BasicResults.lean new file mode 100644 index 0000000000000000000000000000000000000000..998c77977a678c4956a9452e941bcb5458a195ff --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/BasicResults.lean @@ -0,0 +1,205 @@ +import OAI.Combinatorics.EditApproximation.Geometry.ComparisonLift +import OAI.Combinatorics.EditApproximation.Refinement.StageTerminal +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalRefinementSpatial +import OAI.Combinatorics.EditApproximation.Numerics.RationalWideSpatial +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalRefinementInvariants +import OAI.Combinatorics.EditApproximation.Refinement.ComputedBandSpacing +import OAI.Combinatorics.EditApproximation.Geometry.UnskippedBands +import OAI.Combinatorics.EditApproximation.Numerics.RationalWideStep +import OAI.Combinatorics.EditApproximation.Refinement.StageComparison +import OAI.Combinatorics.EditApproximation.Geometry.OnlineActionDraw +import OAI.Combinatorics.EditApproximation.Geometry.ComparisonPhysical +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalLeaves +import OAI.Combinatorics.EditApproximation.Refinement.ComputedComparisonBand +import OAI.Combinatorics.EditApproximation.Geometry.BandRounding +import OAI.Combinatorics.EditApproximation.Geometry.BandEnvelopes +import OAI.Combinatorics.EditApproximation.Geometry.BandGuards +import OAI.Combinatorics.EditApproximation.Refinement.StageWarmup +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalSpatial +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalWarmupSlack +import OAI.Combinatorics.EditApproximation.Geometry.BandParameters +import OAI.Combinatorics.EditApproximation.Geometry.ComparisonBandCoverage +import OAI.Combinatorics.EditApproximation.Geometry.RepresentativeBands +import OAI.Combinatorics.EditApproximation.Geometry.PrefixComparison +import OAI.Combinatorics.EditApproximation.Refinement.ComputedBands +import OAI.Combinatorics.EditApproximation.Geometry.InitialSeedTable +import OAI.Combinatorics.EditApproximation.Geometry.ComparisonParameters +import OAI.Combinatorics.EditApproximation.Numerics.RationalPrefix +import OAI.Combinatorics.EditApproximation.Coarse.CoarseArrayEval +import OAI.Combinatorics.EditApproximation.Coarse.CoarseGlobalSeed +import OAI.Combinatorics.EditApproximation.Geometry.WideBellman +import OAI.Combinatorics.EditApproximation.Geometry.PrefixCosts +import OAI.Combinatorics.EditApproximation.Geometry.ComparisonBounds +import OAI.Combinatorics.EditApproximation.Geometry.StateDomain +import OAI.Combinatorics.EditApproximation.Geometry.SharedActions +import OAI.Combinatorics.EditApproximation.Geometry.SourcePrefixes +import OAI.Combinatorics.EditApproximation.Geometry.ComparisonTree +import OAI.Combinatorics.EditApproximation.Geometry.RoundedComparison +import OAI.Combinatorics.EditApproximation.Refinement.ComputedSeed +import OAI.Combinatorics.EditApproximation.Coarse.CoarseParameters +import OAI.Combinatorics.EditApproximation.Coarse.CoarsePrecision +import OAI.Combinatorics.EditApproximation.Coarse.CoarseInitialWork +import OAI.Combinatorics.EditApproximation.Geometry.Accuracy +import OAI.Combinatorics.EditApproximation.Probability.Amplification +import OAI.Combinatorics.EditApproximation.Geometry.ActionLower +import OAI.Combinatorics.EditApproximation.Geometry.ActionVectors +import OAI.Combinatorics.EditApproximation.Geometry.ActualActionValues +import OAI.Combinatorics.EditApproximation.Geometry.AlignedStates +import OAI.Combinatorics.EditApproximation.Geometry.AlignmentSplitting +import OAI.Combinatorics.EditApproximation.Geometry.Bands +import OAI.Combinatorics.EditApproximation.Geometry.Bellman +import OAI.Combinatorics.EditApproximation.Geometry.BandRegret +import OAI.Combinatorics.EditApproximation.Geometry.BalancedIntervals +import OAI.Combinatorics.EditApproximation.Geometry.BalancedWidths +import OAI.Combinatorics.EditApproximation.Geometry.ChildIncrements +import OAI.Combinatorics.EditApproximation.Coarse.CoarseAccuracy +import OAI.Combinatorics.EditApproximation.Coarse.CoarseEstimator +import OAI.Combinatorics.EditApproximation.Coarse.CoarseSampling +import OAI.Combinatorics.EditApproximation.Coarse.CoarseProbability +import OAI.Combinatorics.EditApproximation.Coarse.CoarseTransforms +import OAI.Combinatorics.EditApproximation.Coarse.CoarseWork +import OAI.Combinatorics.EditApproximation.Coarse.CoarsePadding +import OAI.Combinatorics.EditApproximation.Coarse.CoarseInitial +import OAI.Combinatorics.EditApproximation.Coarse.CoarseSeed +import OAI.Combinatorics.EditApproximation.Geometry.ComparisonAccounting +import OAI.Combinatorics.EditApproximation.Probability.Concentration +import OAI.Combinatorics.EditApproximation.Geometry.Cones +import OAI.Combinatorics.EditApproximation.Geometry.ConeLocality +import OAI.Combinatorics.EditApproximation.Geometry.Connections +import OAI.Combinatorics.EditApproximation.Geometry.Curvature +import OAI.Combinatorics.EditApproximation.Geometry.DomainCounts +import OAI.Combinatorics.EditApproximation.Geometry.DomainExponential +import OAI.Combinatorics.EditApproximation.Probability.Exact +import OAI.Combinatorics.EditApproximation.Probability.ExactSampling +import OAI.Combinatorics.EditApproximation.Probability.ExpectedRegret +import OAI.Combinatorics.EditApproximation.Geometry.FirstCrossing +import OAI.Combinatorics.EditApproximation.Probability.FiniteAssignments +import OAI.Combinatorics.EditApproximation.Geometry.GroupSampling +import OAI.Combinatorics.EditApproximation.Geometry.Grid +import OAI.Combinatorics.EditApproximation.Geometry.Leaves +import OAI.Combinatorics.EditApproximation.Geometry.LocalGrid +import OAI.Combinatorics.EditApproximation.Geometry.LocalInitialCones +import OAI.Combinatorics.EditApproximation.Geometry.InitialCones +import OAI.Combinatorics.EditApproximation.Geometry.InitialConeGrid +import OAI.Combinatorics.EditApproximation.Geometry.InitialConeTable +import OAI.Combinatorics.EditApproximation.Probability.Median +import OAI.Combinatorics.EditApproximation.Numerics.Numerics +import OAI.Combinatorics.EditApproximation.Numerics.NumericalWork +import OAI.Combinatorics.EditApproximation.Geometry.NodeRegret +import OAI.Combinatorics.EditApproximation.Geometry.ParameterSlack +import OAI.Combinatorics.EditApproximation.Geometry.Parameters +import OAI.Combinatorics.EditApproximation.Geometry.PartitionIntervals +import OAI.Combinatorics.EditApproximation.Numerics.RationalRefinement +import OAI.Combinatorics.EditApproximation.Probability.SampledRegret +import OAI.Combinatorics.EditApproximation.Geometry.StateGeometry +import OAI.Combinatorics.EditApproximation.Probability.ThresholdMoments +import OAI.Combinatorics.EditApproximation.Geometry.TreeAccounting +import OAI.Combinatorics.EditApproximation.Geometry.TreeParameters +import OAI.Combinatorics.EditApproximation.Geometry.Work +import OAI.Combinatorics.EditApproximation.Geometry.WeightedTreeWork +import OAI.Combinatorics.EditApproximation.Geometry.WideActions +import OAI.Combinatorics.EditApproximation.Geometry.BandGroupSampling +import OAI.Combinatorics.EditApproximation.Geometry.CellGroupSelection +import OAI.Combinatorics.EditApproximation.Geometry.ComparisonLiftBounds +import OAI.Combinatorics.EditApproximation.Refinement.ComputedGroupAccuracy +import OAI.Combinatorics.EditApproximation.Refinement.ComputedGroupNumerical +import OAI.Combinatorics.EditApproximation.Geometry.GroupCells +import OAI.Combinatorics.EditApproximation.Geometry.GroupNumerical +import OAI.Combinatorics.EditApproximation.Geometry.GroupSmallConstants +import OAI.Combinatorics.EditApproximation.Geometry.ListBandRegret +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalGroupAccuracy +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalOnlineBand +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalNodeRegret +import OAI.Combinatorics.EditApproximation.Refinement.StageComparisonEnergy +import OAI.Combinatorics.EditApproximation.Refinement.StageParameterBounds + +import OAI.Combinatorics.EditApproximation.Geometry.ComparisonLiftStep +import OAI.Combinatorics.EditApproximation.Refinement.StageComparisonCharges +import OAI.Combinatorics.EditApproximation.Refinement.StageComparisonBad +import OAI.Combinatorics.EditApproximation.Geometry.BandDimension +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalUnskippedComparison +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalTreeRegret +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalGenericRegret +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalComparisonBand +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalTreeGeneric +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalTreeExpectation +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalExpectedRegret +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalParentDraw +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalRefinementLocality +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalResampledRegret +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalConditionalNode +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalSelectionProgram +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalSelectionResampling +import OAI.Combinatorics.EditApproximation.Probability.FiniteResampling +import OAI.Combinatorics.EditApproximation.Refinement.StageComparisonPrediction +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalTreeNear +import OAI.Combinatorics.EditApproximation.Geometry.UnskippedRegretBudget +import OAI.Combinatorics.EditApproximation.Refinement.ComputedStageParameters +import OAI.Combinatorics.EditApproximation.Refinement.ComputedStageTime +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalBoundsAllSeeds +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalTreeBudget +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalProgramLaw +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalProgramRefreshWiring +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalProgramNodeRegret +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalProgramComparisonRegret +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalProgramAccuracy +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalOnlineLocality +import OAI.Combinatorics.EditApproximation.Geometry.RefinementErrorTerms +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalDenominator +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalValueBits +import OAI.Combinatorics.EditApproximation.Numerics.RationalPruning +import OAI.Combinatorics.EditApproximation.Geometry.RefinementConeLocality +import OAI.Combinatorics.EditApproximation.Geometry.LocalCells +import OAI.Combinatorics.EditApproximation.Geometry.LocalRefinementCones +import OAI.Combinatorics.EditApproximation.Geometry.GroupSamplingWork +import OAI.Combinatorics.EditApproximation.Geometry.LocalGroupCones +import OAI.Combinatorics.EditApproximation.Geometry.RoundedGroupStates +import OAI.Combinatorics.EditApproximation.Geometry.DyadicQueryWindow +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalSubtree +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalSubtreeMass +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalSubtreeCharges +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalSubtreeRegret +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalSubtreeExpectation +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalSubtreeBad +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalSubtreeGeneric +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalSubtreePrediction +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalSubtreeNear +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalSubtreeBudget +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalProgramSubtreeRegret +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalProgramStateAccuracy +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalSeedMedian +import OAI.Combinatorics.EditApproximation.Geometry.ActualRoundedGroupInputs +import OAI.Combinatorics.EditApproximation.Geometry.SharedGroupInputBudget +import OAI.Combinatorics.EditApproximation.Geometry.SeedPassNumerics +import OAI.Combinatorics.EditApproximation.Geometry.SeedFactorSchedule +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalQueryBudget +import OAI.Combinatorics.EditApproximation.Geometry.LocalGroupBudget +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalSeedPass +import OAI.Combinatorics.EditApproximation.Probability.AdaptiveSeedLaw +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalSeedTables +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalSeedSchedule +import OAI.Combinatorics.EditApproximation.Binary.BinaryMemo +import OAI.Combinatorics.EditApproximation.Geometry.CurrentQueryInputs +import OAI.Combinatorics.EditApproximation.Geometry.GroupInputDependence +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalLocalGroupProgram +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalLocalWarmup +import OAI.Combinatorics.EditApproximation.Probability.FiniteSeedFinal +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalCoarseSeedLaw +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalFinalAccuracy +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalConditionalAccuracy +import OAI.Combinatorics.EditApproximation.Geometry.LocalWideStep +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalLocalRefinement +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalLocalRefinementEquality +import OAI.Combinatorics.EditApproximation.Refinement.ComputedCurrentQueryBudget + +import OAI.Combinatorics.EditApproximation.AlmostLinear + +/-! +# Almost-linear approximation of edit distance + +A uniform binary randomized approximation scheme attains success probability +at least two thirds, returns zero on equal strings, uses almost-linear expected +work for each fixed binary accuracy, and has polynomial space on every outcome. +Finite Bernstein concentration discharges the hypotheses of its conditional +accuracy and work bounds. +-/ diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryActionSelection.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryActionSelection.lean new file mode 100644 index 0000000000000000000000000000000000000000..edd18e0b9c3396b65f1640bb5afec5851207d173 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryActionSelection.lean @@ -0,0 +1,147 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryOptimizerWork +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! The final Boolean maximization retains the actual action label. This +is the sampled atom of the optimizer, rather than its averaged vector. -/ + +namespace EditApproximation +namespace BinaryFraction + +open Finset + +theorem dotWithWork_value {d : ℕ} (left right : Vector BinaryFraction d) : + (dotWithWork left right).1.value = ∑ i, (left.get i).value * (right.get i).value := by + rw [← representation_value, dotWithWork_representation, UnreducedRational.dot_value] + simp only [vector_map_get, representation_value] + +theorem gradientWithWork_value {d : ℕ} (G : ℕ) (linear point : Vector BinaryFraction d) (i : Fin d) : + ((gradientWithWork G linear point).1.get i).value = + rationalSmoothedGradient G (fun j => (linear.get j).value) (fun j => (point.get j).value) i := by + have h := congrArg (fun v : Vector UnreducedRational d => (v.get i).value) + (gradientWithWork_representation G linear point) + simp only [vector_map_get, representation_value, UnreducedRational.gradient_value] at h + simpa only [vector_map_get, representation_value] using h + + + +theorem selectionWithWork_value {α : Type*} {d : ℕ} + (vertices : List (α × Vector BinaryFraction d)) (linear : Vector BinaryFraction d) (G j : ℕ) : + (selectionWithWork vertices linear G j).1 = + (materializedSelectionWithWork + (vertices.map fun v => (v.1, v.2.map value)) (linear.map value) G j).1 := by + rw [materializedSelectionWithWork_value, argmax_map_commutes] + simp only [selectionWithWork, scoredArgmaxWithWork_value, Option.map_map, Function.comp_def] + apply congrArg (fun score => (vertices.argmax score).map Prod.fst) + funext vertex + rw [dotWithWork_value] + have hget (v : Vector BinaryFraction d) : (v.map value).get = fun i => (v.get i).value := by + funext i + exact vector_map_get value v i + simp only [gradientWithWork_value, finiteOptimizerWithWork_value, + List.map_map, vector_map_get, Function.comp_def, hget] + +theorem scoredArgmaxWithWork_map_cost {α β : Type*} (mapping : α → β) + (score : β → BinaryFraction × ℕ) (values : List α) : + (scoredArgmaxWithWork (fun a => score (mapping a)) values).2 = + (scoredArgmaxWithWork score (values.map mapping)).2 := by + have h : (scoredArgmaxWithWork score (values.map mapping)).1 = + (scoredArgmaxWithWork (fun a => score (mapping a)) values).1.map + (fun result => (mapping result.1, result.2)) ∧ + (scoredArgmaxWithWork (fun a => score (mapping a)) values).2 = + (scoredArgmaxWithWork score (values.map mapping)).2 := by + induction values with + | nil => exact ⟨rfl, rfl⟩ + | cons head tail ih => + simp only [List.map_cons, scoredArgmaxWithWork, ih.1, ← ih.2] + cases htail : (scoredArgmaxWithWork (fun a => score (mapping a)) tail).1 with + | none => exact ⟨rfl, rfl⟩ + | some best => + simp only [Option.map_some] + split_ifs <;> simp + exact h.2 + +def selectionBitBudget (d vertices G K B Bv L V : ℕ) : ℕ := + let P := optimizerPointWordBudget K B Bv + let W := optimizerGradientWordBudget G K B Bv L + optimizerBitBudget d vertices G K B Bv L V + d * (gradientCellBitBudget G P L + 6) + + maximizerBitBudget d vertices (max P W) (2 * G ^ 60 + 1 + V + 1) + +theorem selectionWithWork_cost {α : Type*} {d : ℕ} + (vertices : List (α × Vector BinaryFraction d)) (linear : Vector BinaryFraction d) + (G K B Bv L V : ℕ) (hvertices : vertices ≠ []) + (hinput : ∀ v ∈ vertices, ∀ i : Fin d, + (v.2.get i).width ≤ (v.2.get i).representation.storageBits ∧ + (0 ≤ (v.2.get i).value ∧ (v.2.get i).value ≤ 1) ∧ + Nat.size (v.2.get i).representation.den ≤ B) + (hvw : ∀ v ∈ vertices, ∀ i, (v.2.get i).width ≤ Bv) + (hlw : ∀ i, (linear.get i).width ≤ L) + (hlv : ∀ i, |(linear.get i).value| ≤ V) : + (selectionWithWork vertices linear G K).2 ≤ selectionBitBudget d vertices.length G K B Bv L V := by + let points := vertices.map Prod.snd + let point := (finiteOptimizerWithWork points linear G K).1 + let grad := (gradientWithWork G linear point).1 + let P := optimizerPointWordBudget K B Bv + let W := optimizerGradientWordBudget G K B Bv L + have hpnonempty : points ≠ [] := by + intro h + exact hvertices (List.map_eq_nil_iff.mp h) + have hpinput (v : Vector BinaryFraction d) (hv : v ∈ points) (i : Fin d) : + (v.get i).width ≤ (v.get i).representation.storageBits ∧ + (0 ≤ (v.get i).value ∧ (v.get i).value ≤ 1) ∧ Nat.size (v.get i).representation.den ≤ B := by + obtain ⟨a, ha, rfl⟩ := List.mem_map.mp hv + exact hinput a ha i + have hpw (v : Vector BinaryFraction d) (hv : v ∈ points) (i : Fin d) : (v.get i).width ≤ Bv := by + obtain ⟨a, ha, rfl⟩ := List.mem_map.mp hv + exact hvw a ha i + have hpoint (i : Fin d) : (point.get i).width ≤ P := by + have h := finiteOptimizerWithWork_coordinate_width points linear G K B hpnonempty hpinput i + change (point.get i).width ≤ _ at h + dsimp only [P, optimizerPointWordBudget] + omega + have hpositive (i : Fin d) : 0 ≤ (point.get i).value := by + have hn : (points.map fun v i => (v.get i).value) ≠ [] := by + intro h + exact hpnonempty (List.map_eq_nil_iff.mp h) + have h := finiteRationalOptimizer_coordinate_bounds univ + (points.map fun v i => (v.get i).value) (fun i => (linear.get i).value) G K hn i (by + intro v hv + obtain ⟨w, hw, rfl⟩ := List.mem_map.mp hv + exact (hpinput w hw i).2.1) + rw [← congrFun (finiteOptimizerWithWork_value points linear G K) i] at h + exact h.1 + have hgw (i : Fin d) : (grad.get i).width ≤ W := + gradientWithWork_width G linear point P L hpositive hpoint hlw i + have hgv (i : Fin d) : |(grad.get i).value| ≤ (2 * G ^ 60 + 1 + V + 1 : ℕ) := + (gradientWithWork_abs G V linear point hpositive hlv i).trans + (by exact_mod_cast Nat.le_add_right (2 * G ^ 60 + 1 + V) 1) + have hvP (v : Vector BinaryFraction d) (hv : v ∈ points) (i : Fin d) : (v.get i).width ≤ P := by + have h := hpw v hv i + dsimp only [P, optimizerPointWordBudget] + omega + have hvabs (v : Vector BinaryFraction d) (hv : v ∈ points) (i : Fin d) : + |(v.get i).value| ≤ (2 * G ^ 60 + 1 + V + 1 : ℕ) := by + rw [abs_of_nonneg (hpinput v hv i).2.1.1] + exact (hpinput v hv i).2.1.2.trans (by exact_mod_cast + (show 1 ≤ 2 * G ^ 60 + 1 + V + 1 by omega)) + have hiterate := finiteOptimizerWithWork_cost points linear G K B Bv L V hpnonempty hpinput hpw hlw hlv + have hgradient := gradientWithWork_cost G linear point P L hpositive hpoint hlw + have hselected := maximizerWithWork_cost grad points (max P W) (2 * G ^ 60 + 1 + V + 1) + (fun i => (hgw i).trans (Nat.le_max_right _ _)) hgv + (fun v hv i => (hvP v hv i).trans (Nat.le_max_left _ _)) hvabs + rw [maximizerWithWork, ← scoredArgmaxWithWork_map_cost Prod.snd (dotWithWork grad) vertices] at hselected + simp only [points, List.length_map] at hiterate hselected + change (finiteOptimizerWithWork points linear G K).2 ≤ _ at hiterate + change (finiteOptimizerWithWork points linear G K).2 + (gradientWithWork G linear point).2 + + (scoredArgmaxWithWork (fun vertex => dotWithWork grad vertex.2) vertices).2 + 1 ≤ _ + change _ ≤ optimizerBitBudget d vertices.length G K B Bv L V + + d * (gradientCellBitBudget G P L + 6) + + maximizerBitBudget d vertices.length (max P W) (2 * G ^ 60 + 1 + V + 1) + omega + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryActualBandOptimizer.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryActualBandOptimizer.lean new file mode 100644 index 0000000000000000000000000000000000000000..7fbe980ace107de21fd1fbf058e110a57c89cb36 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryActualBandOptimizer.lean @@ -0,0 +1,124 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryBandEnvelope +import OAI.Combinatorics.EditApproximation.Binary.BinaryPreparedOptimizer + +namespace OAI + +/-! The complete Boolean band optimizer constructs its envelopes from the +stored initial table, then constructs the vertices and history vector. The +normalized history bounds follow from actual band-coordinate membership. -/ + +namespace EditApproximation +namespace BinaryFraction + +open Finset + +theorem listedBandCoordinateVector_coverage {M : ℕ} {σ : Type*} [DecidableEq σ] + (band : List (Fin M → σ)) (i : Fin (listedBandCoordinates band).length) : + ∃ action ∈ band, action ((listedBandCoordinateVector band).get i).1 = + ((listedBandCoordinateVector band).get i).2 := by + have hc : (listedBandCoordinateVector band).get i ∈ listedBandCoordinates band := by + simp only [listedBandCoordinateVector, vector_get_ofFn] + exact List.get_mem _ _ + obtain ⟨action, ha, hc⟩ := List.mem_flatMap.mp (List.mem_dedup.mp hc) + obtain ⟨child, hchild⟩ := List.mem_ofFn.mp hc + refine ⟨action, ha, ?_⟩ + rw [← hchild] + +def envelopeVectorWithWork {M ny : ℕ} (b : ℕ) + (band : List (Fin M → TargetInterval ny)) + (initial : Fin M → TargetInterval ny → BinaryFraction) : Vector BinaryFraction M × ℕ := + vectorMapWithWork M (bandEnvelopeWithWork b band initial) + +theorem envelopeVectorWithWork_value {M ny : ℕ} (b : ℕ) + (band : List (Fin M → TargetInterval ny)) + (initial : Fin M → TargetInterval ny → BinaryFraction) (hb : 0 < b) (i : Fin M) : + ((envelopeVectorWithWork b band initial).1.get i).value = + bandChildEnvelope b band (fun j q => (initial j q).value) i := by + simp only [envelopeVectorWithWork, vectorMapWithWork_value] + exact bandEnvelopeWithWork_value b band initial i hb + +def bandOptimizerWithWork {M d ny : ℕ} + (coordinates : Vector (Fin M × TargetInterval ny) d) (b : ℕ) + (initial : Fin M → TargetInterval ny → BinaryFraction) + (table : ℕ → Fin M × TargetInterval ny → BinaryFraction) (eta kappa : BinaryFraction) + (band : List (Fin M → TargetInterval ny)) (G K t : ℕ) : Vector BinaryFraction d × ℕ := + let mass := envelopeVectorWithWork b band initial + let result := preparedBandOptimizerWithWork coordinates mass.1 table eta kappa band G K t + (result.1, mass.2 + result.2 + 1) + +theorem bandOptimizerWithWork_value {M d ny : ℕ} + (coordinates : Vector (Fin M × TargetInterval ny) d) (b : ℕ) + (initial : Fin M → TargetInterval ny → BinaryFraction) + (table : ℕ → Fin M × TargetInterval ny → BinaryFraction) (eta kappa : BinaryFraction) + (band : List (Fin M → TargetInterval ny)) (G K t : ℕ) (hb : 0 < b) : + (fun i => ((bandOptimizerWithWork coordinates b initial table eta kappa band G K t).1.get i).value) = + finiteRationalOptimizer univ + (band.map fun action i => actionVector + (bandChildEnvelope b band (fun j q => (initial j q).value)) action (coordinates.get i)) + (fun i => rationalOnlineLinear eta.value kappa.value + (childGain (bandChildEnvelope b band (fun j q => (initial j q).value)) + (fun s j => (table s j).value)) + (childDecrement (bandChildEnvelope b band (fun j q => (initial j q).value)) + (fun s j => (table s j).value)) t (coordinates.get i)) G K := by + simp only [bandOptimizerWithWork, preparedBandOptimizerWithWork_value] + have hm : (fun j => ((envelopeVectorWithWork b band initial).1.get j).value) = + bandChildEnvelope b band (fun j q => (initial j q).value) := by + funext j + exact envelopeVectorWithWork_value b band initial hb j + rw [hm] + +def actualBandOptimizerBitBudget (M d b vertices G K t Be Bk Bi Bt E : ℕ) : ℕ := + M * (bandEnvelopeBitBudget b M vertices Bi + 6) + + preparedBandOptimizerBitBudget M d vertices G K t Be Bk + (3 * bandEnvelopeWordBudget b M Bi + 1) Bt E + 1 + +theorem bandOptimizerWithWork_cost {M d ny : ℕ} + (coordinates : Vector (Fin M × TargetInterval ny) d) (b : ℕ) + (initial : Fin M → TargetInterval ny → BinaryFraction) + (table : ℕ → Fin M × TargetInterval ny → BinaryFraction) (eta kappa : BinaryFraction) + (band : List (Fin M → TargetInterval ny)) (G K t Be Bk Bi Bt E : ℕ) + (hband : band ≠ []) (hb : 0 < b) (hM : 0 < M) + (hcoverage : ∀ i, ∃ action ∈ band, action (coordinates.get i).1 = (coordinates.get i).2) + (he : eta.width ≤ Be) (hk : kappa.width ≤ Bk) + (hi : ∀ action ∈ band, ∀ j, (initial j (action j)).width ≤ Bi) + (ht : ∀ s ≤ t + 1, ∀ i, (table s (coordinates.get i)).width ≤ Bt) + (heabs : |eta.value| ≤ E) (hkrange : 0 ≤ kappa.value ∧ kappa.value ≤ 1) + (htrange : ∀ s ≤ t + 1, ∀ i, 0 ≤ (table s (coordinates.get i)).value ∧ + (table s (coordinates.get i)).value ≤ (initial (coordinates.get i).1 (coordinates.get i).2).value) : + (bandOptimizerWithWork coordinates b initial table eta kappa band G K t).2 ≤ + actualBandOptimizerBitBudget M d b band.length G K t Be Bk Bi Bt E := by + let mass := (envelopeVectorWithWork b band initial).1 + have hmv (j : Fin M) : (mass.get j).value = bandChildEnvelope b band (fun j q => (initial j q).value) j := + envelopeVectorWithWork_value b band initial hb j + have hm (j : Fin M) : (mass.get j).width ≤ 3 * bandEnvelopeWordBudget b M Bi + 1 := by + simp only [mass, envelopeVectorWithWork, vectorMapWithWork_value] + exact bandEnvelopeWithWork_width b band initial j Bi (fun action ha => hi action ha j) + have hmpos (j : Fin M) : 0 < (mass.get j).value := by + rw [hmv] + exact lt_of_lt_of_le (div_pos (by exact_mod_cast hb) (by exact_mod_cast hM)) + (bandChildEnvelope_lower b band (fun j q => (initial j q).value) j).1 + have hnormalized (s : ℕ) (hs : s ≤ t + 1) (i : Fin d) : + 0 ≤ (table s (coordinates.get i)).value ∧ + (table s (coordinates.get i)).value ≤ (mass.get (coordinates.get i).1).value := by + refine ⟨(htrange s hs i).1, ?_⟩ + obtain ⟨action, ha, heq⟩ := hcoverage i + have henv := (bandChildEnvelope_lower b band (fun j q => (initial j q).value) + (coordinates.get i).1).2 action ha + rw [heq] at henv + rw [hmv] + exact (htrange s hs i).2.trans henv + have hp := preparedBandOptimizerWithWork_cost coordinates mass table eta kappa band G K t + Be Bk (3 * bandEnvelopeWordBudget b M Bi + 1) Bt E hband he hk hm hmpos ht heabs hkrange hnormalized + have hc := vectorMapWithWork_cost_le M (bandEnvelopeWithWork b band initial) + (bandEnvelopeBitBudget b M band.length Bi) + (fun j => bandEnvelopeWithWork_cost b band initial j Bi (fun action ha => hi action ha j)) + change (envelopeVectorWithWork b band initial).2 + + (preparedBandOptimizerWithWork coordinates mass table eta kappa band G K t).2 + 1 ≤ _ + change (envelopeVectorWithWork b band initial).2 ≤ _ at hc + unfold actualBandOptimizerBitBudget + omega + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryAffineGuard.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryAffineGuard.lean new file mode 100644 index 0000000000000000000000000000000000000000..07564e8b7bb2199370f1b63ab36c604c385b4b2a --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryAffineGuard.lean @@ -0,0 +1,103 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryDistanceWork +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Boolean tests for the affine errors in band membership. The literal +product, both subtractions and final comparison have charged bit work. -/ + +namespace EditApproximation +namespace BinaryFraction + +theorem canonicalMulWithWork_width (a b : BinaryFraction) (B : ℕ) + (ha : a.width ≤ B) (hb : b.width ≤ B) : + (a.canonicalMulWithWork b).1.width ≤ 4 * B + 2 := by + have hs := UnreducedRational.storageBits_mul a.representation b.representation + have ha' := representation_storageBits_le a + have hb' := representation_storageBits_le b + have hw := canonicalMulWithWork_self_width a b + rw [canonicalMulWithWork_representation] at hw + omega + + + +@[simp] theorem affineErrorWithWork_value (position offset velocity prediction tolerance : BinaryFraction) : + (affineErrorWithWork position offset velocity prediction tolerance).1 = true ↔ + |position.value - offset.value - velocity.value * prediction.value| ≤ tolerance.value := by + simp only [affineErrorWithWork, leWithWork_value, absolute_value, + subWithWork_value, canonicalMulWithWork_value] + +def affineGuardBitBudget (B : ℕ) : ℕ := + 6000 * (B + 1) ^ 2 + 1 + 2000 * (B + 1) ^ 2 + + (6000 * (12 * B + 9) ^ 2 + 1) + + (1000 * (96 * B + 71) ^ 2 + 1) + 4 + +theorem affineErrorWithWork_cost (position offset velocity prediction tolerance : BinaryFraction) + (B : ℕ) (hp : position.width ≤ B) (ho : offset.width ≤ B) + (hv : velocity.width ≤ B) (hpred : prediction.width ≤ B) (ht : tolerance.width ≤ B) : + (affineErrorWithWork position offset velocity prediction tolerance).2 ≤ affineGuardBitBudget B := by + have hdw := subWithWork_width position offset B hp ho + have hmw := canonicalMulWithWork_width velocity prediction B hv hpred + have hd := subWithWork_cost position offset B hp ho + have hm := canonicalMulWithWork_cost velocity prediction B hv hpred + have hew := subWithWork_width (position.subWithWork offset).1 + (velocity.canonicalMulWithWork prediction).1 (12 * B + 8) (by omega) (by omega) + have he := subWithWork_cost (position.subWithWork offset).1 + (velocity.canonicalMulWithWork prediction).1 (12 * B + 8) (by omega) (by omega) + have hc := leWithWork_cost ((position.subWithWork offset).1.subWithWork + (velocity.canonicalMulWithWork prediction).1).1.absolute tolerance (96 * B + 70) + (by simpa only [absolute_width] using (hew.trans (by omega : 8 * (12 * B + 8) + 6 ≤ 96 * B + 70))) (by omega) + simp only [Nat.add_assoc, Nat.reduceAdd] at he hc + change _ + _ + _ + _ + 4 ≤ _ + unfold affineGuardBitBudget + omega + +/-- Threshold used in every internal-cut predicate. -/ + + +@[simp] theorem bandToleranceWithWork_value (tau theta : BinaryFraction) (b M : ℕ) : + (bandToleranceWithWork tau theta b M).1.value = tau.value * theta.value * b / M := by + simp only [bandToleranceWithWork, divWithWork_value, canonicalMulWithWork_value, nat_value] + +theorem divWithWork_width_uniform (a b : BinaryFraction) (B : ℕ) + (ha : a.width ≤ B) (hb : b.width ≤ B) : + (a.divWithWork b).1.width ≤ 4 * B + 4 := by + have hs := UnreducedRational.storageBits_div a.representation b.representation + have ha' := representation_storageBits_le a + have hb' := representation_storageBits_le b + have hw := divWithWork_self_width a b + rw [divWithWork_representation] at hw + omega + +def bandToleranceBitBudget (B : ℕ) : ℕ := + 2000 * (B + 1) ^ 2 + 2000 * (4 * B + 3) ^ 2 + + 2100 * (16 * B + 12) ^ 2 + 2 * B + 3 + +theorem bandToleranceWithWork_bounds (tau theta : BinaryFraction) (b M B : ℕ) + (htau : tau.width ≤ B) (htheta : theta.width ≤ B) + (hb : Nat.size b + 2 ≤ B) (hM : Nat.size M + 2 ≤ B) : + (bandToleranceWithWork tau theta b M).1.width ≤ 64 * B + 44 ∧ + (bandToleranceWithWork tau theta b M).2 ≤ bandToleranceBitBudget B := by + have hpw := canonicalMulWithWork_width tau theta B htau htheta + have hp := canonicalMulWithWork_cost tau theta B htau htheta + have hsw := canonicalMulWithWork_width (canonicalMulWithWork tau theta).1 (nat b) + (4 * B + 2) hpw ((nat_width_le b).trans (by omega)) + have hs := canonicalMulWithWork_cost (canonicalMulWithWork tau theta).1 (nat b) + (4 * B + 2) hpw ((nat_width_le b).trans (by omega)) + have htw := divWithWork_width_uniform (canonicalMulWithWork + (canonicalMulWithWork tau theta).1 (nat b)).1 (nat M) (16 * B + 10) + (by omega) ((nat_width_le M).trans (by omega)) + have ht := divWithWork_cost (canonicalMulWithWork + (canonicalMulWithWork tau theta).1 (nat b)).1 (nat M) (16 * B + 10) + (by omega) ((nat_width_le M).trans (by omega)) + refine ⟨by dsimp only [bandToleranceWithWork]; omega, ?_⟩ + simp only [Nat.add_assoc, Nat.reduceAdd] at hs ht + change _ + _ + _ + Nat.size b + Nat.size M + 3 ≤ _ + unfold bandToleranceBitBudget + omega + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryArithmeticWork.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryArithmeticWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..df76d248945ff15c78c055849df4f68500fe2496 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryArithmeticWork.lean @@ -0,0 +1,167 @@ +import Mathlib.Data.Nat.Size +import Mathlib.Tactic +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Literal Boolean ripple addition. The counter counts Boolean gates and +bit writes, not unit-cost arithmetic on unbounded integers. -/ + +namespace EditApproximation + + + + + + + +theorem bitAdder_value (a b carry : Bool) : + (bitSum a b carry).toNat + 2 * (bitCarry a b carry).toNat = + a.toNat + b.toNat + carry.toNat := by + cases a <;> cases b <;> cases carry <;> decide + + + + + +theorem bitAddWithWork_value (left right : List Bool) (carry : Bool) : + bitWordValue (bitAddWithWork left right carry).1 = + bitWordValue left + bitWordValue right + carry.toNat := by + induction left generalizing right carry with + | nil => + simp only [bitAddWithWork] + induction right generalizing carry with + | nil => cases carry <;> simp [bitAddNilLeftWithWork, bitWordValue] + | cons b bs ih => + simp only [bitAddNilLeftWithWork, bitWordValue, ih] + have h := bitAdder_value false b carry + simp only [Bool.toNat_false] at h + omega + | cons a as ih => + cases right with + | nil => + simp only [bitAddWithWork, bitWordValue, ih] + have h := bitAdder_value a false carry + simp only [Bool.toNat_false] at h + omega + | cons b bs => + simp only [bitAddWithWork, bitWordValue, ih] + have h := bitAdder_value a b carry + omega + +theorem bitAddWithWork_cost (left right : List Bool) (carry : Bool) : + (bitAddWithWork left right carry).2 ≤ 9 * (left.length + right.length) + 1 := by + induction left generalizing right carry with + | nil => + simp only [bitAddWithWork] + induction right generalizing carry with + | nil => cases carry <;> simp [bitAddNilLeftWithWork] + | cons b bs ih => + simp only [bitAddNilLeftWithWork, List.length_cons, List.length_nil] + have h := ih (bitCarry false b carry) + simp only [List.length_nil] at h + omega + | cons a as ih => + cases right with + | nil => + simp only [bitAddWithWork, List.length_cons, List.length_nil] + have h := ih [] (bitCarry a false carry) + simp only [List.length_nil] at h + omega + | cons b bs => + simp only [bitAddWithWork, List.length_cons] + have h := ih bs (bitCarry a b carry) + omega + +theorem bitAddWithWork_length (left right : List Bool) (carry : Bool) : + (bitAddWithWork left right carry).1.length ≤ max left.length right.length + 1 := by + induction left generalizing right carry with + | nil => + simp only [bitAddWithWork] + induction right generalizing carry with + | nil => cases carry <;> simp [bitAddNilLeftWithWork] + | cons b bs ih => + simp only [bitAddNilLeftWithWork, List.length_cons, List.length_nil, Nat.zero_max] + have h := ih (bitCarry false b carry) + simp only [List.length_nil, Nat.zero_max] at h + omega + | cons a as ih => + cases right with + | nil => + simp only [bitAddWithWork, List.length_cons, List.length_nil, Nat.max_zero] + have h := ih [] (bitCarry a false carry) + simp only [List.length_nil, Nat.max_zero] at h + omega + | cons b bs => + simp only [bitAddWithWork, List.length_cons] + have h := ih bs (bitCarry a b carry) + omega + +theorem bitWordValue_bits (n : ℕ) : bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [bitWordValue, ih, Nat.bit, Nat.add_comm] + + + +theorem binaryNaturalAddWithWork_value (a b : ℕ) : + bitWordValue (binaryNaturalAddWithWork a b).1 = a + b := by + simp [binaryNaturalAddWithWork, bitAddWithWork_value, bitWordValue_bits] + +theorem binaryNaturalAddWithWork_cost (a b : ℕ) : + (binaryNaturalAddWithWork a b).2 ≤ 9 * (Nat.size a + Nat.size b) + 1 := by + simpa only [binaryNaturalAddWithWork, Nat.size_eq_bits_len] using + bitAddWithWork_cost a.bits b.bits false + + + +theorem bitMulWithWork_value (left right : List Bool) : + bitWordValue (bitMulWithWork left right).1 = bitWordValue left * bitWordValue right := by + induction left with + | nil => simp [bitMulWithWork, bitWordValue] + | cons bit bits ih => + cases bit <;> simp [bitMulWithWork, bitWordValue, bitAddWithWork_value, ih] <;> ring + +theorem bitMulWithWork_length (left right : List Bool) : + (bitMulWithWork left right).1.length ≤ 2 * left.length + right.length + 1 := by + induction left with + | nil => simp [bitMulWithWork] + | cons bit bits ih => + cases bit + · simp only [bitMulWithWork, Bool.false_eq_true, ↓reduceIte, List.length_cons] + omega + · simp only [bitMulWithWork, ↓reduceIte, List.length_cons] + have h := bitAddWithWork_length (false :: (bitMulWithWork bits right).1) right false + simp only [List.length_cons] at h + omega + +theorem bitMulWithWork_cost (left right : List Bool) : + (bitMulWithWork left right).2 ≤ 20 * (left.length + 1) * (left.length + right.length + 1) := by + induction left with + | nil => simp [bitMulWithWork]; omega + | cons bit bits ih => + have hlength := bitMulWithWork_length bits right + have hadd := bitAddWithWork_cost (false :: (bitMulWithWork bits right).1) right false + simp only [List.length_cons] at hadd + cases bit + · simp only [bitMulWithWork, Bool.false_eq_true, ↓reduceIte, List.length_cons] + nlinarith only [ih] + · simp only [bitMulWithWork, ↓reduceIte, List.length_cons] + nlinarith only [ih, hlength, hadd] + + + +theorem binaryNaturalMulWithWork_value (a b : ℕ) : + bitWordValue (binaryNaturalMulWithWork a b).1 = a * b := by + simp [binaryNaturalMulWithWork, bitMulWithWork_value, bitWordValue_bits] + +theorem binaryNaturalMulWithWork_cost (a b : ℕ) : + (binaryNaturalMulWithWork a b).2 ≤ 20 * (Nat.size a + 1) * (Nat.size a + Nat.size b + 1) := by + simpa only [binaryNaturalMulWithWork, Nat.size_eq_bits_len] using bitMulWithWork_cost a.bits b.bits + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryBandAction.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryBandAction.lean new file mode 100644 index 0000000000000000000000000000000000000000..be8c4a412f6f2010b1b8b2f962db9384046110f7 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryBandAction.lean @@ -0,0 +1,249 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryActionSelection +import OAI.Combinatorics.EditApproximation.Binary.BinaryActualBandOptimizer + +namespace OAI + +/-! Materialized Boolean vertices retain their band labels. The resulting +selected action, including every tie, is the action used by the online +sampler in the accuracy development. -/ + +namespace EditApproximation +namespace BinaryFraction + +def labeledBandVerticesWithWork {M d : ℕ} {σ : Type*} [DecidableEq σ] + (coordinates : Vector (Fin M × σ) d) (mass : Vector BinaryFraction M) + (band : List (Fin M → σ)) : List ((Fin M → σ) × Vector BinaryFraction d) × ℕ := + let total := bandMassTotalWithWork mass + let vertices := band.map fun action => + let vertex := vectorMapWithWork d fun i => + bandCoordinateWithWork mass total.1 action (coordinates.get i) + ((action, vertex.1), vertex.2) + (vertices.map Prod.fst, total.2 + (vertices.map Prod.snd).sum + 8 * band.length) + +theorem labeledBandVerticesWithWork_vectors {M d : ℕ} {σ : Type*} [DecidableEq σ] + (coordinates : Vector (Fin M × σ) d) (mass : Vector BinaryFraction M) + (band : List (Fin M → σ)) : + (labeledBandVerticesWithWork coordinates mass band).1.map Prod.snd = + (bandVerticesWithWork coordinates mass band).1 := by + simp only [labeledBandVerticesWithWork, bandVerticesWithWork, List.map_map, Function.comp_def] + +theorem labeledBandVerticesWithWork_values {M d : ℕ} {σ : Type*} [DecidableEq σ] + (coordinates : Vector (Fin M × σ) d) (mass : Vector BinaryFraction M) + (band : List (Fin M → σ)) : + (labeledBandVerticesWithWork coordinates mass band).1.map + (fun pair => (pair.1, pair.2.map value)) = + band.map (fun action => (action, + restrictOptimizerVector coordinates (actionVector (fun j => (mass.get j).value) action))) := by + simp only [labeledBandVerticesWithWork, List.map_map, Function.comp_def] + apply List.map_congr_left + intro action _ + apply Prod.ext + · rfl + apply Vector.ext + intro i hi + simp only [Vector.getElem_map] + change ((vectorMapWithWork (α := BinaryFraction) d _).1.get ⟨i, hi⟩).value = + (restrictOptimizerVector coordinates (actionVector (fun j => (mass.get j).value) action)).get ⟨i, hi⟩ + rw [vectorMapWithWork_value, bandCoordinateWithWork_value, restrictOptimizerVector_get] + +theorem labeledBandVerticesWithWork_cost {M d : ℕ} {σ : Type*} [DecidableEq σ] + (coordinates : Vector (Fin M × σ) d) (mass : Vector BinaryFraction M) + (band : List (Fin M → σ)) : + (labeledBandVerticesWithWork coordinates mass band).2 = + (bandVerticesWithWork coordinates mass band).2 + 2 * band.length := by + simp only [labeledBandVerticesWithWork, bandVerticesWithWork, List.map_map, Function.comp_def] + omega + +def preparedBandActionWithWork {M : ℕ} {σ : Type*} [DecidableEq σ] + (mass : Vector BinaryFraction M) (table : ℕ → Fin M × σ → BinaryFraction) + (eta kappa : BinaryFraction) (band : List (Fin M → σ)) (G j t : ℕ) : + Option (Fin M → σ) × ℕ := + let coordinates := listedBandCoordinateVector band + let vertices := labeledBandVerticesWithWork coordinates mass band + let linear := vectorMapWithWork _ fun i => + onlineLinearWithWork (fun j => mass.get j) table eta kappa t (coordinates.get i) + let selected := selectionWithWork vertices.1 linear.1 G j + (selected.1, vertices.2 + linear.2 + selected.2 + 2) + +theorem preparedBandActionWithWork_value {M : ℕ} {σ : Type*} [DecidableEq σ] + (mass : Vector BinaryFraction M) (table : ℕ → Fin M × σ → BinaryFraction) + (eta kappa : BinaryFraction) (band : List (Fin M → σ)) (hband : band ≠ []) (G j t : ℕ) : + (preparedBandActionWithWork mass table eta kappa band G j t).1.getD (band.head hband) = + finiteOptimizerAction band hband (fun i => (mass.get i).value) + (rationalOnlineLinear eta.value kappa.value + (childGain (fun i => (mass.get i).value) (fun s i => (table s i).value)) + (childDecrement (fun i => (mass.get i).value) (fun s i => (table s i).value)) t) G j := by + let coordinates := listedBandCoordinateVector band + let linear := rationalOnlineLinear eta.value kappa.value + (childGain (fun i => (mass.get i).value) (fun s i => (table s i).value)) + (childDecrement (fun i => (mass.get i).value) (fun s i => (table s i).value)) t + have hl : (vectorMapWithWork _ (fun i => onlineLinearWithWork + (fun k => mass.get k) table eta kappa t (coordinates.get i))).1.map value = + restrictOptimizerVector coordinates linear := by + apply Vector.ext + intro i hi + simp only [Vector.getElem_map] + change ((vectorMapWithWork (α := BinaryFraction) _ _).1.get ⟨i, hi⟩).value = + (restrictOptimizerVector coordinates linear).get ⟨i, hi⟩ + rw [vectorMapWithWork_value, onlineLinearWithWork_value, restrictOptimizerVector_get] + change (selectionWithWork (labeledBandVerticesWithWork coordinates mass band).1 + (vectorMapWithWork _ (fun i => onlineLinearWithWork + (fun k => mass.get k) table eta kappa t (coordinates.get i))).1 G j).1.getD _ = _ + rw [selectionWithWork_value, labeledBandVerticesWithWork_values, hl] + exact materializedBandActionWithWork_value band hband (fun i => (mass.get i).value) linear G j + +def preparedBandActionBitBudget (M d vertices G K t Be Bk Bm Bt E : ℕ) : ℕ := + bandPreparationBitBudget M d vertices Bm + 2 * vertices + + d * (onlineLinearBitBudget Be Bk Bm Bt t + 6) + + selectionBitBudget d vertices G K (bandVertexWordBudget M Bm) (bandVertexWordBudget M Bm) + (onlineLinearStorageBudget Be Bk Bm Bt t) (E * (2 * t + 1)) + 2 + +theorem preparedBandActionWithWork_cost {M : ℕ} {σ : Type*} [DecidableEq σ] + (mass : Vector BinaryFraction M) (table : ℕ → Fin M × σ → BinaryFraction) + (eta kappa : BinaryFraction) (band : List (Fin M → σ)) (G K t Be Bk Bm Bt E : ℕ) + (hband : band ≠ []) (he : eta.width ≤ Be) (hk : kappa.width ≤ Bk) + (hm : ∀ j, (mass.get j).width ≤ Bm) (hmpos : ∀ j, 0 < (mass.get j).value) + (ht : ∀ s ≤ t + 1, ∀ i : Fin (listedBandCoordinates band).length, + (table s ((listedBandCoordinateVector band).get i)).width ≤ Bt) + (heabs : |eta.value| ≤ E) (hkrange : 0 ≤ kappa.value ∧ kappa.value ≤ 1) + (htrange : ∀ s ≤ t + 1, ∀ i : Fin (listedBandCoordinates band).length, + 0 ≤ (table s ((listedBandCoordinateVector band).get i)).value ∧ + (table s ((listedBandCoordinateVector band).get i)).value ≤ + (mass.get ((listedBandCoordinateVector band).get i).1).value) : + (preparedBandActionWithWork mass table eta kappa band G K t).2 ≤ + preparedBandActionBitBudget M (listedBandCoordinates band).length band.length G K t Be Bk Bm Bt E := by + let coordinates := listedBandCoordinateVector band + let vertices := (labeledBandVerticesWithWork coordinates mass band).1 + let linear := (vectorMapWithWork _ fun i => + onlineLinearWithWork (fun j => mass.get j) table eta kappa t (coordinates.get i)).1 + have hlength : vertices.length = band.length := by + simp only [vertices, labeledBandVerticesWithWork, List.length_map] + have hvertices : vertices ≠ [] := by + intro h + rw [h, List.length_nil] at hlength + exact hband (List.length_eq_zero_iff.mp hlength.symm) + have hv (v : (Fin M → σ) × Vector BinaryFraction (listedBandCoordinates band).length) + (hmem : v ∈ vertices) (i : Fin (listedBandCoordinates band).length) := + bandVerticesWithWork_input_bounds coordinates mass band Bm hm hmpos v.2 + (by rw [← labeledBandVerticesWithWork_vectors] + exact List.mem_map.mpr ⟨v, hmem, rfl⟩) i + have hlwidth (i : Fin (listedBandCoordinates band).length) : + (linear.get i).width ≤ onlineLinearStorageBudget Be Bk Bm Bt t := by + simp only [linear, vectorMapWithWork_value] + exact onlineLinearWithWork_storage (fun j => mass.get j) table eta kappa t + (coordinates.get i) Be Bk Bm Bt he hk (hm _) (fun s hs => ht s hs i) + have hlvalue (i : Fin (listedBandCoordinates band).length) : + |(linear.get i).value| ≤ (E * (2 * t + 1) : ℕ) := by + simp only [linear, vectorMapWithWork_value, onlineLinearWithWork_value] + have h := rationalOnlineLinear_abs (fun j => (mass.get j).value) + (fun s j => (table s j).value) eta.value kappa.value t E (coordinates.get i) + heabs (hmpos _) hkrange (fun s hs => htrange s hs i) + simpa only [Nat.cast_mul, Nat.cast_add, Nat.cast_ofNat, Nat.cast_one] using h + have hc := selectionWithWork_cost vertices linear G K (bandVertexWordBudget M Bm) + (bandVertexWordBudget M Bm) (onlineLinearStorageBudget Be Bk Bm Bt t) (E * (2 * t + 1)) + hvertices (fun v hv' i => ⟨(hv v hv' i).1, (hv v hv' i).2.1, (hv v hv' i).2.2.1⟩) + (fun v hv' i => (hv v hv' i).2.2.2) hlwidth hlvalue + rw [hlength] at hc + have hp := bandVerticesWithWork_cost coordinates mass band Bm hm + have hl := vectorMapWithWork_cost_le _ + (fun i => onlineLinearWithWork (fun j => mass.get j) table eta kappa t (coordinates.get i)) + (onlineLinearBitBudget Be Bk Bm Bt t) (fun i => onlineLinearWithWork_cost + (fun j => mass.get j) table eta kappa t (coordinates.get i) Be Bk Bm Bt + he hk (hm _) (fun s hs => ht s hs i)) + change (labeledBandVerticesWithWork coordinates mass band).2 + + (vectorMapWithWork _ (fun i => onlineLinearWithWork (fun j => mass.get j) + table eta kappa t (coordinates.get i))).2 + + (selectionWithWork vertices linear G K).2 + 2 ≤ _ + rw [labeledBandVerticesWithWork_cost] + unfold preparedBandActionBitBudget + omega + +def bandActionWithWork {M ny : ℕ} (b : ℕ) + (initial : Fin M → TargetInterval ny → BinaryFraction) + (table : ℕ → Fin M × TargetInterval ny → BinaryFraction) + (eta kappa : BinaryFraction) (band : List (Fin M → TargetInterval ny)) (G j t : ℕ) : + Option (Fin M → TargetInterval ny) × ℕ := + let mass := envelopeVectorWithWork b band initial + let selected := preparedBandActionWithWork mass.1 table eta kappa band G j t + (selected.1, mass.2 + selected.2 + 1) + +theorem bandActionWithWork_value {M ny : ℕ} (b : ℕ) + (initial : Fin M → TargetInterval ny → BinaryFraction) + (table : ℕ → Fin M × TargetInterval ny → BinaryFraction) + (eta kappa : BinaryFraction) (band : List (Fin M → TargetInterval ny)) + (hband : band ≠ []) (G j t : ℕ) (hb : 0 < b) : + (bandActionWithWork b initial table eta kappa band G j t).1.getD (band.head hband) = + finiteOptimizerAction band hband (bandChildEnvelope b band (fun i q => (initial i q).value)) + (rationalOnlineLinear eta.value kappa.value + (childGain (bandChildEnvelope b band (fun i q => (initial i q).value)) + (fun s i => (table s i).value)) + (childDecrement (bandChildEnvelope b band (fun i q => (initial i q).value)) + (fun s i => (table s i).value)) t) G j := by + change (preparedBandActionWithWork (envelopeVectorWithWork b band initial).1 + table eta kappa band G j t).1.getD _ = _ + rw [preparedBandActionWithWork_value] + have hm : (fun i => ((envelopeVectorWithWork b band initial).1.get i).value) = + bandChildEnvelope b band (fun i q => (initial i q).value) := by + funext i + exact envelopeVectorWithWork_value b band initial hb i + rw [hm] + +def bandActionBitBudget (M d b vertices G K t Be Bk Bi Bt E : ℕ) : ℕ := + M * (bandEnvelopeBitBudget b M vertices Bi + 6) + + preparedBandActionBitBudget M d vertices G K t Be Bk + (3 * bandEnvelopeWordBudget b M Bi + 1) Bt E + 1 + +theorem bandActionWithWork_cost {M ny : ℕ} (b : ℕ) + (initial : Fin M → TargetInterval ny → BinaryFraction) + (table : ℕ → Fin M × TargetInterval ny → BinaryFraction) + (eta kappa : BinaryFraction) (band : List (Fin M → TargetInterval ny)) + (G K t Be Bk Bi Bt E : ℕ) (hband : band ≠ []) (hb : 0 < b) (hM : 0 < M) + (he : eta.width ≤ Be) (hk : kappa.width ≤ Bk) + (hi : ∀ action ∈ band, ∀ j, (initial j (action j)).width ≤ Bi) + (ht : ∀ s ≤ t + 1, ∀ i : Fin (listedBandCoordinates band).length, + (table s ((listedBandCoordinateVector band).get i)).width ≤ Bt) + (heabs : |eta.value| ≤ E) (hkrange : 0 ≤ kappa.value ∧ kappa.value ≤ 1) + (htrange : ∀ s ≤ t + 1, ∀ i : Fin (listedBandCoordinates band).length, + 0 ≤ (table s ((listedBandCoordinateVector band).get i)).value ∧ + (table s ((listedBandCoordinateVector band).get i)).value ≤ + (initial ((listedBandCoordinateVector band).get i).1 + ((listedBandCoordinateVector band).get i).2).value) : + (bandActionWithWork b initial table eta kappa band G K t).2 ≤ + bandActionBitBudget M (listedBandCoordinates band).length b band.length G K t Be Bk Bi Bt E := by + let coordinates := listedBandCoordinateVector band + let mass := (envelopeVectorWithWork b band initial).1 + have hmv (j : Fin M) : (mass.get j).value = + bandChildEnvelope b band (fun k q => (initial k q).value) j := + envelopeVectorWithWork_value b band initial hb j + have hm (j : Fin M) : (mass.get j).width ≤ 3 * bandEnvelopeWordBudget b M Bi + 1 := by + simp only [mass, envelopeVectorWithWork, vectorMapWithWork_value] + exact bandEnvelopeWithWork_width b band initial j Bi (fun action ha => hi action ha j) + have hmpos (j : Fin M) : 0 < (mass.get j).value := by + rw [hmv] + exact lt_of_lt_of_le (div_pos (by exact_mod_cast hb) (by exact_mod_cast hM)) + (bandChildEnvelope_lower b band (fun j q => (initial j q).value) j).1 + have hnormalized (s : ℕ) (hs : s ≤ t + 1) (i : Fin (listedBandCoordinates band).length) : + 0 ≤ (table s (coordinates.get i)).value ∧ + (table s (coordinates.get i)).value ≤ (mass.get (coordinates.get i).1).value := by + refine ⟨(htrange s hs i).1, ?_⟩ + obtain ⟨action, ha, heq⟩ := listedBandCoordinateVector_coverage band i + have henv := (bandChildEnvelope_lower b band (fun j q => (initial j q).value) + (coordinates.get i).1).2 action ha + rw [heq] at henv + rw [hmv] + exact (htrange s hs i).2.trans henv + have hp := preparedBandActionWithWork_cost mass table eta kappa band G K t + Be Bk (3 * bandEnvelopeWordBudget b M Bi + 1) Bt E hband he hk hm hmpos ht heabs hkrange hnormalized + have hc := vectorMapWithWork_cost_le M (bandEnvelopeWithWork b band initial) + (bandEnvelopeBitBudget b M band.length Bi) + (fun j => bandEnvelopeWithWork_cost b band initial j Bi (fun action ha => hi action ha j)) + change (envelopeVectorWithWork b band initial).2 + + (preparedBandActionWithWork mass table eta kappa band G K t).2 + 1 ≤ _ + change (envelopeVectorWithWork b band initial).2 ≤ _ at hc + unfold bandActionBitBudget + omega + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryBandActionReads.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryBandActionReads.lean new file mode 100644 index 0000000000000000000000000000000000000000..2929cd18f90fe891fb487a0862974926e10acbad --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryBandActionReads.lean @@ -0,0 +1,199 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryOnlineReads +import OAI.Combinatorics.EditApproximation.Binary.BinaryBandAction +import OAI.Combinatorics.EditApproximation.Binary.BinaryCoordinateAction +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! The actual labelled online action, with charged initial and history reads. -/ + +namespace EditApproximation +namespace BinaryFraction + +def preparedBandActionReadWithWork {M : ℕ} {σ : Type*} [DecidableEq σ] + (mass : Vector BinaryFraction M) (read : ℕ → Fin M × σ → BinaryFraction × ℕ) + (eta kappa : BinaryFraction) (band : List (Fin M → σ)) (G j t : ℕ) : + Option (Fin M → σ) × ℕ := + let coordinates := listedBandCoordinateVector band + let vertices := labeledBandVerticesWithWork coordinates mass band + let linear := vectorMapWithWork _ fun i => + onlineLinearReadWithWork (fun j => mass.get j) read eta kappa t (coordinates.get i) + let selected := selectionWithWork vertices.1 linear.1 G j + (selected.1, vertices.2 + linear.2 + selected.2 + 2) + +theorem preparedBandActionReadWithWork_eq_cost {M : ℕ} {σ : Type*} [DecidableEq σ] + (mass : Vector BinaryFraction M) (read : ℕ → Fin M × σ → BinaryFraction × ℕ) + (eta kappa : BinaryFraction) (band : List (Fin M → σ)) (G j t R : ℕ) + (hr : ∀ s ≤ t + 1, ∀ i : Fin (listedBandCoordinates band).length, + (read s ((listedBandCoordinateVector band).get i)).2 ≤ R) : + (preparedBandActionReadWithWork mass read eta kappa band G j t).1 = + (preparedBandActionWithWork mass (fun s i => (read s i).1) eta kappa band G j t).1 ∧ + (preparedBandActionReadWithWork mass read eta kappa band G j t).2 ≤ + (preparedBandActionWithWork mass (fun s i => (read s i).1) eta kappa band G j t).2 + + (listedBandCoordinates band).length * ((3 * t + 1) * R) := by + have hl := vectorMapWithWork_extra (listedBandCoordinates band).length + (fun i => onlineLinearReadWithWork (fun j => mass.get j) read eta kappa t + ((listedBandCoordinateVector band).get i)) + (fun i => onlineLinearWithWork (fun j => mass.get j) (fun s k => (read s k).1) eta kappa t + ((listedBandCoordinateVector band).get i)) + ((3 * t + 1) * R) + (fun i => (onlineLinearReadWithWork_eq_cost _ read eta kappa t _ R + (fun s hs => hr s hs i)).1) + (fun i => (onlineLinearReadWithWork_eq_cost _ read eta kappa t _ R + (fun s hs => hr s hs i)).2) + unfold preparedBandActionReadWithWork preparedBandActionWithWork + dsimp only + rw [hl.1] + exact ⟨rfl, by omega⟩ + +def bandActionReadWithWork {M n : ℕ} (b : ℕ) + (initial : Fin M → TargetInterval n → BinaryFraction × ℕ) + (read : ℕ → Fin M × TargetInterval n → BinaryFraction × ℕ) + (eta kappa : BinaryFraction) (band : List (Fin M → TargetInterval n)) (G j t : ℕ) : + Option (Fin M → TargetInterval n) × ℕ := + let mass := envelopeVectorReadWithWork b band initial + let selected := preparedBandActionReadWithWork mass.1 read eta kappa band G j t + (selected.1, mass.2 + selected.2 + 1) + +theorem bandActionReadWithWork_eq_cost {M n : ℕ} (b : ℕ) + (initial : Fin M → TargetInterval n → BinaryFraction × ℕ) + (read : ℕ → Fin M × TargetInterval n → BinaryFraction × ℕ) + (eta kappa : BinaryFraction) (band : List (Fin M → TargetInterval n)) (G j t R C : ℕ) + (hi : ∀ i q, (initial i q).2 ≤ C) + (hr : ∀ s ≤ t + 1, ∀ i : Fin (listedBandCoordinates band).length, + (read s ((listedBandCoordinateVector band).get i)).2 ≤ R) : + (bandActionReadWithWork b initial read eta kappa band G j t).1 = + (bandActionWithWork b (fun i q => (initial i q).1) + (fun s i => (read s i).1) eta kappa band G j t).1 ∧ + (bandActionReadWithWork b initial read eta kappa band G j t).2 ≤ + (bandActionWithWork b (fun i q => (initial i q).1) + (fun s i => (read s i).1) eta kappa band G j t).2 + + M * (band.length * (C + 3)) + + (listedBandCoordinates band).length * ((3 * t + 1) * R) := by + have hm := envelopeVectorReadWithWork_eq_cost b band initial C hi + have hs := preparedBandActionReadWithWork_eq_cost + (envelopeVectorWithWork b band (fun i q => (initial i q).1)).1 read + eta kappa band G j t R hr + unfold bandActionReadWithWork bandActionWithWork + dsimp only + rw [hm.1] + exact ⟨hs.1, by omega⟩ + +def sampledOnlineActionReadWithWork {n M : ℕ} (center : TargetInterval n) (b : ℕ) + (initial : Fin M → TargetInterval n → BinaryFraction × ℕ) + (read : ℕ → Fin M × TargetInterval n → BinaryFraction × ℕ) + (eta kappa : BinaryFraction) (band : List (Fin M → TargetInterval n)) (hne : band ≠ []) + (G K t : ℕ) (integer : Fin (optimizerTriangularMass K)) : + BinaryBellmanAction (TargetInterval n) (Fin M × TargetInterval n) M × ℕ := + let chosen := triangularChoiceWithWork K integer + let selected := bandActionReadWithWork b initial read eta kappa band G chosen.1.val t + let states := selected.1.getD (band.head hne) + (⟨center, zero, fun i => (i, states i)⟩, chosen.2 + selected.2 + M + 2) + +theorem sampledOnlineActionReadWithWork_eq_cost {n M : ℕ} (center : TargetInterval n) (b : ℕ) + (initial : Fin M → TargetInterval n → BinaryFraction × ℕ) + (read : ℕ → Fin M × TargetInterval n → BinaryFraction × ℕ) + (eta kappa : BinaryFraction) (band : List (Fin M → TargetInterval n)) (hne : band ≠ []) + (G K t R C : ℕ) (integer : Fin (optimizerTriangularMass K)) + (hi : ∀ i q, (initial i q).2 ≤ C) + (hr : ∀ s ≤ t + 1, ∀ i : Fin (listedBandCoordinates band).length, + (read s ((listedBandCoordinateVector band).get i)).2 ≤ R) : + (sampledOnlineActionReadWithWork center b initial read eta kappa band hne G K t integer).1 = + (sampledOnlineActionWithWork center b (fun i q => (initial i q).1) + (fun s i => (read s i).1) eta kappa band hne G K t integer).1 ∧ + (sampledOnlineActionReadWithWork center b initial read eta kappa band hne G K t integer).2 ≤ + (sampledOnlineActionWithWork center b (fun i q => (initial i q).1) + (fun s i => (read s i).1) eta kappa band hne G K t integer).2 + + M * (band.length * (C + 3)) + + (listedBandCoordinates band).length * ((3 * t + 1) * R) := by + have hs := bandActionReadWithWork_eq_cost b initial read eta kappa band G + (triangularChoiceWithWork K integer).1.val t R C hi hr + unfold sampledOnlineActionReadWithWork sampledOnlineActionWithWork + dsimp only + rw [hs.1] + exact ⟨rfl, by omega⟩ + + + + +theorem countedPreparedActionReadWithWork_eq_cost {M n : ℕ} (mass : Vector BinaryFraction M) + (read : ℕ → Fin M × TargetInterval n → BinaryFraction × ℕ) + (eta kappa : BinaryFraction) (band : List (Fin M → TargetInterval n)) (G j t R : ℕ) + (hr : ∀ s ≤ t + 1, ∀ i : Fin (listedBandCoordinates band).length, + (read s ((listedBandCoordinateVector band).get i)).2 ≤ R) : + (countedPreparedActionReadWithWork mass read eta kappa band G j t).1 = + (countedPreparedActionWithWork mass (fun s i => (read s i).1) eta kappa band G j t).1 ∧ + (countedPreparedActionReadWithWork mass read eta kappa band G j t).2 ≤ + (countedPreparedActionWithWork mass (fun s i => (read s i).1) eta kappa band G j t).2 + + (listedBandCoordinates band).length * ((3 * t + 1) * R) := by + have hl := vectorMapWithWork_extra (listedBandCoordinates band).length + (fun i => onlineLinearReadWithWork (fun j => mass.get j) read eta kappa t + ((listedBandCoordinateVector band).get i)) + (fun i => onlineLinearWithWork (fun j => mass.get j) (fun s k => (read s k).1) eta kappa t + ((listedBandCoordinateVector band).get i)) + ((3 * t + 1) * R) + (fun i => (onlineLinearReadWithWork_eq_cost _ read eta kappa t _ R + (fun s hs => hr s hs i)).1) + (fun i => (onlineLinearReadWithWork_eq_cost _ read eta kappa t _ R + (fun s hs => hr s hs i)).2) + unfold countedPreparedActionReadWithWork countedPreparedActionWithWork + simp only [coordinateVectorWithWork_value] + rw [hl.1] + exact ⟨rfl, by omega⟩ + + + +theorem countedBandActionReadWithWork_eq_cost {M n : ℕ} (b : ℕ) + (initial : Fin M → TargetInterval n → BinaryFraction × ℕ) + (read : ℕ → Fin M × TargetInterval n → BinaryFraction × ℕ) + (eta kappa : BinaryFraction) (band : List (Fin M → TargetInterval n)) (G j t R C : ℕ) + (hi : ∀ i q, (initial i q).2 ≤ C) + (hr : ∀ s ≤ t + 1, ∀ i : Fin (listedBandCoordinates band).length, + (read s ((listedBandCoordinateVector band).get i)).2 ≤ R) : + (countedBandActionReadWithWork b initial read eta kappa band G j t).1 = + (countedBandActionWithWork b (fun i q => (initial i q).1) + (fun s i => (read s i).1) eta kappa band G j t).1 ∧ + (countedBandActionReadWithWork b initial read eta kappa band G j t).2 ≤ + (countedBandActionWithWork b (fun i q => (initial i q).1) + (fun s i => (read s i).1) eta kappa band G j t).2 + + M * (band.length * (C + 3)) + + (listedBandCoordinates band).length * ((3 * t + 1) * R) := by + have hm := envelopeVectorReadWithWork_eq_cost b band initial C hi + have hs := countedPreparedActionReadWithWork_eq_cost + (envelopeVectorWithWork b band (fun i q => (initial i q).1)).1 read + eta kappa band G j t R hr + unfold countedBandActionReadWithWork countedBandActionWithWork + dsimp only + rw [hm.1] + exact ⟨hs.1, by omega⟩ + + + +theorem countedSampledOnlineReadWithWork_eq_cost {n M : ℕ} (center : TargetInterval n) (b : ℕ) + (initial : Fin M → TargetInterval n → BinaryFraction × ℕ) + (read : ℕ → Fin M × TargetInterval n → BinaryFraction × ℕ) + (eta kappa : BinaryFraction) (band : List (Fin M → TargetInterval n)) (hne : band ≠ []) + (G K t R C : ℕ) (integer : Fin (optimizerTriangularMass K)) + (hi : ∀ i q, (initial i q).2 ≤ C) + (hr : ∀ s ≤ t + 1, ∀ i : Fin (listedBandCoordinates band).length, + (read s ((listedBandCoordinateVector band).get i)).2 ≤ R) : + (countedSampledOnlineReadWithWork center b initial read eta kappa band hne G K t integer).1 = + (countedSampledOnlineWithWork center b (fun i q => (initial i q).1) + (fun s i => (read s i).1) eta kappa band hne G K t integer).1 ∧ + (countedSampledOnlineReadWithWork center b initial read eta kappa band hne G K t integer).2 ≤ + (countedSampledOnlineWithWork center b (fun i q => (initial i q).1) + (fun s i => (read s i).1) eta kappa band hne G K t integer).2 + + M * (band.length * (C + 3)) + + (listedBandCoordinates band).length * ((3 * t + 1) * R) := by + have hs := countedBandActionReadWithWork_eq_cost b initial read eta kappa band G + (triangularChoiceWithWork K integer).1.val t R C hi hr + unfold countedSampledOnlineReadWithWork countedSampledOnlineWithWork + dsimp only + rw [hs.1] + exact ⟨rfl, by omega⟩ + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryBandCoordinates.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryBandCoordinates.lean new file mode 100644 index 0000000000000000000000000000000000000000..5ce9e830f9d75a9afb37efd7851c1dc3ddfbec32 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryBandCoordinates.lean @@ -0,0 +1,139 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryRoundedWork +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Materialization of the online coordinate array includes its equality +tests and duplicate-removal scan. Endpoints and child indices are compared +by the verified binary natural comparator. -/ + +namespace EditApproximation + + + +@[simp] theorem coordinateEqualWithWork_value {M n : ℕ} (a b : Fin M × TargetInterval n) : + (coordinateEqualWithWork a b).1 = true ↔ a = b := by + simp only [coordinateEqualWithWork, Bool.and_eq_true, naturalEqualWithWork_value] + constructor + · rintro ⟨⟨hc, hl⟩, hh⟩ + have hi : a.1 = b.1 := Fin.ext hc + have hq : a.2 = b.2 := by + rcases a with ⟨i, q⟩ + rcases b with ⟨j, r⟩ + cases q + cases r + cases hl + cases hh + rfl + exact Prod.ext hi hq + · intro h + subst b + exact ⟨⟨rfl, rfl⟩, rfl⟩ + +theorem coordinateEqualWithWork_cost {M n : ℕ} (a b : Fin M × TargetInterval n) + (B : ℕ) (hM : Nat.size M ≤ B) (hn : Nat.size n ≤ B) : + (coordinateEqualWithWork a b).2 ≤ 24 * B + 8 := by + have hc := naturalEqualWithWork_cost a.1.val b.1.val B + ((Nat.size_le_size a.1.isLt.le).trans hM) ((Nat.size_le_size b.1.isLt.le).trans hM) + have hl := naturalEqualWithWork_cost a.2.lo b.2.lo B + ((Nat.size_le_size (a.2.ordered.trans a.2.valid)).trans hn) + ((Nat.size_le_size (b.2.ordered.trans b.2.valid)).trans hn) + have hh := naturalEqualWithWork_cost a.2.hi b.2.hi B + ((Nat.size_le_size a.2.valid).trans hn) ((Nat.size_le_size b.2.valid).trans hn) + change _ + _ + _ + 2 ≤ _ + omega + + + +theorem memberByWithWork_value {α : Type*} (equal : α → α → Bool × ℕ) + (heq : ∀ a b, (equal a b).1 = true ↔ a = b) (a : α) (xs : List α) : + (memberByWithWork equal a xs).1 = true ↔ a ∈ xs := by + induction xs with + | nil => simp only [memberByWithWork, Bool.false_eq_true, List.not_mem_nil] + | cons b xs ih => simp only [memberByWithWork, Bool.or_eq_true, heq, ih, List.mem_cons] + +theorem memberByWithWork_cost {α : Type*} (equal : α → α → Bool × ℕ) + (C : ℕ) (hC : ∀ a b, (equal a b).2 ≤ C) (a : α) (xs : List α) : + (memberByWithWork equal a xs).2 ≤ 1 + xs.length * (C + 1) := by + induction xs with + | nil => simp only [memberByWithWork, List.length_nil, Nat.zero_mul, Nat.add_zero, le_refl] + | cons b xs ih => + have h := hC a b + change _ + _ + 1 ≤ _ + simp only [List.length_cons, Nat.add_mul, Nat.one_mul] + omega + + + +theorem dedupByWithWork_value {α : Type*} [DecidableEq α] (equal : α → α → Bool × ℕ) + (heq : ∀ a b, (equal a b).1 = true ↔ a = b) (xs : List α) : + (dedupByWithWork equal xs).1 = xs.dedup := by + induction xs with + | nil => rfl + | cons a rest ih => + have hm := memberByWithWork_value equal heq a rest + have ht : (memberByWithWork equal a rest).1 = decide (a ∈ rest) := + Bool.eq_iff_iff.mpr (by simpa only [decide_eq_true_eq] using hm) + simp only [dedupByWithWork, ht, ih, List.dedup_cons, decide_eq_true_eq] + +theorem dedupByWithWork_cost {α : Type*} (equal : α → α → Bool × ℕ) + (C : ℕ) (hC : ∀ a b, (equal a b).2 ≤ C) (xs : List α) : + (dedupByWithWork equal xs).2 ≤ (xs.length + 1) ^ 2 * (C + 4) := by + induction xs with + | nil => simp only [dedupByWithWork, List.length_nil]; nlinarith + | cons a rest ih => + have hm := memberByWithWork_cost equal C hC a rest + change _ + _ + 2 ≤ _ + simp only [List.length_cons] + nlinarith only [ih, hm, Nat.zero_le C, Nat.zero_le rest.length] + +namespace BinaryFraction + + + +@[simp] theorem bandCoordinatesWithWork_value {M n : ℕ} (band : List (Fin M → TargetInterval n)) : + (bandCoordinatesWithWork band).1 = listedBandCoordinates band := by + simp only [bandCoordinatesWithWork, dedupByWithWork_value _ coordinateEqualWithWork_value, + arithmeticFlatMapWithWork_value, arithmeticMapWithWork_value, listedBandCoordinates, + List.ofFn_eq_map] + +def bandCoordinatesBitBudget (M vertices B : ℕ) : ℕ := + vertices * (5 * M + 3) + (vertices * M + 1) ^ 2 * (24 * B + 12) + 1 + +theorem bandCoordinatesWithWork_cost {M n : ℕ} (band : List (Fin M → TargetInterval n)) + (B : ℕ) (hM : Nat.size M ≤ B) (hn : Nat.size n ≤ B) : + (bandCoordinatesWithWork band).2 ≤ bandCoordinatesBitBudget M band.length B := by + let raw := arithmeticFlatMapWithWork (fun action : Fin M → TargetInterval n => + arithmeticMapWithWork (fun i : Fin M => ((i, action i), 1)) (List.finRange M)) band + have hlength : raw.1.length = band.length * M := by + dsimp only [raw] + simp only [arithmeticFlatMapWithWork_value, arithmeticMapWithWork_value] + induction band with + | nil => simp + | cons a rest ih => + simp only [List.flatMap_cons, List.length_append, List.length_map, List.length_finRange, + List.length_cons, Nat.add_mul, Nat.one_mul] + omega + have hraw := arithmeticFlatMapWithWork_cost + (fun action : Fin M → TargetInterval n => + arithmeticMapWithWork (fun i : Fin M => ((i, action i), 1)) (List.finRange M)) + band (4 * M) M (by + intro action _ + have h := arithmeticMapWithWork_cost + (fun i : Fin M => ((i, action i), 1)) (List.finRange M) 1 (by intros; rfl) + simpa only [List.length_finRange, Nat.mul_comm] using h) (by + intro action _ + simp only [arithmeticMapWithWork_value, List.length_map, List.length_finRange, le_refl]) + change raw.2 ≤ _ at hraw + have hunique := dedupByWithWork_cost coordinateEqualWithWork (24 * B + 8) + (fun a b => coordinateEqualWithWork_cost a b B hM hn) raw.1 + rw [hlength] at hunique + change raw.2 + (dedupByWithWork coordinateEqualWithWork raw.1).2 + 1 ≤ _ + unfold bandCoordinatesBitBudget + nlinarith only [hraw, hunique] + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryBandEnvelope.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryBandEnvelope.lean new file mode 100644 index 0000000000000000000000000000000000000000..29dc353709d14ed6cdeff62c0a9cc84fcc14be03 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryBandEnvelope.lean @@ -0,0 +1,175 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryDyadicCeiling +import OAI.Combinatorics.EditApproximation.Binary.BinaryOnlineInputs +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Literal Boolean construction of the child envelope of a finite band. +It scans the actual child values, compares with `b/M`, and runs the exact +bounded dyadic scan. Table reads are accounted for by the query program. -/ + +namespace EditApproximation +namespace BinaryFraction + + + +theorem maxWithWork_value (a b : BinaryFraction) : + (maxWithWork a b).1.value = max a.value b.value := by + by_cases h : a.value < b.value + · simp only [maxWithWork, (ltWithWork_value a b).mpr h, ↓reduceIte, max_eq_right h.le] + · have hb : (a.ltWithWork b).1 = false := Bool.eq_false_iff.mpr (fun hh => h ((ltWithWork_value a b).mp hh)) + simp only [maxWithWork, hb, Bool.false_eq_true, ↓reduceIte, max_eq_left (le_of_not_gt h)] + +theorem maxWithWork_width (a b : BinaryFraction) : + (maxWithWork a b).1.width ≤ max a.width b.width := by + unfold maxWithWork + dsimp only + split_ifs + · exact le_max_right _ _ + · exact le_max_left _ _ + +theorem maxWithWork_cost (a b : BinaryFraction) (B : ℕ) (ha : a.width ≤ B) (hb : b.width ≤ B) : + (maxWithWork a b).2 ≤ 1000 * (B + 1) ^ 2 + 1 := + Nat.add_le_add_right (ltWithWork_cost a b B ha hb) 1 + + + +theorem maximumWithWork_value (fallback : BinaryFraction) (values : List BinaryFraction) : + (maximumWithWork fallback values).1.value = rationalMaximum fallback.value (values.map value) := by + induction values with + | nil => rfl + | cons head rest ih => + simp only [maximumWithWork, maxWithWork_value, ih, List.map_cons, rationalMaximum] + +theorem maximumWithWork_width (fallback : BinaryFraction) (values : List BinaryFraction) + (B : ℕ) (hf : fallback.width ≤ B) (hvalues : ∀ a ∈ values, a.width ≤ B) : + (maximumWithWork fallback values).1.width ≤ B := by + induction values with + | nil => exact hf + | cons head rest ih => + exact (maxWithWork_width head (maximumWithWork fallback rest).1).trans + (max_le (hvalues head List.mem_cons_self) (ih (fun a ha => hvalues a (List.mem_cons_of_mem _ ha)))) + +theorem maximumWithWork_cost (fallback : BinaryFraction) (values : List BinaryFraction) + (B : ℕ) (hf : fallback.width ≤ B) (hvalues : ∀ a ∈ values, a.width ≤ B) : + (maximumWithWork fallback values).2 ≤ 1 + values.length * (1000 * (B + 1) ^ 2 + 2) := by + induction values with + | nil => simp [maximumWithWork] + | cons head rest ih => + have htail := ih (fun a ha => hvalues a (List.mem_cons_of_mem _ ha)) + have hw := maximumWithWork_width fallback rest B hf (fun a ha => hvalues a (List.mem_cons_of_mem _ ha)) + have hc := maxWithWork_cost head (maximumWithWork fallback rest).1 B + (hvalues head List.mem_cons_self) hw + change (maximumWithWork fallback rest).2 + (maxWithWork head (maximumWithWork fallback rest).1).2 + 1 ≤ _ + simp only [List.length_cons] + rw [Nat.add_mul, Nat.one_mul] + omega + +def bandEnvelopeWithWork {M ny : ℕ} (b : ℕ) + (band : List (Fin M → TargetInterval ny)) + (initial : Fin M → TargetInterval ny → BinaryFraction) (i : Fin M) : BinaryFraction × ℕ := + let floor := divWithWork (nat b) (nat M) + let maximum := maximumWithWork zero (band.map fun action => initial i (action i)) + let input := maxWithWork floor.1 maximum.1 + let result := dyadicCeilingWithWork input.1 + (result.1, floor.2 + maximum.2 + input.2 + result.2 + band.length + 4) + +theorem bandEnvelopeWithWork_value {M ny : ℕ} (b : ℕ) + (band : List (Fin M → TargetInterval ny)) + (initial : Fin M → TargetInterval ny → BinaryFraction) (i : Fin M) + (hb : 0 < b) : + (bandEnvelopeWithWork b band initial i).1.value = + bandChildEnvelope b band (fun j q => (initial j q).value) i := by + have hM : 0 < M := Nat.pos_of_ne_zero (fun h => by cases h; exact Fin.elim0 i) + have hfloor : (divWithWork (nat b) (nat M)).1.value = (b : ℚ) / M := by + rw [divWithWork_value, ← representation_value (nat b), nat_representation, + UnreducedRational.value_nat, ← representation_value (nat M), nat_representation, + UnreducedRational.value_nat] + have hp : 0 < (maxWithWork (divWithWork (nat b) (nat M)).1 + (maximumWithWork zero (band.map fun action => initial i (action i))).1).1.value := by + rw [maxWithWork_value, hfloor] + exact lt_of_lt_of_le (div_pos (by exact_mod_cast hb) (by exact_mod_cast hM)) (le_max_left _ _) + change (dyadicCeilingWithWork _).1.value = _ + rw [dyadicCeilingWithWork_value _ hp, maxWithWork_value, hfloor, maximumWithWork_value] + simp only [zero_representation, ← representation_value zero, UnreducedRational.value_zero, + List.map_map, Function.comp_def, bandChildEnvelope] + +def bandEnvelopeWordBudget (b M B : ℕ) : ℕ := B + Nat.size b + Nat.size M + 8 + +theorem bandEnvelopeWithWork_width {M ny : ℕ} (b : ℕ) + (band : List (Fin M → TargetInterval ny)) + (initial : Fin M → TargetInterval ny → BinaryFraction) (i : Fin M) + (B : ℕ) (hbits : ∀ action ∈ band, (initial i (action i)).width ≤ B) : + (bandEnvelopeWithWork b band initial i).1.width ≤ 3 * bandEnvelopeWordBudget b M B + 1 := by + let W := bandEnvelopeWordBudget b M B + have hfloor := divWithWork_self_width (nat b) (nat M) + rw [divWithWork_representation, nat_representation, nat_representation] at hfloor + have hf := UnreducedRational.storageBits_div (UnreducedRational.nat b) (UnreducedRational.nat M) + simp only [UnreducedRational.storageBits_nat] at hf + have hfW : (divWithWork (nat b) (nat M)).1.width ≤ W := by + dsimp only [W, bandEnvelopeWordBudget] + omega + have hmW := maximumWithWork_width zero (band.map fun action => initial i (action i)) W + (by change 1 ≤ W; dsimp only [W, bandEnvelopeWordBudget]; omega) + (by intro a ha; obtain ⟨action, haction, rfl⟩ := List.mem_map.mp ha + exact (hbits action haction).trans (by dsimp only [W, bandEnvelopeWordBudget]; omega)) + have hin := (maxWithWork_width (divWithWork (nat b) (nat M)).1 + (maximumWithWork zero (band.map fun action => initial i (action i))).1).trans (max_le hfW hmW) + have h := dyadicCeilingWithWork_width (maxWithWork (divWithWork (nat b) (nat M)).1 + (maximumWithWork zero (band.map fun action => initial i (action i))).1).1 + change (dyadicCeilingWithWork _).1.width ≤ _ + omega + + +def bandEnvelopeBitBudget (b M size B : ℕ) : ℕ := + let W := bandEnvelopeWordBudget b M B + 2100 * (Nat.size b + Nat.size M + 6) ^ 2 + + (1 + size * (1000 * (W + 1) ^ 2 + 2)) + (1000 * (W + 1) ^ 2 + 1) + + (1 + 2 * W * (1000 * (3 * W + 2) ^ 2 + 2) + 3 * W + 5) + size + 4 + +theorem bandEnvelopeWithWork_cost {M ny : ℕ} (b : ℕ) + (band : List (Fin M → TargetInterval ny)) + (initial : Fin M → TargetInterval ny → BinaryFraction) (i : Fin M) + (B : ℕ) (hbits : ∀ action ∈ band, (initial i (action i)).width ≤ B) : + (bandEnvelopeWithWork b band initial i).2 ≤ bandEnvelopeBitBudget b M band.length B := by + let W := bandEnvelopeWordBudget b M B + let floor := (divWithWork (nat b) (nat M)).1 + let maximum := (maximumWithWork zero (band.map fun action => initial i (action i))).1 + let input := (maxWithWork floor maximum).1 + have hfloor := divWithWork_self_width (nat b) (nat M) + rw [divWithWork_representation, nat_representation, nat_representation] at hfloor + have hf := UnreducedRational.storageBits_div (UnreducedRational.nat b) (UnreducedRational.nat M) + simp only [UnreducedRational.storageBits_nat] at hf + have hfW : floor.width ≤ W := by + dsimp only [W, bandEnvelopeWordBudget] + change floor.width ≤ _ at hfloor + omega + have hmW : maximum.width ≤ W := maximumWithWork_width zero + (band.map fun action => initial i (action i)) W + (by change 1 ≤ W; dsimp only [W, bandEnvelopeWordBudget]; omega) + (by intro a ha; obtain ⟨action, haction, rfl⟩ := List.mem_map.mp ha + exact (hbits action haction).trans (by dsimp only [W, bandEnvelopeWordBudget]; omega)) + have hiW : input.width ≤ W := (maxWithWork_width floor maximum).trans (max_le hfW hmW) + have hfc := divWithWork_cost (nat b) (nat M) (Nat.size b + Nat.size M + 4) + ((nat_width_le b).trans (by omega)) ((nat_width_le M).trans (by omega)) + rw [show Nat.size b + Nat.size M + 4 + 2 = Nat.size b + Nat.size M + 6 by omega] at hfc + have hmc := maximumWithWork_cost zero (band.map fun action => initial i (action i)) W + (by change 1 ≤ W; dsimp only [W, bandEnvelopeWordBudget]; omega) + (by intro a ha; obtain ⟨action, haction, rfl⟩ := List.mem_map.mp ha + exact (hbits action haction).trans (by dsimp only [W, bandEnvelopeWordBudget]; omega)) + simp only [List.length_map] at hmc + have hic := maxWithWork_cost floor maximum W hfW hmW + have hdc := dyadicCeilingWithWork_cost_le input W hiW + change (divWithWork (nat b) (nat M)).2 + + (maximumWithWork zero (band.map fun action => initial i (action i))).2 + + (maxWithWork floor maximum).2 + (dyadicCeilingWithWork input).2 + band.length + 4 ≤ _ + change _ ≤ 2100 * (Nat.size b + Nat.size M + 6) ^ 2 + + (1 + band.length * (1000 * (W + 1) ^ 2 + 2)) + (1000 * (W + 1) ^ 2 + 1) + + (1 + 2 * W * (1000 * (3 * W + 2) ^ 2 + 2) + 3 * W + 5) + band.length + 4 + omega + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryBandGuardWork.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryBandGuardWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..5371435a23962c6ff051335db685f28c1f73fb9f --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryBandGuardWork.lean @@ -0,0 +1,326 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryPrefixWork +import OAI.Combinatorics.EditApproximation.Binary.BinaryAffineGuard +import OAI.Combinatorics.EditApproximation.Refinement.ComputedBands +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Exact finite band predicates evaluated on stored Boolean fractions. +The cut tests use the actual finite prefix minimum; the other tests are +Boolean comparisons of the actual interval endpoints. -/ + +namespace EditApproximation + +open Finset + + + +@[simp] theorem naturalEqualWithWork_value (a b : ℕ) : + (naturalEqualWithWork a b).1 = true ↔ a = b := by + simp only [naturalEqualWithWork, decide_eq_true_eq, binaryNaturalCompareWithWork_eq] + +theorem naturalEqualWithWork_cost (a b B : ℕ) (ha : Nat.size a ≤ B) (hb : Nat.size b ≤ B) : + (naturalEqualWithWork a b).2 ≤ 8 * B + 2 := by + have h := binaryNaturalCompareWithWork_cost a b + change (binaryNaturalCompareWithWork a b).2 + 1 ≤ _ + omega + + + +@[simp] theorem zeroConnectionWithWork_value {n : ℕ} (start finish : ℕ) + (states : List (TargetInterval n)) : + (zeroConnectionWithWork start states finish).1 = true ↔ + connectionBudget start states finish = 0 := by + induction states generalizing start with + | nil => + change (naturalEqualWithWork start finish).1 = true ↔ Nat.dist start finish = 0 + exact (naturalEqualWithWork_value start finish).trans + ⟨Nat.dist_eq_zero, Nat.eq_of_dist_eq_zero⟩ + | cons state rest ih => + change ((naturalEqualWithWork start state.lo).1 && + (zeroConnectionWithWork state.hi rest finish).1) = true ↔ + Nat.dist start state.lo + connectionBudget state.hi rest finish = 0 + rw [Bool.and_eq_true, naturalEqualWithWork_value, ih, Nat.add_eq_zero_iff] + constructor + · rintro ⟨hs, ht⟩ + exact ⟨Nat.dist_eq_zero hs, ht⟩ + · rintro ⟨hs, ht⟩ + exact ⟨Nat.eq_of_dist_eq_zero hs, ht⟩ + +theorem zeroConnectionWithWork_cost {n : ℕ} (start finish : ℕ) + (states : List (TargetInterval n)) (B : ℕ) + (hs : Nat.size start ≤ B) (hf : Nat.size finish ≤ B) + (he : ∀ s ∈ states, Nat.size s.lo ≤ B ∧ Nat.size s.hi ≤ B) : + (zeroConnectionWithWork start states finish).2 ≤ (states.length + 1) * (8 * B + 3) := by + induction states generalizing start with + | nil => + have h := naturalEqualWithWork_cost start finish B hs hf + simpa only [zeroConnectionWithWork, List.length_nil, zero_add, one_mul] using + h.trans (by omega : 8 * B + 2 ≤ 8 * B + 3) + | cons state rest ih => + have hstate := he state List.mem_cons_self + have hc := naturalEqualWithWork_cost start state.lo B hs hstate.1 + have ht := ih state.hi hstate.2 (fun s h => he s (List.mem_cons_of_mem _ h)) + change _ + _ + 1 ≤ _ + simp only [List.length_cons] + rw [show rest.length + 1 + 1 = (rest.length + 1) + 1 by omega, Nat.add_mul, Nat.one_mul] + omega + +/-- Construct a translated endpoint by the actual binary subtract/add routines. -/ + + +@[simp] theorem translatedEndpointWithWork_value (reference root endpoint : ℕ) (h : root ≤ endpoint) : + (translatedEndpointWithWork reference root endpoint).1 = reference + (endpoint - root) := by + simp only [translatedEndpointWithWork, binaryNaturalAddWithWork_value, + binaryNaturalSubtractWithWork_value endpoint root h] + +theorem translatedEndpointWithWork_cost (reference root endpoint B : ℕ) + (h : root ≤ endpoint) (hr : Nat.size reference ≤ B) + (hroot : Nat.size root ≤ B) (he : Nat.size endpoint ≤ B) : + (translatedEndpointWithWork reference root endpoint).2 ≤ 36 * B + 4 := by + have hd := binaryNaturalSubtractWithWork_cost endpoint root + have ha := binaryNaturalAddWithWork_cost reference + (bitWordValue (binaryNaturalSubtractWithWork endpoint root).1) + have hw : Nat.size (bitWordValue (binaryNaturalSubtractWithWork endpoint root).1) ≤ B := by + rw [binaryNaturalSubtractWithWork_value endpoint root h] + exact (Nat.size_le_size (Nat.sub_le endpoint root)).trans he + change _ + _ + 2 ≤ _ + omega + +namespace BinaryFraction + +private theorem nat_dist_cast (a b : ℕ) : (Nat.dist a b : ℚ) = |(a : ℚ) - b| := by + rcases le_total a b with h | h + · rw [Nat.dist_eq_sub_of_le h, Nat.cast_sub h, abs_of_nonpos (sub_nonpos.mpr (by exact_mod_cast h))] + ring + · rw [Nat.dist_eq_sub_of_le_right h, Nat.cast_sub h, abs_of_nonneg (sub_nonneg.mpr (by exact_mod_cast h))] + + + +@[simp] theorem naturalDistanceLeWithWork_value (a b radius : ℕ) : + (naturalDistanceLeWithWork a b radius).1 = true ↔ Nat.dist a b ≤ radius := by + simp only [naturalDistanceLeWithWork, leWithWork_value, distanceWithWork_value, nat_value] + rw [← nat_dist_cast] + constructor <;> intro h <;> exact_mod_cast h + +def naturalDistanceBitBudget (B : ℕ) : ℕ := + 6000 * (B + 1) ^ 2 + 2 + (1000 * (8 * B + 7) ^ 2 + 1) + 3 * B + 3 + +theorem naturalDistanceLeWithWork_cost (a b radius B : ℕ) + (ha : Nat.size a + 2 ≤ B) (hb : Nat.size b + 2 ≤ B) + (hr : Nat.size radius + 2 ≤ B) : + (naturalDistanceLeWithWork a b radius).2 ≤ naturalDistanceBitBudget B := by + have hdw := distanceWithWork_width (nat a) (nat b) B + ((nat_width_le a).trans ha) ((nat_width_le b).trans hb) + have hd := distanceWithWork_cost (nat a) (nat b) B + ((nat_width_le a).trans ha) ((nat_width_le b).trans hb) + have hc := leWithWork_cost (distanceWithWork (nat a) (nat b)).1 (nat radius) + (8 * B + 6) hdw ((nat_width_le radius).trans (by omega)) + simp only [Nat.add_assoc, Nat.reduceAdd] at hc + change _ + _ + Nat.size a + Nat.size b + Nat.size radius + 3 ≤ _ + unfold naturalDistanceBitBudget + omega + +def cutGuardWithWork {nx ny M : ℕ} (parent : TargetInterval nx) + (r : TargetInterval ny) (actions : List (Fin M → TargetInterval ny)) (hne : actions ≠ []) + (child : Fin M → TargetInterval ny → BinaryFraction) (states : Fin M → TargetInterval ny) + (velocity tolerance : BinaryFraction) (j : Fin M) : Bool × ℕ := + if j.val = 0 then (true, 1) else + let shift := subWithWork (nat (states j).lo) (nat (sourceChild parent j).lo) + let offset := subWithWork (nat r.lo) (nat parent.lo) + let prediction := prefixMinimumWithWork parent r actions hne child j.val shift.1 + let result := affineErrorWithWork shift.1 offset.1 velocity prediction.1 tolerance + (result.1, shift.2 + offset.2 + prediction.2 + result.2 + + Nat.size (states j).lo + Nat.size (sourceChild parent j).lo + Nat.size r.lo + Nat.size parent.lo + 5) + +@[simp] theorem cutGuardWithWork_value {nx ny M : ℕ} (parent : TargetInterval nx) + (r : TargetInterval ny) (actions : List (Fin M → TargetInterval ny)) (hne : actions ≠ []) + (child : Fin M → TargetInterval ny → BinaryFraction) (states : Fin M → TargetInterval ny) + (velocity tolerance : BinaryFraction) (j : Fin M) : + (cutGuardWithWork parent r actions hne child states velocity tolerance j).1 = true ↔ + (0 < j.val → |bandCutShift parent states j - ((r.lo : ℚ) - parent.lo) - velocity.value * + rationalWidePrefixMinimum parent r actions hne (fun i q => (child i q).value) + j.val (bandCutShift parent states j)| ≤ tolerance.value) := by + by_cases hj : j.val = 0 + · simp [cutGuardWithWork, hj] + · rw [cutGuardWithWork, ite_eq_right hj] + dsimp only + rw [affineErrorWithWork_value] + simp only [subWithWork_value, nat_value, prefixMinimumWithWork_value, bandCutShift] + constructor + · intro h _ + exact h + · intro h + exact h (Nat.pos_of_ne_zero hj) + +def cutGuardWordBudget (M j B : ℕ) : ℕ := + prefixWordBudget M j (8 * B + 6) + 76 * B + 50 + +def cutGuardBitBudget (M j v B : ℕ) : ℕ := + 2 * (6000 * (B + 1) ^ 2 + 1) + + prefixMinimumBitBudget M j v (8 * B + 6) + + affineGuardBitBudget (cutGuardWordBudget M j B) + 4 * B + 6 + +theorem cutGuardWithWork_cost {nx ny M : ℕ} (parent : TargetInterval nx) + (r : TargetInterval ny) (actions : List (Fin M → TargetInterval ny)) (hne : actions ≠ []) + (child : Fin M → TargetInterval ny → BinaryFraction) (states : Fin M → TargetInterval ny) + (velocity tolerance : BinaryFraction) (j : Fin M) (B : ℕ) + (hvel : velocity.width ≤ B) (htol : tolerance.width ≤ 64 * B + 44) + (hr : Nat.size r.lo + 2 ≤ B) (hp : Nat.size parent.lo + 2 ≤ B) + (hs : Nat.size (states j).lo + 2 ≤ B) + (hc : Nat.size (sourceChild parent j).lo + 2 ≤ B) + (hcut : Nat.size (balancedCut parent.lo (parent.hi - parent.lo) M j.val) + 2 ≤ B) + (hstates : ∀ action ∈ actions, ∀ i, + Nat.size (action i).lo + 2 ≤ B ∧ Nat.size (action i).hi + 2 ≤ B) + (hchild : ∀ action ∈ actions, ∀ i, (child i (action i)).width ≤ B) : + (cutGuardWithWork parent r actions hne child states velocity tolerance j).2 ≤ + cutGuardBitBudget M j.val actions.length B := by + by_cases hj : j.val = 0 + · simp only [cutGuardWithWork, hj, ↓reduceIte] + unfold cutGuardBitBudget + omega + · have hshift := subWithWork_width (nat (states j).lo) (nat (sourceChild parent j).lo) B + ((nat_width_le _).trans hs) ((nat_width_le _).trans hc) + have hoffset := subWithWork_width (nat r.lo) (nat parent.lo) B + ((nat_width_le _).trans hr) ((nat_width_le _).trans hp) + have hshiftCost := subWithWork_cost (nat (states j).lo) (nat (sourceChild parent j).lo) B + ((nat_width_le _).trans hs) ((nat_width_le _).trans hc) + have hoffsetCost := subWithWork_cost (nat r.lo) (nat parent.lo) B + ((nat_width_le _).trans hr) ((nat_width_le _).trans hp) + have hlarge : B ≤ 8 * B + 6 := by omega + obtain ⟨hpred, hpredCost⟩ := prefixMinimumWithWork_bounds parent r actions hne child j.val + (subWithWork (nat (states j).lo) (nat (sourceChild parent j).lo)).1 (8 * B + 6) + hshift (hr.trans hlarge) (hcut.trans hlarge) + (fun action ha i => ⟨(hstates action ha i).1.trans hlarge, + (hstates action ha i).2.trans hlarge⟩) + (fun action ha i => (hchild action ha i).trans hlarge) + have herr := affineErrorWithWork_cost + (subWithWork (nat (states j).lo) (nat (sourceChild parent j).lo)).1 + (subWithWork (nat r.lo) (nat parent.lo)).1 velocity + (prefixMinimumWithWork parent r actions hne child j.val + (subWithWork (nat (states j).lo) (nat (sourceChild parent j).lo)).1).1 + tolerance (cutGuardWordBudget M j.val B) + (by unfold cutGuardWordBudget; omega) (by unfold cutGuardWordBudget; omega) + (by unfold cutGuardWordBudget; omega) (by unfold cutGuardWordBudget; omega) + (by unfold cutGuardWordBudget; omega) + simp only [cutGuardWithWork, hj, ↓reduceIte] + unfold cutGuardBitBudget + omega + +def bandPredicateWithWork {nx ny M : ℕ} (parent : TargetInterval nx) + (r : TargetInterval ny) (b : ℕ) (tau theta velocity : BinaryFraction) + (actions : List (Fin M → TargetInterval ny)) (hne : actions ≠ []) + (child : Fin M → TargetInterval ny → BinaryFraction) (states : Fin M → TargetInterval ny) : Bool × ℕ := + let connection := zeroConnectionWithWork r.lo (List.ofFn states) r.hi + let anchors := allWithWork (fun i : Fin M => + let leftAnchor := translatedEndpointWithWork r.lo parent.lo (sourceChild parent i).lo + let rightAnchor := translatedEndpointWithWork r.lo parent.lo (sourceChild parent i).hi + let radius := binaryNaturalMulWithWork 6 b + let left := naturalDistanceLeWithWork leftAnchor.1 (states i).lo (bitWordValue radius.1) + let right := naturalDistanceLeWithWork rightAnchor.1 (states i).hi (bitWordValue radius.1) + (left.1 && right.1, leftAnchor.2 + rightAnchor.2 + radius.2 + left.2 + right.2 + 3)) (List.finRange M) + let tolerance := bandToleranceWithWork tau theta b M + let cuts := allWithWork (cutGuardWithWork parent r actions hne child states velocity tolerance.1) + (List.finRange M) + (connection.1 && anchors.1 && cuts.1, connection.2 + anchors.2 + tolerance.2 + cuts.2 + 4) + +@[simp] theorem bandPredicateWithWork_value {nx ny M : ℕ} (parent : TargetInterval nx) + (r : TargetInterval ny) (b : ℕ) (tau theta velocity : BinaryFraction) + (actions : List (Fin M → TargetInterval ny)) (hne : actions ≠ []) + (child : Fin M → TargetInterval ny → BinaryFraction) (states : Fin M → TargetInterval ny) : + (bandPredicateWithWork parent r b tau theta velocity actions hne child states).1 = true ↔ + bandActionPredicate parent r b tau.value theta.value velocity.value actions hne + (fun i q => (child i q).value) states := by + have hlo (i : Fin M) : parent.lo ≤ (sourceChild parent i).lo := Nat.le_add_right _ _ + have hhi (i : Fin M) : parent.lo ≤ (sourceChild parent i).hi := Nat.le_add_right _ _ + simp only [bandPredicateWithWork, Bool.and_eq_true, zeroConnectionWithWork_value, + allWithWork_value, naturalDistanceLeWithWork_value, cutGuardWithWork_value, + translatedEndpointWithWork_value _ _ _ (hlo _), translatedEndpointWithWork_value _ _ _ (hhi _), + binaryNaturalMulWithWork_value, bandToleranceWithWork_value, List.mem_finRange, forall_true_left, + endpointActionConnection, bandActionPredicate] + exact and_assoc + +def anchorGuardBitBudget (B : ℕ) : ℕ := + 2 * (36 * B + 4) + 80 * (B + 4) + 2 * naturalDistanceBitBudget B + 3 + +def bandPredicateBitBudget (M B C : ℕ) : ℕ := + (M + 1) * (8 * B + 3) + M * (anchorGuardBitBudget B + 3) + + bandToleranceBitBudget B + M * (C + 3) + 4 + +theorem bandPredicateWithWork_cost {nx ny M : ℕ} (parent : TargetInterval nx) + (r : TargetInterval ny) (b : ℕ) (tau theta velocity : BinaryFraction) + (actions : List (Fin M → TargetInterval ny)) (hne : actions ≠ []) + (child : Fin M → TargetInterval ny → BinaryFraction) (states : Fin M → TargetInterval ny) + (B C : ℕ) (hstatesMem : states ∈ actions) + (htau : tau.width ≤ B) (htheta : theta.width ≤ B) (hvel : velocity.width ≤ B) + (hb : Nat.size b + 2 ≤ B) (hM : Nat.size M + 2 ≤ B) + (hr : Nat.size r.lo + 2 ≤ B) (hrhi : Nat.size r.hi + 2 ≤ B) + (hp : Nat.size parent.lo + 2 ≤ B) + (hsource : ∀ i : Fin M, Nat.size (sourceChild parent i).lo + 2 ≤ B ∧ + Nat.size (sourceChild parent i).hi + 2 ≤ B) + (hanchor : ∀ i : Fin M, Nat.size (r.lo + ((sourceChild parent i).lo - parent.lo)) + 2 ≤ B ∧ + Nat.size (r.lo + ((sourceChild parent i).hi - parent.lo)) + 2 ≤ B) + (hradius : Nat.size (6 * b) + 2 ≤ B) + (hstates : ∀ action ∈ actions, ∀ i, + Nat.size (action i).lo + 2 ≤ B ∧ Nat.size (action i).hi + 2 ≤ B) + (hchild : ∀ action ∈ actions, ∀ i, (child i (action i)).width ≤ B) + (hC : ∀ j : Fin M, cutGuardBitBudget M j.val actions.length B ≤ C) : + (bandPredicateWithWork parent r b tau theta velocity actions hne child states).2 ≤ + bandPredicateBitBudget M B C := by + have hstate := hstates states hstatesMem + have hlo (i : Fin M) : parent.lo ≤ (sourceChild parent i).lo := Nat.le_add_right _ _ + have hhi (i : Fin M) : parent.lo ≤ (sourceChild parent i).hi := Nat.le_add_right _ _ + have hconn := zeroConnectionWithWork_cost r.lo r.hi (List.ofFn states) B (by omega) (by omega) (by + intro state hs + obtain ⟨i, rfl⟩ := List.mem_ofFn.mp hs + have := hstate i + omega) + have hanchorCost (i : Fin M) : + (let leftAnchor := translatedEndpointWithWork r.lo parent.lo (sourceChild parent i).lo + let rightAnchor := translatedEndpointWithWork r.lo parent.lo (sourceChild parent i).hi + let radius := binaryNaturalMulWithWork 6 b + let left := naturalDistanceLeWithWork leftAnchor.1 (states i).lo (bitWordValue radius.1) + let right := naturalDistanceLeWithWork rightAnchor.1 (states i).hi (bitWordValue radius.1) + (left.1 && right.1, leftAnchor.2 + rightAnchor.2 + radius.2 + left.2 + right.2 + 3)).2 ≤ + anchorGuardBitBudget B := by + have hl := translatedEndpointWithWork_cost r.lo parent.lo (sourceChild parent i).lo B + (hlo i) (by omega) (by omega) (by have := hsource i; omega) + have hh := translatedEndpointWithWork_cost r.lo parent.lo (sourceChild parent i).hi B + (hhi i) (by omega) (by omega) (by have := hsource i; omega) + have hrad := binaryNaturalMulWithWork_cost 6 b + have hleft := naturalDistanceLeWithWork_cost + (translatedEndpointWithWork r.lo parent.lo (sourceChild parent i).lo).1 (states i).lo + (bitWordValue (binaryNaturalMulWithWork 6 b).1) B + (by rw [translatedEndpointWithWork_value _ _ _ (hlo i)]; exact (hanchor i).1) + (hstate i).1 (by rw [binaryNaturalMulWithWork_value]; exact hradius) + have hright := naturalDistanceLeWithWork_cost + (translatedEndpointWithWork r.lo parent.lo (sourceChild parent i).hi).1 (states i).hi + (bitWordValue (binaryNaturalMulWithWork 6 b).1) B + (by rw [translatedEndpointWithWork_value _ _ _ (hhi i)]; exact (hanchor i).2) + (hstate i).2 (by rw [binaryNaturalMulWithWork_value]; exact hradius) + norm_num only [show Nat.size 6 = 3 by decide] at hrad + dsimp only + unfold anchorGuardBitBudget + omega + have ha := allWithWork_cost _ (List.finRange M) (anchorGuardBitBudget B) + (fun i _ => hanchorCost i) + obtain ⟨htw, htc⟩ := bandToleranceWithWork_bounds tau theta b M B htau htheta hb hM + have hc := allWithWork_cost + (cutGuardWithWork parent r actions hne child states velocity (bandToleranceWithWork tau theta b M).1) + (List.finRange M) C (by + intro j _ + exact (cutGuardWithWork_cost parent r actions hne child states velocity + (bandToleranceWithWork tau theta b M).1 j B hvel htw hr hp (hstate j).1 + (hsource j).1 (hsource j).1 hstates hchild).trans (hC j)) + simp only [List.length_ofFn] at hconn + simp only [List.length_finRange] at ha hc + change _ + _ + _ + _ + 4 ≤ _ + unfold bandPredicateBitBudget + dsimp only at ha hc ⊢ + omega + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryBandInputWork.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryBandInputWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..b34d2416cc1e8205fcb989057e2935b91fe13193 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryBandInputWork.lean @@ -0,0 +1,103 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryBandInputs + +namespace OAI + +/-! Bit-operation costs for preparing the actual stored band vertices. The +large numerical values in the generic dot-product bound occur only inside +`Nat.size`; the resulting bound is polynomial in the stored word width. -/ + +namespace EditApproximation +namespace BinaryFraction + +def storedSumWordBudget (n B : ℕ) : ℕ := + (B + 1) + Nat.size n + 2 * (B + 2) + 2 * (1 + n * ((B + 1) + (B + 1))) + 1 + +def storedSumBitBudget (n B : ℕ) : ℕ := + 1 + n * (100000 * (storedSumWordBudget n B + 1) ^ 2) + +theorem bandMassTotalWithWork_cost {M : ℕ} (mass : Vector BinaryFraction M) + (B : ℕ) (hmass : ∀ i, (mass.get i).width ≤ B) : + (bandMassTotalWithWork mass).2 ≤ storedSumBitBudget M B := by + have hvalue (i : Fin M) : |(mass.get i).value| ≤ ((2 ^ (B + 1) : ℕ) : ℚ) := by + have h := (value_abs_le_pow_width (mass.get i)).trans + (pow_le_pow_right₀ (by norm_num : (1 : ℚ) ≤ 2) + (show (mass.get i).width ≤ B + 1 by have := hmass i; omega)) + simpa only [Nat.cast_pow, Nat.cast_ofNat] using h + have honew : one.width ≤ B + 1 := by + change 1 ≤ B + 1 + omega + have hone : |one.value| ≤ ((2 ^ (B + 1) : ℕ) : ℚ) := by + have hp : 1 ≤ 2 ^ (B + 1) := Nat.one_le_pow _ _ (by decide) + rw [← representation_value one, one_representation, UnreducedRational.value_one, abs_one] + exact_mod_cast hp + have h := dotListWithWork_cost_in mass (Vector.replicate M one) + (List.finRange M) M (B + 1) (2 ^ (B + 1)) (by simp) + (by intro i _; have := hmass i; omega) + (by intro i _; simpa using honew) + (by intro i _; exact hvalue i) + (by intro i _; simpa using hone) + have hs1 := natural_product_bit_length (M * 2 ^ (B + 1)) (2 ^ (B + 1)) + have hs2 := natural_product_bit_length M (2 ^ (B + 1)) + have hp : Nat.size (2 ^ (B + 1)) = B + 2 := by rw [Nat.size_pow] + have hword : dotWordBudget M (B + 1) (2 ^ (B + 1)) ≤ storedSumWordBudget M B := by + unfold dotWordBudget storedSumWordBudget + omega + change (dotListWithWork mass (Vector.replicate M one) (List.finRange M)).2 ≤ _ + simp only [List.length_finRange] at h + exact h.trans (Nat.add_le_add_left (Nat.mul_le_mul_left M + (Nat.mul_le_mul_left 100000 (Nat.pow_le_pow_left (by omega) 2))) 1) + +def bandCoordinateBitBudget (M B : ℕ) : ℕ := + 2100 * (B + bandMassTotalStorageBudget M B + 2) ^ 2 + +theorem bandCoordinateWithWork_cost {M : ℕ} {σ : Type*} [DecidableEq σ] + (mass : Vector BinaryFraction M) (action : Fin M → σ) (coordinate : Fin M × σ) + (B : ℕ) (hmass : ∀ i, (mass.get i).width ≤ B) : + (bandCoordinateWithWork mass (bandMassTotalWithWork mass).1 action coordinate).2 ≤ + bandCoordinateBitBudget M B := by + have ht := (dotListWithWork_width_le_storageBits mass (Vector.replicate M one) + (List.finRange M)).trans (bandMassTotalWithWork_storage mass B hmass) + change (bandMassTotalWithWork mass).1.width ≤ bandMassTotalStorageBudget M B at ht + unfold bandCoordinateWithWork + split_ifs + · exact divWithWork_cost _ _ (B + bandMassTotalStorageBudget M B) + ((hmass coordinate.1).trans (Nat.le_add_right _ _)) (by omega) + · unfold bandCoordinateBitBudget + have hp : 1 ≤ (B + bandMassTotalStorageBudget M B + 2) ^ 2 := by + exact Nat.one_le_pow _ _ (by omega) + omega + +def bandPreparationBitBudget (M d vertices B : ℕ) : ℕ := + storedSumBitBudget M B + vertices * (d * (bandCoordinateBitBudget M B + 6)) + 6 * vertices + +theorem bandVerticesWithWork_cost {M d : ℕ} {σ : Type*} [DecidableEq σ] + (coordinates : Vector (Fin M × σ) d) (mass : Vector BinaryFraction M) + (band : List (Fin M → σ)) (B : ℕ) (hmass : ∀ i, (mass.get i).width ≤ B) : + (bandVerticesWithWork coordinates mass band).2 ≤ + bandPreparationBitBudget M d band.length B := by + have hc (action : Fin M → σ) : + (vectorMapWithWork d (fun i => bandCoordinateWithWork mass + (bandMassTotalWithWork mass).1 action (coordinates.get i))).2 ≤ + d * (bandCoordinateBitBudget M B + 6) := + vectorMapWithWork_cost_le d _ _ (fun i => + bandCoordinateWithWork_cost mass action (coordinates.get i) B hmass) + have hs : ((band.map fun action => vectorMapWithWork d fun i => + bandCoordinateWithWork mass (bandMassTotalWithWork mass).1 action + (coordinates.get i)).map Prod.snd).sum ≤ + band.length * (d * (bandCoordinateBitBudget M B + 6)) := by + induction band with + | nil => simp + | cons action band ih => + simp only [List.map_cons, List.sum_cons, List.length_cons] + have ha := hc action + rw [Nat.add_mul, Nat.one_mul] + omega + have ht := bandMassTotalWithWork_cost mass B hmass + change (bandMassTotalWithWork mass).2 + _ + 6 * band.length ≤ _ + unfold bandPreparationBitBudget + omega + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryBandInputs.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryBandInputs.lean new file mode 100644 index 0000000000000000000000000000000000000000..757b3658eec6bc54daa367d2edac3da23eebfb90 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryBandInputs.lean @@ -0,0 +1,155 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryOptimizerWork +import OAI.Combinatorics.EditApproximation.Geometry.BandNumericalBits +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Actual Boolean construction of the normalized band vertices. +The input masses are stored fractions; their sum and divisions use the +counted routines and no reduced-rational conversion is performed. -/ + +namespace EditApproximation +namespace BinaryFraction + +open Finset + +theorem value_abs_le_pow_width (a : BinaryFraction) : |a.value| ≤ (2 : ℚ) ^ a.width := by + have hn := (bitWordValue_lt_pow_length a.numerator.bits).le + have hw : a.numerator.bits.length ≤ a.width := le_max_left _ _ + have hn' : bitWordValue a.numerator.bits ≤ 2 ^ a.width := + hn.trans (Nat.pow_le_pow_right (by decide) hw) + have hden : (1 : ℚ) ≤ bitWordValue a.denominator := by exact_mod_cast a.denominator_pos + have habs : |(a.numerator.value : ℚ)| = bitWordValue a.numerator.bits := by + cases h : a.numerator.negative <;> simp [SignedBinary.value, signedMagnitude, h] + unfold value + rw [abs_div, habs, abs_of_pos (lt_of_lt_of_le (by norm_num : (0 : ℚ) < 1) hden)] + apply (div_le_iff₀ (lt_of_lt_of_le (by norm_num : (0 : ℚ) < 1) hden)).mpr + have hnQ : (bitWordValue a.numerator.bits : ℚ) ≤ (2 : ℚ) ^ a.width := by exact_mod_cast hn' + exact hnQ.trans (le_mul_of_one_le_right (by positivity) hden) + + + +theorem bandMassTotalWithWork_value {M : ℕ} (mass : Vector BinaryFraction M) : + (bandMassTotalWithWork mass).1.value = ∑ i, (mass.get i).value := by + rw [bandMassTotalWithWork, ← representation_value, dotWithWork_representation, + UnreducedRational.dot_value] + simp [one_representation] + +def bandMassTotalStorageBudget (M B : ℕ) : ℕ := + Nat.size M + B + 2 * (1 + M * (B + 1)) + 2 + +theorem bandMassTotalWithWork_storage {M : ℕ} (mass : Vector BinaryFraction M) + (B : ℕ) (hmass : ∀ i, (mass.get i).width ≤ B) : + (bandMassTotalWithWork mass).1.representation.storageBits ≤ bandMassTotalStorageBudget M B := by + have hvalue (i : Fin M) : |(mass.get i).value| ≤ ((2 ^ B : ℕ) : ℚ) := by + have h := (value_abs_le_pow_width (mass.get i)).trans + (pow_le_pow_right₀ (by norm_num : (1 : ℚ) ≤ 2) (hmass i)) + simpa only [Nat.cast_pow, Nat.cast_ofNat] using h + have h := UnreducedRational.dotList_storageBits + (mass.map representation) ((Vector.replicate M one).map representation) + (List.finRange M) B 1 (2 ^ B) 1 + (by intro i _; simpa only [vector_map_get] using (representation_den_bits_le_width (mass.get i)).trans (hmass i)) + (by intro i _; simp [one_representation, UnreducedRational.one, UnreducedRational.ofRat]) + (by intro i _; simpa only [vector_map_get, representation_value] using hvalue i) + (by intro i _; simp [one_representation]) + simp only [List.length_finRange, Nat.mul_one] at h + have hsize := (natural_product_bit_length M (2 ^ B)).trans + (Nat.add_le_add_left (by rw [Nat.size_pow] : Nat.size (2 ^ B) ≤ B + 1) M.size) + rw [bandMassTotalWithWork, dotWithWork_representation] + change (UnreducedRational.dotList (mass.map representation) + ((Vector.replicate M one).map representation) (List.finRange M)).storageBits ≤ _ + unfold bandMassTotalStorageBudget + omega + +def bandVertexWordBudget (M B : ℕ) : ℕ := 2 * B + bandMassTotalStorageBudget M B + 3 + +def bandCoordinateWithWork {M : ℕ} {σ : Type*} [DecidableEq σ] + (mass : Vector BinaryFraction M) (total : BinaryFraction) + (action : Fin M → σ) (coordinate : Fin M × σ) : BinaryFraction × ℕ := + if coordinate.2 = action coordinate.1 then divWithWork (mass.get coordinate.1) total else (zero, 1) + +theorem bandCoordinateWithWork_value {M : ℕ} {σ : Type*} [DecidableEq σ] + (mass : Vector BinaryFraction M) (action : Fin M → σ) (coordinate : Fin M × σ) : + (bandCoordinateWithWork mass (bandMassTotalWithWork mass).1 action coordinate).1.value = + actionVector (fun i => (mass.get i).value) action coordinate := by + unfold bandCoordinateWithWork actionVector + split_ifs + · rw [← representation_value, divWithWork_representation, + UnreducedRational.value_div, representation_value, representation_value, + bandMassTotalWithWork_value] + · simp [zero, value, SignedBinary.value, signedMagnitude, bitWordValue] + +theorem bandCoordinateWithWork_bounds {M : ℕ} {σ : Type*} [DecidableEq σ] + (mass : Vector BinaryFraction M) (action : Fin M → σ) (coordinate : Fin M × σ) + (B : ℕ) (hmass : ∀ i, (mass.get i).width ≤ B) (hpos : ∀ i, 0 < (mass.get i).value) : + let output := (bandCoordinateWithWork mass (bandMassTotalWithWork mass).1 action coordinate).1 + output.width ≤ output.representation.storageBits ∧ + (0 ≤ output.value ∧ output.value ≤ 1) ∧ + output.representation.storageBits ≤ bandVertexWordBudget M B := by + dsimp only + have hvalues := actionVector_zero_one (fun i => (mass.get i).value) action coordinate hpos + rw [← bandCoordinateWithWork_value mass action coordinate] at hvalues + refine ⟨?_, hvalues, ?_⟩ + · unfold bandCoordinateWithWork + split_ifs + · exact divWithWork_self_width _ _ + · exact zero_width_le_storageBits + · have ht := bandMassTotalWithWork_storage mass B hmass + have hm := representation_storageBits_le (mass.get coordinate.1) + have hi := hmass coordinate.1 + unfold bandCoordinateWithWork + split_ifs + · rw [divWithWork_representation] + have hd := UnreducedRational.storageBits_div (mass.get coordinate.1).representation + (bandMassTotalWithWork mass).1.representation + unfold bandVertexWordBudget + omega + · change UnreducedRational.zero.storageBits ≤ _ + rw [UnreducedRational.storageBits_zero] + unfold bandVertexWordBudget + omega + +def bandVerticesWithWork {M d : ℕ} {σ : Type*} [DecidableEq σ] + (coordinates : Vector (Fin M × σ) d) (mass : Vector BinaryFraction M) + (band : List (Fin M → σ)) : List (Vector BinaryFraction d) × ℕ := + let total := bandMassTotalWithWork mass + let vertices := band.map fun action => vectorMapWithWork d fun i => + bandCoordinateWithWork mass total.1 action (coordinates.get i) + (vertices.map Prod.fst, total.2 + (vertices.map Prod.snd).sum + 6 * band.length) + +theorem bandVerticesWithWork_values {M d : ℕ} {σ : Type*} [DecidableEq σ] + (coordinates : Vector (Fin M × σ) d) (mass : Vector BinaryFraction M) + (band : List (Fin M → σ)) : + (bandVerticesWithWork coordinates mass band).1.map (fun v i => (v.get i).value) = + band.map (fun action i => actionVector (fun i => (mass.get i).value) action (coordinates.get i)) := by + simp only [bandVerticesWithWork, List.map_map, Function.comp_def] + apply List.map_congr_left + intro action _ + funext i + simp only [vectorMapWithWork_value, bandCoordinateWithWork_value] + +theorem bandVerticesWithWork_input_bounds {M d : ℕ} {σ : Type*} [DecidableEq σ] + (coordinates : Vector (Fin M × σ) d) (mass : Vector BinaryFraction M) + (band : List (Fin M → σ)) (B : ℕ) + (hmass : ∀ i, (mass.get i).width ≤ B) (hpos : ∀ i, 0 < (mass.get i).value) + (v : Vector BinaryFraction d) (hv : v ∈ (bandVerticesWithWork coordinates mass band).1) + (i : Fin d) : + (v.get i).width ≤ (v.get i).representation.storageBits ∧ + (0 ≤ (v.get i).value ∧ (v.get i).value ≤ 1) ∧ + Nat.size (v.get i).representation.den ≤ bandVertexWordBudget M B ∧ + (v.get i).width ≤ bandVertexWordBudget M B := by + simp only [bandVerticesWithWork, List.map_map, Function.comp_def] at hv + obtain ⟨action, _, rfl⟩ := List.mem_map.mp hv + simp only [vectorMapWithWork_value] + have h := bandCoordinateWithWork_bounds mass action (coordinates.get i) B hmass hpos + dsimp only at h + refine ⟨h.1, h.2.1, ?_, h.1.trans h.2.2⟩ + apply le_trans ?_ h.2.2 + unfold UnreducedRational.storageBits + omega + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryBandReadCosts.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryBandReadCosts.lean new file mode 100644 index 0000000000000000000000000000000000000000..99d30b4f1d05741bb31889f479c1ec41f714bde5 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryBandReadCosts.lean @@ -0,0 +1,252 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryReadCostBounds +import OAI.Combinatorics.EditApproximation.Binary.BinaryBandReads +import OAI.Combinatorics.EditApproximation.Binary.BinaryRoundedReads +import OAI.Combinatorics.EditApproximation.Binary.BinaryUnskippedReads + +namespace OAI + +/-! A finite-buffer lookup multiplies local band-loop work by a fixed +linear factor. Every comparison uses the same actual band and output. -/ + +namespace EditApproximation +namespace BinaryFraction + +theorem wideMinimumReadWithWork_factor {n M : ℕ} (r : TargetInterval n) + (read : Fin M → TargetInterval n → BinaryFraction × ℕ) + (actions : List (Fin M → TargetInterval n)) (hne : actions ≠ []) + (R : ℕ) (hr : ∀ action ∈ actions, ∀ i, (read i (action i)).2 ≤ R) : + (wideMinimumReadWithWork r read actions hne).2 ≤ + (wideMinimumWithWork r (fun i q => (read i q).1) actions hne).2 * tableReadFactor R := by + have hm := arithmeticMapWithWork_factor + (endpointScoreReadWithWork r read) (endpointScoreWithWork r (fun i q => (read i q).1)) + actions (tableReadFactor R) (tableReadFactor_pos R) + (fun action _ => endpointScoreReadWithWork_eq r read action) + (fun action ha => endpointScoreReadWithWork_factor r read action R (hr action ha)) + have hf := endpointScoreReadWithWork_factor r read (actions.head hne) R + (hr _ (List.head_mem hne)) + have hc := Nat.add_le_add hf hm.2 + rw [← Nat.add_mul] at hc + apply cost_replace_factor _ _ _ _ _ hc (tableReadFactor_pos R) + · unfold wideMinimumWithWork + dsimp only + omega + · unfold wideMinimumReadWithWork wideMinimumWithWork + dsimp only + rw [hm.1, endpointScoreReadWithWork_eq] + omega + +theorem prefixMinimumReadWithWork_factor {nx n M : ℕ} (parent : TargetInterval nx) + (r : TargetInterval n) (actions : List (Fin M → TargetInterval n)) (hne : actions ≠ []) + (read : Fin M → TargetInterval n → BinaryFraction × ℕ) (j : ℕ) (p : BinaryFraction) + (R : ℕ) (hr : ∀ action ∈ actions, ∀ i, (read i (action i)).2 ≤ R) : + (prefixMinimumReadWithWork parent r actions hne read j p).2 ≤ + (prefixMinimumWithWork parent r actions hne (fun i q => (read i q).1) j p).2 * + tableReadFactor R := by + have hm := arithmeticMapWithWork_factor + (fun action => prefixReadWithWork parent r action read j p) + (fun action => prefixWithWork parent r action (fun i q => (read i q).1) j p) + actions (tableReadFactor R) (tableReadFactor_pos R) + (fun action _ => prefixReadWithWork_eq parent r action read j p) + (fun action ha => prefixReadWithWork_factor parent r action read j p R (hr action ha)) + have hf := prefixReadWithWork_factor parent r (actions.head hne) read j p R + (hr _ (List.head_mem hne)) + have hc := Nat.add_le_add hf hm.2 + rw [← Nat.add_mul] at hc + apply cost_replace_factor _ _ _ _ _ hc (tableReadFactor_pos R) + · unfold prefixMinimumWithWork + dsimp only + omega + · unfold prefixMinimumReadWithWork prefixMinimumWithWork + dsimp only + rw [hm.1, prefixReadWithWork_eq] + omega + +theorem cutGuardReadWithWork_factor {nx n M : ℕ} (parent : TargetInterval nx) + (r : TargetInterval n) (actions : List (Fin M → TargetInterval n)) (hne : actions ≠ []) + (read : Fin M → TargetInterval n → BinaryFraction × ℕ) (states : Fin M → TargetInterval n) + (velocity tolerance : BinaryFraction) (j : Fin M) (R : ℕ) + (hr : ∀ action ∈ actions, ∀ i, (read i (action i)).2 ≤ R) : + (cutGuardReadWithWork parent r actions hne read states velocity tolerance j).2 ≤ + (cutGuardWithWork parent r actions hne (fun i q => (read i q).1) states velocity tolerance j).2 * + tableReadFactor R := by + unfold cutGuardReadWithWork cutGuardWithWork + split_ifs + · simpa only [Nat.one_mul] using tableReadFactor_pos R + · have h := prefixMinimumReadWithWork_factor parent r actions hne read j.val + (subWithWork (nat (states j).lo) (nat (sourceChild parent j).lo)).1 R hr + dsimp only + rw [prefixMinimumReadWithWork_eq] + apply cost_replace_factor _ _ _ _ _ h (tableReadFactor_pos R) + · omega + · omega + +theorem bandPredicateReadWithWork_factor {nx n M : ℕ} (parent : TargetInterval nx) + (r : TargetInterval n) (b : ℕ) (tau theta velocity : BinaryFraction) + (actions : List (Fin M → TargetInterval n)) (hne : actions ≠ []) + (read : Fin M → TargetInterval n → BinaryFraction × ℕ) (states : Fin M → TargetInterval n) + (R : ℕ) (hr : ∀ action ∈ actions, ∀ i, (read i (action i)).2 ≤ R) : + (bandPredicateReadWithWork parent r b tau theta velocity actions hne read states).2 ≤ + (bandPredicateWithWork parent r b tau theta velocity actions hne (fun i q => (read i q).1) states).2 * + tableReadFactor R := by + have hc := allWithWork_factor + (cutGuardReadWithWork parent r actions hne read states velocity (bandToleranceWithWork tau theta b M).1) + (cutGuardWithWork parent r actions hne (fun i q => (read i q).1) states velocity + (bandToleranceWithWork tau theta b M).1) + (List.finRange M) (tableReadFactor R) (tableReadFactor_pos R) + (fun j _ => cutGuardReadWithWork_eq parent r actions hne read states velocity _ j) + (fun j _ => cutGuardReadWithWork_factor parent r actions hne read states velocity _ j R hr) + apply cost_replace_factor _ _ _ _ _ hc.2 (tableReadFactor_pos R) + · unfold bandPredicateWithWork + dsimp only + omega + · unfold bandPredicateReadWithWork bandPredicateWithWork + dsimp only + omega + +theorem bandFromActionsReadWithWork_factor {nx n M : ℕ} (parent : TargetInterval nx) + (r : TargetInterval n) (b : ℕ) (tau theta velocity : BinaryFraction) + (read : Fin M → TargetInterval n → BinaryFraction × ℕ) + (actions : List (Fin M → TargetInterval n)) (hne : actions ≠ []) + (R : ℕ) (hr : ∀ action ∈ actions, ∀ i, (read i (action i)).2 ≤ R) : + (bandFromActionsReadWithWork parent r b tau theta velocity read actions hne).2 ≤ + (bandFromActionsWithWork parent r b tau theta velocity (fun i q => (read i q).1) actions hne).2 * + tableReadFactor R := by + have hf := filterWithWork_factor + (bandPredicateReadWithWork parent r b tau theta velocity actions hne read) + (bandPredicateWithWork parent r b tau theta velocity actions hne (fun i q => (read i q).1)) + actions (tableReadFactor R) (tableReadFactor_pos R) + (fun action _ => (bandPredicateReadWithWork_eq_cost parent r b tau theta velocity actions hne + read action R hr).1) + (fun action _ => bandPredicateReadWithWork_factor parent r b tau theta velocity actions hne + read action R hr) + unfold bandFromActionsReadWithWork bandFromActionsWithWork + dsimp only + split_ifs + · apply cost_replace_factor _ _ _ _ _ hf.2 (tableReadFactor_pos R) + · omega + · omega + · exact Nat.le_mul_of_pos_right _ (by have := tableReadFactor_pos R; omega) + +theorem representativeFromActionsReadWithWork_factor {nx n M : ℕ} (parent : TargetInterval nx) + (r : TargetInterval n) (sourceLength b : ℕ) (tau theta : BinaryFraction) + (read : Fin M → TargetInterval n → BinaryFraction × ℕ) + (actions : List (Fin M → TargetInterval n)) (R : ℕ) + (hr : ∀ action ∈ actions, ∀ i, (read i (action i)).2 ≤ R) : + (representativeFromActionsReadWithWork parent r sourceLength b tau theta read actions).2 ≤ + (representativeFromActionsWithWork parent r sourceLength b tau theta + (fun i q => (read i q).1) actions).2 * tableReadFactor R := by + unfold representativeFromActionsReadWithWork representativeFromActionsWithWork + by_cases hne : actions = [] + · simp only [dite_eq_left hne] + simpa only [Nat.one_mul] using tableReadFactor_pos R + · simp only [dite_eq_right hne] + have hz := wideMinimumReadWithWork_factor r read actions hne R hr + rw [wideMinimumReadWithWork_eq] + split_ifs + · have hb := bandFromActionsReadWithWork_factor parent r b tau theta + (divWithWork (stateGapWithWork sourceLength r).1 + (wideMinimumWithWork r (fun i q => (read i q).1) actions hne).1).1 read actions hne R hr + have hc := Nat.add_le_add hz hb + rw [← Nat.add_mul] at hc + apply cost_replace_factor _ _ _ _ _ hc (tableReadFactor_pos R) <;> omega + · apply cost_replace_factor _ _ _ _ _ hz (tableReadFactor_pos R) <;> omega + +theorem preparedRepresentativeReadWithWork_factor {nx n M : ℕ} (parent : TargetInterval nx) + (r : TargetInterval n) (sourceLength b P : ℕ) (tau theta : BinaryFraction) + (read : Fin M → TargetInterval n → BinaryFraction × ℕ) (R : ℕ) + (hr : ∀ i q, (read i q).2 ≤ R) : + (preparedRepresentativeReadWithWork parent r sourceLength b P tau theta read).2 ≤ + (preparedRepresentativeWithWork parent r sourceLength b P tau theta + (fun i q => (read i q).1)).2 * tableReadFactor R := by + have h := representativeFromActionsReadWithWork_factor parent r sourceLength b tau theta read + ((wideActionGridWithWork M parent r b P).1.map Vector.get) R (fun _ _ i => hr i _) + unfold preparedRepresentativeReadWithWork preparedRepresentativeWithWork + dsimp only + apply cost_replace_factor _ _ _ _ _ h (tableReadFactor_pos R) <;> omega + +theorem envelopeVectorReadWithWork_factor {n M : ℕ} (b : ℕ) + (band : List (Fin M → TargetInterval n)) + (read : Fin M → TargetInterval n → BinaryFraction × ℕ) (R : ℕ) + (hr : ∀ i q, (read i q).2 ≤ R) : + (envelopeVectorReadWithWork b band read).2 ≤ + (envelopeVectorWithWork b band (fun i q => (read i q).1)).2 * tableReadFactor R := by + exact (vectorMapWithWork_factor M + (bandEnvelopeReadWithWork b band read) + (bandEnvelopeWithWork b band (fun i q => (read i q).1)) + (tableReadFactor R) (tableReadFactor_pos R) + (fun i => bandEnvelopeReadWithWork_eq b band read i) + (fun i => bandEnvelopeReadWithWork_factor b band read i R (fun _ _ => hr i _))).2 + +theorem roundedBandReadWithWork_factor {n M : ℕ} (exponent b : ℕ) + (band : List (Fin M → TargetInterval n)) (hne : band ≠ []) + (read : Fin M → TargetInterval n → BinaryFraction × ℕ) (R : ℕ) + (hr : ∀ i q, (read i q).2 ≤ R) : + (roundedBandReadWithWork exponent b band hne read).2 ≤ + (roundedBandWithWork exponent b band hne (fun i q => (read i q).1)).2 * tableReadFactor R := by + apply (vectorMapWithWork_factor M _ _ (tableReadFactor R) (tableReadFactor_pos R) ?_ ?_).2 + · intro i + simp only [bandEnvelopeReadWithWork_eq] + · intro i + have h := bandEnvelopeReadWithWork_factor b band read i R (fun _ _ => hr i _) + dsimp only + simp only [bandEnvelopeReadWithWork_eq] + apply cost_replace_factor _ _ _ _ _ h (tableReadFactor_pos R) <;> omega + +theorem unskippedGuardReadWithWork_factor {nx n M : ℕ} (parent : TargetInterval nx) + (r : TargetInterval n) (b exponent : ℕ) (F : BinaryFraction) + (band wide : List (Fin M → TargetInterval n)) (hne : band ≠ []) + (read : Fin M → TargetInterval n → BinaryFraction × ℕ) (R : ℕ) + (hr : ∀ i q, (read i q).2 ≤ R) : + (unskippedGuardReadWithWork parent r b exponent F band wide hne read).2 ≤ + (unskippedGuardWithWork parent r b exponent F band wide hne + (fun i q => (read i q).1)).2 * tableReadFactor R := by + have he := envelopeVectorReadWithWork_factor b band read R hr + have heq := (envelopeVectorReadWithWork_eq_cost b band read R hr).1 + have hrnd := roundedBandReadWithWork_factor exponent b band hne read R hr + have hrndq := (roundedBandReadWithWork_eq_cost exponent b band hne read R hr).1 + have h := Nat.add_le_add he hrnd + rw [← Nat.add_mul] at h + unfold unskippedGuardReadWithWork unskippedGuardWithWork + dsimp only + rw [heq, hrndq] + apply cost_replace_factor _ _ _ _ _ h (tableReadFactor_pos R) <;> omega + +theorem preparedUnskippedReadWithWork_factor {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (b P exponent : ℕ) (hb : 0 < b) (hP : 0 < P) + (tau F : BinaryFraction) + (read initial : Fin M → TargetInterval target.length → BinaryFraction × ℕ) + (R : ℕ) (hr : ∀ i q, (read i q).2 ≤ R) (hi : ∀ i q, (initial i q).2 ≤ R) + (center : TargetInterval target.length) : + (preparedUnskippedReadWithWork source target parent b P exponent hb hP tau F + read initial R R hr hi center).2 ≤ + (preparedUnskippedCandidateWithWork source target parent b P exponent hb hP tau F + (fun i q => (read i q).1) (fun i q => (initial i q).1) center).2 * tableReadFactor R := by + have hband := preparedRepresentativeReadWithWork_factor parent center (parent.hi - parent.lo) + b P tau (inversePowerTwo exponent) read R hr + have hbandq := (preparedRepresentativeReadWithWork_eq_cost parent center (parent.hi - parent.lo) + b P tau (inversePowerTwo exponent) read R hr).1 + unfold preparedUnskippedReadWithWork preparedUnskippedCandidateWithWork + dsimp only + simp only [hbandq] + by_cases hempty : (preparedRepresentativeWithWork parent center (parent.hi - parent.lo) + b P tau (inversePowerTwo exponent) (fun i q => (read i q).1)).1 = [] + · simp only [dite_eq_left hempty] + apply cost_replace_factor _ _ _ _ _ hband (tableReadFactor_pos R) <;> omega + · simp only [dite_eq_right hempty] + have hg := unskippedGuardReadWithWork_factor parent center b exponent F + (preparedRepresentativeWithWork parent center (parent.hi - parent.lo) b P + tau (inversePowerTwo exponent) (fun i q => (read i q).1)).1 + ((wideActionGridWithWork M parent center b P).1.map Vector.get) hempty initial R hi + have hgq := (unskippedGuardReadWithWork_eq_cost parent center b exponent F + (preparedRepresentativeWithWork parent center (parent.hi - parent.lo) b P + tau (inversePowerTwo exponent) (fun i q => (read i q).1)).1 + ((wideActionGridWithWork M parent center b P).1.map Vector.get) hempty initial R hi).1 + simp only [hgq] + have h := Nat.add_le_add hband hg + rw [← Nat.add_mul] at h + split_ifs <;> apply cost_replace_factor _ _ _ _ _ h (tableReadFactor_pos R) <;> omega + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryBandReads.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryBandReads.lean new file mode 100644 index 0000000000000000000000000000000000000000..98f09c0a9808386788690ef5b833e029246ef1e3 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryBandReads.lean @@ -0,0 +1,105 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryCutReads +import OAI.Combinatorics.EditApproximation.Binary.BinaryScoreReads +import OAI.Combinatorics.EditApproximation.Binary.BinaryPreparedRepresentative +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Representative bands with charged child-table reads in every score +and prefix predicate over the materialized wide grid. -/ + +namespace EditApproximation +namespace BinaryFraction + + + +theorem bandFromActionsReadWithWork_eq_cost {nx ny M : ℕ} (parent : TargetInterval nx) + (r : TargetInterval ny) (b : ℕ) (tau theta velocity : BinaryFraction) + (read : Fin M → TargetInterval ny → BinaryFraction × ℕ) + (actions : List (Fin M → TargetInterval ny)) (hne : actions ≠ []) (R : ℕ) + (hr : ∀ action ∈ actions, ∀ i, (read i (action i)).2 ≤ R) : + (bandFromActionsReadWithWork parent r b tau theta velocity read actions hne).1 = + (bandFromActionsWithWork parent r b tau theta velocity (fun i q => (read i q).1) actions hne).1 ∧ + (bandFromActionsReadWithWork parent r b tau theta velocity read actions hne).2 ≤ + (bandFromActionsWithWork parent r b tau theta velocity (fun i q => (read i q).1) actions hne).2 + + actions.length * (M * ((actions.length + 1) * (M * (R + 4)))) := by + have costBound (a a' m g A : ℕ) (ha : a ≤ a' + A) : + m + g + a + 2 ≤ m + g + a' + 2 + A := by + omega + have h := filterWithWork_extra + (bandPredicateReadWithWork parent r b tau theta velocity actions hne read) + (bandPredicateWithWork parent r b tau theta velocity actions hne (fun i q => (read i q).1)) + (fun _ => M * ((actions.length + 1) * (M * (R + 4)))) actions + (fun states _ => (bandPredicateReadWithWork_eq_cost parent r b tau theta velocity actions hne read states R hr).1) + (fun states _ => (bandPredicateReadWithWork_eq_cost parent r b tau theta velocity actions hne read states R hr).2) + simp only [List.map_const', List.sum_replicate, smul_eq_mul] at h + unfold bandFromActionsReadWithWork bandFromActionsWithWork + dsimp only + split_ifs + · exact ⟨h.1, costBound _ _ _ _ _ h.2⟩ + · exact ⟨rfl, Nat.le_add_right _ _⟩ + + + +def representativeReadOverhead (M vertices R : ℕ) : ℕ := + (vertices + 1) * (M * (R + 4)) + vertices * (M * ((vertices + 1) * (M * (R + 4)))) + +theorem representativeFromActionsReadWithWork_eq_cost {nx ny M : ℕ} (parent : TargetInterval nx) + (r : TargetInterval ny) (sourceLength b : ℕ) (tau theta : BinaryFraction) + (read : Fin M → TargetInterval ny → BinaryFraction × ℕ) + (actions : List (Fin M → TargetInterval ny)) (R : ℕ) + (hr : ∀ action ∈ actions, ∀ i, (read i (action i)).2 ≤ R) : + (representativeFromActionsReadWithWork parent r sourceLength b tau theta read actions).1 = + (representativeFromActionsWithWork parent r sourceLength b tau theta (fun i q => (read i q).1) actions).1 ∧ + (representativeFromActionsReadWithWork parent r sourceLength b tau theta read actions).2 ≤ + (representativeFromActionsWithWork parent r sourceLength b tau theta (fun i q => (read i q).1) actions).2 + + representativeReadOverhead M actions.length R := by + have costBound (a a' c c' x y z A B : ℕ) + (ha : a ≤ a' + A) (hc : c ≤ c' + B) : + a + x + y + z + c + 3 ≤ a' + x + y + z + c' + 3 + (A + B) := by + omega + have shortCostBound (a a' x A B : ℕ) (ha : a ≤ a' + A) : + a + x + 2 ≤ a' + x + 2 + (A + B) := by + omega + unfold representativeFromActionsReadWithWork representativeFromActionsWithWork + by_cases hne : actions = [] + · simp only [dite_eq_left hne] + exact ⟨trivial, Nat.le_add_right _ _⟩ + · simp only [dite_eq_right hne] + have hz := wideMinimumReadWithWork_cost r read actions hne R hr + have hmono : (actions.length + 1) * (M * (R + 3)) ≤ (actions.length + 1) * (M * (R + 4)) := by + exact Nat.mul_le_mul_left _ (Nat.mul_le_mul_left _ + (Nat.add_le_add_left (by decide : 3 ≤ 4) R)) + have hz' := hz.trans (Nat.add_le_add_left hmono _) + rw [wideMinimumReadWithWork_eq] + split_ifs + · have hb := bandFromActionsReadWithWork_eq_cost parent r b tau theta + (divWithWork (stateGapWithWork sourceLength r).1 + (wideMinimumWithWork r (fun i q => (read i q).1) actions hne).1).1 read actions hne R hr + refine ⟨hb.1, ?_⟩ + exact costBound _ _ _ _ _ _ _ _ _ hz' hb.2 + · exact ⟨rfl, shortCostBound _ _ _ _ _ hz'⟩ + + + +theorem preparedRepresentativeReadWithWork_eq_cost {nx ny M : ℕ} (parent : TargetInterval nx) + (center : TargetInterval ny) (sourceLength b P : ℕ) (tau theta : BinaryFraction) + (read : Fin M → TargetInterval ny → BinaryFraction × ℕ) (R : ℕ) + (hr : ∀ i q, (read i q).2 ≤ R) : + (preparedRepresentativeReadWithWork parent center sourceLength b P tau theta read).1 = + (preparedRepresentativeWithWork parent center sourceLength b P tau theta (fun i q => (read i q).1)).1 ∧ + (preparedRepresentativeReadWithWork parent center sourceLength b P tau theta read).2 ≤ + (preparedRepresentativeWithWork parent center sourceLength b P tau theta (fun i q => (read i q).1)).2 + + representativeReadOverhead M (wideActionGridWithWork M parent center b P).1.length R := by + have h := representativeFromActionsReadWithWork_eq_cost parent center sourceLength b tau theta read + ((wideActionGridWithWork M parent center b P).1.map Vector.get) R (fun _ _ i => hr i _) + simp only [List.length_map] at h + unfold preparedRepresentativeReadWithWork preparedRepresentativeWithWork + dsimp only + exact ⟨h.1, by omega⟩ + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryBandSpace.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryBandSpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..d53c5b7dfdac23a71b36f7e5f1c1a5d64a9dc553 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryBandSpace.lean @@ -0,0 +1,67 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryGuardSpace +import OAI.Combinatorics.EditApproximation.Binary.BinaryBandReads +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation.BinaryFraction + + + +theorem anchorGuardAllocation_le_work {nx ny M : ℕ} (parent : TargetInterval nx) (r : TargetInterval ny) + (b : ℕ) (states : Fin M → TargetInterval ny) (i : Fin M) : + anchorGuardAllocation parent r b states i ≤ + (translatedEndpointWithWork r.lo parent.lo (sourceChild parent i).lo).2 + + (translatedEndpointWithWork r.lo parent.lo (sourceChild parent i).hi).2 + + (binaryNaturalMulWithWork 6 b).2 + + (naturalDistanceLeWithWork (translatedEndpointWithWork r.lo parent.lo (sourceChild parent i).lo).1 + (states i).lo (bitWordValue (binaryNaturalMulWithWork 6 b).1)).2 + + (naturalDistanceLeWithWork (translatedEndpointWithWork r.lo parent.lo (sourceChild parent i).hi).1 + (states i).hi (bitWordValue (binaryNaturalMulWithWork 6 b).1)).2 + 3 := by + have hl := translatedEndpointAllocation_le_work r.lo parent.lo (sourceChild parent i).lo + have hr := translatedEndpointAllocation_le_work r.lo parent.lo (sourceChild parent i).hi + have hm := binaryNaturalMulAllocation_le_work 6 b + have hld := naturalDistanceLeAllocation_le_work + (translatedEndpointWithWork r.lo parent.lo (sourceChild parent i).lo).1 + (states i).lo (bitWordValue (binaryNaturalMulWithWork 6 b).1) + have hrd := naturalDistanceLeAllocation_le_work + (translatedEndpointWithWork r.lo parent.lo (sourceChild parent i).hi).1 + (states i).hi (bitWordValue (binaryNaturalMulWithWork 6 b).1) + unfold anchorGuardAllocation + dsimp only + omega + + + +theorem bandPredicateReadAllocation_le_work {nx ny M : ℕ} (parent : TargetInterval nx) (r : TargetInterval ny) + (b : ℕ) (tau theta velocity : BinaryFraction) + (actions : List (Fin M → TargetInterval ny)) (hne : actions ≠ []) + (read : Fin M → TargetInterval ny → BinaryFraction × ℕ) + (allocation : Fin M → TargetInterval ny → ℕ) (states : Fin M → TargetInterval ny) + (h : ∀ action ∈ actions, ∀ i, allocation i (action i) ≤ (read i (action i)).2) : + bandPredicateReadAllocation parent r b tau theta velocity actions hne read allocation states ≤ + (bandPredicateReadWithWork parent r b tau theta velocity actions hne read states).2 := by + have hz := zeroConnectionAllocation_le_work r.lo r.hi (List.ofFn states) + have ha := allAllocation_with_spine (fun i : Fin M => + let leftAnchor := translatedEndpointWithWork r.lo parent.lo (sourceChild parent i).lo + let rightAnchor := translatedEndpointWithWork r.lo parent.lo (sourceChild parent i).hi + let radius := binaryNaturalMulWithWork 6 b + let left := naturalDistanceLeWithWork leftAnchor.1 (states i).lo (bitWordValue radius.1) + let right := naturalDistanceLeWithWork rightAnchor.1 (states i).hi (bitWordValue radius.1) + (left.1 && right.1, leftAnchor.2 + rightAnchor.2 + radius.2 + left.2 + right.2 + 3)) + (anchorGuardAllocation parent r b states) (List.finRange M) + (fun i _ => anchorGuardAllocation_le_work parent r b states i) + have ht := bandToleranceAllocation_le_work tau theta b M + have hc := allAllocation_le_work + (cutGuardReadWithWork parent r actions hne read states velocity (bandToleranceWithWork tau theta b M).1) + (cutGuardReadAllocation parent r actions hne read allocation states velocity (bandToleranceWithWork tau theta b M).1) + (List.finRange M) (fun i _ => cutGuardReadAllocation_le_work parent r actions hne read allocation states velocity _ i h) + simp only [List.length_finRange] at ha + unfold bandPredicateReadAllocation bandPredicateReadWithWork + dsimp only at ha hc ⊢ + omega + +end EditApproximation.BinaryFraction + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryBandStorage.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryBandStorage.lean new file mode 100644 index 0000000000000000000000000000000000000000..a226e4601bfee2d9d35f7d66438b63da02480826 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryBandStorage.lean @@ -0,0 +1,99 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryOptimizerSpace +import OAI.Combinatorics.EditApproximation.Binary.BinaryReductionSpace +import OAI.Combinatorics.EditApproximation.Binary.BinaryBandInputs + +namespace OAI + +namespace EditApproximation.BinaryFraction + +def bandCoordinateAllocation {M : ℕ} {σ : Type*} [DecidableEq σ] + (mass : Vector BinaryFraction M) (total : BinaryFraction) + (action : Fin M → σ) (coordinate : Fin M × σ) : ℕ := + if coordinate.2 = action coordinate.1 then divAllocation (mass.get coordinate.1) total else 0 + +def bandCoordinateInvocations {M : ℕ} {σ : Type*} [DecidableEq σ] + (mass : Vector BinaryFraction M) (total : BinaryFraction) + (action : Fin M → σ) (coordinate : Fin M × σ) : ℕ := + if coordinate.2 = action coordinate.1 then divInvocations (mass.get coordinate.1) total else 1 + +theorem bandCoordinateAllocation_le_work {M : ℕ} {σ : Type*} [DecidableEq σ] + (mass : Vector BinaryFraction M) (total : BinaryFraction) + (action : Fin M → σ) (coordinate : Fin M × σ) : + bandCoordinateAllocation mass total action coordinate ≤ (bandCoordinateWithWork mass total action coordinate).2 := by + unfold bandCoordinateAllocation bandCoordinateWithWork + split_ifs + · exact divAllocation_le_work _ _ + · exact Nat.zero_le _ + +theorem bandCoordinateInvocations_le_work {M : ℕ} {σ : Type*} [DecidableEq σ] + (mass : Vector BinaryFraction M) (total : BinaryFraction) + (action : Fin M → σ) (coordinate : Fin M × σ) : + bandCoordinateInvocations mass total action coordinate ≤ (bandCoordinateWithWork mass total action coordinate).2 := by + unfold bandCoordinateInvocations bandCoordinateWithWork + split_ifs + · exact divInvocations_le_work _ _ + · exact le_refl _ + +def bandVerticesAllocation {M d : ℕ} {σ : Type*} [DecidableEq σ] + (coordinates : Vector (Fin M × σ) d) (mass : Vector BinaryFraction M) + (band : List (Fin M → σ)) : ℕ := + bandMassAllocation mass + + (band.map fun action => vectorMapAllocation d fun i => + bandCoordinateAllocation mass (bandMassTotalWithWork mass).1 action (coordinates.get i)).sum + + 3 * band.length + +def bandVerticesInvocations {M d : ℕ} {σ : Type*} [DecidableEq σ] + (coordinates : Vector (Fin M × σ) d) (mass : Vector BinaryFraction M) + (band : List (Fin M → σ)) : ℕ := + bandMassInvocations mass + + (band.map fun action => vectorMapInvocations d fun i => + bandCoordinateInvocations mass (bandMassTotalWithWork mass).1 action (coordinates.get i)).sum + + 3 * band.length + 1 + +theorem bandVerticesAllocation_le_work {M d : ℕ} {σ : Type*} [DecidableEq σ] + (coordinates : Vector (Fin M × σ) d) (mass : Vector BinaryFraction M) + (band : List (Fin M → σ)) : + bandVerticesAllocation coordinates mass band ≤ (bandVerticesWithWork coordinates mass band).2 := by + have hm := bandMassAllocation_le_work mass + have hs : (band.map fun action => vectorMapAllocation d fun i => + bandCoordinateAllocation mass (bandMassTotalWithWork mass).1 action (coordinates.get i)).sum ≤ + (band.map fun action => (vectorMapWithWork d fun i => + bandCoordinateWithWork mass (bandMassTotalWithWork mass).1 action (coordinates.get i)).2).sum := by + induction band with + | nil => simp + | cons a rest ih => + have h := vectorMapAllocation_le_work d + (fun i => bandCoordinateWithWork mass (bandMassTotalWithWork mass).1 a (coordinates.get i)) + (fun i => bandCoordinateAllocation mass (bandMassTotalWithWork mass).1 a (coordinates.get i)) + (fun i => bandCoordinateAllocation_le_work _ _ _ _) + simp only [List.map_cons, List.sum_cons] + omega + unfold bandVerticesAllocation bandVerticesWithWork + simp only [List.map_map, Function.comp_def] + omega + +theorem bandVerticesInvocations_le_work_add_one {M d : ℕ} {σ : Type*} [DecidableEq σ] + (coordinates : Vector (Fin M × σ) d) (mass : Vector BinaryFraction M) + (band : List (Fin M → σ)) : + bandVerticesInvocations coordinates mass band ≤ (bandVerticesWithWork coordinates mass band).2 + 1 := by + have hm := bandMassInvocations_le_work mass + have hs : (band.map fun action => vectorMapInvocations d fun i => + bandCoordinateInvocations mass (bandMassTotalWithWork mass).1 action (coordinates.get i)).sum ≤ + (band.map fun action => (vectorMapWithWork d fun i => + bandCoordinateWithWork mass (bandMassTotalWithWork mass).1 action (coordinates.get i)).2).sum + band.length := by + induction band with + | nil => simp + | cons a rest ih => + have h := vectorMapInvocations_le_work_add_one d + (fun i => bandCoordinateWithWork mass (bandMassTotalWithWork mass).1 a (coordinates.get i)) + (fun i => bandCoordinateInvocations mass (bandMassTotalWithWork mass).1 a (coordinates.get i)) + (fun i => bandCoordinateInvocations_le_work _ _ _ _) + simp only [List.map_cons, List.sum_cons, List.length_cons] + omega + unfold bandVerticesInvocations bandVerticesWithWork + simp only [List.map_map, Function.comp_def] + omega + +end EditApproximation.BinaryFraction + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryBandTailWork.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryBandTailWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..4d5b10b3eb2c0e3e508d3138c15f762632543818 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryBandTailWork.lean @@ -0,0 +1,160 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryRepresentativeWork + +namespace OAI + +/-! Work of the literal representative tail. The sole callback premise is +an explicit bound on the already-defined band predicate, whose primitive +bound is `bandPredicateWithWork_cost`; no accuracy property is assumed. -/ + +namespace EditApproximation +namespace BinaryFraction + +def bandFromActionsBitBudget (n B C : ℕ) : ℕ := + 6000 * (B + 1) ^ 2 + 1000 * (8 * B + 7) ^ 2 + n * (C + 3) + 4 + +theorem bandFromActionsWithWork_cost {nx ny M : ℕ} (parent : TargetInterval nx) + (r : TargetInterval ny) (b : ℕ) (tau theta velocity : BinaryFraction) + (child : Fin M → TargetInterval ny → BinaryFraction) + (actions : List (Fin M → TargetInterval ny)) (hne : actions ≠ []) (B C : ℕ) + (hB : 1 ≤ B) (htau : tau.width ≤ B) (hvel : velocity.width ≤ B) + (hC : ∀ states ∈ actions, + (bandPredicateWithWork parent r b tau theta velocity actions hne child states).2 ≤ C) : + (bandFromActionsWithWork parent r b tau theta velocity child actions hne).2 ≤ + bandFromActionsBitBudget actions.length B C := by + let margin := subWithWork one tau + have hmw := subWithWork_width one tau B (by exact hB) htau + have hmc := subWithWork_cost one tau B (by exact hB) htau + have hgc := leWithWork_cost velocity.absolute margin.1 (8 * B + 6) + (by change velocity.width ≤ _; omega) hmw + have hfc := filterWithWork_cost + (bandPredicateWithWork parent r b tau theta velocity actions hne child) actions C hC + unfold bandFromActionsWithWork + dsimp only + split_ifs + · change margin.2 + (leWithWork velocity.absolute margin.1).2 + + (filterWithWork (bandPredicateWithWork parent r b tau theta velocity actions hne child) actions).2 + 2 ≤ _ + change margin.2 ≤ _ at hmc + unfold bandFromActionsBitBudget + simp only [Nat.add_assoc, Nat.reduceAdd] at hgc + omega + · change margin.2 + (leWithWork velocity.absolute margin.1).2 + 1 ≤ _ + change margin.2 ≤ _ at hmc + unfold bandFromActionsBitBudget + simp only [Nat.add_assoc, Nat.reduceAdd] at hgc + omega + +def representativeTailInputBudget (M B : ℕ) : ℕ := + B + endpointScoreWordBudget M B + stateGapWordBudget B + 1 + +def representativeTailBitBudget (M n B C : ℕ) : ℕ := + let W := representativeTailInputBudget M B + wideMinimumBitBudget M n B + 1000 * (W + 1) ^ 2 + stateGapBitBudget B + + 2100 * (W + 2) ^ 2 + bandFromActionsBitBudget n (4 * W + 4) C + 3 + +theorem representativeFromActionsWithWork_cost {nx ny M : ℕ} (parent : TargetInterval nx) + (r : TargetInterval ny) (sourceLength b : ℕ) (tau theta : BinaryFraction) + (child : Fin M → TargetInterval ny → BinaryFraction) + (actions : List (Fin M → TargetInterval ny)) (B C : ℕ) + (htau : tau.width ≤ B) (hsource : Nat.size sourceLength + 2 ≤ B) + (hrl : Nat.size r.lo + 2 ≤ B) (hrh : Nat.size r.hi + 2 ≤ B) + (he : ∀ states ∈ actions, ∀ i, Nat.size (states i).lo + 2 ≤ B ∧ + Nat.size (states i).hi + 2 ≤ B) + (hv : ∀ states ∈ actions, ∀ i, (child i (states i)).width ≤ B) + (hC : ∀ (hne : actions ≠ []) (velocity : BinaryFraction), + velocity.width ≤ 4 * representativeTailInputBudget M B + 4 → + ∀ states ∈ actions, + (bandPredicateWithWork parent r b tau theta velocity actions hne child states).2 ≤ C) : + (representativeFromActionsWithWork parent r sourceLength b tau theta child actions).2 ≤ + representativeTailBitBudget M actions.length B C := by + by_cases hnil : actions = [] + · simp only [representativeFromActionsWithWork, dite_eq_left hnil] + dsimp only [representativeTailBitBudget] + omega + · let W := representativeTailInputBudget M B + let Z := wideMinimumWithWork r child actions hnil + have hW : B ≤ W := by dsimp only [W, representativeTailInputBudget]; omega + have hWpos : 1 ≤ W := by dsimp only [W, representativeTailInputBudget]; omega + have hz := wideMinimumWithWork_bounds r child actions hnil B hrl hrh he hv + have hZw : Z.1.width ≤ W := hz.1.trans (by dsimp only [W, representativeTailInputBudget]; omega) + have hpositive := ltWithWork_cost zero Z.1 W hWpos hZw + have hgap := stateGapWithWork_bounds sourceLength r B hsource hrl hrh + have hgapW : (stateGapWithWork sourceLength r).1.width ≤ W := hgap.1.trans (by + dsimp only [W, representativeTailInputBudget]; omega) + have hvel := divWithWork_width_uniform (stateGapWithWork sourceLength r).1 Z.1 W hgapW hZw + have hvelc := divWithWork_cost (stateGapWithWork sourceLength r).1 Z.1 W hgapW hZw + have hband := bandFromActionsWithWork_cost parent r b tau theta + (divWithWork (stateGapWithWork sourceLength r).1 Z.1).1 child actions hnil (4 * W + 4) C + (by omega) (htau.trans (by omega)) hvel (hC hnil _ hvel) + unfold representativeFromActionsWithWork + rw [dite_eq_right hnil] + dsimp only + split_ifs + · change Z.2 + (ltWithWork zero Z.1).2 + (stateGapWithWork sourceLength r).2 + + (divWithWork (stateGapWithWork sourceLength r).1 Z.1).2 + + (bandFromActionsWithWork parent r b tau theta + (divWithWork (stateGapWithWork sourceLength r).1 Z.1).1 child actions hnil).2 + 3 ≤ + wideMinimumBitBudget M actions.length B + 1000 * (W + 1) ^ 2 + stateGapBitBudget B + + 2100 * (W + 2) ^ 2 + bandFromActionsBitBudget actions.length (4 * W + 4) C + 3 + have hzc : Z.2 ≤ wideMinimumBitBudget M actions.length B := hz.2 + omega + · change Z.2 + (ltWithWork zero Z.1).2 + 2 ≤ + wideMinimumBitBudget M actions.length B + 1000 * (W + 1) ^ 2 + stateGapBitBudget B + + 2100 * (W + 2) ^ 2 + bandFromActionsBitBudget actions.length (4 * W + 4) C + 3 + have hzc : Z.2 ≤ wideMinimumBitBudget M actions.length B := hz.2 + omega + +def representativeGuardInputBudget (M vertices B : ℕ) : ℕ := + 4 * representativeTailInputBudget M B + 4 + B + M + vertices + 2 + +def representativeCompleteBitBudget (M vertices B : ℕ) : ℕ := + let S := representativeGuardInputBudget M vertices B + representativeTailBitBudget M vertices B + (bandPredicateBitBudget M S (S ^ prefixArithmeticDegree)) + +/-- Every prefix-cut callback in the representative tail is bounded by +the proved finite-prefix implementation, rather than an assumed callback +budget. The premises concern only the stored input widths. -/ +theorem representativeFromActionsWithWork_complete_cost {nx ny M : ℕ} (parent : TargetInterval nx) + (r : TargetInterval ny) (sourceLength b : ℕ) (tau theta : BinaryFraction) + (child : Fin M → TargetInterval ny → BinaryFraction) + (actions : List (Fin M → TargetInterval ny)) (B : ℕ) + (htau : tau.width ≤ B) (htheta : theta.width ≤ B) + (hsourceLength : Nat.size sourceLength + 2 ≤ B) + (hb : Nat.size b + 2 ≤ B) (hM : Nat.size M + 2 ≤ B) + (hrl : Nat.size r.lo + 2 ≤ B) (hrh : Nat.size r.hi + 2 ≤ B) + (hp : Nat.size parent.lo + 2 ≤ B) + (hsource : ∀ i : Fin M, Nat.size (sourceChild parent i).lo + 2 ≤ B ∧ + Nat.size (sourceChild parent i).hi + 2 ≤ B) + (hanchor : ∀ i : Fin M, Nat.size (r.lo + ((sourceChild parent i).lo - parent.lo)) + 2 ≤ B ∧ + Nat.size (r.lo + ((sourceChild parent i).hi - parent.lo)) + 2 ≤ B) + (hradius : Nat.size (6 * b) + 2 ≤ B) + (he : ∀ states ∈ actions, ∀ i, Nat.size (states i).lo + 2 ≤ B ∧ + Nat.size (states i).hi + 2 ≤ B) + (hv : ∀ states ∈ actions, ∀ i, (child i (states i)).width ≤ B) : + (representativeFromActionsWithWork parent r sourceLength b tau theta child actions).2 ≤ + representativeCompleteBitBudget M actions.length B := by + let S := representativeGuardInputBudget M actions.length B + have hBS : B ≤ S := by dsimp only [S, representativeGuardInputBudget]; omega + have hS : 2 ≤ S := by dsimp only [S, representativeGuardInputBudget]; omega + have hMS : M ≤ S := by dsimp only [S, representativeGuardInputBudget]; omega + have hnS : actions.length ≤ S := by dsimp only [S, representativeGuardInputBudget]; omega + apply representativeFromActionsWithWork_cost parent r sourceLength b tau theta child actions B + (bandPredicateBitBudget M S (S ^ prefixArithmeticDegree)) htau hsourceLength hrl hrh he hv + intro hne velocity hvelocity states hstates + apply bandPredicateWithWork_cost parent r b tau theta velocity actions hne child states S + (S ^ prefixArithmeticDegree) hstates (htau.trans hBS) (htheta.trans hBS) + (hvelocity.trans (by dsimp only [S, representativeGuardInputBudget]; omega)) + (hb.trans hBS) (hM.trans hBS) (hrl.trans hBS) (hrh.trans hBS) (hp.trans hBS) + (fun i => ⟨(hsource i).1.trans hBS, (hsource i).2.trans hBS⟩) + (fun i => ⟨(hanchor i).1.trans hBS, (hanchor i).2.trans hBS⟩) + (hradius.trans hBS) + (fun a ha i => ⟨(he a ha i).1.trans hBS, (he a ha i).2.trans hBS⟩) + (fun a ha i => (hv a ha i).trans hBS) + intro j + exact (prefix_guard_budgets_le_fixed_power M j.val actions.length S S hS hMS + (j.isLt.le.trans hMS) hnS le_rfl).2.2.2.2.1 + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryBellmanKernel.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryBellmanKernel.lean new file mode 100644 index 0000000000000000000000000000000000000000..630a3d82f7e5cefe43ed560bc3b5bc3ec40a025f --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryBellmanKernel.lean @@ -0,0 +1,267 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryBandGuardWork +import OAI.Combinatorics.EditApproximation.Numerics.RationalWideStep +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Stored-fraction execution of the Bellman and refinement continuations. +The action lists and child entries have already been gathered; the routines +below perform every numerical operation returning the next table value. -/ + +namespace EditApproximation + + + +def BinaryBellmanAction.decode {Parent Child : Type*} {M : ℕ} + (action : BinaryBellmanAction Parent Child M) : RationalBellmanAction Parent Child M := + ⟨action.center, action.connection.value, action.childState⟩ + +namespace BinaryFraction + +open Finset + +def bellmanActionWithWork {Parent Child : Type*} {M : ℕ} + (distance : Parent → Parent → BinaryFraction × ℕ) (L : BinaryFraction) + (child : Child → BinaryFraction) (query : Parent) (action : BinaryBellmanAction Parent Child M) : + BinaryFraction × ℕ := + let dist := distance query action.center + let spatial := canonicalMulWithWork L dist.1 + let connection := canonicalAddWithWork spatial.1 action.connection + let children := sumListWithWork (List.ofFn fun i => child (action.childState i)) + let result := canonicalAddWithWork connection.1 children.1 + (result.1, dist.2 + spatial.2 + connection.2 + children.2 + result.2 + 3) + +@[simp] theorem bellmanActionWithWork_value {Parent Child : Type*} {M : ℕ} + (distance : Parent → Parent → BinaryFraction × ℕ) (L : BinaryFraction) + (child : Child → BinaryFraction) (query : Parent) (action : BinaryBellmanAction Parent Child M) : + (bellmanActionWithWork distance L child query action).1.value = + rationalActionValue (fun q r => (distance q r).1.value) L.value + (fun s => (child s).value) query action.decode := by + simp only [bellmanActionWithWork, canonicalAddWithWork_value, canonicalMulWithWork_value, + sumListWithWork_value, List.map_ofFn, List.sum_ofFn, rationalActionValue, BinaryBellmanAction.decode, Function.comp_def] + +def bellmanActionWordBudget (M B : ℕ) : ℕ := + 8 * (40 * B + 22 + bandMassTotalStorageBudget M B) + 6 + +def bellmanActionBitBudget (M B C : ℕ) : ℕ := + C + 2000 * (B + 1) ^ 2 + 6000 * (5 * B + 3) ^ 2 + storedSumBitBudget M B + 6 * M + + 6000 * (40 * B + 22 + bandMassTotalStorageBudget M B + 1) ^ 2 + 3 + +theorem bellmanActionWithWork_bounds {Parent Child : Type*} {M : ℕ} + (distance : Parent → Parent → BinaryFraction × ℕ) (L : BinaryFraction) + (child : Child → BinaryFraction) (query : Parent) (action : BinaryBellmanAction Parent Child M) + (B C : ℕ) (hL : L.width ≤ B) (hd : (distance query action.center).1.width ≤ B) + (hdc : (distance query action.center).2 ≤ C) (hconn : action.connection.width ≤ B) + (hchild : ∀ i, (child (action.childState i)).width ≤ B) : + (bellmanActionWithWork distance L child query action).1.width ≤ bellmanActionWordBudget M B ∧ + (bellmanActionWithWork distance L child query action).2 ≤ bellmanActionBitBudget M B C := by + have hsw := canonicalMulWithWork_width L (distance query action.center).1 B hL hd + have hsc := canonicalMulWithWork_cost L (distance query action.center).1 B hL hd + have hcw := canonicalAddWithWork_width (canonicalMulWithWork L (distance query action.center).1).1 + action.connection (5 * B + 2) (by omega) (by omega) + have hcc := canonicalAddWithWork_cost (canonicalMulWithWork L (distance query action.center).1).1 + action.connection (5 * B + 2) (by omega) (by omega) + have hlist : ∀ a ∈ (List.ofFn fun i => child (action.childState i)), a.width ≤ B := by + intro a ha + obtain ⟨i, rfl⟩ := List.mem_ofFn.mp ha + exact hchild i + have htw := sumListWithWork_width _ B hlist + have htc := sumListWithWork_cost _ B hlist + simp only [List.length_ofFn] at htw htc + have htotalw := canonicalAddWithWork_width + (canonicalAddWithWork (canonicalMulWithWork L (distance query action.center).1).1 action.connection).1 + (sumListWithWork (List.ofFn fun i => child (action.childState i))).1 + (40 * B + 22 + bandMassTotalStorageBudget M B) (by omega) (by omega) + have htotalc := canonicalAddWithWork_cost + (canonicalAddWithWork (canonicalMulWithWork L (distance query action.center).1).1 action.connection).1 + (sumListWithWork (List.ofFn fun i => child (action.childState i))).1 + (40 * B + 22 + bandMassTotalStorageBudget M B) (by omega) (by omega) + constructor + · exact htotalw + · simp only [Nat.add_assoc, Nat.reduceAdd] at hcc + change _ + _ + _ + _ + _ + 3 ≤ _ + unfold bellmanActionBitBudget + omega + +def bellmanWithWork {Parent Child : Type*} {M : ℕ} + (distance : Parent → Parent → BinaryFraction × ℕ) (L fallback : BinaryFraction) + (child : Child → BinaryFraction) (query : Parent) (actions : List (BinaryBellmanAction Parent Child M)) : + BinaryFraction × ℕ := + let scores := arithmeticMapWithWork (bellmanActionWithWork distance L child query) actions + let result := minimumWithWork fallback scores.1 + (result.1, scores.2 + result.2 + 1) + +@[simp] theorem bellmanWithWork_value {Parent Child : Type*} {M : ℕ} + (distance : Parent → Parent → BinaryFraction × ℕ) (L fallback : BinaryFraction) + (child : Child → BinaryFraction) (query : Parent) (actions : List (BinaryBellmanAction Parent Child M)) : + (bellmanWithWork distance L fallback child query actions).1.value = + rationalBellman (fun _ => fallback.value) (fun q r => (distance q r).1.value) L.value + (actions.map BinaryBellmanAction.decode) (fun s => (child s).value) query := by + simp only [bellmanWithWork, minimumWithWork_value, arithmeticMapWithWork_value, List.map_map, + Function.comp_def, bellmanActionWithWork_value, rationalBellman] + +def bellmanBitBudget (M n B F C : ℕ) : ℕ := + n * (bellmanActionBitBudget M B C + 3) + + (1 + n * (1000 * (F + bellmanActionWordBudget M B + 1) ^ 2 + 2)) + 1 + +theorem bellmanWithWork_bounds {Parent Child : Type*} {M : ℕ} + (distance : Parent → Parent → BinaryFraction × ℕ) (L fallback : BinaryFraction) + (child : Child → BinaryFraction) (query : Parent) (actions : List (BinaryBellmanAction Parent Child M)) + (B F C : ℕ) (hL : L.width ≤ B) (hf : fallback.width ≤ F) + (hd : ∀ action ∈ actions, (distance query action.center).1.width ≤ B) + (hdc : ∀ action ∈ actions, (distance query action.center).2 ≤ C) + (hc : ∀ action ∈ actions, action.connection.width ≤ B) + (hv : ∀ action ∈ actions, ∀ i, (child (action.childState i)).width ≤ B) : + (bellmanWithWork distance L fallback child query actions).1.width ≤ F + bellmanActionWordBudget M B ∧ + (bellmanWithWork distance L fallback child query actions).2 ≤ bellmanBitBudget M actions.length B F C := by + let scores := arithmeticMapWithWork (bellmanActionWithWork distance L child query) actions + have hs (value : BinaryFraction) (hvalue : value ∈ scores.1) : value.width ≤ bellmanActionWordBudget M B := by + simp only [scores, arithmeticMapWithWork_value] at hvalue + obtain ⟨action, ha, heq⟩ := List.mem_map.mp hvalue + subst value + exact (bellmanActionWithWork_bounds distance L child query action B C hL + (hd action ha) (hdc action ha) (hc action ha) (hv action ha)).1 + have hlen : scores.1.length = actions.length := by + simp only [scores, arithmeticMapWithWork_value, List.length_map] + have hmap := arithmeticMapWithWork_cost (bellmanActionWithWork distance L child query) actions + (bellmanActionBitBudget M B C) (fun action ha => + (bellmanActionWithWork_bounds distance L child query action B C hL + (hd action ha) (hdc action ha) (hc action ha) (hv action ha)).2) + have hminw := minimumWithWork_width fallback scores.1 (F + bellmanActionWordBudget M B) + (by omega) (fun value hv => (hs value hv).trans (by omega)) + have hminc := minimumWithWork_cost fallback scores.1 (F + bellmanActionWordBudget M B) + (by omega) (fun value hv => (hs value hv).trans (by omega)) + rw [hlen] at hminc + refine ⟨hminw, ?_⟩ + change scores.2 + (minimumWithWork fallback scores.1).2 + 1 ≤ _ + change scores.2 ≤ _ at hmap + unfold bellmanBitBudget + omega + + + +@[simp] theorem onlineMinimumWithWork_value (values : List BinaryFraction) : + ((onlineMinimumWithWork values).1.map value) = rationalOnlineMinimum (values.map value) := by + cases values with + | nil => rfl + | cons first rest => simp only [onlineMinimumWithWork, Option.map_some, minimumWithWork_value, + rationalOnlineMinimum, List.map_cons] + +theorem onlineMinimumWithWork_bounds (values : List BinaryFraction) (B : ℕ) + (hv : ∀ value ∈ values, value.width ≤ B) : + (∀ value ∈ (onlineMinimumWithWork values).1, value.width ≤ B) ∧ + (onlineMinimumWithWork values).2 ≤ 2 + values.length * (1000 * (B + 1) ^ 2 + 2) := by + cases values with + | nil => + constructor + · simp [onlineMinimumWithWork] + · change 1 ≤ 2 + 0 * _ + omega + | cons head rest => + have hw := minimumWithWork_width head rest B (hv head (by simp)) + (fun value h => hv value (by simp [h])) + have hc := minimumWithWork_cost head rest B (hv head (by simp)) + (fun value h => hv value (by simp [h])) + constructor + · intro value hvalue + have heq : value = (minimumWithWork head rest).1 := by simpa only [onlineMinimumWithWork, + Option.mem_def, Option.some.injEq] using hvalue.symm + exact heq ▸ hw + · change _ + 1 ≤ _ + simp only [List.length_cons, Nat.add_mul, Nat.one_mul] + omega + + + +@[simp] theorem refinementUpdateWithWork_value (delta cone : BinaryFraction) (online : Option BinaryFraction) : + (refinementUpdateWithWork delta cone online).1.value = + rationalRefinementUpdate delta.value cone.value (online.map value) := by + cases online with + | none => rfl + | some online => + simp only [refinementUpdateWithWork, minWithWork_value, maxWithWork_value, + divWithWork_value, canonicalAddWithWork_value, one, nat_value, + Nat.cast_one, Option.map_some, rationalRefinementUpdate] + +def refinementUpdateWordBudget (B : ℕ) : ℕ := 32 * B + 28 + +def refinementUpdateBitBudget (B : ℕ) : ℕ := + 6000 * (B + 1) ^ 2 + 2100 * (8 * B + 8) ^ 2 + + 2 * (1000 * (32 * B + 29) ^ 2 + 1) + 2 + +theorem refinementUpdateWithWork_bounds (delta cone : BinaryFraction) (online : Option BinaryFraction) + (B : ℕ) (hB : 1 ≤ B) (hd : delta.width ≤ B) (hc : cone.width ≤ B) + (ho : ∀ a ∈ online, a.width ≤ B) : + (refinementUpdateWithWork delta cone online).1.width ≤ refinementUpdateWordBudget B ∧ + (refinementUpdateWithWork delta cone online).2 ≤ refinementUpdateBitBudget B := by + cases online with + | none => + refine ⟨?_, ?_⟩ + · change cone.width ≤ _ + unfold refinementUpdateWordBudget + omega + · change 1 ≤ _ + unfold refinementUpdateBitBudget + omega + | some online => + have hwone : one.width ≤ B := by change 1 ≤ B; exact hB + have hdw := canonicalAddWithWork_width one delta B hwone hd + have hdc := canonicalAddWithWork_cost one delta B hwone hd + have hlw := divWithWork_width_uniform cone (canonicalAddWithWork one delta).1 (8 * B + 6) + (by omega) hdw + have hlc := divWithWork_cost cone (canonicalAddWithWork one delta).1 (8 * B + 6) + (by omega) hdw + have how : online.width ≤ B := ho online (by simp) + have hmaxw := maxWithWork_width (divWithWork cone (canonicalAddWithWork one delta).1).1 online + have hmaxc := maxWithWork_cost (divWithWork cone (canonicalAddWithWork one delta).1).1 online + (32 * B + 28) (by omega) (by omega) + have hminw := minWithWork_width cone (maxWithWork + (divWithWork cone (canonicalAddWithWork one delta).1).1 online).1 + have hminc := minWithWork_cost cone (maxWithWork + (divWithWork cone (canonicalAddWithWork one delta).1).1 online).1 (32 * B + 28) + (by omega) (by omega) + constructor + · change (minWithWork cone (maxWithWork + (divWithWork cone (canonicalAddWithWork one delta).1).1 online).1).1.width ≤ refinementUpdateWordBudget B + unfold refinementUpdateWordBudget + omega + · simp only [Nat.add_assoc, Nat.reduceAdd] at hlc hmaxc hminc + change _ + _ + _ + _ + 2 ≤ _ + unfold refinementUpdateBitBudget + omega + +/-- Numerical tail of the actual local refinement query, after its finite +wide, group and online lists have been prepared from gathered data. -/ +def localContinuationWithWork {Parent Child : Type*} {M : ℕ} + (distance : Parent → Parent → BinaryFraction × ℕ) (L delta fallback : BinaryFraction) + (old current : Child → BinaryFraction) (query : Parent) + (wide groups online : List (BinaryBellmanAction Parent Child M)) : BinaryFraction × ℕ := + let warm := bellmanWithWork distance L fallback old query wide + let cone := bellmanWithWork distance L warm.1 current query groups + let scores := arithmeticMapWithWork (bellmanActionWithWork distance L current query) online + let onlineMin := onlineMinimumWithWork scores.1 + let result := refinementUpdateWithWork delta cone.1 onlineMin.1 + (result.1, warm.2 + cone.2 + scores.2 + onlineMin.2 + result.2 + 3) + +@[simp] theorem localContinuationWithWork_value {Parent Child : Type*} {M : ℕ} + (distance : Parent → Parent → BinaryFraction × ℕ) (L delta fallback : BinaryFraction) + (old current : Child → BinaryFraction) (query : Parent) + (wide groups online : List (BinaryBellmanAction Parent Child M)) : + (localContinuationWithWork distance L delta fallback old current query wide groups online).1.value = + rationalRefinementUpdate delta.value + (rationalMinimum + (rationalBellman (fun _ => fallback.value) (fun q r => (distance q r).1.value) L.value + (wide.map BinaryBellmanAction.decode) (fun s => (old s).value) query) + ((groups.map BinaryBellmanAction.decode).map + (rationalActionValue (fun q r => (distance q r).1.value) L.value (fun s => (current s).value) query))) + (rationalOnlineMinimum ((online.map BinaryBellmanAction.decode).map + (rationalActionValue (fun q r => (distance q r).1.value) L.value (fun s => (current s).value) query))) := by + simp only [localContinuationWithWork, refinementUpdateWithWork_value, bellmanWithWork_value, + onlineMinimumWithWork_value, arithmeticMapWithWork_value, List.map_map, Function.comp_def, + bellmanActionWithWork_value, rationalBellman] + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryBellmanReads.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryBellmanReads.lean new file mode 100644 index 0000000000000000000000000000000000000000..4e2ae004737ff48319c8a184025d582a0ab3b161 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryBellmanReads.lean @@ -0,0 +1,86 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryBellmanKernel +import OAI.Combinatorics.EditApproximation.Binary.BinaryReadComposition +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Bellman action evaluation with literal finite-table reader calls. +Child words are gathered once, then Boolean arithmetic +operates on that stored list. Reader scans are part of the returned cost. -/ + +namespace EditApproximation +namespace BinaryFraction + + + +theorem bellmanActionReadWithWork_eq {Parent Child : Type*} {M : ℕ} + (distance : Parent → Parent → BinaryFraction × ℕ) (L : BinaryFraction) + (read : Child → BinaryFraction × ℕ) (query : Parent) + (action : BinaryBellmanAction Parent Child M) : + (bellmanActionReadWithWork distance L read query action).1 = + (bellmanActionWithWork distance L (fun s => (read s).1) query action).1 := by + simp only [bellmanActionReadWithWork, arithmeticMapWithWork_value, + bellmanActionWithWork, List.ofFn_eq_map] + +theorem bellmanActionReadWithWork_cost {Parent Child : Type*} {M : ℕ} + (distance : Parent → Parent → BinaryFraction × ℕ) (L : BinaryFraction) + (read : Child → BinaryFraction × ℕ) (query : Parent) + (action : BinaryBellmanAction Parent Child M) (R : ℕ) + (hread : ∀ i, (read (action.childState i)).2 ≤ R) : + (bellmanActionReadWithWork distance L read query action).2 ≤ + (bellmanActionWithWork distance L (fun s => (read s).1) query action).2 + M * (R + 3) := by + have h := arithmeticMapWithWork_cost (fun i => read (action.childState i)) + (List.finRange M) R (fun i _ => hread i) + simp only [List.length_finRange] at h + simp only [bellmanActionReadWithWork, arithmeticMapWithWork_value, + bellmanActionWithWork, List.ofFn_eq_map] + omega + + + +theorem bellmanReadWithWork_eq {Parent Child : Type*} {M : ℕ} + (distance : Parent → Parent → BinaryFraction × ℕ) (L fallback : BinaryFraction) + (read : Child → BinaryFraction × ℕ) (query : Parent) + (actions : List (BinaryBellmanAction Parent Child M)) : + (bellmanReadWithWork distance L fallback read query actions).1 = + (bellmanWithWork distance L fallback (fun s => (read s).1) query actions).1 := by + simp only [bellmanReadWithWork, bellmanWithWork, arithmeticMapWithWork_value, + bellmanActionReadWithWork_eq] + +theorem bellmanReadWithWork_cost {Parent Child : Type*} {M : ℕ} + (distance : Parent → Parent → BinaryFraction × ℕ) (L fallback : BinaryFraction) + (read : Child → BinaryFraction × ℕ) (query : Parent) + (actions : List (BinaryBellmanAction Parent Child M)) (R : ℕ) + (hread : ∀ action ∈ actions, ∀ i, (read (action.childState i)).2 ≤ R) : + (bellmanReadWithWork distance L fallback read query actions).2 ≤ + (bellmanWithWork distance L fallback (fun s => (read s).1) query actions).2 + + actions.length * (M * (R + 3)) := by + have h := arithmeticMapWithWork_extra + (bellmanActionReadWithWork distance L read query) + (bellmanActionWithWork distance L (fun s => (read s).1) query) + (fun _ => M * (R + 3)) actions + (fun action _ => bellmanActionReadWithWork_eq distance L read query action) + (fun action ha => bellmanActionReadWithWork_cost distance L read query action R (hread action ha)) + have hs : (actions.map (fun _ => M * (R + 3))).sum = actions.length * (M * (R + 3)) := by + simp only [List.map_const', List.sum_replicate, smul_eq_mul] + rw [hs] at h + unfold bellmanReadWithWork bellmanWithWork + dsimp only + rw [h.1] + omega + +theorem bellmanWithWork_action_count {Parent Child : Type*} {M : ℕ} + (distance : Parent → Parent → BinaryFraction × ℕ) (L fallback : BinaryFraction) + (child : Child → BinaryFraction) (query : Parent) + (actions : List (BinaryBellmanAction Parent Child M)) : + actions.length ≤ (bellmanWithWork distance L fallback child query actions).2 := by + have h := arithmeticMapWithWork_length_le_cost + (bellmanActionWithWork distance L child query) actions + change actions.length ≤ _ + _ + 1 + omega + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryBellmanSpace.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryBellmanSpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..18fa8cfd6d1af691461d416884cf6489544fdb09 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryBellmanSpace.lean @@ -0,0 +1,57 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryBellmanReads +import OAI.Combinatorics.EditApproximation.Binary.BinaryGeometrySpace +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation.BinaryFraction + +/-- Actual temporary cells allocated while scoring one action; child values +are retained pointers and their lookup scratch is counted by `footprint`. -/ + + +theorem bellmanActionReadAllocation_le_work {Parent Child : Type*} {M : ℕ} + (distance : Parent → Parent → BinaryFraction × ℕ) (distanceAllocation : Parent → Parent → ℕ) + (L : BinaryFraction) (read : Child → BinaryFraction × ℕ) (footprint : Child → ℕ) + (query : Parent) (action : BinaryBellmanAction Parent Child M) + (hd : distanceAllocation query action.center ≤ (distance query action.center).2) + (hr : ∀ i, footprint (action.childState i) ≤ (read (action.childState i)).2) : + bellmanActionReadAllocation distance distanceAllocation L read footprint query action ≤ + (bellmanActionReadWithWork distance L read query action).2 := by + have hw := arithmeticMapAllocation_le_work (fun i => read (action.childState i)) + (fun i => footprint (action.childState i)) (List.finRange M) (fun i _ => hr i) + have hm := canonicalMulAllocation_le_work L (distance query action.center).1 + have ha := canonicalAddAllocation_le_work (canonicalMulWithWork L (distance query action.center).1).1 action.connection + let words := (arithmeticMapWithWork (fun i => read (action.childState i)) (List.finRange M)).1 + have hs := sumListAllocation_le_work words + have hf := canonicalAddAllocation_le_work + (canonicalAddWithWork (canonicalMulWithWork L (distance query action.center).1).1 action.connection).1 + (sumListWithWork words).1 + unfold bellmanActionReadAllocation bellmanActionReadWithWork + dsimp only [words] at hs hf ⊢ + omega + + + +theorem bellmanReadAllocation_le_work {Parent Child : Type*} {M : ℕ} + (distance : Parent → Parent → BinaryFraction × ℕ) (distanceAllocation : Parent → Parent → ℕ) + (L fallback : BinaryFraction) (read : Child → BinaryFraction × ℕ) (footprint : Child → ℕ) + (query : Parent) (actions : List (BinaryBellmanAction Parent Child M)) + (hd : ∀ action ∈ actions, distanceAllocation query action.center ≤ (distance query action.center).2) + (hr : ∀ action ∈ actions, ∀ i, footprint (action.childState i) ≤ (read (action.childState i)).2) : + bellmanReadAllocation distance distanceAllocation L fallback read footprint query actions ≤ + (bellmanReadWithWork distance L fallback read query actions).2 := by + have hs := arithmeticMapAllocation_le_work (bellmanActionReadWithWork distance L read query) + (bellmanActionReadAllocation distance distanceAllocation L read footprint query) actions + (fun action ha => bellmanActionReadAllocation_le_work distance distanceAllocation L read footprint + query action (hd action ha) (hr action ha)) + have hm := minimumAllocation_le_work fallback + (arithmeticMapWithWork (bellmanActionReadWithWork distance L read query) actions).1 + unfold bellmanReadAllocation bellmanReadWithWork + dsimp only + omega + +end EditApproximation.BinaryFraction + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryBufferInputBounds.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryBufferInputBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..80cb291ecf578ae68ec8aba9540698289d00e234 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryBufferInputBounds.lean @@ -0,0 +1,40 @@ +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalPreparedInputBounds +import OAI.Combinatorics.EditApproximation.Geometry.RefinementBufferRanges + +namespace OAI + +/-! A refinement continuation has a separate current-index buffer. +Only the earlier-history buffer enters the online objective, so its +range invariant does not require any relation at unused current keys. -/ + +namespace EditApproximation +namespace BinaryFraction + +theorem PreparedKernelNumericBounds.with_independent_cached_values {nx ny M : ℕ} + {N P F exponent H Q eM eF B E S t : ℕ} + {tau a eta kappa delta : BinaryFraction} + {integer : ℕ → TargetInterval ny → ℕ} + (hn : PreparedKernelNumericBounds (nx := nx) (M := M) + N P F exponent H Q eM eF B E S t tau a eta kappa delta integer) + (parentInitial : TargetInterval ny → BinaryFraction) + (childMass childInitial : Fin M → TargetInterval ny → BinaryFraction) + (old current : Fin M × TargetInterval ny → BinaryFraction) + (history : ℕ → Fin M × TargetInterval ny → BinaryFraction) + (hp : ∀ r, (parentInitial r).width ≤ B) + (hm : ∀ i r, (childMass i r).width ≤ B) + (hi : ∀ i r, (childInitial i r).width ≤ B) + (ho : ∀ input, (old input).width ≤ B) + (hc : ∀ input, (current input).width ≤ B) + (hh : ∀ s ≤ t + 1, ∀ i r, (history s (i, r)).width ≤ B) + (hpnonneg : ∀ r, 0 ≤ (parentInitial r).value) + (hrange : ∀ s ≤ t + 1, ∀ i r, 0 ≤ (history s (i, r)).value ∧ + (history s (i, r)).value ≤ (childInitial i r).value) : + PreparedKernelInputBounds (nx := nx) N P F exponent H Q eM eF B E S t + tau a eta kappa delta parentInitial childMass childInitial old current history integer := by + exact { (hn.with_cached_values parentInitial childMass childInitial history + hp hm hi hh hpnonneg hrange) with oldSize := ho, currentSize := hc } + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryBufferSpace.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryBufferSpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..b24cbbe1782e40d24706b727f66e854474e943c2 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryBufferSpace.lean @@ -0,0 +1,101 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryGatheredValues +import OAI.Combinatorics.EditApproximation.Binary.BinaryLoopSpace +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Stored key/value words and the actual linear lookup call tree. Reads +return pointers to retained words; only comparison scratch is fresh. -/ + +namespace EditApproximation.BinaryFraction + +def storedCells (word : BinaryFraction) : ℕ := + word.numerator.bits.length + word.denominator.length + 1 + +def bufferCells {κ : Type*} (code : κ → ℕ) (keys : List κ) (values : List BinaryFraction) : ℕ := + (keys.map fun key => Nat.size (code key) + 1).sum + + (values.map fun value => storedCells value + 1).sum + +theorem storedCells_le_width (word : BinaryFraction) : storedCells word ≤ 2 * word.width + 1 := by + have hn : word.numerator.bits.length ≤ word.width := le_max_left _ _ + have hd : word.denominator.length ≤ word.width := le_max_right _ _ + unfold storedCells + omega + +theorem bufferCells_le {κ : Type*} (code : κ → ℕ) (keys : List κ) (values : List BinaryFraction) + (B : ℕ) (hk : ∀ key ∈ keys, Nat.size (code key) ≤ B) + (hv : ∀ value ∈ values, value.width ≤ B) : + bufferCells code keys values ≤ keys.length * (B + 1) + values.length * (2 * B + 2) := by + have hkeys := sum_map_le_length_mul keys (fun key => Nat.size (code key) + 1) (B + 1) + (fun key hkey => Nat.add_le_add_right (hk key hkey) 1) + have hvalues := sum_map_le_length_mul values (fun value => storedCells value + 1) (2 * B + 2) + (fun value hvalue => by have h := storedCells_le_width value; have hb := hv value hvalue; omega) + unfold bufferCells + omega + +theorem bufferCells_le_fourthPower {κ : Type*} (code : κ → ℕ) + (keys : List κ) (values : List BinaryFraction) (B X : ℕ) + (hX : 4 ≤ X) (hk : ∀ key ∈ keys, Nat.size (code key) ≤ B) + (hv : ∀ value ∈ values, value.width ≤ B) + (hkeys : keys.length ≤ X) (hvalues : values.length ≤ X) (hB : B ≤ X) : + bufferCells code keys values ≤ X ^ 4 := by + have h := bufferCells_le code keys values B hk hv + have h1 := Nat.mul_le_mul hkeys (Nat.add_le_add_right hB 1) + have h2 := Nat.mul_le_mul hvalues (show 2 * B + 2 ≤ 2 * X + 2 by omega) + have hsmall : keys.length * (B + 1) + values.length * (2 * B + 2) ≤ 4 * X ^ 2 := by + nlinarith only [hX, h1, h2] + have hsq : 4 ≤ X ^ 2 := by nlinarith only [hX] + exact h.trans (hsmall.trans (by + calc + 4 * X ^ 2 ≤ X ^ 2 * X ^ 2 := Nat.mul_le_mul_right _ hsq + _ = X ^ 4 := by ring)) + + + +def gatheredLookupInvocations {κ : Type*} (equal : κ → κ → Bool × ℕ) + (invocations : κ → κ → ℕ) : List κ → List BinaryFraction → κ → ℕ + | key :: keys, _value :: values, query => + invocations query key + if (equal query key).1 then 1 + else gatheredLookupInvocations equal invocations keys values query + 1 + | _, _, _ => 1 + +theorem gatheredLookupAllocation_le_work {κ : Type*} (equal : κ → κ → Bool × ℕ) + (allocation : κ → κ → ℕ) (keys : List κ) (values : List BinaryFraction) (query : κ) + (h : ∀ key ∈ keys, allocation query key ≤ (equal query key).2) : + gatheredLookupAllocation equal allocation keys values query ≤ + (gatheredWordLookupWithWork equal keys values query).2 := by + induction keys generalizing values with + | nil => exact Nat.zero_le 1 + | cons key keys ih => + cases values with + | nil => exact Nat.zero_le 1 + | cons value values => + have hc := h key List.mem_cons_self + have ht := ih values (fun k hk => h k (List.mem_cons_of_mem _ hk)) + unfold gatheredLookupAllocation gatheredWordLookupWithWork + dsimp only + split_ifs <;> dsimp only + · exact Nat.add_le_add hc (Nat.zero_le 1) + · exact (Nat.add_le_add hc ht).trans (Nat.le_succ _) + +theorem gatheredLookupInvocations_le_work {κ : Type*} (equal : κ → κ → Bool × ℕ) + (invocations : κ → κ → ℕ) (keys : List κ) (values : List BinaryFraction) (query : κ) + (h : ∀ key ∈ keys, invocations query key ≤ (equal query key).2) : + gatheredLookupInvocations equal invocations keys values query ≤ + (gatheredWordLookupWithWork equal keys values query).2 := by + induction keys generalizing values with + | nil => rfl + | cons key keys ih => + cases values with + | nil => rfl + | cons value values => + have hc := h key List.mem_cons_self + have ht := ih values (fun k hk => h k (List.mem_cons_of_mem _ hk)) + unfold gatheredLookupInvocations gatheredWordLookupWithWork + dsimp only + split_ifs <;> dsimp only <;> omega + +end EditApproximation.BinaryFraction + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryCachedContinuation.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryCachedContinuation.lean new file mode 100644 index 0000000000000000000000000000000000000000..c2c60d70c2245110c122d028c35cb9ae60942420 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryCachedContinuation.lean @@ -0,0 +1,69 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryPhysicalContinuation +import OAI.Combinatorics.EditApproximation.Binary.BinaryPowerStorage +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Cache insertion compresses the actual continuation result by executed +Boolean multiplication and division. Its cost is part of the return +counter; no rational normalization operation is assigned unit cost. -/ + +namespace EditApproximation +namespace BinaryFraction + + + +theorem finishCachedWithWork_value (raw : BinaryFraction × ℕ) (base : List Bool) + (hbase : 0 < bitWordValue base) (remaining : ℕ) + (hden : raw.1.value.den ∣ bitWordValue base ^ remaining) : + (finishCachedWithWork raw base hbase remaining).1.value = raw.1.value := + powerDenominatorWithWork_value raw.1 base hbase remaining hden + +theorem finishCachedWithWork_bounds (raw : BinaryFraction × ℕ) (base : List Bool) + (hbase : 0 < bitWordValue base) (remaining A B C V : ℕ) + (ha : raw.1.width ≤ A) (hb : base.length ≤ B) (hc : raw.2 ≤ C) + (hden : raw.1.value.den ∣ bitWordValue base ^ remaining) (hv : |raw.1.value| ≤ V) : + (finishCachedWithWork raw base hbase remaining).1.width ≤ + Nat.size V + 2 * (remaining * B + 1) + 1 ∧ + (finishCachedWithWork raw base hbase remaining).2 ≤ + C + powerDenominatorBitBudget remaining A B + 1 := by + refine ⟨powerDenominatorWithWork_width raw.1 base hbase remaining V B hb hden hv, ?_⟩ + exact Nat.add_le_add_right (Nat.add_le_add hc + (powerDenominatorWithWork_cost raw.1 base hbase remaining A B ha hb)) 1 + +def cachedPhysicalContinuationWithWork {nx ny M : ℕ} (parent : TargetInterval nx) + (representatives : List (ℕ × TargetInterval ny)) (P F : ℕ) + (delta fallback : BinaryFraction) + (old current : Fin M × TargetInterval ny → BinaryFraction) + (groups online : List (BinaryBellmanAction (TargetInterval ny) (Fin M × TargetInterval ny) M)) + (query : TargetInterval ny) (base : List Bool) (hbase : 0 < bitWordValue base) (remaining : ℕ) : + BinaryFraction × ℕ := + finishCachedWithWork + (physicalContinuationWithWork parent representatives P F delta fallback old current groups online query) + base hbase remaining + +theorem cachedPhysicalContinuationWithWork_value {nx ny M : ℕ} (parent : TargetInterval nx) + (representatives : List (ℕ × TargetInterval ny)) (P F : ℕ) + (delta fallback : BinaryFraction) + (old current : Fin M × TargetInterval ny → BinaryFraction) + (groups online : List (BinaryBellmanAction (TargetInterval ny) (Fin M × TargetInterval ny) M)) + (query : TargetInterval ny) (base : List Bool) (hbase : 0 < bitWordValue base) (remaining : ℕ) + (hP : 0 < P) + (hden : (rationalWideStep parent representatives P (fun _ => fallback.value) (128 * F) delta.value + (fun s => (old s).value) (fun s => (current s).value) + (groups.map BinaryBellmanAction.decode) (online.map BinaryBellmanAction.decode) query).den ∣ + bitWordValue base ^ remaining) : + (cachedPhysicalContinuationWithWork parent representatives P F delta fallback old current groups online + query base hbase remaining).1.value = + rationalWideStep parent representatives P (fun _ => fallback.value) (128 * F) delta.value + (fun s => (old s).value) (fun s => (current s).value) + (groups.map BinaryBellmanAction.decode) (online.map BinaryBellmanAction.decode) query := by + apply (finishCachedWithWork_value _ base hbase remaining ?_).trans + (physicalContinuationWithWork_value parent representatives P F delta fallback old current groups online query hP) + rwa [physicalContinuationWithWork_value parent representatives P F delta fallback old current groups online query hP] + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryCachedShellWork.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryCachedShellWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..0a409b9d81bc3ba73bd27fd0592ec09b6896588b --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryCachedShellWork.lean @@ -0,0 +1,180 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryInitialGridWork +import OAI.Combinatorics.EditApproximation.Binary.BinaryLocalWarmupWork +import OAI.Combinatorics.EditApproximation.Binary.BinaryCachedContinuation +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalDenominator + +namespace OAI + +/-! Initial and warmup returns are integers on every seed. Their cache +representation is produced by the counted fixed-denominator routine, rather +than by an uncharged conversion of a rational value. -/ + +namespace EditApproximation + +theorem localInitialConeTable_den_one {α : Type*} (source target : List α) + (U : TargetInterval target.length → ℕ) (N P F : ℕ) (A a : ℚ) + (query : TargetInterval target.length) : + (localInitialConeTable source target U N P F A a query).den = 1 := by + unfold localInitialConeTable + split_ifs + · exact Rat.den_zero + · apply Nat.eq_one_of_dvd_one + apply rationalMinimum_den_dvd + · have heq : (32 * F + 1 : ℚ) * N = (((32 * F + 1) * N : ℕ) : ℚ) := by + push_cast + rfl + rw [heq, Rat.den_natCast] + · intro v hv + obtain ⟨r, _, rfl⟩ := List.mem_map.mp hv + unfold initialConeValue scaledSeedValue + apply rat_den_add_dvd + · apply rat_den_max_dvd + · simp only [Rat.den_natCast, dvd_refl] + · have heq : rationalStateGap source target r = + (((r.hi : ℤ) - r.lo - source.length : ℤ) : ℚ) := by + simp only [rationalStateGap, Int.cast_sub, Int.cast_natCast] + rw [heq, ← Int.cast_abs] + simp only [Rat.den_intCast, dvd_refl] + · have heq : (32 * F : ℚ) * targetEndpointDistance query r = + ((32 * F * targetEndpointDistance query r : ℕ) : ℚ) := by + push_cast + rfl + rw [heq, Rat.den_natCast] + +namespace BinaryFraction + +attribute [local irreducible] initialProgramWithWork localWarmupKernelWithWork + +def cachedInitialProgramWithWork {n : ℕ} (sourceLength N P F : ℕ) (A a : BinaryFraction) + (U : TargetInterval n → ℕ) (query : TargetInterval n) : BinaryFraction × ℕ := + finishCachedWithWork (initialProgramWithWork sourceLength N P F A a U query) + [true] (by decide) 0 + +def cachedInitialProgramBitBudget (P Amax B : ℕ) : ℕ := + initialProgramBitBudget P Amax B + powerDenominatorBitBudget 0 (initialMinimumWordBudget (B + 4)) 1 + 1 + +theorem cachedInitialProgramWithWork_cost {n : ℕ} (sourceLength N P F Amax B : ℕ) + (A a : BinaryFraction) (U : TargetInterval n → ℕ) (q : TargetInterval n) + (hB : 8 ≤ B) (hP : 0 < P) (hN : Nat.size N ≤ B) (hPb : Nat.size P ≤ B) + (hF : Nat.size F ≤ B) (hs : Nat.size sourceLength ≤ B) (hn : Nat.size n ≤ B) + (hU : ∀ r, Nat.size (U r) ≤ B) (hAb : A.width ≤ B) (ha : a.width ≤ B) + (hA : 1 ≤ A.value) (hmax : A.value ≤ Amax) : + (cachedInitialProgramWithWork sourceLength N P F A a U q).2 ≤ + cachedInitialProgramBitBudget P Amax B := by + have hb := initialProgramWithWork_bounds sourceLength N P F Amax B A a U q + hB hP hN hPb hF hs hn hU hAb ha hA hmax + have hc := powerDenominatorWithWork_cost + (initialProgramWithWork sourceLength N P F A a U q).1 [true] (by decide) 0 + (initialMinimumWordBudget (B + 4)) 1 hb.1 (by decide) + exact Nat.add_le_add_right (Nat.add_le_add hb.2 hc) 1 + +theorem cachedInitialProgramWithWork_value_width {α : Type*} (source target : List α) + (N P F : ℕ) (A a : BinaryFraction) (U : TargetInterval target.length → ℕ) + (query : TargetInterval target.length) (hP : 0 < P) : + (cachedInitialProgramWithWork source.length N P F A a U query).1.value = + localInitialConeTable source target U N P F A.value a.value query ∧ + (cachedInitialProgramWithWork source.length N P F A a U query).1.width ≤ + Nat.size ((32 * F + 1) * N) + 3 := by + let raw := initialProgramWithWork source.length N P F A a U query + have hraw := initialProgramWithWork_value source target N P F A a U query hP + have hd : raw.1.value.den ∣ bitWordValue [true] ^ 0 := by + rw [hraw, localInitialConeTable_den_one] + exact one_dvd _ + have hv : |raw.1.value| ≤ (((32 * F + 1) * N : ℕ) : ℚ) := by + rw [hraw, abs_of_nonneg (localInitialConeTable_nonneg source target U N P F A.value a.value query)] + unfold localInitialConeTable + split_ifs + · exact Nat.cast_nonneg _ + · simpa only [Nat.cast_mul, Nat.cast_add, Nat.cast_one, Nat.cast_ofNat] using + rationalMinimum_le_fallback ((32 * F + 1 : ℚ) * N) _ + exact ⟨(finishCachedWithWork_value raw [true] (by decide) 0 hd).trans hraw, + by + change (powerDenominatorWithWork raw.1 [true] (by decide) 0).1.width ≤ _ + simpa only [Nat.zero_mul, Nat.zero_add, Nat.one_mul, Nat.mul_one, Nat.add_assoc, Nat.reduceAdd] using + powerDenominatorWithWork_width raw.1 [true] (by decide) 0 ((32 * F + 1) * N) 1 + (by decide) hd hv⟩ + +def cachedLocalWarmupKernelWithWork {nx ny M : ℕ} (parent : TargetInterval nx) + (N P F : ℕ) (a : BinaryFraction) (initial : TargetInterval ny → BinaryFraction) + (child : Fin M × TargetInterval ny → BinaryFraction) (query : TargetInterval ny) : + BinaryFraction × ℕ := + finishCachedWithWork (localWarmupKernelWithWork parent N P F a initial child query) + [true] (by decide) 0 + +theorem localWarmupKernelWithWork_integer_bounds {nx ny M : ℕ} (parent : TargetInterval nx) + (N P F V : ℕ) (a : BinaryFraction) (initial : TargetInterval ny → BinaryFraction) + (child : Fin M × TargetInterval ny → BinaryFraction) (query : TargetInterval ny) + (hP : 0 < P) (hi : ∀ r, (initial r).value.den = 1) + (hic : ∀ r, 0 ≤ (initial r).value ∧ (initial r).value ≤ V) + (hc : ∀ s, (child s).value.den = 1) (hcn : ∀ s, 0 ≤ (child s).value) : + (localWarmupKernelWithWork parent N P F a initial child query).1.value.den = 1 ∧ + |(localWarmupKernelWithWork parent N P F a initial child query).1.value| ≤ V := by + rw [localWarmupKernelWithWork_value parent N P F hP a initial child query] + let actions := rationalActualWideActions (M := M) parent + (localRefinementRepresentatives N P F a.value (fun q => (initial q).value) query) P + have hd : (rationalBellman (fun q => (initial q).value) + (fun p q => (targetEndpointDistance p q : ℚ)) (128 * F) actions + (fun s => (child s).value) query).den ∣ 1 := by + apply rationalMinimum_den_dvd + · rw [hi] + · intro value hv + obtain ⟨action, ha, rfl⟩ := List.mem_map.mp hv + apply rationalActionValue_den_dvd + · exact Rat.den_natCast _ + · simpa only [Nat.cast_mul, Nat.cast_ofNat] using Rat.den_natCast (128 * F) + · exact rationalActualWideActions_connection_den parent _ P action ha + · intro i + rw [hc] + have hn : 0 ≤ rationalBellman (fun q => (initial q).value) + (fun p q => (targetEndpointDistance p q : ℚ)) (128 * F) actions + (fun s => (child s).value) query := by + apply (le_rationalMinimum_iff _ _ _).2 + refine ⟨(hic query).1, ?_⟩ + intro value hv + obtain ⟨action, ha, rfl⟩ := List.mem_map.mp hv + unfold rationalActionValue + exact add_nonneg (add_nonneg (mul_nonneg (by positivity) (Nat.cast_nonneg _)) + (rationalActualWideActions_connection_nonneg parent _ P action ha)) + (Finset.sum_nonneg fun i _ => hcn _) + refine ⟨Nat.eq_one_of_dvd_one hd, ?_⟩ + rw [abs_of_nonneg hn] + exact (rationalMinimum_le_fallback _ _).trans (hic query).2 + +theorem cachedLocalWarmupKernelWithWork_value_width {nx ny M : ℕ} (parent : TargetInterval nx) + (N P F V : ℕ) (a : BinaryFraction) (initial : TargetInterval ny → BinaryFraction) + (child : Fin M × TargetInterval ny → BinaryFraction) (query : TargetInterval ny) + (hP : 0 < P) (hi : ∀ r, (initial r).value.den = 1) + (hic : ∀ r, 0 ≤ (initial r).value ∧ (initial r).value ≤ V) + (hc : ∀ s, (child s).value.den = 1) (hcn : ∀ s, 0 ≤ (child s).value) : + (cachedLocalWarmupKernelWithWork parent N P F a initial child query).1.value = + (localWarmupKernelWithWork parent N P F a initial child query).1.value ∧ + (cachedLocalWarmupKernelWithWork parent N P F a initial child query).1.width ≤ Nat.size V + 3 := by + let raw := localWarmupKernelWithWork parent N P F a initial child query + have hb := localWarmupKernelWithWork_integer_bounds parent N P F V a initial child query hP hi hic hc hcn + have hd : raw.1.value.den ∣ bitWordValue [true] ^ 0 := by rw [hb.1]; exact one_dvd _ + exact ⟨finishCachedWithWork_value raw [true] (by decide) 0 hd, + by + change (powerDenominatorWithWork raw.1 [true] (by decide) 0).1.width ≤ _ + simpa only [Nat.zero_mul, Nat.zero_add, Nat.one_mul, Nat.mul_one, Nat.add_assoc, Nat.reduceAdd] using + powerDenominatorWithWork_width raw.1 [true] (by decide) 0 V 1 (by decide) hd hb.2⟩ + +theorem cachedLocalWarmupKernelWithWork_cost {nx ny M : ℕ} (parent : TargetInterval nx) + (N P F B : ℕ) (a : BinaryFraction) (initial : TargetInterval ny → BinaryFraction) + (child : Fin M × TargetInterval ny → BinaryFraction) (query : TargetInterval ny) + (hP : 0 < P) (hFpos : 1 ≤ F) (hB : 10 ≤ B) (hN : Nat.size N ≤ B) + (hnx : Nat.size nx + 2 ≤ B) (hny : Nat.size ny + 2 ≤ B) (hM : Nat.size M ≤ B) + (hPbits : Nat.size P ≤ B) (hF : Nat.size F + 2 ≤ B) (ha : a.width ≤ B) + (hi : ∀ r, (initial r).width ≤ B) (hc : ∀ s, (child s).width ≤ B) : + (cachedLocalWarmupKernelWithWork parent N P F a initial child query).2 ≤ + localWarmupBitBudget M P F B + powerDenominatorBitBudget 0 (localWarmupWordBudget M B) 1 + 1 := by + have hb := localWarmupKernelWithWork_bounds parent N P F B hP hFpos a initial child query + hB hN hnx hny hM hPbits hF ha hi hc + have hp := powerDenominatorWithWork_cost + (localWarmupKernelWithWork parent N P F a initial child query).1 [true] (by decide) 0 + (localWarmupWordBudget M B) 1 hb.1 (by decide) + exact Nat.add_le_add_right (Nat.add_le_add hb.2 hp) 1 + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryCanonicalWork.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryCanonicalWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..746cb4a70449b83e5b4d760f50cd7631cd5f8cda --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryCanonicalWork.lean @@ -0,0 +1,57 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryArithmeticWork +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Removing only leading zero bits of an integer word. This is unrelated +to rational reduction: no common divisor is computed. -/ + +namespace EditApproximation + + + +theorem trimBitWordWithWork_value (bits : List Bool) : + bitWordValue (trimBitWordWithWork bits).1 = bitWordValue bits := by + induction bits with + | nil => rfl + | cons bit bits ih => + simp only [trimBitWordWithWork] + split_ifs with h + · have ht : bitWordValue bits = 0 := by rw [← ih, h.1]; rfl + simp [h.2, bitWordValue, ht] + · simp only [bitWordValue, ih] + +theorem trimBitWordWithWork_canonical (bits : List Bool) : + (trimBitWordWithWork bits).1 = (bitWordValue bits).bits := by + induction bits with + | nil => rfl + | cons bit bits ih => + by_cases hzero : bitWordValue bits = 0 + · rw [trimBitWordWithWork, ih, hzero] + cases bit <;> simp [bitWordValue, hzero] + · have hnonempty : (bitWordValue bits).bits ≠ [] := by + intro h + have hv := bitWordValue_bits (bitWordValue bits) + rw [h] at hv + exact hzero hv.symm + have hvalue : bitWordValue (bit :: bits) = Nat.bit bit (bitWordValue bits) := by + cases bit <;> simp [bitWordValue, Nat.bit, Nat.add_comm] + rw [trimBitWordWithWork, ih, ite_eq_right (by simp [hnonempty]), hvalue, + Nat.bits_append_bit _ _ (fun h => False.elim (hzero h))] + +theorem trimBitWordWithWork_length (bits : List Bool) : + (trimBitWordWithWork bits).1.length = Nat.size (bitWordValue bits) := by + rw [trimBitWordWithWork_canonical, Nat.size_eq_bits_len] + +theorem trimBitWordWithWork_cost (bits : List Bool) : + (trimBitWordWithWork bits).2 = 3 * bits.length + 1 := by + induction bits with + | nil => rfl + | cons bit bits ih => + simp only [trimBitWordWithWork, List.length_cons, ih] + omega + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryCeilingWork.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryCeilingWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..9de0cd9b23a5b78096a5e8886084cfa8667c29cd --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryCeilingWork.lean @@ -0,0 +1,105 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryDivisionWork +import OAI.Combinatorics.EditApproximation.Binary.BinaryRawCost +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Exact natural ceilings from the executed binary quotient and remainder. +Negative fractions have natural ceiling zero, as in the seed update. -/ + +namespace EditApproximation + + + +theorem bitCeilDivWithWork_value (divisor bits : List Bool) (hd : 0 < bitWordValue divisor) : + bitWordValue (bitCeilDivWithWork divisor bits).1 = + ⌈((bitWordValue bits : ℚ) / bitWordValue divisor)⌉₊ := by + let q := bitWordValue (bitDivModWithWork divisor bits).1 + let r := bitWordValue (bitDivModWithWork divisor bits).2.1 + have h := bitDivModWithWork_value divisor bits hd + have heq : bitWordValue bits = bitWordValue divisor * q + r := h.1 + have hr : r < bitWordValue divisor := h.2 + have hdQ : (0 : ℚ) < bitWordValue divisor := by exact_mod_cast hd + unfold bitCeilDivWithWork + dsimp only + split_ifs with hz + · have hr0 : r = 0 := by + exact (bitCompareWithWork_eq (bitDivModWithWork divisor bits).2.1 []).1 hz + have hratio : (bitWordValue bits : ℚ) / bitWordValue divisor = (q : ℚ) := by + apply (div_eq_iff hdQ.ne').mpr + exact_mod_cast (show bitWordValue bits = q * bitWordValue divisor by nlinarith only [heq, hr0]) + rw [hratio] + exact (Nat.ceil_natCast q).symm + · have hr0 : r ≠ 0 := by + intro hzero + exact hz ((bitCompareWithWork_eq (bitDivModWithWork divisor bits).2.1 []).2 hzero) + rw [bitAddWithWork_value] + change q + 1 + 0 = _ + simp only [Nat.add_zero] + symm + apply (Nat.ceil_eq_iff (by omega : q + 1 ≠ 0)).mpr + constructor + · simp only [Nat.add_sub_cancel] + rw [lt_div_iff₀ hdQ] + exact_mod_cast (show q * bitWordValue divisor < bitWordValue bits by + nlinarith only [heq, Nat.pos_of_ne_zero hr0]) + · rw [div_le_iff₀ hdQ] + push_cast + exact_mod_cast (show bitWordValue bits ≤ (q + 1) * bitWordValue divisor by nlinarith only [heq, hr]) + +theorem bitCeilDivWithWork_length (divisor bits : List Bool) : + (bitCeilDivWithWork divisor bits).1.length ≤ bits.length + 2 := by + have hq := (bitDivModWithWork_lengths divisor bits).1 + have ha := bitAddWithWork_length (bitDivModWithWork divisor bits).1 [true] false + unfold bitCeilDivWithWork + dsimp only + split_ifs <;> dsimp only + · omega + · simp only [List.length_cons, List.length_nil] at ha + omega + +theorem bitCeilDivWithWork_cost (divisor bits : List Bool) : + (bitCeilDivWithWork divisor bits).2 ≤ + 100 * (bits.length + divisor.length + 1) ^ 2 := by + have hdiv := bitDivModWithWork_cost divisor bits + have hl := bitDivModWithWork_lengths divisor bits + have hc := bitCompareWithWork_cost (bitDivModWithWork divisor bits).2.1 [] + have ha := bitAddWithWork_cost (bitDivModWithWork divisor bits).1 [true] false + simp only [List.length_nil, List.length_cons, Nat.add_zero] at hc ha + unfold bitCeilDivWithWork + dsimp only + split_ifs <;> dsimp only <;> nlinarith only [hdiv, hl.1, hl.2, hc, ha] + +namespace BinaryFraction + + + +theorem naturalCeilingWithWork_value (a : BinaryFraction) : + bitWordValue (a.naturalCeilingWithWork).1 = ⌈a.value⌉₊ := by + cases hs : a.numerator.negative + · simpa only [naturalCeilingWithWork, hs, Bool.false_eq_true, ↓reduceIte, + value, SignedBinary.value, signedMagnitude, Int.cast_natCast] using + bitCeilDivWithWork_value a.denominator a.numerator.bits a.denominator_pos + · have hn : a.value ≤ 0 := by + simp only [value, SignedBinary.value, signedMagnitude, hs, ↓reduceIte, Int.cast_neg, Int.cast_natCast] + exact div_nonpos_of_nonpos_of_nonneg (neg_nonpos.mpr (Nat.cast_nonneg _)) (Nat.cast_nonneg _) + simp only [naturalCeilingWithWork, hs, ↓reduceIte, bitWordValue] + exact (Nat.ceil_eq_zero.mpr hn).symm + +theorem naturalCeilingWithWork_cost (a : BinaryFraction) : + (a.naturalCeilingWithWork).2 ≤ 500 * (a.width + 1) ^ 2 := by + have hn : a.numerator.bits.length ≤ a.width := le_max_left _ _ + have hd : a.denominator.length ≤ a.width := le_max_right _ _ + have hc := bitCeilDivWithWork_cost a.denominator a.numerator.bits + unfold naturalCeilingWithWork + split_ifs <;> dsimp only + · nlinarith only [Nat.zero_le a.width] + · have hm := Nat.mul_self_le_mul_self (show a.numerator.bits.length + a.denominator.length + 1 ≤ + 2 * a.width + 1 by omega) + nlinarith only [hc, hm, Nat.zero_le a.width] + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryCellCenters.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryCellCenters.lean new file mode 100644 index 0000000000000000000000000000000000000000..e57689d472e7aea75006ba644986a986d74eca4f --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryCellCenters.lean @@ -0,0 +1,44 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryCellGrid +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Literal eligibility scans for the whole-cell representative list. -/ + +namespace EditApproximation +namespace BinaryFraction + + + +@[simp] theorem centerEligibilityWithWork_value (b F : ℕ) (a initial : BinaryFraction) : + (centerEligibilityWithWork b F a initial).1 = true ↔ + (b : ℚ) / (4 * a.value) ≤ initial.value ∧ initial.value ≤ 8 * F * b := by + simp only [centerEligibilityWithWork, Bool.and_eq_true, leWithWork_value, + divWithWork_value, canonicalMulWithWork_value, nat_value] + norm_num + +def cellCentersWithWork {n : ℕ} (P F b : ℕ) (a theta : BinaryFraction) + (initial : TargetInterval n → BinaryFraction) (cell : ℕ × ℕ) : + List (TargetInterval n) × ℕ := + let spacing := seedGridSpacingWithWork b P + let side := canonicalMulWithWork theta (nat b) + let states := cellStatesWithWork n (bitWordValue spacing.1) side.1 cell + let selected := filterWithWork (fun r => centerEligibilityWithWork b F a (initial r)) states.1 + (selected.1, spacing.2 + side.2 + states.2 + selected.2 + 3) + +@[simp] theorem cellCentersWithWork_value {n : ℕ} (P F b : ℕ) (a theta : BinaryFraction) + (initial : TargetInterval n → BinaryFraction) (cell : ℕ × ℕ) (hP : 0 < P) : + (cellCentersWithWork P F b a theta initial cell).1 = + cellRepresentativeStates n P F b a.value (fun r => (initial r).value) theta.value cell := by + have htest (r : TargetInterval n) : (centerEligibilityWithWork b F a (initial r)).1 = + decide ((b : ℚ) / (4 * a.value) ≤ (initial r).value ∧ (initial r).value ≤ 8 * F * b) := + Bool.eq_iff_iff.mpr (by simp only [centerEligibilityWithWork_value, decide_eq_true_eq]) + simp only [cellCentersWithWork, filterWithWork_value, cellStatesWithWork_value, + seedGridSpacingWithWork_value b P hP, canonicalMulWithWork_value, nat_value, + htest, cellRepresentativeStates] + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryCellCentersWork.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryCellCentersWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..4185938839697071061de6d7fcee194777a44777 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryCellCentersWork.lean @@ -0,0 +1,130 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryCellGridWork +import OAI.Combinatorics.EditApproximation.Binary.BinaryLocalGuardWork +import OAI.Combinatorics.EditApproximation.Binary.BinaryWideChildWork + +namespace OAI + +/-! Complete work for a whole-cell representative scan, including both +endpoint grids and every initial-value eligibility test. -/ + +namespace EditApproximation +namespace BinaryFraction + +private theorem flatMap_length_bound {α β : Type*} (f : α → List β) + (xs : List α) (n : ℕ) (h : ∀ x ∈ xs, (f x).length ≤ n) : + (xs.flatMap f).length ≤ xs.length * n := by + induction xs with + | nil => simp + | cons x xs ih => + simp only [List.flatMap_cons, List.length_append, List.length_cons] + have hh := h x (by simp) + have ht := ih (fun y hy => h y (by simp [hy])) + rw [Nat.add_mul, Nat.one_mul] + omega + +theorem cellStatesWithWork_length (n g : ℕ) (side : BinaryFraction) (cell : ℕ × ℕ) : + (cellStatesWithWork n g side cell).1.length ≤ + (cellGridPoints side.value g cell.1).length * + (cellGridPoints side.value g cell.2).length := by + simp only [cellStatesWithWork, arithmeticFlatMapWithWork_value, filterMapWithWork_value, + makeStateWithWork_value] + have h := flatMap_length_bound + (fun lo => ((cellGridPointsWithWork side g cell.2).1.filterMap (makeTargetState n lo))) + (cellGridPointsWithWork side g cell.1).1 (cellGridPointsWithWork side g cell.2).1.length + (fun _ _ => List.length_filterMap_le _ _) + simpa only [cellGridPointsWithWork_value] using h + +def cellCentersBitBudget (left right B : ℕ) : ℕ := + 100 * (B + 2) ^ 2 + 2000 * (B + 1) ^ 2 + + cellStatesBitBudget left right (4 * B + 40) + + left * right * (localEligibilityBitBudget B + 3) + 3 + +theorem cellCentersWithWork_cost {n : ℕ} (P F b B : ℕ) (a theta : BinaryFraction) + (initial : TargetInterval n → BinaryFraction) (cell : ℕ × ℕ) + (hB : 6 ≤ B) (hn : Nat.size n ≤ B) (hb : Nat.size b + 2 ≤ B) + (hP : Nat.size P ≤ B) (hF : Nat.size F + 2 ≤ B) + (ha : a.width ≤ B) (htheta : theta.width ≤ B) + (hi : ∀ q, (initial q).width ≤ B) + (hleft : Nat.size cell.1 ≤ B) (hright : Nat.size cell.2 ≤ B) : + (cellCentersWithWork P F b a theta initial cell).2 ≤ + cellCentersBitBudget + (cellGridPoints (theta.value * b) (bitWordValue (seedGridSpacingWithWork b P).1) cell.1).length + (cellGridPoints (theta.value * b) (bitWordValue (seedGridSpacingWithWork b P).1) cell.2).length B := by + let spacing := seedGridSpacingWithWork b P + let side := canonicalMulWithWork theta (nat b) + let states := cellStatesWithWork n (bitWordValue spacing.1) side.1 cell + let C := 4 * B + 40 + have hspacing := seedGridSpacingWithWork_bounds b P B (by omega) hP + have hgs : Nat.size (bitWordValue spacing.1) ≤ C := + (Nat.size_le.mpr (bitWordValue_lt_pow_length spacing.1)).trans (by + have hh : spacing.1.length ≤ B + 1 := hspacing.1 + dsimp only [C] + omega) + have hsidew := canonicalMulWithWork_width theta (nat b) B htheta ((nat_width_le b).trans hb) + have hsidec := canonicalMulWithWork_cost theta (nat b) B htheta ((nat_width_le b).trans hb) + change side.1.width ≤ 4 * B + 2 at hsidew + have hstates := cellStatesWithWork_cost n (bitWordValue spacing.1) C side.1 cell + (by dsimp only [C]; omega) hgs (by dsimp only [C]; omega) + (by dsimp only [C]; omega) (by dsimp only [C]; omega) + have hcount := cellStatesWithWork_length n (bitWordValue spacing.1) side.1 cell + have hselected := filterWithWork_cost + (fun r => centerEligibilityWithWork b F a (initial r)) states.1 + (localEligibilityBitBudget B) + (fun r _ => centerEligibilityWithWork_cost b F B a (initial r) hB hb hF ha (hi r)) + change states.1.length ≤ _ at hcount + change states.2 ≤ _ at hstates + change side.2 ≤ _ at hsidec + change spacing.2 + side.2 + states.2 + + (filterWithWork (fun r => centerEligibilityWithWork b F a (initial r)) states.1).2 + 3 ≤ _ + have hsc : spacing.2 ≤ 100 * (B + 2) ^ 2 := hspacing.2 + have hv : side.1.value = theta.value * b := by + simp only [side, canonicalMulWithWork_value, nat_value] + rw [hv] at hstates hcount + unfold cellCentersBitBudget + change _ ≤ 100 * (B + 2) ^ 2 + 2000 * (B + 1) ^ 2 + + cellStatesBitBudget + (cellGridPoints (theta.value * b) (bitWordValue spacing.1) cell.1).length + (cellGridPoints (theta.value * b) (bitWordValue spacing.1) cell.2).length (4 * B + 40) + + (cellGridPoints (theta.value * b) (bitWordValue spacing.1) cell.1).length * + (cellGridPoints (theta.value * b) (bitWordValue spacing.1) cell.2).length * + (localEligibilityBitBudget B + 3) + 3 + have hfilter := hselected.trans (Nat.mul_le_mul_right _ hcount) + dsimp only [C] at hstates + omega + +theorem cellCentersBitBudget_mono_count (l l' r r' B : ℕ) (hl : l ≤ l') (hr : r ≤ r') : + cellCentersBitBudget l r B ≤ cellCentersBitBudget l' r' B := by + unfold cellCentersBitBudget cellStatesBitBudget cellGridPointsBitBudget + gcongr + +theorem cellCentersWithWork_uniform_cost {n : ℕ} (P F b B : ℕ) (a theta : BinaryFraction) + (initial : TargetInterval n → BinaryFraction) (cell : ℕ × ℕ) + (hB : 6 ≤ B) (hn : Nat.size n ≤ B) (hb : Nat.size b + 2 ≤ B) + (hP : Nat.size P ≤ B) (hF : Nat.size F + 2 ≤ B) + (ha : a.width ≤ B) (htheta : theta.width ≤ B) + (hi : ∀ q, (initial q).width ≤ B) + (hleft : Nat.size cell.1 ≤ B) (hright : Nat.size cell.2 ≤ B) + (hthetaValue : 0 ≤ theta.value ∧ theta.value ≤ 1) + (hbdyadic : ∃ e : ℕ, b = 2 ^ e) (hPdyadic : ∃ e : ℕ, P = 2 ^ e) : + (cellCentersWithWork P F b a theta initial cell).2 ≤ cellCentersBitBudget P P B := by + have hPpos : 0 < P := by obtain ⟨e, rfl⟩ := hPdyadic; exact Nat.two_pow_pos e + have hg : (0 : ℚ) < seedGridSpacing b P := by + exact_mod_cast (show 0 < seedGridSpacing b P by unfold seedGridSpacing; omega) + have hcover : (b : ℚ) ≤ P * (seedGridSpacing b P : ℚ) := by + exact_mod_cast seedGridSpacing_covers_dyadic hbdyadic hPdyadic + have hsize : theta.value * b / seedGridSpacing b P ≤ (P : ℚ) := by + apply (div_le_iff₀ hg).2 + have hb : theta.value * b ≤ (b : ℚ) := by + simpa only [one_mul] using + mul_le_mul_of_nonneg_right hthetaValue.2 (Nat.cast_nonneg (α := ℚ) b) + exact hb.trans hcover + have hlen (j : ℕ) : (cellGridPoints (theta.value * b) (seedGridSpacing b P) j).length ≤ P := + cellGridPoints_length_le (mul_nonneg hthetaValue.1 (Nat.cast_nonneg _)) hsize + have hc := cellCentersWithWork_cost P F b B a theta initial cell hB hn hb hP hF ha htheta hi hleft hright + rw [seedGridSpacingWithWork_value b P hPpos] at hc + exact hc.trans (cellCentersBitBudget_mono_count _ _ _ _ B (hlen cell.1) (hlen cell.2)) + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryCellGrid.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryCellGrid.lean new file mode 100644 index 0000000000000000000000000000000000000000..22ea4733d545a6f1b81b2cb3f310bc1079fb9ce2 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryCellGrid.lean @@ -0,0 +1,80 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryScaleGrid +import OAI.Combinatorics.EditApproximation.Geometry.LocalCells +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! The whole-cell grids and nearby cell indices are generated by literal +binary quotient, endpoint and bounded-range operations. -/ + +namespace EditApproximation +namespace BinaryFraction + + + +@[simp] theorem naturalFloorWithWork_value (a : BinaryFraction) : + bitWordValue (naturalFloorWithWork a).1 = ⌊a.value⌋₊ := by + cases hs : a.numerator.negative + · have hdiv := bitDivModWithWork_value a.denominator a.numerator.bits a.denominator_pos + have hq : bitWordValue (bitDivModWithWork a.denominator a.numerator.bits).1 = + bitWordValue a.numerator.bits / bitWordValue a.denominator := by + conv_rhs => rw [hdiv.1] + rw [Nat.mul_add_div a.denominator_pos, Nat.div_eq_of_lt hdiv.2, Nat.add_zero] + simpa only [naturalFloorWithWork, hs, Bool.false_eq_true, ↓reduceIte, value, + SignedBinary.value, signedMagnitude, Int.cast_natCast, Nat.floor_div_eq_div] using hq + · have hn : a.value ≤ 0 := by + simp only [value, SignedBinary.value, signedMagnitude, hs, ↓reduceIte, + Int.cast_neg, Int.cast_natCast] + exact div_nonpos_of_nonpos_of_nonneg (neg_nonpos.mpr (Nat.cast_nonneg _)) (Nat.cast_nonneg _) + simp only [naturalFloorWithWork, hs, ↓reduceIte, bitWordValue] + exact (Nat.floor_eq_zero.mpr (lt_of_le_of_lt hn (by norm_num))).symm + +theorem naturalFloorWithWork_bounds (a : BinaryFraction) : + (naturalFloorWithWork a).1.length ≤ a.width ∧ + (naturalFloorWithWork a).2 ≤ 200 * (a.width + 1) ^ 2 := by + have hn : a.numerator.bits.length ≤ a.width := le_max_left _ _ + have hd : a.denominator.length ≤ a.width := le_max_right _ _ + have hlen := (bitDivModWithWork_lengths a.denominator a.numerator.bits).1 + have hc := bitDivModWithWork_cost a.denominator a.numerator.bits + unfold naturalFloorWithWork + split_ifs <;> dsimp only + · exact ⟨Nat.zero_le _, by nlinarith only [Nat.zero_le a.width]⟩ + · exact ⟨hlen.le.trans hn, by nlinarith only [hc, hn, hd, Nat.zero_le a.width]⟩ + + + +@[simp] theorem cellCoordinatesWithWork_value (side : BinaryFraction) (p radius : ℕ) : + (cellCoordinatesWithWork side p radius).1 = localCellCoordinates side.value p radius := by + simp only [cellCoordinatesWithWork, naturalFloorWithWork_value, divWithWork_value, + nat_value, saturatingSubtractWithWork_value, binaryNaturalAddWithWork_value, + localCellCoordinates] + + + +@[simp] theorem targetCellsWithWork_value {n : ℕ} (side : BinaryFraction) (radius : ℕ) + (q : TargetInterval n) : + (targetCellsWithWork side radius q).1 = localTargetCells side.value radius q := by + simp only [targetCellsWithWork, arithmeticFlatMapWithWork_value, arithmeticMapWithWork_value, + cellCoordinatesWithWork_value, localTargetCells] + + + +@[simp] theorem cellGridPointsWithWork_value (side : BinaryFraction) (g cell : ℕ) : + (cellGridPointsWithWork side g cell).1 = cellGridPoints side.value g cell := by + simp only [cellGridPointsWithWork, arithmeticMapWithWork_value, binaryNaturalMulWithWork_value, + binaryNaturalAddWithWork_value, canonicalMulWithWork_value, divWithWork_value, + naturalCeilingWithWork_value, nat_value, saturatingSubtractWithWork_value, cellGridPoints, + Nat.cast_add, Nat.cast_one] + + + +@[simp] theorem cellStatesWithWork_value (n g : ℕ) (side : BinaryFraction) (cell : ℕ × ℕ) : + (cellStatesWithWork n g side cell).1 = cellTargetStates n g side.value cell := by + simp only [cellStatesWithWork, arithmeticFlatMapWithWork_value, filterMapWithWork_value, + cellGridPointsWithWork_value, makeStateWithWork_value, cellTargetStates] + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryCellGridWork.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryCellGridWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..6705756baaed18af7c09e82fd613219319fbec27 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryCellGridWork.lean @@ -0,0 +1,314 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryCellCenters +import OAI.Combinatorics.EditApproximation.Binary.BinaryLocalGridWork +import OAI.Combinatorics.EditApproximation.Binary.BinaryAffineGuard + +namespace OAI + +/-! Word-size bounds for the literal whole-cell index scans. The +cardinalities here are the emitted local ranges, not the target length. -/ + +namespace EditApproximation +namespace BinaryFraction + +private theorem naturalWordSize_le (bits : List Bool) : Nat.size (bitWordValue bits) ≤ bits.length := + Nat.size_le.mpr (bitWordValue_lt_pow_length bits) + +def cellCoordinateSetupBitBudget (B : ℕ) : ℕ := + 100 * (B + 1) + 4200 * (B + 6) ^ 2 + 400 * (4 * B + 21) ^ 2 + 100 * (4 * B + 25) + +theorem cellCoordinatesWithWork_bounds (side : BinaryFraction) (p radius B : ℕ) + (hs : side.width ≤ B) (hp : Nat.size p ≤ B) (hr : Nat.size radius ≤ B) : + (cellCoordinatesWithWork side p radius).2 ≤ + cellCoordinateSetupBitBudget B + (localCellCoordinates side.value p radius).length ∧ + ∀ x ∈ (cellCoordinatesWithWork side p radius).1, Nat.size x ≤ 4 * B + 23 := by + let lower := saturatingSubtractWithWork p radius + let upper := binaryNaturalAddWithWork p radius + let firstQ := divWithWork (nat (bitWordValue lower.1)) side + let lastQ := divWithWork (nat (bitWordValue upper.1)) side + let first := naturalFloorWithWork firstQ.1 + let last := naturalFloorWithWork lastQ.1 + let stop := binaryNaturalAddWithWork (bitWordValue last.1) 1 + let count := saturatingSubtractWithWork (bitWordValue stop.1) (bitWordValue first.1) + have hl : Nat.size (bitWordValue lower.1) ≤ B := by + rw [saturatingSubtractWithWork_value] + exact (Nat.size_le_size (Nat.sub_le _ _)).trans hp + have hu : Nat.size (bitWordValue upper.1) ≤ B + 2 := by + rw [binaryNaturalAddWithWork_value] + exact (binaryNaturalAdd_size_le p radius).trans (by omega) + have hfl := divWithWork_width_uniform (nat (bitWordValue lower.1)) side (B + 4) + ((nat_width_le _).trans (by omega)) (by omega) + have hll := divWithWork_width_uniform (nat (bitWordValue upper.1)) side (B + 4) + ((nat_width_le _).trans (by omega)) (by omega) + have hfc := divWithWork_cost (nat (bitWordValue lower.1)) side (B + 4) + ((nat_width_le _).trans (by omega)) (by omega) + have hlc := divWithWork_cost (nat (bitWordValue upper.1)) side (B + 4) + ((nat_width_le _).trans (by omega)) (by omega) + change firstQ.1.width ≤ _ at hfl + change lastQ.1.width ≤ _ at hll + change firstQ.2 ≤ _ at hfc + change lastQ.2 ≤ _ at hlc + simp only [Nat.add_assoc, Nat.reduceAdd] at hfc hlc + have hf := naturalFloorWithWork_bounds firstQ.1 + have hl' := naturalFloorWithWork_bounds lastQ.1 + have hfirst : Nat.size (bitWordValue first.1) ≤ 4 * B + 20 := + ((naturalWordSize_le _).trans hf.1).trans (by omega) + have hlast : Nat.size (bitWordValue last.1) ≤ 4 * B + 20 := + ((naturalWordSize_le _).trans hl'.1).trans (by omega) + have hstop : Nat.size (bitWordValue stop.1) ≤ 4 * B + 23 := by + rw [binaryNaturalAddWithWork_value] + exact (binaryNaturalAdd_size_le _ 1).trans (by simp only [Nat.size_one]; omega) + have hfloorFirst : first.2 ≤ 200 * (4 * B + 21) ^ 2 := + hf.2.trans (Nat.mul_le_mul_left _ (Nat.pow_le_pow_left (by omega) _)) + have hfloorLast : last.2 ≤ 200 * (4 * B + 21) ^ 2 := + hl'.2.trans (Nat.mul_le_mul_left _ (Nat.pow_le_pow_left (by omega) _)) + have hlowCost := saturatingSubtractWithWork_cost p radius + have huppCost := binaryNaturalAddWithWork_cost p radius + have hstopCost := binaryNaturalAddWithWork_cost (bitWordValue last.1) 1 + have hcountCost := saturatingSubtractWithWork_cost (bitWordValue stop.1) (bitWordValue first.1) + change lower.2 ≤ _ at hlowCost + change upper.2 ≤ _ at huppCost + change stop.2 ≤ _ at hstopCost + change count.2 ≤ _ at hcountCost + simp only [Nat.size_one] at hstopCost + have hlength : (List.range' (bitWordValue first.1) (bitWordValue count.1)).length = + (localCellCoordinates side.value p radius).length := by + have hv := congrArg List.length (cellCoordinatesWithWork_value side p radius) + simpa only [cellCoordinatesWithWork, lower, upper, firstQ, lastQ, first, last, + stop, count] using hv + constructor + · change lower.2 + upper.2 + firstQ.2 + lastQ.2 + first.2 + last.2 + stop.2 + count.2 + + (List.range' (bitWordValue first.1) (bitWordValue count.1)).length + Nat.size p + Nat.size radius + 9 ≤ _ + rw [hlength] + unfold cellCoordinateSetupBitBudget + omega + · intro x hx + have hx' : x ∈ List.range' (bitWordValue first.1) (bitWordValue count.1) := by + simpa only [cellCoordinatesWithWork, lower, upper, firstQ, lastQ, first, last, + stop, count] using hx + obtain ⟨j, hj, hxj⟩ := List.mem_range'.mp hx' + have hcount : bitWordValue count.1 = bitWordValue stop.1 - bitWordValue first.1 := + saturatingSubtractWithWork_value _ _ + have hxstop : x ≤ bitWordValue stop.1 := by omega + exact (Nat.size_le_size hxstop).trans hstop + +theorem cellCoordinatesWithWork_cost (side : BinaryFraction) (p radius B : ℕ) + (hs : side.width ≤ B) (hp : Nat.size p ≤ B) (hr : Nat.size radius ≤ B) : + (cellCoordinatesWithWork side p radius).2 ≤ + cellCoordinateSetupBitBudget B + (localCellCoordinates side.value p radius).length := + (cellCoordinatesWithWork_bounds side p radius B hs hp hr).1 + +def targetCellsBitBudget (left right B : ℕ) : ℕ := + 2 * cellCoordinateSetupBitBudget B + left + right + left * (5 * right + 3) + 2 + +theorem targetCellsWithWork_cost {n : ℕ} (side : BinaryFraction) (radius B : ℕ) + (query : TargetInterval n) (hs : side.width ≤ B) (hn : Nat.size n ≤ B) + (hr : Nat.size radius ≤ B) : + (targetCellsWithWork side radius query).2 ≤ targetCellsBitBudget + (localCellCoordinates side.value query.lo radius).length + (localCellCoordinates side.value query.hi radius).length B := by + let left := cellCoordinatesWithWork side query.lo radius + let right := cellCoordinatesWithWork side query.hi radius + have hl := cellCoordinatesWithWork_cost side query.lo radius B hs + ((Nat.size_le_size (query.ordered.trans query.valid)).trans hn) hr + have hh := cellCoordinatesWithWork_cost side query.hi radius B hs + ((Nat.size_le_size query.valid).trans hn) hr + have hm (lo : ℕ) : (arithmeticMapWithWork (fun hi => ((lo, hi), 1)) right.1).2 ≤ + right.1.length * 4 := arithmeticMapWithWork_cost _ _ 1 (fun _ _ => le_rfl) + have hf := arithmeticFlatMapWithWork_cost + (fun lo => arithmeticMapWithWork (fun hi => ((lo, hi), 1)) right.1) left.1 + (right.1.length * 4) right.1.length (fun lo _ => hm lo) + (fun _ _ => by simp only [arithmeticMapWithWork_value, List.length_map]; exact le_rfl) + change left.2 ≤ _ at hl + change right.2 ≤ _ at hh + change left.2 + right.2 + (arithmeticFlatMapWithWork + (fun lo => arithmeticMapWithWork (fun hi => ((lo, hi), 1)) right.1) left.1).2 + 2 ≤ _ + have hleft : left.1.length = (localCellCoordinates side.value query.lo radius).length := + congrArg List.length (cellCoordinatesWithWork_value side query.lo radius) + have hright : right.1.length = (localCellCoordinates side.value query.hi radius).length := + congrArg List.length (cellCoordinatesWithWork_value side query.hi radius) + have hflat : (arithmeticFlatMapWithWork + (fun lo => arithmeticMapWithWork (fun hi => ((lo, hi), 1)) right.1) left.1).2 ≤ + (localCellCoordinates side.value query.lo radius).length * + (5 * (localCellCoordinates side.value query.hi radius).length + 3) := by + calc + _ ≤ left.1.length * (right.1.length * 4 + right.1.length + 3) := hf + _ = _ := by rw [hleft, hright]; ring + unfold targetCellsBitBudget + omega + + +theorem targetCellsWithWork_keys {n : ℕ} (side : BinaryFraction) (radius B : ℕ) + (query : TargetInterval n) (hs : side.width ≤ B) (hn : Nat.size n ≤ B) + (hr : Nat.size radius ≤ B) (cell : ℕ × ℕ) + (hcell : cell ∈ (targetCellsWithWork side radius query).1) : + Nat.size cell.1 ≤ 4 * B + 23 ∧ Nat.size cell.2 ≤ 4 * B + 23 := by + have hl := (cellCoordinatesWithWork_bounds side query.lo radius B hs + ((Nat.size_le_size (query.ordered.trans query.valid)).trans hn) hr).2 + have hh := (cellCoordinatesWithWork_bounds side query.hi radius B hs + ((Nat.size_le_size query.valid).trans hn) hr).2 + simp only [targetCellsWithWork, arithmeticFlatMapWithWork_value, + arithmeticMapWithWork_value] at hcell + obtain ⟨lo, hlo, hc⟩ := List.mem_flatMap.mp hcell + obtain ⟨hi, hhi, rfl⟩ := List.mem_map.mp hc + exact ⟨hl lo hlo, hh hi hhi⟩ + +def cellGridSetupBitBudget (B : ℕ) : ℕ := 2000000 * (B + 100) ^ 2 + +def cellGridPointBitBudget (B : ℕ) : ℕ := 1000 * (B + 100) ^ 2 + +def cellGridPointsBitBudget (count B : ℕ) : ℕ := + cellGridSetupBitBudget B + count * (cellGridPointBitBudget B + 5) + +theorem cellGridPointsWithWork_bounds (side : BinaryFraction) (g cell B : ℕ) + (hs : side.width ≤ B) (hg : Nat.size g ≤ B) (hc : Nat.size cell ≤ B) : + (cellGridPointsWithWork side g cell).2 ≤ + cellGridPointsBitBudget (cellGridPoints side.value g cell).length B ∧ + ∀ x ∈ (cellGridPointsWithWork side g cell).1, Nat.size x ≤ 17 * B + 78 := by + let next := binaryNaturalAddWithWork cell 1 + let lower := canonicalMulWithWork (nat cell) side + let upper := canonicalMulWithWork (nat (bitWordValue next.1)) side + let firstQ := divWithWork lower.1 (nat g) + let lastQ := divWithWork upper.1 (nat g) + let first := naturalCeilingWithWork firstQ.1 + let last := naturalCeilingWithWork lastQ.1 + let count := saturatingSubtractWithWork (bitWordValue last.1) (bitWordValue first.1) + let indices := List.range' (bitWordValue first.1) (bitWordValue count.1) + have hnext : Nat.size (bitWordValue next.1) ≤ B + 2 := by + rw [binaryNaturalAddWithWork_value] + have hv := naturalWordSize_le (binaryNaturalAddWithWork cell 1).1 + rw [binaryNaturalAddWithWork_value] at hv + have hl := bitAddWithWork_length cell.bits (1 : ℕ).bits false + have h : Nat.size (cell + 1) ≤ max (Nat.size cell) 1 + 1 := by + simpa only [binaryNaturalAddWithWork, Nat.size_eq_bits_len, Nat.size_one] using hv.trans hl + omega + have hlow := canonicalMulWithWork_width (nat cell) side (B + 4) + ((nat_width_le cell).trans (by omega)) (by omega) + have hupp := canonicalMulWithWork_width (nat (bitWordValue next.1)) side (B + 4) + ((nat_width_le _).trans (by omega)) (by omega) + change lower.1.width ≤ _ at hlow + change upper.1.width ≤ _ at hupp + have hfirstQ := divWithWork_width_uniform lower.1 (nat g) (4 * B + 18) + (by omega) ((nat_width_le g).trans (by omega)) + have hlastQ := divWithWork_width_uniform upper.1 (nat g) (4 * B + 18) + (by omega) ((nat_width_le g).trans (by omega)) + change firstQ.1.width ≤ _ at hfirstQ + change lastQ.1.width ≤ _ at hlastQ + have hfirst : Nat.size (bitWordValue first.1) ≤ 16 * B + 78 := by + have h := (naturalWordSize_le first.1).trans (naturalCeilingWithWork_length firstQ.1) + omega + have hlast : Nat.size (bitWordValue last.1) ≤ 16 * B + 78 := by + have h := (naturalWordSize_le last.1).trans (naturalCeilingWithWork_length lastQ.1) + omega + have hindex (i : ℕ) (hi : i ∈ indices) : Nat.size i ≤ 16 * B + 78 := by + obtain ⟨j, hj, hij⟩ := List.mem_range'.mp hi + have hcount : bitWordValue count.1 = bitWordValue last.1 - bitWordValue first.1 := + saturatingSubtractWithWork_value _ _ + have hle : i ≤ bitWordValue last.1 := by omega + exact (Nat.size_le_size hle).trans hlast + let point := fun i => + let product := binaryNaturalMulWithWork g i + (bitWordValue product.1, product.2 + Nat.size i + 2) + have hpoint (i : ℕ) (hi : i ∈ indices) : (point i).2 ≤ cellGridPointBitBudget B := by + have hm := binaryNaturalMulWithWork_cost g i + have his := hindex i hi + dsimp only [point] + unfold cellGridPointBitBudget + nlinarith only [hm, his, hg, Nat.zero_le B] + have hmap := arithmeticMapWithWork_cost point indices (cellGridPointBitBudget B) hpoint + have hmaplen : indices.length = (cellGridPoints side.value g cell).length := by + have hv := congrArg List.length (cellGridPointsWithWork_value side g cell) + simpa only [cellGridPointsWithWork, arithmeticMapWithWork_value, List.length_map] using hv + have hnextc := binaryNaturalAddWithWork_cost cell 1 + have hlowc := canonicalMulWithWork_cost (nat cell) side (B + 4) + ((nat_width_le cell).trans (by omega)) (by omega) + have huppc := canonicalMulWithWork_cost (nat (bitWordValue next.1)) side (B + 4) + ((nat_width_le _).trans (by omega)) (by omega) + have hfirstc := divWithWork_cost lower.1 (nat g) (4 * B + 18) + (by omega) ((nat_width_le g).trans (by omega)) + have hlastc := divWithWork_cost upper.1 (nat g) (4 * B + 18) + (by omega) ((nat_width_le g).trans (by omega)) + have hfc := (naturalCeilingWithWork_cost firstQ.1).trans + (Nat.mul_le_mul_left 500 (Nat.pow_le_pow_left (by omega : firstQ.1.width + 1 ≤ 16 * B + 77) 2)) + have hlc := (naturalCeilingWithWork_cost lastQ.1).trans + (Nat.mul_le_mul_left 500 (Nat.pow_le_pow_left (by omega : lastQ.1.width + 1 ≤ 16 * B + 77) 2)) + have hcc := saturatingSubtractWithWork_cost (bitWordValue last.1) (bitWordValue first.1) + change next.2 ≤ _ at hnextc + change lower.2 ≤ _ at hlowc + change upper.2 ≤ _ at huppc + change firstQ.2 ≤ _ at hfirstc + change lastQ.2 ≤ _ at hlastc + change first.2 ≤ _ at hfc + change last.2 ≤ _ at hlc + change count.2 ≤ _ at hcc + simp only [Nat.size_one, Nat.add_assoc, Nat.reduceAdd] at hnextc hlowc huppc hfirstc hlastc + have hsetup : next.2 + lower.2 + upper.2 + firstQ.2 + lastQ.2 + first.2 + last.2 + count.2 + + Nat.size cell + Nat.size g + 10 ≤ cellGridSetupBitBudget B := by + unfold cellGridSetupBitBudget + nlinarith only [hnextc, hlowc, huppc, hfirstc, hlastc, hfc, hlc, hcc, + hfirst, hlast, hc, hg, Nat.zero_le B] + constructor + · change next.2 + lower.2 + upper.2 + firstQ.2 + lastQ.2 + first.2 + last.2 + count.2 + + (arithmeticMapWithWork point indices).2 + indices.length + Nat.size cell + Nat.size g + 10 ≤ _ + unfold cellGridPointsBitBudget + rw [← hmaplen] + nlinarith only [hsetup, hmap, Nat.zero_le indices.length] + · intro x hx + have hx' : x ∈ (arithmeticMapWithWork point indices).1 := by + simpa only [cellGridPointsWithWork, next, lower, upper, firstQ, lastQ, first, + last, count, indices, point] using hx + rw [arithmeticMapWithWork_value] at hx' + obtain ⟨i, hi, rfl⟩ := List.mem_map.mp hx' + dsimp only [point] + rw [binaryNaturalMulWithWork_value] + have hprod := natural_product_bit_length g i + have hidx := hindex i hi + omega + +theorem cellGridPointsWithWork_cost (side : BinaryFraction) (g cell B : ℕ) + (hs : side.width ≤ B) (hg : Nat.size g ≤ B) (hc : Nat.size cell ≤ B) : + (cellGridPointsWithWork side g cell).2 ≤ + cellGridPointsBitBudget (cellGridPoints side.value g cell).length B := + (cellGridPointsWithWork_bounds side g cell B hs hg hc).1 + + +def cellStatesBitBudget (left right B : ℕ) : ℕ := + cellGridPointsBitBudget left B + cellGridPointsBitBudget right B + + left * (right * (16 * (17 * B + 78) + 11) + right + 3) + 2 + +theorem cellStatesWithWork_cost (n g B : ℕ) (side : BinaryFraction) (cell : ℕ × ℕ) + (hn : Nat.size n ≤ B) (hg : Nat.size g ≤ B) (hs : side.width ≤ B) + (hleft : Nat.size cell.1 ≤ B) (hright : Nat.size cell.2 ≤ B) : + (cellStatesWithWork n g side cell).2 ≤ cellStatesBitBudget + (cellGridPoints side.value g cell.1).length (cellGridPoints side.value g cell.2).length B := by + let left := cellGridPointsWithWork side g cell.1 + let right := cellGridPointsWithWork side g cell.2 + have hl := cellGridPointsWithWork_bounds side g cell.1 B hs hg hleft + have hr := cellGridPointsWithWork_bounds side g cell.2 B hs hg hright + have htest (lo : ℕ) (hlo : lo ∈ left.1) : + (filterMapWithWork (makeStateWithWork n lo) right.1).2 ≤ + right.1.length * (16 * (17 * B + 78) + 11) := by + exact filterMapWithWork_cost _ _ (16 * (17 * B + 78) + 8) (fun hi hhi => + makeStateWithWork_cost n lo hi (17 * B + 78) (by omega) (hl.2 lo hlo) (hr.2 hi hhi)) + have hlen (lo : ℕ) : (filterMapWithWork (makeStateWithWork n lo) right.1).1.length ≤ + right.1.length := by + rw [filterMapWithWork_value] + exact List.length_filterMap_le _ _ + have hf := arithmeticFlatMapWithWork_cost (fun lo => filterMapWithWork (makeStateWithWork n lo) right.1) + left.1 (right.1.length * (16 * (17 * B + 78) + 11)) right.1.length + htest (fun lo _ => hlen lo) + have hll : left.1.length = (cellGridPoints side.value g cell.1).length := + congrArg List.length (cellGridPointsWithWork_value side g cell.1) + have hrl : right.1.length = (cellGridPoints side.value g cell.2).length := + congrArg List.length (cellGridPointsWithWork_value side g cell.2) + rw [hll, hrl] at hf + change left.2 + right.2 + (arithmeticFlatMapWithWork + (fun lo => filterMapWithWork (makeStateWithWork n lo) right.1) left.1).2 + 2 ≤ _ + unfold cellStatesBitBudget + have hlc : left.2 ≤ _ := hl.1 + have hrc : right.2 ≤ _ := hr.1 + omega + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryCellGroupKernel.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryCellGroupKernel.lean new file mode 100644 index 0000000000000000000000000000000000000000..4377ffd625d8699d1f720ec0b50ba10c9b9bd838 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryCellGroupKernel.lean @@ -0,0 +1,106 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryCellCenters +import OAI.Combinatorics.EditApproximation.Binary.BinaryDyadicSampledGroups +import OAI.Combinatorics.EditApproximation.Binary.BinaryUnskippedKernel + +namespace OAI + +/-! One complete whole-cell group: enumerate its eligible centers, execute +every band guard, estimate all surviving members with the original finite +draws, and select the same ordered minimum. -/ + +namespace EditApproximation +namespace BinaryFraction + +abbrev cellScaleDraw (M b Q : ℕ) (f : ℚ) := + ∀ t : Fin (groupDyadicScales M b f).length, + Fin (groupSampleCount M Q b (groupDyadicScaleAt M b f t)) → Fin M + +def cellReferenceAction {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (b P F exponent Q : ℕ) (tau a f : ℚ) + (parentInitial : TargetInterval target.length → ℚ) + (child initial current : Fin M → TargetInterval target.length → ℚ) + (cell : ℕ × ℕ) (draw : cellScaleDraw M b Q f) : Option (PhysicalRationalAction M target.length) := + let members := unskippedBandList source target parent b P exponent tau f child initial + (cellRepresentativeStates target.length P F b a parentInitial ((2 : ℚ) ^ (-(exponent : ℤ))) cell) + if h : members = [] then none else some (chooseUnskippedGroup Q current members h draw).rationalAction + +theorem cellReferenceAction_transport {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (b P F exponent Q : ℕ) (tau a f g : ℚ) (h : f = g) + (parentInitial : TargetInterval target.length → ℚ) + (child initial current : Fin M → TargetInterval target.length → ℚ) + (cell : ℕ × ℕ) (draw : cellScaleDraw M b Q f) : + cellReferenceAction source target parent b P F exponent Q tau a f parentInitial child initial current cell draw = + cellReferenceAction source target parent b P F exponent Q tau a g parentInitial child initial current cell + (Eq.mp (congrArg (cellScaleDraw M b Q) h) draw) := by + cases h + rfl + +section Cell +variable {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (b P F exponent Q : ℕ) (hb : 0 < b) + (tau a : BinaryFraction) + (parentInitial : TargetInterval target.length → BinaryFraction) + (child initial current : Fin M → TargetInterval target.length → BinaryFraction) + (raw : List BinaryFraction) + (hraw : raw.map value = groupDyadicScales M b (nat F).value) + (draw : ∀ t : Fin (groupDyadicScales M b (nat F).value).length, + Fin (groupSampleCount M Q b (groupDyadicScaleAt M b (nat F).value t)) → Fin M) + +def cellGroupWithWork (cell : ℕ × ℕ) : + Option (BinaryBellmanAction (TargetInterval target.length) + (Fin M × TargetInterval target.length) M) × ℕ := + let centers := cellCentersWithWork P F b a (inversePowerTwo exponent) parentInitial cell + let members := filterMapWithWork + (unskippedCandidateWithWork source target parent b P exponent hb tau (nat F) child initial) centers.1 + if h : members.1 = [] then (none, centers.2 + members.2 + 1) else + let selected := dyadicSampledGroupActionWithWork source target parent b P exponent Q tau (nat F) + child initial current raw hraw draw members.1 h + (some selected.1, centers.2 + members.2 + selected.2 + 2) + +theorem cellGroupWithWork_reference (cell : ℕ × ℕ) (hP : 0 < P) : + ((cellGroupWithWork source target parent b P F exponent Q hb tau a parentInitial child initial current + raw hraw draw cell).1.map BinaryBellmanAction.decode) = + cellReferenceAction source target parent b P F exponent Q tau.value a.value (nat F).value + (fun q => (parentInitial q).value) (fun i q => (child i q).value) + (fun i q => (initial i q).value) (fun i q => (current i q).value) cell draw := by + have hcenters := cellCentersWithWork_value P F b a (inversePowerTwo exponent) parentInitial cell hP + simp only [inversePowerTwo_value] at hcenters + have hmembers : (filterMapWithWork + (unskippedCandidateWithWork source target parent b P exponent hb tau (nat F) child initial) + (cellCentersWithWork P F b a (inversePowerTwo exponent) parentInitial cell).1).1 = + unskippedBandList source target parent b P exponent tau.value (nat F).value + (fun i q => (child i q).value) (fun i q => (initial i q).value) + (cellRepresentativeStates target.length P F b a.value + (fun q => (parentInitial q).value) ((2 : ℚ) ^ (-(exponent : ℤ))) cell) := by + simp only [filterMapWithWork_value, unskippedCandidateWithWork_value, hcenters, unskippedBandList] + unfold cellGroupWithWork + dsimp only + split_ifs with hempty + · have hnil := hempty + rw [hmembers] at hnil + simp only [Option.map_none, cellReferenceAction, dite_eq_left hnil] + · rw [Option.map_some, dyadicSampledGroupActionWithWork_value source target parent b P exponent Q + tau (nat F) child initial current raw hraw draw _ hempty hb] + have hnonempty := hempty + rw [hmembers] at hnonempty + simp only [hmembers, cellReferenceAction, dite_eq_right hnonempty] + +/-- The rational cell-group program at the exact natural parameter. +Transport preserves its values and changes only proof indices. -/ +theorem cellGroupWithWork_value (cell : ℕ × ℕ) (hP : 0 < P) : + ((cellGroupWithWork source target parent b P F exponent Q hb tau a parentInitial child initial current + raw hraw draw cell).1.map BinaryBellmanAction.decode) = + chooseCellGroupAction source target parent b P F exponent Q tau.value a.value + (fun q => (parentInitial q).value) (fun i q => (child i q).value) + (fun i q => (initial i q).value) (fun i q => (current i q).value) cell + (Eq.mp (congrArg (cellScaleDraw M b Q) (nat_value F)) draw) := by + exact (cellGroupWithWork_reference source target parent b P F exponent Q hb tau a parentInitial + child initial current raw hraw draw cell hP).trans + (cellReferenceAction_transport source target parent b P F exponent Q tau.value a.value _ _ + (nat_value F) _ _ _ _ cell draw) + +end Cell +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryCellReadCosts.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryCellReadCosts.lean new file mode 100644 index 0000000000000000000000000000000000000000..9d25feab04b83f72a1b4d4ec82aa88a3d98c8207 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryCellReadCosts.lean @@ -0,0 +1,79 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryGroupReadCosts +import OAI.Combinatorics.EditApproximation.Binary.BinaryCellReads + +namespace OAI + +/-! The complete whole-cell estimator, including its ordered choice, +executes with a linear factor for each finite-buffer lookup. -/ + +namespace EditApproximation +namespace BinaryFraction + +theorem cellCentersReadWithWork_factor {n : ℕ} (P F b : ℕ) (a theta : BinaryFraction) + (initial : TargetInterval n → BinaryFraction × ℕ) (cell : ℕ × ℕ) + (R : ℕ) (hr : ∀ r, (initial r).2 ≤ R) : + (cellCentersReadWithWork P F b a theta initial cell).2 ≤ + (cellCentersWithWork P F b a theta (fun r => (initial r).1) cell).2 * tableReadFactor R := by + have h := (cellCentersReadWithWork_eq_cost P F b a theta initial cell R hr).2 + have hK : R + 1 ≤ tableReadFactor R := by unfold tableReadFactor; omega + exact h.trans (Nat.mul_le_mul_left _ hK) + +section Cell +variable {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (b P F exponent Q : ℕ) (hb : 0 < b) (hP : 0 < P) + (tau a : BinaryFraction) + (parentInitial : TargetInterval target.length → BinaryFraction × ℕ) + (child initial current : Fin M → TargetInterval target.length → BinaryFraction × ℕ) + (R : ℕ) (hc : ∀ i q, (child i q).2 ≤ R) (hi : ∀ i q, (initial i q).2 ≤ R) + (raw : List BinaryFraction) (hraw : raw.map value = groupDyadicScales M b (nat F).value) + (draw : ∀ t : Fin (groupDyadicScales M b (nat F).value).length, + Fin (groupSampleCount M Q b (groupDyadicScaleAt M b (nat F).value t)) → Fin M) + +theorem preparedCellGroupReadWithWork_factor (cell : ℕ × ℕ) + (hp : ∀ r, (parentInitial r).2 ≤ R) (hn : ∀ i q, (current i q).2 ≤ R) : + (preparedCellGroupReadWithWork source target parent b P F exponent Q hb hP tau a + parentInitial child initial current R R hc hi raw hraw draw cell).2 ≤ + (preparedCellGroupWithWork source target parent b P F exponent Q hb tau a + (fun r => (parentInitial r).1) (fun i q => (child i q).1) + (fun i q => (initial i q).1) (fun i q => (current i q).1) raw hraw draw hP cell).2 * + tableReadFactor R := by + have hcenters := cellCentersReadWithWork_factor P F b a (inversePowerTwo exponent) + parentInitial cell R hp + have hcentersq := (cellCentersReadWithWork_eq_cost P F b a (inversePowerTwo exponent) + parentInitial cell R hp).1 + have hm := filterMapWithWork_factor + (preparedUnskippedReadWithWork source target parent b P exponent hb hP tau (nat F) + child initial R R hc hi) + (preparedUnskippedCandidateWithWork source target parent b P exponent hb hP tau (nat F) + (fun i q => (child i q).1) (fun i q => (initial i q).1)) + (cellCentersWithWork P F b a (inversePowerTwo exponent) (fun r => (parentInitial r).1) cell).1 + (tableReadFactor R) (tableReadFactor_pos R) + (fun center _ => preparedUnskippedReadWithWork_value source target parent b P exponent hb hP + tau (nat F) child initial R R hc hi center) + (fun center _ => preparedUnskippedReadWithWork_factor source target parent b P exponent hb hP + tau (nat F) child initial R hc hi center) + have hcm := Nat.add_le_add hcenters hm.2 + rw [← Nat.add_mul] at hcm + unfold preparedCellGroupReadWithWork preparedCellGroupWithWork + dsimp only + simp only [hcentersq, hm.1] + split_ifs with hempty + · apply cost_replace_factor _ _ _ _ _ hcm (tableReadFactor_pos R) <;> omega + · have hs := sampledGroupActionReadWithWork_factor source target parent b P exponent Q tau + (nat F) (fun i q => (child i q).1) initial current + (indexedGroupScales raw M b (nat F).value hraw) + (fun t j => draw t (Fin.cast (congrArg (groupSampleCount M Q b) + (indexedGroupScales_value raw M b (nat F).value hraw t)) j)) + _ hempty R hi hn + have h := Nat.add_le_add hcm hs + rw [← Nat.add_mul] at h + change _ ≤ _ at hs + unfold dyadicSampledGroupActionReadWithWork dyadicSampledGroupActionWithWork + dsimp only + apply cost_replace_factor _ _ _ _ _ h (tableReadFactor_pos R) <;> omega + +end Cell +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryCellReads.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryCellReads.lean new file mode 100644 index 0000000000000000000000000000000000000000..5643fb44d0900b2734f18e1e334710a1fbdf0060 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryCellReads.lean @@ -0,0 +1,114 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryGroupActionReads +import OAI.Combinatorics.EditApproximation.Binary.BinaryUnskippedReads +import OAI.Combinatorics.EditApproximation.Binary.BinaryPreparedCellGroup +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Reader-aware whole-cell construction. Every eligibility test reads its +initial word, and every accepted band and selected action uses the counted +reader kernels. -/ + +namespace EditApproximation + +theorem filterMapWithWork_extra {α β : Type*} (read plain : α → Option β × ℕ) + (extra : α → ℕ) (xs : List α) + (hv : ∀ x ∈ xs, (read x).1 = (plain x).1) + (hc : ∀ x ∈ xs, (read x).2 ≤ (plain x).2 + extra x) : + (filterMapWithWork read xs).1 = (filterMapWithWork plain xs).1 ∧ + (filterMapWithWork read xs).2 ≤ (filterMapWithWork plain xs).2 + (xs.map extra).sum := by + induction xs with + | nil => exact ⟨rfl, by simp only [filterMapWithWork, List.map_nil, List.sum_nil, + Nat.add_zero, le_refl]⟩ + | cons x xs ih => + have hx := hv x List.mem_cons_self + have hcx := hc x List.mem_cons_self + have ht := ih (fun y hy => hv y (List.mem_cons_of_mem _ hy)) + (fun y hy => hc y (List.mem_cons_of_mem _ hy)) + simp only [filterMapWithWork, hx, ht.1, List.map_cons, List.sum_cons] + cases (plain x).1 with + | none => exact ⟨trivial, by omega⟩ + | some value => exact ⟨trivial, by omega⟩ + +namespace BinaryFraction + + + +theorem cellCentersReadWithWork_eq_cost {n : ℕ} (P F b : ℕ) (a theta : BinaryFraction) + (initial : TargetInterval n → BinaryFraction × ℕ) (cell : ℕ × ℕ) + (R : ℕ) (hr : ∀ r, (initial r).2 ≤ R) : + (cellCentersReadWithWork P F b a theta initial cell).1 = + (cellCentersWithWork P F b a theta (fun r => (initial r).1) cell).1 ∧ + (cellCentersReadWithWork P F b a theta initial cell).2 ≤ + (cellCentersWithWork P F b a theta (fun r => (initial r).1) cell).2 * (R + 1) := by + have hs := filterWithWork_add_read + (fun r => centerEligibilityWithWork b F a (initial r).1) (fun r => (initial r).2) + (cellStatesWithWork n (bitWordValue (seedGridSpacingWithWork b P).1) + (canonicalMulWithWork theta (nat b)).1 cell).1 R (fun r _ => hr r) + unfold cellCentersReadWithWork cellCentersWithWork + dsimp only + have he : (fun r => let word := initial r; let tested := centerEligibilityWithWork b F a word.1; + (tested.1, word.2 + tested.2)) = + (fun r => ((centerEligibilityWithWork b F a (initial r).1).1, + (centerEligibilityWithWork b F a (initial r).1).2 + (initial r).2)) := by + funext r + simp only [Nat.add_comm] + rw [he, hs.1] + exact ⟨rfl, by nlinarith only [hs.2]⟩ + +section Cell +variable {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (b P F exponent Q : ℕ) (hb : 0 < b) (hP : 0 < P) + (tau a : BinaryFraction) + (parentInitial : TargetInterval target.length → BinaryFraction × ℕ) + (child initial current : Fin M → TargetInterval target.length → BinaryFraction × ℕ) + (R C : ℕ) (hr : ∀ i q, (child i q).2 ≤ R) (hi : ∀ i q, (initial i q).2 ≤ C) + (raw : List BinaryFraction) (hraw : raw.map value = groupDyadicScales M b (nat F).value) + (draw : ∀ t : Fin (groupDyadicScales M b (nat F).value).length, + Fin (groupSampleCount M Q b (groupDyadicScaleAt M b (nat F).value t)) → Fin M) + +def preparedCellGroupReadWithWork (cell : ℕ × ℕ) : + Option (BinaryBellmanAction (TargetInterval target.length) + (Fin M × TargetInterval target.length) M) × ℕ := + let centers := cellCentersReadWithWork P F b a (inversePowerTwo exponent) parentInitial cell + let members := filterMapWithWork + (preparedUnskippedReadWithWork source target parent b P exponent hb hP tau (nat F) + child initial R C hr hi) centers.1 + if h : members.1 = [] then (none, centers.2 + members.2 + 1) else + let selected := dyadicSampledGroupActionReadWithWork source target parent b P exponent Q tau (nat F) + (fun i q => (child i q).1) initial current raw hraw draw members.1 h + (some selected.1, centers.2 + members.2 + selected.2 + 2) + +theorem preparedCellGroupReadWithWork_eq (cell : ℕ × ℕ) (Rp Rc : ℕ) + (hp : ∀ r, (parentInitial r).2 ≤ Rp) (hc : ∀ i q, (current i q).2 ≤ Rc) : + (preparedCellGroupReadWithWork source target parent b P F exponent Q hb hP tau a + parentInitial child initial current R C hr hi raw hraw draw cell).1 = + (preparedCellGroupWithWork source target parent b P F exponent Q hb tau a + (fun r => (parentInitial r).1) (fun i q => (child i q).1) + (fun i q => (initial i q).1) (fun i q => (current i q).1) raw hraw draw hP cell).1 := by + have hcenters := (cellCentersReadWithWork_eq_cost P F b a (inversePowerTwo exponent) + parentInitial cell Rp hp).1 + have hm : (filterMapWithWork + (preparedUnskippedReadWithWork source target parent b P exponent hb hP tau (nat F) + child initial R C hr hi) + (cellCentersWithWork P F b a (inversePowerTwo exponent) (fun r => (parentInitial r).1) cell).1).1 = + (filterMapWithWork + (preparedUnskippedCandidateWithWork source target parent b P exponent hb hP tau (nat F) + (fun i q => (child i q).1) (fun i q => (initial i q).1)) + (cellCentersWithWork P F b a (inversePowerTwo exponent) (fun r => (parentInitial r).1) cell).1).1 := by + simp only [filterMapWithWork_value, preparedUnskippedReadWithWork_value] + unfold preparedCellGroupReadWithWork preparedCellGroupWithWork + dsimp only + simp only [hcenters, hm] + split_ifs with hempty + · rfl + · apply congrArg some + exact (sampledGroupActionReadWithWork_eq_cost source target parent b P exponent Q tau (nat F) + (fun i q => (child i q).1) initial current _ _ _ hempty Rc C hi hc).1 + +end Cell +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryCellSourcePort.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryCellSourcePort.lean new file mode 100644 index 0000000000000000000000000000000000000000..b7c3173afc2fc58b19be30648482df0cfb054fb9 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryCellSourcePort.lean @@ -0,0 +1,80 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinarySampledSourcePort +import OAI.Combinatorics.EditApproximation.Binary.BinaryCellReads + +namespace OAI + +namespace EditApproximation.BinaryFraction + +section Cell +variable {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (b P F exponent Q : ℕ) (hb : 0 < b) (hP : 0 < P) + (tau a : BinaryFraction) + (parentInitial : TargetInterval target.length → BinaryFraction × ℕ) + (child initial current : Fin M → TargetInterval target.length → BinaryFraction × ℕ) + (R C : ℕ) (hr : ∀ i q, (child i q).2 ≤ R) (hi : ∀ i q, (initial i q).2 ≤ C) + (raw : List BinaryFraction) (hraw : raw.map value = groupDyadicScales M b (nat F).value) + (draw : ∀ t : Fin (groupDyadicScales M b (nat F).value).length, + Fin (groupSampleCount M Q b (groupDyadicScaleAt M b (nat F).value t)) → Fin M × ℕ) + +/-- The same raw dyadic scale list and Fin-count indices as the original +cell estimator, now with the cost of decoding every sampled coordinate. -/ +def preparedCellGroupSourceWithWork (cell : ℕ × ℕ) : + Option (BinaryBellmanAction (TargetInterval target.length) + (Fin M × TargetInterval target.length) M) × ℕ := + let centers := cellCentersReadWithWork P F b a (inversePowerTwo exponent) parentInitial cell + let members := filterMapWithWork + (preparedUnskippedReadWithWork source target parent b P exponent hb hP tau (nat F) + child initial R C hr hi) centers.1 + if h : members.1 = [] then (none, centers.2 + members.2 + 1) else + let selected := sampledGroupActionSourceWithWork source target parent b P exponent Q tau (nat F) + (fun i q => (child i q).1) initial current (indexedGroupScales raw M b (nat F).value hraw) + (fun t j => draw t (Fin.cast (congrArg (groupSampleCount M Q b) + (indexedGroupScales_value raw M b (nat F).value hraw t)) j)) members.1 h + (some selected.1, centers.2 + members.2 + selected.2 + 2) + +theorem preparedCellGroupSourceWithWork_eq_cost (cell : ℕ × ℕ) (S : ℕ) + (hs : ∀ t i, (draw t i).2 ≤ S) : + (preparedCellGroupSourceWithWork source target parent b P F exponent Q hb hP tau a + parentInitial child initial current R C hr hi raw hraw draw cell).1 = + (preparedCellGroupReadWithWork source target parent b P F exponent Q hb hP tau a + parentInitial child initial current R C hr hi raw hraw (fun t i => (draw t i).1) cell).1 ∧ + (preparedCellGroupSourceWithWork source target parent b P F exponent Q hb hP tau a + parentInitial child initial current R C hr hi raw hraw draw cell).2 ≤ + (preparedCellGroupReadWithWork source target parent b P F exponent Q hb hP tau a + parentInitial child initial current R C hr hi raw hraw (fun t i => (draw t i).1) cell).2 * (S + 4) := by + let centers := cellCentersReadWithWork P F b a (inversePowerTwo exponent) parentInitial cell + let members := filterMapWithWork + (preparedUnskippedReadWithWork source target parent b P exponent hb hP tau (nat F) + child initial R C hr hi) centers.1 + unfold preparedCellGroupSourceWithWork preparedCellGroupReadWithWork + dsimp only + split_ifs with hempty + · exact ⟨rfl, by dsimp only; nlinarith only [Nat.zero_le S]⟩ + · have h := sampledGroupActionSourceWithWork_eq_cost source target parent b P exponent Q tau (nat F) + (fun i q => (child i q).1) initial current (indexedGroupScales raw M b (nat F).value hraw) + (fun t j => draw t (Fin.cast (congrArg (groupSampleCount M Q b) + (indexedGroupScales_value raw M b (nat F).value hraw t)) j)) members.1 hempty S + (fun t j => hs t _) + dsimp only [dyadicSampledGroupActionReadWithWork] + rw [h.1] + exact ⟨rfl, by nlinarith only [h.2]⟩ + +theorem preparedCellGroupSourceWithWork_value (cell : ℕ × ℕ) : + (preparedCellGroupSourceWithWork source target parent b P F exponent Q hb hP tau a + parentInitial child initial current R C hr hi raw hraw draw cell).1 = + (preparedCellGroupReadWithWork source target parent b P F exponent Q hb hP tau a + parentInitial child initial current R C hr hi raw hraw (fun t i => (draw t i).1) cell).1 := by + unfold preparedCellGroupSourceWithWork preparedCellGroupReadWithWork + dsimp only + split_ifs with hempty + · rfl + · apply congrArg some + exact sampledGroupActionSourceWithWork_value source target parent b P exponent Q tau (nat F) + (fun i q => (child i q).1) initial current (indexedGroupScales raw M b (nat F).value hraw) + (fun t j => draw t (Fin.cast (congrArg (groupSampleCount M Q b) + (indexedGroupScales_value raw M b (nat F).value hraw t)) j)) _ hempty + +end Cell +end EditApproximation.BinaryFraction + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryCellSourceSpace.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryCellSourceSpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..5349311ca80155bc9cb22d4194501e4effd395d9 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryCellSourceSpace.lean @@ -0,0 +1,89 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryGroupActionSourceSpace +import OAI.Combinatorics.EditApproximation.Binary.BinaryCellSourcePort +import OAI.Combinatorics.EditApproximation.Binary.BinaryUnskippedSpace +import OAI.Combinatorics.EditApproximation.Queries.QueryLocalRepresentativeSpace + +namespace OAI + +namespace EditApproximation.BinaryFraction + +section Cell +variable {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (b P F exponent Q : ℕ) (hb : 0 < b) (hP : 0 < P) + (tau a : BinaryFraction) + (parentInitial : TargetInterval target.length → BinaryFraction × ℕ) + (child initial current : Fin M → TargetInterval target.length → BinaryFraction × ℕ) + (R C : ℕ) (hr : ∀ i q, (child i q).2 ≤ R) (hi : ∀ i q, (initial i q).2 ≤ C) + (raw : List BinaryFraction) (hraw : raw.map value = groupDyadicScales M b (nat F).value) + (draw : ∀ t : Fin (groupDyadicScales M b (nat F).value).length, + Fin (groupSampleCount M Q b (groupDyadicScaleAt M b (nat F).value t)) → Fin M × ℕ) + (parentAllocation : TargetInterval target.length → ℕ) + (childAllocation initialAllocation currentAllocation : Fin M → TargetInterval target.length → ℕ) + (drawAllocation : ∀ t : Fin (groupDyadicScales M b (nat F).value).length, + Fin (groupSampleCount M Q b (groupDyadicScaleAt M b (nat F).value t)) → ℕ) + +def preparedCellGroupSourceAllocation (cell : ℕ × ℕ) : ℕ := + let centers := (cellCentersReadWithWork P F b a (inversePowerTwo exponent) parentInitial cell).1 + let members := (filterMapWithWork + (preparedUnskippedReadWithWork source target parent b P exponent hb hP tau (nat F) + child initial R C hr hi) centers).1 + cellCentersReadAllocation P F b a (inversePowerTwo exponent) parentInitial parentAllocation cell + + filterMapAllocation (preparedUnskippedReadWithWork source target parent b P exponent hb hP tau (nat F) + child initial R C hr hi) + (fun center => preparedUnskippedReadAllocation parent center b P exponent tau (nat F) + child initial childAllocation initialAllocation) centers + + if hempty : members = [] then 0 else + sampledGroupActionSourceAllocation source target parent b P exponent Q tau (nat F) + (fun i q => (child i q).1) initial current initialAllocation currentAllocation + (indexedGroupScales raw M b (nat F).value hraw) + (fun t j => draw t (Fin.cast (congrArg (groupSampleCount M Q b) + (indexedGroupScales_value raw M b (nat F).value hraw t)) j)) + (fun t j => drawAllocation t (Fin.cast (congrArg (groupSampleCount M Q b) + (indexedGroupScales_value raw M b (nat F).value hraw t)) j)) members hempty + 1 + +theorem preparedCellGroupSourceAllocation_le_work (cell : ℕ × ℕ) + (hp : ∀ q, parentAllocation q ≤ (parentInitial q).2) + (hc : ∀ i q, childAllocation i q ≤ (child i q).2) + (hin : ∀ i q, initialAllocation i q ≤ (initial i q).2) + (hcur : ∀ i q, currentAllocation i q ≤ (current i q).2) + (hd : ∀ t i, drawAllocation t i ≤ (draw t i).2) : + preparedCellGroupSourceAllocation source target parent b P F exponent Q hb hP tau a + parentInitial child initial current R C hr hi raw hraw draw + parentAllocation childAllocation initialAllocation currentAllocation drawAllocation cell ≤ + (preparedCellGroupSourceWithWork source target parent b P F exponent Q hb hP tau a + parentInitial child initial current R C hr hi raw hraw draw cell).2 := by + let centers := (cellCentersReadWithWork P F b a (inversePowerTwo exponent) parentInitial cell).1 + let members := (filterMapWithWork + (preparedUnskippedReadWithWork source target parent b P exponent hb hP tau (nat F) + child initial R C hr hi) centers).1 + have hcenters := cellCentersReadAllocation_le_work P F b a (inversePowerTwo exponent) + parentInitial parentAllocation cell hp + have hmembers := filterMapAllocation_le_work + (preparedUnskippedReadWithWork source target parent b P exponent hb hP tau (nat F) + child initial R C hr hi) + (fun center => preparedUnskippedReadAllocation parent center b P exponent tau (nat F) + child initial childAllocation initialAllocation) centers + (fun center _ => preparedUnskippedReadAllocation_le_work source target parent center b P exponent + hb hP tau (nat F) child initial childAllocation initialAllocation R C hr hi hc hin) + dsimp only [centers] at hmembers + unfold preparedCellGroupSourceAllocation preparedCellGroupSourceWithWork + dsimp only + split_ifs with hempty + · exact Nat.add_le_add (Nat.add_le_add hcenters hmembers) (by decide : 0 ≤ 1) + · have hsample := sampledGroupActionSourceAllocation_le_work source target parent b P exponent Q + tau (nat F) (fun i q => (child i q).1) initial current initialAllocation currentAllocation + (indexedGroupScales raw M b (nat F).value hraw) + (fun t j => draw t (Fin.cast (congrArg (groupSampleCount M Q b) + (indexedGroupScales_value raw M b (nat F).value hraw t)) j)) + (fun t j => drawAllocation t (Fin.cast (congrArg (groupSampleCount M Q b) + (indexedGroupScales_value raw M b (nat F).value hraw t)) j)) members hempty hin hcur + (fun t j => hd t _) + dsimp only [centers, members] at hmembers hsample + exact (Nat.add_assoc _ _ _).symm.le.trans + (Nat.add_le_add (Nat.add_le_add (Nat.add_le_add hcenters hmembers) hsample) + (by decide : 1 ≤ 2)) + +end Cell +end EditApproximation.BinaryFraction + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryCellSpace.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryCellSpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..c1ad0b17acea712287fddb02e6ca00e19851ef12 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryCellSpace.lean @@ -0,0 +1,98 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryGridSpace +import OAI.Combinatorics.EditApproximation.Queries.QueryBufferSpace +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation.BinaryFraction + + + +theorem cellCoordinatesAllocation_le_work (side : BinaryFraction) (p radius : ℕ) : + cellCoordinatesAllocation side p radius ≤ (cellCoordinatesWithWork side p radius).2 := by + let lower := (saturatingSubtractWithWork p radius).1 + let upper := (binaryNaturalAddWithWork p radius).1 + let firstQ := (divWithWork (nat (bitWordValue lower)) side).1 + let lastQ := (divWithWork (nat (bitWordValue upper)) side).1 + let first := (naturalFloorWithWork firstQ).1 + let last := (naturalFloorWithWork lastQ).1 + let stop := (binaryNaturalAddWithWork (bitWordValue last) 1).1 + have h1 := saturatingSubtractAllocation_le_work p radius + have h2 := binaryNaturalAddAllocation_le_work p radius + have h3 := divAllocation_le_work (nat (bitWordValue lower)) side + have h4 := divAllocation_le_work (nat (bitWordValue upper)) side + have h5 := naturalFloorAllocation_le_work firstQ + have h6 := naturalFloorAllocation_le_work lastQ + have h7 := binaryNaturalAddAllocation_le_work (bitWordValue last) 1 + have h8 := saturatingSubtractAllocation_le_work (bitWordValue stop) (bitWordValue first) + unfold cellCoordinatesAllocation cellCoordinatesWithWork + dsimp only [lower, upper, firstQ, lastQ, first, last, stop] at h3 h4 h5 h6 h7 h8 ⊢ + rw [List.length_range'] + omega + + + +theorem targetCellsAllocation_le_work {n : ℕ} (side : BinaryFraction) (radius : ℕ) (q : TargetInterval n) : + targetCellsAllocation side radius q ≤ (targetCellsWithWork side radius q).2 := by + have hl := cellCoordinatesAllocation_le_work side q.lo radius + have hr := cellCoordinatesAllocation_le_work side q.hi radius + have hm := arithmeticFlatMapAllocation_le_work + (fun lo => arithmeticMapWithWork (fun hi => ((lo, hi), 1)) (cellCoordinatesWithWork side q.hi radius).1) + (fun _ => arithmeticMapAllocation (fun _ => 1) (cellCoordinatesWithWork side q.hi radius).1) + (cellCoordinatesWithWork side q.lo radius).1 (fun _ _ => + arithmeticMapAllocation_le_work _ _ _ (fun _ _ => le_rfl)) + unfold targetCellsAllocation targetCellsWithWork + dsimp only + omega + + + +theorem cellGridPointsAllocation_le_work (side : BinaryFraction) (g cell : ℕ) : + cellGridPointsAllocation side g cell ≤ (cellGridPointsWithWork side g cell).2 := by + let next := (binaryNaturalAddWithWork cell 1).1 + let lower := (canonicalMulWithWork (nat cell) side).1 + let upper := (canonicalMulWithWork (nat (bitWordValue next)) side).1 + let firstQ := (divWithWork lower (nat g)).1 + let lastQ := (divWithWork upper (nat g)).1 + let first := (naturalCeilingWithWork firstQ).1 + let last := (naturalCeilingWithWork lastQ).1 + let count := (saturatingSubtractWithWork (bitWordValue last) (bitWordValue first)).1 + let indices := List.range' (bitWordValue first) (bitWordValue count) + have h1 := binaryNaturalAddAllocation_le_work cell 1 + have h2 := canonicalMulAllocation_le_work (nat cell) side + have h3 := canonicalMulAllocation_le_work (nat (bitWordValue next)) side + have h4 := divAllocation_le_work lower (nat g) + have h5 := divAllocation_le_work upper (nat g) + have h6 := naturalCeilingAllocation_le_work firstQ + have h7 := naturalCeilingAllocation_le_work lastQ + have h8 := saturatingSubtractAllocation_le_work (bitWordValue last) (bitWordValue first) + have h9 := arithmeticMapAllocation_le_work (fun i => + (bitWordValue (binaryNaturalMulWithWork g i).1, (binaryNaturalMulWithWork g i).2 + Nat.size i + 2)) + (fun i => binaryNaturalMulAllocation g i + Nat.size i) indices (by + intro i _ + have h := binaryNaturalMulAllocation_le_work g i + dsimp only + omega) + unfold cellGridPointsAllocation cellGridPointsWithWork + dsimp only [next, lower, upper, firstQ, lastQ, first, last, count, indices] at h3 h4 h5 h6 h7 h8 h9 ⊢ + omega + + + +theorem cellStatesAllocation_le_work (n g : ℕ) (side : BinaryFraction) (cell : ℕ × ℕ) : + cellStatesAllocation n g side cell ≤ (cellStatesWithWork n g side cell).2 := by + have hl := cellGridPointsAllocation_le_work side g cell.1 + have hr := cellGridPointsAllocation_le_work side g cell.2 + have hm := arithmeticFlatMapAllocation_le_work + (fun lo => filterMapWithWork (makeStateWithWork n lo) (cellGridPointsWithWork side g cell.2).1) + (fun lo => filterMapAllocation (makeStateWithWork n lo) (makeStateAllocation n lo) (cellGridPointsWithWork side g cell.2).1) + (cellGridPointsWithWork side g cell.1).1 (fun lo _ => filterMapAllocation_le_work _ _ _ + (fun hi _ => makeStateAllocation_le_work n lo hi)) + unfold cellStatesAllocation cellStatesWithWork + dsimp only + omega + +end EditApproximation.BinaryFraction + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryComputedCellGroup.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryComputedCellGroup.lean new file mode 100644 index 0000000000000000000000000000000000000000..6a60cefa18c2cf713cba7b1f6dae60a5a78ff035 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryComputedCellGroup.lean @@ -0,0 +1,52 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryCellGroupKernel + +namespace OAI + +/-! The cell kernel constructs its rational scales from the dyadic +parameter exponents. -/ + +namespace EditApproximation +namespace BinaryFraction + +theorem computedGroupScales_value (M b F eM eb eF : ℕ) + (hM : M = 2 ^ eM) (hb : b = 2 ^ eb) (hF : F = 2 ^ eF) : + (groupScalesWithWork eM eb eF).1.map value = groupDyadicScales M b (nat F).value := by + rw [nat_value, hM, hb, hF, Nat.cast_pow, Nat.cast_ofNat] + exact groupScalesWithWork_value eM eb eF + +def computedCellGroupWithWork {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (b P F exponent Q eM eb eF : ℕ) + (hM : M = 2 ^ eM) (hb : b = 2 ^ eb) (hF : F = 2 ^ eF) + (tau a : BinaryFraction) (parentInitial : TargetInterval target.length → BinaryFraction) + (child initial current : Fin M → TargetInterval target.length → BinaryFraction) + (draw : cellScaleDraw M b Q (nat F).value) (cell : ℕ × ℕ) : + Option (BinaryBellmanAction (TargetInterval target.length) + (Fin M × TargetInterval target.length) M) × ℕ := + let scales := groupScalesWithWork eM eb eF + let result := cellGroupWithWork source target parent b P F exponent Q + (by rw [hb]; exact Nat.two_pow_pos eb) tau a parentInitial child initial current scales.1 + (computedGroupScales_value M b F eM eb eF hM hb hF) draw cell + (result.1, scales.2 + result.2 + 1) + +theorem computedCellGroupWithWork_value {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (b P F exponent Q eM eb eF : ℕ) + (hM : M = 2 ^ eM) (hb : b = 2 ^ eb) (hF : F = 2 ^ eF) + (tau a : BinaryFraction) (parentInitial : TargetInterval target.length → BinaryFraction) + (child initial current : Fin M → TargetInterval target.length → BinaryFraction) + (draw : cellScaleDraw M b Q (nat F).value) (cell : ℕ × ℕ) (hP : 0 < P) : + ((computedCellGroupWithWork source target parent b P F exponent Q eM eb eF hM hb hF tau a + parentInitial child initial current draw cell).1.map BinaryBellmanAction.decode) = + chooseCellGroupAction source target parent b P F exponent Q tau.value a.value + (fun q => (parentInitial q).value) (fun i q => (child i q).value) + (fun i q => (initial i q).value) (fun i q => (current i q).value) cell + (Eq.mp (congrArg (cellScaleDraw M b Q) (nat_value F)) draw) := by + have h := cellGroupWithWork_value source target parent b P F exponent Q + (by rw [hb]; exact Nat.two_pow_pos eb) tau a parentInitial child initial current + (groupScalesWithWork eM eb eF).1 (computedGroupScales_value M b F eM eb eF hM hb hF) + draw cell hP + simpa only [computedCellGroupWithWork] using h + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryContinuationReadCosts.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryContinuationReadCosts.lean new file mode 100644 index 0000000000000000000000000000000000000000..8e09253a79001b00bc9c8c41451885020fc41163 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryContinuationReadCosts.lean @@ -0,0 +1,92 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryReadCostBounds +import OAI.Combinatorics.EditApproximation.Binary.BinaryContinuationReads + +namespace OAI + +/-! Continuation cost transfer includes both Bellman scans and the +literal online score array, with each child lookup charged. -/ + +namespace EditApproximation +namespace BinaryFraction + +theorem bellmanActionReadWithWork_factor {Parent Child : Type*} {M : ℕ} + (distance : Parent → Parent → BinaryFraction × ℕ) (L : BinaryFraction) + (read : Child → BinaryFraction × ℕ) (query : Parent) + (action : BinaryBellmanAction Parent Child M) (R : ℕ) + (hr : ∀ i, (read (action.childState i)).2 ≤ R) : + (bellmanActionReadWithWork distance L read query action).2 ≤ + (bellmanActionWithWork distance L (fun s => (read s).1) query action).2 * tableReadFactor R := by + apply tableReadFactor_absorb _ _ M R + (bellmanActionReadWithWork_cost distance L read query action R hr) + have hs : M ≤ (sumListWithWork (List.ofFn fun i => (read (action.childState i)).1)).2 := by + simp only [sumListWithWork, List.length_ofFn] + omega + unfold bellmanActionWithWork + dsimp only + omega + +theorem bellmanReadWithWork_factor {Parent Child : Type*} {M : ℕ} + (distance : Parent → Parent → BinaryFraction × ℕ) (L fallback : BinaryFraction) + (read : Child → BinaryFraction × ℕ) (query : Parent) + (actions : List (BinaryBellmanAction Parent Child M)) (R : ℕ) + (hr : ∀ action ∈ actions, ∀ i, (read (action.childState i)).2 ≤ R) : + (bellmanReadWithWork distance L fallback read query actions).2 ≤ + (bellmanWithWork distance L fallback (fun s => (read s).1) query actions).2 * tableReadFactor R := by + have hs := arithmeticMapWithWork_factor + (bellmanActionReadWithWork distance L read query) + (bellmanActionWithWork distance L (fun s => (read s).1) query) + actions (tableReadFactor R) (tableReadFactor_pos R) + (fun action _ => bellmanActionReadWithWork_eq distance L read query action) + (fun action ha => bellmanActionReadWithWork_factor distance L read query action R (hr action ha)) + unfold bellmanReadWithWork bellmanWithWork + dsimp only + rw [hs.1] + apply cost_replace_factor _ _ _ _ _ hs.2 (tableReadFactor_pos R) <;> omega + +theorem localContinuationReadWithWork_factor {Parent Child : Type*} {M : ℕ} + (distance : Parent → Parent → BinaryFraction × ℕ) (L delta fallback : BinaryFraction) + (old current : Child → BinaryFraction × ℕ) (query : Parent) + (wide groups online : List (BinaryBellmanAction Parent Child M)) (R : ℕ) + (ho : ∀ s, (old s).2 ≤ R) (hn : ∀ s, (current s).2 ≤ R) : + (localContinuationReadWithWork distance L delta fallback old current query wide groups online).2 ≤ + (localContinuationWithWork distance L delta fallback (fun s => (old s).1) + (fun s => (current s).1) query wide groups online).2 * tableReadFactor R := by + have hw := bellmanReadWithWork_factor distance L fallback old query wide R (fun _ _ _ => ho _) + have hwq := bellmanReadWithWork_eq distance L fallback old query wide + have hg := bellmanReadWithWork_factor distance L + (bellmanWithWork distance L fallback (fun s => (old s).1) query wide).1 current query groups R + (fun _ _ _ => hn _) + have hgq := bellmanReadWithWork_eq distance L + (bellmanWithWork distance L fallback (fun s => (old s).1) query wide).1 current query groups + have hs := arithmeticMapWithWork_factor + (bellmanActionReadWithWork distance L current query) + (bellmanActionWithWork distance L (fun s => (current s).1) query) + online (tableReadFactor R) (tableReadFactor_pos R) + (fun action _ => bellmanActionReadWithWork_eq distance L current query action) + (fun action _ => bellmanActionReadWithWork_factor distance L current query action R (fun _ => hn _)) + have h := Nat.add_le_add (Nat.add_le_add hw hg) hs.2 + simp only [← Nat.add_mul] at h + unfold localContinuationReadWithWork localContinuationWithWork + dsimp only + rw [hwq, hgq, hs.1] + apply cost_replace_factor _ _ _ _ _ h (tableReadFactor_pos R) <;> omega + +theorem physicalContinuationReadWithWork_factor {nx n M : ℕ} (parent : TargetInterval nx) + (representatives : List (ℕ × TargetInterval n)) (P F : ℕ) + (delta fallback : BinaryFraction) (old current : Fin M × TargetInterval n → BinaryFraction × ℕ) + (groups online : List (BinaryBellmanAction (TargetInterval n) (Fin M × TargetInterval n) M)) + (query : TargetInterval n) (R : ℕ) (ho : ∀ s, (old s).2 ≤ R) (hn : ∀ s, (current s).2 ≤ R) : + (physicalContinuationReadWithWork parent representatives P F delta fallback old current groups online query).2 ≤ + (physicalContinuationWithWork parent representatives P F delta fallback + (fun s => (old s).1) (fun s => (current s).1) groups online query).2 * tableReadFactor R := by + have h := localContinuationReadWithWork_factor endpointDistanceWithWork + (canonicalMulWithWork (nat 128) (nat F)).1 delta fallback old current query + (wideActionsFromRepresentativesWithWork M parent representatives P).1 groups online R ho hn + unfold physicalContinuationReadWithWork physicalContinuationWithWork + dsimp only + apply cost_replace_factor _ _ _ _ _ h (tableReadFactor_pos R) <;> omega + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryContinuationReads.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryContinuationReads.lean new file mode 100644 index 0000000000000000000000000000000000000000..315c141ccd60a397586ce27cf2352ccb4d0bc5e5 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryContinuationReads.lean @@ -0,0 +1,75 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryBellmanReads +import OAI.Combinatorics.EditApproximation.Binary.BinaryCachedContinuation +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Both Bellman minima and the online score list execute their table +lookups before evaluating the final stored-fraction decrement. -/ + +namespace EditApproximation +namespace BinaryFraction + + + +theorem localContinuationReadWithWork_eq_cost {Parent Child : Type*} {M : ℕ} + (distance : Parent → Parent → BinaryFraction × ℕ) (L delta fallback : BinaryFraction) + (old current : Child → BinaryFraction × ℕ) (query : Parent) + (wide groups online : List (BinaryBellmanAction Parent Child M)) (R : ℕ) + (ho : ∀ s, (old s).2 ≤ R) (hn : ∀ s, (current s).2 ≤ R) : + (localContinuationReadWithWork distance L delta fallback old current query wide groups online).1 = + (localContinuationWithWork distance L delta fallback (fun s => (old s).1) + (fun s => (current s).1) query wide groups online).1 ∧ + (localContinuationReadWithWork distance L delta fallback old current query wide groups online).2 ≤ + (localContinuationWithWork distance L delta fallback (fun s => (old s).1) + (fun s => (current s).1) query wide groups online).2 + + (wide.length + groups.length + online.length) * (M * (R + 3)) := by + have hwv := bellmanReadWithWork_eq distance L fallback old query wide + have hwc := bellmanReadWithWork_cost distance L fallback old query wide R (fun _ _ _ => ho _) + have hgv := bellmanReadWithWork_eq distance L + (bellmanWithWork distance L fallback (fun s => (old s).1) query wide).1 current query groups + have hgc := bellmanReadWithWork_cost distance L + (bellmanWithWork distance L fallback (fun s => (old s).1) query wide).1 current query groups R + (fun _ _ _ => hn _) + have hs := arithmeticMapWithWork_extra + (bellmanActionReadWithWork distance L current query) + (bellmanActionWithWork distance L (fun s => (current s).1) query) + (fun _ => M * (R + 3)) online + (fun a _ => bellmanActionReadWithWork_eq distance L current query a) + (fun a _ => bellmanActionReadWithWork_cost distance L current query a R (fun _ => hn _)) + have hsum : (online.map (fun _ => M * (R + 3))).sum = online.length * (M * (R + 3)) := by + simp only [List.map_const', List.sum_replicate, smul_eq_mul] + rw [hsum] at hs + unfold localContinuationReadWithWork localContinuationWithWork + dsimp only + rw [hwv, hgv, hs.1] + exact ⟨rfl, by nlinarith only [hwc, hgc, hs.2]⟩ + + + +theorem physicalContinuationReadWithWork_eq_cost {nx ny M : ℕ} (parent : TargetInterval nx) + (representatives : List (ℕ × TargetInterval ny)) (P F : ℕ) + (delta fallback : BinaryFraction) + (old current : Fin M × TargetInterval ny → BinaryFraction × ℕ) + (groups online : List (BinaryBellmanAction (TargetInterval ny) (Fin M × TargetInterval ny) M)) + (query : TargetInterval ny) (R : ℕ) (ho : ∀ s, (old s).2 ≤ R) (hn : ∀ s, (current s).2 ≤ R) : + (physicalContinuationReadWithWork parent representatives P F delta fallback old current groups online query).1 = + (physicalContinuationWithWork parent representatives P F delta fallback + (fun s => (old s).1) (fun s => (current s).1) groups online query).1 ∧ + (physicalContinuationReadWithWork parent representatives P F delta fallback old current groups online query).2 ≤ + (physicalContinuationWithWork parent representatives P F delta fallback + (fun s => (old s).1) (fun s => (current s).1) groups online query).2 + + ((wideActionsFromRepresentativesWithWork M parent representatives P).1.length + + groups.length + online.length) * (M * (R + 3)) := by + have h := localContinuationReadWithWork_eq_cost endpointDistanceWithWork + (canonicalMulWithWork (nat 128) (nat F)).1 delta fallback old current query + (wideActionsFromRepresentativesWithWork M parent representatives P).1 groups online R ho hn + unfold physicalContinuationReadWithWork physicalContinuationWithWork + dsimp only + exact ⟨h.1, by omega⟩ + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryContinuationSpace.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryContinuationSpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..239c39def19e128f3bbbb9ad253b1ad3d6c86b8c --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryContinuationSpace.lean @@ -0,0 +1,69 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryBellmanSpace +import OAI.Combinatorics.EditApproximation.Binary.BinaryContinuationReads +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation.BinaryFraction + + + +theorem onlineMinimumAllocation_le_work (values : List BinaryFraction) : + onlineMinimumAllocation values ≤ (onlineMinimumWithWork values).2 := by + cases values with + | nil => exact Nat.zero_le _ + | cons first rest => exact (minimumAllocation_le_work first rest).trans (Nat.le_add_right _ _) + + + +theorem refinementUpdateAllocation_le_work (delta cone : BinaryFraction) (online : Option BinaryFraction) : + refinementUpdateAllocation delta cone online ≤ (refinementUpdateWithWork delta cone online).2 := by + cases online with + | none => exact Nat.zero_le _ + | some online => + have ha := canonicalAddAllocation_le_work one delta + have hd := divAllocation_le_work cone (canonicalAddWithWork one delta).1 + have hm := maxAllocation_le_work (divWithWork cone (canonicalAddWithWork one delta).1).1 online + have hf := minAllocation_le_work cone + (maxWithWork (divWithWork cone (canonicalAddWithWork one delta).1).1 online).1 + unfold refinementUpdateAllocation refinementUpdateWithWork + dsimp only + omega + +/-- The two Bellman passes, materialized online scores and final arithmetic +retain their actual primitive allocation traces. -/ + + +theorem localContinuationReadAllocation_le_work {Parent Child : Type*} {M : ℕ} + (distance : Parent → Parent → BinaryFraction × ℕ) (distanceAllocation : Parent → Parent → ℕ) + (L delta fallback : BinaryFraction) (old current : Child → BinaryFraction × ℕ) + (oldAllocation currentAllocation : Child → ℕ) (query : Parent) + (wide groups online : List (BinaryBellmanAction Parent Child M)) + (hd : ∀ state, distanceAllocation query state ≤ (distance query state).2) + (ho : ∀ child, oldAllocation child ≤ (old child).2) + (hc : ∀ child, currentAllocation child ≤ (current child).2) : + localContinuationReadAllocation distance distanceAllocation L delta fallback old current + oldAllocation currentAllocation query wide groups online ≤ + (localContinuationReadWithWork distance L delta fallback old current query wide groups online).2 := by + have hw := bellmanReadAllocation_le_work distance distanceAllocation L fallback old oldAllocation query wide + (fun action _ => hd action.center) (fun action _ i => ho (action.childState i)) + have hg := bellmanReadAllocation_le_work distance distanceAllocation L + (bellmanReadWithWork distance L fallback old query wide).1 current currentAllocation query groups + (fun action _ => hd action.center) (fun action _ i => hc (action.childState i)) + have hs := arithmeticMapAllocation_le_work (bellmanActionReadWithWork distance L current query) + (bellmanActionReadAllocation distance distanceAllocation L current currentAllocation query) online + (fun action _ => bellmanActionReadAllocation_le_work distance distanceAllocation L current + currentAllocation query action (hd action.center) (fun i => hc (action.childState i))) + let scores := (arithmeticMapWithWork (bellmanActionReadWithWork distance L current query) online).1 + have hm := onlineMinimumAllocation_le_work scores + have hf := refinementUpdateAllocation_le_work delta + (bellmanReadWithWork distance L (bellmanReadWithWork distance L fallback old query wide).1 current query groups).1 + (onlineMinimumWithWork scores).1 + unfold localContinuationReadAllocation localContinuationReadWithWork + dsimp only [scores] at hm hf ⊢ + omega + +end EditApproximation.BinaryFraction + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryContinuationWork.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryContinuationWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..9cbb2c1c5316a27fb87c8ac3b8cc99c90060b242 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryContinuationWork.lean @@ -0,0 +1,96 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryBellmanKernel + +namespace OAI + +/-! Bit costs for the full numerical tail after its finite candidate lists +have been prepared. Both Bellman minima, the online score minimum, and the +final clipped decrement are executed by the counter being bounded. -/ + +namespace EditApproximation +namespace BinaryFraction + +def localContinuationInputBudget (M B : ℕ) : ℕ := + B + 2 * bellmanActionWordBudget M B + 1 + +def localContinuationWordBudget (M B : ℕ) : ℕ := + refinementUpdateWordBudget (localContinuationInputBudget M B) + +def localContinuationBitBudget (M nw ng no B C : ℕ) : ℕ := + bellmanBitBudget M nw B B C + + bellmanBitBudget M ng B (B + bellmanActionWordBudget M B) C + + no * (bellmanActionBitBudget M B C + 3) + + (2 + no * (1000 * (bellmanActionWordBudget M B + 1) ^ 2 + 2)) + + refinementUpdateBitBudget (localContinuationInputBudget M B) + 3 + +theorem localContinuationWithWork_bounds {Parent Child : Type*} {M : ℕ} + (distance : Parent → Parent → BinaryFraction × ℕ) (L delta fallback : BinaryFraction) + (old current : Child → BinaryFraction) (query : Parent) + (wide groups online : List (BinaryBellmanAction Parent Child M)) (B C : ℕ) + (hL : L.width ≤ B) (hdelta : delta.width ≤ B) (hf : fallback.width ≤ B) + (hd : ∀ action ∈ wide ++ groups ++ online, (distance query action.center).1.width ≤ B) + (hdc : ∀ action ∈ wide ++ groups ++ online, (distance query action.center).2 ≤ C) + (hc : ∀ action ∈ wide ++ groups ++ online, action.connection.width ≤ B) + (ho : ∀ action ∈ wide, ∀ i, (old (action.childState i)).width ≤ B) + (hn : ∀ action ∈ groups ++ online, ∀ i, (current (action.childState i)).width ≤ B) : + (localContinuationWithWork distance L delta fallback old current query wide groups online).1.width ≤ + localContinuationWordBudget M B ∧ + (localContinuationWithWork distance L delta fallback old current query wide groups online).2 ≤ + localContinuationBitBudget M wide.length groups.length online.length B C := by + let warm := bellmanWithWork distance L fallback old query wide + let cone := bellmanWithWork distance L warm.1 current query groups + let scores := arithmeticMapWithWork (bellmanActionWithWork distance L current query) online + let onlineMin := onlineMinimumWithWork scores.1 + have hw := bellmanWithWork_bounds distance L fallback old query wide B B C hL hf + (fun a ha => hd a (by simp [ha])) + (fun a ha => hdc a (by simp [ha])) + (fun a ha => hc a (by simp [ha])) ho + have hg := bellmanWithWork_bounds distance L warm.1 current query groups B + (B + bellmanActionWordBudget M B) C hL hw.1 + (fun a ha => hd a (by simp [ha])) + (fun a ha => hdc a (by simp [ha])) + (fun a ha => hc a (by simp [ha])) + (fun a ha => hn a (List.mem_append_left online ha)) + have hs (a : BinaryBellmanAction Parent Child M) (ha : a ∈ online) := + bellmanActionWithWork_bounds distance L current query a B C hL + (hd a (by simp [ha])) (hdc a (by simp [ha])) + (hc a (by simp [ha])) (hn a (List.mem_append_right groups ha)) + have hsw : ∀ value ∈ scores.1, value.width ≤ bellmanActionWordBudget M B := by + intro value hvalue + simp only [scores, arithmeticMapWithWork_value] at hvalue + obtain ⟨a, ha, rfl⟩ := List.mem_map.mp hvalue + exact (hs a ha).1 + have hsc := arithmeticMapWithWork_cost (bellmanActionWithWork distance L current query) online + (bellmanActionBitBudget M B C) (fun a ha => (hs a ha).2) + have hom := onlineMinimumWithWork_bounds scores.1 (bellmanActionWordBudget M B) hsw + have hlen : scores.1.length = online.length := by + simp only [scores, arithmeticMapWithWork_value, List.length_map] + rw [hlen] at hom + have hinput : 1 ≤ localContinuationInputBudget M B := by + unfold localContinuationInputBudget + omega + have hdelta' : delta.width ≤ localContinuationInputBudget M B := hdelta.trans (by + unfold localContinuationInputBudget; omega) + have hcone : cone.1.width ≤ localContinuationInputBudget M B := hg.1.trans (by + unfold localContinuationInputBudget; omega) + have honline : ∀ value ∈ onlineMin.1, value.width ≤ localContinuationInputBudget M B := by + intro value hv + exact (hom.1 value hv).trans (by unfold localContinuationInputBudget; omega) + have hresult := refinementUpdateWithWork_bounds delta cone.1 onlineMin.1 + (localContinuationInputBudget M B) hinput hdelta' hcone honline + refine ⟨hresult.1, ?_⟩ + change warm.2 + cone.2 + scores.2 + onlineMin.2 + + (refinementUpdateWithWork delta cone.1 onlineMin.1).2 + 3 ≤ _ + have hwc := hw.2 + have hgc := hg.2 + change warm.2 ≤ _ at hwc + change cone.2 ≤ _ at hgc + change scores.2 ≤ _ at hsc + have homc := hom.2 + change onlineMin.2 ≤ _ at homc + unfold localContinuationBitBudget + omega + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryCoordinateAction.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryCoordinateAction.lean new file mode 100644 index 0000000000000000000000000000000000000000..66c3c6ced0907bae2c3453e7a179618a8639a9bd --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryCoordinateAction.lean @@ -0,0 +1,122 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryBandCoordinates +import OAI.Combinatorics.EditApproximation.Binary.BinaryBandAction +import OAI.Combinatorics.EditApproximation.Binary.BinarySampledOnline +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! The prepared online action explicitly constructs its coordinate array +and compares stored endpoints when constructing each vertex. -/ + +namespace EditApproximation +namespace BinaryFraction + + + +@[simp] theorem coordinateVectorWithWork_value {M n : ℕ} (band : List (Fin M → TargetInterval n)) : + (coordinateVectorWithWork band).1 = listedBandCoordinateVector band := by + unfold coordinateVectorWithWork listedBandCoordinateVector + apply Vector.ext + intro i hi + simp only [Vector.getElem_ofFn, List.get_eq_getElem] + exact List.getElem_of_eq (bandCoordinatesWithWork_value band) _ + + + +theorem countedBandCoordinateWithWork_eq {M n : ℕ} (mass : Vector BinaryFraction M) + (total : BinaryFraction) (action : Fin M → TargetInterval n) + (coordinate : Fin M × TargetInterval n) : + (countedBandCoordinateWithWork mass total action coordinate).1 = + (bandCoordinateWithWork mass total action coordinate).1 ∧ + (countedBandCoordinateWithWork mass total action coordinate).2 = + (coordinateEqualWithWork coordinate (coordinate.1, action coordinate.1)).2 + + (bandCoordinateWithWork mass total action coordinate).2 + 1 := by + have ht : (coordinateEqualWithWork coordinate (coordinate.1, action coordinate.1)).1 = true ↔ + coordinate.2 = action coordinate.1 := by + rw [coordinateEqualWithWork_value] + exact ⟨fun h => congrArg Prod.snd h, fun h => Prod.ext rfl h⟩ + unfold countedBandCoordinateWithWork bandCoordinateWithWork + dsimp only + by_cases h : coordinate.2 = action coordinate.1 + · simp only [ite_eq_left h, ite_eq_left (ht.mpr h), and_self] + · simp only [ite_eq_right h, ite_eq_right (fun hp => h (ht.mp hp)), and_self] + + + +@[simp] theorem countedBandVerticesWithWork_value {M n d : ℕ} + (coordinates : Vector (Fin M × TargetInterval n) d) + (mass : Vector BinaryFraction M) (band : List (Fin M → TargetInterval n)) : + (countedBandVerticesWithWork coordinates mass band).1 = + (labeledBandVerticesWithWork coordinates mass band).1 := by + simp only [countedBandVerticesWithWork, labeledBandVerticesWithWork, List.map_map, + Function.comp_def] + apply List.map_congr_left + intro action _ + apply congrArg (Prod.mk action) + apply Vector.ext + intro i hi + change ((vectorMapWithWork d _).1.get ⟨i, hi⟩) = ((vectorMapWithWork d _).1.get ⟨i, hi⟩) + rw [vectorMapWithWork_value, vectorMapWithWork_value] + exact (countedBandCoordinateWithWork_eq _ _ _ _).1 + +def countedPreparedActionWithWork {M n : ℕ} (mass : Vector BinaryFraction M) + (table : ℕ → Fin M × TargetInterval n → BinaryFraction) + (eta kappa : BinaryFraction) (band : List (Fin M → TargetInterval n)) (G j t : ℕ) : + Option (Fin M → TargetInterval n) × ℕ := + let coordinates := coordinateVectorWithWork band + let vertices := countedBandVerticesWithWork coordinates.1 mass band + let linear := vectorMapWithWork _ fun i => + onlineLinearWithWork (fun child => mass.get child) table eta kappa t (coordinates.1.get i) + let selected := selectionWithWork vertices.1 linear.1 G j + (selected.1, coordinates.2 + vertices.2 + linear.2 + selected.2 + 3) + +@[simp] theorem countedPreparedActionWithWork_value {M n : ℕ} + (mass : Vector BinaryFraction M) (table : ℕ → Fin M × TargetInterval n → BinaryFraction) + (eta kappa : BinaryFraction) (band : List (Fin M → TargetInterval n)) (G j t : ℕ) : + (countedPreparedActionWithWork mass table eta kappa band G j t).1 = + (preparedBandActionWithWork mass table eta kappa band G j t).1 := by + simp only [countedPreparedActionWithWork, coordinateVectorWithWork_value, + countedBandVerticesWithWork_value, preparedBandActionWithWork] + +def countedBandActionWithWork {M n : ℕ} (b : ℕ) + (initial : Fin M → TargetInterval n → BinaryFraction) + (table : ℕ → Fin M × TargetInterval n → BinaryFraction) (eta kappa : BinaryFraction) + (band : List (Fin M → TargetInterval n)) (G j t : ℕ) : + Option (Fin M → TargetInterval n) × ℕ := + let mass := envelopeVectorWithWork b band initial + let selected := countedPreparedActionWithWork mass.1 table eta kappa band G j t + (selected.1, mass.2 + selected.2 + 1) + +@[simp] theorem countedBandActionWithWork_value {M n : ℕ} (b : ℕ) + (initial : Fin M → TargetInterval n → BinaryFraction) + (table : ℕ → Fin M × TargetInterval n → BinaryFraction) (eta kappa : BinaryFraction) + (band : List (Fin M → TargetInterval n)) (G j t : ℕ) : + (countedBandActionWithWork b initial table eta kappa band G j t).1 = + (bandActionWithWork b initial table eta kappa band G j t).1 := by + simp only [countedBandActionWithWork, countedPreparedActionWithWork_value, bandActionWithWork] + +def countedSampledOnlineWithWork {M n : ℕ} (center : TargetInterval n) (b : ℕ) + (initial : Fin M → TargetInterval n → BinaryFraction) + (table : ℕ → Fin M × TargetInterval n → BinaryFraction) (eta kappa : BinaryFraction) + (band : List (Fin M → TargetInterval n)) (hne : band ≠ []) + (G K t : ℕ) (integer : Fin (optimizerTriangularMass K)) : + BinaryBellmanAction (TargetInterval n) (Fin M × TargetInterval n) M × ℕ := + let chosen := triangularChoiceWithWork K integer + let selected := countedBandActionWithWork b initial table eta kappa band G chosen.1.val t + let states := selected.1.getD (band.head hne) + (⟨center, zero, fun i => (i, states i)⟩, chosen.2 + selected.2 + M + 2) + +@[simp] theorem countedSampledOnlineWithWork_value {M n : ℕ} (center : TargetInterval n) (b : ℕ) + (initial : Fin M → TargetInterval n → BinaryFraction) + (table : ℕ → Fin M × TargetInterval n → BinaryFraction) (eta kappa : BinaryFraction) + (band : List (Fin M → TargetInterval n)) (hne : band ≠ []) + (G K t : ℕ) (integer : Fin (optimizerTriangularMass K)) : + (countedSampledOnlineWithWork center b initial table eta kappa band hne G K t integer).1 = + (sampledOnlineActionWithWork center b initial table eta kappa band hne G K t integer).1 := by + simp only [countedSampledOnlineWithWork, countedBandActionWithWork_value, sampledOnlineActionWithWork] + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryCoordinateActionWork.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryCoordinateActionWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..b960e2b842e3ee7e9352d99721bff7ccda6ec676 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryCoordinateActionWork.lean @@ -0,0 +1,112 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryCoordinateAction + +namespace OAI + +/-! The cost of coordinate construction and every endpoint equality is +added to the complete optimizer cost, with no unit-cost rational +or uncharged generic equality operation. -/ + +namespace EditApproximation +namespace BinaryFraction + +private theorem vectorMap_cost_le_add {α β : Type*} (d : ℕ) + (first : Fin d → α × ℕ) (second : Fin d → β × ℕ) (C : ℕ) + (h : ∀ i, (first i).2 ≤ (second i).2 + C) : + (vectorMapWithWork d first).2 ≤ (vectorMapWithWork d second).2 + d * C := by + simp only [vectorMapWithWork, Vector.toList_map, Vector.toList_ofFn, + List.map_ofFn, Function.comp_def, List.sum_ofFn] + have hs := Finset.sum_le_sum (s := Finset.univ) (fun i _ => h i) + simp only [Finset.sum_add_distrib, Finset.sum_const, Finset.card_univ, Fintype.card_fin, + smul_eq_mul] at hs + omega + +theorem countedBandVerticesWithWork_cost {M n d : ℕ} + (coordinates : Vector (Fin M × TargetInterval n) d) (mass : Vector BinaryFraction M) + (band : List (Fin M → TargetInterval n)) (B : ℕ) + (hM : Nat.size M ≤ B) (hn : Nat.size n ≤ B) : + (countedBandVerticesWithWork coordinates mass band).2 ≤ + (labeledBandVerticesWithWork coordinates mass band).2 + band.length * d * (24 * B + 9) := by + have hvertex (action : Fin M → TargetInterval n) : + (vectorMapWithWork d (fun i => countedBandCoordinateWithWork mass + (bandMassTotalWithWork mass).1 action (coordinates.get i))).2 ≤ + (vectorMapWithWork d (fun i => bandCoordinateWithWork mass + (bandMassTotalWithWork mass).1 action (coordinates.get i))).2 + d * (24 * B + 9) := by + apply vectorMap_cost_le_add + intro i + rw [(countedBandCoordinateWithWork_eq _ _ _ _).2] + have hc := coordinateEqualWithWork_cost (coordinates.get i) + ((coordinates.get i).1, action (coordinates.get i).1) B hM hn + omega + have hsum : + (band.map (fun action => (vectorMapWithWork d (fun i => countedBandCoordinateWithWork mass + (bandMassTotalWithWork mass).1 action (coordinates.get i))).2)).sum ≤ + (band.map (fun action => (vectorMapWithWork d (fun i => bandCoordinateWithWork mass + (bandMassTotalWithWork mass).1 action (coordinates.get i))).2)).sum + + band.length * (d * (24 * B + 9)) := by + induction band with + | nil => simp + | cons action rest ih => + have ha := hvertex action + simp only [List.map_cons, List.sum_cons, List.length_cons, Nat.add_mul, Nat.one_mul] + omega + simp only [countedBandVerticesWithWork, labeledBandVerticesWithWork, List.map_map, + Function.comp_def] + simpa only [Nat.mul_assoc] using (show + (bandMassTotalWithWork mass).2 + _ + 8 * band.length ≤ + (bandMassTotalWithWork mass).2 + _ + 8 * band.length + band.length * (d * (24 * B + 9)) by omega) + +theorem countedPreparedActionWithWork_cost {M n : ℕ} (mass : Vector BinaryFraction M) + (table : ℕ → Fin M × TargetInterval n → BinaryFraction) (eta kappa : BinaryFraction) + (band : List (Fin M → TargetInterval n)) (G j t B : ℕ) + (hM : Nat.size M ≤ B) (hn : Nat.size n ≤ B) : + (countedPreparedActionWithWork mass table eta kappa band G j t).2 ≤ + (preparedBandActionWithWork mass table eta kappa band G j t).2 + + bandCoordinatesBitBudget M band.length B + (listedBandCoordinates band).length + + band.length * (listedBandCoordinates band).length * (24 * B + 9) + 2 := by + have hc := bandCoordinatesWithWork_cost band B hM hn + have hv := countedBandVerticesWithWork_cost (listedBandCoordinateVector band) mass band B hM hn + unfold countedPreparedActionWithWork + simp only [coordinateVectorWithWork_value, countedBandVerticesWithWork_value] + change (coordinateVectorWithWork band).2 + + (countedBandVerticesWithWork (listedBandCoordinateVector band) mass band).2 + _ + _ + 3 ≤ _ + unfold coordinateVectorWithWork + simp only [bandCoordinatesWithWork_value] + unfold preparedBandActionWithWork + dsimp only + omega + +theorem countedBandActionWithWork_cost {M n : ℕ} (b : ℕ) + (initial : Fin M → TargetInterval n → BinaryFraction) + (table : ℕ → Fin M × TargetInterval n → BinaryFraction) (eta kappa : BinaryFraction) + (band : List (Fin M → TargetInterval n)) (G j t B : ℕ) + (hM : Nat.size M ≤ B) (hn : Nat.size n ≤ B) : + (countedBandActionWithWork b initial table eta kappa band G j t).2 ≤ + (bandActionWithWork b initial table eta kappa band G j t).2 + + bandCoordinatesBitBudget M band.length B + (listedBandCoordinates band).length + + band.length * (listedBandCoordinates band).length * (24 * B + 9) + 2 := by + have h := countedPreparedActionWithWork_cost (envelopeVectorWithWork b band initial).1 + table eta kappa band G j t B hM hn + unfold countedBandActionWithWork bandActionWithWork + dsimp only + omega + +theorem countedSampledOnlineWithWork_cost {M n : ℕ} (center : TargetInterval n) (b : ℕ) + (initial : Fin M → TargetInterval n → BinaryFraction) + (table : ℕ → Fin M × TargetInterval n → BinaryFraction) (eta kappa : BinaryFraction) + (band : List (Fin M → TargetInterval n)) (hne : band ≠ []) + (G K t B : ℕ) (integer : Fin (optimizerTriangularMass K)) + (hM : Nat.size M ≤ B) (hn : Nat.size n ≤ B) : + (countedSampledOnlineWithWork center b initial table eta kappa band hne G K t integer).2 ≤ + (sampledOnlineActionWithWork center b initial table eta kappa band hne G K t integer).2 + + bandCoordinatesBitBudget M band.length B + (listedBandCoordinates band).length + + band.length * (listedBandCoordinates band).length * (24 * B + 9) + 2 := by + have h := countedBandActionWithWork_cost b initial table eta kappa band G + (triangularChoiceWithWork K integer).1.val t B hM hn + unfold countedSampledOnlineWithWork sampledOnlineActionWithWork + dsimp only + omega + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryCountedActionSpace.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryCountedActionSpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..bb62b1f2191b5f0a9f589d038f8943bfcd87eefd --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryCountedActionSpace.lean @@ -0,0 +1,68 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryCountedOptimizerSpace +import OAI.Combinatorics.EditApproximation.Queries.QueryCoordinateSpace +import OAI.Combinatorics.EditApproximation.Binary.BinaryEnvelopeSpace +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation.BinaryFraction + +/-- All counted optimizer allocations, including coordinate construction. -/ + + +theorem countedPreparedActionAllocation_le_work {M n : ℕ} (mass : Vector BinaryFraction M) + (read : ℕ → Fin M × TargetInterval n → BinaryFraction × ℕ) + (footprint : ℕ → Fin M × TargetInterval n → ℕ) + (eta kappa : BinaryFraction) (band : List (Fin M → TargetInterval n)) (G j t : ℕ) + (h : ∀ s coordinate, footprint s coordinate ≤ (read s coordinate).2) : + countedPreparedActionAllocation mass read footprint eta kappa band G j t ≤ + 3 * (countedPreparedActionReadWithWork mass read eta kappa band G j t).2 := by + have hc := coordinateVectorAllocation_le_work band + have hk := countedPreparedActionKernelAllocation_le_work mass read footprint eta kappa band G j t h + have hlocal : (coordinateVectorWithWork band).2 ≤ + (countedPreparedActionReadWithWork mass read eta kappa band G j t).2 := by + unfold countedPreparedActionReadWithWork + dsimp only + omega + unfold countedPreparedActionAllocation + omega + + + +theorem countedBandActionAllocation_le_work {M n : ℕ} (b : ℕ) + (initial : Fin M → TargetInterval n → BinaryFraction × ℕ) + (initialAllocation : Fin M → TargetInterval n → ℕ) + (read : ℕ → Fin M × TargetInterval n → BinaryFraction × ℕ) + (footprint : ℕ → Fin M × TargetInterval n → ℕ) + (eta kappa : BinaryFraction) (band : List (Fin M → TargetInterval n)) (G j t : ℕ) + (hi : ∀ i state, initialAllocation i state ≤ (initial i state).2) + (hr : ∀ s coordinate, footprint s coordinate ≤ (read s coordinate).2) : + countedBandActionAllocation b initial initialAllocation read footprint eta kappa band G j t ≤ + 3 * (countedBandActionReadWithWork b initial read eta kappa band G j t).2 := by + have he := envelopeVectorReadAllocation_le_work b band initial initialAllocation (fun i action _ => hi i (action i)) + have hc := countedPreparedActionAllocation_le_work (envelopeVectorReadWithWork b band initial).1 + read footprint eta kappa band G j t hr + unfold countedBandActionAllocation countedBandActionReadWithWork + dsimp only + omega + +/-- The actual gathered-history specialization of the labeled action sampler. -/ +def queryCountedActionAllocation {M n : ℕ} (mass : Vector BinaryFraction M) + (keys : List (Fin M × ℕ × TargetInterval n)) (values : List BinaryFraction) + (eta kappa : BinaryFraction) (band : List (Fin M → TargetInterval n)) (G j t : ℕ) : ℕ := + countedPreparedActionAllocation mass (queryHistoryReadWithWork keys values) + (queryHistoryReadAllocation keys values) eta kappa band G j t + +theorem queryCountedActionAllocation_le_work {M n : ℕ} (mass : Vector BinaryFraction M) + (keys : List (Fin M × ℕ × TargetInterval n)) (values : List BinaryFraction) + (eta kappa : BinaryFraction) (band : List (Fin M → TargetInterval n)) (G j t : ℕ) : + queryCountedActionAllocation mass keys values eta kappa band G j t ≤ + 3 * (countedPreparedActionReadWithWork mass (queryHistoryReadWithWork keys values) + eta kappa band G j t).2 := + countedPreparedActionAllocation_le_work mass _ _ eta kappa band G j t + (fun _ _ => queryHistoryReadAllocation_le_work _ _ _ _) + +end EditApproximation.BinaryFraction + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryCountedGroup.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryCountedGroup.lean new file mode 100644 index 0000000000000000000000000000000000000000..0438f82f832eb4d407550c48bfdee7b8bbc25215 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryCountedGroup.lean @@ -0,0 +1,70 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryGroupSetupWork +import OAI.Combinatorics.EditApproximation.Binary.BinaryGradientWork + +namespace OAI + +/-! Group evaluation reads the exact finite sampler indexed by the count +computed from the stored rational scale. Casting indices below is proof +transport only; the emitted natural count is used by the executed loop. -/ + +namespace EditApproximation +namespace BinaryFraction + +def countedGroupMemberWithWork {M T : ℕ} (Q b : ℕ) (scales : Fin T → BinaryFraction) + (connection : BinaryFraction) (envelope values : Vector BinaryFraction M) + (draw : ∀ t, Fin (groupSampleCount M Q b (scales t).value) → Fin M) : BinaryFraction × ℕ := + let counts := vectorMapWithWork T fun t => groupSampleCountWithWork M Q b (scales t) + let count := fun t => bitWordValue (counts.1.get t) + let heq : ∀ t, count t = groupSampleCount M Q b (scales t).value := by + intro t + simp only [count, counts, vectorMapWithWork_value, groupSampleCountWithWork_value] + let result := groupMemberWithWork scales count connection envelope values + (fun t j => draw t (Fin.cast (heq t) j)) + (result.1, counts.2 + result.2 + 1) + +theorem groupMemberWithWork_transport {M T : ℕ} + (scales : Fin T → BinaryFraction) (left right : Fin T → ℕ) (h : ∀ t, left t = right t) + (connection : BinaryFraction) (envelope values : Vector BinaryFraction M) + (draw : ∀ t, Fin (right t) → Fin M) : + groupMemberWithWork scales left connection envelope values (fun t j => draw t (Fin.cast (h t) j)) = + groupMemberWithWork scales right connection envelope values draw := by + have heq : left = right := funext h + subst right + rfl + +@[simp] theorem countedGroupMemberWithWork_value {M T : ℕ} (Q b : ℕ) (scales : Fin T → BinaryFraction) + (connection : BinaryFraction) (envelope values : Vector BinaryFraction M) + (draw : ∀ t, Fin (groupSampleCount M Q b (scales t).value) → Fin M) : + (countedGroupMemberWithWork Q b scales connection envelope values draw).1.value = + groupMemberEstimate (fun t => (scales t).value) (fun t => groupSampleCount M Q b (scales t).value) + connection.value (fun i => (envelope.get i).value) (fun i => (values.get i).value) draw := by + unfold countedGroupMemberWithWork + dsimp only + rw [groupMemberWithWork_transport] + exact groupMemberWithWork_value _ _ _ _ _ _ + +theorem countedGroupMemberWithWork_cost {M T : ℕ} (Q b : ℕ) (scales : Fin T → BinaryFraction) + (connection : BinaryFraction) (envelope values : Vector BinaryFraction M) + (draw : ∀ t, Fin (groupSampleCount M Q b (scales t).value) → Fin M) + (B C W : ℕ) (hM : Nat.size M + 2 ≤ B) (hQ : Nat.size Q + 2 ≤ B) + (hb : Nat.size b + 2 ≤ B) (hs : ∀ t, (scales t).width ≤ B) + (hconn : connection.width ≤ B) + (hc : ∀ t, (groupScaleWithWork (groupSampleCount M Q b (scales t).value) (scales t) + envelope values (draw t)).2 ≤ C) + (hw : ∀ t, (groupScaleWithWork (groupSampleCount M Q b (scales t).value) (scales t) + envelope values (draw t)).1.width ≤ W) : + (countedGroupMemberWithWork Q b scales connection envelope values draw).2 ≤ + T * (groupSampleCountBitBudget B + 6) + groupMemberBitBudget T B C W + 1 := by + have hcounts := vectorMapWithWork_cost_le T (fun t => groupSampleCountWithWork M Q b (scales t)) + (groupSampleCountBitBudget B) (fun t => (groupSampleCountWithWork_bounds M Q b (scales t) B hM hQ hb (hs t)).2) + have hmember := (groupMemberWithWork_bounds scales + (fun t => groupSampleCount M Q b (scales t).value) connection envelope values draw B C W hconn hc hw).2 + unfold countedGroupMemberWithWork + dsimp only + rw [groupMemberWithWork_transport] + omega + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryCountedGroupWork.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryCountedGroupWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..bb74ee2bb790029a13c2530e51cf2c149f2fe12b --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryCountedGroupWork.lean @@ -0,0 +1,85 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryCountedGroup + +namespace OAI + +/-! The count used by every sampled scale is at most the actual child +arity. Consequently the complete group counter is bounded from stored +input widths, without assuming estimates on its internal callbacks. -/ + +namespace EditApproximation +namespace BinaryFraction + +private theorem sumStorage_mono {n m B : ℕ} (h : n ≤ m) : + bandMassTotalStorageBudget n B ≤ bandMassTotalStorageBudget m B := by + have hs := Nat.size_le_size h + unfold bandMassTotalStorageBudget + gcongr + +private theorem storedSumWork_mono {n m B : ℕ} (h : n ≤ m) : + storedSumBitBudget n B ≤ storedSumBitBudget m B := by + have hs := Nat.size_le_size h + unfold storedSumBitBudget storedSumWordBudget + gcongr + +def boundedScaleWordBudget (M B : ℕ) : ℕ := + 4 * (4 * B + 4 + bandMassTotalStorageBudget M B) + 2 + +def boundedScaleBitBudget (M B : ℕ) : ℕ := + groupIndexBitBudget M B + (2100 * (B + 2) ^ 2 + 1) + + 2000 * (4 * B + 4 + bandMassTotalStorageBudget M B + 1) ^ 2 + 2 * B + 3 + +private theorem groupScale_budget_le (M k B : ℕ) (hk : k ≤ M) : + groupScaleWordBudget M k B ≤ boundedScaleWordBudget M B ∧ + groupScaleBitBudget M k B ≤ boundedScaleBitBudget M B := by + have ht : groupScaleTermCount M k ≤ M := by + unfold groupScaleTermCount + split_ifs <;> omega + have hsum := sumStorage_mono (B := B) ht + have hwork := storedSumWork_mono (B := B) ht + constructor + · unfold groupScaleWordBudget boundedScaleWordBudget + omega + · unfold groupScaleBitBudget boundedScaleBitBudget groupIndexBitBudget + have hprod := Nat.mul_le_mul_right (2 * (1000 * (B + 1) ^ 2 + 1) + 6) ht + have hsq := Nat.pow_le_pow_left (show + 4 * B + 4 + bandMassTotalStorageBudget (groupScaleTermCount M k) B + 1 ≤ + 4 * B + 4 + bandMassTotalStorageBudget M B + 1 by omega) 2 + omega + +def countedGroupBitBudget (M T B : ℕ) : ℕ := + T * (groupSampleCountBitBudget B + 6) + + groupMemberBitBudget T B (boundedScaleBitBudget M B) (boundedScaleWordBudget M B) + 1 + +theorem countedGroupMemberWithWork_bounds {M T : ℕ} (Q b : ℕ) (scales : Fin T → BinaryFraction) + (connection : BinaryFraction) (envelope values : Vector BinaryFraction M) + (draw : ∀ t, Fin (groupSampleCount M Q b (scales t).value) → Fin M) + (B : ℕ) (hB : 1 ≤ B) (hM : Nat.size M + 2 ≤ B) (hQ : Nat.size Q + 2 ≤ B) + (hb : Nat.size b + 2 ≤ B) (hs : ∀ t, (scales t).width ≤ B) + (hconn : connection.width ≤ B) (he : ∀ i, (envelope.get i).width ≤ B) + (hv : ∀ i, (values.get i).width ≤ B) : + (countedGroupMemberWithWork Q b scales connection envelope values draw).1.width ≤ + groupMemberWordBudget T B (boundedScaleWordBudget M B) ∧ + (countedGroupMemberWithWork Q b scales connection envelope values draw).2 ≤ + countedGroupBitBudget M T B := by + have hk (t : Fin T) : groupSampleCount M Q b (scales t).value ≤ M := by + exact min_le_left _ _ + have hscale (t : Fin T) := groupScaleWithWork_bounds + (groupSampleCount M Q b (scales t).value) (scales t) envelope values (draw t) B + hB (hs t) he hv hM ((Nat.add_le_add_right (Nat.size_le_size (hk t)) 2).trans hM) + have hc (t : Fin T) := (hscale t).2.trans (groupScale_budget_le M _ B (hk t)).2 + have hw (t : Fin T) := (hscale t).1.trans (groupScale_budget_le M _ B (hk t)).1 + constructor + · have hmember := (groupMemberWithWork_bounds scales + (fun t => groupSampleCount M Q b (scales t).value) connection envelope values draw B + (boundedScaleBitBudget M B) (boundedScaleWordBudget M B) hconn hc hw).1 + unfold countedGroupMemberWithWork + dsimp only + rw [groupMemberWithWork_transport] + exact hmember + · exact countedGroupMemberWithWork_cost Q b scales connection envelope values draw B + (boundedScaleBitBudget M B) (boundedScaleWordBudget M B) hM hQ hb hs hconn hc hw + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryCountedOptimizerSpace.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryCountedOptimizerSpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..e38fa8dd66ba4f418366c04d5e2c121e51918017 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryCountedOptimizerSpace.lean @@ -0,0 +1,73 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinarySelectionSpace +import OAI.Combinatorics.EditApproximation.Binary.BinaryBandActionReads +import OAI.Combinatorics.EditApproximation.Queries.QueryBufferSpace +import OAI.Combinatorics.EditApproximation.Binary.BinaryOnlineSpace +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation.BinaryFraction + + + +theorem countedBandCoordinateAllocation_le_work {M n : ℕ} (mass : Vector BinaryFraction M) + (total : BinaryFraction) (action : Fin M → TargetInterval n) (coordinate : Fin M × TargetInterval n) : + countedBandCoordinateAllocation mass total action coordinate ≤ + (countedBandCoordinateWithWork mass total action coordinate).2 := by + have hc := coordinateEqualAllocation_le_work coordinate (coordinate.1, action coordinate.1) + have hd := divAllocation_le_work (mass.get coordinate.1) total + unfold countedBandCoordinateAllocation countedBandCoordinateWithWork + dsimp only + split_ifs <;> (try dsimp only) <;> omega + + + +theorem countedBandVerticesAllocation_le_work {M n d : ℕ} (coordinates : Vector (Fin M × TargetInterval n) d) + (mass : Vector BinaryFraction M) (band : List (Fin M → TargetInterval n)) : + countedBandVerticesAllocation coordinates mass band ≤ (countedBandVerticesWithWork coordinates mass band).2 := by + have hm := bandMassAllocation_le_work mass + have hs : (band.map fun action => vectorMapAllocation d fun i => + countedBandCoordinateAllocation mass (bandMassTotalWithWork mass).1 action (coordinates.get i)).sum ≤ + (band.map fun action => (vectorMapWithWork d fun i => + countedBandCoordinateWithWork mass (bandMassTotalWithWork mass).1 action (coordinates.get i)).2).sum := by + induction band with + | nil => simp + | cons a rest ih => + have h := vectorMapAllocation_le_work d + (fun i => countedBandCoordinateWithWork mass (bandMassTotalWithWork mass).1 a (coordinates.get i)) + (fun i => countedBandCoordinateAllocation mass (bandMassTotalWithWork mass).1 a (coordinates.get i)) + (fun i => countedBandCoordinateAllocation_le_work _ _ _ _) + simp only [List.map_cons, List.sum_cons] + omega + unfold countedBandVerticesAllocation countedBandVerticesWithWork + simp only [List.map_map, Function.comp_def] + omega + +/-- Arithmetic and labeled-vector allocation after coordinate construction. +Coordinate construction itself is accounted by its separate list allocator. -/ + + +theorem countedPreparedActionKernelAllocation_le_work {M n : ℕ} (mass : Vector BinaryFraction M) + (read : ℕ → Fin M × TargetInterval n → BinaryFraction × ℕ) + (footprint : ℕ → Fin M × TargetInterval n → ℕ) + (eta kappa : BinaryFraction) (band : List (Fin M → TargetInterval n)) (G j t : ℕ) + (h : ∀ s coordinate, footprint s coordinate ≤ (read s coordinate).2) : + countedPreparedActionKernelAllocation mass read footprint eta kappa band G j t ≤ + 2 * (countedPreparedActionReadWithWork mass read eta kappa band G j t).2 := by + let coordinates := (coordinateVectorWithWork band).1 + have hv := countedBandVerticesAllocation_le_work coordinates mass band + have hl := vectorMapAllocation_le_work _ + (fun i => onlineLinearReadWithWork (fun child => mass.get child) read eta kappa t (coordinates.get i)) + (fun i => onlineLinearReadAllocation (fun child => mass.get child) read footprint eta kappa t (coordinates.get i)) + (fun i => onlineLinearReadAllocation_le_work _ _ _ _ _ _ _ (fun s _ => h s _)) + have hs := selectionAllocation_le_work (countedBandVerticesWithWork coordinates mass band).1 + (vectorMapWithWork _ fun i => onlineLinearReadWithWork (fun child => mass.get child) + read eta kappa t (coordinates.get i)).1 G j + unfold countedPreparedActionKernelAllocation countedPreparedActionReadWithWork + dsimp only [coordinates] at hv hl hs ⊢ + omega + +end EditApproximation.BinaryFraction + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryCutReads.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryCutReads.lean new file mode 100644 index 0000000000000000000000000000000000000000..4307413200af8037fb2b40fa17335c56524cd67f --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryCutReads.lean @@ -0,0 +1,103 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryPrefixReads +import OAI.Combinatorics.EditApproximation.Binary.BinaryBandGuardWork +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Literal cut predicates and all-cut loops with costed child readers. -/ + +namespace EditApproximation + +theorem allWithWork_extra {α : Type*} (read plain : α → Bool × ℕ) (extra : α → ℕ) + (xs : List α) (hv : ∀ x ∈ xs, (read x).1 = (plain x).1) + (hc : ∀ x ∈ xs, (read x).2 ≤ (plain x).2 + extra x) : + (allWithWork read xs).1 = (allWithWork plain xs).1 ∧ + (allWithWork read xs).2 ≤ (allWithWork plain xs).2 + (xs.map extra).sum := by + have costBound (a a' b b' A B : ℕ) (ha : a ≤ a' + A) (hb : b ≤ b' + B) : + a + b + 3 ≤ a' + b' + 3 + (A + B) := by + omega + induction xs with + | nil => exact ⟨rfl, Nat.le_refl _⟩ + | cons x xs ih => + have hh := hv x List.mem_cons_self + have hhCost := hc x List.mem_cons_self + have ht := ih (fun y hy => hv y (List.mem_cons_of_mem _ hy)) + (fun y hy => hc y (List.mem_cons_of_mem _ hy)) + constructor + · change ((read x).1 && (allWithWork read xs).1) = + ((plain x).1 && (allWithWork plain xs).1) + rw [hh, ht.1] + · change (read x).2 + (allWithWork read xs).2 + 3 ≤ + (plain x).2 + (allWithWork plain xs).2 + 3 + (extra x + (xs.map extra).sum) + exact costBound _ _ _ _ _ _ hhCost ht.2 + +namespace BinaryFraction + + + +theorem cutGuardReadWithWork_eq {nx ny M : ℕ} (parent : TargetInterval nx) (r : TargetInterval ny) + (actions : List (Fin M → TargetInterval ny)) (hne : actions ≠ []) + (read : Fin M → TargetInterval ny → BinaryFraction × ℕ) (states : Fin M → TargetInterval ny) + (velocity tolerance : BinaryFraction) (j : Fin M) : + (cutGuardReadWithWork parent r actions hne read states velocity tolerance j).1 = + (cutGuardWithWork parent r actions hne (fun i q => (read i q).1) states velocity tolerance j).1 := by + simp only [cutGuardReadWithWork, cutGuardWithWork] + split_ifs + · rfl + · simp only [prefixMinimumReadWithWork_eq] + +theorem cutGuardReadWithWork_cost {nx ny M : ℕ} (parent : TargetInterval nx) (r : TargetInterval ny) + (actions : List (Fin M → TargetInterval ny)) (hne : actions ≠ []) + (read : Fin M → TargetInterval ny → BinaryFraction × ℕ) (states : Fin M → TargetInterval ny) + (velocity tolerance : BinaryFraction) (j : Fin M) (R : ℕ) + (hr : ∀ action ∈ actions, ∀ i, (read i (action i)).2 ≤ R) : + (cutGuardReadWithWork parent r actions hne read states velocity tolerance j).2 ≤ + (cutGuardWithWork parent r actions hne (fun i q => (read i q).1) states velocity tolerance j).2 + + (actions.length + 1) * (M * (R + 4)) := by + have costBound (s o p p' v u w x y A : ℕ) (hp : p ≤ p' + A) : + s + o + p + v + u + w + x + y + 5 ≤ s + o + p' + v + u + w + x + y + 5 + A := by + omega + unfold cutGuardReadWithWork cutGuardWithWork + split_ifs + · exact Nat.le_add_right _ _ + · have h := prefixMinimumReadWithWork_cost parent r actions hne read j.val + (subWithWork (nat (states j).lo) (nat (sourceChild parent j).lo)).1 R hr + dsimp only + rw [prefixMinimumReadWithWork_eq] + exact costBound _ _ _ _ _ _ _ _ _ _ h + + + +theorem bandPredicateReadWithWork_eq_cost {nx ny M : ℕ} + (parent : TargetInterval nx) (r : TargetInterval ny) (b : ℕ) (tau theta velocity : BinaryFraction) + (actions : List (Fin M → TargetInterval ny)) (hne : actions ≠ []) + (read : Fin M → TargetInterval ny → BinaryFraction × ℕ) (states : Fin M → TargetInterval ny) + (R : ℕ) (hr : ∀ action ∈ actions, ∀ i, (read i (action i)).2 ≤ R) : + (bandPredicateReadWithWork parent r b tau theta velocity actions hne read states).1 = + (bandPredicateWithWork parent r b tau theta velocity actions hne + (fun i q => (read i q).1) states).1 ∧ + (bandPredicateReadWithWork parent r b tau theta velocity actions hne read states).2 ≤ + (bandPredicateWithWork parent r b tau theta velocity actions hne + (fun i q => (read i q).1) states).2 + M * ((actions.length + 1) * (M * (R + 4))) := by + have costBound (c a t k k' A : ℕ) (hk : k ≤ k' + A) : + c + a + t + k + 4 ≤ c + a + t + k' + 4 + A := by + omega + have h := allWithWork_extra + (cutGuardReadWithWork parent r actions hne read states velocity (bandToleranceWithWork tau theta b M).1) + (cutGuardWithWork parent r actions hne (fun i q => (read i q).1) states velocity + (bandToleranceWithWork tau theta b M).1) + (fun _ => (actions.length + 1) * (M * (R + 4))) (List.finRange M) + (fun i _ => cutGuardReadWithWork_eq parent r actions hne read states velocity _ i) + (fun i _ => cutGuardReadWithWork_cost parent r actions hne read states velocity _ i R hr) + simp only [List.map_const', List.length_finRange, List.sum_replicate, smul_eq_mul] at h + constructor + · simp only [bandPredicateReadWithWork, bandPredicateWithWork, h.1] + · unfold bandPredicateReadWithWork bandPredicateWithWork + dsimp only + exact costBound _ _ _ _ _ _ h.2 + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryDistanceWork.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryDistanceWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..5879102d5c2d8eb4afb851643f7bad57fe783c65 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryDistanceWork.lean @@ -0,0 +1,171 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryFiniteLoops +import OAI.Combinatorics.EditApproximation.Probability.FiniteEnumerationWork +import OAI.Combinatorics.EditApproximation.Numerics.RationalPrefix +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Absolute differences used in the literal prefix and band tests. +The sign update retains the magnitude words; subtraction uses signed +Boolean arithmetic. -/ + +namespace EditApproximation +namespace BinaryFraction + + + +@[simp] theorem absolute_value (a : BinaryFraction) : a.absolute.value = |a.value| := by + have hn : |(a.numerator.value : ℚ)| = (bitWordValue a.numerator.bits : ℚ) := by + cases h : a.numerator.negative <;> simp [SignedBinary.value, signedMagnitude, h] + have hd : (0 : ℚ) < bitWordValue a.denominator := by exact_mod_cast a.denominator_pos + change (bitWordValue a.numerator.bits : ℚ) / bitWordValue a.denominator = + |(a.numerator.value : ℚ) / bitWordValue a.denominator| + rw [abs_div, hn, abs_of_pos hd] + +@[simp] theorem absolute_width (a : BinaryFraction) : a.absolute.width = a.width := rfl + +@[simp] theorem nat_value (n : ℕ) : (nat n).value = (n : ℚ) := by + rw [← representation_value, nat_representation, UnreducedRational.value_nat] + +theorem canonicalAddWithWork_width (a b : BinaryFraction) (B : ℕ) + (ha : a.width ≤ B) (hb : b.width ≤ B) : + (a.canonicalAddWithWork b).1.width ≤ 8 * B + 6 := by + have hs := UnreducedRational.storageBits_add a.representation b.representation + have ha' := representation_storageBits_le a + have hb' := representation_storageBits_le b + have hw := canonicalAddWithWork_self_width a b + rw [canonicalAddWithWork_representation] at hw + omega + +theorem subWithWork_width (a b : BinaryFraction) (B : ℕ) + (ha : a.width ≤ B) (hb : b.width ≤ B) : + (a.subWithWork b).1.width ≤ 8 * B + 6 := by + exact canonicalAddWithWork_width a b.neg B ha (by simpa only [neg_width] using hb) + + + +@[simp] theorem distanceWithWork_value (a b : BinaryFraction) : + (distanceWithWork a b).1.value = |a.value - b.value| := by + simp only [distanceWithWork, absolute_value, subWithWork_value] + +theorem distanceWithWork_width (a b : BinaryFraction) (B : ℕ) + (ha : a.width ≤ B) (hb : b.width ≤ B) : + (distanceWithWork a b).1.width ≤ 8 * B + 6 := + subWithWork_width a b B ha hb + +theorem distanceWithWork_cost (a b : BinaryFraction) (B : ℕ) + (ha : a.width ≤ B) (hb : b.width ≤ B) : + (distanceWithWork a b).2 ≤ 6000 * (B + 1) ^ 2 + 2 := by + exact Nat.add_le_add_right (subWithWork_cost a b B ha hb) 1 + +/-- List of the literal endpoint differences. Natural endpoints are encoded +when encountered, and their bit-writing work is charged here. -/ + + +@[simp] theorem connectionTermsWithWork_length {n : ℕ} (start finish : BinaryFraction) + (states : List (TargetInterval n)) : + (connectionTermsWithWork start states finish).1.length = states.length + 1 := by + induction states generalizing start with + | nil => rfl + | cons state rest ih => + simp only [connectionTermsWithWork, List.length_cons, ih] + +theorem connectionTermsWithWork_value {n : ℕ} (start finish : BinaryFraction) + (states : List (TargetInterval n)) : + ((connectionTermsWithWork start states finish).1.map value).sum = + rationalConnectionBudget start.value states finish.value := by + induction states generalizing start with + | nil => simp only [connectionTermsWithWork, List.map_cons, List.map_nil, + List.sum_cons, List.sum_nil, add_zero, distanceWithWork_value, rationalConnectionBudget] + | cons state rest ih => + simp only [connectionTermsWithWork, List.map_cons, List.sum_cons, + distanceWithWork_value, nat_value, ih, rationalConnectionBudget] + +theorem connectionTermsWithWork_width {n : ℕ} (start finish : BinaryFraction) + (states : List (TargetInterval n)) (B : ℕ) + (hs : start.width ≤ B) (hf : finish.width ≤ B) + (he : ∀ state ∈ states, Nat.size state.lo + 2 ≤ B ∧ Nat.size state.hi + 2 ≤ B) : + ∀ a ∈ (connectionTermsWithWork start states finish).1, a.width ≤ 8 * B + 6 := by + induction states generalizing start with + | nil => + intro a ha + simp only [connectionTermsWithWork, List.mem_singleton] at ha + subst a + exact distanceWithWork_width start finish B hs hf + | cons state rest ih => + have hstate := he state List.mem_cons_self + intro a ha + simp only [connectionTermsWithWork, List.mem_cons] at ha + rcases ha with rfl | ha + · exact distanceWithWork_width start (nat state.lo) B hs + ((nat_width_le state.lo).trans hstate.1) + · exact ih (nat state.hi) ((nat_width_le state.hi).trans hstate.2) + (fun s h => he s (List.mem_cons_of_mem _ h)) a ha + + def connectionTermsBitBudget (k B : ℕ) : ℕ := + (k + 1) * (6000 * (B + 1) ^ 2 + 4) + k * (2 * B + 6) + +theorem connectionTermsWithWork_cost {n : ℕ} (start finish : BinaryFraction) + (states : List (TargetInterval n)) (B : ℕ) + (hs : start.width ≤ B) (hf : finish.width ≤ B) + (he : ∀ state ∈ states, Nat.size state.lo + 2 ≤ B ∧ Nat.size state.hi + 2 ≤ B) : + (connectionTermsWithWork start states finish).2 ≤ connectionTermsBitBudget states.length B := by + induction states generalizing start with + | nil => + have hc := distanceWithWork_cost start finish B hs hf + change (distanceWithWork start finish).2 + 2 ≤ _ + simpa only [connectionTermsBitBudget, List.length_nil, zero_add, one_mul, zero_mul, + add_zero] using Nat.add_le_add_right hc 2 + | cons state rest ih => + have hstate := he state List.mem_cons_self + have hc := distanceWithWork_cost start (nat state.lo) B hs + ((nat_width_le state.lo).trans hstate.1) + have ht := ih (nat state.hi) ((nat_width_le state.hi).trans hstate.2) + (fun s h => he s (List.mem_cons_of_mem _ h)) + change (distanceWithWork start (nat state.lo)).2 + + (connectionTermsWithWork (nat state.hi) rest finish).2 + Nat.size state.lo + + Nat.size state.hi + 6 ≤ _ + simp only [connectionTermsBitBudget, List.length_cons] at ht ⊢ + simp only [Nat.add_mul, Nat.one_mul] at ht ⊢ + omega + + + +@[simp] theorem connectionWithWork_value {n : ℕ} (start finish : BinaryFraction) + (states : List (TargetInterval n)) : + (connectionWithWork start finish states).1.value = + rationalConnectionBudget start.value states finish.value := by + simp only [connectionWithWork, sumListWithWork_value, connectionTermsWithWork_value] + +def connectionWordBudget (k B : ℕ) : ℕ := bandMassTotalStorageBudget (k + 1) (8 * B + 6) + +def connectionBitBudget (k B : ℕ) : ℕ := + connectionTermsBitBudget k B + storedSumBitBudget (k + 1) (8 * B + 6) + 6 * (k + 1) + 1 + +theorem connectionWithWork_width {n : ℕ} (start finish : BinaryFraction) + (states : List (TargetInterval n)) (B : ℕ) + (hs : start.width ≤ B) (hf : finish.width ≤ B) + (he : ∀ state ∈ states, Nat.size state.lo + 2 ≤ B ∧ Nat.size state.hi + 2 ≤ B) : + (connectionWithWork start finish states).1.width ≤ connectionWordBudget states.length B := by + have h := sumListWithWork_width (connectionTermsWithWork start states finish).1 + (8 * B + 6) (connectionTermsWithWork_width start finish states B hs hf he) + simpa only [connectionWithWork, connectionTermsWithWork_length, connectionWordBudget] using h + +theorem connectionWithWork_cost {n : ℕ} (start finish : BinaryFraction) + (states : List (TargetInterval n)) (B : ℕ) + (hs : start.width ≤ B) (hf : finish.width ≤ B) + (he : ∀ state ∈ states, Nat.size state.lo + 2 ≤ B ∧ Nat.size state.hi + 2 ≤ B) : + (connectionWithWork start finish states).2 ≤ connectionBitBudget states.length B := by + have ht := connectionTermsWithWork_cost start finish states B hs hf he + have hs' := sumListWithWork_cost (connectionTermsWithWork start states finish).1 + (8 * B + 6) (connectionTermsWithWork_width start finish states B hs hf he) + simp only [connectionTermsWithWork_length] at hs' + change _ + _ + 1 ≤ _ + unfold connectionBitBudget + omega + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryDivisionWork.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryDivisionWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..f0c67f624decdbdc2af86cd3839daabcbc9d9d2e --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryDivisionWork.lean @@ -0,0 +1,106 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinarySubtractWork +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Binary long division. A high-prefix quotient and remainder are extended +by one source bit, then compared with the positive divisor and reduced by +at most one ripple-borrow subtraction. -/ + +namespace EditApproximation + + + +theorem bitDivModWithWork_value (divisor bits : List Bool) (hd : 0 < bitWordValue divisor) : + bitWordValue bits = bitWordValue divisor * bitWordValue (bitDivModWithWork divisor bits).1 + + bitWordValue (bitDivModWithWork divisor bits).2.1 ∧ + bitWordValue (bitDivModWithWork divisor bits).2.1 < bitWordValue divisor := by + induction bits with + | nil => simp [bitDivModWithWork, bitWordValue, hd] + | cons bit bits ih => + let previous := bitDivModWithWork divisor bits + let candidate := bit :: previous.2.1 + have hp : bitWordValue bits = bitWordValue divisor * bitWordValue previous.1 + + bitWordValue previous.2.1 := ih.1 + have hr : bitWordValue previous.2.1 < bitWordValue divisor := ih.2 + have hc : bitWordValue candidate < 2 * bitWordValue divisor := by + dsimp only [candidate, bitWordValue] + cases bit <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega + by_cases hlt : (bitCompareWithWork candidate divisor).1 = .lt + · have hv := (bitCompareWithWork_lt candidate divisor).1 hlt + simp only [bitDivModWithWork, show (bitCompareWithWork (bit :: (bitDivModWithWork divisor bits).2.1) + divisor).1 = .lt from hlt, ↓reduceIte] + change bitWordValue (bit :: bits) = bitWordValue divisor * + bitWordValue (false :: previous.1) + bitWordValue candidate ∧ bitWordValue candidate < _ + constructor + · simp only [bitWordValue, Bool.toNat_false] + dsimp only [candidate, bitWordValue] + nlinarith only [hp] + · exact hv + · have hv : bitWordValue divisor ≤ bitWordValue candidate := by + exact Nat.le_of_not_gt (fun h => hlt ((bitCompareWithWork_lt candidate divisor).2 h)) + have hs := bitSubtractWithWork_sub candidate divisor hv + simp only [bitDivModWithWork, show (bitCompareWithWork (bit :: (bitDivModWithWork divisor bits).2.1) + divisor).1 ≠ .lt from hlt, ↓reduceIte] + change bitWordValue (bit :: bits) = bitWordValue divisor * bitWordValue (true :: previous.1) + + bitWordValue (bitSubtractWithWork candidate divisor false).1 ∧ + bitWordValue (bitSubtractWithWork candidate divisor false).1 < _ + rw [hs] + constructor + · simp only [bitWordValue, Bool.toNat_true] + have he := Nat.sub_add_cancel hv + dsimp only [candidate, bitWordValue] at he ⊢ + nlinarith only [hp, he] + · omega + +theorem bitDivModWithWork_lengths (divisor bits : List Bool) : + (bitDivModWithWork divisor bits).1.length = bits.length ∧ + (bitDivModWithWork divisor bits).2.1.length ≤ bits.length + divisor.length := by + induction bits with + | nil => simp [bitDivModWithWork] + | cons bit bits ih => + simp only [bitDivModWithWork] + split_ifs + · simp only [List.length_cons] + exact ⟨by omega, by omega⟩ + · have hs := bitSubtractWithWork_length (bit :: (bitDivModWithWork divisor bits).2.1) divisor false + simp only [List.length_cons] at hs ⊢ + exact ⟨by omega, by omega⟩ + +theorem bitDivModWithWork_cost (divisor bits : List Bool) : + (bitDivModWithWork divisor bits).2.2 ≤ + 30 * (bits.length + 1) * (bits.length + divisor.length + 1) := by + induction bits with + | nil => simp [bitDivModWithWork]; omega + | cons bit bits ih => + have hl := (bitDivModWithWork_lengths divisor bits).2 + have hc := bitCompareWithWork_cost (bit :: (bitDivModWithWork divisor bits).2.1) divisor + have hs := bitSubtractWithWork_cost (bit :: (bitDivModWithWork divisor bits).2.1) divisor false + simp only [List.length_cons] at hc hs + simp only [bitDivModWithWork, List.length_cons] + split_ifs <;> nlinarith only [ih, hl, hc, hs] + + + +theorem binaryNaturalDivModWithWork_spec (n d : ℕ) (hd : 0 < d) : + bitWordValue (binaryNaturalDivModWithWork n d).1 = n / d ∧ + bitWordValue (binaryNaturalDivModWithWork n d).2.1 = n % d := by + have h := bitDivModWithWork_value d.bits n.bits (by simpa only [bitWordValue_bits] using hd) + simp only [bitWordValue_bits] at h + have hmod : n % d = bitWordValue (bitDivModWithWork d.bits n.bits).2.1 := by + conv_lhs => rw [h.1] + simp only [Nat.add_mod, Nat.mul_mod_right, Nat.zero_add, Nat.mod_eq_of_lt h.2] + have hdiv : n / d = bitWordValue (bitDivModWithWork d.bits n.bits).1 := by + conv_lhs => rw [h.1] + rw [Nat.mul_add_div hd, Nat.div_eq_of_lt h.2, Nat.add_zero] + exact ⟨hdiv.symm, hmod.symm⟩ + +theorem binaryNaturalDivModWithWork_cost (n d : ℕ) : + (binaryNaturalDivModWithWork n d).2.2 ≤ + 30 * (Nat.size n + 1) * (Nat.size n + Nat.size d + 1) := by + simpa only [binaryNaturalDivModWithWork, Nat.size_eq_bits_len] using bitDivModWithWork_cost d.bits n.bits + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryDyadicCeiling.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryDyadicCeiling.lean new file mode 100644 index 0000000000000000000000000000000000000000..b1a651f661debbe6a1fc7d971f66261ac340abeb --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryDyadicCeiling.lean @@ -0,0 +1,179 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryBandInputs +import OAI.Combinatorics.EditApproximation.Geometry.BandEnvelopes +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! The dyadic envelope is found by a bounded sequence of exact Boolean +comparisons. The scan starts at `2⁻ᴮ`, doubles at most `2B` times, and uses +the stored fraction width `B`; no real logarithm is evaluated. -/ + +namespace EditApproximation + + + +theorem powerTwoWord_value (n : ℕ) : bitWordValue (powerTwoWord n) = 2 ^ n := by + induction n with + | zero => simp [powerTwoWord, bitWordValue] + | succ n ih => + simp only [powerTwoWord, List.replicate_succ, List.cons_append, bitWordValue, + Bool.toNat_false, zero_add] at * + rw [ih, pow_succ] + omega + +theorem powerTwoWord_length (n : ℕ) : (powerTwoWord n).length = n + 1 := by + simp [powerTwoWord] + +namespace BinaryFraction + + + +theorem inversePowerTwo_value (n : ℕ) : (inversePowerTwo n).value = (2 : ℚ) ^ (-(n : ℤ)) := by + simp only [inversePowerTwo, value, SignedBinary.value, signedMagnitude, Bool.false_eq_true, + ↓reduceIte, bitWordValue, Bool.toNat_true, + Int.cast_natCast, powerTwoWord_value, Nat.cast_pow, Nat.cast_ofNat, zpow_neg, zpow_natCast] + norm_num [one_div] + +theorem inversePowerTwo_width (n : ℕ) : (inversePowerTwo n).width = n + 1 := by + simp [inversePowerTwo, width, powerTwoWord_length] + + + +theorem doubleFraction_value (a : BinaryFraction) : (doubleFraction a).value = 2 * a.value := by + cases h : a.numerator.negative <;> + simp [doubleFraction, value, SignedBinary.value, signedMagnitude, h, bitWordValue] <;> ring + +theorem doubleFraction_width (a : BinaryFraction) : (doubleFraction a).width ≤ a.width + 1 := by + unfold doubleFraction width + simp only [List.length_cons] + omega + + + +private theorem dyadicCeiling_eq_of_bounds (r : ℚ) (e : ℤ) (hr : 0 < r) + (hlower : (2 : ℚ) ^ (e - 1) < r) (hupper : r ≤ (2 : ℚ) ^ e) : + rationalDyadicCeiling r = (2 : ℚ) ^ e := by + have hl := (Int.zpow_lt_iff_lt_clog (by decide : 1 < 2) hr).mp hlower + have hu := (Int.le_zpow_iff_clog_le (by decide : 1 < 2) hr).mp hupper + have he : Int.clog 2 r = e := by omega + rw [rationalDyadicCeiling, he] + +theorem dyadicScanWithWork_value (a candidate : BinaryFraction) (n : ℕ) (e : ℤ) + (ha : 0 < a.value) (hc : candidate.value = (2 : ℚ) ^ e) + (hlower : (2 : ℚ) ^ (e - 1) < a.value) + (hupper : a.value ≤ candidate.value * (2 : ℚ) ^ n) : + (dyadicScanWithWork a candidate n).1.value = rationalDyadicCeiling a.value := by + induction n generalizing candidate e with + | zero => + simp only [pow_zero, mul_one] at hupper + exact hc.trans (dyadicCeiling_eq_of_bounds a.value e ha hlower (hc ▸ hupper)).symm + | succ n ih => + unfold dyadicScanWithWork + dsimp only + split_ifs with hlt + · have hlt' := (ltWithWork_value candidate a).mp hlt + have hc' : (doubleFraction candidate).value = (2 : ℚ) ^ (e + 1) := by + rw [doubleFraction_value, hc, zpow_add₀ (by norm_num : (2 : ℚ) ≠ 0), zpow_one] + ring + apply ih _ (e + 1) hc' + · simpa only [add_sub_cancel_right, ← hc] using hlt' + · rw [doubleFraction_value] + simpa only [pow_succ, mul_comm, mul_left_comm, mul_assoc] using hupper + · have hupper' : a.value ≤ candidate.value := + le_of_not_gt (fun h => hlt ((ltWithWork_value candidate a).mpr h)) + exact hc.trans (dyadicCeiling_eq_of_bounds a.value e ha hlower (hc ▸ hupper')).symm + +theorem dyadicScanWithWork_width (a candidate : BinaryFraction) (n : ℕ) : + (dyadicScanWithWork a candidate n).1.width ≤ candidate.width + n := by + induction n generalizing candidate with + | zero => simp [dyadicScanWithWork] + | succ n ih => + unfold dyadicScanWithWork + dsimp only + split_ifs + · exact (ih _).trans (by have h := doubleFraction_width candidate; omega) + · change candidate.width ≤ candidate.width + (n + 1) + omega + +theorem dyadicScanWithWork_cost (a candidate : BinaryFraction) (n W : ℕ) + (ha : a.width ≤ W) (hc : candidate.width + n ≤ W) : + (dyadicScanWithWork a candidate n).2 ≤ 1 + n * (1000 * (W + 1) ^ 2 + 2) := by + induction n generalizing candidate with + | zero => simp [dyadicScanWithWork] + | succ n ih => + have hcmp := ltWithWork_cost candidate a W (by omega) ha + have hdouble := doubleFraction_width candidate + have hnext := ih (doubleFraction candidate) (by omega) + unfold dyadicScanWithWork + dsimp only + split_ifs + · rw [Nat.add_mul, Nat.one_mul] + omega + · have hp : 1000 * (W + 1) ^ 2 + 2 ≤ (n + 1) * (1000 * (W + 1) ^ 2 + 2) := + Nat.le_mul_of_pos_left _ (by omega) + omega + +theorem positive_value_lower (a : BinaryFraction) (ha : 0 < a.value) : + (2 : ℚ) ^ (-(a.width : ℤ)) ≤ a.value := by + have hd : (0 : ℚ) < bitWordValue a.denominator := by exact_mod_cast a.denominator_pos + have hn : (0 : ℚ) < a.numerator.value := (div_pos_iff_of_pos_right hd).mp ha + have hnum : (1 : ℚ) ≤ a.numerator.value := by + have hnZ : (0 : ℤ) < a.numerator.value := by exact_mod_cast hn + exact_mod_cast (show (1 : ℤ) ≤ a.numerator.value by omega) + have hden : (bitWordValue a.denominator : ℚ) ≤ (2 : ℚ) ^ a.width := by + exact_mod_cast (bitWordValue_lt_pow_length a.denominator).le.trans + (Nat.pow_le_pow_right (by decide) (le_max_right _ _)) + rw [zpow_neg, zpow_natCast, ← one_div] + change 1 / (2 : ℚ) ^ a.width ≤ (a.numerator.value : ℚ) / bitWordValue a.denominator + apply (div_le_div_iff₀ (pow_pos (by norm_num : (0 : ℚ) < 2) _) hd).mpr + simpa only [one_mul] using + hden.trans (le_mul_of_one_le_left (pow_nonneg (by norm_num) _) hnum) + + + +theorem dyadicCeilingWithWork_value (a : BinaryFraction) (ha : 0 < a.value) : + (dyadicCeilingWithWork a).1.value = rationalDyadicCeiling a.value := by + apply dyadicScanWithWork_value a (inversePowerTwo a.width) (2 * a.width) (-(a.width : ℤ)) ha + (inversePowerTwo_value _) + · have hpos : (0 : ℚ) < (2 : ℚ) ^ (-(a.width : ℤ) - 1) := zpow_pos (by norm_num) _ + have hdouble : (2 : ℚ) ^ (-(a.width : ℤ) - 1) * 2 = (2 : ℚ) ^ (-(a.width : ℤ)) := by + rw [← zpow_add_one₀ (by norm_num : (2 : ℚ) ≠ 0)] + congr 1 + omega + have hl := positive_value_lower a ha + nlinarith only [hpos, hdouble, hl] + · rw [inversePowerTwo_value, ← zpow_natCast] + rw [← zpow_add₀ (by norm_num : (2 : ℚ) ≠ 0)] + have he : -(a.width : ℤ) + (2 * a.width : ℕ) = (a.width : ℤ) := by omega + rw [he, zpow_natCast] + exact (le_abs_self _).trans (value_abs_le_pow_width a) + +theorem dyadicCeilingWithWork_width (a : BinaryFraction) : + (dyadicCeilingWithWork a).1.width ≤ 3 * a.width + 1 := by + have h := dyadicScanWithWork_width a (inversePowerTwo a.width) (2 * a.width) + rw [inversePowerTwo_width] at h + exact h.trans (by omega) + +theorem dyadicCeilingWithWork_cost (a : BinaryFraction) : + (dyadicCeilingWithWork a).2 ≤ + 1 + 2 * a.width * (1000 * (3 * a.width + 2) ^ 2 + 2) + 3 * a.width + 5 := by + have h := dyadicScanWithWork_cost a (inversePowerTwo a.width) (2 * a.width) (3 * a.width + 1) + (by omega) (by rw [inversePowerTwo_width]; omega) + rw [show 3 * a.width + 1 + 1 = 3 * a.width + 2 by omega] at h + exact Nat.add_le_add_right (Nat.add_le_add_right h (3 * a.width)) 5 + + +theorem dyadicCeilingWithWork_cost_le (a : BinaryFraction) (B : ℕ) (hB : a.width ≤ B) : + (dyadicCeilingWithWork a).2 ≤ + 1 + 2 * B * (1000 * (3 * B + 2) ^ 2 + 2) + 3 * B + 5 := by + have h := dyadicCeilingWithWork_cost a + have hs := Nat.pow_le_pow_left (show 3 * a.width + 2 ≤ 3 * B + 2 by omega) 2 + have hp := Nat.mul_le_mul (show 2 * a.width ≤ 2 * B by omega) + (show 1000 * (3 * a.width + 2) ^ 2 + 2 ≤ 1000 * (3 * B + 2) ^ 2 + 2 by omega) + omega + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryDyadicSampledGroups.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryDyadicSampledGroups.lean new file mode 100644 index 0000000000000000000000000000000000000000..33e3c39061f8dd2f750805a911d1210670bd9018 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryDyadicSampledGroups.lean @@ -0,0 +1,74 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinarySampledGroups +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! The generated binary scale list is reindexed into the finite +draw domain. Only proof transport is used: the accepted draw count is the +same natural computed by `groupSampleCountWithWork`. -/ + +namespace EditApproximation +namespace BinaryFraction + + + +@[simp] theorem indexedGroupScales_value (raw : List BinaryFraction) (M b : ℕ) (F : ℚ) + (h : raw.map value = groupDyadicScales M b F) + (i : Fin (groupDyadicScales M b F).length) : + (indexedGroupScales raw M b F h i).value = groupDyadicScaleAt M b F i := by + unfold indexedGroupScales groupDyadicScaleAt + simp only [List.get_eq_getElem] + rw [← List.getElem_map value (l := raw) (i := i.val) (h := by rw [h]; exact i.isLt)] + simp only [h] + +theorem unskippedEstimate_scale_transport {α : Type*} {source target : List α} {M T : ℕ} + {parent : TargetInterval source.length} {b P exponent Q : ℕ} {tau F : ℚ} + {child initial : Fin M → TargetInterval target.length → ℚ} + (left right : Fin T → ℚ) (h : left = right) + (current : Fin M → TargetInterval target.length → ℚ) + (member : UnskippedBand source target parent b P exponent tau F child initial) + (draw : ∀ t, Fin (groupSampleCount M Q b (right t)) → Fin M) : + unskippedGroupEstimate left (fun t => groupSampleCount M Q b (left t)) current member + (fun t j => draw t (Fin.cast (congrArg (groupSampleCount M Q b) (congrFun h t)) j)) = + unskippedGroupEstimate right (fun t => groupSampleCount M Q b (right t)) current member draw := by + cases h + rfl + +section Physical +variable {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (b P exponent Q : ℕ) + (tau F : BinaryFraction) + (child initial current : Fin M → TargetInterval target.length → BinaryFraction) + (raw : List BinaryFraction) (hraw : raw.map value = groupDyadicScales M b F.value) + (draw : ∀ t : Fin (groupDyadicScales M b F.value).length, + Fin (groupSampleCount M Q b (groupDyadicScaleAt M b F.value t)) → Fin M) + +local notation "Member" => UnskippedBand source target parent b P exponent + (BinaryFraction.value tau) (BinaryFraction.value F) + (fun i q => BinaryFraction.value (child i q)) (fun i q => BinaryFraction.value (initial i q)) + +def dyadicSampledGroupActionWithWork (members : List Member) (hne : members ≠ []) := + sampledGroupActionWithWork source target parent b P exponent Q tau F child initial current + (indexedGroupScales raw M b F.value hraw) + (fun t j => draw t (Fin.cast (congrArg (groupSampleCount M Q b) + (indexedGroupScales_value raw M b F.value hraw t)) j)) members hne + +theorem dyadicSampledGroupActionWithWork_value (members : List Member) (hne : members ≠ []) + (hb : 0 < b) : + (dyadicSampledGroupActionWithWork source target parent b P exponent Q tau F child initial current + raw hraw draw members hne).1.decode = + (chooseUnskippedGroup Q (fun i q => (current i q).value) members hne draw).rationalAction := by + unfold dyadicSampledGroupActionWithWork + rw [sampledGroupActionWithWork_value source target parent b P exponent Q hb] + unfold chooseUnskippedGroup dyadicUnskippedGroupEstimate + congr 2 + funext member + exact unskippedEstimate_scale_transport _ _ + (funext (indexedGroupScales_value raw M b F.value hraw)) _ member draw + +end Physical +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryEnvelopeReads.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryEnvelopeReads.lean new file mode 100644 index 0000000000000000000000000000000000000000..be41b3528625b7dad5bcf8d4cfdabe437cbf476b --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryEnvelopeReads.lean @@ -0,0 +1,65 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryActualBandOptimizer +import OAI.Combinatorics.EditApproximation.Binary.BinaryReadComposition +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! The dyadic child envelope explicitly gathers its initial-value +words before taking the maximum. -/ + +namespace EditApproximation + +theorem vectorMapWithWork_extra {α : Type*} (d : ℕ) (read plain : Fin d → α × ℕ) (C : ℕ) + (hv : ∀ i, (read i).1 = (plain i).1) (hc : ∀ i, (read i).2 ≤ (plain i).2 + C) : + (vectorMapWithWork d read).1 = (vectorMapWithWork d plain).1 ∧ + (vectorMapWithWork d read).2 ≤ (vectorMapWithWork d plain).2 + d * C := by + constructor + · apply Vector.ext + intro i hi + change (vectorMapWithWork d read).1.get ⟨i, hi⟩ = (vectorMapWithWork d plain).1.get ⟨i, hi⟩ + rw [vectorMapWithWork_value, vectorMapWithWork_value] + exact hv _ + · simp only [vectorMapWithWork, Vector.toList_map, Vector.toList_ofFn, + List.map_ofFn, Function.comp_def, List.sum_ofFn] + have h := Finset.sum_le_sum (s := Finset.univ) (fun i _ => hc i) + simp only [Finset.sum_add_distrib, Finset.sum_const, Finset.card_univ, Fintype.card_fin, + smul_eq_mul] at h + exact (Nat.add_le_add_right h (6 * d)).trans_eq (Nat.add_right_comm _ _ _) + +namespace BinaryFraction + + + +theorem bandEnvelopeReadWithWork_eq {M n : ℕ} (b : ℕ) (band : List (Fin M → TargetInterval n)) + (read : Fin M → TargetInterval n → BinaryFraction × ℕ) (i : Fin M) : + (bandEnvelopeReadWithWork b band read i).1 = + (bandEnvelopeWithWork b band (fun j q => (read j q).1) i).1 := by + simp only [bandEnvelopeReadWithWork, bandEnvelopeWithWork, arithmeticMapWithWork_value] + +theorem bandEnvelopeReadWithWork_cost {M n : ℕ} (b : ℕ) (band : List (Fin M → TargetInterval n)) + (read : Fin M → TargetInterval n → BinaryFraction × ℕ) (i : Fin M) (R : ℕ) + (hr : ∀ action ∈ band, (read i (action i)).2 ≤ R) : + (bandEnvelopeReadWithWork b band read i).2 ≤ + (bandEnvelopeWithWork b band (fun j q => (read j q).1) i).2 + band.length * (R + 3) := by + have h := arithmeticMapWithWork_cost (fun action => read i (action i)) band R hr + simp only [bandEnvelopeReadWithWork, bandEnvelopeWithWork, arithmeticMapWithWork_value] + omega + + + +theorem envelopeVectorReadWithWork_eq_cost {M n : ℕ} (b : ℕ) + (band : List (Fin M → TargetInterval n)) (read : Fin M → TargetInterval n → BinaryFraction × ℕ) + (R : ℕ) (hr : ∀ i q, (read i q).2 ≤ R) : + (envelopeVectorReadWithWork b band read).1 = + (envelopeVectorWithWork b band (fun i q => (read i q).1)).1 ∧ + (envelopeVectorReadWithWork b band read).2 ≤ + (envelopeVectorWithWork b band (fun i q => (read i q).1)).2 + M * (band.length * (R + 3)) := by + exact vectorMapWithWork_extra M _ _ _ + (bandEnvelopeReadWithWork_eq b band read) + (fun i => bandEnvelopeReadWithWork_cost b band read i R (fun _ _ => hr i _)) + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryEnvelopeSpace.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryEnvelopeSpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..6936949a6ec0924b718850581d9a83b47451ef2d --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryEnvelopeSpace.lean @@ -0,0 +1,137 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryReductionSpace +import OAI.Combinatorics.EditApproximation.Binary.BinaryOptimizerSpace +import OAI.Combinatorics.EditApproximation.Binary.BinaryEnvelopeReads +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Scratch replay for the bounded dyadic scan and the actual band +initial-value reads used to form each child envelope. -/ + +namespace EditApproximation.BinaryFraction + + + +theorem dyadicScanAllocation_le_work (a candidate : BinaryFraction) (n : ℕ) : + dyadicScanAllocation a candidate n ≤ (dyadicScanWithWork a candidate n).2 := by + induction n generalizing candidate with + | zero => simp only [dyadicScanAllocation, dyadicScanWithWork]; exact Nat.zero_le _ + | succ n ih => + have hc := ltAllocation_le_work candidate a + have ht := ih (doubleFraction candidate) + unfold dyadicScanAllocation dyadicScanWithWork + dsimp only + split_ifs <;> dsimp only + · exact (Nat.add_assoc _ _ _).symm.le.trans + (Nat.add_le_add (Nat.add_le_add hc ht) (by decide : 1 ≤ 2)) + · exact Nat.add_le_add hc (Nat.zero_le 1) + + + +theorem dyadicCeilingAllocation_le_work (a : BinaryFraction) : + dyadicCeilingAllocation a ≤ (dyadicCeilingWithWork a).2 := by + have h := dyadicScanAllocation_le_work a (inversePowerTwo a.width) (2 * a.width) + unfold dyadicCeilingAllocation dyadicCeilingWithWork + dsimp only + omega + + + +theorem bandEnvelopeReadAllocation_le_work {M n : ℕ} (b : ℕ) (band : List (Fin M → TargetInterval n)) + (read : Fin M → TargetInterval n → BinaryFraction × ℕ) + (footprint : Fin M → TargetInterval n → ℕ) (i : Fin M) + (h : ∀ action ∈ band, footprint i (action i) ≤ (read i (action i)).2) : + bandEnvelopeReadAllocation b band read footprint i ≤ (bandEnvelopeReadWithWork b band read i).2 := by + have hv := arithmeticMapAllocation_le_work (fun action => read i (action i)) + (fun action => footprint i (action i)) band h + let values := (arithmeticMapWithWork (fun action => read i (action i)) band).1 + have hd := divAllocation_le_work (nat b) (nat M) + have hm := maximumAllocation_le_work zero values + have hx := maxAllocation_le_work (divWithWork (nat b) (nat M)).1 (maximumWithWork zero values).1 + have he := dyadicCeilingAllocation_le_work + (maxWithWork (divWithWork (nat b) (nat M)).1 (maximumWithWork zero values).1).1 + unfold bandEnvelopeReadAllocation bandEnvelopeReadWithWork + dsimp only + dsimp only [values] at hm hx he + omega + + + +theorem envelopeVectorReadAllocation_le_work {M n : ℕ} (b : ℕ) (band : List (Fin M → TargetInterval n)) + (read : Fin M → TargetInterval n → BinaryFraction × ℕ) + (footprint : Fin M → TargetInterval n → ℕ) + (h : ∀ i action, action ∈ band → footprint i (action i) ≤ (read i (action i)).2) : + envelopeVectorReadAllocation b band read footprint ≤ (envelopeVectorReadWithWork b band read).2 := by + exact vectorMapAllocation_le_work M _ _ (fun i => bandEnvelopeReadAllocation_le_work b band read footprint i (h i)) + +def dyadicScanInvocations (a candidate : BinaryFraction) : ℕ → ℕ + | 0 => 1 + | n + 1 => + compareInvocations candidate a + if (candidate.ltWithWork a).1 then + dyadicScanInvocations a (doubleFraction candidate) n + 1 else 1 + +theorem dyadicScanInvocations_le_work (a candidate : BinaryFraction) (n : ℕ) : + dyadicScanInvocations a candidate n ≤ (dyadicScanWithWork a candidate n).2 := by + induction n generalizing candidate with + | zero => simp only [dyadicScanInvocations, dyadicScanWithWork]; omega + | succ n ih => + have hc := compareInvocations_le_work candidate a + have ht := ih (doubleFraction candidate) + unfold dyadicScanInvocations dyadicScanWithWork + dsimp only + split_ifs <;> dsimp only <;> omega + +def dyadicCeilingInvocations (a : BinaryFraction) : ℕ := + dyadicScanInvocations a (inversePowerTwo a.width) (2 * a.width) + a.width + 2 + +theorem dyadicCeilingInvocations_le_work (a : BinaryFraction) : + dyadicCeilingInvocations a ≤ (dyadicCeilingWithWork a).2 := by + have h := dyadicScanInvocations_le_work a (inversePowerTwo a.width) (2 * a.width) + unfold dyadicCeilingInvocations dyadicCeilingWithWork + dsimp only + omega + +def bandEnvelopeReadInvocations {M n : ℕ} (b : ℕ) (band : List (Fin M → TargetInterval n)) + (read : Fin M → TargetInterval n → BinaryFraction × ℕ) + (footprint : Fin M → TargetInterval n → ℕ) (i : Fin M) : ℕ := + let values := (arithmeticMapWithWork (fun action => read i (action i)) band).1 + let floor := (divWithWork (nat b) (nat M)).1 + let maximum := (maximumWithWork zero values).1 + arithmeticMapInvocations (fun action => footprint i (action i)) band + + divInvocations (nat b) (nat M) + maximumInvocations zero values + maxInvocations floor maximum + + dyadicCeilingInvocations (maxWithWork floor maximum).1 + 1 + +theorem bandEnvelopeReadInvocations_le_work {M n : ℕ} (b : ℕ) (band : List (Fin M → TargetInterval n)) + (read : Fin M → TargetInterval n → BinaryFraction × ℕ) + (footprint : Fin M → TargetInterval n → ℕ) (i : Fin M) + (h : ∀ action ∈ band, footprint i (action i) ≤ (read i (action i)).2) : + bandEnvelopeReadInvocations b band read footprint i ≤ (bandEnvelopeReadWithWork b band read i).2 := by + have hv := arithmeticMapInvocations_le_work (fun action => read i (action i)) + (fun action => footprint i (action i)) band h + let values := (arithmeticMapWithWork (fun action => read i (action i)) band).1 + have hd := divInvocations_le_work (nat b) (nat M) + have hm := maximumInvocations_le_work zero values + have hx := maxInvocations_le_work (divWithWork (nat b) (nat M)).1 (maximumWithWork zero values).1 + have he := dyadicCeilingInvocations_le_work + (maxWithWork (divWithWork (nat b) (nat M)).1 (maximumWithWork zero values).1).1 + unfold bandEnvelopeReadInvocations bandEnvelopeReadWithWork + dsimp only + dsimp only [values] at hm hx he + omega + +def envelopeVectorReadInvocations {M n : ℕ} (b : ℕ) (band : List (Fin M → TargetInterval n)) + (read : Fin M → TargetInterval n → BinaryFraction × ℕ) + (footprint : Fin M → TargetInterval n → ℕ) : ℕ := + vectorMapInvocations M (bandEnvelopeReadInvocations b band read footprint) + +theorem envelopeVectorReadInvocations_le_work_add_one {M n : ℕ} (b : ℕ) (band : List (Fin M → TargetInterval n)) + (read : Fin M → TargetInterval n → BinaryFraction × ℕ) + (footprint : Fin M → TargetInterval n → ℕ) + (h : ∀ i action, action ∈ band → footprint i (action i) ≤ (read i (action i)).2) : + envelopeVectorReadInvocations b band read footprint ≤ (envelopeVectorReadWithWork b band read).2 + 1 := by + exact vectorMapInvocations_le_work_add_one M _ _ (fun i => bandEnvelopeReadInvocations_le_work b band read footprint i (h i)) + +end EditApproximation.BinaryFraction + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryFinalAnswer.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryFinalAnswer.lean new file mode 100644 index 0000000000000000000000000000000000000000..31caec2d28051ff7ec059dcdb89f2d2bdd94a3f3 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryFinalAnswer.lean @@ -0,0 +1,54 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryCellGrid +import OAI.Combinatorics.EditApproximation.Binary.BinaryMedianKernel +import OAI.Combinatorics.EditApproximation.Geometry.Accuracy +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation +namespace BinaryFraction + +/-- Clamp the final value to the input length and round down by binary division. -/ + + +theorem finalAnswerWithWork_value (N : ℕ) (a : BinaryFraction) : + bitWordValue (finalAnswerWithWork N a).1 = integerAnswer N (a.value : ℝ) := by + have hfloor : ⌊(a.value : ℝ)⌋₊ = ⌊a.value⌋₊ := by + apply Nat.floor_congr + intro n + norm_cast + simp only [finalAnswerWithWork, wordMinWithWork_value, bitWordValue_bits, naturalFloorWithWork_value] + rw [← hfloor] + unfold integerAnswer + by_cases hn : a.value ≤ 0 + · have hnR : (a.value : ℝ) ≤ 0 := by exact_mod_cast hn + rw [Nat.floor_of_nonpos hnR, min_eq_right (Nat.zero_le N)] + have hm : min (N : ℝ) (a.value : ℝ) ≤ 0 := (min_le_right _ _).trans hnR + rw [max_eq_left hm, Nat.floor_zero] + · have hnR : 0 ≤ (a.value : ℝ) := by exact_mod_cast (le_of_not_ge hn) + have hm : 0 ≤ min (N : ℝ) (a.value : ℝ) := le_min (Nat.cast_nonneg _) hnR + rw [max_eq_right hm] + by_cases hN : (a.value : ℝ) ≤ N + · have hf : ⌊(a.value : ℝ)⌋₊ ≤ N := by + simpa only [Nat.floor_natCast] using Nat.floor_mono hN + rw [min_eq_right hN, min_eq_right hf] + · have hf : N ≤ ⌊(a.value : ℝ)⌋₊ := Nat.le_floor (le_of_not_ge hN) + rw [min_eq_left (le_of_not_ge hN), Nat.floor_natCast, min_eq_left hf] + +theorem finalAnswerWithWork_cost (N : ℕ) (a : BinaryFraction) : + (finalAnswerWithWork N a).2 ≤ 400 * (a.width + Nat.size N + 1) ^ 2 := by + have hf := (naturalFloorWithWork_bounds a).2 + have hl := (naturalFloorWithWork_bounds a).1 + have hc := wordLEWithWork_cost N.bits (naturalFloorWithWork a).1 + rw [Nat.size_eq_bits_len] at hc + have hpoly := Nat.pow_le_pow_left (show a.width + 1 ≤ a.width + Nat.size N + 1 by omega) 2 + unfold finalAnswerWithWork wordMinWithWork + dsimp only + nlinarith only [hf, hl, hc, hpoly, Nat.zero_le a.width, Nat.zero_le (Nat.size N), + sq_nonneg (a.width + Nat.size N)] + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryFinalSpace.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryFinalSpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..1fb1ae42bcecefbfbb3d06781971a358691bbef7 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryFinalSpace.lean @@ -0,0 +1,22 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryFinalAnswer +import OAI.Combinatorics.EditApproximation.Binary.BinaryInitialGuardSpace +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation.BinaryFraction + + + +theorem finalAnswerAllocation_le_work (N : ℕ) (a : BinaryFraction) : + finalAnswerAllocation N a ≤ (finalAnswerWithWork N a).2 := by + have hf := naturalFloorAllocation_le_work a + have hm := naturalWordLEAllocation_le_work N.bits (naturalFloorWithWork a).1 + unfold finalAnswerAllocation finalAnswerWithWork wordMinWithWork + dsimp only + omega + +end EditApproximation.BinaryFraction + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryFiniteLoops.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryFiniteLoops.lean new file mode 100644 index 0000000000000000000000000000000000000000..1c436c2382156837874b0a9dca22337701cfa1db --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryFiniteLoops.lean @@ -0,0 +1,161 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryBandEnvelope +import OAI.Combinatorics.EditApproximation.Binary.BinaryBandInputWork +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Executed finite filters and stored fraction reductions used by the +band tests. Callback costs and list construction are included. -/ + +namespace EditApproximation + + + +theorem filterWithWork_value {α : Type*} (test : α → Bool × ℕ) (values : List α) : + (filterWithWork test values).1 = values.filter (fun a => (test a).1) := by + induction values with + | nil => rfl + | cons a rest ih => + simp only [filterWithWork, List.filter_cons, ih] + +theorem filterWithWork_cost {α : Type*} (test : α → Bool × ℕ) (values : List α) + (C : ℕ) (hC : ∀ a ∈ values, (test a).2 ≤ C) : + (filterWithWork test values).2 ≤ values.length * (C + 3) := by + induction values with + | nil => simp [filterWithWork] + | cons a rest ih => + have ha := hC a List.mem_cons_self + have ht := ih (fun b hb => hC b (List.mem_cons_of_mem _ hb)) + change (test a).2 + (filterWithWork test rest).2 + 3 ≤ _ + simp only [List.length_cons] + rw [Nat.add_mul, Nat.one_mul] + omega + +/-- Both branch values are visited; this makes the work count independent +of the outcome while returning the usual finite conjunction. -/ + + +theorem allWithWork_value {α : Type*} (test : α → Bool × ℕ) (values : List α) : + (allWithWork test values).1 = true ↔ ∀ a ∈ values, (test a).1 = true := by + induction values with + | nil => simp [allWithWork] + | cons a rest ih => simp only [allWithWork, Bool.and_eq_true, ih, List.forall_mem_cons] + +theorem allWithWork_cost {α : Type*} (test : α → Bool × ℕ) (values : List α) + (C : ℕ) (hC : ∀ a ∈ values, (test a).2 ≤ C) : + (allWithWork test values).2 ≤ values.length * (C + 3) := by + induction values with + | nil => simp [allWithWork] + | cons a rest ih => + have ha := hC a List.mem_cons_self + have ht := ih (fun b hb => hC b (List.mem_cons_of_mem _ hb)) + change (test a).2 + (allWithWork test rest).2 + 3 ≤ _ + simp only [List.length_cons] + rw [Nat.add_mul, Nat.one_mul] + omega + +namespace BinaryFraction + + + +theorem leWithWork_value (a b : BinaryFraction) : + (a.leWithWork b).1 = true ↔ a.value ≤ b.value := by + simp only [leWithWork, Bool.not_eq_true_eq_eq_false] + rw [Bool.eq_false_iff] + constructor + · intro h + exact le_of_not_gt (fun hlt => h ((ltWithWork_value b a).mpr hlt)) + · intro h hlt + exact (not_lt_of_ge h) ((ltWithWork_value b a).mp hlt) + +theorem leWithWork_cost (a b : BinaryFraction) (B : ℕ) (ha : a.width ≤ B) (hb : b.width ≤ B) : + (a.leWithWork b).2 ≤ 1000 * (B + 1) ^ 2 + 1 := + Nat.add_le_add_right (ltWithWork_cost b a B hb ha) 1 + + + + +theorem minWithWork_value (a b : BinaryFraction) : + (minWithWork a b).1.value = min a.value b.value := by + by_cases h : a.value < b.value + · simp only [minWithWork, (ltWithWork_value a b).mpr h, ↓reduceIte, min_eq_left h.le] + · have hb : (a.ltWithWork b).1 = false := + Bool.eq_false_iff.mpr (fun hh => h ((ltWithWork_value a b).mp hh)) + simp only [minWithWork, hb, Bool.false_eq_true, ↓reduceIte, min_eq_right (le_of_not_gt h)] + +theorem minWithWork_width (a b : BinaryFraction) : + (minWithWork a b).1.width ≤ max a.width b.width := by + unfold minWithWork + dsimp only + split_ifs + · exact le_max_left _ _ + · exact le_max_right _ _ + +theorem minWithWork_cost (a b : BinaryFraction) (B : ℕ) (ha : a.width ≤ B) (hb : b.width ≤ B) : + (minWithWork a b).2 ≤ 1000 * (B + 1) ^ 2 + 1 := + Nat.add_le_add_right (ltWithWork_cost a b B ha hb) 1 + + + +theorem minimumWithWork_value (fallback : BinaryFraction) (values : List BinaryFraction) : + (minimumWithWork fallback values).1.value = rationalMinimum fallback.value (values.map value) := by + induction values with + | nil => rfl + | cons head rest ih => + simp only [minimumWithWork, minWithWork_value, ih, List.map_cons, rationalMinimum] + +theorem minimumWithWork_width (fallback : BinaryFraction) (values : List BinaryFraction) + (B : ℕ) (hf : fallback.width ≤ B) (hvalues : ∀ a ∈ values, a.width ≤ B) : + (minimumWithWork fallback values).1.width ≤ B := by + induction values with + | nil => exact hf + | cons head rest ih => + exact (minWithWork_width head (minimumWithWork fallback rest).1).trans + (max_le (hvalues head List.mem_cons_self) (ih (fun a ha => hvalues a (List.mem_cons_of_mem _ ha)))) + +theorem minimumWithWork_cost (fallback : BinaryFraction) (values : List BinaryFraction) + (B : ℕ) (hf : fallback.width ≤ B) (hvalues : ∀ a ∈ values, a.width ≤ B) : + (minimumWithWork fallback values).2 ≤ 1 + values.length * (1000 * (B + 1) ^ 2 + 2) := by + induction values with + | nil => simp [minimumWithWork] + | cons head rest ih => + have htail := ih (fun a ha => hvalues a (List.mem_cons_of_mem _ ha)) + have hw := minimumWithWork_width fallback rest B hf (fun a ha => hvalues a (List.mem_cons_of_mem _ ha)) + have hc := minWithWork_cost head (minimumWithWork fallback rest).1 B + (hvalues head List.mem_cons_self) hw + change (minimumWithWork fallback rest).2 + (minWithWork head (minimumWithWork fallback rest).1).2 + 1 ≤ _ + simp only [List.length_cons] + rw [Nat.add_mul, Nat.one_mul] + omega + + + +theorem sumListWithWork_value (values : List BinaryFraction) : + (sumListWithWork values).1.value = (values.map value).sum := by + rw [sumListWithWork, bandMassTotalWithWork_value] + simp only [vector_get_ofFn] + rw [← List.sum_ofFn, List.ofFn_comp', List.ofFn_get] + +theorem sumListWithWork_width (values : List BinaryFraction) (B : ℕ) + (hB : ∀ a ∈ values, a.width ≤ B) : + (sumListWithWork values).1.width ≤ bandMassTotalStorageBudget values.length B := by + exact (dotListWithWork_width_le_storageBits (Vector.ofFn values.get) + (Vector.replicate values.length one) (List.finRange values.length)).trans + (bandMassTotalWithWork_storage (Vector.ofFn values.get) B (by + intro i + rw [vector_get_ofFn] + exact hB _ (List.get_mem _ _))) + +theorem sumListWithWork_cost (values : List BinaryFraction) (B : ℕ) + (hB : ∀ a ∈ values, a.width ≤ B) : + (sumListWithWork values).2 ≤ storedSumBitBudget values.length B + 6 * values.length := by + exact Nat.add_le_add_right (bandMassTotalWithWork_cost (Vector.ofFn values.get) B (by + intro i + rw [vector_get_ofFn] + exact hB _ (List.get_mem _ _))) _ + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryFixedDenominator.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryFixedDenominator.lean new file mode 100644 index 0000000000000000000000000000000000000000..7e49e2b5422a1eaade91e64b1124b6c625abdb64 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryFixedDenominator.lean @@ -0,0 +1,136 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryDivisionWork +import OAI.Combinatorics.EditApproximation.Binary.BinaryRawCost +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Exact cache-value compression to a prescribed denominator. It performs +one Boolean multiplication and one Boolean long division, followed only by +leading-zero removal. No rational gcd or reduced-rational conversion is used. -/ + +namespace EditApproximation +namespace BinaryFraction + +theorem raw_den_dvd_scaled_num (a : BinaryFraction) (D : ℕ) (hD : a.value.den ∣ D) : + bitWordValue a.denominator ∣ bitWordValue a.numerator.bits * D := by + have hd : (a.representation.den : ℤ) ≠ 0 := by exact_mod_cast a.representation.den_pos.ne' + obtain ⟨c, hn, hd'⟩ := Rat.num_den_mk (q := a.value) (n := a.representation.num) + (d := (a.representation.den : ℤ)) hd (by + rw [Rat.divInt_eq_div, Int.cast_natCast] + exact (representation_value a).symm) + obtain ⟨k, hk⟩ := hD + have hi : (a.representation.den : ℤ) ∣ a.representation.num * (D : ℤ) := by + refine ⟨a.value.num * k, ?_⟩ + rw [hn, hd', hk, Nat.cast_mul] + ring + have habs := Int.natCast_dvd_natCast.mp (Int.dvd_natAbs.mpr hi) + have hnum : a.representation.num.natAbs = bitWordValue a.numerator.bits := by + cases h : a.numerator.negative <;> simp [representation, SignedBinary.value, signedMagnitude, h] + change bitWordValue a.denominator ∣ (a.representation.num * (D : ℤ)).natAbs at habs + simpa only [Int.natAbs_mul, Int.natAbs_natCast, hnum] using habs + + + +theorem fixedDenominatorWithWork_value (a : BinaryFraction) (denominator : List Bool) + (hden : 0 < bitWordValue denominator) (hD : a.value.den ∣ bitWordValue denominator) : + (fixedDenominatorWithWork a denominator hden).1.value = a.value := by + let product := bitMulWithWork a.numerator.bits denominator + let quotient := bitDivModWithWork a.denominator product.1 + have hdvd := raw_den_dvd_scaled_num a (bitWordValue denominator) hD + have h := bitDivModWithWork_value a.denominator product.1 a.denominator_pos + have hm : bitWordValue product.1 = bitWordValue a.numerator.bits * bitWordValue denominator := + bitMulWithWork_value _ _ + have hmod : bitWordValue quotient.2.1 = 0 := by + have hz : bitWordValue product.1 % bitWordValue a.denominator = 0 := by + rw [hm] + exact Nat.mod_eq_zero_of_dvd hdvd + rw [h.1, Nat.add_mod, Nat.mul_mod_right, Nat.zero_add] at hz + simp only [Nat.mod_mod] at hz + exact (Nat.mod_eq_of_lt h.2).symm.trans hz + have hq : bitWordValue a.denominator * bitWordValue quotient.1 = + bitWordValue a.numerator.bits * bitWordValue denominator := by + have heq := h.1 + change bitWordValue product.1 = bitWordValue a.denominator * bitWordValue quotient.1 + bitWordValue quotient.2.1 at heq + rw [hmod, Nat.add_zero] at heq + exact heq.symm.trans hm + let raw : BinaryFraction := ⟨⟨a.numerator.negative, quotient.1⟩, denominator, hden⟩ + have hc : (canonicalizeWithWork raw).1.value = raw.value := by + rw [← representation_value, canonicalizeWithWork_representation, representation_value] + change (canonicalizeWithWork raw).1.value = a.value + rw [hc] + have hdQ : (bitWordValue a.denominator : ℚ) ≠ 0 := by exact_mod_cast a.denominator_pos.ne' + have hDQ : (bitWordValue denominator : ℚ) ≠ 0 := by exact_mod_cast hden.ne' + have hqQ : (bitWordValue a.denominator : ℚ) * bitWordValue quotient.1 = + (bitWordValue a.numerator.bits : ℚ) * bitWordValue denominator := by exact_mod_cast hq + cases hs : a.numerator.negative <;> + simp only [raw, value, SignedBinary.value, signedMagnitude, hs, Bool.false_eq_true, + ↓reduceIte, Int.cast_natCast, Int.cast_neg] <;> + apply (div_eq_div_iff hDQ hdQ).mpr <;> nlinarith only [hqQ] + +theorem fixedDenominatorWithWork_den (a : BinaryFraction) (denominator : List Bool) + (hden : 0 < bitWordValue denominator) : + (fixedDenominatorWithWork a denominator hden).1.representation.den = bitWordValue denominator := by + unfold fixedDenominatorWithWork + dsimp only + rw [canonicalizeWithWork_representation] + rfl + +theorem fixedDenominatorWithWork_width (a : BinaryFraction) (denominator : List Bool) + (hden : 0 < bitWordValue denominator) (hD : a.value.den ∣ bitWordValue denominator) + (V B : ℕ) (hv : |a.value| ≤ V) (hB : denominator.length ≤ B) : + (fixedDenominatorWithWork a denominator hden).1.width ≤ Nat.size V + 2 * B + 1 := by + let answer := (fixedDenominatorWithWork a denominator hden).1 + have hvalue : |answer.representation.value| ≤ V := by + rw [representation_value] + change |(fixedDenominatorWithWork a denominator hden).1.value| ≤ V + rw [fixedDenominatorWithWork_value a denominator hden hD] + exact hv + have hbits : Nat.size answer.representation.den ≤ B := by + rw [fixedDenominatorWithWork_den] + exact (Nat.size_le.mpr (bitWordValue_lt_pow_length denominator)).trans hB + have hstorage := UnreducedRational.storageBits_le answer.representation V B hvalue hbits + have hwidth : answer.width ≤ answer.representation.storageBits := by + unfold answer fixedDenominatorWithWork + dsimp only + rw [canonicalizeWithWork_width, canonicalizeWithWork_representation] + unfold UnreducedRational.storageBits + omega + exact hwidth.trans hstorage + +theorem fixedDenominatorWithWork_cost (a : BinaryFraction) (denominator : List Bool) + (hden : 0 < bitWordValue denominator) (A B : ℕ) + (ha : a.width ≤ A) (hB : denominator.length ≤ B) : + (fixedDenominatorWithWork a denominator hden).2 ≤ 5000 * (A + B + 2) ^ 2 := by + let product := bitMulWithWork a.numerator.bits denominator + let quotient := bitDivModWithWork a.denominator product.1 + let raw : BinaryFraction := ⟨⟨a.numerator.negative, quotient.1⟩, denominator, hden⟩ + have hn : a.numerator.bits.length ≤ A := (le_max_left _ _).trans ha + have hd : a.denominator.length ≤ A := (le_max_right _ _).trans ha + have hp := bitMulWithWork_cost a.numerator.bits denominator + have hpl := bitMulWithWork_length a.numerator.bits denominator + have hq := bitDivModWithWork_cost a.denominator product.1 + have hql := (bitDivModWithWork_lengths a.denominator product.1).1 + change product.1.length ≤ 2 * a.numerator.bits.length + denominator.length + 1 at hpl + change quotient.1.length = product.1.length at hql + have hraw : raw.width ≤ 2 * A + B + 1 := by + change max quotient.1.length denominator.length ≤ _ + exact max_le (by omega) (by omega) + have hc := canonicalizeWithWork_cost raw + change product.2 + quotient.2.2 + (canonicalizeWithWork raw).2 + 4 ≤ _ + have hprod : product.2 ≤ 20 * (A + B + 2) ^ 2 := by + apply hp.trans + have h1 : a.numerator.bits.length + 1 ≤ A + B + 2 := by omega + have h2 : a.numerator.bits.length + denominator.length + 1 ≤ A + B + 2 := by omega + nlinarith only [Nat.mul_le_mul h1 h2] + have hquot : quotient.2.2 ≤ 30 * (3 * (A + B + 2)) * (4 * (A + B + 2)) := by + apply hq.trans + have h1 : product.1.length + 1 ≤ 3 * (A + B + 2) := by omega + have h2 : product.1.length + a.denominator.length + 1 ≤ 4 * (A + B + 2) := by omega + nlinarith only [Nat.mul_le_mul h1 h2] + nlinarith only [hprod, hquot, hc, hraw, Nat.zero_le A, Nat.zero_le B] + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryFractionWork.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryFractionWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..4f01b52344ad25746e93a260dad95d1e8b1c30ef --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryFractionWork.lean @@ -0,0 +1,209 @@ +import OAI.Combinatorics.EditApproximation.Binary.UnreducedRational +import OAI.Combinatorics.EditApproximation.Binary.SignedBinaryOrderWork +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Unreduced fractions stored as Boolean words. Every numerator operation +below runs the literal signed ripple/shift-add code; denominator products +run the literal Boolean multiplication routine. -/ + +namespace EditApproximation + + + +namespace BinaryFraction + + + + + +@[simp] theorem representation_value (a : BinaryFraction) : a.representation.value = a.value := rfl + + + + + +@[simp] theorem denominatorInteger_value (a : BinaryFraction) : + a.denominatorInteger.value = (bitWordValue a.denominator : ℤ) := rfl + + + + + +theorem addWithWork_value (a b : BinaryFraction) : + (a.addWithWork b).1.value = a.value + b.value := by + simp only [addWithWork, value, SignedBinary.addWithWork_value, SignedBinary.mulWithWork_value, + denominatorInteger_value, bitMulWithWork_value] + push_cast + have ha : (bitWordValue a.denominator : ℚ) ≠ 0 := by exact_mod_cast a.denominator_pos.ne' + have hb : (bitWordValue b.denominator : ℚ) ≠ 0 := by exact_mod_cast b.denominator_pos.ne' + field_simp [ha, hb] + +theorem mulWithWork_value (a b : BinaryFraction) : + (a.mulWithWork b).1.value = a.value * b.value := by + simp only [mulWithWork, value, SignedBinary.mulWithWork_value, bitMulWithWork_value] + push_cast + exact mul_div_mul_comm _ _ _ _ + +theorem addWithWork_representation (a b : BinaryFraction) : + (a.addWithWork b).1.representation = a.representation.add b.representation := by + apply UnreducedRational.eq_of_num_den + · simp only [addWithWork, representation, UnreducedRational.add, + SignedBinary.addWithWork_value, SignedBinary.mulWithWork_value, denominatorInteger_value] + · exact bitMulWithWork_value a.denominator b.denominator + +theorem mulWithWork_representation (a b : BinaryFraction) : + (a.mulWithWork b).1.representation = a.representation.mul b.representation := by + apply UnreducedRational.eq_of_num_den + · exact SignedBinary.mulWithWork_value a.numerator b.numerator + · exact bitMulWithWork_value a.denominator b.denominator + +theorem addWithWork_cost (a b : BinaryFraction) (B : ℕ) (ha : a.width ≤ B) (hb : b.width ≤ B) : + (a.addWithWork b).2 ≤ 5000 * (B + 1) ^ 2 := by + have han : a.numerator.bits.length ≤ B := (le_max_left _ _).trans ha + have had : a.denominator.length ≤ B := (le_max_right _ _).trans ha + have hbn : b.numerator.bits.length ≤ B := (le_max_left _ _).trans hb + have hbd : b.denominator.length ≤ B := (le_max_right _ _).trans hb + have hfirst := SignedBinary.mulWithWork_cost a.numerator b.denominatorInteger + have hsecond := SignedBinary.mulWithWork_cost b.numerator a.denominatorInteger + have hfl := SignedBinary.mulWithWork_length a.numerator b.denominatorInteger + have hsl := SignedBinary.mulWithWork_length b.numerator a.denominatorInteger + have hsum := SignedBinary.addWithWork_cost (a.numerator.mulWithWork b.denominatorInteger).1 + (b.numerator.mulWithWork a.denominatorInteger).1 + have hden := bitMulWithWork_cost a.denominator b.denominator + simp only [denominatorInteger] at hfirst hsecond hfl hsl + change (a.numerator.mulWithWork b.denominatorInteger).2 + + (b.numerator.mulWithWork a.denominatorInteger).2 + + ((a.numerator.mulWithWork b.denominatorInteger).1.addWithWork + (b.numerator.mulWithWork a.denominatorInteger).1).2 + + (bitMulWithWork a.denominator b.denominator).2 + 8 ≤ _ + simp only [denominatorInteger] at hsum ⊢ + nlinarith only [han, had, hbn, hbd, hfirst, hsecond, hfl, hsl, hsum, hden, + Nat.mul_self_le_mul_self (show a.numerator.bits.length + b.denominator.length + 1 ≤ 2 * B + 1 by omega), + Nat.mul_self_le_mul_self (show b.numerator.bits.length + a.denominator.length + 1 ≤ 2 * B + 1 by omega), + Nat.mul_le_mul (show a.denominator.length + 1 ≤ B + 1 by omega) + (show a.denominator.length + b.denominator.length + 1 ≤ 2 * B + 1 by omega)] + +theorem mulWithWork_cost (a b : BinaryFraction) (B : ℕ) (ha : a.width ≤ B) (hb : b.width ≤ B) : + (a.mulWithWork b).2 ≤ 1000 * (B + 1) ^ 2 := by + have han : a.numerator.bits.length ≤ B := (le_max_left _ _).trans ha + have had : a.denominator.length ≤ B := (le_max_right _ _).trans ha + have hbn : b.numerator.bits.length ≤ B := (le_max_left _ _).trans hb + have hbd : b.denominator.length ≤ B := (le_max_right _ _).trans hb + have hnum := SignedBinary.mulWithWork_cost a.numerator b.numerator + have hden := bitMulWithWork_cost a.denominator b.denominator + change (a.numerator.mulWithWork b.numerator).2 + (bitMulWithWork a.denominator b.denominator).2 + 4 ≤ _ + nlinarith only [han, had, hbn, hbd, hnum, hden, + Nat.mul_self_le_mul_self (show a.numerator.bits.length + b.numerator.bits.length + 1 ≤ 2 * B + 1 by omega), + Nat.mul_le_mul (show a.denominator.length + 1 ≤ B + 1 by omega) + (show a.denominator.length + b.denominator.length + 1 ≤ 2 * B + 1 by omega)] + + + + + + + +theorem neg_value (a : BinaryFraction) : a.neg.value = -a.value := by + simp [neg, value, neg_div] + +theorem invWithWork_value (a : BinaryFraction) : (a.invWithWork).1.value = a.value⁻¹ := by + unfold invWithWork + dsimp only + split_ifs with h + · have hnum : bitWordValue a.numerator.bits = 0 := by + simpa only [bitWordValue] using (bitCompareWithWork_eq a.numerator.bits []).1 h + simp [zero, value, SignedBinary.value, signedMagnitude, hnum, bitWordValue] + · have hn : bitWordValue a.numerator.bits ≠ 0 := by + intro hzero + exact h ((bitCompareWithWork_eq a.numerator.bits []).2 (by simpa [bitWordValue] using hzero)) + cases hsign : a.numerator.negative <;> + simp [value, SignedBinary.value, signedMagnitude, hsign, inv_div, neg_div] + +theorem invWithWork_cost (a : BinaryFraction) : + (a.invWithWork).2 ≤ 4 * a.width + 3 := by + have h := bitCompareWithWork_cost a.numerator.bits [] + have hn : a.numerator.bits.length ≤ a.width := le_max_left _ _ + simp only [List.length_nil, Nat.add_zero] at h + unfold invWithWork + dsimp only + split_ifs <;> omega + +theorem zero_representation : zero.representation = UnreducedRational.zero := by + apply UnreducedRational.eq_of_num_den <;> rfl + +theorem neg_representation (a : BinaryFraction) : + a.neg.representation = a.representation.neg := by + apply UnreducedRational.eq_of_num_den + · exact SignedBinary.value_neg a.numerator + · rfl + +theorem invWithWork_representation (a : BinaryFraction) : + (a.invWithWork).1.representation = a.representation.inv := by + unfold invWithWork + dsimp only + split_ifs with h + · have hz : bitWordValue a.numerator.bits = 0 := by + simpa only [bitWordValue] using (bitCompareWithWork_eq a.numerator.bits []).1 h + have hv : a.numerator.value = 0 := by simp [SignedBinary.value, signedMagnitude, hz] + simp only [UnreducedRational.inv, representation, hv, ↓reduceDIte] + exact zero_representation + · have hn : bitWordValue a.numerator.bits ≠ 0 := by + intro hz + exact h ((bitCompareWithWork_eq a.numerator.bits []).2 (by simpa [bitWordValue] using hz)) + have hv : a.numerator.value ≠ 0 := by + cases hs : a.numerator.negative <;> simp [SignedBinary.value, signedMagnitude, hs, hn] + simp only [UnreducedRational.inv, representation, hv, ↓reduceDIte] + apply UnreducedRational.eq_of_num_den + · cases hs : a.numerator.negative <;> + simp [SignedBinary.value, signedMagnitude, hs, Int.sign_natCast_of_ne_zero hn] + · cases hs : a.numerator.negative <;> simp [SignedBinary.value, signedMagnitude, hs] + + + +theorem ltWithWork_representation (a b : BinaryFraction) : + (a.ltWithWork b).1 = a.representation.lt b.representation := by + apply Bool.eq_iff_iff.mpr + rw [UnreducedRational.lt_eq_true] + simp only [ltWithWork, SignedBinary.ltWithWork_value, SignedBinary.mulWithWork_value, + denominatorInteger_value, representation_value] + unfold value + rw [div_lt_div_iff₀ (by exact_mod_cast a.denominator_pos : (0 : ℚ) < bitWordValue a.denominator) + (by exact_mod_cast b.denominator_pos : (0 : ℚ) < bitWordValue b.denominator)] + exact_mod_cast (Iff.rfl : + a.numerator.value * (bitWordValue b.denominator : ℤ) < + b.numerator.value * (bitWordValue a.denominator : ℤ) ↔ _) + +theorem ltWithWork_value (a b : BinaryFraction) : + (a.ltWithWork b).1 = true ↔ a.value < b.value := by + rw [ltWithWork_representation, UnreducedRational.lt_eq_true] + rfl + +theorem ltWithWork_cost (a b : BinaryFraction) (B : ℕ) (ha : a.width ≤ B) (hb : b.width ≤ B) : + (a.ltWithWork b).2 ≤ 1000 * (B + 1) ^ 2 := by + have han : a.numerator.bits.length ≤ B := (le_max_left _ _).trans ha + have had : a.denominator.length ≤ B := (le_max_right _ _).trans ha + have hbn : b.numerator.bits.length ≤ B := (le_max_left _ _).trans hb + have hbd : b.denominator.length ≤ B := (le_max_right _ _).trans hb + have hl := SignedBinary.mulWithWork_cost a.numerator b.denominatorInteger + have hr := SignedBinary.mulWithWork_cost b.numerator a.denominatorInteger + have hll := SignedBinary.mulWithWork_length a.numerator b.denominatorInteger + have hrl := SignedBinary.mulWithWork_length b.numerator a.denominatorInteger + have hc := SignedBinary.ltWithWork_cost (a.numerator.mulWithWork b.denominatorInteger).1 + (b.numerator.mulWithWork a.denominatorInteger).1 + simp only [denominatorInteger] at hl hr hll hrl + change (a.numerator.mulWithWork b.denominatorInteger).2 + + (b.numerator.mulWithWork a.denominatorInteger).2 + + ((a.numerator.mulWithWork b.denominatorInteger).1.ltWithWork + (b.numerator.mulWithWork a.denominatorInteger).1).2 + 4 ≤ _ + simp only [denominatorInteger] at hc ⊢ + nlinarith only [hl, hr, hll, hrl, hc, han, had, hbn, hbd, + Nat.mul_self_le_mul_self (show a.numerator.bits.length + b.denominator.length + 1 ≤ 2 * B + 1 by omega), + Nat.mul_self_le_mul_self (show b.numerator.bits.length + a.denominator.length + 1 ≤ 2 * B + 1 by omega)] + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryGatheredValues.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryGatheredValues.lean new file mode 100644 index 0000000000000000000000000000000000000000..154d915a466ab54ff2b49f7538c96fa9cc350d3a --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryGatheredValues.lean @@ -0,0 +1,144 @@ +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalBinaryMass +import OAI.Combinatorics.EditApproximation.Binary.BinaryBandCoordinates +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalWarmupQuery +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Finite stored-word tables for gathered earlier values. The lookup scan +and the construction of every gathered warmup mean are explicit. -/ + +namespace EditApproximation +namespace BinaryFraction + + + +theorem gatheredWordLookupWithWork_value {κ : Type*} [DecidableEq κ] + (equal : κ → κ → Bool × ℕ) (heq : ∀ a b, (equal a b).1 = true ↔ a = b) + (keys : List κ) (values : List BinaryFraction) (query : κ) : + (gatheredWordLookupWithWork equal keys values query).1.value = + finiteAnswerTable keys (values.map BinaryFraction.value) query := by + induction keys generalizing values with + | nil => simp only [gatheredWordLookupWithWork, finiteAnswerTable, nat_value, Nat.cast_zero] + | cons key keys ih => + cases values with + | nil => simp only [gatheredWordLookupWithWork, List.map_nil, finiteAnswerTable, nat_value, Nat.cast_zero] + | cons value values => + simp only [gatheredWordLookupWithWork, List.map_cons, finiteAnswerTable] + by_cases h : query = key + · rw [ite_eq_left ((heq query key).mpr h), ite_eq_left h] + · rw [ite_eq_right (fun hx => h ((heq query key).mp hx)), ite_eq_right h] + exact ih values + +theorem gatheredWordLookupWithWork_cost {κ : Type*} + (equal : κ → κ → Bool × ℕ) (C : ℕ) (hC : ∀ a b, (equal a b).2 ≤ C) + (keys : List κ) (values : List BinaryFraction) (query : κ) : + (gatheredWordLookupWithWork equal keys values query).2 ≤ 1 + keys.length * (C + 1) := by + induction keys generalizing values with + | nil => simp only [gatheredWordLookupWithWork, List.length_nil, Nat.zero_mul, Nat.add_zero, le_rfl] + | cons key keys ih => + cases values with + | nil => simp only [gatheredWordLookupWithWork]; omega + | cons value values => + have hc := hC query key + have hi := ih values + simp only [gatheredWordLookupWithWork] + split_ifs <;> simp only [List.length_cons, Nat.add_mul, Nat.one_mul] <;> omega + +theorem gatheredWordLookupWithWork_width {κ : Type*} + (equal : κ → κ → Bool × ℕ) (keys : List κ) (values : List BinaryFraction) (query : κ) + (B : ℕ) (hB : 2 ≤ B) (hvalues : ∀ value ∈ values, value.width ≤ B) : + (gatheredWordLookupWithWork equal keys values query).1.width ≤ B := by + induction keys generalizing values with + | nil => exact (nat_width_le 0).trans (by simpa using hB) + | cons key keys ih => + cases values with + | nil => exact (nat_width_le 0).trans (by simpa using hB) + | cons value values => + simp only [gatheredWordLookupWithWork] + split_ifs + · exact hvalues value List.mem_cons_self + · exact ih values (fun v hv => hvalues v (List.mem_cons_of_mem _ hv)) + +def gatheredMassWordsWithWork {ny M : ℕ} (T : ℕ) + (words : Fin M → ℕ → TargetInterval ny → BinaryFraction) + (inputs : List (Fin M × TargetInterval ny)) : List BinaryFraction × ℕ := + arithmeticMapWithWork (fun input => physicalWarmupMassWithWork T (words input.1) input.2) inputs + +@[simp] theorem gatheredMassWordsWithWork_value {ny M : ℕ} (T : ℕ) + (words : Fin M → ℕ → TargetInterval ny → BinaryFraction) + (inputs : List (Fin M × TargetInterval ny)) : + (gatheredMassWordsWithWork T words inputs).1 = + inputs.map (fun input => (physicalWarmupMassWithWork T (words input.1) input.2).1) := + arithmeticMapWithWork_value _ _ + +theorem gatheredMassWordsWithWork_bounds {ny M : ℕ} (T B : ℕ) + (words : Fin M → ℕ → TargetInterval ny → BinaryFraction) + (inputs : List (Fin M × TargetInterval ny)) + (hwords : ∀ i j, j < T → ∀ r, (words i j r).width ≤ B) : + (gatheredMassWordsWithWork T words inputs).2 ≤ + 1 + inputs.length * (warmupAverageBitBudget T B + T + 4) ∧ + ∀ value ∈ (gatheredMassWordsWithWork T words inputs).1, + value.width ≤ warmupAverageWordBudget T B := by + constructor + · have h := arithmeticMapWithWork_cost + (fun input : Fin M × TargetInterval ny => physicalWarmupMassWithWork T (words input.1) input.2) + inputs (warmupAverageBitBudget T B + T + 1) (by + intro input _ + exact (physicalWarmupMassWithWork_bounds T B (words input.1) + (fun j hj r => hwords input.1 j hj r) input.2).2) + simpa only [gatheredMassWordsWithWork, Nat.add_assoc, Nat.reduceAdd] using h.trans (Nat.le_add_left _ 1) + · intro value hv + rw [gatheredMassWordsWithWork_value] at hv + obtain ⟨input, _, rfl⟩ := List.mem_map.mp hv + exact (physicalWarmupMassWithWork_bounds T B (words input.1) + (fun j hj r => hwords input.1 j hj r) input.2).1 + +theorem gatheredMassLookup_value {α : Type*} [DecidableEq α] {M J : ℕ} + (source target : List α) (U : PhysicalEntry M J target.length → ℕ) + (N P F T : ℕ) (A : ℚ) (node : PhysicalNode M J) (hbelow : node.1.val < J) + (words : Fin M → ℕ → TargetInterval target.length → BinaryFraction) + (inputs : List (Fin M × TargetInterval target.length)) + (hwords : ∀ i j, j < T → ∀ r, (words i j r).value = + physicalLocalWarmup source target U N P F A j (physicalChild node hbelow i, r)) + (query : Fin M × TargetInterval target.length) (hquery : query ∈ inputs) : + (gatheredWordLookupWithWork coordinateEqualWithWork inputs + (gatheredMassWordsWithWork T words inputs).1 query).1.value = + physicalLocalChildMass source target U N P F A T node hbelow query.1 query.2 := by + rw [gatheredWordLookupWithWork_value _ coordinateEqualWithWork_value, + gatheredMassWordsWithWork_value, List.map_map] + rw [finiteAnswerTable_map _ _ query hquery] + exact physicalWarmupMassWithWork_value source target U N P F T A + (physicalChild node hbelow query.1) (words query.1) (hwords query.1) query.2 + + +def gatheredWordBits (values : List BinaryFraction) : ℕ := + (values.map fun value => value.width + 1).sum + +theorem gatheredWordBits_le (values : List BinaryFraction) (B : ℕ) + (hb : ∀ value ∈ values, value.width ≤ B) : + gatheredWordBits values ≤ values.length * (B + 1) := by + induction values with + | nil => simp only [gatheredWordBits, List.map_nil, List.sum_nil, List.length_nil, Nat.zero_mul, le_refl] + | cons value values ih => + have hhead := hb value List.mem_cons_self + have htail := ih (fun v hv => hb v (List.mem_cons_of_mem _ hv)) + simp only [gatheredWordBits, List.map_cons, List.sum_cons, List.length_cons, + Nat.add_mul, Nat.one_mul] at * + omega + +theorem gatheredMassWordsWithWork_storage {ny M : ℕ} (T B : ℕ) + (words : Fin M → ℕ → TargetInterval ny → BinaryFraction) + (inputs : List (Fin M × TargetInterval ny)) + (hwords : ∀ i j, j < T → ∀ r, (words i j r).width ≤ B) : + gatheredWordBits (gatheredMassWordsWithWork T words inputs).1 ≤ + inputs.length * (warmupAverageWordBudget T B + 1) := by + have h := gatheredWordBits_le (gatheredMassWordsWithWork T words inputs).1 + (warmupAverageWordBudget T B) (gatheredMassWordsWithWork_bounds T B words inputs hwords).2 + simpa only [gatheredMassWordsWithWork_value, List.length_map] using h + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryGeometrySpace.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryGeometrySpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..e20424d22f3e01573b98ece2b53a13b9d28e220f --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryGeometrySpace.lean @@ -0,0 +1,257 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryReductionSpace +import OAI.Combinatorics.EditApproximation.Binary.BinaryScoreReads +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Endpoint geometry and actual finite score/minimum scans retain +all arithmetic scratch and all callback read invocations. -/ + +namespace EditApproximation.BinaryFraction + + + +theorem distanceAllocation_le_work (a b : BinaryFraction) : + distanceAllocation a b ≤ (distanceWithWork a b).2 := by + have h := subAllocation_le_work a b + unfold distanceAllocation distanceWithWork + dsimp only + omega + + + +theorem connectionTermsAllocation_le_work {n : ℕ} (start finish : BinaryFraction) + (states : List (TargetInterval n)) : + connectionTermsAllocation start states finish ≤ (connectionTermsWithWork start states finish).2 := by + induction states generalizing start with + | nil => + have h := distanceAllocation_le_work start finish + unfold connectionTermsAllocation connectionTermsWithWork + dsimp only + exact Nat.add_le_add h (by decide : 1 ≤ 2) + | cons state rest ih => + have hc := distanceAllocation_le_work start (nat state.lo) + have ht := ih (nat state.hi) + unfold connectionTermsAllocation connectionTermsWithWork + dsimp only + exact Nat.add_le_add + (Nat.add_le_add_right (Nat.add_le_add_right (Nat.add_le_add hc ht) _) _) + (by decide : 3 ≤ 6) + + + +theorem connectionAllocation_le_work {n : ℕ} (start finish : BinaryFraction) + (states : List (TargetInterval n)) : + connectionAllocation start finish states ≤ (connectionWithWork start finish states).2 := by + have ht := connectionTermsAllocation_le_work start finish states + have hs := sumListAllocation_le_work (connectionTermsWithWork start states finish).1 + unfold connectionAllocation connectionWithWork + dsimp only + omega + + + +theorem endpointDistanceAllocation_le_work {n : ℕ} (q r : TargetInterval n) : + endpointDistanceAllocation q r ≤ (endpointDistanceWithWork q r).2 := by + have hl := distanceAllocation_le_work (nat q.lo) (nat r.lo) + have hr := distanceAllocation_le_work (nat q.hi) (nat r.hi) + have ha := canonicalAddAllocation_le_work (distanceWithWork (nat q.lo) (nat r.lo)).1 + (distanceWithWork (nat q.hi) (nat r.hi)).1 + unfold endpointDistanceAllocation endpointDistanceWithWork + dsimp only + omega + + + +theorem endpointConnectionAllocation_le_work {n M : ℕ} (r : TargetInterval n) + (states : Fin M → TargetInterval n) : + endpointConnectionAllocation r states ≤ (endpointConnectionWithWork r states).2 := by + have h := connectionAllocation_le_work (nat r.lo) (nat r.hi) (List.ofFn states) + unfold endpointConnectionAllocation endpointConnectionWithWork + dsimp only + omega + + + +theorem stateGapAllocation_le_work {n : ℕ} (sourceLength : ℕ) (r : TargetInterval n) : + stateGapAllocation sourceLength r ≤ (stateGapWithWork sourceLength r).2 := by + have h1 := subAllocation_le_work (nat r.hi) (nat r.lo) + have h2 := subAllocation_le_work (subWithWork (nat r.hi) (nat r.lo)).1 (nat sourceLength) + unfold stateGapAllocation stateGapWithWork + dsimp only + omega + + + +theorem endpointScoreReadAllocation_le_work {n M : ℕ} (r : TargetInterval n) + (read : Fin M → TargetInterval n → BinaryFraction × ℕ) + (footprint : Fin M → TargetInterval n → ℕ) (states : Fin M → TargetInterval n) + (h : ∀ i, footprint i (states i) ≤ (read i (states i)).2) : + endpointScoreReadAllocation r read footprint states ≤ (endpointScoreReadWithWork r read states).2 := by + have hw := arithmeticMapAllocation_le_work (fun i => read i (states i)) + (fun i => footprint i (states i)) (List.finRange M) (fun i _ => h i) + have hc := endpointConnectionAllocation_le_work r states + let words := (arithmeticMapWithWork (fun i => read i (states i)) (List.finRange M)).1 + have hs := sumListAllocation_le_work words + have ha := canonicalAddAllocation_le_work (endpointConnectionWithWork r states).1 (sumListWithWork words).1 + unfold endpointScoreReadAllocation endpointScoreReadWithWork + dsimp only + dsimp only [words] at hs ha + omega + + + +theorem wideMinimumReadAllocation_le_work {n M : ℕ} (r : TargetInterval n) + (read : Fin M → TargetInterval n → BinaryFraction × ℕ) + (footprint : Fin M → TargetInterval n → ℕ) + (actions : List (Fin M → TargetInterval n)) (hne : actions ≠ []) + (h : ∀ action ∈ actions, ∀ i, footprint i (action i) ≤ (read i (action i)).2) : + wideMinimumReadAllocation r read footprint actions hne ≤ (wideMinimumReadWithWork r read actions hne).2 := by + have hf := endpointScoreReadAllocation_le_work r read footprint (actions.head hne) (h _ (List.head_mem hne)) + have hs := arithmeticMapAllocation_le_work (endpointScoreReadWithWork r read) + (endpointScoreReadAllocation r read footprint) actions + (fun action ha => endpointScoreReadAllocation_le_work r read footprint action (h action ha)) + have hm := minimumAllocation_le_work (endpointScoreReadWithWork r read (actions.head hne)).1 + (arithmeticMapWithWork (endpointScoreReadWithWork r read) actions).1 + unfold wideMinimumReadAllocation wideMinimumReadWithWork + dsimp only + omega + +def distanceInvocations (a b : BinaryFraction) : ℕ := subInvocations a b + 1 + +theorem distanceInvocations_le_work (a b : BinaryFraction) : + distanceInvocations a b ≤ (distanceWithWork a b).2 := by + have h := subInvocations_le_work a b + unfold distanceInvocations distanceWithWork + dsimp only + omega + +def connectionTermsInvocations {n : ℕ} (start : BinaryFraction) : + List (TargetInterval n) → BinaryFraction → ℕ + | [], finish => distanceInvocations start finish + 1 + | state :: rest, finish => distanceInvocations start (nat state.lo) + + connectionTermsInvocations (nat state.hi) rest finish + 1 + +theorem connectionTermsInvocations_le_work {n : ℕ} (start finish : BinaryFraction) + (states : List (TargetInterval n)) : + connectionTermsInvocations start states finish ≤ (connectionTermsWithWork start states finish).2 := by + induction states generalizing start with + | nil => + have h := distanceInvocations_le_work start finish + unfold connectionTermsInvocations connectionTermsWithWork + dsimp only + omega + | cons state rest ih => + have hc := distanceInvocations_le_work start (nat state.lo) + have ht := ih (nat state.hi) + unfold connectionTermsInvocations connectionTermsWithWork + dsimp only + omega + +def connectionInvocations {n : ℕ} (start finish : BinaryFraction) + (states : List (TargetInterval n)) : ℕ := + connectionTermsInvocations start states finish + + sumListInvocations (connectionTermsWithWork start states finish).1 + 1 + +theorem connectionInvocations_le_work {n : ℕ} (start finish : BinaryFraction) + (states : List (TargetInterval n)) : + connectionInvocations start finish states ≤ (connectionWithWork start finish states).2 := by + have ht := connectionTermsInvocations_le_work start finish states + have hs := sumListInvocations_le_work (connectionTermsWithWork start states finish).1 + unfold connectionInvocations connectionWithWork + dsimp only + omega + +def endpointDistanceInvocations {n : ℕ} (q r : TargetInterval n) : ℕ := + distanceInvocations (nat q.lo) (nat r.lo) + distanceInvocations (nat q.hi) (nat r.hi) + + canonicalAddInvocations (distanceWithWork (nat q.lo) (nat r.lo)).1 + (distanceWithWork (nat q.hi) (nat r.hi)).1 + 1 + +theorem endpointDistanceInvocations_le_work {n : ℕ} (q r : TargetInterval n) : + endpointDistanceInvocations q r ≤ (endpointDistanceWithWork q r).2 := by + have hl := distanceInvocations_le_work (nat q.lo) (nat r.lo) + have hr := distanceInvocations_le_work (nat q.hi) (nat r.hi) + have ha := canonicalAddInvocations_le_work (distanceWithWork (nat q.lo) (nat r.lo)).1 + (distanceWithWork (nat q.hi) (nat r.hi)).1 + unfold endpointDistanceInvocations endpointDistanceWithWork + dsimp only + omega + +def endpointConnectionInvocations {n M : ℕ} (r : TargetInterval n) + (states : Fin M → TargetInterval n) : ℕ := + connectionInvocations (nat r.lo) (nat r.hi) (List.ofFn states) + 1 + +theorem endpointConnectionInvocations_le_work {n M : ℕ} (r : TargetInterval n) + (states : Fin M → TargetInterval n) : + endpointConnectionInvocations r states ≤ (endpointConnectionWithWork r states).2 := by + have h := connectionInvocations_le_work (nat r.lo) (nat r.hi) (List.ofFn states) + unfold endpointConnectionInvocations endpointConnectionWithWork + dsimp only + omega + +def stateGapInvocations {n : ℕ} (sourceLength : ℕ) (r : TargetInterval n) : ℕ := + subInvocations (nat r.hi) (nat r.lo) + + subInvocations (subWithWork (nat r.hi) (nat r.lo)).1 (nat sourceLength) + 1 + +theorem stateGapInvocations_le_work {n : ℕ} (sourceLength : ℕ) (r : TargetInterval n) : + stateGapInvocations sourceLength r ≤ (stateGapWithWork sourceLength r).2 := by + have h1 := subInvocations_le_work (nat r.hi) (nat r.lo) + have h2 := subInvocations_le_work (subWithWork (nat r.hi) (nat r.lo)).1 (nat sourceLength) + unfold stateGapInvocations stateGapWithWork + dsimp only + omega + +def endpointScoreReadInvocations {n M : ℕ} (r : TargetInterval n) + (read : Fin M → TargetInterval n → BinaryFraction × ℕ) + (footprint : Fin M → TargetInterval n → ℕ) (states : Fin M → TargetInterval n) : ℕ := + let words := (arithmeticMapWithWork (fun i => read i (states i)) (List.finRange M)).1 + arithmeticMapInvocations (fun i => footprint i (states i)) (List.finRange M) + + endpointConnectionInvocations r states + sumListInvocations words + + canonicalAddInvocations (endpointConnectionWithWork r states).1 (sumListWithWork words).1 + 1 + +theorem endpointScoreReadInvocations_le_work {n M : ℕ} (r : TargetInterval n) + (read : Fin M → TargetInterval n → BinaryFraction × ℕ) + (footprint : Fin M → TargetInterval n → ℕ) (states : Fin M → TargetInterval n) + (h : ∀ i, footprint i (states i) ≤ (read i (states i)).2) : + endpointScoreReadInvocations r read footprint states ≤ (endpointScoreReadWithWork r read states).2 := by + have hw := arithmeticMapInvocations_le_work (fun i => read i (states i)) + (fun i => footprint i (states i)) (List.finRange M) (fun i _ => h i) + have hc := endpointConnectionInvocations_le_work r states + let words := (arithmeticMapWithWork (fun i => read i (states i)) (List.finRange M)).1 + have hs := sumListInvocations_le_work words + have ha := canonicalAddInvocations_le_work (endpointConnectionWithWork r states).1 (sumListWithWork words).1 + unfold endpointScoreReadInvocations endpointScoreReadWithWork + dsimp only + dsimp only [words] at hs ha + omega + +def wideMinimumReadInvocations {n M : ℕ} (r : TargetInterval n) + (read : Fin M → TargetInterval n → BinaryFraction × ℕ) + (footprint : Fin M → TargetInterval n → ℕ) + (actions : List (Fin M → TargetInterval n)) (hne : actions ≠ []) : ℕ := + let fallback := (endpointScoreReadWithWork r read (actions.head hne)).1 + let scores := (arithmeticMapWithWork (endpointScoreReadWithWork r read) actions).1 + endpointScoreReadInvocations r read footprint (actions.head hne) + + arithmeticMapInvocations (endpointScoreReadInvocations r read footprint) actions + + minimumInvocations fallback scores + 1 + +theorem wideMinimumReadInvocations_le_work {n M : ℕ} (r : TargetInterval n) + (read : Fin M → TargetInterval n → BinaryFraction × ℕ) + (footprint : Fin M → TargetInterval n → ℕ) + (actions : List (Fin M → TargetInterval n)) (hne : actions ≠ []) + (h : ∀ action ∈ actions, ∀ i, footprint i (action i) ≤ (read i (action i)).2) : + wideMinimumReadInvocations r read footprint actions hne ≤ (wideMinimumReadWithWork r read actions hne).2 := by + have hf := endpointScoreReadInvocations_le_work r read footprint (actions.head hne) (h _ (List.head_mem hne)) + have hs := arithmeticMapInvocations_le_work (endpointScoreReadWithWork r read) + (endpointScoreReadInvocations r read footprint) actions + (fun action ha => endpointScoreReadInvocations_le_work r read footprint action (h action ha)) + have hm := minimumInvocations_le_work (endpointScoreReadWithWork r read (actions.head hne)).1 + (arithmeticMapWithWork (endpointScoreReadWithWork r read) actions).1 + unfold wideMinimumReadInvocations wideMinimumReadWithWork + dsimp only + omega + +end EditApproximation.BinaryFraction + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryGradientWork.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryGradientWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..b3a591539b6c290b672e5dd5ccfa9562769a709d --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryGradientWork.lean @@ -0,0 +1,135 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryLogWork + +namespace OAI + +/-! A bit-operation bound for each actually materialized gradient coordinate. -/ + +namespace EditApproximation +namespace BinaryFraction + +def smoothingStorageBudget (G : ℕ) : ℕ := 3 + 50 * (Nat.size G + 2) + +def shiftedStorageBudget (G pointBits : ℕ) : ℕ := 4 * pointBits + 2 * smoothingStorageBudget G + 8 + +def gradientLogStorageBudget (G pointBits : ℕ) : ℕ := + UnreducedRational.logarithmStorageBudget (shiftedStorageBudget G pointBits) (G ^ 60) + +def gradientCellBitBudget (G pointBits linearBits : ℕ) : ℕ := + let S := smoothingStorageBudget G + let R := shiftedStorageBudget G pointBits + let L := gradientLogStorageBudget G pointBits + (1 + 50 * (2000 * (generalPowerWordBudget (nat G) 50 + 1) ^ 2 + 1)) + + (4 * S + 3) + 6000 * (pointBits + S + 2) ^ 2 + logarithmBitBudget R (G ^ 60) + + (6000 * (L + 4) ^ 2 + 1) + 6000 * (linearBits + 2 * L + 9) ^ 2 + Nat.size G + 70 + +theorem gradientCellWithWork_cost {d : ℕ} (G : ℕ) (linear point : Vector BinaryFraction d) + (i : Fin d) (hpoint : 0 ≤ (point.get i).value) : + (gradientCellWithWork G linear point i).2 ≤ + gradientCellBitBudget G (point.get i).width (linear.get i).width := by + let smoothing := powWithWork (nat G) 50 + let shifted := canonicalAddWithWork (point.get i) smoothing.1.invWithWork.1 + let logarithm := logarithmWithWork shifted.1 (G ^ 60) + let deficit := subWithWork logarithm.1.neg one + let S := smoothingStorageBudget G + let R := shiftedStorageBudget G (point.get i).width + let L := gradientLogStorageBudget G (point.get i).width + have hsm : smoothing.1.representation.storageBits ≤ S := by + rw [powWithWork_representation, nat_representation] + simpa only [UnreducedRational.storageBits_nat, S, smoothingStorageBudget] using + UnreducedRational.pow_storageBits (UnreducedRational.nat G) 50 + have hsw : smoothing.1.width ≤ S := (powWithWork_width_le_storageBits (nat G) 50).trans hsm + have his : smoothing.1.invWithWork.1.representation.storageBits ≤ S + 2 := by + rw [invWithWork_representation] + exact (UnreducedRational.storageBits_inv _).trans (Nat.add_le_add_right hsm 2) + have hsi : smoothing.1.invWithWork.1.width ≤ S + 1 := + (invWithWork_width smoothing.1).trans (Nat.add_le_add_right hsw 1) + have hps := representation_storageBits_le (point.get i) + have hshift : shifted.1.representation.storageBits ≤ R := by + change (canonicalAddWithWork (point.get i) smoothing.1.invWithWork.1).1.representation.storageBits ≤ R + rw [canonicalAddWithWork_representation] + have h := UnreducedRational.storageBits_add (point.get i).representation smoothing.1.invWithWork.1.representation + dsimp only [R, shiftedStorageBudget] + omega + have hshiftw : shifted.1.width ≤ R := (canonicalAddWithWork_self_width _ _).trans hshift + have hshiftpos : 0 ≤ shifted.1.value := by + change 0 ≤ (canonicalAddWithWork (point.get i) smoothing.1.invWithWork.1).1.value + rw [← representation_value, canonicalAddWithWork_representation, invWithWork_representation, + powWithWork_representation, nat_representation] + simp only [UnreducedRational.value_add, UnreducedRational.value_inv, + UnreducedRational.value_pow, UnreducedRational.value_nat, representation_value] + exact add_nonneg hpoint (inv_nonneg.mpr (pow_nonneg (Nat.cast_nonneg G) 50)) + have hlogs : logarithm.1.representation.storageBits ≤ L := by + rw [logarithmWithWork_representation] + exact (UnreducedRational.logarithm_storageBits_poly shifted.1.representation (G ^ 60) hshiftpos).trans + (UnreducedRational.logarithmStorageBudget_mono hshift _) + have hlogw : logarithm.1.width ≤ L := (logarithmWithWork_width_le_storageBits _ _).trans hlogs + have hdeficit : deficit.1.width ≤ 2 * L + 8 := by + have hwidth := canonicalAddWithWork_self_width logarithm.1.neg one.neg + change deficit.1.width ≤ deficit.1.representation.storageBits at hwidth + rw [subWithWork_representation, neg_representation, one_representation] at hwidth + have h := UnreducedRational.storageBits_sub logarithm.1.representation.neg UnreducedRational.one + rw [UnreducedRational.storageBits_neg, UnreducedRational.storageBits_one] at h + omega + have csm := powWithWork_cost_general (nat G) 50 + have csi := invWithWork_cost smoothing.1 + have cshift := canonicalAddWithWork_cost (point.get i) smoothing.1.invWithWork.1 + ((point.get i).width + S + 1) (by omega) (by omega) + have clog := (logarithmWithWork_cost shifted.1 (G ^ 60) hshiftpos).trans + (logarithmBitBudget_mono hshiftw _) + have cdef := subWithWork_cost logarithm.1.neg one (L + 3) + (by rw [neg_width]; omega) (by have h := one_width; omega) + have cfinal := canonicalAddWithWork_cost deficit.1 (linear.get i) + ((linear.get i).width + 2 * L + 8) (by omega) (by omega) + change smoothing.2 + smoothing.1.invWithWork.2 + shifted.2 + logarithm.2 + deficit.2 + + (canonicalAddWithWork deficit.1 (linear.get i)).2 + Nat.size G + 70 ≤ _ + change _ ≤ (1 + 50 * (2000 * (generalPowerWordBudget (nat G) 50 + 1) ^ 2 + 1)) + + (4 * S + 3) + 6000 * ((point.get i).width + S + 2) ^ 2 + logarithmBitBudget R (G ^ 60) + + (6000 * (L + 4) ^ 2 + 1) + 6000 * ((linear.get i).width + 2 * L + 9) ^ 2 + Nat.size G + 70 + change logarithm.2 ≤ logarithmBitBudget R (G ^ 60) at clog + change deficit.2 ≤ 6000 * (L + 3 + 1) ^ 2 + 1 at cdef + change smoothing.2 ≤ _ at csm + nlinarith only [csm, csi, cshift, clog, cdef, cfinal, hsw] + +theorem gradientCellBitBudget_mono (G : ℕ) {A B C D : ℕ} (hpoint : A ≤ B) (hlinear : C ≤ D) : + gradientCellBitBudget G A C ≤ gradientCellBitBudget G B D := by + have hR : shiftedStorageBudget G A ≤ shiftedStorageBudget G B := by + unfold shiftedStorageBudget + omega + have hL : gradientLogStorageBudget G A ≤ gradientLogStorageBudget G B := + UnreducedRational.logarithmStorageBudget_mono hR _ + have hc := logarithmBitBudget_mono hR (G ^ 60) + have h1 := Nat.mul_self_le_mul_self + (show A + smoothingStorageBudget G + 2 ≤ B + smoothingStorageBudget G + 2 by omega) + have h2 := Nat.mul_self_le_mul_self + (show gradientLogStorageBudget G A + 4 ≤ gradientLogStorageBudget G B + 4 by omega) + have h3 := Nat.mul_self_le_mul_self + (show C + 2 * gradientLogStorageBudget G A + 9 ≤ D + 2 * gradientLogStorageBudget G B + 9 by omega) + simp only [← pow_two] at h1 h2 h3 + unfold gradientCellBitBudget + dsimp only + omega + +theorem vectorMapWithWork_cost_le {α : Type*} (d : ℕ) (f : Fin d → α × ℕ) + (C : ℕ) (hC : ∀ i, (f i).2 ≤ C) : + (vectorMapWithWork d f).2 ≤ d * (C + 6) := by + simp only [vectorMapWithWork, Vector.toList_map, Vector.toList_ofFn, + List.map_ofFn, Function.comp_def, List.sum_ofFn] + have hs : (∑ i : Fin d, (f i).2) ≤ d * C := by + calc + _ ≤ ∑ _ : Fin d, C := Finset.sum_le_sum (fun i _ => hC i) + _ = d * C := by simp + nlinarith only [hs] + +theorem gradientWithWork_cost {d : ℕ} (G : ℕ) (linear point : Vector BinaryFraction d) + (P L : ℕ) (hp : ∀ i, 0 ≤ (point.get i).value) + (hpw : ∀ i, (point.get i).width ≤ P) (hlw : ∀ i, (linear.get i).width ≤ L) : + (gradientWithWork G linear point).2 ≤ d * (gradientCellBitBudget G P L + 6) := by + apply vectorMapWithWork_cost_le + intro i + exact (gradientCellWithWork_cost G linear point i (hp i)).trans + (gradientCellBitBudget_mono G (hpw i) (hlw i)) + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryGridSpace.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryGridSpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..9e88baef5ef220b398575452ae932de4ac3002ba --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryGridSpace.lean @@ -0,0 +1,101 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryCoordinateSpace +import OAI.Combinatorics.EditApproximation.Binary.BinaryWideGrid +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation + + + +theorem binaryNaturalAddAllocation_le_work (a b : ℕ) : + binaryNaturalAddAllocation a b ≤ (binaryNaturalAddWithWork a b).2 := bitAddAllocation_le_work _ _ _ + + + +theorem binaryNaturalMulAllocation_le_work (a b : ℕ) : + binaryNaturalMulAllocation a b ≤ (binaryNaturalMulWithWork a b).2 := bitMulAllocation_le_work _ _ + + + +theorem binaryNaturalDivAllocation_le_work (a b : ℕ) : + binaryNaturalDivAllocation a b ≤ (binaryNaturalDivModWithWork a b).2.2 := bitDivModAllocation_le_work _ _ + + + +theorem naturalWordLEAllocation_le_work (a b : List Bool) : + naturalWordLEAllocation a b ≤ (wordLEWithWork a b).2 := by + have h := bitCompareWithWork_input_cells b a + change a.length + b.length + 1 ≤ (bitCompareWithWork b a).2 + 1 + omega + + + +theorem saturatingSubtractAllocation_le_work (a b : ℕ) : + saturatingSubtractAllocation a b ≤ (saturatingSubtractWithWork a b).2 := by + have hc := bitCompareWithWork_input_cells a.bits b.bits + have hs := bitSubtractAllocation_le_work a.bits b.bits false + unfold saturatingSubtractAllocation saturatingSubtractWithWork binaryNaturalCompareWithWork binaryNaturalSubtractWithWork + dsimp only + split_ifs <;> omega + + + +theorem gridPointsAllocation_le_work (g lo hi : ℕ) : + gridPointsAllocation g lo hi ≤ (gridPointsWithWork g lo hi).2 := by + let lower := (bitCeilDivWithWork g.bits lo.bits).1 + let upper := (binaryNaturalDivModWithWork hi g).1 + let stop := (binaryNaturalAddWithWork (bitWordValue upper) 1).1 + let count := (saturatingSubtractWithWork (bitWordValue stop) (bitWordValue lower)).1 + let indices := List.range' (bitWordValue lower) (bitWordValue count) + have hl := bitCeilDivAllocation_le_work g.bits lo.bits + have hu := binaryNaturalDivAllocation_le_work hi g + have hs := binaryNaturalAddAllocation_le_work (bitWordValue upper) 1 + have hc := saturatingSubtractAllocation_le_work (bitWordValue stop) (bitWordValue lower) + have hm := arithmeticMapAllocation_with_spine + (fun i => (bitWordValue (binaryNaturalMulWithWork g i).1, (binaryNaturalMulWithWork g i).2 + Nat.size i + 2)) + (fun i => binaryNaturalMulAllocation g i) indices + (fun i _ => (binaryNaturalMulAllocation_le_work g i).trans (by omega)) + unfold gridPointsAllocation gridPointsWithWork + dsimp only [lower, upper, stop, count, indices] at hl hu hs hc hm ⊢ + omega + + + +theorem makeStateAllocation_le_work (n lo hi : ℕ) : + makeStateAllocation n lo hi ≤ (makeStateWithWork n lo hi).2 := by + have hl := naturalWordLEAllocation_le_work lo.bits hi.bits + have hh := naturalWordLEAllocation_le_work hi.bits n.bits + unfold makeStateAllocation makeStateWithWork + dsimp only + split_ifs <;> omega + + + +theorem gridStateBoxAllocation_le_work (n g radius lo hi : ℕ) : + gridStateBoxAllocation n g radius lo hi ≤ (gridStateBoxWithWork n g radius lo hi).2 := by + let leftLow := (saturatingSubtractWithWork lo radius).1 + let leftHigh := (binaryNaturalAddWithWork lo radius).1 + let rightLow := (saturatingSubtractWithWork hi radius).1 + let rightHigh := (binaryNaturalAddWithWork hi radius).1 + let left := (gridPointsWithWork g (bitWordValue leftLow) (bitWordValue leftHigh)).1 + let right := (gridPointsWithWork g (bitWordValue rightLow) (bitWordValue rightHigh)).1 + have h1 := saturatingSubtractAllocation_le_work lo radius + have h2 := binaryNaturalAddAllocation_le_work lo radius + have h3 := saturatingSubtractAllocation_le_work hi radius + have h4 := binaryNaturalAddAllocation_le_work hi radius + have h5 := gridPointsAllocation_le_work g (bitWordValue leftLow) (bitWordValue leftHigh) + have h6 := gridPointsAllocation_le_work g (bitWordValue rightLow) (bitWordValue rightHigh) + have hf := arithmeticFlatMapAllocation_le_work + (fun s => filterMapWithWork (makeStateWithWork n s) right) + (fun s => filterMapAllocation (makeStateWithWork n s) (makeStateAllocation n s) right) left + (fun s _ => filterMapAllocation_le_work (makeStateWithWork n s) (makeStateAllocation n s) right + (fun k _ => makeStateAllocation_le_work n s k)) + unfold gridStateBoxAllocation gridStateBoxWithWork + dsimp only [leftLow, leftHigh, rightLow, rightHigh, left, right] at h5 h6 hf ⊢ + omega + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryGridWork.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryGridWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..6a9b842f1b01cac737aaf4eacfd144bdc533e0fb --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryGridWork.lean @@ -0,0 +1,55 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryCeilingWork +import OAI.Combinatorics.EditApproximation.Geometry.Grid +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Endpoint rounding executed by binary division followed by multiplication. -/ + +namespace EditApproximation + + + +theorem binaryGridRoundWithWork_value (spacing position : ℕ) (hspacing : 0 < spacing) : + bitWordValue (binaryGridRoundWithWork spacing position).1 = gridRound spacing position := by + simp only [binaryGridRoundWithWork, bitMulWithWork_value, bitWordValue_bits, + (binaryNaturalDivModWithWork_spec position spacing hspacing).1, gridRound] + +theorem binaryGridRoundWithWork_cost (spacing position : ℕ) : + (binaryGridRoundWithWork spacing position).2 ≤ + 60 * (Nat.size spacing + Nat.size position + 1) ^ 2 := by + have hd := binaryNaturalDivModWithWork_cost position spacing + have hq := (bitDivModWithWork_lengths spacing.bits position.bits).1 + have hm := bitMulWithWork_cost spacing.bits (binaryNaturalDivModWithWork position spacing).1 + change (binaryNaturalDivModWithWork position spacing).1.length = position.bits.length at hq + simp only [Nat.size_eq_bits_len] at hq hm + rw [hq] at hm + change (binaryNaturalDivModWithWork position spacing).2.2 + + (bitMulWithWork spacing.bits (binaryNaturalDivModWithWork position spacing).1).2 + 2 ≤ _ + nlinarith only [hd, hm, Nat.zero_le (Nat.size spacing), Nat.zero_le (Nat.size position)] + + + +theorem binaryIntervalRoundWithWork_value {n : ℕ} (spacing : ℕ) (hspacing : 0 < spacing) + (q : TargetInterval n) : + (bitWordValue (binaryIntervalRoundWithWork spacing q.lo q.hi).1.1, + bitWordValue (binaryIntervalRoundWithWork spacing q.lo q.hi).1.2) = + ((roundInterval spacing q).lo, (roundInterval spacing q).hi) := by + simp only [binaryIntervalRoundWithWork, binaryGridRoundWithWork_value _ _ hspacing, + roundInterval] + +theorem binaryIntervalRoundWithWork_cost (spacing lo hi B : ℕ) + (hs : Nat.size spacing ≤ B) (hl : Nat.size lo ≤ B) (hh : Nat.size hi ≤ B) : + (binaryIntervalRoundWithWork spacing lo hi).2 ≤ 500 * (B + 1) ^ 2 := by + have hleft := binaryGridRoundWithWork_cost spacing lo + have hright := binaryGridRoundWithWork_cost spacing hi + have hfirst := Nat.mul_self_le_mul_self (show Nat.size spacing + Nat.size lo + 1 ≤ 2 * B + 1 by omega) + have hsecond := Nat.mul_self_le_mul_self (show Nat.size spacing + Nat.size hi + 1 ≤ 2 * B + 1 by omega) + simp only [← pow_two] at hfirst hsecond + change (binaryGridRoundWithWork spacing lo).2 + (binaryGridRoundWithWork spacing hi).2 + 1 ≤ _ + nlinarith only [hleft, hright, hfirst, hsecond, Nat.zero_le B] + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryGroupActionReads.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryGroupActionReads.lean new file mode 100644 index 0000000000000000000000000000000000000000..31aaab8afb93e36e752d993e00e14c2dc040c5da --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryGroupActionReads.lean @@ -0,0 +1,80 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryGroupReads +import OAI.Combinatorics.EditApproximation.Binary.BinaryDyadicSampledGroups + +namespace OAI + +/-! The selected group action uses the same minimizing member and rounded +endpoints, while charging both the initial and current-table readers. -/ + +namespace EditApproximation +namespace BinaryFraction + +section Group +variable {α : Type*} (source target : List α) {M T : ℕ} + (parent : TargetInterval source.length) (b P exponent Q : ℕ) + (tau F : BinaryFraction) + (child : Fin M → TargetInterval target.length → BinaryFraction) + (initial current : Fin M → TargetInterval target.length → BinaryFraction × ℕ) + (scales : Fin T → BinaryFraction) + (draw : ∀ t, Fin (groupSampleCount M Q b (scales t).value) → Fin M) + +local notation "Member" => UnskippedBand source target parent b P exponent + (BinaryFraction.value tau) (BinaryFraction.value F) + (fun i q => BinaryFraction.value (child i q)) + (fun i q => BinaryFraction.value (Prod.fst (initial i q))) + +def sampledGroupActionReadWithWork (members : List Member) (hne : members ≠ []) : + BinaryBellmanAction (TargetInterval target.length) (Fin M × TargetInterval target.length) M × ℕ := + let selected := chooseUnskippedReadWithWork source target parent b P exponent Q tau F + child initial current scales draw members hne + let rounded := roundedBandReadWithWork exponent b selected.1.actions selected.1.nonempty initial + let result := endpointActionWithWork selected.1.center rounded.1.get + (result.1, selected.2 + rounded.2 + result.2 + 3) + +theorem sampledGroupActionReadWithWork_eq_cost (members : List Member) (hne : members ≠ []) (R C : ℕ) + (hi : ∀ i q, (initial i q).2 ≤ C) (hr : ∀ i q, (current i q).2 ≤ R) : + (sampledGroupActionReadWithWork source target parent b P exponent Q tau F child initial current + scales draw members hne).1 = + (sampledGroupActionWithWork source target parent b P exponent Q tau F child + (fun i q => (initial i q).1) (fun i q => (current i q).1) scales draw members hne).1 ∧ + (sampledGroupActionReadWithWork source target parent b P exponent Q tau F child initial current + scales draw members hne).2 ≤ + (sampledGroupActionWithWork source target parent b P exponent Q tau F child + (fun i q => (initial i q).1) (fun i q => (current i q).1) scales draw members hne).2 + + (members.map fun member => M * (member.actions.length * (C + 3)) + + M * (member.actions.length * (C + 3)) + M * R).sum + + M * (((chooseBinaryUnskippedWithWork source target parent b P exponent Q tau F child + (fun i q => (initial i q).1) (fun i q => (current i q).1) scales draw members hne).1.actions).length * + (C + 3)) := by + have hs := chooseUnskippedReadWithWork_eq_cost source target parent b P exponent Q tau F + child initial current scales draw members hne R C hi hr + have hp := roundedBandReadWithWork_eq_cost exponent b + (chooseBinaryUnskippedWithWork source target parent b P exponent Q tau F child + (fun i q => (initial i q).1) (fun i q => (current i q).1) scales draw members hne).1.actions + (chooseBinaryUnskippedWithWork source target parent b P exponent Q tau F child + (fun i q => (initial i q).1) (fun i q => (current i q).1) scales draw members hne).1.nonempty initial C hi + unfold sampledGroupActionReadWithWork sampledGroupActionWithWork + dsimp only + simp only [hs.1, hp.1] + exact ⟨trivial, by omega⟩ + +end Group + +def dyadicSampledGroupActionReadWithWork {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (b P exponent Q : ℕ) (tau F : BinaryFraction) + (child : Fin M → TargetInterval target.length → BinaryFraction) + (initial current : Fin M → TargetInterval target.length → BinaryFraction × ℕ) + (raw : List BinaryFraction) (hraw : raw.map value = groupDyadicScales M b F.value) + (draw : ∀ t : Fin (groupDyadicScales M b F.value).length, + Fin (groupSampleCount M Q b (groupDyadicScaleAt M b F.value t)) → Fin M) + (members : List (UnskippedBand source target parent b P exponent tau.value F.value + (fun i q => (child i q).value) (fun i q => (initial i q).1.value))) (hne : members ≠ []) := + sampledGroupActionReadWithWork source target parent b P exponent Q tau F child initial current + (indexedGroupScales raw M b F.value hraw) + (fun t j => draw t (Fin.cast (congrArg (groupSampleCount M Q b) + (indexedGroupScales_value raw M b F.value hraw t)) j)) members hne + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryGroupActionSourceSpace.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryGroupActionSourceSpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..9e28e3020db36d628c410c45c5b78aa74368e5d7 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryGroupActionSourceSpace.lean @@ -0,0 +1,104 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryGroupSourceSpace +import OAI.Combinatorics.EditApproximation.Queries.QueryContinuationSpace +import OAI.Combinatorics.EditApproximation.Binary.BinaryRoundingSpace +import OAI.Combinatorics.EditApproximation.Binary.BinarySampledSourcePort + +namespace OAI + +namespace EditApproximation.BinaryFraction + +section Group +variable {α : Type*} (source target : List α) {M T : ℕ} + (parent : TargetInterval source.length) (b P exponent Q : ℕ) + (tau F : BinaryFraction) (child : Fin M → TargetInterval target.length → BinaryFraction) + (initial current : Fin M → TargetInterval target.length → BinaryFraction × ℕ) + (initialAllocation currentAllocation : Fin M → TargetInterval target.length → ℕ) + (scales : Fin T → BinaryFraction) + (draw : ∀ t, Fin (groupSampleCount M Q b (scales t).value) → Fin M × ℕ) + (drawAllocation : ∀ t, Fin (groupSampleCount M Q b (scales t).value) → ℕ) + +local notation "Member" => UnskippedBand source target parent b P exponent + (BinaryFraction.value tau) (BinaryFraction.value F) + (fun i q => BinaryFraction.value (child i q)) + (fun i q => BinaryFraction.value (Prod.fst (initial i q))) + +def unskippedEstimateSourceAllocation (member : Member) : ℕ := + let mass := (envelopeVectorReadWithWork b member.actions initial).1 + let rounded := (roundedBandReadWithWork exponent b member.actions member.nonempty initial).1 + let values := (vectorMapWithWork M (fun i => current i (rounded.get i))).1 + let connection := (endpointConnectionWithWork member.center rounded.get).1 + envelopeVectorReadAllocation b member.actions initial initialAllocation + + roundedBandReadAllocation exponent b member.actions member.nonempty initial initialAllocation + + vectorMapAllocation M (fun i => currentAllocation i (rounded.get i)) + + endpointConnectionAllocation member.center rounded.get + countedGroupMemberSourceAllocation Q b scales connection mass values draw drawAllocation + +theorem unskippedEstimateSourceAllocation_le_work (member : Member) + (hi : ∀ i q, initialAllocation i q ≤ (initial i q).2) + (hc : ∀ i q, currentAllocation i q ≤ (current i q).2) + (ha : ∀ t i, drawAllocation t i ≤ (draw t i).2) : + unskippedEstimateSourceAllocation source target parent b P exponent Q tau F child initial current + initialAllocation currentAllocation scales draw drawAllocation member ≤ + (unskippedEstimateSourceWithWork source target parent b P exponent Q tau F child initial current scales draw member).2 := by + let mass := (envelopeVectorReadWithWork b member.actions initial).1 + let rounded := (roundedBandReadWithWork exponent b member.actions member.nonempty initial).1 + let values := (vectorMapWithWork M (fun i => current i (rounded.get i))).1 + have he := envelopeVectorReadAllocation_le_work b member.actions initial initialAllocation (fun i action _ => hi i (action i)) + have hr := roundedBandReadAllocation_le_work exponent b member.actions member.nonempty initial initialAllocation hi + have hv := vectorMapAllocation_le_work M (fun i => current i (rounded.get i)) + (fun i => currentAllocation i (rounded.get i)) (fun i => hc i (rounded.get i)) + have hg := endpointConnectionAllocation_le_work member.center rounded.get + have hm := countedGroupMemberSourceAllocation_le_work Q b scales + (endpointConnectionWithWork member.center rounded.get).1 mass values draw drawAllocation ha + unfold unskippedEstimateSourceAllocation unskippedEstimateSourceWithWork + dsimp only [mass, rounded, values] at hv hg hm ⊢ + omega + +def chooseUnskippedSourceAllocation (members : List Member) : ℕ := + selectGroupAllocation members + (unskippedEstimateSourceWithWork source target parent b P exponent Q tau F child initial current scales draw) + (unskippedEstimateSourceAllocation source target parent b P exponent Q tau F child initial current + initialAllocation currentAllocation scales draw drawAllocation) + +theorem chooseUnskippedSourceAllocation_le_work (members : List Member) (hne : members ≠ []) + (hi : ∀ i q, initialAllocation i q ≤ (initial i q).2) + (hc : ∀ i q, currentAllocation i q ≤ (current i q).2) + (ha : ∀ t i, drawAllocation t i ≤ (draw t i).2) : + chooseUnskippedSourceAllocation source target parent b P exponent Q tau F child initial current + initialAllocation currentAllocation scales draw drawAllocation members ≤ + (chooseUnskippedSourceWithWork source target parent b P exponent Q tau F child initial current scales draw members hne).2 := + selectGroupAllocation_le_work members hne _ _ (fun member _ => + unskippedEstimateSourceAllocation_le_work source target parent b P exponent Q tau F child initial current + initialAllocation currentAllocation scales draw drawAllocation member hi hc ha) + +def sampledGroupActionSourceAllocation (members : List Member) (hne : members ≠ []) : ℕ := + let selected := (chooseUnskippedSourceWithWork source target parent b P exponent Q tau F child initial current + scales draw members hne).1 + let rounded := (roundedBandReadWithWork exponent b selected.actions selected.nonempty initial).1 + chooseUnskippedSourceAllocation source target parent b P exponent Q tau F child initial current + initialAllocation currentAllocation scales draw drawAllocation members + + roundedBandReadAllocation exponent b selected.actions selected.nonempty initial initialAllocation + + endpointActionAllocation selected.center rounded.get + +theorem sampledGroupActionSourceAllocation_le_work (members : List Member) (hne : members ≠ []) + (hi : ∀ i q, initialAllocation i q ≤ (initial i q).2) + (hc : ∀ i q, currentAllocation i q ≤ (current i q).2) + (ha : ∀ t i, drawAllocation t i ≤ (draw t i).2) : + sampledGroupActionSourceAllocation source target parent b P exponent Q tau F child initial current + initialAllocation currentAllocation scales draw drawAllocation members hne ≤ + (sampledGroupActionSourceWithWork source target parent b P exponent Q tau F child initial current scales draw members hne).2 := by + let selected := (chooseUnskippedSourceWithWork source target parent b P exponent Q tau F child initial current + scales draw members hne).1 + have hs := chooseUnskippedSourceAllocation_le_work source target parent b P exponent Q tau F child initial current + initialAllocation currentAllocation scales draw drawAllocation members hne hi hc ha + have hr := roundedBandReadAllocation_le_work exponent b selected.actions selected.nonempty initial initialAllocation hi + have ha := endpointActionAllocation_le_work selected.center + (roundedBandReadWithWork exponent b selected.actions selected.nonempty initial).1.get + unfold sampledGroupActionSourceAllocation sampledGroupActionSourceWithWork + dsimp only [selected] at hr ha ⊢ + omega + +end Group + +end EditApproximation.BinaryFraction + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryGroupKernel.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryGroupKernel.lean new file mode 100644 index 0000000000000000000000000000000000000000..05c2cd6f6e36b60df85b38a2e42c00f78d834bfa --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryGroupKernel.lean @@ -0,0 +1,246 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryBellmanKernel +import OAI.Combinatorics.EditApproximation.Geometry.BandGroupSampling +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Literal group estimates on gathered stored fractions. Each child/scale +comparison is executed, the supplied draw indices are reused, and ordered +selection uses the same tie rule as the mathematical group program. -/ + +namespace EditApproximation +namespace BinaryFraction + +open Finset + + + +@[simp] theorem equalWithWork_value (a b : BinaryFraction) : + (equalWithWork a b).1 = true ↔ a.value = b.value := by + simp only [equalWithWork, Bool.and_eq_true, leWithWork_value] + exact ⟨fun h => le_antisymm h.1 h.2, fun h => ⟨h.le, h.ge⟩⟩ + +theorem equalWithWork_cost (a b : BinaryFraction) (B : ℕ) (ha : a.width ≤ B) (hb : b.width ≤ B) : + (equalWithWork a b).2 ≤ 2 * (1000 * (B + 1) ^ 2 + 1) + 1 := by + have hl := leWithWork_cost a b B ha hb + have hr := leWithWork_cost b a B hb ha + change _ + _ + 1 ≤ _ + omega + + + +@[simp] theorem groupTermsWithWork_value {M : ℕ} (h : BinaryFraction) + (envelope values : Vector BinaryFraction M) (indices : List (Fin M)) : + ((groupTermsWithWork h envelope values indices).1.map value) = + indices.map (fun i => if (envelope.get i).value = h.value then (values.get i).value else 0) := by + simp only [groupTermsWithWork, arithmeticMapWithWork_value, List.map_map, Function.comp_def] + apply List.map_congr_left + intro i _ + by_cases hi : (envelope.get i).value = h.value + · have ht := (equalWithWork_value (envelope.get i) h).mpr hi + simp only [ht, ↓reduceIte, hi] + · have ht : (equalWithWork (envelope.get i) h).1 = false := + Bool.eq_false_iff.mpr (fun h => hi ((equalWithWork_value _ _).mp h)) + simp only [ht, Bool.false_eq_true, ↓reduceIte, hi] + rw [← representation_value, zero_representation, UnreducedRational.value_zero] + + + +@[simp] theorem groupIndexWithWork_value {M : ℕ} (h : BinaryFraction) + (envelope values : Vector BinaryFraction M) (indices : List (Fin M)) : + (groupIndexWithWork h envelope values indices).1.value = + (indices.map fun i => if (envelope.get i).value = h.value then (values.get i).value else 0).sum := by + simp only [groupIndexWithWork, sumListWithWork_value, groupTermsWithWork_value] + +def groupIndexBitBudget (n B : ℕ) : ℕ := + n * (2 * (1000 * (B + 1) ^ 2 + 1) + 6) + storedSumBitBudget n B + 6 * n + 1 + +theorem groupIndexWithWork_bounds {M : ℕ} (h : BinaryFraction) + (envelope values : Vector BinaryFraction M) (indices : List (Fin M)) (B : ℕ) + (hB : 1 ≤ B) (hh : h.width ≤ B) (he : ∀ i, (envelope.get i).width ≤ B) + (hv : ∀ i, (values.get i).width ≤ B) : + (groupIndexWithWork h envelope values indices).1.width ≤ bandMassTotalStorageBudget indices.length B ∧ + (groupIndexWithWork h envelope values indices).2 ≤ groupIndexBitBudget indices.length B := by + have hwidth : ∀ a ∈ (groupTermsWithWork h envelope values indices).1, a.width ≤ B := by + intro a ha + simp only [groupTermsWithWork, arithmeticMapWithWork_value] at ha + obtain ⟨i, _, heq⟩ := List.mem_map.mp ha + subst a + split_ifs + · exact hv i + · exact hB + have hlen : (groupTermsWithWork h envelope values indices).1.length = indices.length := by + simp only [groupTermsWithWork, arithmeticMapWithWork_value, List.length_map] + have hw := sumListWithWork_width _ B hwidth + have hc := sumListWithWork_cost _ B hwidth + rw [hlen] at hw hc + have ht : (groupTermsWithWork h envelope values indices).2 ≤ + indices.length * (2 * (1000 * (B + 1) ^ 2 + 1) + 6) := by + apply arithmeticMapWithWork_cost + intro i _ + have h := equalWithWork_cost (envelope.get i) h B (he i) hh + change _ + 2 ≤ _ + omega + refine ⟨hw, ?_⟩ + change _ + _ + 1 ≤ _ + unfold groupIndexBitBudget + omega + +def groupScaleWithWork {M : ℕ} (k : ℕ) (h : BinaryFraction) + (envelope values : Vector BinaryFraction M) (draw : Fin k → Fin M) : BinaryFraction × ℕ := + let indices := if k = M then List.finRange M else (List.finRange k).map draw + let subtotal := groupIndexWithWork h envelope values indices + let factor := if k = M then (one, 1) else divWithWork (nat M) (nat k) + let result := canonicalMulWithWork factor.1 subtotal.1 + (result.1, subtotal.2 + factor.2 + result.2 + Nat.size M + Nat.size k + 3) + +@[simp] theorem groupScaleWithWork_value {M : ℕ} (k : ℕ) (h : BinaryFraction) + (envelope values : Vector BinaryFraction M) (draw : Fin k → Fin M) : + (groupScaleWithWork k h envelope values draw).1.value = + groupScaleEstimate k h.value (fun i => (envelope.get i).value) (fun i => (values.get i).value) draw := by + unfold groupScaleWithWork groupScaleEstimate + split_ifs with heq + · simp only [canonicalMulWithWork_value, groupIndexWithWork_value, one, nat_value, Nat.cast_one, one_mul] + simp only [groupScaleTrueCost, ← List.ofFn_eq_map, List.sum_ofFn] + · simp only [canonicalMulWithWork_value, groupIndexWithWork_value, divWithWork_value, nat_value, + List.map_map, Function.comp_def] + rw [← List.ofFn_eq_map, List.sum_ofFn] + +def groupScaleTermCount (M k : ℕ) : ℕ := if k = M then M else k + +def groupScaleWordBudget (M k B : ℕ) : ℕ := + 4 * (4 * B + 4 + bandMassTotalStorageBudget (groupScaleTermCount M k) B) + 2 + +def groupScaleBitBudget (M k B : ℕ) : ℕ := + groupIndexBitBudget (groupScaleTermCount M k) B + (2100 * (B + 2) ^ 2 + 1) + + 2000 * (4 * B + 4 + bandMassTotalStorageBudget (groupScaleTermCount M k) B + 1) ^ 2 + 2 * B + 3 + +theorem groupScaleWithWork_bounds {M : ℕ} (k : ℕ) (h : BinaryFraction) + (envelope values : Vector BinaryFraction M) (draw : Fin k → Fin M) (B : ℕ) + (hB : 1 ≤ B) (hh : h.width ≤ B) (he : ∀ i, (envelope.get i).width ≤ B) + (hv : ∀ i, (values.get i).width ≤ B) (hM : Nat.size M + 2 ≤ B) (hk : Nat.size k + 2 ≤ B) : + (groupScaleWithWork k h envelope values draw).1.width ≤ groupScaleWordBudget M k B ∧ + (groupScaleWithWork k h envelope values draw).2 ≤ groupScaleBitBudget M k B := by + let indices := if k = M then List.finRange M else (List.finRange k).map draw + let factor : BinaryFraction × ℕ := if k = M then (one, 1) else divWithWork (nat M) (nat k) + have hlen : indices.length = groupScaleTermCount M k := by + dsimp only [indices, groupScaleTermCount] + split_ifs <;> simp only [List.length_finRange, List.length_map] + obtain ⟨hsw, hsc⟩ := groupIndexWithWork_bounds h envelope values indices B hB hh he hv + rw [hlen] at hsw hsc + have hfw : factor.1.width ≤ 4 * B + 4 := by + dsimp only [factor] + split_ifs + · change 1 ≤ 4 * B + 4 + omega + · exact divWithWork_width_uniform _ _ B ((nat_width_le _).trans hM) ((nat_width_le _).trans hk) + have hfc : factor.2 ≤ 2100 * (B + 2) ^ 2 + 1 := by + dsimp only [factor] + split_ifs + · omega + · exact (divWithWork_cost _ _ B ((nat_width_le _).trans hM) + ((nat_width_le _).trans hk)).trans (Nat.le_succ _) + have hrw := canonicalMulWithWork_width factor.1 (groupIndexWithWork h envelope values indices).1 + (4 * B + 4 + bandMassTotalStorageBudget (groupScaleTermCount M k) B) (by omega) (by omega) + have hrc := canonicalMulWithWork_cost factor.1 (groupIndexWithWork h envelope values indices).1 + (4 * B + 4 + bandMassTotalStorageBudget (groupScaleTermCount M k) B) (by omega) (by omega) + refine ⟨hrw, ?_⟩ + change (groupIndexWithWork h envelope values indices).2 + factor.2 + + (canonicalMulWithWork factor.1 (groupIndexWithWork h envelope values indices).1).2 + + Nat.size M + Nat.size k + 3 ≤ _ + unfold groupScaleBitBudget + omega + +/-- Every scale is accumulated using the same finite child arrays. -/ +def groupMemberWithWork {M T : ℕ} (scales : Fin T → BinaryFraction) (count : Fin T → ℕ) + (connection : BinaryFraction) (envelope values : Vector BinaryFraction M) + (draw : ∀ s : Fin T, Fin (count s) → Fin M) : BinaryFraction × ℕ := + let terms := arithmeticMapWithWork (fun s => groupScaleWithWork (count s) (scales s) + envelope values (draw s)) (List.finRange T) + let subtotal := sumListWithWork terms.1 + let result := canonicalAddWithWork connection subtotal.1 + (result.1, terms.2 + subtotal.2 + result.2 + 1) + +@[simp] theorem groupMemberWithWork_value {M T : ℕ} (scales : Fin T → BinaryFraction) + (count : Fin T → ℕ) (connection : BinaryFraction) (envelope values : Vector BinaryFraction M) + (draw : ∀ s : Fin T, Fin (count s) → Fin M) : + (groupMemberWithWork scales count connection envelope values draw).1.value = + groupMemberEstimate (fun s => (scales s).value) count connection.value + (fun i => (envelope.get i).value) (fun i => (values.get i).value) draw := by + simp only [groupMemberWithWork, canonicalAddWithWork_value, sumListWithWork_value, + arithmeticMapWithWork_value, List.map_map, Function.comp_def, groupScaleWithWork_value, + groupMemberEstimate] + rw [← List.ofFn_eq_map, List.sum_ofFn] + +def groupMemberWordBudget (T B W : ℕ) : ℕ := + 8 * (B + bandMassTotalStorageBudget T W) + 6 + +def groupMemberBitBudget (T B C W : ℕ) : ℕ := + T * (C + 3) + storedSumBitBudget T W + 6 * T + + 6000 * (B + bandMassTotalStorageBudget T W + 1) ^ 2 + 1 + +theorem groupMemberWithWork_bounds {M T : ℕ} (scales : Fin T → BinaryFraction) + (count : Fin T → ℕ) (connection : BinaryFraction) (envelope values : Vector BinaryFraction M) + (draw : ∀ s : Fin T, Fin (count s) → Fin M) (B C W : ℕ) + (hb : connection.width ≤ B) + (hc : ∀ s, (groupScaleWithWork (count s) (scales s) envelope values (draw s)).2 ≤ C) + (hw : ∀ s, (groupScaleWithWork (count s) (scales s) envelope values (draw s)).1.width ≤ W) : + (groupMemberWithWork scales count connection envelope values draw).1.width ≤ groupMemberWordBudget T B W ∧ + (groupMemberWithWork scales count connection envelope values draw).2 ≤ groupMemberBitBudget T B C W := by + let terms := arithmeticMapWithWork (fun s => groupScaleWithWork (count s) (scales s) + envelope values (draw s)) (List.finRange T) + have hlen : terms.1.length = T := by + simp only [terms, arithmeticMapWithWork_value, List.length_map, List.length_finRange] + have hterms : ∀ a ∈ terms.1, a.width ≤ W := by + intro a ha + simp only [terms, arithmeticMapWithWork_value] at ha + obtain ⟨s, _, heq⟩ := List.mem_map.mp ha + subst a + exact hw s + have htw := sumListWithWork_width terms.1 W hterms + have htc := sumListWithWork_cost terms.1 W hterms + rw [hlen] at htw htc + have hmc := arithmeticMapWithWork_cost (fun s => groupScaleWithWork (count s) (scales s) + envelope values (draw s)) (List.finRange T) C (fun s _ => hc s) + simp only [List.length_finRange] at hmc + have hrw := canonicalAddWithWork_width connection (sumListWithWork terms.1).1 + (B + bandMassTotalStorageBudget T W) (by omega) (by omega) + have hrc := canonicalAddWithWork_cost connection (sumListWithWork terms.1).1 + (B + bandMassTotalStorageBudget T W) (by omega) (by omega) + refine ⟨hrw, ?_⟩ + change terms.2 + (sumListWithWork terms.1).2 + (canonicalAddWithWork connection + (sumListWithWork terms.1).1).2 + 1 ≤ _ + unfold groupMemberBitBudget + change terms.2 ≤ T * (C + 3) at hmc + omega + + + +@[simp] theorem selectGroupWithWork_value {ι : Type*} (members : List ι) (hne : members ≠ []) + (estimate : ι → BinaryFraction × ℕ) : + (selectGroupWithWork members hne estimate).1 = + selectGroupMember members hne (fun member => (estimate member).1.value) := by + simp only [selectGroupWithWork, scoredArgmaxWithWork_value, neg_value, + Option.map_map, Function.comp_def, selectGroupMember] + congr 1 + cases members.argmax (fun member => -(estimate member).1.value) <;> rfl + +theorem selectGroupWithWork_cost {ι : Type*} (members : List ι) (hne : members ≠ []) + (estimate : ι → BinaryFraction × ℕ) (C W : ℕ) + (hc : ∀ member ∈ members, (estimate member).2 ≤ C) + (hw : ∀ member ∈ members, (estimate member).1.width ≤ W) : + (selectGroupWithWork members hne estimate).2 ≤ + members.length * (C + 1000 * (W + 1) ^ 2 + 3) + 1 := by + have h := scoredArgmaxWithWork_cost (fun member => ((estimate member).1.neg, (estimate member).2 + 1)) + members (C + 1) W (by intro member hm; have := hc member hm; omega) + (by intro member hm; simpa only [neg_width] using hw member hm) + change _ + 1 ≤ _ + have heq : (C + 1) + 1000 * (W + 1) ^ 2 + 2 = C + 1000 * (W + 1) ^ 2 + 3 := by omega + rw [heq] at h + exact Nat.add_le_add_right h 1 + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryGroupMemberSource.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryGroupMemberSource.lean new file mode 100644 index 0000000000000000000000000000000000000000..3acfdd8f5369d6eeb8324c6b2ac7f20b659229df --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryGroupMemberSource.lean @@ -0,0 +1,93 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryGroupSourcePort +import OAI.Combinatorics.EditApproximation.Binary.BinaryReadCostBounds +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation + +namespace BinaryFraction + + + +theorem groupMemberSourceWithWork_value {M T : ℕ} (scales : Fin T → BinaryFraction) + (count : Fin T → ℕ) (connection : BinaryFraction) (envelope values : Vector BinaryFraction M) + (draw : ∀ s : Fin T, Fin (count s) → Fin M × ℕ) : + (groupMemberSourceWithWork scales count connection envelope values draw).1 = + (groupMemberWithWork scales count connection envelope values (fun s i => (draw s i).1)).1 := by + simp only [groupMemberSourceWithWork, groupMemberWithWork, arithmeticMapWithWork_value, + groupScaleSourceWithWork_value] + +theorem groupMemberSourceWithWork_eq_cost {M T : ℕ} (scales : Fin T → BinaryFraction) + (count : Fin T → ℕ) (connection : BinaryFraction) (envelope values : Vector BinaryFraction M) + (draw : ∀ s : Fin T, Fin (count s) → Fin M × ℕ) (R : ℕ) + (hr : ∀ s i, (draw s i).2 ≤ R) : + (groupMemberSourceWithWork scales count connection envelope values draw).1 = + (groupMemberWithWork scales count connection envelope values (fun s i => (draw s i).1)).1 ∧ + (groupMemberSourceWithWork scales count connection envelope values draw).2 ≤ + (groupMemberWithWork scales count connection envelope values (fun s i => (draw s i).1)).2 * (R + 4) := by + have hm := arithmeticMapWithWork_factor + (fun s => groupScaleSourceWithWork (count s) (scales s) envelope values (draw s)) + (fun s => groupScaleWithWork (count s) (scales s) envelope values (fun i => (draw s i).1)) + (List.finRange T) (R + 4) (by omega) + (fun s _ => groupScaleSourceWithWork_value _ _ _ _ _) + (fun s _ => groupScaleSourceWithWork_cost _ _ _ _ _ R (hr s)) + unfold groupMemberSourceWithWork groupMemberWithWork + dsimp only + rw [hm.1] + exact ⟨rfl, by nlinarith only [hm.2]⟩ + + + +theorem groupMemberSourceWithWork_transport {M T : ℕ} + (scales : Fin T → BinaryFraction) (left right : Fin T → ℕ) (h : ∀ t, left t = right t) + (connection : BinaryFraction) (envelope values : Vector BinaryFraction M) + (draw : ∀ t, Fin (right t) → Fin M × ℕ) : + groupMemberSourceWithWork scales left connection envelope values (fun t j => draw t (Fin.cast (h t) j)) = + groupMemberSourceWithWork scales right connection envelope values draw := by + have heq : left = right := funext h + subst right + rfl + +theorem countedGroupMemberSourceWithWork_eq_cost {M T : ℕ} (Q b : ℕ) + (scales : Fin T → BinaryFraction) (connection : BinaryFraction) + (envelope values : Vector BinaryFraction M) + (draw : ∀ t, Fin (groupSampleCount M Q b (scales t).value) → Fin M × ℕ) + (R : ℕ) (hr : ∀ t i, (draw t i).2 ≤ R) : + (countedGroupMemberSourceWithWork Q b scales connection envelope values draw).1 = + (countedGroupMemberWithWork Q b scales connection envelope values (fun t i => (draw t i).1)).1 ∧ + (countedGroupMemberSourceWithWork Q b scales connection envelope values draw).2 ≤ + (countedGroupMemberWithWork Q b scales connection envelope values (fun t i => (draw t i).1)).2 * (R + 4) := by + let counts := vectorMapWithWork T fun t => groupSampleCountWithWork M Q b (scales t) + let count := fun t => bitWordValue (counts.1.get t) + have heq : ∀ t, count t = groupSampleCount M Q b (scales t).value := by + intro t + simp only [count, counts, vectorMapWithWork_value, groupSampleCountWithWork_value] + have hm := groupMemberSourceWithWork_eq_cost scales count connection envelope values + (fun t j => draw t (Fin.cast (heq t) j)) R (fun t j => hr t _) + unfold countedGroupMemberSourceWithWork countedGroupMemberWithWork + dsimp only + change _ = (groupMemberWithWork scales count connection envelope values + (fun t j => (draw t (Fin.cast (heq t) j)).1)).1 ∧ _ + rw [hm.1] + exact ⟨rfl, by nlinarith only [hm.2]⟩ + +theorem countedGroupMemberSourceWithWork_value {M T : ℕ} (Q b : ℕ) + (scales : Fin T → BinaryFraction) (connection : BinaryFraction) + (envelope values : Vector BinaryFraction M) + (draw : ∀ t, Fin (groupSampleCount M Q b (scales t).value) → Fin M × ℕ) : + (countedGroupMemberSourceWithWork Q b scales connection envelope values draw).1 = + (countedGroupMemberWithWork Q b scales connection envelope values (fun t i => (draw t i).1)).1 := by + let counts := vectorMapWithWork T fun t => groupSampleCountWithWork M Q b (scales t) + let count := fun t => bitWordValue (counts.1.get t) + have heq : ∀ t, count t = groupSampleCount M Q b (scales t).value := by + intro t + simp only [count, counts, vectorMapWithWork_value, groupSampleCountWithWork_value] + exact groupMemberSourceWithWork_value scales count connection envelope values + (fun t j => draw t (Fin.cast (heq t) j)) + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryGroupReadCosts.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryGroupReadCosts.lean new file mode 100644 index 0000000000000000000000000000000000000000..28edf30ce49f3de1e2facb54a1a923cdcc0e8767 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryGroupReadCosts.lean @@ -0,0 +1,142 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryBandReadCosts +import OAI.Combinatorics.EditApproximation.Binary.BinaryGroupActionReads + +namespace OAI + +/-! Exact group score scans charge the finite-buffer readers through the +same loops as their arithmetic-only counterparts. -/ + +namespace EditApproximation +namespace BinaryFraction + +theorem scoredArgmaxWithWork_factor {α : Type*} (read plain : α → BinaryFraction × ℕ) + (xs : List α) (K : ℕ) (hK : 1 ≤ K) + (hv : ∀ x ∈ xs, (read x).1 = (plain x).1) + (hc : ∀ x ∈ xs, (read x).2 ≤ (plain x).2 * K) : + (scoredArgmaxWithWork read xs).1 = (scoredArgmaxWithWork plain xs).1 ∧ + (scoredArgmaxWithWork read xs).2 ≤ (scoredArgmaxWithWork plain xs).2 * K := by + induction xs with + | nil => exact ⟨rfl, by simp only [scoredArgmaxWithWork, Nat.zero_mul, le_refl]⟩ + | cons x xs ih => + have hx := hv x List.mem_cons_self + have hcx := hc x List.mem_cons_self + have ht := ih (fun y hy => hv y (List.mem_cons_of_mem _ hy)) + (fun y hy => hc y (List.mem_cons_of_mem _ hy)) + have h := Nat.add_le_add ht.2 hcx + rw [← Nat.add_mul] at h + simp only [scoredArgmaxWithWork, ht.1, hx] + cases (scoredArgmaxWithWork plain xs).1 with + | none => + refine ⟨rfl, ?_⟩ + dsimp only + apply cost_replace_factor _ _ _ _ _ h hK <;> omega + | some best => + refine ⟨rfl, ?_⟩ + dsimp only + apply cost_replace_factor _ _ _ _ _ h hK <;> omega + +theorem selectGroupWithWork_factor {α : Type*} (read plain : α → BinaryFraction × ℕ) + (xs : List α) (hne : xs ≠ []) (K : ℕ) (hK : 1 ≤ K) + (hv : ∀ x ∈ xs, (read x).1 = (plain x).1) + (hc : ∀ x ∈ xs, (read x).2 ≤ (plain x).2 * K) : + (selectGroupWithWork xs hne read).1 = (selectGroupWithWork xs hne plain).1 ∧ + (selectGroupWithWork xs hne read).2 ≤ (selectGroupWithWork xs hne plain).2 * K := by + have h := scoredArgmaxWithWork_factor + (fun x => ((read x).1.neg, (read x).2 + 1)) + (fun x => ((plain x).1.neg, (plain x).2 + 1)) xs K hK + (fun x hx => by rw [hv x hx]) (fun x hx => by + apply cost_replace_factor _ _ _ _ _ (hc x hx) hK <;> omega) + unfold selectGroupWithWork + dsimp only + rw [h.1] + refine ⟨rfl, ?_⟩ + apply cost_replace_factor _ _ _ _ _ h.2 hK <;> omega + +section Group +variable {α : Type*} (source target : List α) {M T : ℕ} + (parent : TargetInterval source.length) (b P exponent Q : ℕ) + (tau F : BinaryFraction) + (child : Fin M → TargetInterval target.length → BinaryFraction) + (initial current : Fin M → TargetInterval target.length → BinaryFraction × ℕ) + (scales : Fin T → BinaryFraction) + (draw : ∀ t, Fin (groupSampleCount M Q b (scales t).value) → Fin M) + +local notation "Member" => UnskippedBand source target parent b P exponent + (BinaryFraction.value tau) (BinaryFraction.value F) + (fun i q => BinaryFraction.value (child i q)) + (fun i q => BinaryFraction.value (Prod.fst (initial i q))) + +theorem unskippedEstimateReadWithWork_factor (member : Member) (R : ℕ) + (hi : ∀ i q, (initial i q).2 ≤ R) (hr : ∀ i q, (current i q).2 ≤ R) : + (unskippedEstimateReadWithWork source target parent b P exponent Q tau F child initial current + scales draw member).2 ≤ + (unskippedEstimateWithWork source target parent b P exponent Q tau F child + (fun i q => (initial i q).1) (fun i q => (current i q).1) scales draw member).2 * + tableReadFactor R := by + have hm := envelopeVectorReadWithWork_factor b member.actions initial R hi + have hmq := (envelopeVectorReadWithWork_eq_cost b member.actions initial R hi).1 + have hp := roundedBandReadWithWork_factor exponent b member.actions member.nonempty initial R hi + have hpq := (roundedBandReadWithWork_eq_cost exponent b member.actions member.nonempty initial R hi).1 + have hv := vectorMapWithWork_factor M + (fun i => current i ((roundedBandWithWork exponent b member.actions member.nonempty + (fun j q => (initial j q).1)).1.get i)) + (fun i => ((current i ((roundedBandWithWork exponent b member.actions member.nonempty + (fun j q => (initial j q).1)).1.get i)).1, 1)) + (tableReadFactor R) (tableReadFactor_pos R) (fun _ => rfl) + (fun i => by + change (current i _).2 ≤ 1 * tableReadFactor R + have hR : R ≤ tableReadFactor R := by unfold tableReadFactor; omega + simpa only [Nat.one_mul] using (hr i _).trans hR) + have h := Nat.add_le_add (Nat.add_le_add hm hp) hv.2 + simp only [← Nat.add_mul] at h + unfold unskippedEstimateReadWithWork unskippedEstimateWithWork + dsimp only + rw [hmq, hpq, hv.1] + apply cost_replace_factor _ _ _ _ _ h (tableReadFactor_pos R) <;> omega + +theorem chooseUnskippedReadWithWork_factor (members : List Member) (hne : members ≠ []) (R : ℕ) + (hi : ∀ i q, (initial i q).2 ≤ R) (hr : ∀ i q, (current i q).2 ≤ R) : + (chooseUnskippedReadWithWork source target parent b P exponent Q tau F child initial current + scales draw members hne).2 ≤ + (chooseBinaryUnskippedWithWork source target parent b P exponent Q tau F child + (fun i q => (initial i q).1) (fun i q => (current i q).1) scales draw members hne).2 * + tableReadFactor R := by + exact (selectGroupWithWork_factor _ _ members hne (tableReadFactor R) (tableReadFactor_pos R) + (fun member _ => (unskippedEstimateReadWithWork_eq_cost source target parent b P exponent Q + tau F child initial current scales draw member R R hi hr).1) + (fun member _ => unskippedEstimateReadWithWork_factor source target parent b P exponent Q + tau F child initial current scales draw member R hi hr)).2 + +theorem sampledGroupActionReadWithWork_factor (members : List Member) (hne : members ≠ []) (R : ℕ) + (hi : ∀ i q, (initial i q).2 ≤ R) (hr : ∀ i q, (current i q).2 ≤ R) : + (sampledGroupActionReadWithWork source target parent b P exponent Q tau F child initial current + scales draw members hne).2 ≤ + (sampledGroupActionWithWork source target parent b P exponent Q tau F child + (fun i q => (initial i q).1) (fun i q => (current i q).1) scales draw members hne).2 * + tableReadFactor R := by + have hc := chooseUnskippedReadWithWork_factor source target parent b P exponent Q tau F + child initial current scales draw members hne R hi hr + have hcq := (chooseUnskippedReadWithWork_eq_cost source target parent b P exponent Q tau F + child initial current scales draw members hne R R hi hr).1 + have hp := roundedBandReadWithWork_factor exponent b + (chooseBinaryUnskippedWithWork source target parent b P exponent Q tau F child + (fun i q => (initial i q).1) (fun i q => (current i q).1) scales draw members hne).1.actions + (chooseBinaryUnskippedWithWork source target parent b P exponent Q tau F child + (fun i q => (initial i q).1) (fun i q => (current i q).1) scales draw members hne).1.nonempty initial R hi + have hpq := (roundedBandReadWithWork_eq_cost exponent b + (chooseBinaryUnskippedWithWork source target parent b P exponent Q tau F child + (fun i q => (initial i q).1) (fun i q => (current i q).1) scales draw members hne).1.actions + (chooseBinaryUnskippedWithWork source target parent b P exponent Q tau F child + (fun i q => (initial i q).1) (fun i q => (current i q).1) scales draw members hne).1.nonempty initial R hi).1 + have h := Nat.add_le_add hc hp + rw [← Nat.add_mul] at h + unfold sampledGroupActionReadWithWork sampledGroupActionWithWork + dsimp only + simp only [hcq, hpq] + apply cost_replace_factor _ _ _ _ _ h (tableReadFactor_pos R) <;> omega + +end Group +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryGroupReads.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryGroupReads.lean new file mode 100644 index 0000000000000000000000000000000000000000..cf5f2e204ffbc12c4722b49fb1f6ebae76b7c5ea --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryGroupReads.lean @@ -0,0 +1,123 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryRoundedReads +import OAI.Combinatorics.EditApproximation.Binary.BinarySampledGroups + +namespace OAI + +/-! Group estimates and the ordered minimizing scan retain finite-table +lookup costs, using Fin-indexed source arrays. -/ + +namespace EditApproximation +namespace BinaryFraction + +theorem scoredArgmaxWithWork_extra {α : Type*} (read plain : α → BinaryFraction × ℕ) + (extra : α → ℕ) (xs : List α) + (hv : ∀ x ∈ xs, (read x).1 = (plain x).1) + (hc : ∀ x ∈ xs, (read x).2 ≤ (plain x).2 + extra x) : + (scoredArgmaxWithWork read xs).1 = (scoredArgmaxWithWork plain xs).1 ∧ + (scoredArgmaxWithWork read xs).2 ≤ + (scoredArgmaxWithWork plain xs).2 + (xs.map extra).sum := by + induction xs with + | nil => exact ⟨rfl, by simp only [scoredArgmaxWithWork, List.map_nil, List.sum_nil, + Nat.add_zero, le_refl]⟩ + | cons x xs ih => + have hx := hv x List.mem_cons_self + have hcx := hc x List.mem_cons_self + have ht := ih (fun y hy => hv y (List.mem_cons_of_mem _ hy)) + (fun y hy => hc y (List.mem_cons_of_mem _ hy)) + simp only [scoredArgmaxWithWork, ht.1, hx, List.map_cons, List.sum_cons] + cases (scoredArgmaxWithWork plain xs).1 with + | none => exact ⟨rfl, by dsimp only; omega⟩ + | some best => exact ⟨rfl, by dsimp only; omega⟩ + +theorem selectGroupWithWork_extra {α : Type*} (read plain : α → BinaryFraction × ℕ) + (extra : α → ℕ) (xs : List α) (hne : xs ≠ []) + (hv : ∀ x ∈ xs, (read x).1 = (plain x).1) + (hc : ∀ x ∈ xs, (read x).2 ≤ (plain x).2 + extra x) : + (selectGroupWithWork xs hne read).1 = (selectGroupWithWork xs hne plain).1 ∧ + (selectGroupWithWork xs hne read).2 ≤ + (selectGroupWithWork xs hne plain).2 + (xs.map extra).sum := by + have h := scoredArgmaxWithWork_extra + (fun x => ((read x).1.neg, (read x).2 + 1)) + (fun x => ((plain x).1.neg, (plain x).2 + 1)) extra xs + (fun x hx => by rw [hv x hx]) (fun x hx => by have := hc x hx; omega) + unfold selectGroupWithWork + dsimp only + rw [h.1] + exact ⟨rfl, by omega⟩ + +section Group +variable {α : Type*} (source target : List α) {M T : ℕ} + (parent : TargetInterval source.length) (b P exponent Q : ℕ) + (tau F : BinaryFraction) + (child : Fin M → TargetInterval target.length → BinaryFraction) + (initial current : Fin M → TargetInterval target.length → BinaryFraction × ℕ) + (scales : Fin T → BinaryFraction) + (draw : ∀ t, Fin (groupSampleCount M Q b (scales t).value) → Fin M) + +local notation "Member" => UnskippedBand source target parent b P exponent + (BinaryFraction.value tau) (BinaryFraction.value F) + (fun i q => BinaryFraction.value (child i q)) + (fun i q => BinaryFraction.value (Prod.fst (initial i q))) + +def unskippedEstimateReadWithWork (member : Member) : BinaryFraction × ℕ := + let mass := envelopeVectorReadWithWork b member.actions initial + let rounded := roundedBandReadWithWork exponent b member.actions member.nonempty initial + let values := vectorMapWithWork M fun i => current i (rounded.1.get i) + let connection := endpointConnectionWithWork member.center rounded.1.get + let result := countedGroupMemberWithWork Q b scales connection.1 mass.1 values.1 draw + (result.1, mass.2 + rounded.2 + values.2 + connection.2 + result.2 + 5) + +theorem unskippedEstimateReadWithWork_eq_cost (member : Member) (R C : ℕ) + (hi : ∀ i q, (initial i q).2 ≤ C) (hr : ∀ i q, (current i q).2 ≤ R) : + (unskippedEstimateReadWithWork source target parent b P exponent Q tau F child initial current + scales draw member).1 = + (unskippedEstimateWithWork source target parent b P exponent Q tau F child + (fun i q => (initial i q).1) (fun i q => (current i q).1) scales draw member).1 ∧ + (unskippedEstimateReadWithWork source target parent b P exponent Q tau F child initial current + scales draw member).2 ≤ + (unskippedEstimateWithWork source target parent b P exponent Q tau F child + (fun i q => (initial i q).1) (fun i q => (current i q).1) scales draw member).2 + + M * (member.actions.length * (C + 3)) + M * (member.actions.length * (C + 3)) + M * R := by + have hm := envelopeVectorReadWithWork_eq_cost b member.actions initial C hi + have hp := roundedBandReadWithWork_eq_cost exponent b member.actions member.nonempty initial C hi + have hv := vectorMapWithWork_extra M + (fun i => current i ((roundedBandWithWork exponent b member.actions member.nonempty + (fun j q => (initial j q).1)).1.get i)) + (fun i => ((current i ((roundedBandWithWork exponent b member.actions member.nonempty + (fun j q => (initial j q).1)).1.get i)).1, 1)) R (fun _ => rfl) + (fun i => by have := hr i ((roundedBandWithWork exponent b member.actions member.nonempty + (fun j q => (initial j q).1)).1.get i); omega) + unfold unskippedEstimateReadWithWork unskippedEstimateWithWork + dsimp only + rw [hm.1, hp.1, hv.1] + exact ⟨rfl, by omega⟩ + +def chooseUnskippedReadWithWork (members : List Member) (hne : members ≠ []) : Member × ℕ := + selectGroupWithWork members hne + (unskippedEstimateReadWithWork source target parent b P exponent Q tau F child initial current scales draw) + +theorem chooseUnskippedReadWithWork_eq_cost (members : List Member) (hne : members ≠ []) (R C : ℕ) + (hi : ∀ i q, (initial i q).2 ≤ C) (hr : ∀ i q, (current i q).2 ≤ R) : + (chooseUnskippedReadWithWork source target parent b P exponent Q tau F child initial current + scales draw members hne).1 = + (chooseBinaryUnskippedWithWork source target parent b P exponent Q tau F child + (fun i q => (initial i q).1) (fun i q => (current i q).1) scales draw members hne).1 ∧ + (chooseUnskippedReadWithWork source target parent b P exponent Q tau F child initial current + scales draw members hne).2 ≤ + (chooseBinaryUnskippedWithWork source target parent b P exponent Q tau F child + (fun i q => (initial i q).1) (fun i q => (current i q).1) scales draw members hne).2 + + (members.map fun member => M * (member.actions.length * (C + 3)) + + M * (member.actions.length * (C + 3)) + M * R).sum := by + exact selectGroupWithWork_extra _ _ _ members hne + (fun member _ => (unskippedEstimateReadWithWork_eq_cost source target parent b P exponent Q + tau F child initial current scales draw member R C hi hr).1) + (fun member _ => by + simpa only [Nat.add_assoc] using + (unskippedEstimateReadWithWork_eq_cost source target parent b P exponent Q + tau F child initial current scales draw member R C hi hr).2) + +end Group +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryGroupReductionSpace.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryGroupReductionSpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..42018b8deb15d7a52de7ca3a6458e916eca17e1c --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryGroupReductionSpace.lean @@ -0,0 +1,78 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryGroupSpace +import OAI.Combinatorics.EditApproximation.Binary.BinaryGroupReads +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation.BinaryFraction + +def groupMemberAllocation {M T : ℕ} (scales : Fin T → BinaryFraction) (count : Fin T → ℕ) + (connection : BinaryFraction) (envelope values : Vector BinaryFraction M) + (draw : ∀ s : Fin T, Fin (count s) → Fin M) : ℕ := + let terms := (arithmeticMapWithWork (fun s => groupScaleWithWork (count s) (scales s) + envelope values (draw s)) (List.finRange T)).1 + arithmeticMapAllocation (fun s => groupScaleAllocation (count s) (scales s) envelope values (draw s)) (List.finRange T) + + sumListAllocation terms + canonicalAddAllocation connection (sumListWithWork terms).1 + +theorem groupMemberAllocation_le_work {M T : ℕ} (scales : Fin T → BinaryFraction) (count : Fin T → ℕ) + (connection : BinaryFraction) (envelope values : Vector BinaryFraction M) + (draw : ∀ s : Fin T, Fin (count s) → Fin M) : + groupMemberAllocation scales count connection envelope values draw ≤ + (groupMemberWithWork scales count connection envelope values draw).2 := by + let terms := (arithmeticMapWithWork (fun s => groupScaleWithWork (count s) (scales s) + envelope values (draw s)) (List.finRange T)).1 + have ht := arithmeticMapAllocation_le_work + (fun s => groupScaleWithWork (count s) (scales s) envelope values (draw s)) + (fun s => groupScaleAllocation (count s) (scales s) envelope values (draw s)) (List.finRange T) + (fun s _ => groupScaleAllocation_le_work (count s) (scales s) envelope values (draw s)) + have hs := sumListAllocation_le_work terms + have ha := canonicalAddAllocation_le_work connection (sumListWithWork terms).1 + unfold groupMemberAllocation groupMemberWithWork + dsimp only [terms] at hs ha ⊢ + omega + +def countedGroupMemberAllocation {M T : ℕ} (Q b : ℕ) (scales : Fin T → BinaryFraction) + (connection : BinaryFraction) (envelope values : Vector BinaryFraction M) + (draw : ∀ t, Fin (groupSampleCount M Q b (scales t).value) → Fin M) : ℕ := + let counts := vectorMapWithWork T fun t => groupSampleCountWithWork M Q b (scales t) + let count := fun t => bitWordValue (counts.1.get t) + let heq : ∀ t, count t = groupSampleCount M Q b (scales t).value := by + intro t + simp only [count, counts, vectorMapWithWork_value, groupSampleCountWithWork_value] + vectorMapAllocation T (fun t => groupSampleCountAllocation M Q b (scales t)) + + groupMemberAllocation scales count connection envelope values (fun t j => draw t (Fin.cast (heq t) j)) + +theorem countedGroupMemberAllocation_le_work {M T : ℕ} (Q b : ℕ) (scales : Fin T → BinaryFraction) + (connection : BinaryFraction) (envelope values : Vector BinaryFraction M) + (draw : ∀ t, Fin (groupSampleCount M Q b (scales t).value) → Fin M) : + countedGroupMemberAllocation Q b scales connection envelope values draw ≤ + (countedGroupMemberWithWork Q b scales connection envelope values draw).2 := by + let counts := vectorMapWithWork T fun t => groupSampleCountWithWork M Q b (scales t) + let count := fun t => bitWordValue (counts.1.get t) + have heq : ∀ t, count t = groupSampleCount M Q b (scales t).value := by + intro t + simp only [count, counts, vectorMapWithWork_value, groupSampleCountWithWork_value] + have hc := vectorMapAllocation_le_work T (fun t => groupSampleCountWithWork M Q b (scales t)) + (fun t => groupSampleCountAllocation M Q b (scales t)) (fun t => groupSampleCountAllocation_le_work M Q b (scales t)) + have hg := groupMemberAllocation_le_work scales count connection envelope values (fun t j => draw t (Fin.cast (heq t) j)) + unfold countedGroupMemberAllocation countedGroupMemberWithWork + dsimp only [count, counts] at hg ⊢ + omega + + + +theorem selectGroupAllocation_le_work {ι : Type*} (members : List ι) (hne : members ≠ []) + (estimate : ι → BinaryFraction × ℕ) (allocation : ι → ℕ) + (h : ∀ member ∈ members, allocation member ≤ (estimate member).2) : + selectGroupAllocation members estimate allocation ≤ (selectGroupWithWork members hne estimate).2 := by + have hs := scoredArgmaxAllocation_le_work + (fun member => ((estimate member).1.neg, (estimate member).2 + 1)) allocation members + (fun member hm => (h member hm).trans (Nat.le_succ _)) + unfold selectGroupAllocation selectGroupWithWork + dsimp only + omega + +end EditApproximation.BinaryFraction + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryGroupSetup.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryGroupSetup.lean new file mode 100644 index 0000000000000000000000000000000000000000..ae9b553ec38926bab4c648d9445016d09350b662 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryGroupSetup.lean @@ -0,0 +1,75 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryMedianKernel +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! The literal scale list and sample counts, including scales below one. +Dyadic input exponents are carried by the computed parameter construction; +no real logarithm is evaluated by these routines. -/ + +namespace EditApproximation +namespace BinaryFraction + + + +@[simp] theorem signedPowerTwoWithWork_value (e : ℤ) : + (signedPowerTwoWithWork e).1.value = (2 : ℚ) ^ e := by + unfold signedPowerTwoWithWork + split_ifs with h + · change (bitWordValue (powerTwoWord e.toNat) : ℚ) / 1 = (2 : ℚ) ^ e + rw [div_one, powerTwoWord_value, Nat.cast_pow, Nat.cast_ofNat, ← zpow_natCast, + Int.toNat_of_nonneg h] + · rw [inversePowerTwo_value, Int.toNat_of_nonneg + (show 0 ≤ -e from neg_nonneg.mpr (le_of_lt (lt_of_not_ge h))), neg_neg] + +theorem signedPowerTwoWithWork_width (e : ℤ) : + (signedPowerTwoWithWork e).1.width ≤ e.natAbs + 1 := by + unfold signedPowerTwoWithWork + split_ifs with h + · simp only [width, powerTwoWord_length, List.length_cons, List.length_nil] + have hs := Int.toNat_add_toNat_neg_eq_natAbs e + have he : e.toNat ≤ e.natAbs := by omega + omega + · rw [inversePowerTwo_width] + have hs := Int.toNat_add_toNat_neg_eq_natAbs e + have he : (-e).toNat ≤ e.natAbs := by omega + omega + + + +@[simp] theorem groupScalesWithWork_value (eM eb eF : ℕ) : + ((groupScalesWithWork eM eb eF).1.map value) = + groupDyadicScales (2 ^ eM) (2 ^ eb) ((2 : ℚ) ^ eF) := by + have hlower : ((2 ^ eb : ℕ) : ℚ) / (2 ^ eM : ℕ) = (2 : ℚ) ^ ((eb : ℤ) - eM) := by + rw [Nat.cast_pow, Nat.cast_pow, Nat.cast_ofNat, zpow_sub₀ (by norm_num : (2 : ℚ) ≠ 0), + zpow_natCast, zpow_natCast] + have hupper : (64 : ℚ) * (2 : ℚ) ^ eF * (2 ^ eb : ℕ) = + (2 : ℚ) ^ ((6 + eF + eb : ℕ) : ℤ) := by + rw [Nat.cast_pow, Nat.cast_ofNat, zpow_natCast, pow_add, pow_add] + norm_num + have hlog : Int.log 2 ((2 : ℚ) ^ ((6 + eF + eb : ℕ) : ℤ)) = ((6 + eF + eb : ℕ) : ℤ) := by + simpa only [Nat.cast_ofNat] using Int.log_zpow (R := ℚ) (by decide : 1 < 2) ((6 + eF + eb : ℕ) : ℤ) + have hclog : Int.clog 2 ((2 : ℚ) ^ ((eb : ℤ) - eM)) = (eb : ℤ) - eM := by + simpa only [Nat.cast_ofNat] using Int.clog_zpow (R := ℚ) (by decide : 1 < 2) ((eb : ℤ) - eM) + simp only [groupScalesWithWork, arithmeticMapWithWork_value, List.map_map, + Function.comp_def, signedPowerTwoWithWork_value, groupDyadicScales, hlower, hupper, hlog, hclog] + +theorem groupScalesWithWork_length (eM eb eF : ℕ) : + (groupScalesWithWork eM eb eF).1.length = 7 + eM + eF := by + have h := congrArg List.length (groupScalesWithWork_value eM eb eF) + simpa only [List.length_map, groupDyadicScales_length_dyadic] using h + +/-- Exact versus sampled is decided from the actual binary sample count. -/ + + +@[simp] theorem groupSampleCountWithWork_value (M Q b : ℕ) (h : BinaryFraction) : + bitWordValue (groupSampleCountWithWork M Q b h).1 = groupSampleCount M Q b h.value := by + simp only [groupSampleCountWithWork, wordMinWithWork_value, bitWordValue_bits, + naturalCeilingWithWork_value, divWithWork_value, canonicalMulWithWork_value, + nat_value, groupSampleCount] + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryGroupSetupWork.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryGroupSetupWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..a15d46114a227a7a526df4e24db2c0c2b6c5049d --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryGroupSetupWork.lean @@ -0,0 +1,107 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryGroupSetup + +namespace OAI + +/-! Explicit bit costs of the dyadic-scale and exact sample-count builders. +The generated count determines the finite draw type. -/ + +namespace EditApproximation +namespace BinaryFraction + +theorem signedPowerTwoWithWork_cost (e : ℤ) : + (signedPowerTwoWithWork e).2 ≤ e.natAbs + 3 := by + have h := Int.toNat_add_toNat_neg_eq_natAbs e + unfold signedPowerTwoWithWork + split_ifs <;> dsimp only <;> omega + +def groupScalesBitBudget (eM eb eF : ℕ) : ℕ := + (7 + eM + eF) * (eM + eb + eF + 13) + + Nat.size eM + Nat.size eb + Nat.size eF + 8 + +theorem groupScalesWithWork_bounds (eM eb eF : ℕ) : + (∀ value ∈ (groupScalesWithWork eM eb eF).1, + value.width ≤ eM + eb + eF + 7) ∧ + (groupScalesWithWork eM eb eF).2 ≤ groupScalesBitBudget eM eb eF := by + let exponents := integerClosedRange ((eb : ℤ) - eM) ((6 + eF + eb : ℕ) : ℤ) + have habs (e : ℤ) (he : e ∈ exponents) : e.natAbs ≤ eM + eb + eF + 6 := by + have h := (integerClosedRange_mem _ _ _).mp he + have hp : e ≤ (eM + eb + eF + 6 : ℕ) := by omega + have ha : |e| ≤ (eM + eb + eF + 6 : ℕ) := abs_le.mpr ⟨by omega, hp⟩ + have hn : (e.natAbs : ℤ) ≤ (eM + eb + eF + 6 : ℕ) := by + simpa only [Int.natCast_natAbs] using ha + exact_mod_cast hn + have hlen : exponents.length = 7 + eM + eF := by + simp only [exponents, integerClosedRange, List.length_map, List.length_range] + omega + constructor + · intro value hvalue + simp only [groupScalesWithWork, arithmeticMapWithWork_value] at hvalue + obtain ⟨e, he, rfl⟩ := List.mem_map.mp hvalue + exact (signedPowerTwoWithWork_width e).trans (Nat.add_le_add_right (habs e he) 1) + · have hmap := arithmeticMapWithWork_cost signedPowerTwoWithWork exponents + (eM + eb + eF + 9) (fun e he => (signedPowerTwoWithWork_cost e).trans (by + have h := habs e he + omega)) + rw [hlen] at hmap + change (arithmeticMapWithWork signedPowerTwoWithWork exponents).2 + exponents.length + + Nat.size eM + Nat.size eb + Nat.size eF + 8 ≤ _ + unfold groupScalesBitBudget + rw [hlen] + nlinarith only [hmap] + +def groupSampleCountWordBudget (B : ℕ) : ℕ := 64 * B + 46 + +def groupSampleCountBitBudget (B : ℕ) : ℕ := + 2000 * (B + 1) ^ 2 + 2000 * (4 * B + 3) ^ 2 + + 2100 * (16 * B + 12) ^ 2 + 500 * (64 * B + 45) ^ 2 + + 4 * (65 * B + 46) + 3 * B + 8 + +theorem groupSampleCountWithWork_bounds (M Q b : ℕ) (h : BinaryFraction) (B : ℕ) + (hM : Nat.size M + 2 ≤ B) (hQ : Nat.size Q + 2 ≤ B) + (hb : Nat.size b + 2 ≤ B) (hh : h.width ≤ B) : + (groupSampleCountWithWork M Q b h).1.length ≤ groupSampleCountWordBudget B ∧ + (groupSampleCountWithWork M Q b h).2 ≤ groupSampleCountBitBudget B := by + have hMw := (nat_width_le M).trans hM + have hQw := (nat_width_le Q).trans hQ + have hbw := (nat_width_le b).trans hb + have hqm := canonicalMulWithWork_width (nat Q) (nat M) B hQw hMw + have hqmc := canonicalMulWithWork_cost (nat Q) (nat M) B hQw hMw + have hn := canonicalMulWithWork_width (canonicalMulWithWork (nat Q) (nat M)).1 h + (4 * B + 2) hqm (by omega) + have hnc := canonicalMulWithWork_cost (canonicalMulWithWork (nat Q) (nat M)).1 h + (4 * B + 2) hqm (by omega) + have hn' : (canonicalMulWithWork (canonicalMulWithWork (nat Q) (nat M)).1 h).1.width ≤ + 16 * B + 10 := by omega + have hr := divWithWork_width_uniform + (canonicalMulWithWork (canonicalMulWithWork (nat Q) (nat M)).1 h).1 (nat b) + (16 * B + 10) hn' (by omega) + have hrc := divWithWork_cost + (canonicalMulWithWork (canonicalMulWithWork (nat Q) (nat M)).1 h).1 (nat b) + (16 * B + 10) hn' (by omega) + let ratio := divWithWork (canonicalMulWithWork (canonicalMulWithWork (nat Q) (nat M)).1 h).1 (nat b) + change ratio.1.width ≤ _ at hr + change ratio.2 ≤ _ at hrc + have hceil := naturalCeilingWithWork_length ratio.1 + have hceilc := naturalCeilingWithWork_cost ratio.1 + have hsquare := Nat.pow_le_pow_left (show ratio.1.width + 1 ≤ 64 * B + 45 by omega) 2 + have hmin := wordMinWithWork_length M.bits (naturalCeilingWithWork ratio.1).1 + have hminc := wordLEWithWork_cost M.bits (naturalCeilingWithWork ratio.1).1 + simp only [Nat.size_eq_bits_len] at hmin hminc + constructor + · change (wordMinWithWork M.bits (naturalCeilingWithWork ratio.1).1).1.length ≤ _ + unfold groupSampleCountWordBudget + omega + · change _ + _ + ratio.2 + (naturalCeilingWithWork ratio.1).2 + + (wordMinWithWork M.bits (naturalCeilingWithWork ratio.1).1).2 + + Nat.size M + Nat.size Q + Nat.size b + 5 ≤ _ + have hword : (wordMinWithWork M.bits (naturalCeilingWithWork ratio.1).1).2 = + (wordLEWithWork M.bits (naturalCeilingWithWork ratio.1).1).2 + 1 := rfl + rw [hword] + simp only [Nat.add_assoc, Nat.reduceAdd] at hnc hrc + unfold groupSampleCountBitBudget + nlinarith only [hqmc, hnc, hrc, hceilc, hsquare, hminc, hceil, hM, hQ, hb, hr] + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryGroupSourcePort.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryGroupSourcePort.lean new file mode 100644 index 0000000000000000000000000000000000000000..78b4f00fc6ec01ffa3dac04dc12258f4c8419519 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryGroupSourcePort.lean @@ -0,0 +1,68 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryCountedGroup +import OAI.Combinatorics.EditApproximation.Binary.BinaryReadComposition +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Exact finite-count source reads inside a sampled group estimator. +A source read is executed only in the sampled branch; an exact scale +uses the complete child array and makes no random-source lookup. -/ + +namespace EditApproximation.BinaryFraction + +/-- The exact number of source calls at one group scale. -/ +def groupScaleSourceCalls (M k : ℕ) : ℕ := if k = M then 0 else k + + + +theorem groupScaleSourceWithWork_value {M : ℕ} (k : ℕ) (h : BinaryFraction) + (envelope values : Vector BinaryFraction M) (draw : Fin k → Fin M × ℕ) : + (groupScaleSourceWithWork k h envelope values draw).1 = + (groupScaleWithWork k h envelope values (fun i => (draw i).1)).1 := by + unfold groupScaleSourceWithWork groupScaleWithWork + split_ifs <;> simp only [arithmeticMapWithWork_value] + +theorem groupScaleSourceCalls_le_work {M : ℕ} (k : ℕ) (h : BinaryFraction) + (envelope values : Vector BinaryFraction M) (draw : Fin k → Fin M) : + groupScaleSourceCalls M k ≤ (groupScaleWithWork k h envelope values draw).2 := by + unfold groupScaleSourceCalls + split_ifs with heq + · exact Nat.zero_le _ + · have hl := arithmeticMapWithWork_length_le_cost + (fun i : Fin M => let test := equalWithWork (envelope.get i) h + (if test.1 then values.get i else zero, test.2 + 2)) ((List.finRange k).map draw) + simp only [List.length_map, List.length_finRange] at hl + change k ≤ (groupTermsWithWork h envelope values ((List.finRange k).map draw)).2 at hl + unfold groupScaleWithWork + rw [ite_eq_right heq] + unfold groupIndexWithWork + dsimp only + omega + +theorem groupScaleSourceWithWork_cost {M : ℕ} (k : ℕ) (h : BinaryFraction) + (envelope values : Vector BinaryFraction M) (draw : Fin k → Fin M × ℕ) + (R : ℕ) (hr : ∀ i, (draw i).2 ≤ R) : + (groupScaleSourceWithWork k h envelope values draw).2 ≤ + (groupScaleWithWork k h envelope values (fun i => (draw i).1)).2 * (R + 4) := by + have hmap := arithmeticMapWithWork_cost draw (List.finRange k) R (fun i _ => hr i) + simp only [List.length_finRange] at hmap + have hcalls := groupScaleSourceCalls_le_work k h envelope values (fun i => (draw i).1) + by_cases heq : k = M + · unfold groupScaleSourceWithWork groupScaleWithWork + simp only [heq, ite_true, Nat.zero_add] + exact Nat.le_mul_of_pos_right _ (by omega) + · unfold groupScaleSourceWithWork + rw [ite_eq_right heq] + dsimp only + rw [arithmeticMapWithWork_value] + unfold groupScaleWithWork at hcalls ⊢ + rw [ite_eq_right heq] at hcalls ⊢ + unfold groupScaleSourceCalls at hcalls + rw [ite_eq_right heq] at hcalls + simp only [ite_eq_right heq] at hcalls ⊢ + nlinarith only [hmap, hcalls] + +end EditApproximation.BinaryFraction + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryGroupSourceSpace.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryGroupSourceSpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..4556aac7db32616df4fadc9ded9c5a22cd6e3df8 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryGroupSourceSpace.lean @@ -0,0 +1,80 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryGroupReductionSpace +import OAI.Combinatorics.EditApproximation.Binary.BinaryGroupMemberSource +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation.BinaryFraction + +/-- Index decoding, the sampled index spine and the exact/sample reduction. -/ + + +theorem groupScaleSourceAllocation_le_work {M : ℕ} (k : ℕ) (h : BinaryFraction) + (envelope values : Vector BinaryFraction M) (draw : Fin k → Fin M × ℕ) + (allocation : Fin k → ℕ) (ha : ∀ i, allocation i ≤ (draw i).2) : + groupScaleSourceAllocation k h envelope values draw allocation ≤ + (groupScaleSourceWithWork k h envelope values draw).2 := by + let indices := if k = M then (List.finRange M, 0) else arithmeticMapWithWork draw (List.finRange k) + have hi := groupIndexAllocation_le_work h envelope values indices.1 + have hm := arithmeticMapAllocation_le_work draw allocation (List.finRange k) (fun i _ => ha i) + have hd := divAllocation_le_work (nat M) (nat k) + have hp := canonicalMulAllocation_le_work + (if k = M then (one, 1) else divWithWork (nat M) (nat k)).1 + (groupIndexWithWork h envelope values indices.1).1 + unfold groupScaleSourceAllocation groupScaleSourceWithWork + dsimp only [indices] at hi hp + dsimp only + by_cases heq : k = M + · simp only [ite_eq_left heq] at hi hp ⊢ + omega + · simp only [ite_eq_right heq] at hi hp ⊢ + omega + + + +theorem groupMemberSourceAllocation_le_work {M T : ℕ} (scales : Fin T → BinaryFraction) (count : Fin T → ℕ) + (connection : BinaryFraction) (envelope values : Vector BinaryFraction M) + (draw : ∀ s : Fin T, Fin (count s) → Fin M × ℕ) + (allocation : ∀ s : Fin T, Fin (count s) → ℕ) + (ha : ∀ s i, allocation s i ≤ (draw s i).2) : + groupMemberSourceAllocation scales count connection envelope values draw allocation ≤ + (groupMemberSourceWithWork scales count connection envelope values draw).2 := by + let terms := (arithmeticMapWithWork (fun s => groupScaleSourceWithWork (count s) (scales s) + envelope values (draw s)) (List.finRange T)).1 + have ht := arithmeticMapAllocation_le_work + (fun s => groupScaleSourceWithWork (count s) (scales s) envelope values (draw s)) + (fun s => groupScaleSourceAllocation (count s) (scales s) envelope values (draw s) (allocation s)) (List.finRange T) + (fun s _ => groupScaleSourceAllocation_le_work (count s) (scales s) envelope values (draw s) (allocation s) (ha s)) + have hs := sumListAllocation_le_work terms + have ha := canonicalAddAllocation_le_work connection (sumListWithWork terms).1 + unfold groupMemberSourceAllocation groupMemberSourceWithWork + dsimp only [terms] at hs ha ⊢ + omega + + + +theorem countedGroupMemberSourceAllocation_le_work {M T : ℕ} (Q b : ℕ) (scales : Fin T → BinaryFraction) + (connection : BinaryFraction) (envelope values : Vector BinaryFraction M) + (draw : ∀ t, Fin (groupSampleCount M Q b (scales t).value) → Fin M × ℕ) + (allocation : ∀ t, Fin (groupSampleCount M Q b (scales t).value) → ℕ) + (ha : ∀ t i, allocation t i ≤ (draw t i).2) : + countedGroupMemberSourceAllocation Q b scales connection envelope values draw allocation ≤ + (countedGroupMemberSourceWithWork Q b scales connection envelope values draw).2 := by + let counts := vectorMapWithWork T fun t => groupSampleCountWithWork M Q b (scales t) + let count := fun t => bitWordValue (counts.1.get t) + have heq : ∀ t, count t = groupSampleCount M Q b (scales t).value := by + intro t + simp only [count, counts, vectorMapWithWork_value, groupSampleCountWithWork_value] + have hc := vectorMapAllocation_le_work T (fun t => groupSampleCountWithWork M Q b (scales t)) + (fun t => groupSampleCountAllocation M Q b (scales t)) (fun t => groupSampleCountAllocation_le_work M Q b (scales t)) + have hg := groupMemberSourceAllocation_le_work scales count connection envelope values (fun t j => draw t (Fin.cast (heq t) j)) + (fun t j => allocation t (Fin.cast (heq t) j)) (fun t j => ha t _) + unfold countedGroupMemberSourceAllocation countedGroupMemberSourceWithWork + dsimp only [count, counts] at hg ⊢ + omega + + +end EditApproximation.BinaryFraction + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryGroupSpace.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryGroupSpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..0fb44c4f626b5f5099110916b8871b3f3e661c50 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryGroupSpace.lean @@ -0,0 +1,177 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryMedianSpace +import OAI.Combinatorics.EditApproximation.Binary.BinaryOptimizerSpace +import OAI.Combinatorics.EditApproximation.Binary.BinaryCountedGroup +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Literal exact/sample reductions and the sample-count constructor. +The child-index list cells and every comparison are included. -/ + +namespace EditApproximation.BinaryFraction + + + +theorem equalAllocation_le_work (a b : BinaryFraction) : + equalAllocation a b ≤ (equalWithWork a b).2 := by + have hl := ltAllocation_le_work b a + have hr := ltAllocation_le_work a b + unfold equalAllocation equalWithWork leWithWork + dsimp only + omega + + + +theorem groupTermsAllocation_le_work {M : ℕ} + (h : BinaryFraction) (envelope values : Vector BinaryFraction M) (indices : List (Fin M)) : + groupTermsAllocation h envelope indices ≤ (groupTermsWithWork h envelope values indices).2 := by + apply arithmeticMapAllocation_le_work + intro i _ + have hc := equalAllocation_le_work (envelope.get i) h + dsimp only + omega + + + +theorem groupIndexAllocation_le_work {M : ℕ} + (h : BinaryFraction) (envelope values : Vector BinaryFraction M) (indices : List (Fin M)) : + groupIndexAllocation h envelope values indices ≤ (groupIndexWithWork h envelope values indices).2 := by + have ht := groupTermsAllocation_le_work h envelope values indices + have hs := sumListAllocation_le_work (groupTermsWithWork h envelope values indices).1 + unfold groupIndexAllocation groupIndexWithWork + dsimp only + omega + +def groupScaleAllocation {M : ℕ} (k : ℕ) (h : BinaryFraction) + (envelope values : Vector BinaryFraction M) (draw : Fin k → Fin M) : ℕ := + let indices := if k = M then List.finRange M else (List.finRange k).map draw + let subtotal := (groupIndexWithWork h envelope values indices).1 + let factor := if k = M then (one, 1) else divWithWork (nat M) (nat k) + groupIndexAllocation h envelope values indices + + (if k = M then 0 else divAllocation (nat M) (nat k)) + + canonicalMulAllocation factor.1 subtotal + Nat.size M + Nat.size k + +theorem groupScaleAllocation_le_work {M : ℕ} (k : ℕ) (h : BinaryFraction) + (envelope values : Vector BinaryFraction M) (draw : Fin k → Fin M) : + groupScaleAllocation k h envelope values draw ≤ (groupScaleWithWork k h envelope values draw).2 := by + let indices := if k = M then List.finRange M else (List.finRange k).map draw + have hi := groupIndexAllocation_le_work h envelope values indices + have hd := divAllocation_le_work (nat M) (nat k) + have hm := canonicalMulAllocation_le_work + (if k = M then (one, 1) else divWithWork (nat M) (nat k)).1 + (groupIndexWithWork h envelope values indices).1 + unfold groupScaleAllocation groupScaleWithWork + dsimp only [indices] at hi hm + dsimp only + by_cases heq : k = M + · simp only [ite_eq_left heq] at hi hm ⊢ + omega + · simp only [ite_eq_right heq] at hi hm ⊢ + omega + + + +theorem groupSampleCountAllocation_le_work (M Q b : ℕ) (h : BinaryFraction) : + groupSampleCountAllocation M Q b h ≤ (groupSampleCountWithWork M Q b h).2 := by + have h1 := canonicalMulAllocation_le_work (nat Q) (nat M) + have h2 := canonicalMulAllocation_le_work (canonicalMulWithWork (nat Q) (nat M)).1 h + have h3 := divAllocation_le_work (canonicalMulWithWork (canonicalMulWithWork (nat Q) (nat M)).1 h).1 (nat b) + have h4 := naturalCeilingAllocation_le_work + (divWithWork (canonicalMulWithWork (canonicalMulWithWork (nat Q) (nat M)).1 h).1 (nat b)).1 + have h5 := wordLEAllocation_le_work M.bits + (naturalCeilingWithWork (divWithWork (canonicalMulWithWork (canonicalMulWithWork (nat Q) (nat M)).1 h).1 (nat b)).1).1 + unfold groupSampleCountAllocation groupSampleCountWithWork wordMinWithWork + dsimp only + omega + +def equalInvocations (a b : BinaryFraction) : ℕ := + compareInvocations b a + compareInvocations a b + 3 + +theorem equalInvocations_le_work (a b : BinaryFraction) : + equalInvocations a b ≤ (equalWithWork a b).2 := by + have hl := compareInvocations_le_work b a + have hr := compareInvocations_le_work a b + unfold equalInvocations equalWithWork leWithWork + dsimp only + omega + +def groupTermsInvocations {M : ℕ} (h : BinaryFraction) (envelope : Vector BinaryFraction M) + (indices : List (Fin M)) : ℕ := + arithmeticMapInvocations (fun i => equalInvocations (envelope.get i) h + 1) indices + +theorem groupTermsInvocations_le_work_add_one {M : ℕ} + (h : BinaryFraction) (envelope values : Vector BinaryFraction M) (indices : List (Fin M)) : + groupTermsInvocations h envelope indices ≤ (groupTermsWithWork h envelope values indices).2 + 1 := by + apply arithmeticMapInvocations_le_work + intro i _ + have hc := equalInvocations_le_work (envelope.get i) h + dsimp only + omega + +def groupIndexInvocations {M : ℕ} (h : BinaryFraction) (envelope values : Vector BinaryFraction M) + (indices : List (Fin M)) : ℕ := + groupTermsInvocations h envelope indices + + sumListInvocations (groupTermsWithWork h envelope values indices).1 + 1 + +theorem groupIndexInvocations_le_work_add_one {M : ℕ} + (h : BinaryFraction) (envelope values : Vector BinaryFraction M) (indices : List (Fin M)) : + groupIndexInvocations h envelope values indices ≤ (groupIndexWithWork h envelope values indices).2 + 1 := by + have ht := groupTermsInvocations_le_work_add_one h envelope values indices + have hs := sumListInvocations_le_work (groupTermsWithWork h envelope values indices).1 + unfold groupIndexInvocations groupIndexWithWork + dsimp only + omega + +def groupScaleInvocations {M : ℕ} (k : ℕ) (h : BinaryFraction) + (envelope values : Vector BinaryFraction M) (draw : Fin k → Fin M) : ℕ := + let indices := if k = M then List.finRange M else (List.finRange k).map draw + let subtotal := (groupIndexWithWork h envelope values indices).1 + let factor := if k = M then (one, 1) else divWithWork (nat M) (nat k) + groupIndexInvocations h envelope values indices + + (if k = M then 1 else divInvocations (nat M) (nat k)) + + canonicalMulInvocations factor.1 subtotal + 1 + +theorem groupScaleInvocations_le_work {M : ℕ} (k : ℕ) (h : BinaryFraction) + (envelope values : Vector BinaryFraction M) (draw : Fin k → Fin M) : + groupScaleInvocations k h envelope values draw ≤ (groupScaleWithWork k h envelope values draw).2 := by + let indices := if k = M then List.finRange M else (List.finRange k).map draw + have hi := groupIndexInvocations_le_work_add_one h envelope values indices + have hd := divInvocations_le_work (nat M) (nat k) + have hm := canonicalMulInvocations_le_work + (if k = M then (one, 1) else divWithWork (nat M) (nat k)).1 + (groupIndexWithWork h envelope values indices).1 + unfold groupScaleInvocations groupScaleWithWork + dsimp only [indices] at hi hm + dsimp only + by_cases heq : k = M + · simp only [ite_eq_left heq] at hi hm ⊢ + omega + · simp only [ite_eq_right heq] at hi hm ⊢ + omega + +def groupSampleCountInvocations (M Q b : ℕ) (h : BinaryFraction) : ℕ := + let qm := (canonicalMulWithWork (nat Q) (nat M)).1 + let numerator := (canonicalMulWithWork qm h).1 + let ratio := (divWithWork numerator (nat b)).1 + canonicalMulInvocations (nat Q) (nat M) + canonicalMulInvocations qm h + + divInvocations numerator (nat b) + naturalCeilingInvocations ratio + + wordLEInvocations M.bits (naturalCeilingWithWork ratio).1 + + 2 + +theorem groupSampleCountInvocations_le_work (M Q b : ℕ) (h : BinaryFraction) : + groupSampleCountInvocations M Q b h ≤ (groupSampleCountWithWork M Q b h).2 := by + have h1 := canonicalMulInvocations_le_work (nat Q) (nat M) + have h2 := canonicalMulInvocations_le_work (canonicalMulWithWork (nat Q) (nat M)).1 h + have h3 := divInvocations_le_work (canonicalMulWithWork (canonicalMulWithWork (nat Q) (nat M)).1 h).1 (nat b) + have h4 := naturalCeilingInvocations_le_work + (divWithWork (canonicalMulWithWork (canonicalMulWithWork (nat Q) (nat M)).1 h).1 (nat b)).1 + have h5 := wordLEInvocations_le_work M.bits + (naturalCeilingWithWork (divWithWork (canonicalMulWithWork (canonicalMulWithWork (nat Q) (nat M)).1 h).1 (nat b)).1).1 + unfold groupSampleCountInvocations groupSampleCountWithWork wordMinWithWork + dsimp only + omega + +end EditApproximation.BinaryFraction + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryGuardSpace.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryGuardSpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..1b994498831606bfc4d20085a4f8cf2005899431 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryGuardSpace.lean @@ -0,0 +1,140 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryPrefixSpace +import OAI.Combinatorics.EditApproximation.Binary.BinaryWideSpace +import OAI.Combinatorics.EditApproximation.Binary.BinaryCutReads +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation + +/-- List traversal, including the input index spine when it is freshly generated. -/ + + +theorem allAllocation_le_work {α : Type*} (test : α → Bool × ℕ) + (allocation : α → ℕ) (xs : List α) (h : ∀ x ∈ xs, allocation x ≤ (test x).2) : + allAllocation allocation xs ≤ (allWithWork test xs).2 := by + induction xs with + | nil => simp only [allAllocation, allWithWork, Nat.zero_le] + | cons x xs ih => + have hh := h x List.mem_cons_self + have ht := ih (fun y hy => h y (List.mem_cons_of_mem _ hy)) + unfold allAllocation allWithWork + dsimp only + exact Nat.add_le_add (Nat.add_le_add hh ht) (by decide : 1 ≤ 3) + +theorem allAllocation_with_spine {α : Type*} (test : α → Bool × ℕ) + (allocation : α → ℕ) (xs : List α) (h : ∀ x ∈ xs, allocation x ≤ (test x).2) : + allAllocation allocation xs + xs.length ≤ (allWithWork test xs).2 := by + have costBound (a a' b b' l : ℕ) (ha : a ≤ a') (hb : b + l ≤ b') : + a + b + 1 + (l + 1) ≤ a' + b' + 3 := by + omega + induction xs with + | nil => simp only [allAllocation, allWithWork, List.length_nil, Nat.zero_add, Nat.zero_le] + | cons x xs ih => + have hh := h x List.mem_cons_self + have ht := ih (fun y hy => h y (List.mem_cons_of_mem _ hy)) + unfold allAllocation allWithWork + dsimp only + simp only [List.length_cons] + exact costBound _ _ _ _ _ hh ht + + + +theorem zeroConnectionAllocation_le_work {n : ℕ} (start finish : ℕ) (states : List (TargetInterval n)) : + zeroConnectionAllocation start states finish ≤ (zeroConnectionWithWork start states finish).2 := by + induction states generalizing start with + | nil => exact naturalEqualAllocation_le_work start finish + | cons state rest ih => + have hh := naturalEqualAllocation_le_work start state.lo + have ht := ih state.hi + unfold zeroConnectionAllocation zeroConnectionWithWork + dsimp only + exact Nat.add_le_add_right (Nat.add_le_add hh ht) 1 + + + +theorem translatedEndpointAllocation_le_work (reference root endpoint : ℕ) : + translatedEndpointAllocation reference root endpoint ≤ (translatedEndpointWithWork reference root endpoint).2 := by + have hs := bitSubtractAllocation_le_work endpoint.bits root.bits false + have ha := binaryNaturalAddAllocation_le_work reference (bitWordValue (binaryNaturalSubtractWithWork endpoint root).1) + unfold translatedEndpointAllocation translatedEndpointWithWork binaryNaturalSubtractWithWork + dsimp only [binaryNaturalSubtractWithWork] at ha ⊢ + omega + +namespace BinaryFraction + + + +theorem leAllocation_le_work (a b : BinaryFraction) : + leAllocation a b ≤ (leWithWork a b).2 := by + have h := ltAllocation_le_work b a + unfold leAllocation leWithWork + dsimp only + omega + + + +theorem naturalDistanceLeAllocation_le_work (a b radius : ℕ) : + naturalDistanceLeAllocation a b radius ≤ (naturalDistanceLeWithWork a b radius).2 := by + have hd := distanceAllocation_le_work (nat a) (nat b) + have hl := leAllocation_le_work (distanceWithWork (nat a) (nat b)).1 (nat radius) + unfold naturalDistanceLeAllocation naturalDistanceLeWithWork + dsimp only + omega + + + +theorem affineErrorAllocation_le_work (position offset velocity prediction tolerance : BinaryFraction) : + affineErrorAllocation position offset velocity prediction tolerance ≤ + (affineErrorWithWork position offset velocity prediction tolerance).2 := by + have hd := subAllocation_le_work position offset + have hp := canonicalMulAllocation_le_work velocity prediction + have he := subAllocation_le_work (subWithWork position offset).1 (canonicalMulWithWork velocity prediction).1 + have hl := leAllocation_le_work + (subWithWork (subWithWork position offset).1 (canonicalMulWithWork velocity prediction).1).1.absolute tolerance + unfold affineErrorAllocation affineErrorWithWork + dsimp only + omega + + + +theorem bandToleranceAllocation_le_work (tau theta : BinaryFraction) (b M : ℕ) : + bandToleranceAllocation tau theta b M ≤ (bandToleranceWithWork tau theta b M).2 := by + have hp := canonicalMulAllocation_le_work tau theta + have hs := canonicalMulAllocation_le_work (canonicalMulWithWork tau theta).1 (nat b) + have hd := divAllocation_le_work (canonicalMulWithWork (canonicalMulWithWork tau theta).1 (nat b)).1 (nat M) + unfold bandToleranceAllocation bandToleranceWithWork + dsimp only + omega + + + +theorem cutGuardReadAllocation_le_work {nx ny M : ℕ} (parent : TargetInterval nx) (r : TargetInterval ny) + (actions : List (Fin M → TargetInterval ny)) (hne : actions ≠ []) + (read : Fin M → TargetInterval ny → BinaryFraction × ℕ) + (allocation : Fin M → TargetInterval ny → ℕ) (states : Fin M → TargetInterval ny) + (velocity tolerance : BinaryFraction) (j : Fin M) + (h : ∀ action ∈ actions, ∀ i, allocation i (action i) ≤ (read i (action i)).2) : + cutGuardReadAllocation parent r actions hne read allocation states velocity tolerance j ≤ + (cutGuardReadWithWork parent r actions hne read states velocity tolerance j).2 := by + have hs := subAllocation_le_work (nat (states j).lo) (nat (sourceChild parent j).lo) + have ho := subAllocation_le_work (nat r.lo) (nat parent.lo) + have hp := prefixMinimumReadAllocation_le_work parent r actions hne read allocation j.val + (subWithWork (nat (states j).lo) (nat (sourceChild parent j).lo)).1 h + have he := affineErrorAllocation_le_work + (subWithWork (nat (states j).lo) (nat (sourceChild parent j).lo)).1 + (subWithWork (nat r.lo) (nat parent.lo)).1 velocity + (prefixMinimumReadWithWork parent r actions hne read j.val + (subWithWork (nat (states j).lo) (nat (sourceChild parent j).lo)).1).1 tolerance + unfold cutGuardReadAllocation cutGuardReadWithWork + split_ifs <;> dsimp only + · exact Nat.zero_le _ + · have hsum := Nat.add_le_add (Nat.add_le_add (Nat.add_le_add hs ho) hp) he + exact (Nat.add_le_add_right (Nat.add_le_add_right (Nat.add_le_add_right + (Nat.add_le_add_right hsum _) _) _) _).trans (Nat.le_add_right _ 5) + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryIndexedLeaf.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryIndexedLeaf.lean new file mode 100644 index 0000000000000000000000000000000000000000..d81690ee240bd548f7cf99639491e2efd35b2d16 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryIndexedLeaf.lean @@ -0,0 +1,64 @@ +import OAI.Combinatorics.EditApproximation.Geometry.IndexedTerminalWork +import OAI.Combinatorics.EditApproximation.Binary.BinaryDistanceWork +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation + +/-- The indexed terminal result is written directly as a binary rational. -/ + + +theorem indexedLeafWithWork_le (table : BinaryMemo PositionCounts) (symbolBits positionBits : ℕ) + (symbol : Option ℕ) (lo hi : ℕ) : + (indexedLeafWithWork table symbolBits positionBits symbol lo hi).1 ≤ hi + 1 := by + rw [indexedLeafWithWork_value] + cases symbol with + | none => change hi - lo ≤ hi + 1; omega + | some a => + simp only [indexedLeafCost, indexedSingletonCost] + split_ifs <;> omega + +theorem binaryIndexedLeafWithWork_value (table : BinaryMemo PositionCounts) (symbolBits positionBits : ℕ) + (symbol : Option ℕ) (lo hi : ℕ) : + (binaryIndexedLeafWithWork table symbolBits positionBits symbol lo hi).1.value = + (indexedLeafCost table symbolBits positionBits symbol lo hi : ℚ) := by + simp only [binaryIndexedLeafWithWork, BinaryFraction.nat_value, indexedLeafWithWork_value] + +theorem binaryIndexedLeafWithWork_bounds (table : BinaryMemo PositionCounts) (symbolBits positionBits : ℕ) + (symbol : Option ℕ) (lo hi : ℕ) : + (binaryIndexedLeafWithWork table symbolBits positionBits symbol lo hi).1.width ≤ Nat.size (hi + 1) + 2 ∧ + (binaryIndexedLeafWithWork table symbolBits positionBits symbol lo hi).2 ≤ + 2 * symbolBits + 4 * positionBits + Nat.size (hi + 1) + 12 := by + have hv := Nat.size_le_size (indexedLeafWithWork_le table symbolBits positionBits symbol lo hi) + have hc := indexedLeafWithWork_cost table symbolBits positionBits symbol lo hi + constructor + · exact (BinaryFraction.nat_width_le _).trans (Nat.add_le_add_right hv 2) + · change _ + _ + 2 ≤ _ + omega + +theorem integerBinaryIndexedLeafWithWork_cost (C : ℕ) : + ∀ᶠ N : ℕ in Filter.atTop, ∀ source target : List ℤ, source.length + target.length ≤ N → + (∀ z ∈ source ++ target, z.natAbs ≤ (N + 2) ^ C) → ∀ symbol lo hi, hi ≤ N → + (binaryIndexedLeafWithWork (integerOccurrenceIndex source target) (integerInputSymbolBits source target) + (integerInputPositionBits target) symbol lo hi).2 ≤ inputHeight N ^ 4 := by + filter_upwards [integerIndexedLeafWithWork_cost C, + inputHeight_real_tendsto.eventually (Filter.eventually_ge_atTop (100 : ℝ))] with N hc hH + have hH' : 100 ≤ inputHeight N := by exact_mod_cast hH + intro source target hsize halphabet symbol lo hi hhi + have hcost := hc source target hsize halphabet symbol lo hi + have hval := indexedLeafWithWork_le (integerOccurrenceIndex source target) + (integerInputSymbolBits source target) (integerInputPositionBits target) symbol lo hi + have hbits : Nat.size (indexedLeafWithWork (integerOccurrenceIndex source target) + (integerInputSymbolBits source target) (integerInputPositionBits target) symbol lo hi).1 ≤ + inputHeight N + 1 := + (Nat.size_le_size (hval.trans (by omega))).trans (input_length_bits_le N) + have hp := Nat.mul_le_mul_right (inputHeight N ^ 3) hH' + have hh : inputHeight N ≤ inputHeight N ^ 3 := Nat.le_pow (by decide) + change _ + _ + 2 ≤ _ + nlinarith only [hcost, hbits, hp, hh, hH'] + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryInitialGridWork.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryInitialGridWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..0fecf5196d313e75bd9651ce8fc1ba82eec23dd1 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryInitialGridWork.lean @@ -0,0 +1,208 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryInitialGuardWork +import OAI.Combinatorics.EditApproximation.Binary.BinaryPreparedListBounds +import OAI.Combinatorics.EditApproximation.Binary.BinaryInitialMinimumWork + +namespace OAI + +/-! Construction of every local initial-cone center is charged, including +rejected center predicates. The scale test itself bounds the emitted grid. -/ + +namespace EditApproximation +namespace BinaryFraction + +private theorem dyadicScale_size (N B b : ℕ) (hN : Nat.size N ≤ B) (hb : b ∈ dyadicScales N) : + Nat.size b ≤ B + 2 := by + obtain ⟨e, he, rfl⟩ := List.mem_map.mp hb + have hlen : Nat.log 2 N + 1 = max 1 N.bits.length := by + simpa only [dyadicScales, List.length_map, List.length_range] using dyadicScales_length_bits N + have he' := List.mem_range.mp he + rw [hlen, Nat.size_eq_bits_len] at he' + rw [Nat.size_pow] + omega + +private theorem initialGrid_count (P b radius Amax : ℕ) (hP : 0 < P) + (hradius : radius ≤ 16 * Amax ^ 2 * b) : + 2 * radius / seedGridSpacing b P + 2 ≤ 64 * Amax ^ 2 * P + 2 := by + have hg : 0 < seedGridSpacing b P := by unfold seedGridSpacing; omega + have hq : b / P ≤ seedGridSpacing b P := le_max_right _ _ + have hdiv := Nat.lt_mul_div_succ b hP + have hcover : b ≤ 2 * P * seedGridSpacing b P := by nlinarith only [hq, hdiv, hg] + have hnum : 2 * radius ≤ 64 * Amax ^ 2 * P * seedGridSpacing b P := by + nlinarith only [hradius, Nat.mul_le_mul_left (32 * Amax ^ 2) hcover] + have hfloor := Nat.div_mul_le_self (2 * radius) (seedGridSpacing b P) + nlinarith only [hfloor, hnum, hg] + +private theorem initialScale_radius (U b Amax : ℕ) (A : BinaryFraction) + (hA : 1 ≤ A.value) (hmax : A.value ≤ Amax) + (hguard : (initialScaleGuardWithWork U b A).1 = true) : + U ≤ 16 * Amax ^ 2 * b := by + have hw := (initialScaleGuardWithWork_value U b A).mp hguard + have hp : 0 < A.value := by linarith + have hdiv := (div_le_iff₀ (show (0 : ℚ) < 16 * A.value ^ 2 by positivity)).mp hw.1 + have hsq := pow_le_pow_left₀ hp.le hmax 2 + have hmul := mul_le_mul_of_nonneg_right hsq (show (0 : ℚ) ≤ 16 * b by positivity) + have hh : (U : ℚ) ≤ (16 * Amax ^ 2 * b : ℕ) := by push_cast; nlinarith only [hdiv, hmul] + exact_mod_cast hh + +def initialGridScaleBitBudget (P Amax B : ℕ) : ℕ := + let L := 64 * Amax ^ 2 * P + 2 + 100 * (B + 6) ^ 2 + gridStateBoxBitBudget L (B + 5) + + L ^ 2 * (initialCenterGuardBitBudget (B + 4) + 3) + 2 + +attribute [local irreducible] seedGridSpacingWithWork gridStateBoxWithWork filterWithWork + initialCenterGuardWithWork initialScaleGuardWithWork + +private theorem initialGridScale_bounds {n : ℕ} (N P Amax B b : ℕ) + (A : BinaryFraction) (U : TargetInterval n → ℕ) (q : TargetInterval n) + (hB : 8 ≤ B) (hP : 0 < P) (hN : Nat.size N ≤ B) (hPb : Nat.size P ≤ B) + (hn : Nat.size n ≤ B) (hU : ∀ r, Nat.size (U r) ≤ B) (hAb : A.width ≤ B) + (hA : 1 ≤ A.value) (hmax : A.value ≤ Amax) (hb : b ∈ dyadicScales N) + (hguard : (initialScaleGuardWithWork (U q) b A).1 = true) : + let spacing := seedGridSpacingWithWork b P + let points := gridStateBoxWithWork n (bitWordValue spacing.1) (U q) q.lo q.hi + let selected := filterWithWork (fun r => initialCenterGuardWithWork b (U r) A) points.1 + spacing.2 + points.2 + selected.2 + 2 ≤ initialGridScaleBitBudget P Amax B ∧ + selected.1.length ≤ (64 * Amax ^ 2 * P + 2) ^ 2 := by + dsimp only + let spacing := seedGridSpacingWithWork b P + let points := gridStateBoxWithWork n (bitWordValue spacing.1) (U q) q.lo q.hi + let selected := filterWithWork (fun r => initialCenterGuardWithWork b (U r) A) points.1 + let L := 64 * Amax ^ 2 * P + 2 + have hbs := dyadicScale_size N B b hN hb + have hs := seedGridSpacingWithWork_bounds b P (B + 4) (by omega) (by omega) + have hsp : Nat.size (bitWordValue spacing.1) ≤ B + 5 := + (Nat.size_le.mpr (bitWordValue_lt_pow_length spacing.1)).trans hs.1 + have hpositive := seedGridSpacingWithWork_pos b P hP + have hcount := initialGrid_count P b (U q) Amax hP (initialScale_radius (U q) b Amax A hA hmax hguard) + have hspvalue : bitWordValue spacing.1 = seedGridSpacing b P := seedGridSpacingWithWork_value b P hP + have hg := gridStateBoxWithWork_cost n (bitWordValue spacing.1) (U q) q.lo q.hi (B + 5) + hpositive (by omega) hsp (by have := hU q; omega) + ((Nat.size_le_size (q.ordered.trans q.valid)).trans (by omega)) + ((Nat.size_le_size q.valid).trans (by omega)) + rw [hspvalue] at hg + have hgc := hg.trans (gridStateBoxBitBudget_mono_count _ L (B + 5) hcount) + have hpl : points.1.length ≤ L ^ 2 := by + rw [show points.1 = localTargetStates n (seedGridSpacing b P) (U q) q by + rw [show points.1 = (gridStateBoxWithWork n (bitWordValue spacing.1) (U q) q.lo q.hi).1 from rfl, + gridStateBoxWithWork_value _ _ _ _ _ hpositive, hspvalue] + rfl] + exact (localTargetStates_length_le (by unfold seedGridSpacing; omega) q).trans + (Nat.pow_le_pow_left hcount 2) + have hf := filterWithWork_cost (fun r : TargetInterval n => initialCenterGuardWithWork b (U r) A) + points.1 (initialCenterGuardBitBudget (B + 4)) (fun r _ => + initialCenterGuardWithWork_cost b (U r) (B + 4) A (by omega) (by omega) (by have := hU r; omega) (by omega)) + have hfc := hf.trans (Nat.mul_le_mul_right _ hpl) + have hselected : selected.1.length ≤ L ^ 2 := by + exact (show selected.1.length ≤ points.1.length by + rw [show selected.1 = points.1.filter (fun r => (initialCenterGuardWithWork b (U r) A).1) by + exact filterWithWork_value _ _] + exact List.length_filter_le _ _).trans hpl + refine ⟨?_, hselected⟩ + have hspacing : spacing.2 ≤ 100 * (B + 6) ^ 2 := by + simpa only [Nat.add_assoc, Nat.reduceAdd] using hs.2 + have hpoints : points.2 ≤ gridStateBoxBitBudget L (B + 5) := by + dsimp only [points] + rw [hspvalue] + exact hgc + have hfilter : selected.2 ≤ L ^ 2 * (initialCenterGuardBitBudget (B + 4) + 3) := hfc + exact Nat.add_le_add_right (Nat.add_le_add (Nat.add_le_add hspacing hpoints) hfilter) 2 + +def initialCentersBitBudget (P Amax B : ℕ) : ℕ := + let L := 64 * Amax ^ 2 * P + 2 + (B + 1) * (B + 9) + 2 + (B + 1) * (initialScaleGuardBitBudget (B + 4) + 3) + + (B + 1) * (initialGridScaleBitBudget P Amax B + L ^ 2 + 3) + 3 + +theorem initialCentersWithWork_bounds {n : ℕ} (N P Amax B : ℕ) + (A : BinaryFraction) (U : TargetInterval n → ℕ) (q : TargetInterval n) + (hB : 8 ≤ B) (hP : 0 < P) (hN : Nat.size N ≤ B) (hPb : Nat.size P ≤ B) + (hn : Nat.size n ≤ B) (hU : ∀ r, Nat.size (U r) ≤ B) (hAb : A.width ≤ B) + (hA : 1 ≤ A.value) (hmax : A.value ≤ Amax) : + (initialCentersWithWork N P A U q).1.length ≤ (B + 1) * (64 * Amax ^ 2 * P + 2) ^ 2 ∧ + (initialCentersWithWork N P A U q).2 ≤ initialCentersBitBudget P Amax B := by + let scales := dyadicScalesWithWork N + let active := filterWithWork (fun b => initialScaleGuardWithWork (U q) b A) scales.1 + let callback := fun b => + let spacing := seedGridSpacingWithWork b P + let points := gridStateBoxWithWork n (bitWordValue spacing.1) (U q) q.lo q.hi + let selected := filterWithWork (fun r => initialCenterGuardWithWork b (U r) A) points.1 + (selected.1, spacing.2 + points.2 + selected.2 + 2) + let L := 64 * Amax ^ 2 * P + 2 + have hscales : scales.1.length ≤ B + 1 := by + simp only [scales, dyadicScalesWithWork_value, dyadicScales_length_bits, Nat.size_eq_bits_len] + omega + have hactive : active.1.length ≤ B + 1 := by + exact (show active.1.length ≤ scales.1.length by + rw [filterWithWork_value]; exact List.length_filter_le _ _).trans hscales + have hmembers (b : ℕ) (hb : b ∈ active.1) : + b ∈ dyadicScales N ∧ (initialScaleGuardWithWork (U q) b A).1 = true := by + have hm := List.mem_filter.mp (show b ∈ scales.1.filter + (fun b => (initialScaleGuardWithWork (U q) b A).1) by simpa only [active, filterWithWork_value] using hb) + exact ⟨by simpa only [scales, dyadicScalesWithWork_value] using hm.1, hm.2⟩ + have hcallback (b : ℕ) (hb : b ∈ active.1) : + (callback b).2 ≤ initialGridScaleBitBudget P Amax B ∧ (callback b).1.length ≤ L ^ 2 := + initialGridScale_bounds N P Amax B b A U q hB hP hN hPb hn hU hAb hA hmax + (hmembers b hb).1 (hmembers b hb).2 + have hg := filterWithWork_cost (fun b => initialScaleGuardWithWork (U q) b A) + scales.1 (initialScaleGuardBitBudget (B + 4)) (by + intro b hb + have hmem : b ∈ dyadicScales N := by simpa only [scales, dyadicScalesWithWork_value] using hb + have hbb := dyadicScale_size N B b hN hmem + exact initialScaleGuardWithWork_cost (U q) b (B + 4) A (by omega) + (by have := hU q; omega) (by omega) (by omega)) + have hgc := hg.trans (Nat.mul_le_mul_right _ hscales) + have hc := arithmeticFlatMapWithWork_cost callback active.1 (initialGridScaleBitBudget P Amax B) + (L ^ 2) (fun b hb => (hcallback b hb).1) (fun b hb => (hcallback b hb).2) + have hcc := hc.trans (Nat.mul_le_mul_right _ hactive) + have hs := dyadicScalesWithWork_cost N + have hsc : scales.2 ≤ (B + 1) * (B + 9) + 2 := by + exact hs.trans (Nat.add_le_add_right (Nat.mul_le_mul (by omega) (by omega)) 2) + constructor + · rw [show (initialCentersWithWork N P A U q).1 = active.1.flatMap (fun b => (callback b).1) by + exact arithmeticFlatMapWithWork_value callback active.1] + exact (list_flatMap_length_le _ _ _ (fun b hb => (hcallback b hb).2)).trans + (Nat.mul_le_mul_right _ hactive) + · change scales.2 + active.2 + (arithmeticFlatMapWithWork callback active.1).2 + 3 ≤ _ + change active.2 ≤ _ at hgc + unfold initialCentersBitBudget + dsimp only + simp only [L] at hcc ⊢ + omega + +def initialProgramBitBudget (P Amax B : ℕ) : ℕ := + initialCentersBitBudget P Amax B + + initialMinimumBitBudget ((B + 1) * (64 * Amax ^ 2 * P + 2) ^ 2) (B + 4) + 1 + +private theorem initialMinimumBitBudget_mono_count (n m B : ℕ) (h : n ≤ m) : + initialMinimumBitBudget n B ≤ initialMinimumBitBudget m B := by + unfold initialMinimumBitBudget + gcongr + +theorem initialProgramWithWork_bounds {n : ℕ} (sourceLength N P F Amax B : ℕ) + (A a : BinaryFraction) (U : TargetInterval n → ℕ) (q : TargetInterval n) + (hB : 8 ≤ B) (hP : 0 < P) (hN : Nat.size N ≤ B) (hPb : Nat.size P ≤ B) + (hF : Nat.size F ≤ B) (hs : Nat.size sourceLength ≤ B) (hn : Nat.size n ≤ B) + (hU : ∀ r, Nat.size (U r) ≤ B) (hAb : A.width ≤ B) (ha : a.width ≤ B) + (hA : 1 ≤ A.value) (hmax : A.value ≤ Amax) : + (initialProgramWithWork sourceLength N P F A a U q).1.width ≤ initialMinimumWordBudget (B + 4) ∧ + (initialProgramWithWork sourceLength N P F A a U q).2 ≤ initialProgramBitBudget P Amax B := by + let centers := initialCentersWithWork N P A U q + have hc := initialCentersWithWork_bounds N P Amax B A U q hB hP hN hPb hn hU hAb hA hmax + have hm := initialMinimumWithWork_bounds sourceLength U N F a q centers.1 (B + 4) + (by omega) (by omega) (by have := hU q; omega) (by omega) (by omega) (by omega) + ((Nat.add_le_add_right (Nat.size_le_size (q.ordered.trans q.valid)) 2).trans (by omega)) + ((Nat.add_le_add_right (Nat.size_le_size q.valid) 2).trans (by omega)) (by + intro r _ + exact ⟨by have := hU r; omega, + (Nat.add_le_add_right (Nat.size_le_size (r.ordered.trans r.valid)) 2).trans (by omega), + (Nat.add_le_add_right (Nat.size_le_size r.valid) 2).trans (by omega)⟩) + have hmc := hm.2.trans (initialMinimumBitBudget_mono_count _ _ (B + 4) hc.1) + refine ⟨hm.1, ?_⟩ + change centers.2 + (initialMinimumWithWork sourceLength U N F a q centers.1).2 + 1 ≤ _ + unfold initialProgramBitBudget + have hcc : centers.2 ≤ initialCentersBitBudget P Amax B := hc.2 + omega + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryInitialGuardSpace.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryInitialGuardSpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..8e5d339b8632edfa233a768eaf93f020ad08c90f --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryInitialGuardSpace.lean @@ -0,0 +1,81 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryNormalizationSpace +import OAI.Combinatorics.EditApproximation.Binary.BinaryInitialReads +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation + + + +theorem dyadicScalesAllocation_le_work (N : ℕ) : + dyadicScalesAllocation N ≤ (dyadicScalesWithWork N).2 := by + have h := arithmeticMapAllocation_le_work + (fun e => (bitWordValue (powerTwoWord e), e + 3)) (fun e => e + 1) + (List.range (max 1 N.bits.length)) (fun _ _ => by dsimp only; omega) + unfold dyadicScalesAllocation dyadicScalesWithWork + dsimp only + omega + +namespace BinaryFraction + + + +theorem initialScaleGuardAllocation_le_work (U b : ℕ) (A : BinaryFraction) : + initialScaleGuardAllocation U b A ≤ (initialScaleGuardWithWork U b A).2 := by + have h1 := canonicalMulAllocation_le_work A A + have h2 := canonicalMulAllocation_le_work (nat 16) (canonicalMulWithWork A A).1 + have h3 := divAllocation_le_work (nat U) (canonicalMulWithWork (nat 16) (canonicalMulWithWork A A).1).1 + have h4 := canonicalMulAllocation_le_work (nat 4) A + have h5 := canonicalMulAllocation_le_work (canonicalMulWithWork (nat 4) A).1 (nat U) + have h6 := leAllocation_le_work (divWithWork (nat U) (canonicalMulWithWork (nat 16) (canonicalMulWithWork A A).1).1).1 (nat b) + have h7 := leAllocation_le_work (nat b) (canonicalMulWithWork (canonicalMulWithWork (nat 4) A).1 (nat U)).1 + unfold initialScaleGuardAllocation initialScaleGuardWithWork + dsimp only + omega + + + +theorem initialCenterGuardAllocation_le_work (b U : ℕ) (A : BinaryFraction) : + initialCenterGuardAllocation b U A ≤ (initialCenterGuardWithWork b U A).2 := by + have h1 := divAllocation_le_work (nat b) (nat 2) + have h2 := canonicalMulAllocation_le_work (nat 4) A + have h3 := canonicalMulAllocation_le_work (canonicalMulWithWork (nat 4) A).1 (nat b) + have h4 := leAllocation_le_work (divWithWork (nat b) (nat 2)).1 (nat U) + have h5 := leAllocation_le_work (nat U) (canonicalMulWithWork (canonicalMulWithWork (nat 4) A).1 (nat b)).1 + unfold initialCenterGuardAllocation initialCenterGuardWithWork + dsimp only + omega + + + +theorem scaledSeedAllocation_le_work (U : ℕ) (a gap : BinaryFraction) : + scaledSeedAllocation U a gap ≤ (scaledSeedWithWork U a gap).2 := by + have hd := divAllocation_le_work (nat U) a + have hc := naturalCeilingAllocation_le_work (divWithWork (nat U) a).1 + have hm := maxAllocation_le_work (ofNaturalWord (naturalCeilingWithWork (divWithWork (nat U) a).1).1) gap.absolute + unfold scaledSeedAllocation scaledSeedWithWork + dsimp only + omega + + + +theorem initialConeAllocation_le_work {n : ℕ} (sourceLength U : ℕ) (a L : BinaryFraction) + (query center : TargetInterval n) : + initialConeAllocation sourceLength U a L query center ≤ + (initialConeWithWork sourceLength (fun _ => U) a L query center).2 := by + have h1 := stateGapAllocation_le_work sourceLength center + have h2 := scaledSeedAllocation_le_work U a (stateGapWithWork sourceLength center).1 + have h3 := endpointDistanceAllocation_le_work query center + have h4 := canonicalMulAllocation_le_work L (endpointDistanceWithWork query center).1 + have h5 := canonicalAddAllocation_le_work (scaledSeedWithWork U a (stateGapWithWork sourceLength center).1).1 + (canonicalMulWithWork L (endpointDistanceWithWork query center).1).1 + unfold initialConeAllocation initialConeWithWork + dsimp only + omega + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryInitialGuardWork.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryInitialGuardWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..2db4354bf5b921a5b3e61ba35ee0be44fd0d1d31 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryInitialGuardWork.lean @@ -0,0 +1,80 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryScaleGrid +import OAI.Combinatorics.EditApproximation.Binary.BinaryAffineGuard + +namespace OAI + +/-! The two initial-grid predicates are evaluated by explicit stored +multiplication, division and comparison. -/ + +namespace EditApproximation +namespace BinaryFraction + +def initialScaleGuardBitBudget (B : ℕ) : ℕ := + 4000 * (B + 1) ^ 2 + 4000 * (4 * B + 3) ^ 2 + 2100 * (16 * B + 12) ^ 2 + + 2 * (1000 * (64 * B + 45) ^ 2 + 1) + 2 * B + 7 + +def initialCenterGuardBitBudget (B : ℕ) : ℕ := + 2100 * (B + 2) ^ 2 + 2000 * (B + 1) ^ 2 + 2000 * (4 * B + 3) ^ 2 + + 2 * (1000 * (16 * B + 11) ^ 2 + 1) + 2 * B + 5 + +theorem initialScaleGuardWithWork_cost (U b B : ℕ) (A : BinaryFraction) + (hB : 8 ≤ B) (hU : Nat.size U + 2 ≤ B) (hb : Nat.size b + 2 ≤ B) (hA : A.width ≤ B) : + (initialScaleGuardWithWork U b A).2 ≤ initialScaleGuardBitBudget B := by + have h16 : (nat 16).width ≤ B := (nat_width_le 16).trans (by change 7 ≤ B; omega) + have h4 : (nat 4).width ≤ B := (nat_width_le 4).trans (by change 5 ≤ B; omega) + have hUn := (nat_width_le U).trans hU + have hbn := (nat_width_le b).trans hb + have hsw := canonicalMulWithWork_width A A B hA hA + have hsc := canonicalMulWithWork_cost A A B hA hA + have hdw := canonicalMulWithWork_width (nat 16) (canonicalMulWithWork A A).1 (4 * B + 2) (by omega) hsw + have hdc := canonicalMulWithWork_cost (nat 16) (canonicalMulWithWork A A).1 (4 * B + 2) (by omega) hsw + have hlw := divWithWork_width_uniform (nat U) + (canonicalMulWithWork (nat 16) (canonicalMulWithWork A A).1).1 (16 * B + 10) (by omega) (by omega) + have hlc := divWithWork_cost (nat U) + (canonicalMulWithWork (nat 16) (canonicalMulWithWork A A).1).1 (16 * B + 10) (by omega) (by omega) + have hfw := canonicalMulWithWork_width (nat 4) A B h4 hA + have hfc := canonicalMulWithWork_cost (nat 4) A B h4 hA + have huw := canonicalMulWithWork_width (canonicalMulWithWork (nat 4) A).1 (nat U) + (4 * B + 2) hfw (by omega) + have huc := canonicalMulWithWork_cost (canonicalMulWithWork (nat 4) A).1 (nat U) + (4 * B + 2) hfw (by omega) + have hlow := leWithWork_cost + (divWithWork (nat U) (canonicalMulWithWork (nat 16) (canonicalMulWithWork A A).1).1).1 + (nat b) (64 * B + 44) (by omega) (by omega) + have hhigh := leWithWork_cost (nat b) + (canonicalMulWithWork (canonicalMulWithWork (nat 4) A).1 (nat U)).1 + (64 * B + 44) (by omega) (by omega) + simp only [Nat.add_assoc, Nat.reduceAdd] at hdc hlc huc hlow hhigh + change _ + _ + _ + _ + _ + _ + _ + Nat.size U + Nat.size b + 7 ≤ _ + unfold initialScaleGuardBitBudget + omega + +theorem initialCenterGuardWithWork_cost (b U B : ℕ) (A : BinaryFraction) + (hB : 8 ≤ B) (hb : Nat.size b + 2 ≤ B) (hU : Nat.size U + 2 ≤ B) (hA : A.width ≤ B) : + (initialCenterGuardWithWork b U A).2 ≤ initialCenterGuardBitBudget B := by + have h2 : (nat 2).width ≤ B := (nat_width_le 2).trans (by change 4 ≤ B; omega) + have h4 : (nat 4).width ≤ B := (nat_width_le 4).trans (by change 5 ≤ B; omega) + have hUn := (nat_width_le U).trans hU + have hbn := (nat_width_le b).trans hb + have hlw := divWithWork_width_uniform (nat b) (nat 2) B hbn h2 + have hlc := divWithWork_cost (nat b) (nat 2) B hbn h2 + have hfw := canonicalMulWithWork_width (nat 4) A B h4 hA + have hfc := canonicalMulWithWork_cost (nat 4) A B h4 hA + have huw := canonicalMulWithWork_width (canonicalMulWithWork (nat 4) A).1 (nat b) + (4 * B + 2) hfw (by omega) + have huc := canonicalMulWithWork_cost (canonicalMulWithWork (nat 4) A).1 (nat b) + (4 * B + 2) hfw (by omega) + have hlow := leWithWork_cost (divWithWork (nat b) (nat 2)).1 (nat U) + (16 * B + 10) (by omega) (by omega) + have hhigh := leWithWork_cost (nat U) + (canonicalMulWithWork (canonicalMulWithWork (nat 4) A).1 (nat b)).1 + (16 * B + 10) (by omega) (by omega) + simp only [Nat.add_assoc, Nat.reduceAdd] at hlc huc hlow hhigh + change _ + _ + _ + _ + _ + Nat.size b + Nat.size U + 5 ≤ _ + unfold initialCenterGuardBitBudget + omega + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryInitialKernel.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryInitialKernel.lean new file mode 100644 index 0000000000000000000000000000000000000000..2d5968c5beb29492c67f46093876cdcdd381b7d8 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryInitialKernel.lean @@ -0,0 +1,80 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryRepresentativeKernel +import OAI.Combinatorics.EditApproximation.Binary.BinaryMedianKernel +import OAI.Combinatorics.EditApproximation.Geometry.LocalInitialCones +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Literal initial-cone arithmetic on gathered integer seed entries. The +local grid list is supplied by its bounded enumerator; all values, ceilings, +spatial charges and the fallback minimum are computed on binary storage. -/ + +namespace EditApproximation +namespace BinaryFraction + + + +@[simp] theorem ofNaturalWord_value (bits : List Bool) : + (ofNaturalWord bits).value = (bitWordValue bits : ℚ) := by + simp only [ofNaturalWord, value, SignedBinary.value, signedMagnitude, Bool.false_eq_true, + ↓reduceIte, Int.cast_natCast, bitWordValue, Bool.toNat_true, Nat.mul_zero, Nat.add_zero, + Nat.cast_one, div_one] + +@[simp] theorem ofNaturalWord_width (bits : List Bool) : + (ofNaturalWord bits).width = max bits.length 1 := rfl + + + +@[simp] theorem scaledSeedWithWork_value (U : ℕ) (a gap : BinaryFraction) : + (scaledSeedWithWork U a gap).1.value = scaledSeedValue U a.value gap.value := by + simp only [scaledSeedWithWork, maxWithWork_value, ofNaturalWord_value, + naturalCeilingWithWork_value, divWithWork_value, nat_value, absolute_value, scaledSeedValue] + + + +@[simp] theorem initialConeWithWork_value {α : Type*} (source target : List α) + (U : TargetInterval target.length → ℕ) (a L : BinaryFraction) + (query center : TargetInterval target.length) : + (initialConeWithWork source.length U a L query center).1.value = + initialConeValue source target U a.value L.value query center := by + simp only [initialConeWithWork, canonicalAddWithWork_value, canonicalMulWithWork_value, + scaledSeedWithWork_value, stateGapWithWork_value, endpointDistanceWithWork_value, + initialConeValue, rationalStateGap] + +/-- The local initial-cone arithmetic after the center list has been +constructed and the corresponding seed values gathered. -/ +def initialMinimumWithWork {n : ℕ} (sourceLength : ℕ) (U : TargetInterval n → ℕ) + (N F : ℕ) (a : BinaryFraction) (query : TargetInterval n) (centers : List (TargetInterval n)) : + BinaryFraction × ℕ := + let zeroTest := naturalEqualWithWork (U query) 0 + if zeroTest.1 then (zero, zeroTest.2 + 1) else + let L := canonicalMulWithWork (nat 32) (nat F) + let coefficient := canonicalAddWithWork L.1 one + let fallback := canonicalMulWithWork coefficient.1 (nat N) + let scores := arithmeticMapWithWork (initialConeWithWork sourceLength U a L.1 query) centers + let result := minimumWithWork fallback.1 scores.1 + (result.1, zeroTest.2 + L.2 + coefficient.2 + fallback.2 + scores.2 + result.2 + + Nat.size F + Nat.size N + 6) + +theorem initialMinimumWithWork_value {α : Type*} (source target : List α) + (U : TargetInterval target.length → ℕ) (N P F : ℕ) (A : ℚ) (a : BinaryFraction) + (query : TargetInterval target.length) : + (initialMinimumWithWork source.length U N F a query + (localInitialConeCenters N P A U query)).1.value = + localInitialConeTable source target U N P F A a.value query := by + have hzero : (naturalEqualWithWork (U query) 0).1 = true ↔ U query = 0 := + naturalEqualWithWork_value _ _ + unfold initialMinimumWithWork localInitialConeTable + by_cases hz : U query = 0 + · rw [ite_eq_left (hzero.mpr hz), ite_eq_left hz] + rw [← representation_value, zero_representation, UnreducedRational.value_zero] + · rw [ite_eq_right (fun h => hz (hzero.mp h)), ite_eq_right hz] + simp only [minimumWithWork_value, canonicalMulWithWork_value, canonicalAddWithWork_value, + arithmeticMapWithWork_value, List.map_map, Function.comp_def, initialConeWithWork_value, + nat_value, one, Nat.cast_one, Nat.cast_ofNat] + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryInitialMinimumWork.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryInitialMinimumWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..ff583a7575d66361c8d297722971ed73d9e004f5 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryInitialMinimumWork.lean @@ -0,0 +1,104 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryInitialWork + +namespace OAI + +/-! The initial entry's complete arithmetic counter, including its zero +test, spatial coefficient, fallback and finite minimum. Grid construction +is charged by the separate local endpoint enumerator. -/ + +namespace EditApproximation +namespace BinaryFraction + +def initialMinimumInputBudget (B : ℕ) : ℕ := 40 * B + 22 + +def initialMinimumWordBudget (B : ℕ) : ℕ := + 128 * B + 90 + initialConeWordBudget (initialMinimumInputBudget B) + +def initialMinimumBitBudget (n B : ℕ) : ℕ := + (8 * B + 2) + 2000 * (B + 1) ^ 2 + 6000 * (4 * B + 3) ^ 2 + + 2000 * (32 * B + 23) ^ 2 + n * (initialConeBitBudget (initialMinimumInputBudget B) + 3) + + (1 + n * (1000 * (initialMinimumWordBudget B + 1) ^ 2 + 2)) + 2 * B + 6 + +theorem initialMinimumWithWork_bounds {n : ℕ} (sourceLength : ℕ) (U : TargetInterval n → ℕ) + (N F : ℕ) (a : BinaryFraction) (query : TargetInterval n) (centers : List (TargetInterval n)) + (B : ℕ) (hB : 8 ≤ B) (hs : Nat.size sourceLength + 2 ≤ B) + (hUq : Nat.size (U query) ≤ B) (hN : Nat.size N + 2 ≤ B) (hF : Nat.size F + 2 ≤ B) + (ha : a.width ≤ B) (hql : Nat.size query.lo + 2 ≤ B) (hqh : Nat.size query.hi + 2 ≤ B) + (hcenters : ∀ center ∈ centers, Nat.size (U center) + 2 ≤ B ∧ + Nat.size center.lo + 2 ≤ B ∧ Nat.size center.hi + 2 ≤ B) : + (initialMinimumWithWork sourceLength U N F a query centers).1.width ≤ initialMinimumWordBudget B ∧ + (initialMinimumWithWork sourceLength U N F a query centers).2 ≤ + initialMinimumBitBudget centers.length B := by + let L := canonicalMulWithWork (nat 32) (nat F) + let coefficient := canonicalAddWithWork L.1 one + let fallback := canonicalMulWithWork coefficient.1 (nat N) + let W := initialMinimumInputBudget B + have hW : B ≤ W := by dsimp only [W, initialMinimumInputBudget]; omega + have h32 : (nat 32).width ≤ B := by + have h : (nat 32).width ≤ 8 := by decide + omega + have hFw := (nat_width_le F).trans hF + have hNw := (nat_width_le N).trans hN + have hL := canonicalMulWithWork_width (nat 32) (nat F) B h32 hFw + have hLc := canonicalMulWithWork_cost (nat 32) (nat F) B h32 hFw + have hcoef := canonicalAddWithWork_width L.1 one (4 * B + 2) hL (by change 1 ≤ _; omega) + have hcoefc := canonicalAddWithWork_cost L.1 one (4 * B + 2) hL (by change 1 ≤ _; omega) + have hcoefBound : coefficient.1.width ≤ 32 * B + 22 := by + change coefficient.1.width ≤ _ at hcoef + omega + have hfall := canonicalMulWithWork_width coefficient.1 (nat N) (32 * B + 22) hcoefBound (by omega) + have hfallc := canonicalMulWithWork_cost coefficient.1 (nat N) (32 * B + 22) hcoefBound (by omega) + have hscore (center : TargetInterval n) (hc : center ∈ centers) := + initialConeWithWork_bounds sourceLength U a L.1 query center W (by omega) + (hs.trans hW) ((hcenters center hc).1.trans hW) (ha.trans hW) (hL.trans (by + dsimp only [W, initialMinimumInputBudget]; omega)) + (hql.trans hW) (hqh.trans hW) ((hcenters center hc).2.1.trans hW) + ((hcenters center hc).2.2.trans hW) + let scores := arithmeticMapWithWork (initialConeWithWork sourceLength U a L.1 query) centers + have hscoreWidths : ∀ score ∈ scores.1, score.width ≤ initialMinimumWordBudget B := by + intro score hscore' + simp only [scores, arithmeticMapWithWork_value] at hscore' + obtain ⟨center, hc, rfl⟩ := List.mem_map.mp hscore' + exact (hscore center hc).1.trans (by + change initialConeWordBudget (initialMinimumInputBudget B) ≤ _ + unfold initialMinimumWordBudget + omega) + have hfallWidth : fallback.1.width ≤ initialMinimumWordBudget B := hfall.trans (by + unfold initialMinimumWordBudget; omega) + have hscoreCost := arithmeticMapWithWork_cost (initialConeWithWork sourceLength U a L.1 query) + centers (initialConeBitBudget W) (fun center hc => (hscore center hc).2) + have hmin := minimumWithWork_width fallback.1 scores.1 (initialMinimumWordBudget B) + hfallWidth hscoreWidths + have hminCost := minimumWithWork_cost fallback.1 scores.1 (initialMinimumWordBudget B) + hfallWidth hscoreWidths + have hlen : scores.1.length = centers.length := by + simp only [scores, arithmeticMapWithWork_value, List.length_map] + rw [hlen] at hminCost + have hz := naturalEqualWithWork_cost (U query) 0 B hUq (by simp) + unfold initialMinimumWithWork + dsimp only + split_ifs with hzero + · constructor + · have hwidth : zero.width = 1 := rfl + change zero.width ≤ _ + rw [hwidth] + unfold initialMinimumWordBudget + omega + · change (naturalEqualWithWork (U query) 0).2 + 1 ≤ _ + unfold initialMinimumBitBudget + omega + · refine ⟨hmin, ?_⟩ + change (naturalEqualWithWork (U query) 0).2 + L.2 + coefficient.2 + fallback.2 + + scores.2 + (minimumWithWork fallback.1 scores.1).2 + Nat.size F + Nat.size N + 6 ≤ _ + change scores.2 ≤ centers.length * (initialConeBitBudget (initialMinimumInputBudget B) + 3) at hscoreCost + change L.2 ≤ _ at hLc + change coefficient.2 ≤ _ at hcoefc + change fallback.2 ≤ _ at hfallc + simp only [Nat.add_assoc, Nat.reduceAdd] at hcoefc hfallc + unfold initialMinimumBitBudget + omega + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryInitialReadSpace.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryInitialReadSpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..288c2e442c4b2dc5342879c005c29ce4f00719e0 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryInitialReadSpace.lean @@ -0,0 +1,107 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryInitialGuardSpace +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation.BinaryFraction + +section Reads +variable {n : ℕ} (read : TargetInterval n → List Bool × ℕ) (allocation : TargetInterval n → ℕ) + + + +theorem initialGridReadAllocation_le_work (P : ℕ) (A : BinaryFraction) (radius : ℕ) (q : TargetInterval n) (b : ℕ) + (ha : ∀ r, allocation r ≤ (read r).2) : + initialGridReadAllocation read allocation P A radius q b ≤ (initialGridReadWithWork P A read radius q b).2 := by + let spacing := (seedGridSpacingWithWork b P).1 + have hs := seedGridSpacingAllocation_le_work b P + have hg := gridStateBoxAllocation_le_work n (bitWordValue spacing) radius q.lo q.hi + have hf := filterAllocation_le_work + (fun r => ((initialCenterGuardWithWork b (bitWordValue (read r).1) A).1, + (initialCenterGuardWithWork b (bitWordValue (read r).1) A).2 + (read r).2)) + (fun r => initialCenterGuardAllocation b (bitWordValue (read r).1) A + allocation r) + (gridStateBoxWithWork n (bitWordValue spacing) radius q.lo q.hi).1 + (fun r _ => Nat.add_le_add (initialCenterGuardAllocation_le_work b (bitWordValue (read r).1) A) (ha r)) + unfold initialGridReadAllocation initialGridReadWithWork + dsimp only [spacing] at hg hf ⊢ + omega + + + +theorem initialCentersReadAllocation_le_work (N P : ℕ) (A : BinaryFraction) (q : TargetInterval n) + (ha : ∀ r, allocation r ≤ (read r).2) : + initialCentersReadAllocation read allocation N P A q ≤ (initialCentersReadWithWork N P A read q).2 := by + let Uq := bitWordValue (read q).1 + have hq := ha q + have hd := dyadicScalesAllocation_le_work N + have hf := filterAllocation_le_work (fun b => initialScaleGuardWithWork Uq b A) + (fun b => initialScaleGuardAllocation Uq b A) (dyadicScalesWithWork N).1 + (fun b _ => initialScaleGuardAllocation_le_work Uq b A) + have hm := arithmeticFlatMapAllocation_le_work (initialGridReadWithWork P A read Uq q) + (initialGridReadAllocation read allocation P A Uq q) + (filterWithWork (fun b => initialScaleGuardWithWork Uq b A) (dyadicScalesWithWork N).1).1 + (fun b _ => initialGridReadAllocation_le_work read allocation P A Uq q b ha) + unfold initialCentersReadAllocation initialCentersReadWithWork + dsimp only [Uq] at hf hm ⊢ + omega + + + +theorem initialConeReadAllocation_le_work (sourceLength : ℕ) (a L : BinaryFraction) (query center : TargetInterval n) + (ha : ∀ r, allocation r ≤ (read r).2) : + initialConeReadAllocation read allocation sourceLength a L query center ≤ + (initialConeReadWithWork sourceLength read a L query center).2 := by + have hr := ha center + have hc := initialConeAllocation_le_work sourceLength (bitWordValue (read center).1) a L query center + unfold initialConeReadAllocation initialConeReadWithWork + dsimp only + omega + + + +theorem initialMinimumReadAllocation_le_work (sourceLength N F : ℕ) (a : BinaryFraction) + (query : TargetInterval n) (centers : List (TargetInterval n)) (ha : ∀ r, allocation r ≤ (read r).2) : + initialMinimumReadAllocation read allocation sourceLength N F a query centers ≤ + (initialMinimumReadWithWork sourceLength read N F a query centers).2 := by + let L := (canonicalMulWithWork (nat 32) (nat F)).1 + let coefficient := (canonicalAddWithWork L one).1 + have hq := ha query + have hz := naturalEqualAllocation_le_work (bitWordValue (read query).1) 0 + have hL := canonicalMulAllocation_le_work (nat 32) (nat F) + have hc := canonicalAddAllocation_le_work L one + have hf := canonicalMulAllocation_le_work coefficient (nat N) + have hs := arithmeticMapAllocation_le_work (initialConeReadWithWork sourceLength read a L query) + (initialConeReadAllocation read allocation sourceLength a L query) centers + (fun center _ => initialConeReadAllocation_le_work read allocation sourceLength a L query center ha) + have hm := minimumAllocation_le_work (canonicalMulWithWork coefficient (nat N)).1 + (arithmeticMapWithWork (initialConeReadWithWork sourceLength read a L query) centers).1 + unfold initialMinimumReadAllocation initialMinimumReadWithWork + dsimp only + split_ifs <;> dsimp only [L, coefficient] at hc hf hs hm ⊢ <;> omega + + + +theorem initialProgramReadAllocation_le_work (sourceLength N P F : ℕ) (A a : BinaryFraction) (query : TargetInterval n) + (ha : ∀ r, allocation r ≤ (read r).2) : + initialProgramReadAllocation read allocation sourceLength N P F A a query ≤ + (initialProgramReadWithWork sourceLength N P F A a read query).2 := by + have hc := initialCentersReadAllocation_le_work read allocation N P A query ha + have hm := initialMinimumReadAllocation_le_work read allocation sourceLength N F a query + (initialCentersReadWithWork N P A read query).1 ha + unfold initialProgramReadAllocation initialProgramReadWithWork + dsimp only + omega + + + +theorem cachedInitialProgramReadAllocation_le_work (sourceLength N P F : ℕ) (A a : BinaryFraction) + (query : TargetInterval n) (ha : ∀ r, allocation r ≤ (read r).2) : + cachedInitialProgramReadAllocation read allocation sourceLength N P F A a query ≤ + (cachedInitialProgramReadWithWork sourceLength N P F A a read query).2 := + finishCachedAllocation_le_work _ _ _ _ _ (initialProgramReadAllocation_le_work read allocation sourceLength N P F A a query ha) + +end Reads +end EditApproximation.BinaryFraction + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryInitialReads.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryInitialReads.lean new file mode 100644 index 0000000000000000000000000000000000000000..ed44c3ae8b23ba37671b51882026015a32388383 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryInitialReads.lean @@ -0,0 +1,169 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryScaleGrid +import OAI.Combinatorics.EditApproximation.Binary.BinaryReadComposition +import OAI.Combinatorics.EditApproximation.Binary.BinaryCachedShellWork +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Inline initial-cone evaluation reads the gathered previous-pass seed +words explicitly. Each query seed is loaded once per routine and each +visited center load contributes its measured lookup cost. -/ + +namespace EditApproximation +namespace BinaryFraction + + + +def initialGridPlainWithWork {n : ℕ} (P : ℕ) (A : BinaryFraction) + (U : TargetInterval n → ℕ) (radius : ℕ) (q : TargetInterval n) (b : ℕ) : + List (TargetInterval n) × ℕ := + let spacing := seedGridSpacingWithWork b P + let points := gridStateBoxWithWork n (bitWordValue spacing.1) radius q.lo q.hi + let selected := filterWithWork (fun r => initialCenterGuardWithWork b (U r) A) points.1 + (selected.1, spacing.2 + points.2 + selected.2 + 2) + +theorem initialGridReadWithWork_eq_cost {n : ℕ} (P : ℕ) (A : BinaryFraction) + (read : TargetInterval n → List Bool × ℕ) (radius : ℕ) (q : TargetInterval n) (b R : ℕ) + (hR : ∀ r, (read r).2 ≤ R) : + (initialGridReadWithWork P A read radius q b).1 = + (initialGridPlainWithWork P A (fun r => bitWordValue (read r).1) radius q b).1 ∧ + (initialGridReadWithWork P A read radius q b).2 ≤ + (initialGridPlainWithWork P A (fun r => bitWordValue (read r).1) radius q b).2 * (R + 1) := by + let spacing := seedGridSpacingWithWork b P + let points := gridStateBoxWithWork n (bitWordValue spacing.1) radius q.lo q.hi + have h := filterWithWork_add_read + (fun r => initialCenterGuardWithWork b (bitWordValue (read r).1) A) + (fun r => (read r).2) points.1 R (fun r _ => hR r) + constructor + · simpa only [initialGridReadWithWork, initialGridPlainWithWork, spacing, points] using h.1 + · change spacing.2 + points.2 + _ + 2 ≤ (spacing.2 + points.2 + _ + 2) * (R + 1) + nlinarith only [h.2] + + + +theorem initialCentersReadWithWork_eq_cost {n : ℕ} (N P : ℕ) (A : BinaryFraction) + (read : TargetInterval n → List Bool × ℕ) (q : TargetInterval n) (R : ℕ) + (hR : ∀ r, (read r).2 ≤ R) : + (initialCentersReadWithWork N P A read q).1 = + (initialCentersWithWork N P A (fun r => bitWordValue (read r).1) q).1 ∧ + (initialCentersReadWithWork N P A read q).2 ≤ + (initialCentersWithWork N P A (fun r => bitWordValue (read r).1) q).2 * (R + 2) := by + let Uq := bitWordValue (read q).1 + let scales := dyadicScalesWithWork N + let active := filterWithWork (fun b => initialScaleGuardWithWork Uq b A) scales.1 + let plain := initialGridPlainWithWork P A (fun r => bitWordValue (read r).1) Uq q + have h := arithmeticFlatMapWithWork_factor (initialGridReadWithWork P A read Uq q) + plain active.1 (R + 1) (by omega) + (fun b _ => (initialGridReadWithWork_eq_cost P A read Uq q b R hR).1) + (fun b _ => (initialGridReadWithWork_eq_cost P A read Uq q b R hR).2) + have hq := hR q + refine ⟨h.1, ?_⟩ + change (read q).2 + scales.2 + active.2 + _ + 3 ≤ + (scales.2 + active.2 + (arithmeticFlatMapWithWork plain active.1).2 + 3) * (R + 2) + nlinarith only [h.2, hq] + + + +theorem initialConeReadWithWork_eq_cost {n : ℕ} (sourceLength : ℕ) + (read : TargetInterval n → List Bool × ℕ) (a L : BinaryFraction) + (query center : TargetInterval n) (R : ℕ) (hR : (read center).2 ≤ R) : + (initialConeReadWithWork sourceLength read a L query center).1 = + (initialConeWithWork sourceLength (fun r => bitWordValue (read r).1) a L query center).1 ∧ + (initialConeReadWithWork sourceLength read a L query center).2 ≤ + (initialConeWithWork sourceLength (fun r => bitWordValue (read r).1) a L query center).2 + R := by + constructor + · rfl + · have heq : initialConeWithWork sourceLength (fun _ => bitWordValue (read center).1) a L query center = + initialConeWithWork sourceLength (fun r => bitWordValue (read r).1) a L query center := rfl + change (read center).2 + _ ≤ _ + R + rw [heq] + omega + + + +theorem initialMinimumReadWithWork_eq_cost {n : ℕ} (sourceLength : ℕ) + (read : TargetInterval n → List Bool × ℕ) (N F : ℕ) (a : BinaryFraction) + (query : TargetInterval n) (centers : List (TargetInterval n)) (R : ℕ) + (hR : ∀ r, (read r).2 ≤ R) : + (initialMinimumReadWithWork sourceLength read N F a query centers).1 = + (initialMinimumWithWork sourceLength (fun r => bitWordValue (read r).1) N F a query centers).1 ∧ + (initialMinimumReadWithWork sourceLength read N F a query centers).2 ≤ + (initialMinimumWithWork sourceLength (fun r => bitWordValue (read r).1) N F a query centers).2 * + (R + 2) := by + let L := canonicalMulWithWork (nat 32) (nat F) + have hmap := arithmeticMapWithWork_extra + (initialConeReadWithWork sourceLength read a L.1 query) + (initialConeWithWork sourceLength (fun r => bitWordValue (read r).1) a L.1 query) + (fun _ => R) centers + (fun r _ => (initialConeReadWithWork_eq_cost sourceLength read a L.1 query r R (hR r)).1) + (fun r _ => (initialConeReadWithWork_eq_cost sourceLength read a L.1 query r R (hR r)).2) + have hs : (centers.map (fun _ => R)).sum = centers.length * R := by + simp only [List.map_const', List.sum_replicate, smul_eq_mul] + rw [hs] at hmap + have hlen := arithmeticMapWithWork_length_le_cost + (initialConeWithWork sourceLength (fun r => bitWordValue (read r).1) a L.1 query) centers + have hquery := hR query + unfold initialMinimumReadWithWork initialMinimumWithWork + dsimp only + split_ifs + · constructor + · rfl + · nlinarith only [hquery] + · constructor + · simp only [L, hmap.1] + · dsimp only + rw [show (canonicalMulWithWork (nat 32) (nat F)) = L from rfl, hmap.1] + have hprod := Nat.mul_le_mul_right R hlen + nlinarith only [hmap.2, hquery, hprod] + + + +theorem initialProgramReadWithWork_eq_cost {n : ℕ} (sourceLength N P F : ℕ) (A a : BinaryFraction) + (read : TargetInterval n → List Bool × ℕ) (query : TargetInterval n) (R : ℕ) + (hR : ∀ r, (read r).2 ≤ R) : + (initialProgramReadWithWork sourceLength N P F A a read query).1 = + (initialProgramWithWork sourceLength N P F A a (fun r => bitWordValue (read r).1) query).1 ∧ + (initialProgramReadWithWork sourceLength N P F A a read query).2 ≤ + (initialProgramWithWork sourceLength N P F A a (fun r => bitWordValue (read r).1) query).2 * + (R + 2) := by + have hc := initialCentersReadWithWork_eq_cost N P A read query R hR + have hm := initialMinimumReadWithWork_eq_cost sourceLength read N F a query + (initialCentersWithWork N P A (fun r => bitWordValue (read r).1) query).1 R hR + unfold initialProgramReadWithWork initialProgramWithWork + dsimp only + rw [hc.1] + constructor + · exact hm.1 + · nlinarith only [hc.2, hm.2] + +theorem finishCachedWithWork_read_factor (read plain : BinaryFraction × ℕ) + (base : List Bool) (hbase : 0 < bitWordValue base) (remaining K : ℕ) + (hK : 1 ≤ K) (hvalue : read.1 = plain.1) (hcost : read.2 ≤ plain.2 * K) : + (finishCachedWithWork read base hbase remaining).1 = + (finishCachedWithWork plain base hbase remaining).1 ∧ + (finishCachedWithWork read base hbase remaining).2 ≤ + (finishCachedWithWork plain base hbase remaining).2 * K := by + unfold finishCachedWithWork + dsimp only + rw [hvalue] + refine ⟨rfl, ?_⟩ + nlinarith only [hK, hcost] + + + +theorem cachedInitialProgramReadWithWork_eq_cost {n : ℕ} (sourceLength N P F : ℕ) (A a : BinaryFraction) + (read : TargetInterval n → List Bool × ℕ) (query : TargetInterval n) (R : ℕ) + (hR : ∀ r, (read r).2 ≤ R) : + (cachedInitialProgramReadWithWork sourceLength N P F A a read query).1 = + (cachedInitialProgramWithWork sourceLength N P F A a (fun r => bitWordValue (read r).1) query).1 ∧ + (cachedInitialProgramReadWithWork sourceLength N P F A a read query).2 ≤ + (cachedInitialProgramWithWork sourceLength N P F A a (fun r => bitWordValue (read r).1) query).2 * + (R + 2) := by + have h := initialProgramReadWithWork_eq_cost sourceLength N P F A a read query R hR + exact finishCachedWithWork_read_factor _ _ [true] (by decide) 0 (R + 2) (by omega) h.1 h.2 + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryInitialWork.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryInitialWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..5f2382a215a36b73170b82e70f8b473ab6598cad --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryInitialWork.lean @@ -0,0 +1,99 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryInitialKernel +import OAI.Combinatorics.EditApproximation.Binary.BinaryRepresentativeWork + +namespace OAI + +/-! Input-width bounds for executed ceilings and initial-cone arithmetic. -/ + +namespace EditApproximation +namespace BinaryFraction + +def scaledSeedWordBudget (B : ℕ) : ℕ := 4 * B + 6 + +def scaledSeedBitBudget (B : ℕ) : ℕ := + 2100 * (B + 2) ^ 2 + 500 * (4 * B + 5) ^ 2 + + (1000 * (4 * B + 7) ^ 2 + 1) + B + 3 + +theorem scaledSeedWithWork_bounds (U : ℕ) (a gap : BinaryFraction) (B : ℕ) + (_hB : 1 ≤ B) (hU : Nat.size U + 2 ≤ B) (ha : a.width ≤ B) (hg : gap.width ≤ B) : + (scaledSeedWithWork U a gap).1.width ≤ scaledSeedWordBudget B ∧ + (scaledSeedWithWork U a gap).2 ≤ scaledSeedBitBudget B := by + have hUw := (nat_width_le U).trans hU + have hrw := divWithWork_width_uniform (nat U) a B hUw ha + have hrc := divWithWork_cost (nat U) a B hUw ha + have hcw := naturalCeilingWithWork_length (divWithWork (nat U) a).1 + have hcc := naturalCeilingWithWork_cost (divWithWork (nat U) a).1 + have hp := Nat.pow_le_pow_left (show (divWithWork (nat U) a).1.width + 1 ≤ 4 * B + 5 by omega) 2 + have hround : (ofNaturalWord (naturalCeilingWithWork (divWithWork (nat U) a).1).1).width ≤ 4 * B + 6 := by + rw [ofNaturalWord_width] + omega + have hgw : gap.absolute.width ≤ 4 * B + 6 := (absolute_width gap).le.trans (by omega) + have hmw := maxWithWork_width (ofNaturalWord (naturalCeilingWithWork (divWithWork (nat U) a).1).1) gap.absolute + have hmc := maxWithWork_cost (ofNaturalWord (naturalCeilingWithWork (divWithWork (nat U) a).1).1) + gap.absolute (4 * B + 6) hround hgw + constructor + · change (maxWithWork (ofNaturalWord (naturalCeilingWithWork (divWithWork (nat U) a).1).1) + gap.absolute).1.width ≤ scaledSeedWordBudget B + unfold scaledSeedWordBudget + omega + · change _ + _ + _ + Nat.size U + 3 ≤ _ + simp only [Nat.add_assoc, Nat.reduceAdd] at hmc + unfold scaledSeedBitBudget + omega + +def initialConeInputBudget (B : ℕ) : ℕ := B + endpointDistanceWordBudget B + stateGapWordBudget B + +def initialConeWordBudget (B : ℕ) : ℕ := 32 * initialConeInputBudget B + 54 + +def initialConeBitBudget (B : ℕ) : ℕ := + stateGapBitBudget B + scaledSeedBitBudget (initialConeInputBudget B) + endpointDistanceBitBudget B + + 2000 * (initialConeInputBudget B + 1) ^ 2 + + 6000 * (4 * initialConeInputBudget B + 7) ^ 2 + 4 + +theorem initialConeWithWork_bounds {n : ℕ} (sourceLength : ℕ) (U : TargetInterval n → ℕ) + (a L : BinaryFraction) (query center : TargetInterval n) (B : ℕ) (hB : 1 ≤ B) + (hs : Nat.size sourceLength + 2 ≤ B) (hU : Nat.size (U center) + 2 ≤ B) + (ha : a.width ≤ B) (hL : L.width ≤ B) + (hql : Nat.size query.lo + 2 ≤ B) (hqh : Nat.size query.hi + 2 ≤ B) + (hcl : Nat.size center.lo + 2 ≤ B) (hch : Nat.size center.hi + 2 ≤ B) : + (initialConeWithWork sourceLength U a L query center).1.width ≤ initialConeWordBudget B ∧ + (initialConeWithWork sourceLength U a L query center).2 ≤ initialConeBitBudget B := by + let W := initialConeInputBudget B + have hBW : B ≤ W := by dsimp only [W, initialConeInputBudget]; omega + have hgap := stateGapWithWork_bounds sourceLength center B hs hcl hch + have hdist := endpointDistanceWithWork_bounds query center B hql hqh hcl hch + have hgapW : (stateGapWithWork sourceLength center).1.width ≤ W := hgap.1.trans (by + dsimp only [W, initialConeInputBudget]; omega) + have hdistW : (endpointDistanceWithWork query center).1.width ≤ W := hdist.1.trans (by + dsimp only [W, initialConeInputBudget]; omega) + have hseed := scaledSeedWithWork_bounds (U center) a (stateGapWithWork sourceLength center).1 W + (hB.trans hBW) (hU.trans hBW) (ha.trans hBW) hgapW + have hspw := canonicalMulWithWork_width L (endpointDistanceWithWork query center).1 W + (hL.trans hBW) hdistW + have hspc := canonicalMulWithWork_cost L (endpointDistanceWithWork query center).1 W + (hL.trans hBW) hdistW + have hseedW : (scaledSeedWithWork (U center) a (stateGapWithWork sourceLength center).1).1.width ≤ 4 * W + 6 := + hseed.1 + have hlastw := canonicalAddWithWork_width + (scaledSeedWithWork (U center) a (stateGapWithWork sourceLength center).1).1 + (canonicalMulWithWork L (endpointDistanceWithWork query center).1).1 (4 * W + 6) hseedW (by omega) + have hlastc := canonicalAddWithWork_cost + (scaledSeedWithWork (U center) a (stateGapWithWork sourceLength center).1).1 + (canonicalMulWithWork L (endpointDistanceWithWork query center).1).1 (4 * W + 6) hseedW (by omega) + constructor + · change (canonicalAddWithWork (scaledSeedWithWork (U center) a (stateGapWithWork sourceLength center).1).1 + (canonicalMulWithWork L (endpointDistanceWithWork query center).1).1).1.width ≤ initialConeWordBudget B + unfold initialConeWordBudget + change _ ≤ 32 * W + 54 + omega + · change _ + _ + _ + _ + _ + 4 ≤ _ + simp only [Nat.add_assoc, Nat.reduceAdd] at hlastc + unfold initialConeBitBudget + change _ ≤ stateGapBitBudget B + scaledSeedBitBudget W + endpointDistanceBitBudget B + + 2000 * (W + 1) ^ 2 + 6000 * (4 * W + 7) ^ 2 + 4 + omega + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryKeyedOnline.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryKeyedOnline.lean new file mode 100644 index 0000000000000000000000000000000000000000..5810bd3e9dbf02cbd6c58c24d4222a6cfa2e198e --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryKeyedOnline.lean @@ -0,0 +1,159 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryCoordinateActionWork +import OAI.Combinatorics.EditApproximation.Binary.BinaryUnskippedKernel +import OAI.Combinatorics.EditApproximation.Binary.BinaryPowerStorage +import OAI.Combinatorics.EditApproximation.Geometry.LocalOnlineProgram +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! The online branch computes its representative, all guards, coordinate +count, iteration bound and accepted source residue before executing the +literal finite optimizer. -/ + +namespace EditApproximation +namespace BinaryFraction + + + +@[simp] theorem reduceOnlineIntegerWithWork_value (K : ℕ) (hK : 0 < K) (integer : ℕ) : + (reduceOnlineIntegerWithWork K hK integer).1 = + boundedOnlineInteger (optimizerTriangularMass K) (optimizerTriangularMass_positive K hK) integer := by + apply Fin.ext + change bitWordValue (binaryNaturalDivModWithWork integer + (bitWordValue (triangularMassWithWork K).1)).2.1 = integer % optimizerTriangularMass K + rw [triangularMassWithWork_value] + exact (binaryNaturalDivModWithWork_spec integer _ (optimizerTriangularMass_positive K hK)).2 + + + +@[simp] theorem onlineIndexSetupWithWork_value {M n : ℕ} (H : ℕ) + (band : List (Fin M → TargetInterval n)) : + (onlineIndexSetupWithWork H band).1 = H + (listedBandCoordinates band).length + 2 := by + simp only [onlineIndexSetupWithWork, binaryNaturalAddWithWork_value, bandCoordinatesWithWork_value] + +private def onlineBandReference {M n : ℕ} (center : TargetInterval n) (b G : ℕ) (hG : 0 < G) + (initial : Fin M → TargetInterval n → BinaryFraction) + (table : ℕ → Fin M × TargetInterval n → BinaryFraction) (eta kappa : BinaryFraction) + (band : List (Fin M → TargetInterval n)) (hne : band ≠ []) (t integer : ℕ) : + PhysicalRationalAction M n := + sharedBandRationalAction center + (finiteOptimizerActionDraw band hne (bandChildEnvelope b band (fun i q => (initial i q).value)) + (rationalOnlineLinear eta.value kappa.value + (childGain (bandChildEnvelope b band (fun i q => (initial i q).value)) + (fun s coordinate => (table s coordinate).value)) + (childDecrement (bandChildEnvelope b band (fun i q => (initial i q).value)) + (fun s coordinate => (table s coordinate).value)) t) + G (G ^ 80) (boundedOnlineInteger _ (optimizerTriangularMass_positive _ (pow_pos hG _)) integer)) + +private theorem onlineBandReference_congr {M n : ℕ} (center : TargetInterval n) + (b G G' : ℕ) (hG : 0 < G) (hG' : 0 < G') (heq : G = G') + (initial : Fin M → TargetInterval n → BinaryFraction) + (table : ℕ → Fin M × TargetInterval n → BinaryFraction) (eta kappa : BinaryFraction) + (band band' : List (Fin M → TargetInterval n)) (hband : band = band') + (hne : band ≠ []) (hne' : band' ≠ []) (t integer : ℕ) : + onlineBandReference center b G hG initial table eta kappa band hne t integer = + onlineBandReference center b G' hG' initial table eta kappa band' hne' t integer := by + cases heq + cases hband + rfl + +def keyedOnlineWithWork {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (P F exponent H b : ℕ) (hb : 0 < b) + (tau eta kappa : BinaryFraction) + (child initial : Fin M → TargetInterval target.length → BinaryFraction) + (table : ℕ → Fin M × TargetInterval target.length → BinaryFraction) + (t : ℕ) (center : TargetInterval target.length) (integer : ℕ) : + Option (BinaryBellmanAction (TargetInterval target.length) + (Fin M × TargetInterval target.length) M) × ℕ := + let band := representativeBandWithWork parent center (parent.hi - parent.lo) b P + tau (inversePowerTwo exponent) child + let setup := onlineIndexSetupWithWork H band.1 + let G := setup.1 + let accepted := reduceOnlineIntegerWithWork (G ^ 80) (by + dsimp only [G, setup] + rw [onlineIndexSetupWithWork_value] + positivity) integer + if hband : band.1 = [] then (none, band.2 + setup.2 + accepted.2 + 1) else + let guard := unskippedCandidateWithWork source target parent b P exponent hb tau (nat F) child initial center + if guard.1.isSome then + let sampled := countedSampledOnlineWithWork center b initial table eta kappa band.1 hband + G (G ^ 80) t accepted.1 + (some sampled.1, band.2 + setup.2 + accepted.2 + guard.2 + sampled.2 + 2) + else (none, band.2 + setup.2 + accepted.2 + guard.2 + 1) + +theorem keyedOnlineWithWork_value {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (P F exponent H b : ℕ) (hb : 0 < b) + (tau eta kappa : BinaryFraction) + (child initial : Fin M → TargetInterval target.length → BinaryFraction) + (table : ℕ → Fin M × TargetInterval target.length → BinaryFraction) + (t : ℕ) (center : TargetInterval target.length) (integer : ℕ) : + ((keyedOnlineWithWork source target parent P F exponent H b hb tau eta kappa child initial table + t center integer).1.map BinaryBellmanAction.decode) = + keyedOnlineCandidate source target parent P F exponent H b tau.value eta.value kappa.value + (fun i q => (child i q).value) (fun i q => (initial i q).value) + (fun i s q => (table s (i, q)).value) t center integer := by + have hband := representativeBandWithWork_value source target parent center b P tau (inversePowerTwo exponent) child + simp only [inversePowerTwo_value] at hband + have hG : (onlineIndexSetupWithWork H (representativeBandWithWork parent center + (parent.hi - parent.lo) b P tau (inversePowerTwo exponent) child).1).1 = + keyedOnlineBandG source target parent P exponent H b tau.value (fun i q => (child i q).value) center := by + rw [onlineIndexSetupWithWork_value, listedBandCoordinates_length, hband] + rfl + have hGpos : 0 < (onlineIndexSetupWithWork H (representativeBandWithWork parent center + (parent.hi - parent.lo) b P tau (inversePowerTwo exponent) child).1).1 := by + rw [onlineIndexSetupWithWork_value] + omega + have hGpos' : 0 < keyedOnlineBandG source target parent P exponent H b tau.value + (fun i q => (child i q).value) center := by + rw [← hG] + exact hGpos + have htest := unskippedCandidateWithWork_value source target parent b P exponent hb tau (nat F) child initial center + unfold keyedOnlineWithWork + dsimp only + split_ifs with hempty hactive + · have he : representativeBandActions source target parent center b P tau.value + ((2 : ℚ) ^ (-(exponent : ℤ))) (fun i q => (child i q).value) = [] := hband.symm.trans hempty + simp only [Option.map_none, keyedOnlineCandidate, dite_eq_left he] + · have he : representativeBandActions source target parent center b P tau.value + ((2 : ℚ) ^ (-(exponent : ℤ))) (fun i q => (child i q).value) ≠ [] := + fun hz => hempty (hband.trans hz) + rw [htest] at hactive + rw [congrArg (fun f : ℚ => (testUnskippedBand source target parent b P exponent tau.value f + (fun i q => (child i q).value) (fun i q => (initial i q).value) center).isSome) (nat_value F)] at hactive + unfold keyedOnlineCandidate + simp only [dite_eq_right he] + cases ht : testUnskippedBand source target parent b P exponent tau.value (F : ℚ) + (fun i q => (child i q).value) (fun i q => (initial i q).value) center with + | none => + have hf : (none : Option (UnskippedBand source target parent b P exponent tau.value (F : ℚ) + (fun i q => (child i q).value) (fun i q => (initial i q).value))).isSome = true := by + simpa only [← ht] using hactive + cases hf + | some member => + simp only [Option.map_some, countedSampledOnlineWithWork_value, + sampledOnlineActionWithWork_value _ _ _ _ _ _ _ _ _ _ _ _ hb, + reduceOnlineIntegerWithWork_value] + apply congrArg some + exact onlineBandReference_congr center b _ _ hGpos hGpos' hG initial table eta kappa _ _ hband hempty he t integer + · have he : representativeBandActions source target parent center b P tau.value + ((2 : ℚ) ^ (-(exponent : ℤ))) (fun i q => (child i q).value) ≠ [] := + fun hz => hempty (hband.trans hz) + rw [htest] at hactive + rw [congrArg (fun f : ℚ => (testUnskippedBand source target parent b P exponent tau.value f + (fun i q => (child i q).value) (fun i q => (initial i q).value) center).isSome) (nat_value F)] at hactive + unfold keyedOnlineCandidate + simp only [dite_eq_right he, Option.map_none] + cases ht : testUnskippedBand source target parent b P exponent tau.value (F : ℚ) + (fun i q => (child i q).value) (fun i q => (initial i q).value) center with + | none => rfl + | some member => + apply False.elim + apply hactive + rw [ht] + rfl + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryLocalGrid.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryLocalGrid.lean new file mode 100644 index 0000000000000000000000000000000000000000..94f7d0c1086ee64b956c310688fd66ad73d8b12c --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryLocalGrid.lean @@ -0,0 +1,101 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryRoundedKernel +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Local endpoint lists executed with binary division, multiplication, +subtraction and validity comparisons. Only the bounded grid-index range +is visited. -/ + +namespace EditApproximation + + + +@[simp] theorem saturatingSubtractWithWork_value (a b : ℕ) : + bitWordValue (saturatingSubtractWithWork a b).1 = a - b := by + unfold saturatingSubtractWithWork + dsimp only + split_ifs with h + · have hlt := (binaryNaturalCompareWithWork_lt a b).mp h + simp only [bitWordValue, Nat.sub_eq_zero_of_le hlt.le] + · exact binaryNaturalSubtractWithWork_value a b (le_of_not_gt (fun hab => + h ((binaryNaturalCompareWithWork_lt a b).mpr hab))) + +theorem saturatingSubtractWithWork_cost (a b : ℕ) : + (saturatingSubtractWithWork a b).2 ≤ 13 * (Nat.size a + Nat.size b) + 4 := by + have htest := binaryNaturalCompareWithWork_cost a b + have hsub := binaryNaturalSubtractWithWork_cost a b + unfold saturatingSubtractWithWork + dsimp only + split_ifs <;> omega + +theorem naturalCeiling_div_eq_ceilDiv (lo g : ℕ) (hg : 0 < g) : + ⌈(lo : ℚ) / g⌉₊ = lo ⌈/⌉ g := by + have hgQ : (0 : ℚ) < g := by exact_mod_cast hg + apply Nat.le_antisymm + · apply Nat.ceil_le.mpr + apply (div_le_iff₀ hgQ).mpr + have h := (ceilDiv_le_iff_le_mul hg).mp (le_rfl : lo ⌈/⌉ g ≤ lo ⌈/⌉ g) + exact_mod_cast (by simpa only [mul_comm] using h : lo ≤ (lo ⌈/⌉ g) * g) + · apply (ceilDiv_le_iff_le_mul hg).mpr + have h := (div_le_iff₀ hgQ).mp (Nat.le_ceil ((lo : ℚ) / g)) + exact_mod_cast (by simpa only [mul_comm] using h : (lo : ℚ) ≤ g * ⌈(lo : ℚ) / g⌉₊) + + + +@[simp] theorem gridPointsWithWork_value (g lo hi : ℕ) (hg : 0 < g) : + (gridPointsWithWork g lo hi).1 = gridPointsBetween g lo hi := by + have hl : bitWordValue (bitCeilDivWithWork g.bits lo.bits).1 = lo ⌈/⌉ g := by + rw [bitCeilDivWithWork_value _ _ (by simpa only [bitWordValue_bits] using hg), + bitWordValue_bits, bitWordValue_bits, naturalCeiling_div_eq_ceilDiv lo g hg] + have hu := (binaryNaturalDivModWithWork_spec hi g hg).1 + simp only [gridPointsWithWork, arithmeticMapWithWork_value, binaryNaturalMulWithWork_value, + saturatingSubtractWithWork_value, binaryNaturalAddWithWork_value, hl, hu, gridPointsBetween] + + + +@[simp] theorem makeStateWithWork_value (n lo hi : ℕ) : + (makeStateWithWork n lo hi).1 = makeTargetState n lo hi := by + have htest : ((wordLEWithWork lo.bits hi.bits).1 && (wordLEWithWork hi.bits n.bits).1) = true ↔ + lo ≤ hi ∧ hi ≤ n := by + simp only [Bool.and_eq_true, wordLEWithWork_value, bitWordValue_bits] + unfold makeStateWithWork makeTargetState + dsimp only + by_cases h : lo ≤ hi ∧ hi ≤ n + · rw [dite_eq_left (htest.mpr h), dite_eq_left h] + · rw [dite_eq_right (fun ht => h (htest.mp ht)), dite_eq_right h] + + + +@[simp] theorem filterMapWithWork_value {α β : Type*} (f : α → Option β × ℕ) (values : List α) : + (filterMapWithWork f values).1 = values.filterMap (fun a => (f a).1) := by + induction values with + | nil => rfl + | cons a rest ih => + simp only [filterMapWithWork, List.filterMap_cons, ih] + cases (f a).1 <;> rfl + +theorem filterMapWithWork_cost {α β : Type*} (f : α → Option β × ℕ) (values : List α) + (C : ℕ) (hC : ∀ a ∈ values, (f a).2 ≤ C) : + (filterMapWithWork f values).2 ≤ values.length * (C + 3) := by + induction values with + | nil => simp only [filterMapWithWork, List.length_nil, Nat.zero_mul, le_refl] + | cons a rest ih => + have ha := hC a (by simp) + have ht := ih (fun b hb => hC b (by simp [hb])) + change (f a).2 + (filterMapWithWork f rest).2 + 3 ≤ _ + simp only [List.length_cons, Nat.add_mul, Nat.one_mul] + omega + + + +@[simp] theorem gridStateBoxWithWork_value (n g radius lo hi : ℕ) (hg : 0 < g) : + (gridStateBoxWithWork n g radius lo hi).1 = gridStateBox n g radius lo hi := by + simp only [gridStateBoxWithWork, arithmeticFlatMapWithWork_value, filterMapWithWork_value, + makeStateWithWork_value, gridPointsWithWork_value _ _ _ hg, saturatingSubtractWithWork_value, + binaryNaturalAddWithWork_value, gridStateBox] + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryLocalGridWork.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryLocalGridWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..fb28cc7d79842131c90b56c34e92bbb3c6b001b6 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryLocalGridWork.lean @@ -0,0 +1,191 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryLocalGrid + +namespace OAI + +/-! Binary work for the actual bounded endpoint-index loops. The bound is +linear in the emitted one-dimensional grid size and quadratic in bit width. -/ + +namespace EditApproximation + +private theorem wordValue_size_le (bits : List Bool) : Nat.size (bitWordValue bits) ≤ bits.length := + Nat.size_le.mpr (bitWordValue_lt_pow_length bits) + +theorem binaryNaturalAdd_size_le (a b : ℕ) : + Nat.size (a + b) ≤ max (Nat.size a) (Nat.size b) + 2 := by + have hv := wordValue_size_le (binaryNaturalAddWithWork a b).1 + have hl := bitAddWithWork_length a.bits b.bits false + rw [binaryNaturalAddWithWork_value] at hv + have hsmall : Nat.size (a + b) ≤ max (Nat.size a) (Nat.size b) + 1 := by + simpa only [binaryNaturalAddWithWork, Nat.size_eq_bits_len] using hv.trans hl + omega + +def gridPointsBitBudget (n B : ℕ) : ℕ := + 1000 * (B + 2) ^ 2 + n * (100 * (B + 3) ^ 2 + 5) + +theorem gridPointsWithWork_cost (g lo hi B : ℕ) (hg : 0 < g) + (hgs : Nat.size g ≤ B) (hlo : Nat.size lo ≤ B) (hhi : Nat.size hi ≤ B) : + (gridPointsWithWork g lo hi).2 ≤ gridPointsBitBudget (gridPointsBetween g lo hi).length B := by + let lower := bitCeilDivWithWork g.bits lo.bits + let upper := binaryNaturalDivModWithWork hi g + let stop := binaryNaturalAddWithWork (bitWordValue upper.1) 1 + let count := saturatingSubtractWithWork (bitWordValue stop.1) (bitWordValue lower.1) + let indices := List.range' (bitWordValue lower.1) (bitWordValue count.1) + have hlowers : Nat.size (bitWordValue lower.1) ≤ B + 2 := by + have h := (wordValue_size_le lower.1).trans (bitCeilDivWithWork_length g.bits lo.bits) + exact h.trans (by simpa only [Nat.size_eq_bits_len] using Nat.add_le_add_right hlo 2) + have huppers : Nat.size (bitWordValue upper.1) ≤ B := by + rw [(binaryNaturalDivModWithWork_spec hi g hg).1] + exact (Nat.size_le_size (Nat.div_le_self hi g)).trans hhi + have hstops : Nat.size (bitWordValue stop.1) ≤ B + 3 := by + rw [binaryNaturalAddWithWork_value] + have h := binaryNaturalAdd_size_le (bitWordValue upper.1) 1 + have hone : Nat.size 1 = 1 := by decide + rw [hone] at h + omega + have hindex (i : ℕ) (hi' : i ∈ indices) : Nat.size i ≤ B + 3 := by + have hmem := List.mem_range'.mp hi' + have hcount : bitWordValue count.1 = bitWordValue stop.1 - bitWordValue lower.1 := + saturatingSubtractWithWork_value _ _ + obtain ⟨j, hj, hij⟩ := hmem + have hle : i ≤ bitWordValue stop.1 := by omega + exact (Nat.size_le_size hle).trans hstops + let points := arithmeticMapWithWork (fun i => + let product := binaryNaturalMulWithWork g i + (bitWordValue product.1, product.2 + Nat.size i + 2)) indices + have hmap := arithmeticMapWithWork_cost (fun i => + let product := binaryNaturalMulWithWork g i + (bitWordValue product.1, product.2 + Nat.size i + 2)) indices + (100 * (B + 3) ^ 2 + 2) (by + intro i hi' + have hcost := binaryNaturalMulWithWork_cost g i + have his := hindex i hi' + change (binaryNaturalMulWithWork g i).2 + Nat.size i + 2 ≤ _ + nlinarith only [hcost, hgs, his, Nat.zero_le B]) + have hlength : indices.length = (gridPointsBetween g lo hi).length := by + have hl : bitWordValue lower.1 = lo ⌈/⌉ g := by + -- The ceiling start is independent of the upper endpoint. + rw [bitCeilDivWithWork_value _ _ (by simpa only [bitWordValue_bits] using hg), + bitWordValue_bits, bitWordValue_bits] + exact naturalCeiling_div_eq_ceilDiv lo g hg + simp only [indices, List.length_range', count, saturatingSubtractWithWork_value, + stop, binaryNaturalAddWithWork_value, upper, + (binaryNaturalDivModWithWork_spec hi g hg).1, hl, gridPointsBetween_length] + rw [hlength] at hmap + change points.2 ≤ _ at hmap + simp only [Nat.add_assoc, Nat.reduceAdd] at hmap + have hlcost := bitCeilDivWithWork_cost g.bits lo.bits + have hucost := binaryNaturalDivModWithWork_cost hi g + have hscost := binaryNaturalAddWithWork_cost (bitWordValue upper.1) 1 + have hccost := saturatingSubtractWithWork_cost (bitWordValue stop.1) (bitWordValue lower.1) + simp only [Nat.size_eq_bits_len] at hlcost + change lower.2 + upper.2.2 + stop.2 + count.2 + + points.2 + Nat.size g + Nat.size lo + Nat.size hi + 5 ≤ _ + change lower.2 ≤ _ at hlcost + change upper.2.2 ≤ _ at hucost + change stop.2 ≤ _ at hscost + change count.2 ≤ _ at hccost + have hlpow := Nat.pow_le_pow_left (show Nat.size lo + Nat.size g + 1 ≤ 2 * B + 1 by omega) 2 + have huprod := Nat.mul_le_mul (show Nat.size hi + 1 ≤ B + 1 by omega) + (show Nat.size hi + Nat.size g + 1 ≤ 2 * B + 1 by omega) + simp only [Nat.size_one] at hscost + have hsetup : lower.2 + upper.2.2 + stop.2 + count.2 + + Nat.size g + Nat.size lo + Nat.size hi + 5 ≤ 1000 * (B + 2) ^ 2 := by + nlinarith only [hlcost, hucost, hscost, hccost, hlpow, huprod, hgs, hlo, hhi, + hlowers, huppers, hstops, Nat.zero_le B] + unfold gridPointsBitBudget + omega + +theorem makeStateWithWork_cost (n lo hi B : ℕ) + (hn : Nat.size n ≤ B) (hl : Nat.size lo ≤ B) (hh : Nat.size hi ≤ B) : + (makeStateWithWork n lo hi).2 ≤ 16 * B + 8 := by + have hfirst := wordLEWithWork_cost lo.bits hi.bits + have hsecond := wordLEWithWork_cost hi.bits n.bits + simp only [Nat.size_eq_bits_len] at hfirst hsecond + unfold makeStateWithWork + dsimp only + split_ifs <;> omega + +def gridStateBoxBitBudget (count B : ℕ) : ℕ := + 96 * (B + 1) + 2 * gridPointsBitBudget count (B + 2) + + count * (count * (16 * (B + 2) + 11) + count + 3) + 6 + +theorem gridStateBoxWithWork_cost (n g radius lo hi B : ℕ) (hg : 0 < g) + (hn : Nat.size n ≤ B) (hgs : Nat.size g ≤ B) (hr : Nat.size radius ≤ B) + (hl : Nat.size lo ≤ B) (hh : Nat.size hi ≤ B) : + (gridStateBoxWithWork n g radius lo hi).2 ≤ + gridStateBoxBitBudget (2 * radius / g + 2) B := by + let leftLow := saturatingSubtractWithWork lo radius + let leftHigh := binaryNaturalAddWithWork lo radius + let rightLow := saturatingSubtractWithWork hi radius + let rightHigh := binaryNaturalAddWithWork hi radius + let left := gridPointsWithWork g (bitWordValue leftLow.1) (bitWordValue leftHigh.1) + let right := gridPointsWithWork g (bitWordValue rightLow.1) (bitWordValue rightHigh.1) + let count := 2 * radius / g + 2 + have hleft : left.1 = gridPointsBetween g (lo - radius) (lo + radius) := by + simp only [left, leftLow, leftHigh, gridPointsWithWork_value _ _ _ hg, + saturatingSubtractWithWork_value, binaryNaturalAddWithWork_value] + have hright : right.1 = gridPointsBetween g (hi - radius) (hi + radius) := by + simp only [right, rightLow, rightHigh, gridPointsWithWork_value _ _ _ hg, + saturatingSubtractWithWork_value, binaryNaturalAddWithWork_value] + have hlen (p : ℕ) : (gridPointsBetween g (p - radius) (p + radius)).length ≤ count := by + have h := gridPointsBetween_length_le g (p - radius) (p + radius) hg + have hsub : p + radius - (p - radius) ≤ 2 * radius := by omega + exact h.trans (Nat.add_le_add_right (Nat.div_le_div_right hsub) 2) + have hllen : left.1.length ≤ count := by rw [hleft]; exact hlen lo + have hrlen : right.1.length ≤ count := by rw [hright]; exact hlen hi + have hleftWidth (s : ℕ) (hs : s ∈ left.1) : Nat.size s ≤ B + 2 := by + have hp := (gridPointsBetween_sound hg (hleft ▸ hs)).2.1 + exact (Nat.size_le_size hp).trans ((binaryNaturalAdd_size_le lo radius).trans (by omega)) + have hrightWidth (s : ℕ) (hs : s ∈ right.1) : Nat.size s ≤ B + 2 := by + have hp := (gridPointsBetween_sound hg (hright ▸ hs)).2.1 + exact (Nat.size_le_size hp).trans ((binaryNaturalAdd_size_le hi radius).trans (by omega)) + have hstate (s : ℕ) (hs : s ∈ left.1) : + (filterMapWithWork (makeStateWithWork n s) right.1).2 ≤ + count * (16 * (B + 2) + 11) := by + have h := filterMapWithWork_cost (makeStateWithWork n s) right.1 (16 * (B + 2) + 8) + (fun t ht => makeStateWithWork_cost n s t (B + 2) (by omega) (hleftWidth s hs) (hrightWidth t ht)) + exact h.trans (Nat.mul_le_mul_right _ hrlen) + have hstateLen (s : ℕ) : (filterMapWithWork (makeStateWithWork n s) right.1).1.length ≤ count := by + rw [filterMapWithWork_value] + exact (List.length_filterMap_le _ _).trans hrlen + have hflat := arithmeticFlatMapWithWork_cost + (fun s => filterMapWithWork (makeStateWithWork n s) right.1) left.1 + (count * (16 * (B + 2) + 11)) count hstate (fun s _ => hstateLen s) + have hflat' := hflat.trans (Nat.mul_le_mul_right _ hllen) + have hlc := gridPointsWithWork_cost g (bitWordValue leftLow.1) (bitWordValue leftHigh.1) (B + 2) hg + (by omega) (by rw [saturatingSubtractWithWork_value]; exact (Nat.size_le_size (Nat.sub_le _ _)).trans (by omega)) + (by rw [binaryNaturalAddWithWork_value]; exact (binaryNaturalAdd_size_le lo radius).trans (by omega)) + have hrc := gridPointsWithWork_cost g (bitWordValue rightLow.1) (bitWordValue rightHigh.1) (B + 2) hg + (by omega) (by rw [saturatingSubtractWithWork_value]; exact (Nat.size_le_size (Nat.sub_le _ _)).trans (by omega)) + (by rw [binaryNaturalAddWithWork_value]; exact (binaryNaturalAdd_size_le hi radius).trans (by omega)) + conv_rhs at hlc => + simp only [leftLow, leftHigh, saturatingSubtractWithWork_value, binaryNaturalAddWithWork_value] + conv_rhs at hrc => + simp only [rightLow, rightHigh, saturatingSubtractWithWork_value, binaryNaturalAddWithWork_value] + have hlc' : left.2 ≤ gridPointsBitBudget count (B + 2) := by + apply hlc.trans + unfold gridPointsBitBudget + exact Nat.add_le_add_left (Nat.mul_le_mul_right _ (hlen lo)) _ + have hrc' : right.2 ≤ gridPointsBitBudget count (B + 2) := by + apply hrc.trans + unfold gridPointsBitBudget + exact Nat.add_le_add_left (Nat.mul_le_mul_right _ (hlen hi)) _ + have hll := saturatingSubtractWithWork_cost lo radius + have hlh := binaryNaturalAddWithWork_cost lo radius + have hrl := saturatingSubtractWithWork_cost hi radius + have hrh := binaryNaturalAddWithWork_cost hi radius + change leftLow.2 ≤ _ at hll + change leftHigh.2 ≤ _ at hlh + change rightLow.2 ≤ _ at hrl + change rightHigh.2 ≤ _ at hrh + let states := arithmeticFlatMapWithWork (fun s => filterMapWithWork (makeStateWithWork n s) right.1) left.1 + change states.2 ≤ _ at hflat' + change leftLow.2 + leftHigh.2 + rightLow.2 + rightHigh.2 + left.2 + right.2 + states.2 + 6 ≤ _ + unfold gridStateBoxBitBudget + change _ ≤ 96 * (B + 1) + 2 * gridPointsBitBudget count (B + 2) + + count * (count * (16 * (B + 2) + 11) + count + 3) + 6 + omega + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryLocalGroupActions.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryLocalGroupActions.lean new file mode 100644 index 0000000000000000000000000000000000000000..300fdf0c4ca4d20fc782aa9a58ebcfd2ecd0002c --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryLocalGroupActions.lean @@ -0,0 +1,148 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryComputedCellGroup +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! The complete local group list is obtained by executed scale, cell, +band, and sampled-selection loops. The source keeps the original finite +sample counts and shares its draws between all members of each cell. -/ + +namespace EditApproximation +namespace BinaryFraction + + + +@[simp] theorem refinementScaleGuardWithWork_value (F b : ℕ) (a w : BinaryFraction) : + (refinementScaleGuardWithWork F b a w).1 = true ↔ + w.value / (16 * F) ≤ b ∧ (b : ℚ) ≤ 8 * a.value * w.value := by + simp only [refinementScaleGuardWithWork, Bool.and_eq_true, leWithWork_value, + canonicalMulWithWork_value, divWithWork_value, nat_value, Nat.cast_ofNat] + +private theorem cellDraw_roundtrip (M b Q : ℕ) (f g : ℚ) (h : f = g) + (draw : cellScaleDraw M b Q g) : + Eq.mp (congrArg (cellScaleDraw M b Q) h) + (Eq.mpr (congrArg (cellScaleDraw M b Q) h) draw) = draw := by + cases h + rfl + +def localGroupScaleWithWork {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (P F exponent Q eM eF eb : ℕ) + (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (tau a : BinaryFraction) + (parentInitial : TargetInterval target.length → BinaryFraction) + (child initial current : Fin M → TargetInterval target.length → BinaryFraction) + (draw : CellGroupDraws M F Q) (query : TargetInterval target.length) : + List (BinaryBellmanAction (TargetInterval target.length) + (Fin M × TargetInterval target.length) M) × ℕ := + let b := 2 ^ eb + let side := canonicalMulWithWork (inversePowerTwo exponent) (nat b) + let radius := naturalCeilingWithWork (parentInitial query) + let cells := targetCellsWithWork side.1 (bitWordValue radius.1) query + let selected := filterMapWithWork (fun cell => + computedCellGroupWithWork source target parent b P F exponent Q eM eb eF hM rfl hF + tau a parentInitial child initial current + (Eq.mpr (congrArg (cellScaleDraw M b Q) (nat_value F)) (draw b cell)) cell) cells.1 + (selected.1, side.2 + radius.2 + cells.2 + selected.2 + eb + 4) + +theorem localGroupScaleWithWork_value {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (P F exponent Q eM eF eb : ℕ) + (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (tau a : BinaryFraction) + (parentInitial : TargetInterval target.length → BinaryFraction) + (child initial current : Fin M → TargetInterval target.length → BinaryFraction) + (draw : CellGroupDraws M F Q) (query : TargetInterval target.length) (hP : 0 < P) : + ((localGroupScaleWithWork source target parent P F exponent Q eM eF eb hM hF tau a + parentInitial child initial current draw query).1.map BinaryBellmanAction.decode) = + (localTargetCells (((2 : ℚ) ^ (-(exponent : ℤ))) * (2 ^ eb : ℕ)) + ⌈(parentInitial query).value⌉₊ query).filterMap (fun cell => + chooseCellGroupAction source target parent (2 ^ eb) P F exponent Q tau.value a.value + (fun r => (parentInitial r).value) (fun i r => (child i r).value) + (fun i r => (initial i r).value) (fun i r => (current i r).value) cell (draw (2 ^ eb) cell)) := by + simp only [localGroupScaleWithWork, filterMapWithWork_value, List.map_filterMap, + targetCellsWithWork_value, canonicalMulWithWork_value, inversePowerTwo_value, nat_value, + naturalCeilingWithWork_value] + apply List.filterMap_congr + intro cell _ + have hv := computedCellGroupWithWork_value source target parent (2 ^ eb) P F exponent Q eM eb eF + hM rfl hF tau a parentInitial child initial current + (Eq.mpr (congrArg (cellScaleDraw M (2 ^ eb) Q) (nat_value F)) (draw (2 ^ eb) cell)) cell hP + rw [cellDraw_roundtrip M (2 ^ eb) Q (nat F).value (F : ℚ) (nat_value F) + (draw (2 ^ eb) cell)] at hv + exact hv + +def localCellGroupsWithWork {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (N P F exponent Q eM eF : ℕ) + (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (tau a : BinaryFraction) + (parentInitial : TargetInterval target.length → BinaryFraction) + (child initial current : Fin M → TargetInterval target.length → BinaryFraction) + (draw : CellGroupDraws M F Q) (query : TargetInterval target.length) : + List (BinaryBellmanAction (TargetInterval target.length) + (Fin M × TargetInterval target.length) M) × ℕ := + let count := max 1 N.bits.length + let groups := arithmeticFlatMapWithWork (fun eb => + let guard := refinementScaleGuardWithWork F (2 ^ eb) a (parentInitial query) + if guard.1 then + let selected := localGroupScaleWithWork source target parent P F exponent Q eM eF eb hM hF + tau a parentInitial child initial current draw query + (selected.1, guard.2 + selected.2 + eb + 4) + else ([], guard.2 + eb + 4)) (List.range count) + (groups.1, groups.2 + count + N.bits.length + 2) + +private theorem flatMap_filter_condition {α β : Type*} (p : α → Bool) (f : α → List β) + (xs : List α) : + xs.flatMap (fun x => if p x then f x else []) = (xs.filter p).flatMap f := by + induction xs with + | nil => rfl + | cons x xs ih => + simp only [List.flatMap_cons, List.filter_cons] + cases p x <;> simp only [Bool.false_eq_true, ↓reduceIte, List.flatMap_cons, + List.nil_append, ih] + +theorem localCellGroupsWithWork_value {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (N P F exponent Q eM eF : ℕ) + (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (tau a : BinaryFraction) + (parentInitial : TargetInterval target.length → BinaryFraction) + (child initial current : Fin M → TargetInterval target.length → BinaryFraction) + (draw : CellGroupDraws M F Q) (query : TargetInterval target.length) (hP : 0 < P) : + ((localCellGroupsWithWork source target parent N P F exponent Q eM eF hM hF tau a + parentInitial child initial current draw query).1.map BinaryBellmanAction.decode) = + localCellGroupActions source target parent N P F exponent Q tau.value a.value + (fun r => (parentInitial r).value) (fun i r => (child i r).value) + (fun i r => (initial i r).value) (fun i r => (current i r).value) draw query := by + let predicate := fun b : ℕ => decide ((parentInitial query).value / (16 * (F : ℚ)) ≤ b ∧ + (b : ℚ) ≤ 8 * a.value * (parentInitial query).value) + let values := fun b : ℕ => (localTargetCells (((2 : ℚ) ^ (-(exponent : ℤ))) * b) + ⌈(parentInitial query).value⌉₊ query).filterMap (fun cell => + chooseCellGroupAction source target parent b P F exponent Q tau.value a.value + (fun r => (parentInitial r).value) (fun i r => (child i r).value) + (fun i r => (initial i r).value) (fun i r => (current i r).value) cell (draw b cell)) + have hscale : (List.range (max 1 N.bits.length)).map (fun eb => 2 ^ eb) = dyadicScales N := by + simpa only [dyadicScalesWithWork, arithmeticMapWithWork_value, powerTwoWord_value] using + dyadicScalesWithWork_value N + have hguard (eb : ℕ) : (refinementScaleGuardWithWork F (2 ^ eb) a (parentInitial query)).1 = + predicate (2 ^ eb) := Bool.eq_iff_iff.mpr (by + simp only [refinementScaleGuardWithWork_value, predicate, decide_eq_true_eq]) + unfold localCellGroupsWithWork + simp only [arithmeticFlatMapWithWork_value, List.map_flatMap] + trans (List.range (max 1 N.bits.length)).flatMap + (fun eb => if predicate (2 ^ eb) then values (2 ^ eb) else []) + · apply List.flatMap_congr + intro eb _ + by_cases hg : (refinementScaleGuardWithWork F (2 ^ eb) a (parentInitial query)).1 = true + · have hp : predicate (2 ^ eb) = true := (hguard eb) ▸ hg + simp only [ite_eq_left hg, ite_eq_left hp] + exact localGroupScaleWithWork_value source target parent P F exponent Q eM eF eb hM hF + tau a parentInitial child initial current draw query hP + · have hp : predicate (2 ^ eb) ≠ true := by simpa only [← hguard eb] using hg + simp only [ite_eq_right hg, ite_eq_right hp, List.map_nil] + · calc + _ = ((List.range (max 1 N.bits.length)).map (fun eb => 2 ^ eb)).flatMap + (fun b => if predicate b then values b else []) := + (List.flatMap_map _ _ _).symm + _ = (((List.range (max 1 N.bits.length)).map (fun eb => 2 ^ eb)).filter predicate).flatMap + values := flatMap_filter_condition _ _ _ + _ = _ := by rw [hscale]; rfl + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryLocalGroupReads.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryLocalGroupReads.lean new file mode 100644 index 0000000000000000000000000000000000000000..a9e42a8cd6a652ad81631613c705aaadaf59594a --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryLocalGroupReads.lean @@ -0,0 +1,115 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryCellReads +import OAI.Combinatorics.EditApproximation.Binary.BinaryPreparedLocalGroups + +namespace OAI + +/-! The physical query's outer whole-cell loops use the same dyadic +scales and exact Fin-count draws, with explicit initial-table lookups. -/ + +namespace EditApproximation +namespace BinaryFraction + +section Local +variable {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (P F exponent Q eM eF : ℕ) + (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (hP : 0 < P) + (tau a : BinaryFraction) + (parentInitial : TargetInterval target.length → BinaryFraction × ℕ) + (child initial current : Fin M → TargetInterval target.length → BinaryFraction × ℕ) + (R : ℕ) (hc : ∀ i q, (child i q).2 ≤ R) (hi : ∀ i q, (initial i q).2 ≤ R) + +def preparedComputedCellReadWithWork (b eb : ℕ) (hb : b = 2 ^ eb) + (draw : cellScaleDraw M b Q (nat F).value) (cell : ℕ × ℕ) : + Option (BinaryBellmanAction (TargetInterval target.length) + (Fin M × TargetInterval target.length) M) × ℕ := + let scales := groupScalesWithWork eM eb eF + let result := preparedCellGroupReadWithWork source target parent b P F exponent Q + (by rw [hb]; exact Nat.two_pow_pos eb) hP tau a parentInitial child initial current + R R hc hi scales.1 (computedGroupScales_value M b F eM eb eF hM hb hF) draw cell + (result.1, scales.2 + result.2 + 1) + +theorem preparedComputedCellReadWithWork_eq (b eb : ℕ) (hb : b = 2 ^ eb) + (draw : cellScaleDraw M b Q (nat F).value) (cell : ℕ × ℕ) + (hp : ∀ r, (parentInitial r).2 ≤ R) (hcurrent : ∀ i q, (current i q).2 ≤ R) : + (preparedComputedCellReadWithWork source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial current R hc hi b eb hb draw cell).1 = + (preparedComputedCellGroupWithWork source target parent b P F exponent Q eM eb eF hM hb hF hP + tau a (fun r => (parentInitial r).1) (fun i q => (child i q).1) + (fun i q => (initial i q).1) (fun i q => (current i q).1) draw cell).1 := by + have h := preparedCellGroupReadWithWork_eq source target parent b P F exponent Q + (by rw [hb]; exact Nat.two_pow_pos eb) hP tau a parentInitial child initial current + R R hc hi (groupScalesWithWork eM eb eF).1 + (computedGroupScales_value M b F eM eb eF hM hb hF) draw cell R R hp hcurrent + simpa only [preparedComputedCellReadWithWork, preparedComputedCellGroupWithWork] using h + +def preparedLocalGroupScaleReadWithWork (eb : ℕ) + (draw : CellGroupDraws M F Q) (query : TargetInterval target.length) : + List (BinaryBellmanAction (TargetInterval target.length) + (Fin M × TargetInterval target.length) M) × ℕ := + let b := 2 ^ eb + let word := parentInitial query + let side := canonicalMulWithWork (inversePowerTwo exponent) (nat b) + let radius := naturalCeilingWithWork word.1 + let cells := targetCellsWithWork side.1 (bitWordValue radius.1) query + let selected := filterMapWithWork (fun cell => + preparedComputedCellReadWithWork source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial current R hc hi b eb rfl + (Eq.mpr (congrArg (cellScaleDraw M b Q) (nat_value F)) (draw b cell)) cell) cells.1 + (selected.1, word.2 + side.2 + radius.2 + cells.2 + selected.2 + eb + 4) + +theorem preparedLocalGroupScaleReadWithWork_eq (eb : ℕ) + (draw : CellGroupDraws M F Q) (query : TargetInterval target.length) + (hp : ∀ r, (parentInitial r).2 ≤ R) (hcurrent : ∀ i q, (current i q).2 ≤ R) : + (preparedLocalGroupScaleReadWithWork source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial current R hc hi eb draw query).1 = + (preparedLocalGroupScaleWithWork source target parent P F exponent Q eM eF eb hM hF hP tau a + (fun r => (parentInitial r).1) (fun i q => (child i q).1) + (fun i q => (initial i q).1) (fun i q => (current i q).1) draw query).1 := by + simp only [preparedLocalGroupScaleReadWithWork, preparedLocalGroupScaleWithWork, + filterMapWithWork_value] + apply List.filterMap_congr + intro cell _ + have h := preparedComputedCellReadWithWork_eq source target parent P F exponent Q eM eF hM hF hP + tau a parentInitial child initial current R hc hi (2 ^ eb) eb rfl + (Eq.mpr (congrArg (cellScaleDraw M (2 ^ eb) Q) (nat_value F)) (draw (2 ^ eb) cell)) + cell hp hcurrent + simpa only using h + +def preparedLocalCellGroupsReadWithWork (N : ℕ) + (draw : CellGroupDraws M F Q) (query : TargetInterval target.length) : + List (BinaryBellmanAction (TargetInterval target.length) + (Fin M × TargetInterval target.length) M) × ℕ := + let count := max 1 N.bits.length + let word := parentInitial query + let groups := arithmeticFlatMapWithWork (fun eb => + let guard := refinementScaleGuardWithWork F (2 ^ eb) a word.1 + if guard.1 then + let selected := preparedLocalGroupScaleReadWithWork source target parent P F exponent Q eM eF + hM hF hP tau a parentInitial child initial current R hc hi eb draw query + (selected.1, guard.2 + selected.2 + eb + 4) + else ([], guard.2 + eb + 4)) (List.range count) + (groups.1, word.2 + groups.2 + count + N.bits.length + 2) + +theorem preparedLocalCellGroupsReadWithWork_eq (N : ℕ) + (draw : CellGroupDraws M F Q) (query : TargetInterval target.length) + (hp : ∀ r, (parentInitial r).2 ≤ R) (hcurrent : ∀ i q, (current i q).2 ≤ R) : + (preparedLocalCellGroupsReadWithWork source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial current R hc hi N draw query).1 = + (preparedLocalCellGroupsWithWork source target parent N P F exponent Q eM eF hM hF hP tau a + (fun r => (parentInitial r).1) (fun i q => (child i q).1) + (fun i q => (initial i q).1) (fun i q => (current i q).1) draw query).1 := by + simp only [preparedLocalCellGroupsReadWithWork, preparedLocalCellGroupsWithWork, + arithmeticFlatMapWithWork_value] + apply List.flatMap_congr + intro eb _ + split_ifs + · have h := preparedLocalGroupScaleReadWithWork_eq source target parent P F exponent Q eM eF hM hF hP + tau a parentInitial child initial current R hc hi eb draw query hp hcurrent + simpa only using h + · rfl + +end Local +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryLocalGroupSource.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryLocalGroupSource.lean new file mode 100644 index 0000000000000000000000000000000000000000..3e2483db3f6689b51f454fde652f7a4dafabdc1c --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryLocalGroupSource.lean @@ -0,0 +1,278 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryCellSourcePort +import OAI.Combinatorics.EditApproximation.Binary.BinaryLocalGroupReads +import OAI.Combinatorics.EditApproximation.Binary.BinaryReadCostBounds +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation + + + + + +private theorem cellScaleReadDraw_cast_plain (M b Q : ℕ) (f g : ℚ) (h : f = g) + (draw : cellScaleReadDraw M b Q g) : + (fun t i => ((Eq.mpr (congrArg (cellScaleReadDraw M b Q) h) draw) t i).1) = + Eq.mpr (congrArg (BinaryFraction.cellScaleDraw M b Q) h) (fun t i => (draw t i).1) := by + cases h + rfl + +private theorem cellScaleReadDraw_cast_bound (M b Q : ℕ) (f g : ℚ) (h : f = g) + (draw : cellScaleReadDraw M b Q g) (S : ℕ) (hs : ∀ t i, (draw t i).2 ≤ S) : + ∀ t i, ((Eq.mpr (congrArg (cellScaleReadDraw M b Q) h) draw) t i).2 ≤ S := by + cases h + exact hs + +namespace BinaryFraction +section Local +variable {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (P F exponent Q eM eF : ℕ) + (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (hP : 0 < P) + (tau a : BinaryFraction) + (parentInitial : TargetInterval target.length → BinaryFraction × ℕ) + (child initial current : Fin M → TargetInterval target.length → BinaryFraction × ℕ) + (R : ℕ) (hc : ∀ i q, (child i q).2 ≤ R) (hi : ∀ i q, (initial i q).2 ≤ R) + +def preparedComputedCellSourceWithWork (b eb : ℕ) (hb : b = 2 ^ eb) + (draw : ∀ t : Fin (groupDyadicScales M b (nat F).value).length, + Fin (groupSampleCount M Q b (groupDyadicScaleAt M b (nat F).value t)) → Fin M × ℕ) + (cell : ℕ × ℕ) : + Option (BinaryBellmanAction (TargetInterval target.length) + (Fin M × TargetInterval target.length) M) × ℕ := + let scales := groupScalesWithWork eM eb eF + let result := preparedCellGroupSourceWithWork source target parent b P F exponent Q + (by rw [hb]; exact Nat.two_pow_pos eb) hP tau a parentInitial child initial current + R R hc hi scales.1 (computedGroupScales_value M b F eM eb eF hM hb hF) draw cell + (result.1, scales.2 + result.2 + 1) + +theorem preparedComputedCellSourceWithWork_eq_cost (b eb : ℕ) (hb : b = 2 ^ eb) + (draw : ∀ t : Fin (groupDyadicScales M b (nat F).value).length, + Fin (groupSampleCount M Q b (groupDyadicScaleAt M b (nat F).value t)) → Fin M × ℕ) + (cell : ℕ × ℕ) (S : ℕ) (hs : ∀ t i, (draw t i).2 ≤ S) : + (preparedComputedCellSourceWithWork source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial current R hc hi b eb hb draw cell).1 = + (preparedComputedCellReadWithWork source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial current R hc hi b eb hb (fun t i => (draw t i).1) cell).1 ∧ + (preparedComputedCellSourceWithWork source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial current R hc hi b eb hb draw cell).2 ≤ + (preparedComputedCellReadWithWork source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial current R hc hi b eb hb (fun t i => (draw t i).1) cell).2 * (S + 4) := by + have h := preparedCellGroupSourceWithWork_eq_cost source target parent b P F exponent Q + (by rw [hb]; exact Nat.two_pow_pos eb) hP tau a parentInitial child initial current R R hc hi + (groupScalesWithWork eM eb eF).1 (computedGroupScales_value M b F eM eb eF hM hb hF) + draw cell S hs + unfold preparedComputedCellSourceWithWork preparedComputedCellReadWithWork + dsimp only + rw [h.1] + exact ⟨rfl, by nlinarith only [h.2]⟩ + +private theorem add_source_cost (u v read plain S : ℕ) (h : read ≤ plain * (S + 4)) : + u + read + v ≤ (u + plain + v) * (S + 4) := by + have hconst : u + v ≤ (u + v) * (S + 4) := + Nat.le_mul_of_pos_right _ (by omega) + calc + u + read + v ≤ u + plain * (S + 4) + v := by omega + _ = plain * (S + 4) + (u + v) := by omega + _ ≤ plain * (S + 4) + (u + v) * (S + 4) := Nat.add_le_add_left hconst _ + _ = (u + plain + v) * (S + 4) := by ring + +private theorem computedCellSource_cast_cost (b eb : ℕ) (hb : b = 2 ^ eb) + (draw : cellScaleReadDraw M b Q F) (cell : ℕ × ℕ) (S : ℕ) + (hs : ∀ t i, (draw t i).2 ≤ S) : + let castDraw := Eq.mpr (congrArg (cellScaleReadDraw M b Q) (nat_value F)) draw + let plainDraw := Eq.mpr (congrArg (cellScaleDraw M b Q) (nat_value F)) (fun t i => (draw t i).1) + (preparedComputedCellSourceWithWork source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial current R hc hi b eb hb castDraw cell).1 = + (preparedComputedCellReadWithWork source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial current R hc hi b eb hb plainDraw cell).1 ∧ + (preparedComputedCellSourceWithWork source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial current R hc hi b eb hb castDraw cell).2 ≤ + (preparedComputedCellReadWithWork source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial current R hc hi b eb hb plainDraw cell).2 * (S + 4) := by + dsimp only + have h := preparedComputedCellSourceWithWork_eq_cost source target parent P F exponent Q eM eF + hM hF hP tau a parentInitial child initial current R hc hi b eb hb + (Eq.mpr (congrArg (cellScaleReadDraw M b Q) (nat_value F)) draw) cell S + (cellScaleReadDraw_cast_bound M b Q _ _ (nat_value F) draw S hs) + rw [cellScaleReadDraw_cast_plain M b Q _ _ (nat_value F) draw] at h + exact h + +def preparedLocalGroupScaleSourceWithWork (eb : ℕ) + (draw : CellGroupReadDraws M F Q) (query : TargetInterval target.length) : + List (BinaryBellmanAction (TargetInterval target.length) + (Fin M × TargetInterval target.length) M) × ℕ := + let b := 2 ^ eb + let word := parentInitial query + let side := canonicalMulWithWork (inversePowerTwo exponent) (nat b) + let radius := naturalCeilingWithWork word.1 + let cells := targetCellsWithWork side.1 (bitWordValue radius.1) query + let selected := filterMapWithWork (fun cell => + preparedComputedCellSourceWithWork source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial current R hc hi b eb rfl + (Eq.mpr (congrArg (cellScaleReadDraw M b Q) (nat_value F)) (draw b cell)) cell) cells.1 + (selected.1, word.2 + side.2 + radius.2 + cells.2 + selected.2 + eb + 4) + +theorem preparedLocalGroupScaleSourceWithWork_eq_cost_on (eb : ℕ) + (draw : CellGroupReadDraws M F Q) (query : TargetInterval target.length) + (S : ℕ) (hs : ∀ cell ∈ (targetCellsWithWork + (canonicalMulWithWork (inversePowerTwo exponent) (nat (2 ^ eb))).1 + (bitWordValue (naturalCeilingWithWork (parentInitial query).1).1) query).1, + ∀ t i, (draw (2 ^ eb) cell t i).2 ≤ S) : + (preparedLocalGroupScaleSourceWithWork source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial current R hc hi eb draw query).1 = + (preparedLocalGroupScaleReadWithWork source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial current R hc hi eb (fun b cell t i => (draw b cell t i).1) query).1 ∧ + (preparedLocalGroupScaleSourceWithWork source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial current R hc hi eb draw query).2 ≤ + (preparedLocalGroupScaleReadWithWork source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial current R hc hi eb (fun b cell t i => (draw b cell t i).1) query).2 * (S + 4) := by + let b := 2 ^ eb + let drawn (cell : ℕ × ℕ) : cellScaleReadDraw M b Q (nat F).value := + Eq.mpr (congrArg (cellScaleReadDraw M b Q) (nat_value F)) (draw b cell) + let cells := targetCellsWithWork (canonicalMulWithWork (inversePowerTwo exponent) (nat b)).1 + (bitWordValue (naturalCeilingWithWork (parentInitial query).1).1) query + let read := fun cell => preparedComputedCellSourceWithWork source target parent P F exponent Q + eM eF hM hF hP tau a parentInitial child initial current R hc hi b eb rfl (drawn cell) cell + let plain := fun cell => preparedComputedCellReadWithWork source target parent P F exponent Q + eM eF hM hF hP tau a parentInitial child initial current R hc hi b eb rfl + (Eq.mpr (congrArg (cellScaleDraw M b Q) (nat_value F)) + (fun t i => (draw b cell t i).1)) cell + have one (cell : ℕ × ℕ) (hcell : cell ∈ cells.1) : + (read cell).1 = (plain cell).1 ∧ (read cell).2 ≤ (plain cell).2 * (S + 4) := by + simpa only [read, plain, drawn] using + computedCellSource_cast_cost source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial current R hc hi b eb rfl (draw b cell) cell S (hs cell hcell) + have h := filterMapWithWork_factor read plain cells.1 (S + 4) (by omega) + (fun cell hcell => (one cell hcell).1) (fun cell hcell => (one cell hcell).2) + have hcost : + (parentInitial query).2 + (canonicalMulWithWork (inversePowerTwo exponent) (nat b)).2 + + (naturalCeilingWithWork (parentInitial query).1).2 + cells.2 + + (filterMapWithWork read cells.1).2 + eb + 4 ≤ + ((parentInitial query).2 + (canonicalMulWithWork (inversePowerTwo exponent) (nat b)).2 + + (naturalCeilingWithWork (parentInitial query).1).2 + cells.2 + + (filterMapWithWork plain cells.1).2 + eb + 4) * (S + 4) := by + simpa only [Nat.add_assoc] using add_source_cost + ((parentInitial query).2 + (canonicalMulWithWork (inversePowerTwo exponent) (nat b)).2 + + (naturalCeilingWithWork (parentInitial query).1).2 + cells.2) + (eb + 4) (filterMapWithWork read cells.1).2 (filterMapWithWork plain cells.1).2 S h.2 + simpa only [preparedLocalGroupScaleSourceWithWork, preparedLocalGroupScaleReadWithWork, + b, drawn, cells, read, plain] using And.intro h.1 hcost + +theorem preparedLocalGroupScaleSourceWithWork_eq_cost (eb : ℕ) + (draw : CellGroupReadDraws M F Q) (query : TargetInterval target.length) + (S : ℕ) (hs : ∀ b cell t i, (draw b cell t i).2 ≤ S) : + (preparedLocalGroupScaleSourceWithWork source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial current R hc hi eb draw query).1 = + (preparedLocalGroupScaleReadWithWork source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial current R hc hi eb (fun b cell t i => (draw b cell t i).1) query).1 ∧ + (preparedLocalGroupScaleSourceWithWork source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial current R hc hi eb draw query).2 ≤ + (preparedLocalGroupScaleReadWithWork source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial current R hc hi eb (fun b cell t i => (draw b cell t i).1) query).2 * (S + 4) := by + exact preparedLocalGroupScaleSourceWithWork_eq_cost_on source target parent P F exponent Q + eM eF hM hF hP tau a parentInitial child initial current R hc hi eb draw query S + (fun cell _ => hs (2 ^ eb) cell) + +/-- Every admitted scale uses the source-aware whole-cell loop. -/ +def preparedLocalCellGroupsSourceWithWork (N : ℕ) + (draw : CellGroupReadDraws M F Q) (query : TargetInterval target.length) : + List (BinaryBellmanAction (TargetInterval target.length) + (Fin M × TargetInterval target.length) M) × ℕ := + let count := max 1 N.bits.length + let word := parentInitial query + let groups := arithmeticFlatMapWithWork (fun eb => + let guard := refinementScaleGuardWithWork F (2 ^ eb) a word.1 + if guard.1 then + let selected := preparedLocalGroupScaleSourceWithWork source target parent P F exponent Q eM eF + hM hF hP tau a parentInitial child initial current R hc hi eb draw query + (selected.1, guard.2 + selected.2 + eb + 4) + else ([], guard.2 + eb + 4)) (List.range count) + (groups.1, word.2 + groups.2 + count + N.bits.length + 2) + +theorem preparedLocalCellGroupsSourceWithWork_eq_cost_on (N : ℕ) + (draw : CellGroupReadDraws M F Q) (query : TargetInterval target.length) + (S : ℕ) + (hs : ∀ eb ∈ List.range (max 1 N.bits.length), + (refinementScaleGuardWithWork F (2 ^ eb) a (parentInitial query).1).1 = true → + ∀ cell ∈ (targetCellsWithWork + (canonicalMulWithWork (inversePowerTwo exponent) (nat (2 ^ eb))).1 + (bitWordValue (naturalCeilingWithWork (parentInitial query).1).1) query).1, + ∀ t i, (draw (2 ^ eb) cell t i).2 ≤ S) : + (preparedLocalCellGroupsSourceWithWork source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial current R hc hi N draw query).1 = + (preparedLocalCellGroupsReadWithWork source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial current R hc hi N (fun b cell t i => (draw b cell t i).1) query).1 ∧ + (preparedLocalCellGroupsSourceWithWork source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial current R hc hi N draw query).2 ≤ + (preparedLocalCellGroupsReadWithWork source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial current R hc hi N (fun b cell t i => (draw b cell t i).1) query).2 * (S + 4) := by + let read := fun eb => + let guard := refinementScaleGuardWithWork F (2 ^ eb) a (parentInitial query).1 + if guard.1 then + let selected := preparedLocalGroupScaleSourceWithWork source target parent P F exponent Q eM eF + hM hF hP tau a parentInitial child initial current R hc hi eb draw query + (selected.1, guard.2 + selected.2 + eb + 4) + else ([], guard.2 + eb + 4) + let plain := fun eb => + let guard := refinementScaleGuardWithWork F (2 ^ eb) a (parentInitial query).1 + if guard.1 then + let selected := preparedLocalGroupScaleReadWithWork source target parent P F exponent Q eM eF + hM hF hP tau a parentInitial child initial current R hc hi eb + (fun b cell t i => (draw b cell t i).1) query + (selected.1, guard.2 + selected.2 + eb + 4) + else ([], guard.2 + eb + 4) + have one (eb : ℕ) (heb : eb ∈ List.range (max 1 N.bits.length)) : (read eb).1 = (plain eb).1 ∧ (read eb).2 ≤ (plain eb).2 * (S + 4) := by + dsimp only [read, plain] + split_ifs with hguard + · have h := preparedLocalGroupScaleSourceWithWork_eq_cost_on source target parent P F exponent Q + eM eF hM hF hP tau a parentInitial child initial current R hc hi eb draw query S (hs eb heb hguard) + have hcost := add_source_cost + (refinementScaleGuardWithWork F (2 ^ eb) a (parentInitial query).1).2 (eb + 4) + (preparedLocalGroupScaleSourceWithWork source target parent P F exponent Q eM eF + hM hF hP tau a parentInitial child initial current R hc hi eb draw query).2 + (preparedLocalGroupScaleReadWithWork source target parent P F exponent Q eM eF + hM hF hP tau a parentInitial child initial current R hc hi eb + (fun b cell t i => (draw b cell t i).1) query).2 S h.2 + simpa only [Nat.add_assoc] using And.intro h.1 hcost + · have hvalue := Eq.refl ([] : List (BinaryBellmanAction (TargetInterval target.length) + (Fin M × TargetInterval target.length) M)) + have hcost := Nat.le_mul_of_pos_right + ((refinementScaleGuardWithWork F (2 ^ eb) a (parentInitial query).1).2 + eb + 4) + (by omega : 0 < S + 4) + simpa only using And.intro hvalue hcost + have h := arithmeticFlatMapWithWork_factor read plain (List.range (max 1 N.bits.length)) + (S + 4) (by omega) (fun eb heb => (one eb heb).1) (fun eb heb => (one eb heb).2) + have hcost : + (parentInitial query).2 + (arithmeticFlatMapWithWork read (List.range (max 1 N.bits.length))).2 + + max 1 N.bits.length + N.bits.length + 2 ≤ + ((parentInitial query).2 + (arithmeticFlatMapWithWork plain (List.range (max 1 N.bits.length))).2 + + max 1 N.bits.length + N.bits.length + 2) * (S + 4) := by + simpa only [Nat.add_assoc] using add_source_cost (parentInitial query).2 + (max 1 N.bits.length + N.bits.length + 2) + (arithmeticFlatMapWithWork read (List.range (max 1 N.bits.length))).2 + (arithmeticFlatMapWithWork plain (List.range (max 1 N.bits.length))).2 S h.2 + simpa only [preparedLocalCellGroupsSourceWithWork, preparedLocalCellGroupsReadWithWork, + read, plain] using And.intro h.1 hcost + +theorem preparedLocalCellGroupsSourceWithWork_eq_cost (N : ℕ) + (draw : CellGroupReadDraws M F Q) (query : TargetInterval target.length) + (S : ℕ) (hs : ∀ b cell t i, (draw b cell t i).2 ≤ S) : + (preparedLocalCellGroupsSourceWithWork source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial current R hc hi N draw query).1 = + (preparedLocalCellGroupsReadWithWork source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial current R hc hi N (fun b cell t i => (draw b cell t i).1) query).1 ∧ + (preparedLocalCellGroupsSourceWithWork source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial current R hc hi N draw query).2 ≤ + (preparedLocalCellGroupsReadWithWork source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial current R hc hi N (fun b cell t i => (draw b cell t i).1) query).2 * (S + 4) := by + exact preparedLocalCellGroupsSourceWithWork_eq_cost_on source target parent P F exponent Q + eM eF hM hF hP tau a parentInitial child initial current R hc hi N draw query S + (fun eb _ _ cell _ => hs (2 ^ eb) cell) + +end Local +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryLocalGroupSourceSpace.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryLocalGroupSourceSpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..b541f0459ab77849893b29878fb44a0a367a0c2a --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryLocalGroupSourceSpace.lean @@ -0,0 +1,218 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryCellSourceSpace +import OAI.Combinatorics.EditApproximation.Binary.BinaryLocalGroupSource +import OAI.Combinatorics.EditApproximation.Queries.QueryGroupSetupSpace +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation + + + +private theorem transportedSourceAllocation_le {M b Q : ℕ} {f g : ℚ} (h : f = g) + (draw : cellScaleReadDraw M b Q g) + (allocation : ∀ t : Fin (groupDyadicScales M b g).length, + Fin (groupSampleCount M Q b (groupDyadicScaleAt M b g t)) → ℕ) + (ha : ∀ t i, allocation t i ≤ (draw t i).2) : + ∀ t i, (Eq.mpr (congrArg (fun f => ∀ t : Fin (groupDyadicScales M b f).length, + Fin (groupSampleCount M Q b (groupDyadicScaleAt M b f t)) → ℕ) h) allocation) t i ≤ + (Eq.mpr (congrArg (cellScaleReadDraw M b Q) h) draw t i).2 := by + cases h + exact ha + +namespace BinaryFraction +section Local +variable {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (P F exponent Q eM eF : ℕ) + (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (hP : 0 < P) + (tau a : BinaryFraction) + (parentInitial : TargetInterval target.length → BinaryFraction × ℕ) + (child initial current : Fin M → TargetInterval target.length → BinaryFraction × ℕ) + (R : ℕ) (hc : ∀ i q, (child i q).2 ≤ R) (hi : ∀ i q, (initial i q).2 ≤ R) + (parentAllocation : TargetInterval target.length → ℕ) + (childAllocation initialAllocation currentAllocation : Fin M → TargetInterval target.length → ℕ) + +def preparedComputedCellSourceAllocation (b eb : ℕ) (hb : b = 2 ^ eb) + (draw : cellScaleReadDraw M b Q (nat F).value) + (drawAllocation : ∀ t : Fin (groupDyadicScales M b (nat F).value).length, + Fin (groupSampleCount M Q b (groupDyadicScaleAt M b (nat F).value t)) → ℕ) + (cell : ℕ × ℕ) : ℕ := + groupScalesAllocation eM eb eF + + preparedCellGroupSourceAllocation source target parent b P F exponent Q + (by rw [hb]; exact Nat.two_pow_pos eb) hP tau a parentInitial child initial current + R R hc hi (groupScalesWithWork eM eb eF).1 (computedGroupScales_value M b F eM eb eF hM hb hF) + draw parentAllocation childAllocation initialAllocation currentAllocation drawAllocation cell + +theorem preparedComputedCellSourceAllocation_le_work (b eb : ℕ) (hb : b = 2 ^ eb) + (draw : cellScaleReadDraw M b Q (nat F).value) + (drawAllocation : ∀ t : Fin (groupDyadicScales M b (nat F).value).length, + Fin (groupSampleCount M Q b (groupDyadicScaleAt M b (nat F).value t)) → ℕ) + (cell : ℕ × ℕ) + (hp : ∀ q, parentAllocation q ≤ (parentInitial q).2) + (hca : ∀ i q, childAllocation i q ≤ (child i q).2) + (hia : ∀ i q, initialAllocation i q ≤ (initial i q).2) + (hcur : ∀ i q, currentAllocation i q ≤ (current i q).2) + (hd : ∀ t i, drawAllocation t i ≤ (draw t i).2) : + preparedComputedCellSourceAllocation source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial current R hc hi parentAllocation childAllocation initialAllocation currentAllocation + b eb hb draw drawAllocation cell ≤ + (preparedComputedCellSourceWithWork source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial current R hc hi b eb hb draw cell).2 := by + have hs := groupScalesAllocation_le_work eM eb eF + have ha := preparedCellGroupSourceAllocation_le_work source target parent b P F exponent Q + (by rw [hb]; exact Nat.two_pow_pos eb) hP tau a parentInitial child initial current R R hc hi + (groupScalesWithWork eM eb eF).1 (computedGroupScales_value M b F eM eb eF hM hb hF) + draw parentAllocation childAllocation initialAllocation currentAllocation drawAllocation cell hp hca hia hcur hd + unfold preparedComputedCellSourceAllocation preparedComputedCellSourceWithWork + dsimp only + omega + +variable (draw : CellGroupReadDraws M F Q) (drawAllocation : CellGroupSourceAllocations M F Q) + +private def castGroupSourceAllocation (b : ℕ) (cell : ℕ × ℕ) : + ∀ t : Fin (groupDyadicScales M b (nat F).value).length, + Fin (groupSampleCount M Q b (groupDyadicScaleAt M b (nat F).value t)) → ℕ := + Eq.mpr (congrArg (fun f => ∀ t : Fin (groupDyadicScales M b f).length, + Fin (groupSampleCount M Q b (groupDyadicScaleAt M b f t)) → ℕ) (nat_value F)) (drawAllocation b cell) + +private theorem castGroupSourceAllocation_le (b : ℕ) (cell : ℕ × ℕ) + (hd : ∀ t i, drawAllocation b cell t i ≤ (draw b cell t i).2) : + ∀ t i, castGroupSourceAllocation F Q drawAllocation b cell t i ≤ + (Eq.mpr (congrArg (cellScaleReadDraw M b Q) (nat_value F)) (draw b cell) t i).2 := by + exact transportedSourceAllocation_le (nat_value F) (draw b cell) (drawAllocation b cell) hd + +def preparedLocalGroupScaleSourceAllocation (eb : ℕ) (query : TargetInterval target.length) : ℕ := + let b := 2 ^ eb + let side := (canonicalMulWithWork (inversePowerTwo exponent) (nat b)).1 + let radius := (naturalCeilingWithWork (parentInitial query).1).1 + let cells := (targetCellsWithWork side (bitWordValue radius) query).1 + parentAllocation query + canonicalMulAllocation (inversePowerTwo exponent) (nat b) + + naturalCeilingAllocation (parentInitial query).1 + targetCellsAllocation side (bitWordValue radius) query + + filterMapAllocation (fun cell => + preparedComputedCellSourceWithWork source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial current R hc hi b eb rfl + (Eq.mpr (congrArg (cellScaleReadDraw M b Q) (nat_value F)) (draw b cell)) cell) + (fun cell => preparedComputedCellSourceAllocation source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial current R hc hi parentAllocation childAllocation initialAllocation currentAllocation + b eb rfl (Eq.mpr (congrArg (cellScaleReadDraw M b Q) (nat_value F)) (draw b cell)) + (castGroupSourceAllocation F Q drawAllocation b cell) cell) cells + eb + +theorem preparedLocalGroupScaleSourceAllocation_le_work (eb : ℕ) (query : TargetInterval target.length) + (hp : ∀ q, parentAllocation q ≤ (parentInitial q).2) + (hca : ∀ i q, childAllocation i q ≤ (child i q).2) + (hia : ∀ i q, initialAllocation i q ≤ (initial i q).2) + (hcur : ∀ i q, currentAllocation i q ≤ (current i q).2) + (hd : ∀ b cell t i, drawAllocation b cell t i ≤ (draw b cell t i).2) : + preparedLocalGroupScaleSourceAllocation source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial current R hc hi parentAllocation childAllocation initialAllocation currentAllocation + draw drawAllocation eb query ≤ + (preparedLocalGroupScaleSourceWithWork source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial current R hc hi eb draw query).2 := by + let b := 2 ^ eb + let side := (canonicalMulWithWork (inversePowerTwo exponent) (nat b)).1 + let cells := (targetCellsWithWork side (bitWordValue (naturalCeilingWithWork (parentInitial query).1).1) query).1 + have hm := canonicalMulAllocation_le_work (inversePowerTwo exponent) (nat b) + have hr := naturalCeilingAllocation_le_work (parentInitial query).1 + have ht := targetCellsAllocation_le_work side (bitWordValue (naturalCeilingWithWork (parentInitial query).1).1) query + have hf := filterMapAllocation_le_work + (fun cell => preparedComputedCellSourceWithWork source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial current R hc hi b eb rfl + (Eq.mpr (congrArg (cellScaleReadDraw M b Q) (nat_value F)) (draw b cell)) cell) + (fun cell => preparedComputedCellSourceAllocation source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial current R hc hi parentAllocation childAllocation initialAllocation currentAllocation + b eb rfl (Eq.mpr (congrArg (cellScaleReadDraw M b Q) (nat_value F)) (draw b cell)) + (castGroupSourceAllocation F Q drawAllocation b cell) cell) cells + (fun cell _ => preparedComputedCellSourceAllocation_le_work source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial current R hc hi parentAllocation childAllocation initialAllocation currentAllocation + b eb rfl _ _ cell hp hca hia hcur (castGroupSourceAllocation_le F Q draw drawAllocation b cell (hd b cell))) + have hq := hp query + unfold preparedLocalGroupScaleSourceAllocation preparedLocalGroupScaleSourceWithWork + dsimp only [b, side, cells] at hm ht hf ⊢ + omega + +def localGroupSourceScaleBlock (eb : ℕ) (query : TargetInterval target.length) : + List (BinaryBellmanAction (TargetInterval target.length) (Fin M × TargetInterval target.length) M) × ℕ := + let guard := refinementScaleGuardWithWork F (2 ^ eb) a (parentInitial query).1 + if guard.1 then + let selected := preparedLocalGroupScaleSourceWithWork source target parent P F exponent Q eM eF + hM hF hP tau a parentInitial child initial current R hc hi eb draw query + (selected.1, guard.2 + selected.2 + eb + 4) + else ([], guard.2 + eb + 4) + +def localGroupSourceScaleBlockAllocation (eb : ℕ) (query : TargetInterval target.length) : ℕ := + refinementScaleGuardAllocation F (2 ^ eb) a (parentInitial query).1 + eb + + if (refinementScaleGuardWithWork F (2 ^ eb) a (parentInitial query).1).1 then + preparedLocalGroupScaleSourceAllocation source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial current R hc hi parentAllocation childAllocation initialAllocation currentAllocation + draw drawAllocation eb query + else 0 + +theorem localGroupSourceScaleBlockAllocation_le_work (eb : ℕ) (query : TargetInterval target.length) + (hp : ∀ q, parentAllocation q ≤ (parentInitial q).2) + (hca : ∀ i q, childAllocation i q ≤ (child i q).2) + (hia : ∀ i q, initialAllocation i q ≤ (initial i q).2) + (hcur : ∀ i q, currentAllocation i q ≤ (current i q).2) + (hd : ∀ b cell t i, drawAllocation b cell t i ≤ (draw b cell t i).2) : + localGroupSourceScaleBlockAllocation source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial current R hc hi parentAllocation childAllocation initialAllocation currentAllocation + draw drawAllocation eb query ≤ + (localGroupSourceScaleBlock source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial current R hc hi draw eb query).2 := by + have costBound (g g' s s' e : ℕ) (hg : g ≤ g') (hs : s ≤ s') : + g + e + s ≤ g' + s' + e + 4 := by + omega + have hg := refinementScaleGuardAllocation_le_work F (2 ^ eb) a (parentInitial query).1 + have hs := preparedLocalGroupScaleSourceAllocation_le_work source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial current R hc hi parentAllocation childAllocation initialAllocation currentAllocation + draw drawAllocation eb query hp hca hia hcur hd + unfold localGroupSourceScaleBlockAllocation localGroupSourceScaleBlock + dsimp only + split_ifs <;> dsimp only + · exact costBound _ _ _ _ _ hg hs + · exact (Nat.add_le_add_right hg eb).trans (Nat.le_add_right _ 4) + +def preparedLocalCellGroupsSourceAllocation (N : ℕ) (query : TargetInterval target.length) : ℕ := + let count := max 1 N.bits.length + parentAllocation query + count + N.bits.length + + arithmeticFlatMapAllocation + (fun eb => localGroupSourceScaleBlock source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial current R hc hi draw eb query) + (fun eb => localGroupSourceScaleBlockAllocation source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial current R hc hi parentAllocation childAllocation initialAllocation currentAllocation + draw drawAllocation eb query) (List.range count) + +theorem preparedLocalCellGroupsSourceAllocation_le_work (N : ℕ) (query : TargetInterval target.length) + (hp : ∀ q, parentAllocation q ≤ (parentInitial q).2) + (hca : ∀ i q, childAllocation i q ≤ (child i q).2) + (hia : ∀ i q, initialAllocation i q ≤ (initial i q).2) + (hcur : ∀ i q, currentAllocation i q ≤ (current i q).2) + (hd : ∀ b cell t i, drawAllocation b cell t i ≤ (draw b cell t i).2) : + preparedLocalCellGroupsSourceAllocation source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial current R hc hi parentAllocation childAllocation initialAllocation currentAllocation + draw drawAllocation N query ≤ + (preparedLocalCellGroupsSourceWithWork source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial current R hc hi N draw query).2 := by + have hm := arithmeticFlatMapAllocation_le_work + (fun eb => localGroupSourceScaleBlock source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial current R hc hi draw eb query) + (fun eb => localGroupSourceScaleBlockAllocation source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial current R hc hi parentAllocation childAllocation initialAllocation currentAllocation + draw drawAllocation eb query) (List.range (max 1 N.bits.length)) + (fun eb _ => localGroupSourceScaleBlockAllocation_le_work source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial current R hc hi parentAllocation childAllocation initialAllocation currentAllocation + draw drawAllocation eb query hp hca hia hcur hd) + have hq := hp query + change _ ≤ (parentInitial query).2 + + (arithmeticFlatMapWithWork (fun eb => localGroupSourceScaleBlock source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial current R hc hi draw eb query) (List.range (max 1 N.bits.length))).2 + + max 1 N.bits.length + N.bits.length + 2 + unfold preparedLocalCellGroupsSourceAllocation + dsimp only + omega + +end Local +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryLocalGuardWork.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryLocalGuardWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..7b21d05ed02dad65b8185c761c2ddd56018c7838 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryLocalGuardWork.lean @@ -0,0 +1,87 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryLocalGroupActions +import OAI.Combinatorics.EditApproximation.Binary.BinaryAffineGuard + +namespace OAI + +/-! Every local eligibility test is charged at the bit level, including +its rational divisions and the construction of its two thresholds. -/ + +namespace EditApproximation +namespace BinaryFraction + +def localEligibilityBitBudget (B : ℕ) : ℕ := + 4000 * (B + 1) ^ 2 + 2100 * (4 * B + 4) ^ 2 + 2000 * (4 * B + 3) ^ 2 + + 2 * (1000 * (16 * B + 13) ^ 2 + 1) + 2 * B + 8 + +theorem centerEligibilityWithWork_cost (b F B : ℕ) (a initial : BinaryFraction) + (hB : 6 ≤ B) (hb : Nat.size b + 2 ≤ B) (hF : Nat.size F + 2 ≤ B) + (ha : a.width ≤ B) (hi : initial.width ≤ B) : + (centerEligibilityWithWork b F a initial).2 ≤ localEligibilityBitBudget B := by + have hfour : (nat 4).width ≤ B := (nat_width_le 4).trans (by + have h : Nat.size 4 = 3 := by decide + omega) + have height : (nat 8).width ≤ B := (nat_width_le 8).trans (by + have h : Nat.size 8 = 4 := by decide + omega) + have hbn := (nat_width_le b).trans hb + have hFn := (nat_width_le F).trans hF + have hdw := canonicalMulWithWork_width (nat 4) a B hfour ha + have hdc := canonicalMulWithWork_cost (nat 4) a B hfour ha + have hlw := divWithWork_width_uniform (nat b) (canonicalMulWithWork (nat 4) a).1 + (4 * B + 2) (by omega) hdw + have hlc := divWithWork_cost (nat b) (canonicalMulWithWork (nat 4) a).1 + (4 * B + 2) (by omega) hdw + have hfw := canonicalMulWithWork_width (nat 8) (nat F) B height hFn + have hfc := canonicalMulWithWork_cost (nat 8) (nat F) B height hFn + have huw := canonicalMulWithWork_width (canonicalMulWithWork (nat 8) (nat F)).1 (nat b) + (4 * B + 2) hfw (by omega) + have huc := canonicalMulWithWork_cost (canonicalMulWithWork (nat 8) (nat F)).1 (nat b) + (4 * B + 2) hfw (by omega) + have hlow := leWithWork_cost (divWithWork (nat b) (canonicalMulWithWork (nat 4) a).1).1 + initial (16 * B + 12) (by omega) (by omega) + have hhigh := leWithWork_cost initial + (canonicalMulWithWork (canonicalMulWithWork (nat 8) (nat F)).1 (nat b)).1 + (16 * B + 12) (by omega) (by omega) + simp only [Nat.add_assoc, Nat.reduceAdd] at hlc huc hlow hhigh + change _ + _ + _ + _ + _ + _ + Nat.size b + Nat.size F + 8 ≤ _ + unfold localEligibilityBitBudget + omega + +theorem refinementScaleGuardWithWork_cost (F b B : ℕ) (a w : BinaryFraction) + (hB : 7 ≤ B) (hb : Nat.size b + 2 ≤ B) (hF : Nat.size F + 2 ≤ B) + (ha : a.width ≤ B) (hw : w.width ≤ B) : + (refinementScaleGuardWithWork F b a w).2 ≤ localEligibilityBitBudget B := by + have hsixteen : (nat 16).width ≤ B := (nat_width_le 16).trans (by + have h : Nat.size 16 = 5 := by decide + omega) + have height : (nat 8).width ≤ B := (nat_width_le 8).trans (by + have h : Nat.size 8 = 4 := by decide + omega) + have hbn := (nat_width_le b).trans hb + have hFn := (nat_width_le F).trans hF + have hdw := canonicalMulWithWork_width (nat 16) (nat F) B hsixteen hFn + have hdc := canonicalMulWithWork_cost (nat 16) (nat F) B hsixteen hFn + have hlw := divWithWork_width_uniform w (canonicalMulWithWork (nat 16) (nat F)).1 + (4 * B + 2) (by omega) hdw + have hlc := divWithWork_cost w (canonicalMulWithWork (nat 16) (nat F)).1 + (4 * B + 2) (by omega) hdw + have hfw := canonicalMulWithWork_width (nat 8) a B height ha + have hfc := canonicalMulWithWork_cost (nat 8) a B height ha + have huw := canonicalMulWithWork_width (canonicalMulWithWork (nat 8) a).1 w + (4 * B + 2) hfw (by omega) + have huc := canonicalMulWithWork_cost (canonicalMulWithWork (nat 8) a).1 w + (4 * B + 2) hfw (by omega) + have hlow := leWithWork_cost (divWithWork w (canonicalMulWithWork (nat 16) (nat F)).1).1 + (nat b) (16 * B + 12) (by omega) (by omega) + have hhigh := leWithWork_cost (nat b) + (canonicalMulWithWork (canonicalMulWithWork (nat 8) a).1 w).1 + (16 * B + 12) (by omega) (by omega) + simp only [Nat.add_assoc, Nat.reduceAdd] at hlc huc hlow hhigh + change _ + _ + _ + _ + _ + _ + Nat.size b + Nat.size F + 8 ≤ _ + unfold localEligibilityBitBudget + omega + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryLocalOnlineReads.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryLocalOnlineReads.lean new file mode 100644 index 0000000000000000000000000000000000000000..98333020c7f2efa17175f7b80510436b4e36a1f0 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryLocalOnlineReads.lean @@ -0,0 +1,78 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryPreparedOnlineReads +import OAI.Combinatorics.EditApproximation.Binary.BinaryPreparedLocalOnline + +namespace OAI + +/-! Query-local online scales explicitly read the initial value at the +query and at each rounded center before running the full band kernel. -/ + +namespace EditApproximation +namespace BinaryFraction + +section Local +variable {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (P F exponent H : ℕ) (hP : 0 < P) + (tau a eta kappa : BinaryFraction) + (parentInitial : TargetInterval target.length → BinaryFraction × ℕ) + (child initial : Fin M → TargetInterval target.length → BinaryFraction × ℕ) + (table : ℕ → Fin M × TargetInterval target.length → BinaryFraction × ℕ) + (R : ℕ) (hc : ∀ i q, (child i q).2 ≤ R) (hi : ∀ i q, (initial i q).2 ≤ R) + (t : ℕ) (integer : ℕ → TargetInterval target.length → ℕ) + +def preparedLocalOnlineScaleReadWithWork (e : ℕ) (query : TargetInterval target.length) : + Option (BinaryBellmanAction (TargetInterval target.length) + (Fin M × TargetInterval target.length) M) × ℕ := + let b := 2 ^ e + let spacing := seedGridSpacingWithWork b P + let center := roundStateWithWork (bitWordValue spacing.1) (seedGridSpacingWithWork_pos b P hP) query + let word := parentInitial center.1 + let eligible := centerEligibilityWithWork b F a word.1 + if eligible.1 then + let selected := preparedOnlineReadWithWork source target parent P F exponent H b (Nat.two_pow_pos e) hP + tau eta kappa child initial table R hc hi t center.1 (integer b center.1) + (selected.1, spacing.2 + center.2 + word.2 + eligible.2 + selected.2 + e + 4) + else (none, spacing.2 + center.2 + word.2 + eligible.2 + e + 3) + +theorem preparedLocalOnlineScaleReadWithWork_eq (e : ℕ) (query : TargetInterval target.length) + (ht : ∀ s ≤ t + 1, ∀ i, (table s i).2 ≤ R) : + (preparedLocalOnlineScaleReadWithWork source target parent P F exponent H hP tau a eta kappa + parentInitial child initial table R hc hi t integer e query).1 = + (preparedLocalOnlineScaleWithWork source target parent P F exponent H e hP tau a eta kappa + (fun r => (parentInitial r).1) (fun i q => (child i q).1) (fun i q => (initial i q).1) + (fun s i => (table s i).1) t integer query).1 := by + unfold preparedLocalOnlineScaleReadWithWork preparedLocalOnlineScaleWithWork + dsimp only + split_ifs + · exact (preparedOnlineReadWithWork_eq_cost source target parent P F exponent H (2 ^ e) + (Nat.two_pow_pos e) hP tau eta kappa child initial table R hc hi t _ _ ht).1 + · rfl + +def preparedLocalOnlineActionsReadWithWork (N : ℕ) (query : TargetInterval target.length) : + List (BinaryBellmanAction (TargetInterval target.length) + (Fin M × TargetInterval target.length) M) × ℕ := + let word := parentInitial query + let scales := queryExponentsWithWork N F a word.1 + let selected := filterMapWithWork + (fun e => preparedLocalOnlineScaleReadWithWork source target parent P F exponent H hP tau a eta kappa + parentInitial child initial table R hc hi t integer e query) scales.1 + (selected.1, word.2 + scales.2 + selected.2 + 1) + +theorem preparedLocalOnlineActionsReadWithWork_eq (N : ℕ) (query : TargetInterval target.length) + (ht : ∀ s ≤ t + 1, ∀ i, (table s i).2 ≤ R) : + (preparedLocalOnlineActionsReadWithWork source target parent P F exponent H hP tau a eta kappa + parentInitial child initial table R hc hi t integer N query).1 = + (preparedLocalOnlineActionsWithWork source target parent N P F exponent H hP tau a eta kappa + (fun r => (parentInitial r).1) (fun i q => (child i q).1) (fun i q => (initial i q).1) + (fun s i => (table s i).1) t integer query).1 := by + simp only [preparedLocalOnlineActionsReadWithWork, preparedLocalOnlineActionsWithWork, + filterMapWithWork_value] + apply List.filterMap_congr + intro e _ + exact preparedLocalOnlineScaleReadWithWork_eq source target parent P F exponent H hP tau a eta kappa + parentInitial child initial table R hc hi t integer e query ht + +end Local +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryLocalOnlineSource.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryLocalOnlineSource.lean new file mode 100644 index 0000000000000000000000000000000000000000..8fe1f6c166213fc02486709584c15ea4d1aaeee6 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryLocalOnlineSource.lean @@ -0,0 +1,145 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryLocalOnlineReads +import OAI.Combinatorics.EditApproximation.Binary.BinaryReadCostBounds + +namespace OAI + +/-! Online candidate selection charges the finite source-buffer decoder +at the point where its integer is consumed. Ineligible centers do not +read a random coordinate. -/ + +namespace EditApproximation.BinaryFraction +section Local +variable {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (P F exponent H : ℕ) (hP : 0 < P) + (tau a eta kappa : BinaryFraction) + (parentInitial : TargetInterval target.length → BinaryFraction × ℕ) + (child initial : Fin M → TargetInterval target.length → BinaryFraction × ℕ) + (table : ℕ → Fin M × TargetInterval target.length → BinaryFraction × ℕ) + (R : ℕ) (hc : ∀ i q, (child i q).2 ≤ R) (hi : ∀ i q, (initial i q).2 ≤ R) + (t : ℕ) (integer : ℕ → TargetInterval target.length → ℕ × ℕ) + +def preparedLocalOnlineScaleSourceWithWork (e : ℕ) (query : TargetInterval target.length) : + Option (BinaryBellmanAction (TargetInterval target.length) + (Fin M × TargetInterval target.length) M) × ℕ := + let b := 2 ^ e + let spacing := seedGridSpacingWithWork b P + let center := roundStateWithWork (bitWordValue spacing.1) (seedGridSpacingWithWork_pos b P hP) query + let word := parentInitial center.1 + let eligible := centerEligibilityWithWork b F a word.1 + if eligible.1 then + let sample := integer b center.1 + let selected := preparedOnlineReadWithWork source target parent P F exponent H b (Nat.two_pow_pos e) hP + tau eta kappa child initial table R hc hi t center.1 sample.1 + (selected.1, spacing.2 + center.2 + word.2 + eligible.2 + selected.2 + sample.2 + e + 5) + else (none, spacing.2 + center.2 + word.2 + eligible.2 + e + 3) + +theorem preparedLocalOnlineScaleSourceWithWork_value (e : ℕ) (query : TargetInterval target.length) : + (preparedLocalOnlineScaleSourceWithWork source target parent P F exponent H hP tau a eta kappa + parentInitial child initial table R hc hi t integer e query).1 = + (preparedLocalOnlineScaleReadWithWork source target parent P F exponent H hP tau a eta kappa + parentInitial child initial table R hc hi t (fun b q => (integer b q).1) e query).1 := by + unfold preparedLocalOnlineScaleSourceWithWork preparedLocalOnlineScaleReadWithWork + dsimp only + split_ifs <;> rfl + +theorem preparedLocalOnlineScaleSourceWithWork_eq_cost_on (e : ℕ) (query : TargetInterval target.length) + (S : ℕ) + (hs : (centerEligibilityWithWork (2 ^ e) F a + (parentInitial (roundStateWithWork (bitWordValue (seedGridSpacingWithWork (2 ^ e) P).1) + (seedGridSpacingWithWork_pos (2 ^ e) P hP) query).1).1).1 = true → + (integer (2 ^ e) (roundStateWithWork (bitWordValue (seedGridSpacingWithWork (2 ^ e) P).1) + (seedGridSpacingWithWork_pos (2 ^ e) P hP) query).1).2 ≤ S) : + (preparedLocalOnlineScaleSourceWithWork source target parent P F exponent H hP tau a eta kappa + parentInitial child initial table R hc hi t integer e query).1 = + (preparedLocalOnlineScaleReadWithWork source target parent P F exponent H hP tau a eta kappa + parentInitial child initial table R hc hi t (fun b q => (integer b q).1) e query).1 ∧ + (preparedLocalOnlineScaleSourceWithWork source target parent P F exponent H hP tau a eta kappa + parentInitial child initial table R hc hi t integer e query).2 ≤ + (preparedLocalOnlineScaleReadWithWork source target parent P F exponent H hP tau a eta kappa + parentInitial child initial table R hc hi t (fun b q => (integer b q).1) e query).2 * (S + 4) := by + unfold preparedLocalOnlineScaleSourceWithWork preparedLocalOnlineScaleReadWithWork + dsimp only + split_ifs with hguard + · refine ⟨rfl, ?_⟩ + have hsample := hs hguard + nlinarith only [hsample] + · exact ⟨rfl, by nlinarith only [Nat.zero_le S]⟩ +theorem preparedLocalOnlineScaleSourceWithWork_eq_cost (e : ℕ) (query : TargetInterval target.length) + (S : ℕ) (hs : ∀ b q, (integer b q).2 ≤ S) : + (preparedLocalOnlineScaleSourceWithWork source target parent P F exponent H hP tau a eta kappa + parentInitial child initial table R hc hi t integer e query).1 = + (preparedLocalOnlineScaleReadWithWork source target parent P F exponent H hP tau a eta kappa + parentInitial child initial table R hc hi t (fun b q => (integer b q).1) e query).1 ∧ + (preparedLocalOnlineScaleSourceWithWork source target parent P F exponent H hP tau a eta kappa + parentInitial child initial table R hc hi t integer e query).2 ≤ + (preparedLocalOnlineScaleReadWithWork source target parent P F exponent H hP tau a eta kappa + parentInitial child initial table R hc hi t (fun b q => (integer b q).1) e query).2 * (S + 4) := by + exact preparedLocalOnlineScaleSourceWithWork_eq_cost_on source target parent P F exponent H hP + tau a eta kappa parentInitial child initial table R hc hi t integer e query S (fun _ => hs _ _) + +def preparedLocalOnlineActionsSourceWithWork (N : ℕ) (query : TargetInterval target.length) : + List (BinaryBellmanAction (TargetInterval target.length) + (Fin M × TargetInterval target.length) M) × ℕ := + let word := parentInitial query + let scales := queryExponentsWithWork N F a word.1 + let selected := filterMapWithWork + (fun e => preparedLocalOnlineScaleSourceWithWork source target parent P F exponent H hP tau a eta kappa + parentInitial child initial table R hc hi t integer e query) scales.1 + (selected.1, word.2 + scales.2 + selected.2 + 1) + +theorem preparedLocalOnlineActionsSourceWithWork_value (N : ℕ) (query : TargetInterval target.length) : + (preparedLocalOnlineActionsSourceWithWork source target parent P F exponent H hP tau a eta kappa + parentInitial child initial table R hc hi t integer N query).1 = + (preparedLocalOnlineActionsReadWithWork source target parent P F exponent H hP tau a eta kappa + parentInitial child initial table R hc hi t (fun b q => (integer b q).1) N query).1 := by + simp only [preparedLocalOnlineActionsSourceWithWork, preparedLocalOnlineActionsReadWithWork, + filterMapWithWork_value, preparedLocalOnlineScaleSourceWithWork_value] + +theorem preparedLocalOnlineActionsSourceWithWork_eq_cost_on (N : ℕ) (query : TargetInterval target.length) + (S : ℕ) + (hs : ∀ e ∈ (queryExponentsWithWork N F a (parentInitial query).1).1, + (centerEligibilityWithWork (2 ^ e) F a + (parentInitial (roundStateWithWork (bitWordValue (seedGridSpacingWithWork (2 ^ e) P).1) + (seedGridSpacingWithWork_pos (2 ^ e) P hP) query).1).1).1 = true → + (integer (2 ^ e) (roundStateWithWork (bitWordValue (seedGridSpacingWithWork (2 ^ e) P).1) + (seedGridSpacingWithWork_pos (2 ^ e) P hP) query).1).2 ≤ S) : + (preparedLocalOnlineActionsSourceWithWork source target parent P F exponent H hP tau a eta kappa + parentInitial child initial table R hc hi t integer N query).1 = + (preparedLocalOnlineActionsReadWithWork source target parent P F exponent H hP tau a eta kappa + parentInitial child initial table R hc hi t (fun b q => (integer b q).1) N query).1 ∧ + (preparedLocalOnlineActionsSourceWithWork source target parent P F exponent H hP tau a eta kappa + parentInitial child initial table R hc hi t integer N query).2 ≤ + (preparedLocalOnlineActionsReadWithWork source target parent P F exponent H hP tau a eta kappa + parentInitial child initial table R hc hi t (fun b q => (integer b q).1) N query).2 * (S + 4) := by + have h := filterMapWithWork_factor + (fun e => preparedLocalOnlineScaleSourceWithWork source target parent P F exponent H hP tau a eta kappa + parentInitial child initial table R hc hi t integer e query) + (fun e => preparedLocalOnlineScaleReadWithWork source target parent P F exponent H hP tau a eta kappa + parentInitial child initial table R hc hi t (fun b q => (integer b q).1) e query) + (queryExponentsWithWork N F a (parentInitial query).1).1 (S + 4) (by omega) + (fun e he => (preparedLocalOnlineScaleSourceWithWork_eq_cost_on source target parent P F exponent H hP + tau a eta kappa parentInitial child initial table R hc hi t integer e query S (hs e he)).1) + (fun e he => (preparedLocalOnlineScaleSourceWithWork_eq_cost_on source target parent P F exponent H hP + tau a eta kappa parentInitial child initial table R hc hi t integer e query S (hs e he)).2) + unfold preparedLocalOnlineActionsSourceWithWork preparedLocalOnlineActionsReadWithWork + dsimp only + rw [h.1] + exact ⟨rfl, by nlinarith only [h.2]⟩ +theorem preparedLocalOnlineActionsSourceWithWork_eq_cost (N : ℕ) (query : TargetInterval target.length) + (S : ℕ) (hs : ∀ b q, (integer b q).2 ≤ S) : + (preparedLocalOnlineActionsSourceWithWork source target parent P F exponent H hP tau a eta kappa + parentInitial child initial table R hc hi t integer N query).1 = + (preparedLocalOnlineActionsReadWithWork source target parent P F exponent H hP tau a eta kappa + parentInitial child initial table R hc hi t (fun b q => (integer b q).1) N query).1 ∧ + (preparedLocalOnlineActionsSourceWithWork source target parent P F exponent H hP tau a eta kappa + parentInitial child initial table R hc hi t integer N query).2 ≤ + (preparedLocalOnlineActionsReadWithWork source target parent P F exponent H hP tau a eta kappa + parentInitial child initial table R hc hi t (fun b q => (integer b q).1) N query).2 * (S + 4) := by + exact preparedLocalOnlineActionsSourceWithWork_eq_cost_on source target parent P F exponent H hP + tau a eta kappa parentInitial child initial table R hc hi t integer N query S + (fun e _ _ => hs _ _) + +end Local +end EditApproximation.BinaryFraction + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryLocalOnlineSourceSpace.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryLocalOnlineSourceSpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..0b500be4c39f079eb6c46f8d2d7a4ef780cdf93b --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryLocalOnlineSourceSpace.lean @@ -0,0 +1,112 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryOnlineSourceSpace +import OAI.Combinatorics.EditApproximation.Queries.QueryEligibilitySpace + +namespace OAI + +namespace EditApproximation.BinaryFraction + +section Local +variable {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (P F exponent H : ℕ) (hP : 0 < P) + (tau a eta kappa : BinaryFraction) + (parentInitial : TargetInterval target.length → BinaryFraction × ℕ) + (child initial : Fin M → TargetInterval target.length → BinaryFraction × ℕ) + (table : ℕ → Fin M × TargetInterval target.length → BinaryFraction × ℕ) + (R : ℕ) (hc : ∀ i q, (child i q).2 ≤ R) (hi : ∀ i q, (initial i q).2 ≤ R) + (t : ℕ) (integer : ℕ → TargetInterval target.length → ℕ × ℕ) + (parentAllocation : TargetInterval target.length → ℕ) + (childAllocation initialAllocation : Fin M → TargetInterval target.length → ℕ) + (tableAllocation : ℕ → Fin M × TargetInterval target.length → ℕ) + (integerAllocation : ℕ → TargetInterval target.length → ℕ) + +def preparedLocalOnlineScaleSourceAllocation (e : ℕ) (query : TargetInterval target.length) : ℕ := + let b := 2 ^ e + let center := (roundStateWithWork (bitWordValue (seedGridSpacingWithWork b P).1) + (seedGridSpacingWithWork_pos b P hP) query).1 + seedGridSpacingAllocation b P + roundStateAllocation (bitWordValue (seedGridSpacingWithWork b P).1) query + + parentAllocation center + centerEligibilityAllocation b F a (parentInitial center).1 + e + + if (centerEligibilityWithWork b F a (parentInitial center).1).1 then + integerAllocation b center + preparedOnlineReadAllocation source target parent P F exponent H b + (Nat.two_pow_pos e) hP tau eta kappa child initial table R hc hi + childAllocation initialAllocation tableAllocation t center (integer b center).1 + else 0 + +theorem preparedLocalOnlineScaleSourceAllocation_le_work (e : ℕ) (query : TargetInterval target.length) + (hp : ∀ q, parentAllocation q ≤ (parentInitial q).2) + (hca : ∀ i q, childAllocation i q ≤ (child i q).2) + (hia : ∀ i q, initialAllocation i q ≤ (initial i q).2) + (hta : ∀ s q, tableAllocation s q ≤ (table s q).2) + (hint : ∀ b q, integerAllocation b q ≤ (integer b q).2) : + preparedLocalOnlineScaleSourceAllocation source target parent P F exponent H hP tau a eta kappa + parentInitial child initial table R hc hi t integer parentAllocation childAllocation initialAllocation + tableAllocation integerAllocation e query ≤ + 3 * (preparedLocalOnlineScaleSourceWithWork source target parent P F exponent H hP tau a eta kappa + parentInitial child initial table R hc hi t integer e query).2 := by + have costBound (s s' r r' p p' g g' i i' a a' e k : ℕ) + (hs : s ≤ s') (hr : r ≤ r') (hp : p ≤ p') (hg : g ≤ g') + (hi : i ≤ i') (ha : a ≤ 3 * a') : + s + r + p + g + e + (i + a) ≤ 3 * (s' + r' + p' + g' + a' + i' + e + k) := by + omega + have emptyBound (s s' r r' p p' g g' e : ℕ) + (hs : s ≤ s') (hr : r ≤ r') (hp : p ≤ p') (hg : g ≤ g') : + s + r + p + g + e + 0 ≤ 3 * (s' + r' + p' + g' + e + 3) := by + omega + let b := 2 ^ e + let center := (roundStateWithWork (bitWordValue (seedGridSpacingWithWork b P).1) + (seedGridSpacingWithWork_pos b P hP) query).1 + have hs := seedGridSpacingAllocation_le_work b P + have hr := roundStateAllocation_le_work (bitWordValue (seedGridSpacingWithWork b P).1) + (seedGridSpacingWithWork_pos b P hP) query + have hg := centerEligibilityAllocation_le_work b F a (parentInitial center).1 + have hp' := hp center + have hint' := hint b center + have hsample := preparedOnlineReadAllocation_le_work source target parent P F exponent H b + (Nat.two_pow_pos e) hP tau eta kappa child initial table R hc hi + childAllocation initialAllocation tableAllocation t center (integer b center).1 hca hia hta + unfold preparedLocalOnlineScaleSourceAllocation preparedLocalOnlineScaleSourceWithWork + dsimp only + split_ifs <;> dsimp only [b, center] at hs hr hg hp' hint' hsample ⊢ + · exact costBound _ _ _ _ _ _ _ _ _ _ _ _ _ _ hs hr hp' hg hint' hsample + · exact emptyBound _ _ _ _ _ _ _ _ _ hs hr hp' hg + +def preparedLocalOnlineActionsSourceAllocation (N : ℕ) (query : TargetInterval target.length) : ℕ := + parentAllocation query + queryExponentsAllocation N F a (parentInitial query).1 + + filterMapAllocation + (fun e => preparedLocalOnlineScaleSourceWithWork source target parent P F exponent H hP tau a eta kappa + parentInitial child initial table R hc hi t integer e query) + (fun e => preparedLocalOnlineScaleSourceAllocation source target parent P F exponent H hP tau a eta kappa + parentInitial child initial table R hc hi t integer parentAllocation childAllocation initialAllocation + tableAllocation integerAllocation e query) + (queryExponentsWithWork N F a (parentInitial query).1).1 + +theorem preparedLocalOnlineActionsSourceAllocation_le_work (N : ℕ) (query : TargetInterval target.length) + (hp : ∀ q, parentAllocation q ≤ (parentInitial q).2) + (hca : ∀ i q, childAllocation i q ≤ (child i q).2) + (hia : ∀ i q, initialAllocation i q ≤ (initial i q).2) + (hta : ∀ s q, tableAllocation s q ≤ (table s q).2) + (hint : ∀ b q, integerAllocation b q ≤ (integer b q).2) : + preparedLocalOnlineActionsSourceAllocation source target parent P F exponent H hP tau a eta kappa + parentInitial child initial table R hc hi t integer parentAllocation childAllocation initialAllocation + tableAllocation integerAllocation N query ≤ + 3 * (preparedLocalOnlineActionsSourceWithWork source target parent P F exponent H hP tau a eta kappa + parentInitial child initial table R hc hi t integer N query).2 := by + have hq := hp query + have he := queryExponentsAllocation_le_work N F a (parentInitial query).1 + have hm := filterMapAllocation_le_three_work + (fun e => preparedLocalOnlineScaleSourceWithWork source target parent P F exponent H hP tau a eta kappa + parentInitial child initial table R hc hi t integer e query) + (fun e => preparedLocalOnlineScaleSourceAllocation source target parent P F exponent H hP tau a eta kappa + parentInitial child initial table R hc hi t integer parentAllocation childAllocation initialAllocation + tableAllocation integerAllocation e query) + (queryExponentsWithWork N F a (parentInitial query).1).1 + (fun e _ => preparedLocalOnlineScaleSourceAllocation_le_work source target parent P F exponent H hP tau a eta kappa + parentInitial child initial table R hc hi t integer parentAllocation childAllocation initialAllocation + tableAllocation integerAllocation e query hp hca hia hta hint) + unfold preparedLocalOnlineActionsSourceAllocation preparedLocalOnlineActionsSourceWithWork + dsimp only + omega + +end Local +end EditApproximation.BinaryFraction + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryLocalReadValues.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryLocalReadValues.lean new file mode 100644 index 0000000000000000000000000000000000000000..f951606155932c16ccfbf670b5f26dae7e5194c4 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryLocalReadValues.lean @@ -0,0 +1,145 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryLocalGroupReads +import OAI.Combinatorics.EditApproximation.Binary.BinaryLocalOnlineReads +import OAI.Combinatorics.EditApproximation.Geometry.StateDomain + +namespace OAI + +/-! Value preservation of local data readers does not require a chosen +work cap for arbitrary answer tables. Finite bounds used below exist only +inside these proofs and are never constructed by the algorithm. -/ + +namespace EditApproximation.BinaryFraction + +private theorem finite_work_bound {ι : Type*} [Fintype ι] (work : ι → ℕ) : + ∃ R, ∀ i, work i ≤ R := by + classical + exact ⟨∑ i, work i, fun i => Finset.single_le_sum (f := work) (fun _ _ => Nat.zero_le _) (Finset.mem_univ i)⟩ + +section Group +variable {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (P F exponent Q eM eF : ℕ) + (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (hP : 0 < P) + (tau a : BinaryFraction) + (parentInitial : TargetInterval target.length → BinaryFraction × ℕ) + (child initial current : Fin M → TargetInterval target.length → BinaryFraction × ℕ) + (R : ℕ) (hc : ∀ i q, (child i q).2 ≤ R) (hi : ∀ i q, (initial i q).2 ≤ R) + +theorem preparedComputedCellReadWithWork_value_only (b eb : ℕ) (hb : b = 2 ^ eb) + (draw : cellScaleDraw M b Q (nat F).value) (cell : ℕ × ℕ) : + (preparedComputedCellReadWithWork source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial current R hc hi b eb hb draw cell).1 = + (preparedComputedCellGroupWithWork source target parent b P F exponent Q eM eb eF hM hb hF hP + tau a (fun r => (parentInitial r).1) (fun i q => (child i q).1) + (fun i q => (initial i q).1) (fun i q => (current i q).1) draw cell).1 := by + classical + obtain ⟨Rp, hp⟩ := finite_work_bound (fun r => (parentInitial r).2) + obtain ⟨Rc, hcur⟩ := finite_work_bound (fun iq : Fin M × TargetInterval target.length => + (current iq.1 iq.2).2) + have h := preparedCellGroupReadWithWork_eq source target parent b P F exponent Q + (by rw [hb]; exact Nat.two_pow_pos eb) hP tau a parentInitial child initial current + R R hc hi (groupScalesWithWork eM eb eF).1 + (computedGroupScales_value M b F eM eb eF hM hb hF) draw cell Rp Rc hp + (fun i q => hcur (i, q)) + simpa only [preparedComputedCellReadWithWork, preparedComputedCellGroupWithWork] using h + +theorem preparedLocalGroupScaleReadWithWork_value_only (eb : ℕ) + (draw : CellGroupDraws M F Q) (query : TargetInterval target.length) : + (preparedLocalGroupScaleReadWithWork source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial current R hc hi eb draw query).1 = + (preparedLocalGroupScaleWithWork source target parent P F exponent Q eM eF eb hM hF hP tau a + (fun r => (parentInitial r).1) (fun i q => (child i q).1) + (fun i q => (initial i q).1) (fun i q => (current i q).1) draw query).1 := by + simp only [preparedLocalGroupScaleReadWithWork, preparedLocalGroupScaleWithWork, + filterMapWithWork_value] + apply List.filterMap_congr + intro cell _ + have h := preparedComputedCellReadWithWork_value_only source target parent P F exponent Q eM eF + hM hF hP tau a parentInitial child initial current R hc hi (2 ^ eb) eb rfl + (Eq.mpr (congrArg (cellScaleDraw M (2 ^ eb) Q) (nat_value F)) (draw (2 ^ eb) cell)) cell + simpa only using h + +theorem preparedLocalCellGroupsReadWithWork_value_only (N : ℕ) + (draw : CellGroupDraws M F Q) (query : TargetInterval target.length) : + (preparedLocalCellGroupsReadWithWork source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial current R hc hi N draw query).1 = + (preparedLocalCellGroupsWithWork source target parent N P F exponent Q eM eF hM hF hP tau a + (fun r => (parentInitial r).1) (fun i q => (child i q).1) + (fun i q => (initial i q).1) (fun i q => (current i q).1) draw query).1 := by + simp only [preparedLocalCellGroupsReadWithWork, preparedLocalCellGroupsWithWork, + arithmeticFlatMapWithWork_value] + apply List.flatMap_congr + intro eb _ + split_ifs + · have h := preparedLocalGroupScaleReadWithWork_value_only source target parent P F exponent Q eM eF + hM hF hP tau a parentInitial child initial current R hc hi eb draw query + simpa only using h + · rfl +end Group + +section Online +variable {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (P F exponent H : ℕ) (hP : 0 < P) + (tau a eta kappa : BinaryFraction) + (parentInitial : TargetInterval target.length → BinaryFraction × ℕ) + (child initial : Fin M → TargetInterval target.length → BinaryFraction × ℕ) + (table : ℕ → Fin M × TargetInterval target.length → BinaryFraction × ℕ) + (R : ℕ) (hc : ∀ i q, (child i q).2 ≤ R) (hi : ∀ i q, (initial i q).2 ≤ R) + (t : ℕ) (integer : ℕ → TargetInterval target.length → ℕ) + +private theorem preparedOnlineReadWithWork_cap_irrel (b : ℕ) (hb : 0 < b) + (R' : ℕ) (hc' : ∀ i q, (child i q).2 ≤ R') (hi' : ∀ i q, (initial i q).2 ≤ R') + (center : TargetInterval target.length) (sample : ℕ) : + preparedOnlineReadWithWork source target parent P F exponent H b hb hP tau eta kappa + child initial table R hc hi t center sample = + preparedOnlineReadWithWork source target parent P F exponent H b hb hP tau eta kappa + child initial table R' hc' hi' t center sample := by + rfl + +theorem preparedOnlineReadWithWork_value_only (b : ℕ) (hb : 0 < b) + (center : TargetInterval target.length) (sample : ℕ) : + (preparedOnlineReadWithWork source target parent P F exponent H b hb hP tau eta kappa + child initial table R hc hi t center sample).1 = + (preparedOnlineWithWork source target parent P F exponent H b hb hP tau eta kappa + (fun i q => (child i q).1) (fun i q => (initial i q).1) + (fun s i => (table s i).1) t center sample).1 := by + classical + obtain ⟨S, hs⟩ := finite_work_bound (fun si : Fin (t + 2) × (Fin M × TargetInterval target.length) => + (table si.1.val si.2).2) + let R' := max R S + have hc' : ∀ i q, (child i q).2 ≤ R' := fun i q => (hc i q).trans (Nat.le_max_left _ _) + have hi' : ∀ i q, (initial i q).2 ≤ R' := fun i q => (hi i q).trans (Nat.le_max_left _ _) + rw [preparedOnlineReadWithWork_cap_irrel source target parent P F exponent H hP + tau eta kappa child initial table R hc hi t b hb R' hc' hi' center sample] + exact (preparedOnlineReadWithWork_eq_cost source target parent P F exponent H b hb hP + tau eta kappa child initial table R' hc' hi' t center sample (fun s hst iq => + (hs (⟨s, by omega⟩, iq)).trans (Nat.le_max_right R S))).1 + +theorem preparedLocalOnlineScaleReadWithWork_value_only (e : ℕ) (query : TargetInterval target.length) : + (preparedLocalOnlineScaleReadWithWork source target parent P F exponent H hP tau a eta kappa + parentInitial child initial table R hc hi t integer e query).1 = + (preparedLocalOnlineScaleWithWork source target parent P F exponent H e hP tau a eta kappa + (fun r => (parentInitial r).1) (fun i q => (child i q).1) (fun i q => (initial i q).1) + (fun s i => (table s i).1) t integer query).1 := by + unfold preparedLocalOnlineScaleReadWithWork preparedLocalOnlineScaleWithWork + dsimp only + split_ifs + · exact preparedOnlineReadWithWork_value_only source target parent P F exponent H hP + tau eta kappa child initial table R hc hi t (2 ^ e) (Nat.two_pow_pos e) _ _ + · rfl + +theorem preparedLocalOnlineActionsReadWithWork_value_only (N : ℕ) (query : TargetInterval target.length) : + (preparedLocalOnlineActionsReadWithWork source target parent P F exponent H hP tau a eta kappa + parentInitial child initial table R hc hi t integer N query).1 = + (preparedLocalOnlineActionsWithWork source target parent N P F exponent H hP tau a eta kappa + (fun r => (parentInitial r).1) (fun i q => (child i q).1) (fun i q => (initial i q).1) + (fun s i => (table s i).1) t integer query).1 := by + simp only [preparedLocalOnlineActionsReadWithWork, preparedLocalOnlineActionsWithWork, + filterMapWithWork_value] + apply List.filterMap_congr + intro e _ + exact preparedLocalOnlineScaleReadWithWork_value_only source target parent P F exponent H hP + tau a eta kappa parentInitial child initial table R hc hi t integer e query +end Online +end EditApproximation.BinaryFraction + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryLocalRepresentativeWork.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryLocalRepresentativeWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..9c62f4fac0172f41603985c293c9b32a267bffc4 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryLocalRepresentativeWork.lean @@ -0,0 +1,196 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryRefinementLists +import OAI.Combinatorics.EditApproximation.Binary.BinaryLocalGuardWork +import OAI.Combinatorics.EditApproximation.Binary.BinaryWideChildWork +import OAI.Combinatorics.EditApproximation.Geometry.InitialInputBudget + +namespace OAI + +/-! Complete bit work of the query-local scale and center loops. The +one-dimensional grid size follows from the tested scale inequality. -/ + +namespace EditApproximation +namespace BinaryFraction + +def queryExponentsBitBudget (B : ℕ) : ℕ := + (B + 1) * (localEligibilityBitBudget (B + 4) + B + 5) + 2 * B + 3 + +theorem queryExponentsWithWork_bounds (N F B : ℕ) (a w : BinaryFraction) + (hB : 7 ≤ B) (hN : Nat.size N ≤ B) (hF : Nat.size F + 2 ≤ B) + (ha : a.width ≤ B) (hw : w.width ≤ B) : + (queryExponentsWithWork N F a w).2 ≤ queryExponentsBitBudget B ∧ + (queryExponentsWithWork N F a w).1.length ≤ B + 1 := by + let count := max 1 N.bits.length + have hc : count ≤ B + 1 := by + dsimp only [count] + rw [Nat.size_eq_bits_len] + omega + have hcost := filterWithWork_cost (fun e => + let guard := refinementScaleGuardWithWork F (2 ^ e) a w + (guard.1, guard.2 + e + 2)) (List.range count) + (localEligibilityBitBudget (B + 4) + B + 2) (by + intro e he + have he' := List.mem_range.mp he + have hpow : Nat.size (2 ^ e) + 2 ≤ B + 4 := by + rw [Nat.size_pow] + omega + have h := refinementScaleGuardWithWork_cost F (2 ^ e) (B + 4) a w + (by omega) hpow (by omega) (by omega) (by omega) + change (refinementScaleGuardWithWork F (2 ^ e) a w).2 + e + 2 ≤ _ + omega) + simp only [List.length_range] at hcost + have hlen : (filterWithWork (fun e => + let guard := refinementScaleGuardWithWork F (2 ^ e) a w + (guard.1, guard.2 + e + 2)) (List.range count)).1.length ≤ count := by + rw [filterWithWork_value] + exact (List.length_filter_le _ _).trans_eq (List.length_range) + constructor + · have hcost' := hcost.trans (Nat.mul_le_mul_right _ hc) + change (filterWithWork (fun e => ((refinementScaleGuardWithWork F (2 ^ e) a w).1, + (refinementScaleGuardWithWork F (2 ^ e) a w).2 + e + 2)) (List.range count)).2 + + count + N.bits.length + 2 ≤ _ + simp only [Nat.add_assoc, Nat.reduceAdd] at hcost' + unfold queryExponentsBitBudget + rw [Nat.size_eq_bits_len] + simp only [Nat.add_assoc] at hcost' ⊢ + omega + · exact hlen.trans hc + +private theorem query_grid_count (P b radius F : ℕ) (hP : 0 < P) + (hr : radius ≤ 16 * F * b) : + 2 * radius / seedGridSpacing b P + 2 ≤ 64 * F * P + 2 := by + have hg : 0 < seedGridSpacing b P := by unfold seedGridSpacing; omega + have hq : b / P ≤ seedGridSpacing b P := le_max_right _ _ + have hdiv := Nat.lt_mul_div_succ b hP + have hb : b ≤ 2 * P * seedGridSpacing b P := by nlinarith only [hq, hdiv, hg] + have hnum : 2 * radius ≤ 64 * F * P * seedGridSpacing b P := by + nlinarith only [hr, Nat.mul_le_mul_left (32 * F) hb] + have hfloor := Nat.div_mul_le_self (2 * radius) (seedGridSpacing b P) + nlinarith only [hfloor, hnum, hg] + +def localRepresentativeScaleBitBudget (P F B : ℕ) : ℕ := + let C := B + 4 + let L := 64 * F * P + 2 + 100 * (C + 2) ^ 2 + gridStateBoxBitBudget L C + + L ^ 2 * (localEligibilityBitBudget C + 3) + L ^ 2 * 4 + B + 6 + +def localRepresentativesBitBudget (P F B : ℕ) : ℕ := + queryExponentsBitBudget B + 500 * (B + 1) ^ 2 + + (B + 1) * (localRepresentativeScaleBitBudget P F B + (64 * F * P + 2) ^ 2 + 3) + 3 + +theorem localRepresentativesWithWork_cost {n : ℕ} (N P F B : ℕ) (a : BinaryFraction) + (initial : TargetInterval n → BinaryFraction) (query : TargetInterval n) + (hB : 7 ≤ B) (hN : Nat.size N ≤ B) (hF : Nat.size F + 2 ≤ B) + (hFpos : 1 ≤ F) (hPbits : Nat.size P ≤ B) (hP : 0 < P) (hn : Nat.size n ≤ B) + (ha : a.width ≤ B) (hi : ∀ r, (initial r).width ≤ B) : + (localRepresentativesWithWork N P F a initial query).2 ≤ localRepresentativesBitBudget P F B := by + let scales := queryExponentsWithWork N F a (initial query) + let radius := naturalCeilingWithWork (initial query) + let C := B + 4 + let L := 64 * F * P + 2 + have hscales := queryExponentsWithWork_bounds N F B a (initial query) hB hN hF ha (hi query) + have hradius : Nat.size (bitWordValue radius.1) ≤ B + 2 := + (Nat.size_le.mpr (bitWordValue_lt_pow_length radius.1)).trans + ((naturalCeilingWithWork_length (initial query)).trans (by have hh := hi query; omega)) + have hradiusCost := (naturalCeilingWithWork_cost (initial query)).trans + (Nat.mul_le_mul_left 500 (Nat.pow_le_pow_left (Nat.add_le_add_right (hi query) 1) 2)) + let callback := fun e => + let b := 2 ^ e + let spacing := seedGridSpacingWithWork b P + let points := gridStateBoxWithWork n (bitWordValue spacing.1) (bitWordValue radius.1) query.lo query.hi + let selected := filterWithWork (fun r => centerEligibilityWithWork b F a (initial r)) points.1 + let labeled := arithmeticMapWithWork (fun r => ((b, r), 1)) selected.1 + (labeled.1, spacing.2 + points.2 + selected.2 + labeled.2 + e + 5) + have hcallback (e : ℕ) (he : e ∈ scales.1) : + (callback e).2 ≤ localRepresentativeScaleBitBudget P F B ∧ (callback e).1.length ≤ L ^ 2 := by + have hmem := he + change e ∈ (queryExponentsWithWork N F a (initial query)).1 at hmem + simp only [queryExponentsWithWork, filterWithWork_value] at hmem + obtain ⟨heRange, heGuard⟩ := List.mem_filter.mp hmem + have heBound : e ≤ B := by + have he' := List.mem_range.mp heRange + rw [Nat.size_eq_bits_len] at he' + omega + have hb : Nat.size (2 ^ e) + 2 ≤ C := by rw [Nat.size_pow]; dsimp only [C]; omega + have hspacing := seedGridSpacingWithWork_bounds (2 ^ e) P C (by omega) (by dsimp only [C]; omega) + have hgs : 0 < bitWordValue (seedGridSpacingWithWork (2 ^ e) P).1 := by + rw [seedGridSpacingWithWork_value _ _ hP] + unfold seedGridSpacing + omega + have hgsBits : Nat.size (bitWordValue (seedGridSpacingWithWork (2 ^ e) P).1) ≤ C := by + rw [seedGridSpacingWithWork_value _ _ hP] + have hdiv : Nat.size ((2 ^ e) / P) ≤ Nat.size (2 ^ e) := Nat.size_le_size (Nat.div_le_self _ _) + rw [seedGridSpacing] + rw [Nat.size_pow] at hdiv + have hmax : max 1 ((2 ^ e) / P) = 1 ∨ max 1 ((2 ^ e) / P) = (2 ^ e) / P := max_choice _ _ + rcases hmax with hh | hh + · rw [hh, Nat.size_one] + dsimp only [C] + omega + · rw [hh] + dsimp only [C] + omega + have hw := (refinementScaleGuardWithWork_value F (2 ^ e) a (initial query)).mp heGuard + have hceil : bitWordValue radius.1 ≤ 16 * F * 2 ^ e := by + rw [naturalCeilingWithWork_value] + apply Nat.ceil_le.mpr + have hden : (0 : ℚ) < 16 * F := by + have hpositive : (0 : ℚ) < F := by exact_mod_cast (show 0 < F by omega) + positivity + have hh := (div_le_iff₀ hden).mp hw.1 + calc + _ ≤ ((2 ^ e : ℕ) : ℚ) * (16 * (F : ℚ)) := hh + _ = ((16 * F * 2 ^ e : ℕ) : ℚ) := by push_cast; ring + have hcount : 2 * bitWordValue radius.1 / + bitWordValue (seedGridSpacingWithWork (2 ^ e) P).1 + 2 ≤ L := by + rw [seedGridSpacingWithWork_value _ _ hP] + exact query_grid_count P (2 ^ e) _ F hP hceil + let points := gridStateBoxWithWork n (bitWordValue (seedGridSpacingWithWork (2 ^ e) P).1) + (bitWordValue radius.1) query.lo query.hi + have hpCost := (gridStateBoxWithWork_cost n _ _ query.lo query.hi C hgs + (by dsimp only [C]; omega) hgsBits (by dsimp only [C]; omega) + ((Nat.size_le_size (query.ordered.trans query.valid)).trans (by dsimp only [C]; omega)) + ((Nat.size_le_size query.valid).trans (by dsimp only [C]; omega))).trans + (gridStateBoxBitBudget_mono_count _ _ C hcount) + have hpLen : points.1.length ≤ L ^ 2 := by + rw [gridStateBoxWithWork_value _ _ _ _ _ hgs] + exact (localTargetStates_length_le hgs query).trans (Nat.pow_le_pow_left hcount 2) + have hfilt := filterWithWork_cost + (fun r => centerEligibilityWithWork (2 ^ e) F a (initial r)) points.1 + (localEligibilityBitBudget C) (fun r _ => centerEligibilityWithWork_cost (2 ^ e) F C a (initial r) + (by dsimp only [C]; omega) hb (by dsimp only [C]; omega) (by dsimp only [C]; omega) + ((hi r).trans (by dsimp only [C]; omega))) + have hselected : (filterWithWork + (fun r => centerEligibilityWithWork (2 ^ e) F a (initial r)) points.1).1.length ≤ L ^ 2 := by + rw [filterWithWork_value] + exact (List.length_filter_le _ _).trans hpLen + have hlabel := arithmeticMapWithWork_cost (fun r : TargetInterval n => ((2 ^ e, r), 1)) + (filterWithWork (fun r => centerEligibilityWithWork (2 ^ e) F a (initial r)) points.1).1 1 + (fun _ _ => le_rfl) + have hfilt' := hfilt.trans (Nat.mul_le_mul_right _ hpLen) + have hlabel' := hlabel.trans (Nat.mul_le_mul_right _ hselected) + constructor + · change (seedGridSpacingWithWork (2 ^ e) P).2 + points.2 + + (filterWithWork (fun r => centerEligibilityWithWork (2 ^ e) F a (initial r)) points.1).2 + + (arithmeticMapWithWork (fun r => ((2 ^ e, r), 1)) + (filterWithWork (fun r => centerEligibilityWithWork (2 ^ e) F a (initial r)) points.1).1).2 + e + 5 ≤ _ + have hpc : points.2 ≤ gridStateBoxBitBudget L C := hpCost + unfold localRepresentativeScaleBitBudget + change _ ≤ 100 * (C + 2) ^ 2 + gridStateBoxBitBudget L C + + L ^ 2 * (localEligibilityBitBudget C + 3) + L ^ 2 * 4 + B + 6 + omega + · simpa only [callback, arithmeticMapWithWork_value, List.length_map] using hselected + have hflat := arithmeticFlatMapWithWork_cost callback scales.1 + (localRepresentativeScaleBitBudget P F B) (L ^ 2) + (fun e he => (hcallback e he).1) (fun e he => (hcallback e he).2) + have hflat' := hflat.trans (Nat.mul_le_mul_right _ hscales.2) + change scales.2 + radius.2 + (arithmeticFlatMapWithWork callback scales.1).2 + 3 ≤ _ + unfold localRepresentativesBitBudget + have hsc : scales.2 ≤ queryExponentsBitBudget B := hscales.1 + change radius.2 ≤ _ at hradiusCost + dsimp only [L] at hflat' + omega + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryLocalSourceKernel.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryLocalSourceKernel.lean new file mode 100644 index 0000000000000000000000000000000000000000..7de06bb390170eff6c3be60b6a96a06586426140 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryLocalSourceKernel.lean @@ -0,0 +1,63 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryLocalGroupSource +import OAI.Combinatorics.EditApproximation.Binary.BinaryLocalOnlineSource +import OAI.Combinatorics.EditApproximation.Binary.BinaryPreparedKernelReads + +namespace OAI + +/-! The full local continuation with both data reads and scalar source +reads charged. Its binary return word agrees with the refinement kernel. -/ + +namespace EditApproximation.BinaryFraction +section Kernel +variable {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (N P F exponent H Q eM eF : ℕ) + (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) + (tau a eta kappa delta : BinaryFraction) + (parentInitial : TargetInterval target.length → BinaryFraction × ℕ) + (childMass childInitial : Fin M → TargetInterval target.length → BinaryFraction × ℕ) + (old current : Fin M × TargetInterval target.length → BinaryFraction × ℕ) + (history : ℕ → Fin M × TargetInterval target.length → BinaryFraction × ℕ) + (R : ℕ) (hm : ∀ i q, (childMass i q).2 ≤ R) (hi : ∀ i q, (childInitial i q).2 ≤ R) + (t : ℕ) (draw : CellGroupReadDraws M F Q) + (integer : ℕ → TargetInterval target.length → ℕ × ℕ) + (query : TargetInterval target.length) + +def preparedLocalSourceKernelWithWork : BinaryFraction × ℕ := + let fallback := parentInitial query + let representatives := localRepresentativeReadWithWork N P F a parentInitial query + let groups := preparedLocalCellGroupsSourceWithWork source target parent P F exponent Q eM eF + hM hF hP tau a parentInitial childMass childInitial (fun i r => current (i, r)) R hm hi N draw query + let online := preparedLocalOnlineActionsSourceWithWork source target parent P F exponent H hP tau a eta kappa + parentInitial childMass childInitial history R hm hi t integer N query + let result := physicalContinuationReadWithWork parent representatives.1 P F delta fallback.1 + old current groups.1 online.1 query + (result.1, fallback.2 + representatives.2 + groups.2 + online.2 + result.2 + 4) + +theorem preparedLocalSourceKernelWithWork_eq_cost (S : ℕ) + (hd : ∀ b cell s i, (draw b cell s i).2 ≤ S) (hs : ∀ b q, (integer b q).2 ≤ S) : + (preparedLocalSourceKernelWithWork source target parent N P F exponent H Q eM eF hP hM hF + tau a eta kappa delta parentInitial childMass childInitial old current history R hm hi t + draw integer query).1 = + (preparedLocalKernelReadWithWork source target parent N P F exponent H Q eM eF hP hM hF + tau a eta kappa delta parentInitial childMass childInitial old current history R hm hi t + (fun b cell s i => (draw b cell s i).1) (fun b q => (integer b q).1) query).1 ∧ + (preparedLocalSourceKernelWithWork source target parent N P F exponent H Q eM eF hP hM hF + tau a eta kappa delta parentInitial childMass childInitial old current history R hm hi t + draw integer query).2 ≤ + (preparedLocalKernelReadWithWork source target parent N P F exponent H Q eM eF hP hM hF + tau a eta kappa delta parentInitial childMass childInitial old current history R hm hi t + (fun b cell s i => (draw b cell s i).1) (fun b q => (integer b q).1) query).2 * (S + 4) := by + have hg := preparedLocalCellGroupsSourceWithWork_eq_cost source target parent P F exponent Q eM eF + hM hF hP tau a parentInitial childMass childInitial (fun i r => current (i, r)) R hm hi + N draw query S hd + have ho := preparedLocalOnlineActionsSourceWithWork_eq_cost source target parent P F exponent H hP + tau a eta kappa parentInitial childMass childInitial history R hm hi t integer N query S hs + unfold preparedLocalSourceKernelWithWork preparedLocalKernelReadWithWork + dsimp only + rw [hg.1, ho.1] + exact ⟨rfl, by nlinarith only [hg.2, ho.2]⟩ + +end Kernel +end EditApproximation.BinaryFraction + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryLocalSourceValues.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryLocalSourceValues.lean new file mode 100644 index 0000000000000000000000000000000000000000..217ce2a4f605fece70e9d20476d7ed0636a88ef4 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryLocalSourceValues.lean @@ -0,0 +1,123 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryLocalSourceKernel +import OAI.Combinatorics.EditApproximation.Binary.BinaryLocalReadValues + +namespace OAI + +/-! Exact local source-port values for arbitrary gathered answer lists. +No cost bound on unqueried coordinates enters these identities. -/ + +namespace EditApproximation + +private theorem sourceDraw_project_cast (M b Q : ℕ) (f g : ℚ) (h : f = g) + (draw : cellScaleReadDraw M b Q g) : + (fun t i => ((Eq.mpr (congrArg (cellScaleReadDraw M b Q) h) draw) t i).1) = + Eq.mpr (congrArg (BinaryFraction.cellScaleDraw M b Q) h) (fun t i => (draw t i).1) := by + cases h + rfl + +namespace BinaryFraction +section Group +variable {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (P F exponent Q eM eF : ℕ) + (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (hP : 0 < P) + (tau a : BinaryFraction) + (parentInitial : TargetInterval target.length → BinaryFraction × ℕ) + (child initial current : Fin M → TargetInterval target.length → BinaryFraction × ℕ) + (R : ℕ) (hc : ∀ i q, (child i q).2 ≤ R) (hi : ∀ i q, (initial i q).2 ≤ R) + +theorem preparedComputedCellSourceWithWork_value (b eb : ℕ) (hb : b = 2 ^ eb) + (draw : cellScaleReadDraw M b Q (nat F).value) (cell : ℕ × ℕ) : + (preparedComputedCellSourceWithWork source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial current R hc hi b eb hb draw cell).1 = + (preparedComputedCellReadWithWork source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial current R hc hi b eb hb (fun t i => (draw t i).1) cell).1 := by + have h := preparedCellGroupSourceWithWork_value source target parent b P F exponent Q + (by rw [hb]; exact Nat.two_pow_pos eb) hP tau a parentInitial child initial current R R hc hi + (groupScalesWithWork eM eb eF).1 (computedGroupScales_value M b F eM eb eF hM hb hF) draw cell + simpa only [preparedComputedCellSourceWithWork, preparedComputedCellReadWithWork] using h + +private theorem computedCellSource_cast_value (b eb : ℕ) (hb : b = 2 ^ eb) + (draw : cellScaleReadDraw M b Q F) (cell : ℕ × ℕ) : + (preparedComputedCellSourceWithWork source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial current R hc hi b eb hb + (Eq.mpr (congrArg (cellScaleReadDraw M b Q) (nat_value F)) draw) cell).1 = + (preparedComputedCellReadWithWork source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial current R hc hi b eb hb + (Eq.mpr (congrArg (cellScaleDraw M b Q) (nat_value F)) (fun t i => (draw t i).1)) cell).1 := by + have h := preparedComputedCellSourceWithWork_value source target parent P F exponent Q eM eF + hM hF hP tau a parentInitial child initial current R hc hi b eb hb + (Eq.mpr (congrArg (cellScaleReadDraw M b Q) (nat_value F)) draw) cell + rw [sourceDraw_project_cast M b Q _ _ (nat_value F) draw] at h + exact h + +theorem preparedLocalGroupScaleSourceWithWork_value (eb : ℕ) + (draw : CellGroupReadDraws M F Q) (query : TargetInterval target.length) : + (preparedLocalGroupScaleSourceWithWork source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial current R hc hi eb draw query).1 = + (preparedLocalGroupScaleReadWithWork source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial current R hc hi eb (fun b cell t i => (draw b cell t i).1) query).1 := by + simp only [preparedLocalGroupScaleSourceWithWork, preparedLocalGroupScaleReadWithWork, + filterMapWithWork_value] + apply List.filterMap_congr + intro cell _ + have h := computedCellSource_cast_value source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial current R hc hi (2 ^ eb) eb rfl (draw (2 ^ eb) cell) cell + simpa only using h + +theorem preparedLocalCellGroupsSourceWithWork_value (N : ℕ) + (draw : CellGroupReadDraws M F Q) (query : TargetInterval target.length) : + (preparedLocalCellGroupsSourceWithWork source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial current R hc hi N draw query).1 = + (preparedLocalCellGroupsReadWithWork source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial current R hc hi N (fun b cell t i => (draw b cell t i).1) query).1 := by + simp only [preparedLocalCellGroupsSourceWithWork, preparedLocalCellGroupsReadWithWork, + arithmeticFlatMapWithWork_value] + apply List.flatMap_congr + intro eb _ + split_ifs + · have h := preparedLocalGroupScaleSourceWithWork_value source target parent P F exponent Q eM eF + hM hF hP tau a parentInitial child initial current R hc hi eb draw query + simpa only using h + · rfl + +theorem preparedLocalCellGroupsSourceWithWork_semantic_value (N : ℕ) + (draw : CellGroupReadDraws M F Q) (query : TargetInterval target.length) : + (preparedLocalCellGroupsSourceWithWork source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial current R hc hi N draw query).1 = + (preparedLocalCellGroupsWithWork source target parent N P F exponent Q eM eF hM hF hP tau a + (fun r => (parentInitial r).1) (fun i r => (child i r).1) + (fun i r => (initial i r).1) (fun i r => (current i r).1) + (fun b cell t i => (draw b cell t i).1) query).1 := + (preparedLocalCellGroupsSourceWithWork_value source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial current R hc hi N draw query).trans + (preparedLocalCellGroupsReadWithWork_value_only source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial current R hc hi N (fun b cell t i => (draw b cell t i).1) query) +end Group + +section Online +variable {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (P F exponent H : ℕ) (hP : 0 < P) + (tau a eta kappa : BinaryFraction) + (parentInitial : TargetInterval target.length → BinaryFraction × ℕ) + (child initial : Fin M → TargetInterval target.length → BinaryFraction × ℕ) + (table : ℕ → Fin M × TargetInterval target.length → BinaryFraction × ℕ) + (R : ℕ) (hc : ∀ i q, (child i q).2 ≤ R) (hi : ∀ i q, (initial i q).2 ≤ R) + (t : ℕ) (integer : ℕ → TargetInterval target.length → ℕ × ℕ) + +theorem preparedLocalOnlineActionsSourceWithWork_semantic_value (N : ℕ) + (query : TargetInterval target.length) : + (preparedLocalOnlineActionsSourceWithWork source target parent P F exponent H hP tau a eta kappa + parentInitial child initial table R hc hi t integer N query).1 = + (preparedLocalOnlineActionsWithWork source target parent N P F exponent H hP tau a eta kappa + (fun r => (parentInitial r).1) (fun i q => (child i q).1) (fun i q => (initial i q).1) + (fun s i => (table s i).1) t (fun b q => (integer b q).1) query).1 := + (preparedLocalOnlineActionsSourceWithWork_value source target parent P F exponent H hP tau a eta kappa + parentInitial child initial table R hc hi t integer N query).trans + (preparedLocalOnlineActionsReadWithWork_value_only source target parent P F exponent H hP tau a eta kappa + parentInitial child initial table R hc hi t (fun b q => (integer b q).1) N query) +end Online + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryLocalWarmupKernel.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryLocalWarmupKernel.lean new file mode 100644 index 0000000000000000000000000000000000000000..525933f077d1256929c872e2f7fe14916402fa8c --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryLocalWarmupKernel.lean @@ -0,0 +1,39 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryRefinementLists +import OAI.Combinatorics.EditApproximation.Binary.BinaryPhysicalContinuation + +namespace OAI + +/-! The nonterminal warmup step uses the same local representative grids, +but computes a single Bellman minimum and performs no online update. -/ + +namespace EditApproximation +namespace BinaryFraction + +def localWarmupKernelWithWork {nx ny M : ℕ} (parent : TargetInterval nx) + (N P F : ℕ) (a : BinaryFraction) (initial : TargetInterval ny → BinaryFraction) + (child : Fin M × TargetInterval ny → BinaryFraction) (query : TargetInterval ny) : + BinaryFraction × ℕ := + let representatives := localRepresentativesWithWork N P F a initial query + let actions := wideActionsFromRepresentativesWithWork M parent representatives.1 P + let L := canonicalMulWithWork (nat 128) (nat F) + let result := bellmanWithWork endpointDistanceWithWork L.1 (initial query) child query actions.1 + (result.1, representatives.2 + actions.2 + L.2 + result.2 + 3) + +theorem localWarmupKernelWithWork_value {nx ny M : ℕ} (parent : TargetInterval nx) + (N P F : ℕ) (hP : 0 < P) (a : BinaryFraction) (initial : TargetInterval ny → BinaryFraction) + (child : Fin M × TargetInterval ny → BinaryFraction) (query : TargetInterval ny) : + (localWarmupKernelWithWork parent N P F a initial child query).1.value = + rationalBellman (fun q => (initial q).value) (fun p q => (targetEndpointDistance p q : ℚ)) (128 * F) + (rationalActualWideActions parent + (localRefinementRepresentatives N P F a.value (fun q => (initial q).value) query) P) + (fun is => (child is).value) query := by + simp only [localWarmupKernelWithWork, bellmanWithWork_value, + wideActionsFromRepresentativesWithWork_decode _ _ _ _ hP, + localRepresentativesWithWork_value _ _ _ hP, canonicalMulWithWork_value, + nat_value, endpointDistanceWithWork_value] + rfl + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryLocalWarmupWork.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryLocalWarmupWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..6038480273b87d0295128c9774451a87f76a6f8d --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryLocalWarmupWork.lean @@ -0,0 +1,137 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryPhysicalContinuationWork +import OAI.Combinatorics.EditApproximation.Binary.BinaryPreparedListBounds + +namespace OAI + +/-! The warmup branch constructs its actual local representative/action +lists and evaluates their finite Bellman minimum with counted arithmetic. -/ + +namespace EditApproximation +namespace BinaryFraction + +def localWarmupWordBudget (M B : ℕ) : ℕ := + let W := physicalContinuationInputBudget M (B + 4) + W + bellmanActionWordBudget M W + +def localWarmupBitBudget (M P F B : ℕ) : ℕ := + let nr := (B + 1) * (64 * F * P + 2) ^ 2 + let W := physicalContinuationInputBudget M (B + 4) + localRepresentativesBitBudget P F B + wideActionsBitBudget M P nr (B + 4) + + 2000 * (B + 5) ^ 2 + bellmanBitBudget M (nr * (40 * P + 2) ^ (2 * M)) W W + (endpointDistanceBitBudget (B + 4)) + 3 + +private theorem wideWork_mono (M P n m B : ℕ) (h : n ≤ m) : + wideActionsBitBudget M P n B ≤ wideActionsBitBudget M P m B := by + unfold wideActionsBitBudget + dsimp only + exact Nat.mul_le_mul_right _ h + +private theorem bellmanWork_mono (M n m B F C : ℕ) (h : n ≤ m) : + bellmanBitBudget M n B F C ≤ bellmanBitBudget M m B F C := by + unfold bellmanBitBudget + gcongr + +private theorem endpointDistance_uniform {n : ℕ} (q r : TargetInterval n) (B : ℕ) + (hn : Nat.size n + 2 ≤ B) : + (endpointDistanceWithWork q r).1.width ≤ endpointDistanceWordBudget B ∧ + (endpointDistanceWithWork q r).2 ≤ endpointDistanceBitBudget B := + endpointDistanceWithWork_bounds q r B + ((Nat.add_le_add_right (Nat.size_le_size (q.ordered.trans q.valid)) 2).trans hn) + ((Nat.add_le_add_right (Nat.size_le_size q.valid) 2).trans hn) + ((Nat.add_le_add_right (Nat.size_le_size (r.ordered.trans r.valid)) 2).trans hn) + ((Nat.add_le_add_right (Nat.size_le_size r.valid) 2).trans hn) + +private theorem warmupCoefficient_bounds (F B : ℕ) (hB : 10 ≤ B) + (hF : Nat.size F + 2 ≤ B) : + (canonicalMulWithWork (nat 128) (nat F)).1.width ≤ 4 * (B + 4) + 2 ∧ + (canonicalMulWithWork (nat 128) (nat F)).2 ≤ 2000 * (B + 5) ^ 2 := by + have h128 : (nat 128).width ≤ B + 4 := + (nat_width_le 128).trans (by change 10 ≤ B + 4; omega) + have hFw : (nat F).width ≤ B + 4 := (nat_width_le F).trans (by omega) + exact ⟨canonicalMulWithWork_width _ _ (B + 4) h128 hFw, + canonicalMulWithWork_cost _ _ (B + 4) h128 hFw⟩ + +private theorem warmupBellman_bounds {ny M : ℕ} (F B : ℕ) + (initial : TargetInterval ny → BinaryFraction) + (child : Fin M × TargetInterval ny → BinaryFraction) (query : TargetInterval ny) + (actions : List (BinaryBellmanAction (TargetInterval ny) (Fin M × TargetInterval ny) M)) + (hB : 10 ≤ B) (hny : Nat.size ny + 2 ≤ B) (hF : Nat.size F + 2 ≤ B) + (hi : ∀ r, (initial r).width ≤ B) (hc : ∀ s, (child s).width ≤ B) + (hconn : ∀ action ∈ actions, action.connection.width ≤ connectionWordBudget M (B + 4)) : + (bellmanWithWork endpointDistanceWithWork (canonicalMulWithWork (nat 128) (nat F)).1 + (initial query) child query actions).1.width ≤ localWarmupWordBudget M B ∧ + (bellmanWithWork endpointDistanceWithWork (canonicalMulWithWork (nat 128) (nat F)).1 + (initial query) child query actions).2 ≤ bellmanBitBudget M actions.length + (physicalContinuationInputBudget M (B + 4)) (physicalContinuationInputBudget M (B + 4)) + (endpointDistanceBitBudget (B + 4)) := by + let W := physicalContinuationInputBudget M (B + 4) + have hBW : B ≤ W := by dsimp only [W, physicalContinuationInputBudget]; omega + have hL := (warmupCoefficient_bounds F B hB hF).1 + have hWcoefficient : 4 * (B + 4) + 2 ≤ W := by + dsimp only [W, physicalContinuationInputBudget]; omega + exact bellmanWithWork_bounds endpointDistanceWithWork _ (initial query) child query actions W W + (endpointDistanceBitBudget (B + 4)) (hL.trans hWcoefficient) ((hi query).trans hBW) + (fun action _ => (endpointDistance_uniform query action.center (B + 4) (by omega)).1.trans + (by dsimp only [W, physicalContinuationInputBudget]; omega)) + (fun action _ => (endpointDistance_uniform query action.center (B + 4) (by omega)).2) + (fun action ha => (hconn action ha).trans (by dsimp only [W, physicalContinuationInputBudget]; omega)) + (fun action _ i => (hc _).trans hBW) + +private theorem warmupWide_bounds {nx ny M : ℕ} (parent : TargetInterval nx) + (reps : List (ℕ × TargetInterval ny)) (P F B : ℕ) (hP : 0 < P) + (initial : TargetInterval ny → BinaryFraction) + (child : Fin M × TargetInterval ny → BinaryFraction) (query : TargetInterval ny) + (hB : 10 ≤ B) (hnx : Nat.size nx + 2 ≤ B) (hny : Nat.size ny + 2 ≤ B) + (hM : Nat.size M ≤ B) (hPbits : Nat.size P ≤ B) (hF : Nat.size F + 2 ≤ B) + (hrep : ∀ br ∈ reps, Nat.size br.1 ≤ B + 4) + (hi : ∀ r, (initial r).width ≤ B) (hc : ∀ s, (child s).width ≤ B) : + (bellmanWithWork endpointDistanceWithWork (canonicalMulWithWork (nat 128) (nat F)).1 + (initial query) child query (wideActionsFromRepresentativesWithWork M parent reps P).1).1.width ≤ + localWarmupWordBudget M B ∧ + (wideActionsFromRepresentativesWithWork M parent reps P).2 + + (canonicalMulWithWork (nat 128) (nat F)).2 + + (bellmanWithWork endpointDistanceWithWork (canonicalMulWithWork (nat 128) (nat F)).1 + (initial query) child query (wideActionsFromRepresentativesWithWork M parent reps P).1).2 ≤ + wideActionsBitBudget M P reps.length (B + 4) + 2000 * (B + 5) ^ 2 + + bellmanBitBudget M (reps.length * (40 * P + 2) ^ (2 * M)) + (physicalContinuationInputBudget M (B + 4)) (physicalContinuationInputBudget M (B + 4)) + (endpointDistanceBitBudget (B + 4)) := by + have hw := wideActionsFromRepresentativesWithWork_bounds (M := M) parent reps P (B + 4) hP + (by omega) (by omega) (by omega) (by omega) hrep + have hb := warmupBellman_bounds F B initial child query _ hB hny hF hi hc hw.2.1 + have hbc := hb.2.trans (bellmanWork_mono M _ _ _ _ _ hw.1) + exact ⟨hb.1, Nat.add_le_add (Nat.add_le_add hw.2.2 (warmupCoefficient_bounds F B hB hF).2) hbc⟩ + +attribute [local irreducible] localRepresentativesWithWork wideActionsFromRepresentativesWithWork + +theorem localWarmupKernelWithWork_bounds {nx ny M : ℕ} (parent : TargetInterval nx) + (N P F B : ℕ) (hP : 0 < P) (hFpos : 1 ≤ F) (a : BinaryFraction) + (initial : TargetInterval ny → BinaryFraction) (child : Fin M × TargetInterval ny → BinaryFraction) + (query : TargetInterval ny) (hB : 10 ≤ B) (hN : Nat.size N ≤ B) + (hnx : Nat.size nx + 2 ≤ B) (hny : Nat.size ny + 2 ≤ B) + (hM : Nat.size M ≤ B) (hPbits : Nat.size P ≤ B) (hF : Nat.size F + 2 ≤ B) + (ha : a.width ≤ B) (hi : ∀ r, (initial r).width ≤ B) (hc : ∀ s, (child s).width ≤ B) : + (localWarmupKernelWithWork parent N P F a initial child query).1.width ≤ localWarmupWordBudget M B ∧ + (localWarmupKernelWithWork parent N P F a initial child query).2 ≤ localWarmupBitBudget M P F B := by + let reps := localRepresentativesWithWork N P F a initial query + have hr := localRepresentativesWithWork_cost N P F B a initial query (by omega) hN hF hFpos + hPbits hP (by omega) ha hi + have hrl := localRepresentativesWithWork_length_le N P F B hP hFpos a initial query hN + have htail := warmupWide_bounds parent reps.1 P F B hP initial child query hB hnx hny hM hPbits hF + (fun br hbr => (localRepresentativesWithWork_scale_bits N P F B hP a initial query hN br hbr).trans (by omega)) hi hc + have hwide := wideWork_mono M P _ ((B + 1) * (64 * F * P + 2) ^ 2) (B + 4) hrl + have hbellman := bellmanWork_mono M _ _ (physicalContinuationInputBudget M (B + 4)) + (physicalContinuationInputBudget M (B + 4)) (endpointDistanceBitBudget (B + 4)) + (Nat.mul_le_mul_right ((40 * P + 2) ^ (2 * M)) hrl) + refine ⟨htail.1, ?_⟩ + change reps.2 + _ + _ + _ + 3 ≤ _ + change reps.2 ≤ _ at hr + unfold localWarmupBitBudget + dsimp only + simp only [reps] at htail hwide hbellman hr ⊢ + omega + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryLogWork.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryLogWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..10bb1f19b6165f7d058b1e583e49bc876e770827 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryLogWork.lean @@ -0,0 +1,247 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryRawCost + +namespace OAI + +/-! Bit cost of the finite logarithm series on unreduced Boolean fractions. +Every bound is for the executed power/division/addition loops. -/ + +namespace EditApproximation +namespace BinaryFraction + +def logarithmPartialWordBudget (b : BinaryFraction) (K : ℕ) : ℕ := + b.width + + (Nat.size K + 2 * (K * K * Nat.size b.representation.den + + K * (Nat.size (2 * K + 1) + 1) + 1) + 1) + + (2 * ((2 * K + 1) * Nat.size b.representation.den + 1) + 2) + + Nat.size (2 * K + 1) + 10 + +theorem logarithmPartialWordBudget_input (b : BinaryFraction) (K : ℕ) : + b.width ≤ logarithmPartialWordBudget b K := by + unfold logarithmPartialWordBudget + omega + +theorem logarithmPartialWordBudget_power (b : BinaryFraction) (K j : ℕ) + (hj : j ≤ 2 * K + 1) (hb : |b.value| ≤ 1) : + (b.powWithWork j).1.width ≤ logarithmPartialWordBudget b K := by + have h := powWithWork_width_abs_le_one b j hb + have hm := Nat.mul_le_mul_right (Nat.size b.representation.den) hj + unfold logarithmPartialWordBudget + omega + +theorem logarithmPartialWordBudget_partial (b : BinaryFraction) (K j : ℕ) + (hj : j ≤ K) (hb : |b.value| ≤ 1) : + (b.logarithmPartialWithWork j).1.width ≤ logarithmPartialWordBudget b K := by + have hw := logarithmPartialWithWork_width_le_storageBits b j + rw [logarithmPartialWithWork_representation] at hw + have hs := UnreducedRational.logarithmPartial_storageBits_uniform b.representation j K hj hb + unfold logarithmPartialWordBudget + omega + +theorem logarithmPartialWordBudget_nat (b : BinaryFraction) (K j : ℕ) (hj : j ≤ K) : + (nat (2 * j + 1)).width ≤ logarithmPartialWordBudget b K := by + have hw := nat_width_le_storageBits (2 * j + 1) + rw [nat_representation, UnreducedRational.storageBits_nat] at hw + have hs := Nat.size_le_size (show 2 * j + 1 ≤ 2 * K + 1 by omega) + unfold logarithmPartialWordBudget + omega + +theorem divWithWork_self_width (a b : BinaryFraction) : + (a.divWithWork b).1.width ≤ (a.divWithWork b).1.representation.storageBits := + canonicalMulWithWork_self_width _ _ + +theorem logarithmPartialWordBudget_term (b : BinaryFraction) (K j : ℕ) + (hj : j ≤ K) (hb : |b.value| ≤ 1) : + ((b.powWithWork (2 * j + 1)).1.divWithWork (nat (2 * j + 1))).1.width ≤ + logarithmPartialWordBudget b K := by + have hw := divWithWork_self_width (b.powWithWork (2 * j + 1)).1 (nat (2 * j + 1)) + rw [divWithWork_representation, powWithWork_representation, nat_representation] at hw + have hs := UnreducedRational.storageBits_div (b.representation.pow (2 * j + 1)) + (UnreducedRational.nat (2 * j + 1)) + rw [UnreducedRational.storageBits_nat] at hs + have hp := UnreducedRational.pow_storageBits_abs_le_one b.representation (2 * j + 1) hb + have hm := Nat.mul_le_mul_right (Nat.size b.representation.den) + (show 2 * j + 1 ≤ 2 * K + 1 by omega) + have hn := Nat.size_le_size (show 2 * j + 1 ≤ 2 * K + 1 by omega) + unfold logarithmPartialWordBudget + omega + +def logarithmPartialBitStep (W K : ℕ) : ℕ := + (2 * K + 1) * (2000 * (W + 1) ^ 2 + 1) + + 2100 * (W + 2) ^ 2 + 6000 * (W + 1) ^ 2 + Nat.size (2 * K + 1) + 6 + +theorem logarithmPartialWithWork_cost_le (b : BinaryFraction) (K j : ℕ) + (hj : j ≤ K) (hb : |b.value| ≤ 1) : + (b.logarithmPartialWithWork j).2 ≤ + 1 + j * logarithmPartialBitStep (logarithmPartialWordBudget b K) K := by + induction j with + | zero => simp [logarithmPartialWithWork] + | succ j ih => + let W := logarithmPartialWordBudget b K + have hp := ih (by omega) + have hpower := powWithWork_cost_of_width b (2 * j + 1) W + (logarithmPartialWordBudget_input b K) (by + intro m hm + exact logarithmPartialWordBudget_power b K m (by omega) hb) + have hpower' : (b.powWithWork (2 * j + 1)).2 ≤ + 1 + (2 * K + 1) * (2000 * (W + 1) ^ 2 + 1) := by + have hm := Nat.mul_le_mul_right (2000 * (W + 1) ^ 2 + 1) + (show 2 * j + 1 ≤ 2 * K + 1 by omega) + omega + have hdiv := divWithWork_cost (b.powWithWork (2 * j + 1)).1 (nat (2 * j + 1)) W + (logarithmPartialWordBudget_power b K (2 * j + 1) (by omega) hb) + (logarithmPartialWordBudget_nat b K j (by omega)) + have hadd := canonicalAddWithWork_cost (b.logarithmPartialWithWork j).1 + ((b.powWithWork (2 * j + 1)).1.divWithWork (nat (2 * j + 1))).1 W + (logarithmPartialWordBudget_partial b K j (by omega) hb) + (logarithmPartialWordBudget_term b K j (by omega) hb) + have hn := Nat.size_le_size (show 2 * j + 1 ≤ 2 * K + 1 by omega) + change (b.logarithmPartialWithWork j).2 + (b.powWithWork (2 * j + 1)).2 + + ((b.powWithWork (2 * j + 1)).1.divWithWork (nat (2 * j + 1))).2 + + (canonicalAddWithWork (b.logarithmPartialWithWork j).1 + ((b.powWithWork (2 * j + 1)).1.divWithWork (nat (2 * j + 1))).1).2 + + Nat.size (2 * j + 1) + 5 ≤ _ + change (b.logarithmPartialWithWork j).2 ≤ 1 + j * logarithmPartialBitStep W K at hp + change _ ≤ 1 + (j + 1) * logarithmPartialBitStep W K + unfold logarithmPartialBitStep at hp ⊢ + nlinarith only [hp, hpower', hdiv, hadd, hn] + +theorem logarithmPartialWithWork_cost (b : BinaryFraction) (K : ℕ) (hb : |b.value| ≤ 1) : + (b.logarithmPartialWithWork K).2 ≤ + 1 + K * logarithmPartialBitStep (logarithmPartialWordBudget b K) K := + logarithmPartialWithWork_cost_le b K K le_rfl hb + +theorem logarithmRatio_abs_le_one (r : BinaryFraction) (hr : 0 ≤ r.value) : + |((r.subWithWork one).1.divWithWork (canonicalAddWithWork r one).1).1.value| ≤ 1 := by + rw [← representation_value, divWithWork_representation, subWithWork_representation, + canonicalAddWithWork_representation, one_representation] + simp only [UnreducedRational.value_div, UnreducedRational.value_sub, + UnreducedRational.value_add, UnreducedRational.value_one, representation_value] + have hd : 0 < r.value + 1 := by linarith + rw [abs_div, abs_of_pos hd] + exact (div_le_one₀ hd).mpr (abs_le.mpr ⟨by linarith, by linarith⟩) + +def logarithmUniversalWordBudget (B K : ℕ) : ℕ := + B + (Nat.size K + 2 * (K * K * B + K * (Nat.size (2 * K + 1) + 1) + 1) + 1) + + (2 * ((2 * K + 1) * B + 1) + 2) + Nat.size (2 * K + 1) + 10 + +theorem logarithmPartialWordBudget_le (b : BinaryFraction) (B K : ℕ) (hw : b.width ≤ B) : + logarithmPartialWordBudget b K ≤ logarithmUniversalWordBudget B K := by + have hd := (representation_den_bits_le_width b).trans hw + have hquad := Nat.mul_le_mul_left (K * K) hd + have hlin := Nat.mul_le_mul_left (2 * K + 1) hd + unfold logarithmPartialWordBudget logarithmUniversalWordBudget + omega + +theorem logarithmPartialBitStep_mono {A B : ℕ} (h : A ≤ B) (K : ℕ) : + logarithmPartialBitStep A K ≤ logarithmPartialBitStep B K := by + have h1 := Nat.mul_self_le_mul_self (show A + 1 ≤ B + 1 by omega) + have h2 := Nat.mul_self_le_mul_self (show A + 2 ≤ B + 2 by omega) + simp only [← pow_two] at h1 h2 + have hm := Nat.mul_le_mul_left (2 * K + 1) + (show 2000 * (A + 1) ^ 2 + 1 ≤ 2000 * (B + 1) ^ 2 + 1 by omega) + unfold logarithmPartialBitStep + omega + +def logarithmRatio (r : BinaryFraction) : BinaryFraction := + ((r.subWithWork one).1.divWithWork (canonicalAddWithWork r one).1).1 + +theorem logarithmRatio_width (r : BinaryFraction) : (logarithmRatio r).width ≤ 8 * r.width + 22 := by + have hw := divWithWork_self_width (r.subWithWork one).1 (canonicalAddWithWork r one).1 + rw [divWithWork_representation, subWithWork_representation, canonicalAddWithWork_representation, + one_representation] at hw + have hs := UnreducedRational.logarithmRatio_storageBits r.representation + have hr := representation_storageBits_le r + change (logarithmRatio r).width ≤ _ at hw + omega + +theorem one_width : one.width ≤ 3 := by decide + +theorem sub_one_width (r : BinaryFraction) : (r.subWithWork one).1.width ≤ 4 * r.width + 10 := by + have hw := canonicalAddWithWork_self_width r one.neg + change (r.subWithWork one).1.width ≤ (r.subWithWork one).1.representation.storageBits at hw + rw [subWithWork_representation, one_representation] at hw + have hs := UnreducedRational.storageBits_sub r.representation UnreducedRational.one + rw [UnreducedRational.storageBits_one] at hs + have hr := representation_storageBits_le r + omega + +theorem add_one_width (r : BinaryFraction) : (canonicalAddWithWork r one).1.width ≤ 4 * r.width + 10 := by + have hw := canonicalAddWithWork_width_le_storageBits r one + rw [one_representation] at hw + have hs := UnreducedRational.storageBits_add r.representation UnreducedRational.one + rw [UnreducedRational.storageBits_one] at hs + have hr := representation_storageBits_le r + omega + +def logarithmBitBudget (B K : ℕ) : ℕ := + let W := logarithmUniversalWordBudget (8 * B + 22) K + 12000 * (B + 4) ^ 2 + 2100 * (4 * B + 12) ^ 2 + + K * logarithmPartialBitStep W K + 2000 * (W + 5) ^ 2 + 10 + +theorem logarithmWithWork_cost (r : BinaryFraction) (K : ℕ) (hr : 0 ≤ r.value) : + (r.logarithmWithWork K).2 ≤ logarithmBitBudget r.width K := by + let b := logarithmRatio r + let W := logarithmUniversalWordBudget (8 * r.width + 22) K + have hb : |b.value| ≤ 1 := logarithmRatio_abs_le_one r hr + have hW : logarithmPartialWordBudget b K ≤ W := + logarithmPartialWordBudget_le b (8 * r.width + 22) K (logarithmRatio_width r) + have hsub := subWithWork_cost r one (r.width + 3) (by omega) (by have h := one_width; omega) + have hadd := canonicalAddWithWork_cost r one (r.width + 3) (by omega) (by have h := one_width; omega) + have hdiv := divWithWork_cost (r.subWithWork one).1 (canonicalAddWithWork r one).1 + (4 * r.width + 10) (sub_one_width r) (add_one_width r) + have hpartial := logarithmPartialWithWork_cost b K hb + have hstep := Nat.mul_le_mul_left K (logarithmPartialBitStep_mono hW K) + have hpartial' : (b.logarithmPartialWithWork K).2 ≤ 1 + K * logarithmPartialBitStep W K := by omega + have hpwidth := (logarithmPartialWordBudget_partial b K K le_rfl hb).trans hW + have htwo : (nat 2).width ≤ 4 := by decide + have hmul := canonicalMulWithWork_cost (nat 2) (b.logarithmPartialWithWork K).1 + (W + 4) (by omega) (by omega) + change (r.subWithWork one).2 + (canonicalAddWithWork r one).2 + + ((r.subWithWork one).1.divWithWork (canonicalAddWithWork r one).1).2 + + (b.logarithmPartialWithWork K).2 + + (canonicalMulWithWork (nat 2) (b.logarithmPartialWithWork K).1).2 + 5 ≤ _ + change _ ≤ 12000 * (r.width + 4) ^ 2 + 2100 * (4 * r.width + 12) ^ 2 + + K * logarithmPartialBitStep W K + 2000 * (W + 5) ^ 2 + 10 + nlinarith only [hsub, hadd, hdiv, hpartial', hmul] + +def generalPowerWordBudget (a : BinaryFraction) (n : ℕ) : ℕ := + a.width + 3 + n * (2 * a.width + 1) + +theorem powWithWork_cost_general (a : BinaryFraction) (n : ℕ) : + (a.powWithWork n).2 ≤ 1 + n * (2000 * (generalPowerWordBudget a n + 1) ^ 2 + 1) := by + apply powWithWork_cost_of_width + · unfold generalPowerWordBudget + omega + · intro j hj + have hw := powWithWork_width_le_storageBits a j + rw [powWithWork_representation] at hw + have hs := UnreducedRational.pow_storageBits a.representation j + have hi := representation_storageBits_le a + have hm := Nat.mul_le_mul hj.le hi + unfold generalPowerWordBudget + omega + +theorem logarithmUniversalWordBudget_mono {A B : ℕ} (h : A ≤ B) (K : ℕ) : + logarithmUniversalWordBudget A K ≤ logarithmUniversalWordBudget B K := by + have hquad := Nat.mul_le_mul_left (K * K) h + have hlin := Nat.mul_le_mul_left (2 * K + 1) h + unfold logarithmUniversalWordBudget + omega + +theorem logarithmBitBudget_mono {A B : ℕ} (h : A ≤ B) (K : ℕ) : + logarithmBitBudget A K ≤ logarithmBitBudget B K := by + have hw := logarithmUniversalWordBudget_mono (show 8 * A + 22 ≤ 8 * B + 22 by omega) K + have hs := Nat.mul_le_mul_left K (logarithmPartialBitStep_mono hw K) + have h1 := Nat.mul_self_le_mul_self (show A + 4 ≤ B + 4 by omega) + have h2 := Nat.mul_self_le_mul_self (show 4 * A + 12 ≤ 4 * B + 12 by omega) + have h3 := Nat.mul_self_le_mul_self (show logarithmUniversalWordBudget (8 * A + 22) K + 5 ≤ + logarithmUniversalWordBudget (8 * B + 22) K + 5 by omega) + simp only [← pow_two] at h1 h2 h3 + unfold logarithmBitBudget + dsimp only + omega + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryLoopSpace.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryLoopSpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..ca1a8caeccc1ac1063f2e6e55d136c2a68708951 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryLoopSpace.lean @@ -0,0 +1,109 @@ +import OAI.Combinatorics.EditApproximation.Numerics.ScalarControlSpace +import OAI.Combinatorics.EditApproximation.Binary.BinaryReadComposition +import OAI.Combinatorics.EditApproximation.Binary.BinaryLocalGrid +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Fresh result-spine cells and recursive call frames for the literal +finite loops used in local continuation arithmetic. Callback footprints +are accounted separately; list elements are retained by pointer. -/ + +namespace EditApproximation + + + +def arithmeticFlatMapInvocations {α β : Type*} (f : α → List β × ℕ) + (invocations : α → ℕ) : List α → ℕ + | [] => 1 + | x :: xs => invocations x + arithmeticFlatMapInvocations f invocations xs + 1 + +theorem arithmeticFlatMapAllocation_le_work {α β : Type*} (f : α → List β × ℕ) + (allocation : α → ℕ) (xs : List α) (h : ∀ x ∈ xs, allocation x ≤ (f x).2) : + arithmeticFlatMapAllocation f allocation xs ≤ (arithmeticFlatMapWithWork f xs).2 := by + induction xs with + | nil => rfl + | cons x xs ih => + have hx := h x List.mem_cons_self + have ht := ih (fun y hy => h y (List.mem_cons_of_mem _ hy)) + simp only [arithmeticFlatMapAllocation, arithmeticFlatMapWithWork] + omega + +theorem arithmeticFlatMapInvocations_le_work_add_one {α β : Type*} (f : α → List β × ℕ) + (invocations : α → ℕ) (xs : List α) (h : ∀ x ∈ xs, invocations x ≤ (f x).2) : + arithmeticFlatMapInvocations f invocations xs ≤ (arithmeticFlatMapWithWork f xs).2 + 1 := by + induction xs with + | nil => rfl + | cons x xs ih => + have hx := h x List.mem_cons_self + have ht := ih (fun y hy => h y (List.mem_cons_of_mem _ hy)) + simp only [arithmeticFlatMapInvocations, arithmeticFlatMapWithWork] + omega + + + +def filterInvocations {α : Type*} (invocations : α → ℕ) : List α → ℕ + | [] => 1 + | x :: xs => invocations x + filterInvocations invocations xs + 1 + +theorem filterAllocation_le_work {α : Type*} (test : α → Bool × ℕ) + (allocation : α → ℕ) (xs : List α) (h : ∀ x ∈ xs, allocation x ≤ (test x).2) : + filterAllocation test allocation xs ≤ (filterWithWork test xs).2 := by + induction xs with + | nil => rfl + | cons x xs ih => + have hx := h x List.mem_cons_self + have ht := ih (fun y hy => h y (List.mem_cons_of_mem _ hy)) + simp only [filterAllocation, filterWithWork] + split_ifs <;> omega + +theorem filterInvocations_le_work_add_one {α : Type*} (test : α → Bool × ℕ) + (invocations : α → ℕ) (xs : List α) (h : ∀ x ∈ xs, invocations x ≤ (test x).2) : + filterInvocations invocations xs ≤ (filterWithWork test xs).2 + 1 := by + induction xs with + | nil => rfl + | cons x xs ih => + have hx := h x List.mem_cons_self + have ht := ih (fun y hy => h y (List.mem_cons_of_mem _ hy)) + simp only [filterInvocations, filterWithWork] + omega + + + +theorem filterMapAllocation_le_work {α β : Type*} (f : α → Option β × ℕ) + (allocation : α → ℕ) (xs : List α) (h : ∀ x ∈ xs, allocation x ≤ (f x).2) : + filterMapAllocation f allocation xs ≤ (filterMapWithWork f xs).2 := by + induction xs with + | nil => rfl + | cons x xs ih => + have hx := h x List.mem_cons_self + have ht := ih (fun y hy => h y (List.mem_cons_of_mem _ hy)) + simp only [filterMapAllocation, filterMapWithWork] + cases he : (f x).1 <;> simp only [Option.isSome, Bool.false_eq_true, ↓reduceIte] <;> omega + +theorem filterMapInvocations_le_work_add_one {α β : Type*} (f : α → Option β × ℕ) + (invocations : α → ℕ) (xs : List α) (h : ∀ x ∈ xs, invocations x ≤ (f x).2) : + filterInvocations invocations xs ≤ (filterMapWithWork f xs).2 + 1 := by + induction xs with + | nil => rfl + | cons x xs ih => + have hx := h x List.mem_cons_self + have ht := ih (fun y hy => h y (List.mem_cons_of_mem _ hy)) + simp only [filterInvocations, filterMapWithWork] + omega + +theorem allInvocations_le_work_add_one {α : Type*} (test : α → Bool × ℕ) + (invocations : α → ℕ) (xs : List α) (h : ∀ x ∈ xs, invocations x ≤ (test x).2) : + filterInvocations invocations xs ≤ (allWithWork test xs).2 + 1 := by + induction xs with + | nil => rfl + | cons x xs ih => + have hx := h x List.mem_cons_self + have ht := ih (fun y hy => h y (List.mem_cons_of_mem _ hy)) + simp only [filterInvocations, allWithWork] + omega + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryMaximizerWork.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryMaximizerWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..b9463e824e65be23f85081cf2ec346786e1a7fcf --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryMaximizerWork.lean @@ -0,0 +1,78 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryGradientWork + +namespace OAI + +/-! Counted stored-score maximization for Boolean fraction coordinates. -/ + +namespace EditApproximation +namespace BinaryFraction + +open Finset + +theorem scoredArgmaxWithWork_score_width {α : Type*} (score : α → BinaryFraction × ℕ) + (values : List α) (W : ℕ) (hw : ∀ a ∈ values, (score a).1.width ≤ W) + (best : α × BinaryFraction) (hbest : (scoredArgmaxWithWork score values).1 = some best) : + best.2.width ≤ W := by + rw [scoredArgmaxWithWork_value] at hbest + cases h : values.argmax (fun a => (score a).1.value) with + | none => simp only [h, Option.map_none] at hbest; contradiction + | some a => + have ha : a ∈ values := List.argmax_mem (by rw [h]; simp) + simp only [h, Option.map_some, Option.some.injEq] at hbest + rw [← hbest] + exact hw a ha + +theorem scoredArgmaxWithWork_cost {α : Type*} (score : α → BinaryFraction × ℕ) + (values : List α) (C W : ℕ) (hc : ∀ a ∈ values, (score a).2 ≤ C) + (hw : ∀ a ∈ values, (score a).1.width ≤ W) : + (scoredArgmaxWithWork score values).2 ≤ values.length * (C + 1000 * (W + 1) ^ 2 + 2) := by + induction values with + | nil => simp [scoredArgmaxWithWork] + | cons a rest ih => + have ht := ih (fun b hb => hc b (List.mem_cons_of_mem _ hb)) + (fun b hb => hw b (List.mem_cons_of_mem _ hb)) + have ha := hc a List.mem_cons_self + have haw := hw a List.mem_cons_self + cases hbest : (scoredArgmaxWithWork score rest).1 with + | none => + simp only [scoredArgmaxWithWork, hbest, List.length_cons] + nlinarith only [ht, ha] + | some best => + have hbw := scoredArgmaxWithWork_score_width score rest W + (fun b hb => hw b (List.mem_cons_of_mem _ hb)) best hbest + have hcmp := ltWithWork_cost (score a).1 best.2 W haw hbw + simp only [scoredArgmaxWithWork, hbest, List.length_cons] + nlinarith only [ht, ha, hcmp] + +def maximizerWordBudget (d B V : ℕ) : ℕ := dotWordBudget d B V + +def maximizerBitBudget (d v B V : ℕ) : ℕ := + let W := maximizerWordBudget d B V + v * (1 + d * (100000 * (W + 1) ^ 2) + 1000 * (W + 1) ^ 2 + 2) + d + 1 + +theorem maximizerWithWork_cost {d : ℕ} (gradient : Vector BinaryFraction d) + (vertices : List (Vector BinaryFraction d)) (B V : ℕ) + (hgw : ∀ i, (gradient.get i).width ≤ B) + (hgv : ∀ i, |(gradient.get i).value| ≤ V) + (hvw : ∀ v ∈ vertices, ∀ i, (v.get i).width ≤ B) + (hvv : ∀ v ∈ vertices, ∀ i, |(v.get i).value| ≤ V) : + (maximizerWithWork gradient vertices).2 ≤ maximizerBitBudget d vertices.length B V := by + let W := maximizerWordBudget d B V + have hc : ∀ v ∈ vertices, (dotWithWork gradient v).2 ≤ 1 + d * (100000 * (W + 1) ^ 2) := by + intro v hv + simpa only [dotWithWork, W, maximizerWordBudget, List.length_finRange] using + dotListWithWork_cost_in gradient v (List.finRange d) d B V (by simp) + (fun i _ => hgw i) (fun i _ => hvw v hv i) (fun i _ => hgv i) (fun i _ => hvv v hv i) + have hw : ∀ v ∈ vertices, (dotWithWork gradient v).1.width ≤ W := by + intro v hv + exact dotListWithWork_width_in gradient v (List.finRange d) d B V (by simp) + (fun i _ => hgw i) (fun i _ => hvw v hv i) (fun i _ => hgv i) (fun i _ => hvv v hv i) + have h := scoredArgmaxWithWork_cost (dotWithWork gradient) vertices + (1 + d * (100000 * (W + 1) ^ 2)) W hc hw + change (scoredArgmaxWithWork (dotWithWork gradient) vertices).2 + d + 1 ≤ _ + exact Nat.add_le_add_right (Nat.add_le_add_right h d) 1 + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryMedianKernel.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryMedianKernel.lean new file mode 100644 index 0000000000000000000000000000000000000000..bcc5b096c7ef0b79da9506228a78691a4a8f75fc --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryMedianKernel.lean @@ -0,0 +1,248 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryGroupKernel +import OAI.Combinatorics.EditApproximation.Binary.BinaryCeilingWork +import OAI.Combinatorics.EditApproximation.Probability.Median +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Binary multiplication, natural ceiling, sorting and clamping for the +literal seed median. The stored words are sorted without decoding them. -/ + +namespace EditApproximation + +/-- Comparison of two stored nonnegative binary words. -/ + + +@[simp] theorem wordLEWithWork_value (a b : List Bool) : + (wordLEWithWork a b).1 = true ↔ bitWordValue a ≤ bitWordValue b := by + simp only [wordLEWithWork, Bool.not_eq_true', decide_eq_false_iff_not, + bitCompareWithWork_lt, not_lt] + +theorem wordLEWithWork_cost (a b : List Bool) : + (wordLEWithWork a b).2 ≤ 4 * (a.length + b.length) + 2 := by + have h := bitCompareWithWork_cost b a + change _ + 1 ≤ _ + omega + + + +@[simp] theorem wordMinWithWork_value (a b : List Bool) : + bitWordValue (wordMinWithWork a b).1 = min (bitWordValue a) (bitWordValue b) := by + unfold wordMinWithWork + dsimp only + split_ifs with h + · exact (min_eq_left ((wordLEWithWork_value a b).mp h)).symm + · exact (min_eq_right (le_of_not_ge (fun hle => h ((wordLEWithWork_value a b).mpr hle)))).symm + +theorem wordMinWithWork_length (a b : List Bool) : + (wordMinWithWork a b).1.length ≤ max a.length b.length := by + unfold wordMinWithWork + dsimp only + split_ifs <;> omega + + + +@[simp] theorem wordInsertWithWork_value (a : List Bool) (words : List (List Bool)) : + ((wordInsertWithWork a words).1.map bitWordValue) = + List.orderedInsert (· ≤ ·) (bitWordValue a) (words.map bitWordValue) := by + induction words with + | nil => rfl + | cons b rest ih => + unfold wordInsertWithWork + dsimp only + by_cases h : (wordLEWithWork a b).1 = true + · have hle := (wordLEWithWork_value a b).mp h + simp only [h, ↓reduceIte, List.map_cons, List.orderedInsert, hle] + · have hle : ¬ bitWordValue a ≤ bitWordValue b := fun hle => h ((wordLEWithWork_value a b).mpr hle) + simp only [h, Bool.false_eq_true, ↓reduceIte, List.map_cons, List.orderedInsert, hle, ih] + +theorem wordInsertWithWork_length (a : List Bool) (words : List (List Bool)) : + (wordInsertWithWork a words).1.length = words.length + 1 := by + have h := congrArg List.length (wordInsertWithWork_value a words) + simpa only [List.length_map, List.orderedInsert_length] using h + +theorem wordInsertWithWork_words (a : List Bool) (words : List (List Bool)) (B : ℕ) + (ha : a.length ≤ B) (hwords : ∀ b ∈ words, b.length ≤ B) : + ∀ b ∈ (wordInsertWithWork a words).1, b.length ≤ B := by + induction words with + | nil => + intro b hb + have heq : b = a := by simpa only [wordInsertWithWork, List.mem_singleton] using hb + exact heq ▸ ha + | cons b rest ih => + unfold wordInsertWithWork + dsimp only + split_ifs + · intro c hc + rcases List.mem_cons.mp hc with heq | hc + · exact heq ▸ ha + · exact hwords c hc + · intro c hc + rcases List.mem_cons.mp hc with heq | hc + · exact heq ▸ hwords b (by simp) + · exact ih (fun d hd => hwords d (by simp [hd])) c hc + +theorem wordInsertWithWork_cost (a : List Bool) (words : List (List Bool)) (B : ℕ) + (ha : a.length ≤ B) (hwords : ∀ b ∈ words, b.length ≤ B) : + (wordInsertWithWork a words).2 ≤ (words.length + 1) * (8 * B + 4) := by + induction words with + | nil => simp only [wordInsertWithWork, List.length_nil, zero_add, one_mul]; omega + | cons b rest ih => + have hb := hwords b (by simp) + have hcmp := wordLEWithWork_cost a b + have htail := ih (fun c hc => hwords c (by simp [hc])) + unfold wordInsertWithWork + dsimp only + simp only [List.length_cons] + rw [show rest.length + 1 + 1 = (rest.length + 1) + 1 by omega, Nat.add_mul, Nat.one_mul] + split_ifs <;> omega + + + +@[simp] theorem wordSortWithWork_value (words : List (List Bool)) : + ((wordSortWithWork words).1.map bitWordValue) = + List.insertionSort (· ≤ ·) (words.map bitWordValue) := by + induction words with + | nil => rfl + | cons a rest ih => + simp only [wordSortWithWork, wordInsertWithWork_value, ih, + List.map_cons, List.insertionSort_cons] + +theorem wordSortWithWork_length (words : List (List Bool)) : + (wordSortWithWork words).1.length = words.length := by + have h := congrArg List.length (wordSortWithWork_value words) + simpa only [List.length_map, List.length_insertionSort] using h + +theorem wordSortWithWork_words (words : List (List Bool)) (B : ℕ) + (hwords : ∀ b ∈ words, b.length ≤ B) : + ∀ b ∈ (wordSortWithWork words).1, b.length ≤ B := by + induction words with + | nil => simp only [wordSortWithWork, List.not_mem_nil, false_implies, implies_true] + | cons a rest ih => + exact wordInsertWithWork_words a (wordSortWithWork rest).1 B (hwords a (by simp)) + (ih (fun b hb => hwords b (by simp [hb]))) + +theorem wordSortWithWork_cost (words : List (List Bool)) (B : ℕ) + (hwords : ∀ b ∈ words, b.length ≤ B) : + (wordSortWithWork words).2 ≤ (words.length + 1) ^ 2 * (8 * B + 6) := by + induction words with + | nil => simp only [wordSortWithWork, List.length_nil, zero_add, one_pow, one_mul]; omega + | cons a rest ih => + have hr : ∀ b ∈ rest, b.length ≤ B := fun b hb => hwords b (by simp [hb]) + have ht := ih hr + have hi := wordInsertWithWork_cost a (wordSortWithWork rest).1 B (hwords a (by simp)) + (wordSortWithWork_words rest B hr) + rw [wordSortWithWork_length] at hi + change _ + _ + 2 ≤ _ + simp only [List.length_cons] + nlinarith only [ht, hi, Nat.zero_le rest.length, Nat.zero_le B] + +namespace BinaryFraction + +theorem naturalCeilingWithWork_length (a : BinaryFraction) : + (a.naturalCeilingWithWork).1.length ≤ a.width + 2 := by + have hn : a.numerator.bits.length ≤ a.width := le_max_left _ _ + have h := bitCeilDivWithWork_length a.denominator a.numerator.bits + unfold naturalCeilingWithWork + split_ifs + · change 0 ≤ a.width + 2 + omega + · change (bitCeilDivWithWork a.denominator a.numerator.bits).1.length ≤ a.width + 2 + omega + + + +@[simp] theorem scaledCeilingWithWork_value (multiplier : ℕ) (a : BinaryFraction) : + bitWordValue (scaledCeilingWithWork multiplier a).1 = ⌈(multiplier : ℚ) * a.value⌉₊ := by + simp only [scaledCeilingWithWork, naturalCeilingWithWork_value, + canonicalMulWithWork_value, nat_value] + +def scaledCeilingBitBudget (B : ℕ) : ℕ := + 2000 * (B + 1) ^ 2 + 500 * (4 * B + 3) ^ 2 + B + 3 + +theorem scaledCeilingWithWork_bounds (multiplier : ℕ) (a : BinaryFraction) (B : ℕ) + (hm : Nat.size multiplier + 2 ≤ B) (ha : a.width ≤ B) : + (scaledCeilingWithWork multiplier a).1.length ≤ 4 * B + 4 ∧ + (scaledCeilingWithWork multiplier a).2 ≤ scaledCeilingBitBudget B := by + have hm' : (nat multiplier).width ≤ B := (nat_width_le _).trans hm + have hpw := canonicalMulWithWork_width (nat multiplier) a B hm' ha + have hpc := canonicalMulWithWork_cost (nat multiplier) a B hm' ha + have hcw := naturalCeilingWithWork_length (canonicalMulWithWork (nat multiplier) a).1 + have hcc := naturalCeilingWithWork_cost (canonicalMulWithWork (nat multiplier) a).1 + have hs := Nat.pow_le_pow_left (show (canonicalMulWithWork (nat multiplier) a).1.width + 1 ≤ + 4 * B + 3 by omega) 2 + constructor + · change (naturalCeilingWithWork (canonicalMulWithWork (nat multiplier) a).1).1.length ≤ _ + omega + · change _ + _ + _ + 3 ≤ _ + unfold scaledCeilingBitBudget + omega + +/-- The exact clamped upper median on binary words, including every copy's +multiplication and ceiling, all sorting comparisons and the middle read. -/ + + +@[simp] theorem medianSeedWithWork_value (N multiplier : ℕ) (values : List BinaryFraction) : + bitWordValue (medianSeedWithWork N multiplier values).1 = + min N (upperMedian (values.map fun a => ⌈(multiplier : ℚ) * a.value⌉₊)) := by + unfold medianSeedWithWork + rw [wordMinWithWork_value, bitWordValue_bits] + congr 1 + rw [upperMedian, List.length_map, List.mergeSort_eq_insertionSort] + have hs := wordSortWithWork_value + (arithmeticMapWithWork (scaledCeilingWithWork multiplier) values).1 + rw [arithmeticMapWithWork_value, List.map_map] at hs + simp only [Function.comp_def, scaledCeilingWithWork_value] at hs + have hm := congrArg (fun words : List ℕ => words.getD (values.length / 2) 0) hs + change ((wordSortWithWork (values.map (fun a => (scaledCeilingWithWork multiplier a).1))).1.map + bitWordValue).getD (values.length / 2) (bitWordValue []) = _ at hm + rw [List.getD_map] at hm + simpa only [arithmeticMapWithWork_value] using hm + +def medianSeedBitBudget (n B : ℕ) : ℕ := + n * (scaledCeilingBitBudget B + 3) + (n + 1) ^ 2 * (8 * (4 * B + 4) + 6) + + n + 4 * (B + (4 * B + 4)) + 3 + B + 3 + +theorem medianSeedWithWork_bounds (N multiplier : ℕ) (values : List BinaryFraction) (B : ℕ) + (hN : Nat.size N ≤ B) (hm : Nat.size multiplier + 2 ≤ B) + (hv : ∀ a ∈ values, a.width ≤ B) : + (medianSeedWithWork N multiplier values).1.length ≤ 4 * B + 4 ∧ + (medianSeedWithWork N multiplier values).2 ≤ medianSeedBitBudget values.length B := by + let rounded := arithmeticMapWithWork (scaledCeilingWithWork multiplier) values + have hlen : rounded.1.length = values.length := by + simp only [rounded, arithmeticMapWithWork_value, List.length_map] + have hrounded : ∀ word ∈ rounded.1, word.length ≤ 4 * B + 4 := by + intro word hword + simp only [rounded, arithmeticMapWithWork_value] at hword + obtain ⟨a, ha, heq⟩ := List.mem_map.mp hword + subst word + exact (scaledCeilingWithWork_bounds multiplier a B hm (hv a ha)).1 + have hmc := arithmeticMapWithWork_cost (scaledCeilingWithWork multiplier) values + (scaledCeilingBitBudget B) (fun a ha => (scaledCeilingWithWork_bounds multiplier a B hm (hv a ha)).2) + have hsort := wordSortWithWork_cost rounded.1 (4 * B + 4) hrounded + rw [hlen] at hsort + let middle := (wordSortWithWork rounded.1).1.getD (values.length / 2) [] + have hmid : middle.length ≤ 4 * B + 4 := by + by_cases hi : values.length / 2 < (wordSortWithWork rounded.1).1.length + · dsimp only [middle] + rw [List.getD_eq_getElem _ _ hi] + exact wordSortWithWork_words rounded.1 (4 * B + 4) hrounded _ (List.getElem_mem hi) + · simp only [middle, List.getD_eq_default _ _ (Nat.le_of_not_gt hi), List.length_nil] + omega + have hc := wordLEWithWork_cost N.bits middle + have hn : N.bits.length ≤ B := by simpa only [← Nat.size_eq_bits_len] using hN + have hl := wordMinWithWork_length N.bits middle + constructor + · change (wordMinWithWork N.bits middle).1.length ≤ _ + omega + · change rounded.2 + (wordSortWithWork rounded.1).2 + values.length + + ((wordLEWithWork N.bits middle).2 + 1) + Nat.size N + 3 ≤ _ + unfold medianSeedBitBudget + change rounded.2 ≤ _ at hmc + omega + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryMedianSpace.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryMedianSpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..d3f6a5fbdf56fefeb88d18c561a188d5be77b3a9 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryMedianSpace.lean @@ -0,0 +1,163 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryReductionSpace +import OAI.Combinatorics.EditApproximation.Binary.BinarySeedMedianWork +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Every insertion-sort copy, median traversal, ceiling and final trimming +scan is retained in these seed-branch allocation and call-frame counters. -/ + +namespace EditApproximation + + + +theorem wordLEAllocation_le_work (a b : List Bool) : + wordLEAllocation a b ≤ (wordLEWithWork a b).2 := by + exact Nat.zero_le _ + + + +theorem wordInsertAllocation_le_work (a : List Bool) (words : List (List Bool)) : + wordInsertAllocation a words ≤ (wordInsertWithWork a words).2 := by + induction words with + | nil => rfl + | cons b rest ih => + have hc := wordLEAllocation_le_work a b + unfold wordInsertAllocation wordInsertWithWork + dsimp only + split_ifs <;> dsimp only + · exact Nat.add_le_add_right hc 2 + · calc + _ = (wordLEAllocation a b + wordInsertAllocation a rest) + 1 := (Nat.add_assoc _ _ _).symm + _ ≤ _ := Nat.add_le_add (Nat.add_le_add hc ih) (by decide : 1 ≤ 2) + + + +theorem wordSortAllocation_le_work (words : List (List Bool)) : + wordSortAllocation words ≤ (wordSortWithWork words).2 := by + induction words with + | nil => simp only [wordSortAllocation, wordSortWithWork]; omega + | cons a rest ih => + have hi := wordInsertAllocation_le_work a (wordSortWithWork rest).1 + simp only [wordSortAllocation, wordSortWithWork] + omega + +def wordLEInvocations (a b : List Bool) : ℕ := bitCompareInvocations b a + 1 + +theorem wordLEInvocations_le_work (a b : List Bool) : + wordLEInvocations a b ≤ (wordLEWithWork a b).2 := by + exact Nat.add_le_add_right (bitCompareInvocations_le_work b a) 1 + +def wordInsertInvocations (a : List Bool) : List (List Bool) → ℕ + | [] => 1 + | b :: rest => wordLEInvocations a b + + if (wordLEWithWork a b).1 then 1 else wordInsertInvocations a rest + 1 + +theorem wordInsertInvocations_le_work (a : List Bool) (words : List (List Bool)) : + wordInsertInvocations a words ≤ (wordInsertWithWork a words).2 := by + induction words with + | nil => rfl + | cons b rest ih => + have hc := wordLEInvocations_le_work a b + unfold wordInsertInvocations wordInsertWithWork + dsimp only + split_ifs <;> dsimp only <;> omega + +def wordSortInvocations : List (List Bool) → ℕ + | [] => 1 + | a :: rest => wordSortInvocations rest + + wordInsertInvocations a (wordSortWithWork rest).1 + 1 + +theorem wordSortInvocations_le_work (words : List (List Bool)) : + wordSortInvocations words ≤ (wordSortWithWork words).2 := by + induction words with + | nil => simp only [wordSortInvocations, wordSortWithWork]; omega + | cons a rest ih => + have hi := wordInsertInvocations_le_work a (wordSortWithWork rest).1 + simp only [wordSortInvocations, wordSortWithWork] + omega + +namespace BinaryFraction + + + +theorem scaledCeilingAllocation_le_work (multiplier : ℕ) (a : BinaryFraction) : + scaledCeilingAllocation multiplier a ≤ (scaledCeilingWithWork multiplier a).2 := by + have hm := canonicalMulAllocation_le_work (nat multiplier) a + have hc := naturalCeilingAllocation_le_work (canonicalMulWithWork (nat multiplier) a).1 + unfold scaledCeilingAllocation scaledCeilingWithWork + dsimp only + omega + + + +theorem medianSeedAllocation_le_work (N multiplier : ℕ) (values : List BinaryFraction) : + medianSeedAllocation N multiplier values ≤ (medianSeedWithWork N multiplier values).2 := by + have hm := arithmeticMapAllocation_le_work (scaledCeilingWithWork multiplier) + (scaledCeilingAllocation multiplier) values (fun a _ => scaledCeilingAllocation_le_work multiplier a) + let rounded := (arithmeticMapWithWork (scaledCeilingWithWork multiplier) values).1 + have hs := wordSortAllocation_le_work rounded + have hc := wordLEAllocation_le_work N.bits ((wordSortWithWork rounded).1.getD (values.length / 2) []) + unfold medianSeedAllocation medianSeedWithWork wordMinWithWork + dsimp only + dsimp only [rounded] at hs hc + omega + + + +theorem seedMedianAllocation_le_work (N multiplier : ℕ) (values : List BinaryFraction) : + seedMedianAllocation N multiplier values ≤ (seedMedianWithWork N multiplier values).2 := by + have hm := medianSeedAllocation_le_work N multiplier values + have ht := trimBitWordAllocation_le_work (medianSeedWithWork N multiplier values).1 + unfold seedMedianAllocation seedMedianWithWork + dsimp only + omega + +def scaledCeilingInvocations (multiplier : ℕ) (a : BinaryFraction) : ℕ := + canonicalMulInvocations (nat multiplier) a + + naturalCeilingInvocations (canonicalMulWithWork (nat multiplier) a).1 + 1 + +theorem scaledCeilingInvocations_le_work (multiplier : ℕ) (a : BinaryFraction) : + scaledCeilingInvocations multiplier a ≤ (scaledCeilingWithWork multiplier a).2 := by + have hm := canonicalMulInvocations_le_work (nat multiplier) a + have hc := naturalCeilingInvocations_le_work (canonicalMulWithWork (nat multiplier) a).1 + unfold scaledCeilingInvocations scaledCeilingWithWork + dsimp only + omega + +def medianSeedInvocations (N multiplier : ℕ) (values : List BinaryFraction) : ℕ := + let rounded := (arithmeticMapWithWork (scaledCeilingWithWork multiplier) values).1 + let sorted := (wordSortWithWork rounded).1 + arithmeticMapInvocations (scaledCeilingInvocations multiplier) values + wordSortInvocations rounded + + wordLEInvocations N.bits (sorted.getD (values.length / 2) []) + + values.length + 1 + +theorem medianSeedInvocations_le_work (N multiplier : ℕ) (values : List BinaryFraction) : + medianSeedInvocations N multiplier values ≤ (medianSeedWithWork N multiplier values).2 := by + have hm := arithmeticMapInvocations_le_work (scaledCeilingWithWork multiplier) + (scaledCeilingInvocations multiplier) values (fun a _ => scaledCeilingInvocations_le_work multiplier a) + let rounded := (arithmeticMapWithWork (scaledCeilingWithWork multiplier) values).1 + have hs := wordSortInvocations_le_work rounded + have hc := wordLEInvocations_le_work N.bits ((wordSortWithWork rounded).1.getD (values.length / 2) []) + unfold medianSeedInvocations medianSeedWithWork wordMinWithWork + dsimp only + dsimp only [rounded] at hs hc + omega + +def seedMedianInvocations (N multiplier : ℕ) (values : List BinaryFraction) : ℕ := + medianSeedInvocations N multiplier values + + trimBitWordInvocations (medianSeedWithWork N multiplier values).1 + 1 + +theorem seedMedianInvocations_le_work (N multiplier : ℕ) (values : List BinaryFraction) : + seedMedianInvocations N multiplier values ≤ (seedMedianWithWork N multiplier values).2 := by + have hm := medianSeedInvocations_le_work N multiplier values + have ht := trimBitWordInvocations_le_work (medianSeedWithWork N multiplier values).1 + unfold seedMedianInvocations seedMedianWithWork + dsimp only + omega + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryMemo.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryMemo.lean new file mode 100644 index 0000000000000000000000000000000000000000..48a0a7c1de4b3c6aa4d0eb24349a567c0d287220 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryMemo.lean @@ -0,0 +1,146 @@ +import Mathlib +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! A finite binary dictionary for gathered and globally memoized inputs. +Each recursive step reads one key bit and touches one node. The explicit +counters charge pointer/node operations; multiword key/value processing +is accounted for separately by their bit lengths. -/ + +namespace EditApproximation + + + +namespace BinaryMemo + +variable {α : Type*} + + + + + + + + + + + +@[simp] theorem lookup_insert_same (tree : BinaryMemo α) (key : List Bool) (a : α) : + (tree.insert key a).lookup key = some a := by + induction key generalizing tree with + | nil => rfl + | cons b rest ih => cases b <;> simpa only [insert, lookup, left, right] using ih _ + +theorem lookup_insert_other (tree : BinaryMemo α) (key query : List Bool) (a : α) + (hne : query ≠ key) : (tree.insert key a).lookup query = tree.lookup query := by + induction key generalizing tree query with + | nil => + cases query with + | nil => exact False.elim (hne rfl) + | cons b rest => cases b <;> rfl + | cons b rest ih => + cases query with + | nil => cases b <;> rfl + | cons c tail => + cases b <;> cases c + · exact ih tree.left tail (fun h => hne (congrArg (List.cons false) h)) + · rfl + · rfl + · exact ih tree.right tail (fun h => hne (congrArg (List.cons true) h)) + +@[simp] theorem lookup_empty (key : List Bool) : (empty : BinaryMemo α).lookup key = none := by + induction key with + | nil => rfl + | cons b rest ih => cases b <;> exact ih + +def nodes : BinaryMemo α → ℕ + | .empty => 0 + | .node _ l r => 1 + l.nodes + r.nodes + +theorem child_nodes (tree : BinaryMemo α) : + tree.left.nodes + tree.right.nodes ≤ tree.nodes := by + cases tree <;> simp only [left, right, nodes] <;> omega + +theorem insert_nodes (tree : BinaryMemo α) (key : List Bool) (a : α) : + (tree.insert key a).nodes ≤ tree.nodes + key.length + 1 := by + induction key generalizing tree with + | nil => + have h := child_nodes tree + simp only [insert, nodes, List.length_nil] + omega + | cons b rest ih => + have h := child_nodes tree + cases b + · have hi := ih tree.left + simp only [insert, nodes, List.length_cons] + omega + · have hi := ih tree.right + simp only [insert, nodes, List.length_cons] + omega + +/-- An instrumented lookup returns exactly the ordinary dictionary +answer, charging one node visit per consumed bit and one terminal visit. -/ + + +theorem lookupCosted_spec (tree : BinaryMemo α) (key : List Bool) : + tree.lookupCosted key = (tree.lookup key, key.length + 1) := by + induction key generalizing tree with + | nil => rfl + | cons b rest ih => cases b <;> simp only [lookupCosted, lookup, ih, List.length_cons] + +/-- Persistent insertion allocates one new node at each visited level; +the two untouched subtrees are retained by pointer. -/ + + +theorem insertCosted_spec (tree : BinaryMemo α) (key : List Bool) (a : α) : + tree.insertCosted key a = (tree.insert key a, key.length + 1) := by + induction key generalizing tree with + | nil => rfl + | cons b rest ih => cases b <;> simp only [insertCosted, insert, ih, List.length_cons] + +end BinaryMemo + +/-- Fixed-width, least-significant-bit first encoding; no allocation +proportional to the numerical magnitude of a key is required. -/ + + +@[simp] theorem binaryMemoKey_length (d n : ℕ) : (binaryMemoKey d n).length = d := by + induction d generalizing n with + | zero => rfl + | succ d ih => simp only [binaryMemoKey, List.length_cons, ih] + +theorem binaryMemoKey_injective (d : ℕ) : + Set.InjOn (binaryMemoKey d) {n | n < 2 ^ d} := by + induction d with + | zero => intro n hn m hm _; simp only [pow_zero, Set.mem_ofPred_eq] at hn hm; omega + | succ d ih => + intro n hn m hm heq + have hpair := List.cons.inj heq + have hmod : n % 2 = m % 2 := by + have hiff := decide_eq_decide.mp hpair.1 + omega + have hnq : n / 2 < 2 ^ d := by + simp only [Set.mem_ofPred_eq, pow_succ] at hn + omega + have hmq : m / 2 < 2 ^ d := by + simp only [Set.mem_ofPred_eq, pow_succ] at hm + omega + have hquot := ih hnq hmq hpair.2 + omega + +theorem binaryMemo_lookup_insert {α : Type*} (tree : BinaryMemo α) + (d key query : ℕ) (hkey : key < 2 ^ d) (hquery : query < 2 ^ d) (a : α) : + (tree.insert (binaryMemoKey d key) a).lookup (binaryMemoKey d query) = + if query = key then some a else tree.lookup (binaryMemoKey d query) := by + split_ifs with heq + · subst query + exact BinaryMemo.lookup_insert_same _ _ _ + · apply BinaryMemo.lookup_insert_other + intro hencoded + exact heq (binaryMemoKey_injective d hquery hkey hencoded) + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryMemoSpace.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryMemoSpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..6689cab291aeb437a9fcf41ea680217c2ca1831d --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryMemoSpace.lean @@ -0,0 +1,107 @@ +import OAI.Combinatorics.EditApproximation.Geometry.RankedMemoWork + +namespace OAI + +/-! A fixed-width binary memo has bounded height on every execution, +including failed approximation events and repeated lookups. This bound +uses the actual returned tree and does not count a complete table allocation. -/ + +namespace EditApproximation + +namespace BinaryMemo + +def height {α : Type*} : BinaryMemo α → ℕ + | .empty => 0 + | .node _ left right => max left.height right.height + 1 + +theorem child_height {α : Type*} (tree : BinaryMemo α) : + tree.left.height ≤ tree.height ∧ tree.right.height ≤ tree.height := by + cases tree with + | empty => exact ⟨le_rfl, le_rfl⟩ + | node value left right => + exact ⟨(le_max_left _ _).trans (Nat.le_succ _), + (le_max_right _ _).trans (Nat.le_succ _)⟩ + +theorem insert_height {α : Type*} (tree : BinaryMemo α) (key : List Bool) (value : α) : + (tree.insert key value).height ≤ max tree.height (key.length + 1) := by + induction key generalizing tree with + | nil => + cases tree <;> simp only [insert, left, right, height, List.length_nil] <;> omega + | cons bit key ih => + cases tree with + | empty => + have h := ih (.empty : BinaryMemo α) + cases bit <;> simp only [insert, left, right, height, List.length_cons] at * <;> omega + | node old left right => + have hl := ih left + have hr := ih right + cases bit <;> simp only [insert, BinaryMemo.left, BinaryMemo.right, height, List.length_cons] at * <;> omega + +theorem nodes_le_height {α : Type*} (tree : BinaryMemo α) : + tree.nodes + 1 ≤ 2 ^ tree.height := by + induction tree with + | empty => rfl + | node value left right hl hr => + have hleft := Nat.pow_le_pow_right (by decide : 0 < (2 : ℕ)) (le_max_left left.height right.height) + have hright := Nat.pow_le_pow_right (by decide : 0 < (2 : ℕ)) (le_max_right left.height right.height) + simp only [nodes, height, pow_succ] + omega + +end BinaryMemo + +namespace FiniteQuery + +theorem run_height_bound {ι κ : Type*} + (ask : ι → BinaryMemo ℚ → RecursiveMemoResult κ) (bound : ℕ) + (hask : ∀ key memory, (ask key memory).memory.height ≤ max memory.height bound) + (program : FiniteQuery ι) (memory : BinaryMemo ℚ) : + (run ask program memory).memory.height ≤ max memory.height bound := by + induction program generalizing memory with + | done result => exact le_max_left _ _ + | read key next ih => + have hf := hask key memory + have hr := ih (ask key memory).value (ask key memory).memory + change (run ask (next (ask key memory).value) (ask key memory).memory).memory.height ≤ _ + exact hr.trans (max_le (hf.trans (le_refl _)) (le_max_right _ _)) + +end FiniteQuery + +theorem rankedMemoEvaluate_height_bound {κ : Type*} (rank : κ → ℕ) + (program : (key : κ) → FiniteQuery {child : κ // rank child < rank key}) + (bits : ℕ) (encode : κ → ℕ) (key : κ) (memory : BinaryMemo ℚ) : + (rankedMemoEvaluate rank program bits encode key memory).memory.height ≤ + max memory.height (bits + 1) := by + have hall : ∀ level key, rank key = level → ∀ memory, + (rankedMemoEvaluate rank program bits encode key memory).memory.height ≤ + max memory.height (bits + 1) := by + intro level + induction level using Nat.strong_induction_on with + | h level ih => + intro key hlevel memory + rw [rankedMemoEvaluate] + simp only [BinaryMemo.lookupCosted_spec] + split + · exact le_max_left _ _ + · have hchildren : ∀ (child : {child : κ // rank child < rank key}) previous, + (rankedMemoEvaluate rank program bits encode child.val previous).memory.height ≤ + max previous.height (bits + 1) := by + intro child previous + exact ih (rank child.val) (hlevel ▸ child.property) child.val rfl previous + have hr := FiniteQuery.run_height_bound _ (bits + 1) hchildren (program key) memory + simp only [BinaryMemo.insertCosted_spec] + exact (BinaryMemo.insert_height _ _ _).trans + (max_le hr (by simp only [binaryMemoKey_length]; exact le_max_right _ _)) + exact hall (rank key) key rfl memory + +theorem rankedMemoEvaluate_nodes_bound {κ : Type*} (rank : κ → ℕ) + (program : (key : κ) → FiniteQuery {child : κ // rank child < rank key}) + (bits : ℕ) (encode : κ → ℕ) (key : κ) : + (rankedMemoEvaluate rank program bits encode key .empty).memory.nodes + 1 ≤ 2 ^ (bits + 1) := by + have h := rankedMemoEvaluate_height_bound rank program bits encode key .empty + simp only [BinaryMemo.height, max_eq_right (Nat.zero_le _)] at h + exact (BinaryMemo.nodes_le_height _).trans + (Nat.pow_le_pow_right (by decide : 0 < (2 : ℕ)) h) + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryNormalizationSpace.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryNormalizationSpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fc09ab41116718bde593238d3a7a239ab34c44d --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryNormalizationSpace.lean @@ -0,0 +1,46 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryOnlineRangeSpace +import OAI.Combinatorics.EditApproximation.Binary.BitQuerySpace +import OAI.Combinatorics.EditApproximation.Binary.BitQueryNormalize +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation.BinaryFraction + + + +theorem powerDenominatorAllocation_le_work (a : BinaryFraction) (base : List Bool) + (hbase : 0 < bitWordValue base) (n : ℕ) : + powerDenominatorAllocation a base hbase n ≤ (powerDenominatorWithWork a base hbase n).2 := by + have hp := bitPowerAllocation_le_work base n + have hf := fixedDenominatorAllocation_le_work a (bitPowerWithWork base n).1 + (by rw [bitPowerWithWork_value]; exact Nat.pow_pos hbase) + unfold powerDenominatorAllocation powerDenominatorWithWork + dsimp only + omega + + + +theorem finishCachedAllocation_le_work (raw : BinaryFraction × ℕ) (allocation : ℕ) + (base : List Bool) (hbase : 0 < bitWordValue base) (remaining : ℕ) (ha : allocation ≤ raw.2) : + finishCachedAllocation raw allocation base hbase remaining ≤ (finishCachedWithWork raw base hbase remaining).2 := by + have hp := powerDenominatorAllocation_le_work raw.1 base hbase remaining + unfold finishCachedAllocation finishCachedWithWork + dsimp only + omega + +end EditApproximation.BinaryFraction + +namespace EditApproximation.BitQuery.Heap + +def normalize {ι : Type*} {program : BitQuery ι BinaryFraction} (heap : Heap program) + (base : List Bool) (hbase : 0 < bitWordValue base) (remaining : ℕ) : + Heap (program.normalize base hbase remaining) := + heap.bind _ fun word => computeOf (BinaryFraction.finishCachedWithWork (word, 0) base hbase remaining) + (BinaryFraction.finishCachedAllocation (word, 0) 0 base hbase remaining) + (BinaryFraction.finishCachedAllocation_le_work (word, 0) 0 base hbase remaining le_rfl) + +end EditApproximation.BitQuery.Heap + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryNumericSpace.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryNumericSpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..856c70b235eddeda3801a3a96f5f1aa666aae8d6 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryNumericSpace.lean @@ -0,0 +1,203 @@ +import OAI.Combinatorics.EditApproximation.Numerics.ScalarControlSpace +import OAI.Combinatorics.EditApproximation.Binary.BinaryLoopSpace +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Allocation and invocation traces for the actual Boolean logarithm, +dot-product, and gradient loops. Constant literal words are shared. -/ + +namespace EditApproximation.BinaryFraction + + + +def subInvocations (a b : BinaryFraction) : ℕ := canonicalAddInvocations a b.neg + 1 + +theorem subAllocation_le_work (a b : BinaryFraction) : + subAllocation a b ≤ (subWithWork a b).2 := by + have h := canonicalAddAllocation_le_work a b.neg + unfold subAllocation subWithWork + dsimp only + omega + +theorem subInvocations_le_work (a b : BinaryFraction) : + subInvocations a b ≤ (subWithWork a b).2 := by + exact Nat.add_le_add_right (canonicalAddInvocations_le_work a b.neg) 1 + + + +def powInvocations (a : BinaryFraction) : ℕ → ℕ + | 0 => 1 + | n + 1 => powInvocations a n + canonicalMulInvocations (powWithWork a n).1 a + 1 + +theorem powAllocation_le_work (a : BinaryFraction) (n : ℕ) : + powAllocation a n ≤ (powWithWork a n).2 := by + induction n with + | zero => exact Nat.zero_le _ + | succ n ih => + have h := canonicalMulAllocation_le_work (powWithWork a n).1 a + simp only [powAllocation, powWithWork] + exact (Nat.add_le_add ih h).trans (Nat.le_succ _) + +theorem powInvocations_le_work (a : BinaryFraction) (n : ℕ) : + powInvocations a n ≤ (powWithWork a n).2 := by + induction n with + | zero => rfl + | succ n ih => + have h := canonicalMulInvocations_le_work (powWithWork a n).1 a + simp only [powInvocations, powWithWork] + omega + + + +def logarithmPartialInvocations (b : BinaryFraction) : ℕ → ℕ + | 0 => 1 + | n + 1 => + let previous := (logarithmPartialWithWork b n).1 + let power := (powWithWork b (2 * n + 1)).1 + let term := (divWithWork power (nat (2 * n + 1))).1 + logarithmPartialInvocations b n + powInvocations b (2 * n + 1) + + divInvocations power (nat (2 * n + 1)) + canonicalAddInvocations previous term + 1 + +theorem logarithmPartialAllocation_le_work (b : BinaryFraction) (n : ℕ) : + logarithmPartialAllocation b n ≤ (logarithmPartialWithWork b n).2 := by + induction n with + | zero => exact Nat.zero_le _ + | succ n ih => + have hp := powAllocation_le_work b (2 * n + 1) + have hd := divAllocation_le_work (powWithWork b (2 * n + 1)).1 (nat (2 * n + 1)) + have ha := canonicalAddAllocation_le_work (logarithmPartialWithWork b n).1 + (divWithWork (powWithWork b (2 * n + 1)).1 (nat (2 * n + 1))).1 + simp only [logarithmPartialAllocation, logarithmPartialWithWork] + exact Nat.add_le_add + (Nat.add_le_add_right (Nat.add_le_add (Nat.add_le_add (Nat.add_le_add ih hp) hd) ha) _) + (by decide : 1 ≤ 5) + +theorem logarithmPartialInvocations_le_work (b : BinaryFraction) (n : ℕ) : + logarithmPartialInvocations b n ≤ (logarithmPartialWithWork b n).2 := by + induction n with + | zero => rfl + | succ n ih => + have hp := powInvocations_le_work b (2 * n + 1) + have hd := divInvocations_le_work (powWithWork b (2 * n + 1)).1 (nat (2 * n + 1)) + have ha := canonicalAddInvocations_le_work (logarithmPartialWithWork b n).1 + (divWithWork (powWithWork b (2 * n + 1)).1 (nat (2 * n + 1))).1 + simp only [logarithmPartialInvocations, logarithmPartialWithWork] + omega + + + +def logarithmInvocations (r : BinaryFraction) (n : ℕ) : ℕ := + let numerator := (subWithWork r one).1 + let denominator := (canonicalAddWithWork r one).1 + let ratio := (divWithWork numerator denominator).1 + subInvocations r one + canonicalAddInvocations r one + divInvocations numerator denominator + + logarithmPartialInvocations ratio n + canonicalMulInvocations (nat 2) (logarithmPartialWithWork ratio n).1 + 1 + +theorem logarithmAllocation_le_work (r : BinaryFraction) (n : ℕ) : + logarithmAllocation r n ≤ (logarithmWithWork r n).2 := by + have h1 := subAllocation_le_work r one + have h2 := canonicalAddAllocation_le_work r one + have h3 := divAllocation_le_work (subWithWork r one).1 (canonicalAddWithWork r one).1 + have h4 := logarithmPartialAllocation_le_work (divWithWork (subWithWork r one).1 (canonicalAddWithWork r one).1).1 n + have h5 := canonicalMulAllocation_le_work (nat 2) + (logarithmPartialWithWork (divWithWork (subWithWork r one).1 (canonicalAddWithWork r one).1).1 n).1 + unfold logarithmAllocation logarithmWithWork + dsimp only + omega + +theorem logarithmInvocations_le_work (r : BinaryFraction) (n : ℕ) : + logarithmInvocations r n ≤ (logarithmWithWork r n).2 := by + have h1 := subInvocations_le_work r one + have h2 := canonicalAddInvocations_le_work r one + have h3 := divInvocations_le_work (subWithWork r one).1 (canonicalAddWithWork r one).1 + have h4 := logarithmPartialInvocations_le_work (divWithWork (subWithWork r one).1 (canonicalAddWithWork r one).1).1 n + have h5 := canonicalMulInvocations_le_work (nat 2) + (logarithmPartialWithWork (divWithWork (subWithWork r one).1 (canonicalAddWithWork r one).1).1 n).1 + unfold logarithmInvocations logarithmWithWork + dsimp only + omega + + + +def dotListInvocations {d : ℕ} (left right : Vector BinaryFraction d) : List (Fin d) → ℕ + | [] => 1 + | i :: rest => dotListInvocations left right rest + + canonicalMulInvocations (left.get i) (right.get i) + + canonicalAddInvocations (canonicalMulWithWork (left.get i) (right.get i)).1 (dotListWithWork left right rest).1 + 1 + +theorem dotListAllocation_le_work {d : ℕ} (left right : Vector BinaryFraction d) (indices : List (Fin d)) : + dotListAllocation left right indices ≤ (dotListWithWork left right indices).2 := by + induction indices with + | nil => simp only [dotListAllocation, dotListWithWork, Nat.zero_le] + | cons i rest ih => + have hm := canonicalMulAllocation_le_work (left.get i) (right.get i) + have ha := canonicalAddAllocation_le_work + (canonicalMulWithWork (left.get i) (right.get i)).1 (dotListWithWork left right rest).1 + simp only [dotListAllocation, dotListWithWork] + omega + +theorem dotListInvocations_le_work {d : ℕ} (left right : Vector BinaryFraction d) (indices : List (Fin d)) : + dotListInvocations left right indices ≤ (dotListWithWork left right indices).2 := by + induction indices with + | nil => rfl + | cons i rest ih => + have hm := canonicalMulInvocations_le_work (left.get i) (right.get i) + have ha := canonicalAddInvocations_le_work + (canonicalMulWithWork (left.get i) (right.get i)).1 (dotListWithWork left right rest).1 + simp only [dotListInvocations, dotListWithWork] + omega + + + +def gradientCellInvocations {d : ℕ} (G : ℕ) (linear point : Vector BinaryFraction d) + (i : Fin d) : ℕ := + let smoothing := (powWithWork (nat G) 50).1 + let inverse := smoothing.invWithWork.1 + let shifted := (canonicalAddWithWork (point.get i) inverse).1 + let logarithm := (logarithmWithWork shifted (G ^ 60)).1 + let deficit := (subWithWork logarithm.neg one).1 + powInvocations (nat G) 50 + invInvocations smoothing + + canonicalAddInvocations (point.get i) inverse + logarithmInvocations shifted (G ^ 60) + + subInvocations logarithm.neg one + canonicalAddInvocations deficit (linear.get i) + 1 + +theorem gradientCellAllocation_le_work {d : ℕ} (G : ℕ) + (linear point : Vector BinaryFraction d) (i : Fin d) : + gradientCellAllocation G linear point i ≤ (gradientCellWithWork G linear point i).2 := by + have h1 := powAllocation_le_work (nat G) 50 + have h2 := invAllocation_le_work (powWithWork (nat G) 50).1 + have h3 := canonicalAddAllocation_le_work (point.get i) (powWithWork (nat G) 50).1.invWithWork.1 + have h4 := logarithmAllocation_le_work + (canonicalAddWithWork (point.get i) (powWithWork (nat G) 50).1.invWithWork.1).1 (G ^ 60) + have h5 := subAllocation_le_work + (logarithmWithWork (canonicalAddWithWork (point.get i) + (powWithWork (nat G) 50).1.invWithWork.1).1 (G ^ 60)).1.neg one + have h6 := canonicalAddAllocation_le_work + (subWithWork (logarithmWithWork (canonicalAddWithWork (point.get i) + (powWithWork (nat G) 50).1.invWithWork.1).1 (G ^ 60)).1.neg one).1 (linear.get i) + unfold gradientCellAllocation gradientCellWithWork + dsimp only + omega + +theorem gradientCellInvocations_le_work {d : ℕ} (G : ℕ) + (linear point : Vector BinaryFraction d) (i : Fin d) : + gradientCellInvocations G linear point i ≤ (gradientCellWithWork G linear point i).2 := by + have h1 := powInvocations_le_work (nat G) 50 + have h2 := invInvocations_le_work (powWithWork (nat G) 50).1 + have h3 := canonicalAddInvocations_le_work (point.get i) (powWithWork (nat G) 50).1.invWithWork.1 + have h4 := logarithmInvocations_le_work + (canonicalAddWithWork (point.get i) (powWithWork (nat G) 50).1.invWithWork.1).1 (G ^ 60) + have h5 := subInvocations_le_work + (logarithmWithWork (canonicalAddWithWork (point.get i) + (powWithWork (nat G) 50).1.invWithWork.1).1 (G ^ 60)).1.neg one + have h6 := canonicalAddInvocations_le_work + (subWithWork (logarithmWithWork (canonicalAddWithWork (point.get i) + (powWithWork (nat G) 50).1.invWithWork.1).1 (G ^ 60)).1.neg one).1 (linear.get i) + unfold gradientCellInvocations gradientCellWithWork + dsimp only + omega + +end EditApproximation.BinaryFraction + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryOnlineInputWork.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryOnlineInputWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..cdd82000d07c2917de21a0d3eb3aeb7ea82d2f80 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryOnlineInputWork.lean @@ -0,0 +1,186 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryOnlineInputs +import OAI.Combinatorics.EditApproximation.Binary.BinaryBandInputWork + +namespace OAI + +/-! The finite optimistic-history builder uses only the charged Boolean +fraction instructions. These bounds derive every intermediate width from +the stored table and mass widths. -/ + +namespace EditApproximation +namespace BinaryFraction + +def gainBitBudget (Bm Bt : ℕ) : ℕ := 2100 * (Bm + Bt + 2) ^ 2 + 1 + +theorem gainWithWork_cost {β σ : Type*} (mass : β → BinaryFraction) + (table : ℕ → β × σ → BinaryFraction) (s : ℕ) (i : β × σ) (Bm Bt : ℕ) + (hm : (mass i.1).width ≤ Bm) (ht : (table s i).width ≤ Bt) : + (gainWithWork mass table s i).2 ≤ gainBitBudget Bm Bt := by + have h := divWithWork_cost (table s i).neg (mass i.1) (Bm + Bt) + (by rw [neg_width]; omega) (by omega) + exact Nat.add_le_add_right h 1 + +def decrementBitBudget (Bm Bt : ℕ) : ℕ := + 6000 * (Bt + 1) ^ 2 + 2100 * (8 * Bt + Bm + 8) ^ 2 + 2 + +theorem decrementWithWork_cost {β σ : Type*} (mass : β → BinaryFraction) + (table : ℕ → β × σ → BinaryFraction) (s : ℕ) (i : β × σ) (Bm Bt : ℕ) + (hm : (mass i.1).width ≤ Bm) (ht : (table s i).width ≤ Bt) + (ht' : (table (s + 1) i).width ≤ Bt) : + (decrementWithWork mass table s i).2 ≤ decrementBitBudget Bm Bt := by + have hs := subWithWork_cost (table s i) (table (s + 1) i) Bt ht ht' + have hw := canonicalAddWithWork_self_width (table s i) (table (s + 1) i).neg + change (subWithWork (table s i) (table (s + 1) i)).1.width ≤ + (subWithWork (table s i) (table (s + 1) i)).1.representation.storageBits at hw + rw [subWithWork_representation] at hw + have hraw := UnreducedRational.storageBits_sub (table s i).representation (table (s + 1) i).representation + have ho := representation_storageBits_le (table s i) + have hn := representation_storageBits_le (table (s + 1) i) + have hd := divWithWork_cost (subWithWork (table s i) (table (s + 1) i)).1 + (mass i.1) (8 * Bt + Bm + 6) (by omega) (by omega) + change (subWithWork (table s i) (table (s + 1) i)).2 + + (divWithWork (subWithWork (table s i) (table (s + 1) i)).1 (mass i.1)).2 + 1 ≤ _ + rw [show 8 * Bt + Bm + 6 + 2 = 8 * Bt + Bm + 8 by omega] at hd + unfold decrementBitBudget + omega + +def coefficientBitBudget (Bk : ℕ) : ℕ := + 2000 * (Bk + 3) ^ 2 + 6000 * (2 * Bk + 7) ^ 2 + 2 + +theorem coefficientWithWork_cost (kappa : BinaryFraction) (Bk : ℕ) + (hk : kappa.width ≤ Bk) : + (coefficientWithWork kappa).2 ≤ coefficientBitBudget Bk := by + have htwo : (nat 2).width = 2 := by decide + have hm := canonicalMulWithWork_cost (nat 2) kappa (Bk + 2) (by omega) (by omega) + have hw := canonicalMulWithWork_self_width (nat 2) kappa + rw [canonicalMulWithWork_representation, nat_representation] at hw + have hraw := UnreducedRational.storageBits_mul (UnreducedRational.nat 2) kappa.representation + have hrawtwo : (UnreducedRational.nat 2).storageBits = 4 := by decide + rw [hrawtwo] at hraw + have hk' := representation_storageBits_le kappa + have hs := subWithWork_cost one (canonicalMulWithWork (nat 2) kappa).1 (2 * Bk + 6) + (by change 1 ≤ _; omega) (by omega) + change (canonicalMulWithWork (nat 2) kappa).2 + + (subWithWork one (canonicalMulWithWork (nat 2) kappa).1).2 + 1 ≤ _ + rw [show Bk + 2 + 1 = Bk + 3 by omega] at hm + rw [show 2 * Bk + 6 + 1 = 2 * Bk + 7 by omega] at hs + unfold coefficientBitBudget + omega + +def optimisticTermWordBudget (Bm Bt Bc : ℕ) : ℕ := 8 * Bt + 2 * Bm + 2 * Bc + 12 + +def optimisticTermBitBudget (Bm Bt Bc : ℕ) : ℕ := + gainBitBudget Bm Bt + decrementBitBudget Bm Bt + + 2000 * (optimisticTermWordBudget Bm Bt Bc + 1) ^ 2 + + 6000 * (optimisticTermWordBudget Bm Bt Bc + 1) ^ 2 + 2 + +theorem optimisticTermWithWork_cost {β σ : Type*} (mass : β → BinaryFraction) + (table : ℕ → β × σ → BinaryFraction) (coefficient : BinaryFraction) + (s : ℕ) (i : β × σ) (Bm Bt Bc : ℕ) + (hm : (mass i.1).width ≤ Bm) (ht : (table s i).width ≤ Bt) + (ht' : (table (s + 1) i).width ≤ Bt) (hc : coefficient.width ≤ Bc) : + (optimisticTermWithWork mass table coefficient s i).2 ≤ optimisticTermBitBudget Bm Bt Bc := by + let gain := (gainWithWork mass table s i).1 + let decrement := (decrementWithWork mass table s i).1 + let W := optimisticTermWordBudget Bm Bt Bc + have hgs := gainWithWork_storage mass table s i Bm Bt hm ht + have hds := decrementWithWork_storage mass table s i Bm Bt hm ht ht' + have hgw := divWithWork_self_width (table s i).neg (mass i.1) + change gain.width ≤ gain.representation.storageBits at hgw + have hdw := divWithWork_self_width (subWithWork (table s i) (table (s + 1) i)).1 (mass i.1) + change decrement.width ≤ decrement.representation.storageBits at hdw + change gain.representation.storageBits ≤ _ at hgs + change decrement.representation.storageBits ≤ _ at hds + have hgW : gain.width ≤ W := by dsimp only [W, optimisticTermWordBudget]; omega + have hdW : decrement.width ≤ W := by dsimp only [W, optimisticTermWordBudget]; omega + have hcW : coefficient.width ≤ W := by dsimp only [W, optimisticTermWordBudget]; omega + have hp := canonicalMulWithWork_cost coefficient decrement W hcW hdW + have hpw := canonicalMulWithWork_self_width coefficient decrement + rw [canonicalMulWithWork_representation] at hpw + have hps := UnreducedRational.storageBits_mul coefficient.representation decrement.representation + have hcs := representation_storageBits_le coefficient + have hpW : (canonicalMulWithWork coefficient decrement).1.width ≤ W := by + dsimp only [W, optimisticTermWordBudget] + omega + have ha := canonicalAddWithWork_cost gain (canonicalMulWithWork coefficient decrement).1 W hgW hpW + have hg := gainWithWork_cost mass table s i Bm Bt hm ht + have hd := decrementWithWork_cost mass table s i Bm Bt hm ht ht' + change (gainWithWork mass table s i).2 + (decrementWithWork mass table s i).2 + + (canonicalMulWithWork coefficient decrement).2 + + (canonicalAddWithWork gain (canonicalMulWithWork coefficient decrement).1).2 + 2 ≤ _ + unfold optimisticTermBitBudget + change _ ≤ gainBitBudget Bm Bt + decrementBitBudget Bm Bt + + 2000 * (W + 1) ^ 2 + 6000 * (W + 1) ^ 2 + 2 + omega + +def onlineFinalWordBudget (Be Bk Bm Bt t : ℕ) : ℕ := + Be + bandMassTotalStorageBudget t (optimisticTermStorageBudget Bm Bt (4 * Bk + 18)) + + (2 * Bt + 2 * Bm + 4) + 2 + +def onlineLinearBitBudget (Be Bk Bm Bt t : ℕ) : ℕ := + coefficientBitBudget Bk + t * (optimisticTermBitBudget Bm Bt (4 * Bk + 18) + 6) + + storedSumBitBudget t (optimisticTermStorageBudget Bm Bt (4 * Bk + 18)) + + gainBitBudget Bm Bt + 6000 * (onlineFinalWordBudget Be Bk Bm Bt t + 1) ^ 2 + + 2000 * (2 * onlineFinalWordBudget Be Bk Bm Bt t + 3) ^ 2 + 3 + +theorem onlineLinearWithWork_cost {β σ : Type*} (mass : β → BinaryFraction) + (table : ℕ → β × σ → BinaryFraction) (eta kappa : BinaryFraction) + (t : ℕ) (i : β × σ) (Be Bk Bm Bt : ℕ) + (he : eta.width ≤ Be) (hk : kappa.width ≤ Bk) (hm : (mass i.1).width ≤ Bm) + (ht : ∀ s ≤ t + 1, (table s i).width ≤ Bt) : + (onlineLinearWithWork mass table eta kappa t i).2 ≤ onlineLinearBitBudget Be Bk Bm Bt t := by + let coefficient := (coefficientWithWork kappa).1 + let terms := vectorMapWithWork t fun s => optimisticTermWithWork mass table coefficient s.val i + let history := (bandMassTotalWithWork terms.1).1 + let current := (gainWithWork mass table t i).1 + let W := onlineFinalWordBudget Be Bk Bm Bt t + have hcn := canonicalAddWithWork_self_width one (canonicalMulWithWork (nat 2) kappa).1.neg + change coefficient.width ≤ coefficient.representation.storageBits at hcn + have hc : coefficient.width ≤ 4 * Bk + 18 := hcn.trans (coefficientWithWork_storage kappa Bk hk) + have hterms (s : Fin t) : (terms.1.get s).width ≤ optimisticTermStorageBudget Bm Bt (4 * Bk + 18) := by + simp only [terms, vectorMapWithWork_value] + exact (canonicalAddWithWork_self_width _ _).trans + (optimisticTermWithWork_storage mass table coefficient s.val i Bm Bt (4 * Bk + 18) + hm (ht s.val (by omega)) (ht (s.val + 1) (by omega)) hc) + have htc := vectorMapWithWork_cost_le t + (fun s => optimisticTermWithWork mass table coefficient s.val i) + (optimisticTermBitBudget Bm Bt (4 * Bk + 18)) + (fun s => optimisticTermWithWork_cost mass table coefficient s.val i Bm Bt (4 * Bk + 18) + hm (ht s.val (by omega)) (ht (s.val + 1) (by omega)) hc) + have hhc := bandMassTotalWithWork_cost terms.1 (optimisticTermStorageBudget Bm Bt (4 * Bk + 18)) hterms + have hhs := bandMassTotalWithWork_storage terms.1 (optimisticTermStorageBudget Bm Bt (4 * Bk + 18)) hterms + change history.representation.storageBits ≤ _ at hhs + have hhw := dotListWithWork_width_le_storageBits terms.1 (Vector.replicate t one) (List.finRange t) + change history.width ≤ history.representation.storageBits at hhw + have hgc := gainWithWork_cost mass table t i Bm Bt hm (ht t (by omega)) + have hgs := gainWithWork_storage mass table t i Bm Bt hm (ht t (by omega)) + change current.representation.storageBits ≤ _ at hgs + have hgw := divWithWork_self_width (table t i).neg (mass i.1) + change current.width ≤ current.representation.storageBits at hgw + have hhW : history.width ≤ W := by dsimp only [W, onlineFinalWordBudget]; omega + have hgW : current.width ≤ W := by dsimp only [W, onlineFinalWordBudget]; omega + have hac := canonicalAddWithWork_cost history current W hhW hgW + have haw := canonicalAddWithWork_self_width history current + rw [canonicalAddWithWork_representation] at haw + have has := UnreducedRational.storageBits_add history.representation current.representation + have haW : (canonicalAddWithWork history current).1.width ≤ 2 * W + 2 := by + dsimp only [W, onlineFinalWordBudget] + omega + have hmc := canonicalMulWithWork_cost eta (canonicalAddWithWork history current).1 + (2 * W + 2) (by dsimp only [W, onlineFinalWordBudget]; omega) haW + rw [show 2 * W + 2 + 1 = 2 * W + 3 by omega] at hmc + have hcc := coefficientWithWork_cost kappa Bk hk + change (coefficientWithWork kappa).2 + terms.2 + (bandMassTotalWithWork terms.1).2 + + (gainWithWork mass table t i).2 + (canonicalAddWithWork history current).2 + + (canonicalMulWithWork eta (canonicalAddWithWork history current).1).2 + 3 ≤ _ + change terms.2 ≤ _ at htc + unfold onlineLinearBitBudget + change _ ≤ coefficientBitBudget Bk + t * (optimisticTermBitBudget Bm Bt (4 * Bk + 18) + 6) + + storedSumBitBudget t (optimisticTermStorageBudget Bm Bt (4 * Bk + 18)) + gainBitBudget Bm Bt + + 6000 * (W + 1) ^ 2 + 2000 * (2 * W + 3) ^ 2 + 3 + omega + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryOnlineInputs.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryOnlineInputs.lean new file mode 100644 index 0000000000000000000000000000000000000000..9c607bcc3e53d2d35fa8026a643d24729808f986 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryOnlineInputs.lean @@ -0,0 +1,204 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryBandInputs +import OAI.Combinatorics.EditApproximation.Geometry.OnlineLinearBits +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! The actual optimistic linear objective constructed from stored Boolean +fractions, using counted sums, products and divisions. No reduced-rational +conversion is used between the table inputs and the optimizer. -/ + +namespace EditApproximation +namespace BinaryFraction + +open Finset + +@[simp] theorem canonicalAddWithWork_value (a b : BinaryFraction) : + (canonicalAddWithWork a b).1.value = a.value + b.value := by + rw [← representation_value, canonicalAddWithWork_representation, + UnreducedRational.value_add, representation_value, representation_value] + +@[simp] theorem canonicalMulWithWork_value (a b : BinaryFraction) : + (canonicalMulWithWork a b).1.value = a.value * b.value := by + rw [← representation_value, canonicalMulWithWork_representation, + UnreducedRational.value_mul, representation_value, representation_value] + +@[simp] theorem divWithWork_value (a b : BinaryFraction) : + (divWithWork a b).1.value = a.value / b.value := by + rw [← representation_value, divWithWork_representation, + UnreducedRational.value_div, representation_value, representation_value] + +@[simp] theorem subWithWork_value (a b : BinaryFraction) : + (subWithWork a b).1.value = a.value - b.value := by + rw [← representation_value, subWithWork_representation, + UnreducedRational.value_sub, representation_value, representation_value] + +def gainWithWork {β σ : Type*} (mass : β → BinaryFraction) + (table : ℕ → β × σ → BinaryFraction) (s : ℕ) (i : β × σ) : BinaryFraction × ℕ := + let quotient := divWithWork (table s i).neg (mass i.1) + (quotient.1, quotient.2 + 1) + +def decrementWithWork {β σ : Type*} (mass : β → BinaryFraction) + (table : ℕ → β × σ → BinaryFraction) (s : ℕ) (i : β × σ) : BinaryFraction × ℕ := + let difference := subWithWork (table s i) (table (s + 1) i) + let quotient := divWithWork difference.1 (mass i.1) + (quotient.1, difference.2 + quotient.2 + 1) + + + +def optimisticTermWithWork {β σ : Type*} (mass : β → BinaryFraction) + (table : ℕ → β × σ → BinaryFraction) (coefficient : BinaryFraction) + (s : ℕ) (i : β × σ) : BinaryFraction × ℕ := + let gain := gainWithWork mass table s i + let decrement := decrementWithWork mass table s i + let scaled := canonicalMulWithWork coefficient decrement.1 + let total := canonicalAddWithWork gain.1 scaled.1 + (total.1, gain.2 + decrement.2 + scaled.2 + total.2 + 2) + +@[simp] theorem gainWithWork_value {β σ : Type*} (mass : β → BinaryFraction) + (table : ℕ → β × σ → BinaryFraction) (s : ℕ) (i : β × σ) : + (gainWithWork mass table s i).1.value = + childGain (fun j => (mass j).value) (fun t j => (table t j).value) s i := by + simp only [gainWithWork, divWithWork_value, neg_value, childGain] + +@[simp] theorem decrementWithWork_value {β σ : Type*} (mass : β → BinaryFraction) + (table : ℕ → β × σ → BinaryFraction) (s : ℕ) (i : β × σ) : + (decrementWithWork mass table s i).1.value = + childDecrement (fun j => (mass j).value) (fun t j => (table t j).value) s i := by + simp only [decrementWithWork, divWithWork_value, subWithWork_value, childDecrement] + +@[simp] theorem coefficientWithWork_value (kappa : BinaryFraction) : + (coefficientWithWork kappa).1.value = 1 - 2 * kappa.value := by + simp only [coefficientWithWork, subWithWork_value, canonicalMulWithWork_value] + rw [← representation_value one, one_representation, UnreducedRational.value_one, + ← representation_value (nat 2), nat_representation, UnreducedRational.value_nat] + norm_num + +def onlineLinearWithWork {β σ : Type*} (mass : β → BinaryFraction) + (table : ℕ → β × σ → BinaryFraction) (eta kappa : BinaryFraction) + (t : ℕ) (i : β × σ) : BinaryFraction × ℕ := + let coefficient := coefficientWithWork kappa + let terms := vectorMapWithWork t fun s => optimisticTermWithWork mass table coefficient.1 s.val i + let history := bandMassTotalWithWork terms.1 + let current := gainWithWork mass table t i + let total := canonicalAddWithWork history.1 current.1 + let result := canonicalMulWithWork eta total.1 + (result.1, coefficient.2 + terms.2 + history.2 + current.2 + total.2 + result.2 + 3) + +theorem onlineLinearWithWork_value {β σ : Type*} (mass : β → BinaryFraction) + (table : ℕ → β × σ → BinaryFraction) (eta kappa : BinaryFraction) + (t : ℕ) (i : β × σ) : + (onlineLinearWithWork mass table eta kappa t i).1.value = + rationalOnlineLinear eta.value kappa.value (childGain (fun j => (mass j).value) + (fun s j => (table s j).value)) + (childDecrement (fun j => (mass j).value) (fun s j => (table s j).value)) t i := by + simp only [onlineLinearWithWork, canonicalMulWithWork_value, canonicalAddWithWork_value, + bandMassTotalWithWork_value, vectorMapWithWork_value, optimisticTermWithWork, + coefficientWithWork_value, gainWithWork_value, decrementWithWork_value] + unfold rationalOnlineLinear rationalOptimisticHistory + congr 2 + exact Fin.sum_univ_eq_sum_range (fun s => childGain (fun j => (mass j).value) + (fun s j => (table s j).value) s i + (1 - 2 * kappa.value) * + childDecrement (fun j => (mass j).value) (fun s j => (table s j).value) s i) t + +theorem gainWithWork_storage {β σ : Type*} (mass : β → BinaryFraction) + (table : ℕ → β × σ → BinaryFraction) (s : ℕ) (i : β × σ) (Bm Bt : ℕ) + (hm : (mass i.1).width ≤ Bm) (ht : (table s i).width ≤ Bt) : + (gainWithWork mass table s i).1.representation.storageBits ≤ 2 * Bt + 2 * Bm + 4 := by + have hm' := representation_storageBits_le (mass i.1) + have ht' := representation_storageBits_le (table s i) + change (divWithWork (table s i).neg (mass i.1)).1.representation.storageBits ≤ _ + rw [divWithWork_representation, neg_representation] + have h := UnreducedRational.storageBits_div (table s i).representation.neg (mass i.1).representation + rw [UnreducedRational.storageBits_neg] at h + omega + +theorem decrementWithWork_storage {β σ : Type*} (mass : β → BinaryFraction) + (table : ℕ → β × σ → BinaryFraction) (s : ℕ) (i : β × σ) (Bm Bt : ℕ) + (hm : (mass i.1).width ≤ Bm) (ht : (table s i).width ≤ Bt) (ht' : (table (s + 1) i).width ≤ Bt) : + (decrementWithWork mass table s i).1.representation.storageBits ≤ 8 * Bt + 2 * Bm + 9 := by + have hm' := representation_storageBits_le (mass i.1) + have ho := representation_storageBits_le (table s i) + have hn := representation_storageBits_le (table (s + 1) i) + have hs := UnreducedRational.storageBits_sub (table s i).representation (table (s + 1) i).representation + have hd := UnreducedRational.storageBits_div ((table s i).representation.sub (table (s + 1) i).representation) (mass i.1).representation + change (divWithWork (subWithWork (table s i) (table (s + 1) i)).1 (mass i.1)).1.representation.storageBits ≤ _ + rw [divWithWork_representation, subWithWork_representation] + omega + +theorem coefficientWithWork_storage (kappa : BinaryFraction) (Bk : ℕ) (hk : kappa.width ≤ Bk) : + (coefficientWithWork kappa).1.representation.storageBits ≤ 4 * Bk + 18 := by + have hk' := representation_storageBits_le kappa + have hm := UnreducedRational.storageBits_mul (UnreducedRational.nat 2) kappa.representation + have hs := UnreducedRational.storageBits_sub UnreducedRational.one + ((UnreducedRational.nat 2).mul kappa.representation) + have htwo : (UnreducedRational.nat 2).storageBits = 4 := by decide + rw [htwo] at hm + rw [UnreducedRational.storageBits_one] at hs + change (subWithWork one (canonicalMulWithWork (nat 2) kappa).1).1.representation.storageBits ≤ _ + rw [subWithWork_representation, one_representation, canonicalMulWithWork_representation, nat_representation] + omega + +def optimisticTermStorageBudget (Bm Bt Bc : ℕ) : ℕ := 20 * Bt + 8 * Bm + 4 * Bc + 30 + +theorem optimisticTermWithWork_storage {β σ : Type*} (mass : β → BinaryFraction) + (table : ℕ → β × σ → BinaryFraction) (coefficient : BinaryFraction) + (s : ℕ) (i : β × σ) (Bm Bt Bc : ℕ) + (hm : (mass i.1).width ≤ Bm) (ht : (table s i).width ≤ Bt) + (ht' : (table (s + 1) i).width ≤ Bt) (hc : coefficient.width ≤ Bc) : + (optimisticTermWithWork mass table coefficient s i).1.representation.storageBits ≤ + optimisticTermStorageBudget Bm Bt Bc := by + have hg := gainWithWork_storage mass table s i Bm Bt hm ht + have hd := decrementWithWork_storage mass table s i Bm Bt hm ht ht' + have hc' := representation_storageBits_le coefficient + have hp := UnreducedRational.storageBits_mul coefficient.representation + (decrementWithWork mass table s i).1.representation + have ha := UnreducedRational.storageBits_add (gainWithWork mass table s i).1.representation + (coefficient.representation.mul (decrementWithWork mass table s i).1.representation) + change (canonicalAddWithWork (gainWithWork mass table s i).1 + (canonicalMulWithWork coefficient (decrementWithWork mass table s i).1).1).1.representation.storageBits ≤ _ + rw [canonicalAddWithWork_representation, canonicalMulWithWork_representation] + unfold optimisticTermStorageBudget + omega + +def onlineLinearStorageBudget (Be Bk Bm Bt t : ℕ) : ℕ := + 2 * Be + 2 * bandMassTotalStorageBudget t (optimisticTermStorageBudget Bm Bt (4 * Bk + 18)) + + 2 * (2 * Bt + 2 * Bm + 4) + 3 + +theorem onlineLinearWithWork_storage {β σ : Type*} (mass : β → BinaryFraction) + (table : ℕ → β × σ → BinaryFraction) (eta kappa : BinaryFraction) + (t : ℕ) (i : β × σ) (Be Bk Bm Bt : ℕ) + (he : eta.width ≤ Be) (hk : kappa.width ≤ Bk) (hm : (mass i.1).width ≤ Bm) + (ht : ∀ s ≤ t + 1, (table s i).width ≤ Bt) : + (onlineLinearWithWork mass table eta kappa t i).1.width ≤ + onlineLinearStorageBudget Be Bk Bm Bt t := by + let coefficient := (coefficientWithWork kappa).1 + let terms := (vectorMapWithWork t fun s => optimisticTermWithWork mass table coefficient s.val i).1 + let history := (bandMassTotalWithWork terms).1 + let current := (gainWithWork mass table t i).1 + have hcn := canonicalAddWithWork_self_width one (canonicalMulWithWork (nat 2) kappa).1.neg + change coefficient.width ≤ coefficient.representation.storageBits at hcn + have hc : coefficient.width ≤ 4 * Bk + 18 := hcn.trans (coefficientWithWork_storage kappa Bk hk) + have hterms (s : Fin t) : (terms.get s).width ≤ optimisticTermStorageBudget Bm Bt (4 * Bk + 18) := by + have hs := optimisticTermWithWork_storage mass table coefficient s.val i Bm Bt (4 * Bk + 18) + hm (ht s.val (by omega)) (ht (s.val + 1) (by omega)) hc + simp only [terms, vectorMapWithWork_value] + exact (canonicalAddWithWork_self_width _ _).trans hs + have hh := bandMassTotalWithWork_storage terms (optimisticTermStorageBudget Bm Bt (4 * Bk + 18)) hterms + change history.representation.storageBits ≤ _ at hh + have hg := gainWithWork_storage mass table t i Bm Bt hm (ht t (by omega)) + change current.representation.storageBits ≤ _ at hg + have he' := representation_storageBits_le eta + have ha := UnreducedRational.storageBits_add history.representation current.representation + have hp := UnreducedRational.storageBits_mul eta.representation (history.representation.add current.representation) + change (canonicalMulWithWork eta (canonicalAddWithWork history current).1).1.width ≤ _ + have hw := canonicalMulWithWork_self_width eta (canonicalAddWithWork history current).1 + rw [canonicalMulWithWork_representation, canonicalAddWithWork_representation] at hw + unfold onlineLinearStorageBudget + omega + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryOnlineParameters.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryOnlineParameters.lean new file mode 100644 index 0000000000000000000000000000000000000000..6b93bca57950e2bc977bf17532993aa8ce6e1454 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryOnlineParameters.lean @@ -0,0 +1,62 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryPowerStorage +import OAI.Combinatorics.EditApproximation.Geometry.Parameters +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! The two numerical constants used by online optimization are built from +the binary small-log parameter. Their word widths and construction costs +come from the actual multiplication loops. -/ + +namespace EditApproximation +namespace BinaryFraction + + + +theorem onlineParametersWithWork_eta (ell : List Bool) (hell : 0 < bitWordValue ell) : + (onlineParametersWithWork ell hell).1.1.value = (rationalParameters (bitWordValue ell)).eta := by + simp [onlineParametersWithWork, value, SignedBinary.value, signedMagnitude, + bitPowerWithWork_value, bitWordValue, rationalParameters] + +theorem onlineParametersWithWork_kappa (ell : List Bool) (hell : 0 < bitWordValue ell) : + (onlineParametersWithWork ell hell).1.2.value = (rationalParameters (bitWordValue ell)).kappa := by + simp [onlineParametersWithWork, value, SignedBinary.value, signedMagnitude, + bitPowerWithWork_value, bitWordValue, rationalParameters] + +theorem onlineParametersWithWork_width (ell : List Bool) (hell : 0 < bitWordValue ell) + (B : ℕ) (hB : ell.length ≤ B) : + (onlineParametersWithWork ell hell).1.1.width ≤ 5 * B + 1 ∧ + (onlineParametersWithWork ell hell).1.2.width ≤ 4 * B + 1 := by + have he := bitPowerWithWork_length_le ell 5 B hB + have hk := bitPowerWithWork_length_le ell 4 B hB + simp only [onlineParametersWithWork, width, List.length_cons, List.length_nil] + constructor <;> omega + +theorem onlineParametersWithWork_cost (ell : List Bool) (hell : 0 < bitWordValue ell) + (B : ℕ) (hB : ell.length ≤ B) : + (onlineParametersWithWork ell hell).2 ≤ bitPowerBitBudget 5 B + bitPowerBitBudget 4 B + 2 := + Nat.add_le_add_right + (Nat.add_le_add (bitPowerWithWork_cost ell 5 B hB) (bitPowerWithWork_cost ell 4 B hB)) 2 + +theorem onlineParametersWithWork_range (ell : List Bool) (hell : 0 < bitWordValue ell) + (H : ℕ) (hH : bitWordValue ell ≤ H) : + |(onlineParametersWithWork ell hell).1.1.value| ≤ ((H ^ 5 : ℕ) : ℚ) ∧ + 0 ≤ (onlineParametersWithWork ell hell).1.2.value ∧ + (onlineParametersWithWork ell hell).1.2.value ≤ 1 := by + rw [onlineParametersWithWork_eta, onlineParametersWithWork_kappa] + simp only [rationalParameters] + have hn : (0 : ℚ) ≤ bitWordValue ell := Nat.cast_nonneg _ + have hp : (1 : ℚ) ≤ bitWordValue ell := by exact_mod_cast hell + constructor + · rw [abs_of_nonneg (pow_nonneg hn _), Nat.cast_pow] + exact pow_le_pow_left₀ hn (by exact_mod_cast hH) _ + constructor + · exact div_nonneg (by norm_num) (pow_nonneg hn _) + · exact (div_le_one (pow_pos (lt_of_lt_of_le (by norm_num) hp) _)).mpr + (one_le_pow₀ hp) + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryOnlineReadCosts.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryOnlineReadCosts.lean new file mode 100644 index 0000000000000000000000000000000000000000..6487ed6f244fb2f2c020dde9e7d2e883e2ebeb75 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryOnlineReadCosts.lean @@ -0,0 +1,161 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryBandReadCosts +import OAI.Combinatorics.EditApproximation.Binary.BinaryPreparedOnlineReads + +namespace OAI + +/-! Online sampler arithmetic and lookup costs share one linear read factor. -/ + +namespace EditApproximation +namespace BinaryFraction + +theorem countedPreparedActionReadWithWork_factor {M n : ℕ} (mass : Vector BinaryFraction M) + (read : ℕ → Fin M × TargetInterval n → BinaryFraction × ℕ) + (eta kappa : BinaryFraction) (band : List (Fin M → TargetInterval n)) (G j t R : ℕ) + (hr : ∀ s ≤ t + 1, ∀ i : Fin (listedBandCoordinates band).length, + (read s ((listedBandCoordinateVector band).get i)).2 ≤ R) : + (countedPreparedActionReadWithWork mass read eta kappa band G j t).2 ≤ + (countedPreparedActionWithWork mass (fun s i => (read s i).1) eta kappa band G j t).2 * + tableReadFactor R := by + have hl := vectorMapWithWork_factor (listedBandCoordinates band).length + (fun i => onlineLinearReadWithWork (fun j => mass.get j) read eta kappa t + ((listedBandCoordinateVector band).get i)) + (fun i => onlineLinearWithWork (fun j => mass.get j) (fun s k => (read s k).1) eta kappa t + ((listedBandCoordinateVector band).get i)) + (tableReadFactor R) (tableReadFactor_pos R) + (fun i => (onlineLinearReadWithWork_eq_cost _ read eta kappa t _ R + (fun s hs => hr s hs i)).1) + (fun i => onlineLinearReadWithWork_factor _ read eta kappa t _ R (fun s hs => hr s hs i)) + unfold countedPreparedActionReadWithWork countedPreparedActionWithWork + simp only [coordinateVectorWithWork_value, hl.1] + apply cost_replace_factor _ _ _ _ _ hl.2 (tableReadFactor_pos R) <;> omega + +theorem countedBandActionReadWithWork_factor {M n : ℕ} (b : ℕ) + (initial : Fin M → TargetInterval n → BinaryFraction × ℕ) + (read : ℕ → Fin M × TargetInterval n → BinaryFraction × ℕ) + (eta kappa : BinaryFraction) (band : List (Fin M → TargetInterval n)) (G j t R : ℕ) + (hi : ∀ i q, (initial i q).2 ≤ R) + (hr : ∀ s ≤ t + 1, ∀ i : Fin (listedBandCoordinates band).length, + (read s ((listedBandCoordinateVector band).get i)).2 ≤ R) : + (countedBandActionReadWithWork b initial read eta kappa band G j t).2 ≤ + (countedBandActionWithWork b (fun i q => (initial i q).1) + (fun s i => (read s i).1) eta kappa band G j t).2 * tableReadFactor R := by + have hm := envelopeVectorReadWithWork_factor b band initial R hi + have hmq := (envelopeVectorReadWithWork_eq_cost b band initial R hi).1 + have hs := countedPreparedActionReadWithWork_factor + (envelopeVectorWithWork b band (fun i q => (initial i q).1)).1 read eta kappa band G j t R hr + have h := Nat.add_le_add hm hs + rw [← Nat.add_mul] at h + unfold countedBandActionReadWithWork countedBandActionWithWork + dsimp only + rw [hmq] + apply cost_replace_factor _ _ _ _ _ h (tableReadFactor_pos R) <;> omega + +theorem countedSampledOnlineReadWithWork_factor {n M : ℕ} (center : TargetInterval n) (b : ℕ) + (initial : Fin M → TargetInterval n → BinaryFraction × ℕ) + (read : ℕ → Fin M × TargetInterval n → BinaryFraction × ℕ) + (eta kappa : BinaryFraction) (band : List (Fin M → TargetInterval n)) (hne : band ≠ []) + (G K t R : ℕ) (integer : Fin (optimizerTriangularMass K)) + (hi : ∀ i q, (initial i q).2 ≤ R) + (hr : ∀ s ≤ t + 1, ∀ i : Fin (listedBandCoordinates band).length, + (read s ((listedBandCoordinateVector band).get i)).2 ≤ R) : + (countedSampledOnlineReadWithWork center b initial read eta kappa band hne G K t integer).2 ≤ + (countedSampledOnlineWithWork center b (fun i q => (initial i q).1) + (fun s i => (read s i).1) eta kappa band hne G K t integer).2 * tableReadFactor R := by + have hs := countedBandActionReadWithWork_factor b initial read eta kappa band G + (triangularChoiceWithWork K integer).1.val t R hi hr + unfold countedSampledOnlineReadWithWork countedSampledOnlineWithWork + dsimp only + apply cost_replace_factor _ _ _ _ _ hs (tableReadFactor_pos R) <;> omega + +private def onlineCostCore {n M : ℕ} {Action : Type*} (H integer : ℕ) + (band : List (Fin M → TargetInterval n) × ℕ) (guard : Bool × ℕ) + (sample : (xs : List (Fin M → TargetInterval n)) → xs ≠ [] → (G : ℕ) → + Fin (optimizerTriangularMass (G ^ 80)) → Action × ℕ) : Option Action × ℕ := + let setup := onlineIndexSetupWithWork H band.1 + let accepted := reduceOnlineIntegerWithWork (setup.1 ^ 80) (by + rw [onlineIndexSetupWithWork_value] + positivity) integer + if hband : band.1 = [] then (none, band.2 + setup.2 + accepted.2 + 1) else + if guard.1 then + let sampled := sample band.1 hband setup.1 accepted.1 + (some sampled.1, band.2 + setup.2 + accepted.2 + guard.2 + sampled.2 + 2) + else (none, band.2 + setup.2 + accepted.2 + guard.2 + 1) + +private theorem onlineCostCore_factor {n M : ℕ} {Action : Type*} (H integer : ℕ) + (band plain : List (Fin M → TargetInterval n) × ℕ) (guard plainGuard : Bool × ℕ) + (sample plainSample : (xs : List (Fin M → TargetInterval n)) → xs ≠ [] → (G : ℕ) → + Fin (optimizerTriangularMass (G ^ 80)) → Action × ℕ) + (K : ℕ) (hK : 1 ≤ K) (hb : band.1 = plain.1) (hbc : band.2 ≤ plain.2 * K) + (hg : guard.1 = plainGuard.1) (hgc : guard.2 ≤ plainGuard.2 * K) + (hs : ∀ hne G draw, (sample plain.1 hne G draw).2 ≤ (plainSample plain.1 hne G draw).2 * K) : + (onlineCostCore H integer band guard sample).2 ≤ + (onlineCostCore H integer plain plainGuard plainSample).2 * K := by + rcases band with ⟨xs, cost⟩ + rcases plain with ⟨ys, plainCost⟩ + dsimp only at hb hbc hs ⊢ + subst ys + unfold onlineCostCore + dsimp only + simp only [hg] + split_ifs with he ha + · apply cost_replace_factor _ _ _ _ _ hbc hK <;> omega + · have hG : 0 < (onlineIndexSetupWithWork H xs).1 := by + rw [onlineIndexSetupWithWork_value] + omega + have hsample := hs he (onlineIndexSetupWithWork H xs).1 + (reduceOnlineIntegerWithWork ((onlineIndexSetupWithWork H xs).1 ^ 80) + (pow_pos hG _) integer).1 + have h := Nat.add_le_add (Nat.add_le_add hbc hgc) hsample + simp only [← Nat.add_mul] at h + apply cost_replace_factor _ _ _ _ _ h hK <;> omega + · have h := Nat.add_le_add hbc hgc + rw [← Nat.add_mul] at h + apply cost_replace_factor _ _ _ _ _ h hK <;> omega + +theorem preparedOnlineReadWithWork_factor {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (P F exponent H b : ℕ) (hb : 0 < b) (hP : 0 < P) + (tau eta kappa : BinaryFraction) + (child initial : Fin M → TargetInterval target.length → BinaryFraction × ℕ) + (table : ℕ → Fin M × TargetInterval target.length → BinaryFraction × ℕ) + (R : ℕ) (hc : ∀ i q, (child i q).2 ≤ R) (hi : ∀ i q, (initial i q).2 ≤ R) + (t : ℕ) (center : TargetInterval target.length) (integer : ℕ) + (ht : ∀ s ≤ t + 1, ∀ i, (table s i).2 ≤ R) : + (preparedOnlineReadWithWork source target parent P F exponent H b hb hP tau eta kappa + child initial table R hc hi t center integer).2 ≤ + (preparedOnlineWithWork source target parent P F exponent H b hb hP tau eta kappa + (fun i q => (child i q).1) (fun i q => (initial i q).1) + (fun s i => (table s i).1) t center integer).2 * tableReadFactor R := by + apply onlineCostCore_factor H integer + (preparedRepresentativeReadWithWork parent center (parent.hi - parent.lo) b P tau + (inversePowerTwo exponent) child) + (preparedRepresentativeWithWork parent center (parent.hi - parent.lo) b P tau + (inversePowerTwo exponent) (fun i q => (child i q).1)) + ((preparedUnskippedReadWithWork source target parent b P exponent hb hP tau (nat F) + child initial R R hc hi center).1.isSome, + (preparedUnskippedReadWithWork source target parent b P exponent hb hP tau (nat F) + child initial R R hc hi center).2) + ((preparedUnskippedCandidateWithWork source target parent b P exponent hb hP tau (nat F) + (fun i q => (child i q).1) (fun i q => (initial i q).1) center).1.isSome, + (preparedUnskippedCandidateWithWork source target parent b P exponent hb hP tau (nat F) + (fun i q => (child i q).1) (fun i q => (initial i q).1) center).2) + (fun xs hxs G draw => countedSampledOnlineReadWithWork center b initial table eta kappa + xs hxs G (G ^ 80) t draw) + (fun xs hxs G draw => countedSampledOnlineWithWork center b + (fun i q => (initial i q).1) (fun s i => (table s i).1) eta kappa xs hxs G (G ^ 80) t draw) + (tableReadFactor R) (tableReadFactor_pos R) + · exact (preparedRepresentativeReadWithWork_eq_cost parent center (parent.hi - parent.lo) + b P tau (inversePowerTwo exponent) child R hc).1 + · exact preparedRepresentativeReadWithWork_factor parent center (parent.hi - parent.lo) + b P tau (inversePowerTwo exponent) child R hc + · exact congrArg Option.isSome (preparedUnskippedReadWithWork_value source target parent + b P exponent hb hP tau (nat F) child initial R R hc hi center) + · exact preparedUnskippedReadWithWork_factor source target parent b P exponent hb hP + tau (nat F) child initial R hc hi center + · intro hne G draw + exact countedSampledOnlineReadWithWork_factor center b initial table eta kappa _ hne + G (G ^ 80) t R draw hi (fun s hs i => ht s hs _) + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryOnlineReads.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryOnlineReads.lean new file mode 100644 index 0000000000000000000000000000000000000000..ee24cf9bd3e69eb1c26c3600cb5c1f669bbcd2f0 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryOnlineReads.lean @@ -0,0 +1,98 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryEnvelopeReads +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Online objective construction charges every historical table read, +including repeated uses in gain and decrement terms. -/ + +namespace EditApproximation +namespace BinaryFraction + + + + + +@[simp] theorem gainReadWithWork_eq {β σ : Type*} (mass : β → BinaryFraction) + (read : ℕ → β × σ → BinaryFraction × ℕ) (s : ℕ) (i : β × σ) : + (gainReadWithWork mass read s i).1 = (gainWithWork mass (fun t j => (read t j).1) s i).1 := rfl + +@[simp] theorem decrementReadWithWork_eq {β σ : Type*} (mass : β → BinaryFraction) + (read : ℕ → β × σ → BinaryFraction × ℕ) (s : ℕ) (i : β × σ) : + (decrementReadWithWork mass read s i).1 = (decrementWithWork mass (fun t j => (read t j).1) s i).1 := rfl + + + +@[simp] theorem optimisticTermReadWithWork_eq {β σ : Type*} (mass : β → BinaryFraction) + (read : ℕ → β × σ → BinaryFraction × ℕ) (coefficient : BinaryFraction) + (s : ℕ) (i : β × σ) : + (optimisticTermReadWithWork mass read coefficient s i).1 = + (optimisticTermWithWork mass (fun t j => (read t j).1) coefficient s i).1 := rfl + +theorem optimisticTermReadWithWork_cost {β σ : Type*} (mass : β → BinaryFraction) + (read : ℕ → β × σ → BinaryFraction × ℕ) (coefficient : BinaryFraction) + (s : ℕ) (i : β × σ) (R : ℕ) (hs : (read s i).2 ≤ R) (hs' : (read (s + 1) i).2 ≤ R) : + (optimisticTermReadWithWork mass read coefficient s i).2 ≤ + (optimisticTermWithWork mass (fun t j => (read t j).1) coefficient s i).2 + 3 * R := by + simp only [optimisticTermReadWithWork, optimisticTermWithWork, gainReadWithWork, + decrementReadWithWork, gainWithWork, decrementWithWork] + omega + + + +theorem onlineLinearReadWithWork_eq_cost {β σ : Type*} (mass : β → BinaryFraction) + (read : ℕ → β × σ → BinaryFraction × ℕ) (eta kappa : BinaryFraction) + (t : ℕ) (i : β × σ) (R : ℕ) (hr : ∀ s ≤ t + 1, (read s i).2 ≤ R) : + (onlineLinearReadWithWork mass read eta kappa t i).1 = + (onlineLinearWithWork mass (fun s j => (read s j).1) eta kappa t i).1 ∧ + (onlineLinearReadWithWork mass read eta kappa t i).2 ≤ + (onlineLinearWithWork mass (fun s j => (read s j).1) eta kappa t i).2 + (3 * t + 1) * R := by + have ht := vectorMapWithWork_extra t + (fun s => optimisticTermReadWithWork mass read (coefficientWithWork kappa).1 s.val i) + (fun s => optimisticTermWithWork mass (fun t j => (read t j).1) (coefficientWithWork kappa).1 s.val i) + (3 * R) (fun _ => rfl) (fun s => optimisticTermReadWithWork_cost mass read _ s.val i R + (hr _ (by omega)) (hr _ (by omega))) + have hcur := hr t (by omega) + unfold onlineLinearReadWithWork onlineLinearWithWork + dsimp only + rw [ht.1] + refine ⟨rfl, ?_⟩ + simp only [gainReadWithWork, gainWithWork] + nlinarith only [ht.2, hcur] + +def preparedBandOptimizerReadWithWork {M d : ℕ} {σ : Type*} [DecidableEq σ] + (coordinates : Vector (Fin M × σ) d) (mass : Vector BinaryFraction M) + (read : ℕ → Fin M × σ → BinaryFraction × ℕ) (eta kappa : BinaryFraction) + (band : List (Fin M → σ)) (G K t : ℕ) : Vector BinaryFraction d × ℕ := + let vertices := bandVerticesWithWork coordinates mass band + let linear := vectorMapWithWork d fun i => + onlineLinearReadWithWork (fun j => mass.get j) read eta kappa t (coordinates.get i) + let answer := finiteOptimizerWithWork vertices.1 linear.1 G K + (answer.1, vertices.2 + linear.2 + answer.2 + 2) + +theorem preparedBandOptimizerReadWithWork_eq_cost {M d : ℕ} {σ : Type*} [DecidableEq σ] + (coordinates : Vector (Fin M × σ) d) (mass : Vector BinaryFraction M) + (read : ℕ → Fin M × σ → BinaryFraction × ℕ) (eta kappa : BinaryFraction) + (band : List (Fin M → σ)) (G K t R : ℕ) + (hr : ∀ s ≤ t + 1, ∀ i, (read s (coordinates.get i)).2 ≤ R) : + (preparedBandOptimizerReadWithWork coordinates mass read eta kappa band G K t).1 = + (preparedBandOptimizerWithWork coordinates mass (fun s j => (read s j).1) eta kappa band G K t).1 ∧ + (preparedBandOptimizerReadWithWork coordinates mass read eta kappa band G K t).2 ≤ + (preparedBandOptimizerWithWork coordinates mass (fun s j => (read s j).1) eta kappa band G K t).2 + + d * ((3 * t + 1) * R) := by + have hl := vectorMapWithWork_extra d + (fun i => onlineLinearReadWithWork (fun j => mass.get j) read eta kappa t (coordinates.get i)) + (fun i => onlineLinearWithWork (fun j => mass.get j) (fun s j => (read s j).1) eta kappa t (coordinates.get i)) + ((3 * t + 1) * R) + (fun i => (onlineLinearReadWithWork_eq_cost _ read eta kappa t (coordinates.get i) R (fun s hs => hr s hs i)).1) + (fun i => (onlineLinearReadWithWork_eq_cost _ read eta kappa t (coordinates.get i) R (fun s hs => hr s hs i)).2) + unfold preparedBandOptimizerReadWithWork preparedBandOptimizerWithWork + dsimp only + rw [hl.1] + exact ⟨rfl, by omega⟩ + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryOnlineSetupWork.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryOnlineSetupWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..ae866de9acc43871452fb93b7d879510b34c41d9 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryOnlineSetupWork.lean @@ -0,0 +1,90 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryKeyedOnline +import OAI.Combinatorics.EditApproximation.Binary.BinaryCoordinateActionWork +import OAI.Combinatorics.EditApproximation.Binary.BinaryLocalGridWork + +namespace OAI + +/-! Actual coordinate enumeration, index construction and range reduction +preceding the online optimizer, counted in Boolean operations. -/ + +namespace EditApproximation +namespace BinaryFraction + +def onlineIndexBitBudget (M vertices B : ℕ) : ℕ := + bandCoordinatesBitBudget M vertices B + 40 * (B + 4) + + bitPowerBitBudget 80 (B + 4) + 3 + +theorem onlineIndexSetupWithWork_bounds {M n : ℕ} (H B : ℕ) + (band : List (Fin M → TargetInterval n)) + (_hB : 2 ≤ B) (hH : Nat.size H ≤ B) (hM : Nat.size M ≤ B) + (hn : Nat.size n ≤ B) (hd : Nat.size (listedBandCoordinates band).length ≤ B) : + Nat.size (onlineIndexSetupWithWork H band).1 ≤ B + 4 ∧ + (onlineIndexSetupWithWork H band).2 ≤ onlineIndexBitBudget M band.length B := by + let coordinates := bandCoordinatesWithWork band + let total := binaryNaturalAddWithWork H coordinates.1.length + let offset := binaryNaturalAddWithWork (bitWordValue total.1) 2 + have hcoord := bandCoordinatesWithWork_cost band B hM hn + have hd' : Nat.size coordinates.1.length ≤ B := by + simpa only [coordinates, bandCoordinatesWithWork_value] using hd + have htotal : Nat.size (bitWordValue total.1) ≤ B + 2 := by + rw [binaryNaturalAddWithWork_value] + exact (binaryNaturalAdd_size_le _ _).trans (by omega) + have hoffset : offset.1.length ≤ B + 4 := by + have hh := bitAddWithWork_length (bitWordValue total.1).bits (2 : ℕ).bits false + change offset.1.length ≤ _ at hh + rw [Nat.size_eq_bits_len, Nat.size_eq_bits_len] at hh + have htwo : Nat.size 2 = 2 := by decide + omega + have hsize : Nat.size (bitWordValue offset.1) ≤ B + 4 := + (Nat.size_le.mpr (bitWordValue_lt_pow_length offset.1)).trans hoffset + have hsumc := binaryNaturalAddWithWork_cost H coordinates.1.length + have hoffc := binaryNaturalAddWithWork_cost (bitWordValue total.1) 2 + have hpower := bitPowerWithWork_cost offset.1 80 (B + 4) hoffset + have htwo : Nat.size 2 = 2 := by decide + constructor + · exact hsize + · change coordinates.2 + total.2 + offset.2 + (bitPowerWithWork offset.1 80).2 + 3 ≤ _ + change coordinates.2 ≤ _ at hcoord + change total.2 ≤ _ at hsumc + change offset.2 ≤ _ at hoffc + rw [htwo] at hoffc + unfold onlineIndexBitBudget + omega + +def reduceOnlineBitBudget (B : ℕ) : ℕ := + 10000 * (B + 3) ^ 2 + 200 * (4 * B + 6) ^ 2 + B + 2 + +theorem reduceOnlineIntegerWithWork_bounds (K integer B : ℕ) (hK : 0 < K) + (hKB : Nat.size K ≤ B) (hi : Nat.size integer ≤ B) : + Nat.size (reduceOnlineIntegerWithWork K hK integer).1.val ≤ 3 * B + 4 ∧ + (reduceOnlineIntegerWithWork K hK integer).2 ≤ reduceOnlineBitBudget B := by + let mass := triangularMassWithWork K + have hm := triangularMassWithWork_bounds K B hKB + have hms : Nat.size (bitWordValue mass.1) ≤ 3 * B + 4 := + (Nat.size_le.mpr (bitWordValue_lt_pow_length mass.1)).trans hm.1 + have hpos : 0 < bitWordValue mass.1 := by + rw [triangularMassWithWork_value] + exact optimizerTriangularMass_positive K hK + have hsmall := (binaryNaturalDivModWithWork_spec integer (bitWordValue mass.1) hpos).2 + have hrem : Nat.size (bitWordValue (binaryNaturalDivModWithWork integer (bitWordValue mass.1)).2.1) ≤ + 3 * B + 4 := by + rw [hsmall] + exact (Nat.size_le_size (Nat.mod_lt integer hpos).le).trans hms + have hc := binaryNaturalDivModWithWork_cost integer (bitWordValue mass.1) + constructor + · exact hrem + · change mass.2 + (binaryNaturalDivModWithWork integer (bitWordValue mass.1)).2.2 + Nat.size integer + 2 ≤ _ + have hmc : mass.2 ≤ 10000 * (B + 3) ^ 2 := hm.2 + unfold reduceOnlineBitBudget + have hprod : (Nat.size integer + 1) * (Nat.size integer + Nat.size (bitWordValue mass.1) + 1) ≤ + (4 * B + 6) ^ 2 := by + rw [pow_two] + exact Nat.mul_le_mul (by omega) (by omega) + have h30 := Nat.mul_le_mul_left 30 hprod + rw [Nat.mul_assoc] at hc + omega + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryOnlineSourceSpace.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryOnlineSourceSpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..52df76c625e02e6077fcbb1bf14fecb707eb3db1 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryOnlineSourceSpace.lean @@ -0,0 +1,109 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinarySampledOnlineSpace +import OAI.Combinatorics.EditApproximation.Queries.QueryOnlineRangeSpace +import OAI.Combinatorics.EditApproximation.Binary.BinaryUnskippedSpace +import OAI.Combinatorics.EditApproximation.Binary.BinaryLocalOnlineSource +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation + + + +theorem reduceOnlineIntegerAllocation_le_work (K integer : ℕ) (hK : 0 < K) : + reduceOnlineIntegerAllocation K integer ≤ (BinaryFraction.reduceOnlineIntegerWithWork K hK integer).2 := by + have ht := triangularMassAllocation_le_work K + have hd := bitDivModAllocation_le_work (bitWordValue (triangularMassWithWork K).1).bits integer.bits + unfold reduceOnlineIntegerAllocation BinaryFraction.reduceOnlineIntegerWithWork binaryNaturalDivModWithWork + dsimp only + omega + +/-- The only multiplicative allowance needed by the labeled optimizer. -/ +theorem filterMapAllocation_le_three_work {α β : Type*} (f : α → Option β × ℕ) + (allocation : α → ℕ) (xs : List α) (h : ∀ x ∈ xs, allocation x ≤ 3 * (f x).2) : + filterMapAllocation f allocation xs ≤ 3 * (filterMapWithWork f xs).2 := by + induction xs with + | nil => rfl + | cons x xs ih => + have hx := h x List.mem_cons_self + have ht := ih (fun y hy => h y (List.mem_cons_of_mem _ hy)) + simp only [filterMapAllocation, filterMapWithWork] + cases he : (f x).1 <;> simp only [Option.isSome, Bool.false_eq_true, ↓reduceIte] <;> omega + +namespace BinaryFraction +section Online +variable {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (P F exponent H b : ℕ) (hb : 0 < b) (hP : 0 < P) + (tau eta kappa : BinaryFraction) + (child initial : Fin M → TargetInterval target.length → BinaryFraction × ℕ) + (table : ℕ → Fin M × TargetInterval target.length → BinaryFraction × ℕ) + (R : ℕ) (hc : ∀ i q, (child i q).2 ≤ R) (hi : ∀ i q, (initial i q).2 ≤ R) + (childAllocation initialAllocation : Fin M → TargetInterval target.length → ℕ) + (tableAllocation : ℕ → Fin M × TargetInterval target.length → ℕ) + +def preparedOnlineReadAllocation (t : ℕ) (center : TargetInterval target.length) (integer : ℕ) : ℕ := + let band := (preparedRepresentativeReadWithWork parent center (parent.hi - parent.lo) b P + tau (inversePowerTwo exponent) child).1 + let G := (onlineIndexSetupWithWork H band).1 + let accepted := (reduceOnlineIntegerWithWork (G ^ 80) (by + dsimp only [G]; rw [onlineIndexSetupWithWork_value]; positivity) integer).1 + preparedRepresentativeReadAllocation parent center (parent.hi - parent.lo) b P + tau (inversePowerTwo exponent) child childAllocation + + onlineIndexSetupAllocation H band + reduceOnlineIntegerAllocation (G ^ 80) integer + + if hband : band = [] then 0 else + preparedUnskippedReadAllocation parent center b P exponent tau (nat F) + child initial childAllocation initialAllocation + + if (preparedUnskippedReadWithWork source target parent b P exponent hb hP tau (nat F) + child initial R R hc hi center).1.isSome then + countedSampledOnlineAllocation center b initial initialAllocation table tableAllocation eta kappa + band hband G (G ^ 80) t accepted + 1 + else 0 + +theorem preparedOnlineReadAllocation_le_work (t : ℕ) (center : TargetInterval target.length) (integer : ℕ) + (hca : ∀ i q, childAllocation i q ≤ (child i q).2) + (hia : ∀ i q, initialAllocation i q ≤ (initial i q).2) + (hta : ∀ s q, tableAllocation s q ≤ (table s q).2) : + preparedOnlineReadAllocation source target parent P F exponent H b hb hP tau eta kappa child initial table + R hc hi childAllocation initialAllocation tableAllocation t center integer ≤ + 3 * (preparedOnlineReadWithWork source target parent P F exponent H b hb hP tau eta kappa + child initial table R hc hi t center integer).2 := by + have emptyBound (b b' s s' r r' : ℕ) (hb : b ≤ b') (hs : s ≤ s') (hr : r ≤ r') : + b + s + r + 0 ≤ 3 * (b' + s' + r' + 1) := by + omega + have selectedBound (b b' s s' r r' g g' a a' : ℕ) + (hb : b ≤ b') (hs : s ≤ s') (hr : r ≤ r') (hg : g ≤ g') (ha : a ≤ 3 * a') : + b + s + r + (g + (a + 1)) ≤ 3 * (b' + s' + r' + g' + a' + 2) := by + omega + have rejectedBound (b b' s s' r r' g g' : ℕ) + (hb : b ≤ b') (hs : s ≤ s') (hr : r ≤ r') (hg : g ≤ g') : + b + s + r + (g + 0) ≤ 3 * (b' + s' + r' + g' + 1) := by + omega + let band := (preparedRepresentativeReadWithWork parent center (parent.hi - parent.lo) b P + tau (inversePowerTwo exponent) child).1 + let G := (onlineIndexSetupWithWork H band).1 + have hG : 0 < G ^ 80 := by dsimp only [G]; rw [onlineIndexSetupWithWork_value]; positivity + let accepted := (reduceOnlineIntegerWithWork (G ^ 80) hG integer).1 + have hbnd := preparedRepresentativeReadAllocation_le_work parent center (parent.hi - parent.lo) b P + tau (inversePowerTwo exponent) child childAllocation hca + have hsetup := onlineIndexSetupAllocation_le_work H band + have hreduce := reduceOnlineIntegerAllocation_le_work (G ^ 80) integer hG + have hguard := preparedUnskippedReadAllocation_le_work source target parent center b P exponent hb hP + tau (nat F) child initial childAllocation initialAllocation R R hc hi hca hia + unfold preparedOnlineReadAllocation preparedOnlineReadWithWork + dsimp only + split_ifs with he hg + · dsimp only [band, G] at hsetup hreduce + exact emptyBound _ _ _ _ _ _ hbnd hsetup hreduce + · have hsample := countedSampledOnlineAllocation_le_work center b initial initialAllocation table tableAllocation + eta kappa band he G (G ^ 80) t accepted hia hta + dsimp only [band, G, accepted] at hsetup hreduce hsample + exact selectedBound _ _ _ _ _ _ _ _ _ _ hbnd hsetup hreduce hguard hsample + · dsimp only [band, G] at hsetup hreduce + exact rejectedBound _ _ _ _ _ _ _ _ hbnd hsetup hreduce hguard + +end Online +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryOnlineSpace.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryOnlineSpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..5407d1e1a5143b83e064388ff26d583dbeab59fc --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryOnlineSpace.lean @@ -0,0 +1,261 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryBandStorage +import OAI.Combinatorics.EditApproximation.Binary.BinaryOnlineReads +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! The online objective includes every repeated history-buffer read. +Its allocation and frame counters follow the same Boolean arithmetic and +materialized vector passes as the executed continuation. -/ + +namespace EditApproximation.BinaryFraction + + + +theorem coefficientAllocation_le_work (kappa : BinaryFraction) : + coefficientAllocation kappa ≤ (coefficientWithWork kappa).2 := by + have h1 := canonicalMulAllocation_le_work (nat 2) kappa + have h2 := subAllocation_le_work one (canonicalMulWithWork (nat 2) kappa).1 + unfold coefficientAllocation coefficientWithWork + dsimp only + omega + + + +theorem gainReadAllocation_le_work {β σ : Type*} (mass : β → BinaryFraction) + (read : ℕ → β × σ → BinaryFraction × ℕ) (footprint : ℕ → β × σ → ℕ) + (s : ℕ) (i : β × σ) (h : footprint s i ≤ (read s i).2) : + gainReadAllocation mass read footprint s i ≤ (gainReadWithWork mass read s i).2 := by + have hd := divAllocation_le_work (read s i).1.neg (mass i.1) + unfold gainReadAllocation gainReadWithWork + dsimp only + omega + + + +theorem decrementReadAllocation_le_work {β σ : Type*} (mass : β → BinaryFraction) + (read : ℕ → β × σ → BinaryFraction × ℕ) (footprint : ℕ → β × σ → ℕ) + (s : ℕ) (i : β × σ) (h : footprint s i ≤ (read s i).2) + (hnext : footprint (s + 1) i ≤ (read (s + 1) i).2) : + decrementReadAllocation mass read footprint s i ≤ (decrementReadWithWork mass read s i).2 := by + have hs := subAllocation_le_work (read s i).1 (read (s + 1) i).1 + have hd := divAllocation_le_work (subWithWork (read s i).1 (read (s + 1) i).1).1 (mass i.1) + unfold decrementReadAllocation decrementReadWithWork + dsimp only + omega + + + +theorem optimisticTermReadAllocation_le_work {β σ : Type*} (mass : β → BinaryFraction) + (read : ℕ → β × σ → BinaryFraction × ℕ) (footprint : ℕ → β × σ → ℕ) + (coefficient : BinaryFraction) (s : ℕ) (i : β × σ) + (h : footprint s i ≤ (read s i).2) (hnext : footprint (s + 1) i ≤ (read (s + 1) i).2) : + optimisticTermReadAllocation mass read footprint coefficient s i ≤ + (optimisticTermReadWithWork mass read coefficient s i).2 := by + have hg := gainReadAllocation_le_work mass read footprint s i h + have hd := decrementReadAllocation_le_work mass read footprint s i h hnext + have hm := canonicalMulAllocation_le_work coefficient (decrementReadWithWork mass read s i).1 + have ha := canonicalAddAllocation_le_work (gainReadWithWork mass read s i).1 + (canonicalMulWithWork coefficient (decrementReadWithWork mass read s i).1).1 + unfold optimisticTermReadAllocation optimisticTermReadWithWork + dsimp only + omega + + + +theorem onlineLinearReadAllocation_le_work {β σ : Type*} (mass : β → BinaryFraction) + (read : ℕ → β × σ → BinaryFraction × ℕ) (footprint : ℕ → β × σ → ℕ) + (eta kappa : BinaryFraction) (t : ℕ) (i : β × σ) + (h : ∀ s ≤ t + 1, footprint s i ≤ (read s i).2) : + onlineLinearReadAllocation mass read footprint eta kappa t i ≤ + (onlineLinearReadWithWork mass read eta kappa t i).2 := by + have hc := coefficientAllocation_le_work kappa + have ht := vectorMapAllocation_le_work t + (fun s => optimisticTermReadWithWork mass read (coefficientWithWork kappa).1 s.val i) + (fun s => optimisticTermReadAllocation mass read footprint (coefficientWithWork kappa).1 s.val i) + (fun s => optimisticTermReadAllocation_le_work mass read footprint _ s.val i + (h _ (by omega)) (h _ (by omega))) + let terms := (vectorMapWithWork t fun s => + optimisticTermReadWithWork mass read (coefficientWithWork kappa).1 s.val i).1 + have hh := bandMassAllocation_le_work terms + have hg := gainReadAllocation_le_work mass read footprint t i (h _ (by omega)) + have ha := canonicalAddAllocation_le_work (bandMassTotalWithWork terms).1 (gainReadWithWork mass read t i).1 + have hm := canonicalMulAllocation_le_work eta (canonicalAddWithWork (bandMassTotalWithWork terms).1 + (gainReadWithWork mass read t i).1).1 + unfold onlineLinearReadAllocation onlineLinearReadWithWork + dsimp only + dsimp only [terms] at hh ha hm + omega + +def coefficientInvocations (kappa : BinaryFraction) : ℕ := + canonicalMulInvocations (nat 2) kappa + subInvocations one (canonicalMulWithWork (nat 2) kappa).1 + 1 + +theorem coefficientInvocations_le_work (kappa : BinaryFraction) : + coefficientInvocations kappa ≤ (coefficientWithWork kappa).2 := by + have h1 := canonicalMulInvocations_le_work (nat 2) kappa + have h2 := subInvocations_le_work one (canonicalMulWithWork (nat 2) kappa).1 + unfold coefficientInvocations coefficientWithWork + dsimp only + omega + +def gainReadInvocations {β σ : Type*} (mass : β → BinaryFraction) + (read : ℕ → β × σ → BinaryFraction × ℕ) (footprint : ℕ → β × σ → ℕ) + (s : ℕ) (i : β × σ) : ℕ := + footprint s i + divInvocations (read s i).1.neg (mass i.1) + 1 + +theorem gainReadInvocations_le_work {β σ : Type*} (mass : β → BinaryFraction) + (read : ℕ → β × σ → BinaryFraction × ℕ) (footprint : ℕ → β × σ → ℕ) + (s : ℕ) (i : β × σ) (h : footprint s i ≤ (read s i).2) : + gainReadInvocations mass read footprint s i ≤ (gainReadWithWork mass read s i).2 := by + have hd := divInvocations_le_work (read s i).1.neg (mass i.1) + unfold gainReadInvocations gainReadWithWork + dsimp only + omega + +def decrementReadInvocations {β σ : Type*} (mass : β → BinaryFraction) + (read : ℕ → β × σ → BinaryFraction × ℕ) (footprint : ℕ → β × σ → ℕ) + (s : ℕ) (i : β × σ) : ℕ := + footprint s i + footprint (s + 1) i + subInvocations (read s i).1 (read (s + 1) i).1 + + divInvocations (subWithWork (read s i).1 (read (s + 1) i).1).1 (mass i.1) + 1 + +theorem decrementReadInvocations_le_work {β σ : Type*} (mass : β → BinaryFraction) + (read : ℕ → β × σ → BinaryFraction × ℕ) (footprint : ℕ → β × σ → ℕ) + (s : ℕ) (i : β × σ) (h : footprint s i ≤ (read s i).2) + (hnext : footprint (s + 1) i ≤ (read (s + 1) i).2) : + decrementReadInvocations mass read footprint s i ≤ (decrementReadWithWork mass read s i).2 := by + have hs := subInvocations_le_work (read s i).1 (read (s + 1) i).1 + have hd := divInvocations_le_work (subWithWork (read s i).1 (read (s + 1) i).1).1 (mass i.1) + unfold decrementReadInvocations decrementReadWithWork + dsimp only + omega + +def optimisticTermReadInvocations {β σ : Type*} (mass : β → BinaryFraction) + (read : ℕ → β × σ → BinaryFraction × ℕ) (footprint : ℕ → β × σ → ℕ) + (coefficient : BinaryFraction) (s : ℕ) (i : β × σ) : ℕ := + let gain := (gainReadWithWork mass read s i).1 + let decrement := (decrementReadWithWork mass read s i).1 + gainReadInvocations mass read footprint s i + decrementReadInvocations mass read footprint s i + + canonicalMulInvocations coefficient decrement + + canonicalAddInvocations gain (canonicalMulWithWork coefficient decrement).1 + 1 + +theorem optimisticTermReadInvocations_le_work {β σ : Type*} (mass : β → BinaryFraction) + (read : ℕ → β × σ → BinaryFraction × ℕ) (footprint : ℕ → β × σ → ℕ) + (coefficient : BinaryFraction) (s : ℕ) (i : β × σ) + (h : footprint s i ≤ (read s i).2) (hnext : footprint (s + 1) i ≤ (read (s + 1) i).2) : + optimisticTermReadInvocations mass read footprint coefficient s i ≤ + (optimisticTermReadWithWork mass read coefficient s i).2 := by + have hg := gainReadInvocations_le_work mass read footprint s i h + have hd := decrementReadInvocations_le_work mass read footprint s i h hnext + have hm := canonicalMulInvocations_le_work coefficient (decrementReadWithWork mass read s i).1 + have ha := canonicalAddInvocations_le_work (gainReadWithWork mass read s i).1 + (canonicalMulWithWork coefficient (decrementReadWithWork mass read s i).1).1 + unfold optimisticTermReadInvocations optimisticTermReadWithWork + dsimp only + omega + +def onlineLinearReadInvocations {β σ : Type*} (mass : β → BinaryFraction) + (read : ℕ → β × σ → BinaryFraction × ℕ) (footprint : ℕ → β × σ → ℕ) + (eta kappa : BinaryFraction) (t : ℕ) (i : β × σ) : ℕ := + let coefficient := (coefficientWithWork kappa).1 + let terms := (vectorMapWithWork t fun s => optimisticTermReadWithWork mass read coefficient s.val i).1 + let history := (bandMassTotalWithWork terms).1 + let current := (gainReadWithWork mass read t i).1 + coefficientInvocations kappa + + vectorMapInvocations t (fun s => optimisticTermReadInvocations mass read footprint coefficient s.val i) + + bandMassInvocations terms + gainReadInvocations mass read footprint t i + canonicalAddInvocations history current + + canonicalMulInvocations eta (canonicalAddWithWork history current).1 + 1 + +theorem onlineLinearReadInvocations_le_work {β σ : Type*} (mass : β → BinaryFraction) + (read : ℕ → β × σ → BinaryFraction × ℕ) (footprint : ℕ → β × σ → ℕ) + (eta kappa : BinaryFraction) (t : ℕ) (i : β × σ) + (h : ∀ s ≤ t + 1, footprint s i ≤ (read s i).2) : + onlineLinearReadInvocations mass read footprint eta kappa t i ≤ + (onlineLinearReadWithWork mass read eta kappa t i).2 := by + have hc := coefficientInvocations_le_work kappa + have ht := vectorMapInvocations_le_work_add_one t + (fun s => optimisticTermReadWithWork mass read (coefficientWithWork kappa).1 s.val i) + (fun s => optimisticTermReadInvocations mass read footprint (coefficientWithWork kappa).1 s.val i) + (fun s => optimisticTermReadInvocations_le_work mass read footprint _ s.val i + (h _ (by omega)) (h _ (by omega))) + let terms := (vectorMapWithWork t fun s => + optimisticTermReadWithWork mass read (coefficientWithWork kappa).1 s.val i).1 + have hh := bandMassInvocations_le_work terms + have hg := gainReadInvocations_le_work mass read footprint t i (h _ (by omega)) + have ha := canonicalAddInvocations_le_work (bandMassTotalWithWork terms).1 (gainReadWithWork mass read t i).1 + have hm := canonicalMulInvocations_le_work eta (canonicalAddWithWork (bandMassTotalWithWork terms).1 + (gainReadWithWork mass read t i).1).1 + unfold onlineLinearReadInvocations onlineLinearReadWithWork + dsimp only + dsimp only [terms] at hh ha hm + omega + +def preparedOptimizerReadAllocation {M d : ℕ} {σ : Type*} [DecidableEq σ] + (coordinates : Vector (Fin M × σ) d) (mass : Vector BinaryFraction M) + (read : ℕ → Fin M × σ → BinaryFraction × ℕ) + (footprint : ℕ → Fin M × σ → ℕ) (eta kappa : BinaryFraction) + (band : List (Fin M → σ)) (G K t : ℕ) : ℕ := + let vertices := (bandVerticesWithWork coordinates mass band).1 + let linear := (vectorMapWithWork d fun i => + onlineLinearReadWithWork (fun j => mass.get j) read eta kappa t (coordinates.get i)).1 + bandVerticesAllocation coordinates mass band + + vectorMapAllocation d (fun i => onlineLinearReadAllocation + (fun j => mass.get j) read footprint eta kappa t (coordinates.get i)) + + optimizerAllocation vertices linear G K + +def preparedOptimizerReadInvocations {M d : ℕ} {σ : Type*} [DecidableEq σ] + (coordinates : Vector (Fin M × σ) d) (mass : Vector BinaryFraction M) + (read : ℕ → Fin M × σ → BinaryFraction × ℕ) + (footprint : ℕ → Fin M × σ → ℕ) (eta kappa : BinaryFraction) + (band : List (Fin M → σ)) (G K t : ℕ) : ℕ := + let vertices := (bandVerticesWithWork coordinates mass band).1 + let linear := (vectorMapWithWork d fun i => + onlineLinearReadWithWork (fun j => mass.get j) read eta kappa t (coordinates.get i)).1 + bandVerticesInvocations coordinates mass band + + vectorMapInvocations d (fun i => onlineLinearReadInvocations + (fun j => mass.get j) read footprint eta kappa t (coordinates.get i)) + + optimizerInvocations vertices linear G K + 1 + +theorem preparedOptimizerReadAllocation_le_work {M d : ℕ} {σ : Type*} [DecidableEq σ] + (coordinates : Vector (Fin M × σ) d) (mass : Vector BinaryFraction M) + (read : ℕ → Fin M × σ → BinaryFraction × ℕ) + (footprint : ℕ → Fin M × σ → ℕ) (eta kappa : BinaryFraction) + (band : List (Fin M → σ)) (G K t : ℕ) + (h : ∀ s ≤ t + 1, ∀ i, footprint s (coordinates.get i) ≤ (read s (coordinates.get i)).2) : + preparedOptimizerReadAllocation coordinates mass read footprint eta kappa band G K t ≤ + (preparedBandOptimizerReadWithWork coordinates mass read eta kappa band G K t).2 := by + have hv := bandVerticesAllocation_le_work coordinates mass band + have hl := vectorMapAllocation_le_work d + (fun i => onlineLinearReadWithWork (fun j => mass.get j) read eta kappa t (coordinates.get i)) + (fun i => onlineLinearReadAllocation (fun j => mass.get j) read footprint eta kappa t (coordinates.get i)) + (fun i => onlineLinearReadAllocation_le_work _ _ _ _ _ _ _ (fun s hs => h s hs i)) + have ho := optimizerAllocation_le_work (bandVerticesWithWork coordinates mass band).1 + (vectorMapWithWork d fun i => + onlineLinearReadWithWork (fun j => mass.get j) read eta kappa t (coordinates.get i)).1 G K + unfold preparedOptimizerReadAllocation preparedBandOptimizerReadWithWork + dsimp only + omega + +theorem preparedOptimizerReadInvocations_le_work_add_one {M d : ℕ} {σ : Type*} [DecidableEq σ] + (coordinates : Vector (Fin M × σ) d) (mass : Vector BinaryFraction M) + (read : ℕ → Fin M × σ → BinaryFraction × ℕ) + (footprint : ℕ → Fin M × σ → ℕ) (eta kappa : BinaryFraction) + (band : List (Fin M → σ)) (G K t : ℕ) + (h : ∀ s ≤ t + 1, ∀ i, footprint s (coordinates.get i) ≤ (read s (coordinates.get i)).2) : + preparedOptimizerReadInvocations coordinates mass read footprint eta kappa band G K t ≤ + (preparedBandOptimizerReadWithWork coordinates mass read eta kappa band G K t).2 + 1 := by + have hv := bandVerticesInvocations_le_work_add_one coordinates mass band + have hl := vectorMapInvocations_le_work_add_one d + (fun i => onlineLinearReadWithWork (fun j => mass.get j) read eta kappa t (coordinates.get i)) + (fun i => onlineLinearReadInvocations (fun j => mass.get j) read footprint eta kappa t (coordinates.get i)) + (fun i => onlineLinearReadInvocations_le_work _ _ _ _ _ _ _ (fun s hs => h s hs i)) + have ho := optimizerInvocations_le_work (bandVerticesWithWork coordinates mass band).1 + (vectorMapWithWork d fun i => + onlineLinearReadWithWork (fun j => mass.get j) read eta kappa t (coordinates.get i)).1 G K + unfold preparedOptimizerReadInvocations preparedBandOptimizerReadWithWork + dsimp only + omega + +end EditApproximation.BinaryFraction + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryOptimizerSpace.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryOptimizerSpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..0dbd396e88bc1b5f5ade02eea3d2fa833af6b0db --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryOptimizerSpace.lean @@ -0,0 +1,242 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryNumericSpace +import OAI.Combinatorics.EditApproximation.Binary.BinaryRawOptimizer +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Fresh list cells and primitive call frames of the materialized Boolean +optimizer. Intermediate vectors may all remain live; the counters include +every optimizer iteration and every candidate score. -/ + +namespace EditApproximation + + + +def vectorMapInvocations (d : ℕ) (invocations : Fin d → ℕ) : ℕ := + (∑ i, invocations i) + 3 * d + 1 + +theorem vectorMapAllocation_le_work {α : Type*} (d : ℕ) (f : Fin d → α × ℕ) + (allocation : Fin d → ℕ) (h : ∀ i, allocation i ≤ (f i).2) : + vectorMapAllocation d allocation ≤ (vectorMapWithWork d f).2 := by + have hs := Finset.sum_le_sum (fun (i : Fin d) (_ : i ∈ Finset.univ) => h i) + have he : ((Vector.ofFn f).map Prod.snd).toList.sum = ∑ i : Fin d, (f i).2 := by + simp only [Vector.toList_map, Vector.toList_ofFn, List.map_ofFn, Function.comp_def, + List.sum_ofFn] + unfold vectorMapAllocation vectorMapWithWork + dsimp only + rw [he] + omega + +theorem vectorMapInvocations_le_work_add_one {α : Type*} (d : ℕ) (f : Fin d → α × ℕ) + (invocations : Fin d → ℕ) (h : ∀ i, invocations i ≤ (f i).2) : + vectorMapInvocations d invocations ≤ (vectorMapWithWork d f).2 + 1 := by + have hs := Finset.sum_le_sum (fun (i : Fin d) (_ : i ∈ Finset.univ) => h i) + have he : ((Vector.ofFn f).map Prod.snd).toList.sum = ∑ i : Fin d, (f i).2 := by + simp only [Vector.toList_map, Vector.toList_ofFn, List.map_ofFn, Function.comp_def, + List.sum_ofFn] + unfold vectorMapInvocations vectorMapWithWork + dsimp only + rw [he] + omega + +namespace BinaryFraction + + + +def gradientInvocations {d : ℕ} (G : ℕ) (linear point : Vector BinaryFraction d) : ℕ := + vectorMapInvocations d (gradientCellInvocations G linear point) + +theorem gradientAllocation_le_work {d : ℕ} (G : ℕ) (linear point : Vector BinaryFraction d) : + gradientAllocation G linear point ≤ (gradientWithWork G linear point).2 := + vectorMapAllocation_le_work d _ _ (gradientCellAllocation_le_work G linear point) + +theorem gradientInvocations_le_work_add_one {d : ℕ} (G : ℕ) (linear point : Vector BinaryFraction d) : + gradientInvocations G linear point ≤ (gradientWithWork G linear point).2 + 1 := + vectorMapInvocations_le_work_add_one d _ _ (gradientCellInvocations_le_work G linear point) + + + +def scoredArgmaxInvocations {α : Type*} (score : α → BinaryFraction × ℕ) + (invocations : α → ℕ) : List α → ℕ + | [] => 1 + | a :: rest => + scoredArgmaxInvocations score invocations rest + invocations a + + match (scoredArgmaxWithWork score rest).1 with + | none => 1 + | some best => compareInvocations (score a).1 best.2 + 1 + +theorem scoredArgmaxAllocation_le_work {α : Type*} (score : α → BinaryFraction × ℕ) + (allocation : α → ℕ) (xs : List α) (h : ∀ a ∈ xs, allocation a ≤ (score a).2) : + scoredArgmaxAllocation score allocation xs ≤ (scoredArgmaxWithWork score xs).2 := by + induction xs with + | nil => rfl + | cons a xs ih => + have ha := h a List.mem_cons_self + have ht := ih (fun b hb => h b (List.mem_cons_of_mem _ hb)) + simp only [scoredArgmaxAllocation, scoredArgmaxWithWork] + cases he : (scoredArgmaxWithWork score xs).1 with + | none => dsimp only; omega + | some best => + have hc := ltAllocation_le_work (score a).1 best.2 + change scoredArgmaxAllocation score allocation xs + allocation a + + (ltAllocation (score a).1 best.2 + 1) ≤ + (scoredArgmaxWithWork score xs).2 + (score a).2 + + ((score a).1.ltWithWork best.2).2 + 2 + omega + +theorem scoredArgmaxInvocations_le_work_add_one {α : Type*} (score : α → BinaryFraction × ℕ) + (invocations : α → ℕ) (xs : List α) (h : ∀ a ∈ xs, invocations a ≤ (score a).2) : + scoredArgmaxInvocations score invocations xs ≤ (scoredArgmaxWithWork score xs).2 + 1 := by + induction xs with + | nil => rfl + | cons a xs ih => + have ha := h a List.mem_cons_self + have ht := ih (fun b hb => h b (List.mem_cons_of_mem _ hb)) + simp only [scoredArgmaxInvocations, scoredArgmaxWithWork] + cases he : (scoredArgmaxWithWork score xs).1 with + | none => dsimp only; omega + | some best => + have hc := compareInvocations_le_work (score a).1 best.2 + change scoredArgmaxInvocations score invocations xs + invocations a + + (compareInvocations (score a).1 best.2 + 1) ≤ + ((scoredArgmaxWithWork score xs).2 + (score a).2 + + ((score a).1.ltWithWork best.2).2 + 2) + 1 + omega + + + +def maximizerInvocations {d : ℕ} (gradient : Vector BinaryFraction d) + (vertices : List (Vector BinaryFraction d)) : ℕ := + scoredArgmaxInvocations (dotWithWork gradient) + (fun v => dotListInvocations gradient v (List.finRange d)) vertices + 1 + +theorem maximizerAllocation_le_work {d : ℕ} (gradient : Vector BinaryFraction d) + (vertices : List (Vector BinaryFraction d)) : + maximizerAllocation gradient vertices ≤ (maximizerWithWork gradient vertices).2 := by + have h := scoredArgmaxAllocation_le_work (dotWithWork gradient) + (fun v => dotListAllocation gradient v (List.finRange d)) vertices + (fun v _ => dotListAllocation_le_work gradient v (List.finRange d)) + unfold maximizerAllocation maximizerWithWork + dsimp only + omega + +theorem maximizerInvocations_le_work_add_one {d : ℕ} (gradient : Vector BinaryFraction d) + (vertices : List (Vector BinaryFraction d)) : + maximizerInvocations gradient vertices ≤ (maximizerWithWork gradient vertices).2 + 1 := by + have h := scoredArgmaxInvocations_le_work_add_one (dotWithWork gradient) + (fun v => dotListInvocations gradient v (List.finRange d)) vertices + (fun v _ => dotListInvocations_le_work gradient v (List.finRange d)) + unfold maximizerInvocations maximizerWithWork + dsimp only + omega + + + +def optimizerUpdateCellInvocations {d : ℕ} (step complement : BinaryFraction) + (previous selected : Vector BinaryFraction d) (i : Fin d) : ℕ := + canonicalMulInvocations complement (previous.get i) + canonicalMulInvocations step (selected.get i) + + canonicalAddInvocations (canonicalMulWithWork complement (previous.get i)).1 + (canonicalMulWithWork step (selected.get i)).1 + 1 + + + +def optimizerUpdateInvocations {d : ℕ} (j : ℕ) (previous selected : Vector BinaryFraction d) : ℕ := + let step := (divWithWork (nat 2) (nat (j + 2))).1 + let complement := (subWithWork one step).1 + divInvocations (nat 2) (nat (j + 2)) + subInvocations one step + + vectorMapInvocations d (optimizerUpdateCellInvocations step complement previous selected) + 1 + +theorem optimizerUpdateAllocation_le_work {d : ℕ} (j : ℕ) (previous selected : Vector BinaryFraction d) : + optimizerUpdateAllocation j previous selected ≤ (optimizerUpdateWithWork j previous selected).2 := by + have h1 := divAllocation_le_work (nat 2) (nat (j + 2)) + have h2 := subAllocation_le_work one (divWithWork (nat 2) (nat (j + 2))).1 + have h3 := vectorMapAllocation_le_work d + (fun i => + let first := canonicalMulWithWork (subWithWork one (divWithWork (nat 2) (nat (j + 2))).1).1 (previous.get i) + let second := canonicalMulWithWork (divWithWork (nat 2) (nat (j + 2))).1 (selected.get i) + let total := canonicalAddWithWork first.1 second.1 + (total.1, first.2 + second.2 + total.2 + 4)) + (optimizerUpdateCellAllocation (divWithWork (nat 2) (nat (j + 2))).1 + (subWithWork one (divWithWork (nat 2) (nat (j + 2))).1).1 previous selected) (by + intro i + have hm1 := canonicalMulAllocation_le_work (subWithWork one (divWithWork (nat 2) (nat (j + 2))).1).1 (previous.get i) + have hm2 := canonicalMulAllocation_le_work (divWithWork (nat 2) (nat (j + 2))).1 (selected.get i) + have ha := canonicalAddAllocation_le_work + (canonicalMulWithWork (subWithWork one (divWithWork (nat 2) (nat (j + 2))).1).1 (previous.get i)).1 + (canonicalMulWithWork (divWithWork (nat 2) (nat (j + 2))).1 (selected.get i)).1 + unfold optimizerUpdateCellAllocation + dsimp only + omega) + unfold optimizerUpdateAllocation optimizerUpdateWithWork + dsimp only at h3 ⊢ + omega + +theorem optimizerUpdateInvocations_le_work {d : ℕ} (j : ℕ) (previous selected : Vector BinaryFraction d) : + optimizerUpdateInvocations j previous selected ≤ (optimizerUpdateWithWork j previous selected).2 := by + have h1 := divInvocations_le_work (nat 2) (nat (j + 2)) + have h2 := subInvocations_le_work one (divWithWork (nat 2) (nat (j + 2))).1 + have h3 := vectorMapInvocations_le_work_add_one d + (fun i => + let first := canonicalMulWithWork (subWithWork one (divWithWork (nat 2) (nat (j + 2))).1).1 (previous.get i) + let second := canonicalMulWithWork (divWithWork (nat 2) (nat (j + 2))).1 (selected.get i) + let total := canonicalAddWithWork first.1 second.1 + (total.1, first.2 + second.2 + total.2 + 4)) + (optimizerUpdateCellInvocations (divWithWork (nat 2) (nat (j + 2))).1 + (subWithWork one (divWithWork (nat 2) (nat (j + 2))).1).1 previous selected) (by + intro i + have hm1 := canonicalMulInvocations_le_work (subWithWork one (divWithWork (nat 2) (nat (j + 2))).1).1 (previous.get i) + have hm2 := canonicalMulInvocations_le_work (divWithWork (nat 2) (nat (j + 2))).1 (selected.get i) + have ha := canonicalAddInvocations_le_work + (canonicalMulWithWork (subWithWork one (divWithWork (nat 2) (nat (j + 2))).1).1 (previous.get i)).1 + (canonicalMulWithWork (divWithWork (nat 2) (nat (j + 2))).1 (selected.get i)).1 + unfold optimizerUpdateCellInvocations + dsimp only + omega) + unfold optimizerUpdateInvocations optimizerUpdateWithWork + dsimp only at h3 ⊢ + omega + + + +def optimizerInvocations {d : ℕ} (vertices : List (Vector BinaryFraction d)) + (linear : Vector BinaryFraction d) (G : ℕ) : ℕ → ℕ + | 0 => 1 + | j + 1 => + let previous := (finiteOptimizerWithWork vertices linear G j).1 + let gradient := (gradientWithWork G linear previous).1 + let selected := (maximizerWithWork gradient vertices).1 + optimizerInvocations vertices linear G j + gradientInvocations G linear previous + + maximizerInvocations gradient vertices + optimizerUpdateInvocations j previous selected + 1 + +theorem optimizerAllocation_le_work {d : ℕ} (vertices : List (Vector BinaryFraction d)) + (linear : Vector BinaryFraction d) (G K : ℕ) : + optimizerAllocation vertices linear G K ≤ (finiteOptimizerWithWork vertices linear G K).2 := by + induction K with + | zero => exact Nat.le_succ _ + | succ K ih => + have hg := gradientAllocation_le_work G linear (finiteOptimizerWithWork vertices linear G K).1 + have hm := maximizerAllocation_le_work (gradientWithWork G linear (finiteOptimizerWithWork vertices linear G K).1).1 vertices + have hu := optimizerUpdateAllocation_le_work K (finiteOptimizerWithWork vertices linear G K).1 + (maximizerWithWork (gradientWithWork G linear (finiteOptimizerWithWork vertices linear G K).1).1 vertices).1 + simp only [optimizerAllocation, finiteOptimizerWithWork] + exact (Nat.add_le_add (Nat.add_le_add (Nat.add_le_add ih hg) hm) hu).trans + (Nat.le_add_right _ 3) + +theorem optimizerInvocations_le_work {d : ℕ} (vertices : List (Vector BinaryFraction d)) + (linear : Vector BinaryFraction d) (G K : ℕ) : + optimizerInvocations vertices linear G K ≤ (finiteOptimizerWithWork vertices linear G K).2 := by + induction K with + | zero => simp only [optimizerInvocations, finiteOptimizerWithWork]; omega + | succ K ih => + have hg := gradientInvocations_le_work_add_one G linear (finiteOptimizerWithWork vertices linear G K).1 + have hm := maximizerInvocations_le_work_add_one (gradientWithWork G linear (finiteOptimizerWithWork vertices linear G K).1).1 vertices + have hu := optimizerUpdateInvocations_le_work K (finiteOptimizerWithWork vertices linear G K).1 + (maximizerWithWork (gradientWithWork G linear (finiteOptimizerWithWork vertices linear G K).1).1 vertices).1 + simp only [optimizerInvocations, finiteOptimizerWithWork] + omega + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryOptimizerWork.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryOptimizerWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..3b9d9ecdaec19baa3a3db209dedabb4653550e14 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryOptimizerWork.lean @@ -0,0 +1,168 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryUpdateWork + +namespace OAI + +/-! Total bit operations of the executed Boolean-fraction optimizer. +The bound includes logarithm sums, gradient materialization, scored vertex +search and every coordinate update, with no unit-cost rational primitive. -/ + +namespace EditApproximation +namespace BinaryFraction + +open Finset + +theorem maximizerWithWork_mem {d : ℕ} (gradient : Vector BinaryFraction d) + (vertices : List (Vector BinaryFraction d)) (hvertices : vertices ≠ []) : + (maximizerWithWork gradient vertices).1 ∈ vertices := by + unfold maximizerWithWork + dsimp only + rw [scoredArgmaxWithWork_value] + cases h : vertices.argmax (fun vertex => (dotWithWork gradient vertex).1.value) with + | none => exact False.elim (hvertices (List.argmax_eq_none.mp h)) + | some vertex => + simp only [Option.map_some, Option.getD_some] + exact List.argmax_mem (by rw [h]; simp) + +theorem gradientStorageBudget_mono (G : ℕ) {A B C D : ℕ} + (hpoint : A ≤ B) (hlinear : C ≤ D) : + UnreducedRational.gradientStorageBudget G A C ≤ + UnreducedRational.gradientStorageBudget G B D := by + have hs := UnreducedRational.logarithmStorageBudget_mono + (show 2 * A + 2 * (5 + 50 * (Nat.size G + 2)) + 2 ≤ + 2 * B + 2 * (5 + 50 * (Nat.size G + 2)) + 2 by omega) (G ^ 60) + unfold UnreducedRational.gradientStorageBudget + omega + +theorem gradientWithWork_width {d : ℕ} (G : ℕ) (linear point : Vector BinaryFraction d) + (P L : ℕ) (hp : ∀ i, 0 ≤ (point.get i).value) + (hpw : ∀ i, (point.get i).width ≤ P) (hlw : ∀ i, (linear.get i).width ≤ L) (i : Fin d) : + ((gradientWithWork G linear point).1.get i).width ≤ + UnreducedRational.gradientStorageBudget G (2 * P + 1) (2 * L + 1) := by + simp only [gradientWithWork, vectorMapWithWork_value] + apply (gradientCellWithWork_width G linear point i (hp i)).trans + apply gradientStorageBudget_mono + · exact (representation_storageBits_le _).trans (by have h := hpw i; omega) + · exact (representation_storageBits_le _).trans (by have h := hlw i; omega) + +theorem gradientWithWork_abs {d : ℕ} (G V : ℕ) (linear point : Vector BinaryFraction d) + (hp : ∀ i, 0 ≤ (point.get i).value) + (hlv : ∀ i, |(linear.get i).value| ≤ V) (i : Fin d) : + |((gradientWithWork G linear point).1.get i).value| ≤ (2 * G ^ 60 + 1 + V : ℕ) := by + have hv := congrArg (fun v : Vector UnreducedRational d => (v.get i).value) + (gradientWithWork_representation G linear point) + simp only [vector_map_get, representation_value, UnreducedRational.gradient_value] at hv + rw [hv] + have hpos : 0 ≤ (point.get i).value + 1 / (G : ℚ) ^ 50 := + add_nonneg (hp i) (div_nonneg (by norm_num) (pow_nonneg (Nat.cast_nonneg _) _)) + have hlog := rationalLogApproximation_abs_bound _ (G ^ 60) hpos + unfold rationalSmoothedGradient + calc + _ ≤ |-rationalLogApproximation ((point.get i).value + 1 / (G : ℚ) ^ 50) (G ^ 60) - 1| + + |(linear.get i).value| := abs_add_le _ _ + _ ≤ |rationalLogApproximation ((point.get i).value + 1 / (G : ℚ) ^ 50) (G ^ 60)| + 1 + + |(linear.get i).value| := by + have h := abs_add_le (-rationalLogApproximation + ((point.get i).value + 1 / (G : ℚ) ^ 50) (G ^ 60)) (-1) + exact add_le_add (by simpa only [sub_eq_add_neg, abs_neg, abs_one] using h) le_rfl + _ ≤ 2 * (G ^ 60 : ℕ) + 1 + (V : ℚ) := add_le_add (add_le_add hlog le_rfl) (hlv i) + _ = _ := by push_cast; rfl + +def optimizerPointWordBudget (K B Bv : ℕ) : ℕ := + Bv + 2 * (B + K * (2 * Nat.size (K + 1) + B)) + 2 + +def optimizerGradientWordBudget (G K B Bv L : ℕ) : ℕ := + UnreducedRational.gradientStorageBudget G (2 * optimizerPointWordBudget K B Bv + 1) (2 * L + 1) + +def optimizerRoundBitBudget (d v G K B Bv L V : ℕ) : ℕ := + let P := optimizerPointWordBudget K B Bv + let W := optimizerGradientWordBudget G K B Bv L + d * (gradientCellBitBudget G P L + 6) + + maximizerBitBudget d v (max P W) (2 * G ^ 60 + 1 + V + 1) + + optimizerUpdateBitBudget d K P + 3 + +def optimizerBitBudget (d v G K B Bv L V : ℕ) : ℕ := + d + 1 + K * optimizerRoundBitBudget d v G K B Bv L V + +theorem finiteOptimizerWithWork_cost {d : ℕ} + (vertices : List (Vector BinaryFraction d)) (linear : Vector BinaryFraction d) + (G K B Bv L V : ℕ) (hvertices : vertices ≠ []) + (hinput : ∀ v ∈ vertices, ∀ i : Fin d, + (v.get i).width ≤ (v.get i).representation.storageBits ∧ + (0 ≤ (v.get i).value ∧ (v.get i).value ≤ 1) ∧ + Nat.size (v.get i).representation.den ≤ B) + (hvw : ∀ v ∈ vertices, ∀ i, (v.get i).width ≤ Bv) + (hlw : ∀ i, (linear.get i).width ≤ L) + (hlv : ∀ i, |(linear.get i).value| ≤ V) : + (finiteOptimizerWithWork vertices linear G K).2 ≤ + optimizerBitBudget d vertices.length G K B Bv L V := by + let P := optimizerPointWordBudget K B Bv + let W := optimizerGradientWordBudget G K B Bv L + have hpoint (j : ℕ) (hj : j ≤ K) (i : Fin d) : + ((finiteOptimizerWithWork vertices linear G j).1.get i).width ≤ P := by + have hw := finiteOptimizerWithWork_coordinate_width vertices linear G j B hvertices hinput i + have hsize := Nat.size_le_size (show j + 1 ≤ K + 1 by omega) + have hm := Nat.mul_le_mul hj + (show 2 * Nat.size (j + 1) + B ≤ 2 * Nat.size (K + 1) + B by omega) + dsimp only [P, optimizerPointWordBudget] + omega + have hpositive (j : ℕ) (i : Fin d) : + 0 ≤ ((finiteOptimizerWithWork vertices linear G j).1.get i).value := by + have hn : (vertices.map fun v i => (v.get i).value) ≠ [] := by + intro h + exact hvertices (List.map_eq_nil_iff.mp h) + have h := finiteRationalOptimizer_coordinate_bounds univ + (vertices.map fun v i => (v.get i).value) (fun i => (linear.get i).value) G j hn i (by + intro v hv + obtain ⟨w, hw, rfl⟩ := List.mem_map.mp hv + exact (hinput w hw i).2.1) + rw [← congrFun (finiteOptimizerWithWork_value vertices linear G j) i] at h + exact h.1 + have hvert (v : Vector BinaryFraction d) (hv : v ∈ vertices) (i : Fin d) : (v.get i).width ≤ P := by + have h := hvw v hv i + dsimp only [P, optimizerPointWordBudget] + omega + have hvertexAbs (v : Vector BinaryFraction d) (hv : v ∈ vertices) (i : Fin d) : + |(v.get i).value| ≤ (2 * G ^ 60 + 1 + V + 1 : ℕ) := by + rw [abs_of_nonneg (hinput v hv i).2.1.1] + exact (hinput v hv i).2.1.2.trans (by exact_mod_cast (show 1 ≤ 2 * G ^ 60 + 1 + V + 1 by omega)) + have hcost : ∀ j ≤ K, (finiteOptimizerWithWork vertices linear G j).2 ≤ + d + 1 + j * optimizerRoundBitBudget d vertices.length G K B Bv L V := by + intro j + induction j with + | zero => intro _; simp only [finiteOptimizerWithWork, Nat.zero_mul, Nat.add_zero, le_refl] + | succ j ih => + intro hj + have hj' : j ≤ K := by omega + have hcprev := ih hj' + let previous := (finiteOptimizerWithWork vertices linear G j).1 + let grad := (gradientWithWork G linear previous).1 + let selected := (maximizerWithWork grad vertices).1 + have hcgrad := gradientWithWork_cost G linear previous P L + (hpositive j) (hpoint j hj') hlw + have hwgrad (i : Fin d) : (grad.get i).width ≤ W := + gradientWithWork_width G linear previous P L (hpositive j) (hpoint j hj') hlw i + have hvgrad (i : Fin d) : |(grad.get i).value| ≤ (2 * G ^ 60 + 1 + V + 1 : ℕ) := + (gradientWithWork_abs G V linear previous (hpositive j) hlv i).trans (by exact_mod_cast Nat.le_add_right _ 1) + have hcmax := maximizerWithWork_cost grad vertices (max P W) (2 * G ^ 60 + 1 + V + 1) + (fun i => (hwgrad i).trans (Nat.le_max_right _ _)) hvgrad + (fun v hv i => (hvert v hv i).trans (Nat.le_max_left _ _)) hvertexAbs + have hcupdate := optimizerUpdateWithWork_cost j K P hj' previous selected + (hpoint j hj') (fun i => hvert selected (maximizerWithWork_mem grad vertices hvertices) i) + change (finiteOptimizerWithWork vertices linear G j).2 + (gradientWithWork G linear previous).2 + + (maximizerWithWork grad vertices).2 + (optimizerUpdateWithWork j previous selected).2 + 3 ≤ _ + change _ ≤ d + 1 + (j + 1) * + (d * (gradientCellBitBudget G P L + 6) + + maximizerBitBudget d vertices.length (max P W) (2 * G ^ 60 + 1 + V + 1) + + optimizerUpdateBitBudget d K P + 3) + change (finiteOptimizerWithWork vertices linear G j).2 ≤ d + 1 + j * + (d * (gradientCellBitBudget G P L + 6) + + maximizerBitBudget d vertices.length (max P W) (2 * G ^ 60 + 1 + V + 1) + + optimizerUpdateBitBudget d K P + 3) at hcprev + rw [Nat.add_mul, Nat.one_mul] + omega + exact hcost K le_rfl + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryOrderWork.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryOrderWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..1b7340eeda2d60bed0aed7b3a381402680130a44 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryOrderWork.lean @@ -0,0 +1,97 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryArithmeticWork +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Most-significant comparison performed directly on little-endian Boolean +words, allowing leading zero bits. -/ + +namespace EditApproximation + + + + + +theorem bitOrdering_matches (high : Ordering) (a b : Bool) (x y : ℕ) + (h : orderingMatches high x y) : + orderingMatches (bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [bitOrdering, orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + + + + + +theorem bitCompareWithWork_matches (left right : List Bool) : + orderingMatches (bitCompareWithWork left right).1 (bitWordValue left) (bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [bitCompareWithWork] + induction right with + | nil => simp [bitCompareNilLeftWithWork, orderingMatches, bitWordValue] + | cons b bs ih => + simpa only [bitCompareNilLeftWithWork, bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using bitOrdering_matches (bitCompareNilLeftWithWork bs).1 false b 0 (bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [bitCompareWithWork, bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using bitOrdering_matches (bitCompareWithWork as []).1 a false (bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [bitCompareWithWork, bitWordValue] using + bitOrdering_matches (bitCompareWithWork as bs).1 a b (bitWordValue as) (bitWordValue bs) (ih bs) + +theorem bitCompareWithWork_lt (left right : List Bool) : + (bitCompareWithWork left right).1 = .lt ↔ bitWordValue left < bitWordValue right := by + have h := bitCompareWithWork_matches left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + +theorem bitCompareWithWork_eq (left right : List Bool) : + (bitCompareWithWork left right).1 = .eq ↔ bitWordValue left = bitWordValue right := by + have h := bitCompareWithWork_matches left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + +theorem bitCompareWithWork_cost (left right : List Bool) : + (bitCompareWithWork left right).2 ≤ 4 * (left.length + right.length) + 1 := by + induction left generalizing right with + | nil => + simp only [bitCompareWithWork] + induction right with + | nil => simp [bitCompareNilLeftWithWork] + | cons b bs ih => + simp only [bitCompareNilLeftWithWork, List.length_cons, List.length_nil] at * + omega + | cons a as ih => + cases right with + | nil => + have h := ih [] + simp only [bitCompareWithWork, List.length_cons, List.length_nil] at * + omega + | cons b bs => + have h := ih bs + simp only [bitCompareWithWork, List.length_cons] at * + omega + + + +theorem binaryNaturalCompareWithWork_lt (a b : ℕ) : + (binaryNaturalCompareWithWork a b).1 = .lt ↔ a < b := by + simpa only [binaryNaturalCompareWithWork, bitWordValue_bits] using bitCompareWithWork_lt a.bits b.bits + +theorem binaryNaturalCompareWithWork_eq (a b : ℕ) : + (binaryNaturalCompareWithWork a b).1 = .eq ↔ a = b := by + simpa only [binaryNaturalCompareWithWork, bitWordValue_bits] using bitCompareWithWork_eq a.bits b.bits + +theorem binaryNaturalCompareWithWork_cost (a b : ℕ) : + (binaryNaturalCompareWithWork a b).2 ≤ 4 * (Nat.size a + Nat.size b) + 1 := by + simpa only [binaryNaturalCompareWithWork, Nat.size_eq_bits_len] using bitCompareWithWork_cost a.bits b.bits + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryOuterReadCosts.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryOuterReadCosts.lean new file mode 100644 index 0000000000000000000000000000000000000000..fe118ae9f9cc86511ed0ab8488e8181324325d04 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryOuterReadCosts.lean @@ -0,0 +1,181 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryCellReadCosts +import OAI.Combinatorics.EditApproximation.Binary.BinaryOnlineReadCosts +import OAI.Combinatorics.EditApproximation.Binary.BinaryLocalGroupReads +import OAI.Combinatorics.EditApproximation.Binary.BinaryLocalOnlineReads +import OAI.Combinatorics.EditApproximation.Binary.BinaryRepresentativeReads + +namespace OAI + +/-! The outer local loops preserve the same lookup factor, including +initial-value reads at the query and at rounded representative centers. -/ + +namespace EditApproximation +namespace BinaryFraction + +theorem cost_replace_with_read (a c old new r R : ℕ) (hc : c ≤ a * tableReadFactor R) + (hr : r ≤ R) (ha : a + 1 ≤ old) (hn : new + a ≤ old + c + r) : + new ≤ old * tableReadFactor R := by + have hK : R + 1 ≤ tableReadFactor R := by unfold tableReadFactor; omega + have h := cost_factor_with_read a c (old - a) r R (tableReadFactor R) + hc hr (by omega) hK + have he : a + (old - a) = old := by omega + rw [he] at h + exact (by omega : new ≤ r + c + (old - a)).trans h + +section Group +variable {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (P F exponent Q eM eF : ℕ) + (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (hP : 0 < P) + (tau a : BinaryFraction) + (parentInitial : TargetInterval target.length → BinaryFraction × ℕ) + (child initial current : Fin M → TargetInterval target.length → BinaryFraction × ℕ) + (R : ℕ) (hc : ∀ i q, (child i q).2 ≤ R) (hi : ∀ i q, (initial i q).2 ≤ R) + +theorem preparedComputedCellReadWithWork_factor (b eb : ℕ) (hb : b = 2 ^ eb) + (draw : cellScaleDraw M b Q (nat F).value) (cell : ℕ × ℕ) + (hp : ∀ r, (parentInitial r).2 ≤ R) (hcurrent : ∀ i q, (current i q).2 ≤ R) : + (preparedComputedCellReadWithWork source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial current R hc hi b eb hb draw cell).2 ≤ + (preparedComputedCellGroupWithWork source target parent b P F exponent Q eM eb eF hM hb hF hP + tau a (fun r => (parentInitial r).1) (fun i q => (child i q).1) + (fun i q => (initial i q).1) (fun i q => (current i q).1) draw cell).2 * tableReadFactor R := by + have h := preparedCellGroupReadWithWork_factor source target parent b P F exponent Q + (by rw [hb]; exact Nat.two_pow_pos eb) hP tau a parentInitial child initial current + R hc hi (groupScalesWithWork eM eb eF).1 + (computedGroupScales_value M b F eM eb eF hM hb hF) draw cell hp hcurrent + unfold preparedComputedCellReadWithWork preparedComputedCellGroupWithWork + dsimp only + apply cost_replace_factor _ _ _ _ _ h (tableReadFactor_pos R) <;> omega + +theorem preparedLocalGroupScaleReadWithWork_factor (eb : ℕ) + (draw : CellGroupDraws M F Q) (query : TargetInterval target.length) + (hp : ∀ r, (parentInitial r).2 ≤ R) (hcurrent : ∀ i q, (current i q).2 ≤ R) : + (preparedLocalGroupScaleReadWithWork source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial current R hc hi eb draw query).2 ≤ + (preparedLocalGroupScaleWithWork source target parent P F exponent Q eM eF eb hM hF hP tau a + (fun r => (parentInitial r).1) (fun i q => (child i q).1) + (fun i q => (initial i q).1) (fun i q => (current i q).1) draw query).2 * tableReadFactor R := by + have hs := filterMapWithWork_factor + (fun cell => preparedComputedCellReadWithWork source target parent P F exponent Q eM eF + hM hF hP tau a parentInitial child initial current R hc hi (2 ^ eb) eb rfl + (Eq.mpr (congrArg (cellScaleDraw M (2 ^ eb) Q) (nat_value F)) (draw (2 ^ eb) cell)) cell) + (fun cell => preparedComputedCellGroupWithWork source target parent (2 ^ eb) P F exponent Q eM eb eF + hM rfl hF hP tau a (fun r => (parentInitial r).1) (fun i q => (child i q).1) + (fun i q => (initial i q).1) (fun i q => (current i q).1) + (Eq.mpr (congrArg (cellScaleDraw M (2 ^ eb) Q) (nat_value F)) (draw (2 ^ eb) cell)) cell) + (targetCellsWithWork (canonicalMulWithWork (inversePowerTwo exponent) (nat (2 ^ eb))).1 + (bitWordValue (naturalCeilingWithWork (parentInitial query).1).1) query).1 + (tableReadFactor R) (tableReadFactor_pos R) + (fun cell _ => preparedComputedCellReadWithWork_eq source target parent P F exponent Q eM eF + hM hF hP tau a parentInitial child initial current R hc hi _ eb rfl _ cell hp hcurrent) + (fun cell _ => preparedComputedCellReadWithWork_factor source target parent P F exponent Q eM eF + hM hF hP tau a parentInitial child initial current R hc hi _ eb rfl _ cell hp hcurrent) + unfold preparedLocalGroupScaleReadWithWork preparedLocalGroupScaleWithWork + dsimp only + apply cost_replace_with_read _ _ _ _ (parentInitial query).2 R hs.2 (hp query) <;> omega + +theorem preparedLocalCellGroupsReadWithWork_factor (N : ℕ) + (draw : CellGroupDraws M F Q) (query : TargetInterval target.length) + (hp : ∀ r, (parentInitial r).2 ≤ R) (hcurrent : ∀ i q, (current i q).2 ≤ R) : + (preparedLocalCellGroupsReadWithWork source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial current R hc hi N draw query).2 ≤ + (preparedLocalCellGroupsWithWork source target parent N P F exponent Q eM eF hM hF hP tau a + (fun r => (parentInitial r).1) (fun i q => (child i q).1) + (fun i q => (initial i q).1) (fun i q => (current i q).1) draw query).2 * tableReadFactor R := by + let first := fun eb => + let guard := refinementScaleGuardWithWork F (2 ^ eb) a (parentInitial query).1 + if guard.1 then + let selected := preparedLocalGroupScaleReadWithWork source target parent P F exponent Q eM eF + hM hF hP tau a parentInitial child initial current R hc hi eb draw query + (selected.1, guard.2 + selected.2 + eb + 4) + else ([], guard.2 + eb + 4) + let second := fun eb => + let guard := refinementScaleGuardWithWork F (2 ^ eb) a (parentInitial query).1 + if guard.1 then + let selected := preparedLocalGroupScaleWithWork source target parent P F exponent Q eM eF eb + hM hF hP tau a (fun r => (parentInitial r).1) (fun i q => (child i q).1) + (fun i q => (initial i q).1) (fun i q => (current i q).1) draw query + (selected.1, guard.2 + selected.2 + eb + 4) + else ([], guard.2 + eb + 4) + have h := arithmeticFlatMapWithWork_factor first second (List.range (max 1 N.bits.length)) + (tableReadFactor R) (tableReadFactor_pos R) (by + intro eb _ + dsimp only [first, second] + split_ifs + · have heq := preparedLocalGroupScaleReadWithWork_eq source target parent P F exponent Q eM eF + hM hF hP tau a parentInitial child initial current R hc hi eb draw query hp hcurrent + simpa only using heq + · rfl) (by + intro eb _ + dsimp only [first, second] + split_ifs + · have hs := preparedLocalGroupScaleReadWithWork_factor source target parent P F exponent Q eM eF + hM hF hP tau a parentInitial child initial current R hc hi eb draw query hp hcurrent + apply cost_replace_factor _ _ _ _ _ hs (tableReadFactor_pos R) <;> omega + · exact Nat.le_mul_of_pos_right _ (by have := tableReadFactor_pos R; omega)) + change (parentInitial query).2 + (arithmeticFlatMapWithWork first _).2 + _ + _ + 2 ≤ + ((arithmeticFlatMapWithWork second _).2 + _ + _ + 2) * tableReadFactor R + apply cost_replace_with_read _ _ _ _ (parentInitial query).2 R h.2 (hp query) <;> omega + +end Group + +section Online +variable {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (P F exponent H : ℕ) (hP : 0 < P) + (tau a eta kappa : BinaryFraction) + (parentInitial : TargetInterval target.length → BinaryFraction × ℕ) + (child initial : Fin M → TargetInterval target.length → BinaryFraction × ℕ) + (table : ℕ → Fin M × TargetInterval target.length → BinaryFraction × ℕ) + (R : ℕ) (hc : ∀ i q, (child i q).2 ≤ R) (hi : ∀ i q, (initial i q).2 ≤ R) + (t : ℕ) (integer : ℕ → TargetInterval target.length → ℕ) + +theorem preparedLocalOnlineScaleReadWithWork_factor (e : ℕ) (query : TargetInterval target.length) + (hp : ∀ r, (parentInitial r).2 ≤ R) (ht : ∀ s ≤ t + 1, ∀ i, (table s i).2 ≤ R) : + (preparedLocalOnlineScaleReadWithWork source target parent P F exponent H hP tau a eta kappa + parentInitial child initial table R hc hi t integer e query).2 ≤ + (preparedLocalOnlineScaleWithWork source target parent P F exponent H e hP tau a eta kappa + (fun r => (parentInitial r).1) (fun i q => (child i q).1) (fun i q => (initial i q).1) + (fun s i => (table s i).1) t integer query).2 * tableReadFactor R := by + let center := (roundStateWithWork + (bitWordValue (seedGridSpacingWithWork (2 ^ e) P).1) + (seedGridSpacingWithWork_pos (2 ^ e) P hP) query).1 + have hpcenter := hp center + dsimp only [center] at hpcenter + unfold preparedLocalOnlineScaleReadWithWork preparedLocalOnlineScaleWithWork + dsimp only + split_ifs + · have h := preparedOnlineReadWithWork_factor source target parent P F exponent H (2 ^ e) + (Nat.two_pow_pos e) hP tau eta kappa child initial table R hc hi t + center (integer (2 ^ e) center) ht + dsimp only [center] at h + apply cost_replace_with_read _ _ _ _ _ R h hpcenter <;> omega + · apply cost_replace_with_read 0 0 _ _ _ R (by simp) hpcenter <;> omega + +theorem preparedLocalOnlineActionsReadWithWork_factor (N : ℕ) (query : TargetInterval target.length) + (hp : ∀ r, (parentInitial r).2 ≤ R) (ht : ∀ s ≤ t + 1, ∀ i, (table s i).2 ≤ R) : + (preparedLocalOnlineActionsReadWithWork source target parent P F exponent H hP tau a eta kappa + parentInitial child initial table R hc hi t integer N query).2 ≤ + (preparedLocalOnlineActionsWithWork source target parent N P F exponent H hP tau a eta kappa + (fun r => (parentInitial r).1) (fun i q => (child i q).1) (fun i q => (initial i q).1) + (fun s i => (table s i).1) t integer query).2 * tableReadFactor R := by + have hs := filterMapWithWork_factor + (fun e => preparedLocalOnlineScaleReadWithWork source target parent P F exponent H hP tau a eta kappa + parentInitial child initial table R hc hi t integer e query) + (fun e => preparedLocalOnlineScaleWithWork source target parent P F exponent H e hP tau a eta kappa + (fun r => (parentInitial r).1) (fun i q => (child i q).1) (fun i q => (initial i q).1) + (fun s i => (table s i).1) t integer query) + (queryExponentsWithWork N F a (parentInitial query).1).1 + (tableReadFactor R) (tableReadFactor_pos R) + (fun e _ => preparedLocalOnlineScaleReadWithWork_eq source target parent P F exponent H hP + tau a eta kappa parentInitial child initial table R hc hi t integer e query ht) + (fun e _ => preparedLocalOnlineScaleReadWithWork_factor source target parent P F exponent H hP + tau a eta kappa parentInitial child initial table R hc hi t integer e query hp ht) + unfold preparedLocalOnlineActionsReadWithWork preparedLocalOnlineActionsWithWork + dsimp only + apply cost_replace_with_read _ _ _ _ (parentInitial query).2 R hs.2 (hp query) <;> omega + +end Online +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryPhysicalContinuation.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryPhysicalContinuation.lean new file mode 100644 index 0000000000000000000000000000000000000000..30cc66cd0c0f0b064150ca4f7fd017539aff8feb --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryPhysicalContinuation.lean @@ -0,0 +1,96 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryContinuationWork +import OAI.Combinatorics.EditApproximation.Binary.BinaryWideChildWork +import OAI.Combinatorics.EditApproximation.Geometry.LocalWideStep +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! The local refinement return is computed by the binary-fraction +continuation. Wide actions are built from the emitted endpoint grids, and +their connection charges are evaluated before the two Bellman minima. -/ + +namespace EditApproximation +namespace BinaryFraction + + + +@[simp] theorem endpointActionWithWork_decode {ny M : ℕ} (center : TargetInterval ny) + (states : Fin M → TargetInterval ny) : + (endpointActionWithWork center states).1.decode = + (⟨center, endpointActionConnection center states, fun i => (i, states i)⟩ : + PhysicalRationalAction M ny) := by + simp only [endpointActionWithWork, BinaryBellmanAction.decode, endpointConnectionWithWork_value] + + + +@[simp] theorem wideActionsFromRepresentativesWithWork_decode {nx ny : ℕ} (M : ℕ) + (parent : TargetInterval nx) (representatives : List (ℕ × TargetInterval ny)) (P : ℕ) + (hP : 0 < P) : + ((wideActionsFromRepresentativesWithWork M parent representatives P).1.map + BinaryBellmanAction.decode) = rationalActualWideActions parent representatives P := by + simp only [wideActionsFromRepresentativesWithWork, arithmeticFlatMapWithWork_value, + List.map_flatMap, arithmeticMapWithWork_value, List.map_map, Function.comp_def, + endpointActionWithWork_decode, rationalActualWideActions] + apply List.flatMap_congr + intro br _ + rw [← wideActionGridWithWork_value M parent br.2 br.1 P hP, List.map_map] + rfl + +def physicalContinuationWithWork {nx ny M : ℕ} (parent : TargetInterval nx) + (representatives : List (ℕ × TargetInterval ny)) (P F : ℕ) + (delta fallback : BinaryFraction) + (old current : Fin M × TargetInterval ny → BinaryFraction) + (groups online : List (BinaryBellmanAction (TargetInterval ny) (Fin M × TargetInterval ny) M)) + (query : TargetInterval ny) : BinaryFraction × ℕ := + let wide := wideActionsFromRepresentativesWithWork M parent representatives P + let L := canonicalMulWithWork (nat 128) (nat F) + let result := localContinuationWithWork endpointDistanceWithWork L.1 delta fallback + old current query wide.1 groups online + (result.1, wide.2 + L.2 + result.2 + 1) + +theorem physicalContinuationWithWork_value {nx ny M : ℕ} (parent : TargetInterval nx) + (representatives : List (ℕ × TargetInterval ny)) (P F : ℕ) + (delta fallback : BinaryFraction) + (old current : Fin M × TargetInterval ny → BinaryFraction) + (groups online : List (BinaryBellmanAction (TargetInterval ny) (Fin M × TargetInterval ny) M)) + (query : TargetInterval ny) (hP : 0 < P) : + (physicalContinuationWithWork parent representatives P F delta fallback old current groups online query).1.value = + rationalWideStep parent representatives P (fun _ => fallback.value) (128 * F) delta.value + (fun s => (old s).value) (fun s => (current s).value) + (groups.map BinaryBellmanAction.decode) (online.map BinaryBellmanAction.decode) query := by + simp only [physicalContinuationWithWork, localContinuationWithWork_value, + wideActionsFromRepresentativesWithWork_decode M parent representatives P hP, + endpointDistanceWithWork_value, canonicalMulWithWork_value, nat_value] + rfl + +/-- Exact local-program wiring. The two equalities are representation +identities for the already-computed sampled action lists. -/ +theorem physicalContinuationWithWork_local_value {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (N P F exponent Q : ℕ) + (tau a : ℚ) (delta : BinaryFraction) + (parentInitial : TargetInterval target.length → BinaryFraction) + (childMass childInitial : Fin M → TargetInterval target.length → ℚ) + (old current : Fin M × TargetInterval target.length → BinaryFraction) + (draw : CellGroupDraws M F Q) + (groups online : List (BinaryBellmanAction (TargetInterval target.length) + (Fin M × TargetInterval target.length) M)) + (logicalOnline : List (PhysicalRationalAction M target.length)) (query : TargetInterval target.length) + (hP : 0 < P) + (hgroups : groups.map BinaryBellmanAction.decode = localCellGroupActions source target parent + N P F exponent Q tau a (fun r => (parentInitial r).value) childMass childInitial + (fun i r => (current (i, r)).value) draw query) + (honline : online.map BinaryBellmanAction.decode = logicalOnline) : + (physicalContinuationWithWork parent + (localRefinementRepresentatives N P F a (fun r => (parentInitial r).value) query) + P F delta (parentInitial query) old current groups online query).1.value = + rationalLocalWideStep source target parent N P F exponent Q tau a delta.value + (fun r => (parentInitial r).value) childMass childInitial + (fun i r => (old (i, r)).value) (fun i r => (current (i, r)).value) draw logicalOnline query := by + rw [physicalContinuationWithWork_value _ _ _ _ _ _ _ _ _ _ _ hP, hgroups, honline] + rfl + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryPhysicalContinuationWork.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryPhysicalContinuationWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..6761a5948efb83aa4a740103409c086777975624 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryPhysicalContinuationWork.lean @@ -0,0 +1,93 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryPreparedActionStorage +import OAI.Combinatorics.EditApproximation.Binary.BinaryLocalWarmupKernel + +namespace OAI + +/-! Actual endpoint distances and connection words supply all representation +premises of the two Bellman scans and final refinement update. -/ + +namespace EditApproximation +namespace BinaryFraction + +def physicalContinuationInputBudget (M B : ℕ) : ℕ := + B + connectionWordBudget M B + endpointDistanceWordBudget B + 4 * B + 2 + +def physicalContinuationBitBudget (M P nr ng no B : ℕ) : ℕ := + wideActionsBitBudget M P nr B + 2000 * (B + 1) ^ 2 + + localContinuationBitBudget M (nr * (40 * P + 2) ^ (2 * M)) ng no + (physicalContinuationInputBudget M B) (endpointDistanceBitBudget B) + 1 + +private theorem endpointDistance_uniform {n : ℕ} (q r : TargetInterval n) (B : ℕ) + (hn : Nat.size n + 2 ≤ B) : + (endpointDistanceWithWork q r).1.width ≤ endpointDistanceWordBudget B ∧ + (endpointDistanceWithWork q r).2 ≤ endpointDistanceBitBudget B := + endpointDistanceWithWork_bounds q r B + ((Nat.add_le_add_right (Nat.size_le_size (q.ordered.trans q.valid)) 2).trans hn) + ((Nat.add_le_add_right (Nat.size_le_size q.valid) 2).trans hn) + ((Nat.add_le_add_right (Nat.size_le_size (r.ordered.trans r.valid)) 2).trans hn) + ((Nat.add_le_add_right (Nat.size_le_size r.valid) 2).trans hn) + +theorem physicalContinuationWithWork_bounds {nx ny M : ℕ} (parent : TargetInterval nx) + (representatives : List (ℕ × TargetInterval ny)) (P F B : ℕ) + (delta fallback : BinaryFraction) (old current : Fin M × TargetInterval ny → BinaryFraction) + (groups online : List (BinaryBellmanAction (TargetInterval ny) (Fin M × TargetInterval ny) M)) + (query : TargetInterval ny) (hPpos : 0 < P) (hB : 10 ≤ B) + (hnx : Nat.size nx ≤ B) (hny : Nat.size ny + 2 ≤ B) + (hM : Nat.size M ≤ B) (hP : Nat.size P ≤ B) (hF : Nat.size F + 2 ≤ B) + (hrep : ∀ br ∈ representatives, Nat.size br.1 ≤ B) + (hdelta : delta.width ≤ B) (hfallback : fallback.width ≤ B) + (hold : ∀ s, (old s).width ≤ B) (hcurrent : ∀ s, (current s).width ≤ B) + (hgroups : ∀ action ∈ groups, action.connection.width ≤ connectionWordBudget M B) + (honline : ∀ action ∈ online, action.connection.width ≤ connectionWordBudget M B) : + (physicalContinuationWithWork parent representatives P F delta fallback old current groups online query).1.width ≤ + localContinuationWordBudget M (physicalContinuationInputBudget M B) ∧ + (physicalContinuationWithWork parent representatives P F delta fallback old current groups online query).2 ≤ + physicalContinuationBitBudget M P representatives.length groups.length online.length B := by + let wide := wideActionsFromRepresentativesWithWork M parent representatives P + let L := canonicalMulWithWork (nat 128) (nat F) + let W := physicalContinuationInputBudget M B + have hBW : B ≤ W := by dsimp only [W, physicalContinuationInputBudget]; omega + have h128 : (nat 128).width ≤ B := + (nat_width_le 128).trans (by change 10 ≤ B; exact hB) + have hL := canonicalMulWithWork_width (nat 128) (nat F) B h128 ((nat_width_le F).trans hF) + have hLc := canonicalMulWithWork_cost (nat 128) (nat F) B h128 ((nat_width_le F).trans hF) + have hw := wideActionsFromRepresentativesWithWork_bounds parent representatives P B + hPpos hnx hny hM hP hrep + have htail := localContinuationWithWork_bounds endpointDistanceWithWork L.1 delta fallback + old current query wide.1 groups online W (endpointDistanceBitBudget B) + (hL.trans (by dsimp only [W, physicalContinuationInputBudget]; omega)) + (hdelta.trans hBW) (hfallback.trans hBW) + (fun action _ => (endpointDistance_uniform query action.center B hny).1.trans (by + dsimp only [W, physicalContinuationInputBudget]; omega)) + (fun action _ => (endpointDistance_uniform query action.center B hny).2) + (by + intro action ha + rcases List.mem_append.mp ha with ha | ha + · rcases List.mem_append.mp ha with ha | ha + · exact (hw.2.1 action ha).trans (by dsimp only [W, physicalContinuationInputBudget]; omega) + · exact (hgroups action ha).trans (by dsimp only [W, physicalContinuationInputBudget]; omega) + · exact (honline action ha).trans (by dsimp only [W, physicalContinuationInputBudget]; omega)) + (fun action _ i => (hold (action.childState i)).trans hBW) + (fun action _ i => (hcurrent (action.childState i)).trans hBW) + refine ⟨htail.1, ?_⟩ + have htailCost := htail.2.trans (show + localContinuationBitBudget M wide.1.length groups.length online.length W (endpointDistanceBitBudget B) ≤ + localContinuationBitBudget M (representatives.length * (40 * P + 2) ^ (2 * M)) groups.length online.length W + (endpointDistanceBitBudget B) by + unfold localContinuationBitBudget bellmanBitBudget + gcongr <;> exact hw.1) + change wide.2 + L.2 + + (localContinuationWithWork endpointDistanceWithWork L.1 delta fallback old current query wide.1 groups online).2 + 1 ≤ _ + have hwc := hw.2.2 + change wide.2 ≤ _ at hwc + change L.2 ≤ _ at hLc + unfold physicalContinuationBitBudget + change _ ≤ wideActionsBitBudget M P representatives.length B + 2000 * (B + 1) ^ 2 + + localContinuationBitBudget M (representatives.length * (40 * P + 2) ^ (2 * M)) + groups.length online.length W (endpointDistanceBitBudget B) + 1 + omega + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryPowerStorage.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryPowerStorage.lean new file mode 100644 index 0000000000000000000000000000000000000000..22ddb5f33202da5bfaef7f22827beb8eef1c24db --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryPowerStorage.lean @@ -0,0 +1,148 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryFixedDenominator +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Construction of a prescribed power denominator uses literal Boolean +multiplication and trimming. The subsequent cache compression therefore has +no uncharged conversion from a natural number to its binary representation. -/ + +namespace EditApproximation + + + +theorem bitPowerWithWork_value (base : List Bool) (n : ℕ) : + bitWordValue (bitPowerWithWork base n).1 = bitWordValue base ^ n := by + induction n with + | zero => simp [bitPowerWithWork, bitWordValue] + | succ n ih => + simp only [bitPowerWithWork, trimBitWordWithWork_value, bitMulWithWork_value, ih, pow_succ] + +theorem bitPowerWithWork_length (base : List Bool) (n : ℕ) : + (bitPowerWithWork base n).1.length = Nat.size (bitWordValue base ^ n) := by + cases n with + | zero => simp [bitPowerWithWork] + | succ n => + simp only [bitPowerWithWork, trimBitWordWithWork_length, bitMulWithWork_value, + bitPowerWithWork_value, pow_succ] + +theorem bitPowerWithWork_length_le (base : List Bool) (n B : ℕ) (hB : base.length ≤ B) : + (bitPowerWithWork base n).1.length ≤ n * B + 1 := by + rw [bitPowerWithWork_length] + exact (natural_power_bit_length _ _).trans + (Nat.add_le_add_right (Nat.mul_le_mul_left n + ((Nat.size_le.mpr (bitWordValue_lt_pow_length base)).trans hB)) 1) + +def bitPowerBitBudget (n B : ℕ) : ℕ := + 1 + n * (200 * ((n + 1) * (B + 1) + 1) ^ 2) + +theorem bitPowerWithWork_cost (base : List Bool) (n B : ℕ) (hB : base.length ≤ B) : + (bitPowerWithWork base n).2 ≤ bitPowerBitBudget n B := by + let W := (n + 1) * (B + 1) + have hbase : base.length ≤ W := by + have := Nat.le_mul_of_pos_left (B + 1) (by omega : 0 < n + 1) + dsimp only [W] + omega + have hwidth (j : ℕ) (hj : j ≤ n) : (bitPowerWithWork base j).1.length ≤ W := by + have hb := bitPowerWithWork_length_le base j B hB + have hm := Nat.mul_le_mul_right B hj + dsimp only [W] + nlinarith only [hb, hm, Nat.zero_le n, Nat.zero_le B] + have hcost (j : ℕ) (hj : j ≤ n) : + (bitPowerWithWork base j).2 ≤ 1 + j * (200 * (W + 1) ^ 2) := by + induction j with + | zero => simp [bitPowerWithWork] + | succ j ih => + have hj' : j ≤ n := by omega + have hi := ih hj' + have hw := hwidth j hj' + let previous := bitPowerWithWork base j + let product := bitMulWithWork previous.1 base + change previous.1.length ≤ W at hw + have hp := bitMulWithWork_cost previous.1 base + have hpl := bitMulWithWork_length previous.1 base + have ht := trimBitWordWithWork_cost product.1 + change product.2 ≤ _ at hp + have hstep : product.2 + (trimBitWordWithWork product.1).2 + 2 ≤ 200 * (W + 1) ^ 2 := by + have hmul := Nat.mul_le_mul (show previous.1.length + 1 ≤ W + 1 by omega) + (show previous.1.length + base.length + 1 ≤ 2 * W + 1 by omega) + change product.1.length ≤ 2 * previous.1.length + base.length + 1 at hpl + nlinarith only [hp, hpl, ht, hmul, hw, hbase, Nat.zero_le W] + change (bitPowerWithWork base j).2 + product.2 + (trimBitWordWithWork product.1).2 + 2 ≤ _ + rw [Nat.add_mul, Nat.one_mul] + omega + exact hcost n le_rfl + + + +theorem refinementBaseWithWork_value (ell : List Bool) : + bitWordValue (refinementBaseWithWork ell).1 = bitWordValue ell ^ 10 + 1 := by + simp only [refinementBaseWithWork, trimBitWordWithWork_value, bitAddWithWork_value, + bitPowerWithWork_value, bitWordValue, Bool.toNat_true, Bool.toNat_false] + +theorem refinementBaseWithWork_length (ell : List Bool) : + (refinementBaseWithWork ell).1.length = Nat.size (bitWordValue ell ^ 10 + 1) := by + simp only [refinementBaseWithWork, trimBitWordWithWork_length, bitAddWithWork_value, + bitPowerWithWork_value, bitWordValue, Bool.toNat_true, Bool.toNat_false] + +theorem refinementBaseWithWork_length_le (ell : List Bool) (B : ℕ) (hB : ell.length ≤ B) : + (refinementBaseWithWork ell).1.length ≤ 10 * B + 3 := by + rw [refinementBaseWithWork_length] + have hp := natural_power_bit_length (bitWordValue ell) 10 + have hs := natural_sum_bit_length (bitWordValue ell ^ 10) 1 + have hb := (Nat.size_le.mpr (bitWordValue_lt_pow_length ell)).trans hB + simp only [Nat.size_one] at hs + omega + +theorem refinementBaseWithWork_cost (ell : List Bool) (B : ℕ) (hB : ell.length ≤ B) : + (refinementBaseWithWork ell).2 ≤ bitPowerBitBudget 10 B + 200 * (B + 1) := by + have hp := bitPowerWithWork_cost ell 10 B hB + have hpl := bitPowerWithWork_length_le ell 10 B hB + have ha := bitAddWithWork_cost (bitPowerWithWork ell 10).1 [true] false + have hal := bitAddWithWork_length (bitPowerWithWork ell 10).1 [true] false + have ht := trimBitWordWithWork_cost (bitAddWithWork (bitPowerWithWork ell 10).1 [true] false).1 + simp only [List.length_cons, List.length_nil] at ha hal + have hmax : max (bitPowerWithWork ell 10).1.length 1 ≤ 10 * B + 1 := max_le hpl (by omega) + change (bitPowerWithWork ell 10).2 + + (bitAddWithWork (bitPowerWithWork ell 10).1 [true] false).2 + + (trimBitWordWithWork (bitAddWithWork (bitPowerWithWork ell 10).1 [true] false).1).2 + 2 ≤ _ + omega + +namespace BinaryFraction + + + +theorem powerDenominatorWithWork_value (a : BinaryFraction) (base : List Bool) + (hbase : 0 < bitWordValue base) (n : ℕ) (hden : a.value.den ∣ bitWordValue base ^ n) : + (powerDenominatorWithWork a base hbase n).1.value = a.value := by + apply fixedDenominatorWithWork_value + simpa only [bitPowerWithWork_value] using hden + +theorem powerDenominatorWithWork_width (a : BinaryFraction) (base : List Bool) + (hbase : 0 < bitWordValue base) (n V B : ℕ) (hB : base.length ≤ B) + (hden : a.value.den ∣ bitWordValue base ^ n) (hv : |a.value| ≤ V) : + (powerDenominatorWithWork a base hbase n).1.width ≤ Nat.size V + 2 * (n * B + 1) + 1 := by + apply fixedDenominatorWithWork_width a (bitPowerWithWork base n).1 _ _ V (n * B + 1) + · exact hv + · exact bitPowerWithWork_length_le base n B hB + · simpa only [bitPowerWithWork_value] using hden + +def powerDenominatorBitBudget (n A B : ℕ) : ℕ := + bitPowerBitBudget n B + 5000 * (A + (n * B + 1) + 2) ^ 2 + 1 + +theorem powerDenominatorWithWork_cost (a : BinaryFraction) (base : List Bool) + (hbase : 0 < bitWordValue base) (n A B : ℕ) (ha : a.width ≤ A) (hB : base.length ≤ B) : + (powerDenominatorWithWork a base hbase n).2 ≤ powerDenominatorBitBudget n A B := by + have hp := bitPowerWithWork_cost base n B hB + have hf := fixedDenominatorWithWork_cost a (bitPowerWithWork base n).1 + (by rw [bitPowerWithWork_value]; exact Nat.pow_pos hbase) A (n * B + 1) + ha (bitPowerWithWork_length_le base n B hB) + change (bitPowerWithWork base n).2 + (fixedDenominatorWithWork a (bitPowerWithWork base n).1 _).2 + 1 ≤ _ + unfold powerDenominatorBitBudget + omega + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryPrefixReads.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryPrefixReads.lean new file mode 100644 index 0000000000000000000000000000000000000000..de8f7f3392ce984afe376ddab9c62b80d3087ce5 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryPrefixReads.lean @@ -0,0 +1,90 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryPrefixWork +import OAI.Combinatorics.EditApproximation.Binary.BinaryReadComposition +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Prefix predictors retain the costs of the child words they inspect. -/ + +namespace EditApproximation +namespace BinaryFraction + + + +theorem prefixReadWithWork_eq {nx ny M : ℕ} (parent : TargetInterval nx) (r : TargetInterval ny) + (states : Fin M → TargetInterval ny) (read : Fin M → TargetInterval ny → BinaryFraction × ℕ) + (j : ℕ) (p : BinaryFraction) : + (prefixReadWithWork parent r states read j p).1 = + (prefixWithWork parent r states (fun i q => (read i q).1) j p).1 := by + have hw : (arithmeticMapWithWork (fun i : Fin M => + if i.val < j then read i (states i) else (zero, 1)) (List.finRange M)).1 = + List.ofFn (fun i : Fin M => if i.val < j then (read i (states i)).1 else zero) := by + simp only [arithmeticMapWithWork_value, List.ofFn_eq_map] + apply List.map_congr_left + intro i _ + split_ifs <;> rfl + simp only [prefixReadWithWork, hw, prefixWithWork] + +theorem prefixReadWithWork_cost {nx ny M : ℕ} (parent : TargetInterval nx) (r : TargetInterval ny) + (states : Fin M → TargetInterval ny) (read : Fin M → TargetInterval ny → BinaryFraction × ℕ) + (j : ℕ) (p : BinaryFraction) (R : ℕ) (hr : ∀ i, (read i (states i)).2 ≤ R) : + (prefixReadWithWork parent r states read j p).2 ≤ + (prefixWithWork parent r states (fun i q => (read i q).1) j p).2 + M * (R + 4) := by + let get := fun i : Fin M => if i.val < j then read i (states i) else (zero, 1) + have h := arithmeticMapWithWork_cost get (List.finRange M) (R + 1) (by + intro i _ + dsimp only [get] + split_ifs + · exact (hr i).trans (Nat.le_succ R) + · omega) + have hw : (arithmeticMapWithWork get (List.finRange M)).1 = + List.ofFn (fun i : Fin M => if i.val < j then (read i (states i)).1 else zero) := by + simp only [arithmeticMapWithWork_value, List.ofFn_eq_map] + apply List.map_congr_left + intro i _ + dsimp only [get] + split_ifs <;> rfl + simp only [List.length_finRange, Nat.add_assoc, Nat.reduceAdd] at h + change (arithmeticMapWithWork get (List.finRange M)).2 + _ + _ + _ + _ + _ + _ + 6 * M + 5 ≤ _ + rw [hw] + unfold prefixWithWork + dsimp only + omega + + + +theorem prefixMinimumReadWithWork_eq {nx ny M : ℕ} (parent : TargetInterval nx) (r : TargetInterval ny) + (actions : List (Fin M → TargetInterval ny)) (hne : actions ≠ []) + (read : Fin M → TargetInterval ny → BinaryFraction × ℕ) (j : ℕ) (p : BinaryFraction) : + (prefixMinimumReadWithWork parent r actions hne read j p).1 = + (prefixMinimumWithWork parent r actions hne (fun i q => (read i q).1) j p).1 := by + simp only [prefixMinimumReadWithWork, prefixMinimumWithWork, arithmeticMapWithWork_value, + prefixReadWithWork_eq] + +theorem prefixMinimumReadWithWork_cost {nx ny M : ℕ} (parent : TargetInterval nx) (r : TargetInterval ny) + (actions : List (Fin M → TargetInterval ny)) (hne : actions ≠ []) + (read : Fin M → TargetInterval ny → BinaryFraction × ℕ) (j : ℕ) (p : BinaryFraction) + (R : ℕ) (hr : ∀ action ∈ actions, ∀ i, (read i (action i)).2 ≤ R) : + (prefixMinimumReadWithWork parent r actions hne read j p).2 ≤ + (prefixMinimumWithWork parent r actions hne (fun i q => (read i q).1) j p).2 + + (actions.length + 1) * (M * (R + 4)) := by + have h := arithmeticMapWithWork_extra (fun action => prefixReadWithWork parent r action read j p) + (fun action => prefixWithWork parent r action (fun i q => (read i q).1) j p) + (fun _ => M * (R + 4)) actions + (fun action _ => prefixReadWithWork_eq parent r action read j p) + (fun action ha => prefixReadWithWork_cost parent r action read j p R (hr action ha)) + have hf := prefixReadWithWork_cost parent r (actions.head hne) read j p R (hr _ (List.head_mem hne)) + have hs : (actions.map (fun _ => M * (R + 4))).sum = actions.length * (M * (R + 4)) := by + simp only [List.map_const', List.sum_replicate, smul_eq_mul] + rw [hs] at h + unfold prefixMinimumReadWithWork prefixMinimumWithWork + dsimp only + rw [prefixReadWithWork_eq, h.1] + simp only [Nat.add_mul, Nat.one_mul] + omega + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryPrefixSpace.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryPrefixSpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..717e33ec1233c0a6afaa1daeaa2d187d32946ae5 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryPrefixSpace.lean @@ -0,0 +1,60 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryGeometrySpace +import OAI.Combinatorics.EditApproximation.Binary.BinaryPrefixReads +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation.BinaryFraction + + + +theorem prefixReadAllocation_le_work {nx ny M : ℕ} (parent : TargetInterval nx) (r : TargetInterval ny) + (states : Fin M → TargetInterval ny) (read : Fin M → TargetInterval ny → BinaryFraction × ℕ) + (allocation : Fin M → TargetInterval ny → ℕ) (j : ℕ) (p : BinaryFraction) + (h : ∀ i, allocation i (states i) ≤ (read i (states i)).2) : + prefixReadAllocation parent r states read allocation j p ≤ + (prefixReadWithWork parent r states read j p).2 := by + let words := (arithmeticMapWithWork (fun i : Fin M => + if i.val < j then read i (states i) else (zero, 1)) (List.finRange M)).1 + let finish := (canonicalAddWithWork (nat (balancedCut parent.lo (parent.hi - parent.lo) M j)) p).1 + have hw := arithmeticMapAllocation_le_work + (fun i : Fin M => if i.val < j then read i (states i) else (zero, 1)) + (fun i : Fin M => if i.val < j then allocation i (states i) else 0) (List.finRange M) (by + intro i _ + split_ifs + · exact h i + · exact Nat.zero_le _) + have hf := canonicalAddAllocation_le_work (nat (balancedCut parent.lo (parent.hi - parent.lo) M j)) p + have hc := connectionAllocation_le_work (nat r.lo) finish ((List.ofFn states).take j) + have hs := sumListAllocation_le_work words + have ha := canonicalAddAllocation_le_work + (connectionWithWork (nat r.lo) finish ((List.ofFn states).take j)).1 (sumListWithWork words).1 + unfold prefixReadAllocation prefixReadWithWork + dsimp only [words, finish] at hc hs ha ⊢ + omega + + + +theorem prefixMinimumReadAllocation_le_work {nx ny M : ℕ} (parent : TargetInterval nx) (r : TargetInterval ny) + (actions : List (Fin M → TargetInterval ny)) (hne : actions ≠ []) + (read : Fin M → TargetInterval ny → BinaryFraction × ℕ) + (allocation : Fin M → TargetInterval ny → ℕ) (j : ℕ) (p : BinaryFraction) + (h : ∀ action ∈ actions, ∀ i, allocation i (action i) ≤ (read i (action i)).2) : + prefixMinimumReadAllocation parent r actions hne read allocation j p ≤ + (prefixMinimumReadWithWork parent r actions hne read j p).2 := by + have hf := prefixReadAllocation_le_work parent r (actions.head hne) read allocation j p + (h _ (List.head_mem hne)) + have hs := arithmeticMapAllocation_le_work + (fun action => prefixReadWithWork parent r action read j p) + (fun action => prefixReadAllocation parent r action read allocation j p) actions + (fun action ha => prefixReadAllocation_le_work parent r action read allocation j p (h action ha)) + have hm := minimumAllocation_le_work (prefixReadWithWork parent r (actions.head hne) read j p).1 + (arithmeticMapWithWork (fun action => prefixReadWithWork parent r action read j p) actions).1 + unfold prefixMinimumReadAllocation prefixMinimumReadWithWork + dsimp only + omega + +end EditApproximation.BinaryFraction + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryPrefixWork.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryPrefixWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..a36cc2b502d4d683ec2ed3a4ead26ed4d08bbf54 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryPrefixWork.lean @@ -0,0 +1,188 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryDistanceWork + +namespace OAI + +/-! Literal stored-fraction evaluation of the finite prefix predictor. +Every prefix minimum scans the finite action array and uses exact +Boolean comparisons. No rational operation is assigned unit cost. -/ + +namespace EditApproximation +namespace BinaryFraction + +open Finset + +def prefixWithWork {nx ny M : ℕ} (parent : TargetInterval nx) + (r : TargetInterval ny) (states : Fin M → TargetInterval ny) + (child : Fin M → TargetInterval ny → BinaryFraction) (j : ℕ) (p : BinaryFraction) : + BinaryFraction × ℕ := + let finish := canonicalAddWithWork (nat (balancedCut parent.lo (parent.hi - parent.lo) M j)) p + let connection := connectionWithWork (nat r.lo) finish.1 ((List.ofFn states).take j) + let total := sumListWithWork (List.ofFn fun i : Fin M => + if i.val < j then child i (states i) else zero) + let result := canonicalAddWithWork connection.1 total.1 + (result.1, finish.2 + connection.2 + total.2 + result.2 + + Nat.size (balancedCut parent.lo (parent.hi - parent.lo) M j) + Nat.size r.lo + 6 * M + 5) + +@[simp] theorem prefixWithWork_value {nx ny M : ℕ} (parent : TargetInterval nx) + (r : TargetInterval ny) (states : Fin M → TargetInterval ny) + (child : Fin M → TargetInterval ny → BinaryFraction) (j : ℕ) (p : BinaryFraction) : + (prefixWithWork parent r states child j p).1.value = + rationalWidePrefixCost parent r states (fun i q => (child i q).value) j p.value := by + simp only [prefixWithWork, canonicalAddWithWork_value, connectionWithWork_value, + nat_value, sumListWithWork_value, List.map_ofFn, List.sum_ofFn, rationalWidePrefixCost] + congr 1 + apply sum_congr rfl + intro i _ + by_cases hi : i.val < j <;> simp [hi, zero, value, SignedBinary.value, signedMagnitude, bitWordValue] + +def prefixConnectionWord (M j B : ℕ) : ℕ := connectionWordBudget (min j M) (8 * B + 6) + +def prefixWordBudget (M j B : ℕ) : ℕ := + 8 * (prefixConnectionWord M j B + bandMassTotalStorageBudget M B) + 6 + +def prefixBitBudget (M j B : ℕ) : ℕ := + 6000 * (B + 1) ^ 2 + connectionBitBudget (min j M) (8 * B + 6) + + storedSumBitBudget M B + 6 * M + + 6000 * (prefixConnectionWord M j B + bandMassTotalStorageBudget M B + 1) ^ 2 + + 2 * B + 6 * M + 5 + +private theorem prefix_parts {nx ny M : ℕ} (parent : TargetInterval nx) + (r : TargetInterval ny) (states : Fin M → TargetInterval ny) + (child : Fin M → TargetInterval ny → BinaryFraction) (j : ℕ) (p : BinaryFraction) + (B : ℕ) (hp : p.width ≤ B) (hr : Nat.size r.lo + 2 ≤ B) + (hcut : Nat.size (balancedCut parent.lo (parent.hi - parent.lo) M j) + 2 ≤ B) + (hstate : ∀ i, Nat.size (states i).lo + 2 ≤ B ∧ Nat.size (states i).hi + 2 ≤ B) + (hchild : ∀ i, (child i (states i)).width ≤ B) : + let finish := canonicalAddWithWork (nat (balancedCut parent.lo (parent.hi - parent.lo) M j)) p + let connection := connectionWithWork (nat r.lo) finish.1 ((List.ofFn states).take j) + let total := sumListWithWork (List.ofFn fun i : Fin M => + if i.val < j then child i (states i) else zero) + connection.1.width ≤ prefixConnectionWord M j B ∧ + total.1.width ≤ bandMassTotalStorageBudget M B ∧ + connection.2 ≤ connectionBitBudget (min j M) (8 * B + 6) ∧ + total.2 ≤ storedSumBitBudget M B + 6 * M := by + dsimp only + have hfinish := canonicalAddWithWork_width + (nat (balancedCut parent.lo (parent.hi - parent.lo) M j)) p B + ((nat_width_le _).trans hcut) hp + have hstart : (nat r.lo).width ≤ 8 * B + 6 := by + have := (nat_width_le r.lo).trans hr + omega + have hend : ∀ state ∈ (List.ofFn states).take j, + Nat.size state.lo + 2 ≤ 8 * B + 6 ∧ Nat.size state.hi + 2 ≤ 8 * B + 6 := by + intro state hs + obtain ⟨i, rfl⟩ := List.mem_ofFn.mp (List.mem_of_mem_take hs) + have hi := hstate i + omega + have hlist : ∀ a ∈ (List.ofFn fun i : Fin M => + if i.val < j then child i (states i) else zero), a.width ≤ B := by + intro a ha + obtain ⟨i, rfl⟩ := List.mem_ofFn.mp ha + split_ifs + · exact hchild i + · have : zero.width = 1 := rfl + have := hcut + omega + have hw := connectionWithWork_width (nat r.lo) _ ((List.ofFn states).take j) + (8 * B + 6) hstart hfinish hend + have hc := connectionWithWork_cost (nat r.lo) _ ((List.ofFn states).take j) + (8 * B + 6) hstart hfinish hend + have htw := sumListWithWork_width _ B hlist + have htc := sumListWithWork_cost _ B hlist + simp only [List.length_take, List.length_ofFn] at hw hc htw htc + exact ⟨hw, htw, hc, htc⟩ + +theorem prefixWithWork_width {nx ny M : ℕ} (parent : TargetInterval nx) + (r : TargetInterval ny) (states : Fin M → TargetInterval ny) + (child : Fin M → TargetInterval ny → BinaryFraction) (j : ℕ) (p : BinaryFraction) + (B : ℕ) (hp : p.width ≤ B) (hr : Nat.size r.lo + 2 ≤ B) + (hcut : Nat.size (balancedCut parent.lo (parent.hi - parent.lo) M j) + 2 ≤ B) + (hstate : ∀ i, Nat.size (states i).lo + 2 ≤ B ∧ Nat.size (states i).hi + 2 ≤ B) + (hchild : ∀ i, (child i (states i)).width ≤ B) : + (prefixWithWork parent r states child j p).1.width ≤ prefixWordBudget M j B := by + obtain ⟨hw, htw, _, _⟩ := prefix_parts parent r states child j p B hp hr hcut hstate hchild + exact canonicalAddWithWork_width _ _ _ + (hw.trans (Nat.le_add_right _ _)) (htw.trans (Nat.le_add_left _ _)) + +theorem prefixWithWork_cost {nx ny M : ℕ} (parent : TargetInterval nx) + (r : TargetInterval ny) (states : Fin M → TargetInterval ny) + (child : Fin M → TargetInterval ny → BinaryFraction) (j : ℕ) (p : BinaryFraction) + (B : ℕ) (hp : p.width ≤ B) (hr : Nat.size r.lo + 2 ≤ B) + (hcut : Nat.size (balancedCut parent.lo (parent.hi - parent.lo) M j) + 2 ≤ B) + (hstate : ∀ i, Nat.size (states i).lo + 2 ≤ B ∧ Nat.size (states i).hi + 2 ≤ B) + (hchild : ∀ i, (child i (states i)).width ≤ B) : + (prefixWithWork parent r states child j p).2 ≤ prefixBitBudget M j B := by + obtain ⟨hw, htw, hc, htc⟩ := prefix_parts parent r states child j p B hp hr hcut hstate hchild + have hf := canonicalAddWithWork_cost + (nat (balancedCut parent.lo (parent.hi - parent.lo) M j)) p B + ((nat_width_le _).trans hcut) hp + have ha := canonicalAddWithWork_cost _ _ + (prefixConnectionWord M j B + bandMassTotalStorageBudget M B) + (hw.trans (Nat.le_add_right _ _)) (htw.trans (Nat.le_add_left _ _)) + change _ + _ + _ + _ + _ + _ + 6 * M + 5 ≤ _ + unfold prefixBitBudget + omega + +def prefixMinimumWithWork {nx ny M : ℕ} (parent : TargetInterval nx) + (r : TargetInterval ny) (actions : List (Fin M → TargetInterval ny)) (hne : actions ≠ []) + (child : Fin M → TargetInterval ny → BinaryFraction) (j : ℕ) (p : BinaryFraction) : + BinaryFraction × ℕ := + let fallback := prefixWithWork parent r (actions.head hne) child j p + let scores := arithmeticMapWithWork (fun action => prefixWithWork parent r action child j p) actions + let result := minimumWithWork fallback.1 scores.1 + (result.1, fallback.2 + scores.2 + result.2 + 1) + +@[simp] theorem prefixMinimumWithWork_value {nx ny M : ℕ} (parent : TargetInterval nx) + (r : TargetInterval ny) (actions : List (Fin M → TargetInterval ny)) (hne : actions ≠ []) + (child : Fin M → TargetInterval ny → BinaryFraction) (j : ℕ) (p : BinaryFraction) : + (prefixMinimumWithWork parent r actions hne child j p).1.value = + rationalWidePrefixMinimum parent r actions hne (fun i q => (child i q).value) j p.value := by + simp only [prefixMinimumWithWork, minimumWithWork_value, arithmeticMapWithWork_value, + List.map_map, Function.comp_def, prefixWithWork_value, rationalWidePrefixMinimum] + +def prefixMinimumBitBudget (M j v B : ℕ) : ℕ := + prefixBitBudget M j B + v * (prefixBitBudget M j B + 3) + + (1 + v * (1000 * (prefixWordBudget M j B + 1) ^ 2 + 2)) + 1 + +theorem prefixMinimumWithWork_bounds {nx ny M : ℕ} (parent : TargetInterval nx) + (r : TargetInterval ny) (actions : List (Fin M → TargetInterval ny)) (hne : actions ≠ []) + (child : Fin M → TargetInterval ny → BinaryFraction) (j : ℕ) (p : BinaryFraction) + (B : ℕ) (hp : p.width ≤ B) (hr : Nat.size r.lo + 2 ≤ B) + (hcut : Nat.size (balancedCut parent.lo (parent.hi - parent.lo) M j) + 2 ≤ B) + (hstate : ∀ action ∈ actions, ∀ i, + Nat.size (action i).lo + 2 ≤ B ∧ Nat.size (action i).hi + 2 ≤ B) + (hchild : ∀ action ∈ actions, ∀ i, (child i (action i)).width ≤ B) : + (prefixMinimumWithWork parent r actions hne child j p).1.width ≤ prefixWordBudget M j B ∧ + (prefixMinimumWithWork parent r actions hne child j p).2 ≤ + prefixMinimumBitBudget M j actions.length B := by + have hw (action) (ha : action ∈ actions) := + prefixWithWork_width parent r action child j p B hp hr hcut (hstate action ha) (hchild action ha) + have hc (action) (ha : action ∈ actions) := + prefixWithWork_cost parent r action child j p B hp hr hcut (hstate action ha) (hchild action ha) + have hf := List.head_mem hne + have hmap : ∀ a ∈ (arithmeticMapWithWork + (fun action => prefixWithWork parent r action child j p) actions).1, + a.width ≤ prefixWordBudget M j B := by + intro a ha + rw [arithmeticMapWithWork_value] at ha + obtain ⟨action, hmem, heq⟩ := List.mem_map.mp ha + subst a + exact hw action hmem + have hmw := minimumWithWork_width _ _ _ (hw _ hf) hmap + have hmc := minimumWithWork_cost _ _ _ (hw _ hf) hmap + have hsc := arithmeticMapWithWork_cost + (fun action => prefixWithWork parent r action child j p) actions (prefixBitBudget M j B) hc + have hlen : (arithmeticMapWithWork + (fun action => prefixWithWork parent r action child j p) actions).1.length = actions.length := by + rw [arithmeticMapWithWork_value, List.length_map] + rw [hlen] at hmc + refine ⟨hmw, ?_⟩ + have hfc := hc _ hf + change _ + _ + _ + 1 ≤ _ + unfold prefixMinimumBitBudget + omega + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryPreparedActionStorage.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryPreparedActionStorage.lean new file mode 100644 index 0000000000000000000000000000000000000000..c50a283ea60957e5b7d3ef369d52263a302b3303 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryPreparedActionStorage.lean @@ -0,0 +1,243 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryPreparedLocalKernel +import OAI.Combinatorics.EditApproximation.Binary.BinaryWideActionsWork + +namespace OAI + +/-! Every emitted group/online action carries a bounded stored connection. +This is a property of the literal constructors on every draw, without a +successful-seed event or an assumed geometric bound. -/ + +namespace EditApproximation +namespace BinaryFraction + +private theorem optionalBranch_property {A : Type*} (p : Prop) [Decidable p] + (emptyCost : ℕ) (selected : ¬p → A × ℕ) (selectedCost : ¬p → ℕ) + (property : A → Prop) (hselected : ∀ h, property (selected h).1) (action : A) + (ha : (if h : p then (none, emptyCost) else + (some (selected h).1, selectedCost h)).1 = some action) : property action := by + by_cases h : p + · have hnone : (none : Option A) = some action := by + simpa only [dite_eq_left h] using ha + cases hnone + · have hsome : some (selected h).1 = some action := by + simpa only [dite_eq_right h] using ha + exact (Option.some.inj hsome) ▸ hselected h + +private theorem filterMapWithWork_property {A C : Type*} + (callback : C → Option A × ℕ) (inputs : List C) (property : A → Prop) + (hcallback : ∀ input action, (callback input).1 = some action → property action) + (action : A) (ha : action ∈ (filterMapWithWork callback inputs).1) : property action := by + rw [filterMapWithWork_value] at ha + obtain ⟨input, _, hsome⟩ := List.mem_filterMap.mp ha + exact hcallback input action hsome + +private theorem arithmeticFlatMapWithWork_property {A C : Type*} + (callback : C → List A × ℕ) (inputs : List C) (property : A → Prop) + (hcallback : ∀ input action, action ∈ (callback input).1 → property action) + (action : A) (ha : action ∈ (arithmeticFlatMapWithWork callback inputs).1) : property action := by + rw [arithmeticFlatMapWithWork_value] at ha + obtain ⟨input, _, hmem⟩ := List.mem_flatMap.mp ha + exact hcallback input action hmem + +private theorem conditionalList_property {A : Type*} (p : Prop) [Decidable p] + (selected : List A × ℕ) (selectedCost emptyCost : ℕ) (property : A → Prop) + (hselected : ∀ action ∈ selected.1, property action) (action : A) + (ha : action ∈ (if p then (selected.1, selectedCost) else ([], emptyCost)).1) : + property action := by + by_cases h : p + · have hmem : action ∈ selected.1 := by simpa only [ite_eq_left h] using ha + exact hselected action hmem + · have hmem : action ∈ ([] : List A) := by simpa only [ite_eq_right h] using ha + exact False.elim (List.not_mem_nil hmem) + +section Group +variable {α : Type*} (source target : List α) {M T : ℕ} + (parent : TargetInterval source.length) (b P exponent Q : ℕ) + (tau F : BinaryFraction) + (child initial current : Fin M → TargetInterval target.length → BinaryFraction) + (scales : Fin T → BinaryFraction) + (draw : ∀ t, Fin (groupSampleCount M Q b (scales t).value) → Fin M) + (members : List (UnskippedBand source target parent b P exponent tau.value F.value + (fun i q => (child i q).value) (fun i q => (initial i q).value))) (hne : members ≠ []) + +theorem sampledGroupActionWithWork_connection (B : ℕ) (hn : Nat.size target.length + 2 ≤ B) : + (sampledGroupActionWithWork source target parent b P exponent Q tau F child initial current + scales draw members hne).1.connection.width ≤ connectionWordBudget M B := by + unfold sampledGroupActionWithWork + exact (endpointActionWithWork_bounds _ _ B hn).1 + +end Group + +section Cell +variable {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (b P F exponent Q : ℕ) (hb : 0 < b) + (tau a : BinaryFraction) + (parentInitial : TargetInterval target.length → BinaryFraction) + (child initial current : Fin M → TargetInterval target.length → BinaryFraction) + (raw : List BinaryFraction) + (hraw : raw.map value = groupDyadicScales M b (nat F).value) + (draw : ∀ t : Fin (groupDyadicScales M b (nat F).value).length, + Fin (groupSampleCount M Q b (groupDyadicScaleAt M b (nat F).value t)) → Fin M) + (hP : 0 < P) (cell : ℕ × ℕ) + +theorem preparedCellGroupWithWork_connection + (action : BinaryBellmanAction (TargetInterval target.length) (Fin M × TargetInterval target.length) M) + (ha : (preparedCellGroupWithWork source target parent b P F exponent Q hb tau a parentInitial + child initial current raw hraw draw hP cell).1 = some action) + (B : ℕ) (hn : Nat.size target.length + 2 ≤ B) : + action.connection.width ≤ connectionWordBudget M B := by + let centers := cellCentersWithWork P F b a (inversePowerTwo exponent) parentInitial cell + let members := filterMapWithWork + (preparedUnskippedCandidateWithWork source target parent b P exponent hb hP tau (nat F) child initial) + centers.1 + let selected := fun hne : members.1 ≠ [] => + dyadicSampledGroupActionWithWork source target parent b P exponent Q tau (nat F) + child initial current raw hraw draw members.1 hne + have hconnection (hne : members.1 ≠ []) : + (selected hne).1.connection.width ≤ connectionWordBudget M B := by + have hh := sampledGroupActionWithWork_connection source target parent b P exponent Q tau (nat F) + child initial current (indexedGroupScales raw M b (nat F).value hraw) + (fun t j => draw t (Fin.cast (congrArg (groupSampleCount M Q b) + (indexedGroupScales_value raw M b (nat F).value hraw t)) j)) members.1 hne B hn + simpa only [selected, dyadicSampledGroupActionWithWork] using hh + have habranch : (if h : members.1 = [] then (none, centers.2 + members.2 + 1) else + (some (selected h).1, centers.2 + members.2 + (selected h).2 + 2)).1 = some action := by + simpa only [preparedCellGroupWithWork, centers, members, selected] using ha + exact optionalBranch_property (members.1 = []) (centers.2 + members.2 + 1) selected + (fun hne => centers.2 + members.2 + (selected hne).2 + 2) + (fun action => action.connection.width ≤ connectionWordBudget M B) hconnection action habranch + +end Cell + +theorem preparedComputedCellGroupWithWork_connection {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (b P F exponent Q eM eb eF : ℕ) + (hM : M = 2 ^ eM) (hb : b = 2 ^ eb) (hF : F = 2 ^ eF) (hP : 0 < P) + (tau a : BinaryFraction) (parentInitial : TargetInterval target.length → BinaryFraction) + (child initial current : Fin M → TargetInterval target.length → BinaryFraction) + (draw : cellScaleDraw M b Q (nat F).value) (cell : ℕ × ℕ) + (action : BinaryBellmanAction (TargetInterval target.length) (Fin M × TargetInterval target.length) M) + (ha : (preparedComputedCellGroupWithWork source target parent b P F exponent Q eM eb eF + hM hb hF hP tau a parentInitial child initial current draw cell).1 = some action) + (B : ℕ) (hn : Nat.size target.length + 2 ≤ B) : + action.connection.width ≤ connectionWordBudget M B := by + have hcell : (preparedCellGroupWithWork source target parent b P F exponent Q + (by rw [hb]; exact Nat.two_pow_pos eb) tau a parentInitial child initial current + (groupScalesWithWork eM eb eF).1 (computedGroupScales_value M b F eM eb eF hM hb hF) + draw hP cell).1 = some action := by + simpa only [preparedComputedCellGroupWithWork] using ha + exact preparedCellGroupWithWork_connection source target parent b P F exponent Q + (by rw [hb]; exact Nat.two_pow_pos eb) tau a parentInitial child initial current + (groupScalesWithWork eM eb eF).1 (computedGroupScales_value M b F eM eb eF hM hb hF) + draw hP cell action hcell B hn + +theorem preparedLocalGroupScaleWithWork_connection {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (P F exponent Q eM eF eb : ℕ) + (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (hP : 0 < P) + (tau a : BinaryFraction) (parentInitial : TargetInterval target.length → BinaryFraction) + (child initial current : Fin M → TargetInterval target.length → BinaryFraction) + (draw : CellGroupDraws M F Q) (query : TargetInterval target.length) + (B : ℕ) (hn : Nat.size target.length + 2 ≤ B) + (action : BinaryBellmanAction (TargetInterval target.length) (Fin M × TargetInterval target.length) M) + (ha : action ∈ (preparedLocalGroupScaleWithWork source target parent P F exponent Q eM eF eb + hM hF hP tau a parentInitial child initial current draw query).1) : + action.connection.width ≤ connectionWordBudget M B := by + let cellDraw := fun cell : ℕ × ℕ => + Eq.mpr (congrArg (cellScaleDraw M (2 ^ eb) Q) (nat_value F)) (draw (2 ^ eb) cell) + let callback := fun cell : ℕ × ℕ => + preparedComputedCellGroupWithWork source target parent (2 ^ eb) P F exponent Q eM eb eF + hM rfl hF hP tau a parentInitial child initial current (cellDraw cell) cell + let cells := (targetCellsWithWork + (canonicalMulWithWork (inversePowerTwo exponent) (nat (2 ^ eb))).1 + (bitWordValue (naturalCeilingWithWork (parentInitial query)).1) query).1 + have hcallback (cell : ℕ × ℕ) + (result : BinaryBellmanAction (TargetInterval target.length) + (Fin M × TargetInterval target.length) M) + (hresult : (callback cell).1 = some result) : + result.connection.width ≤ connectionWordBudget M B := by + have hcell : (preparedComputedCellGroupWithWork source target parent (2 ^ eb) P F exponent Q eM eb eF + hM rfl hF hP tau a parentInitial child initial current (cellDraw cell) cell).1 = some result := by + simpa only [callback] using hresult + have hh := preparedComputedCellGroupWithWork_connection source target parent (2 ^ eb) P F exponent Q eM eb eF + hM rfl hF hP tau a parentInitial child initial current (cellDraw cell) cell result hcell B hn + exact hh + have hfiltered : action ∈ (filterMapWithWork callback cells).1 := by + simpa only [preparedLocalGroupScaleWithWork, callback, cells, cellDraw] using ha + exact filterMapWithWork_property callback cells + (fun result => result.connection.width ≤ connectionWordBudget M B) hcallback action hfiltered + +theorem preparedLocalCellGroupsWithWork_connection {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (N P F exponent Q eM eF : ℕ) + (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (hP : 0 < P) + (tau a : BinaryFraction) (parentInitial : TargetInterval target.length → BinaryFraction) + (child initial current : Fin M → TargetInterval target.length → BinaryFraction) + (draw : CellGroupDraws M F Q) (query : TargetInterval target.length) + (B : ℕ) (hn : Nat.size target.length + 2 ≤ B) + (action : BinaryBellmanAction (TargetInterval target.length) (Fin M × TargetInterval target.length) M) + (ha : action ∈ (preparedLocalCellGroupsWithWork source target parent N P F exponent Q eM eF + hM hF hP tau a parentInitial child initial current draw query).1) : + action.connection.width ≤ connectionWordBudget M B := by + let callback := fun eb : ℕ => + let guard := refinementScaleGuardWithWork F (2 ^ eb) a (parentInitial query) + if guard.1 then + let selected := preparedLocalGroupScaleWithWork source target parent P F exponent Q eM eF eb + hM hF hP tau a parentInitial child initial current draw query + (selected.1, guard.2 + selected.2 + eb + 4) + else ([], guard.2 + eb + 4) + have hcallback (eb : ℕ) + (result : BinaryBellmanAction (TargetInterval target.length) + (Fin M × TargetInterval target.length) M) + (hresult : result ∈ (callback eb).1) : + result.connection.width ≤ connectionWordBudget M B := by + let guard := refinementScaleGuardWithWork F (2 ^ eb) a (parentInitial query) + let selected := preparedLocalGroupScaleWithWork source target parent P F exponent Q eM eF eb + hM hF hP tau a parentInitial child initial current draw query + have hguarded : result ∈ (if guard.1 = true then + (selected.1, guard.2 + selected.2 + eb + 4) else ([], guard.2 + eb + 4)).1 := by + simpa only [callback, guard, selected] using hresult + exact conditionalList_property (guard.1 = true) selected + (guard.2 + selected.2 + eb + 4) (guard.2 + eb + 4) + (fun result => result.connection.width ≤ connectionWordBudget M B) + (fun result hmem => preparedLocalGroupScaleWithWork_connection source target parent P F exponent Q + eM eF eb hM hF hP tau a parentInitial child initial current draw query B hn result hmem) + result hguarded + have hflat : action ∈ (arithmeticFlatMapWithWork callback (List.range (max 1 N.bits.length))).1 := by + simpa only [preparedLocalCellGroupsWithWork, callback] using ha + exact arithmeticFlatMapWithWork_property callback (List.range (max 1 N.bits.length)) + (fun result => result.connection.width ≤ connectionWordBudget M B) hcallback action hflat + +theorem preparedOnlineWithWork_connection {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (P F exponent H b : ℕ) (hb : 0 < b) (hP : 0 < P) + (tau eta kappa : BinaryFraction) + (child initial : Fin M → TargetInterval target.length → BinaryFraction) + (table : ℕ → Fin M × TargetInterval target.length → BinaryFraction) + (t : ℕ) (center : TargetInterval target.length) (integer : ℕ) + (action : BinaryBellmanAction (TargetInterval target.length) (Fin M × TargetInterval target.length) M) + (ha : (preparedOnlineWithWork source target parent P F exponent H b hb hP tau eta kappa child initial + table t center integer).1 = some action) : action.connection = zero := by + unfold preparedOnlineWithWork at ha + dsimp only at ha + split_ifs at ha with hempty hactive + cases ha + rfl + +theorem preparedLocalOnlineActionsWithWork_connection {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (N P F exponent H : ℕ) (hP : 0 < P) + (tau a eta kappa : BinaryFraction) (parentInitial : TargetInterval target.length → BinaryFraction) + (child initial : Fin M → TargetInterval target.length → BinaryFraction) + (table : ℕ → Fin M × TargetInterval target.length → BinaryFraction) (t : ℕ) + (integer : ℕ → TargetInterval target.length → ℕ) (query : TargetInterval target.length) + (action : BinaryBellmanAction (TargetInterval target.length) (Fin M × TargetInterval target.length) M) + (ha : action ∈ (preparedLocalOnlineActionsWithWork source target parent N P F exponent H hP tau a + eta kappa parentInitial child initial table t integer query).1) : action.connection = zero := by + simp only [preparedLocalOnlineActionsWithWork, filterMapWithWork_value] at ha + obtain ⟨eb, _, hmem⟩ := List.mem_filterMap.mp ha + unfold preparedLocalOnlineScaleWithWork at hmem + dsimp only at hmem + split_ifs at hmem with heligible + exact preparedOnlineWithWork_connection source target parent P F exponent H (2 ^ eb) + (Nat.two_pow_pos _) hP tau eta kappa child initial table t _ _ action hmem + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryPreparedCellGroup.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryPreparedCellGroup.lean new file mode 100644 index 0000000000000000000000000000000000000000..56382ad888261c0f62d2569d0ea2832e65f88025 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryPreparedCellGroup.lean @@ -0,0 +1,79 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryCellGroupKernel +import OAI.Combinatorics.EditApproximation.Binary.BinaryPreparedUnskipped + +namespace OAI + +/-! Whole-cell selection with the prepared-grid band constructor. -/ + +namespace EditApproximation +namespace BinaryFraction + +section Cell +variable {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (b P F exponent Q : ℕ) (hb : 0 < b) + (tau a : BinaryFraction) + (parentInitial : TargetInterval target.length → BinaryFraction) + (child initial current : Fin M → TargetInterval target.length → BinaryFraction) + (raw : List BinaryFraction) + (hraw : raw.map value = groupDyadicScales M b (nat F).value) + (draw : ∀ t : Fin (groupDyadicScales M b (nat F).value).length, + Fin (groupSampleCount M Q b (groupDyadicScaleAt M b (nat F).value t)) → Fin M) + +def preparedCellGroupWithWork (hP : 0 < P) (cell : ℕ × ℕ) : + Option (BinaryBellmanAction (TargetInterval target.length) + (Fin M × TargetInterval target.length) M) × ℕ := + let centers := cellCentersWithWork P F b a (inversePowerTwo exponent) parentInitial cell + let members := filterMapWithWork + (preparedUnskippedCandidateWithWork source target parent b P exponent hb hP tau (nat F) child initial) centers.1 + if h : members.1 = [] then (none, centers.2 + members.2 + 1) else + let selected := dyadicSampledGroupActionWithWork source target parent b P exponent Q tau (nat F) + child initial current raw hraw draw members.1 h + (some selected.1, centers.2 + members.2 + selected.2 + 2) + +theorem preparedCellGroupWithWork_reference (cell : ℕ × ℕ) (hP : 0 < P) : + ((preparedCellGroupWithWork source target parent b P F exponent Q hb tau a parentInitial child initial current + raw hraw draw hP cell).1.map BinaryBellmanAction.decode) = + cellReferenceAction source target parent b P F exponent Q tau.value a.value (nat F).value + (fun q => (parentInitial q).value) (fun i q => (child i q).value) + (fun i q => (initial i q).value) (fun i q => (current i q).value) cell draw := by + have hcenters := cellCentersWithWork_value P F b a (inversePowerTwo exponent) parentInitial cell hP + simp only [inversePowerTwo_value] at hcenters + have hmembers : (filterMapWithWork + (preparedUnskippedCandidateWithWork source target parent b P exponent hb hP tau (nat F) child initial) + (cellCentersWithWork P F b a (inversePowerTwo exponent) parentInitial cell).1).1 = + unskippedBandList source target parent b P exponent tau.value (nat F).value + (fun i q => (child i q).value) (fun i q => (initial i q).value) + (cellRepresentativeStates target.length P F b a.value + (fun q => (parentInitial q).value) ((2 : ℚ) ^ (-(exponent : ℤ))) cell) := by + simp only [filterMapWithWork_value, preparedUnskippedCandidateWithWork_value, hcenters, unskippedBandList] + unfold preparedCellGroupWithWork + dsimp only + split_ifs with hempty + · have hnil := hempty + rw [hmembers] at hnil + simp only [Option.map_none, cellReferenceAction, dite_eq_left hnil] + · rw [Option.map_some, dyadicSampledGroupActionWithWork_value source target parent b P exponent Q + tau (nat F) child initial current raw hraw draw _ hempty hb] + have hnonempty := hempty + rw [hmembers] at hnonempty + simp only [hmembers, cellReferenceAction, dite_eq_right hnonempty] + +/-- The rational cell-group program at the exact natural parameter. +Transport preserves its values and changes only proof indices. -/ +theorem preparedCellGroupWithWork_value (cell : ℕ × ℕ) (hP : 0 < P) : + ((preparedCellGroupWithWork source target parent b P F exponent Q hb tau a parentInitial child initial current + raw hraw draw hP cell).1.map BinaryBellmanAction.decode) = + chooseCellGroupAction source target parent b P F exponent Q tau.value a.value + (fun q => (parentInitial q).value) (fun i q => (child i q).value) + (fun i q => (initial i q).value) (fun i q => (current i q).value) cell + (Eq.mp (congrArg (cellScaleDraw M b Q) (nat_value F)) draw) := by + exact (preparedCellGroupWithWork_reference source target parent b P F exponent Q hb tau a parentInitial + child initial current raw hraw draw cell hP).trans + (cellReferenceAction_transport source target parent b P F exponent Q tau.value a.value _ _ + (nat_value F) _ _ _ _ cell draw) + +end Cell +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryPreparedCellGroupWork.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryPreparedCellGroupWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..dec45c27da1edcc625a97128055009a41d2b26f0 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryPreparedCellGroupWork.lean @@ -0,0 +1,114 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryPreparedCellGroup +import OAI.Combinatorics.EditApproximation.Binary.BinaryPreparedUnskippedWork +import OAI.Combinatorics.EditApproximation.Binary.BinaryCellCentersWork +import OAI.Combinatorics.EditApproximation.Binary.BinarySelectedGroupWork + +namespace OAI + +/-! Complete per-cell arithmetic. The count includes construction and +testing of every candidate, and the actual finite-count sampled selector. -/ + +namespace EditApproximation +namespace BinaryFraction + +def preparedCellGroupBitBudget (M T e b P B : ℕ) : ℕ := + let V := (40 * P + 2) ^ (2 * M) + cellCentersBitBudget P P B + + (P + 1) ^ 2 * (preparedUnskippedBitBudget e b M P V V B + 3) + + selectedGroupBitBudget M T e b ((P + 1) ^ 2) V B + 2 + +theorem preparedCellGroupWithWork_cost {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (b P F e Q B : ℕ) + (hbpos : 0 < b) (tau a : BinaryFraction) + (parentInitial : TargetInterval target.length → BinaryFraction) + (child initial current : Fin M → TargetInterval target.length → BinaryFraction) + (raw : List BinaryFraction) + (hraw : raw.map value = groupDyadicScales M b (nat F).value) + (draw : ∀ t : Fin (groupDyadicScales M b (nat F).value).length, + Fin (groupSampleCount M Q b (groupDyadicScaleAt M b (nat F).value t)) → Fin M) + (hPpos : 0 < P) (cell : ℕ × ℕ) + (hB : 6 ≤ B) (hnx : Nat.size source.length + 2 ≤ B) + (hny : Nat.size target.length + 2 ≤ B) (hM : Nat.size M + 2 ≤ B) + (hQ : Nat.size Q + 2 ≤ B) (hb : Nat.size b + 2 ≤ B) + (hP : Nat.size P ≤ B) (hF : Nat.size F + 2 ≤ B) (he : e + 1 ≤ B) + (htau : tau.width ≤ B) (ha : a.width ≤ B) + (hparent : ∀ q, (parentInitial q).width ≤ B) + (hchild : ∀ i q, (child i q).width ≤ B) + (hinitial : ∀ i q, (initial i q).width ≤ B) + (hcurrent : ∀ i q, (current i q).width ≤ B) + (hscale : ∀ x ∈ raw, x.width ≤ B) + (hleft : Nat.size cell.1 ≤ B) (hright : Nat.size cell.2 ≤ B) + (hbdyadic : ∃ j : ℕ, b = 2 ^ j) (hPdyadic : ∃ j : ℕ, P = 2 ^ j) : + (preparedCellGroupWithWork source target parent b P F e Q hbpos tau a + parentInitial child initial current raw hraw draw hPpos cell).2 ≤ + preparedCellGroupBitBudget M (groupDyadicScales M b (nat F).value).length e b P B := by + let V := (40 * P + 2) ^ (2 * M) + let centers := cellCentersWithWork P F b a (inversePowerTwo e) parentInitial cell + let members := filterMapWithWork + (preparedUnskippedCandidateWithWork source target parent b P e hbpos hPpos tau (nat F) child initial) + centers.1 + have ht : (inversePowerTwo e).width ≤ B := by rw [inversePowerTwo_width]; exact he + have htValue : 0 ≤ (inversePowerTwo e).value ∧ (inversePowerTwo e).value ≤ 1 := by + rw [inversePowerTwo_value, zpow_neg, zpow_natCast] + exact ⟨by positivity, inv_le_one_of_one_le₀ (one_le_pow₀ (by norm_num))⟩ + have hc := cellCentersWithWork_uniform_cost P F b B a (inversePowerTwo e) parentInitial cell + hB (by omega) hb hP hF ha ht hparent hleft hright htValue hbdyadic hPdyadic + change centers.2 ≤ cellCentersBitBudget P P B at hc + have hclen : centers.1.length ≤ (P + 1) ^ 2 := by + rw [cellCentersWithWork_value P F b a (inversePowerTwo e) parentInitial cell hPpos] + exact cellRepresentativeStates_length_le a.value (fun q => (parentInitial q).value) + (inversePowerTwo e).value cell htValue hbdyadic hPdyadic + have hmc := filterMapWithWork_cost + (preparedUnskippedCandidateWithWork source target parent b P e hbpos hPpos tau (nat F) child initial) + centers.1 (preparedUnskippedBitBudget e b M P V V B) (fun r _ => + preparedUnskippedCandidateWithWork_uniform_cost source target parent b P e B hbpos hPpos + tau (nat F) child initial r hnx hny (by omega) hb hP he htau + ((nat_width_le F).trans hF) hchild hinitial) + change members.2 ≤ _ at hmc + have hmlen : members.1.length ≤ (P + 1) ^ 2 := by + have hm : members.1.length ≤ centers.1.length := by + dsimp only [members] + rw [filterMapWithWork_value] + exact List.length_filterMap_le _ _ + exact hm.trans hclen + have hmc' := hmc.trans (Nat.mul_le_mul_right _ hclen) + unfold preparedCellGroupWithWork + dsimp only + by_cases hempty : members.1 = [] + · rw [dite_eq_left hempty] + change centers.2 + members.2 + 1 ≤ _ + unfold preparedCellGroupBitBudget + change _ ≤ cellCentersBitBudget P P B + + (P + 1) ^ 2 * (preparedUnskippedBitBudget e b M P V V B + 3) + _ + 2 + omega + · rw [dite_eq_right hempty] + have hselected := sampledGroupActionWithWork_cost source target parent b P e Q tau (nat F) + child initial current (indexedGroupScales raw M b (nat F).value hraw) + (fun t j => draw t (Fin.cast (congrArg (groupSampleCount M Q b) + (indexedGroupScales_value raw M b (nat F).value hraw t)) j)) members.1 hempty V B + hM hQ hb hny (fun t => hscale _ (List.get_mem _ _)) + (fun member _ => (representativeBandActions_length_le source target parent member.center b P + tau.value ((2 : ℚ) ^ (-(e : ℤ))) (fun i q => (child i q).value)).trans + (wideActionList_length_le M parent member.center b P hPpos)) + (fun _ _ _ _ i => hinitial i _) hcurrent + change (dyadicSampledGroupActionWithWork source target parent b P e Q tau (nat F) + child initial current raw hraw draw members.1 hempty).2 ≤ _ at hselected + have hselected' : (dyadicSampledGroupActionWithWork source target parent b P e Q tau (nat F) + child initial current raw hraw draw members.1 hempty).2 ≤ + selectedGroupBitBudget M (groupDyadicScales M b (nat F).value).length e b ((P + 1) ^ 2) V B := by + apply hselected.trans + unfold selectedGroupBitBudget + gcongr + change centers.2 + members.2 + + (dyadicSampledGroupActionWithWork source target parent b P e Q tau (nat F) + child initial current raw hraw draw members.1 hempty).2 + 2 ≤ _ + unfold preparedCellGroupBitBudget + change _ ≤ cellCentersBitBudget P P B + + (P + 1) ^ 2 * (preparedUnskippedBitBudget e b M P V V B + 3) + + selectedGroupBitBudget M (groupDyadicScales M b (nat F).value).length e b ((P + 1) ^ 2) V B + 2 + omega + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryPreparedComputedCell.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryPreparedComputedCell.lean new file mode 100644 index 0000000000000000000000000000000000000000..7f0d34ecb108c41e18b28eaca40596f5d405f5df --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryPreparedComputedCell.lean @@ -0,0 +1,47 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryPreparedCellGroup +import OAI.Combinatorics.EditApproximation.Binary.BinaryComputedCellGroup + +namespace OAI + +/-! The cell kernel constructs its rational scales from the dyadic +parameter exponents. -/ + +namespace EditApproximation +namespace BinaryFraction + +def preparedComputedCellGroupWithWork {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (b P F exponent Q eM eb eF : ℕ) + (hM : M = 2 ^ eM) (hb : b = 2 ^ eb) (hF : F = 2 ^ eF) (hP : 0 < P) + (tau a : BinaryFraction) (parentInitial : TargetInterval target.length → BinaryFraction) + (child initial current : Fin M → TargetInterval target.length → BinaryFraction) + (draw : cellScaleDraw M b Q (nat F).value) (cell : ℕ × ℕ) : + Option (BinaryBellmanAction (TargetInterval target.length) + (Fin M × TargetInterval target.length) M) × ℕ := + let scales := groupScalesWithWork eM eb eF + let result := preparedCellGroupWithWork source target parent b P F exponent Q + (by rw [hb]; exact Nat.two_pow_pos eb) tau a parentInitial child initial current scales.1 + (computedGroupScales_value M b F eM eb eF hM hb hF) draw hP cell + (result.1, scales.2 + result.2 + 1) + +theorem preparedComputedCellGroupWithWork_value {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (b P F exponent Q eM eb eF : ℕ) + (hM : M = 2 ^ eM) (hb : b = 2 ^ eb) (hF : F = 2 ^ eF) + (tau a : BinaryFraction) (parentInitial : TargetInterval target.length → BinaryFraction) + (child initial current : Fin M → TargetInterval target.length → BinaryFraction) + (draw : cellScaleDraw M b Q (nat F).value) (cell : ℕ × ℕ) (hP : 0 < P) : + ((preparedComputedCellGroupWithWork source target parent b P F exponent Q eM eb eF hM hb hF hP tau a + parentInitial child initial current draw cell).1.map BinaryBellmanAction.decode) = + chooseCellGroupAction source target parent b P F exponent Q tau.value a.value + (fun q => (parentInitial q).value) (fun i q => (child i q).value) + (fun i q => (initial i q).value) (fun i q => (current i q).value) cell + (Eq.mp (congrArg (cellScaleDraw M b Q) (nat_value F)) draw) := by + have h := preparedCellGroupWithWork_value source target parent b P F exponent Q + (by rw [hb]; exact Nat.two_pow_pos eb) tau a parentInitial child initial current + (groupScalesWithWork eM eb eF).1 (computedGroupScales_value M b F eM eb eF hM hb hF) + draw cell hP + simpa only [preparedComputedCellGroupWithWork] using h + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryPreparedComputedCellWork.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryPreparedComputedCellWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..e05abc4abc8486ec53aaac3076b869b6715f7952 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryPreparedComputedCellWork.lean @@ -0,0 +1,47 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryPreparedComputedCell +import OAI.Combinatorics.EditApproximation.Binary.BinaryPreparedCellGroupWork +import OAI.Combinatorics.EditApproximation.Binary.BinaryGroupSetupWork + +namespace OAI + +/-! The cell cost includes materializing the exact dyadic scale array; +the finite draw counts are then those of the original cell sampler. -/ + +namespace EditApproximation +namespace BinaryFraction + +theorem preparedComputedCellGroupWithWork_cost {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (b P F e Q eM eb eF B : ℕ) + (hMdef : M = 2 ^ eM) (hbdef : b = 2 ^ eb) (hFdef : F = 2 ^ eF) (hPpos : 0 < P) + (tau a : BinaryFraction) (parentInitial : TargetInterval target.length → BinaryFraction) + (child initial current : Fin M → TargetInterval target.length → BinaryFraction) + (draw : cellScaleDraw M b Q (nat F).value) (cell : ℕ × ℕ) + (hB : 6 ≤ B) (hnx : Nat.size source.length + 2 ≤ B) + (hny : Nat.size target.length + 2 ≤ B) (hM : Nat.size M + 2 ≤ B) + (hQ : Nat.size Q + 2 ≤ B) (hb : Nat.size b + 2 ≤ B) + (hP : Nat.size P ≤ B) (hF : Nat.size F + 2 ≤ B) (he : e + 1 ≤ B) + (htau : tau.width ≤ B) (ha : a.width ≤ B) + (hparent : ∀ q, (parentInitial q).width ≤ B) + (hchild : ∀ i q, (child i q).width ≤ B) + (hinitial : ∀ i q, (initial i q).width ≤ B) + (hcurrent : ∀ i q, (current i q).width ≤ B) + (hscale : eM + eb + eF + 7 ≤ B) + (hleft : Nat.size cell.1 ≤ B) (hright : Nat.size cell.2 ≤ B) + (hPdyadic : ∃ j : ℕ, P = 2 ^ j) : + (preparedComputedCellGroupWithWork source target parent b P F e Q eM eb eF + hMdef hbdef hFdef hPpos tau a parentInitial child initial current draw cell).2 ≤ + groupScalesBitBudget eM eb eF + + preparedCellGroupBitBudget M (groupDyadicScales M b (nat F).value).length e b P B + 1 := by + have hs := groupScalesWithWork_bounds eM eb eF + have hc := preparedCellGroupWithWork_cost source target parent b P F e Q B + (by rw [hbdef]; exact Nat.two_pow_pos eb) tau a parentInitial child initial current + (groupScalesWithWork eM eb eF).1 (computedGroupScales_value M b F eM eb eF hMdef hbdef hFdef) + draw hPpos cell hB hnx hny hM hQ hb hP hF he htau ha hparent hchild hinitial hcurrent + (fun x hx => (hs.1 x hx).trans hscale) hleft hright ⟨eb, hbdef⟩ hPdyadic + change (groupScalesWithWork eM eb eF).2 + _ + 1 ≤ _ + omega + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryPreparedKernelReads.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryPreparedKernelReads.lean new file mode 100644 index 0000000000000000000000000000000000000000..3dc5276c223d4dcaeef21daf0cb6d74cf9f7ce13 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryPreparedKernelReads.lean @@ -0,0 +1,88 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryLocalGroupReads +import OAI.Combinatorics.EditApproximation.Binary.BinaryLocalOnlineReads +import OAI.Combinatorics.EditApproximation.Binary.BinaryContinuationReads +import OAI.Combinatorics.EditApproximation.Binary.BinaryRepresentativeReads +import OAI.Combinatorics.EditApproximation.Binary.BinaryPreparedLocalKernel + +namespace OAI + +/-! Complete reader-aware local refinement. Initial, mass, historical, +and current values are obtained through costed finite-buffer readers; +the complete Boolean continuation has exactly the original return word. -/ + +namespace EditApproximation +namespace BinaryFraction + +section Kernel +variable {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (N P F exponent H Q eM eF : ℕ) + (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) + (tau a eta kappa delta : BinaryFraction) + (parentInitial : TargetInterval target.length → BinaryFraction × ℕ) + (childMass childInitial : Fin M → TargetInterval target.length → BinaryFraction × ℕ) + (old current : Fin M × TargetInterval target.length → BinaryFraction × ℕ) + (history : ℕ → Fin M × TargetInterval target.length → BinaryFraction × ℕ) + (R : ℕ) (hm : ∀ i q, (childMass i q).2 ≤ R) (hi : ∀ i q, (childInitial i q).2 ≤ R) + (t : ℕ) (draw : CellGroupDraws M F Q) (integer : ℕ → TargetInterval target.length → ℕ) + (query : TargetInterval target.length) + +def preparedLocalKernelReadWithWork : BinaryFraction × ℕ := + let fallback := parentInitial query + let representatives := localRepresentativeReadWithWork N P F a parentInitial query + let groups := preparedLocalCellGroupsReadWithWork source target parent P F exponent Q eM eF + hM hF hP tau a parentInitial childMass childInitial (fun i r => current (i, r)) R hm hi N draw query + let online := preparedLocalOnlineActionsReadWithWork source target parent P F exponent H hP tau a eta kappa + parentInitial childMass childInitial history R hm hi t integer N query + let result := physicalContinuationReadWithWork parent representatives.1 P F delta fallback.1 + old current groups.1 online.1 query + (result.1, fallback.2 + representatives.2 + groups.2 + online.2 + result.2 + 4) + +theorem preparedLocalKernelReadWithWork_eq + (hp : ∀ r, (parentInitial r).2 ≤ R) (ho : ∀ s, (old s).2 ≤ R) + (hn : ∀ s, (current s).2 ≤ R) (hh : ∀ s ≤ t + 1, ∀ i, (history s i).2 ≤ R) : + (preparedLocalKernelReadWithWork source target parent N P F exponent H Q eM eF hP hM hF + tau a eta kappa delta parentInitial childMass childInitial old current history R hm hi t draw integer query).1 = + (preparedLocalKernelWithWork source target parent N P F exponent H Q eM eF hP hM hF + tau a eta kappa delta (fun r => (parentInitial r).1) (fun i r => (childMass i r).1) + (fun i r => (childInitial i r).1) (fun s => (old s).1) (fun s => (current s).1) + (fun t s => (history t s).1) t draw integer query).1 := by + have hr := (localRepresentativeReadWithWork_eq_cost N P F a parentInitial query R hp).1 + have hg := preparedLocalCellGroupsReadWithWork_eq source target parent P F exponent Q eM eF + hM hF hP tau a parentInitial childMass childInitial (fun i r => current (i, r)) R hm hi + N draw query hp (fun i r => hn (i, r)) + have honline := preparedLocalOnlineActionsReadWithWork_eq source target parent P F exponent H hP + tau a eta kappa parentInitial childMass childInitial history R hm hi t integer N query hh + unfold preparedLocalKernelReadWithWork preparedLocalKernelWithWork + dsimp only + rw [hr, hg, honline] + exact (physicalContinuationReadWithWork_eq_cost parent _ P F delta (parentInitial query).1 + old current _ _ query R ho hn).1 + +def cachedPreparedLocalKernelReadWithWork (base : List Bool) + (hbase : 0 < bitWordValue base) (remaining : ℕ) : BinaryFraction × ℕ := + finishCachedWithWork + (preparedLocalKernelReadWithWork source target parent N P F exponent H Q eM eF hP hM hF + tau a eta kappa delta parentInitial childMass childInitial old current history R hm hi t draw integer query) + base hbase remaining + +theorem cachedPreparedLocalKernelReadWithWork_eq (base : List Bool) + (hbase : 0 < bitWordValue base) (remaining : ℕ) + (hp : ∀ r, (parentInitial r).2 ≤ R) (ho : ∀ s, (old s).2 ≤ R) + (hn : ∀ s, (current s).2 ≤ R) (hh : ∀ s ≤ t + 1, ∀ i, (history s i).2 ≤ R) : + (cachedPreparedLocalKernelReadWithWork source target parent N P F exponent H Q eM eF hP hM hF + tau a eta kappa delta parentInitial childMass childInitial old current history R hm hi t draw integer query + base hbase remaining).1 = + (cachedPreparedLocalKernelWithWork source target parent N P F exponent H Q eM eF hP hM hF + tau a eta kappa delta (fun r => (parentInitial r).1) (fun i r => (childMass i r).1) + (fun i r => (childInitial i r).1) (fun s => (old s).1) (fun s => (current s).1) + (fun t s => (history t s).1) t draw integer query base hbase remaining).1 := by + simp only [cachedPreparedLocalKernelReadWithWork, cachedPreparedLocalKernelWithWork, + finishCachedWithWork, preparedLocalKernelReadWithWork_eq source target parent N P F exponent H Q eM eF + hP hM hF tau a eta kappa delta parentInitial childMass childInitial old current history R hm hi + t draw integer query hp ho hn hh] + +end Kernel +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryPreparedKernelWork.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryPreparedKernelWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..e27ea0065d42564a80f3adf4aa85f2e41250a6b4 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryPreparedKernelWork.lean @@ -0,0 +1,158 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryPhysicalContinuationWork +import OAI.Combinatorics.EditApproximation.Binary.BinaryPreparedLocalOnlineWork +import OAI.Combinatorics.EditApproximation.Binary.BinaryPreparedLocalGroupWork +import OAI.Combinatorics.EditApproximation.Binary.BinaryPreparedListBounds + +namespace OAI + +/-! The complete prepared refinement kernel has a single arithmetic bound. +All generated grids, guards, selected actions and the returned value are +charged. The premises below describe only stored input words and numeric +parameters; action geometry and output-list bounds are derived. -/ + +namespace EditApproximation +namespace BinaryFraction + +structure PreparedKernelInputBounds {nx ny M : ℕ} + (N P F exponent H Q eM eF B E S t : ℕ) + (tau a eta kappa delta : BinaryFraction) + (parentInitial : TargetInterval ny → BinaryFraction) + (childMass childInitial : Fin M → TargetInterval ny → BinaryFraction) + (old current : Fin M × TargetInterval ny → BinaryFraction) + (history : ℕ → Fin M × TargetInterval ny → BinaryFraction) + (integer : ℕ → TargetInterval ny → ℕ) : Prop where + largeBits : 10 ≤ B + inputSize : Nat.size N ≤ B + sourceSize : Nat.size nx + 2 ≤ B + targetSize : Nat.size ny + 2 ≤ B + aritySize : Nat.size M + 2 ≤ B + precisionSize : Nat.size P ≤ B + factorSize : Nat.size F + 2 ≤ B + sampleSize : Nat.size Q + 2 ≤ B + thetaSize : exponent + 1 ≤ B + scaleSizes : eM + eF + 7 ≤ B + heightSize : Nat.size H ≤ B + coordinateSize : Nat.size (M * (40 * P + 2) ^ 2) ≤ B + iterationSize : Nat.size ((H + M * (40 * P + 2) ^ 2 + 2) ^ 80) ≤ B + drawSize : ∀ b r, Nat.size (integer b r) ≤ B + tauSize : tau.width ≤ B + factorWidth : a.width ≤ B + rateSize : eta.width ≤ B + optimismSize : kappa.width ≤ B + decrementSize : delta.width ≤ B + parentSize : ∀ r, (parentInitial r).width ≤ B + massSize : ∀ i r, (childMass i r).width ≤ B + initialSize : ∀ i r, (childInitial i r).width ≤ B + oldSize : ∀ s, (old s).width ≤ B + currentSize : ∀ s, (current s).width ≤ B + historySize : ∀ s ≤ t + 1, ∀ i r, (history s (i, r)).width ≤ B + parentNonneg : ∀ r, 0 ≤ (parentInitial r).value + rateMagnitude : |eta.value| ≤ E + optimismRange : 0 ≤ kappa.value ∧ kappa.value ≤ 1 + historyRange : ∀ s ≤ t + 1, ∀ i r, 0 ≤ (history s (i, r)).value ∧ + (history s (i, r)).value ≤ (childInitial i r).value + scalePositive : 2 ≤ S + arityCap : M ≤ S + precisionCap : P ≤ S + rateCap : E ≤ S + timeCap : t ≤ S + wordCap : 3 * (B + 4) + 4 ≤ S + actionCap : (40 * P + 2) ^ (2 * M) ≤ S + cartesianCap : ((40 * P + 2) ^ 2 + 1) ^ (M + 1) ≤ S + iterationCap : (H + M * (40 * P + 2) ^ 2 + 2) ^ 80 ≤ S + +def preparedKernelBitBudget (N M P F exponent eM eF B S : ℕ) : ℕ := + localRepresentativesBitBudget P F B + preparedLocalGroupsBitBudget N M P F exponent eM eF B + + preparedLocalOnlineBitBudget M P B S + + physicalContinuationBitBudget M P ((B + 1) * (64 * F * P + 2) ^ 2) + ((B + 1) * ((32 * F + 2) * 2 ^ exponent + 2) ^ 2) (B + 1) (B + 4) + 4 + +def preparedKernelWordBudget (M B : ℕ) : ℕ := + localContinuationWordBudget M (physicalContinuationInputBudget M (B + 4)) + +private theorem physicalContinuationBitBudget_mono_counts (M P nr ng no nr' ng' no' B : ℕ) + (hr : nr ≤ nr') (hg : ng ≤ ng') (ho : no ≤ no') : + physicalContinuationBitBudget M P nr ng no B ≤ physicalContinuationBitBudget M P nr' ng' no' B := by + unfold physicalContinuationBitBudget wideActionsBitBudget localContinuationBitBudget bellmanBitBudget + dsimp only + gcongr + +theorem preparedLocalKernelWithWork_bounds {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (N P F exponent H Q eM eF B E S : ℕ) + (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (hPdyadic : ∃ j : ℕ, P = 2 ^ j) + (tau a eta kappa delta : BinaryFraction) + (parentInitial : TargetInterval target.length → BinaryFraction) + (childMass childInitial : Fin M → TargetInterval target.length → BinaryFraction) + (old current : Fin M × TargetInterval target.length → BinaryFraction) + (history : ℕ → Fin M × TargetInterval target.length → BinaryFraction) (t : ℕ) + (draw : CellGroupDraws M F Q) (integer : ℕ → TargetInterval target.length → ℕ) + (query : TargetInterval target.length) + (hb : PreparedKernelInputBounds (nx := source.length) N P F exponent H Q eM eF B E S t + tau a eta kappa delta parentInitial childMass childInitial old current history integer) : + (preparedLocalKernelWithWork source target parent N P F exponent H Q eM eF hP hM hF + tau a eta kappa delta parentInitial childMass childInitial old current history t draw integer query).1.width ≤ + preparedKernelWordBudget M B ∧ + (preparedLocalKernelWithWork source target parent N P F exponent H Q eM eF hP hM hF + tau a eta kappa delta parentInitial childMass childInitial old current history t draw integer query).2 ≤ + preparedKernelBitBudget N M P F exponent eM eF B S := by + let reps := localRepresentativesWithWork N P F a parentInitial query + let groups := preparedLocalCellGroupsWithWork source target parent N P F exponent Q eM eF hM hF hP + tau a parentInitial childMass childInitial (fun i r => current (i, r)) draw query + let online := preparedLocalOnlineActionsWithWork source target parent N P F exponent H hP tau a eta kappa + parentInitial childMass childInitial history t integer query + have hFpos : 1 ≤ F := by rw [hF]; exact Nat.one_le_two_pow + have hMpos : 0 < M := by rw [hM]; exact Nat.two_pow_pos _ + have hr := localRepresentativesWithWork_cost N P F B a parentInitial query (by have := hb.largeBits; omega) + hb.inputSize hb.factorSize hFpos hb.precisionSize hP (by have := hb.targetSize; omega) + hb.factorWidth hb.parentSize + have hg := preparedLocalCellGroupsWithWork_cost source target parent N P F exponent Q eM eF B hM hF hP + tau a parentInitial childMass childInitial (fun i r => current (i, r)) draw query + (by have := hb.largeBits; omega) hb.inputSize hb.sourceSize hb.targetSize hb.aritySize hb.sampleSize + hb.precisionSize hb.factorSize hb.thetaSize hb.scaleSizes hb.tauSize hb.factorWidth hb.parentSize + hb.massSize hb.initialSize (fun i r => hb.currentSize (i, r)) (hb.parentNonneg query) hPdyadic + have ho := preparedLocalOnlineActionsWithWork_cost source target parent N P F exponent H B E S hP hMpos + tau a eta kappa parentInitial childMass childInitial history t integer query + (by have := hb.largeBits; omega) hb.inputSize hb.sourceSize hb.targetSize (by have := hb.aritySize; omega) + hb.precisionSize hb.factorSize hb.thetaSize hb.heightSize hb.coordinateSize hb.iterationSize hb.drawSize + hb.tauSize hb.factorWidth hb.rateSize hb.optimismSize hb.parentSize hb.massSize hb.initialSize + hb.historySize hb.rateMagnitude hb.optimismRange hb.historyRange hb.scalePositive hb.arityCap + hb.precisionCap hb.rateCap hb.timeCap hb.wordCap hb.actionCap hb.cartesianCap hb.iterationCap + have htail := physicalContinuationWithWork_bounds parent reps.1 P F (B + 4) delta (parentInitial query) + old current groups.1 online.1 query hP (by have := hb.largeBits; omega) + (by have := hb.sourceSize; omega) (by have := hb.targetSize; omega) + (by have := hb.aritySize; omega) (by have := hb.precisionSize; omega) (by have := hb.factorSize; omega) + (fun br hbr => (localRepresentativesWithWork_scale_bits N P F B hP a parentInitial query hb.inputSize br hbr).trans + (by omega)) + (hb.decrementSize.trans (by omega)) ((hb.parentSize query).trans (by omega)) + (fun s => (hb.oldSize s).trans (by omega)) (fun s => (hb.currentSize s).trans (by omega)) + (fun action ha => preparedLocalCellGroupsWithWork_connection source target parent N P F exponent Q eM eF + hM hF hP tau a parentInitial childMass childInitial (fun i r => current (i, r)) draw query + (B + 4) (by have := hb.targetSize; omega) action ha) + (by + intro action ha + rw [preparedLocalOnlineActionsWithWork_connection source target parent N P F exponent H hP + tau a eta kappa parentInitial childMass childInitial history t integer query action ha] + change 1 ≤ connectionWordBudget M (B + 4) + unfold connectionWordBudget bandMassTotalStorageBudget + omega) + have hrlen := localRepresentativesWithWork_length_le N P F B hP hFpos a parentInitial query hb.inputSize + have hglen := preparedLocalCellGroupsWithWork_length_le source target parent N P F exponent Q eM eF B + hM hF hP tau a parentInitial childMass childInitial (fun i r => current (i, r)) draw query + hb.inputSize (hb.parentNonneg query) + have holen := preparedLocalOnlineActionsWithWork_length_le source target parent N P F exponent H B hP + tau a eta kappa parentInitial childMass childInitial history t integer query hb.inputSize + have htailCost := htail.2.trans (physicalContinuationBitBudget_mono_counts M P _ _ _ _ _ _ (B + 4) + hrlen hglen holen) + refine ⟨htail.1, ?_⟩ + change reps.2 + groups.2 + online.2 + + (physicalContinuationWithWork parent reps.1 P F delta (parentInitial query) old current groups.1 online.1 query).2 + 4 ≤ _ + change reps.2 ≤ _ at hr + change groups.2 ≤ _ at hg + change online.2 ≤ _ at ho + unfold preparedKernelBitBudget + omega + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryPreparedListBounds.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryPreparedListBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..6c3999a24c91c70aa18d484b6b9e07f7b0a174ae --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryPreparedListBounds.lean @@ -0,0 +1,104 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryPreparedLocalKernel +import OAI.Combinatorics.EditApproximation.Binary.BinaryLocalRepresentativeWork +import OAI.Combinatorics.EditApproximation.Geometry.LocalGroupBudget + +namespace OAI + +/-! Literal candidate counts of the three local loops, on every seed. -/ + +namespace EditApproximation +namespace BinaryFraction + +theorem dyadicScales_length_bits (N : ℕ) : (dyadicScales N).length = max 1 N.bits.length := by + have h := congrArg List.length (dyadicScalesWithWork_value N) + simpa only [dyadicScalesWithWork, arithmeticMapWithWork_value, List.length_map, + List.length_range] using h.symm + +theorem queryExponentsWithWork_length_le (N F B : ℕ) (a w : BinaryFraction) + (hN : Nat.size N ≤ B) : (queryExponentsWithWork N F a w).1.length ≤ B + 1 := by + change (filterWithWork _ (List.range (max 1 N.bits.length))).1.length ≤ _ + rw [filterWithWork_value] + apply (List.length_filter_le _ _).trans + rw [List.length_range, Nat.size_eq_bits_len] + omega + +theorem localRepresentativesWithWork_scale_bits {n : ℕ} (N P F B : ℕ) (hP : 0 < P) + (a : BinaryFraction) (initial : TargetInterval n → BinaryFraction) (query : TargetInterval n) + (hN : Nat.size N ≤ B) (br : ℕ × TargetInterval n) + (hbr : br ∈ (localRepresentativesWithWork N P F a initial query).1) : Nat.size br.1 ≤ B + 2 := by + rw [localRepresentativesWithWork_value N P F hP] at hbr + have hb := (representativeList_conditions a.value (fun r => (initial r).value) + (localRefinementRepresentatives_subset N P F a.value (fun r => (initial r).value) query br hbr)).1 + obtain ⟨e, he, hscale⟩ := List.mem_map.mp hb + have hlen : Nat.log 2 N + 1 = max 1 N.bits.length := by + simpa only [dyadicScales, List.length_map, List.length_range] using dyadicScales_length_bits N + have her := List.mem_range.mp he + rw [hlen, Nat.size_eq_bits_len] at her + rw [← hscale, Nat.size_pow] + omega + +theorem localRepresentativesWithWork_length_le {n : ℕ} (N P F B : ℕ) (hP : 0 < P) + (hF : 1 ≤ F) (a : BinaryFraction) (initial : TargetInterval n → BinaryFraction) + (query : TargetInterval n) (hN : Nat.size N ≤ B) : + (localRepresentativesWithWork N P F a initial query).1.length ≤ + (B + 1) * (64 * F * P + 2) ^ 2 := by + rw [localRepresentativesWithWork_value N P F hP] + unfold localRefinementRepresentatives + apply (list_flatMap_length_le _ _ _ ?_).trans + (Nat.mul_le_mul_right _ ((List.length_filter_le _ _).trans (show + (dyadicScales N).length ≤ B + 1 by rw [dyadicScales_length_bits, Nat.size_eq_bits_len]; omega))) + intro b hb + have hwindow := of_decide_eq_true (List.mem_filter.mp hb).2 + have hFp : (0 : ℚ) < 16 * F := by + have : (0 : ℚ) < F := by exact_mod_cast (show 0 < F by omega) + positivity + have hr : ⌈(initial query).value⌉₊ ≤ (16 * F) * b := by + apply Nat.ceil_le.mpr + have hh := (div_le_iff₀ hFp).mp hwindow.1 + push_cast + nlinarith only [hh] + simp only [List.length_map] + exact (List.length_filter_le _ _).trans (by + simpa only [show 4 * (16 * F) * P = 64 * F * P by ring] using + localTargetStates_length_from_scale P b ⌈(initial query).value⌉₊ (16 * F) query hP hr) + +theorem preparedLocalCellGroupsWithWork_length_le {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (N P F exponent Q eM eF B : ℕ) + (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (hP : 0 < P) (tau a : BinaryFraction) + (parentInitial : TargetInterval target.length → BinaryFraction) + (child initial current : Fin M → TargetInterval target.length → BinaryFraction) + (draw : CellGroupDraws M F Q) (query : TargetInterval target.length) + (hN : Nat.size N ≤ B) (hw : 0 ≤ (parentInitial query).value) : + (preparedLocalCellGroupsWithWork source target parent N P F exponent Q eM eF hM hF hP + tau a parentInitial child initial current draw query).1.length ≤ + (B + 1) * ((32 * F + 2) * 2 ^ exponent + 2) ^ 2 := by + have hv := congrArg List.length (preparedLocalCellGroupsWithWork_value source target parent + N P F exponent Q eM eF hM hF hP tau a parentInitial child initial current draw query) + rw [List.length_map] at hv + rw [hv] + apply (localCellGroupActions_length source target parent N P F exponent Q tau.value a.value + (fun r => (parentInitial r).value) (fun i r => (child i r).value) + (fun i r => (initial i r).value) (fun i r => (current i r).value) draw query + (by rw [hF]; exact Nat.one_le_two_pow) hw).trans + apply Nat.mul_le_mul_right + apply (List.length_filter_le _ _).trans + rw [dyadicScales_length_bits, Nat.size_eq_bits_len] + omega + +theorem preparedLocalOnlineActionsWithWork_length_le {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (N P F exponent H B : ℕ) (hP : 0 < P) + (tau a eta kappa : BinaryFraction) (parentInitial : TargetInterval target.length → BinaryFraction) + (child initial : Fin M → TargetInterval target.length → BinaryFraction) + (table : ℕ → Fin M × TargetInterval target.length → BinaryFraction) (t : ℕ) + (integer : ℕ → TargetInterval target.length → ℕ) (query : TargetInterval target.length) + (hN : Nat.size N ≤ B) : + (preparedLocalOnlineActionsWithWork source target parent N P F exponent H hP tau a eta kappa + parentInitial child initial table t integer query).1.length ≤ B + 1 := by + change (filterMapWithWork _ (queryExponentsWithWork N F a (parentInitial query)).1).1.length ≤ _ + rw [filterMapWithWork_value] + exact (List.length_filterMap_le _ _).trans (queryExponentsWithWork_length_le N F B a _ hN) + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryPreparedLocalGroupWork.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryPreparedLocalGroupWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..642244d5f8d493490c274cdaf961cc6e30491331 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryPreparedLocalGroupWork.lean @@ -0,0 +1,250 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryPreparedLocalGroups +import OAI.Combinatorics.EditApproximation.Binary.BinaryPreparedComputedCellWork +import OAI.Combinatorics.EditApproximation.Binary.BinaryLocalRepresentativeWork + +namespace OAI + +/-! Bit work of the literal query-local whole-cell loops. The tested scale +inequality bounds both coordinate ranges; every generated cell invokes the +complete counted band and sampled-action routine. -/ + +namespace EditApproximation +namespace BinaryFraction + +private theorem queryCellCoordinates_length (F b exponent p : ℕ) (w : ℚ) + (hF : 1 ≤ F) (hb : 1 ≤ b) (hw : 0 ≤ w) (hwindow : w / (16 * F) ≤ b) : + (localCellCoordinates ((2 : ℚ) ^ (-(exponent : ℤ)) * b) p ⌈w⌉₊).length ≤ + (32 * F + 2) * 2 ^ exponent + 2 := by + have hFp : (0 : ℚ) < F := by exact_mod_cast (show 0 < F by omega) + have hbp : (0 : ℚ) < b := by exact_mod_cast (show 0 < b by omega) + have hbR : (1 : ℚ) ≤ b := by exact_mod_cast hb + have hs : 0 < (2 : ℚ) ^ (-(exponent : ℤ)) * b := by positivity + apply localCellCoordinates_length_le _ hs _ _ ((32 * F + 2) * 2 ^ exponent) + apply (div_le_iff₀ hs).2 + have hw' : w ≤ 16 * (F : ℚ) * b := by + nlinarith only [(div_le_iff₀ (by positivity : (0 : ℚ) < 16 * F)).mp hwindow] + have hc : (⌈w⌉₊ : ℚ) < w + 1 := Nat.ceil_lt_add_one hw + have heq : (((32 * F + 2) * 2 ^ exponent : ℕ) : ℚ) * + ((2 : ℚ) ^ (-(exponent : ℤ)) * b) = (32 * (F : ℚ) + 2) * b := by + push_cast + rw [zpow_neg, zpow_natCast] + field_simp + rw [heq] + nlinarith only [hc, hw', hbR] + +def preparedLocalGroupScaleBitBudget (M P F exponent eM eF eb B : ℕ) : ℕ := + let K := (32 * F + 2) * 2 ^ exponent + 2 + let C := 16 * B + 200 + 2000 * (B + 4) ^ 2 + 500 * (B + 1) ^ 2 + + targetCellsBitBudget K K (4 * B + 40) + + K ^ 2 * (groupScalesBitBudget eM eb eF + + preparedCellGroupBitBudget M (7 + eM + eF) exponent (2 ^ eb) P C + 4) + eb + 4 + +theorem preparedLocalGroupScaleWithWork_cost {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (P F exponent Q eM eF eb B : ℕ) + (hMdef : M = 2 ^ eM) (hFdef : F = 2 ^ eF) (hPpos : 0 < P) + (tau a : BinaryFraction) (parentInitial : TargetInterval target.length → BinaryFraction) + (child initial current : Fin M → TargetInterval target.length → BinaryFraction) + (draw : CellGroupDraws M F Q) (query : TargetInterval target.length) + (hB : 7 ≤ B) (hnx : Nat.size source.length + 2 ≤ B) + (hny : Nat.size target.length + 2 ≤ B) (hM : Nat.size M + 2 ≤ B) + (hQ : Nat.size Q + 2 ≤ B) (hP : Nat.size P ≤ B) + (hF : Nat.size F + 2 ≤ B) (he : exponent + 1 ≤ B) (heb : eb ≤ B) + (hes : eM + eF + 7 ≤ B) + (htau : tau.width ≤ B) (ha : a.width ≤ B) + (hparent : ∀ q, (parentInitial q).width ≤ B) + (hchild : ∀ i q, (child i q).width ≤ B) + (hinitial : ∀ i q, (initial i q).width ≤ B) + (hcurrent : ∀ i q, (current i q).width ≤ B) + (hnonneg : 0 ≤ (parentInitial query).value) + (hwindow : (parentInitial query).value / (16 * F) ≤ (2 ^ eb : ℕ)) + (hPdyadic : ∃ j : ℕ, P = 2 ^ j) : + (preparedLocalGroupScaleWithWork source target parent P F exponent Q eM eF eb + hMdef hFdef hPpos tau a parentInitial child initial current draw query).2 ≤ + preparedLocalGroupScaleBitBudget M P F exponent eM eF eb B := by + let b := 2 ^ eb + let side := canonicalMulWithWork (inversePowerTwo exponent) (nat b) + let radius := naturalCeilingWithWork (parentInitial query) + let cells := targetCellsWithWork side.1 (bitWordValue radius.1) query + let K := (32 * F + 2) * 2 ^ exponent + 2 + let C := 16 * B + 200 + have htheta : (inversePowerTwo exponent).width ≤ B := + by rw [inversePowerTwo_width]; exact he + have hb : Nat.size b + 2 ≤ B + 3 := by dsimp only [b]; rw [Nat.size_pow]; omega + have hbn : (nat b).width ≤ B + 3 := (nat_width_le b).trans hb + have hsw := canonicalMulWithWork_width (inversePowerTwo exponent) (nat b) (B + 3) + (by omega) hbn + have hsc := canonicalMulWithWork_cost (inversePowerTwo exponent) (nat b) (B + 3) + (by omega) hbn + have hrw : Nat.size (bitWordValue radius.1) ≤ B + 2 := + (Nat.size_le.mpr (bitWordValue_lt_pow_length radius.1)).trans + ((naturalCeilingWithWork_length (parentInitial query)).trans (by have hh := hparent query; omega)) + have hrc := (naturalCeilingWithWork_cost (parentInitial query)).trans + (Nat.mul_le_mul_left 500 (Nat.pow_le_pow_left (Nat.add_le_add_right (hparent query) 1) 2)) + have hcoords (p : ℕ) : (localCellCoordinates side.1.value p (bitWordValue radius.1)).length ≤ K := by + simp only [side, canonicalMulWithWork_value, inversePowerTwo_value, nat_value, + radius, naturalCeilingWithWork_value] + exact queryCellCoordinates_length F b exponent p (parentInitial query).value + (by rw [hFdef]; exact Nat.succ_le_of_lt (Nat.two_pow_pos _)) + (Nat.succ_le_of_lt (Nat.two_pow_pos _)) hnonneg hwindow + have hcc := targetCellsWithWork_cost side.1 (bitWordValue radius.1) (4 * B + 40) + query (by change side.1.width ≤ _ at hsw; omega) + (by omega) (by omega) + have hcells : cells.2 ≤ targetCellsBitBudget K K (4 * B + 40) := hcc.trans (by + unfold targetCellsBitBudget + gcongr <;> apply hcoords) + have hlen : cells.1.length ≤ K ^ 2 := by + rw [targetCellsWithWork_value] + simp only [side, canonicalMulWithWork_value, inversePowerTwo_value, nat_value, + radius, naturalCeilingWithWork_value] + exact localTargetCells_query_length F b exponent query (parentInitial query).value + (by rw [hFdef]; exact Nat.succ_le_of_lt (Nat.two_pow_pos _)) + (Nat.succ_le_of_lt (Nat.two_pow_pos _)) hnonneg hwindow + have hslen : (groupDyadicScales M b (nat F).value).length = 7 + eM + eF := by + have hh := computedGroupScales_value M b F eM eb eF hMdef rfl hFdef + have hlen' := congrArg List.length hh + rw [List.length_map, groupScalesWithWork_length] at hlen' + exact hlen'.symm + have hcell (cell : ℕ × ℕ) (hc : cell ∈ cells.1) := + targetCellsWithWork_keys side.1 (bitWordValue radius.1) (4 * B + 40) query + (by change side.1.width ≤ _ at hsw; omega) + (by omega) (by omega) cell hc + have hentry (cell : ℕ × ℕ) (hc : cell ∈ cells.1) : + (preparedComputedCellGroupWithWork source target parent b P F exponent Q eM eb eF + hMdef rfl hFdef hPpos tau a parentInitial child initial current + (Eq.mpr (congrArg (cellScaleDraw M b Q) (nat_value F)) (draw b cell)) cell).2 ≤ + groupScalesBitBudget eM eb eF + + preparedCellGroupBitBudget M (7 + eM + eF) exponent b P C + 1 := by + have hk := hcell cell hc + have hh := preparedComputedCellGroupWithWork_cost source target parent b P F exponent Q eM eb eF C + hMdef rfl hFdef hPpos tau a parentInitial child initial current + (Eq.mpr (congrArg (cellScaleDraw M b Q) (nat_value F)) (draw b cell)) cell + (by dsimp only [C]; omega) (by dsimp only [C]; omega) (by dsimp only [C]; omega) + (by dsimp only [C]; omega) (by dsimp only [C]; omega) (by dsimp only [C]; omega) + (by dsimp only [C]; omega) (by dsimp only [C]; omega) (by dsimp only [C]; omega) + (htau.trans (by dsimp only [C]; omega)) (ha.trans (by dsimp only [C]; omega)) + (fun q => (hparent q).trans (by dsimp only [C]; omega)) + (fun i q => (hchild i q).trans (by dsimp only [C]; omega)) + (fun i q => (hinitial i q).trans (by dsimp only [C]; omega)) + (fun i q => (hcurrent i q).trans (by dsimp only [C]; omega)) + (by dsimp only [C]; omega) (by dsimp only [C]; omega) (by dsimp only [C]; omega) hPdyadic + simpa only [hslen] using hh + have hfilter := filterMapWithWork_cost (fun cell => + preparedComputedCellGroupWithWork source target parent b P F exponent Q eM eb eF + hMdef rfl hFdef hPpos tau a parentInitial child initial current + (Eq.mpr (congrArg (cellScaleDraw M b Q) (nat_value F)) (draw b cell)) cell) + cells.1 (groupScalesBitBudget eM eb eF + + preparedCellGroupBitBudget M (7 + eM + eF) exponent b P C + 1) hentry + have hf := hfilter.trans (Nat.mul_le_mul_right _ hlen) + change side.2 + radius.2 + cells.2 + + (filterMapWithWork (fun cell => + preparedComputedCellGroupWithWork source target parent b P F exponent Q eM eb eF + hMdef rfl hFdef hPpos tau a parentInitial child initial current + (Eq.mpr (congrArg (cellScaleDraw M b Q) (nat_value F)) (draw b cell)) cell) cells.1).2 + eb + 4 ≤ _ + change side.2 ≤ _ at hsc + change radius.2 ≤ _ at hrc + unfold preparedLocalGroupScaleBitBudget + change _ ≤ 2000 * (B + 4) ^ 2 + 500 * (B + 1) ^ 2 + + targetCellsBitBudget K K (4 * B + 40) + K ^ 2 * + (groupScalesBitBudget eM eb eF + preparedCellGroupBitBudget M (7 + eM + eF) exponent b P C + 4) + eb + 4 + simp only [Nat.add_assoc, Nat.reduceAdd] at hsc hf ⊢ + omega + +private theorem flatMap_cost_sum {α β : Type*} (f : α → List β × ℕ) + (xs : List α) (C L : α → ℕ) + (hc : ∀ x ∈ xs, (f x).2 ≤ C x) (hl : ∀ x ∈ xs, (f x).1.length ≤ L x) : + (arithmeticFlatMapWithWork f xs).2 ≤ (xs.map (fun x => C x + L x + 3)).sum := by + induction xs with + | nil => rfl + | cons x xs ih => + have hx := hc x (by simp) + have hxl := hl x (by simp) + have ht := ih (fun y hy => hc y (by simp [hy])) (fun y hy => hl y (by simp [hy])) + simp only [arithmeticFlatMapWithWork, List.map_cons, List.sum_cons] + omega + +def preparedLocalGroupsBitBudget (N M P F exponent eM eF B : ℕ) : ℕ := + let count := max 1 N.bits.length + let cells := ((32 * F + 2) * 2 ^ exponent + 2) ^ 2 + ((List.range count).map fun eb => localEligibilityBitBudget (B + 3) + + preparedLocalGroupScaleBitBudget M P F exponent eM eF eb B + eb + 4 + cells + 3).sum + + count + N.bits.length + 2 + +theorem preparedLocalCellGroupsWithWork_cost {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (N P F exponent Q eM eF B : ℕ) + (hMdef : M = 2 ^ eM) (hFdef : F = 2 ^ eF) (hPpos : 0 < P) + (tau a : BinaryFraction) (parentInitial : TargetInterval target.length → BinaryFraction) + (child initial current : Fin M → TargetInterval target.length → BinaryFraction) + (draw : CellGroupDraws M F Q) (query : TargetInterval target.length) + (hB : 7 ≤ B) (hN : Nat.size N ≤ B) (hnx : Nat.size source.length + 2 ≤ B) + (hny : Nat.size target.length + 2 ≤ B) (hM : Nat.size M + 2 ≤ B) + (hQ : Nat.size Q + 2 ≤ B) (hP : Nat.size P ≤ B) + (hF : Nat.size F + 2 ≤ B) (he : exponent + 1 ≤ B) (hes : eM + eF + 7 ≤ B) + (htau : tau.width ≤ B) (ha : a.width ≤ B) + (hparent : ∀ q, (parentInitial q).width ≤ B) + (hchild : ∀ i q, (child i q).width ≤ B) + (hinitial : ∀ i q, (initial i q).width ≤ B) + (hcurrent : ∀ i q, (current i q).width ≤ B) + (hnonneg : 0 ≤ (parentInitial query).value) + (hPdyadic : ∃ j : ℕ, P = 2 ^ j) : + (preparedLocalCellGroupsWithWork source target parent N P F exponent Q eM eF + hMdef hFdef hPpos tau a parentInitial child initial current draw query).2 ≤ + preparedLocalGroupsBitBudget N M P F exponent eM eF B := by + let count := max 1 N.bits.length + let K := ((32 * F + 2) * 2 ^ exponent + 2) ^ 2 + let callback := fun eb => + let guard := refinementScaleGuardWithWork F (2 ^ eb) a (parentInitial query) + if guard.1 then + let selected := preparedLocalGroupScaleWithWork source target parent P F exponent Q eM eF eb + hMdef hFdef hPpos tau a parentInitial child initial current draw query + (selected.1, guard.2 + selected.2 + eb + 4) + else ([], guard.2 + eb + 4) + have heb (eb : ℕ) (hh : eb ∈ List.range count) : eb ≤ B := by + have hh' := List.mem_range.mp hh + dsimp only [count] at hh' + rw [Nat.size_eq_bits_len] at hh' + omega + have hcallback (eb : ℕ) (hh : eb ∈ List.range count) : + (callback eb).2 ≤ localEligibilityBitBudget (B + 3) + + preparedLocalGroupScaleBitBudget M P F exponent eM eF eb B + eb + 4 ∧ + (callback eb).1.length ≤ K := by + have he' := heb eb hh + have hguard := refinementScaleGuardWithWork_cost F (2 ^ eb) (B + 3) a (parentInitial query) + (hB.trans (Nat.le_add_right B 3)) (by rw [Nat.size_pow]; omega) + (hF.trans (Nat.le_add_right B 3)) (ha.trans (Nat.le_add_right B 3)) + ((hparent query).trans (Nat.le_add_right B 3)) + dsimp only [callback] + split_ifs with hg + · have hwindow := ((refinementScaleGuardWithWork_value F (2 ^ eb) a (parentInitial query)).mp hg).1 + have hscale := preparedLocalGroupScaleWithWork_cost source target parent P F exponent Q eM eF eb B + hMdef hFdef hPpos tau a parentInitial child initial current draw query + hB hnx hny hM hQ hP hF he he' hes htau ha hparent hchild hinitial hcurrent hnonneg hwindow hPdyadic + have hlen : (preparedLocalGroupScaleWithWork source target parent P F exponent Q eM eF eb + hMdef hFdef hPpos tau a parentInitial child initial current draw query).1.length ≤ K := by + unfold preparedLocalGroupScaleWithWork + rw [filterMapWithWork_value] + apply (List.length_filterMap_le _ _).trans + rw [targetCellsWithWork_value] + simp only [canonicalMulWithWork_value, inversePowerTwo_value, nat_value, + naturalCeilingWithWork_value] + exact localTargetCells_query_length F (2 ^ eb) exponent query (parentInitial query).value + (by rw [hFdef]; exact Nat.succ_le_of_lt (Nat.two_pow_pos _)) + (Nat.succ_le_of_lt (Nat.two_pow_pos _)) hnonneg hwindow + have hcost := Nat.add_le_add_right (Nat.add_le_add_right + (Nat.add_le_add hguard hscale) eb) 4 + simpa only using And.intro hcost hlen + · have hcost := Nat.add_le_add_right (Nat.add_le_add_right + (hguard.trans (Nat.le_add_right (localEligibilityBitBudget (B + 3)) + (preparedLocalGroupScaleBitBudget M P F exponent eM eF eb B))) eb) 4 + simpa only [List.length_nil] using And.intro hcost (Nat.zero_le K) + have hsum := flatMap_cost_sum callback (List.range count) + (fun eb => localEligibilityBitBudget (B + 3) + + preparedLocalGroupScaleBitBudget M P F exponent eM eF eb B + eb + 4) + (fun _ => K) (fun eb hh => (hcallback eb hh).1) (fun eb hh => (hcallback eb hh).2) + change (arithmeticFlatMapWithWork callback (List.range count)).2 + count + N.bits.length + 2 ≤ _ + exact Nat.add_le_add_right (Nat.add_le_add_right (Nat.add_le_add_right hsum count) N.bits.length) 2 + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryPreparedLocalGroups.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryPreparedLocalGroups.lean new file mode 100644 index 0000000000000000000000000000000000000000..9d5c822a700e66cb43e7fb678435c3b01d1f57b9 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryPreparedLocalGroups.lean @@ -0,0 +1,137 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryLocalGroupActions +import OAI.Combinatorics.EditApproximation.Binary.BinaryPreparedComputedCell + +namespace OAI + +/-! Whole-cell query groups with fully constructed endpoint grids. -/ + +namespace EditApproximation +namespace BinaryFraction + +private theorem prepared_cellDraw_roundtrip (M b Q : ℕ) (f g : ℚ) (h : f = g) + (draw : cellScaleDraw M b Q g) : + Eq.mp (congrArg (cellScaleDraw M b Q) h) + (Eq.mpr (congrArg (cellScaleDraw M b Q) h) draw) = draw := by + cases h + rfl + +def preparedLocalGroupScaleWithWork {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (P F exponent Q eM eF eb : ℕ) + (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (hP : 0 < P) (tau a : BinaryFraction) + (parentInitial : TargetInterval target.length → BinaryFraction) + (child initial current : Fin M → TargetInterval target.length → BinaryFraction) + (draw : CellGroupDraws M F Q) (query : TargetInterval target.length) : + List (BinaryBellmanAction (TargetInterval target.length) + (Fin M × TargetInterval target.length) M) × ℕ := + let b := 2 ^ eb + let side := canonicalMulWithWork (inversePowerTwo exponent) (nat b) + let radius := naturalCeilingWithWork (parentInitial query) + let cells := targetCellsWithWork side.1 (bitWordValue radius.1) query + let selected := filterMapWithWork (fun cell => + preparedComputedCellGroupWithWork source target parent b P F exponent Q eM eb eF hM rfl hF hP + tau a parentInitial child initial current + (Eq.mpr (congrArg (cellScaleDraw M b Q) (nat_value F)) (draw b cell)) cell) cells.1 + (selected.1, side.2 + radius.2 + cells.2 + selected.2 + eb + 4) + +theorem preparedLocalGroupScaleWithWork_value {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (P F exponent Q eM eF eb : ℕ) + (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (hP : 0 < P) (tau a : BinaryFraction) + (parentInitial : TargetInterval target.length → BinaryFraction) + (child initial current : Fin M → TargetInterval target.length → BinaryFraction) + (draw : CellGroupDraws M F Q) (query : TargetInterval target.length) : + ((preparedLocalGroupScaleWithWork source target parent P F exponent Q eM eF eb hM hF hP tau a + parentInitial child initial current draw query).1.map BinaryBellmanAction.decode) = + (localTargetCells (((2 : ℚ) ^ (-(exponent : ℤ))) * (2 ^ eb : ℕ)) + ⌈(parentInitial query).value⌉₊ query).filterMap (fun cell => + chooseCellGroupAction source target parent (2 ^ eb) P F exponent Q tau.value a.value + (fun r => (parentInitial r).value) (fun i r => (child i r).value) + (fun i r => (initial i r).value) (fun i r => (current i r).value) cell (draw (2 ^ eb) cell)) := by + simp only [preparedLocalGroupScaleWithWork, filterMapWithWork_value, List.map_filterMap, + targetCellsWithWork_value, canonicalMulWithWork_value, inversePowerTwo_value, nat_value, + naturalCeilingWithWork_value] + apply List.filterMap_congr + intro cell _ + have hv := preparedComputedCellGroupWithWork_value source target parent (2 ^ eb) P F exponent Q eM eb eF + hM rfl hF tau a parentInitial child initial current + (Eq.mpr (congrArg (cellScaleDraw M (2 ^ eb) Q) (nat_value F)) (draw (2 ^ eb) cell)) cell hP + rw [prepared_cellDraw_roundtrip M (2 ^ eb) Q (nat F).value (F : ℚ) (nat_value F) + (draw (2 ^ eb) cell)] at hv + exact hv + +def preparedLocalCellGroupsWithWork {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (N P F exponent Q eM eF : ℕ) + (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (hP : 0 < P) (tau a : BinaryFraction) + (parentInitial : TargetInterval target.length → BinaryFraction) + (child initial current : Fin M → TargetInterval target.length → BinaryFraction) + (draw : CellGroupDraws M F Q) (query : TargetInterval target.length) : + List (BinaryBellmanAction (TargetInterval target.length) + (Fin M × TargetInterval target.length) M) × ℕ := + let count := max 1 N.bits.length + let groups := arithmeticFlatMapWithWork (fun eb => + let guard := refinementScaleGuardWithWork F (2 ^ eb) a (parentInitial query) + if guard.1 then + let selected := preparedLocalGroupScaleWithWork source target parent P F exponent Q eM eF eb hM hF hP + tau a parentInitial child initial current draw query + (selected.1, guard.2 + selected.2 + eb + 4) + else ([], guard.2 + eb + 4)) (List.range count) + (groups.1, groups.2 + count + N.bits.length + 2) + +private theorem flatMap_filter_condition {α β : Type*} (p : α → Bool) (f : α → List β) + (xs : List α) : + xs.flatMap (fun x => if p x then f x else []) = (xs.filter p).flatMap f := by + induction xs with + | nil => rfl + | cons x xs ih => + simp only [List.flatMap_cons, List.filter_cons] + cases p x <;> simp only [Bool.false_eq_true, ↓reduceIte, List.flatMap_cons, + List.nil_append, ih] + +theorem preparedLocalCellGroupsWithWork_value {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (N P F exponent Q eM eF : ℕ) + (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (hP : 0 < P) (tau a : BinaryFraction) + (parentInitial : TargetInterval target.length → BinaryFraction) + (child initial current : Fin M → TargetInterval target.length → BinaryFraction) + (draw : CellGroupDraws M F Q) (query : TargetInterval target.length) : + ((preparedLocalCellGroupsWithWork source target parent N P F exponent Q eM eF hM hF hP tau a + parentInitial child initial current draw query).1.map BinaryBellmanAction.decode) = + localCellGroupActions source target parent N P F exponent Q tau.value a.value + (fun r => (parentInitial r).value) (fun i r => (child i r).value) + (fun i r => (initial i r).value) (fun i r => (current i r).value) draw query := by + let predicate := fun b : ℕ => decide ((parentInitial query).value / (16 * (F : ℚ)) ≤ b ∧ + (b : ℚ) ≤ 8 * a.value * (parentInitial query).value) + let values := fun b : ℕ => (localTargetCells (((2 : ℚ) ^ (-(exponent : ℤ))) * b) + ⌈(parentInitial query).value⌉₊ query).filterMap (fun cell => + chooseCellGroupAction source target parent b P F exponent Q tau.value a.value + (fun r => (parentInitial r).value) (fun i r => (child i r).value) + (fun i r => (initial i r).value) (fun i r => (current i r).value) cell (draw b cell)) + have hscale : (List.range (max 1 N.bits.length)).map (fun eb => 2 ^ eb) = dyadicScales N := by + simpa only [dyadicScalesWithWork, arithmeticMapWithWork_value, powerTwoWord_value] using + dyadicScalesWithWork_value N + have hguard (eb : ℕ) : (refinementScaleGuardWithWork F (2 ^ eb) a (parentInitial query)).1 = + predicate (2 ^ eb) := Bool.eq_iff_iff.mpr (by + simp only [refinementScaleGuardWithWork_value, predicate, decide_eq_true_eq]) + unfold preparedLocalCellGroupsWithWork + simp only [arithmeticFlatMapWithWork_value, List.map_flatMap] + trans (List.range (max 1 N.bits.length)).flatMap + (fun eb => if predicate (2 ^ eb) then values (2 ^ eb) else []) + · apply List.flatMap_congr + intro eb _ + by_cases hg : (refinementScaleGuardWithWork F (2 ^ eb) a (parentInitial query)).1 = true + · have hp : predicate (2 ^ eb) = true := (hguard eb) ▸ hg + simp only [ite_eq_left hg, ite_eq_left hp] + exact preparedLocalGroupScaleWithWork_value source target parent P F exponent Q eM eF eb hM hF hP + tau a parentInitial child initial current draw query + · have hp : predicate (2 ^ eb) ≠ true := by simpa only [← hguard eb] using hg + simp only [ite_eq_right hg, ite_eq_right hp, List.map_nil] + · calc + _ = ((List.range (max 1 N.bits.length)).map (fun eb => 2 ^ eb)).flatMap + (fun b => if predicate b then values b else []) := + (List.flatMap_map _ _ _).symm + _ = (((List.range (max 1 N.bits.length)).map (fun eb => 2 ^ eb)).filter predicate).flatMap + values := flatMap_filter_condition _ _ _ + _ = _ := by rw [hscale]; rfl + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryPreparedLocalKernel.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryPreparedLocalKernel.lean new file mode 100644 index 0000000000000000000000000000000000000000..d49954cab8ec71283585ced96358ebb95bdd75f2 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryPreparedLocalKernel.lean @@ -0,0 +1,80 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryPreparedLocalOnline +import OAI.Combinatorics.EditApproximation.Binary.BinaryPreparedLocalGroups +import OAI.Combinatorics.EditApproximation.Binary.BinaryCachedContinuation + +namespace OAI + +/-! Full stored-data local refinement kernel. All candidate lists are +built by their literal counted routines, then the Bellman/online update +is performed. No action-list equality premise is assumed. -/ + +namespace EditApproximation +namespace BinaryFraction + +def preparedLocalKernelWithWork {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (N P F exponent H Q eM eF : ℕ) + (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) + (tau a eta kappa delta : BinaryFraction) + (parentInitial : TargetInterval target.length → BinaryFraction) + (childMass childInitial : Fin M → TargetInterval target.length → BinaryFraction) + (old current : Fin M × TargetInterval target.length → BinaryFraction) + (history : ℕ → Fin M × TargetInterval target.length → BinaryFraction) (t : ℕ) + (draw : CellGroupDraws M F Q) (integer : ℕ → TargetInterval target.length → ℕ) + (query : TargetInterval target.length) : BinaryFraction × ℕ := + let representatives := localRepresentativesWithWork N P F a parentInitial query + let groups := preparedLocalCellGroupsWithWork source target parent N P F exponent Q eM eF hM hF hP + tau a parentInitial childMass childInitial (fun i r => current (i, r)) draw query + let online := preparedLocalOnlineActionsWithWork source target parent N P F exponent H hP tau a eta kappa + parentInitial childMass childInitial history t integer query + let result := physicalContinuationWithWork parent representatives.1 P F delta (parentInitial query) + old current groups.1 online.1 query + (result.1, representatives.2 + groups.2 + online.2 + result.2 + 4) + +theorem preparedLocalKernelWithWork_value {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (N P F exponent H Q eM eF : ℕ) + (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) + (tau a eta kappa delta : BinaryFraction) + (parentInitial : TargetInterval target.length → BinaryFraction) + (childMass childInitial : Fin M → TargetInterval target.length → BinaryFraction) + (old current : Fin M × TargetInterval target.length → BinaryFraction) + (history : ℕ → Fin M × TargetInterval target.length → BinaryFraction) (t : ℕ) + (draw : CellGroupDraws M F Q) (integer : ℕ → TargetInterval target.length → ℕ) + (query : TargetInterval target.length) : + (preparedLocalKernelWithWork source target parent N P F exponent H Q eM eF hP hM hF + tau a eta kappa delta parentInitial childMass childInitial old current history t draw integer query).1.value = + rationalLocalWideStep source target parent N P F exponent Q tau.value a.value delta.value + (fun r => (parentInitial r).value) (fun i r => (childMass i r).value) + (fun i r => (childInitial i r).value) (fun i r => (old (i, r)).value) + (fun i r => (current (i, r)).value) draw + (localOnlineCandidates source target parent N P F exponent H tau.value a.value eta.value kappa.value + (fun r => (parentInitial r).value) (fun i r => (childMass i r).value) + (fun i r => (childInitial i r).value) (fun i s r => (history s (i, r)).value) t integer query) query := by + unfold preparedLocalKernelWithWork + rw [physicalContinuationWithWork_value _ _ _ _ _ _ _ _ _ _ _ hP] + rw [localRepresentativesWithWork_value N P F hP a parentInitial query, + preparedLocalCellGroupsWithWork_value source target parent N P F exponent Q eM eF hM hF hP tau a + parentInitial childMass childInitial (fun i r => current (i, r)) draw query, + preparedLocalOnlineActionsWithWork_value source target parent N P F exponent H hP tau a eta kappa + parentInitial childMass childInitial history t integer query] + rfl + +def cachedPreparedLocalKernelWithWork {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (N P F exponent H Q eM eF : ℕ) + (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) + (tau a eta kappa delta : BinaryFraction) + (parentInitial : TargetInterval target.length → BinaryFraction) + (childMass childInitial : Fin M → TargetInterval target.length → BinaryFraction) + (old current : Fin M × TargetInterval target.length → BinaryFraction) + (history : ℕ → Fin M × TargetInterval target.length → BinaryFraction) (t : ℕ) + (draw : CellGroupDraws M F Q) (integer : ℕ → TargetInterval target.length → ℕ) + (query : TargetInterval target.length) (base : List Bool) (hbase : 0 < bitWordValue base) + (remaining : ℕ) : BinaryFraction × ℕ := + finishCachedWithWork + (preparedLocalKernelWithWork source target parent N P F exponent H Q eM eF hP hM hF + tau a eta kappa delta parentInitial childMass childInitial old current history t draw integer query) + base hbase remaining + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryPreparedLocalOnline.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryPreparedLocalOnline.lean new file mode 100644 index 0000000000000000000000000000000000000000..689be432572b566c67f93bf3f2dad02e47e9ee06 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryPreparedLocalOnline.lean @@ -0,0 +1,117 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryPreparedOnline +import OAI.Combinatorics.EditApproximation.Binary.BinaryRefinementLists + +namespace OAI + +/-! One rounded center is queried at each retained dyadic scale. Both +eligibility and the complete online optimizer are charged. -/ + +namespace EditApproximation +namespace BinaryFraction + +def preparedLocalOnlineScaleWithWork {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (P F exponent H e : ℕ) (hP : 0 < P) + (tau a eta kappa : BinaryFraction) (parentInitial : TargetInterval target.length → BinaryFraction) + (child initial : Fin M → TargetInterval target.length → BinaryFraction) + (table : ℕ → Fin M × TargetInterval target.length → BinaryFraction) (t : ℕ) + (integer : ℕ → TargetInterval target.length → ℕ) (query : TargetInterval target.length) : + Option (BinaryBellmanAction (TargetInterval target.length) + (Fin M × TargetInterval target.length) M) × ℕ := + let b := 2 ^ e + let spacing := seedGridSpacingWithWork b P + let center := roundStateWithWork (bitWordValue spacing.1) (seedGridSpacingWithWork_pos b P hP) query + let eligible := centerEligibilityWithWork b F a (parentInitial center.1) + if eligible.1 then + let selected := preparedOnlineWithWork source target parent P F exponent H b (Nat.two_pow_pos e) hP + tau eta kappa child initial table t center.1 (integer b center.1) + (selected.1, spacing.2 + center.2 + eligible.2 + selected.2 + e + 4) + else (none, spacing.2 + center.2 + eligible.2 + e + 3) + +theorem preparedLocalOnlineScaleWithWork_value {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (P F exponent H e : ℕ) (hP : 0 < P) + (tau a eta kappa : BinaryFraction) (parentInitial : TargetInterval target.length → BinaryFraction) + (child initial : Fin M → TargetInterval target.length → BinaryFraction) + (table : ℕ → Fin M × TargetInterval target.length → BinaryFraction) (t : ℕ) + (integer : ℕ → TargetInterval target.length → ℕ) (query : TargetInterval target.length) : + ((preparedLocalOnlineScaleWithWork source target parent P F exponent H e hP tau a eta kappa parentInitial + child initial table t integer query).1.map BinaryBellmanAction.decode) = + (let b := 2 ^ e + let r := roundInterval (seedGridSpacing b P) query + if (b : ℚ) / (4 * a.value) ≤ (parentInitial r).value ∧ + (parentInitial r).value ≤ 8 * F * b then + keyedOnlineCandidate source target parent P F exponent H b tau.value eta.value kappa.value + (fun i q => (child i q).value) (fun i q => (initial i q).value) + (fun i s q => (table s (i, q)).value) t r (integer b r) + else none) := by + unfold preparedLocalOnlineScaleWithWork + simp only [roundStateWithWork_value, seedGridSpacingWithWork_value _ _ hP] + by_cases h : (centerEligibilityWithWork (2 ^ e) F a + (parentInitial (roundInterval (seedGridSpacing (2 ^ e) P) query))).1 = true + · have hp := (centerEligibilityWithWork_value _ _ _ _).mp h + rw [ite_eq_left h, ite_eq_left hp] + exact preparedOnlineWithWork_value source target parent P F exponent H (2 ^ e) (Nat.two_pow_pos e) hP + tau eta kappa child initial table t (roundInterval (seedGridSpacing (2 ^ e) P) query) + (integer (2 ^ e) (roundInterval (seedGridSpacing (2 ^ e) P) query)) + · have hp : ¬ (((2 ^ e : ℕ) : ℚ) / (4 * a.value) ≤ + (parentInitial (roundInterval (seedGridSpacing (2 ^ e) P) query)).value ∧ + (parentInitial (roundInterval (seedGridSpacing (2 ^ e) P) query)).value ≤ 8 * F * (2 ^ e : ℕ)) := + fun hx => h ((centerEligibilityWithWork_value _ _ _ _).mpr hx) + rw [ite_eq_right h, ite_eq_right hp] + rfl + +def preparedLocalOnlineActionsWithWork {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (N P F exponent H : ℕ) (hP : 0 < P) + (tau a eta kappa : BinaryFraction) (parentInitial : TargetInterval target.length → BinaryFraction) + (child initial : Fin M → TargetInterval target.length → BinaryFraction) + (table : ℕ → Fin M × TargetInterval target.length → BinaryFraction) (t : ℕ) + (integer : ℕ → TargetInterval target.length → ℕ) (query : TargetInterval target.length) : + List (BinaryBellmanAction (TargetInterval target.length) + (Fin M × TargetInterval target.length) M) × ℕ := + let scales := queryExponentsWithWork N F a (parentInitial query) + let selected := filterMapWithWork + (fun e => preparedLocalOnlineScaleWithWork source target parent P F exponent H e hP tau a eta kappa + parentInitial child initial table t integer query) scales.1 + (selected.1, scales.2 + selected.2 + 1) + +theorem preparedLocalOnlineActionsWithWork_value {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (N P F exponent H : ℕ) (hP : 0 < P) + (tau a eta kappa : BinaryFraction) (parentInitial : TargetInterval target.length → BinaryFraction) + (child initial : Fin M → TargetInterval target.length → BinaryFraction) + (table : ℕ → Fin M × TargetInterval target.length → BinaryFraction) (t : ℕ) + (integer : ℕ → TargetInterval target.length → ℕ) (query : TargetInterval target.length) : + ((preparedLocalOnlineActionsWithWork source target parent N P F exponent H hP tau a eta kappa parentInitial + child initial table t integer query).1.map BinaryBellmanAction.decode) = + localOnlineCandidates source target parent N P F exponent H tau.value a.value eta.value kappa.value + (fun r => (parentInitial r).value) (fun i r => (child i r).value) + (fun i r => (initial i r).value) (fun i s r => (table s (i, r)).value) t integer query := by + unfold preparedLocalOnlineActionsWithWork + simp only [filterMapWithWork_value, List.map_filterMap] + trans (queryExponentsWithWork N F a (parentInitial query)).1.filterMap (fun e => + let b := 2 ^ e + let r := roundInterval (seedGridSpacing b P) query + if (b : ℚ) / (4 * a.value) ≤ (parentInitial r).value ∧ (parentInitial r).value ≤ 8 * F * b then + keyedOnlineCandidate source target parent P F exponent H b tau.value eta.value kappa.value + (fun i q => (child i q).value) (fun i q => (initial i q).value) + (fun i s q => (table s (i, q)).value) t r (integer b r) + else none) + · apply List.filterMap_congr + intro e _ + exact preparedLocalOnlineScaleWithWork_value source target parent P F exponent H e hP tau a eta kappa + parentInitial child initial table t integer query + · trans ((queryExponentsWithWork N F a (parentInitial query)).1.map (fun e => 2 ^ e)).filterMap + (fun b => + let r := roundInterval (seedGridSpacing b P) query + if (b : ℚ) / (4 * a.value) ≤ (parentInitial r).value ∧ (parentInitial r).value ≤ 8 * F * b then + keyedOnlineCandidate source target parent P F exponent H b tau.value eta.value kappa.value + (fun i q => (child i q).value) (fun i q => (initial i q).value) + (fun i s q => (table s (i, q)).value) t r (integer b r) + else none) + · rw [List.filterMap_map] + rfl + · rw [queryExponentsWithWork_value] + rfl + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryPreparedLocalOnlineWork.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryPreparedLocalOnlineWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..d6c2ea0c1e499f9d7647b73ef5a47113058c5935 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryPreparedLocalOnlineWork.lean @@ -0,0 +1,157 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryPreparedOnlineWork +import OAI.Combinatorics.EditApproximation.Binary.BinaryLocalRepresentativeWork +import OAI.Combinatorics.EditApproximation.Binary.BinaryPreparedLocalOnline + +namespace OAI + +/-! All selected scales execute rounding, the center guard, and the complete +sampled optimizer. The list contains at most one action per tested scale. -/ + +namespace EditApproximation +namespace BinaryFraction + +def preparedLocalOnlineScaleBitBudget (M P B S : ℕ) : ℕ := + let W := B + 4 + 100 * (W + 2) ^ 2 + (500 * (W + 1) ^ 2 + 1) + + localEligibilityBitBudget W + preparedOnlineBitBudget M P W S + B + 4 + +def preparedLocalOnlineBitBudget (M P B S : ℕ) : ℕ := + queryExponentsBitBudget B + (B + 1) * (preparedLocalOnlineScaleBitBudget M P B S + 3) + 1 + +theorem preparedLocalOnlineScaleWithWork_cost {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (P F exponent H e B E S : ℕ) + (hPpos : 0 < P) (hMpos : 0 < M) + (tau a eta kappa : BinaryFraction) (parentInitial : TargetInterval target.length → BinaryFraction) + (child initial : Fin M → TargetInterval target.length → BinaryFraction) + (table : ℕ → Fin M × TargetInterval target.length → BinaryFraction) (t : ℕ) + (integer : ℕ → TargetInterval target.length → ℕ) (query : TargetInterval target.length) + (hB : 7 ≤ B) (heScale : e ≤ B) (hnx : Nat.size source.length + 2 ≤ B) + (hny : Nat.size target.length + 2 ≤ B) (hMb : Nat.size M ≤ B) + (hP : Nat.size P ≤ B) (hF : Nat.size F + 2 ≤ B) + (he : exponent + 1 ≤ B) (hH : Nat.size H ≤ B) + (hdBits : Nat.size (M * (40 * P + 2) ^ 2) ≤ B) + (hKBits : Nat.size ((H + M * (40 * P + 2) ^ 2 + 2) ^ 80) ≤ B) + (hInteger : ∀ b r, Nat.size (integer b r) ≤ B) + (htau : tau.width ≤ B) (ha : a.width ≤ B) (heta : eta.width ≤ B) (hkappa : kappa.width ≤ B) + (hparent : ∀ r, (parentInitial r).width ≤ B) + (hchild : ∀ i q, (child i q).width ≤ B) (hinitial : ∀ i q, (initial i q).width ≤ B) + (htable : ∀ s ≤ t + 1, ∀ i q, (table s (i, q)).width ≤ B) + (hetaValue : |eta.value| ≤ E) (hkappaValue : 0 ≤ kappa.value ∧ kappa.value ≤ 1) + (hvalues : ∀ s ≤ t + 1, ∀ i q, 0 ≤ (table s (i, q)).value ∧ + (table s (i, q)).value ≤ (initial i q).value) + (hS : 2 ≤ S) (hMS : M ≤ S) (hPS : P ≤ S) (hES : E ≤ S) (htS : t ≤ S) + (hBS : 3 * (B + 4) + 4 ≤ S) (hvS : (40 * P + 2) ^ (2 * M) ≤ S) + (hcartS : ((40 * P + 2) ^ 2 + 1) ^ (M + 1) ≤ S) + (hKS : (H + M * (40 * P + 2) ^ 2 + 2) ^ 80 ≤ S) : + (preparedLocalOnlineScaleWithWork source target parent P F exponent H e hPpos tau a eta kappa + parentInitial child initial table t integer query).2 ≤ preparedLocalOnlineScaleBitBudget M P B S := by + let W := B + 4 + let spacing := seedGridSpacingWithWork (2 ^ e) P + let center := roundStateWithWork (bitWordValue spacing.1) + (seedGridSpacingWithWork_pos (2 ^ e) P hPpos) query + have hb : Nat.size (2 ^ e) + 2 ≤ W := by rw [Nat.size_pow]; dsimp only [W]; omega + have hspacing := seedGridSpacingWithWork_bounds (2 ^ e) P W (by omega) (by dsimp only [W]; omega) + have hspacingBits : Nat.size (bitWordValue spacing.1) ≤ W := by + rw [seedGridSpacingWithWork_value _ _ hPpos] + have hh : max 1 (2 ^ e / P) = 1 ∨ max 1 (2 ^ e / P) = 2 ^ e / P := max_choice _ _ + rcases hh with hh | hh + · rw [seedGridSpacing, hh, Nat.size_one] + dsimp only [W] + omega + · rw [seedGridSpacing, hh] + exact (Nat.size_le_size (Nat.div_le_self _ _)).trans (by omega) + have hround := roundStateWithWork_cost (bitWordValue spacing.1) + (seedGridSpacingWithWork_pos (2 ^ e) P hPpos) query W hspacingBits (by dsimp only [W]; omega) + have hguard := centerEligibilityWithWork_cost (2 ^ e) F W a (parentInitial center.1) + (by dsimp only [W]; omega) hb (by dsimp only [W]; omega) + (ha.trans (by dsimp only [W]; omega)) ((hparent _).trans (by dsimp only [W]; omega)) + have honline := preparedOnlineWithWork_cost source target parent P F exponent H (2 ^ e) W E S + (Nat.two_pow_pos _) hPpos hMpos tau eta kappa child initial table t center.1 + (integer (2 ^ e) center.1) (by dsimp only [W]; omega) + (by dsimp only [W]; omega) (by dsimp only [W]; omega) (by dsimp only [W]; omega) + hb (by dsimp only [W]; omega) (by dsimp only [W]; omega) (by dsimp only [W]; omega) + (by dsimp only [W]; omega) (by dsimp only [W]; omega) (by dsimp only [W]; omega) + ((hInteger _ _).trans (by dsimp only [W]; omega)) + (htau.trans (by dsimp only [W]; omega)) (heta.trans (by dsimp only [W]; omega)) + (hkappa.trans (by dsimp only [W]; omega)) + (fun i q => (hchild i q).trans (by dsimp only [W]; omega)) + (fun i q => (hinitial i q).trans (by dsimp only [W]; omega)) + (fun s hs i q => (htable s hs i q).trans (by dsimp only [W]; omega)) + hetaValue hkappaValue hvalues hS hMS hPS hES htS hBS hvS hcartS hKS + have hs : spacing.2 ≤ 100 * (W + 2) ^ 2 := hspacing.2 + have hr : center.2 ≤ 500 * (W + 1) ^ 2 + 1 := hround + unfold preparedLocalOnlineScaleWithWork + dsimp only + split_ifs + · change spacing.2 + center.2 + (centerEligibilityWithWork (2 ^ e) F a (parentInitial center.1)).2 + + (preparedOnlineWithWork source target parent P F exponent H (2 ^ e) (Nat.two_pow_pos e) hPpos + tau eta kappa child initial table t center.1 (integer (2 ^ e) center.1)).2 + e + 4 ≤ _ + unfold preparedLocalOnlineScaleBitBudget + change _ ≤ 100 * (W + 2) ^ 2 + (500 * (W + 1) ^ 2 + 1) + + localEligibilityBitBudget W + preparedOnlineBitBudget M P W S + B + 4 + omega + · change spacing.2 + center.2 + (centerEligibilityWithWork (2 ^ e) F a (parentInitial center.1)).2 + e + 3 ≤ _ + unfold preparedLocalOnlineScaleBitBudget + change _ ≤ 100 * (W + 2) ^ 2 + (500 * (W + 1) ^ 2 + 1) + + localEligibilityBitBudget W + preparedOnlineBitBudget M P W S + B + 4 + omega + +theorem preparedLocalOnlineActionsWithWork_cost {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (N P F exponent H B E S : ℕ) + (hPpos : 0 < P) (hMpos : 0 < M) + (tau a eta kappa : BinaryFraction) (parentInitial : TargetInterval target.length → BinaryFraction) + (child initial : Fin M → TargetInterval target.length → BinaryFraction) + (table : ℕ → Fin M × TargetInterval target.length → BinaryFraction) (t : ℕ) + (integer : ℕ → TargetInterval target.length → ℕ) (query : TargetInterval target.length) + (hB : 7 ≤ B) (hN : Nat.size N ≤ B) (hnx : Nat.size source.length + 2 ≤ B) + (hny : Nat.size target.length + 2 ≤ B) (hMb : Nat.size M ≤ B) + (hP : Nat.size P ≤ B) (hF : Nat.size F + 2 ≤ B) + (he : exponent + 1 ≤ B) (hH : Nat.size H ≤ B) + (hdBits : Nat.size (M * (40 * P + 2) ^ 2) ≤ B) + (hKBits : Nat.size ((H + M * (40 * P + 2) ^ 2 + 2) ^ 80) ≤ B) + (hInteger : ∀ b r, Nat.size (integer b r) ≤ B) + (htau : tau.width ≤ B) (ha : a.width ≤ B) (heta : eta.width ≤ B) (hkappa : kappa.width ≤ B) + (hparent : ∀ r, (parentInitial r).width ≤ B) + (hchild : ∀ i q, (child i q).width ≤ B) (hinitial : ∀ i q, (initial i q).width ≤ B) + (htable : ∀ s ≤ t + 1, ∀ i q, (table s (i, q)).width ≤ B) + (hetaValue : |eta.value| ≤ E) (hkappaValue : 0 ≤ kappa.value ∧ kappa.value ≤ 1) + (hvalues : ∀ s ≤ t + 1, ∀ i q, 0 ≤ (table s (i, q)).value ∧ + (table s (i, q)).value ≤ (initial i q).value) + (hS : 2 ≤ S) (hMS : M ≤ S) (hPS : P ≤ S) (hES : E ≤ S) (htS : t ≤ S) + (hBS : 3 * (B + 4) + 4 ≤ S) (hvS : (40 * P + 2) ^ (2 * M) ≤ S) + (hcartS : ((40 * P + 2) ^ 2 + 1) ^ (M + 1) ≤ S) + (hKS : (H + M * (40 * P + 2) ^ 2 + 2) ^ 80 ≤ S) : + (preparedLocalOnlineActionsWithWork source target parent N P F exponent H hPpos tau a eta kappa + parentInitial child initial table t integer query).2 ≤ preparedLocalOnlineBitBudget M P B S := by + let scales := queryExponentsWithWork N F a (parentInitial query) + have hs := queryExponentsWithWork_bounds N F B a (parentInitial query) hB hN hF ha (hparent query) + have hc (e : ℕ) (heMem : e ∈ scales.1) : + (preparedLocalOnlineScaleWithWork source target parent P F exponent H e hPpos tau a eta kappa + parentInitial child initial table t integer query).2 ≤ preparedLocalOnlineScaleBitBudget M P B S := by + have heRange := heMem + change e ∈ (queryExponentsWithWork N F a (parentInitial query)).1 at heRange + simp only [queryExponentsWithWork, filterWithWork_value] at heRange + have heB : e ≤ B := by + have hh := List.mem_range.mp (List.mem_filter.mp heRange).1 + rw [Nat.size_eq_bits_len] at hh + omega + exact preparedLocalOnlineScaleWithWork_cost source target parent P F exponent H e B E S + hPpos hMpos tau a eta kappa parentInitial child initial table t integer query + hB heB hnx hny hMb hP hF he hH hdBits hKBits hInteger htau ha heta hkappa hparent + hchild hinitial htable hetaValue hkappaValue hvalues hS hMS hPS hES htS hBS hvS hcartS hKS + have hf := filterMapWithWork_cost + (fun e => preparedLocalOnlineScaleWithWork source target parent P F exponent H e hPpos + tau a eta kappa parentInitial child initial table t integer query) scales.1 + (preparedLocalOnlineScaleBitBudget M P B S) hc + have hfc := hf.trans (Nat.mul_le_mul_right _ hs.2) + change scales.2 + (filterMapWithWork + (fun e => preparedLocalOnlineScaleWithWork source target parent P F exponent H e hPpos + tau a eta kappa parentInitial child initial table t integer query) scales.1).2 + 1 ≤ _ + have hsc : scales.2 ≤ queryExponentsBitBudget B := hs.1 + unfold preparedLocalOnlineBitBudget + omega + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryPreparedOnline.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryPreparedOnline.lean new file mode 100644 index 0000000000000000000000000000000000000000..60bbbbf8da642860802165b803179a70ff4a8201 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryPreparedOnline.lean @@ -0,0 +1,136 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryKeyedOnline +import OAI.Combinatorics.EditApproximation.Binary.BinaryPreparedUnskipped + +namespace OAI + +/-! The keyed online branch executes the actual endpoint grids before +its guard and optimizer. The original finite source range is preserved. -/ + +namespace EditApproximation +namespace BinaryFraction + +private def preparedOnlineBandReference {M n : ℕ} (center : TargetInterval n) (b G : ℕ) (hG : 0 < G) + (initial : Fin M → TargetInterval n → BinaryFraction) + (table : ℕ → Fin M × TargetInterval n → BinaryFraction) (eta kappa : BinaryFraction) + (band : List (Fin M → TargetInterval n)) (hne : band ≠ []) (t integer : ℕ) : + PhysicalRationalAction M n := + sharedBandRationalAction center + (finiteOptimizerActionDraw band hne (bandChildEnvelope b band (fun i q => (initial i q).value)) + (rationalOnlineLinear eta.value kappa.value + (childGain (bandChildEnvelope b band (fun i q => (initial i q).value)) + (fun s coordinate => (table s coordinate).value)) + (childDecrement (bandChildEnvelope b band (fun i q => (initial i q).value)) + (fun s coordinate => (table s coordinate).value)) t) + G (G ^ 80) (boundedOnlineInteger _ (optimizerTriangularMass_positive _ (pow_pos hG _)) integer)) + +private theorem preparedOnlineBandReference_congr {M n : ℕ} (center : TargetInterval n) + (b G G' : ℕ) (hG : 0 < G) (hG' : 0 < G') (heq : G = G') + (initial : Fin M → TargetInterval n → BinaryFraction) + (table : ℕ → Fin M × TargetInterval n → BinaryFraction) (eta kappa : BinaryFraction) + (band band' : List (Fin M → TargetInterval n)) (hband : band = band') + (hne : band ≠ []) (hne' : band' ≠ []) (t integer : ℕ) : + preparedOnlineBandReference center b G hG initial table eta kappa band hne t integer = + preparedOnlineBandReference center b G' hG' initial table eta kappa band' hne' t integer := by + cases heq + cases hband + rfl + +def preparedOnlineWithWork {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (P F exponent H b : ℕ) (hb : 0 < b) (hP : 0 < P) + (tau eta kappa : BinaryFraction) + (child initial : Fin M → TargetInterval target.length → BinaryFraction) + (table : ℕ → Fin M × TargetInterval target.length → BinaryFraction) + (t : ℕ) (center : TargetInterval target.length) (integer : ℕ) : + Option (BinaryBellmanAction (TargetInterval target.length) + (Fin M × TargetInterval target.length) M) × ℕ := + let band := preparedRepresentativeWithWork parent center (parent.hi - parent.lo) b P + tau (inversePowerTwo exponent) child + let setup := onlineIndexSetupWithWork H band.1 + let G := setup.1 + let accepted := reduceOnlineIntegerWithWork (G ^ 80) (by + dsimp only [G, setup] + rw [onlineIndexSetupWithWork_value] + positivity) integer + if hband : band.1 = [] then (none, band.2 + setup.2 + accepted.2 + 1) else + let guard := preparedUnskippedCandidateWithWork source target parent b P exponent hb hP tau (nat F) child initial center + if guard.1.isSome then + let sampled := countedSampledOnlineWithWork center b initial table eta kappa band.1 hband + G (G ^ 80) t accepted.1 + (some sampled.1, band.2 + setup.2 + accepted.2 + guard.2 + sampled.2 + 2) + else (none, band.2 + setup.2 + accepted.2 + guard.2 + 1) + +theorem preparedOnlineWithWork_value {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (P F exponent H b : ℕ) (hb : 0 < b) (hP : 0 < P) + (tau eta kappa : BinaryFraction) + (child initial : Fin M → TargetInterval target.length → BinaryFraction) + (table : ℕ → Fin M × TargetInterval target.length → BinaryFraction) + (t : ℕ) (center : TargetInterval target.length) (integer : ℕ) : + ((preparedOnlineWithWork source target parent P F exponent H b hb hP tau eta kappa child initial table + t center integer).1.map BinaryBellmanAction.decode) = + keyedOnlineCandidate source target parent P F exponent H b tau.value eta.value kappa.value + (fun i q => (child i q).value) (fun i q => (initial i q).value) + (fun i s q => (table s (i, q)).value) t center integer := by + have hband := preparedRepresentativeWithWork_value source target parent center b P hP tau (inversePowerTwo exponent) child + simp only [inversePowerTwo_value] at hband + have hG : (onlineIndexSetupWithWork H (preparedRepresentativeWithWork parent center + (parent.hi - parent.lo) b P tau (inversePowerTwo exponent) child).1).1 = + keyedOnlineBandG source target parent P exponent H b tau.value (fun i q => (child i q).value) center := by + rw [onlineIndexSetupWithWork_value, listedBandCoordinates_length, hband] + rfl + have hGpos : 0 < (onlineIndexSetupWithWork H (preparedRepresentativeWithWork parent center + (parent.hi - parent.lo) b P tau (inversePowerTwo exponent) child).1).1 := by + rw [onlineIndexSetupWithWork_value] + omega + have hGpos' : 0 < keyedOnlineBandG source target parent P exponent H b tau.value + (fun i q => (child i q).value) center := by + rw [← hG] + exact hGpos + have htest := preparedUnskippedCandidateWithWork_value source target parent b P exponent hb hP tau (nat F) child initial center + unfold preparedOnlineWithWork + dsimp only + split_ifs with hempty hactive + · have he : representativeBandActions source target parent center b P tau.value + ((2 : ℚ) ^ (-(exponent : ℤ))) (fun i q => (child i q).value) = [] := hband.symm.trans hempty + simp only [Option.map_none, keyedOnlineCandidate, dite_eq_left he] + · have he : representativeBandActions source target parent center b P tau.value + ((2 : ℚ) ^ (-(exponent : ℤ))) (fun i q => (child i q).value) ≠ [] := + fun hz => hempty (hband.trans hz) + rw [htest] at hactive + rw [congrArg (fun f : ℚ => (testUnskippedBand source target parent b P exponent tau.value f + (fun i q => (child i q).value) (fun i q => (initial i q).value) center).isSome) (nat_value F)] at hactive + unfold keyedOnlineCandidate + simp only [dite_eq_right he] + cases ht : testUnskippedBand source target parent b P exponent tau.value (F : ℚ) + (fun i q => (child i q).value) (fun i q => (initial i q).value) center with + | none => + have hf : (none : Option (UnskippedBand source target parent b P exponent tau.value (F : ℚ) + (fun i q => (child i q).value) (fun i q => (initial i q).value))).isSome = true := by + simpa only [← ht] using hactive + cases hf + | some member => + simp only [Option.map_some, countedSampledOnlineWithWork_value, + sampledOnlineActionWithWork_value _ _ _ _ _ _ _ _ _ _ _ _ hb, + reduceOnlineIntegerWithWork_value] + apply congrArg some + exact preparedOnlineBandReference_congr center b _ _ hGpos hGpos' hG initial table eta kappa _ _ hband hempty he t integer + · have he : representativeBandActions source target parent center b P tau.value + ((2 : ℚ) ^ (-(exponent : ℤ))) (fun i q => (child i q).value) ≠ [] := + fun hz => hempty (hband.trans hz) + rw [htest] at hactive + rw [congrArg (fun f : ℚ => (testUnskippedBand source target parent b P exponent tau.value f + (fun i q => (child i q).value) (fun i q => (initial i q).value) center).isSome) (nat_value F)] at hactive + unfold keyedOnlineCandidate + simp only [dite_eq_right he, Option.map_none] + cases ht : testUnskippedBand source target parent b P exponent tau.value (F : ℚ) + (fun i q => (child i q).value) (fun i q => (initial i q).value) center with + | none => rfl + | some member => + apply False.elim + apply hactive + rw [ht] + rfl + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryPreparedOnlineReads.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryPreparedOnlineReads.lean new file mode 100644 index 0000000000000000000000000000000000000000..b64fbad77251911fbc67031a8a32c48a02ac9590 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryPreparedOnlineReads.lean @@ -0,0 +1,155 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryBandActionReads +import OAI.Combinatorics.EditApproximation.Binary.BinaryUnskippedReads +import OAI.Combinatorics.EditApproximation.Binary.BinaryPreparedOnline + +namespace OAI + +/-! The prepared online candidate executes its band reads, guard reads, +and historical reads. The accepted source integer and counted coordinate +representation are exactly the original ones. -/ + +namespace EditApproximation +namespace BinaryFraction + +private def preparedOnlineReadCore {n M : ℕ} {Action : Type*} (H integer : ℕ) + (band : List (Fin M → TargetInterval n) × ℕ) (guard : Bool × ℕ) + (sample : (xs : List (Fin M → TargetInterval n)) → xs ≠ [] → (G : ℕ) → + Fin (optimizerTriangularMass (G ^ 80)) → Action × ℕ) : Option Action × ℕ := + let setup := onlineIndexSetupWithWork H band.1 + let accepted := reduceOnlineIntegerWithWork (setup.1 ^ 80) (by + rw [onlineIndexSetupWithWork_value] + positivity) integer + if hband : band.1 = [] then (none, band.2 + setup.2 + accepted.2 + 1) else + if guard.1 then + let sampled := sample band.1 hband setup.1 accepted.1 + (some sampled.1, band.2 + setup.2 + accepted.2 + guard.2 + sampled.2 + 2) + else (none, band.2 + setup.2 + accepted.2 + guard.2 + 1) + +private theorem preparedOnlineReadCore_compare {n M : ℕ} {Action : Type*} (H integer : ℕ) + (band plain : List (Fin M → TargetInterval n) × ℕ) (guard plainGuard : Bool × ℕ) + (sample plainSample : (xs : List (Fin M → TargetInterval n)) → xs ≠ [] → (G : ℕ) → + Fin (optimizerTriangularMass (G ^ 80)) → Action × ℕ) + (B C E : ℕ) (hb : band.1 = plain.1) (hbc : band.2 ≤ plain.2 + B) + (hg : guard.1 = plainGuard.1) (hgc : guard.2 ≤ plainGuard.2 + C) + (hs : ∀ hne G draw, (sample plain.1 hne G draw).1 = (plainSample plain.1 hne G draw).1 ∧ + (sample plain.1 hne G draw).2 ≤ (plainSample plain.1 hne G draw).2 + E) : + (preparedOnlineReadCore H integer band guard sample).1 = + (preparedOnlineReadCore H integer plain plainGuard plainSample).1 ∧ + (preparedOnlineReadCore H integer band guard sample).2 ≤ + (preparedOnlineReadCore H integer plain plainGuard plainSample).2 + (B + C + E) := by + rcases band with ⟨xs, cost⟩ + rcases plain with ⟨ys, plainCost⟩ + dsimp only at hb hbc hs ⊢ + subst ys + unfold preparedOnlineReadCore + dsimp only + simp only [hg] + split_ifs with he ha + · exact ⟨rfl, by omega⟩ + · have hG : 0 < (onlineIndexSetupWithWork H xs).1 := by + rw [onlineIndexSetupWithWork_value] + omega + have hsample := hs he (onlineIndexSetupWithWork H xs).1 + (reduceOnlineIntegerWithWork ((onlineIndexSetupWithWork H xs).1 ^ 80) + (pow_pos hG _) integer).1 + exact ⟨congrArg some hsample.1, by omega⟩ + · exact ⟨rfl, by omega⟩ + +def preparedOnlineReadWithWork {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (P F exponent H b : ℕ) (hb : 0 < b) (hP : 0 < P) + (tau eta kappa : BinaryFraction) + (child initial : Fin M → TargetInterval target.length → BinaryFraction × ℕ) + (table : ℕ → Fin M × TargetInterval target.length → BinaryFraction × ℕ) + (R : ℕ) (hc : ∀ i q, (child i q).2 ≤ R) (hi : ∀ i q, (initial i q).2 ≤ R) + (t : ℕ) (center : TargetInterval target.length) (integer : ℕ) : + Option (BinaryBellmanAction (TargetInterval target.length) + (Fin M × TargetInterval target.length) M) × ℕ := + let band := preparedRepresentativeReadWithWork parent center (parent.hi - parent.lo) b P + tau (inversePowerTwo exponent) child + let setup := onlineIndexSetupWithWork H band.1 + let G := setup.1 + let accepted := reduceOnlineIntegerWithWork (G ^ 80) (by + dsimp only [G, setup] + rw [onlineIndexSetupWithWork_value] + positivity) integer + if hband : band.1 = [] then (none, band.2 + setup.2 + accepted.2 + 1) else + let guard := preparedUnskippedReadWithWork source target parent b P exponent hb hP tau (nat F) + child initial R R hc hi center + if guard.1.isSome then + let sampled := countedSampledOnlineReadWithWork center b initial table eta kappa band.1 hband + G (G ^ 80) t accepted.1 + (some sampled.1, band.2 + setup.2 + accepted.2 + guard.2 + sampled.2 + 2) + else (none, band.2 + setup.2 + accepted.2 + guard.2 + 1) + +def preparedOnlineReadExtra {nx n : ℕ} (M : ℕ) (parent : TargetInterval nx) + (center : TargetInterval n) (b P exponent R t : ℕ) (tau : BinaryFraction) + (child : Fin M → TargetInterval n → BinaryFraction) : ℕ := + let band := (preparedRepresentativeWithWork parent center (parent.hi - parent.lo) b P + tau (inversePowerTwo exponent) child).1 + 2 * representativeReadOverhead M (wideActionGridWithWork M parent center b P).1.length R + + 3 * (M * (band.length * (R + 3))) + + (listedBandCoordinates band).length * ((3 * t + 1) * R) + +theorem preparedOnlineReadWithWork_eq_cost {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (P F exponent H b : ℕ) (hb : 0 < b) (hP : 0 < P) + (tau eta kappa : BinaryFraction) + (child initial : Fin M → TargetInterval target.length → BinaryFraction × ℕ) + (table : ℕ → Fin M × TargetInterval target.length → BinaryFraction × ℕ) + (R : ℕ) (hc : ∀ i q, (child i q).2 ≤ R) (hi : ∀ i q, (initial i q).2 ≤ R) + (t : ℕ) (center : TargetInterval target.length) (integer : ℕ) + (ht : ∀ s ≤ t + 1, ∀ i, (table s i).2 ≤ R) : + (preparedOnlineReadWithWork source target parent P F exponent H b hb hP tau eta kappa + child initial table R hc hi t center integer).1 = + (preparedOnlineWithWork source target parent P F exponent H b hb hP tau eta kappa + (fun i q => (child i q).1) (fun i q => (initial i q).1) + (fun s i => (table s i).1) t center integer).1 ∧ + (preparedOnlineReadWithWork source target parent P F exponent H b hb hP tau eta kappa + child initial table R hc hi t center integer).2 ≤ + (preparedOnlineWithWork source target parent P F exponent H b hb hP tau eta kappa + (fun i q => (child i q).1) (fun i q => (initial i q).1) + (fun s i => (table s i).1) t center integer).2 + + preparedOnlineReadExtra M parent center b P exponent R t tau (fun i q => (child i q).1) := by + have hband := preparedRepresentativeReadWithWork_eq_cost parent center (parent.hi - parent.lo) + b P tau (inversePowerTwo exponent) child R hc + have hguard := preparedUnskippedReadWithWork_value source target parent b P exponent hb hP + tau (nat F) child initial R R hc hi center + have hguardCost := preparedUnskippedReadWithWork_cost source target parent b P exponent hb hP + tau (nat F) child initial R R hc hi center + have h := preparedOnlineReadCore_compare H integer + (preparedRepresentativeReadWithWork parent center (parent.hi - parent.lo) b P tau + (inversePowerTwo exponent) child) + (preparedRepresentativeWithWork parent center (parent.hi - parent.lo) b P tau + (inversePowerTwo exponent) (fun i q => (child i q).1)) + ((preparedUnskippedReadWithWork source target parent b P exponent hb hP tau (nat F) + child initial R R hc hi center).1.isSome, + (preparedUnskippedReadWithWork source target parent b P exponent hb hP tau (nat F) + child initial R R hc hi center).2) + ((preparedUnskippedCandidateWithWork source target parent b P exponent hb hP tau (nat F) + (fun i q => (child i q).1) (fun i q => (initial i q).1) center).1.isSome, + (preparedUnskippedCandidateWithWork source target parent b P exponent hb hP tau (nat F) + (fun i q => (child i q).1) (fun i q => (initial i q).1) center).2) + (fun xs hxs G draw => countedSampledOnlineReadWithWork center b initial table eta kappa + xs hxs G (G ^ 80) t draw) + (fun xs hxs G draw => countedSampledOnlineWithWork center b + (fun i q => (initial i q).1) (fun s i => (table s i).1) eta kappa xs hxs G (G ^ 80) t draw) + (representativeReadOverhead M (wideActionGridWithWork M parent center b P).1.length R) + (representativeReadOverhead M (wideActionGridWithWork M parent center b P).1.length R + + 2 * (M * ((preparedRepresentativeWithWork parent center (parent.hi - parent.lo) b P tau + (inversePowerTwo exponent) (fun i q => (child i q).1)).1.length * (R + 3)))) + (M * ((preparedRepresentativeWithWork parent center (parent.hi - parent.lo) b P tau + (inversePowerTwo exponent) (fun i q => (child i q).1)).1.length * (R + 3)) + + (listedBandCoordinates (preparedRepresentativeWithWork parent center (parent.hi - parent.lo) b P tau + (inversePowerTwo exponent) (fun i q => (child i q).1)).1).length * ((3 * t + 1) * R)) + hband.1 hband.2 (congrArg Option.isSome hguard) (by omega) + (fun hne G draw => by + simpa only [Nat.add_assoc] using countedSampledOnlineReadWithWork_eq_cost center b initial table eta kappa + _ hne G (G ^ 80) t R R draw hi (fun s hs i => ht s hs _)) + refine ⟨h.1, ?_⟩ + convert h.2 using 1 <;> first + | rfl + | (dsimp only [preparedOnlineReadExtra, preparedOnlineWithWork, preparedOnlineReadCore]; ring) + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryPreparedOnlineWork.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryPreparedOnlineWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..938d759443e05105bf702848b88e03798db8f252 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryPreparedOnlineWork.lean @@ -0,0 +1,151 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryPreparedOnline +import OAI.Combinatorics.EditApproximation.Binary.BinaryOnlineSetupWork +import OAI.Combinatorics.EditApproximation.Binary.BinarySampledOnlinePolynomial +import OAI.Combinatorics.EditApproximation.Geometry.PreparedBandPolynomial +import OAI.Combinatorics.EditApproximation.Geometry.LocalOnlineMassBound + +namespace OAI + +/-! The complete local online call: materialized endpoint grids, all band +guards, explicit index/range construction and the actual sampled optimizer. -/ + +namespace EditApproximation +namespace BinaryFraction + +def preparedOnlineBitBudget (M P B S : ℕ) : ℕ := + 2 * S ^ preparedBandBitDegree + + onlineIndexBitBudget M ((40 * P + 2) ^ (2 * M)) B + + reduceOnlineBitBudget B + S ^ sampledOnlineBitDegree + 3 + +theorem onlineIndexBitBudget_mono_vertices (M B vertices vertices' : ℕ) + (hvertices : vertices ≤ vertices') : + onlineIndexBitBudget M vertices B ≤ onlineIndexBitBudget M vertices' B := by + unfold onlineIndexBitBudget bandCoordinatesBitBudget + gcongr + +theorem preparedOnlineWithWork_cost {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (P F exponent H b B E S : ℕ) + (hbpos : 0 < b) (hPpos : 0 < P) (hMpos : 0 < M) + (tau eta kappa : BinaryFraction) + (child initial : Fin M → TargetInterval target.length → BinaryFraction) + (table : ℕ → Fin M × TargetInterval target.length → BinaryFraction) + (t : ℕ) (center : TargetInterval target.length) (integer : ℕ) + (hB : 7 ≤ B) (hnx : Nat.size source.length + 2 ≤ B) + (hny : Nat.size target.length + 2 ≤ B) (hMb : Nat.size M ≤ B) + (hb : Nat.size b + 2 ≤ B) (hP : Nat.size P ≤ B) (hF : Nat.size F + 2 ≤ B) + (he : exponent + 1 ≤ B) (hH : Nat.size H ≤ B) + (hdBits : Nat.size (M * (40 * P + 2) ^ 2) ≤ B) + (hKBits : Nat.size ((H + M * (40 * P + 2) ^ 2 + 2) ^ 80) ≤ B) + (hInteger : Nat.size integer ≤ B) + (htau : tau.width ≤ B) (heta : eta.width ≤ B) (hkappa : kappa.width ≤ B) + (hchild : ∀ i q, (child i q).width ≤ B) + (hinitial : ∀ i q, (initial i q).width ≤ B) + (htable : ∀ s ≤ t + 1, ∀ i q, (table s (i, q)).width ≤ B) + (hetaValue : |eta.value| ≤ E) (hkappaValue : 0 ≤ kappa.value ∧ kappa.value ≤ 1) + (hvalues : ∀ s ≤ t + 1, ∀ i q, 0 ≤ (table s (i, q)).value ∧ + (table s (i, q)).value ≤ (initial i q).value) + (hS : 2 ≤ S) (hMS : M ≤ S) (hPS : P ≤ S) (hES : E ≤ S) (htS : t ≤ S) + (hBS : 3 * B + 4 ≤ S) (hvS : (40 * P + 2) ^ (2 * M) ≤ S) + (hcartS : ((40 * P + 2) ^ 2 + 1) ^ (M + 1) ≤ S) + (hKS : (H + M * (40 * P + 2) ^ 2 + 2) ^ 80 ≤ S) : + (preparedOnlineWithWork source target parent P F exponent H b hbpos hPpos tau eta kappa + child initial table t center integer).2 ≤ preparedOnlineBitBudget M P B S := by + let band := preparedRepresentativeWithWork parent center (parent.hi - parent.lo) b P + tau (inversePowerTwo exponent) child + let setup := onlineIndexSetupWithWork H band.1 + let G := setup.1 + let accepted := reduceOnlineIntegerWithWork (G ^ 80) (by + dsimp only [G, setup] + rw [onlineIndexSetupWithWork_value] + positivity) integer + let V := (40 * P + 2) ^ (2 * M) + let D := M * (40 * P + 2) ^ 2 + have hbandValue : band.1 = representativeBandActions source target parent center b P tau.value + (inversePowerTwo exponent).value (fun i q => (child i q).value) := + preparedRepresentativeWithWork_value source target parent center b P hPpos tau (inversePowerTwo exponent) child + have hbandLen : band.1.length ≤ V := by + rw [hbandValue] + exact (representativeBandActions_length_le source target parent center b P tau.value + (inversePowerTwo exponent).value (fun i q => (child i q).value)).trans + (wideActionList_length_le M parent center b P hPpos) + have hd : (listedBandCoordinates band.1).length ≤ D := by + rw [listedBandCoordinates_length, hbandValue] + exact bandCoordinates_card_le parent center hPpos _ + (fun action ha => representativeBandActions_wide source target parent center b P tau.value + (inversePowerTwo exponent).value (fun i q => (child i q).value) action ha) + have hg : G ≤ H + D + 2 := by + dsimp only [G, setup] + rw [onlineIndexSetupWithWork_value] + omega + have hgp : 0 < G := by + dsimp only [G, setup] + rw [onlineIndexSetupWithWork_value] + omega + have hK : G ^ 80 ≤ (H + D + 2) ^ 80 := Nat.pow_le_pow_left hg 80 + have hGtotal : H + D + 2 ≤ S := + (Nat.le_pow (by omega : 0 < 80)).trans hKS + have hdimS : (listedBandCoordinates band.1).length ≤ S := hd.trans (by omega) + have hbS : B ≤ S := by omega + have hguard := (preparedUnskippedCandidateWithWork_uniform_cost source target parent b P exponent B + hbpos hPpos tau (nat F) child initial center hnx hny hMb hb hP he htau + ((nat_width_le F).trans hF) hchild hinitial).trans + (preparedUnskippedBitBudget_fixedPower exponent b M P V V B S hS (by omega) (by omega) + hMS hPS hvS hvS hbS hcartS) + have hwide : (wideActionGridWithWork M parent center b P).1.length ≤ V := by + have hh := congrArg List.length (wideActionGridWithWork_value M parent center b P hPpos) + simp only [List.length_map] at hh + rw [hh] + exact wideActionList_length_le M parent center b P hPpos + have hbandCost := preparedRepresentativeWithWork_complete_cost parent center b P B hPpos tau + (inversePowerTwo exponent) child (by omega) (by omega) hMb (by omega) hP htau + (by rw [inversePowerTwo_width]; exact he) hchild + have hrepMono := representativeCompleteBitBudget_mono_vertices M _ V (4 * B + 20) hwide + have hbandPower : band.2 ≤ S ^ preparedBandBitDegree := by + have hcap := preparedUnskippedBitBudget_fixedPower exponent b M P V V B S hS (by omega) + (by omega) hMS hPS hvS hvS hbS hcartS + apply le_trans _ hcap + unfold preparedUnskippedBitBudget + change band.2 ≤ _ at hbandCost + omega + have hsetup := onlineIndexSetupWithWork_bounds H B band.1 (by omega) hH hMb (by omega) + ((Nat.size_le_size hd).trans hdBits) + have hsetupCost : setup.2 ≤ onlineIndexBitBudget M V B := + hsetup.2.trans (onlineIndexBitBudget_mono_vertices M B _ _ hbandLen) + have hKsize : Nat.size (G ^ 80) ≤ B := (Nat.size_le_size hK).trans hKBits + have haccepted := reduceOnlineIntegerWithWork_bounds (G ^ 80) integer B (pow_pos hgp _) hKsize hInteger + have hsample (hne : band.1 ≠ []) : + (countedSampledOnlineWithWork center b initial table eta kappa band.1 hne G (G ^ 80) t accepted.1).2 ≤ + S ^ sampledOnlineBitDegree := by + apply countedSampledOnlineWithWork_fixedPower center b initial table eta kappa band.1 hne + G (G ^ 80) t (3 * B + 4) E S accepted.1 hS hMpos hbpos hMS + (hbandLen.trans hvS) hdimS (hg.trans hGtotal) (hK.trans hKS) htS hBS hES (by omega) + (by omega) (by omega) (by omega) haccepted.1 + (heta.trans (by omega)) (hkappa.trans (by omega)) + (fun i q => (hinitial i q).trans (by omega)) + (fun s hs i q => (htable s hs i q).trans (by omega)) hetaValue hkappaValue hvalues + dsimp only [V] at hsetupCost + unfold preparedOnlineWithWork + dsimp only + split_ifs with hempty hactive + · change band.2 + setup.2 + accepted.2 + 1 ≤ _ + have hc : accepted.2 ≤ reduceOnlineBitBudget B := haccepted.2 + unfold preparedOnlineBitBudget + omega + · have hs := hsample hempty + have hc : accepted.2 ≤ reduceOnlineBitBudget B := haccepted.2 + change band.2 + setup.2 + accepted.2 + + (preparedUnskippedCandidateWithWork source target parent b P exponent hbpos hPpos tau (nat F) + child initial center).2 + + (countedSampledOnlineWithWork center b initial table eta kappa band.1 hempty + G (G ^ 80) t accepted.1).2 + 2 ≤ _ + unfold preparedOnlineBitBudget + omega + · have hc : accepted.2 ≤ reduceOnlineBitBudget B := haccepted.2 + change band.2 + setup.2 + accepted.2 + _ + 1 ≤ _ + unfold preparedOnlineBitBudget + omega + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryPreparedOptimizer.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryPreparedOptimizer.lean new file mode 100644 index 0000000000000000000000000000000000000000..dbef4a875cf68c735a480ace69198e30f65da585 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryPreparedOptimizer.lean @@ -0,0 +1,97 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryOnlineInputWork + +namespace OAI + +/-! The complete Boolean optimizer call, including construction of its +vertices and optimistic linear vector from stored input fractions. -/ + +namespace EditApproximation +namespace BinaryFraction + +open Finset + +def preparedBandOptimizerWithWork {M d : ℕ} {σ : Type*} [DecidableEq σ] + (coordinates : Vector (Fin M × σ) d) (mass : Vector BinaryFraction M) + (table : ℕ → Fin M × σ → BinaryFraction) (eta kappa : BinaryFraction) + (band : List (Fin M → σ)) (G K t : ℕ) : Vector BinaryFraction d × ℕ := + let vertices := bandVerticesWithWork coordinates mass band + let linear := vectorMapWithWork d fun i => + onlineLinearWithWork (fun j => mass.get j) table eta kappa t (coordinates.get i) + let answer := finiteOptimizerWithWork vertices.1 linear.1 G K + (answer.1, vertices.2 + linear.2 + answer.2 + 2) + +theorem preparedBandOptimizerWithWork_value {M d : ℕ} {σ : Type*} [DecidableEq σ] + (coordinates : Vector (Fin M × σ) d) (mass : Vector BinaryFraction M) + (table : ℕ → Fin M × σ → BinaryFraction) (eta kappa : BinaryFraction) + (band : List (Fin M → σ)) (G K t : ℕ) : + (fun i => ((preparedBandOptimizerWithWork coordinates mass table eta kappa band G K t).1.get i).value) = + finiteRationalOptimizer univ + (band.map fun action i => actionVector (fun j => (mass.get j).value) action (coordinates.get i)) + (fun i => rationalOnlineLinear eta.value kappa.value + (childGain (fun j => (mass.get j).value) (fun s j => (table s j).value)) + (childDecrement (fun j => (mass.get j).value) (fun s j => (table s j).value)) + t (coordinates.get i)) G K := by + simp only [preparedBandOptimizerWithWork, finiteOptimizerWithWork_value, + bandVerticesWithWork_values, vectorMapWithWork_value, onlineLinearWithWork_value] + +def preparedBandOptimizerBitBudget (M d vertices G K t Be Bk Bm Bt E : ℕ) : ℕ := + bandPreparationBitBudget M d vertices Bm + + d * (onlineLinearBitBudget Be Bk Bm Bt t + 6) + + optimizerBitBudget d vertices G K (bandVertexWordBudget M Bm) (bandVertexWordBudget M Bm) + (onlineLinearStorageBudget Be Bk Bm Bt t) (E * (2 * t + 1)) + 2 + +theorem preparedBandOptimizerWithWork_cost {M d : ℕ} {σ : Type*} [DecidableEq σ] + (coordinates : Vector (Fin M × σ) d) (mass : Vector BinaryFraction M) + (table : ℕ → Fin M × σ → BinaryFraction) (eta kappa : BinaryFraction) + (band : List (Fin M → σ)) (G K t Be Bk Bm Bt E : ℕ) + (hband : band ≠ []) (he : eta.width ≤ Be) (hk : kappa.width ≤ Bk) + (hm : ∀ j, (mass.get j).width ≤ Bm) (hmpos : ∀ j, 0 < (mass.get j).value) + (ht : ∀ s ≤ t + 1, ∀ i, (table s (coordinates.get i)).width ≤ Bt) + (heabs : |eta.value| ≤ E) (hkrange : 0 ≤ kappa.value ∧ kappa.value ≤ 1) + (htrange : ∀ s ≤ t + 1, ∀ i, + 0 ≤ (table s (coordinates.get i)).value ∧ + (table s (coordinates.get i)).value ≤ (mass.get (coordinates.get i).1).value) : + (preparedBandOptimizerWithWork coordinates mass table eta kappa band G K t).2 ≤ + preparedBandOptimizerBitBudget M d band.length G K t Be Bk Bm Bt E := by + let vertices := (bandVerticesWithWork coordinates mass band).1 + let linear := (vectorMapWithWork d fun i => + onlineLinearWithWork (fun j => mass.get j) table eta kappa t (coordinates.get i)).1 + have hlength : vertices.length = band.length := by simp [vertices, bandVerticesWithWork] + have hvertices : vertices ≠ [] := by + intro h + rw [h, List.length_nil] at hlength + exact hband (List.length_eq_zero_iff.mp hlength.symm) + have hv (v : Vector BinaryFraction d) (hv : v ∈ vertices) (i : Fin d) := + bandVerticesWithWork_input_bounds coordinates mass band Bm hm hmpos v hv i + have hlwidth (i : Fin d) : (linear.get i).width ≤ onlineLinearStorageBudget Be Bk Bm Bt t := by + simp only [linear, vectorMapWithWork_value] + exact onlineLinearWithWork_storage (fun j => mass.get j) table eta kappa t + (coordinates.get i) Be Bk Bm Bt he hk (hm _) (fun s hs => ht s hs i) + have hlvalue (i : Fin d) : |(linear.get i).value| ≤ (E * (2 * t + 1) : ℕ) := by + simp only [linear, vectorMapWithWork_value, onlineLinearWithWork_value] + have h := rationalOnlineLinear_abs (fun j => (mass.get j).value) + (fun s j => (table s j).value) eta.value kappa.value t E (coordinates.get i) + heabs (hmpos _) hkrange (fun s hs => htrange s hs i) + simpa only [Nat.cast_mul, Nat.cast_add, Nat.cast_ofNat, Nat.cast_one] using h + have hc := finiteOptimizerWithWork_cost vertices linear G K (bandVertexWordBudget M Bm) + (bandVertexWordBudget M Bm) (onlineLinearStorageBudget Be Bk Bm Bt t) (E * (2 * t + 1)) + hvertices (fun v hv' i => ⟨(hv v hv' i).1, (hv v hv' i).2.1, (hv v hv' i).2.2.1⟩) + (fun v hv' i => (hv v hv' i).2.2.2) hlwidth hlvalue + rw [hlength] at hc + have hp := bandVerticesWithWork_cost coordinates mass band Bm hm + have hl := vectorMapWithWork_cost_le d + (fun i => onlineLinearWithWork (fun j => mass.get j) table eta kappa t (coordinates.get i)) + (onlineLinearBitBudget Be Bk Bm Bt t) (fun i => onlineLinearWithWork_cost + (fun j => mass.get j) table eta kappa t (coordinates.get i) Be Bk Bm Bt + he hk (hm _) (fun s hs => ht s hs i)) + change (bandVerticesWithWork coordinates mass band).2 + + (vectorMapWithWork d (fun i => onlineLinearWithWork (fun j => mass.get j) + table eta kappa t (coordinates.get i))).2 + + (finiteOptimizerWithWork vertices linear G K).2 + 2 ≤ _ + unfold preparedBandOptimizerBitBudget + omega + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryPreparedRepresentative.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryPreparedRepresentative.lean new file mode 100644 index 0000000000000000000000000000000000000000..809ec5ac70bdf23289d490dc0ed21e9c0edb647f --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryPreparedRepresentative.lean @@ -0,0 +1,41 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryWideChildWork +import OAI.Combinatorics.EditApproximation.Binary.BinaryBandTailWork + +namespace OAI + +/-! The representative constructor executes the balanced child grids +before materializing the Cartesian product and evaluating its scores. -/ + +namespace EditApproximation +namespace BinaryFraction + +def preparedRepresentativeWithWork {nx ny M : ℕ} (parent : TargetInterval nx) + (center : TargetInterval ny) (sourceLength b P : ℕ) (tau theta : BinaryFraction) + (child : Fin M → TargetInterval ny → BinaryFraction) : List (Fin M → TargetInterval ny) × ℕ := + let wide := wideActionGridWithWork M parent center b P + let result := representativeFromActionsWithWork parent center sourceLength b tau theta child + (wide.1.map Vector.get) + (result.1, wide.2 + result.2 + wide.1.length + 1) + +theorem preparedRepresentativeWithWork_eq {nx ny M : ℕ} (parent : TargetInterval nx) + (center : TargetInterval ny) (sourceLength b P : ℕ) (hP : 0 < P) + (tau theta : BinaryFraction) (child : Fin M → TargetInterval ny → BinaryFraction) : + (preparedRepresentativeWithWork parent center sourceLength b P tau theta child).1 = + (representativeBandWithWork parent center sourceLength b P tau theta child).1 := by + simp only [preparedRepresentativeWithWork, representativeBandWithWork, + wideActionGridWithWork_value M parent center b P hP, materializedWideActionsWithWork_value] + +@[simp] theorem preparedRepresentativeWithWork_value {α : Type*} (source target : List α) + {M : ℕ} (parent : TargetInterval source.length) (center : TargetInterval target.length) + (b P : ℕ) (hP : 0 < P) (tau theta : BinaryFraction) + (child : Fin M → TargetInterval target.length → BinaryFraction) : + (preparedRepresentativeWithWork parent center (parent.hi - parent.lo) b P tau theta child).1 = + representativeBandActions source target parent center b P tau.value theta.value + (fun i q => (child i q).value) := by + rw [preparedRepresentativeWithWork_eq _ _ _ _ _ hP] + exact representativeBandWithWork_value source target parent center b P tau theta child + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryPreparedRepresentativeWork.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryPreparedRepresentativeWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..d7b43216fda160b48e6a64dc6f5af70c4dd83855 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryPreparedRepresentativeWork.lean @@ -0,0 +1,77 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryPreparedRepresentative + +namespace OAI + +/-! Complete representative work, with every endpoint grid construction +and every score/prefix predicate charged. Only input word bounds occur. -/ + +namespace EditApproximation +namespace BinaryFraction + +def wideMaterializationBitBudget (M P B : ℕ) : ℕ := + M * (wideChildGridBitBudget P B + 6) + + (M + 1) * (6 * M + 10) * ((40 * P + 2) ^ 2 + 1) ^ (M + 1) + 1 + +theorem wideActionGridWithWork_complete_cost {nx ny : ℕ} (M : ℕ) + (parent : TargetInterval nx) (center : TargetInterval ny) (b P B : ℕ) + (hPpos : 0 < P) (hnx : Nat.size nx ≤ B) (hny : Nat.size ny ≤ B) + (hM : Nat.size M ≤ B) (hb : Nat.size b ≤ B) (hP : Nat.size P ≤ B) : + (wideActionGridWithWork M parent center b P).2 ≤ wideMaterializationBitBudget M P B := + wideActionGridWithWork_cost M parent center b P _ hPpos + (fun i => wideChildGridWithWork_cost parent center b P B i hPpos hnx hny hM hb hP) + +theorem preparedRepresentativeWithWork_complete_cost {nx ny M : ℕ} + (parent : TargetInterval nx) (center : TargetInterval ny) (b P B : ℕ) + (hPpos : 0 < P) (tau theta : BinaryFraction) + (child : Fin M → TargetInterval ny → BinaryFraction) + (hnx : Nat.size nx ≤ B) (hny : Nat.size ny ≤ B) + (hM : Nat.size M ≤ B) (hb : Nat.size b ≤ B) (hP : Nat.size P ≤ B) + (htau : tau.width ≤ B) (htheta : theta.width ≤ B) + (hchild : ∀ i q, (child i q).width ≤ B) : + (preparedRepresentativeWithWork parent center (parent.hi - parent.lo) b P tau theta child).2 ≤ + wideMaterializationBitBudget M P B + + representativeCompleteBitBudget M (wideActionGridWithWork M parent center b P).1.length (4 * B + 20) + + (wideActionGridWithWork M parent center b P).1.length + 1 := by + let wide := wideActionGridWithWork M parent center b P + let C := 4 * B + 20 + have hBC : B + 5 ≤ C := by dsimp only [C]; omega + have hcenterlo : Nat.size center.lo ≤ B := + (Nat.size_le_size (center.ordered.trans center.valid)).trans hny + have hcenterhi : Nat.size center.hi ≤ B := (Nat.size_le_size center.valid).trans hny + have hparentlo : Nat.size parent.lo ≤ B := + (Nat.size_le_size (parent.ordered.trans parent.valid)).trans hnx + have hparenthi : Nat.size parent.hi ≤ B := (Nat.size_le_size parent.valid).trans hnx + have hsource (i : Fin M) : Nat.size (sourceChild parent i).lo ≤ B ∧ + Nat.size (sourceChild parent i).hi ≤ B := + ⟨(Nat.size_le_size ((sourceChild parent i).ordered.trans (sourceChild parent i).valid)).trans hnx, + (Nat.size_le_size (sourceChild parent i).valid).trans hnx⟩ + have hanchor (x : ℕ) (hx : Nat.size x ≤ B) : + Nat.size (center.lo + (x - parent.lo)) + 2 ≤ C := by + have hs : Nat.size (x - parent.lo) ≤ B := (Nat.size_le_size (Nat.sub_le _ _)).trans hx + have ha := binaryNaturalAdd_size_le center.lo (x - parent.lo) + omega + have hradius : Nat.size (6 * b) + 2 ≤ C := by + have hp := natural_product_bit_length 6 b + have h6 : Nat.size 6 = 3 := by decide + omega + have htail := representativeFromActionsWithWork_complete_cost parent center + (parent.hi - parent.lo) b tau theta child (wide.1.map Vector.get) C + (by omega) (by omega) + (by have h := (Nat.size_le_size (Nat.sub_le parent.hi parent.lo)).trans hparenthi; omega) + (by omega) (by omega) (by omega) (by omega) (by omega) + (fun i => ⟨by have h := (hsource i).1; omega, by have h := (hsource i).2; omega⟩) + (fun i => ⟨hanchor _ (hsource i).1, hanchor _ (hsource i).2⟩) hradius + (fun states _ i => + ⟨by have h := (Nat.size_le_size ((states i).ordered.trans (states i).valid)).trans hny; omega, + by have h := (Nat.size_le_size (states i).valid).trans hny; omega⟩) + (fun _ _ i => (hchild i _).trans (by omega)) + have hwide := wideActionGridWithWork_complete_cost M parent center b P B hPpos hnx hny hM hb hP + simp only [List.length_map] at htail + change wide.2 + (representativeFromActionsWithWork parent center (parent.hi - parent.lo) + b tau theta child (wide.1.map Vector.get)).2 + wide.1.length + 1 ≤ _ + exact Nat.add_le_add_right (Nat.add_le_add_right (Nat.add_le_add hwide htail) _) _ + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryPreparedUnskipped.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryPreparedUnskipped.lean new file mode 100644 index 0000000000000000000000000000000000000000..a6a08d68dfa76ec02e99438be75bc7a746fcc2cc --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryPreparedUnskipped.lean @@ -0,0 +1,106 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryPreparedRepresentative + +namespace OAI + +/-! Complete band guards construct the actual child endpoint grids before +testing the rounded action. Proof fields carry no runtime cost. -/ + +namespace EditApproximation +namespace BinaryFraction + +private theorem prepared_rounded_band_congr {ny M : ℕ} (e b : ℕ) + {first second : List (Fin M → TargetInterval ny)} (h : first = second) + (hf : first ≠ []) (hs : second ≠ []) (initial : Fin M → TargetInterval ny → ℚ) : + canonicalRoundedBandAction e b first hf initial = + canonicalRoundedBandAction e b second hs initial := by + subst second + rfl + +def preparedUnskippedCandidateWithWork {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (b P thetaExponent : ℕ) (hb : 0 < b) (hP : 0 < P) + (tau F : BinaryFraction) (child initial : Fin M → TargetInterval target.length → BinaryFraction) + (center : TargetInterval target.length) : + Option (UnskippedBand source target parent b P thetaExponent tau.value F.value + (fun i q => (child i q).value) (fun i q => (initial i q).value)) × ℕ := + let band := preparedRepresentativeWithWork parent center (parent.hi - parent.lo) b P + tau (inversePowerTwo thetaExponent) child + if hband : band.1 = [] then (none, band.2 + 1) else + let wide := wideActionGridWithWork M parent center b P + let guard := unskippedGuardWithWork parent center b thetaExponent F band.1 + (wide.1.map Vector.get) hband initial + if hguard : guard.1 = true then + let facts := (unskippedGuardWithWork_value source target parent center b thetaExponent F + band.1 (wide.1.map Vector.get) hband initial hb).mp hguard + let hbandValue : band.1 = representativeBandActions source target parent center b P tau.value + ((2 : ℚ) ^ (-(thetaExponent : ℤ))) (fun i q => (child i q).value) := by + simpa only [inversePowerTwo_value] using preparedRepresentativeWithWork_value source target parent center b P hP + tau (inversePowerTwo thetaExponent) child + let hwideValue : wide.1.map Vector.get = wideActionList M parent center b P := + wideActionGridWithWork_value M parent center b P hP + (some { + center := center + nonempty := by + intro hzero + apply hband + exact hbandValue.trans hzero + sum_guard := by + simpa only [hbandValue] using facts.1 + wide_guard := by + have hw := facts.2.1 + rw [hwideValue] at hw + rw [prepared_rounded_band_congr thetaExponent b hbandValue hband _] at hw + exact hw + imbalance_guard := by + simpa only [hbandValue] using facts.2.2 }, + band.2 + wide.2 + guard.2 + wide.1.length + 3) + else (none, band.2 + wide.2 + guard.2 + wide.1.length + 2) + +@[simp] theorem preparedUnskippedCandidateWithWork_value {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (b P thetaExponent : ℕ) (hb : 0 < b) (hP : 0 < P) + (tau F : BinaryFraction) (child initial : Fin M → TargetInterval target.length → BinaryFraction) + (center : TargetInterval target.length) : + (preparedUnskippedCandidateWithWork source target parent b P thetaExponent hb hP tau F child initial center).1 = + testUnskippedBand source target parent b P thetaExponent tau.value F.value + (fun i q => (child i q).value) (fun i q => (initial i q).value) center := by + let band := representativeBandActions source target parent center b P tau.value + ((2 : ℚ) ^ (-(thetaExponent : ℤ))) (fun i q => (child i q).value) + have hbandValue : (preparedRepresentativeWithWork parent center (parent.hi - parent.lo) b P + tau (inversePowerTwo thetaExponent) child).1 = band := by + simpa only [inversePowerTwo_value] using + preparedRepresentativeWithWork_value source target parent center b P hP tau (inversePowerTwo thetaExponent) child + unfold preparedUnskippedCandidateWithWork testUnskippedBand + dsimp only + change _ = (if hband : band = [] then _ else _) + by_cases hband : band = [] + · have hactual := hbandValue.trans hband + simp only [dite_eq_left hactual, dite_eq_left hband] + · have hactual : (preparedRepresentativeWithWork parent center (parent.hi - parent.lo) b P + tau (inversePowerTwo thetaExponent) child).1 ≠ [] := fun h => hband (hbandValue.symm.trans h) + simp only [dite_eq_right hactual, dite_eq_right hband] + have hround := prepared_rounded_band_congr thetaExponent b hbandValue hactual hband + (fun j q => (initial j q).value) + have hguard := unskippedGuardWithWork_value source target parent center b thetaExponent F + (preparedRepresentativeWithWork parent center (parent.hi - parent.lo) b P + tau (inversePowerTwo thetaExponent) child).1 + ((wideActionGridWithWork M parent center b P).1.map Vector.get) hactual initial hb + conv_rhs at hguard => + rw [wideActionGridWithWork_value M parent center b P hP, hround] + simp only [hbandValue] + by_cases hs : (∑ i, bandChildEnvelope b band (fun j q => (initial j q).value) i) ≤ 64 * F.value * b + · rw [dite_eq_left hs] + by_cases hw : canonicalRoundedBandAction thetaExponent b band hband + (fun j q => (initial j q).value) ∈ wideActionList M parent center b P + · rw [dite_eq_left hw] + by_cases hg : ∀ i, |rationalStateGap + (substring source (sourceChild parent i).lo (sourceChild parent i).hi) target + (canonicalRoundedBandAction thetaExponent b band hband (fun j q => (initial j q).value) i)| ≤ + 2 * bandChildEnvelope b band (fun j q => (initial j q).value) i + · rw [dite_eq_left hg, dite_eq_left (hguard.mpr ⟨hs, hw, hg⟩)] + · rw [dite_eq_right hg, dite_eq_right (fun h => hg (hguard.mp h).2.2)] + · rw [dite_eq_right hw, dite_eq_right (fun h => hw (hguard.mp h).2.1)] + · rw [dite_eq_right hs, dite_eq_right (fun h => hs (hguard.mp h).1)] + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryPreparedUnskippedWork.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryPreparedUnskippedWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..b4c9533aced7a92508a27993b5ee119f892e4eff --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryPreparedUnskippedWork.lean @@ -0,0 +1,121 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryPreparedUnskipped +import OAI.Combinatorics.EditApproximation.Binary.BinaryPreparedRepresentativeWork +import OAI.Combinatorics.EditApproximation.Binary.BinaryUnskippedGuardWork +import OAI.Combinatorics.EditApproximation.Geometry.LocalArithmeticBudget + +namespace OAI + +/-! The complete unskipped-band constructor pays for both actual wide +grids, every prefix predicate, all child envelopes, and the final guards. -/ + +namespace EditApproximation +namespace BinaryFraction + +def preparedUnskippedBitBudget (e b M P v w B : ℕ) : ℕ := + 2 * wideMaterializationBitBudget M P B + + representativeCompleteBitBudget M w (4 * B + 20) + + unskippedGuardBitBudget e b M v w B + 2 * w + 4 + +theorem representativeCompleteBitBudget_mono_vertices (M v w B : ℕ) (h : v ≤ w) : + representativeCompleteBitBudget M v B ≤ representativeCompleteBitBudget M w B := by + unfold representativeCompleteBitBudget representativeTailBitBudget bandFromActionsBitBudget + wideMinimumBitBudget bandPredicateBitBudget anchorGuardBitBudget bandToleranceBitBudget + representativeGuardInputBudget naturalDistanceBitBudget + dsimp only + gcongr + +theorem unskippedGuardBitBudget_mono_vertices (e b M v v' w w' B : ℕ) + (hv : v ≤ v') (hw : w ≤ w') : + unskippedGuardBitBudget e b M v w B ≤ unskippedGuardBitBudget e b M v' w' B := by + unfold unskippedGuardBitBudget roundedBandBitBudget bandEnvelopeBitBudget + dsimp only + gcongr + +theorem preparedUnskippedBitBudget_mono_vertices (e b M P v v' w w' B : ℕ) + (hv : v ≤ v') (hw : w ≤ w') : + preparedUnskippedBitBudget e b M P v w B ≤ preparedUnskippedBitBudget e b M P v' w' B := by + have hr := representativeCompleteBitBudget_mono_vertices M w w' (4 * B + 20) hw + have hg := unskippedGuardBitBudget_mono_vertices e b M v v' w w' B hv hw + unfold preparedUnskippedBitBudget + omega + +theorem preparedUnskippedCandidateWithWork_cost {α : Type*} (source target : List α) + {M : ℕ} (parent : TargetInterval source.length) (b P e B : ℕ) + (hbpos : 0 < b) (hPpos : 0 < P) (tau F : BinaryFraction) + (child initial : Fin M → TargetInterval target.length → BinaryFraction) + (center : TargetInterval target.length) + (hnx : Nat.size source.length + 2 ≤ B) (hny : Nat.size target.length + 2 ≤ B) + (hM : Nat.size M ≤ B) (hb : Nat.size b + 2 ≤ B) (hP : Nat.size P ≤ B) + (he : e + 1 ≤ B) (htau : tau.width ≤ B) (hF : F.width ≤ B) + (hchild : ∀ i q, (child i q).width ≤ B) + (hinitial : ∀ i q, (initial i q).width ≤ B) : + let band := preparedRepresentativeWithWork parent center (parent.hi - parent.lo) b P + tau (inversePowerTwo e) child + let wide := wideActionGridWithWork M parent center b P + (preparedUnskippedCandidateWithWork source target parent b P e hbpos hPpos tau F + child initial center).2 ≤ preparedUnskippedBitBudget e b M P band.1.length wide.1.length B := by + dsimp only + let band := preparedRepresentativeWithWork parent center (parent.hi - parent.lo) b P + tau (inversePowerTwo e) child + let wide := wideActionGridWithWork M parent center b P + have htheta : (inversePowerTwo e).width ≤ B := by + rw [inversePowerTwo_width] + exact he + have hband := preparedRepresentativeWithWork_complete_cost parent center b P B hPpos tau + (inversePowerTwo e) child (by omega) (by omega) hM (by omega) hP htau htheta hchild + have hwide := wideActionGridWithWork_complete_cost M parent center b P B hPpos + (by omega) (by omega) hM (by omega) hP + change band.2 ≤ wideMaterializationBitBudget M P B + + representativeCompleteBitBudget M wide.1.length (4 * B + 20) + wide.1.length + 1 at hband + change wide.2 ≤ wideMaterializationBitBudget M P B at hwide + change (preparedUnskippedCandidateWithWork source target parent b P e hbpos hPpos tau F + child initial center).2 ≤ preparedUnskippedBitBudget e b M P band.1.length wide.1.length B + unfold preparedUnskippedCandidateWithWork + dsimp only + by_cases hempty : band.1 = [] + · rw [dite_eq_left hempty] + change band.2 + 1 ≤ _ + unfold preparedUnskippedBitBudget + omega + · rw [dite_eq_right hempty] + have hguard := unskippedGuardWithWork_cost parent center b e F band.1 + (wide.1.map Vector.get) hempty initial B hF hb hnx hny + (fun action _ i => hinitial i (action i)) + simp only [List.length_map] at hguard + split_ifs + all_goals + change band.2 + wide.2 + + (unskippedGuardWithWork parent center b e F band.1 (wide.1.map Vector.get) hempty initial).2 + + wide.1.length + _ ≤ _ + unfold preparedUnskippedBitBudget + omega + +theorem preparedUnskippedCandidateWithWork_uniform_cost {α : Type*} (source target : List α) + {M : ℕ} (parent : TargetInterval source.length) (b P e B : ℕ) + (hbpos : 0 < b) (hPpos : 0 < P) (tau F : BinaryFraction) + (child initial : Fin M → TargetInterval target.length → BinaryFraction) + (center : TargetInterval target.length) + (hnx : Nat.size source.length + 2 ≤ B) (hny : Nat.size target.length + 2 ≤ B) + (hM : Nat.size M ≤ B) (hb : Nat.size b + 2 ≤ B) (hP : Nat.size P ≤ B) + (he : e + 1 ≤ B) (htau : tau.width ≤ B) (hF : F.width ≤ B) + (hchild : ∀ i q, (child i q).width ≤ B) + (hinitial : ∀ i q, (initial i q).width ≤ B) : + (preparedUnskippedCandidateWithWork source target parent b P e hbpos hPpos tau F + child initial center).2 ≤ preparedUnskippedBitBudget e b M P + ((40 * P + 2) ^ (2 * M)) ((40 * P + 2) ^ (2 * M)) B := by + apply (preparedUnskippedCandidateWithWork_cost source target parent b P e B hbpos hPpos + tau F child initial center hnx hny hM hb hP he htau hF hchild hinitial).trans + apply preparedUnskippedBitBudget_mono_vertices + · rw [preparedRepresentativeWithWork_value source target parent center b P hPpos] + exact (representativeBandActions_length_le source target parent center b P tau.value + (inversePowerTwo e).value (fun i q => (child i q).value)).trans + (wideActionList_length_le M parent center b P hPpos) + · have h := congrArg List.length (wideActionGridWithWork_value M parent center b P hPpos) + simp only [List.length_map] at h + rw [h] + exact wideActionList_length_le M parent center b P hPpos + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryRawCost.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryRawCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..5ee396a79ab6b2af6eb177fb85e319652e55578a --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryRawCost.lean @@ -0,0 +1,160 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryRawStorage + +namespace OAI + +/-! Bit-operation bounds for the literal Boolean arithmetic calls and +bounded-width power loops used inside the entropy optimizer. -/ + +namespace EditApproximation +namespace BinaryFraction + +theorem representation_storageBits_le (a : BinaryFraction) : + a.representation.storageBits ≤ 2 * a.width + 1 := by + have hn : Nat.size (bitWordValue a.numerator.bits) ≤ a.numerator.bits.length := + Nat.size_le.mpr (bitWordValue_lt_pow_length _) + have hd : Nat.size (bitWordValue a.denominator) ≤ a.denominator.length := + Nat.size_le.mpr (bitWordValue_lt_pow_length _) + have hmag : a.numerator.value.natAbs = bitWordValue a.numerator.bits := by + cases h : a.numerator.negative <;> simp [SignedBinary.value, signedMagnitude, h] + have hnw : a.numerator.bits.length ≤ a.width := le_max_left _ _ + have hdw : a.denominator.length ≤ a.width := le_max_right _ _ + simp only [representation, UnreducedRational.storageBits, hmag] + omega + +theorem neg_width (a : BinaryFraction) : a.neg.width = a.width := rfl + +theorem invWithWork_width (a : BinaryFraction) : (a.invWithWork).1.width ≤ a.width + 1 := by + unfold invWithWork + dsimp only + split_ifs + · change 1 ≤ a.width + 1 + omega + · change max a.denominator.length a.numerator.bits.length ≤ a.width + 1 + rw [max_comm] + exact Nat.le_add_right _ _ + +theorem subWithWork_cost (a b : BinaryFraction) (B : ℕ) (ha : a.width ≤ B) (hb : b.width ≤ B) : + (a.subWithWork b).2 ≤ 6000 * (B + 1) ^ 2 + 1 := by + have h := canonicalAddWithWork_cost a b.neg B ha (by simpa only [neg_width] using hb) + exact Nat.add_le_add_right h 1 + +theorem divWithWork_cost (a b : BinaryFraction) (B : ℕ) (ha : a.width ≤ B) (hb : b.width ≤ B) : + (a.divWithWork b).2 ≤ 2100 * (B + 2) ^ 2 := by + have hi := invWithWork_cost b + have hw := invWithWork_width b + have hm := canonicalMulWithWork_cost a (b.invWithWork).1 (B + 1) + (by omega) (by omega) + change (b.invWithWork).2 + (canonicalMulWithWork a (b.invWithWork).1).2 + 1 ≤ _ + nlinarith only [hi, hw, hm, hb] + +theorem powWithWork_cost_of_width (a : BinaryFraction) (n B : ℕ) + (ha : a.width ≤ B) + (hprevious : ∀ j < n, (a.powWithWork j).1.width ≤ B) : + (a.powWithWork n).2 ≤ 1 + n * (2000 * (B + 1) ^ 2 + 1) := by + induction n with + | zero => simp [powWithWork] + | succ n ih => + have hp := ih (fun j hj => hprevious j (by omega)) + have hm := canonicalMulWithWork_cost (a.powWithWork n).1 a B + (hprevious n (by omega)) ha + change (a.powWithWork n).2 + (canonicalMulWithWork (a.powWithWork n).1 a).2 + 1 ≤ _ + nlinarith only [hp, hm] + +def powerWordBudget (a : BinaryFraction) (n : ℕ) : ℕ := + a.width + 2 * (n * Nat.size a.representation.den + 1) + 2 + +theorem powWithWork_width_abs_le_one (a : BinaryFraction) (n : ℕ) (ha : |a.value| ≤ 1) : + (a.powWithWork n).1.width ≤ 2 * (n * Nat.size a.representation.den + 1) + 2 := by + have hwidth := powWithWork_width_le_storageBits a n + rw [powWithWork_representation] at hwidth + exact hwidth.trans (UnreducedRational.pow_storageBits_abs_le_one _ _ ha) + +theorem powWithWork_cost_abs_le_one (a : BinaryFraction) (n : ℕ) (ha : |a.value| ≤ 1) : + (a.powWithWork n).2 ≤ 1 + n * (2000 * (powerWordBudget a n + 1) ^ 2 + 1) := by + apply powWithWork_cost_of_width + · dsimp only [powerWordBudget] + omega + · intro j hj + have hw := powWithWork_width_abs_le_one a j ha + have hm := Nat.mul_le_mul_right (Nat.size a.representation.den) hj.le + dsimp only [powerWordBudget] + omega + +theorem representation_den_bits_le_width (a : BinaryFraction) : + Nat.size a.representation.den ≤ a.width := by + have hd : Nat.size (bitWordValue a.denominator) ≤ a.denominator.length := + Nat.size_le.mpr (bitWordValue_lt_pow_length _) + exact hd.trans (le_max_right _ _) + +def dotWordBudget (n B V : ℕ) : ℕ := + B + Nat.size (n * V * V) + 2 * (1 + n * (B + B)) + 1 + +theorem dotListWithWork_width_in {d : ℕ} (left right : Vector BinaryFraction d) + (indices : List (Fin d)) (n B V : ℕ) (hlen : indices.length ≤ n) + (hlwidth : ∀ i ∈ indices, (left.get i).width ≤ B) + (hrwidth : ∀ i ∈ indices, (right.get i).width ≤ B) + (hlvalue : ∀ i ∈ indices, |(left.get i).value| ≤ V) + (hrvalue : ∀ i ∈ indices, |(right.get i).value| ≤ V) : + (dotListWithWork left right indices).1.width ≤ dotWordBudget n B V := by + have hw := dotListWithWork_width left right indices B B V V + (fun i hi => (representation_den_bits_le_width _).trans (hlwidth i hi)) + (fun i hi => (representation_den_bits_le_width _).trans (hrwidth i hi)) hlvalue hrvalue + have hs := Nat.size_le_size (Nat.mul_le_mul_right V (Nat.mul_le_mul_right V hlen)) + have hm := Nat.mul_le_mul_right (B + B) hlen + unfold dotWordBudget + omega + +theorem dotListWithWork_cost_in {d : ℕ} (left right : Vector BinaryFraction d) + (indices : List (Fin d)) (n B V : ℕ) (hlen : indices.length ≤ n) + (hlwidth : ∀ i ∈ indices, (left.get i).width ≤ B) + (hrwidth : ∀ i ∈ indices, (right.get i).width ≤ B) + (hlvalue : ∀ i ∈ indices, |(left.get i).value| ≤ V) + (hrvalue : ∀ i ∈ indices, |(right.get i).value| ≤ V) : + (dotListWithWork left right indices).2 ≤ + 1 + indices.length * (100000 * (dotWordBudget n B V + 1) ^ 2) := by + induction indices with + | nil => simp [dotListWithWork] + | cons i rest ih => + let W := dotWordBudget n B V + have hBW : B ≤ W := by dsimp only [W, dotWordBudget]; omega + have hl := hlwidth i List.mem_cons_self + have hr := hrwidth i List.mem_cons_self + have ht := ih (by simp only [List.length_cons] at hlen; omega) + (fun i hi => hlwidth i (List.mem_cons_of_mem _ hi)) + (fun i hi => hrwidth i (List.mem_cons_of_mem _ hi)) + (fun i hi => hlvalue i (List.mem_cons_of_mem _ hi)) + (fun i hi => hrvalue i (List.mem_cons_of_mem _ hi)) + have htail : (dotListWithWork left right rest).1.width ≤ W := + dotListWithWork_width_in left right rest n B V (by simp only [List.length_cons] at hlen; omega) + (fun i hi => hlwidth i (List.mem_cons_of_mem _ hi)) + (fun i hi => hrwidth i (List.mem_cons_of_mem _ hi)) + (fun i hi => hlvalue i (List.mem_cons_of_mem _ hi)) + (fun i hi => hrvalue i (List.mem_cons_of_mem _ hi)) + have hp := canonicalMulWithWork_cost (left.get i) (right.get i) W (hl.trans hBW) (hr.trans hBW) + have hproduct : (canonicalMulWithWork (left.get i) (right.get i)).1.width ≤ 4 * W + 2 := by + have hc := canonicalMulWithWork_width_le_storageBits (left.get i) (right.get i) + have hm := UnreducedRational.storageBits_mul (left.get i).representation (right.get i).representation + have hls := (representation_storageBits_le (left.get i)).trans + (Nat.add_le_add_right (Nat.mul_le_mul_left 2 (hl.trans hBW)) 1) + have hrs := (representation_storageBits_le (right.get i)).trans + (Nat.add_le_add_right (Nat.mul_le_mul_left 2 (hr.trans hBW)) 1) + omega + have ha := canonicalAddWithWork_cost (canonicalMulWithWork (left.get i) (right.get i)).1 + (dotListWithWork left right rest).1 (4 * W + 2) hproduct (by omega) + have hstep : (canonicalMulWithWork (left.get i) (right.get i)).2 + + (canonicalAddWithWork (canonicalMulWithWork (left.get i) (right.get i)).1 + (dotListWithWork left right rest).1).2 + 5 ≤ 100000 * (W + 1) ^ 2 := by + nlinarith only [hp, ha, Nat.zero_le W] + change (dotListWithWork left right rest).2 + + (canonicalMulWithWork (left.get i) (right.get i)).2 + + (canonicalAddWithWork (canonicalMulWithWork (left.get i) (right.get i)).1 + (dotListWithWork left right rest).1).2 + 5 ≤ _ + simp only [List.length_cons] + change _ ≤ 1 + (rest.length + 1) * (100000 * (W + 1) ^ 2) + change (dotListWithWork left right rest).2 ≤ 1 + rest.length * (100000 * (W + 1) ^ 2) at ht + nlinarith only [ht, hstep] + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryRawNumerics.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryRawNumerics.lean new file mode 100644 index 0000000000000000000000000000000000000000..a382543592daf6637636db966fdc33ed0de4eb07 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryRawNumerics.lean @@ -0,0 +1,172 @@ +import OAI.Combinatorics.EditApproximation.Geometry.CanonicalFractionWork +import OAI.Combinatorics.EditApproximation.Binary.UnreducedOptimizer +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! The optimizer's numerical loops executed on Boolean fraction storage. +The value proofs identify the unreduced numerator and denominator, not just +the represented rational. Thus the raw storage bounds apply to this code. -/ + +namespace EditApproximation +namespace BinaryFraction + +@[simp] theorem vector_map_get {α β : Type*} {d : ℕ} (f : α → β) (v : Vector α d) (i : Fin d) : + (v.map f).get i = f (v.get i) := Vector.getElem_map f i.isLt + + +def ofUnreduced (a : UnreducedRational) : BinaryFraction := + ⟨SignedBinary.ofInt a.num, a.den.bits, by simpa only [bitWordValue_bits] using a.den_pos⟩ + +@[simp] theorem ofUnreduced_representation (a : UnreducedRational) : + (ofUnreduced a).representation = a := by + apply UnreducedRational.eq_of_num_den + · exact SignedBinary.value_ofInt _ + · exact bitWordValue_bits _ + +theorem ofUnreduced_width (a : UnreducedRational) : + (ofUnreduced a).width = max (Nat.size a.num.natAbs) (Nat.size a.den) := by + simp only [ofUnreduced, width, SignedBinary.ofInt, ← Nat.size_eq_bits_len] + + + + +@[simp] theorem nat_representation (n : ℕ) : (nat n).representation = UnreducedRational.nat n := by + apply UnreducedRational.eq_of_num_den + · change (SignedBinary.ofInt (n : ℤ)).value = (n : ℤ) + exact SignedBinary.value_ofInt _ + · rfl + + + +theorem one_representation : one.representation = UnreducedRational.one := by + rw [one, nat_representation] + rfl + + + +theorem subWithWork_representation (a b : BinaryFraction) : + (a.subWithWork b).1.representation = a.representation.sub b.representation := by + simp only [subWithWork, canonicalAddWithWork_representation, neg_representation, + UnreducedRational.sub] + + + +theorem divWithWork_representation (a b : BinaryFraction) : + (a.divWithWork b).1.representation = a.representation.div b.representation := by + simp only [divWithWork, canonicalMulWithWork_representation, invWithWork_representation, + UnreducedRational.div] + + + +theorem powWithWork_representation (a : BinaryFraction) (k : ℕ) : + (a.powWithWork k).1.representation = a.representation.pow k := by + induction k with + | zero => exact one_representation + | succ k ih => simp only [powWithWork, canonicalMulWithWork_representation, + UnreducedRational.pow, ih] + + + +theorem logarithmPartialWithWork_representation (b : BinaryFraction) (k : ℕ) : + (b.logarithmPartialWithWork k).1.representation = b.representation.logarithmPartial k := by + induction k with + | zero => exact zero_representation + | succ k ih => simp only [logarithmPartialWithWork, canonicalAddWithWork_representation, + divWithWork_representation, powWithWork_representation, nat_representation, + UnreducedRational.logarithmPartial, ih] + + + +theorem logarithmWithWork_representation (r : BinaryFraction) (k : ℕ) : + (r.logarithmWithWork k).1.representation = r.representation.logarithm k := by + simp only [logarithmWithWork, canonicalMulWithWork_representation, + logarithmPartialWithWork_representation, divWithWork_representation, + subWithWork_representation, canonicalAddWithWork_representation, + nat_representation, one_representation, UnreducedRational.logarithm] + + + +theorem dotListWithWork_representation {d : ℕ} (left right : Vector BinaryFraction d) + (indices : List (Fin d)) : + (dotListWithWork left right indices).1.representation = + UnreducedRational.dotList (left.map representation) (right.map representation) indices := by + induction indices with + | nil => exact zero_representation + | cons i rest ih => + simp only [dotListWithWork, canonicalAddWithWork_representation, + canonicalMulWithWork_representation, UnreducedRational.dotList, ih, vector_map_get] + + + +theorem dotWithWork_representation {d : ℕ} (left right : Vector BinaryFraction d) : + (dotWithWork left right).1.representation = + UnreducedRational.dot (left.map representation) (right.map representation) := + dotListWithWork_representation _ _ _ + + + +theorem gradientCellWithWork_representation {d : ℕ} (G : ℕ) + (linear point : Vector BinaryFraction d) (i : Fin d) : + (gradientCellWithWork G linear point i).1.representation = + UnreducedRational.gradientCell G (linear.map representation) (point.map representation) i := by + simp only [gradientCellWithWork, canonicalAddWithWork_representation, + subWithWork_representation, logarithmWithWork_representation, neg_representation, + one_representation, invWithWork_representation, powWithWork_representation, + nat_representation, UnreducedRational.gradientCell, vector_map_get] + +theorem nat_width_le_storageBits (n : ℕ) : (nat n).width ≤ (nat n).representation.storageBits := by + rw [nat_representation] + have hw : (nat n).width = max (Nat.size n) 1 := by + simp only [nat, width, SignedBinary.ofInt, Int.natAbs_natCast, ← Nat.size_eq_bits_len, + List.length_cons, List.length_nil] + rw [hw] + simp only [UnreducedRational.nat, UnreducedRational.storageBits, Int.natAbs_natCast, Nat.size_one] + omega + +theorem zero_width_le_storageBits : zero.width ≤ zero.representation.storageBits := by decide + +theorem powWithWork_width_le_storageBits (a : BinaryFraction) (n : ℕ) : + (a.powWithWork n).1.width ≤ (a.powWithWork n).1.representation.storageBits := by + cases n with + | zero => exact nat_width_le_storageBits 1 + | succ n => + dsimp only [powWithWork] + exact canonicalMulWithWork_self_width (a.powWithWork n).1 a + +theorem logarithmPartialWithWork_width_le_storageBits (b : BinaryFraction) (n : ℕ) : + (b.logarithmPartialWithWork n).1.width ≤ + (b.logarithmPartialWithWork n).1.representation.storageBits := by + cases n with + | zero => exact zero_width_le_storageBits + | succ n => + dsimp only [logarithmPartialWithWork] + exact canonicalAddWithWork_self_width _ _ + +theorem logarithmWithWork_width_le_storageBits (r : BinaryFraction) (n : ℕ) : + (r.logarithmWithWork n).1.width ≤ (r.logarithmWithWork n).1.representation.storageBits := by + dsimp only [logarithmWithWork] + exact canonicalMulWithWork_self_width _ _ + +theorem dotListWithWork_width_le_storageBits {d : ℕ} (left right : Vector BinaryFraction d) + (indices : List (Fin d)) : + (dotListWithWork left right indices).1.width ≤ + (dotListWithWork left right indices).1.representation.storageBits := by + cases indices with + | nil => exact zero_width_le_storageBits + | cons i rest => + dsimp only [dotListWithWork] + exact canonicalAddWithWork_self_width _ _ + +theorem gradientCellWithWork_width_le_storageBits {d : ℕ} (G : ℕ) + (linear point : Vector BinaryFraction d) (i : Fin d) : + (gradientCellWithWork G linear point i).1.width ≤ + (gradientCellWithWork G linear point i).1.representation.storageBits := by + dsimp only [gradientCellWithWork] + exact canonicalAddWithWork_self_width _ _ + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryRawOptimizer.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryRawOptimizer.lean new file mode 100644 index 0000000000000000000000000000000000000000..e43c391cb2409b6fbc6550aacfe611aaf296e2ef --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryRawOptimizer.lean @@ -0,0 +1,127 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryRawNumerics +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Complete materialized entropy optimizer on Boolean fraction storage. +Every arithmetic operation invokes the counted Boolean implementation. -/ + +namespace EditApproximation +namespace BinaryFraction + +open Finset + + + +theorem gradientWithWork_representation {d : ℕ} (G : ℕ) (linear point : Vector BinaryFraction d) : + (gradientWithWork G linear point).1.map representation = + UnreducedRational.gradient G (linear.map representation) (point.map representation) := by + apply Vector.ext + intro i hi + simp only [Vector.getElem_map] + change ((gradientWithWork G linear point).1.get ⟨i, hi⟩).representation = + (UnreducedRational.gradient G (linear.map representation) (point.map representation)).get ⟨i, hi⟩ + rw [gradientWithWork, vectorMapWithWork_value] + simpa only [UnreducedRational.gradient, vector_get_ofFn] using + gradientCellWithWork_representation G linear point ⟨i, hi⟩ + + + +theorem scoredArgmaxWithWork_value {α : Type*} (score : α → BinaryFraction × ℕ) (values : List α) : + (scoredArgmaxWithWork score values).1 = + (values.argmax (fun a => (score a).1.value)).map (fun a => (a, (score a).1)) := by + induction values with + | nil => rfl + | cons a rest ih => + simp only [scoredArgmaxWithWork, ih, List.argmax_cons] + cases h : rest.argmax (fun a => (score a).1.value) with + | none => rfl + | some best => simp only [Option.map_some, ltWithWork_value]; split_ifs <;> rfl + + + +theorem maximizerWithWork_representation {d : ℕ} (gradient : Vector BinaryFraction d) + (vertices : List (Vector BinaryFraction d)) : + (maximizerWithWork gradient vertices).1.map representation = + UnreducedRational.maximizer (gradient.map representation) (vertices.map fun v => v.map representation) := by + have hscore (v : Vector BinaryFraction d) : + (dotWithWork gradient v).1.value = + (UnreducedRational.dot (gradient.map representation) (v.map representation)).value := by + rw [← dotWithWork_representation, representation_value] + have hmap := argmax_map_commutes (fun v : Vector BinaryFraction d => v.map representation) + (fun v => (UnreducedRational.dot (gradient.map representation) v).value) vertices + simp only [maximizerWithWork, scoredArgmaxWithWork_value, hscore, Option.map_map, + Function.comp_def, UnreducedRational.maximizer, UnreducedRational.scoredArgmax_spec] + rw [hmap] + cases h : vertices.argmax (fun v => + (UnreducedRational.dot (gradient.map representation) (v.map representation)).value) with + | none => + apply Vector.ext + intro i hi + simp [zero_representation] + | some v => rfl + + + +theorem optimizerUpdateWithWork_representation {d : ℕ} (j : ℕ) + (previous selected : Vector BinaryFraction d) (i : Fin d) : + ((optimizerUpdateWithWork j previous selected).1.get i).representation = + ((UnreducedRational.one.sub (UnreducedRational.optimizerStep j)).mul + (previous.get i).representation).add + ((UnreducedRational.optimizerStep j).mul (selected.get i).representation) := by + simp only [optimizerUpdateWithWork, vectorMapWithWork_value, + canonicalAddWithWork_representation, canonicalMulWithWork_representation, + subWithWork_representation, divWithWork_representation, nat_representation, + one_representation, UnreducedRational.optimizerStep] + + + +theorem finiteOptimizerWithWork_representation {d : ℕ} (vertices : List (Vector BinaryFraction d)) + (linear : Vector BinaryFraction d) (G K : ℕ) : + (finiteOptimizerWithWork vertices linear G K).1.map representation = + UnreducedRational.finiteOptimizer (vertices.map fun v => v.map representation) + (linear.map representation) G K := by + induction K with + | zero => + cases vertices with + | nil => + apply Vector.ext + intro i hi + simp [finiteOptimizerWithWork, UnreducedRational.finiteOptimizer, zero_representation] + | cons v vs => rfl + | succ K ih => + apply Vector.ext + intro i hi + simp only [Vector.getElem_map] + change (((optimizerUpdateWithWork K (finiteOptimizerWithWork vertices linear G K).1 + (maximizerWithWork (gradientWithWork G linear + (finiteOptimizerWithWork vertices linear G K).1).1 vertices).1).1.get ⟨i, hi⟩).representation) = _ + rw [optimizerUpdateWithWork_representation] + have hg := gradientWithWork_representation G linear (finiteOptimizerWithWork vertices linear G K).1 + rw [ih] at hg + have hm := maximizerWithWork_representation + (gradientWithWork G linear (finiteOptimizerWithWork vertices linear G K).1).1 vertices + rw [hg] at hm + have hp := congrArg (fun v : Vector UnreducedRational d => v.get ⟨i, hi⟩) ih + have hs := congrArg (fun v : Vector UnreducedRational d => v.get ⟨i, hi⟩) hm + simpa only [UnreducedRational.finiteOptimizer, vector_map_get, Vector.getElem_ofFn] using + congrArg₂ UnreducedRational.add + (congrArg (UnreducedRational.mul (UnreducedRational.one.sub (UnreducedRational.optimizerStep K))) hp) + (congrArg (UnreducedRational.mul (UnreducedRational.optimizerStep K)) hs) + +theorem finiteOptimizerWithWork_value {d : ℕ} (vertices : List (Vector BinaryFraction d)) + (linear : Vector BinaryFraction d) (G K : ℕ) : + (fun i => ((finiteOptimizerWithWork vertices linear G K).1.get i).value) = + finiteRationalOptimizer univ (vertices.map fun v i => (v.get i).value) + (fun i => (linear.get i).value) G K := by + have h := finiteOptimizerWithWork_representation vertices linear G K + have hvalue := UnreducedRational.finiteOptimizer_value + (vertices.map fun v => v.map representation) (linear.map representation) G K + rw [← h] at hvalue + simpa only [vector_map_get, representation_value, List.map_map, Function.comp_def] using hvalue + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryRawStorage.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryRawStorage.lean new file mode 100644 index 0000000000000000000000000000000000000000..eae6ebd3760adc1dfe38ba69f9906e70071b8c9a --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryRawStorage.lean @@ -0,0 +1,91 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryRawOptimizer +import OAI.Combinatorics.EditApproximation.Binary.UnreducedStorage + +namespace OAI + +/-! Actual Boolean word lengths in the materialized numerical implementation. +These bounds use the stored unreduced values, without a gcd reduction. -/ + +namespace EditApproximation +namespace BinaryFraction + +theorem gradientCellWithWork_width {d : ℕ} (G : ℕ) + (linear point : Vector BinaryFraction d) (i : Fin d) (hpoint : 0 ≤ (point.get i).value) : + (gradientCellWithWork G linear point i).1.width ≤ + UnreducedRational.gradientStorageBudget G (point.get i).representation.storageBits + (linear.get i).representation.storageBits := by + have hraw := UnreducedRational.gradientCell_storageBits G (linear.map representation) + (point.map representation) i (by simpa only [vector_map_get, representation_value] using hpoint) + simp only [vector_map_get] at hraw + have hwidth := gradientCellWithWork_width_le_storageBits G linear point i + rw [gradientCellWithWork_representation] at hwidth + exact hwidth.trans hraw + +theorem logarithmWithWork_width (r : BinaryFraction) (K : ℕ) (hr : 0 ≤ r.value) : + (r.logarithmWithWork K).1.width ≤ + UnreducedRational.logarithmStorageBudget r.representation.storageBits K := by + have hwidth := logarithmWithWork_width_le_storageBits r K + rw [logarithmWithWork_representation] at hwidth + exact hwidth.trans (UnreducedRational.logarithm_storageBits_poly _ _ hr) + +theorem dotListWithWork_width {d : ℕ} (left right : Vector BinaryFraction d) + (indices : List (Fin d)) (BL BR VL VR : ℕ) + (hlbits : ∀ i ∈ indices, Nat.size (left.get i).representation.den ≤ BL) + (hrbits : ∀ i ∈ indices, Nat.size (right.get i).representation.den ≤ BR) + (hlvalue : ∀ i ∈ indices, |(left.get i).value| ≤ VL) + (hrvalue : ∀ i ∈ indices, |(right.get i).value| ≤ VR) : + (dotListWithWork left right indices).1.width ≤ Nat.size (indices.length * VL * VR) + + 2 * (1 + indices.length * (BL + BR)) + 1 := by + have hwidth := dotListWithWork_width_le_storageBits left right indices + rw [dotListWithWork_representation] at hwidth + apply hwidth.trans + apply UnreducedRational.dotList_storageBits _ _ _ BL BR VL VR + · simpa only [vector_map_get] using hlbits + · simpa only [vector_map_get] using hrbits + · simpa only [vector_map_get, representation_value] using hlvalue + · simpa only [vector_map_get, representation_value] using hrvalue + +theorem finiteOptimizerWithWork_coordinate_normalized {d : ℕ} + (vertices : List (Vector BinaryFraction d)) (linear : Vector BinaryFraction d) (G K : ℕ) + (hvertices : vertices ≠ []) + (hinput : ∀ v ∈ vertices, ∀ i : Fin d, (v.get i).width ≤ (v.get i).representation.storageBits) + (i : Fin d) : + ((finiteOptimizerWithWork vertices linear G K).1.get i).width ≤ + ((finiteOptimizerWithWork vertices linear G K).1.get i).representation.storageBits := by + cases K with + | zero => + cases vertices with + | nil => exact False.elim (hvertices rfl) + | cons v vs => exact hinput v List.mem_cons_self i + | succ K => + simp only [finiteOptimizerWithWork, optimizerUpdateWithWork, vectorMapWithWork_value] + exact canonicalAddWithWork_self_width _ _ + +theorem finiteOptimizerWithWork_coordinate_width {d : ℕ} + (vertices : List (Vector BinaryFraction d)) (linear : Vector BinaryFraction d) (G K B : ℕ) + (hvertices : vertices ≠ []) + (hinput : ∀ v ∈ vertices, ∀ i : Fin d, + (v.get i).width ≤ (v.get i).representation.storageBits ∧ + (0 ≤ (v.get i).value ∧ (v.get i).value ≤ 1) ∧ Nat.size (v.get i).representation.den ≤ B) + (i : Fin d) : + ((finiteOptimizerWithWork vertices linear G K).1.get i).width ≤ + 2 * (B + K * (2 * Nat.size (K + 1) + B)) + 2 := by + have hn : (vertices.map fun v => v.map representation) ≠ [] := by + intro h + exact hvertices (List.map_eq_nil_iff.mp h) + have hr := UnreducedRational.finiteOptimizer_storageBits + (vertices.map fun v => v.map representation) (linear.map representation) G K B i hn (by + intro v hv + obtain ⟨w, hw, rfl⟩ := List.mem_map.mp hv + simpa only [vector_map_get, representation_value] using (hinput w hw i).2) + have hrep := congrArg (fun v : Vector UnreducedRational d => v.get i) + (finiteOptimizerWithWork_representation vertices linear G K) + simp only [vector_map_get] at hrep + rw [← hrep] at hr + exact (finiteOptimizerWithWork_coordinate_normalized vertices linear G K hvertices + (fun v hv i => (hinput v hv i).1) i).trans hr + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryReadComposition.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryReadComposition.lean new file mode 100644 index 0000000000000000000000000000000000000000..27ae6e39dfcf147db622d77b49386fa3352ae04a --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryReadComposition.lean @@ -0,0 +1,138 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryFiniteLoops +import OAI.Combinatorics.EditApproximation.Probability.FiniteEnumerationWork + +namespace OAI + +/-! Callback work is retained when a finite loop is supplied with a +costed reader. These lemmas compare the literal loop counters, so a +lookup cannot disappear when its returned word is passed to arithmetic. -/ + +namespace EditApproximation + +theorem arithmeticMapWithWork_extra {α β : Type*} (read plain : α → β × ℕ) + (extra : α → ℕ) (xs : List α) + (hvalue : ∀ x ∈ xs, (read x).1 = (plain x).1) + (hcost : ∀ x ∈ xs, (read x).2 ≤ (plain x).2 + extra x) : + (arithmeticMapWithWork read xs).1 = (arithmeticMapWithWork plain xs).1 ∧ + (arithmeticMapWithWork read xs).2 ≤ + (arithmeticMapWithWork plain xs).2 + (xs.map extra).sum := by + have costBound (a a' b b' A B : ℕ) (ha : a ≤ a' + A) (hb : b ≤ b' + B) : + a + b + 3 ≤ a' + b' + 3 + (A + B) := by + omega + induction xs with + | nil => exact ⟨rfl, Nat.le_refl _⟩ + | cons x xs ih => + have hv := hvalue x List.mem_cons_self + have hc := hcost x List.mem_cons_self + have ht := ih (fun y hy => hvalue y (List.mem_cons_of_mem _ hy)) + (fun y hy => hcost y (List.mem_cons_of_mem _ hy)) + constructor + · change (read x).1 :: (arithmeticMapWithWork read xs).1 = + (plain x).1 :: (arithmeticMapWithWork plain xs).1 + rw [hv, ht.1] + · change (read x).2 + (arithmeticMapWithWork read xs).2 + 3 ≤ + (plain x).2 + (arithmeticMapWithWork plain xs).2 + 3 + (extra x + (xs.map extra).sum) + exact costBound _ _ _ _ _ _ hc ht.2 + +theorem arithmeticFlatMapWithWork_extra {α β : Type*} (read plain : α → List β × ℕ) + (extra : α → ℕ) (xs : List α) + (hvalue : ∀ x ∈ xs, (read x).1 = (plain x).1) + (hcost : ∀ x ∈ xs, (read x).2 ≤ (plain x).2 + extra x) : + (arithmeticFlatMapWithWork read xs).1 = (arithmeticFlatMapWithWork plain xs).1 ∧ + (arithmeticFlatMapWithWork read xs).2 ≤ + (arithmeticFlatMapWithWork plain xs).2 + (xs.map extra).sum := by + induction xs with + | nil => exact ⟨rfl, by simp only [arithmeticFlatMapWithWork, List.map_nil, List.sum_nil, Nat.add_zero, le_refl]⟩ + | cons x xs ih => + have hv := hvalue x List.mem_cons_self + have hc := hcost x List.mem_cons_self + have ht := ih (fun y hy => hvalue y (List.mem_cons_of_mem _ hy)) + (fun y hy => hcost y (List.mem_cons_of_mem _ hy)) + constructor + · simp only [arithmeticFlatMapWithWork, hv, ht.1] + · simp only [arithmeticFlatMapWithWork, hv, List.map_cons, List.sum_cons] + omega + +theorem filterWithWork_extra {α : Type*} (read plain : α → Bool × ℕ) + (extra : α → ℕ) (xs : List α) + (hvalue : ∀ x ∈ xs, (read x).1 = (plain x).1) + (hcost : ∀ x ∈ xs, (read x).2 ≤ (plain x).2 + extra x) : + (filterWithWork read xs).1 = (filterWithWork plain xs).1 ∧ + (filterWithWork read xs).2 ≤ + (filterWithWork plain xs).2 + (xs.map extra).sum := by + have costBound (a a' b b' A B : ℕ) (ha : a ≤ a' + A) (hb : b ≤ b' + B) : + a + b + 3 ≤ a' + b' + 3 + (A + B) := by + omega + induction xs with + | nil => exact ⟨rfl, Nat.le_refl _⟩ + | cons x xs ih => + have hv := hvalue x List.mem_cons_self + have hc := hcost x List.mem_cons_self + have ht := ih (fun y hy => hvalue y (List.mem_cons_of_mem _ hy)) + (fun y hy => hcost y (List.mem_cons_of_mem _ hy)) + constructor + · change (if (read x).1 then x :: (filterWithWork read xs).1 else (filterWithWork read xs).1) = + (if (plain x).1 then x :: (filterWithWork plain xs).1 else (filterWithWork plain xs).1) + rw [hv, ht.1] + · change (read x).2 + (filterWithWork read xs).2 + 3 ≤ + (plain x).2 + (filterWithWork plain xs).2 + 3 + (extra x + (xs.map extra).sum) + exact costBound _ _ _ _ _ _ hc ht.2 + +theorem sum_map_le_length_mul {α : Type*} (xs : List α) (f : α → ℕ) (C : ℕ) + (h : ∀ x ∈ xs, f x ≤ C) : (xs.map f).sum ≤ xs.length * C := by + induction xs with + | nil => simp only [List.map_nil, List.sum_nil, List.length_nil, Nat.zero_mul, le_refl] + | cons x xs ih => + have hh := h x List.mem_cons_self + have ht := ih (fun y hy => h y (List.mem_cons_of_mem _ hy)) + simp only [List.map_cons, List.sum_cons, List.length_cons, Nat.add_mul, Nat.one_mul] + omega + +theorem arithmeticFlatMapWithWork_factor {α β : Type*} (read plain : α → List β × ℕ) + (xs : List α) (K : ℕ) (hK : 1 ≤ K) + (hvalue : ∀ x ∈ xs, (read x).1 = (plain x).1) + (hcost : ∀ x ∈ xs, (read x).2 ≤ (plain x).2 * K) : + (arithmeticFlatMapWithWork read xs).1 = (arithmeticFlatMapWithWork plain xs).1 ∧ + (arithmeticFlatMapWithWork read xs).2 ≤ (arithmeticFlatMapWithWork plain xs).2 * K := by + induction xs with + | nil => exact ⟨rfl, by simp only [arithmeticFlatMapWithWork, Nat.zero_mul, le_refl]⟩ + | cons x xs ih => + have hv := hvalue x List.mem_cons_self + have hc := hcost x List.mem_cons_self + have ht := ih (fun y hy => hvalue y (List.mem_cons_of_mem _ hy)) + (fun y hy => hcost y (List.mem_cons_of_mem _ hy)) + constructor + · simp only [arithmeticFlatMapWithWork, hv, ht.1] + · simp only [arithmeticFlatMapWithWork, hv] + have hl : (plain x).1.length ≤ (plain x).1.length * K := by + simpa only [Nat.mul_one] using Nat.mul_le_mul_left (plain x).1.length hK + nlinarith only [hc, ht.2, hl, hK] + +theorem filterWithWork_length_le_cost {α : Type*} (test : α → Bool × ℕ) (xs : List α) : + xs.length ≤ (filterWithWork test xs).2 := by + induction xs with + | nil => simp only [List.length_nil, Nat.zero_le] + | cons x xs ih => simp only [List.length_cons, filterWithWork]; omega + +theorem arithmeticMapWithWork_length_le_cost {α β : Type*} (f : α → β × ℕ) (xs : List α) : + xs.length ≤ (arithmeticMapWithWork f xs).2 := by + induction xs with + | nil => simp only [List.length_nil, Nat.zero_le] + | cons x xs ih => simp only [List.length_cons, arithmeticMapWithWork]; omega + +theorem filterWithWork_add_read {α : Type*} (test : α → Bool × ℕ) + (readCost : α → ℕ) (xs : List α) (R : ℕ) (hR : ∀ x ∈ xs, readCost x ≤ R) : + (filterWithWork (fun x => ((test x).1, (test x).2 + readCost x)) xs).1 = + (filterWithWork test xs).1 ∧ + (filterWithWork (fun x => ((test x).1, (test x).2 + readCost x)) xs).2 ≤ + (filterWithWork test xs).2 * (R + 1) := by + have h := filterWithWork_extra (fun x => ((test x).1, (test x).2 + readCost x)) + test readCost xs (fun _ _ => rfl) (fun _ _ => le_rfl) + have hs := sum_map_le_length_mul xs readCost R hR + have hl := filterWithWork_length_le_cost test xs + refine ⟨h.1, ?_⟩ + nlinarith only [h.2, hs, hl] + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryReadCostBounds.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryReadCostBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..0be90954ad636d1a804764eac2a7ff31ee4fbaf7 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryReadCostBounds.lean @@ -0,0 +1,211 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryOnlineReads +import OAI.Combinatorics.EditApproximation.Binary.BinaryPrefixReads +import OAI.Combinatorics.EditApproximation.Binary.BinaryScoreReads +import OAI.Combinatorics.EditApproximation.Binary.BinaryBellmanReads +import OAI.Combinatorics.EditApproximation.Binary.BinaryLocalGrid + +namespace OAI + +/-! Lookup overhead is controlled by the loops that actually run. +These comparisons require only a bound on one finite-buffer lookup. -/ + +namespace EditApproximation + +theorem vectorMapWithWork_cost_lower {α : Type*} (d : ℕ) (f : Fin d → α × ℕ) (C : ℕ) + (h : ∀ i, C ≤ (f i).2) : d * C ≤ (vectorMapWithWork d f).2 := by + simp only [vectorMapWithWork, Vector.toList_map, Vector.toList_ofFn, + List.map_ofFn, Function.comp_def, List.sum_ofFn] + have hs := Finset.sum_le_sum (s := Finset.univ) (fun i _ => h i) + simp only [Finset.sum_const, Finset.card_univ, Fintype.card_fin, smul_eq_mul] at hs + omega + +theorem arithmeticMapWithWork_factor {α β : Type*} (read plain : α → β × ℕ) + (xs : List α) (K : ℕ) (hK : 1 ≤ K) + (hv : ∀ x ∈ xs, (read x).1 = (plain x).1) + (hc : ∀ x ∈ xs, (read x).2 ≤ (plain x).2 * K) : + (arithmeticMapWithWork read xs).1 = (arithmeticMapWithWork plain xs).1 ∧ + (arithmeticMapWithWork read xs).2 ≤ (arithmeticMapWithWork plain xs).2 * K := by + induction xs with + | nil => exact ⟨rfl, by simp only [arithmeticMapWithWork, Nat.zero_mul, le_refl]⟩ + | cons x xs ih => + have hx := hv x List.mem_cons_self + have hcx := hc x List.mem_cons_self + have ht := ih (fun y hy => hv y (List.mem_cons_of_mem _ hy)) + (fun y hy => hc y (List.mem_cons_of_mem _ hy)) + constructor + · simp only [arithmeticMapWithWork, hx, ht.1] + · simp only [arithmeticMapWithWork] + nlinarith only [hcx, ht.2, hK] + +theorem vectorMapWithWork_factor {α : Type*} (d : ℕ) (read plain : Fin d → α × ℕ) + (K : ℕ) (hK : 1 ≤ K) (hv : ∀ i, (read i).1 = (plain i).1) + (hc : ∀ i, (read i).2 ≤ (plain i).2 * K) : + (vectorMapWithWork d read).1 = (vectorMapWithWork d plain).1 ∧ + (vectorMapWithWork d read).2 ≤ (vectorMapWithWork d plain).2 * K := by + constructor + · apply Vector.ext + intro i hi + change (vectorMapWithWork d read).1.get ⟨i, hi⟩ = (vectorMapWithWork d plain).1.get ⟨i, hi⟩ + rw [vectorMapWithWork_value, vectorMapWithWork_value] + exact hv _ + · simp only [vectorMapWithWork, Vector.toList_map, Vector.toList_ofFn, + List.map_ofFn, Function.comp_def, List.sum_ofFn] + have hs := Finset.sum_le_sum (s := Finset.univ) (fun i _ => hc i) + rw [← Finset.sum_mul] at hs + have hd := Nat.mul_le_mul_left (6 * d) hK + simp only [Nat.mul_one] at hd + nlinarith only [hs, hd] + + +theorem filterWithWork_factor {α : Type*} (read plain : α → Bool × ℕ) + (xs : List α) (K : ℕ) (hK : 1 ≤ K) + (hv : ∀ x ∈ xs, (read x).1 = (plain x).1) + (hc : ∀ x ∈ xs, (read x).2 ≤ (plain x).2 * K) : + (filterWithWork read xs).1 = (filterWithWork plain xs).1 ∧ + (filterWithWork read xs).2 ≤ (filterWithWork plain xs).2 * K := by + induction xs with + | nil => exact ⟨rfl, by simp only [filterWithWork, Nat.zero_mul, le_refl]⟩ + | cons x xs ih => + have hx := hv x List.mem_cons_self + have hcx := hc x List.mem_cons_self + have ht := ih (fun y hy => hv y (List.mem_cons_of_mem _ hy)) + (fun y hy => hc y (List.mem_cons_of_mem _ hy)) + constructor + · simp only [filterWithWork, hx, ht.1] + · simp only [filterWithWork] + nlinarith only [hcx, ht.2, hK] + +theorem allWithWork_factor {α : Type*} (read plain : α → Bool × ℕ) + (xs : List α) (K : ℕ) (hK : 1 ≤ K) + (hv : ∀ x ∈ xs, (read x).1 = (plain x).1) + (hc : ∀ x ∈ xs, (read x).2 ≤ (plain x).2 * K) : + (allWithWork read xs).1 = (allWithWork plain xs).1 ∧ + (allWithWork read xs).2 ≤ (allWithWork plain xs).2 * K := by + induction xs with + | nil => exact ⟨rfl, by simp only [allWithWork, Nat.zero_mul, le_refl]⟩ + | cons x xs ih => + have hx := hv x List.mem_cons_self + have hcx := hc x List.mem_cons_self + have ht := ih (fun y hy => hv y (List.mem_cons_of_mem _ hy)) + (fun y hy => hc y (List.mem_cons_of_mem _ hy)) + constructor + · simp only [allWithWork, hx, ht.1] + · simp only [allWithWork] + nlinarith only [hcx, ht.2, hK] + +theorem filterMapWithWork_factor {α β : Type*} (read plain : α → Option β × ℕ) + (xs : List α) (K : ℕ) (hK : 1 ≤ K) + (hv : ∀ x ∈ xs, (read x).1 = (plain x).1) + (hc : ∀ x ∈ xs, (read x).2 ≤ (plain x).2 * K) : + (filterMapWithWork read xs).1 = (filterMapWithWork plain xs).1 ∧ + (filterMapWithWork read xs).2 ≤ (filterMapWithWork plain xs).2 * K := by + induction xs with + | nil => exact ⟨rfl, by simp only [filterMapWithWork, Nat.zero_mul, le_refl]⟩ + | cons x xs ih => + have hx := hv x List.mem_cons_self + have hcx := hc x List.mem_cons_self + have ht := ih (fun y hy => hv y (List.mem_cons_of_mem _ hy)) + (fun y hy => hc y (List.mem_cons_of_mem _ hy)) + simp only [filterMapWithWork, hx, ht.1] + cases (plain x).1 with + | none => exact ⟨trivial, by nlinarith only [hcx, ht.2, hK]⟩ + | some value => exact ⟨trivial, by nlinarith only [hcx, ht.2, hK]⟩ + +/-- Multiplicative work bounds are preserved when the same nonnegative +overhead is added to both counters. -/ +theorem cost_replace_factor (a c old new K : ℕ) (hc : c ≤ a * K) (hK : 1 ≤ K) + (ha : a ≤ old) (hn : new + a ≤ old + c) : new ≤ old * K := by + have hx := Nat.mul_le_mul_left (old - a) hK + simp only [Nat.mul_one] at hx + have he : a + (old - a) = old := by omega + calc + new ≤ c + (old - a) := by omega + _ ≤ a * K + (old - a) * K := Nat.add_le_add hc hx + _ = old * K := by rw [← Nat.add_mul, he] + +/-- A compulsory constant instruction pays for one additional lookup. -/ +theorem cost_factor_with_read (a c x r R K : ℕ) (hc : c ≤ a * K) + (hr : r ≤ R) (hx : 1 ≤ x) (hK : R + 1 ≤ K) : + r + c + x ≤ (a + x) * K := by + have hmul := Nat.mul_le_mul_left x hK + have hR := Nat.mul_le_mul_right R hx + simp only [Nat.one_mul] at hR + have hrest : r + x ≤ x * K := by nlinarith only [hmul, hR, hr] + calc + r + c + x = c + (r + x) := by omega + _ ≤ a * K + x * K := Nat.add_le_add hc hrest + _ = (a + x) * K := by ring + +namespace BinaryFraction + +def tableReadFactor (R : ℕ) : ℕ := 4 * (R + 4) + +theorem tableReadFactor_pos (R : ℕ) : 1 ≤ tableReadFactor R := by + unfold tableReadFactor + omega + +theorem tableReadFactor_absorb (a c n R : ℕ) (hc : c ≤ a + n * (R + 3)) (hn : n ≤ a) : + c ≤ a * tableReadFactor R := by + have hm := Nat.mul_le_mul_right (R + 3) hn + have hk : R + 4 ≤ tableReadFactor R := by unfold tableReadFactor; omega + calc + c ≤ a + a * (R + 3) := hc.trans (Nat.add_le_add_left hm a) + _ = a * (R + 4) := by ring + _ ≤ a * tableReadFactor R := Nat.mul_le_mul_left a hk + +theorem endpointScoreReadWithWork_factor {n M : ℕ} (r : TargetInterval n) + (read : Fin M → TargetInterval n → BinaryFraction × ℕ) (states : Fin M → TargetInterval n) + (R : ℕ) (hr : ∀ i, (read i (states i)).2 ≤ R) : + (endpointScoreReadWithWork r read states).2 ≤ + (endpointScoreWithWork r (fun i q => (read i q).1) states).2 * tableReadFactor R := by + apply tableReadFactor_absorb _ _ M R (endpointScoreReadWithWork_cost r read states R hr) + simp only [endpointScoreWithWork, endpointConnectionWithWork] + omega + +theorem prefixReadWithWork_factor {nx n M : ℕ} (parent : TargetInterval nx) (r : TargetInterval n) + (states : Fin M → TargetInterval n) (read : Fin M → TargetInterval n → BinaryFraction × ℕ) + (j : ℕ) (p : BinaryFraction) (R : ℕ) (hr : ∀ i, (read i (states i)).2 ≤ R) : + (prefixReadWithWork parent r states read j p).2 ≤ + (prefixWithWork parent r states (fun i q => (read i q).1) j p).2 * tableReadFactor R := by + have hc := prefixReadWithWork_cost parent r states read j p R hr + have hn : M ≤ (prefixWithWork parent r states (fun i q => (read i q).1) j p).2 := by + simp only [prefixWithWork] + omega + have hm := Nat.mul_le_mul_right (R + 4) hn + have hk : R + 5 ≤ tableReadFactor R := by unfold tableReadFactor; omega + calc + _ ≤ _ + M * (R + 4) := hc + _ ≤ _ + (prefixWithWork parent r states (fun i q => (read i q).1) j p).2 * (R + 4) := + Nat.add_le_add_left hm _ + _ = (prefixWithWork parent r states (fun i q => (read i q).1) j p).2 * (R + 5) := by ring + _ ≤ _ := Nat.mul_le_mul_left _ hk + +theorem bandEnvelopeReadWithWork_factor {M n : ℕ} (b : ℕ) (band : List (Fin M → TargetInterval n)) + (read : Fin M → TargetInterval n → BinaryFraction × ℕ) (i : Fin M) (R : ℕ) + (hr : ∀ action ∈ band, (read i (action i)).2 ≤ R) : + (bandEnvelopeReadWithWork b band read i).2 ≤ + (bandEnvelopeWithWork b band (fun j q => (read j q).1) i).2 * tableReadFactor R := by + apply tableReadFactor_absorb _ _ band.length R (bandEnvelopeReadWithWork_cost b band read i R hr) + simp only [bandEnvelopeWithWork] + omega + +theorem onlineLinearReadWithWork_factor {β σ : Type*} (mass : β → BinaryFraction) + (read : ℕ → β × σ → BinaryFraction × ℕ) (eta kappa : BinaryFraction) + (t : ℕ) (i : β × σ) (R : ℕ) (hr : ∀ s ≤ t + 1, (read s i).2 ≤ R) : + (onlineLinearReadWithWork mass read eta kappa t i).2 ≤ + (onlineLinearWithWork mass (fun s j => (read s j).1) eta kappa t i).2 * tableReadFactor R := by + have hc := (onlineLinearReadWithWork_eq_cost mass read eta kappa t i R hr).2 + have ht : 6 * t ≤ (vectorMapWithWork t (fun s => optimisticTermWithWork mass + (fun v j => (read v j).1) (coefficientWithWork kappa).1 s.val i)).2 := by + simp only [vectorMapWithWork] + omega + have hn : 3 * t + 1 ≤ (onlineLinearWithWork mass (fun s j => (read s j).1) eta kappa t i).2 := by + simp only [onlineLinearWithWork, gainWithWork] + omega + apply tableReadFactor_absorb _ _ (3 * t + 1) R _ hn + exact hc.trans (Nat.add_le_add_left (Nat.mul_le_mul_left _ (by omega : R ≤ R + 3)) _) + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryReductionSpace.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryReductionSpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..004cc39854956019260b97d735b73265fe45dd15 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryReductionSpace.lean @@ -0,0 +1,174 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryNumericSpace +import OAI.Combinatorics.EditApproximation.Binary.BinaryWarmupAverage +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Actual reduction scratch: comparisons retain their cross-products; +sums retain all dot-product intermediates and the materialized vectors. -/ + +namespace EditApproximation.BinaryFraction + +/-- Two materialized index/value list spines fit the dot loop's per-cell charge. -/ +theorem dotListAllocation_with_spines_le_work {d : ℕ} + (left right : Vector BinaryFraction d) (indices : List (Fin d)) : + dotListAllocation left right indices + 2 * indices.length ≤ (dotListWithWork left right indices).2 := by + induction indices with + | nil => simp only [dotListAllocation, dotListWithWork, List.length_nil]; omega + | cons i rest ih => + have hm := canonicalMulAllocation_le_work (left.get i) (right.get i) + have ha := canonicalAddAllocation_le_work + (canonicalMulWithWork (left.get i) (right.get i)).1 (dotListWithWork left right rest).1 + simp only [dotListAllocation, dotListWithWork, List.length_cons] + omega + +theorem dotListInvocations_with_spines_le_work {d : ℕ} + (left right : Vector BinaryFraction d) (indices : List (Fin d)) : + dotListInvocations left right indices + 2 * indices.length ≤ (dotListWithWork left right indices).2 := by + induction indices with + | nil => rfl + | cons i rest ih => + have hm := canonicalMulInvocations_le_work (left.get i) (right.get i) + have ha := canonicalAddInvocations_le_work + (canonicalMulWithWork (left.get i) (right.get i)).1 (dotListWithWork left right rest).1 + simp only [dotListInvocations, dotListWithWork, List.length_cons] + omega + + + +def bandMassInvocations {M : ℕ} (mass : Vector BinaryFraction M) : ℕ := + dotListInvocations mass (Vector.replicate M one) (List.finRange M) + 2 * M + +theorem bandMassAllocation_le_work {M : ℕ} (mass : Vector BinaryFraction M) : + bandMassAllocation mass ≤ (bandMassTotalWithWork mass).2 := by + simpa only [bandMassAllocation, bandMassTotalWithWork, dotWithWork, List.length_finRange] using + dotListAllocation_with_spines_le_work mass (Vector.replicate M one) (List.finRange M) + +theorem bandMassInvocations_le_work {M : ℕ} (mass : Vector BinaryFraction M) : + bandMassInvocations mass ≤ (bandMassTotalWithWork mass).2 := by + simpa only [bandMassInvocations, bandMassTotalWithWork, dotWithWork, List.length_finRange] using + dotListInvocations_with_spines_le_work mass (Vector.replicate M one) (List.finRange M) + + + +def minInvocations (a b : BinaryFraction) : ℕ := compareInvocations a b + 1 + +theorem minAllocation_le_work (a b : BinaryFraction) : + minAllocation a b ≤ (minWithWork a b).2 := by + exact (ltAllocation_le_work a b).trans (Nat.le_add_right _ _) + +theorem minInvocations_le_work (a b : BinaryFraction) : + minInvocations a b ≤ (minWithWork a b).2 := + Nat.add_le_add_right (compareInvocations_le_work a b) 1 + + + +def minimumInvocations (fallback : BinaryFraction) : List BinaryFraction → ℕ + | [] => 1 + | head :: rest => minimumInvocations fallback rest + + minInvocations head (minimumWithWork fallback rest).1 + 1 + +theorem minimumAllocation_le_work (fallback : BinaryFraction) (values : List BinaryFraction) : + minimumAllocation fallback values ≤ (minimumWithWork fallback values).2 := by + induction values with + | nil => simp only [minimumAllocation, minimumWithWork, Nat.zero_le] + | cons head rest ih => + have h := minAllocation_le_work head (minimumWithWork fallback rest).1 + simp only [minimumAllocation, minimumWithWork] + omega + +theorem minimumInvocations_le_work (fallback : BinaryFraction) (values : List BinaryFraction) : + minimumInvocations fallback values ≤ (minimumWithWork fallback values).2 := by + induction values with + | nil => rfl + | cons head rest ih => + have h := minInvocations_le_work head (minimumWithWork fallback rest).1 + simp only [minimumInvocations, minimumWithWork] + omega + + + +def maxInvocations (a b : BinaryFraction) : ℕ := compareInvocations a b + 1 + +theorem maxAllocation_le_work (a b : BinaryFraction) : + maxAllocation a b ≤ (maxWithWork a b).2 := by + exact (ltAllocation_le_work a b).trans (Nat.le_add_right _ _) + +theorem maxInvocations_le_work (a b : BinaryFraction) : + maxInvocations a b ≤ (maxWithWork a b).2 := + Nat.add_le_add_right (compareInvocations_le_work a b) 1 + + + +def maximumInvocations (fallback : BinaryFraction) : List BinaryFraction → ℕ + | [] => 1 + | head :: rest => maximumInvocations fallback rest + + maxInvocations head (maximumWithWork fallback rest).1 + 1 + +theorem maximumAllocation_le_work (fallback : BinaryFraction) (values : List BinaryFraction) : + maximumAllocation fallback values ≤ (maximumWithWork fallback values).2 := by + induction values with + | nil => simp only [maximumAllocation, maximumWithWork, Nat.zero_le] + | cons head rest ih => + have h := maxAllocation_le_work head (maximumWithWork fallback rest).1 + simp only [maximumAllocation, maximumWithWork] + omega + +theorem maximumInvocations_le_work (fallback : BinaryFraction) (values : List BinaryFraction) : + maximumInvocations fallback values ≤ (maximumWithWork fallback values).2 := by + induction values with + | nil => rfl + | cons head rest ih => + have h := maxInvocations_le_work head (maximumWithWork fallback rest).1 + simp only [maximumInvocations, maximumWithWork] + omega + + + +def sumListInvocations (values : List BinaryFraction) : ℕ := + dotListInvocations (Vector.ofFn values.get) (Vector.replicate values.length one) + (List.finRange values.length) + 3 * values.length + +theorem sumListAllocation_le_work (values : List BinaryFraction) : + sumListAllocation values ≤ (sumListWithWork values).2 := by + have h := dotListAllocation_le_work (Vector.ofFn values.get) (Vector.replicate values.length one) + (List.finRange values.length) + unfold sumListAllocation sumListWithWork bandMassTotalWithWork dotWithWork + dsimp only + omega + +theorem sumListInvocations_le_work (values : List BinaryFraction) : + sumListInvocations values ≤ (sumListWithWork values).2 := by + have h := dotListInvocations_le_work (Vector.ofFn values.get) (Vector.replicate values.length one) + (List.finRange values.length) + unfold sumListInvocations sumListWithWork bandMassTotalWithWork dotWithWork + dsimp only + omega + +def warmupAverageAllocation (values : List BinaryFraction) : ℕ := + sumListAllocation values + divAllocation (sumListWithWork values).1 (nat values.length) + + Nat.size values.length + 1 + +def warmupAverageInvocations (values : List BinaryFraction) : ℕ := + sumListInvocations values + divInvocations (sumListWithWork values).1 (nat values.length) + 1 + +theorem warmupAverageAllocation_le_work (values : List BinaryFraction) : + warmupAverageAllocation values ≤ (warmupAverageWithWork values).2 := by + have hs := sumListAllocation_le_work values + have hd := divAllocation_le_work (sumListWithWork values).1 (nat values.length) + unfold warmupAverageAllocation warmupAverageWithWork + dsimp only + omega + +theorem warmupAverageInvocations_le_work (values : List BinaryFraction) : + warmupAverageInvocations values ≤ (warmupAverageWithWork values).2 := by + have hs := sumListInvocations_le_work values + have hd := divInvocations_le_work (sumListWithWork values).1 (nat values.length) + unfold warmupAverageInvocations warmupAverageWithWork + dsimp only + omega + +end EditApproximation.BinaryFraction + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryRefinementLists.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryRefinementLists.lean new file mode 100644 index 0000000000000000000000000000000000000000..589df9a4428b13605d50c968666e814cd419ad22 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryRefinementLists.lean @@ -0,0 +1,74 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryLocalGroupActions +import OAI.Combinatorics.EditApproximation.Binary.BinaryWideGridWork +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Literal local scale and representative lists. Each bounded endpoint +grid is constructed before the center eligibility tests are performed. -/ + +namespace EditApproximation +namespace BinaryFraction + + + +@[simp] theorem queryExponentsWithWork_value (N F : ℕ) (a w : BinaryFraction) : + ((queryExponentsWithWork N F a w).1.map (fun e => 2 ^ e)) = + dyadicQueryWindow N w.value a.value F := by + have hscale : (List.range (max 1 N.bits.length)).map (fun e => 2 ^ e) = dyadicScales N := by + simpa only [dyadicScalesWithWork, arithmeticMapWithWork_value, powerTwoWord_value] using + dyadicScalesWithWork_value N + have hguard (e : ℕ) : (refinementScaleGuardWithWork F (2 ^ e) a w).1 = + decide (w.value / (16 * F) ≤ (2 ^ e : ℕ) ∧ ((2 ^ e : ℕ) : ℚ) ≤ 8 * a.value * w.value) := + Bool.eq_iff_iff.mpr (by simp only [refinementScaleGuardWithWork_value, decide_eq_true_eq]) + simp only [queryExponentsWithWork, filterWithWork_value, hguard] + unfold dyadicQueryWindow + rw [← hscale, List.filter_map] + rfl + +def localRepresentativesWithWork {n : ℕ} (N P F : ℕ) (a : BinaryFraction) + (initial : TargetInterval n → BinaryFraction) (query : TargetInterval n) : + List (ℕ × TargetInterval n) × ℕ := + let scales := queryExponentsWithWork N F a (initial query) + let radius := naturalCeilingWithWork (initial query) + let result := arithmeticFlatMapWithWork (fun e => + let b := 2 ^ e + let spacing := seedGridSpacingWithWork b P + let points := gridStateBoxWithWork n (bitWordValue spacing.1) (bitWordValue radius.1) query.lo query.hi + let selected := filterWithWork (fun r => centerEligibilityWithWork b F a (initial r)) points.1 + let labeled := arithmeticMapWithWork (fun r => ((b, r), 1)) selected.1 + (labeled.1, spacing.2 + points.2 + selected.2 + labeled.2 + e + 5)) scales.1 + (result.1, scales.2 + radius.2 + result.2 + 3) + +@[simp] theorem localRepresentativesWithWork_value {n : ℕ} (N P F : ℕ) (hP : 0 < P) + (a : BinaryFraction) (initial : TargetInterval n → BinaryFraction) (query : TargetInterval n) : + (localRepresentativesWithWork N P F a initial query).1 = + localRefinementRepresentatives N P F a.value (fun r => (initial r).value) query := by + have hcenter (b : ℕ) (r : TargetInterval n) : (centerEligibilityWithWork b F a (initial r)).1 = + decide ((b : ℚ) / (4 * a.value) ≤ (initial r).value ∧ (initial r).value ≤ 8 * F * b) := + Bool.eq_iff_iff.mpr (by simp only [centerEligibilityWithWork_value, decide_eq_true_eq]) + have hgrid (e : ℕ) : (gridStateBoxWithWork n (seedGridSpacing (2 ^ e) P) + ⌈(initial query).value⌉₊ query.lo query.hi).1 = + localTargetStates n (seedGridSpacing (2 ^ e) P) ⌈(initial query).value⌉₊ query := by + rw [gridStateBoxWithWork_value _ _ _ _ _ (by unfold seedGridSpacing; omega)] + rfl + unfold localRepresentativesWithWork + simp only [arithmeticFlatMapWithWork_value, arithmeticMapWithWork_value, filterWithWork_value, + hcenter, naturalCeilingWithWork_value, seedGridSpacingWithWork_value _ _ hP, hgrid] + change (queryExponentsWithWork N F a (initial query)).1.flatMap + (fun e => (((localTargetStates n (seedGridSpacing (2 ^ e) P) ⌈(initial query).value⌉₊ query).filter + (fun r => decide (((2 ^ e : ℕ) : ℚ) / (4 * a.value) ≤ (initial r).value ∧ + (initial r).value ≤ 8 * F * (2 ^ e : ℕ)))).map (fun r => (2 ^ e, r)))) = _ + trans ((queryExponentsWithWork N F a (initial query)).1.map (fun e => 2 ^ e)).flatMap + (fun b => ((localTargetStates n (seedGridSpacing b P) ⌈(initial query).value⌉₊ query).filter + (fun r => decide ((b : ℚ) / (4 * a.value) ≤ (initial r).value ∧ + (initial r).value ≤ 8 * F * b))).map (fun r => (b, r))) + · rw [List.flatMap_map] + · rw [queryExponentsWithWork_value] + rfl + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryRefinementParameters.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryRefinementParameters.lean new file mode 100644 index 0000000000000000000000000000000000000000..84780c4f6c85557d96b8f4a4e08955fd03074274 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryRefinementParameters.lean @@ -0,0 +1,54 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryOnlineParameters +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! The decrement is constructed on the same Boolean words as the online +constants. In particular no rational literal or uncharged inversion is +needed at a local refinement entry. -/ + +namespace EditApproximation +namespace BinaryFraction + + + +@[simp] theorem refinementDecrementWithWork_value (ell : List Bool) (hell : 0 < bitWordValue ell) : + (refinementDecrementWithWork ell hell).1.value = 1 / (bitWordValue ell : ℚ) ^ 10 := by + simp [refinementDecrementWithWork, value, SignedBinary.value, signedMagnitude, + bitPowerWithWork_value, bitWordValue] + +theorem refinementDecrementWithWork_width (ell : List Bool) (hell : 0 < bitWordValue ell) + (B : ℕ) (hB : ell.length ≤ B) : (refinementDecrementWithWork ell hell).1.width ≤ 10 * B + 1 := by + have h := bitPowerWithWork_length_le ell 10 B hB + simp only [refinementDecrementWithWork, width, List.length_cons, List.length_nil] + exact max_le (by omega) h + +theorem refinementDecrementWithWork_cost (ell : List Bool) (hell : 0 < bitWordValue ell) + (B : ℕ) (hB : ell.length ≤ B) : + (refinementDecrementWithWork ell hell).2 ≤ bitPowerBitBudget 10 B + 1 := + Nat.add_le_add_right (bitPowerWithWork_cost ell 10 B hB) 1 + +theorem refinementDecrementWithWork_cap (ell : List Bool) (hell : 0 < bitWordValue ell) + (H : ℕ) (hH : 64 ≤ H) (hwidth : ell.length ≤ H) : + (refinementDecrementWithWork ell hell).1.width ≤ H ^ 2 ∧ + (refinementDecrementWithWork ell hell).2 ≤ H ^ 8 := by + constructor + · exact (refinementDecrementWithWork_width ell hell H hwidth).trans (by nlinarith only [hH]) + · have h := refinementDecrementWithWork_cost ell hell H hwidth + have hsmall : 11 * (H + 1) + 1 ≤ 12 * H := by omega + have hsq := Nat.pow_le_pow_left hsmall 2 + have hnum : bitPowerBitBudget 10 H + 1 ≤ 300000 * H ^ 2 := by + unfold bitPowerBitBudget + nlinarith only [hsq, hH] + have hc : 300000 ≤ H ^ 6 := + (by norm_num : 300000 ≤ (64 : ℕ) ^ 6).trans (Nat.pow_le_pow_left hH 6) + exact h.trans (hnum.trans (by + calc + 300000 * H ^ 2 ≤ H ^ 6 * H ^ 2 := Nat.mul_le_mul_right _ hc + _ = H ^ 8 := by ring)) + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryRepresentativeKernel.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryRepresentativeKernel.lean new file mode 100644 index 0000000000000000000000000000000000000000..7ae0c7e00e30d7416309e699886cd59bab738256 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryRepresentativeKernel.lean @@ -0,0 +1,183 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryBellmanKernel +import OAI.Combinatorics.EditApproximation.Geometry.RepresentativeBands +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! The finite representative-band construction on stored binary fractions: +connection and child sums, the exact wide minimum, velocity, and every +literal band predicate. The Cartesian product materializes the wide-action enumeration. -/ + +namespace EditApproximation +namespace BinaryFraction + +open Finset + +private theorem nat_distance_value (a b : ℕ) : (Nat.dist a b : ℚ) = |(a : ℚ) - b| := by + rcases le_total a b with h | h + · rw [Nat.dist_eq_sub_of_le h, Nat.cast_sub h, abs_of_nonpos (sub_nonpos.mpr (by exact_mod_cast h))] + ring + · rw [Nat.dist_eq_sub_of_le_right h, Nat.cast_sub h, abs_of_nonneg (sub_nonneg.mpr (by exact_mod_cast h))] + +private theorem rationalConnectionBudget_nat {n : ℕ} (start finish : ℕ) + (states : List (TargetInterval n)) : + rationalConnectionBudget start states finish = (connectionBudget start states finish : ℚ) := by + induction states generalizing start with + | nil => simp only [rationalConnectionBudget, connectionBudget, nat_distance_value] + | cons state rest ih => + simp only [rationalConnectionBudget, connectionBudget, Nat.cast_add, ih, nat_distance_value] + + + +@[simp] theorem endpointDistanceWithWork_value {n : ℕ} (q r : TargetInterval n) : + (endpointDistanceWithWork q r).1.value = (targetEndpointDistance q r : ℚ) := by + simp only [endpointDistanceWithWork, canonicalAddWithWork_value, distanceWithWork_value, + nat_value, targetEndpointDistance, Nat.cast_add, nat_distance_value] + + + +@[simp] theorem endpointConnectionWithWork_value {n M : ℕ} (r : TargetInterval n) + (states : Fin M → TargetInterval n) : + (endpointConnectionWithWork r states).1.value = (endpointActionConnection r states : ℚ) := by + simp only [endpointConnectionWithWork, connectionWithWork_value, nat_value, + rationalConnectionBudget_nat, endpointActionConnection] + +def endpointScoreWithWork {n M : ℕ} (r : TargetInterval n) + (child : Fin M → TargetInterval n → BinaryFraction) (states : Fin M → TargetInterval n) : + BinaryFraction × ℕ := + let connection := endpointConnectionWithWork r states + let children := sumListWithWork (List.ofFn fun i => child i (states i)) + let result := canonicalAddWithWork connection.1 children.1 + (result.1, connection.2 + children.2 + result.2 + 2) + +@[simp] theorem endpointScoreWithWork_value {n M : ℕ} (r : TargetInterval n) + (child : Fin M → TargetInterval n → BinaryFraction) (states : Fin M → TargetInterval n) : + (endpointScoreWithWork r child states).1.value = + rationalEndpointActionValue r states (fun i s => (child i s).value) := by + simp only [endpointScoreWithWork, canonicalAddWithWork_value, endpointConnectionWithWork_value, + sumListWithWork_value, List.map_ofFn, List.sum_ofFn, rationalEndpointActionValue, Function.comp_def] + +def wideMinimumWithWork {n M : ℕ} (r : TargetInterval n) + (child : Fin M → TargetInterval n → BinaryFraction) + (actions : List (Fin M → TargetInterval n)) (hne : actions ≠ []) : BinaryFraction × ℕ := + let fallback := endpointScoreWithWork r child (actions.head hne) + let scores := arithmeticMapWithWork (endpointScoreWithWork r child) actions + let result := minimumWithWork fallback.1 scores.1 + (result.1, fallback.2 + scores.2 + result.2 + 2) + +@[simp] theorem wideMinimumWithWork_value {nx ny M : ℕ} (parent : TargetInterval nx) + (r : TargetInterval ny) (b P : ℕ) (child : Fin M → TargetInterval ny → BinaryFraction) + (hne : wideActionList M parent r b P ≠ []) : + (wideMinimumWithWork r child (wideActionList M parent r b P) hne).1.value = + rationalWideActionMinimum parent r b P hne (fun i s => (child i s).value) := by + simp only [wideMinimumWithWork, minimumWithWork_value, arithmeticMapWithWork_value, + List.map_map, Function.comp_def, endpointScoreWithWork_value, rationalWideActionMinimum] + + + +@[simp] theorem stateGapWithWork_value {n : ℕ} (sourceLength : ℕ) (r : TargetInterval n) : + (stateGapWithWork sourceLength r).1.value = (r.hi : ℚ) - r.lo - sourceLength := by + simp only [stateGapWithWork, subWithWork_value, nat_value] + +/-- Every filter callback is the literal binary band predicate. -/ +def bandFromActionsWithWork {nx ny M : ℕ} (parent : TargetInterval nx) + (r : TargetInterval ny) (b : ℕ) (tau theta velocity : BinaryFraction) + (child : Fin M → TargetInterval ny → BinaryFraction) + (actions : List (Fin M → TargetInterval ny)) (hne : actions ≠ []) : + List (Fin M → TargetInterval ny) × ℕ := + let margin := subWithWork one tau + let guard := leWithWork velocity.absolute margin.1 + if guard.1 then + let filtered := filterWithWork + (bandPredicateWithWork parent r b tau theta velocity actions hne child) actions + (filtered.1, margin.2 + guard.2 + filtered.2 + 2) + else ([], margin.2 + guard.2 + 1) + +@[simp] theorem bandFromActionsWithWork_value {nx ny M : ℕ} (parent : TargetInterval nx) + (r : TargetInterval ny) (b : ℕ) (tau theta velocity : BinaryFraction) + (child : Fin M → TargetInterval ny → BinaryFraction) + (actions : List (Fin M → TargetInterval ny)) (hne : actions ≠ []) : + (bandFromActionsWithWork parent r b tau theta velocity child actions hne).1 = + if |velocity.value| ≤ 1 - tau.value then + actions.filter (fun states => decide (bandActionPredicate parent r b tau.value theta.value + velocity.value actions hne (fun i s => (child i s).value) states)) else [] := by + have hguard : (leWithWork velocity.absolute (subWithWork one tau).1).1 = true ↔ + |velocity.value| ≤ 1 - tau.value := by + simp only [leWithWork_value, absolute_value, subWithWork_value, one, nat_value, Nat.cast_one] + unfold bandFromActionsWithWork + dsimp only + by_cases h : |velocity.value| ≤ 1 - tau.value + · rw [ite_eq_left (hguard.mpr h), ite_eq_left h, filterWithWork_value] + apply List.filter_congr + intro states _ + apply Bool.eq_iff_iff.mpr + exact (bandPredicateWithWork_value parent r b tau theta velocity actions hne child states).trans + decide_eq_true_iff.symm + · rw [ite_eq_right (fun hg => h (hguard.mp hg)), ite_eq_right h] + +/-- The actions have been materialized once and are reused for the wide +minimum and all prefix queries. -/ +def representativeFromActionsWithWork {nx ny M : ℕ} (parent : TargetInterval nx) + (r : TargetInterval ny) (sourceLength b : ℕ) (tau theta : BinaryFraction) + (child : Fin M → TargetInterval ny → BinaryFraction) + (actions : List (Fin M → TargetInterval ny)) : List (Fin M → TargetInterval ny) × ℕ := + if hne : actions = [] then ([], 1) else + let Z := wideMinimumWithWork r child actions hne + let positive := ltWithWork zero Z.1 + if positive.1 then + let gap := stateGapWithWork sourceLength r + let velocity := divWithWork gap.1 Z.1 + let result := bandFromActionsWithWork parent r b tau theta velocity.1 child actions hne + (result.1, Z.2 + positive.2 + gap.2 + velocity.2 + result.2 + 3) + else ([], Z.2 + positive.2 + 2) + +/-- Full stored-data representative construction, including the Cartesian +product and all subsequent numerical work. -/ +def representativeBandWithWork {nx ny M : ℕ} (parent : TargetInterval nx) + (r : TargetInterval ny) (sourceLength b P : ℕ) (tau theta : BinaryFraction) + (child : Fin M → TargetInterval ny → BinaryFraction) : List (Fin M → TargetInterval ny) × ℕ := + let wide := materializedWideActionsWithWork M parent r b P + let result := representativeFromActionsWithWork parent r sourceLength b tau theta child (wide.1.map Vector.get) + (result.1, wide.2 + result.2 + wide.1.length + 1) + +theorem representativeFromActionsWithWork_value {α : Type*} (source target : List α) + {M : ℕ} (parent : TargetInterval source.length) (r : TargetInterval target.length) + (b P : ℕ) (tau theta : BinaryFraction) (child : Fin M → TargetInterval target.length → BinaryFraction) : + (representativeFromActionsWithWork parent r (parent.hi - parent.lo) b tau theta child + (wideActionList M parent r b P)).1 = + representativeBandActions source target parent r b P tau.value theta.value + (fun i s => (child i s).value) := by + have hgap : (stateGapWithWork (parent.hi - parent.lo) r).1.value = + rationalStateGap (substring source parent.lo parent.hi) target r := by + rw [stateGapWithWork_value, rationalStateGap, substring_length source parent.lo parent.hi parent.valid] + by_cases hne : wideActionList M parent r b P = [] + · simp only [representativeFromActionsWithWork, representativeBandActions, dite_eq_left hne] + · have hz := wideMinimumWithWork_value parent r b P child hne + have hzero : zero.value = 0 := by + rw [← representation_value, zero_representation, UnreducedRational.value_zero] + have hpositive : (ltWithWork zero (wideMinimumWithWork r child + (wideActionList M parent r b P) hne).1).1 = true ↔ + 0 < rationalWideActionMinimum parent r b P hne (fun i s => (child i s).value) := by + rw [ltWithWork_value, hz, hzero] + simp only [representativeFromActionsWithWork, representativeBandActions, dite_eq_right hne] + by_cases hp : 0 < rationalWideActionMinimum parent r b P hne (fun i s => (child i s).value) + · rw [ite_eq_left (hpositive.mpr hp), ite_eq_left hp] + dsimp only + rw [bandFromActionsWithWork_value] + simp only [divWithWork_value, hgap, hz, computedBandActions, dite_eq_right hne] + · rw [ite_eq_right (fun h => hp (hpositive.mp h)), ite_eq_right hp] + +theorem representativeBandWithWork_value {α : Type*} (source target : List α) + {M : ℕ} (parent : TargetInterval source.length) (r : TargetInterval target.length) + (b P : ℕ) (tau theta : BinaryFraction) (child : Fin M → TargetInterval target.length → BinaryFraction) : + (representativeBandWithWork parent r (parent.hi - parent.lo) b P tau theta child).1 = + representativeBandActions source target parent r b P tau.value theta.value + (fun i s => (child i s).value) := by + simp only [representativeBandWithWork, materializedWideActionsWithWork_value] + exact representativeFromActionsWithWork_value source target parent r b P tau theta child + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryRepresentativeReads.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryRepresentativeReads.lean new file mode 100644 index 0000000000000000000000000000000000000000..ba1d6470e15e2b09829d996316ef60420269ff7e --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryRepresentativeReads.lean @@ -0,0 +1,83 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryLocalRepresentativeWork +import OAI.Combinatorics.EditApproximation.Binary.BinaryReadComposition +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Query-local representative construction reads its finite initial +table explicitly. Each center lookup is charged before testing it. -/ + +namespace EditApproximation +namespace BinaryFraction + +def representativeScalePlainWithWork {n : ℕ} (P F : ℕ) (a : BinaryFraction) + (initial : TargetInterval n → BinaryFraction) (radius : List Bool) + (query : TargetInterval n) (e : ℕ) : List (ℕ × TargetInterval n) × ℕ := + let b := 2 ^ e + let spacing := seedGridSpacingWithWork b P + let points := gridStateBoxWithWork n (bitWordValue spacing.1) (bitWordValue radius) query.lo query.hi + let selected := filterWithWork (fun r => centerEligibilityWithWork b F a (initial r)) points.1 + let labeled := arithmeticMapWithWork (fun r => ((b, r), 1)) selected.1 + (labeled.1, spacing.2 + points.2 + selected.2 + labeled.2 + e + 5) + + + +theorem representativeScaleReadWithWork_eq_cost {n : ℕ} (P F : ℕ) (a : BinaryFraction) + (read : TargetInterval n → BinaryFraction × ℕ) (radius : List Bool) + (query : TargetInterval n) (e R : ℕ) (hR : ∀ r, (read r).2 ≤ R) : + (representativeScaleReadWithWork P F a read radius query e).1 = + (representativeScalePlainWithWork P F a (fun r => (read r).1) radius query e).1 ∧ + (representativeScaleReadWithWork P F a read radius query e).2 ≤ + (representativeScalePlainWithWork P F a (fun r => (read r).1) radius query e).2 * (R + 1) := by + let spacing := seedGridSpacingWithWork (2 ^ e) P + let points := gridStateBoxWithWork n (bitWordValue spacing.1) (bitWordValue radius) query.lo query.hi + have h := filterWithWork_add_read (fun r => centerEligibilityWithWork (2 ^ e) F a (read r).1) + (fun r => (read r).2) points.1 R (fun r _ => hR r) + constructor + · simp only [representativeScaleReadWithWork, representativeScalePlainWithWork, spacing, points, h.1] + · unfold representativeScaleReadWithWork representativeScalePlainWithWork + change spacing.2 + points.2 + _ + _ + e + 5 ≤ (spacing.2 + points.2 + _ + _ + e + 5) * _ + rw [h.1] + nlinarith only [h.2] + + + +theorem localRepresentativeReadWithWork_eq_cost {n : ℕ} (N P F : ℕ) (a : BinaryFraction) + (read : TargetInterval n → BinaryFraction × ℕ) (query : TargetInterval n) + (R : ℕ) (hR : ∀ r, (read r).2 ≤ R) : + (localRepresentativeReadWithWork N P F a read query).1 = + (localRepresentativesWithWork N P F a (fun r => (read r).1) query).1 ∧ + (localRepresentativeReadWithWork N P F a read query).2 ≤ + (localRepresentativesWithWork N P F a (fun r => (read r).1) query).2 * (R + 2) := by + let scales := queryExponentsWithWork N F a (read query).1 + let radius := naturalCeilingWithWork (read query).1 + let plain := representativeScalePlainWithWork P F a (fun r => (read r).1) radius.1 query + let withRead := representativeScaleReadWithWork P F a read radius.1 query + have h := arithmeticFlatMapWithWork_factor withRead plain scales.1 (R + 1) (by omega) + (fun e _ => (representativeScaleReadWithWork_eq_cost P F a read radius.1 query e R hR).1) + (fun e _ => (representativeScaleReadWithWork_eq_cost P F a read radius.1 query e R hR).2) + have hquery := hR query + constructor + · exact h.1 + · change (read query).2 + scales.2 + radius.2 + + (arithmeticFlatMapWithWork withRead scales.1).2 + 3 ≤ + (scales.2 + radius.2 + (arithmeticFlatMapWithWork plain scales.1).2 + 3) * (R + 2) + nlinarith only [h.2, hquery] + +theorem localRepresentativeReadWithWork_cost {n : ℕ} (N P F B R : ℕ) (a : BinaryFraction) + (read : TargetInterval n → BinaryFraction × ℕ) (query : TargetInterval n) + (hB : 7 ≤ B) (hN : Nat.size N ≤ B) (hF : Nat.size F + 2 ≤ B) + (hFpos : 1 ≤ F) (hPbits : Nat.size P ≤ B) (hP : 0 < P) (hn : Nat.size n ≤ B) + (ha : a.width ≤ B) (hi : ∀ r, (read r).1.width ≤ B) (hR : ∀ r, (read r).2 ≤ R) : + (localRepresentativeReadWithWork N P F a read query).2 ≤ + localRepresentativesBitBudget P F B * (R + 2) := + (localRepresentativeReadWithWork_eq_cost N P F a read query R hR).2.trans + (Nat.mul_le_mul_right _ + (localRepresentativesWithWork_cost N P F B a (fun r => (read r).1) query + hB hN hF hFpos hPbits hP hn ha hi)) + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryRepresentativeSpace.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryRepresentativeSpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..ead13a501d7724b32f01c6f9fad9d49b06ae729e --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryRepresentativeSpace.lean @@ -0,0 +1,79 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryBandSpace +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation.BinaryFraction + + + +theorem bandFromActionsReadAllocation_le_work {nx ny M : ℕ} (parent : TargetInterval nx) + (r : TargetInterval ny) (b : ℕ) (tau theta velocity : BinaryFraction) + (read : Fin M → TargetInterval ny → BinaryFraction × ℕ) + (allocation : Fin M → TargetInterval ny → ℕ) + (actions : List (Fin M → TargetInterval ny)) (hne : actions ≠ []) + (h : ∀ action ∈ actions, ∀ i, allocation i (action i) ≤ (read i (action i)).2) : + bandFromActionsReadAllocation parent r b tau theta velocity read allocation actions hne ≤ + (bandFromActionsReadWithWork parent r b tau theta velocity read actions hne).2 := by + have hm := subAllocation_le_work one tau + have hg := leAllocation_le_work velocity.absolute (subWithWork one tau).1 + have hf := filterAllocation_le_work + (bandPredicateReadWithWork parent r b tau theta velocity actions hne read) + (bandPredicateReadAllocation parent r b tau theta velocity actions hne read allocation) actions + (fun action _ => bandPredicateReadAllocation_le_work parent r b tau theta velocity actions hne read allocation action h) + unfold bandFromActionsReadAllocation bandFromActionsReadWithWork + dsimp only + split_ifs <;> dsimp only + · exact (Nat.add_le_add (Nat.add_le_add hm hg) hf).trans (Nat.le_add_right _ 2) + · exact Nat.add_le_add (Nat.add_le_add hm hg) (Nat.zero_le 1) + + + +theorem representativeFromActionsReadAllocation_le_work {nx ny M : ℕ} (parent : TargetInterval nx) + (r : TargetInterval ny) (sourceLength b : ℕ) (tau theta : BinaryFraction) + (read : Fin M → TargetInterval ny → BinaryFraction × ℕ) + (allocation : Fin M → TargetInterval ny → ℕ) + (actions : List (Fin M → TargetInterval ny)) + (h : ∀ action ∈ actions, ∀ i, allocation i (action i) ≤ (read i (action i)).2) : + representativeFromActionsReadAllocation parent r sourceLength b tau theta read allocation actions ≤ + (representativeFromActionsReadWithWork parent r sourceLength b tau theta read actions).2 := by + have costBound (z z' p p' g g' d d' b b' : ℕ) + (hz : z ≤ z') (hp : p ≤ p') (hg : g ≤ g') (hd : d ≤ d') (hb : b ≤ b') : + z + p + (g + d + b) ≤ z' + p' + g' + d' + b' + 3 := by + omega + unfold representativeFromActionsReadAllocation representativeFromActionsReadWithWork + by_cases hne : actions = [] + · simp only [hne, ↓reduceDIte, Nat.zero_le] + · simp only [hne, ↓reduceDIte] + have hz := wideMinimumReadAllocation_le_work r read allocation actions hne h + have hp := ltAllocation_le_work zero (wideMinimumReadWithWork r read actions hne).1 + have hg := stateGapAllocation_le_work sourceLength r + have hd := divAllocation_le_work (stateGapWithWork sourceLength r).1 + (wideMinimumReadWithWork r read actions hne).1 + have hb := bandFromActionsReadAllocation_le_work parent r b tau theta + (divWithWork (stateGapWithWork sourceLength r).1 (wideMinimumReadWithWork r read actions hne).1).1 + read allocation actions hne h + split_ifs <;> dsimp only + · exact costBound _ _ _ _ _ _ _ _ _ _ hz hp hg hd hb + · exact Nat.add_le_add (Nat.add_le_add hz hp) (by decide : 0 ≤ 2) + + + +theorem preparedRepresentativeReadAllocation_le_work {nx ny M : ℕ} (parent : TargetInterval nx) + (center : TargetInterval ny) (sourceLength b P : ℕ) (tau theta : BinaryFraction) + (read : Fin M → TargetInterval ny → BinaryFraction × ℕ) + (allocation : Fin M → TargetInterval ny → ℕ) + (h : ∀ i q, allocation i q ≤ (read i q).2) : + preparedRepresentativeReadAllocation parent center sourceLength b P tau theta read allocation ≤ + (preparedRepresentativeReadWithWork parent center sourceLength b P tau theta read).2 := by + have hw := wideActionGridAllocation_le_work M parent center b P + have hr := representativeFromActionsReadAllocation_le_work parent center sourceLength b tau theta read allocation + ((wideActionGridWithWork M parent center b P).1.map Vector.get) (fun _ _ i => h i _) + unfold preparedRepresentativeReadAllocation preparedRepresentativeReadWithWork + dsimp only + omega + +end EditApproximation.BinaryFraction + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryRepresentativeWork.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryRepresentativeWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..ee61bd831dbf9e247c7b8642a148a6ab5e4126f7 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryRepresentativeWork.lean @@ -0,0 +1,160 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryRepresentativeKernel +import OAI.Combinatorics.EditApproximation.Geometry.PrefixBitEnvelope + +namespace OAI + +/-! Bounds for the executed representative scores and velocity. They use +only the widths of actual stored inputs, and apply on every seed. -/ + +namespace EditApproximation +namespace BinaryFraction + +open Finset + +def endpointDistanceWordBudget (B : ℕ) : ℕ := 64 * B + 54 + +def endpointDistanceBitBudget (B : ℕ) : ℕ := + 2 * (6000 * (B + 1) ^ 2 + 2) + 6000 * (8 * B + 7) ^ 2 + 4 * B + 3 + +theorem endpointDistanceWithWork_bounds {n : ℕ} (q r : TargetInterval n) (B : ℕ) + (hql : Nat.size q.lo + 2 ≤ B) (hqh : Nat.size q.hi + 2 ≤ B) + (hrl : Nat.size r.lo + 2 ≤ B) (hrh : Nat.size r.hi + 2 ≤ B) : + (endpointDistanceWithWork q r).1.width ≤ endpointDistanceWordBudget B ∧ + (endpointDistanceWithWork q r).2 ≤ endpointDistanceBitBudget B := by + have hlw := distanceWithWork_width (nat q.lo) (nat r.lo) B + ((nat_width_le _).trans hql) ((nat_width_le _).trans hrl) + have hhw := distanceWithWork_width (nat q.hi) (nat r.hi) B + ((nat_width_le _).trans hqh) ((nat_width_le _).trans hrh) + have hlc := distanceWithWork_cost (nat q.lo) (nat r.lo) B + ((nat_width_le _).trans hql) ((nat_width_le _).trans hrl) + have hhc := distanceWithWork_cost (nat q.hi) (nat r.hi) B + ((nat_width_le _).trans hqh) ((nat_width_le _).trans hrh) + have hw := canonicalAddWithWork_width (distanceWithWork (nat q.lo) (nat r.lo)).1 + (distanceWithWork (nat q.hi) (nat r.hi)).1 (8 * B + 6) hlw hhw + have hc := canonicalAddWithWork_cost (distanceWithWork (nat q.lo) (nat r.lo)).1 + (distanceWithWork (nat q.hi) (nat r.hi)).1 (8 * B + 6) hlw hhw + constructor + · change (canonicalAddWithWork (distanceWithWork (nat q.lo) (nat r.lo)).1 + (distanceWithWork (nat q.hi) (nat r.hi)).1).1.width ≤ endpointDistanceWordBudget B + unfold endpointDistanceWordBudget + omega + · change _ + _ + _ + _ + _ + _ + _ + 3 ≤ _ + simp only [Nat.add_assoc, Nat.reduceAdd] at hc + unfold endpointDistanceBitBudget + omega + +def endpointScoreWordBudget (M B : ℕ) : ℕ := + 8 * (connectionWordBudget M B + bandMassTotalStorageBudget M B) + 6 + +def endpointScoreBitBudget (M B : ℕ) : ℕ := + connectionBitBudget M B + 2 * B + M + 2 + storedSumBitBudget M B + 6 * M + + 6000 * (connectionWordBudget M B + bandMassTotalStorageBudget M B + 1) ^ 2 + 2 + +theorem endpointScoreWithWork_bounds {n M : ℕ} (r : TargetInterval n) + (child : Fin M → TargetInterval n → BinaryFraction) (states : Fin M → TargetInterval n) + (B : ℕ) (hrl : Nat.size r.lo + 2 ≤ B) (hrh : Nat.size r.hi + 2 ≤ B) + (he : ∀ i, Nat.size (states i).lo + 2 ≤ B ∧ Nat.size (states i).hi + 2 ≤ B) + (hv : ∀ i, (child i (states i)).width ≤ B) : + (endpointScoreWithWork r child states).1.width ≤ endpointScoreWordBudget M B ∧ + (endpointScoreWithWork r child states).2 ≤ endpointScoreBitBudget M B := by + have hlist : ∀ s ∈ List.ofFn states, Nat.size s.lo + 2 ≤ B ∧ Nat.size s.hi + 2 ≤ B := by + intro s hs + obtain ⟨i, rfl⟩ := List.mem_ofFn.mp hs + exact he i + have hcw := connectionWithWork_width (nat r.lo) (nat r.hi) (List.ofFn states) B + ((nat_width_le _).trans hrl) ((nat_width_le _).trans hrh) hlist + have hcc := connectionWithWork_cost (nat r.lo) (nat r.hi) (List.ofFn states) B + ((nat_width_le _).trans hrl) ((nat_width_le _).trans hrh) hlist + simp only [List.length_ofFn] at hcw hcc + have hew : (endpointConnectionWithWork r states).1.width ≤ connectionWordBudget M B := hcw + have hec : (endpointConnectionWithWork r states).2 ≤ connectionBitBudget M B + 2 * B + M + 2 := by + change _ + Nat.size r.lo + Nat.size r.hi + M + 2 ≤ _ + omega + have hvlist : ∀ a ∈ List.ofFn (fun i => child i (states i)), a.width ≤ B := by + intro a ha + obtain ⟨i, rfl⟩ := List.mem_ofFn.mp ha + exact hv i + have hsw := sumListWithWork_width _ B hvlist + have hsc := sumListWithWork_cost _ B hvlist + simp only [List.length_ofFn] at hsw hsc + have htw := canonicalAddWithWork_width (endpointConnectionWithWork r states).1 + (sumListWithWork (List.ofFn fun i => child i (states i))).1 + (connectionWordBudget M B + bandMassTotalStorageBudget M B) (by omega) (by omega) + have htc := canonicalAddWithWork_cost (endpointConnectionWithWork r states).1 + (sumListWithWork (List.ofFn fun i => child i (states i))).1 + (connectionWordBudget M B + bandMassTotalStorageBudget M B) (by omega) (by omega) + refine ⟨htw, ?_⟩ + change _ + _ + _ + 2 ≤ _ + unfold endpointScoreBitBudget + omega + +def wideMinimumBitBudget (M n B : ℕ) : ℕ := + endpointScoreBitBudget M B + n * (endpointScoreBitBudget M B + 3) + + (1 + n * (1000 * (endpointScoreWordBudget M B + 1) ^ 2 + 2)) + 2 + +theorem wideMinimumWithWork_bounds {n M : ℕ} (r : TargetInterval n) + (child : Fin M → TargetInterval n → BinaryFraction) + (actions : List (Fin M → TargetInterval n)) (hne : actions ≠ []) (B : ℕ) + (hrl : Nat.size r.lo + 2 ≤ B) (hrh : Nat.size r.hi + 2 ≤ B) + (he : ∀ states ∈ actions, ∀ i, Nat.size (states i).lo + 2 ≤ B ∧ Nat.size (states i).hi + 2 ≤ B) + (hv : ∀ states ∈ actions, ∀ i, (child i (states i)).width ≤ B) : + (wideMinimumWithWork r child actions hne).1.width ≤ endpointScoreWordBudget M B ∧ + (wideMinimumWithWork r child actions hne).2 ≤ wideMinimumBitBudget M actions.length B := by + have hf := endpointScoreWithWork_bounds r child (actions.head hne) B hrl hrh + (he _ (List.head_mem hne)) (hv _ (List.head_mem hne)) + let scores := arithmeticMapWithWork (endpointScoreWithWork r child) actions + have hs : ∀ value ∈ scores.1, value.width ≤ endpointScoreWordBudget M B := by + intro value hvalue + simp only [scores, arithmeticMapWithWork_value] at hvalue + obtain ⟨states, hstates, heq⟩ := List.mem_map.mp hvalue + subst value + exact (endpointScoreWithWork_bounds r child states B hrl hrh (he states hstates) (hv states hstates)).1 + have hlen : scores.1.length = actions.length := by + simp only [scores, arithmeticMapWithWork_value, List.length_map] + have hsc := arithmeticMapWithWork_cost (endpointScoreWithWork r child) actions + (endpointScoreBitBudget M B) (fun states hstates => + (endpointScoreWithWork_bounds r child states B hrl hrh (he states hstates) (hv states hstates)).2) + have hmw := minimumWithWork_width (endpointScoreWithWork r child (actions.head hne)).1 + scores.1 (endpointScoreWordBudget M B) hf.1 hs + have hmc := minimumWithWork_cost (endpointScoreWithWork r child (actions.head hne)).1 + scores.1 (endpointScoreWordBudget M B) hf.1 hs + rw [hlen] at hmc + refine ⟨hmw, ?_⟩ + change (endpointScoreWithWork r child (actions.head hne)).2 + scores.2 + + (minimumWithWork (endpointScoreWithWork r child (actions.head hne)).1 scores.1).2 + 2 ≤ _ + change scores.2 ≤ _ at hsc + unfold wideMinimumBitBudget + omega + +def stateGapWordBudget (B : ℕ) : ℕ := 64 * B + 54 + +def stateGapBitBudget (B : ℕ) : ℕ := + (6000 * (B + 1) ^ 2 + 1) + (6000 * (8 * B + 7) ^ 2 + 1) + 3 * B + 2 + +theorem stateGapWithWork_bounds {n : ℕ} (sourceLength : ℕ) (r : TargetInterval n) (B : ℕ) + (hs : Nat.size sourceLength + 2 ≤ B) (hrl : Nat.size r.lo + 2 ≤ B) + (hrh : Nat.size r.hi + 2 ≤ B) : + (stateGapWithWork sourceLength r).1.width ≤ stateGapWordBudget B ∧ + (stateGapWithWork sourceLength r).2 ≤ stateGapBitBudget B := by + have htw := subWithWork_width (nat r.hi) (nat r.lo) B + ((nat_width_le _).trans hrh) ((nat_width_le _).trans hrl) + have htc := subWithWork_cost (nat r.hi) (nat r.lo) B + ((nat_width_le _).trans hrh) ((nat_width_le _).trans hrl) + have hsw : (nat sourceLength).width ≤ 8 * B + 6 := (nat_width_le _).trans (by omega) + have hrw := subWithWork_width (subWithWork (nat r.hi) (nat r.lo)).1 (nat sourceLength) + (8 * B + 6) htw hsw + have hrc := subWithWork_cost (subWithWork (nat r.hi) (nat r.lo)).1 (nat sourceLength) + (8 * B + 6) htw hsw + constructor + · change (subWithWork (subWithWork (nat r.hi) (nat r.lo)).1 (nat sourceLength)).1.width ≤ stateGapWordBudget B + unfold stateGapWordBudget + omega + · change _ + _ + _ + _ + _ + 2 ≤ _ + simp only [Nat.add_assoc, Nat.reduceAdd] at hrc + unfold stateGapBitBudget + omega + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryRoundedKernel.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryRoundedKernel.lean new file mode 100644 index 0000000000000000000000000000000000000000..f1eab3c61738e234c88e738ed607fe23f101366d --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryRoundedKernel.lean @@ -0,0 +1,153 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryRepresentativeKernel +import OAI.Combinatorics.EditApproximation.Binary.BinaryMedianKernel +import OAI.Combinatorics.EditApproximation.Binary.BinaryGridWork +import OAI.Combinatorics.EditApproximation.Binary.BinaryActualBandOptimizer +import OAI.Combinatorics.EditApproximation.Geometry.UnskippedBands +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Exact rounded canonical actions from their computed binary envelopes. +Rounding spacing is obtained by a natural ceiling, since the dyadic product +is either below one or an integer. No logarithm is evaluated. -/ + +namespace EditApproximation + +open Finset + +private theorem interval_eq_of_endpoints {n : ℕ} (a b : TargetInterval n) + (hl : a.lo = b.lo) (hh : a.hi = b.hi) : a = b := by + cases a + cases b + cases hl + cases hh + rfl + +/-- A binary interval output, with its order/range proofs erased. -/ + + +@[simp] theorem roundStateWithWork_value {n : ℕ} (spacing : ℕ) (hspacing : 0 < spacing) + (q : TargetInterval n) : (roundStateWithWork spacing hspacing q).1 = roundInterval spacing q := by + apply interval_eq_of_endpoints + · exact congrArg Prod.fst (binaryIntervalRoundWithWork_value spacing hspacing q) + · exact congrArg Prod.snd (binaryIntervalRoundWithWork_value spacing hspacing q) + + + +@[simp] theorem actionEqualWithWork_value {n M : ℕ} (a b : Fin M → TargetInterval n) : + (actionEqualWithWork a b).1 = true ↔ a = b := by + simp only [actionEqualWithWork, allWithWork_value, List.mem_finRange, forall_true_left, + Bool.and_eq_true, naturalEqualWithWork_value] + constructor + · intro h + funext i + exact interval_eq_of_endpoints _ _ (h i).1 (h i).2 + · intro h + subst b + exact fun _ => ⟨rfl, rfl⟩ + +/-- A literal membership scan, preserving the wide-list definition on +inaccurate as well as accurate input seeds. -/ + + +@[simp] theorem actionMemberWithWork_value {n M : ℕ} (a : Fin M → TargetInterval n) + (actions : List (Fin M → TargetInterval n)) : + (actionMemberWithWork a actions).1 = true ↔ a ∈ actions := by + induction actions with + | nil => simp only [actionMemberWithWork, Bool.false_eq_true, List.not_mem_nil] + | cons b rest ih => + simp only [actionMemberWithWork, Bool.or_eq_true, actionEqualWithWork_value, ih, List.mem_cons] + +namespace BinaryFraction + + + +@[simp] theorem roundedSpacingWithWork_value (theta envelope : BinaryFraction) : + bitWordValue (roundedSpacingWithWork theta envelope).1 = ⌈max 1 (theta.value * envelope.value)⌉₊ := by + simp only [roundedSpacingWithWork, naturalCeilingWithWork_value, maxWithWork_value, + canonicalMulWithWork_value, one, nat_value, Nat.cast_one] + +theorem roundedSpacingWithWork_pos (theta envelope : BinaryFraction) : + 0 < bitWordValue (roundedSpacingWithWork theta envelope).1 := by + rw [roundedSpacingWithWork_value, Nat.ceil_pos] + exact lt_of_lt_of_le (by norm_num : (0 : ℚ) < 1) (le_max_left _ _) + +theorem roundedSpacingWithWork_band_value {ny M : ℕ} (thetaExponent b : ℕ) + (band : List (Fin M → TargetInterval ny)) + (initial : Fin M → TargetInterval ny → BinaryFraction) (i : Fin M) (hb : 0 < b) : + bitWordValue (roundedSpacingWithWork (inversePowerTwo thetaExponent) + (bandEnvelopeWithWork b band initial i).1).1 = + bandRoundSpacing thetaExponent b band (fun j q => (initial j q).value) i := by + rw [roundedSpacingWithWork_value, inversePowerTwo_value, bandEnvelopeWithWork_value _ _ _ _ hb, + ← bandRoundSpacing_exact thetaExponent b band (fun j q => (initial j q).value) i, Nat.ceil_natCast] + +def roundedBandWithWork {ny M : ℕ} (thetaExponent b : ℕ) + (band : List (Fin M → TargetInterval ny)) (hne : band ≠ []) + (initial : Fin M → TargetInterval ny → BinaryFraction) : + Vector (TargetInterval ny) M × ℕ := + vectorMapWithWork M fun i => + let envelope := bandEnvelopeWithWork b band initial i + let spacing := roundedSpacingWithWork (inversePowerTwo thetaExponent) envelope.1 + let rounded := roundStateWithWork (bitWordValue spacing.1) + (roundedSpacingWithWork_pos _ _) (band.head hne i) + (rounded.1, envelope.2 + spacing.2 + rounded.2 + thetaExponent + 3) + +@[simp] theorem roundedBandWithWork_value {ny M : ℕ} (thetaExponent b : ℕ) + (band : List (Fin M → TargetInterval ny)) (hne : band ≠ []) + (initial : Fin M → TargetInterval ny → BinaryFraction) (hb : 0 < b) : + (roundedBandWithWork thetaExponent b band hne initial).1.get = + canonicalRoundedBandAction thetaExponent b band hne (fun j q => (initial j q).value) := by + funext i + simp only [roundedBandWithWork, vectorMapWithWork_value, roundStateWithWork_value, + roundedSpacingWithWork_band_value _ _ _ _ _ hb, + canonicalRoundedBandAction, roundedBandAction] + +/-- All numerical acceptance tests after a nonempty band has been built. -/ +def unskippedGuardWithWork {nx ny M : ℕ} (parent : TargetInterval nx) (_center : TargetInterval ny) + (b thetaExponent : ℕ) (F : BinaryFraction) (band wide : List (Fin M → TargetInterval ny)) + (hne : band ≠ []) (initial : Fin M → TargetInterval ny → BinaryFraction) : Bool × ℕ := + let envelope := envelopeVectorWithWork b band initial + let total := bandMassTotalWithWork envelope.1 + let fb := canonicalMulWithWork F (nat b) + let limit := canonicalMulWithWork (nat 64) fb.1 + let sumGuard := leWithWork total.1 limit.1 + let rounded := roundedBandWithWork thetaExponent b band hne initial + let wideGuard := actionMemberWithWork rounded.1.get wide + let gapGuard := allWithWork (fun i => + let sourceLength := binaryNaturalSubtractWithWork (sourceChild parent i).hi (sourceChild parent i).lo + let gap := stateGapWithWork (bitWordValue sourceLength.1) (rounded.1.get i) + let bound := canonicalMulWithWork (nat 2) (envelope.1.get i) + let test := leWithWork gap.1.absolute bound.1 + (test.1, sourceLength.2 + gap.2 + bound.2 + test.2 + 3)) (List.finRange M) + (sumGuard.1 && wideGuard.1 && gapGuard.1, + envelope.2 + total.2 + fb.2 + limit.2 + sumGuard.2 + rounded.2 + wideGuard.2 + gapGuard.2 + 5) + +@[simp] theorem unskippedGuardWithWork_value {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (center : TargetInterval target.length) + (b thetaExponent : ℕ) (F : BinaryFraction) + (band wide : List (Fin M → TargetInterval target.length)) (hne : band ≠ []) + (initial : Fin M → TargetInterval target.length → BinaryFraction) (hb : 0 < b) : + (unskippedGuardWithWork parent center b thetaExponent F band wide hne initial).1 = true ↔ + (∑ i, bandChildEnvelope b band (fun j q => (initial j q).value) i) ≤ 64 * F.value * b ∧ + canonicalRoundedBandAction thetaExponent b band hne (fun j q => (initial j q).value) ∈ wide ∧ + ∀ i, |rationalStateGap + (substring source (sourceChild parent i).lo (sourceChild parent i).hi) target + (canonicalRoundedBandAction thetaExponent b band hne (fun j q => (initial j q).value) i)| ≤ + 2 * bandChildEnvelope b band (fun j q => (initial j q).value) i := by + have hsub (i : Fin M) : + bitWordValue (binaryNaturalSubtractWithWork (sourceChild parent i).hi (sourceChild parent i).lo).1 = + (sourceChild parent i).hi - (sourceChild parent i).lo := + binaryNaturalSubtractWithWork_value _ _ (sourceChild parent i).ordered + simp only [unskippedGuardWithWork, Bool.and_eq_true, leWithWork_value, + bandMassTotalWithWork_value, canonicalMulWithWork_value, nat_value, + envelopeVectorWithWork_value b band initial hb, roundedBandWithWork_value _ _ _ _ _ hb, + actionMemberWithWork_value, allWithWork_value, List.mem_finRange, forall_true_left, + absolute_value, stateGapWithWork_value, hsub, rationalStateGap, + substring_length source _ _ (sourceChild parent _).valid] + rw [mul_assoc, Nat.cast_ofNat, and_assoc, Nat.cast_ofNat] + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryRoundedReads.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryRoundedReads.lean new file mode 100644 index 0000000000000000000000000000000000000000..99b49b6fe4210d526da014bcd9c9667d57faf920 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryRoundedReads.lean @@ -0,0 +1,57 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryEnvelopeReads +import OAI.Combinatorics.EditApproximation.Binary.BinaryRoundedKernel +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Rounded canonical actions and their acceptance guards retain the +literal initial-table reads used by each child-envelope computation. -/ + +namespace EditApproximation +namespace BinaryFraction + + + +theorem roundedBandReadWithWork_eq_cost {n M : ℕ} (exponent b : ℕ) + (band : List (Fin M → TargetInterval n)) (hne : band ≠ []) + (read : Fin M → TargetInterval n → BinaryFraction × ℕ) (R : ℕ) + (hr : ∀ i q, (read i q).2 ≤ R) : + (roundedBandReadWithWork exponent b band hne read).1 = + (roundedBandWithWork exponent b band hne (fun i q => (read i q).1)).1 ∧ + (roundedBandReadWithWork exponent b band hne read).2 ≤ + (roundedBandWithWork exponent b band hne (fun i q => (read i q).1)).2 + M * (band.length * (R + 3)) := by + have add_cost (a b s t e D : ℕ) (h : a ≤ b + D) : + a + s + t + e + 3 ≤ b + s + t + e + 3 + D := by omega + apply vectorMapWithWork_extra + · intro i + simp only [bandEnvelopeReadWithWork_eq] + · intro i + have h := bandEnvelopeReadWithWork_cost b band read i R (fun _ _ => hr i _) + dsimp only + simp only [bandEnvelopeReadWithWork_eq] + exact add_cost _ _ _ _ _ _ h + + + +theorem unskippedGuardReadWithWork_eq_cost {nx ny M : ℕ} (parent : TargetInterval nx) + (center : TargetInterval ny) (b exponent : ℕ) (F : BinaryFraction) + (band wide : List (Fin M → TargetInterval ny)) (hne : band ≠ []) + (read : Fin M → TargetInterval ny → BinaryFraction × ℕ) (R : ℕ) + (hr : ∀ i q, (read i q).2 ≤ R) : + (unskippedGuardReadWithWork parent center b exponent F band wide hne read).1 = + (unskippedGuardWithWork parent center b exponent F band wide hne (fun i q => (read i q).1)).1 ∧ + (unskippedGuardReadWithWork parent center b exponent F band wide hne read).2 ≤ + (unskippedGuardWithWork parent center b exponent F band wide hne (fun i q => (read i q).1)).2 + + M * (band.length * (R + 3)) + M * (band.length * (R + 3)) := by + have he := envelopeVectorReadWithWork_eq_cost b band read R hr + have hrnd := roundedBandReadWithWork_eq_cost exponent b band hne read R hr + unfold unskippedGuardReadWithWork unskippedGuardWithWork + dsimp only + rw [he.1, hrnd.1] + exact ⟨rfl, by omega⟩ + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryRoundedWork.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryRoundedWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..bf6b80e950788fac9f8098e6d43f4987dff9ee3b --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryRoundedWork.lean @@ -0,0 +1,137 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryRoundedKernel + +namespace OAI + +/-! Boolean work for the actual canonical rounding and wide-membership +tests. Interval endpoints retain their original target bound after rounding. -/ + +namespace EditApproximation + +theorem actionEqualWithWork_cost {n M : ℕ} (a b : Fin M → TargetInterval n) (B : ℕ) + (hn : Nat.size n ≤ B) : + (actionEqualWithWork a b).2 ≤ M * (16 * B + 8) := by + have hpoint (i : Fin M) : + (naturalEqualWithWork (a i).lo (b i).lo).2 + + (naturalEqualWithWork (a i).hi (b i).hi).2 + 1 ≤ 16 * B + 5 := by + have hlow := naturalEqualWithWork_cost (a i).lo (b i).lo B + ((Nat.size_le_size ((a i).ordered.trans (a i).valid)).trans hn) + ((Nat.size_le_size ((b i).ordered.trans (b i).valid)).trans hn) + have hhigh := naturalEqualWithWork_cost (a i).hi (b i).hi B + ((Nat.size_le_size (a i).valid).trans hn) ((Nat.size_le_size (b i).valid).trans hn) + omega + have h := allWithWork_cost (fun i => + let left := naturalEqualWithWork (a i).lo (b i).lo + let right := naturalEqualWithWork (a i).hi (b i).hi + (left.1 && right.1, left.2 + right.2 + 1)) (List.finRange M) (16 * B + 5) + (fun i _ => hpoint i) + simpa only [actionEqualWithWork, List.length_finRange] using h + +theorem actionMemberWithWork_cost {n M : ℕ} (a : Fin M → TargetInterval n) + (actions : List (Fin M → TargetInterval n)) (B : ℕ) (hn : Nat.size n ≤ B) : + (actionMemberWithWork a actions).2 ≤ 1 + actions.length * (M * (16 * B + 8) + 1) := by + induction actions with + | nil => simp only [actionMemberWithWork, List.length_nil, Nat.zero_mul, Nat.add_zero, le_refl] + | cons head rest ih => + have h := actionEqualWithWork_cost a head B hn + change (actionEqualWithWork a head).2 + (actionMemberWithWork a rest).2 + 1 ≤ _ + simp only [List.length_cons, Nat.add_mul, Nat.one_mul] + omega + +theorem roundStateWithWork_cost {n : ℕ} (spacing : ℕ) (hspacing : 0 < spacing) + (q : TargetInterval n) (B : ℕ) (hs : Nat.size spacing ≤ B) (hn : Nat.size n ≤ B) : + (roundStateWithWork spacing hspacing q).2 ≤ 500 * (B + 1) ^ 2 + 1 := by + have h := binaryIntervalRoundWithWork_cost spacing q.lo q.hi B hs + ((Nat.size_le_size (q.ordered.trans q.valid)).trans hn) + ((Nat.size_le_size q.valid).trans hn) + change (binaryIntervalRoundWithWork spacing q.lo q.hi).2 + 1 ≤ _ + omega + +namespace BinaryFraction + +def roundedSpacingWordBudget (B : ℕ) : ℕ := 4 * B + 4 + +def roundedSpacingBitBudget (B : ℕ) : ℕ := + 2000 * (B + 1) ^ 2 + 1500 * (4 * B + 3) ^ 2 + 3 + +theorem roundedSpacingWithWork_bounds (theta envelope : BinaryFraction) (B : ℕ) + (ht : theta.width ≤ B) (he : envelope.width ≤ B) : + (roundedSpacingWithWork theta envelope).1.length ≤ roundedSpacingWordBudget B ∧ + (roundedSpacingWithWork theta envelope).2 ≤ roundedSpacingBitBudget B := by + have hp := canonicalMulWithWork_width theta envelope B ht he + have hpc := canonicalMulWithWork_cost theta envelope B ht he + have hm := (maxWithWork_width one (canonicalMulWithWork theta envelope).1).trans + (show max one.width (canonicalMulWithWork theta envelope).1.width ≤ 4 * B + 2 by + change max 1 _ ≤ _ + omega) + have hmc := maxWithWork_cost one (canonicalMulWithWork theta envelope).1 (4 * B + 2) + (by change 1 ≤ _; omega) hp + have hc := naturalCeilingWithWork_length (maxWithWork one (canonicalMulWithWork theta envelope).1).1 + have hcc := naturalCeilingWithWork_cost (maxWithWork one (canonicalMulWithWork theta envelope).1).1 + have hsquare := Nat.pow_le_pow_left (show + (maxWithWork one (canonicalMulWithWork theta envelope).1).1.width + 1 ≤ 4 * B + 3 by omega) 2 + constructor + · change (naturalCeilingWithWork (maxWithWork one (canonicalMulWithWork theta envelope).1).1).1.length ≤ _ + unfold roundedSpacingWordBudget + omega + · change (canonicalMulWithWork theta envelope).2 + + (maxWithWork one (canonicalMulWithWork theta envelope).1).2 + + (naturalCeilingWithWork (maxWithWork one (canonicalMulWithWork theta envelope).1).1).2 + 2 ≤ _ + unfold roundedSpacingBitBudget + nlinarith only [hpc, hmc, hcc, hsquare] + +def roundedBandInputBudget (thetaExponent b M B : ℕ) : ℕ := + thetaExponent + 2 + 3 * bandEnvelopeWordBudget b M B + B + +def roundedBandBitBudget (thetaExponent b M size B : ℕ) : ℕ := + let W := roundedBandInputBudget thetaExponent b M B + M * (bandEnvelopeBitBudget b M size B + roundedSpacingBitBudget W + + 500 * (roundedSpacingWordBudget W + B + 1) ^ 2 + thetaExponent + 11) + +theorem roundedBandWithWork_cost {ny M : ℕ} (thetaExponent b : ℕ) + (band : List (Fin M → TargetInterval ny)) (hne : band ≠ []) + (initial : Fin M → TargetInterval ny → BinaryFraction) (B : ℕ) + (hny : Nat.size ny ≤ B) + (hi : ∀ action ∈ band, ∀ i, (initial i (action i)).width ≤ B) : + (roundedBandWithWork thetaExponent b band hne initial).2 ≤ + roundedBandBitBudget thetaExponent b M band.length B := by + let W := roundedBandInputBudget thetaExponent b M B + have hW : B ≤ W := by dsimp only [W, roundedBandInputBudget]; omega + have ht : (inversePowerTwo thetaExponent).width ≤ W := by + rw [inversePowerTwo_width] + dsimp only [W, roundedBandInputBudget] + omega + have hcell (i : Fin M) : + (let envelope := bandEnvelopeWithWork b band initial i + let spacing := roundedSpacingWithWork (inversePowerTwo thetaExponent) envelope.1 + let rounded := roundStateWithWork (bitWordValue spacing.1) + (roundedSpacingWithWork_pos _ _) (band.head hne i) + (rounded.1, envelope.2 + spacing.2 + rounded.2 + thetaExponent + 3)).2 ≤ + bandEnvelopeBitBudget b M band.length B + roundedSpacingBitBudget W + + 500 * (roundedSpacingWordBudget W + B + 1) ^ 2 + thetaExponent + 5 := by + let envelope := bandEnvelopeWithWork b band initial i + let spacing := roundedSpacingWithWork (inversePowerTwo thetaExponent) envelope.1 + have hew := bandEnvelopeWithWork_width b band initial i B (fun a ha => hi a ha i) + have hec := bandEnvelopeWithWork_cost b band initial i B (fun a ha => hi a ha i) + have heW : envelope.1.width ≤ W := hew.trans (by + dsimp only [W, roundedBandInputBudget]; omega) + have hs := roundedSpacingWithWork_bounds (inversePowerTwo thetaExponent) envelope.1 W ht heW + have hss : Nat.size (bitWordValue spacing.1) ≤ roundedSpacingWordBudget W := + (Nat.size_le.mpr (bitWordValue_lt_pow_length spacing.1)).trans hs.1 + have hr := roundStateWithWork_cost (bitWordValue spacing.1) + (roundedSpacingWithWork_pos _ _) (band.head hne i) (roundedSpacingWordBudget W + B) + (by omega) (hny.trans (by omega)) + change envelope.2 + spacing.2 + (roundStateWithWork (bitWordValue spacing.1) + (roundedSpacingWithWork_pos (inversePowerTwo thetaExponent) envelope.1) + (band.head hne i)).2 + thetaExponent + 3 ≤ _ + change envelope.2 ≤ _ at hec + have hsc : spacing.2 ≤ roundedSpacingBitBudget W := hs.2 + omega + have hmap := vectorMapWithWork_cost_le M _ _ hcell + change (vectorMapWithWork M _).2 ≤ _ + unfold roundedBandBitBudget + simpa only [Nat.add_assoc, Nat.reduceAdd] using hmap + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryRoundingSpace.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryRoundingSpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..94e5445e553177036c72b89924c00d6b13130e77 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryRoundingSpace.lean @@ -0,0 +1,89 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryGuardSpace +import OAI.Combinatorics.EditApproximation.Binary.BinaryEnvelopeSpace +import OAI.Combinatorics.EditApproximation.Binary.BinaryRoundedReads +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation + + + +theorem binaryGridRoundAllocation_le_work (spacing position : ℕ) : + binaryGridRoundAllocation spacing position ≤ (binaryGridRoundWithWork spacing position).2 := by + have hd := binaryNaturalDivAllocation_le_work position spacing + have hm := bitMulAllocation_le_work spacing.bits (binaryNaturalDivModWithWork position spacing).1 + unfold binaryGridRoundAllocation binaryGridRoundWithWork + dsimp only + omega + + + +theorem roundStateAllocation_le_work {n : ℕ} (spacing : ℕ) (hspacing : 0 < spacing) (q : TargetInterval n) : + roundStateAllocation spacing q ≤ (roundStateWithWork spacing hspacing q).2 := by + have hl := binaryGridRoundAllocation_le_work spacing q.lo + have hr := binaryGridRoundAllocation_le_work spacing q.hi + unfold roundStateAllocation roundStateWithWork binaryIntervalRoundWithWork + dsimp only + omega + + + +theorem actionEqualAllocation_le_work {n M : ℕ} (a b : Fin M → TargetInterval n) : + actionEqualAllocation a b ≤ (actionEqualWithWork a b).2 := by + apply allAllocation_le_work + intro i _ + have hl := naturalEqualAllocation_le_work (a i).lo (b i).lo + have hr := naturalEqualAllocation_le_work (a i).hi (b i).hi + dsimp only + omega + + + +theorem actionMemberAllocation_le_work {n M : ℕ} (a : Fin M → TargetInterval n) + (actions : List (Fin M → TargetInterval n)) : + actionMemberAllocation a actions ≤ (actionMemberWithWork a actions).2 := by + induction actions with + | nil => exact Nat.zero_le _ + | cons b rest ih => + have hh := actionEqualAllocation_le_work a b + unfold actionMemberAllocation actionMemberWithWork + dsimp only + exact (Nat.add_le_add hh ih).trans (Nat.le_succ _) + +namespace BinaryFraction + + + +theorem roundedSpacingAllocation_le_work (theta envelope : BinaryFraction) : + roundedSpacingAllocation theta envelope ≤ (roundedSpacingWithWork theta envelope).2 := by + have hp := canonicalMulAllocation_le_work theta envelope + have hm := maxAllocation_le_work one (canonicalMulWithWork theta envelope).1 + have hc := naturalCeilingAllocation_le_work (maxWithWork one (canonicalMulWithWork theta envelope).1).1 + unfold roundedSpacingAllocation roundedSpacingWithWork + dsimp only + omega + + + +theorem roundedBandReadAllocation_le_work {n M : ℕ} (exponent b : ℕ) (band : List (Fin M → TargetInterval n)) + (hne : band ≠ []) (read : Fin M → TargetInterval n → BinaryFraction × ℕ) + (allocation : Fin M → TargetInterval n → ℕ) + (h : ∀ i q, allocation i q ≤ (read i q).2) : + roundedBandReadAllocation exponent b band hne read allocation ≤ + (roundedBandReadWithWork exponent b band hne read).2 := by + apply vectorMapAllocation_le_work + intro i + have he := bandEnvelopeReadAllocation_le_work b band read allocation i (fun action _ => h i (action i)) + have hs := roundedSpacingAllocation_le_work (inversePowerTwo exponent) (bandEnvelopeReadWithWork b band read i).1 + have hr := roundStateAllocation_le_work + (bitWordValue (roundedSpacingWithWork (inversePowerTwo exponent) (bandEnvelopeReadWithWork b band read i).1).1) + (roundedSpacingWithWork_pos _ _) (band.head hne i) + dsimp only + omega + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinarySampledGroupPolynomial.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinarySampledGroupPolynomial.lean new file mode 100644 index 0000000000000000000000000000000000000000..9d9652efaf155927b744578495f9e4432e4fca8a --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinarySampledGroupPolynomial.lean @@ -0,0 +1,89 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinarySampledGroupWork +import OAI.Combinatorics.EditApproximation.Probability.FiniteBitPolynomial + +namespace OAI + +/-! A fixed polynomial bounds the actual sampled-member bit counter. The +scale is supplied through its bit length, so a large distance scale does +not introduce a spurious linear dependence on that scale. -/ + +namespace EditApproximation + +private abbrev GP := FiniteBitPolynomial (Fin 6) +private def gbits (x : GP) : GP := .bitLength x +private def gSumWord (n B : GP) : GP := + (B + 1) + gbits n + 2 * (B + 2) + 2 * (1 + n * ((B + 1) + (B + 1))) + 1 +private def gSumWork (n B : GP) : GP := 1 + n * (100000 * (gSumWord n B + 1) ^ 2) +private def gSumStorage (n B : GP) : GP := gbits n + B + 2 * (1 + n * (B + 1)) + 2 +private def gConnectionWord (M B : GP) : GP := gSumStorage (M + 1) (8 * B + 6) +private def gConnectionWork (M B : GP) : GP := + (M + 1) * (6000 * (B + 1) ^ 2 + 4) + M * (2 * B + 6) + + gSumWork (M + 1) (8 * B + 6) + 6 * (M + 1) + 1 +private def gEnvelopeWord (M bb B : GP) : GP := B + bb + gbits M + 8 +private def gEnvelopeWork (M bb v B : GP) : GP := + let W := gEnvelopeWord M bb B + 2100 * (bb + gbits M + 6) ^ 2 + (1 + v * (1000 * (W + 1) ^ 2 + 2)) + + (1000 * (W + 1) ^ 2 + 1) + + (1 + 2 * W * (1000 * (3 * W + 2) ^ 2 + 2) + 3 * W + 5) + v + 4 +private def gRoundWork (M e bb v B : GP) : GP := + let W := e + 2 + 3 * gEnvelopeWord M bb B + B + M * (gEnvelopeWork M bb v B + (2000 * (W + 1) ^ 2 + 1500 * (4 * W + 3) ^ 2 + 3) + + 500 * (4 * W + 4 + B + 1) ^ 2 + e + 11) +private def gSampleCountWork (B : GP) : GP := + 2000 * (B + 1) ^ 2 + 2000 * (4 * B + 3) ^ 2 + 2100 * (16 * B + 12) ^ 2 + + 500 * (64 * B + 45) ^ 2 + 4 * (65 * B + 46) + 3 * B + 8 +private def gIndexWork (M B : GP) : GP := + M * (2 * (1000 * (B + 1) ^ 2 + 1) + 6) + gSumWork M B + 6 * M + 1 +private def gScaleWord (M B : GP) : GP := 4 * (4 * B + 4 + gSumStorage M B) + 2 +private def gScaleWork (M B : GP) : GP := + gIndexWork M B + (2100 * (B + 2) ^ 2 + 1) + + 2000 * (4 * B + 4 + gSumStorage M B + 1) ^ 2 + 2 * B + 3 +private def gMemberWord (T B W : GP) : GP := 8 * (B + gSumStorage T W) + 6 +private def gMemberWork (T B C W : GP) : GP := + T * (C + 3) + gSumWork T W + 6 * T + 6000 * (B + gSumStorage T W + 1) ^ 2 + 1 +private def gCountedWork (M T B : GP) : GP := + T * (gSampleCountWork B + 6) + gMemberWork T B (gScaleWork M B) (gScaleWord M B) + 1 +private def gInput (M bb B : GP) : GP := + B + (3 * gEnvelopeWord M bb B + 1) + gConnectionWord M B + 1 + +private def sampledGroupPolynomial : GP := + let M := .input 0 + let T := .input 1 + let e := .input 2 + let bb := .input 3 + let v := .input 4 + let B := .input 5 + gMemberWord T (gInput M bb B) (gScaleWord M (gInput M bb B)) + + (M * (gEnvelopeWork M bb v B + 6) + gRoundWork M e bb v B + 7 * M + + (gConnectionWork M B + 2 * B + M + 2) + gCountedWork M T (gInput M bb B) + 5) + +def sampledGroupBitDegree : ℕ := sampledGroupPolynomial.degree + +private def sampledGroupEnvironment (M T exponent b vertices B : ℕ) : Fin 6 → ℕ + | 0 => M + | 1 => T + | 2 => exponent + | 3 => Nat.size b + | 4 => vertices + | _ => B + +private theorem sampledGroupPolynomial_eval (M T exponent b vertices B : ℕ) : + sampledGroupPolynomial.eval (sampledGroupEnvironment M T exponent b vertices B) = + BinaryFraction.sampledMemberWordBudget M T b B + + BinaryFraction.sampledMemberBitBudget M T exponent b vertices B := rfl + +theorem sampledMemberBitBudget_fixedPower (M T exponent b vertices B S : ℕ) + (hS : 2 ≤ S) (hM : M ≤ S) (hT : T ≤ S) (he : exponent ≤ S) + (hb : Nat.size b ≤ S) (hv : vertices ≤ S) (hB : B ≤ S) : + BinaryFraction.sampledMemberWordBudget M T b B ≤ S ^ sampledGroupBitDegree ∧ + BinaryFraction.sampledMemberBitBudget M T exponent b vertices B ≤ S ^ sampledGroupBitDegree := by + have henv : ∀ i, sampledGroupEnvironment M T exponent b vertices B i ≤ S := by + intro i + fin_cases i <;> simp only [sampledGroupEnvironment] <;> assumption + have h := sampledGroupPolynomial.eval_le_pow (sampledGroupEnvironment M T exponent b vertices B) S hS henv + rw [sampledGroupPolynomial_eval] at h + exact ⟨(Nat.le_add_right _ _).trans h, (Nat.le_add_left _ _).trans h⟩ + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinarySampledGroupWork.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinarySampledGroupWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..ce503f7f1414133a95177a7532fe249c8f4a6b29 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinarySampledGroupWork.lean @@ -0,0 +1,98 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinarySampledGroups +import OAI.Combinatorics.EditApproximation.Binary.BinaryRoundedWork + +namespace OAI + +/-! Full bit cost of the sampled member continuation. All its internal +counting, envelope, rounding and summation callbacks are discharged here. -/ + +namespace EditApproximation +namespace BinaryFraction + +def sampledMemberInputBudget (M b B : ℕ) : ℕ := + B + (3 * bandEnvelopeWordBudget b M B + 1) + connectionWordBudget M B + 1 + +def sampledMemberWordBudget (M T b B : ℕ) : ℕ := + let S := sampledMemberInputBudget M b B + groupMemberWordBudget T S (boundedScaleWordBudget M S) + +def sampledMemberBitBudget (M T exponent b vertices B : ℕ) : ℕ := + M * (bandEnvelopeBitBudget b M vertices B + 6) + + roundedBandBitBudget exponent b M vertices B + 7 * M + + (connectionBitBudget M B + 2 * B + M + 2) + + countedGroupBitBudget M T (sampledMemberInputBudget M b B) + 5 + +theorem unskippedEstimateWithWork_bounds {α : Type*} (source target : List α) {M T : ℕ} + (parent : TargetInterval source.length) (b P exponent Q : ℕ) (tau F : BinaryFraction) + (child initial current : Fin M → TargetInterval target.length → BinaryFraction) + (scales : Fin T → BinaryFraction) + (draw : ∀ t, Fin (groupSampleCount M Q b (scales t).value) → Fin M) + (member : UnskippedBand source target parent b P exponent tau.value F.value + (fun i q => (child i q).value) (fun i q => (initial i q).value)) + (B : ℕ) (hM : Nat.size M + 2 ≤ B) (hQ : Nat.size Q + 2 ≤ B) + (hb : Nat.size b + 2 ≤ B) (hny : Nat.size target.length + 2 ≤ B) + (hs : ∀ t, (scales t).width ≤ B) + (hi : ∀ action ∈ member.actions, ∀ i, (initial i (action i)).width ≤ B) + (hv : ∀ i q, (current i q).width ≤ B) : + (unskippedEstimateWithWork source target parent b P exponent Q tau F child initial current + scales draw member).1.width ≤ sampledMemberWordBudget M T b B ∧ + (unskippedEstimateWithWork source target parent b P exponent Q tau F child initial current + scales draw member).2 ≤ sampledMemberBitBudget M T exponent b member.actions.length B := by + let mass := envelopeVectorWithWork b member.actions initial + let rounded := roundedBandWithWork exponent b member.actions member.nonempty initial + let values := vectorMapWithWork M fun i => (current i (rounded.1.get i), 1) + let connection := endpointConnectionWithWork member.center rounded.1.get + let S := sampledMemberInputBudget M b B + have hBS : B ≤ S := by dsimp only [S, sampledMemberInputBudget]; omega + have hmass (i : Fin M) : (mass.1.get i).width ≤ 3 * bandEnvelopeWordBudget b M B + 1 := by + simp only [mass, envelopeVectorWithWork, vectorMapWithWork_value] + exact bandEnvelopeWithWork_width b member.actions initial i B (fun a ha => hi a ha i) + have hmassc := vectorMapWithWork_cost_le M (bandEnvelopeWithWork b member.actions initial) + (bandEnvelopeBitBudget b M member.actions.length B) (fun i => + bandEnvelopeWithWork_cost b member.actions initial i B (fun a ha => hi a ha i)) + change mass.2 ≤ _ at hmassc + have hroundc := roundedBandWithWork_cost exponent b member.actions member.nonempty initial B + (by omega) hi + change rounded.2 ≤ _ at hroundc + have hvalue (i : Fin M) : (values.1.get i).width ≤ B := by + simp only [values, vectorMapWithWork_value] + exact hv i _ + have hvaluec := vectorMapWithWork_cost_le M (fun i => (current i (rounded.1.get i), 1)) 1 + (fun _ => le_rfl) + change values.2 ≤ _ at hvaluec + have hcenterlo : Nat.size member.center.lo + 2 ≤ B := + (Nat.add_le_add_right (Nat.size_le_size (member.center.ordered.trans member.center.valid)) 2).trans hny + have hcenterhi : Nat.size member.center.hi + 2 ≤ B := + (Nat.add_le_add_right (Nat.size_le_size member.center.valid) 2).trans hny + have hstates : ∀ s ∈ List.ofFn rounded.1.get, + Nat.size s.lo + 2 ≤ B ∧ Nat.size s.hi + 2 ≤ B := by + intro s _ + exact ⟨(Nat.add_le_add_right (Nat.size_le_size (s.ordered.trans s.valid)) 2).trans hny, + (Nat.add_le_add_right (Nat.size_le_size s.valid) 2).trans hny⟩ + have hcw := connectionWithWork_width (nat member.center.lo) (nat member.center.hi) + (List.ofFn rounded.1.get) B ((nat_width_le _).trans hcenterlo) + ((nat_width_le _).trans hcenterhi) hstates + have hcc := connectionWithWork_cost (nat member.center.lo) (nat member.center.hi) + (List.ofFn rounded.1.get) B ((nat_width_le _).trans hcenterlo) + ((nat_width_le _).trans hcenterhi) hstates + simp only [List.length_ofFn] at hcw hcc + have hconnw : connection.1.width ≤ connectionWordBudget M B := hcw + have hconnc : connection.2 ≤ connectionBitBudget M B + 2 * B + M + 2 := by + change _ + Nat.size member.center.lo + Nat.size member.center.hi + M + 2 ≤ _ + omega + have hmember := countedGroupMemberWithWork_bounds Q b scales connection.1 mass.1 values.1 draw S + (by omega) (hM.trans hBS) (hQ.trans hBS) (hb.trans hBS) (fun t => (hs t).trans hBS) + (hconnw.trans (by dsimp only [S, sampledMemberInputBudget]; omega)) + (fun i => (hmass i).trans (by dsimp only [S, sampledMemberInputBudget]; omega)) + (fun i => (hvalue i).trans hBS) + refine ⟨hmember.1, ?_⟩ + change mass.2 + rounded.2 + values.2 + connection.2 + + (countedGroupMemberWithWork Q b scales connection.1 mass.1 values.1 draw).2 + 5 ≤ _ + unfold sampledMemberBitBudget + dsimp only [S] at hmember + omega + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinarySampledGroups.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinarySampledGroups.lean new file mode 100644 index 0000000000000000000000000000000000000000..1b34410601276f69b575e048749f5539aa724759 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinarySampledGroups.lean @@ -0,0 +1,95 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryCountedGroupWork +import OAI.Combinatorics.EditApproximation.Binary.BinaryPhysicalContinuation +import OAI.Combinatorics.EditApproximation.Geometry.CellGroupSelection + +namespace OAI + +/-! The sampled group continuation uses the executed envelopes, rounded +states, exact finite sample counts, and ordered minimizing scan. Its output +is the same physical action as the group program used by the accuracy proof. -/ + +namespace EditApproximation +namespace BinaryFraction + +section Group +variable {α : Type*} (source target : List α) {M T : ℕ} + (parent : TargetInterval source.length) (b P exponent Q : ℕ) (hb : 0 < b) + (tau F : BinaryFraction) + (child initial current : Fin M → TargetInterval target.length → BinaryFraction) + (scales : Fin T → BinaryFraction) + (draw : ∀ t, Fin (groupSampleCount M Q b (scales t).value) → Fin M) + +local notation "Member" => UnskippedBand source target parent b P exponent + (BinaryFraction.value tau) (BinaryFraction.value F) + (fun i q => BinaryFraction.value (child i q)) (fun i q => BinaryFraction.value (initial i q)) + +def unskippedEstimateWithWork (member : Member) : BinaryFraction × ℕ := + let mass := envelopeVectorWithWork b member.actions initial + let rounded := roundedBandWithWork exponent b member.actions member.nonempty initial + let values := vectorMapWithWork M fun i => (current i (rounded.1.get i), 1) + let connection := endpointConnectionWithWork member.center rounded.1.get + let result := countedGroupMemberWithWork Q b scales connection.1 mass.1 values.1 draw + (result.1, mass.2 + rounded.2 + values.2 + connection.2 + result.2 + 5) + +include hb in +theorem unskippedEstimateWithWork_value (member : Member) : + (unskippedEstimateWithWork source target parent b P exponent Q tau F child initial current scales draw member).1.value = + unskippedGroupEstimate (fun t => (scales t).value) + (fun t => groupSampleCount M Q b (scales t).value) + (fun i q => (current i q).value) member draw := by + have hround : (roundedBandWithWork exponent b member.actions member.nonempty initial).1.get = + member.rounded := roundedBandWithWork_value exponent b member.actions member.nonempty initial hb + have hmass (i : Fin M) : ((envelopeVectorWithWork b member.actions initial).1.get i).value = + member.envelope i := envelopeVectorWithWork_value b member.actions initial hb i + simp only [unskippedEstimateWithWork, countedGroupMemberWithWork_value, + endpointConnectionWithWork_value, vectorMapWithWork_value, hround, hmass, unskippedGroupEstimate] + +def chooseBinaryUnskippedWithWork (members : List Member) (hne : members ≠ []) : Member × ℕ := + selectGroupWithWork members hne + (unskippedEstimateWithWork source target parent b P exponent Q tau F child initial current scales draw) + +include hb in +theorem chooseBinaryUnskippedWithWork_value (members : List Member) (hne : members ≠ []) : + (chooseBinaryUnskippedWithWork source target parent b P exponent Q tau F child initial current + scales draw members hne).1 = selectGroupMember members hne (fun member => + unskippedGroupEstimate (fun t => (scales t).value) + (fun t => groupSampleCount M Q b (scales t).value) + (fun i q => (current i q).value) member draw) := by + simp only [chooseBinaryUnskippedWithWork, selectGroupWithWork_value, + unskippedEstimateWithWork_value source target parent b P exponent Q hb tau F child initial current scales draw] + +def sampledGroupActionWithWork (members : List Member) (hne : members ≠ []) : + BinaryBellmanAction (TargetInterval target.length) (Fin M × TargetInterval target.length) M × ℕ := + let selected := chooseBinaryUnskippedWithWork source target parent b P exponent Q tau F + child initial current scales draw members hne + let rounded := roundedBandWithWork exponent b selected.1.actions selected.1.nonempty initial + let result := endpointActionWithWork selected.1.center rounded.1.get + (result.1, selected.2 + rounded.2 + result.2 + 3) + +include hb in +theorem sampledGroupActionWithWork_value (members : List Member) (hne : members ≠ []) : + (sampledGroupActionWithWork source target parent b P exponent Q tau F child initial current + scales draw members hne).1.decode = + (selectGroupMember members hne (fun member => + unskippedGroupEstimate (fun t => (scales t).value) + (fun t => groupSampleCount M Q b (scales t).value) + (fun i q => (current i q).value) member draw)).rationalAction := by + let selected : Member := (chooseBinaryUnskippedWithWork source target parent b P exponent Q + tau F child initial current scales draw members hne).1 + have hround := roundedBandWithWork_value exponent b selected.actions selected.nonempty initial hb + have haction : (endpointActionWithWork selected.center + (roundedBandWithWork exponent b selected.actions selected.nonempty initial).1.get).1.decode = + selected.rationalAction := by + exact (endpointActionWithWork_decode _ _).trans (congrArg + (fun states : Fin M → TargetInterval target.length => + (⟨selected.center, endpointActionConnection selected.center states, fun i => (i, states i)⟩ : + PhysicalRationalAction M target.length)) hround) + exact haction.trans (congrArg UnskippedBand.rationalAction + (chooseBinaryUnskippedWithWork_value source target parent b P exponent Q hb tau F + child initial current scales draw members hne)) + +end Group +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinarySampledOnline.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinarySampledOnline.lean new file mode 100644 index 0000000000000000000000000000000000000000..6c7930fb1ae28000988456517f7096b93130bd87 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinarySampledOnline.lean @@ -0,0 +1,46 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryTriangularChoice +import OAI.Combinatorics.EditApproximation.Binary.BinaryBandAction +import OAI.Combinatorics.EditApproximation.Binary.BinaryPhysicalContinuation + +namespace OAI + +/-! A finite uniform source integer is passed through the actual triangular +search and the actual stored-fraction optimizer. The returned zero-connection +physical action has exactly the online sampler's value, including ties. -/ + +namespace EditApproximation +namespace BinaryFraction + +def sampledOnlineActionWithWork {ny M : ℕ} (center : TargetInterval ny) (b : ℕ) + (initial : Fin M → TargetInterval ny → BinaryFraction) + (table : ℕ → Fin M × TargetInterval ny → BinaryFraction) (eta kappa : BinaryFraction) + (band : List (Fin M → TargetInterval ny)) (hne : band ≠ []) + (G K t : ℕ) (integer : Fin (optimizerTriangularMass K)) : + BinaryBellmanAction (TargetInterval ny) (Fin M × TargetInterval ny) M × ℕ := + let chosen := triangularChoiceWithWork K integer + let selected := bandActionWithWork b initial table eta kappa band G chosen.1.val t + let states := selected.1.getD (band.head hne) + (⟨center, zero, fun i => (i, states i)⟩, chosen.2 + selected.2 + M + 2) + +theorem sampledOnlineActionWithWork_value {ny M : ℕ} (center : TargetInterval ny) (b : ℕ) + (initial : Fin M → TargetInterval ny → BinaryFraction) + (table : ℕ → Fin M × TargetInterval ny → BinaryFraction) (eta kappa : BinaryFraction) + (band : List (Fin M → TargetInterval ny)) (hne : band ≠ []) + (G K t : ℕ) (integer : Fin (optimizerTriangularMass K)) (hb : 0 < b) : + (sampledOnlineActionWithWork center b initial table eta kappa band hne G K t integer).1.decode = + sharedBandRationalAction center + (finiteOptimizerActionDraw band hne (bandChildEnvelope b band (fun i q => (initial i q).value)) + (rationalOnlineLinear eta.value kappa.value + (childGain (bandChildEnvelope b band (fun i q => (initial i q).value)) + (fun s i => (table s i).value)) + (childDecrement (bandChildEnvelope b band (fun i q => (initial i q).value)) + (fun s i => (table s i).value)) t) G K integer) := by + simp only [sampledOnlineActionWithWork, BinaryBellmanAction.decode, + bandActionWithWork_value _ _ _ _ _ _ hne _ _ _ hb, triangularChoiceWithWork_value, + finiteOptimizerActionDraw, sharedBandRationalAction] + rw [← representation_value zero, zero_representation, UnreducedRational.value_zero] + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinarySampledOnlinePolynomial.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinarySampledOnlinePolynomial.lean new file mode 100644 index 0000000000000000000000000000000000000000..987108a9eb6f4437965faf14d5ddd6e9ff109b8a --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinarySampledOnlinePolynomial.lean @@ -0,0 +1,84 @@ +import OAI.Combinatorics.EditApproximation.Geometry.BandActionPolynomial +import OAI.Combinatorics.EditApproximation.Binary.BinarySampledOnlineWork +import OAI.Combinatorics.EditApproximation.Binary.BinaryCoordinateActionWork + +namespace OAI + +/-! The complete sampled online action, including the triangular search, +coordinate equality tests, final logarithm-gradient and labeled argmax. -/ + +namespace EditApproximation + +private abbrev SP := FiniteBitPolynomial (Fin 5) +private def sampledOnlineOverhead : SP := + let M := .input 0 + let v := .input 1 + let d := .input 2 + let K := .input 3 + let B := .input 4 + (K + 1) * (10000 * (B + 3) ^ 2 + 30 * (B + 3)) + M + 2 + + (v * (5 * M + 3) + (v * M + 1) ^ 2 * (24 * B + 12) + 1) + d + + v * d * (24 * B + 9) + 2 + +private def sampledOnlineOverheadEnv (M v d K B : ℕ) : Fin 5 → ℕ + | 0 => M + | 1 => v + | 2 => d + | 3 => K + | _ => B + +private theorem sampledOnlineOverhead_eval (M v d K B : ℕ) : + sampledOnlineOverhead.eval (sampledOnlineOverheadEnv M v d K B) = + triangularChoiceBitBudget K B + M + 2 + BinaryFraction.bandCoordinatesBitBudget M v B + d + + v * d * (24 * B + 9) + 2 := rfl + +def sampledOnlineBitDegree : ℕ := max bandActionBitDegree sampledOnlineOverhead.degree + 1 + +theorem countedSampledOnlineWithWork_fixedPower {M n : ℕ} (center : TargetInterval n) (b : ℕ) + (initial : Fin M → TargetInterval n → BinaryFraction) + (table : ℕ → Fin M × TargetInterval n → BinaryFraction) (eta kappa : BinaryFraction) + (band : List (Fin M → TargetInterval n)) (hne : band ≠ []) + (G K t B E S : ℕ) (integer : Fin (optimizerTriangularMass K)) + (hS : 2 ≤ S) (hMpos : 0 < M) (hbpos : 0 < b) + (hM : M ≤ S) (hv : band.length ≤ S) (hd : (listedBandCoordinates band).length ≤ S) + (hG : G ≤ S) (hK : K ≤ S) (ht : t ≤ S) (hB : B ≤ S) (hE : E ≤ S) + (hb : Nat.size b ≤ S) (hMb : Nat.size M ≤ B) (hnb : Nat.size n ≤ B) + (hKb : Nat.size K ≤ B) (hinteger : Nat.size integer.val ≤ B) + (he : eta.width ≤ B) (hk : kappa.width ≤ B) + (hi : ∀ i q, (initial i q).width ≤ B) + (hh : ∀ s ≤ t + 1, ∀ i q, (table s (i, q)).width ≤ B) + (heabs : |eta.value| ≤ E) (hkrange : 0 ≤ kappa.value ∧ kappa.value ≤ 1) + (hhrange : ∀ s ≤ t + 1, ∀ i q, 0 ≤ (table s (i, q)).value ∧ + (table s (i, q)).value ≤ (initial i q).value) : + (BinaryFraction.countedSampledOnlineWithWork center b initial table eta kappa band hne G K t integer).2 ≤ + S ^ sampledOnlineBitDegree := by + let d := (listedBandCoordinates band).length + let j := (triangularChoice K integer).val + have hj : j ≤ S := (triangularChoice K integer).isLt.le.trans hK + have ha := bandActionBitBudget_fixedPower + M d b band.length G j t B B B B E S hS hM hd hb hv hG hj ht hB hB hB hB hE + have hs := BinaryFraction.sampledOnlineActionWithWork_cost center b initial table eta kappa band hne + G K t integer B B B B B E hbpos hMpos hKb hinteger he hk + (fun action _ i => hi i (action i)) + (fun s hs i => hh s hs _ _) heabs hkrange + (fun s hs i => hhrange s hs _ _) + have hc := BinaryFraction.countedSampledOnlineWithWork_cost center b initial table eta kappa + band hne G K t B integer hMb hnb + have henv : ∀ i, sampledOnlineOverheadEnv M band.length d K B i ≤ S := by + intro i + fin_cases i <;> simp only [sampledOnlineOverheadEnv] <;> assumption + have ho := sampledOnlineOverhead.eval_le_pow _ S hS henv + rw [sampledOnlineOverhead_eval] at ho + let D := max bandActionBitDegree sampledOnlineOverhead.degree + have h1 : S ^ bandActionBitDegree ≤ S ^ D := Nat.pow_le_pow_right (by omega) (Nat.le_max_left _ _) + have h2 : S ^ sampledOnlineOverhead.degree ≤ S ^ D := Nat.pow_le_pow_right (by omega) (Nat.le_max_right _ _) + change (BinaryFraction.countedSampledOnlineWithWork center b initial table eta kappa band hne G K t integer).2 ≤ + S ^ (D + 1) + calc + _ ≤ 2 * S ^ D := by dsimp only [d, j] at ha ho; omega + _ ≤ S * S ^ D := Nat.mul_le_mul_right _ hS + _ = _ := (pow_succ' S D).symm + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinarySampledOnlineSpace.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinarySampledOnlineSpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..a4594ba3d60a7234c440b7d2cc1e742ef35eec37 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinarySampledOnlineSpace.lean @@ -0,0 +1,34 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryCountedActionSpace +import OAI.Combinatorics.EditApproximation.Binary.BinaryTriangularSpace +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation.BinaryFraction + +/-- Concrete allocated cells of the sampled labeled online action, including +threshold search, envelopes, coordinate arrays and all optimizer arithmetic. -/ + + +theorem countedSampledOnlineAllocation_le_work {n M : ℕ} (center : TargetInterval n) (b : ℕ) + (initial : Fin M → TargetInterval n → BinaryFraction × ℕ) + (initialAllocation : Fin M → TargetInterval n → ℕ) + (read : ℕ → Fin M × TargetInterval n → BinaryFraction × ℕ) + (readAllocation : ℕ → Fin M × TargetInterval n → ℕ) + (eta kappa : BinaryFraction) (band : List (Fin M → TargetInterval n)) (hne : band ≠ []) + (G K t : ℕ) (integer : Fin (optimizerTriangularMass K)) + (hi : ∀ i state, initialAllocation i state ≤ (initial i state).2) + (hr : ∀ s coordinate, readAllocation s coordinate ≤ (read s coordinate).2) : + countedSampledOnlineAllocation center b initial initialAllocation read readAllocation eta kappa band hne + G K t integer ≤ 3 * (countedSampledOnlineReadWithWork center b initial read eta kappa band hne G K t integer).2 := by + have ht := triangularChoiceAllocation_le_work K integer + have ha := countedBandActionAllocation_le_work b initial initialAllocation read readAllocation + eta kappa band G (triangularChoiceWithWork K integer).1.val t hi hr + unfold countedSampledOnlineAllocation countedSampledOnlineReadWithWork + dsimp only + omega + +end EditApproximation.BinaryFraction + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinarySampledOnlineWork.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinarySampledOnlineWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..d9e264b97b480ce37ce8767c240e4db45296e509 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinarySampledOnlineWork.lean @@ -0,0 +1,43 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinarySampledOnline + +namespace OAI + +/-! Cost of the actual triangular choice followed by the complete stored +fraction online optimizer. This includes the envelope and vertex builders. -/ + +namespace EditApproximation +namespace BinaryFraction + +theorem sampledOnlineActionWithWork_cost {ny M : ℕ} (center : TargetInterval ny) (b : ℕ) + (initial : Fin M → TargetInterval ny → BinaryFraction) + (table : ℕ → Fin M × TargetInterval ny → BinaryFraction) (eta kappa : BinaryFraction) + (band : List (Fin M → TargetInterval ny)) (hne : band ≠ []) + (G K t : ℕ) (integer : Fin (optimizerTriangularMass K)) + (B Be Bk Bi Bt E : ℕ) (hb : 0 < b) (hM : 0 < M) + (hK : Nat.size K ≤ B) (hinteger : Nat.size integer.val ≤ B) + (he : eta.width ≤ Be) (hk : kappa.width ≤ Bk) + (hi : ∀ action ∈ band, ∀ j, (initial j (action j)).width ≤ Bi) + (ht : ∀ s ≤ t + 1, ∀ i : Fin (listedBandCoordinates band).length, + (table s ((listedBandCoordinateVector band).get i)).width ≤ Bt) + (heabs : |eta.value| ≤ E) (hkrange : 0 ≤ kappa.value ∧ kappa.value ≤ 1) + (htrange : ∀ s ≤ t + 1, ∀ i : Fin (listedBandCoordinates band).length, + 0 ≤ (table s ((listedBandCoordinateVector band).get i)).value ∧ + (table s ((listedBandCoordinateVector band).get i)).value ≤ + (initial ((listedBandCoordinateVector band).get i).1 + ((listedBandCoordinateVector band).get i).2).value) : + (sampledOnlineActionWithWork center b initial table eta kappa band hne G K t integer).2 ≤ + triangularChoiceBitBudget K B + + bandActionBitBudget M (listedBandCoordinates band).length b band.length G + (triangularChoice K integer).val t Be Bk Bi Bt E + M + 2 := by + have hchoice := triangularChoiceWithWork_cost K integer B hK hinteger + have hoptimizer := bandActionWithWork_cost b initial table eta kappa band G + (triangularChoice K integer).val t Be Bk Bi Bt E hne hb hM he hk hi ht heabs hkrange htrange + unfold sampledOnlineActionWithWork + dsimp only + rw [triangularChoiceWithWork_value] + omega + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinarySampledSourcePort.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinarySampledSourcePort.lean new file mode 100644 index 0000000000000000000000000000000000000000..307e47f97ca2e13b36cb43fdf6ee82d0f696925b --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinarySampledSourcePort.lean @@ -0,0 +1,152 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryGroupMemberSource +import OAI.Combinatorics.EditApproximation.Binary.BinaryGroupReadCosts + +namespace OAI + +/-! Table-reader and random-source costs are retained together through +member estimation, tie-broken selection, and rounded action return. -/ + +namespace EditApproximation.BinaryFraction + +section Group +variable {α : Type*} (source target : List α) {M T : ℕ} + (parent : TargetInterval source.length) (b P exponent Q : ℕ) + (tau F : BinaryFraction) + (child : Fin M → TargetInterval target.length → BinaryFraction) + (initial current : Fin M → TargetInterval target.length → BinaryFraction × ℕ) + (scales : Fin T → BinaryFraction) + (draw : ∀ t, Fin (groupSampleCount M Q b (scales t).value) → Fin M × ℕ) + +local notation "Member" => UnskippedBand source target parent b P exponent (value tau) (value F) + (fun i q => value (child i q)) (fun i q => value (Prod.fst (initial i q))) + +def unskippedEstimateSourceWithWork (member : Member) : BinaryFraction × ℕ := + let mass := envelopeVectorReadWithWork b member.actions initial + let rounded := roundedBandReadWithWork exponent b member.actions member.nonempty initial + let values := vectorMapWithWork M fun i => current i (rounded.1.get i) + let connection := endpointConnectionWithWork member.center rounded.1.get + let result := countedGroupMemberSourceWithWork Q b scales connection.1 mass.1 values.1 draw + (result.1, mass.2 + rounded.2 + values.2 + connection.2 + result.2 + 5) + +theorem unskippedEstimateSourceWithWork_eq_cost (member : Member) (R : ℕ) + (hr : ∀ s i, (draw s i).2 ≤ R) : + (unskippedEstimateSourceWithWork source target parent b P exponent Q tau F child initial current + scales draw member).1 = + (unskippedEstimateReadWithWork source target parent b P exponent Q tau F child initial current + scales (fun s i => (draw s i).1) member).1 ∧ + (unskippedEstimateSourceWithWork source target parent b P exponent Q tau F child initial current + scales draw member).2 ≤ + (unskippedEstimateReadWithWork source target parent b P exponent Q tau F child initial current + scales (fun s i => (draw s i).1) member).2 * (R + 4) := by + have h := countedGroupMemberSourceWithWork_eq_cost Q b scales + (endpointConnectionWithWork member.center + (roundedBandReadWithWork exponent b member.actions member.nonempty initial).1.get).1 + (envelopeVectorReadWithWork b member.actions initial).1 + (vectorMapWithWork M fun i => current i + ((roundedBandReadWithWork exponent b member.actions member.nonempty initial).1.get i)).1 draw R hr + unfold unskippedEstimateSourceWithWork unskippedEstimateReadWithWork + dsimp only + rw [h.1] + exact ⟨rfl, by nlinarith only [h.2]⟩ + +theorem unskippedEstimateSourceWithWork_value (member : Member) : + (unskippedEstimateSourceWithWork source target parent b P exponent Q tau F child initial current + scales draw member).1 = + (unskippedEstimateReadWithWork source target parent b P exponent Q tau F child initial current + scales (fun s i => (draw s i).1) member).1 := by + exact countedGroupMemberSourceWithWork_value Q b scales _ _ _ draw + +def chooseUnskippedSourceWithWork (members : List Member) (hne : members ≠ []) : Member × ℕ := + selectGroupWithWork members hne + (unskippedEstimateSourceWithWork source target parent b P exponent Q tau F child initial current scales draw) + +theorem chooseUnskippedSourceWithWork_eq_cost (members : List Member) (hne : members ≠ []) + (R : ℕ) (hr : ∀ s i, (draw s i).2 ≤ R) : + (chooseUnskippedSourceWithWork source target parent b P exponent Q tau F child initial current + scales draw members hne).1 = + (chooseUnskippedReadWithWork source target parent b P exponent Q tau F child initial current + scales (fun s i => (draw s i).1) members hne).1 ∧ + (chooseUnskippedSourceWithWork source target parent b P exponent Q tau F child initial current + scales draw members hne).2 ≤ + (chooseUnskippedReadWithWork source target parent b P exponent Q tau F child initial current + scales (fun s i => (draw s i).1) members hne).2 * (R + 4) := by + exact selectGroupWithWork_factor _ _ members hne (R + 4) (by omega) + (fun member _ => (unskippedEstimateSourceWithWork_eq_cost source target parent b P exponent Q + tau F child initial current scales draw member R hr).1) + (fun member _ => (unskippedEstimateSourceWithWork_eq_cost source target parent b P exponent Q + tau F child initial current scales draw member R hr).2) + +theorem chooseUnskippedSourceWithWork_value (members : List Member) (hne : members ≠ []) : + (chooseUnskippedSourceWithWork source target parent b P exponent Q tau F child initial current + scales draw members hne).1 = + (chooseUnskippedReadWithWork source target parent b P exponent Q tau F child initial current + scales (fun s i => (draw s i).1) members hne).1 := by + simp only [chooseUnskippedSourceWithWork, chooseUnskippedReadWithWork, selectGroupWithWork_value] + congr 1 + funext member + rw [unskippedEstimateSourceWithWork_value] + +def sampledGroupActionSourceWithWork (members : List Member) (hne : members ≠ []) : + BinaryBellmanAction (TargetInterval target.length) (Fin M × TargetInterval target.length) M × ℕ := + let selected := chooseUnskippedSourceWithWork source target parent b P exponent Q tau F + child initial current scales draw members hne + let rounded := roundedBandReadWithWork exponent b selected.1.actions selected.1.nonempty initial + let result := endpointActionWithWork selected.1.center rounded.1.get + (result.1, selected.2 + rounded.2 + result.2 + 3) + +theorem sampledGroupActionSourceWithWork_eq_cost (members : List Member) (hne : members ≠ []) + (R : ℕ) (hr : ∀ s i, (draw s i).2 ≤ R) : + (sampledGroupActionSourceWithWork source target parent b P exponent Q tau F child initial current + scales draw members hne).1 = + (sampledGroupActionReadWithWork source target parent b P exponent Q tau F child initial current + scales (fun s i => (draw s i).1) members hne).1 ∧ + (sampledGroupActionSourceWithWork source target parent b P exponent Q tau F child initial current + scales draw members hne).2 ≤ + (sampledGroupActionReadWithWork source target parent b P exponent Q tau F child initial current + scales (fun s i => (draw s i).1) members hne).2 * (R + 4) := by + have h := chooseUnskippedSourceWithWork_eq_cost source target parent b P exponent Q tau F + child initial current scales draw members hne R hr + let finish := fun selected : Member => + let rounded := roundedBandReadWithWork exponent b selected.actions selected.nonempty initial + let result := endpointActionWithWork selected.center rounded.1.get + (result.1, rounded.2 + result.2) + change (finish (chooseUnskippedSourceWithWork source target parent b P exponent Q tau F + child initial current scales draw members hne).1).1 = + (finish (chooseUnskippedReadWithWork source target parent b P exponent Q tau F + child initial current scales (fun s i => (draw s i).1) members hne).1).1 ∧ _ + have hf := congrArg finish h.1 + refine ⟨congrArg Prod.fst hf, ?_⟩ + have hcost : (chooseUnskippedSourceWithWork source target parent b P exponent Q tau F + child initial current scales draw members hne).2 + + (finish (chooseUnskippedSourceWithWork source target parent b P exponent Q tau F + child initial current scales draw members hne).1).2 + 3 ≤ + ((chooseUnskippedReadWithWork source target parent b P exponent Q tau F + child initial current scales (fun s i => (draw s i).1) members hne).2 + + (finish (chooseUnskippedReadWithWork source target parent b P exponent Q tau F + child initial current scales (fun s i => (draw s i).1) members hne).1).2 + 3) * (R + 4) := by + rw [hf] + nlinarith only [h.2] + simpa only [sampledGroupActionSourceWithWork, sampledGroupActionReadWithWork, finish, + Nat.add_assoc] using hcost + + +theorem sampledGroupActionSourceWithWork_value (members : List Member) (hne : members ≠ []) : + (sampledGroupActionSourceWithWork source target parent b P exponent Q tau F child initial current + scales draw members hne).1 = + (sampledGroupActionReadWithWork source target parent b P exponent Q tau F child initial current + scales (fun s i => (draw s i).1) members hne).1 := by + let finish := fun selected : Member => + let rounded := roundedBandReadWithWork exponent b selected.actions selected.nonempty initial + (endpointActionWithWork selected.center rounded.1.get).1 + change finish (chooseUnskippedSourceWithWork source target parent b P exponent Q tau F + child initial current scales draw members hne).1 = + finish (chooseUnskippedReadWithWork source target parent b P exponent Q tau F + child initial current scales (fun s i => (draw s i).1) members hne).1 + exact congrArg finish (chooseUnskippedSourceWithWork_value source target parent b P exponent Q + tau F child initial current scales draw members hne) + + +end Group +end EditApproximation.BinaryFraction + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryScaleGrid.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryScaleGrid.lean new file mode 100644 index 0000000000000000000000000000000000000000..8f749d203146dc421af2ceaf6e5be2ba6d2c5d74 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryScaleGrid.lean @@ -0,0 +1,144 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryLocalGrid +import OAI.Combinatorics.EditApproximation.Binary.BinaryInitialKernel +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Literal dyadic scales and the finite initial-cone center list, with +binary rational comparisons and bounded grid enumeration. -/ + +namespace EditApproximation + +private theorem log_two_add_one_eq_size (N : ℕ) (hN : 0 < N) : + Nat.log 2 N + 1 = Nat.size N := by + apply Nat.le_antisymm + · have h := Nat.pow_log_le_self 2 hN.ne' + have hlt : Nat.log 2 N < Nat.size N := Nat.lt_size.mpr h + omega + · exact Nat.size_le.mpr (Nat.lt_pow_succ_log_self (by decide : 1 < 2) N) + + + +@[simp] theorem dyadicScalesWithWork_value (N : ℕ) : + (dyadicScalesWithWork N).1 = dyadicScales N := by + have hcount : max 1 N.bits.length = Nat.log 2 N + 1 := by + by_cases hz : N = 0 + · subst N + decide + · have h := log_two_add_one_eq_size N (Nat.pos_of_ne_zero hz) + have hp := Nat.size_pos.mpr (Nat.pos_of_ne_zero hz) + rw [Nat.size_eq_bits_len, max_eq_right hp, h] + simp only [dyadicScalesWithWork, arithmeticMapWithWork_value, powerTwoWord_value, hcount, + dyadicScales] + +theorem dyadicScalesWithWork_cost (N : ℕ) : + (dyadicScalesWithWork N).2 ≤ (Nat.size N + 1) * (Nat.size N + 9) + 2 := by + let count := max 1 N.bits.length + have hc : count ≤ Nat.size N + 1 := by dsimp only [count]; rw [Nat.size_eq_bits_len]; omega + have hm := arithmeticMapWithWork_cost + (fun e => (bitWordValue (powerTwoWord e), e + 3)) (List.range count) (count + 3) (by + intro e he + have h := List.mem_range.mp he + omega) + simp only [List.length_range] at hm + change (arithmeticMapWithWork _ (List.range count)).2 + N.bits.length + count + 2 ≤ _ + rw [Nat.size_eq_bits_len] + nlinarith only [hm, hc, Nat.zero_le (Nat.size N)] + + + +@[simp] theorem seedGridSpacingWithWork_value (b P : ℕ) (hP : 0 < P) : + bitWordValue (seedGridSpacingWithWork b P).1 = seedGridSpacing b P := by + have hv := (binaryNaturalDivModWithWork_spec b P hP).1 + unfold seedGridSpacingWithWork seedGridSpacing + dsimp only + split_ifs with ht + · have hq : b / P ≤ 1 := by + have h := (wordLEWithWork_value _ _).mp ht + change bitWordValue (binaryNaturalDivModWithWork b P).1 ≤ 1 at h + rwa [hv] at h + rw [max_eq_left hq] + rfl + · have hq : 1 ≤ b / P := by + have h := mt (wordLEWithWork_value _ _).mpr ht + change ¬ bitWordValue (binaryNaturalDivModWithWork b P).1 ≤ 1 at h + rw [hv] at h + exact Nat.le_of_lt (Nat.lt_of_not_ge h) + rw [max_eq_right hq] + exact hv + +theorem seedGridSpacingWithWork_pos (b P : ℕ) (hP : 0 < P) : + 0 < bitWordValue (seedGridSpacingWithWork b P).1 := by + rw [seedGridSpacingWithWork_value b P hP] + unfold seedGridSpacing + omega + +namespace BinaryFraction + + + +@[simp] theorem initialScaleGuardWithWork_value (U b : ℕ) (A : BinaryFraction) : + (initialScaleGuardWithWork U b A).1 = true ↔ + (U : ℚ) / (16 * A.value ^ 2) ≤ b ∧ (b : ℚ) ≤ 4 * A.value * U := by + simp only [initialScaleGuardWithWork, Bool.and_eq_true, leWithWork_value, + canonicalMulWithWork_value, divWithWork_value, nat_value, pow_two] + norm_num + + + +@[simp] theorem initialCenterGuardWithWork_value (b U : ℕ) (A : BinaryFraction) : + (initialCenterGuardWithWork b U A).1 = true ↔ + (b : ℚ) / 2 ≤ U ∧ (U : ℚ) ≤ 4 * A.value * b := by + simp only [initialCenterGuardWithWork, Bool.and_eq_true, leWithWork_value, + canonicalMulWithWork_value, divWithWork_value, nat_value] + norm_num + +def initialCentersWithWork {n : ℕ} (N P : ℕ) (A : BinaryFraction) + (U : TargetInterval n → ℕ) (q : TargetInterval n) : List (TargetInterval n) × ℕ := + let scales := dyadicScalesWithWork N + let active := filterWithWork (fun b => initialScaleGuardWithWork (U q) b A) scales.1 + let centers := arithmeticFlatMapWithWork (fun b => + let spacing := seedGridSpacingWithWork b P + let points := gridStateBoxWithWork n (bitWordValue spacing.1) (U q) q.lo q.hi + let selected := filterWithWork (fun r => initialCenterGuardWithWork b (U r) A) points.1 + (selected.1, spacing.2 + points.2 + selected.2 + 2)) active.1 + (centers.1, scales.2 + active.2 + centers.2 + 3) + +@[simp] theorem initialCentersWithWork_value {n : ℕ} (N P : ℕ) (A : BinaryFraction) + (U : TargetInterval n → ℕ) (q : TargetInterval n) (hP : 0 < P) : + (initialCentersWithWork N P A U q).1 = localInitialConeCenters N P A.value U q := by + have hscale (b : ℕ) : (initialScaleGuardWithWork (U q) b A).1 = + decide ((U q : ℚ) / (16 * A.value ^ 2) ≤ b ∧ (b : ℚ) ≤ 4 * A.value * U q) := + Bool.eq_iff_iff.mpr (by simp only [initialScaleGuardWithWork_value, decide_eq_true_eq]) + have hcenter (b : ℕ) (r : TargetInterval n) : (initialCenterGuardWithWork b (U r) A).1 = + decide ((b : ℚ) / 2 ≤ U r ∧ (U r : ℚ) ≤ 4 * A.value * b) := + Bool.eq_iff_iff.mpr (by simp only [initialCenterGuardWithWork_value, decide_eq_true_eq]) + have hgrid (b : ℕ) : + (gridStateBoxWithWork n (bitWordValue (seedGridSpacingWithWork b P).1) + (U q) q.lo q.hi).1 = localTargetStates n (seedGridSpacing b P) (U q) q := by + rw [gridStateBoxWithWork_value _ _ _ _ _ (seedGridSpacingWithWork_pos b P hP), + seedGridSpacingWithWork_value b P hP] + rfl + simp only [initialCentersWithWork, arithmeticFlatMapWithWork_value, + filterWithWork_value, dyadicScalesWithWork_value, hgrid, + hscale, hcenter, localInitialConeCenters] + +def initialProgramWithWork {n : ℕ} (sourceLength N P F : ℕ) (A a : BinaryFraction) + (U : TargetInterval n → ℕ) (q : TargetInterval n) : BinaryFraction × ℕ := + let centers := initialCentersWithWork N P A U q + let result := initialMinimumWithWork sourceLength U N F a q centers.1 + (result.1, centers.2 + result.2 + 1) + +@[simp] theorem initialProgramWithWork_value {α : Type*} (source target : List α) + (N P F : ℕ) (A a : BinaryFraction) (U : TargetInterval target.length → ℕ) + (q : TargetInterval target.length) (hP : 0 < P) : + (initialProgramWithWork source.length N P F A a U q).1.value = + localInitialConeTable source target U N P F A.value a.value q := by + simp only [initialProgramWithWork, initialCentersWithWork_value N P A U q hP] + exact initialMinimumWithWork_value source target U N P F A.value a q + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryScoreReads.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryScoreReads.lean new file mode 100644 index 0000000000000000000000000000000000000000..4d643838a9390742904c36b20f267fb988f23df1 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryScoreReads.lean @@ -0,0 +1,70 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryRepresentativeKernel +import OAI.Combinatorics.EditApproximation.Binary.BinaryReadComposition +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Representative scores use literal reader calls at their child +coordinates. The stored value agrees with the previous arithmetic kernel. -/ + +namespace EditApproximation +namespace BinaryFraction + + + +theorem endpointScoreReadWithWork_eq {n M : ℕ} (r : TargetInterval n) + (read : Fin M → TargetInterval n → BinaryFraction × ℕ) (states : Fin M → TargetInterval n) : + (endpointScoreReadWithWork r read states).1 = + (endpointScoreWithWork r (fun i q => (read i q).1) states).1 := by + simp only [endpointScoreReadWithWork, endpointScoreWithWork, + arithmeticMapWithWork_value, List.ofFn_eq_map] + +theorem endpointScoreReadWithWork_cost {n M : ℕ} (r : TargetInterval n) + (read : Fin M → TargetInterval n → BinaryFraction × ℕ) (states : Fin M → TargetInterval n) + (R : ℕ) (hr : ∀ i, (read i (states i)).2 ≤ R) : + (endpointScoreReadWithWork r read states).2 ≤ + (endpointScoreWithWork r (fun i q => (read i q).1) states).2 + M * (R + 3) := by + have h := arithmeticMapWithWork_cost (fun i => read i (states i)) + (List.finRange M) R (fun i _ => hr i) + simp only [List.length_finRange] at h + simp only [endpointScoreReadWithWork, endpointScoreWithWork, + arithmeticMapWithWork_value, List.ofFn_eq_map] + omega + + + +theorem wideMinimumReadWithWork_eq {n M : ℕ} (r : TargetInterval n) + (read : Fin M → TargetInterval n → BinaryFraction × ℕ) + (actions : List (Fin M → TargetInterval n)) (hne : actions ≠ []) : + (wideMinimumReadWithWork r read actions hne).1 = + (wideMinimumWithWork r (fun i q => (read i q).1) actions hne).1 := by + simp only [wideMinimumReadWithWork, wideMinimumWithWork, arithmeticMapWithWork_value, + endpointScoreReadWithWork_eq] + +theorem wideMinimumReadWithWork_cost {n M : ℕ} (r : TargetInterval n) + (read : Fin M → TargetInterval n → BinaryFraction × ℕ) + (actions : List (Fin M → TargetInterval n)) (hne : actions ≠ []) (R : ℕ) + (hr : ∀ action ∈ actions, ∀ i, (read i (action i)).2 ≤ R) : + (wideMinimumReadWithWork r read actions hne).2 ≤ + (wideMinimumWithWork r (fun i q => (read i q).1) actions hne).2 + + (actions.length + 1) * (M * (R + 3)) := by + have h := arithmeticMapWithWork_extra (endpointScoreReadWithWork r read) + (endpointScoreWithWork r (fun i q => (read i q).1)) (fun _ => M * (R + 3)) actions + (fun action _ => endpointScoreReadWithWork_eq r read action) + (fun action ha => endpointScoreReadWithWork_cost r read action R (hr action ha)) + have hf := endpointScoreReadWithWork_cost r read (actions.head hne) R + (hr _ (List.head_mem hne)) + have hs : (actions.map (fun _ => M * (R + 3))).sum = actions.length * (M * (R + 3)) := by + simp only [List.map_const', List.sum_replicate, smul_eq_mul] + rw [hs] at h + unfold wideMinimumReadWithWork wideMinimumWithWork + dsimp only + rw [endpointScoreReadWithWork_eq, h.1] + simp only [Nat.add_mul, Nat.one_mul] + omega + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinarySeedMedianWork.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinarySeedMedianWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..effe199a69ac6cc64a1c6df5e5d077b53d25967a --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinarySeedMedianWork.lean @@ -0,0 +1,41 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryMedianKernel +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! The natural seed cache stores a trimmed result, so repeated median +passes do not accumulate leading zero words. The trimming scan is charged. -/ + +namespace EditApproximation +namespace BinaryFraction + + + +@[simp] theorem seedMedianWithWork_value (N multiplier : ℕ) (values : List BinaryFraction) : + bitWordValue (seedMedianWithWork N multiplier values).1 = + min N (upperMedian (values.map fun a => ⌈(multiplier : ℚ) * a.value⌉₊)) := by + simp only [seedMedianWithWork, trimBitWordWithWork_value, medianSeedWithWork_value] + +theorem seedMedianWithWork_length (N multiplier : ℕ) (values : List BinaryFraction) : + (seedMedianWithWork N multiplier values).1.length ≤ Nat.size N := by + simp only [seedMedianWithWork, trimBitWordWithWork_length, medianSeedWithWork_value] + exact Nat.size_le_size (Nat.min_le_left _ _) + +def seedMedianBitBudget (n B : ℕ) : ℕ := medianSeedBitBudget n B + 12 * B + 14 + +theorem seedMedianWithWork_cost (N multiplier : ℕ) (values : List BinaryFraction) (B : ℕ) + (hN : Nat.size N ≤ B) (hm : Nat.size multiplier + 2 ≤ B) + (hv : ∀ a ∈ values, a.width ≤ B) : + (seedMedianWithWork N multiplier values).2 ≤ seedMedianBitBudget values.length B := by + have hmedian := medianSeedWithWork_bounds N multiplier values B hN hm hv + have htrim := trimBitWordWithWork_cost (medianSeedWithWork N multiplier values).1 + change (medianSeedWithWork N multiplier values).2 + + (trimBitWordWithWork (medianSeedWithWork N multiplier values).1).2 + 1 ≤ _ + unfold seedMedianBitBudget + omega + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinarySelectedGroupWork.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinarySelectedGroupWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..981ecdfe6c4da88e40561c373a365e3256ad772f --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinarySelectedGroupWork.lean @@ -0,0 +1,91 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinarySampledGroupWork + +namespace OAI + +/-! Complete group selection cost, including every sampled member estimate +and reconstruction of the selected rounded action. -/ + +namespace EditApproximation +namespace BinaryFraction + +private theorem roundedBandBitBudget_mono_vertices (e b M v w B : ℕ) (h : v ≤ w) : + roundedBandBitBudget e b M v B ≤ roundedBandBitBudget e b M w B := by + unfold roundedBandBitBudget bandEnvelopeBitBudget + dsimp only + gcongr + +private theorem sampledMemberBitBudget_mono_vertices (M T e b v w B : ℕ) (h : v ≤ w) : + sampledMemberBitBudget M T e b v B ≤ sampledMemberBitBudget M T e b w B := by + have hr := roundedBandBitBudget_mono_vertices e b M v w B h + unfold sampledMemberBitBudget bandEnvelopeBitBudget + dsimp only + gcongr + +def selectedGroupBitBudget (M T e b members vertices B : ℕ) : ℕ := + members * (sampledMemberBitBudget M T e b vertices B + + 1000 * (sampledMemberWordBudget M T b B + 1) ^ 2 + 3) + 1 + + roundedBandBitBudget e b M vertices B + connectionBitBudget M B + 2 * B + 2 * M + 6 + +theorem sampledGroupActionWithWork_cost {α : Type*} (source target : List α) {M T : ℕ} + (parent : TargetInterval source.length) (b P exponent Q : ℕ) (tau F : BinaryFraction) + (child initial current : Fin M → TargetInterval target.length → BinaryFraction) + (scales : Fin T → BinaryFraction) + (draw : ∀ t, Fin (groupSampleCount M Q b (scales t).value) → Fin M) + (members : List (UnskippedBand source target parent b P exponent tau.value F.value + (fun i q => (child i q).value) (fun i q => (initial i q).value))) (hne : members ≠ []) + (V B : ℕ) (hM : Nat.size M + 2 ≤ B) (hQ : Nat.size Q + 2 ≤ B) + (hb : Nat.size b + 2 ≤ B) (hny : Nat.size target.length + 2 ≤ B) + (hs : ∀ t, (scales t).width ≤ B) + (hV : ∀ member ∈ members, member.actions.length ≤ V) + (hi : ∀ member ∈ members, ∀ action ∈ member.actions, ∀ i, (initial i (action i)).width ≤ B) + (hv : ∀ i q, (current i q).width ≤ B) : + (sampledGroupActionWithWork source target parent b P exponent Q tau F child initial current + scales draw members hne).2 ≤ selectedGroupBitBudget M T exponent b members.length V B := by + let estimate := unskippedEstimateWithWork source target parent b P exponent Q tau F + child initial current scales draw + have he (member) (hm : member ∈ members) := unskippedEstimateWithWork_bounds source target parent b P exponent Q + tau F child initial current scales draw member B hM hQ hb hny hs (hi member hm) hv + have hselection := selectGroupWithWork_cost members hne estimate + (sampledMemberBitBudget M T exponent b V B) (sampledMemberWordBudget M T b B) + (fun member hm => (he member hm).2.trans (sampledMemberBitBudget_mono_vertices _ _ _ _ _ _ _ (hV member hm))) + (fun member hm => (he member hm).1) + let selected := (chooseBinaryUnskippedWithWork source target parent b P exponent Q tau F + child initial current scales draw members hne).1 + have hselected : selected ∈ members := by + rw [show selected = selectGroupMember members hne (fun member => (estimate member).1.value) from + selectGroupWithWork_value members hne estimate] + exact (selectGroupMember_spec members hne _).1 + have hrounded := (roundedBandWithWork_cost exponent b selected.actions selected.nonempty initial B + (by omega) (hi selected hselected)).trans + (roundedBandBitBudget_mono_vertices _ _ _ _ _ _ (hV selected hselected)) + let states := (roundedBandWithWork exponent b selected.actions selected.nonempty initial).1.get + have hcenterlo : Nat.size selected.center.lo + 2 ≤ B := + (Nat.add_le_add_right (Nat.size_le_size (selected.center.ordered.trans selected.center.valid)) 2).trans hny + have hcenterhi : Nat.size selected.center.hi + 2 ≤ B := + (Nat.add_le_add_right (Nat.size_le_size selected.center.valid) 2).trans hny + have hstates : ∀ s ∈ List.ofFn states, Nat.size s.lo + 2 ≤ B ∧ Nat.size s.hi + 2 ≤ B := by + intro s _ + exact ⟨(Nat.add_le_add_right (Nat.size_le_size (s.ordered.trans s.valid)) 2).trans hny, + (Nat.add_le_add_right (Nat.size_le_size s.valid) 2).trans hny⟩ + have hconnection := connectionWithWork_cost (nat selected.center.lo) (nat selected.center.hi) + (List.ofFn states) B ((nat_width_le _).trans hcenterlo) + ((nat_width_le _).trans hcenterhi) hstates + simp only [List.length_ofFn] at hconnection + have haction : (endpointActionWithWork selected.center states).2 ≤ + connectionBitBudget M B + 2 * B + 2 * M + 3 := by + change (connectionWithWork (nat selected.center.lo) (nat selected.center.hi) (List.ofFn states)).2 + + Nat.size selected.center.lo + Nat.size selected.center.hi + M + 2 + M + 1 ≤ _ + omega + change (chooseBinaryUnskippedWithWork source target parent b P exponent Q tau F child initial current + scales draw members hne).2 + + (roundedBandWithWork exponent b selected.actions selected.nonempty initial).2 + + (endpointActionWithWork selected.center states).2 + 3 ≤ _ + change (chooseBinaryUnskippedWithWork source target parent b P exponent Q tau F child initial current + scales draw members hne).2 ≤ _ at hselection + unfold selectedGroupBitBudget + omega + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinarySelectionSpace.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinarySelectionSpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..71d58187971cbf04c0a2c9a34075e76c9e41200f --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinarySelectionSpace.lean @@ -0,0 +1,39 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryActionSelection +import OAI.Combinatorics.EditApproximation.Binary.BinaryOptimizerSpace +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation.BinaryFraction + +theorem scoredArgmaxWithWork_count {α : Type*} (score : α → BinaryFraction × ℕ) (values : List α) : + values.length ≤ (scoredArgmaxWithWork score values).2 := by + induction values with + | nil => exact Nat.zero_le _ + | cons value rest ih => + simp only [scoredArgmaxWithWork, List.length_cons] + split <;> dsimp only <;> omega + +/-- Includes the pointer list passed to the optimizer, then the final +label-preserving gradient and maximum scan. -/ + + +theorem selectionAllocation_le_work {α : Type*} {d : ℕ} + (vertices : List (α × Vector BinaryFraction d)) (linear : Vector BinaryFraction d) (G j : ℕ) : + selectionAllocation vertices linear G j ≤ 2 * (selectionWithWork vertices linear G j).2 := by + let iterate := (finiteOptimizerWithWork (vertices.map Prod.snd) linear G j).1 + let gradient := (gradientWithWork G linear iterate).1 + have hi := optimizerAllocation_le_work (vertices.map Prod.snd) linear G j + have hg := gradientAllocation_le_work G linear iterate + have hs := scoredArgmaxAllocation_le_work (fun vertex : α × Vector BinaryFraction d => + dotWithWork gradient vertex.2) (fun vertex => dotListAllocation gradient vertex.2 (List.finRange d)) vertices + (fun vertex _ => dotListAllocation_le_work gradient vertex.2 (List.finRange d)) + have hn := scoredArgmaxWithWork_count (fun vertex : α × Vector BinaryFraction d => dotWithWork gradient vertex.2) vertices + unfold selectionAllocation selectionWithWork + dsimp only [iterate, gradient] at hi hg hs hn ⊢ + omega + +end EditApproximation.BinaryFraction + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinarySourceSelectorBounds.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinarySourceSelectorBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..c12265d731055f43ccafceabd807ad666d96bad4 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinarySourceSelectorBounds.lean @@ -0,0 +1,106 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryLocalSourceKernel +import OAI.Combinatorics.EditApproximation.Binary.BinaryPreparedKernelWork +import OAI.Combinatorics.EditApproximation.Binary.BinaryOuterReadCosts + +namespace OAI + +/-! Complete selector bounds with table and scalar-source reads. The +source-cost premises range only over the guards and cells actually visited. -/ + +namespace EditApproximation.BinaryFraction +section Selectors +variable {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (N P F exponent H Q eM eF B E S : ℕ) + (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) + (tau a eta kappa delta : BinaryFraction) + (parentInitial : TargetInterval target.length → BinaryFraction × ℕ) + (child initial : Fin M → TargetInterval target.length → BinaryFraction × ℕ) + (old current : Fin M × TargetInterval target.length → BinaryFraction × ℕ) + (history : ℕ → Fin M × TargetInterval target.length → BinaryFraction × ℕ) + (R : ℕ) (hc : ∀ i r, (child i r).2 ≤ R) (hi : ∀ i r, (initial i r).2 ≤ R) + (t : ℕ) (draw : CellGroupReadDraws M F Q) + (integer : ℕ → TargetInterval target.length → ℕ × ℕ) + (q : TargetInterval target.length) + (hb : PreparedKernelInputBounds (nx := source.length) N P F exponent H Q eM eF B E S t + tau a eta kappa delta (fun r => (parentInitial r).1) + (fun i r => (child i r).1) (fun i r => (initial i r).1) + (fun s => (old s).1) (fun s => (current s).1) (fun s i => (history s i).1) + (fun b r => (integer b r).1)) + (hp : ∀ r, (parentInitial r).2 ≤ R) + +include hb hp in +theorem preparedLocalCellGroupsSourceWithWork_bounds (hPdyadic : ∃ j : ℕ, P = 2 ^ j) + (hn : ∀ input, (current input).2 ≤ R) (D : ℕ) + (hd : ∀ eb ∈ List.range (max 1 N.bits.length), + (refinementScaleGuardWithWork F (2 ^ eb) a (parentInitial q).1).1 = true → + ∀ cell ∈ (targetCellsWithWork + (canonicalMulWithWork (inversePowerTwo exponent) (nat (2 ^ eb))).1 + (bitWordValue (naturalCeilingWithWork (parentInitial q).1).1) q).1, + ∀ scale sample, (draw (2 ^ eb) cell scale sample).2 ≤ D) : + let selected := preparedLocalCellGroupsSourceWithWork source target parent P F exponent Q eM eF + hM hF hP tau a parentInitial child initial (fun i r => current (i, r)) R hc hi N draw q + selected.1.length ≤ (B + 1) * ((32 * F + 2) * 2 ^ exponent + 2) ^ 2 ∧ + selected.2 ≤ preparedLocalGroupsBitBudget N M P F exponent eM eF B * tableReadFactor R * (D + 4) := by + have hs := preparedLocalCellGroupsSourceWithWork_eq_cost_on source target parent P F exponent Q eM eF + hM hF hP tau a parentInitial child initial (fun i r => current (i, r)) R hc hi N draw q D hd + have heq := preparedLocalCellGroupsReadWithWork_eq source target parent P F exponent Q eM eF + hM hF hP tau a parentInitial child initial (fun i r => current (i, r)) R hc hi N + (fun b cell scale sample => (draw b cell scale sample).1) q hp (fun i r => hn (i, r)) + have hr := preparedLocalCellGroupsReadWithWork_factor source target parent P F exponent Q eM eF + hM hF hP tau a parentInitial child initial (fun i r => current (i, r)) R hc hi N + (fun b cell scale sample => (draw b cell scale sample).1) q hp (fun i r => hn (i, r)) + have hcost := preparedLocalCellGroupsWithWork_cost source target parent N P F exponent Q eM eF B hM hF hP + tau a (fun r => (parentInitial r).1) (fun i r => (child i r).1) (fun i r => (initial i r).1) + (fun i r => (current (i, r)).1) (fun b cell scale sample => (draw b cell scale sample).1) q + (by have := hb.largeBits; omega) hb.inputSize hb.sourceSize hb.targetSize hb.aritySize hb.sampleSize + hb.precisionSize hb.factorSize hb.thetaSize hb.scaleSizes hb.tauSize hb.factorWidth hb.parentSize + hb.massSize hb.initialSize (fun i r => hb.currentSize (i, r)) (hb.parentNonneg q) hPdyadic + constructor + · rw [hs.1, heq] + exact preparedLocalCellGroupsWithWork_length_le source target parent N P F exponent Q eM eF B + hM hF hP tau a (fun r => (parentInitial r).1) (fun i r => (child i r).1) + (fun i r => (initial i r).1) (fun i r => (current (i, r)).1) + (fun b cell scale sample => (draw b cell scale sample).1) q hb.inputSize (hb.parentNonneg q) + · exact hs.2.trans (Nat.mul_le_mul_right (D + 4) + (hr.trans (Nat.mul_le_mul_right (tableReadFactor R) hcost))) + +include hb hp hM in +theorem preparedLocalOnlineActionsSourceWithWork_bounds + (hh : ∀ s ≤ t + 1, ∀ input, (history s input).2 ≤ R) (D : ℕ) + (hd : ∀ e ∈ (queryExponentsWithWork N F a (parentInitial q).1).1, + (centerEligibilityWithWork (2 ^ e) F a + (parentInitial (roundStateWithWork (bitWordValue (seedGridSpacingWithWork (2 ^ e) P).1) + (seedGridSpacingWithWork_pos (2 ^ e) P hP) q).1).1).1 = true → + (integer (2 ^ e) (roundStateWithWork (bitWordValue (seedGridSpacingWithWork (2 ^ e) P).1) + (seedGridSpacingWithWork_pos (2 ^ e) P hP) q).1).2 ≤ D) : + let selected := preparedLocalOnlineActionsSourceWithWork source target parent P F exponent H hP + tau a eta kappa parentInitial child initial history R hc hi t integer N q + selected.1.length ≤ B + 1 ∧ + selected.2 ≤ preparedLocalOnlineBitBudget M P B S * tableReadFactor R * (D + 4) := by + have hs := preparedLocalOnlineActionsSourceWithWork_eq_cost_on source target parent P F exponent H hP + tau a eta kappa parentInitial child initial history R hc hi t integer N q D hd + have heq := preparedLocalOnlineActionsReadWithWork_eq source target parent P F exponent H hP + tau a eta kappa parentInitial child initial history R hc hi t (fun b r => (integer b r).1) N q hh + have hr := preparedLocalOnlineActionsReadWithWork_factor source target parent P F exponent H hP + tau a eta kappa parentInitial child initial history R hc hi t (fun b r => (integer b r).1) N q hp hh + have hcost := preparedLocalOnlineActionsWithWork_cost source target parent N P F exponent H B E S hP + (by rw [hM]; exact Nat.two_pow_pos _) tau a eta kappa (fun r => (parentInitial r).1) + (fun i r => (child i r).1) (fun i r => (initial i r).1) (fun s i => (history s i).1) + t (fun b r => (integer b r).1) q (by have := hb.largeBits; omega) hb.inputSize hb.sourceSize + hb.targetSize (by have := hb.aritySize; omega) hb.precisionSize hb.factorSize hb.thetaSize + hb.heightSize hb.coordinateSize hb.iterationSize hb.drawSize hb.tauSize hb.factorWidth + hb.rateSize hb.optimismSize hb.parentSize hb.massSize hb.initialSize hb.historySize hb.rateMagnitude + hb.optimismRange hb.historyRange hb.scalePositive hb.arityCap hb.precisionCap hb.rateCap hb.timeCap + hb.wordCap hb.actionCap hb.cartesianCap hb.iterationCap + constructor + · rw [hs.1, heq] + exact preparedLocalOnlineActionsWithWork_length_le source target parent N P F exponent H B hP + tau a eta kappa (fun r => (parentInitial r).1) (fun i r => (child i r).1) + (fun i r => (initial i r).1) (fun s i => (history s i).1) t (fun b r => (integer b r).1) q hb.inputSize + · exact hs.2.trans (Nat.mul_le_mul_right (D + 4) + (hr.trans (Nat.mul_le_mul_right (tableReadFactor R) hcost))) + +end Selectors +end EditApproximation.BinaryFraction + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinarySubtractWork.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinarySubtractWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..18dba857591d674c50a21732e826ddda97bab24c --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinarySubtractWork.lean @@ -0,0 +1,145 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryOrderWork +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Ripple-borrow subtraction, used after the magnitude comparison in +signed-integer addition. No unit-cost operation on unbounded integers is +used by this Boolean routine. -/ + +namespace EditApproximation + + + + + +theorem bitSubtractor_value (a b borrow : Bool) : + a.toNat + 2 * (bitBorrow a b borrow).toNat = + b.toNat + borrow.toNat + (bitDifference a b borrow).toNat := by + cases a <;> cases b <;> cases borrow <;> decide + +/-- Ripple-borrow subtraction when the minuend has no remaining bits. -/ + + + + +theorem bitSubtractWithWork_length (left right : List Bool) (borrow : Bool) : + (bitSubtractWithWork left right borrow).1.length = max left.length right.length := by + induction left generalizing right borrow with + | nil => + simp only [bitSubtractWithWork] + induction right generalizing borrow with + | nil => simp [bitSubtractNilLeftWithWork] + | cons b bs ih => simp [bitSubtractNilLeftWithWork, ih] + | cons a as ih => + cases right with + | nil => simp [bitSubtractWithWork, ih] + | cons b bs => simp [bitSubtractWithWork, ih, Nat.succ_max_succ] + +private theorem bitSubtractionRippleEquation (a b borrow nextBorrow difference left right result tail : ℕ) + (htail : result + right + nextBorrow = left + tail) + (hbit : a + 2 * nextBorrow = b + borrow + difference) : + (difference + 2 * result) + (b + 2 * right) + borrow = + (a + 2 * left) + 2 * tail := by + omega + +theorem bitSubtractWithWork_value (left right : List Bool) (borrow : Bool) : + bitWordValue (bitSubtractWithWork left right borrow).1 + bitWordValue right + borrow.toNat = + bitWordValue left + 2 ^ max left.length right.length * + (bitSubtractWithWork left right borrow).2.1.toNat := by + induction left generalizing right borrow with + | nil => + induction right generalizing borrow with + | nil => simp [bitSubtractWithWork, bitSubtractNilLeftWithWork, bitWordValue] + | cons b bs ih => + have h := ih (bitBorrow false b borrow) + have hb := bitSubtractor_value false b borrow + simp only [bitSubtractWithWork, bitSubtractNilLeftWithWork, bitWordValue, + List.length_nil, List.length_cons, Nat.zero_max, pow_succ, Bool.toNat_false] at h hb ⊢ + have hs := bitSubtractionRippleEquation 0 b.toNat borrow.toNat (bitBorrow false b borrow).toNat + (bitDifference false b borrow).toNat 0 (bitWordValue bs) + (bitWordValue (bitSubtractNilLeftWithWork bs (bitBorrow false b borrow)).1) + (2 ^ bs.length * (bitSubtractNilLeftWithWork bs (bitBorrow false b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons a as ih => + cases right with + | nil => + have h := ih [] (bitBorrow a false borrow) + have hb := bitSubtractor_value a false borrow + simp only [bitSubtractWithWork, bitWordValue, List.length_nil, List.length_cons, + Nat.max_zero, pow_succ, Bool.toNat_false] at h hb ⊢ + have hs := bitSubtractionRippleEquation a.toNat 0 borrow.toNat (bitBorrow a false borrow).toNat + (bitDifference a false borrow).toNat (bitWordValue as) 0 + (bitWordValue (bitSubtractWithWork as [] (bitBorrow a false borrow)).1) + (2 ^ as.length * (bitSubtractWithWork as [] (bitBorrow a false borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons b bs => + have h := ih bs (bitBorrow a b borrow) + have hb := bitSubtractor_value a b borrow + simp only [bitSubtractWithWork, bitWordValue, List.length_cons, Nat.succ_max_succ, + pow_succ] at h hb ⊢ + have hs := bitSubtractionRippleEquation a.toNat b.toNat borrow.toNat (bitBorrow a b borrow).toNat + (bitDifference a b borrow).toNat (bitWordValue as) (bitWordValue bs) + (bitWordValue (bitSubtractWithWork as bs (bitBorrow a b borrow)).1) + (2 ^ max as.length bs.length * (bitSubtractWithWork as bs (bitBorrow a b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_assoc, Nat.mul_left_comm] using hs + +theorem bitWordValue_lt_pow_length (bits : List Bool) : bitWordValue bits < 2 ^ bits.length := by + induction bits with + | nil => simp [bitWordValue] + | cons bit bits ih => + cases bit <;> simp only [bitWordValue, List.length_cons, pow_succ, Bool.toNat_false, Bool.toNat_true] <;> omega + +theorem bitSubtractWithWork_sub (left right : List Bool) (h : bitWordValue right ≤ bitWordValue left) : + bitWordValue (bitSubtractWithWork left right false).1 = bitWordValue left - bitWordValue right := by + have hvalue := bitSubtractWithWork_value left right false + have hlt := bitWordValue_lt_pow_length (bitSubtractWithWork left right false).1 + rw [bitSubtractWithWork_length] at hlt + cases hb : (bitSubtractWithWork left right false).2.1 + · simp only [hb, Bool.toNat_false, Nat.mul_zero, Nat.add_zero] at hvalue + omega + · simp only [hb, Bool.toNat_true, Bool.toNat_false, Nat.mul_one, Nat.add_zero] at hvalue + omega + +theorem bitSubtractWithWork_cost (left right : List Bool) (borrow : Bool) : + (bitSubtractWithWork left right borrow).2.2 ≤ 9 * (left.length + right.length) + 1 := by + induction left generalizing right borrow with + | nil => + induction right generalizing borrow with + | nil => simp [bitSubtractWithWork, bitSubtractNilLeftWithWork] + | cons b bs ih => + have h := ih (bitBorrow false b borrow) + simp only [bitSubtractWithWork, bitSubtractNilLeftWithWork, List.length_cons, List.length_nil] at * + omega + | cons a as ih => + cases right with + | nil => + have h := ih [] (bitBorrow a false borrow) + simp only [bitSubtractWithWork, List.length_cons, List.length_nil] at * + omega + | cons b bs => + have h := ih bs (bitBorrow a b borrow) + simp only [bitSubtractWithWork, List.length_cons] at * + omega + + + +theorem binaryNaturalSubtractWithWork_value (a b : ℕ) (h : b ≤ a) : + bitWordValue (binaryNaturalSubtractWithWork a b).1 = a - b := by + simpa only [binaryNaturalSubtractWithWork, bitWordValue_bits] using + bitSubtractWithWork_sub a.bits b.bits (by simpa only [bitWordValue_bits] using h) + +theorem binaryNaturalSubtractWithWork_cost (a b : ℕ) : + (binaryNaturalSubtractWithWork a b).2 ≤ 9 * (Nat.size a + Nat.size b) + 1 := by + simpa only [binaryNaturalSubtractWithWork, Nat.size_eq_bits_len] using + bitSubtractWithWork_cost a.bits b.bits false + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryTriangularChoice.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryTriangularChoice.lean new file mode 100644 index 0000000000000000000000000000000000000000..5dcad382785b30ef1ca0d48f89212448417980e4 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryTriangularChoice.lean @@ -0,0 +1,119 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryGroupSetup +import OAI.Combinatorics.EditApproximation.Binary.BinaryLocalGridWork +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! The optimizer's sampled iteration is obtained by the exact triangular +block search, with every threshold multiplication and comparison charged. -/ + +namespace EditApproximation + + + +@[simp] theorem triangularMassWithWork_value (K : ℕ) : + bitWordValue (triangularMassWithWork K).1 = optimizerTriangularMass K := by + simp only [triangularMassWithWork, binaryNaturalAddWithWork_value, binaryNaturalMulWithWork_value, + (binaryNaturalDivModWithWork_spec _ 2 (by decide)).1] + rw [← optimizerTriangularMass_twice K, Nat.mul_div_cancel_left _ (by decide : 0 < 2)] + + + +@[simp] theorem triangularChoiceWithWork_value (K : ℕ) (integer : Fin (optimizerTriangularMass K)) : + (triangularChoiceWithWork K integer).1 = triangularChoice K integer := by + induction K with + | zero => exact Fin.elim0 integer + | succ K ih => + change (let threshold := triangularMassWithWork K + let test := binaryNaturalCompareWithWork integer.val (bitWordValue threshold.1) + if h : test.1 = .lt then + let hsmall : integer.val < optimizerTriangularMass K := by + have ht := (binaryNaturalCompareWithWork_lt _ _).mp h + simpa only [threshold, triangularMassWithWork_value] using ht + let chosen := triangularChoiceWithWork K ⟨integer.val, hsmall⟩ + (chosen.1.castSucc, threshold.2 + test.2 + chosen.2 + 2) + else (⟨K, Nat.lt_succ_self K⟩, threshold.2 + test.2 + 1) : Fin (K + 1) × ℕ).1 = _ + unfold triangularChoice + dsimp only + by_cases hs : integer.val < optimizerTriangularMass K + · have ht : (binaryNaturalCompareWithWork integer.val + (bitWordValue (triangularMassWithWork K).1)).1 = .lt := by + apply (binaryNaturalCompareWithWork_lt _ _).mpr + simpa only [triangularMassWithWork_value] using hs + simp only [ht, dite_true, hs, ih] + · have ht : (binaryNaturalCompareWithWork integer.val + (bitWordValue (triangularMassWithWork K).1)).1 ≠ .lt := by + intro ht + apply hs + simpa only [triangularMassWithWork_value] using (binaryNaturalCompareWithWork_lt _ _).mp ht + simp only [ht, dite_false, hs] + +theorem triangularMassWithWork_bounds (K B : ℕ) (hK : Nat.size K ≤ B) : + (triangularMassWithWork K).1.length ≤ 3 * B + 4 ∧ + (triangularMassWithWork K).2 ≤ 10000 * (B + 3) ^ 2 := by + let next := binaryNaturalAddWithWork K 1 + let product := binaryNaturalMulWithWork K (bitWordValue next.1) + let quotient := binaryNaturalDivModWithWork (bitWordValue product.1) 2 + have hn : Nat.size (bitWordValue next.1) ≤ B + 3 := by + rw [binaryNaturalAddWithWork_value] + exact (binaryNaturalAdd_size_le K 1).trans (by simp only [Nat.size_one]; omega) + have hp := bitMulWithWork_length K.bits (bitWordValue next.1).bits + change product.1.length ≤ _ at hp + simp only [Nat.size_eq_bits_len] at hp + have hps : Nat.size (bitWordValue product.1) ≤ 3 * B + 4 := + (Nat.size_le.mpr (bitWordValue_lt_pow_length product.1)).trans (by omega) + have hq := (bitDivModWithWork_lengths (2 : ℕ).bits (bitWordValue product.1).bits).1 + change quotient.1.length = _ at hq + rw [Nat.size_eq_bits_len] at hq + have hc1 := binaryNaturalAddWithWork_cost K 1 + have hc2 := binaryNaturalMulWithWork_cost K (bitWordValue next.1) + have hc3 := binaryNaturalDivModWithWork_cost (bitWordValue product.1) 2 + simp only [Nat.size_one, show Nat.size 2 = 2 by decide] at hc1 hc3 + constructor + · change quotient.1.length ≤ _ + omega + · change next.2 + product.2 + quotient.2.2 + 3 ≤ _ + change next.2 ≤ _ at hc1 + change product.2 ≤ _ at hc2 + change quotient.2.2 ≤ _ at hc3 + nlinarith only [hc1, hc2, hc3, hK, hn, hps, Nat.zero_le B] + +def triangularChoiceBitBudget (K B : ℕ) : ℕ := + (K + 1) * (10000 * (B + 3) ^ 2 + 30 * (B + 3)) + +theorem triangularChoiceWithWork_cost (K : ℕ) (integer : Fin (optimizerTriangularMass K)) + (B : ℕ) (hK : Nat.size K ≤ B) (hi : Nat.size integer.val ≤ B) : + (triangularChoiceWithWork K integer).2 ≤ triangularChoiceBitBudget K B := by + induction K generalizing B with + | zero => exact Fin.elim0 integer + | succ K ih => + have hprev : Nat.size K ≤ B := (Nat.size_le_size (Nat.le_succ K)).trans hK + have hthreshold := triangularMassWithWork_bounds K B hprev + have hs : Nat.size (bitWordValue (triangularMassWithWork K).1) ≤ 3 * B + 4 := + (Nat.size_le.mpr (bitWordValue_lt_pow_length _)).trans hthreshold.1 + have hcompare := binaryNaturalCompareWithWork_cost integer.val + (bitWordValue (triangularMassWithWork K).1) + change (let threshold := triangularMassWithWork K + let test := binaryNaturalCompareWithWork integer.val (bitWordValue threshold.1) + if h : test.1 = .lt then + let hsmall : integer.val < optimizerTriangularMass K := by + have ht := (binaryNaturalCompareWithWork_lt _ _).mp h + simpa only [threshold, triangularMassWithWork_value] using ht + let chosen := triangularChoiceWithWork K ⟨integer.val, hsmall⟩ + (chosen.1.castSucc, threshold.2 + test.2 + chosen.2 + 2) + else (⟨K, Nat.lt_succ_self K⟩, threshold.2 + test.2 + 1) : Fin (K + 1) × ℕ).2 ≤ _ + dsimp only + split_ifs with h + · have hsmall : integer.val < optimizerTriangularMass K := by + have hc := (binaryNaturalCompareWithWork_lt _ _).mp h + simpa only [triangularMassWithWork_value] using hc + have hr := ih ⟨integer.val, hsmall⟩ B hprev hi + unfold triangularChoiceBitBudget at hr ⊢ + nlinarith only [hthreshold.2, hcompare, hr, hs, hi, Nat.zero_le K, Nat.zero_le B] + · unfold triangularChoiceBitBudget + nlinarith only [hthreshold.2, hcompare, hs, hi, Nat.zero_le K, Nat.zero_le B] + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryTriangularSpace.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryTriangularSpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..fc5e1e3034149e67199844b2ea52798ac8c74679 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryTriangularSpace.lean @@ -0,0 +1,70 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryTriangularChoice +import OAI.Combinatorics.EditApproximation.Queries.QueryBufferSpace +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation + + + +theorem triangularMassAllocation_le_work (K : ℕ) : + triangularMassAllocation K ≤ (triangularMassWithWork K).2 := by + have ha := bitAddAllocation_le_work K.bits (1 : ℕ).bits false + have hm := bitMulAllocation_le_work K.bits (bitWordValue (binaryNaturalAddWithWork K 1).1).bits + have hd := bitDivModAllocation_le_work (2 : ℕ).bits + (bitWordValue (binaryNaturalMulWithWork K (bitWordValue (binaryNaturalAddWithWork K 1).1)).1).bits + unfold triangularMassAllocation triangularMassWithWork binaryNaturalAddWithWork + binaryNaturalMulWithWork binaryNaturalDivModWithWork at * + dsimp only at * + omega + +/-- Allocate the exact threshold words visited by the triangular sampler. +The sampled integer and thresholds are already bounded finite words. -/ + + +theorem triangularChoiceAllocation_le_work (K : ℕ) (integer : Fin (optimizerTriangularMass K)) : + triangularChoiceAllocation K integer ≤ (triangularChoiceWithWork K integer).2 := by + induction K with + | zero => exact Fin.elim0 integer + | succ K ih => + have ht := triangularMassAllocation_le_work K + have hc := bitCompareWithWork_input_cells integer.val.bits + (bitWordValue (triangularMassWithWork K).1).bits + change _ ≤ (binaryNaturalCompareWithWork integer.val (bitWordValue (triangularMassWithWork K).1)).2 at hc + change (let threshold := triangularMassWithWork K + let test := binaryNaturalCompareWithWork integer.val (bitWordValue threshold.1) + let localCells := triangularMassAllocation K + integer.val.bits.length + + (bitWordValue threshold.1).bits.length + if h : test.1 = .lt then + let hsmall : integer.val < optimizerTriangularMass K := by + have hp := (binaryNaturalCompareWithWork_lt _ _).mp h + simpa only [threshold, triangularMassWithWork_value] using hp + localCells + triangularChoiceAllocation K ⟨integer.val, hsmall⟩ + else localCells) ≤ + (let threshold := triangularMassWithWork K + let test := binaryNaturalCompareWithWork integer.val (bitWordValue threshold.1) + if h : test.1 = .lt then + let hsmall : integer.val < optimizerTriangularMass K := by + have hp := (binaryNaturalCompareWithWork_lt _ _).mp h + simpa only [threshold, triangularMassWithWork_value] using hp + let chosen := triangularChoiceWithWork K ⟨integer.val, hsmall⟩ + (chosen.1.castSucc, threshold.2 + test.2 + chosen.2 + 2) + else (⟨K, Nat.lt_succ_self K⟩, threshold.2 + test.2 + 1) : Fin (K + 1) × ℕ).2 + dsimp only + split_ifs with h + · have hsmall : integer.val < optimizerTriangularMass K := by + have hp := (binaryNaturalCompareWithWork_lt _ _).mp h + simpa only [triangularMassWithWork_value] using hp + have hnext := ih ⟨integer.val, hsmall⟩ + dsimp only + exact (Nat.add_le_add + ((Nat.add_assoc _ _ _).le.trans (Nat.add_le_add ht hc)) hnext).trans + (Nat.le_add_right _ 2) + · dsimp only + exact ((Nat.add_assoc _ _ _).le.trans (Nat.add_le_add ht hc)).trans (Nat.le_succ _) + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryUnskippedGuardWork.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryUnskippedGuardWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..d96f2ca4801f50698ea73d9fea39c31c017823a2 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryUnskippedGuardWork.lean @@ -0,0 +1,143 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinarySelectedGroupWork +import OAI.Combinatorics.EditApproximation.Binary.BinaryBandTailWork + +namespace OAI + +/-! All post-construction band guards, including rounded wide membership +and the child imbalance scan, have explicit Boolean arithmetic costs. -/ + +namespace EditApproximation +namespace BinaryFraction + +def unskippedGuardInputBudget (b M B : ℕ) : ℕ := + let E := 3 * bandEnvelopeWordBudget b M B + 1 + B + E + bandMassTotalStorageBudget M E + stateGapWordBudget B + 10 + +def unskippedGuardBitBudget (e b M v w B : ℕ) : ℕ := + let E := 3 * bandEnvelopeWordBudget b M B + 1 + let W := unskippedGuardInputBudget b M B + M * (bandEnvelopeBitBudget b M v B + 6) + storedSumBitBudget M E + + 2000 * (W + 1) ^ 2 + 2000 * (4 * W + 3) ^ 2 + + (1000 * (16 * W + 11) ^ 2 + 1) + roundedBandBitBudget e b M v B + + (1 + w * (M * (16 * B + 8) + 1)) + + M * (18 * B + 1 + stateGapBitBudget B + 2000 * (W + 1) ^ 2 + + (1000 * (4 * W + 3) ^ 2 + 1) + 6) + 5 + +theorem unskippedGuardWithWork_cost {nx ny M : ℕ} (parent : TargetInterval nx) + (center : TargetInterval ny) (b e : ℕ) (F : BinaryFraction) + (band wide : List (Fin M → TargetInterval ny)) (hne : band ≠ []) + (initial : Fin M → TargetInterval ny → BinaryFraction) (B : ℕ) + (hF : F.width ≤ B) (hb : Nat.size b + 2 ≤ B) + (hnx : Nat.size nx + 2 ≤ B) (hny : Nat.size ny + 2 ≤ B) + (hi : ∀ action ∈ band, ∀ i, (initial i (action i)).width ≤ B) : + (unskippedGuardWithWork parent center b e F band wide hne initial).2 ≤ + unskippedGuardBitBudget e b M band.length wide.length B := by + let E := 3 * bandEnvelopeWordBudget b M B + 1 + let W := unskippedGuardInputBudget b M B + let envelope := envelopeVectorWithWork b band initial + let total := bandMassTotalWithWork envelope.1 + let fb := canonicalMulWithWork F (nat b) + let limit := canonicalMulWithWork (nat 64) fb.1 + let rounded := roundedBandWithWork e b band hne initial + have hBE : B ≤ W := by dsimp only [W, unskippedGuardInputBudget]; omega + have hEW : E ≤ W := by dsimp only [E, W, unskippedGuardInputBudget]; omega + have hW : 10 ≤ W := by dsimp only [W, unskippedGuardInputBudget]; omega + have he (i : Fin M) : (envelope.1.get i).width ≤ E := by + simp only [envelope, envelopeVectorWithWork, vectorMapWithWork_value] + exact bandEnvelopeWithWork_width b band initial i B (fun a ha => hi a ha i) + have hec := vectorMapWithWork_cost_le M (bandEnvelopeWithWork b band initial) + (bandEnvelopeBitBudget b M band.length B) + (fun i => bandEnvelopeWithWork_cost b band initial i B (fun a ha => hi a ha i)) + change envelope.2 ≤ _ at hec + have htc := bandMassTotalWithWork_cost envelope.1 E he + change total.2 ≤ _ at htc + have htw : total.1.width ≤ bandMassTotalStorageBudget M E := by + exact (dotListWithWork_width_le_storageBits envelope.1 (Vector.replicate M one) + (List.finRange M)).trans (bandMassTotalWithWork_storage envelope.1 E he) + have hstorage : bandMassTotalStorageBudget M E ≤ W := by + dsimp only [E, W, unskippedGuardInputBudget] + omega + have h64 : (nat 64).width ≤ W := (nat_width_le 64).trans (by + have h : Nat.size 64 = 7 := by decide + omega) + have h2 : (nat 2).width ≤ W := (nat_width_le 2).trans (by + have h : Nat.size 2 = 2 := by decide + omega) + have hfbw := canonicalMulWithWork_width F (nat b) W (hF.trans hBE) + ((nat_width_le b).trans (hb.trans hBE)) + have hfbc := canonicalMulWithWork_cost F (nat b) W (hF.trans hBE) + ((nat_width_le b).trans (hb.trans hBE)) + change fb.1.width ≤ _ at hfbw + change fb.2 ≤ _ at hfbc + have hlimw := canonicalMulWithWork_width (nat 64) fb.1 (4 * W + 2) (by omega) hfbw + have hlimc := canonicalMulWithWork_cost (nat 64) fb.1 (4 * W + 2) (by omega) hfbw + change limit.1.width ≤ _ at hlimw + change limit.2 ≤ _ at hlimc + have hsum := leWithWork_cost total.1 limit.1 (16 * W + 10) + (htw.trans (hstorage.trans (by omega))) (by omega) + have hround := roundedBandWithWork_cost e b band hne initial B (by omega) hi + change rounded.2 ≤ _ at hround + have hwide := actionMemberWithWork_cost rounded.1.get wide B (by omega) + have hgap (i : Fin M) : + (let sourceLength := binaryNaturalSubtractWithWork (sourceChild parent i).hi (sourceChild parent i).lo + let gap := stateGapWithWork (bitWordValue sourceLength.1) (rounded.1.get i) + let bound := canonicalMulWithWork (nat 2) (envelope.1.get i) + let test := leWithWork gap.1.absolute bound.1 + (test.1, sourceLength.2 + gap.2 + bound.2 + test.2 + 3)).2 ≤ + 18 * B + 1 + stateGapBitBudget B + 2000 * (W + 1) ^ 2 + + (1000 * (4 * W + 3) ^ 2 + 1) + 3 := by + let sourceLength := binaryNaturalSubtractWithWork (sourceChild parent i).hi (sourceChild parent i).lo + let gap := stateGapWithWork (bitWordValue sourceLength.1) (rounded.1.get i) + let bound := canonicalMulWithWork (nat 2) (envelope.1.get i) + have hlo : Nat.size (sourceChild parent i).lo + 2 ≤ B := + (Nat.add_le_add_right (Nat.size_le_size + ((sourceChild parent i).ordered.trans (sourceChild parent i).valid)) 2).trans hnx + have hhi : Nat.size (sourceChild parent i).hi + 2 ≤ B := + (Nat.add_le_add_right (Nat.size_le_size (sourceChild parent i).valid) 2).trans hnx + have hs := binaryNaturalSubtractWithWork_cost (sourceChild parent i).hi (sourceChild parent i).lo + have hlen : Nat.size (bitWordValue sourceLength.1) + 2 ≤ B := by + rw [binaryNaturalSubtractWithWork_value _ _ (sourceChild parent i).ordered] + exact (Nat.add_le_add_right (Nat.size_le_size (Nat.sub_le _ _)) 2).trans hhi + have hg := stateGapWithWork_bounds (bitWordValue sourceLength.1) (rounded.1.get i) B hlen + ((Nat.add_le_add_right (Nat.size_le_size ((rounded.1.get i).ordered.trans (rounded.1.get i).valid)) 2).trans hny) + ((Nat.add_le_add_right (Nat.size_le_size (rounded.1.get i).valid) 2).trans hny) + have hbndw := canonicalMulWithWork_width (nat 2) (envelope.1.get i) W h2 ((he i).trans hEW) + have hbndc := canonicalMulWithWork_cost (nat 2) (envelope.1.get i) W h2 ((he i).trans hEW) + have hgw : gap.1.width ≤ stateGapWordBudget B := hg.1 + have hgapW : stateGapWordBudget B ≤ W := by + dsimp only [W, unskippedGuardInputBudget] + omega + have ht := leWithWork_cost gap.1.absolute bound.1 (4 * W + 2) + (by change gap.1.width ≤ _; exact hgw.trans (hgapW.trans (by omega))) hbndw + change sourceLength.2 ≤ _ at hs + change bound.2 ≤ _ at hbndc + change sourceLength.2 + gap.2 + bound.2 + (leWithWork gap.1.absolute bound.1).2 + 3 ≤ _ + have hgc : gap.2 ≤ stateGapBitBudget B := hg.2 + simp only [Nat.add_assoc, Nat.reduceAdd] at ht + omega + have hall := allWithWork_cost (fun i => + let sourceLength := binaryNaturalSubtractWithWork (sourceChild parent i).hi (sourceChild parent i).lo + let gap := stateGapWithWork (bitWordValue sourceLength.1) (rounded.1.get i) + let bound := canonicalMulWithWork (nat 2) (envelope.1.get i) + let test := leWithWork gap.1.absolute bound.1 + (test.1, sourceLength.2 + gap.2 + bound.2 + test.2 + 3)) (List.finRange M) + (18 * B + 1 + stateGapBitBudget B + 2000 * (W + 1) ^ 2 + + (1000 * (4 * W + 3) ^ 2 + 1) + 3) (fun i _ => hgap i) + simp only [List.length_finRange, Nat.add_assoc, Nat.reduceAdd] at hall hsum hlimc + dsimp only [envelope, rounded] at hall + change envelope.2 + total.2 + fb.2 + limit.2 + (leWithWork total.1 limit.1).2 + rounded.2 + + (actionMemberWithWork rounded.1.get wide).2 + _ + 5 ≤ _ + dsimp only [unskippedGuardBitBudget] + change _ ≤ M * (bandEnvelopeBitBudget b M band.length B + 6) + storedSumBitBudget M E + + 2000 * (W + 1) ^ 2 + 2000 * (4 * W + 3) ^ 2 + + (1000 * (16 * W + 11) ^ 2 + 1) + roundedBandBitBudget e b M band.length B + + (1 + wide.length * (M * (16 * B + 8) + 1)) + + M * (18 * B + 1 + stateGapBitBudget B + 2000 * (W + 1) ^ 2 + + (1000 * (4 * W + 3) ^ 2 + 1) + 6) + 5 + simp only [Nat.add_assoc, Nat.reduceAdd] + omega + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryUnskippedKernel.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryUnskippedKernel.lean new file mode 100644 index 0000000000000000000000000000000000000000..2ad8973af14e0911d6ec4f111b10eedb9490f51a --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryUnskippedKernel.lean @@ -0,0 +1,106 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryRoundedKernel + +namespace OAI + +/-! Successful binary guard evaluation constructs exactly the tested record +used by group sampling. Proof fields carry no runtime cost. -/ + +namespace EditApproximation +namespace BinaryFraction + +private theorem rounded_band_congr {ny M : ℕ} (e b : ℕ) + {first second : List (Fin M → TargetInterval ny)} (h : first = second) + (hf : first ≠ []) (hs : second ≠ []) (initial : Fin M → TargetInterval ny → ℚ) : + canonicalRoundedBandAction e b first hf initial = + canonicalRoundedBandAction e b second hs initial := by + subst second + rfl + +def unskippedCandidateWithWork {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (b P thetaExponent : ℕ) (hb : 0 < b) + (tau F : BinaryFraction) (child initial : Fin M → TargetInterval target.length → BinaryFraction) + (center : TargetInterval target.length) : + Option (UnskippedBand source target parent b P thetaExponent tau.value F.value + (fun i q => (child i q).value) (fun i q => (initial i q).value)) × ℕ := + let band := representativeBandWithWork parent center (parent.hi - parent.lo) b P + tau (inversePowerTwo thetaExponent) child + if hband : band.1 = [] then (none, band.2 + 1) else + let wide := materializedWideActionsWithWork M parent center b P + let guard := unskippedGuardWithWork parent center b thetaExponent F band.1 + (wide.1.map Vector.get) hband initial + if hguard : guard.1 = true then + let facts := (unskippedGuardWithWork_value source target parent center b thetaExponent F + band.1 (wide.1.map Vector.get) hband initial hb).mp hguard + let hbandValue : band.1 = representativeBandActions source target parent center b P tau.value + ((2 : ℚ) ^ (-(thetaExponent : ℤ))) (fun i q => (child i q).value) := by + simpa only [inversePowerTwo_value] using representativeBandWithWork_value source target parent center b P + tau (inversePowerTwo thetaExponent) child + let hwideValue : wide.1.map Vector.get = wideActionList M parent center b P := + materializedWideActionsWithWork_value M parent center b P + (some { + center := center + nonempty := by + intro hzero + apply hband + exact hbandValue.trans hzero + sum_guard := by + simpa only [hbandValue] using facts.1 + wide_guard := by + have hw := facts.2.1 + rw [hwideValue] at hw + rw [rounded_band_congr thetaExponent b hbandValue hband _] at hw + exact hw + imbalance_guard := by + simpa only [hbandValue] using facts.2.2 }, + band.2 + wide.2 + guard.2 + wide.1.length + 3) + else (none, band.2 + wide.2 + guard.2 + wide.1.length + 2) + +@[simp] theorem unskippedCandidateWithWork_value {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (b P thetaExponent : ℕ) (hb : 0 < b) + (tau F : BinaryFraction) (child initial : Fin M → TargetInterval target.length → BinaryFraction) + (center : TargetInterval target.length) : + (unskippedCandidateWithWork source target parent b P thetaExponent hb tau F child initial center).1 = + testUnskippedBand source target parent b P thetaExponent tau.value F.value + (fun i q => (child i q).value) (fun i q => (initial i q).value) center := by + let band := representativeBandActions source target parent center b P tau.value + ((2 : ℚ) ^ (-(thetaExponent : ℤ))) (fun i q => (child i q).value) + have hbandValue : (representativeBandWithWork parent center (parent.hi - parent.lo) b P + tau (inversePowerTwo thetaExponent) child).1 = band := by + simpa only [inversePowerTwo_value] using + representativeBandWithWork_value source target parent center b P tau (inversePowerTwo thetaExponent) child + unfold unskippedCandidateWithWork testUnskippedBand + dsimp only + change _ = (if hband : band = [] then _ else _) + by_cases hband : band = [] + · have hactual := hbandValue.trans hband + simp only [dite_eq_left hactual, dite_eq_left hband] + · have hactual : (representativeBandWithWork parent center (parent.hi - parent.lo) b P + tau (inversePowerTwo thetaExponent) child).1 ≠ [] := fun h => hband (hbandValue.symm.trans h) + simp only [dite_eq_right hactual, dite_eq_right hband] + have hround := rounded_band_congr thetaExponent b hbandValue hactual hband + (fun j q => (initial j q).value) + have hguard := unskippedGuardWithWork_value source target parent center b thetaExponent F + (representativeBandWithWork parent center (parent.hi - parent.lo) b P + tau (inversePowerTwo thetaExponent) child).1 + ((materializedWideActionsWithWork M parent center b P).1.map Vector.get) hactual initial hb + conv_rhs at hguard => + rw [materializedWideActionsWithWork_value, hround] + simp only [hbandValue] + by_cases hs : (∑ i, bandChildEnvelope b band (fun j q => (initial j q).value) i) ≤ 64 * F.value * b + · rw [dite_eq_left hs] + by_cases hw : canonicalRoundedBandAction thetaExponent b band hband + (fun j q => (initial j q).value) ∈ wideActionList M parent center b P + · rw [dite_eq_left hw] + by_cases hg : ∀ i, |rationalStateGap + (substring source (sourceChild parent i).lo (sourceChild parent i).hi) target + (canonicalRoundedBandAction thetaExponent b band hband (fun j q => (initial j q).value) i)| ≤ + 2 * bandChildEnvelope b band (fun j q => (initial j q).value) i + · rw [dite_eq_left hg, dite_eq_left (hguard.mpr ⟨hs, hw, hg⟩)] + · rw [dite_eq_right hg, dite_eq_right (fun h => hg (hguard.mp h).2.2)] + · rw [dite_eq_right hw, dite_eq_right (fun h => hw (hguard.mp h).2.1)] + · rw [dite_eq_right hs, dite_eq_right (fun h => hs (hguard.mp h).1)] + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryUnskippedReads.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryUnskippedReads.lean new file mode 100644 index 0000000000000000000000000000000000000000..ffa9a7acbd523878bee932c3b09dd9d3a3f531d9 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryUnskippedReads.lean @@ -0,0 +1,120 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryBandReads +import OAI.Combinatorics.EditApproximation.Binary.BinaryRoundedReads +import OAI.Combinatorics.EditApproximation.Binary.BinaryPreparedUnskipped + +namespace OAI + +/-! The accepted-band record is built from the reader-aware tests. +Only proof fields are erased; numerical tests and reads remain charged. -/ + +namespace EditApproximation +namespace BinaryFraction + +private theorem rounded_action_congr {n M : ℕ} (e b : ℕ) + {first second : List (Fin M → TargetInterval n)} (h : first = second) + (hf : first ≠ []) (hs : second ≠ []) (initial : Fin M → TargetInterval n → ℚ) : + canonicalRoundedBandAction e b first hf initial = canonicalRoundedBandAction e b second hs initial := by + subst second + rfl + +def preparedUnskippedReadWithWork {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (b P exponent : ℕ) (hb : 0 < b) (hP : 0 < P) + (tau F : BinaryFraction) + (read initial : Fin M → TargetInterval target.length → BinaryFraction × ℕ) + (R C : ℕ) (hr : ∀ i q, (read i q).2 ≤ R) (hi : ∀ i q, (initial i q).2 ≤ C) + (center : TargetInterval target.length) : + Option (UnskippedBand source target parent b P exponent tau.value F.value + (fun i q => (read i q).1.value) (fun i q => (initial i q).1.value)) × ℕ := + let band := preparedRepresentativeReadWithWork parent center (parent.hi - parent.lo) b P + tau (inversePowerTwo exponent) read + if hband : band.1 = [] then (none, band.2 + 1) else + let wide := wideActionGridWithWork M parent center b P + let guard := unskippedGuardReadWithWork parent center b exponent F band.1 + (wide.1.map Vector.get) hband initial + if hguard : guard.1 = true then + let hg := (unskippedGuardReadWithWork_eq_cost parent center b exponent F band.1 + (wide.1.map Vector.get) hband initial C hi).1 + let facts := (unskippedGuardWithWork_value source target parent center b exponent F + band.1 (wide.1.map Vector.get) hband (fun i q => (initial i q).1) hb).mp (hg.symm.trans hguard) + let hbandValue : band.1 = representativeBandActions source target parent center b P tau.value + ((2 : ℚ) ^ (-(exponent : ℤ))) (fun i q => (read i q).1.value) := by + apply (preparedRepresentativeReadWithWork_eq_cost parent center (parent.hi - parent.lo) b P + tau (inversePowerTwo exponent) read R hr).1.trans + simpa only [inversePowerTwo_value] using preparedRepresentativeWithWork_value source target + parent center b P hP tau (inversePowerTwo exponent) (fun i q => (read i q).1) + let hwideValue : wide.1.map Vector.get = wideActionList M parent center b P := + wideActionGridWithWork_value M parent center b P hP + (some { + center := center + nonempty := fun hzero => hband (hbandValue.trans hzero) + sum_guard := by simpa only [hbandValue] using facts.1 + wide_guard := by + have hw := facts.2.1 + rw [hwideValue] at hw + rw [rounded_action_congr exponent b hbandValue hband _] at hw + exact hw + imbalance_guard := by simpa only [hbandValue] using facts.2.2 }, + band.2 + wide.2 + guard.2 + wide.1.length + 3) + else (none, band.2 + wide.2 + guard.2 + wide.1.length + 2) + +theorem preparedUnskippedReadWithWork_value {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (b P exponent : ℕ) (hb : 0 < b) (hP : 0 < P) + (tau F : BinaryFraction) + (read initial : Fin M → TargetInterval target.length → BinaryFraction × ℕ) + (R C : ℕ) (hr : ∀ i q, (read i q).2 ≤ R) (hi : ∀ i q, (initial i q).2 ≤ C) + (center : TargetInterval target.length) : + (preparedUnskippedReadWithWork source target parent b P exponent hb hP tau F read initial R C hr hi center).1 = + (preparedUnskippedCandidateWithWork source target parent b P exponent hb hP tau F + (fun i q => (read i q).1) (fun i q => (initial i q).1) center).1 := by + have hband := (preparedRepresentativeReadWithWork_eq_cost parent center (parent.hi - parent.lo) + b P tau (inversePowerTwo exponent) read R hr).1 + unfold preparedUnskippedReadWithWork preparedUnskippedCandidateWithWork + dsimp only + simp only [hband] + split_ifs with hempty hguard + · rfl + · rfl + · rename_i hplain + have hg := (unskippedGuardReadWithWork_eq_cost parent center b exponent F _ ((wideActionGridWithWork M parent center b P).1.map Vector.get) hempty initial C hi).1 + exact False.elim (hplain (hg.symm.trans hguard)) + · rename_i hplain + have hg := (unskippedGuardReadWithWork_eq_cost parent center b exponent F _ ((wideActionGridWithWork M parent center b P).1.map Vector.get) hempty initial C hi).1 + exact False.elim (hguard (hg.trans hplain)) + · rfl + + +theorem preparedUnskippedReadWithWork_cost {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (b P exponent : ℕ) (hb : 0 < b) (hP : 0 < P) + (tau F : BinaryFraction) + (read initial : Fin M → TargetInterval target.length → BinaryFraction × ℕ) + (R C : ℕ) (hr : ∀ i q, (read i q).2 ≤ R) (hi : ∀ i q, (initial i q).2 ≤ C) + (center : TargetInterval target.length) : + (preparedUnskippedReadWithWork source target parent b P exponent hb hP tau F read initial R C hr hi center).2 ≤ + (preparedUnskippedCandidateWithWork source target parent b P exponent hb hP tau F + (fun i q => (read i q).1) (fun i q => (initial i q).1) center).2 + + representativeReadOverhead M (wideActionGridWithWork M parent center b P).1.length R + + M * ((preparedRepresentativeWithWork parent center (parent.hi - parent.lo) b P + tau (inversePowerTwo exponent) (fun i q => (read i q).1)).1.length * (C + 3)) + + M * ((preparedRepresentativeWithWork parent center (parent.hi - parent.lo) b P + tau (inversePowerTwo exponent) (fun i q => (read i q).1)).1.length * (C + 3)) := by + have hband := preparedRepresentativeReadWithWork_eq_cost parent center (parent.hi - parent.lo) + b P tau (inversePowerTwo exponent) read R hr + unfold preparedUnskippedReadWithWork preparedUnskippedCandidateWithWork + dsimp only + simp only [hband.1] + by_cases hempty : (preparedRepresentativeWithWork parent center (parent.hi - parent.lo) + b P tau (inversePowerTwo exponent) (fun i q => (read i q).1)).1 = [] + · simp only [dite_eq_left hempty] + omega + · simp only [dite_eq_right hempty] + have hg := unskippedGuardReadWithWork_eq_cost parent center b exponent F + (preparedRepresentativeWithWork parent center (parent.hi - parent.lo) b P + tau (inversePowerTwo exponent) (fun i q => (read i q).1)).1 + ((wideActionGridWithWork M parent center b P).1.map Vector.get) hempty initial C hi + simp only [hg.1] + split_ifs <;> omega + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryUnskippedSpace.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryUnskippedSpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..3ed2af9bac314cf9177c77c60d74f771aba91786 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryUnskippedSpace.lean @@ -0,0 +1,106 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryRepresentativeSpace +import OAI.Combinatorics.EditApproximation.Binary.BinaryRoundingSpace +import OAI.Combinatorics.EditApproximation.Binary.BinaryUnskippedReads +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation.BinaryFraction + + + +theorem gapGuardAllocation_le_work {nx ny M : ℕ} (parent : TargetInterval nx) + (envelope : Vector BinaryFraction M) (rounded : Vector (TargetInterval ny) M) (i : Fin M) : + gapGuardAllocation parent envelope rounded i ≤ + (binaryNaturalSubtractWithWork (sourceChild parent i).hi (sourceChild parent i).lo).2 + + (stateGapWithWork (bitWordValue (binaryNaturalSubtractWithWork (sourceChild parent i).hi + (sourceChild parent i).lo).1) (rounded.get i)).2 + + (canonicalMulWithWork (nat 2) (envelope.get i)).2 + + (leWithWork (stateGapWithWork (bitWordValue (binaryNaturalSubtractWithWork (sourceChild parent i).hi + (sourceChild parent i).lo).1) (rounded.get i)).1.absolute + (canonicalMulWithWork (nat 2) (envelope.get i)).1).2 + 3 := by + have hs := bitSubtractAllocation_le_work (sourceChild parent i).hi.bits (sourceChild parent i).lo.bits false + have hg := stateGapAllocation_le_work + (bitWordValue (binaryNaturalSubtractWithWork (sourceChild parent i).hi (sourceChild parent i).lo).1) + (rounded.get i) + have hm := canonicalMulAllocation_le_work (nat 2) (envelope.get i) + have hl := leAllocation_le_work + (stateGapWithWork (bitWordValue (binaryNaturalSubtractWithWork (sourceChild parent i).hi + (sourceChild parent i).lo).1) (rounded.get i)).1.absolute + (canonicalMulWithWork (nat 2) (envelope.get i)).1 + unfold gapGuardAllocation + dsimp only + have hs' : bitSubtractAllocation (sourceChild parent i).hi.bits (sourceChild parent i).lo.bits false ≤ + (binaryNaturalSubtractWithWork (sourceChild parent i).hi (sourceChild parent i).lo).2 := hs + omega + + + +theorem unskippedGuardReadAllocation_le_work {nx ny M : ℕ} (parent : TargetInterval nx) + (center : TargetInterval ny) (b exponent : ℕ) (F : BinaryFraction) + (band wide : List (Fin M → TargetInterval ny)) (hne : band ≠ []) + (read : Fin M → TargetInterval ny → BinaryFraction × ℕ) + (allocation : Fin M → TargetInterval ny → ℕ) + (h : ∀ i q, allocation i q ≤ (read i q).2) : + unskippedGuardReadAllocation parent center b exponent F band wide hne read allocation ≤ + (unskippedGuardReadWithWork parent center b exponent F band wide hne read).2 := by + let envelope := (envelopeVectorReadWithWork b band read).1 + let rounded := (roundedBandReadWithWork exponent b band hne read).1 + have he := envelopeVectorReadAllocation_le_work b band read allocation (fun i action _ => h i (action i)) + have ht := bandMassAllocation_le_work envelope + have hf := canonicalMulAllocation_le_work F (nat b) + have hl := canonicalMulAllocation_le_work (nat 64) (canonicalMulWithWork F (nat b)).1 + have hs := leAllocation_le_work (bandMassTotalWithWork envelope).1 + (canonicalMulWithWork (nat 64) (canonicalMulWithWork F (nat b)).1).1 + have hr := roundedBandReadAllocation_le_work exponent b band hne read allocation h + have hw := actionMemberAllocation_le_work rounded.get wide + have hg := allAllocation_le_work (fun i => + let sourceLength := binaryNaturalSubtractWithWork (sourceChild parent i).hi (sourceChild parent i).lo + let gap := stateGapWithWork (bitWordValue sourceLength.1) (rounded.get i) + let bound := canonicalMulWithWork (nat 2) (envelope.get i) + let test := leWithWork gap.1.absolute bound.1 + (test.1, sourceLength.2 + gap.2 + bound.2 + test.2 + 3)) + (gapGuardAllocation parent envelope rounded) (List.finRange M) + (fun i _ => gapGuardAllocation_le_work parent envelope rounded i) + unfold unskippedGuardReadAllocation unskippedGuardReadWithWork + dsimp only [envelope, rounded] at ht hs hw hg ⊢ + omega + + + +theorem preparedUnskippedReadAllocation_le_work {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (center : TargetInterval target.length) + (b P exponent : ℕ) (hb : 0 < b) (hP : 0 < P) (tau F : BinaryFraction) + (read initial : Fin M → TargetInterval target.length → BinaryFraction × ℕ) + (readAllocation initialAllocation : Fin M → TargetInterval target.length → ℕ) + (R C : ℕ) (hr : ∀ i q, (read i q).2 ≤ R) (hi : ∀ i q, (initial i q).2 ≤ C) + (ha : ∀ i q, readAllocation i q ≤ (read i q).2) + (hinit : ∀ i q, initialAllocation i q ≤ (initial i q).2) : + preparedUnskippedReadAllocation parent center b P exponent tau F read initial readAllocation initialAllocation ≤ + (preparedUnskippedReadWithWork source target parent b P exponent hb hP tau F read initial R C hr hi center).2 := by + have costBound (a a' w w' g g' l k k' : ℕ) + (ha : a ≤ a') (hw : w ≤ w') (hg : g ≤ g') (hk : k ≤ k') : + a + (w + l + g + k) ≤ a' + w' + g' + l + k' := by + omega + have hbnd := preparedRepresentativeReadAllocation_le_work parent center (parent.hi - parent.lo) b P + tau (inversePowerTwo exponent) read readAllocation ha + have hw := wideActionGridAllocation_le_work M parent center b P + unfold preparedUnskippedReadAllocation preparedUnskippedReadWithWork + dsimp only + split_ifs with hband hguard + · exact Nat.add_le_add hbnd (by decide : 0 ≤ 1) + · have hg := unskippedGuardReadAllocation_le_work parent center b exponent F + (preparedRepresentativeReadWithWork parent center (parent.hi - parent.lo) b P tau (inversePowerTwo exponent) read).1 + ((wideActionGridWithWork M parent center b P).1.map Vector.get) hband initial initialAllocation hinit + dsimp only + exact costBound _ _ _ _ _ _ _ 3 3 hbnd hw hg (Nat.le_refl _) + · have hg := unskippedGuardReadAllocation_le_work parent center b exponent F + (preparedRepresentativeReadWithWork parent center (parent.hi - parent.lo) b P tau (inversePowerTwo exponent) read).1 + ((wideActionGridWithWork M parent center b P).1.map Vector.get) hband initial initialAllocation hinit + dsimp only + exact costBound _ _ _ _ _ _ _ 0 2 hbnd hw hg (by decide : 0 ≤ 2) + +end EditApproximation.BinaryFraction + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryUpdateWork.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryUpdateWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..d8ff4493e2a3811ce19e9a77ed355440ad940024 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryUpdateWork.lean @@ -0,0 +1,111 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryMaximizerWork + +namespace OAI + +/-! Bit cost of the actual coordinate update, including construction of +its rational step and complement. -/ + +namespace EditApproximation +namespace BinaryFraction + +def updateCoefficientWordBudget (K : ℕ) : ℕ := Nat.size (K + 2) + 8 + +def updateCoordinateWordBudget (K P : ℕ) : ℕ := P + 2 * updateCoefficientWordBudget K + 8 + +def optimizerUpdateBitBudget (d K P : ℕ) : ℕ := + 2100 * (Nat.size (K + 2) + 6) ^ 2 + + (6000 * (updateCoefficientWordBudget K + 4) ^ 2 + 1) + + d * (110000 * (updateCoordinateWordBudget K P + 1) ^ 2 + 6) + Nat.size (K + 2) + 4 + +theorem nat_width_le (n : ℕ) : (nat n).width ≤ Nat.size n + 2 := by + have h := nat_width_le_storageBits n + rw [nat_representation, UnreducedRational.storageBits_nat] at h + exact h + +theorem optimizerUpdateWithWork_cost {d : ℕ} (j K P : ℕ) (hj : j ≤ K) + (previous selected : Vector BinaryFraction d) + (hp : ∀ i, (previous.get i).width ≤ P) (hs : ∀ i, (selected.get i).width ≤ P) : + (optimizerUpdateWithWork j previous selected).2 ≤ optimizerUpdateBitBudget d K P := by + let step := divWithWork (nat 2) (nat (j + 2)) + let complement := subWithWork one step.1 + let C := updateCoefficientWordBudget K + let W := updateCoordinateWordBudget K P + have hsize := Nat.size_le_size (show j + 2 ≤ K + 2 by omega) + have htwo : Nat.size 2 = 2 := by decide + have hstep : step.1.width ≤ C := by + have hw := divWithWork_self_width (nat 2) (nat (j + 2)) + rw [divWithWork_representation, nat_representation, nat_representation] at hw + have hc := UnreducedRational.storageBits_div (UnreducedRational.nat 2) (UnreducedRational.nat (j + 2)) + rw [UnreducedRational.storageBits_nat, UnreducedRational.storageBits_nat] at hc + rw [htwo] at hc + change step.1.width ≤ _ at hw + dsimp only [C, updateCoefficientWordBudget] + omega + have hstepStorage : step.1.representation.storageBits ≤ C := by + change ((nat 2).divWithWork (nat (j + 2))).1.representation.storageBits ≤ _ + rw [divWithWork_representation, nat_representation, nat_representation] + have h := UnreducedRational.storageBits_div (UnreducedRational.nat 2) (UnreducedRational.nat (j + 2)) + simp only [UnreducedRational.storageBits_nat] at h + rw [htwo] at h + dsimp only [C, updateCoefficientWordBudget] + omega + have hcomp : complement.1.width ≤ 2 * C + 8 := by + have hw := canonicalAddWithWork_self_width one step.1.neg + change complement.1.width ≤ complement.1.representation.storageBits at hw + rw [subWithWork_representation, one_representation] at hw + have h := UnreducedRational.storageBits_sub UnreducedRational.one step.1.representation + rw [UnreducedRational.storageBits_one] at h + omega + have hcpos : 0 ≤ C := Nat.zero_le _ + have hleft (i : Fin d) := canonicalMulWithWork_cost complement.1 (previous.get i) W + (by dsimp only [W, updateCoordinateWordBudget]; omega) + (by dsimp only [W, updateCoordinateWordBudget]; have h := hp i; omega) + have hright (i : Fin d) := canonicalMulWithWork_cost step.1 (selected.get i) W + (by dsimp only [W, updateCoordinateWordBudget]; omega) + (by dsimp only [W, updateCoordinateWordBudget]; have h := hs i; omega) + have hleftw (i : Fin d) : (canonicalMulWithWork complement.1 (previous.get i)).1.width ≤ 4 * W + 2 := by + have hw := canonicalMulWithWork_width_le_storageBits complement.1 (previous.get i) + have hm := UnreducedRational.storageBits_mul complement.1.representation (previous.get i).representation + have hc := representation_storageBits_le complement.1 + have hi := representation_storageBits_le (previous.get i) + have hh := hp i + dsimp only [W, updateCoordinateWordBudget] + omega + have hrightw (i : Fin d) : (canonicalMulWithWork step.1 (selected.get i)).1.width ≤ 4 * W + 2 := by + have hw := canonicalMulWithWork_width_le_storageBits step.1 (selected.get i) + have hm := UnreducedRational.storageBits_mul step.1.representation (selected.get i).representation + have hc := representation_storageBits_le step.1 + have hi := representation_storageBits_le (selected.get i) + have hh := hs i + dsimp only [W, updateCoordinateWordBudget] + omega + have hcell (i : Fin d) : + (canonicalMulWithWork complement.1 (previous.get i)).2 + + (canonicalMulWithWork step.1 (selected.get i)).2 + + (canonicalAddWithWork (canonicalMulWithWork complement.1 (previous.get i)).1 + (canonicalMulWithWork step.1 (selected.get i)).1).2 + 4 ≤ + 110000 * (W + 1) ^ 2 := by + have ha := canonicalAddWithWork_cost (canonicalMulWithWork complement.1 (previous.get i)).1 + (canonicalMulWithWork step.1 (selected.get i)).1 (4 * W + 2) (hleftw i) (hrightw i) + nlinarith only [hleft i, hright i, ha, Nat.zero_le W] + have hmap := vectorMapWithWork_cost_le d (fun i => + let first := canonicalMulWithWork complement.1 (previous.get i) + let second := canonicalMulWithWork step.1 (selected.get i) + let total := canonicalAddWithWork first.1 second.1 + (total.1, first.2 + second.2 + total.2 + 4)) (110000 * (W + 1) ^ 2) hcell + have hn := nat_width_le (j + 2) + have ht : (nat 2).width ≤ Nat.size (K + 2) + 4 := by have h := nat_width_le 2; rw [htwo] at h; omega + have cstep := divWithWork_cost (nat 2) (nat (j + 2)) (Nat.size (K + 2) + 4) ht (by omega) + have ccomp := subWithWork_cost one step.1 (C + 3) + (by have h := one_width; omega) (by omega) + change step.2 + complement.2 + (vectorMapWithWork d _).2 + Nat.size (j + 2) + 4 ≤ _ + change _ ≤ 2100 * (Nat.size (K + 2) + 6) ^ 2 + (6000 * (C + 4) ^ 2 + 1) + + d * (110000 * (W + 1) ^ 2 + 6) + Nat.size (K + 2) + 4 + change step.2 ≤ _ at cstep + change complement.2 ≤ _ at ccomp + nlinarith only [cstep, ccomp, hmap, hsize] + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryWarmupAverage.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryWarmupAverage.lean new file mode 100644 index 0000000000000000000000000000000000000000..d1ee8df1ae82f25bca18d68deff63ed36ca92f87 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryWarmupAverage.lean @@ -0,0 +1,55 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryBandInputWork +import OAI.Combinatorics.EditApproximation.Binary.BinaryAffineGuard + +namespace OAI + +/-! The warmup mass used in band construction is computed from the gathered +warmup entries by a stored sum and one stored division. -/ + +namespace EditApproximation +namespace BinaryFraction + +def warmupAverageWithWork (values : List BinaryFraction) : BinaryFraction × ℕ := + let total := sumListWithWork values + let result := divWithWork total.1 (nat values.length) + (result.1, total.2 + result.2 + Nat.size values.length + 2) + +@[simp] theorem warmupAverageWithWork_value (values : List BinaryFraction) : + (warmupAverageWithWork values).1.value = (values.map value).sum / values.length := by + simp only [warmupAverageWithWork, divWithWork_value, sumListWithWork_value, nat_value] + +theorem warmupAverageWithWork_ofFn_value {T : ℕ} (values : Fin T → BinaryFraction) : + (warmupAverageWithWork (List.ofFn values)).1.value = (∑ i, (values i).value) / T := by + rw [warmupAverageWithWork_value, List.length_ofFn] + simp only [List.map_ofFn, List.sum_ofFn, Function.comp_def] + +def warmupAverageWordBudget (n B : ℕ) : ℕ := + 4 * (bandMassTotalStorageBudget n B + Nat.size n + 2) + 4 + +def warmupAverageBitBudget (n B : ℕ) : ℕ := + storedSumBitBudget n B + 6 * n + + 2100 * (bandMassTotalStorageBudget n B + Nat.size n + 4) ^ 2 + Nat.size n + 2 + +theorem warmupAverageWithWork_bounds (values : List BinaryFraction) (B : ℕ) + (hv : ∀ v ∈ values, v.width ≤ B) : + (warmupAverageWithWork values).1.width ≤ warmupAverageWordBudget values.length B ∧ + (warmupAverageWithWork values).2 ≤ warmupAverageBitBudget values.length B := by + have hs := sumListWithWork_width values B hv + have hc := sumListWithWork_cost values B hv + let W := bandMassTotalStorageBudget values.length B + Nat.size values.length + 2 + have hw : (sumListWithWork values).1.width ≤ W := hs.trans (by dsimp only [W]; omega) + have hn : (nat values.length).width ≤ W := (nat_width_le _).trans (by dsimp only [W]; omega) + have hd := divWithWork_width_uniform (sumListWithWork values).1 (nat values.length) W hw hn + have hdc := divWithWork_cost (sumListWithWork values).1 (nat values.length) W hw hn + refine ⟨hd, ?_⟩ + change (sumListWithWork values).2 + (divWithWork (sumListWithWork values).1 (nat values.length)).2 + + Nat.size values.length + 2 ≤ _ + unfold warmupAverageBitBudget + dsimp only [W] at hdc + simp only [Nat.add_assoc, Nat.reduceAdd] at hdc ⊢ + omega + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryWarmupReads.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryWarmupReads.lean new file mode 100644 index 0000000000000000000000000000000000000000..010a4a1eb2841c6af32a650eb0c82691c100f603 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryWarmupReads.lean @@ -0,0 +1,98 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryRepresentativeReads +import OAI.Combinatorics.EditApproximation.Binary.BinaryBellmanReads +import OAI.Combinatorics.EditApproximation.Binary.BinaryLocalWarmupKernel +import OAI.Combinatorics.EditApproximation.Binary.BinaryInitialReads +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! The warmup continuation evaluates finite input-table lookups and +charges their scan costs at the point where each returned word is used. -/ + +namespace EditApproximation +namespace BinaryFraction + + + +theorem localWarmupReadKernelWithWork_eq {nx ny M : ℕ} (parent : TargetInterval nx) + (N P F : ℕ) (a : BinaryFraction) (initial : TargetInterval ny → BinaryFraction × ℕ) + (child : Fin M × TargetInterval ny → BinaryFraction × ℕ) (query : TargetInterval ny) + (R : ℕ) (hR : ∀ r, (initial r).2 ≤ R) : + (localWarmupReadKernelWithWork parent N P F a initial child query).1 = + (localWarmupKernelWithWork parent N P F a (fun r => (initial r).1) + (fun input => (child input).1) query).1 := by + have hr := (localRepresentativeReadWithWork_eq_cost N P F a initial query R hR).1 + simp only [localWarmupReadKernelWithWork, localWarmupKernelWithWork, hr, bellmanReadWithWork_eq] + +theorem localWarmupReadKernelWithWork_cost {nx ny M : ℕ} (parent : TargetInterval nx) + (N P F : ℕ) (a : BinaryFraction) (initial : TargetInterval ny → BinaryFraction × ℕ) + (child : Fin M × TargetInterval ny → BinaryFraction × ℕ) (query : TargetInterval ny) + (I C : ℕ) (hi : ∀ r, (initial r).2 ≤ I) (hc : ∀ input, (child input).2 ≤ C) : + (localWarmupReadKernelWithWork parent N P F a initial child query).2 ≤ + (localWarmupKernelWithWork parent N P F a (fun r => (initial r).1) + (fun input => (child input).1) query).2 * (I + M * (C + 3) + 4) := by + let reps := localRepresentativesWithWork N P F a (fun r => (initial r).1) query + let acts := wideActionsFromRepresentativesWithWork M parent reps.1 P + let L := canonicalMulWithWork (nat 128) (nat F) + let result := bellmanWithWork endpointDistanceWithWork L.1 (initial query).1 + (fun input => (child input).1) query acts.1 + have hr := localRepresentativeReadWithWork_eq_cost N P F a initial query I hi + have hb := bellmanReadWithWork_cost endpointDistanceWithWork L.1 (initial query).1 + child query acts.1 C (fun action _ i => hc (action.childState i)) + have hn := bellmanWithWork_action_count endpointDistanceWithWork L.1 (initial query).1 + (fun input => (child input).1) query acts.1 + have hquery := hi query + have hr' : (localRepresentativeReadWithWork N P F a initial query).2 ≤ reps.2 * (I + 2) := hr.2 + have hb' : (bellmanReadWithWork endpointDistanceWithWork L.1 (initial query).1 + child query acts.1).2 ≤ result.2 + acts.1.length * (M * (C + 3)) := hb + have hn' : acts.1.length ≤ result.2 := hn + unfold localWarmupReadKernelWithWork + dsimp only + rw [hr.1] + change (initial query).2 + (localRepresentativeReadWithWork N P F a initial query).2 + + acts.2 + L.2 + (bellmanReadWithWork endpointDistanceWithWork L.1 (initial query).1 + child query acts.1).2 + 3 ≤ + (reps.2 + acts.2 + L.2 + result.2 + 3) * (I + M * (C + 3) + 4) + have hh := Nat.mul_le_mul_right (M * (C + 3)) hn' + have hrFactor := Nat.mul_le_mul_left reps.2 + (show I + 2 ≤ I + M * (C + 3) + 4 by omega) + have haFactor : acts.2 ≤ acts.2 * (I + M * (C + 3) + 4) := by + simpa only [Nat.mul_one] using Nat.mul_le_mul_left acts.2 + (show 1 ≤ I + M * (C + 3) + 4 by omega) + have hLFactor : L.2 ≤ L.2 * (I + M * (C + 3) + 4) := by + simpa only [Nat.mul_one] using Nat.mul_le_mul_left L.2 + (show 1 ≤ I + M * (C + 3) + 4 by omega) + have hresultFactor : result.2 + result.2 * (M * (C + 3)) ≤ + result.2 * (I + M * (C + 3) + 4) := by + calc + _ = result.2 * (1 + M * (C + 3)) := by ring + _ ≤ _ := Nat.mul_le_mul_left _ (by omega) + have hconstant : I + 3 ≤ 3 * (I + M * (C + 3) + 4) := by omega + nlinarith only [hr', hb', hquery, hh, hrFactor, haFactor, hLFactor, hresultFactor, hconstant] + +def cachedLocalWarmupReadWithWork {nx ny M : ℕ} (parent : TargetInterval nx) + (N P F : ℕ) (a : BinaryFraction) (initial : TargetInterval ny → BinaryFraction × ℕ) + (child : Fin M × TargetInterval ny → BinaryFraction × ℕ) (query : TargetInterval ny) : + BinaryFraction × ℕ := + finishCachedWithWork (localWarmupReadKernelWithWork parent N P F a initial child query) + [true] (by decide) 0 + +theorem cachedLocalWarmupReadWithWork_eq_cost {nx ny M : ℕ} (parent : TargetInterval nx) + (N P F : ℕ) (a : BinaryFraction) (initial : TargetInterval ny → BinaryFraction × ℕ) + (child : Fin M × TargetInterval ny → BinaryFraction × ℕ) (query : TargetInterval ny) + (I C : ℕ) (hi : ∀ r, (initial r).2 ≤ I) (hc : ∀ input, (child input).2 ≤ C) : + (cachedLocalWarmupReadWithWork parent N P F a initial child query).1 = + (cachedLocalWarmupKernelWithWork parent N P F a (fun r => (initial r).1) + (fun input => (child input).1) query).1 ∧ + (cachedLocalWarmupReadWithWork parent N P F a initial child query).2 ≤ + (cachedLocalWarmupKernelWithWork parent N P F a (fun r => (initial r).1) + (fun input => (child input).1) query).2 * (I + M * (C + 3) + 4) := by + exact finishCachedWithWork_read_factor _ _ [true] (by decide) 0 _ (by omega) + (localWarmupReadKernelWithWork_eq parent N P F a initial child query I hi) + (localWarmupReadKernelWithWork_cost parent N P F a initial child query I C hi hc) + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryWideActionsWork.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryWideActionsWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..c8c50ec00c3a4549feb00e1e08a611452778f211 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryWideActionsWork.lean @@ -0,0 +1,94 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryPhysicalContinuation +import OAI.Combinatorics.EditApproximation.Binary.BinaryPreparedRepresentativeWork + +namespace OAI + +/-! The full wide-action list materializes each grid and each connection +charge. Endpoint representation bounds follow from the interval subtype. -/ + +namespace EditApproximation +namespace BinaryFraction + +theorem endpointActionWithWork_bounds {n M : ℕ} (center : TargetInterval n) + (states : Fin M → TargetInterval n) (B : ℕ) (hn : Nat.size n + 2 ≤ B) : + (endpointActionWithWork center states).1.connection.width ≤ connectionWordBudget M B ∧ + (endpointActionWithWork center states).2 ≤ connectionBitBudget M B + 2 * B + 2 * M + 3 := by + have hlo : (nat center.lo).width ≤ B := (nat_width_le center.lo).trans + ((Nat.add_le_add_right (Nat.size_le_size (center.ordered.trans center.valid)) 2).trans hn) + have hhi : (nat center.hi).width ≤ B := (nat_width_le center.hi).trans + ((Nat.add_le_add_right (Nat.size_le_size center.valid) 2).trans hn) + have hs : ∀ q ∈ List.ofFn states, Nat.size q.lo + 2 ≤ B ∧ Nat.size q.hi + 2 ≤ B := by + intro q _ + exact ⟨(Nat.add_le_add_right (Nat.size_le_size (q.ordered.trans q.valid)) 2).trans hn, + (Nat.add_le_add_right (Nat.size_le_size q.valid) 2).trans hn⟩ + have hw := connectionWithWork_width (nat center.lo) (nat center.hi) (List.ofFn states) B hlo hhi hs + have hc := connectionWithWork_cost (nat center.lo) (nat center.hi) (List.ofFn states) B hlo hhi hs + simp only [List.length_ofFn] at hw hc + constructor + · exact hw + · have hlo' := (Nat.size_le_size (center.ordered.trans center.valid)).trans (show Nat.size n ≤ B by omega) + have hhi' := (Nat.size_le_size center.valid).trans (show Nat.size n ≤ B by omega) + change (connectionWithWork (nat center.lo) (nat center.hi) (List.ofFn states)).2 + + Nat.size center.lo + Nat.size center.hi + M + 2 + M + 1 ≤ _ + omega + +def wideActionsBitBudget (M P count B : ℕ) : ℕ := + let V := (40 * P + 2) ^ (2 * M) + count * (wideMaterializationBitBudget M P B + + V * (connectionBitBudget M B + 2 * B + 2 * M + 6) + 1 + V + 3) + +theorem wideActionsFromRepresentativesWithWork_bounds {nx ny M : ℕ} + (parent : TargetInterval nx) (representatives : List (ℕ × TargetInterval ny)) (P B : ℕ) + (hPpos : 0 < P) (hnx : Nat.size nx ≤ B) (hny : Nat.size ny + 2 ≤ B) + (hM : Nat.size M ≤ B) (hP : Nat.size P ≤ B) + (hrep : ∀ br ∈ representatives, Nat.size br.1 ≤ B) : + (wideActionsFromRepresentativesWithWork M parent representatives P).1.length ≤ + representatives.length * (40 * P + 2) ^ (2 * M) ∧ + (∀ action ∈ (wideActionsFromRepresentativesWithWork M parent representatives P).1, + action.connection.width ≤ connectionWordBudget M B) ∧ + (wideActionsFromRepresentativesWithWork M parent representatives P).2 ≤ + wideActionsBitBudget M P representatives.length B := by + let V := (40 * P + 2) ^ (2 * M) + let callback := fun br : ℕ × TargetInterval ny => + let grids := wideActionGridWithWork M parent br.2 br.1 P + let actions := arithmeticMapWithWork (fun states => endpointActionWithWork br.2 states.get) grids.1 + (actions.1, grids.2 + actions.2 + 1) + have hlen (br : ℕ × TargetInterval ny) : (wideActionGridWithWork M parent br.2 br.1 P).1.length ≤ V := by + have hh := congrArg List.length (wideActionGridWithWork_value M parent br.2 br.1 P hPpos) + simp only [List.length_map] at hh + rw [hh] + exact wideActionList_length_le M parent br.2 br.1 P hPpos + have hc (br : ℕ × TargetInterval ny) (hbr : br ∈ representatives) : + (callback br).2 ≤ wideMaterializationBitBudget M P B + + V * (connectionBitBudget M B + 2 * B + 2 * M + 6) + 1 := by + have hg := wideActionGridWithWork_complete_cost M parent br.2 br.1 P B hPpos hnx + (by omega) hM (hrep br hbr) hP + have hm := arithmeticMapWithWork_cost + (fun states : Vector (TargetInterval ny) M => endpointActionWithWork br.2 states.get) + (wideActionGridWithWork M parent br.2 br.1 P).1 + (connectionBitBudget M B + 2 * B + 2 * M + 3) + (fun states _ => (endpointActionWithWork_bounds br.2 states.get B hny).2) + have hm' := hm.trans (Nat.mul_le_mul_right _ (hlen br)) + change (wideActionGridWithWork M parent br.2 br.1 P).2 + _ + 1 ≤ _ + simp only [Nat.add_assoc, Nat.reduceAdd] at hm' ⊢ + omega + have hl (br : ℕ × TargetInterval ny) : (callback br).1.length ≤ V := by + simpa only [callback, arithmeticMapWithWork_value, List.length_map] using hlen br + have hcost := arithmeticFlatMapWithWork_cost callback representatives + (wideMaterializationBitBudget M P B + V * (connectionBitBudget M B + 2 * B + 2 * M + 6) + 1) + V hc (fun br _ => hl br) + have hlength : (representatives.flatMap (fun br => (callback br).1)).length ≤ representatives.length * V := + list_flatMap_length_le representatives (fun br => (callback br).1) V (fun br _ => hl br) + refine ⟨?_, ?_, hcost⟩ + · simpa only [wideActionsFromRepresentativesWithWork, arithmeticFlatMapWithWork_value] using hlength + · intro action ha + simp only [wideActionsFromRepresentativesWithWork, arithmeticFlatMapWithWork_value, + arithmeticMapWithWork_value] at ha + obtain ⟨br, _, ha⟩ := List.mem_flatMap.mp ha + obtain ⟨states, _, rfl⟩ := List.mem_map.mp ha + exact (endpointActionWithWork_bounds br.2 states.get B hny).1 + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryWideChildWork.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryWideChildWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..333d90e18dca313b4a28d4d54e0e5bc5f0b1d222 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryWideChildWork.lean @@ -0,0 +1,111 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryWideGridWork + +namespace OAI + +/-! Every child-grid list is constructed before the Cartesian product. +These bounds include the balanced endpoints, integer spacing and radius, +endpoint translations, and the two bounded grid loops. -/ + +namespace EditApproximation + +theorem seedGridSpacingWithWork_bounds (b P B : ℕ) + (hb : Nat.size b ≤ B) (hP : Nat.size P ≤ B) : + (seedGridSpacingWithWork b P).1.length ≤ B + 1 ∧ + (seedGridSpacingWithWork b P).2 ≤ 100 * (B + 2) ^ 2 := by + let quotient := binaryNaturalDivModWithWork b P + have hl := (bitDivModWithWork_lengths P.bits b.bits).1 + change quotient.1.length = b.bits.length at hl + rw [Nat.size_eq_bits_len] at hl + have hd := binaryNaturalDivModWithWork_cost b P + have ht := wordLEWithWork_cost quotient.1 [true] + change quotient.2.2 ≤ _ at hd + simp only [List.length_cons, List.length_nil] at ht + unfold seedGridSpacingWithWork + dsimp only + constructor + · split_ifs + · simp only [List.length_cons, List.length_nil] + omega + · change quotient.1.length ≤ B + 1 + omega + · change quotient.2.2 + (wordLEWithWork quotient.1 [true]).2 + 2 ≤ _ + nlinarith only [hd, ht, hl, hb, hP, Nat.zero_le B] + +theorem gridStateBoxBitBudget_mono_count (k l B : ℕ) (h : k ≤ l) : + gridStateBoxBitBudget k B ≤ gridStateBoxBitBudget l B := by + unfold gridStateBoxBitBudget gridPointsBitBudget + gcongr + +def wideChildGridBitBudget (P B : ℕ) : ℕ := + 10000 * (B + 12) ^ 2 + gridStateBoxBitBudget (40 * P + 2) (B + 12) + +theorem wideChildGridWithWork_cost {nx ny M : ℕ} (parent : TargetInterval nx) + (r : TargetInterval ny) (b P B : ℕ) (i : Fin M) (hPpos : 0 < P) + (hnx : Nat.size nx ≤ B) (hny : Nat.size ny ≤ B) + (hM : Nat.size M ≤ B) (hb : Nat.size b ≤ B) (hP : Nat.size P ≤ B) : + (wideChildGridWithWork parent r b P i).2 ≤ wideChildGridBitBudget P B := by + let child := sourceChildWithWork parent i + let spacing := seedGridSpacingWithWork b P + let radius := binaryNaturalMulWithWork 10 b + let leftOffset := saturatingSubtractWithWork child.1.lo parent.lo + let rightOffset := saturatingSubtractWithWork child.1.hi parent.lo + let left := binaryNaturalAddWithWork r.lo (bitWordValue leftOffset.1) + let right := binaryNaturalAddWithWork r.lo (bitWordValue rightOffset.1) + have hparent : Nat.size parent.lo ≤ B := + (Nat.size_le_size (parent.ordered.trans parent.valid)).trans hnx + have hcl : Nat.size child.1.lo ≤ B := + (Nat.size_le_size (child.1.ordered.trans child.1.valid)).trans hnx + have hch : Nat.size child.1.hi ≤ B := (Nat.size_le_size child.1.valid).trans hnx + have hrlo : Nat.size r.lo ≤ B := (Nat.size_le_size (r.ordered.trans r.valid)).trans hny + have hlo : Nat.size (bitWordValue leftOffset.1) ≤ B := by + rw [saturatingSubtractWithWork_value] + exact (Nat.size_le_size (Nat.sub_le _ _)).trans hcl + have hro : Nat.size (bitWordValue rightOffset.1) ≤ B := by + rw [saturatingSubtractWithWork_value] + exact (Nat.size_le_size (Nat.sub_le _ _)).trans hch + have hleft : Nat.size (bitWordValue left.1) ≤ B + 2 := by + rw [binaryNaturalAddWithWork_value] + exact (binaryNaturalAdd_size_le _ _).trans (by omega) + have hright : Nat.size (bitWordValue right.1) ≤ B + 2 := by + rw [binaryNaturalAddWithWork_value] + exact (binaryNaturalAdd_size_le _ _).trans (by omega) + have hspacing := seedGridSpacingWithWork_bounds b P B hb hP + have hspacingCost : spacing.2 ≤ 100 * (B + 2) ^ 2 := hspacing.2 + have hgs : Nat.size (bitWordValue spacing.1) ≤ B + 1 := + (Nat.size_le.mpr (bitWordValue_lt_pow_length spacing.1)).trans hspacing.1 + have hrl := bitMulWithWork_length (10 : ℕ).bits b.bits + change radius.1.length ≤ _ at hrl + simp only [Nat.size_eq_bits_len] at hrl + have hten : Nat.size 10 = 4 := by decide + rw [hten] at hrl + have hrs : Nat.size (bitWordValue radius.1) ≤ B + 9 := + (Nat.size_le.mpr (bitWordValue_lt_pow_length radius.1)).trans (by omega) + have hg := seedGridSpacingWithWork_pos b P hPpos + have hgrid := gridStateBoxWithWork_cost ny (bitWordValue spacing.1) (bitWordValue radius.1) + (bitWordValue left.1) (bitWordValue right.1) (B + 12) hg + (by omega) (by omega) (by omega) (by omega) (by omega) + have hcount : 2 * bitWordValue radius.1 / bitWordValue spacing.1 + 2 ≤ 40 * P + 2 := by + rw [binaryNaturalMulWithWork_value, seedGridSpacingWithWork_value b P hPpos] + simpa only [show 2 * (10 * b) = 20 * b by omega] using seedGridSpacing_radius_count b P hPpos + have hgrid' := hgrid.trans (gridStateBoxBitBudget_mono_count _ _ (B + 12) hcount) + have hc := sourceChildWithWork_cost parent i B hnx hM + have hrad := binaryNaturalMulWithWork_cost 10 b + have hol := saturatingSubtractWithWork_cost child.1.lo parent.lo + have hor := saturatingSubtractWithWork_cost child.1.hi parent.lo + have hal := binaryNaturalAddWithWork_cost r.lo (bitWordValue leftOffset.1) + have har := binaryNaturalAddWithWork_cost r.lo (bitWordValue rightOffset.1) + change child.2 ≤ _ at hc + change radius.2 ≤ _ at hrad + change leftOffset.2 ≤ _ at hol + change rightOffset.2 ≤ _ at hor + change left.2 ≤ _ at hal + change right.2 ≤ _ at har + rw [hten] at hrad + change child.2 + spacing.2 + radius.2 + leftOffset.2 + rightOffset.2 + left.2 + right.2 + _ + 8 ≤ _ + unfold wideChildGridBitBudget + nlinarith only [hc, hspacingCost, hrad, hol, hor, hal, har, hgrid', hcl, hch, hparent, + hrlo, hlo, hro, hb, Nat.zero_le B] + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryWideGrid.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryWideGrid.lean new file mode 100644 index 0000000000000000000000000000000000000000..f47d7f1ad6481b06f495f68db88163c12fcc7901 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryWideGrid.lean @@ -0,0 +1,79 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryScaleGrid +import OAI.Combinatorics.EditApproximation.Binary.BinaryGradientWork +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Actual wide-action materialization starts from binary balanced cuts and +bounded endpoint grids. The Cartesian-product routine receives the lists +just computed, so their construction is included in the counter. -/ + +namespace EditApproximation + + + +@[simp] theorem balancedCutWithWork_value (lo width M i : ℕ) (hM : 0 < M) : + bitWordValue (balancedCutWithWork lo width M i).1 = balancedCut lo width M i := by + simp only [balancedCutWithWork, binaryNaturalAddWithWork_value, + (binaryNaturalDivModWithWork_spec _ M hM).1, binaryNaturalMulWithWork_value, balancedCut] + + + +@[simp] theorem sourceChildWithWork_value {n M : ℕ} (parent : TargetInterval n) (i : Fin M) : + (sourceChildWithWork parent i).1 = sourceChild parent i := by + have hl : (sourceChildWithWork parent i).1.lo = (sourceChild parent i).lo := by + simp only [sourceChildWithWork, balancedCutWithWork_value _ _ _ _ (Nat.zero_lt_of_lt i.isLt), + saturatingSubtractWithWork_value, sourceChild] + have hh : (sourceChildWithWork parent i).1.hi = (sourceChild parent i).hi := by + simp only [sourceChildWithWork, balancedCutWithWork_value _ _ _ _ (Nat.zero_lt_of_lt i.isLt), + saturatingSubtractWithWork_value, binaryNaturalAddWithWork_value, sourceChild] + generalize heq : (sourceChildWithWork parent i).1 = first at hl hh ⊢ + generalize hother : sourceChild parent i = second at hl hh ⊢ + cases first + cases second + cases hl + cases hh + rfl + + + +@[simp] theorem wideChildGridWithWork_value {nx ny M : ℕ} (parent : TargetInterval nx) + (r : TargetInterval ny) (b P : ℕ) (i : Fin M) (hP : 0 < P) : + (wideChildGridWithWork parent r b P i).1 = wideChildStateList parent r b P i := by + simp only [wideChildGridWithWork, sourceChildWithWork_value, + seedGridSpacingWithWork_value b P hP, binaryNaturalMulWithWork_value, + saturatingSubtractWithWork_value, binaryNaturalAddWithWork_value, wideChildStateList] + apply gridStateBoxWithWork_value + unfold seedGridSpacing + omega + + + +@[simp] theorem wideActionGridWithWork_value {nx ny : ℕ} (M : ℕ) (parent : TargetInterval nx) + (r : TargetInterval ny) (b P : ℕ) (hP : 0 < P) : + ((wideActionGridWithWork M parent r b P).1.map Vector.get) = wideActionList M parent r b P := by + have hchoices : (vectorMapWithWork M (wideChildGridWithWork parent r b P)).1.get = + wideChildStateList parent r b P := by + funext i + rw [vectorMapWithWork_value, wideChildGridWithWork_value _ _ _ _ _ hP] + simp only [wideActionGridWithWork, materializedAssignmentsWithWork_value, hchoices, wideActionList] + +theorem wideActionGridWithWork_cost {nx ny : ℕ} (M : ℕ) (parent : TargetInterval nx) + (r : TargetInterval ny) (b P C : ℕ) (hP : 0 < P) + (hc : ∀ i : Fin M, (wideChildGridWithWork parent r b P i).2 ≤ C) : + (wideActionGridWithWork M parent r b P).2 ≤ + M * (C + 6) + (M + 1) * (6 * M + 10) * ((40 * P + 2) ^ 2 + 1) ^ (M + 1) + 1 := by + let choices := vectorMapWithWork M (wideChildGridWithWork parent r b P) + have hm := BinaryFraction.vectorMapWithWork_cost_le M (wideChildGridWithWork parent r b P) C hc + have hchoice (i : Fin M) : (choices.1.get i).length ≤ (40 * P + 2) ^ 2 := by + simp only [choices, vectorMapWithWork_value, wideChildGridWithWork_value _ _ _ _ _ hP] + exact wideChildStateList_length_le parent r hP i + have hp := materializedAssignmentsWithWork_cost M ((40 * P + 2) ^ 2) choices.1.get hchoice + change choices.2 ≤ _ at hm + change choices.2 + (materializedAssignmentsWithWork M choices.1.get).2 + 1 ≤ _ + omega + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryWideGridWork.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryWideGridWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..b611a3a29d1e5b3339b85f402ef6bfc882dedbc0 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryWideGridWork.lean @@ -0,0 +1,66 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryWideGrid +import OAI.Combinatorics.EditApproximation.Binary.BinaryLocalGridWork + +namespace OAI + +/-! Polynomial per-child bit work before the explicitly counted Cartesian +product. All interval endpoints and arities are bounded by their input +word sizes; no good-seed premise occurs in these bounds. -/ + +namespace EditApproximation + +theorem balancedCutWithWork_cost (lo width M i B : ℕ) (hM : 0 < M) + (hl : Nat.size lo ≤ B) (hw : Nat.size width ≤ B) + (hm : Nat.size M ≤ B) (hi : Nat.size i ≤ B) : + (balancedCutWithWork lo width M i).2 ≤ 1000 * (B + 1) ^ 2 := by + let product := binaryNaturalMulWithWork i width + let quotient := binaryNaturalDivModWithWork (bitWordValue product.1) M + have hp := binaryNaturalMulWithWork_cost i width + have hpl := bitMulWithWork_length i.bits width.bits + have hps : Nat.size (bitWordValue product.1) ≤ 3 * B + 1 := by + have hv : Nat.size (bitWordValue product.1) ≤ product.1.length := + Nat.size_le.mpr (bitWordValue_lt_pow_length _) + change product.1.length ≤ _ at hpl + simp only [Nat.size_eq_bits_len] at hpl + omega + have hq := binaryNaturalDivModWithWork_cost (bitWordValue product.1) M + have hqs : Nat.size (bitWordValue quotient.1) ≤ 3 * B + 1 := by + rw [(binaryNaturalDivModWithWork_spec _ M hM).1] + exact (Nat.size_le_size (Nat.div_le_self _ _)).trans hps + have ha := binaryNaturalAddWithWork_cost lo (bitWordValue quotient.1) + change product.2 + quotient.2.2 + (binaryNaturalAddWithWork lo (bitWordValue quotient.1)).2 + 2 ≤ _ + nlinarith only [hp, hq, ha, hps, hqs, hl, hw, hm, hi, Nat.zero_le B] + +theorem sourceChildWithWork_cost {n M : ℕ} (parent : TargetInterval n) (i : Fin M) + (B : ℕ) (hn : Nat.size n ≤ B) (hm : Nat.size M ≤ B) : + (sourceChildWithWork parent i).2 ≤ 2200 * (B + 3) ^ 2 := by + have hlo := (Nat.size_le_size (parent.ordered.trans parent.valid)).trans hn + have hhi := (Nat.size_le_size parent.valid).trans hn + have hi := (Nat.size_le_size i.isLt.le).trans hm + let width := saturatingSubtractWithWork parent.hi parent.lo + let next := binaryNaturalAddWithWork i.val 1 + have hwidth : Nat.size (bitWordValue width.1) ≤ B := by + rw [saturatingSubtractWithWork_value] + exact (Nat.size_le_size (Nat.sub_le _ _)).trans hhi + have hnext : Nat.size (bitWordValue next.1) ≤ B + 2 := by + rw [binaryNaturalAddWithWork_value] + have h := binaryNaturalAdd_size_le i.val 1 + simp only [Nat.size_one] at h + have hMpos : 1 ≤ Nat.size M := Nat.size_pos.mpr (Nat.zero_lt_of_lt i.isLt) + omega + have hleft := balancedCutWithWork_cost parent.lo (bitWordValue width.1) M i.val (B + 2) + (Nat.zero_lt_of_lt i.isLt) (by omega) (by omega) (by omega) (by omega) + have hright := balancedCutWithWork_cost parent.lo (bitWordValue width.1) M + (bitWordValue next.1) (B + 2) (Nat.zero_lt_of_lt i.isLt) + (by omega) (by omega) (by omega) hnext + have hsub := saturatingSubtractWithWork_cost parent.hi parent.lo + have hadd := binaryNaturalAddWithWork_cost i.val 1 + change width.2 + next.2 + _ + _ + 4 ≤ _ + change width.2 ≤ _ at hsub + change next.2 ≤ _ at hadd + simp only [Nat.size_one] at hadd + nlinarith only [hleft, hright, hsub, hadd, hlo, hhi, hi, Nat.zero_le B] + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryWideSpace.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryWideSpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..02465e89b3f44d661a9ba98a41870b46390f004b --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BinaryWideSpace.lean @@ -0,0 +1,111 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryGridSpace +import OAI.Combinatorics.EditApproximation.Binary.BinaryOptimizerSpace +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation + + + +theorem balancedCutAllocation_le_work (lo width M i : ℕ) : + balancedCutAllocation lo width M i ≤ (balancedCutWithWork lo width M i).2 := by + have hm := binaryNaturalMulAllocation_le_work i width + have hd := binaryNaturalDivAllocation_le_work (bitWordValue (binaryNaturalMulWithWork i width).1) M + have ha := binaryNaturalAddAllocation_le_work lo + (bitWordValue (binaryNaturalDivModWithWork (bitWordValue (binaryNaturalMulWithWork i width).1) M).1) + unfold balancedCutAllocation balancedCutWithWork + dsimp only + omega + + + +theorem sourceChildAllocation_le_work {n M : ℕ} (parent : TargetInterval n) (i : Fin M) : + sourceChildAllocation parent i ≤ (sourceChildWithWork parent i).2 := by + have hw := saturatingSubtractAllocation_le_work parent.hi parent.lo + have hn := binaryNaturalAddAllocation_le_work i.val 1 + have hl := balancedCutAllocation_le_work parent.lo + (bitWordValue (saturatingSubtractWithWork parent.hi parent.lo).1) M i.val + have hr := balancedCutAllocation_le_work parent.lo + (bitWordValue (saturatingSubtractWithWork parent.hi parent.lo).1) M + (bitWordValue (binaryNaturalAddWithWork i.val 1).1) + unfold sourceChildAllocation sourceChildWithWork + dsimp only + omega + + + +theorem seedGridSpacingAllocation_le_work (b P : ℕ) : + seedGridSpacingAllocation b P ≤ (seedGridSpacingWithWork b P).2 := by + have hd := binaryNaturalDivAllocation_le_work b P + have hl := naturalWordLEAllocation_le_work (binaryNaturalDivModWithWork b P).1 [true] + unfold seedGridSpacingAllocation seedGridSpacingWithWork + dsimp only + omega + + + +theorem wideChildGridAllocation_le_work {nx ny M : ℕ} (parent : TargetInterval nx) + (r : TargetInterval ny) (b P : ℕ) (i : Fin M) : + wideChildGridAllocation parent r b P i ≤ (wideChildGridWithWork parent r b P i).2 := by + let child := (sourceChildWithWork parent i).1 + let spacing := (seedGridSpacingWithWork b P).1 + let radius := (binaryNaturalMulWithWork 10 b).1 + let leftOffset := (saturatingSubtractWithWork child.lo parent.lo).1 + let rightOffset := (saturatingSubtractWithWork child.hi parent.lo).1 + let left := (binaryNaturalAddWithWork r.lo (bitWordValue leftOffset)).1 + let right := (binaryNaturalAddWithWork r.lo (bitWordValue rightOffset)).1 + have h1 := sourceChildAllocation_le_work parent i + have h2 := seedGridSpacingAllocation_le_work b P + have h3 := binaryNaturalMulAllocation_le_work 10 b + have h4 := saturatingSubtractAllocation_le_work child.lo parent.lo + have h5 := saturatingSubtractAllocation_le_work child.hi parent.lo + have h6 := binaryNaturalAddAllocation_le_work r.lo (bitWordValue leftOffset) + have h7 := binaryNaturalAddAllocation_le_work r.lo (bitWordValue rightOffset) + have h8 := gridStateBoxAllocation_le_work ny (bitWordValue spacing) (bitWordValue radius) + (bitWordValue left) (bitWordValue right) + unfold wideChildGridAllocation wideChildGridWithWork + dsimp only [child, spacing, radius, leftOffset, rightOffset, left, right] at h4 h5 h6 h7 h8 ⊢ + omega + +/-- Allocations of every prefix Cartesian product, including the actual +output vector cells and the nested map/concatenation spines. -/ + + +theorem materializedAssignmentsAllocation_le_work {α : Type*} (M : ℕ) (choices : Fin M → List α) : + materializedAssignmentsAllocation M choices ≤ (materializedAssignmentsWithWork M choices).2 := by + induction M with + | zero => rfl + | succ M ih => + let previous := (materializedAssignmentsWithWork M (fun i => choices i.succ)).1 + let build := fun head => arithmeticMapWithWork (fun tail : Vector α M => + (Vector.ofFn (Fin.cons head tail.get), 3 * (M + 1))) previous + have hp := ih (fun i => choices i.succ) + have hm := arithmeticFlatMapAllocation_le_work build + (fun _ => arithmeticMapAllocation (fun _ : Vector α M => M + 1) previous) (choices 0) (by + intro head _ + exact arithmeticMapAllocation_le_work _ _ previous (fun _ _ => by dsimp only; omega)) + change materializedAssignmentsAllocation M (fun i => choices i.succ) + + arithmeticFlatMapAllocation build + (fun _ => arithmeticMapAllocation (fun _ : Vector α M => M + 1) previous) (choices 0) ≤ + (materializedAssignmentsWithWork M (fun i => choices i.succ)).2 + + (arithmeticFlatMapWithWork build (choices 0)).2 + 1 + omega + + + +theorem wideActionGridAllocation_le_work {nx ny : ℕ} (M : ℕ) (parent : TargetInterval nx) + (r : TargetInterval ny) (b P : ℕ) : + wideActionGridAllocation M parent r b P ≤ (wideActionGridWithWork M parent r b P).2 := by + have hc := vectorMapAllocation_le_work M (wideChildGridWithWork parent r b P) + (wideChildGridAllocation parent r b P) (wideChildGridAllocation_le_work parent r b P) + have hp := materializedAssignmentsAllocation_le_work M + (vectorMapWithWork M (wideChildGridWithWork parent r b P)).1.get + unfold wideActionGridAllocation wideActionGridWithWork + dsimp only + omega + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BitAllocation.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BitAllocation.lean new file mode 100644 index 0000000000000000000000000000000000000000..44d181b1a28aa5f8afa4702d2fdcf2f52b2b2f94 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BitAllocation.lean @@ -0,0 +1,126 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryDivisionWork +import OAI.Combinatorics.EditApproximation.Binary.BinaryCanonicalWork +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Fresh Boolean-list cells allocated by the literal arithmetic routines. +Input tails are shared. Counts include discarded intermediate lists, so they +also bound the cells simultaneously live during evaluation. -/ + +namespace EditApproximation + + + + + +theorem bitAddAllocation_le_work (left right : List Bool) (carry : Bool) : + bitAddAllocation left right carry ≤ (bitAddWithWork left right carry).2 := by + induction left generalizing right carry with + | nil => + simp only [bitAddAllocation, bitAddWithWork] + induction right generalizing carry with + | nil => cases carry <;> simp [bitAddNilLeftAllocation, bitAddNilLeftWithWork] + | cons b bs ih => + have h := ih (bitCarry false b carry) + simp only [bitAddNilLeftAllocation, bitAddNilLeftWithWork] + omega + | cons a as ih => + cases right with + | nil => + have h := ih [] (bitCarry a false carry) + simp only [bitAddAllocation, bitAddWithWork] + omega + | cons b bs => + have h := ih bs (bitCarry a b carry) + simp only [bitAddAllocation, bitAddWithWork] + omega + + + + + +theorem bitSubtractAllocation_le_work (left right : List Bool) (borrow : Bool) : + bitSubtractAllocation left right borrow ≤ (bitSubtractWithWork left right borrow).2.2 := by + induction left generalizing right borrow with + | nil => + simp only [bitSubtractAllocation, bitSubtractWithWork] + induction right generalizing borrow with + | nil => simp [bitSubtractNilLeftAllocation, bitSubtractNilLeftWithWork] + | cons b bs ih => + have h := ih (bitBorrow false b borrow) + simp only [bitSubtractNilLeftAllocation, bitSubtractNilLeftWithWork] + omega + | cons a as ih => + cases right with + | nil => + have h := ih [] (bitBorrow a false borrow) + simp only [bitSubtractAllocation, bitSubtractWithWork] + omega + | cons b bs => + have h := ih bs (bitBorrow a b borrow) + simp only [bitSubtractAllocation, bitSubtractWithWork] + omega + + + +theorem bitMulAllocation_le_work (left right : List Bool) : + bitMulAllocation left right ≤ (bitMulWithWork left right).2 := by + induction left with + | nil => simp [bitMulAllocation, bitMulWithWork] + | cons bit bits ih => + have h := bitAddAllocation_le_work (false :: (bitMulWithWork bits right).1) right false + cases bit <;> simp only [bitMulAllocation, bitMulWithWork, Bool.false_eq_true, ↓reduceIte] <;> + omega + + + +theorem trimBitWordAllocation_le_work (bits : List Bool) : + trimBitWordAllocation bits ≤ (trimBitWordWithWork bits).2 := by + induction bits with + | nil => simp [trimBitWordAllocation, trimBitWordWithWork] + | cons bit bits ih => + simp only [trimBitWordAllocation, trimBitWordWithWork] + split_ifs <;> omega + +/-- Each division step allocates one candidate cell and one quotient cell, +plus the fresh subtraction result exactly when subtraction is executed. -/ + + +theorem bitDivModAllocation_le_work (divisor bits : List Bool) : + bitDivModAllocation divisor bits ≤ (bitDivModWithWork divisor bits).2.2 := by + induction bits with + | nil => simp [bitDivModAllocation, bitDivModWithWork] + | cons bit bits ih => + have h := bitSubtractAllocation_le_work + (bit :: (bitDivModWithWork divisor bits).2.1) divisor false + simp only [bitDivModAllocation, bitDivModWithWork] + split_ifs <;> dsimp only <;> omega + +/-- Comparison allocates no Boolean-list cells. The recursive frames have +height at most the explicitly charged work counter. -/ +theorem bitCompare_recursion_le_work (left right : List Bool) : + max left.length right.length + 1 ≤ (bitCompareWithWork left right).2 := by + induction left generalizing right with + | nil => + simp only [bitCompareWithWork] + induction right with + | nil => simp [bitCompareNilLeftWithWork] + | cons b bs ih => + simp only [bitCompareNilLeftWithWork, List.length_nil, List.length_cons, Nat.zero_max] at * + omega + | cons a as ih => + cases right with + | nil => + have h := ih [] + simp only [bitCompareWithWork, List.length_nil, List.length_cons, Nat.max_zero] at * + omega + | cons b bs => + have h := ih bs + simp only [bitCompareWithWork, List.length_cons, Nat.succ_max_succ] + omega + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BitControlSpace.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BitControlSpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..93332d68a9ffee3e9575f9f441352a13329e1694 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BitControlSpace.lean @@ -0,0 +1,132 @@ +import OAI.Combinatorics.EditApproximation.Numerics.ScalarAllocation + +namespace OAI + +/-! Invocation counts for literal Boolean routines. An active call stack is a +subset of these invocations. Each frame has a fixed number of bit/word/pointer +fields, so these bounds complement (rather than replace) fresh-array storage. -/ + +namespace EditApproximation + +def bitAddInvocations : List Bool → List Bool → Bool → ℕ + | [], [], _ => 1 + | a :: as, [], carry => bitAddInvocations as [] (bitCarry a false carry) + 1 + | [], b :: bs, carry => bitAddInvocations [] bs (bitCarry false b carry) + 1 + | a :: as, b :: bs, carry => bitAddInvocations as bs (bitCarry a b carry) + 1 + +theorem bitAddInvocations_le_work (left right : List Bool) (carry : Bool) : + bitAddInvocations left right carry ≤ (bitAddWithWork left right carry).2 := by + induction left generalizing right carry with + | nil => + simp only [bitAddWithWork] + induction right generalizing carry with + | nil => simp [bitAddInvocations, bitAddNilLeftWithWork] + | cons b bs ih => + have h := ih (bitCarry false b carry) + simp only [bitAddInvocations, bitAddNilLeftWithWork] + omega + | cons a as ih => + cases right with + | nil => + have h := ih [] (bitCarry a false carry) + simp only [bitAddInvocations, bitAddWithWork] + omega + | cons b bs => + have h := ih bs (bitCarry a b carry) + simp only [bitAddInvocations, bitAddWithWork] + omega + +def bitSubtractInvocations : List Bool → List Bool → Bool → ℕ + | [], [], _ => 1 + | a :: as, [], borrow => bitSubtractInvocations as [] (bitBorrow a false borrow) + 1 + | [], b :: bs, borrow => bitSubtractInvocations [] bs (bitBorrow false b borrow) + 1 + | a :: as, b :: bs, borrow => bitSubtractInvocations as bs (bitBorrow a b borrow) + 1 + +theorem bitSubtractInvocations_le_work (left right : List Bool) (borrow : Bool) : + bitSubtractInvocations left right borrow ≤ (bitSubtractWithWork left right borrow).2.2 := by + induction left generalizing right borrow with + | nil => + simp only [bitSubtractWithWork] + induction right generalizing borrow with + | nil => simp [bitSubtractInvocations, bitSubtractNilLeftWithWork] + | cons b bs ih => + have h := ih (bitBorrow false b borrow) + simp only [bitSubtractInvocations, bitSubtractNilLeftWithWork] + omega + | cons a as ih => + cases right with + | nil => + have h := ih [] (bitBorrow a false borrow) + simp only [bitSubtractInvocations, bitSubtractWithWork] + omega + | cons b bs => + have h := ih bs (bitBorrow a b borrow) + simp only [bitSubtractInvocations, bitSubtractWithWork] + omega + +def bitCompareInvocations (left right : List Bool) : ℕ := max left.length right.length + 1 + +theorem bitCompareInvocations_le_work (left right : List Bool) : + bitCompareInvocations left right ≤ (bitCompareWithWork left right).2 := + bitCompare_recursion_le_work left right + +def bitMulInvocations : List Bool → List Bool → ℕ + | [], _ => 1 + | bit :: bits, right => + bitMulInvocations bits right + 1 + + if bit then bitAddInvocations (false :: (bitMulWithWork bits right).1) right false else 0 + +theorem bitMulInvocations_le_work (left right : List Bool) : + bitMulInvocations left right ≤ (bitMulWithWork left right).2 := by + induction left with + | nil => rfl + | cons bit bits ih => + have h := bitAddInvocations_le_work (false :: (bitMulWithWork bits right).1) right false + cases bit <;> simp only [bitMulInvocations, bitMulWithWork, Bool.false_eq_true, ↓reduceIte] <;> omega + +def trimBitWordInvocations (bits : List Bool) : ℕ := bits.length + 1 + +theorem trimBitWordInvocations_le_work (bits : List Bool) : + trimBitWordInvocations bits ≤ (trimBitWordWithWork bits).2 := by + rw [trimBitWordWithWork_cost] + unfold trimBitWordInvocations + omega + +def bitDivModInvocations (divisor : List Bool) : List Bool → ℕ + | [] => 1 + | bit :: bits => + let candidate := bit :: (bitDivModWithWork divisor bits).2.1 + bitDivModInvocations divisor bits + bitCompareInvocations candidate divisor + 1 + + if (bitCompareWithWork candidate divisor).1 = .lt then 0 + else bitSubtractInvocations candidate divisor false + +theorem bitDivModInvocations_le_work (divisor bits : List Bool) : + bitDivModInvocations divisor bits ≤ (bitDivModWithWork divisor bits).2.2 := by + induction bits with + | nil => rfl + | cons bit bits ih => + have hc := bitCompareInvocations_le_work (bit :: (bitDivModWithWork divisor bits).2.1) divisor + have hs := bitSubtractInvocations_le_work (bit :: (bitDivModWithWork divisor bits).2.1) divisor false + simp only [bitDivModInvocations, bitDivModWithWork] + split_ifs <;> dsimp only <;> omega + +def bitPowerInvocations (base : List Bool) : ℕ → ℕ + | 0 => 1 + | n + 1 => + let previous := (bitPowerWithWork base n).1 + bitPowerInvocations base n + bitMulInvocations previous base + + trimBitWordInvocations (bitMulWithWork previous base).1 + 1 + +theorem bitPowerInvocations_le_work (base : List Bool) (n : ℕ) : + bitPowerInvocations base n ≤ (bitPowerWithWork base n).2 := by + induction n with + | zero => rfl + | succ n ih => + have hm := bitMulInvocations_le_work (bitPowerWithWork base n).1 base + have ht := trimBitWordInvocations_le_work (bitMulWithWork (bitPowerWithWork base n).1 base).1 + simp only [bitPowerInvocations, bitPowerWithWork] + omega + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BitMemoHeap.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BitMemoHeap.lean new file mode 100644 index 0000000000000000000000000000000000000000..4906b7ff16a4d850c08a61a01a0734f8976ca8fe --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BitMemoHeap.lean @@ -0,0 +1,108 @@ +import OAI.Combinatorics.EditApproximation.Binary.BitQuerySpace +import OAI.Combinatorics.EditApproximation.Binary.BitRankedMemo +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! A cumulative allocation counter for the actual memo execution. It keeps +all local allocations until the entire run finishes, so it also bounds peak +space. A read retains three continuation/result cells. Each memo call reserves +its address workspace, key bits, traversal frames and the possible new trie +path; existing values and input words are shared by reference. -/ + +namespace EditApproximation +namespace BitQuery.Heap + +def runCells {ι κ : Type*} + (ask : ι → BinaryMemo BinaryFraction → BitRecursiveMemoResult κ) + (childCells : ι → BinaryMemo BinaryFraction → ℕ) + {program : BitQuery ι BinaryFraction} : Heap program → BinaryMemo BinaryFraction → ℕ + | .done _, _ => 0 + | .read key _ continuation, memory => + let first := ask key memory + 3 + childCells key memory + (continuation first.value).runCells ask childCells first.memory + | .charge cells _ next, memory => cells + next.runCells ask childCells memory + +theorem runCells_le {ι κ : Type*} + (ask : ι → BinaryMemo BinaryFraction → BitRecursiveMemoResult κ) + (childCells : ι → BinaryMemo BinaryFraction → ℕ) (D : ℕ) + (hchild : ∀ key memory, childCells key memory + 3 ≤ + 3 * (ask key memory).localWork + D * (ask key memory).requests) + {program : BitQuery ι BinaryFraction} (heap : Heap program) + (memory : BinaryMemo BinaryFraction) : + heap.runCells ask childCells memory ≤ + 3 * (BitQuery.runMemo ask program memory).localWork + + D * (BitQuery.runMemo ask program memory).requests := by + induction heap generalizing memory with + | done value => simp only [runCells, BitQuery.runMemo, Nat.mul_zero, Nat.add_zero, le_refl] + | charge cells bound next ih => + have h := ih memory + simp only [runCells, BitQuery.runMemo] + omega + | read key next continuation ih => + have hc := hchild key memory + have hr := ih (ask key memory).value (ask key memory).memory + simp only [runCells, BitQuery.runMemo, Nat.mul_add] + omega + +end BitQuery.Heap + +/-- Sixteen scalar/frame slots suffice in addition to eight slots per key +bit and the supplied address-construction workspace; the larger fixed reserve +also covers the result record and the empty-trie case. -/ + + +def rankedBitMemoCells {κ : Type*} (rank : κ → ℕ) + (program : (key : κ) → BitQuery {child : κ // rank child < rank key} BinaryFraction) + (heap : ∀ key, BitQuery.Heap (program key)) + (bits : ℕ) (encode addressCells : κ → ℕ) (key : κ) (memory : BinaryMemo BinaryFraction) : ℕ := + let found := memory.lookupCosted (binaryMemoKey bits (encode key)) + match found.1 with + | some _ => memoRequestCells bits (addressCells key) + | none => memoRequestCells bits (addressCells key) + (heap key).runCells + (fun child previous => rankedBitMemoEvaluate rank program bits encode child.val previous) + (fun child previous => rankedBitMemoCells rank program heap bits encode addressCells child.val previous) + memory +termination_by rank key +decreasing_by exact child.property + +theorem rankedBitMemoCells_le {κ : Type*} (rank : κ → ℕ) + (program : (key : κ) → BitQuery {child : κ // rank child < rank key} BinaryFraction) + (heap : ∀ key, BitQuery.Heap (program key)) + (bits : ℕ) (encode addressCells : κ → ℕ) (A : ℕ) + (haddress : ∀ key, addressCells key ≤ A) (key : κ) (memory : BinaryMemo BinaryFraction) : + rankedBitMemoCells rank program heap bits encode addressCells key memory + 3 ≤ + 3 * (rankedBitMemoEvaluate rank program bits encode key memory).localWork + + (memoRequestCells bits A + 3) * (rankedBitMemoEvaluate rank program bits encode key memory).requests := by + have hall : ∀ level key, rank key = level → ∀ memory, + rankedBitMemoCells rank program heap bits encode addressCells key memory + 3 ≤ + 3 * (rankedBitMemoEvaluate rank program bits encode key memory).localWork + + (memoRequestCells bits A + 3) * (rankedBitMemoEvaluate rank program bits encode key memory).requests := by + intro level + induction level using Nat.strong_induction_on with + | h level ih => + intro key hlevel memory + have ha : memoRequestCells bits (addressCells key) ≤ memoRequestCells bits A := by + unfold memoRequestCells + exact Nat.add_le_add_right (Nat.add_le_add_right (haddress key) _) _ + rw [rankedBitMemoCells, rankedBitMemoEvaluate] + dsimp only + cases hf : (memory.lookupCosted (binaryMemoKey bits (encode key))).1 with + | some value => + simp only [Nat.mul_zero, Nat.mul_one, Nat.zero_add] + omega + | none => + have hc (child : {child : κ // rank child < rank key}) previous := + ih (rank child.val) (hlevel ▸ child.property) child.val rfl previous + have hr := BitQuery.Heap.runCells_le + (fun child previous => rankedBitMemoEvaluate rank program bits encode child.val previous) + (fun child previous => rankedBitMemoCells rank program heap bits encode addressCells child.val previous) + (memoRequestCells bits A + 3) hc (heap key) memory + simp only [Nat.mul_add, Nat.mul_one] + omega + exact hall (rank key) key rfl memory + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BitMemoMap.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BitMemoMap.lean new file mode 100644 index 0000000000000000000000000000000000000000..32303f6649b40e904e251c15762e317fb740ec19 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BitMemoMap.lean @@ -0,0 +1,47 @@ +import OAI.Combinatorics.EditApproximation.Binary.BitQuery + +namespace OAI + +/-! A proof-only view of a binary-word memo as its rational-value memo. +The tree shape and every lookup/insertion path are preserved. -/ + +namespace EditApproximation +namespace BinaryMemo + +def mapValues {α β : Type*} (f : α → β) : BinaryMemo α → BinaryMemo β + | .empty => .empty + | .node v l r => .node (v.map f) (mapValues f l) (mapValues f r) + +@[simp] theorem mapValues_value {α β : Type*} (f : α → β) (tree : BinaryMemo α) : + (tree.mapValues f).value = tree.value.map f := by cases tree <;> rfl + +@[simp] theorem mapValues_left {α β : Type*} (f : α → β) (tree : BinaryMemo α) : + (tree.mapValues f).left = tree.left.mapValues f := by cases tree <;> rfl + +@[simp] theorem mapValues_right {α β : Type*} (f : α → β) (tree : BinaryMemo α) : + (tree.mapValues f).right = tree.right.mapValues f := by cases tree <;> rfl + +@[simp] theorem mapValues_lookup {α β : Type*} (f : α → β) (tree : BinaryMemo α) (key : List Bool) : + (tree.mapValues f).lookup key = (tree.lookup key).map f := by + induction key generalizing tree with + | nil => exact mapValues_value f tree + | cons bit rest ih => cases bit <;> simp only [lookup, mapValues_left, mapValues_right, ih] + +@[simp] theorem mapValues_insert {α β : Type*} (f : α → β) (tree : BinaryMemo α) + (key : List Bool) (value : α) : + (tree.insert key value).mapValues f = (tree.mapValues f).insert key (f value) := by + induction key generalizing tree with + | nil => simp only [insert, mapValues, mapValues_left, mapValues_right, Option.map_some] + | cons bit rest ih => + cases bit <;> simp only [insert, mapValues, ih, mapValues_value, mapValues_left, mapValues_right] + +@[simp] theorem mapValues_nodes {α β : Type*} (f : α → β) (tree : BinaryMemo α) : + (tree.mapValues f).nodes = tree.nodes := by + induction tree with + | empty => rfl + | node v l r ihl ihr => simp only [mapValues, nodes, ihl, ihr] + +end BinaryMemo +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BitMemoOn.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BitMemoOn.lean new file mode 100644 index 0000000000000000000000000000000000000000..fabbef7de64a2dcba378098fbdc5a64d308f7565 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BitMemoOn.lean @@ -0,0 +1,47 @@ +import OAI.Combinatorics.EditApproximation.Binary.BitQueryOn + +namespace OAI + +/-! Reachable-oracle simulation retains the exact memo trace while allowing +local output normalization justified by the actual grid invariant. -/ + +namespace EditApproximation.BitQuery + +theorem runMemo_decode_on {ι κ : Type*} (oracle : ι → BinaryFraction) + (invariant : BinaryMemo BinaryFraction → Prop) + (ask : ι → BinaryMemo BinaryFraction → BitRecursiveMemoResult κ) + (expectedAsk : ι → BinaryMemo ℚ → RecursiveMemoResult κ) + (hask : ∀ key memory, invariant memory → + (ask key memory).value = oracle key ∧ invariant (ask key memory).memory ∧ + (ask key memory).decode = expectedAsk key (memory.mapValues BinaryFraction.value)) + {program : BitQuery ι BinaryFraction} {expected : FiniteQuery ι} + (h : RefinesOn oracle (fun word value => word.value = value) program expected) + (memory : BinaryMemo BinaryFraction) (hmemory : invariant memory) : + (runMemo ask program memory).decode = + FiniteQuery.run expectedAsk expected (memory.mapValues BinaryFraction.value) ∧ + invariant (runMemo ask program memory).memory := by + induction h generalizing memory with + | done h => + exact ⟨by simp only [runMemo, FiniteQuery.run, BitRecursiveMemoResult.decode, h], hmemory⟩ + | charge steps h ih => exact ih memory hmemory + | read key next expected h ih => + have hf := hask key memory hmemory + have hvalue := congrArg RecursiveMemoResult.value hf.2.2 + have hmem := congrArg RecursiveMemoResult.memory hf.2.2 + have hfresh := congrArg RecursiveMemoResult.freshKeys hf.2.2 + have hdict := congrArg RecursiveMemoResult.dictionaryVisits hf.2.2 + have hrequests := congrArg RecursiveMemoResult.requests hf.2.2 + have hr := ih (ask key memory).memory hf.2.1 + rw [← hf.1] at hr + refine ⟨?_, hr.2⟩ + unfold runMemo FiniteQuery.run + dsimp only + unfold BitRecursiveMemoResult.decode at hvalue hmem hfresh hdict hrequests hr ⊢ + simp only at hvalue hmem hfresh hdict hrequests + rw [hvalue, hmem] at hr + rw [← hr.1] + simp only [hfresh, hdict, hrequests] + +end EditApproximation.BitQuery + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BitMemoRun.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BitMemoRun.lean new file mode 100644 index 0000000000000000000000000000000000000000..0a2587cfa59057c0ac5a6d16aaf6258ffb814029 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BitMemoRun.lean @@ -0,0 +1,57 @@ +import OAI.Combinatorics.EditApproximation.Binary.BitMemoMap +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Execution of charged adaptive queries on actual binary-word memos. +The rational view is used only to prove preservation of the +memo trace; Boolean local work is retained as an additional counter. -/ + +namespace EditApproximation + + + +def BitRecursiveMemoResult.decode {κ : Type*} (result : BitRecursiveMemoResult κ) : + RecursiveMemoResult κ := + ⟨result.value.value, result.memory.mapValues BinaryFraction.value, + result.freshKeys, result.dictionaryVisits, result.requests⟩ + +namespace BitQuery + + + +theorem runMemo_decode {ι κ : Type*} + (ask : ι → BinaryMemo BinaryFraction → BitRecursiveMemoResult κ) + (expectedAsk : ι → BinaryMemo ℚ → RecursiveMemoResult κ) + (hask : ∀ key memory, (ask key memory).decode = + expectedAsk key (memory.mapValues BinaryFraction.value)) + {program : BitQuery ι BinaryFraction} {expected : FiniteQuery ι} + (h : Refines (fun word value => word.value = value) program expected) + (memory : BinaryMemo BinaryFraction) : + (runMemo ask program memory).decode = + FiniteQuery.run expectedAsk expected (memory.mapValues BinaryFraction.value) := by + induction h generalizing memory with + | done h => + simp only [runMemo, FiniteQuery.run, BitRecursiveMemoResult.decode, h] + | charge steps h ih => exact ih memory + | read key next expected h ih => + have hf := hask key memory + have hvalue := congrArg RecursiveMemoResult.value hf + have hmemory := congrArg RecursiveMemoResult.memory hf + have hfresh := congrArg RecursiveMemoResult.freshKeys hf + have hdict := congrArg RecursiveMemoResult.dictionaryVisits hf + have hrequests := congrArg RecursiveMemoResult.requests hf + have hr := ih (ask key memory).value (ask key memory).memory + unfold runMemo FiniteQuery.run + dsimp only + unfold BitRecursiveMemoResult.decode at hvalue hmemory hfresh hdict hrequests hr ⊢ + simp only at hvalue hmemory hfresh hdict hrequests + rw [hvalue, hmemory] at hr + rw [← hr] + simp only [hfresh, hdict, hrequests] + +end BitQuery +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BitMemoSound.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BitMemoSound.lean new file mode 100644 index 0000000000000000000000000000000000000000..80694c77b937fc4df8249cb1ee3b74fe29377e67 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BitMemoSound.lean @@ -0,0 +1,109 @@ +import OAI.Combinatorics.EditApproximation.Binary.BitRankedMemo +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Memo hits return the same concrete binary word as the deterministic +rank-decreasing program. This stronger invariant also fixes the local +arithmetic work on repeated reads, independently of cache history. -/ + +namespace EditApproximation + +def bitMemoSound {κ : Type*} (bits : ℕ) (encode : κ → ℕ) + (expected : κ → BinaryFraction) (memory : BinaryMemo BinaryFraction) : Prop := + ∀ key value, memory.lookup (binaryMemoKey bits (encode key)) = some value → value = expected key + + +theorem bitMemoSound_empty {κ : Type*} (bits : ℕ) (encode : κ → ℕ) + (expected : κ → BinaryFraction) : bitMemoSound bits encode expected .empty := by + intro key value hvalue + rw [BinaryMemo.lookup_empty] at hvalue + cases hvalue + +namespace BitQuery + +theorem runMemo_sound {ι κ : Type*} (answer : ι → BinaryFraction) + (invariant : BinaryMemo BinaryFraction → Prop) + (ask : ι → BinaryMemo BinaryFraction → BitRecursiveMemoResult κ) + (hask : ∀ key memory, invariant memory → + (ask key memory).value = answer key ∧ invariant (ask key memory).memory) + (program : BitQuery ι BinaryFraction) (memory : BinaryMemo BinaryFraction) + (hmemory : invariant memory) : + (runMemo ask program memory).value = program.value answer ∧ + invariant (runMemo ask program memory).memory := by + induction program generalizing memory with + | done result => exact ⟨rfl, hmemory⟩ + | charge steps next ih => exact ih memory hmemory + | read key next ih => + have hf := hask key memory hmemory + have hr := ih (ask key memory).value (ask key memory).memory hf.2 + exact ⟨by simpa only [runMemo, value, hf.1] using hr.1, hr.2⟩ + +end BitQuery + + + +theorem bitMemoSound_insert {κ : Type*} (bits : ℕ) (encode : κ → ℕ) + (hinjective : Function.Injective encode) (hbounded : ∀ key, encode key < 2 ^ bits) + (expected : κ → BinaryFraction) (memory : BinaryMemo BinaryFraction) + (hmemory : bitMemoSound bits encode expected memory) (key : κ) : + bitMemoSound bits encode expected + (memory.insert (binaryMemoKey bits (encode key)) (expected key)) := by + intro other value hvalue + rw [binaryMemo_lookup_insert _ bits (encode key) (encode other) (hbounded key) (hbounded other)] at hvalue + split_ifs at hvalue with heq + · have hk := hinjective heq + subst other + exact Option.some.inj hvalue.symm + · exact hmemory other value hvalue + +theorem rankedBitMemoEvaluate_sound {κ : Type*} (rank : κ → ℕ) + (program : (key : κ) → BitQuery {child : κ // rank child < rank key} BinaryFraction) + (bits : ℕ) (encode : κ → ℕ) (hinjective : Function.Injective encode) + (hbounded : ∀ key, encode key < 2 ^ bits) (key : κ) (memory : BinaryMemo BinaryFraction) + (hmemory : bitMemoSound bits encode (rankedBitProgramValue rank program) memory) : + (rankedBitMemoEvaluate rank program bits encode key memory).value = rankedBitProgramValue rank program key ∧ + bitMemoSound bits encode (rankedBitProgramValue rank program) + (rankedBitMemoEvaluate rank program bits encode key memory).memory := by + have hall : ∀ level key, rank key = level → ∀ memory, + bitMemoSound bits encode (rankedBitProgramValue rank program) memory → + (rankedBitMemoEvaluate rank program bits encode key memory).value = rankedBitProgramValue rank program key ∧ + bitMemoSound bits encode (rankedBitProgramValue rank program) + (rankedBitMemoEvaluate rank program bits encode key memory).memory := by + intro level + induction level using Nat.strong_induction_on with + | h level ih => + intro key hlevel memory hmem + rw [rankedBitMemoEvaluate] + simp only [BinaryMemo.lookupCosted_spec] + split + · rename_i result hresult + exact ⟨hmem key result hresult, hmem⟩ + · have hchildren : ∀ (child : {child : κ // rank child < rank key}) previous, + bitMemoSound bits encode (rankedBitProgramValue rank program) previous → + (rankedBitMemoEvaluate rank program bits encode child.val previous).value = + rankedBitProgramValue rank program child.val ∧ + bitMemoSound bits encode (rankedBitProgramValue rank program) + (rankedBitMemoEvaluate rank program bits encode child.val previous).memory := by + intro child previous hp + exact ih (rank child.val) (hlevel ▸ child.property) child.val rfl previous hp + have hr := BitQuery.runMemo_sound + (fun child : {child : κ // rank child < rank key} => rankedBitProgramValue rank program child.val) + (bitMemoSound bits encode (rankedBitProgramValue rank program)) + (fun child previous => rankedBitMemoEvaluate rank program bits encode child.val previous) + hchildren (program key) memory hmem + have hv : (BitQuery.runMemo + (fun child previous => rankedBitMemoEvaluate rank program bits encode child.val previous) + (program key) memory).value = rankedBitProgramValue rank program key := by + rw [rankedBitProgramValue] + exact hr.1 + simp only [BinaryMemo.insertCosted_spec] + refine ⟨hv, ?_⟩ + rw [hv] + exact bitMemoSound_insert bits encode hinjective hbounded _ _ hr.2 key + exact hall (rank key) key rfl memory hmemory + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BitMemoStorage.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BitMemoStorage.lean new file mode 100644 index 0000000000000000000000000000000000000000..33f687dbd60eca6e709259a279d0f37a3679d13f --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BitMemoStorage.lean @@ -0,0 +1,110 @@ +import OAI.Combinatorics.EditApproximation.Binary.BitMemoSound +import OAI.Combinatorics.EditApproximation.Geometry.RankedMemoStorage +import OAI.Combinatorics.EditApproximation.Binary.BinaryMemoSpace +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Storage of the actual binary-word memo. Node paths are identical to +the rational evaluator, while stored numerator/denominator bits are +bounded using the deterministic returned-word invariant. -/ + +namespace EditApproximation +namespace BinaryMemo + + + +theorem fractionStorage_le (memory : BinaryMemo BinaryFraction) (B : ℕ) + (hmem : AllValues (fun word => word.width ≤ B) memory) : + memory.fractionStorage ≤ (2 * B + 4) * memory.nodes := by + induction memory with + | empty => simp only [fractionStorage, nodes, Nat.mul_zero, le_refl] + | node word left right ihl ihr => + have hl : AllValues (fun word => word.width ≤ B) left := by + intro key value h + exact hmem (false :: key) value h + have hr : AllValues (fun word => word.width ≤ B) right := by + intro key value h + exact hmem (true :: key) value h + have hw : (word.map fun w => w.numerator.bits.length + w.denominator.length + 1).getD 0 ≤ 2 * B + 1 := by + cases word with + | none => exact Nat.zero_le _ + | some word => + have h := hmem [] word rfl + have hn := (le_max_left word.numerator.bits.length word.denominator.length).trans h + have hd := (le_max_right word.numerator.bits.length word.denominator.length).trans h + change _ + _ + 1 ≤ _ + omega + have hleft := ihl hl + have hright := ihr hr + simp only [fractionStorage, nodes] + nlinarith only [hw, hleft, hright] + +end BinaryMemo + +theorem rankedBitMemoEvaluate_widths {κ : Type*} (rank : κ → ℕ) + (program : (key : κ) → BitQuery {child : κ // rank child < rank key} BinaryFraction) + (bits : ℕ) (encode : κ → ℕ) (hinjective : Function.Injective encode) + (hbounded : ∀ key, encode key < 2 ^ bits) (B : ℕ) + (hwidth : ∀ key, (rankedBitProgramValue rank program key).width ≤ B) + (key : κ) (memory : BinaryMemo BinaryFraction) + (hsound : bitMemoSound bits encode (rankedBitProgramValue rank program) memory) + (hmem : BinaryMemo.AllValues (fun word => word.width ≤ B) memory) : + BinaryMemo.AllValues (fun word => word.width ≤ B) + (rankedBitMemoEvaluate rank program bits encode key memory).memory := by + have hall : ∀ level key, rank key = level → ∀ memory, + bitMemoSound bits encode (rankedBitProgramValue rank program) memory → + BinaryMemo.AllValues (fun word => word.width ≤ B) memory → + BinaryMemo.AllValues (fun word => word.width ≤ B) + (rankedBitMemoEvaluate rank program bits encode key memory).memory := by + intro level + induction level using Nat.strong_induction_on with + | h level ih => + intro key hlevel memory hs hm + rw [rankedBitMemoEvaluate] + simp only [BinaryMemo.lookupCosted_spec] + split + · exact hm + · have hchildren : ∀ (child : {child : κ // rank child < rank key}) previous, + bitMemoSound bits encode (rankedBitProgramValue rank program) previous ∧ + BinaryMemo.AllValues (fun word => word.width ≤ B) previous → + (rankedBitMemoEvaluate rank program bits encode child.val previous).value = + rankedBitProgramValue rank program child.val ∧ + (bitMemoSound bits encode (rankedBitProgramValue rank program) + (rankedBitMemoEvaluate rank program bits encode child.val previous).memory ∧ + BinaryMemo.AllValues (fun word => word.width ≤ B) + (rankedBitMemoEvaluate rank program bits encode child.val previous).memory) := by + intro child previous hp + have hv := rankedBitMemoEvaluate_sound rank program bits encode hinjective hbounded child.val previous hp.1 + exact ⟨hv.1, hv.2, ih (rank child.val) (hlevel ▸ child.property) child.val rfl previous hp.1 hp.2⟩ + have hr := BitQuery.runMemo_sound + (fun child : {child : κ // rank child < rank key} => rankedBitProgramValue rank program child.val) + (fun previous => bitMemoSound bits encode (rankedBitProgramValue rank program) previous ∧ + BinaryMemo.AllValues (fun word => word.width ≤ B) previous) + (fun child previous => rankedBitMemoEvaluate rank program bits encode child.val previous) + hchildren (program key) memory ⟨hs, hm⟩ + have hv : (BitQuery.runMemo + (fun child previous => rankedBitMemoEvaluate rank program bits encode child.val previous) + (program key) memory).value = rankedBitProgramValue rank program key := by + rw [rankedBitProgramValue] + exact hr.1 + simp only [BinaryMemo.insertCosted_spec] + exact hr.2.2.insert _ _ (hv.symm ▸ hwidth key) + exact hall (rank key) key rfl memory hsound hmem + +theorem rankedBitMemoEvaluate_nodes_bound {κ : Type*} (rank : κ → ℕ) + (program : (key : κ) → BitQuery {child : κ // rank child < rank key} BinaryFraction) + (expected : (key : κ) → FiniteQuery {child : κ // rank child < rank key}) + (hprogram : ∀ key, BitQuery.Refines (fun word value => word.value = value) + (program key) (expected key)) (bits : ℕ) (encode : κ → ℕ) (key : κ) : + (rankedBitMemoEvaluate rank program bits encode key .empty).memory.nodes + 1 ≤ 2 ^ (bits + 1) := by + have h := congrArg (fun result : RecursiveMemoResult κ => result.memory.nodes) + (rankedBitMemoEvaluate_decode rank program expected hprogram bits encode key .empty) + simp only [BitRecursiveMemoResult.decode, BinaryMemo.mapValues_nodes, BinaryMemo.mapValues] at h + rw [h] + exact rankedMemoEvaluate_nodes_bound rank expected bits encode key + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BitMemoWork.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BitMemoWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..0bcc9f728901a3f7cf7456fffdb72a3a9de462b3 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BitMemoWork.lean @@ -0,0 +1,88 @@ +import OAI.Combinatorics.EditApproximation.Binary.BitMemoSound +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! The binary memo's local-work counter is exactly the intrinsic Boolean +work summed over actual cache misses. Recursive calls and cache hits do +not trigger a second charge for a previously computed local body. -/ + +namespace EditApproximation +namespace BitQuery + +theorem runMemo_work_eq {ι κ : Type*} (answer : ι → BinaryFraction) + (invariant : BinaryMemo BinaryFraction → Prop) + (ask : ι → BinaryMemo BinaryFraction → BitRecursiveMemoResult κ) (weight : κ → ℕ) + (hsound : ∀ key memory, invariant memory → + (ask key memory).value = answer key ∧ invariant (ask key memory).memory) + (hwork : ∀ key memory, invariant memory → + (ask key memory).localWork = ((ask key memory).freshKeys.map weight).sum) + (program : BitQuery ι BinaryFraction) (memory : BinaryMemo BinaryFraction) + (hmemory : invariant memory) : + (runMemo ask program memory).localWork = program.work answer (fun _ => 0) + + ((runMemo ask program memory).freshKeys.map weight).sum := by + induction program generalizing memory with + | done result => rfl + | charge steps next ih => + simp only [runMemo, work] + rw [ih memory hmemory] + omega + | read key next ih => + have hf := hsound key memory hmemory + have hw := hwork key memory hmemory + have hr := ih (ask key memory).value (ask key memory).memory hf.2 + simp only [runMemo, work, List.map_append, List.sum_append, Nat.zero_add] + rw [hw, hr, hf.1] + omega + +end BitQuery + + + +theorem rankedBitMemoEvaluate_localWork {κ : Type*} (rank : κ → ℕ) + (program : (key : κ) → BitQuery {child : κ // rank child < rank key} BinaryFraction) + (bits : ℕ) (encode : κ → ℕ) (hinjective : Function.Injective encode) + (hbounded : ∀ key, encode key < 2 ^ bits) (key : κ) (memory : BinaryMemo BinaryFraction) + (hmemory : bitMemoSound bits encode (rankedBitProgramValue rank program) memory) : + (rankedBitMemoEvaluate rank program bits encode key memory).localWork = + ((rankedBitMemoEvaluate rank program bits encode key memory).freshKeys.map + (rankedBitLocalWork rank program)).sum := by + have hall : ∀ level key, rank key = level → ∀ memory, + bitMemoSound bits encode (rankedBitProgramValue rank program) memory → + (rankedBitMemoEvaluate rank program bits encode key memory).localWork = + ((rankedBitMemoEvaluate rank program bits encode key memory).freshKeys.map + (rankedBitLocalWork rank program)).sum := by + intro level + induction level using Nat.strong_induction_on with + | h level ih => + intro key hlevel memory hmem + rw [rankedBitMemoEvaluate] + split + · rfl + · have hs : ∀ (child : {child : κ // rank child < rank key}) previous, + bitMemoSound bits encode (rankedBitProgramValue rank program) previous → + (rankedBitMemoEvaluate rank program bits encode child.val previous).value = + rankedBitProgramValue rank program child.val ∧ + bitMemoSound bits encode (rankedBitProgramValue rank program) + (rankedBitMemoEvaluate rank program bits encode child.val previous).memory := by + intro child previous hp + exact rankedBitMemoEvaluate_sound rank program bits encode hinjective hbounded child.val previous hp + have hw : ∀ (child : {child : κ // rank child < rank key}) previous, + bitMemoSound bits encode (rankedBitProgramValue rank program) previous → + (rankedBitMemoEvaluate rank program bits encode child.val previous).localWork = + ((rankedBitMemoEvaluate rank program bits encode child.val previous).freshKeys.map + (rankedBitLocalWork rank program)).sum := by + intro child previous hp + exact ih (rank child.val) (hlevel ▸ child.property) child.val rfl previous hp + have hr := BitQuery.runMemo_work_eq + (fun child : {child : κ // rank child < rank key} => rankedBitProgramValue rank program child.val) + (bitMemoSound bits encode (rankedBitProgramValue rank program)) + (fun child previous => rankedBitMemoEvaluate rank program bits encode child.val previous) + (rankedBitLocalWork rank program) hs hw (program key) memory hmem + simpa only [List.map_cons, List.sum_cons, rankedBitLocalWork] using hr + exact hall (rank key) key rfl memory hmemory + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BitMemoWorkOn.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BitMemoWorkOn.lean new file mode 100644 index 0000000000000000000000000000000000000000..1725530e4b6aa331e0293d0bc33c328458b9e883 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BitMemoWorkOn.lean @@ -0,0 +1,49 @@ +import OAI.Combinatorics.EditApproximation.Binary.BitRankedMemoOn +import OAI.Combinatorics.EditApproximation.Binary.BitMemoWorkTransfer + +namespace OAI + +/-! The same exact fresh-key work accounting applies to normalized +programs whose simulation is justified on reachable child values. -/ + +namespace EditApproximation + +theorem rankedBitMemoEvaluate_work_transfer_on {κ : Type*} (rank : κ → ℕ) + (program : (key : κ) → BitQuery {child : κ // rank child < rank key} BinaryFraction) + (expected : (key : κ) → FiniteQuery {child : κ // rank child < rank key}) + (hprogram : ∀ key, BitQuery.RefinesOn + (fun child => rankedBitProgramValue rank program child.val) + (fun word value => word.value = value) (program key) (expected key)) + (bits : ℕ) (encode : κ → ℕ) (hinjective : Function.Injective encode) + (hbounded : ∀ key, encode key < 2 ^ bits) (key : κ) (memory : BinaryMemo BinaryFraction) + (hmemory : bitMemoSound bits encode (rankedBitProgramValue rank program) memory) : + (rankedBitMemoEvaluate rank program bits encode key memory).localWork = + rankedMemoKernelWork rank expected bits encode (rankedBitLocalWork rank program) + key (memory.mapValues BinaryFraction.value) := by + have hf := congrArg RecursiveMemoResult.freshKeys + (rankedBitMemoEvaluate_decode_on rank program expected hprogram bits encode hinjective hbounded + key memory hmemory) + dsimp only [BitRecursiveMemoResult.decode] at hf + rw [rankedMemoKernelWork_eq_fresh_sum, ← hf] + exact rankedBitMemoEvaluate_localWork rank program bits encode hinjective hbounded key memory hmemory + +theorem rankedBitProgramValue_value_on {κ : Type*} (rank : κ → ℕ) + (program : (key : κ) → BitQuery {child : κ // rank child < rank key} BinaryFraction) + (expected : (key : κ) → FiniteQuery {child : κ // rank child < rank key}) + (hprogram : ∀ key, BitQuery.RefinesOn + (fun child => rankedBitProgramValue rank program child.val) + (fun word value => word.value = value) (program key) (expected key)) + (bits : ℕ) (encode : κ → ℕ) (hinjective : Function.Injective encode) + (hbounded : ∀ key, encode key < 2 ^ bits) (key : κ) : + (rankedBitProgramValue rank program key).value = rankedProgramValue rank expected key := by + have hv := congrArg RecursiveMemoResult.value + (rankedBitMemoEvaluate_decode_on rank program expected hprogram bits encode hinjective hbounded + key .empty (bitMemoSound_empty _ _ _)) + dsimp only [BitRecursiveMemoResult.decode, BinaryMemo.mapValues] at hv + rw [(rankedBitMemoEvaluate_sound rank program bits encode hinjective hbounded key .empty + (bitMemoSound_empty bits encode _)).1] at hv + exact hv.trans (rankedMemoEvaluate_empty rank expected bits encode hinjective hbounded key) + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BitMemoWorkTransfer.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BitMemoWorkTransfer.lean new file mode 100644 index 0000000000000000000000000000000000000000..73b4c6d22e5b8cd11e0bee980ef094e00e5caad6 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BitMemoWorkTransfer.lean @@ -0,0 +1,45 @@ +import OAI.Combinatorics.EditApproximation.Binary.BitMemoWork +import OAI.Combinatorics.EditApproximation.Geometry.RankedMemoKernelFresh + +namespace OAI + +/-! Transfer the concrete binary evaluator's measured local work to the +already bounded rational trace, using equality of the actual miss list. -/ + +namespace EditApproximation + +theorem rankedBitMemoEvaluate_work_transfer {κ : Type*} (rank : κ → ℕ) + (program : (key : κ) → BitQuery {child : κ // rank child < rank key} BinaryFraction) + (expected : (key : κ) → FiniteQuery {child : κ // rank child < rank key}) + (hprogram : ∀ key, BitQuery.Refines (fun word value => word.value = value) + (program key) (expected key)) + (bits : ℕ) (encode : κ → ℕ) (hinjective : Function.Injective encode) + (hbounded : ∀ key, encode key < 2 ^ bits) (key : κ) (memory : BinaryMemo BinaryFraction) + (hmemory : bitMemoSound bits encode (rankedBitProgramValue rank program) memory) : + (rankedBitMemoEvaluate rank program bits encode key memory).localWork = + rankedMemoKernelWork rank expected bits encode (rankedBitLocalWork rank program) + key (memory.mapValues BinaryFraction.value) := by + have hf := congrArg RecursiveMemoResult.freshKeys + (rankedBitMemoEvaluate_decode rank program expected hprogram bits encode key memory) + dsimp only [BitRecursiveMemoResult.decode] at hf + rw [rankedMemoKernelWork_eq_fresh_sum, ← hf] + exact rankedBitMemoEvaluate_localWork rank program bits encode hinjective hbounded key memory hmemory + +theorem rankedBitProgramValue_value {κ : Type*} (rank : κ → ℕ) + (program : (key : κ) → BitQuery {child : κ // rank child < rank key} BinaryFraction) + (expected : (key : κ) → FiniteQuery {child : κ // rank child < rank key}) + (hprogram : ∀ key, BitQuery.Refines (fun word value => word.value = value) + (program key) (expected key)) + (bits : ℕ) (encode : κ → ℕ) (hinjective : Function.Injective encode) + (hbounded : ∀ key, encode key < 2 ^ bits) (key : κ) : + (rankedBitProgramValue rank program key).value = rankedProgramValue rank expected key := by + have hv := congrArg RecursiveMemoResult.value + (rankedBitMemoEvaluate_decode rank program expected hprogram bits encode key .empty) + dsimp only [BitRecursiveMemoResult.decode, BinaryMemo.mapValues] at hv + rw [(rankedBitMemoEvaluate_sound rank program bits encode hinjective hbounded key .empty + (bitMemoSound_empty bits encode _)).1] at hv + exact hv.trans (rankedMemoEvaluate_empty rank expected bits encode hinjective hbounded key) + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BitQuery.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BitQuery.lean new file mode 100644 index 0000000000000000000000000000000000000000..8ba03a3a4cffdcb37df2499c013b8c13747a38f3 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BitQuery.lean @@ -0,0 +1,144 @@ +import OAI.Combinatorics.EditApproximation.Probability.FiniteQueryWork +import OAI.Combinatorics.EditApproximation.Binary.BinaryFractionWork +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Adaptive queries whose answers are stored binary fractions. Local Boolean +computations appear as explicit charged steps. The simulation relation below +preserves the ordered requests as well as the final value; it does not gather +a rational query's keys in advance. -/ + +namespace EditApproximation + + + +namespace BitQuery + + + +def keys {ι β : Type*} (oracle : ι → BinaryFraction) : BitQuery ι β → List ι + | .done _ => [] + | .read key next => key :: keys oracle (next (oracle key)) + | .charge _ next => keys oracle next + + + + + +theorem value_bind {ι α β : Type*} (oracle : ι → BinaryFraction) + (program : BitQuery ι α) (next : α → BitQuery ι β) : + (program.bind next).value oracle = (next (program.value oracle)).value oracle := by + induction program with + | done result => rfl + | read key continuation ih => exact ih (oracle key) + | charge steps continuation ih => exact ih + +theorem keys_bind {ι α β : Type*} (oracle : ι → BinaryFraction) + (program : BitQuery ι α) (next : α → BitQuery ι β) : + (program.bind next).keys oracle = program.keys oracle ++ (next (program.value oracle)).keys oracle := by + induction program with + | done result => rfl + | read key continuation ih => exact congrArg (List.cons key) (ih (oracle key)) + | charge steps continuation ih => exact ih + +theorem work_bind {ι α β : Type*} (oracle : ι → BinaryFraction) (readWork : ι → ℕ) + (program : BitQuery ι α) (next : α → BitQuery ι β) : + (program.bind next).work oracle readWork = + program.work oracle readWork + (next (program.value oracle)).work oracle readWork := by + induction program with + | done result => simp only [bind, work, value, Nat.zero_add] + | read key continuation ih => simp only [bind, work, value, ih, Nat.add_assoc] + | charge steps continuation ih => simp only [bind, work, value, ih, Nat.add_assoc] + +/- A local charged step executes a Boolean routine with an explicit cost. -/ + + +/-- Branches of the reference query are selected only by the values of +answers actually read. The relation can therefore be composed stage by stage. -/ +inductive Refines {ι β : Type*} (relation : β → ℚ → Prop) : + BitQuery ι β → FiniteQuery ι → Prop where + | done {result : β} {expected : ℚ} (h : relation result expected) : + Refines relation (.done result) (.done expected) + | read (key : ι) (next : BinaryFraction → BitQuery ι β) (expected : ℚ → FiniteQuery ι) + (h : ∀ word, Refines relation (next word) (expected word.value)) : + Refines relation (.read key next) (.read key expected) + | charge (steps : ℕ) {program : BitQuery ι β} {expected : FiniteQuery ι} + (h : Refines relation program expected) : Refines relation (.charge steps program) expected + +theorem Refines.value_keys {ι β : Type*} {relation : β → ℚ → Prop} + {program : BitQuery ι β} {expected : FiniteQuery ι} + (h : Refines relation program expected) (oracle : ι → BinaryFraction) : + relation (program.value oracle) (expected.value (fun key => (oracle key).value)) ∧ + program.keys oracle = expected.keys (fun key => (oracle key).value) := by + induction h with + | done h => exact ⟨h, rfl⟩ + | read key next expected h ih => + exact ⟨(ih (oracle key)).1, congrArg (List.cons key) (ih (oracle key)).2⟩ + | charge steps h ih => exact ih + +theorem Refines.read_work_le {ι β : Type*} {relation : β → ℚ → Prop} + {program : BitQuery ι β} {expected : FiniteQuery ι} + (h : Refines relation program expected) (oracle : ι → BinaryFraction) (readWork : ι → ℕ) : + expected.cost (fun key => (oracle key).value) readWork ≤ program.work oracle readWork := by + induction h with + | done h => exact Nat.le_refl 0 + | read key next expected h ih => exact Nat.add_le_add_left (ih (oracle key)) _ + | charge steps h ih => exact ih.trans (Nat.le_add_left _ _) + +theorem Refines.bind {ι α β : Type*} {relation : α → ℚ → Prop} + {nextRelation : β → ℚ → Prop} {program : BitQuery ι α} {expected : FiniteQuery ι} + (h : Refines relation program expected) (next : α → BitQuery ι β) (expectedNext : ℚ → FiniteQuery ι) + (hn : ∀ a v, relation a v → Refines nextRelation (next a) (expectedNext v)) : + Refines nextRelation (program.bind next) (FiniteQuery.bind expected expectedNext) := by + induction h with + | done h => exact hn _ _ h + | read key continuation expected h ih => exact .read key _ _ ih + | charge steps h ih => exact .charge steps ih + + + +theorem Refines.collect {ι κ β : Type*} {relation : β → ℚ → Prop} + (reader : κ → BitQuery ι BinaryFraction) (expectedReader : κ → FiniteQuery ι) + (hr : ∀ key, Refines (fun word value => word.value = value) (reader key) (expectedReader key)) + (inputs : List κ) (next : List BinaryFraction → BitQuery ι β) + (expectedNext : List ℚ → FiniteQuery ι) + (hn : ∀ words, Refines relation (next words) (expectedNext (words.map BinaryFraction.value))) : + Refines relation (BitQuery.collect reader inputs next) + (FiniteQuery.collect expectedReader inputs expectedNext) := by + induction inputs generalizing next expectedNext with + | nil => exact hn [] + | cons key inputs ih => + apply (hr key).bind + intro word value hv + subst value + apply Refines.charge + apply ih + intro words + exact hn (word :: words) + +theorem value_collect {ι κ β : Type*} (oracle : ι → BinaryFraction) + (reader : κ → BitQuery ι BinaryFraction) (inputs : List κ) + (next : List BinaryFraction → BitQuery ι β) : + (collect reader inputs next).value oracle = + (next (inputs.map fun key => (reader key).value oracle)).value oracle := by + induction inputs generalizing next with + | nil => rfl + | cons key inputs ih => simp only [collect, value_bind, value, ih, List.map_cons] + +theorem work_collect {ι κ β : Type*} (oracle : ι → BinaryFraction) (readWork : ι → ℕ) + (reader : κ → BitQuery ι BinaryFraction) (inputs : List κ) + (next : List BinaryFraction → BitQuery ι β) : + (collect reader inputs next).work oracle readWork = + (inputs.map fun key => (reader key).work oracle readWork + 3).sum + + (next (inputs.map fun key => (reader key).value oracle)).work oracle readWork := by + induction inputs generalizing next with + | nil => simp only [collect, List.map_nil, List.sum_nil, Nat.zero_add] + | cons key inputs ih => + simp only [collect, work_bind, work, ih, List.map_cons, List.sum_cons, Nat.add_assoc] + +end BitQuery +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BitQueryKeys.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BitQueryKeys.lean new file mode 100644 index 0000000000000000000000000000000000000000..7af283174c20c9204aee8faa13c54cdb29e40861 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BitQueryKeys.lean @@ -0,0 +1,65 @@ +import OAI.Combinatorics.EditApproximation.Binary.BitQuery +import OAI.Combinatorics.EditApproximation.Binary.BinaryDistanceWork +import OAI.Combinatorics.EditApproximation.Probability.FiniteQueryRestriction +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Key tagging and finite-domain restriction preserve the adaptive +reference program. Executed key tests carry their actual Boolean cost. -/ + +namespace EditApproximation.BitQuery + + + +theorem Refines.mapKeysWithWork {ι κ β : Type*} {relation : β → ℚ → Prop} + (f : ι → κ × ℕ) (g : ι → κ) (hf : ∀ key, (f key).1 = g key) + {program : BitQuery ι β} {expected : FiniteQuery ι} + (h : Refines relation program expected) : + Refines relation (mapKeysWithWork f program) (FiniteQuery.mapKeys g expected) := by + induction h with + | done h => exact .done h + | charge steps h ih => exact .charge steps ih + | read key next expected h ih => + apply Refines.charge + change Refines relation (.read (f key).1 _) (.read (g key) _) + rw [hf key] + exact .read _ _ _ ih + + +theorem mapKeysWithWork_work {ι κ β : Type*} (f : ι → κ × ℕ) + (program : BitQuery ι β) (oracle : κ → BinaryFraction) (readWork : κ → ℕ) : + (mapKeysWithWork f program).work oracle readWork = + program.work (fun key => oracle (f key).1) (fun key => (f key).2 + readWork (f key).1) := by + induction program with + | done result => rfl + | charge steps next ih => exact congrArg (steps + ·) ih + | read key next ih => + simp only [mapKeysWithWork, work, ih, Nat.add_assoc] + + + +theorem Refines.restrictWithWork {ι : Type*} (P : ι → Prop) [DecidablePred P] + (test : ι → Bool × ℕ) (htest : ∀ key, (test key).1 = true ↔ P key) + {program : BitQuery ι BinaryFraction} {expected : FiniteQuery ι} + (h : Refines (fun word value => word.value = value) program expected) : + Refines (fun word value => word.value = value) + (restrictWithWork P test htest program) (FiniteQuery.restrict P expected) := by + induction h with + | done h => exact .done h + | charge steps h ih => exact .charge steps ih + | read key next expected h ih => + apply Refines.charge + change Refines _ (dite ((test key).1 = true) _ _) (dite (P key) _ _) + by_cases hp : P key + · have ht := (htest key).mpr hp + rw [dite_eq_left ht, dite_eq_left hp] + exact .read _ _ _ ih + · have ht : (test key).1 ≠ true := fun ht => hp ((htest key).mp ht) + rw [dite_eq_right ht, dite_eq_right hp] + simpa only [BinaryFraction.nat_value, Nat.cast_zero] using ih (BinaryFraction.nat 0) + +end EditApproximation.BitQuery + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BitQueryKeysSpace.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BitQueryKeysSpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..5aa6d6200850e29c3d7a4d411f2855e09607fc1a --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BitQueryKeysSpace.lean @@ -0,0 +1,36 @@ +import OAI.Combinatorics.EditApproximation.Binary.BitQuerySpace +import OAI.Combinatorics.EditApproximation.Binary.BitQueryKeys + +namespace OAI + +namespace EditApproximation.BitQuery.Heap + +def mapKeysWithWork {ι κ β : Type*} (f : ι → κ × ℕ) (allocation : ι → ℕ) + (ha : ∀ key, allocation key ≤ (f key).2) + {program : BitQuery ι β} (heap : Heap program) : Heap (program.mapKeysWithWork f) := + match heap with + | .done result => .done result + | .read key next continuation => + chargeOf (allocation key) (ha key) + (.read (f key).1 _ (fun word => (continuation word).mapKeysWithWork f allocation ha)) + | .charge localCells bound next => .charge localCells bound (next.mapKeysWithWork f allocation ha) + +def restrictWithWork {ι : Type*} (P : ι → Prop) + (test : ι → Bool × ℕ) (htest : ∀ key, (test key).1 = true ↔ P key) + (allocation : ι → ℕ) (ha : ∀ key, allocation key ≤ (test key).2) + {program : BitQuery ι BinaryFraction} (heap : Heap program) : + Heap (program.restrictWithWork P test htest) := + match heap with + | .done result => .done result + | .charge localCells bound next => .charge localCells bound (next.restrictWithWork P test htest allocation ha) + | .read key next continuation => + chargeOf (allocation key) (ha key) + (by + split + · exact .read _ _ (fun word => (continuation word).restrictWithWork P test htest allocation ha) + · exact (continuation (BinaryFraction.nat 0)).restrictWithWork P test htest allocation ha) + + +end EditApproximation.BitQuery.Heap + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BitQueryNormalizationCost.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BitQueryNormalizationCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..7e2774cb713daed62cd8526bcd6bc946551b7369 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BitQueryNormalizationCost.lean @@ -0,0 +1,39 @@ +import OAI.Combinatorics.EditApproximation.Binary.BitRankedNormalize +import OAI.Combinatorics.EditApproximation.Binary.BitMemoWork + +namespace OAI + +namespace EditApproximation.BitQuery + +theorem normalize_work_bound {ι : Type*} (program : BitQuery ι BinaryFraction) + (base : List Bool) (hbase : 0 < bitWordValue base) (remaining A B C : ℕ) + (oracle : ι → BinaryFraction) (readWork : ι → ℕ) + (ha : (program.value oracle).width ≤ A) (hb : base.length ≤ B) + (hc : program.work oracle readWork ≤ C) : + (program.normalize base hbase remaining).work oracle readWork ≤ + C + BinaryFraction.powerDenominatorBitBudget remaining A B + 1 := by + rw [normalize_work] + have h := BinaryFraction.powerDenominatorWithWork_cost (program.value oracle) base hbase remaining A B ha hb + change program.work oracle readWork + (0 + _ + 1) ≤ _ + dsimp only + omega + +end EditApproximation.BitQuery + +namespace EditApproximation + +theorem rankedNormalizeBody_localWork_bound {κ : Type*} (rank : κ → ℕ) + (raw : (key : κ) → BitQuery {child : κ // rank child < rank key} BinaryFraction) + (base : List Bool) (hbase : 0 < bitWordValue base) (remaining A C : κ → ℕ) + (B : ℕ) (hb : base.length ≤ B) (key : κ) + (ha : ((raw key).value (fun child => rankedBitProgramValue rank + (rankedNormalizeBody rank raw base hbase remaining) child.val)).width ≤ A key) + (hc : (raw key).work (fun child => rankedBitProgramValue rank + (rankedNormalizeBody rank raw base hbase remaining) child.val) (fun _ => 0) ≤ C key) : + rankedBitLocalWork rank (rankedNormalizeBody rank raw base hbase remaining) key ≤ + C key + BinaryFraction.powerDenominatorBitBudget (remaining key) (A key) B + 1 := + BitQuery.normalize_work_bound (raw key) base hbase (remaining key) (A key) B (C key) _ _ ha hb hc + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BitQueryNormalize.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BitQueryNormalize.lean new file mode 100644 index 0000000000000000000000000000000000000000..5323125b87ff287af08763f1235264cb129da3cb --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BitQueryNormalize.lean @@ -0,0 +1,52 @@ +import OAI.Combinatorics.EditApproximation.Binary.BitQueryOn +import OAI.Combinatorics.EditApproximation.Binary.BinaryCachedContinuation +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Executed cache normalization charges the actual Boolean rescaling. +Its exact-value premise is checked on the reachable local result. -/ + +namespace EditApproximation.BitQuery + + + +theorem normalize_value {ι : Type*} (program : BitQuery ι BinaryFraction) + (base : List Bool) (hbase : 0 < bitWordValue base) (remaining : ℕ) + (oracle : ι → BinaryFraction) + (hden : (program.value oracle).value.den ∣ bitWordValue base ^ remaining) : + (normalize program base hbase remaining).value oracle = + (BinaryFraction.finishCachedWithWork (program.value oracle, 0) base hbase remaining).1 ∧ + ((normalize program base hbase remaining).value oracle).value = (program.value oracle).value := by + refine ⟨by simp only [normalize, value_bind, compute, value], ?_⟩ + simp only [normalize, value_bind, compute, value] + exact BinaryFraction.finishCachedWithWork_value _ base hbase remaining hden + +theorem normalize_keys {ι : Type*} (program : BitQuery ι BinaryFraction) + (base : List Bool) (hbase : 0 < bitWordValue base) (remaining : ℕ) + (oracle : ι → BinaryFraction) : + (normalize program base hbase remaining).keys oracle = program.keys oracle := by + simp only [normalize, keys_bind, compute, keys, List.append_nil] + +theorem normalize_work {ι : Type*} (program : BitQuery ι BinaryFraction) + (base : List Bool) (hbase : 0 < bitWordValue base) (remaining : ℕ) + (oracle : ι → BinaryFraction) (readWork : ι → ℕ) : + (normalize program base hbase remaining).work oracle readWork = + program.work oracle readWork + + (BinaryFraction.finishCachedWithWork (program.value oracle, 0) base hbase remaining).2 := by + simp only [normalize, work_bind, compute, work, Nat.add_zero] + +theorem RefinesOn.normalize {ι : Type*} {oracle : ι → BinaryFraction} + {program : BitQuery ι BinaryFraction} {expected : FiniteQuery ι} + (h : RefinesOn oracle (fun word value => word.value = value) program expected) + (base : List Bool) (hbase : 0 < bitWordValue base) (remaining : ℕ) + (hden : (program.value oracle).value.den ∣ bitWordValue base ^ remaining) : + RefinesOn oracle (fun word value => word.value = value) + (normalize program base hbase remaining) expected := by + apply h.finish + exact BinaryFraction.finishCachedWithWork_value _ base hbase remaining hden + +end EditApproximation.BitQuery + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BitQueryOn.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BitQueryOn.lean new file mode 100644 index 0000000000000000000000000000000000000000..a86a05b682e1b30a12e9fb6c6e61762e62d82cf2 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BitQueryOn.lean @@ -0,0 +1,55 @@ +import OAI.Combinatorics.EditApproximation.Binary.BitMemoSound + +namespace OAI + +/-! Simulation along a fixed reachable oracle. This allows a checked +normalization at the end of a local query: its denominator invariant is +required only for the values that the ranked execution actually reaches. -/ + +namespace EditApproximation.BitQuery + +inductive RefinesOn {ι β : Type*} (oracle : ι → BinaryFraction) (relation : β → ℚ → Prop) : + BitQuery ι β → FiniteQuery ι → Prop where + | done {result : β} {expected : ℚ} (h : relation result expected) : + RefinesOn oracle relation (.done result) (.done expected) + | read (key : ι) (next : BinaryFraction → BitQuery ι β) (expected : ℚ → FiniteQuery ι) + (h : RefinesOn oracle relation (next (oracle key)) (expected (oracle key).value)) : + RefinesOn oracle relation (.read key next) (.read key expected) + | charge (steps : ℕ) {program : BitQuery ι β} {expected : FiniteQuery ι} + (h : RefinesOn oracle relation program expected) : + RefinesOn oracle relation (.charge steps program) expected + +theorem Refines.onOracle {ι β : Type*} {relation : β → ℚ → Prop} + {program : BitQuery ι β} {expected : FiniteQuery ι} + (h : Refines relation program expected) (oracle : ι → BinaryFraction) : + RefinesOn oracle relation program expected := by + induction h with + | done h => exact .done h + | charge steps _ ih => exact .charge steps ih + | read key next expected _ ih => exact .read key next expected (ih (oracle key)) + +theorem RefinesOn.value_keys {ι β : Type*} {oracle : ι → BinaryFraction} {relation : β → ℚ → Prop} + {program : BitQuery ι β} {expected : FiniteQuery ι} + (h : RefinesOn oracle relation program expected) : + relation (program.value oracle) (expected.value (fun key => (oracle key).value)) ∧ + program.keys oracle = expected.keys (fun key => (oracle key).value) := by + induction h with + | done h => exact ⟨h, rfl⟩ + | charge steps _ ih => exact ih + | read key next expected _ ih => exact ⟨ih.1, congrArg (List.cons key) ih.2⟩ + +theorem RefinesOn.finish {ι : Type*} {oracle : ι → BinaryFraction} + {program : BitQuery ι BinaryFraction} {expected : FiniteQuery ι} + (h : RefinesOn oracle (fun word value => word.value = value) program expected) + (finish : BinaryFraction → BinaryFraction × ℕ) + (hf : (finish (program.value oracle)).1.value = (program.value oracle).value) : + RefinesOn oracle (fun word value => word.value = value) + (program.bind fun word => compute (finish word)) expected := by + induction h with + | done h => exact .charge _ (.done (hf.trans h)) + | charge steps _ ih => exact .charge steps (ih hf) + | read key next expected _ ih => exact .read key _ _ (ih hf) + +end EditApproximation.BitQuery + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BitQuerySpace.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BitQuerySpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..81fd2a0b1a7125f20f91fc452b549839b3259009 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BitQuerySpace.lean @@ -0,0 +1,71 @@ +import OAI.Combinatorics.EditApproximation.Binary.BitQuery + +namespace OAI + +/-! Allocation annotations for the actual adaptive query. Charge annotations +carry the concrete routine's allocation bound; reads reserve three cells for +its suspended continuation and result pointer. Charge transitions are tail +transitions. Summing all allocations bounds simultaneously live cells even +if no temporary cell is reclaimed until the query returns. -/ + +namespace EditApproximation.BitQuery + +inductive Heap {ι β : Type*} : BitQuery ι β → Type _ where + | done (value : β) : Heap (.done value) + | read (key : ι) (next : BinaryFraction → BitQuery ι β) + (continuation : ∀ word, Heap (next word)) : Heap (.read key next) + | charge {steps : ℕ} {next : BitQuery ι β} (cells : ℕ) + (bound : cells ≤ 3 * steps) (continuation : Heap next) : Heap (.charge steps next) + +namespace Heap + +def cells {ι β : Type*} {program : BitQuery ι β} (oracle : ι → BinaryFraction) : Heap program → ℕ + | .done _ => 0 + | .read key _ next => 3 + cells oracle (next (oracle key)) + | .charge localCells _ next => localCells + cells oracle next + +theorem cells_le_work {ι β : Type*} {program : BitQuery ι β} (oracle : ι → BinaryFraction) + (heap : Heap program) : heap.cells oracle ≤ 3 * program.work oracle (fun _ => 1) := by + induction heap with + | done result => exact le_rfl + | read key next heap ih => + have h := ih (oracle key) + simp only [cells, work] + omega + | charge localCells bound next ih => + simp only [cells, work] + omega + +def bind {ι α β : Type*} {program : BitQuery ι α} (heap : Heap program) + (next : α → BitQuery ι β) (allocation : ∀ value, Heap (next value)) : Heap (program.bind next) := + match heap with + | .done result => allocation result + | .read key continuation stored => .read key _ (fun word => (stored word).bind next allocation) + | .charge localCells bound tail => .charge localCells bound (tail.bind next allocation) + +def compute {ι β : Type*} (execution : β × ℕ) (allocation : ℕ) + (bound : allocation ≤ 3 * execution.2) : Heap (BitQuery.compute (ι := ι) execution) := + .charge allocation bound (.done execution.1) + +def chargeOf {ι β : Type*} {steps : ℕ} {program : BitQuery ι β} (allocation : ℕ) + (bound : allocation ≤ steps) (tail : Heap program) : Heap (.charge steps program) := + .charge allocation (by omega) tail + +def computeOf {ι β : Type*} (execution : β × ℕ) (allocation : ℕ) + (bound : allocation ≤ execution.2) : Heap (BitQuery.compute (ι := ι) execution) := + compute execution allocation (by omega) + +def collect {ι κ β : Type*} (reader : κ → BitQuery ι BinaryFraction) + (allocation : ∀ key, Heap (reader key)) : + (inputs : List κ) → (next : List BinaryFraction → BitQuery ι β) → + (∀ words, Heap (next words)) → Heap (BitQuery.collect reader inputs next) + | [], _, continuation => continuation [] + | key :: rest, next, continuation => + (allocation key).bind _ fun word => .charge 1 (by decide) + (collect reader allocation rest (fun words => next (word :: words)) + (fun words => continuation (word :: words))) + +end Heap +end EditApproximation.BitQuery + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BitRankedMemo.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BitRankedMemo.lean new file mode 100644 index 0000000000000000000000000000000000000000..2d2367b06d357306b5e0ba5dd7b048a3d516c542 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BitRankedMemo.lean @@ -0,0 +1,55 @@ +import OAI.Combinatorics.EditApproximation.Binary.BitMemoRun +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! The rank-decreasing evaluator stores the binary words actually returned +by its local program. Its rational view preserves the fresh-key, +dictionary-visit and request traces. -/ + +namespace EditApproximation + + + +theorem rankedBitMemoEvaluate_decode {κ : Type*} (rank : κ → ℕ) + (program : (key : κ) → BitQuery {child : κ // rank child < rank key} BinaryFraction) + (expected : (key : κ) → FiniteQuery {child : κ // rank child < rank key}) + (hprogram : ∀ key, BitQuery.Refines (fun word value => word.value = value) + (program key) (expected key)) + (bits : ℕ) (encode : κ → ℕ) (key : κ) (memory : BinaryMemo BinaryFraction) : + (rankedBitMemoEvaluate rank program bits encode key memory).decode = + rankedMemoEvaluate rank expected bits encode key (memory.mapValues BinaryFraction.value) := by + have hall : ∀ level key, rank key = level → ∀ memory, + (rankedBitMemoEvaluate rank program bits encode key memory).decode = + rankedMemoEvaluate rank expected bits encode key (memory.mapValues BinaryFraction.value) := by + intro level + induction level using Nat.strong_induction_on with + | h level ih => + intro key hlevel memory + rw [rankedBitMemoEvaluate, rankedMemoEvaluate] + simp only [BinaryMemo.lookupCosted_spec, BinaryMemo.mapValues_lookup] + cases hfound : memory.lookup (binaryMemoKey bits (encode key)) with + | some value => + simp only [Option.map_some, BitRecursiveMemoResult.decode] + | none => + simp only [Option.map_none] + have hr := BitQuery.runMemo_decode + (fun (child : {child : κ // rank child < rank key}) previous => + rankedBitMemoEvaluate rank program bits encode child.val previous) + (fun child previous => rankedMemoEvaluate rank expected bits encode child.val previous) + (fun child previous => ih (rank child.val) (hlevel ▸ child.property) child.val rfl previous) + (hprogram key) memory + have hv := congrArg RecursiveMemoResult.value hr + have hm := congrArg RecursiveMemoResult.memory hr + have hf := congrArg RecursiveMemoResult.freshKeys hr + have hd := congrArg RecursiveMemoResult.dictionaryVisits hr + have hq := congrArg RecursiveMemoResult.requests hr + simp only [BitRecursiveMemoResult.decode] at hv hm hf hd hq + simp only [BinaryMemo.insertCosted_spec, BitRecursiveMemoResult.decode, + BinaryMemo.mapValues_insert, hv, hm, hf, hd, hq] + exact hall (rank key) key rfl memory + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BitRankedMemoOn.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BitRankedMemoOn.lean new file mode 100644 index 0000000000000000000000000000000000000000..5802595d1dc5b68328f9e053059de03ca4b4eced --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BitRankedMemoOn.lean @@ -0,0 +1,64 @@ +import OAI.Combinatorics.EditApproximation.Binary.BitMemoOn + +namespace OAI + +/-! Exact rational trace transfer when local output normalization is +proved only on the canonical reachable child words. -/ + +namespace EditApproximation + +theorem rankedBitMemoEvaluate_decode_on {κ : Type*} (rank : κ → ℕ) + (program : (key : κ) → BitQuery {child : κ // rank child < rank key} BinaryFraction) + (expected : (key : κ) → FiniteQuery {child : κ // rank child < rank key}) + (hprogram : ∀ key, BitQuery.RefinesOn + (fun child => rankedBitProgramValue rank program child.val) + (fun word value => word.value = value) (program key) (expected key)) + (bits : ℕ) (encode : κ → ℕ) (hinjective : Function.Injective encode) + (hbounded : ∀ key, encode key < 2 ^ bits) (key : κ) (memory : BinaryMemo BinaryFraction) + (hmemory : bitMemoSound bits encode (rankedBitProgramValue rank program) memory) : + (rankedBitMemoEvaluate rank program bits encode key memory).decode = + rankedMemoEvaluate rank expected bits encode key (memory.mapValues BinaryFraction.value) := by + have hall : ∀ level key, rank key = level → ∀ memory, + bitMemoSound bits encode (rankedBitProgramValue rank program) memory → + (rankedBitMemoEvaluate rank program bits encode key memory).decode = + rankedMemoEvaluate rank expected bits encode key (memory.mapValues BinaryFraction.value) := by + intro level + induction level using Nat.strong_induction_on with + | h level ih => + intro key hlevel memory hmem + rw [rankedBitMemoEvaluate, rankedMemoEvaluate] + simp only [BinaryMemo.lookupCosted_spec, BinaryMemo.mapValues_lookup] + cases hfound : memory.lookup (binaryMemoKey bits (encode key)) with + | some value => simp only [Option.map_some, BitRecursiveMemoResult.decode] + | none => + simp only [Option.map_none] + have hchildren (child : {child : κ // rank child < rank key}) previous + (hp : bitMemoSound bits encode (rankedBitProgramValue rank program) previous) : + (rankedBitMemoEvaluate rank program bits encode child.val previous).value = + rankedBitProgramValue rank program child.val ∧ + bitMemoSound bits encode (rankedBitProgramValue rank program) + (rankedBitMemoEvaluate rank program bits encode child.val previous).memory ∧ + (rankedBitMemoEvaluate rank program bits encode child.val previous).decode = + rankedMemoEvaluate rank expected bits encode child.val + (previous.mapValues BinaryFraction.value) := by + have hs := rankedBitMemoEvaluate_sound rank program bits encode hinjective hbounded child.val previous hp + exact ⟨hs.1, hs.2, ih (rank child.val) (hlevel ▸ child.property) child.val rfl previous hp⟩ + have hr := (BitQuery.runMemo_decode_on + (fun child : {child : κ // rank child < rank key} => rankedBitProgramValue rank program child.val) + (bitMemoSound bits encode (rankedBitProgramValue rank program)) + (fun child previous => rankedBitMemoEvaluate rank program bits encode child.val previous) + (fun child previous => rankedMemoEvaluate rank expected bits encode child.val previous) + hchildren (hprogram key) memory hmem).1 + have hv := congrArg RecursiveMemoResult.value hr + have hm := congrArg RecursiveMemoResult.memory hr + have hf := congrArg RecursiveMemoResult.freshKeys hr + have hd := congrArg RecursiveMemoResult.dictionaryVisits hr + have hq := congrArg RecursiveMemoResult.requests hr + simp only [BitRecursiveMemoResult.decode] at hv hm hf hd hq + simp only [BinaryMemo.insertCosted_spec, BitRecursiveMemoResult.decode, + BinaryMemo.mapValues_insert, hv, hm, hf, hd, hq] + exact hall (rank key) key rfl memory hmemory + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BitRankedNormalize.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BitRankedNormalize.lean new file mode 100644 index 0000000000000000000000000000000000000000..d601069ad64d1eb717b1efa220d8b7bb6524c7bc --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BitRankedNormalize.lean @@ -0,0 +1,91 @@ +import OAI.Combinatorics.EditApproximation.Binary.BitQueryNormalize +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! The denominator condition is used only at the semantic values of +smaller requests. Strong induction then establishes the actual binary +program's value and normalized trace without assuming its own output. -/ + +namespace EditApproximation + +section Normalize +variable {κ : Type*} (rank : κ → ℕ) + (raw : (key : κ) → BitQuery {child : κ // rank child < rank key} BinaryFraction) + (expected : (key : κ) → FiniteQuery {child : κ // rank child < rank key}) + (semantic : κ → ℚ) + (hrefines : ∀ key, BitQuery.Refines (fun word value => word.value = value) (raw key) (expected key)) + (hbody : ∀ key, (expected key).value (fun child => semantic child.val) = semantic key) + (base : List Bool) (hbase : 0 < bitWordValue base) (remaining : κ → ℕ) + (hden : ∀ key, (semantic key).den ∣ bitWordValue base ^ remaining key) + + + +include hrefines hbody hden in +theorem rankedNormalizeBody_correct (key : κ) : + (rankedBitProgramValue rank (rankedNormalizeBody rank raw base hbase remaining) key).value = + semantic key ∧ + BitQuery.RefinesOn + (fun child => rankedBitProgramValue rank (rankedNormalizeBody rank raw base hbase remaining) child.val) + (fun word value => word.value = value) + (rankedNormalizeBody rank raw base hbase remaining key) (expected key) := by + have hall : ∀ level key, rank key = level → + (rankedBitProgramValue rank (rankedNormalizeBody rank raw base hbase remaining) key).value = + semantic key ∧ + BitQuery.RefinesOn + (fun child => rankedBitProgramValue rank (rankedNormalizeBody rank raw base hbase remaining) child.val) + (fun word value => word.value = value) + (rankedNormalizeBody rank raw base hbase remaining key) (expected key) := by + intro level + induction level using Nat.strong_induction_on with + | h level ih => + intro key hlevel + let oracle := fun child : {child : κ // rank child < rank key} => + rankedBitProgramValue rank (rankedNormalizeBody rank raw base hbase remaining) child.val + have horacle : (fun child => (oracle child).value) = (fun child => semantic child.val) := by + funext child + exact (ih (rank child.val) (hlevel ▸ child.property) child.val rfl).1 + have hraw : ((raw key).value oracle).value = semantic key := by + have hv := ((hrefines key).value_keys oracle).1 + rw [horacle, hbody key] at hv + exact hv + have hd : ((raw key).value oracle).value.den ∣ bitWordValue base ^ remaining key := by + rw [hraw] + exact hden key + have hn := ((hrefines key).onOracle oracle).normalize base hbase (remaining key) hd + refine ⟨?_, hn⟩ + rw [rankedBitProgramValue] + exact hn.value_keys.1.trans (by rw [horacle]; exact hbody key) + exact hall (rank key) key rfl + + +include hrefines hbody hden in +theorem rankedNormalizeBody_width (key : κ) (B V : ℕ) + (hB : base.length ≤ B) (hV : |semantic key| ≤ (V : ℚ)) : + (rankedBitProgramValue rank (rankedNormalizeBody rank raw base hbase remaining) key).width ≤ + Nat.size V + 2 * (remaining key * B + 1) + 1 := by + let oracle := fun child : {child : κ // rank child < rank key} => + rankedBitProgramValue rank (rankedNormalizeBody rank raw base hbase remaining) child.val + have horacle : (fun child => (oracle child).value) = (fun child => semantic child.val) := by + funext child + exact (rankedNormalizeBody_correct rank raw expected semantic hrefines hbody base hbase remaining + hden child.val).1 + have hraw : ((raw key).value oracle).value = semantic key := by + have hv := ((hrefines key).value_keys oracle).1 + rw [horacle, hbody key] at hv + exact hv + have hd : ((raw key).value oracle).value.den ∣ bitWordValue base ^ remaining key := by + rw [hraw] + exact hden key + have hv : |((raw key).value oracle).value| ≤ (V : ℚ) := by rw [hraw]; exact hV + rw [rankedBitProgramValue] + change ((BitQuery.normalize (raw key) base hbase (remaining key)).value oracle).width ≤ _ + rw [(BitQuery.normalize_value (raw key) base hbase (remaining key) oracle hd).1] + exact BinaryFraction.powerDenominatorWithWork_width ((raw key).value oracle) base hbase + (remaining key) V B hB hd hv + +end Normalize +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/BitSourceRanked.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/BitSourceRanked.lean new file mode 100644 index 0000000000000000000000000000000000000000..ec5d061022f46f08ce22f516f0d1b4024d4c9010 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/BitSourceRanked.lean @@ -0,0 +1,35 @@ +import OAI.Combinatorics.EditApproximation.Binary.BitQueryKeys +import OAI.Combinatorics.EditApproximation.Geometry.SourceRankedProgram +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Source draws and table requests share the same concrete binary memo. +Rank-zero sources are stored once; each tagged recursive request pays for +its tag construction before entering the shared dictionary. -/ + +namespace EditApproximation.SourceRanked + +variable {σ κ : Type*} + + + +theorem bitBody_refines (tableRank : κ → ℕ) + (tableBody : (parent : κ) → BitQuery (Sum σ {key : κ // tableRank key < tableRank parent}) BinaryFraction) + (expectedBody : (parent : κ) → FiniteQuery (Sum σ {key : κ // tableRank key < tableRank parent})) + (sourceValue : σ → BinaryFraction × ℕ) + (hbody : ∀ parent, BitQuery.Refines (fun word value => word.value = value) + (tableBody parent) (expectedBody parent)) (key : Sum σ κ) : + BitQuery.Refines (fun word value => word.value = value) + (bitBody tableRank tableBody sourceValue key) + (body tableRank expectedBody (fun source => (sourceValue source).1.value) key) := by + cases key with + | inl source => exact .charge _ (.done rfl) + | inr table => + exact (hbody table).mapKeysWithWork (fun key => (child tableRank table key, 1)) + (child tableRank table) (fun _ => rfl) + +end EditApproximation.SourceRanked + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/FractionAllocation.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/FractionAllocation.lean new file mode 100644 index 0000000000000000000000000000000000000000..f0a0878917c03492523b59db13792bee0cdc8ff0 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/FractionAllocation.lean @@ -0,0 +1,101 @@ +import OAI.Combinatorics.EditApproximation.Binary.BitAllocation +import OAI.Combinatorics.EditApproximation.Geometry.CanonicalFractionWork +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation +namespace SignedBinary + +/-- Fresh magnitude cells in exactly the branch taken by signed addition. -/ + + +theorem addAllocation_le_work (a b : SignedBinary) : + a.addAllocation b ≤ (a.addWithWork b).2 := by + have ha := bitAddAllocation_le_work a.bits b.bits false + have hs := bitSubtractAllocation_le_work a.bits b.bits false + have ht := bitSubtractAllocation_le_work b.bits a.bits false + unfold addAllocation addWithWork + split_ifs + · dsimp only + omega + · cases h : (bitCompareWithWork a.bits b.bits).1 <;> simp only [h] <;> omega + + + +theorem mulAllocation_le_work (a b : SignedBinary) : + a.mulAllocation b ≤ (a.mulWithWork b).2 := by + have h := bitMulAllocation_le_work a.bits b.bits + change bitMulAllocation a.bits b.bits ≤ (bitMulWithWork a.bits b.bits).2 + 4 + omega + +end SignedBinary +namespace BinaryFraction + +/-- Counts every newly allocated magnitude and denominator cell, including +cross-products that are discarded after the numerator is computed. -/ + + +theorem addAllocation_le_work (a b : BinaryFraction) : + a.addAllocation b ≤ (a.addWithWork b).2 := by + have h1 := SignedBinary.mulAllocation_le_work a.numerator b.denominatorInteger + have h2 := SignedBinary.mulAllocation_le_work b.numerator a.denominatorInteger + have h3 := SignedBinary.addAllocation_le_work + (a.numerator.mulWithWork b.denominatorInteger).1 + (b.numerator.mulWithWork a.denominatorInteger).1 + have h4 := bitMulAllocation_le_work a.denominator b.denominator + unfold addAllocation addWithWork + dsimp only + omega + + + +theorem mulAllocation_le_work (a b : BinaryFraction) : + a.mulAllocation b ≤ (a.mulWithWork b).2 := by + have h1 := SignedBinary.mulAllocation_le_work a.numerator b.numerator + have h2 := bitMulAllocation_le_work a.denominator b.denominator + unfold mulAllocation mulWithWork + dsimp only + omega + +/-- Signed comparisons themselves reuse input words; rational comparison +allocates just its two cross-products. -/ + + +theorem ltAllocation_le_work (a b : BinaryFraction) : + a.ltAllocation b ≤ (a.ltWithWork b).2 := by + have h1 := SignedBinary.mulAllocation_le_work a.numerator b.denominatorInteger + have h2 := SignedBinary.mulAllocation_le_work b.numerator a.denominatorInteger + unfold ltAllocation ltWithWork + dsimp only + omega + + + +theorem canonicalizeAllocation_le_work (a : BinaryFraction) : + canonicalizeAllocation a ≤ (canonicalizeWithWork a).2 := by + have hn := trimBitWordAllocation_le_work a.numerator.bits + have hd := trimBitWordAllocation_le_work a.denominator + unfold canonicalizeAllocation canonicalizeWithWork + dsimp only + omega + + + +theorem canonicalAddAllocation_le_work (a b : BinaryFraction) : + canonicalAddAllocation a b ≤ (canonicalAddWithWork a b).2 := by + exact Nat.add_le_add (addAllocation_le_work a b) + (canonicalizeAllocation_le_work (a.addWithWork b).1) + + + +theorem canonicalMulAllocation_le_work (a b : BinaryFraction) : + canonicalMulAllocation a b ≤ (canonicalMulWithWork a b).2 := by + exact Nat.add_le_add (mulAllocation_le_work a b) + (canonicalizeAllocation_le_work (a.mulWithWork b).1) + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/FractionControlSpace.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/FractionControlSpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..1102782f826134eef284796f718c72483436bbb2 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/FractionControlSpace.lean @@ -0,0 +1,139 @@ +import OAI.Combinatorics.EditApproximation.Binary.BitControlSpace + +namespace OAI + +namespace EditApproximation +namespace SignedBinary + +def addInvocations (a b : SignedBinary) : ℕ := + if a.negative = b.negative then bitAddInvocations a.bits b.bits false + 1 + else bitCompareInvocations a.bits b.bits + 1 + + match (bitCompareWithWork a.bits b.bits).1 with + | .eq => 0 + | .lt => bitSubtractInvocations b.bits a.bits false + | .gt => bitSubtractInvocations a.bits b.bits false + +theorem addInvocations_le_work (a b : SignedBinary) : + addInvocations a b ≤ (a.addWithWork b).2 := by + have ha := bitAddInvocations_le_work a.bits b.bits false + have hc := bitCompareInvocations_le_work a.bits b.bits + have hs := bitSubtractInvocations_le_work a.bits b.bits false + have ht := bitSubtractInvocations_le_work b.bits a.bits false + unfold addInvocations addWithWork + split_ifs + · dsimp only + omega + · cases h : (bitCompareWithWork a.bits b.bits).1 <;> simp only [h] <;> omega + +def mulInvocations (a b : SignedBinary) : ℕ := bitMulInvocations a.bits b.bits + 1 + +theorem mulInvocations_le_work (a b : SignedBinary) : + mulInvocations a b ≤ (a.mulWithWork b).2 := by + have h := bitMulInvocations_le_work a.bits b.bits + change bitMulInvocations a.bits b.bits + 1 ≤ (bitMulWithWork a.bits b.bits).2 + 4 + omega + +end SignedBinary +namespace BinaryFraction + +def addInvocations (a b : BinaryFraction) : ℕ := + a.numerator.mulInvocations b.denominatorInteger + + b.numerator.mulInvocations a.denominatorInteger + + ((a.numerator.mulWithWork b.denominatorInteger).1.addInvocations + (b.numerator.mulWithWork a.denominatorInteger).1) + + bitMulInvocations a.denominator b.denominator + 1 + +theorem addInvocations_add_one_le_work (a b : BinaryFraction) : + a.addInvocations b + 1 ≤ (a.addWithWork b).2 := by + have h1 := SignedBinary.mulInvocations_le_work a.numerator b.denominatorInteger + have h2 := SignedBinary.mulInvocations_le_work b.numerator a.denominatorInteger + have h3 := SignedBinary.addInvocations_le_work + (a.numerator.mulWithWork b.denominatorInteger).1 (b.numerator.mulWithWork a.denominatorInteger).1 + have h4 := bitMulInvocations_le_work a.denominator b.denominator + unfold addInvocations addWithWork + dsimp only + omega + +def mulInvocations (a b : BinaryFraction) : ℕ := + a.numerator.mulInvocations b.numerator + bitMulInvocations a.denominator b.denominator + 1 + +theorem mulInvocations_add_one_le_work (a b : BinaryFraction) : + a.mulInvocations b + 1 ≤ (a.mulWithWork b).2 := by + have hn := SignedBinary.mulInvocations_le_work a.numerator b.numerator + have hd := bitMulInvocations_le_work a.denominator b.denominator + unfold mulInvocations mulWithWork + dsimp only + omega + +/-- Signed comparison may compare both words with zero. Its total recursive +Boolean-comparison frames are bounded by the explicitly counted work. -/ +def signedLtInvocations (a b : SignedBinary) : ℕ := + if a.negative then + if b.negative then bitCompareInvocations b.bits a.bits + 1 + else bitCompareInvocations a.bits [] + bitCompareInvocations b.bits [] + 3 + else if b.negative then 1 else bitCompareInvocations a.bits b.bits + 1 + +theorem signedLtInvocations_le_work (a b : SignedBinary) : + signedLtInvocations a b ≤ (a.ltWithWork b).2 := by + have hab := bitCompareInvocations_le_work a.bits b.bits + have hba := bitCompareInvocations_le_work b.bits a.bits + have ha := bitCompareInvocations_le_work a.bits [] + have hb := bitCompareInvocations_le_work b.bits [] + cases hna : a.negative <;> cases hnb : b.negative <;> + simp only [signedLtInvocations, SignedBinary.ltWithWork, hna, hnb, + Bool.false_eq_true, ↓reduceIte, SignedBinary.nonzeroWithWork] <;> omega + +/-- Actual fraction-comparison invocation count, including signed comparison. -/ +def compareInvocations (a b : BinaryFraction) : ℕ := + a.numerator.mulInvocations b.denominatorInteger + + b.numerator.mulInvocations a.denominatorInteger + + signedLtInvocations (a.numerator.mulWithWork b.denominatorInteger).1 + (b.numerator.mulWithWork a.denominatorInteger).1 + 1 + +theorem compareInvocations_le_work (a b : BinaryFraction) : + compareInvocations a b ≤ (a.ltWithWork b).2 := by + have h1 := SignedBinary.mulInvocations_le_work a.numerator b.denominatorInteger + have h2 := SignedBinary.mulInvocations_le_work b.numerator a.denominatorInteger + have h3 := signedLtInvocations_le_work (a.numerator.mulWithWork b.denominatorInteger).1 + (b.numerator.mulWithWork a.denominatorInteger).1 + unfold compareInvocations ltWithWork + dsimp only + omega + +def canonicalizeInvocations (a : BinaryFraction) : ℕ := + trimBitWordInvocations a.numerator.bits + trimBitWordInvocations a.denominator + 1 + +theorem canonicalizeInvocations_le_work (a : BinaryFraction) : + canonicalizeInvocations a ≤ (canonicalizeWithWork a).2 := by + have hn := trimBitWordInvocations_le_work a.numerator.bits + have hd := trimBitWordInvocations_le_work a.denominator + unfold canonicalizeInvocations canonicalizeWithWork + dsimp only + omega + +def canonicalAddInvocations (a b : BinaryFraction) : ℕ := + a.addInvocations b + canonicalizeInvocations (a.addWithWork b).1 + 1 + +theorem canonicalAddInvocations_le_work (a b : BinaryFraction) : + canonicalAddInvocations a b ≤ (canonicalAddWithWork a b).2 := by + have ha := addInvocations_add_one_le_work a b + have hc := canonicalizeInvocations_le_work (a.addWithWork b).1 + unfold canonicalAddInvocations canonicalAddWithWork + dsimp only + omega + +def canonicalMulInvocations (a b : BinaryFraction) : ℕ := + a.mulInvocations b + canonicalizeInvocations (a.mulWithWork b).1 + 1 + +theorem canonicalMulInvocations_le_work (a b : BinaryFraction) : + canonicalMulInvocations a b ≤ (canonicalMulWithWork a b).2 := by + have ha := mulInvocations_add_one_le_work a b + have hc := canonicalizeInvocations_le_work (a.mulWithWork b).1 + unfold canonicalMulInvocations canonicalMulWithWork + dsimp only + omega + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/IntegerAlgorithm.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/IntegerAlgorithm.lean new file mode 100644 index 0000000000000000000000000000000000000000..ab5fd5e8960d797ab79f2ebb7b5046d78b13e163 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/IntegerAlgorithm.lean @@ -0,0 +1,56 @@ +import OAI.Combinatorics.EditApproximation.Refinement.ComputedExecutionLaw +import OAI.Combinatorics.EditApproximation.Binary.IntegerSymbols + +namespace OAI + +/-! The uniform algorithm on explicitly stored integer symbols, together +with its conditional accuracy theorem. The hypothesis is a finite scalar +Bernstein bound for the two computed finite product laws. -/ + +namespace EditApproximation + +open MeasureTheory + +def ComputedBernsteinInputs (N : ℕ) : Prop := + FiniteBernsteinInput (Measure.pi fun _ : Fin (integerParameters N).B => + (PMF.uniformOfFintype (Fin (integerParameters N).B)).toMeasure) ∧ + ∀ b : ℕ, ∀ h : Fin (groupDyadicScales (integerParameters N).M b (inputSmallLog N)).length, + FiniteBernsteinInput (Measure.pi fun _ : Fin + (groupSampleCount (integerParameters N).M (inputSmallLog N ^ 80) b + (groupDyadicScaleAt (integerParameters N).M b (inputSmallLog N) h)) => + (PMF.uniformOfFintype (Fin (integerParameters N).M)).toMeasure) + +abbrev IntegerApproximationOutcome (source target : List ℤ) := + ComputedFullOutcome (source.map integerSymbolCode) (target.map integerSymbolCode) + (source.length + target.length) + +noncomputable def integerApproximationLaw (source target : List ℤ) (epsilon : BinaryFraction) : + Measure (IntegerApproximationOutcome source target) := + computedFullLaw (source.map integerSymbolCode) (target.map integerSymbolCode) + (source.length + target.length) epsilon + +noncomputable def integerApproximationAnswer (source target : List ℤ) + (outcome : IntegerApproximationOutcome source target) : ℕ := + computedFullAnswer (source.map integerSymbolCode) (target.map integerSymbolCode) + (source.length + target.length) outcome + + theorem integerApproximationAnswer_equal (source target : List ℤ) (heq : source = target) + (outcome : IntegerApproximationOutcome source target) : + integerApproximationAnswer source target outcome = 0 := + computedFullAnswer_equal _ _ _ (congrArg (List.map integerSymbolCode) heq) outcome + + theorem integerApproximation_conditional_accuracy (source target : List ℤ) + (epsilon : BinaryFraction) (hepsilon : 0 < epsilon.value) + (bernstein : ComputedBernsteinInputs (source.length + target.length)) : + (2 / 3 : ℝ) ≤ (integerApproximationLaw source target epsilon).real + {outcome | EditDistortion.edit source target ≤ integerApproximationAnswer source target outcome ∧ + (integerApproximationAnswer source target outcome : ℝ) ≤ + (1 + (epsilon.value : ℝ)) * EditDistortion.edit source target} := by + have h := computed_full_conditional_accuracy (source.map integerSymbolCode) + (target.map integerSymbolCode) (source.length + target.length) epsilon hepsilon + (by simp only [List.length_map, le_refl]) bernstein.1 bernstein.2 + simpa only [integerSymbols_edit, integerApproximationLaw, integerApproximationAnswer] using h + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/IntegerBinaryAccuracy.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/IntegerBinaryAccuracy.lean new file mode 100644 index 0000000000000000000000000000000000000000..8b36284d67f6af7b2fb19752b30bda668d490511 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/IntegerBinaryAccuracy.lean @@ -0,0 +1,78 @@ +import OAI.Combinatorics.EditApproximation.Binary.IntegerBinaryOutput + +namespace OAI + +namespace EditApproximation +open MeasureTheory + +/-- The uniform implementation uses exact dynamic programming below the +proved cutoff and the evaluated binary memo above it. -/ +noncomputable def integerBinaryAnswer (source target : List ℤ) (N : ℕ) (epsilon : BinaryFraction) + (outcome : ComputedFullOutcome (source.map integerSymbolCode) (target.map integerSymbolCode) N) : ℕ := + if physicalLargeInput N epsilon then + match outcome with + | .inl _ => exactSuffixAnswer (source.map integerSymbolCode) (target.map integerSymbolCode) + | .inr execution => bitWordValue (integerBinaryOutput source target N + (computedExecutionAccepted _ _ N execution)).1 + else exactSuffixAnswer (source.map integerSymbolCode) (target.map integerSymbolCode) + +theorem integerBinaryAnswer_large (source target : List ℤ) (N : ℕ) (epsilon : BinaryFraction) + (hlarge : physicalLargeInput N epsilon) (hsize : source.length + target.length ≤ N) + (outcome : ComputedFullOutcome (source.map integerSymbolCode) (target.map integerSymbolCode) N) : + integerBinaryAnswer source target N epsilon outcome = + computedFullAnswer (source.map integerSymbolCode) (target.map integerSymbolCode) N outcome := by + cases outcome with + | inl unitValue => simp only [integerBinaryAnswer, hlarge, ite_true]; rfl + | inr execution => + simp only [integerBinaryAnswer, hlarge, ite_true] + exact integerBinaryOutput_execution source target N epsilon hlarge hsize execution + +theorem integerBinaryAnswer_equal (source target : List ℤ) (N : ℕ) (epsilon : BinaryFraction) + (heq : source = target) + (outcome : ComputedFullOutcome (source.map integerSymbolCode) (target.map integerSymbolCode) N) : + integerBinaryAnswer source target N epsilon outcome = 0 := by + have hm : source.map integerSymbolCode = target.map integerSymbolCode := congrArg _ heq + unfold integerBinaryAnswer + split_ifs + · cases outcome with + | inl unitValue => exact exactSuffixAnswer_equal _ _ hm + | inr execution => + simp only [integerBinaryOutput, computedQueryAnswerWithWork, hm, ite_true] + rfl + · exact exactSuffixAnswer_equal _ _ hm + +/-- Accuracy of the concrete binary answer under the finite Bernstein +hypothesis for the reference algorithm. -/ +theorem integerBinaryAnswer_conditional_accuracy (source target : List ℤ) (N : ℕ) + (epsilon : BinaryFraction) (hepsilon : 0 < epsilon.value) + (hsize : source.length + target.length ≤ N) (bernstein : ComputedBernsteinInputs N) : + (2 / 3 : ℝ) ≤ (computedFullLaw (source.map integerSymbolCode) (target.map integerSymbolCode) N epsilon).real + {outcome | EditDistortion.edit source target ≤ integerBinaryAnswer source target N epsilon outcome ∧ + (integerBinaryAnswer source target N epsilon outcome : ℝ) ≤ + (1 + (epsilon.value : ℝ)) * EditDistortion.edit source target} := by + by_cases hlarge : physicalLargeInput N epsilon + · have heq : integerBinaryAnswer source target N epsilon = + computedFullAnswer (source.map integerSymbolCode) (target.map integerSymbolCode) N := + funext (integerBinaryAnswer_large source target N epsilon hlarge hsize) + rw [heq] + have h := computed_full_conditional_accuracy (source.map integerSymbolCode) (target.map integerSymbolCode) + N epsilon hepsilon (by simpa only [List.length_map] using hsize) bernstein.1 bernstein.2 + simpa only [integerSymbols_edit] using h + · have heq (outcome) : integerBinaryAnswer source target N epsilon outcome = EditDistortion.edit source target := by + simp only [integerBinaryAnswer, hlarge, ite_false, exactSuffixAnswer_eq_edit, integerSymbols_edit] + have hupper : (EditDistortion.edit source target : ℝ) ≤ + (1 + (epsilon.value : ℝ)) * EditDistortion.edit source target := by + have hp : (0 : ℝ) < epsilon.value := by exact_mod_cast hepsilon + nlinarith only [hp, Nat.cast_nonneg (α := ℝ) (EditDistortion.edit source target)] + have hevent : {outcome | EditDistortion.edit source target ≤ integerBinaryAnswer source target N epsilon outcome ∧ + (integerBinaryAnswer source target N epsilon outcome : ℝ) ≤ + (1 + (epsilon.value : ℝ)) * EditDistortion.edit source target} = Set.univ := by + ext outcome + simp only [Set.mem_ofPred_eq, heq, le_refl, true_and, Set.mem_univ, iff_true] + exact hupper + rw [hevent, probReal_univ] + norm_num + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/IntegerBinaryOutput.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/IntegerBinaryOutput.lean new file mode 100644 index 0000000000000000000000000000000000000000..e48caf8c49dd77ab567bde2e77acda31ba6822b1 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/IntegerBinaryOutput.lean @@ -0,0 +1,54 @@ +import OAI.Combinatorics.EditApproximation.Refinement.ComputedQueryOutput +import OAI.Combinatorics.EditApproximation.Binary.IntegerAlgorithm + +namespace OAI + +namespace EditApproximation + +/-- Actual binary output on a fixed accepted finite draw. -/ +def integerBinaryOutput (source target : List ℤ) (N : ℕ) + (input : ComputedFamilyInput (source.map integerSymbolCode) (target.map integerSymbolCode) N) := + computedQueryAnswerWithWork (source.map integerSymbolCode) (target.map integerSymbolCode) N + (integerOccurrenceIndex source target) (integerInputSymbolBits source target) (integerInputPositionBits target) input + +theorem integerBinaryOutput_cost (source target : List ℤ) (N : ℕ) + (epsilon : BinaryFraction) (hlarge : physicalLargeInput N epsilon) + (hsize : source.length + target.length ≤ N) + (input : ComputedFamilyInput (source.map integerSymbolCode) (target.map integerSymbolCode) N) : + (integerBinaryOutput source target N input).2 ≤ N + inputHeight N ^ 10 := by + have hf : 3 ≤ smallLogExponent N := by + have h := (Nat.pow_le_pow_iff_right (by decide : 1 < (2 : ℕ))).mp hlarge.2.1.1 + omega + apply computedQueryAnswerWithWork_cost _ _ _ _ _ _ _ + (largeAccuracyInput_pos N epsilon.value hlarge.2.1) hlarge.2.1.1 hf + (by simpa only [List.length_map] using hsize) hlarge.2.2 + · intro a ha + obtain ⟨z, hz, rfl⟩ := List.mem_map.mp ha + exact integerInputSymbolBits_fits source target z (List.mem_append_left _ hz) + · intro a ha + obtain ⟨z, hz, rfl⟩ := List.mem_map.mp ha + exact integerInputSymbolBits_fits source target z (List.mem_append_right _ hz) + · simpa only [List.length_map, integerInputPositionBits] using (Nat.lt_size_self target.length).le + · rfl + +theorem integerBinaryOutput_execution (source target : List ℤ) (N : ℕ) + (epsilon : BinaryFraction) (hlarge : physicalLargeInput N epsilon) + (hsize : source.length + target.length ≤ N) + (execution : ComputedExecutionOutcome (source.map integerSymbolCode) (target.map integerSymbolCode) N) : + bitWordValue (integerBinaryOutput source target N + (computedExecutionAccepted _ _ N execution)).1 = + computedFullAnswer (source.map integerSymbolCode) (target.map integerSymbolCode) N (.inr execution) := by + apply computedQueryAnswerWithWork_execution _ _ _ epsilon hlarge + (by simpa only [List.length_map] using hsize) + · intro a ha + obtain ⟨z, hz, rfl⟩ := List.mem_map.mp ha + exact integerInputSymbolBits_fits source target z (List.mem_append_left _ hz) + · intro a ha + obtain ⟨z, hz, rfl⟩ := List.mem_map.mp ha + exact integerInputSymbolBits_fits source target z (List.mem_append_right _ hz) + · simpa only [List.length_map, integerInputPositionBits] using (Nat.lt_size_self target.length).le + · rfl + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/IntegerBinarySpace.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/IntegerBinarySpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..6df2a35aa350e9b909b8eb75a5a62211d3e4b5ac --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/IntegerBinarySpace.lean @@ -0,0 +1,236 @@ +import OAI.Combinatorics.EditApproximation.Refinement.ComputedQueryTemporarySpace +import OAI.Combinatorics.EditApproximation.Refinement.ComputedQuerySetupSpace +import OAI.Combinatorics.EditApproximation.Refinement.ComputedCoarseScratchSpace +import OAI.Combinatorics.EditApproximation.Refinement.ComputedCoarseControlSpace +import OAI.Combinatorics.EditApproximation.Binary.IntegerStoredDataSpace +import OAI.Combinatorics.EditApproximation.Binary.IntegerBinaryWork +import OAI.Combinatorics.EditApproximation.Binary.BinaryFinalSpace +import OAI.Combinatorics.EditApproximation.Probability.RejectionSpace + +namespace OAI + +namespace EditApproximation +open Filter + +/-- Final conversion allocates only its division and clamping workspace. -/ +def integerFinalAllocation (source target : List ℤ) (N : ℕ) + (input : ComputedFamilyInput (source.map integerSymbolCode) (target.map integerSymbolCode) N) : ℕ := + if source.map integerSymbolCode = target.map integerSymbolCode then 0 else + BinaryFraction.finalAnswerAllocation N + (computedQueryMemoResult (source.map integerSymbolCode) (target.map integerSymbolCode) N + (integerOccurrenceIndex source target) (integerInputSymbolBits source target) + (integerInputPositionBits target) input).value + +theorem integerFinalAllocation_le_work (source target : List ℤ) (N : ℕ) + (input : ComputedFamilyInput (source.map integerSymbolCode) (target.map integerSymbolCode) N) : + integerFinalAllocation source target N input ≤ (integerBinaryOutput source target N input).2 := by + unfold integerFinalAllocation integerBinaryOutput computedQueryAnswerWithWork + split + · exact Nat.zero_le _ + · exact (BinaryFraction.finalAnswerAllocation_le_work _ _).trans (by dsimp only; omega) + +/-- Scans and word-RAM preprocessing reserve eight scalar/control cells per +charged step. Retained input/index cells are counted separately. Numerical +setup, local programs and coarse initialization use their explicit allocation +counters. Streaming samplers reuse a bounded buffer, without storing failed +trial counts or failed words. -/ +noncomputable def integerAcceptedSpaceTerms (source target : List ℤ) (N : ℕ) + (epsilon : BinaryFraction) + (input : ComputedFamilyInput (source.map integerSymbolCode) (target.map integerSymbolCode) N) : List ℕ := + let x := source.map integerSymbolCode + let y := target.map integerSymbolCode + [8 * integerPreevaluationWork source target N epsilon, + 2 * integerStoredDataSpace source target, + computedQuerySetupAllocation N, + (computedQueryMemoResult x y N (integerOccurrenceIndex source target) + (integerInputSymbolBits source target) (integerInputPositionBits target) input).memory.fractionStorage, + computedQueryTemporaryCells x y N (integerOccurrenceIndex source target) + (integerInputSymbolBits source target) (integerInputPositionBits target) input, + computedFamilyCoarseCopyStorage x y N input, + computedFamilyCoarseArrayCapacity x y N input, + computedFamilyCoarseScratchCapacity x y N input, + computedFamilyCoarseControlCapacity x y N input, + 4 * (inputHeight N + (integerParameters N).B + 4), + integerFinalAllocation source target N input, + 8 * (N + 1)] + +/-- The space bound applies to all outcomes, including null-probability +outcomes. The exact branch uses the concrete suffix-DP allocation counter. -/ +noncomputable def integerBinarySpace (source target : List ℤ) (N : ℕ) (epsilon : BinaryFraction) + (outcome : ComputedFullOutcome (source.map integerSymbolCode) (target.map integerSymbolCode) N) : ℕ := + if physicalLargeInput N epsilon then + match outcome with + | .inl _ => 8 * integerPreevaluationWork source target N epsilon + + 2 * integerStoredDataSpace source target + + suffixDPAllocation (source.map integerSymbolCode) (target.map integerSymbolCode) + 8 * (N + 1) + | .inr execution => (integerAcceptedSpaceTerms source target N epsilon + (computedExecutionAccepted _ _ N execution)).sum + else 8 * integerPreevaluationWork source target N epsilon + + 2 * integerStoredDataSpace source target + + suffixDPAllocation (source.map integerSymbolCode) (target.map integerSymbolCode) + 8 * (N + 1) + +private theorem sum_cells_le (values : List ℕ) (B : ℕ) (h : ∀ x ∈ values, x ≤ B) : + values.sum ≤ values.length * B := by + induction values with + | nil => simp + | cons x xs ih => + have hx := h x List.mem_cons_self + have ht := ih (fun y hy => h y (List.mem_cons_of_mem _ hy)) + simp only [List.sum_cons, List.length_cons, Nat.add_mul, Nat.one_mul] + omega + +private theorem embed_space_power (X K e a : ℕ) (hX : 2 ≤ X) (he : e ≤ K) (ha : a ≤ X ^ e) : + a ≤ X ^ K := ha.trans (Nat.pow_le_pow_right (by omega) he) + +private theorem bounded_space_sum (X K : ℕ) (terms : List ℕ) (hX : 2 ≤ X) + (hl : terms.length ≤ 16) (ht : ∀ a ∈ terms, a ≤ X ^ K) : + terms.sum ≤ X ^ (K + 4) := by + have hs := sum_cells_le terms (X ^ K) ht + have h16 : 16 ≤ X ^ 4 := (by decide : 16 ≤ (2 : ℕ) ^ 4).trans (Nat.pow_le_pow_left hX 4) + calc + _ ≤ terms.length * X ^ K := hs + _ ≤ X ^ 4 * X ^ K := Nat.mul_le_mul_right _ (hl.trans h16) + _ = _ := by rw [← pow_add]; congr 1; omega + +theorem integerBinarySpace_polynomial (C : ℕ) (epsilon : BinaryFraction) + (hepsilon : 0 < epsilon.value) : + ∀ᶠ N : ℕ in atTop, ∀ source target : List ℤ, source.length + target.length ≤ N → + (∀ z ∈ source ++ target, z.natAbs ≤ (N + 2) ^ C) → + ∀ outcome, integerBinarySpace source target N epsilon outcome ≤ (N + 2) ^ (C + 65564) := by + filter_upwards [physicalLargeInput_eventually epsilon hepsilon, + integerPreevaluationWork_near_linear C 1 (by norm_num), integerStoredDataSpace_polynomial C, + integerQueryWidths C, computedQueryTemporaryCells_polynomial, integer_encoded_symbol_bits C, + computedFamilyCoarseCopyStorage_polynomial, computedFamilyCoarseArrayCapacity_polynomial, + computedFamilyCoarseScratchCapacity_polynomial, computedFamilyCoarseControlCapacity_polynomial] + with N hlarge hpre hstored hwidth htemp hsymbols hcopy harray hscratch hcontrol + intro source target hsize halphabet outcome + let X := N + 2 + let K := C + 65560 + change _ ≤ X ^ (C + 65564) + rw [← show K + 4 = C + 65564 by dsimp only [K]] + have hX : 2 ≤ X := by dsimp only [X]; omega + have hN := largeAccuracyInput_pos N epsilon.value hlarge.2.1 + have hell := hlarge.2.1.1 + have hf : 3 ≤ smallLogExponent N := by + have h := (Nat.pow_le_pow_iff_right (by decide : 1 < (2 : ℕ))).mp hell + omega + have hsz : (source.map integerSymbolCode).length + (target.map integerSymbolCode).length ≤ N := by + simpa only [List.length_map] using hsize + have hs (a) (ha : a ∈ source.map integerSymbolCode) : a < 2 ^ integerInputSymbolBits source target := by + obtain ⟨z, hz, rfl⟩ := List.mem_map.mp ha + exact integerInputSymbolBits_fits source target z (List.mem_append_left _ hz) + have ht (a) (ha : a ∈ target.map integerSymbolCode) : a < 2 ^ integerInputSymbolBits source target := by + obtain ⟨z, hz, rfl⟩ := List.mem_map.mp ha + exact integerInputSymbolBits_fits source target z (List.mem_append_right _ hz) + have hp : (target.map integerSymbolCode).length ≤ 2 ^ integerInputPositionBits target := by + simpa only [List.length_map, integerInputPositionBits] using (Nat.lt_size_self target.length).le + have hpre2 : integerPreevaluationWork source target N epsilon ≤ X ^ 2 := by + have h := hpre source target hsize halphabet epsilon + norm_num at h + exact_mod_cast h + have hpreK : 8 * integerPreevaluationWork source target N epsilon ≤ X ^ K := by + apply embed_space_power X K 5 _ hX (by dsimp only [K]; omega) + calc + _ ≤ X ^ 3 * X ^ 2 := Nat.mul_le_mul ((by decide : 8 ≤ (2 : ℕ) ^ 3).trans + (Nat.pow_le_pow_left hX 3)) hpre2 + _ = _ := by rw [← pow_add] + have hstoredK : 2 * integerStoredDataSpace source target ≤ X ^ K := by + apply embed_space_power X K (C + 23) _ hX (by dsimp only [K]; omega) + calc + _ ≤ X * X ^ (C + 22) := Nat.mul_le_mul hX (hstored source target hsize halphabet) + _ = _ := by rw [← pow_succ'] + have hlinearK : 8 * (N + 1) ≤ X ^ K := by + apply embed_space_power X K 4 _ hX (by dsimp only [K]; omega) + calc + _ ≤ X ^ 3 * X := Nat.mul_le_mul ((by decide : 8 ≤ (2 : ℕ) ^ 3).trans + (Nat.pow_le_pow_left hX 3)) (by dsimp only [X]; omega) + _ = _ := by rw [← pow_succ] + have hdpK : suffixDPAllocation (source.map integerSymbolCode) (target.map integerSymbolCode) ≤ X ^ K := by + apply embed_space_power X K 10 _ hX (by dsimp only [K]; omega) + calc + _ ≤ 50 * (N + 1) ^ 4 := suffixDPAllocation_polynomial _ _ N hsz + _ ≤ X ^ 6 * X ^ 4 := Nat.mul_le_mul ((by decide : 50 ≤ (2 : ℕ) ^ 6).trans + (Nat.pow_le_pow_left hX 6)) (Nat.pow_le_pow_left (by dsimp only [X]; omega) 4) + _ = _ := by rw [← pow_add] + have hfallback : 8 * integerPreevaluationWork source target N epsilon + + 2 * integerStoredDataSpace source target + + suffixDPAllocation (source.map integerSymbolCode) (target.map integerSymbolCode) + 8 * (N + 1) ≤ + X ^ (K + 4) := by + have hu : 4 ≤ X ^ 4 := (by decide : 4 ≤ (2 : ℕ) ^ 4).trans (Nat.pow_le_pow_left hX 4) + calc + _ ≤ 4 * X ^ K := by omega + _ ≤ X ^ 4 * X ^ K := Nat.mul_le_mul_right _ hu + _ = _ := by rw [← pow_add, Nat.add_comm 4 K] + simp only [integerBinarySpace, hlarge, ite_true] + cases outcome with + | inl unitValue => exact hfallback + | inr execution => + let input := computedExecutionAccepted (source.map integerSymbolCode) (target.map integerSymbolCode) N execution + have hwidths := hwidth source target hsize halphabet + have hmemo := computedQueryMemoResult_storage (source.map integerSymbolCode) (target.map integerSymbolCode) N + (integerOccurrenceIndex source target) (integerInputSymbolBits source target) (integerInputPositionBits target) + input hN hell hf hsz hlarge.2.2 hs ht hp rfl + have htmp := htemp (source.map integerSymbolCode) (target.map integerSymbolCode) hsz input + (integerOccurrenceIndex source target) (integerInputSymbolBits source target) (integerInputPositionBits target) + hwidths.1 hwidths.2 hs ht hp rfl + have hset := (computedQuerySetupAllocation_le_work N).trans (computedQuerySetupWithWork_cost N hN hell) + have hH48 : inputHeight N ^ 12 ≤ X ^ 48 := + (Nat.pow_le_pow_left (computed_height_polynomial N) 12).trans_eq (by rw [← pow_mul]) + have hsetupK := embed_space_power X K 48 _ hX (by dsimp only [K]; omega) (hset.trans hH48) + have hmemoK := embed_space_power (N + 2) K 65557 + (computedQueryMemoResult (source.map integerSymbolCode) (target.map integerSymbolCode) N + (integerOccurrenceIndex source target) (integerInputSymbolBits source target) + (integerInputPositionBits target) input).memory.fractionStorage hX + ((by decide : 65557 ≤ 65560).trans (Nat.le_add_left 65560 C)) hmemo + have htmpK := embed_space_power X K 20 _ hX (by dsimp only [K]; omega) htmp + have hcopyK := embed_space_power X K 18 _ hX (by dsimp only [K]; omega) + (hcopy _ _ hsz (hsymbols source target halphabet) input) + have harrayK := embed_space_power X K 39 _ hX (by dsimp only [K]; omega) (harray _ _ hsz input) + have hscratchK := embed_space_power X K 183 _ hX (by dsimp only [K]; omega) (hscratch _ _ hsz input) + have hcontrolK := embed_space_power X K 184 _ hX (by dsimp only [K]; omega) (hcontrol _ _ hsz input) + have hbufferK : 4 * (inputHeight N + (integerParameters N).B + 4) ≤ X ^ K := by + have hH : inputHeight N ≤ X ^ 4 := computed_height_polynomial N + have hB : (integerParameters N).B ≤ X ^ 4 := + BinaryFraction.computedCoarseBranching_polynomial N hN + (two_hundred_le_two_pow_thousand.trans hell) + have h4 : 4 ≤ X ^ 4 := (by decide : 4 ≤ (2 : ℕ) ^ 4).trans (Nat.pow_le_pow_left hX 4) + have h16 : 16 ≤ X ^ 4 := (by decide : 16 ≤ (2 : ℕ) ^ 4).trans (Nat.pow_le_pow_left hX 4) + apply embed_space_power X K 8 _ hX (by dsimp only [K]; omega) + calc + _ ≤ 4 * (X ^ 4 + X ^ 4 + X ^ 4) := + Nat.mul_le_mul_left 4 (Nat.add_le_add (Nat.add_le_add hH hB) h4) + _ = 12 * X ^ 4 := by ring + _ ≤ 16 * X ^ 4 := Nat.mul_le_mul_right _ (by decide : 12 ≤ 16) + _ ≤ X ^ 4 * X ^ 4 := Nat.mul_le_mul_right _ h16 + _ = _ := by rw [← pow_add] + have houtK : integerFinalAllocation source target N input ≤ X ^ K := by + have hout := (integerFinalAllocation_le_work source target N input).trans + (integerBinaryOutput_cost source target N epsilon hlarge hsize input) + have hH40 : inputHeight N ^ 10 ≤ X ^ 40 := + (Nat.pow_le_pow_left (computed_height_polynomial N) 10).trans_eq (by rw [← pow_mul]) + have hn : N ≤ X ^ 40 := (by dsimp only [X]; omega : N ≤ X).trans (Nat.le_pow (by decide)) + apply embed_space_power X K 41 _ hX (by dsimp only [K]; omega) + calc + _ ≤ 2 * X ^ 40 := by omega + _ ≤ X * X ^ 40 := Nat.mul_le_mul_right _ hX + _ = _ := by rw [← pow_succ'] + apply bounded_space_sum X K _ hX (by change 12 ≤ 16; decide) + intro a ha + simp only [integerAcceptedSpaceTerms, List.mem_cons, List.not_mem_nil, or_false] at ha + rcases ha with rfl | rfl | rfl | rfl | rfl | rfl | rfl | rfl | rfl | rfl | rfl | rfl + · exact hpreK + · exact hstoredK + · exact hsetupK + · exact hmemoK + · exact htmpK + · exact hcopyK + · exact harrayK + · exact hscratchK + · exact hcontrolK + · exact hbufferK + · exact houtK + · exact hlinearK + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/IntegerBinaryWork.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/IntegerBinaryWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..fa73e3e481a049f7032801df7edb63e8b30c6764 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/IntegerBinaryWork.lean @@ -0,0 +1,72 @@ +import OAI.Combinatorics.EditApproximation.Binary.IntegerBinaryOutput +import OAI.Combinatorics.EditApproximation.Refinement.ComputedOutputWork +import OAI.Combinatorics.EditApproximation.Refinement.ComputedQuerySetup + +namespace OAI + +namespace EditApproximation +open Filter MeasureTheory + +/-- Full integer-input runtime with concrete local, setup, and final-output routines. -/ +noncomputable def integerBinaryWork (source target : List ℤ) (N : ℕ) (epsilon : BinaryFraction) := + computedFullOutputWork (source.map integerSymbolCode) (target.map integerSymbolCode) N + (integerQueryLocalWork source target N) (integerPreevaluationWork source target N epsilon) + (computedQuerySetupWithWork N).2 (fun input => (integerBinaryOutput source target N input).2) + (N + 1) + +theorem integerBinaryWork_expected_near_linear (C : ℕ) (epsilon : BinaryFraction) + (hepsilon : 0 < epsilon.value) (epsilonTime : ℝ) (htime : 0 < epsilonTime) : + ∀ᶠ N : ℕ in atTop, ∀ source target : List ℤ, source.length + target.length ≤ N → + (∀ z ∈ source ++ target, z.natAbs ≤ (N + 2) ^ C) → + (∫ outcome, integerBinaryWork source target N epsilon outcome + ∂computedFullLaw (source.map integerSymbolCode) (target.map integerSymbolCode) N epsilon) ≤ + (N + 2 : ℝ) ^ (1 + epsilonTime) := by + have hh : 0 < epsilonTime / 2 := half_pos htime + filter_upwards [physicalLargeInput_eventually epsilon hepsilon, + integerPreevaluationWork_near_linear C (epsilonTime / 2) hh, + computedExecutionTotalWork_expected_near_linear computedQueryWorkDegree (epsilonTime / 2) hh, + integerQueryLocalWork_cap C, integer_encoded_symbol_bits C, + fixed_height_power_subpolynomial 12 (1 + epsilonTime / 2) (by linarith), + constant_le_rpow_eventually 5 (epsilonTime / 2) hh] with N hlarge hpre hwork hcap hsymbols hpower hfive + intro source target hsize halphabet + have hN := largeAccuracyInput_pos N epsilon.value hlarge.2.1 + have hsetup := computedQuerySetupWithWork_cost N hN hlarge.2.1.1 + have hs : ((computedQuerySetupWithWork N).2 : ℝ) ≤ (N + 2 : ℝ) ^ (1 + epsilonTime / 2) := by + have hc : ((computedQuerySetupWithWork N).2 : ℝ) ≤ (inputHeight N : ℝ) ^ 12 := by + exact_mod_cast hsetup + exact hc.trans hpower + have hten : (inputHeight N : ℝ) ^ 10 ≤ (N + 2 : ℝ) ^ (1 + epsilonTime / 2) := + (pow_le_pow_right₀ (by exact_mod_cast (show 1 ≤ inputHeight N from Nat.one_le_pow _ _ (by decide))) + (by decide : 10 ≤ 12)).trans hpower + have hn : (N : ℝ) ≤ (N + 2 : ℝ) ^ (1 + epsilonTime / 2) := by + calc + _ ≤ (N + 2 : ℝ) := le_add_of_nonneg_right (by norm_num) + _ = (N + 2 : ℝ) ^ (1 : ℝ) := (Real.rpow_one _).symm + _ ≤ (N + 2 : ℝ) ^ (1 + epsilonTime / 2) := + Real.rpow_le_rpow_of_exponent_le (by have := Nat.cast_nonneg (α := ℝ) N; linarith) (by linarith) + have hf (input) : ((integerBinaryOutput source target N input).2 : ℝ) ≤ + 2 * (N + 2 : ℝ) ^ (1 + epsilonTime / 2) := by + have hb := integerBinaryOutput_cost source target N epsilon hlarge hsize input + have hbR : ((integerBinaryOutput source target N input).2 : ℝ) ≤ N + (inputHeight N : ℝ) ^ 10 := by + exact_mod_cast hb + linarith only [hbR, hn, hten] + have hw := hwork (source.map integerSymbolCode) (target.map integerSymbolCode) + (by simpa only [List.length_map] using hsize) (hsymbols source target halphabet) + (integerQueryLocalWork source target N) (hcap source target hsize halphabet) + have hfull := computedFullOutputWork_expected_le (source.map integerSymbolCode) (target.map integerSymbolCode) N + (integerQueryLocalWork source target N) (integerPreevaluationWork source target N epsilon) + (computedQuerySetupWithWork N).2 (fun input => (integerBinaryOutput source target N input).2) (N + 1) + epsilon hlarge ((N + 2 : ℝ) ^ (1 + epsilonTime / 2)) + (2 * (N + 2 : ℝ) ^ (1 + epsilonTime / 2)) hw hf + have hp := hpre source target hsize halphabet epsilon + calc + _ ≤ (integerPreevaluationWork source target N epsilon : ℝ) + (computedQuerySetupWithWork N).2 + + (N + 2 : ℝ) ^ (1 + epsilonTime / 2) + 2 * (N + 2 : ℝ) ^ (1 + epsilonTime / 2) := hfull + _ ≤ 5 * (N + 2 : ℝ) ^ (1 + epsilonTime / 2) := by linarith only [hp, hs] + _ ≤ (N + 2 : ℝ) ^ (epsilonTime / 2) * (N + 2 : ℝ) ^ (1 + epsilonTime / 2) := + mul_le_mul_of_nonneg_right hfive (Real.rpow_nonneg (by positivity) _) + _ = _ := by rw [← Real.rpow_add (by positivity)]; congr 1; ring + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/IntegerCoarseSymbolBits.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/IntegerCoarseSymbolBits.lean new file mode 100644 index 0000000000000000000000000000000000000000..27de2a1f612cf2618d25051141565bca106f21cf --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/IntegerCoarseSymbolBits.lean @@ -0,0 +1,32 @@ +import OAI.Combinatorics.EditApproximation.Geometry.HeightPowerWork + +namespace OAI + +namespace EditApproximation +open Filter + +theorem integer_encoded_symbol_bits (C : ℕ) : + ∀ᶠ N : ℕ in atTop, ∀ source target : List ℤ, + (∀ z ∈ source ++ target, z.natAbs ≤ (N + 2) ^ C) → + ∀ a ∈ source.map integerSymbolCode ++ target.map integerSymbolCode, + Nat.size a ≤ inputHeight N ^ 3 := by + filter_upwards [inputHeight_real_tendsto.eventually + (eventually_ge_atTop ((max 100 C : ℕ) : ℝ))] with N hH + have hH' : max 100 C ≤ inputHeight N := by exact_mod_cast hH + intro source target halphabet a ha + rw [← List.map_append] at ha + obtain ⟨z, hz, rfl⟩ := List.mem_map.mp ha + have hcode : Nat.size (integerSymbolCode z) ≤ integerInputSymbolBits source target := + Nat.size_le.mpr (integerInputSymbolBits_fits source target z hz) + have hs := integerInputSymbolBits_polynomial source target N C halphabet + have hn := input_length_bits_le N + have hCH := Nat.mul_le_mul (show C ≤ inputHeight N by omega) hn + have hcube : 100 * inputHeight N ^ 2 ≤ inputHeight N ^ 3 := by + have hm := Nat.mul_le_mul_right (inputHeight N ^ 2) (show 100 ≤ inputHeight N by omega) + nlinarith only [hm] + have h100 : 100 ≤ inputHeight N := by omega + nlinarith only [hcode, hs, hCH, hcube, h100] + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/IntegerInputInspection.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/IntegerInputInspection.lean new file mode 100644 index 0000000000000000000000000000000000000000..cdccd1c5261b4a235f1ad1bf0c397dccfd05bc9d --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/IntegerInputInspection.lean @@ -0,0 +1,69 @@ +import OAI.Combinatorics.EditApproximation.Binary.IntegerOccurrenceIndex +import OAI.Combinatorics.EditApproximation.Probability.ExactSuffixDPWork +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Explicit linear scans select the input-dependent symbol and position +widths. The alphabet exponent is used only in the analysis. -/ + +namespace EditApproximation + + + + theorem integerMagnitudeWithWork_spec (symbols : List ℤ) : + integerMagnitudeWithWork symbols = (integerMagnitude symbols, 2 * symbols.length) := by + induction symbols with + | nil => rfl + | cons z rest ih => + simp only [integerMagnitudeWithWork, ih, integerMagnitude, List.length_cons] + congr 1 + + theorem integerMagnitude_append (source target : List ℤ) : + integerMagnitude (source ++ target) = max (integerMagnitude source) (integerMagnitude target) := by + induction source with + | nil => simp only [List.nil_append, integerMagnitude, Nat.zero_max] + | cons z rest ih => simp only [List.cons_append, integerMagnitude, ih, max_assoc] + +/-- Count the shifts in a literal binary-length loop. -/ + + +private theorem size_div_two (n : ℕ) (hn : n ≠ 0) : n.size = (n / 2).size + 1 := by + have hb : Nat.bit n.bodd n.div2 ≠ 0 := by rwa [Nat.bit_bodd_div2] + have hs := Nat.size_bit hb + rw [Nat.bit_bodd_div2] at hs + simpa only [Nat.div2_val, Nat.succ_eq_add_one] using hs + + theorem inputBitLengthWithWork_spec (n : ℕ) : + inputBitLengthWithWork n = (n.size, 2 * n.size + 1) := by + induction n using Nat.strong_induction_on with + | h n ih => + rw [inputBitLengthWithWork] + split_ifs with hn + · subst n + rfl + · rw [ih (n / 2) (Nat.div_lt_self (by omega) (by decide)), size_div_two n hn] + congr 1 + + + + theorem integerInputInspectionWithWork_spec (source target : List ℤ) : + (integerInputInspectionWithWork source target).1 = + (integerInputSymbolBits source target, integerInputPositionBits target) := by + simp only [integerInputInspectionWithWork, integerMagnitudeWithWork_spec, + dpLength_spec, inputBitLengthWithWork_spec, integerInputSymbolBits, + integerInputPositionBits, integerMagnitude_append] + + theorem integerInputInspectionWithWork_cost (source target : List ℤ) : + (integerInputInspectionWithWork source target).2 ≤ + 4 * (source.length + target.length) + 2 * integerInputSymbolBits source target + + 2 * integerInputPositionBits target + 8 := by + simp only [integerInputInspectionWithWork, integerMagnitudeWithWork_spec, + dpLength_spec, inputBitLengthWithWork_spec, integerInputSymbolBits, + integerInputPositionBits, integerMagnitude_append] + omega + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/IntegerInputStorage.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/IntegerInputStorage.lean new file mode 100644 index 0000000000000000000000000000000000000000..2f3d35d2e9740c55495f99440f3bdb373bbe66e6 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/IntegerInputStorage.lean @@ -0,0 +1,52 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseInputStorage +import OAI.Combinatorics.EditApproximation.Binary.IntegerCoarseSymbolBits +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation +open Filter + +/-- A sign field, magnitude bits and one pointer/header word per input symbol. -/ + + +theorem storedIntegerBits_le (values : List ℤ) (A : ℕ) + (h : ∀ z ∈ values, z.natAbs ≤ A) : + storedIntegerBits values ≤ 1 + values.length * (A + 2) := by + have hs : (values.map fun z => Nat.size z.natAbs + 2).sum ≤ values.length * (A + 2) := by + induction values with + | nil => simp + | cons z values ih => + have hz : Nat.size z.natAbs ≤ A := + (Nat.size_le.mpr z.natAbs.lt_two_pow_self).trans (h z List.mem_cons_self) + have ht := ih (fun z hz => h z (List.mem_cons_of_mem _ hz)) + simp only [List.map_cons, List.sum_cons, List.length_cons, Nat.add_mul, Nat.one_mul] + omega + exact Nat.add_le_add_left hs 1 + +private theorem pair_storage_power (X C nx ny sx sy : ℕ) (hX : 2 ≤ X) + (hn : nx + ny ≤ X) (hs : sx ≤ 1 + nx * (X ^ C + 2)) + (ht : sy ≤ 1 + ny * (X ^ C + 2)) : sx + sy ≤ X ^ (C + 3) := by + have hp : 1 ≤ X ^ C := one_le_pow₀ (by omega) + have hc : 4 ≤ X ^ 2 := by nlinarith only [hX] + calc + _ ≤ 2 + (nx + ny) * (X ^ C + 2) := by nlinarith only [hs, ht] + _ ≤ 4 * X * X ^ C := by + have hm := Nat.mul_le_mul_right (X ^ C + 2) hn + nlinarith only [hm, hX, Nat.mul_le_mul_left X hp] + _ ≤ X ^ 2 * X * X ^ C := Nat.mul_le_mul_right _ (Nat.mul_le_mul_right X hc) + _ = X ^ (C + 3) := by rw [pow_add]; ring + +theorem storedIntegerInput_polynomial (source target : List ℤ) (N C : ℕ) + (hsize : source.length + target.length ≤ N) + (hsymbol : ∀ z ∈ source ++ target, z.natAbs ≤ (N + 2) ^ C) : + storedIntegerBits source + storedIntegerBits target ≤ (N + 2) ^ (C + 3) := by + exact pair_storage_power (N + 2) C source.length target.length + (storedIntegerBits source) (storedIntegerBits target) (by omega) (by omega) + (storedIntegerBits_le source _ (fun z hz => hsymbol z (List.mem_append_left _ hz))) + (storedIntegerBits_le target _ (fun z hz => hsymbol z (List.mem_append_right _ hz))) + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/IntegerKernelWork.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/IntegerKernelWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..8e814f4074601c93754e84d782b616790a7a48a3 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/IntegerKernelWork.lean @@ -0,0 +1,78 @@ +import OAI.Combinatorics.EditApproximation.Refinement.ComputedExecutionKernelWork +import OAI.Combinatorics.EditApproximation.Binary.IntegerReadChargedWork + +namespace OAI + +namespace EditApproximation +open MeasureTheory Filter + +/-- Full execution counter: the exact fallback branch or the charged +randomized execution, including its concrete local kernel costs. -/ +noncomputable def computedFullKernelWork (source target : List ℕ) (N : ℕ) + (cost : ComputedFamilyInput source target N → ComputedFamilyMemoKey source target N → ℕ) + (setup : ℝ) : ComputedFullOutcome source target N → ℝ + | .inl _ => setup + (chargedSuffixDP source target).2 + | .inr execution => setup + computedExecutionTotalWork source target N cost execution + +theorem computedFullKernelWork_expected_le (source target : List ℕ) (N : ℕ) + (cost : ComputedFamilyInput source target N → ComputedFamilyMemoKey source target N → ℕ) + (epsilon : BinaryFraction) (hlarge : physicalLargeInput N epsilon) (setup budget : ℝ) + (hbudget : (∫ execution, computedExecutionTotalWork source target N cost execution + ∂computedExecutionLaw source target N) ≤ budget) : + (∫ outcome, computedFullKernelWork source target N cost setup outcome + ∂computedFullLaw source target N epsilon) ≤ setup + budget := by + have hmap := integral_map (μ := computedExecutionLaw source target N) + measurable_inr.aemeasurable + (measurable_of_countable (computedFullKernelWork source target N cost setup)).aestronglyMeasurable + simp only [computedFullLaw, hlarge, ite_true] + rw [hmap] + change (∫ execution, setup + computedExecutionTotalWork source target N cost execution + ∂computedExecutionLaw source target N) ≤ setup + budget + rw [integral_add (integrable_const setup) (computedExecutionTotalWork_integrable source target N cost)] + simpa [integral_const, add_comm] using add_le_add_left hbudget setup + +noncomputable def integerFullKernelWork (source target : List ℤ) (N : ℕ) + (epsilon : BinaryFraction) + (cost : ComputedFamilyInput (source.map integerSymbolCode) (target.map integerSymbolCode) N → + ComputedFamilyMemoKey (source.map integerSymbolCode) (target.map integerSymbolCode) N → ℕ) : + ComputedFullOutcome (source.map integerSymbolCode) (target.map integerSymbolCode) N → ℝ := + computedFullKernelWork (source.map integerSymbolCode) (target.map integerSymbolCode) N cost + (integerPreevaluationWork source target N epsilon) + +/-- Runtime transport for the concrete local evaluator, with no additional +probability hypothesis. -/ +theorem integerFullKernelWork_expected_near_linear (C D : ℕ) + (epsilon : BinaryFraction) (hepsilon : 0 < epsilon.value) + (epsilonTime : ℝ) (htime : 0 < epsilonTime) : + ∀ᶠ N in atTop, ∀ source target : List ℤ, source.length + target.length ≤ N → + (∀ z ∈ source ++ target, z.natAbs ≤ (N + 2) ^ C) → + ∀ cost : ComputedFamilyInput (source.map integerSymbolCode) (target.map integerSymbolCode) N → + ComputedFamilyMemoKey (source.map integerSymbolCode) (target.map integerSymbolCode) N → ℕ, + (∀ input key, cost input key ≤ computedLocalKernelBudget D N) → + (∫ outcome, integerFullKernelWork source target N epsilon cost outcome + ∂computedFullLaw (source.map integerSymbolCode) (target.map integerSymbolCode) N epsilon) ≤ + (N + 2 : ℝ) ^ (1 + epsilonTime) := by + have hh : 0 < epsilonTime / 2 := half_pos htime + filter_upwards [physicalLargeInput_eventually epsilon hepsilon, + integerPreevaluationWork_near_linear C (epsilonTime / 2) hh, + computedExecutionTotalWork_expected_near_linear D (epsilonTime / 2) hh, + constant_le_rpow_eventually 2 (epsilonTime / 2) hh, integer_encoded_symbol_bits C] + with N hlarge hsetup hwork htwo hsymbols + intro source target hsize halphabet cost hcost + have hw := hwork (source.map integerSymbolCode) (target.map integerSymbolCode) + (by simpa only [List.length_map] using hsize) (hsymbols source target halphabet) cost hcost + have hs := hsetup source target hsize halphabet epsilon + have hf := computedFullKernelWork_expected_le (source.map integerSymbolCode) + (target.map integerSymbolCode) N cost epsilon hlarge + (integerPreevaluationWork source target N epsilon) ((N + 2 : ℝ) ^ (1 + epsilonTime / 2)) hw + calc + _ ≤ (integerPreevaluationWork source target N epsilon : ℝ) + + (N + 2 : ℝ) ^ (1 + epsilonTime / 2) := hf + _ ≤ 2 * (N + 2 : ℝ) ^ (1 + epsilonTime / 2) := by linarith only [hs] + _ ≤ (N + 2 : ℝ) ^ (epsilonTime / 2) * (N + 2 : ℝ) ^ (1 + epsilonTime / 2) := + mul_le_mul_of_nonneg_right htwo (Real.rpow_nonneg (by positivity) _) + _ = _ := by rw [← Real.rpow_add (by positivity)]; congr 1; ring + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/IntegerOccurrenceIndex.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/IntegerOccurrenceIndex.lean new file mode 100644 index 0000000000000000000000000000000000000000..72eebff5eed61b96f33011894e4586b7c32d5387 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/IntegerOccurrenceIndex.lean @@ -0,0 +1,119 @@ +import OAI.Combinatorics.EditApproximation.Binary.IntegerSymbols +import OAI.Combinatorics.EditApproximation.Geometry.OccurrenceLeaf +import OAI.Combinatorics.EditApproximation.Numerics.NumericalWork +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Uniform input preparation chooses dictionary widths from the actual +integer words. No alphabet size or polynomial exponent is an algorithm input. -/ + +namespace EditApproximation + + + +theorem integerMagnitude_mem (zs : List ℤ) (z : ℤ) (hz : z ∈ zs) : + z.natAbs ≤ integerMagnitude zs := by + induction zs with + | nil => simp at hz + | cons a zs ih => + rcases List.mem_cons.mp hz with rfl | hz + · exact le_max_left _ _ + · exact (ih hz).trans (le_max_right _ _) + +theorem integerMagnitude_le (zs : List ℤ) (B : ℕ) (h : ∀ z ∈ zs, z.natAbs ≤ B) : + integerMagnitude zs ≤ B := by + induction zs with + | nil => exact Nat.zero_le _ + | cons z zs ih => + exact max_le (h z List.mem_cons_self) (ih fun a ha => h a (List.mem_cons_of_mem _ ha)) + + + + + +theorem integerInputSymbolBits_fits (source target : List ℤ) (z : ℤ) + (hz : z ∈ source ++ target) : + integerSymbolCode z < 2 ^ integerInputSymbolBits source target := by + exact ((integerSymbolCode_bound z).trans + (Nat.mul_le_mul_left 2 (integerMagnitude_mem _ z hz))).trans_lt (Nat.lt_size_self _) + +theorem integerInputSymbolBits_le (source target : List ℤ) (B : ℕ) + (h : ∀ z ∈ source ++ target, z.natAbs ≤ B) : + integerInputSymbolBits source target ≤ Nat.size (2 * B) := + Nat.size_le_size (Nat.mul_le_mul_left 2 (integerMagnitude_le _ B h)) + + + +def integerOccurrenceQuery (source target : List ℤ) (z : ℤ) (lo hi : ℕ) : Bool := + occurrenceQuery (integerOccurrenceIndex source target) + (integerInputSymbolBits source target) (integerInputPositionBits target) + (integerSymbolCode z) lo hi + +theorem integerOccurrenceQuery_correct (source target : List ℤ) (z : ℤ) + (hz : z ∈ source ++ target) (lo hi : ℕ) (hlohi : lo ≤ hi) (hhi : hi ≤ target.length) : + integerOccurrenceQuery source target z lo hi = true ↔ z ∈ substring target lo hi := by + have hcodes : ∀ a ∈ target.map integerSymbolCode, + a < 2 ^ integerInputSymbolBits source target := by + intro a ha + obtain ⟨z, hz, rfl⟩ := List.mem_map.mp ha + exact integerInputSymbolBits_fits source target z (List.mem_append_right _ hz) + have h := occurrenceQuery_target + (integerInputSymbolBits source target) (integerInputPositionBits target) + (target.map integerSymbolCode) hcodes + (by simpa [integerInputPositionBits] using (Nat.lt_size_self target.length).le) + (integerSymbolCode z) lo hi (integerInputSymbolBits_fits source target z hz) + hlohi (by simpa using hhi) + change _ ↔ _ at h + change occurrenceQuery _ _ _ _ _ _ = true ↔ _ + unfold integerOccurrenceIndex + rw [h] + have hmap : substring (target.map integerSymbolCode) lo hi = + (substring target lo hi).map integerSymbolCode := by + simp only [substring, List.map_drop, List.map_take] + rw [hmap] + constructor + · intro hm + obtain ⟨a, ha, heq⟩ := List.mem_map.mp hm + exact (integerSymbolCode_injective heq) ▸ ha + · intro hm + exact List.mem_map.mpr ⟨z, hm, rfl⟩ + + + +theorem integerOccurrenceBuildWithWork_spec (source target : List ℤ) : + integerOccurrenceBuildWithWork source target = + (integerOccurrenceIndex source target, + target.length * (3 * integerInputSymbolBits source target + + 2 * integerInputPositionBits target + 5)) := by + rw [integerOccurrenceBuildWithWork, occurrenceBuildWithWork_spec] + simp only [List.length_zipIdx, List.length_map, integerOccurrenceIndex] + +/-- Polynomially bounded input words produce logarithmic dictionary keys; +the polynomial degree is only an analysis parameter. -/ +theorem integerInputSymbolBits_polynomial (source target : List ℤ) (N C : ℕ) + (h : ∀ z ∈ source ++ target, z.natAbs ≤ (N + 2) ^ C) : + integerInputSymbolBits source target ≤ C * Nat.size (N + 2) + 3 := by + have hbits := integerInputSymbolBits_le source target ((N + 2) ^ C) h + have hmul := natural_product_bit_length 2 ((N + 2) ^ C) + have hpow := natural_power_bit_length (N + 2) C + have htwo : Nat.size 2 = 2 := by decide + omega + +theorem integerOccurrenceBuildWithWork_polynomial (source target : List ℤ) (N C : ℕ) + (hsize : source.length + target.length ≤ N) + (h : ∀ z ∈ source ++ target, z.natAbs ≤ (N + 2) ^ C) : + (integerOccurrenceBuildWithWork source target).2 ≤ + N * ((3 * C + 2) * Nat.size (N + 2) + 14) := by + rw [integerOccurrenceBuildWithWork_spec] + dsimp only + have hs := integerInputSymbolBits_polynomial source target N C h + have hp : integerInputPositionBits target ≤ Nat.size (N + 2) := + Nat.size_le_size (by omega) + apply Nat.mul_le_mul (by omega) + nlinarith + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/IntegerOccurrenceStorage.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/IntegerOccurrenceStorage.lean new file mode 100644 index 0000000000000000000000000000000000000000..b017d16c619ada1bb27da5b4be05ec6abdab970f --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/IntegerOccurrenceStorage.lean @@ -0,0 +1,64 @@ +import OAI.Combinatorics.EditApproximation.Geometry.OccurrenceStorage +import OAI.Combinatorics.EditApproximation.Binary.IntegerOccurrenceIndex +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation +open Filter + +/-- Actual counters and trie nodes of the encoded target occurrence index. -/ + + +theorem integerOccurrenceStorage_bound (source target : List ℤ) (N C : ℕ) + (hsize : source.length + target.length ≤ N) + (hsymbol : ∀ z ∈ source ++ target, z.natAbs ≤ (N + 2) ^ C) : + integerOccurrenceStorage source target ≤ 9 * (C + 2) * (N + 2) ^ 5 := by + have h := occurrenceBuild_storage (integerInputSymbolBits source target) + (integerInputPositionBits target) ((target.map integerSymbolCode).zipIdx) + simp only [List.length_zipIdx, List.length_map] at h + change integerOccurrenceStorage source target ≤ _ at h + let X := N + 2 + have hX : 2 ≤ X := by dsimp only [X]; omega + have hn : target.length ≤ X := by dsimp only [X]; omega + have hsz : Nat.size target.length ≤ X := + (Nat.size_le_size hn).trans (Nat.size_le.mpr X.lt_two_pow_self) + have hp : integerInputPositionBits target + 1 ≤ 2 * X := by + change Nat.size target.length + 1 ≤ 2 * X + omega + have hs : integerInputSymbolBits source target + 1 ≤ (C + 2) * X := by + have hs := integerInputSymbolBits_polynomial source target N C hsymbol + have hb : Nat.size (N + 2) ≤ X := Nat.size_le.mpr X.lt_two_pow_self + nlinarith only [hs, hb, hX] + have hcounter : Nat.size target.length + 3 ≤ 3 * X := by omega + have hpos := Nat.mul_le_mul hn hp + have htree := Nat.mul_le_mul hcounter hpos + have hdict := Nat.mul_le_mul hn hs + have hunit : 1 ≤ X ^ 3 := one_le_pow₀ (by omega) + have hv : (Nat.size target.length + 3) * (target.length * + (integerInputPositionBits target + 1)) + 3 ≤ 9 * X ^ 3 := by + nlinarith only [htree, hunit] + calc + _ ≤ ((Nat.size target.length + 3) * (target.length * + (integerInputPositionBits target + 1)) + 3) * + (target.length * (integerInputSymbolBits source target + 1)) := h + _ ≤ (9 * X ^ 3) * (X * ((C + 2) * X)) := Nat.mul_le_mul hv hdict + _ = _ := by ring + +theorem integerOccurrenceStorage_polynomial (C : ℕ) : + ∀ᶠ N : ℕ in atTop, ∀ source target : List ℤ, + source.length + target.length ≤ N → + (∀ z ∈ source ++ target, z.natAbs ≤ (N + 2) ^ C) → + integerOccurrenceStorage source target ≤ (N + 2) ^ 6 := by + filter_upwards [eventually_ge_atTop (9 * (C + 2))] with N hN + intro source target hsize hsymbol + calc + _ ≤ 9 * (C + 2) * (N + 2) ^ 5 := + integerOccurrenceStorage_bound source target N C hsize hsymbol + _ ≤ (N + 2) * (N + 2) ^ 5 := Nat.mul_le_mul_right _ (by omega) + _ = _ := by ring + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/IntegerPreprocessing.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/IntegerPreprocessing.lean new file mode 100644 index 0000000000000000000000000000000000000000..c169c4553e73049c678828e48ba5cd704be7a6b0 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/IntegerPreprocessing.lean @@ -0,0 +1,105 @@ +import OAI.Combinatorics.EditApproximation.Binary.IntegerInputInspection +import OAI.Combinatorics.EditApproximation.Refinement.ComputedWidthEnvelope +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation +open Filter +open scoped Topology + + + + theorem integerEqualWithWork_spec (source target : List ℤ) : + (integerEqualWithWork source target).1 = decide (source = target) ∧ + (integerEqualWithWork source target).2 ≤ source.length + target.length + 1 := by + induction source generalizing target with + | nil => cases target <;> simp [integerEqualWithWork] + | cons x xs ih => + cases target with + | nil => simp [integerEqualWithWork] + | cons y ys => + by_cases hxy : x = y + · subst y + have h := ih ys + constructor + · simpa [integerEqualWithWork] using h.1 + · simpa [integerEqualWithWork, Nat.add_assoc, Nat.add_comm, Nat.add_left_comm] using + (show (integerEqualWithWork xs ys).2 + 1 ≤ xs.length + ys.length + 3 by omega) + · simp [integerEqualWithWork, hxy] + +/-- Scans, integer encoding, indexed occurrence preprocessing and the +exact equality guard are charged before the local evaluator starts. -/ + + + theorem input_length_bits_le (N : ℕ) : Nat.size (N + 2) ≤ inputHeight N + 1 := by + apply Nat.size_le.mpr + exact (inputHeight_covers_length N).trans_lt + (Nat.pow_lt_pow_right (by decide : 1 < 2) (Nat.lt_succ_self _)) + +private theorem preprocessing_scalar_bound (N H C L s p : ℕ) + (hH : 8 ≤ H) (hC : C ≤ H) (hL : L ≤ H + 1) + (hs : s ≤ C * L + 3) (hp : p ≤ L) : + 4 * N + 2 * s + 2 * p + 8 + 3 * N + N * ((3 * C + 2) * L + 14) + (N + 1) + 1 ≤ + (N + 2) * H ^ 4 := by + have hCL := Nat.mul_le_mul hC hL + have hs' : s ≤ 3 * H ^ 2 := by nlinarith only [hs, hCL, hH] + have hp' : p ≤ H + 1 := hp.trans hL + have hcoef0 := Nat.mul_le_mul (by omega : 3 * C + 2 ≤ 3 * H + 2) hL + have hcoef : (3 * C + 2) * L + 22 ≤ 10 * H ^ 2 := by + nlinarith only [hcoef0, hH] + have hcN := Nat.mul_le_mul_left N hcoef + have hsquare : 10 * H ^ 2 ≤ H ^ 4 := by + have hh : 10 ≤ H ^ 2 := by nlinarith only [hH] + have hm := Nat.mul_le_mul_right (H ^ 2) hh + nlinarith only [hm] + have hm := Nat.mul_le_mul_left (N + 2) hsquare + nlinarith only [hs', hp', hcN, hm, hH] + + theorem integerPreprocessingWork_le (source target : List ℤ) (N C : ℕ) + (hsize : source.length + target.length ≤ N) + (halphabet : ∀ z ∈ source ++ target, z.natAbs ≤ (N + 2) ^ C) + (hH : 8 ≤ inputHeight N) (hC : C ≤ inputHeight N) : + integerPreprocessingWork source target ≤ (N + 2) * inputHeight N ^ 4 := by + have hi := integerInputInspectionWithWork_cost source target + have heq := (integerEqualWithWork_spec source target).2 + have hoc := integerOccurrenceBuildWithWork_polynomial source target N C hsize halphabet + have hs := integerInputSymbolBits_polynomial source target N C halphabet + have hp : integerInputPositionBits target ≤ Nat.size (N + 2) := Nat.size_le_size (by omega) + have hscalar := preprocessing_scalar_bound N (inputHeight N) C (Nat.size (N + 2)) + (integerInputSymbolBits source target) (integerInputPositionBits target) hH hC + (input_length_bits_le N) hs hp + unfold integerPreprocessingWork + rw [encodeIntegerSymbolsWithWork_spec, encodeIntegerSymbolsWithWork_spec] + dsimp only + omega + + theorem fixed_height_power_near_linear (C : ℕ) (epsilon : ℝ) (hepsilon : 0 < epsilon) : + ∀ᶠ N : ℕ in atTop, (N + 2 : ℝ) * (inputHeight N : ℝ) ^ C ≤ (N + 2 : ℝ) ^ (1 + epsilon) := by + have hlog : Tendsto (fun N : ℕ => Real.log (inputHeight N : ℝ) / inputHeight N) + atTop (𝓝 0) := + Real.isLittleO_log_id_atTop.tendsto_div_nhds_zero.comp inputHeight_real_tendsto + have hlimit := hlog.const_mul (C : ℝ) + simp only [mul_zero] at hlimit + have hf : Tendsto (fun N => ((C : ℝ) * Real.log (inputHeight N : ℝ)) / inputHeight N) + atTop (𝓝 0) := by convert hlimit using 1; ext N; ring + filter_upwards [sublinear_height_near_linear _ hf epsilon hepsilon] with N hN + rwa [← nat_pow_eq_exp_log (inputHeight N) C (Nat.two_pow_pos _)] at hN + + theorem integerPreprocessingWork_near_linear (C : ℕ) (epsilon : ℝ) (hepsilon : 0 < epsilon) : + ∀ᶠ N in atTop, ∀ source target : List ℤ, source.length + target.length ≤ N → + (∀ z ∈ source ++ target, z.natAbs ≤ (N + 2) ^ C) → + (integerPreprocessingWork source target : ℝ) ≤ (N + 2 : ℝ) ^ (1 + epsilon) := by + filter_upwards [fixed_height_power_near_linear 4 epsilon hepsilon, + inputSmallLog_tendsto.eventually (eventually_ge_atTop (max 8 C))] with N htime hH + intro source target hsize halphabet + have hn := integerPreprocessingWork_le source target N C hsize halphabet + ((le_max_left _ _).trans (hH.trans (computed_smallLog_le_height N))) + ((le_max_right _ _).trans (hH.trans (computed_smallLog_le_height N))) + exact (show (integerPreprocessingWork source target : ℝ) ≤ + (N + 2 : ℝ) * (inputHeight N : ℝ) ^ 4 by exact_mod_cast hn).trans htime + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/IntegerQueryWork.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/IntegerQueryWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..56cc3df1df73c2d60810dd18017c68e77ae9beaf --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/IntegerQueryWork.lean @@ -0,0 +1,73 @@ +import OAI.Combinatorics.EditApproximation.Refinement.ComputedQueryWork +import OAI.Combinatorics.EditApproximation.Binary.IntegerKernelWork + +namespace OAI + +namespace EditApproximation +open Filter MeasureTheory + +/-- The actual computed widths of the encoded input index. -/ +theorem integerQueryWidths (C : ℕ) : + ∀ᶠ N : ℕ in atTop, ∀ source target : List ℤ, source.length + target.length ≤ N → + (∀ z ∈ source ++ target, z.natAbs ≤ (N + 2) ^ C) → + integerInputSymbolBits source target ≤ inputHeight N ^ 3 ∧ + integerInputPositionBits target ≤ inputHeight N ^ 3 := by + filter_upwards [inputSmallLog_tendsto.eventually (eventually_ge_atTop (max 100 C))] with N hlarge + intro source target hsize halphabet + have hH : 100 ≤ inputHeight N := (le_max_left _ _).trans (hlarge.trans (computed_smallLog_le_height N)) + have hC : C ≤ inputHeight N := (le_max_right _ _).trans (hlarge.trans (computed_smallLog_le_height N)) + have hs := integerInputSymbolBits_polynomial source target N C halphabet + have hN := input_length_bits_le N + have hm := Nat.mul_le_mul hC hN + have hc : inputHeight N * (inputHeight N + 1) + 3 ≤ inputHeight N ^ 3 := by + have h := Nat.mul_le_mul_right (inputHeight N ^ 2) (show 3 ≤ inputHeight N by omega) + nlinarith only [hH, h] + refine ⟨by omega, ?_⟩ + exact (Nat.size_le_size (show target.length ≤ N from by omega)).trans + ((computed_input_size_le_height N).trans (Nat.le_pow (by decide))) + +def integerQueryLocalWork (source target : List ℤ) (N : ℕ) := + computedQueryLocalWork (source.map integerSymbolCode) (target.map integerSymbolCode) N + (integerOccurrenceIndex source target) (integerInputSymbolBits source target) (integerInputPositionBits target) + +theorem integerQueryLocalWork_cap (C : ℕ) : + ∀ᶠ N : ℕ in atTop, ∀ source target : List ℤ, source.length + target.length ≤ N → + (∀ z ∈ source ++ target, z.natAbs ≤ (N + 2) ^ C) → + ∀ input key, integerQueryLocalWork source target N input key ≤ + computedLocalKernelBudget computedQueryWorkDegree N := by + filter_upwards [computedQueryLocalWork_cap, integerQueryWidths C] with N hwork hwidth + intro source target hsize halphabet input key + have hw := hwidth source target hsize halphabet + apply hwork (source.map integerSymbolCode) (target.map integerSymbolCode) + (by simpa only [List.length_map] using hsize) input (integerOccurrenceIndex source target) + (integerInputSymbolBits source target) (integerInputPositionBits target) hw.1 hw.2 + ?_ ?_ ?_ rfl key + · intro a ha + obtain ⟨z, hz, rfl⟩ := List.mem_map.mp ha + exact integerInputSymbolBits_fits source target z (List.mem_append_left _ hz) + · intro a ha + obtain ⟨z, hz, rfl⟩ := List.mem_map.mp ha + exact integerInputSymbolBits_fits source target z (List.mem_append_right _ hz) + · simpa only [List.length_map, integerInputPositionBits] using (Nat.lt_size_self target.length).le + +/-- Complete integer-input cost with the proved local program, rather than an +unspecified per-key annotation. -/ +noncomputable def integerQueryWork (source target : List ℤ) (N : ℕ) (epsilon : BinaryFraction) := + integerFullKernelWork source target N epsilon (integerQueryLocalWork source target N) + +theorem integerQueryWork_expected_near_linear (C : ℕ) (epsilon : BinaryFraction) + (hepsilon : 0 < epsilon.value) (epsilonTime : ℝ) (htime : 0 < epsilonTime) : + ∀ᶠ N : ℕ in atTop, ∀ source target : List ℤ, source.length + target.length ≤ N → + (∀ z ∈ source ++ target, z.natAbs ≤ (N + 2) ^ C) → + (∫ outcome, integerQueryWork source target N epsilon outcome + ∂computedFullLaw (source.map integerSymbolCode) (target.map integerSymbolCode) N epsilon) ≤ + (N + 2 : ℝ) ^ (1 + epsilonTime) := by + filter_upwards [integerFullKernelWork_expected_near_linear C computedQueryWorkDegree + epsilon hepsilon epsilonTime htime, integerQueryLocalWork_cap C] with N hwork hcap + intro source target hsize halphabet + exact hwork source target hsize halphabet (integerQueryLocalWork source target N) + (hcap source target hsize halphabet) + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/IntegerReadChargedWork.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/IntegerReadChargedWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..7069646d9910b9ce8cbc89b72a1b867812a3982a --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/IntegerReadChargedWork.lean @@ -0,0 +1,68 @@ +import OAI.Combinatorics.EditApproximation.Refinement.ComputedReadChargedWork +import OAI.Combinatorics.EditApproximation.Binary.IntegerCoarseSymbolBits +import OAI.Combinatorics.EditApproximation.Refinement.ComputedPreevaluation +import OAI.Combinatorics.EditApproximation.Binary.IntegerAlgorithm + +namespace OAI + +namespace EditApproximation +open MeasureTheory Filter + +noncomputable def computedFullReadChargedWork (source target : List ℕ) (N : ℕ) (setup : ℝ) : + ComputedFullOutcome source target N → ℝ + | .inl _ => setup + (chargedSuffixDP source target).2 + | .inr execution => setup + computedExecutionReadChargedWork source target N execution + + theorem computedFullReadChargedWork_expected_le (source target : List ℕ) (N : ℕ) + (epsilon : BinaryFraction) (hlarge : physicalLargeInput N epsilon) (setup budget : ℝ) + (hbudget : (∫ execution, computedExecutionReadChargedWork source target N execution + ∂computedExecutionLaw source target N) ≤ budget) : + (∫ outcome, computedFullReadChargedWork source target N setup outcome + ∂computedFullLaw source target N epsilon) ≤ setup + budget := by + have hmap := integral_map (μ := computedExecutionLaw source target N) + measurable_inr.aemeasurable + (measurable_of_countable (computedFullReadChargedWork source target N setup)).aestronglyMeasurable + simp only [computedFullLaw, hlarge, ite_true] + rw [hmap] + change (∫ execution, setup + computedExecutionReadChargedWork source target N execution + ∂computedExecutionLaw source target N) ≤ setup + budget + rw [integral_add (integrable_const setup) (computedExecutionReadChargedWork_integrable source target N)] + simpa [integral_const, add_comm] using add_le_add_left hbudget setup + +noncomputable def integerFullReadChargedWork (source target : List ℤ) (N : ℕ) + (epsilon : BinaryFraction) : + ComputedFullOutcome (source.map integerSymbolCode) (target.map integerSymbolCode) N → ℝ := + computedFullReadChargedWork (source.map integerSymbolCode) (target.map integerSymbolCode) N + (integerPreevaluationWork source target N epsilon) + + theorem integerFullReadChargedWork_expected_near_linear (C : ℕ) + (epsilon : BinaryFraction) (hepsilon : 0 < epsilon.value) + (epsilonTime : ℝ) (htime : 0 < epsilonTime) : + ∀ᶠ N in atTop, ∀ source target : List ℤ, source.length + target.length ≤ N → + (∀ z ∈ source ++ target, z.natAbs ≤ (N + 2) ^ C) → + (∫ outcome, integerFullReadChargedWork source target N epsilon outcome + ∂computedFullLaw (source.map integerSymbolCode) (target.map integerSymbolCode) N epsilon) ≤ + (N + 2 : ℝ) ^ (1 + epsilonTime) := by + have hh : 0 < epsilonTime / 2 := half_pos htime + filter_upwards [physicalLargeInput_eventually epsilon hepsilon, + integerPreevaluationWork_near_linear C (epsilonTime / 2) hh, + computedExecutionReadChargedWork_expected_near_linear (epsilonTime / 2) hh, + constant_le_rpow_eventually 2 (epsilonTime / 2) hh, integer_encoded_symbol_bits C] with N hlarge hsetup hwork htwo hsymbols + intro source target hsize halphabet + have hw := hwork (source.map integerSymbolCode) (target.map integerSymbolCode) + (by simpa only [List.length_map] using hsize) (hsymbols source target halphabet) + have hs := hsetup source target hsize halphabet epsilon + have hf := computedFullReadChargedWork_expected_le (source.map integerSymbolCode) + (target.map integerSymbolCode) N epsilon hlarge + (integerPreevaluationWork source target N epsilon) ((N + 2 : ℝ) ^ (1 + epsilonTime / 2)) hw + calc + _ ≤ (integerPreevaluationWork source target N epsilon : ℝ) + + (N + 2 : ℝ) ^ (1 + epsilonTime / 2) := hf + _ ≤ 2 * (N + 2 : ℝ) ^ (1 + epsilonTime / 2) := by linarith only [hs] + _ ≤ (N + 2 : ℝ) ^ (epsilonTime / 2) * (N + 2 : ℝ) ^ (1 + epsilonTime / 2) := + mul_le_mul_of_nonneg_right htwo (Real.rpow_nonneg (by positivity) _) + _ = _ := by rw [← Real.rpow_add (by positivity)]; congr 1; ring + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/IntegerStoredDataSpace.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/IntegerStoredDataSpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..70a0593808b8d030c2fd6f5b57cd269b29d92c30 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/IntegerStoredDataSpace.lean @@ -0,0 +1,72 @@ +import OAI.Combinatorics.EditApproximation.Binary.IntegerInputStorage +import OAI.Combinatorics.EditApproximation.Binary.IntegerOccurrenceStorage +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation +open Filter + +private theorem natural_pair_storage (source target : List ℕ) (X A : ℕ) + (hX : 2 ≤ X) (hsize : source.length + target.length ≤ X) + (hwidth : ∀ a ∈ source ++ target, Nat.size a ≤ X ^ A) : + storedNaturalBits source + storedNaturalBits target ≤ X ^ (A + 3) := by + have hs := storedNaturalBits_le source (X ^ A) + (fun a ha => hwidth a (List.mem_append_left _ ha)) + have ht := storedNaturalBits_le target (X ^ A) + (fun a ha => hwidth a (List.mem_append_right _ ha)) + have hp : 1 ≤ X ^ A := one_le_pow₀ (by omega) + have hm := Nat.mul_le_mul_right (X ^ A + 1) hsize + have hc : 4 ≤ X ^ 2 := by nlinarith only [hX] + calc + _ ≤ 4 * X * X ^ A := by nlinarith only [hs, ht, hm, hX, Nat.mul_le_mul_left X hp] + _ ≤ X ^ 2 * X * X ^ A := Nat.mul_le_mul_right _ (Nat.mul_le_mul_right X hc) + _ = _ := by rw [pow_add]; ring + +theorem storedNaturalInput_polynomial (source target : List ℕ) (N : ℕ) + (hsize : source.length + target.length ≤ N) + (hsymbol : ∀ a ∈ source ++ target, Nat.size a ≤ inputHeight N ^ 3) : + storedNaturalBits source + storedNaturalBits target ≤ (N + 2) ^ 15 := by + have hh := Nat.pow_le_pow_left (computed_height_polynomial N) 3 + rw [← pow_mul] at hh + exact natural_pair_storage source target (N + 2) 12 (by omega) (by omega) + (fun a ha => (hsymbol a ha).trans hh) + +/-- The explicitly retained original integer input, its encoded arrays, +and the target occurrence index. -/ + + +private theorem combine_input_storage (X C raw encoded index : ℕ) (hX : 2 ≤ X) + (hr : raw ≤ X ^ (C + 3)) (he : encoded ≤ X ^ 15) (hi : index ≤ X ^ 6) : + raw + encoded + index ≤ X ^ (C + 22) := by + let K := C + 20 + have hpos : 0 < X := by omega + have hr' : raw ≤ X ^ K := hr.trans (Nat.pow_le_pow_right hpos (by dsimp only [K]; omega)) + have he' : encoded ≤ X ^ K := he.trans (Nat.pow_le_pow_right hpos (by dsimp only [K]; omega)) + have hi' : index ≤ X ^ K := hi.trans (Nat.pow_le_pow_right hpos (by dsimp only [K]; omega)) + calc + _ ≤ 3 * X ^ K := by omega + _ ≤ X ^ 2 * X ^ K := Nat.mul_le_mul_right _ (by nlinarith only [hX]) + _ = _ := by rw [← pow_add]; congr 1; dsimp only [K]; omega + +theorem integerStoredDataSpace_polynomial (C : ℕ) : + ∀ᶠ N : ℕ in atTop, ∀ source target : List ℤ, + source.length + target.length ≤ N → + (∀ z ∈ source ++ target, z.natAbs ≤ (N + 2) ^ C) → + integerStoredDataSpace source target ≤ (N + 2) ^ (C + 22) := by + filter_upwards [integer_encoded_symbol_bits C, integerOccurrenceStorage_polynomial C] + with N hbits hindex + intro source target hsize hsymbols + have hr := storedIntegerInput_polynomial source target N C hsize hsymbols + have he := storedNaturalInput_polynomial (source.map integerSymbolCode) + (target.map integerSymbolCode) N (by simpa only [List.length_map] using hsize) + (hbits source target hsymbols) + have hi := hindex source target hsize hsymbols + have h := combine_input_storage (N + 2) C _ _ _ (by omega) hr he hi + unfold integerStoredDataSpace + omega + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/IntegerSymbols.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/IntegerSymbols.lean new file mode 100644 index 0000000000000000000000000000000000000000..f5c798396eb1b7ec946a080fdeae31500f271d2f --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/IntegerSymbols.lean @@ -0,0 +1,57 @@ +import OAI.Combinatorics.EditApproximation.Geometry.InputViews +import Mathlib.Logic.Equiv.Nat +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Integer word labels are encoded injectively using a sign bit. The +encoding preserves the actual unit-cost edit distance and takes one +linear pass; no constant-alphabet hypothesis is used. -/ + +namespace EditApproximation + + + +theorem integerSymbolCode_eq (z : ℤ) : integerSymbolCode z = Equiv.intEquivNat z := by + cases z <;> rfl + +theorem integerSymbolCode_injective : Function.Injective integerSymbolCode := by + intro x y heq + apply Equiv.intEquivNat.injective + simpa only [integerSymbolCode_eq] using heq + +theorem integerSymbolCode_bound (z : ℤ) : integerSymbolCode z ≤ 2 * z.natAbs := by + cases z <;> simp only [integerSymbolCode, Int.natAbs] <;> omega + +theorem integerSymbolCode_bits (bound bits : ℕ) (hcapacity : 2 * (bound + 1) ≤ 2 ^ bits) + (z : ℤ) (hz : z.natAbs ≤ bound) : integerSymbolCode z < 2 ^ bits := by + have hcode := integerSymbolCode_bound z + omega + +theorem integerSymbols_edit (source target : List ℤ) : + EditDistortion.edit (source.map integerSymbolCode) (target.map integerSymbolCode) = + EditDistortion.edit source target := by + apply EditDistortion.cost_map_eq_of_leftInverse integerSymbolCode Equiv.intEquivNat.symm + intro z + rw [integerSymbolCode_eq] + exact Equiv.intEquivNat.symm_apply_apply z + +theorem integerSymbols_equal_iff (source target : List ℤ) : + source.map integerSymbolCode = target.map integerSymbolCode ↔ source = target := + ⟨fun h => (List.map_injective_iff.mpr integerSymbolCode_injective) h, + fun h => congrArg (List.map integerSymbolCode) h⟩ + + + +theorem encodeIntegerSymbolsWithWork_spec (symbols : List ℤ) : + encodeIntegerSymbolsWithWork symbols = (symbols.map integerSymbolCode, 3 * symbols.length) := by + induction symbols with + | nil => rfl + | cons z zs ih => + simp only [encodeIntegerSymbolsWithWork, ih, List.map_cons, List.length_cons] + congr 1 + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/SignedBinaryOrderWork.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/SignedBinaryOrderWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..1ec2ad583f01c914b89f82d4bfab24b138aabd11 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/SignedBinaryOrderWork.lean @@ -0,0 +1,50 @@ +import OAI.Combinatorics.EditApproximation.Binary.SignedBinaryWork +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Signed comparisons performed on Boolean magnitude words, including the +noncanonical negative-zero representation. -/ + +namespace EditApproximation +namespace SignedBinary + + + +theorem nonzeroWithWork_value (bits : List Bool) : + (nonzeroWithWork bits).1 = true ↔ bitWordValue bits ≠ 0 := by + simp [nonzeroWithWork, bitCompareWithWork_eq, bitWordValue] + + + +theorem ltWithWork_value (a b : SignedBinary) : + (a.ltWithWork b).1 = true ↔ a.value < b.value := by + cases ha : a.negative <;> cases hb : b.negative + · simp [ltWithWork, ha, hb, value, signedMagnitude, bitCompareWithWork_lt] + · simp [ltWithWork, ha, hb, value, signedMagnitude] + · simp only [ltWithWork, ha, hb, ↓reduceIte, Bool.false_eq_true, + Bool.or_eq_true, nonzeroWithWork_value, value, signedMagnitude] + omega + · simp [ltWithWork, ha, hb, value, signedMagnitude, bitCompareWithWork_lt] + +theorem nonzeroWithWork_cost (bits : List Bool) : + (nonzeroWithWork bits).2 ≤ 4 * bits.length + 2 := by + have h := bitCompareWithWork_cost bits [] + simp only [List.length_nil, Nat.add_zero] at h + change (bitCompareWithWork bits []).2 + 1 ≤ _ + omega + +theorem ltWithWork_cost (a b : SignedBinary) : + (a.ltWithWork b).2 ≤ 4 * (a.bits.length + b.bits.length) + 8 := by + have hab := bitCompareWithWork_cost a.bits b.bits + have hba := bitCompareWithWork_cost b.bits a.bits + have ha := nonzeroWithWork_cost a.bits + have hb := nonzeroWithWork_cost b.bits + cases hna : a.negative <;> cases hnb : b.negative <;> + simp only [ltWithWork, hna, hnb, Bool.false_eq_true, ↓reduceIte] <;> omega + +end SignedBinary +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/SignedBinaryWork.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/SignedBinaryWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..12a268ea4289f230ca1d4fcc3df53ed6eed3293a --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/SignedBinaryWork.lean @@ -0,0 +1,117 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinarySubtractWork +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Signed integers represented by a sign bit and a Boolean magnitude word. +Arithmetic uses Boolean ripple and shift-add routines. -/ + +namespace EditApproximation + + + + + +namespace SignedBinary + + + + + + + + + + + +@[simp] theorem value_ofInt (a : ℤ) : (ofInt a).value = a := by + by_cases h : a < 0 + · simpa only [ofInt, value, bitWordValue_bits, signedMagnitude, h, decide_true, + ↓reduceIte] using (Int.eq_neg_natAbs_of_nonpos (by omega : a ≤ 0)).symm + · simpa only [ofInt, value, bitWordValue_bits, signedMagnitude, h, decide_false, + Bool.false_eq_true, ↓reduceIte] using (Int.eq_natAbs_of_nonneg (by omega : 0 ≤ a)).symm + +@[simp] theorem value_neg (a : SignedBinary) : a.neg.value = -a.value := by + cases a with + | mk negative bits => cases negative <;> simp [neg, value, signedMagnitude] + +private theorem subtract_signed_value (negative : Bool) (a b : List Bool) + (h : bitWordValue b ≤ bitWordValue a) : + signedMagnitude negative (bitWordValue (bitSubtractWithWork a b false).1) = + signedMagnitude negative (bitWordValue a) - signedMagnitude negative (bitWordValue b) := by + rw [bitSubtractWithWork_sub a b h] + cases negative <;> simp only [signedMagnitude, Bool.false_eq_true, ↓reduceIte ] + · exact Int.ofNat_sub h + · rw [Int.ofNat_sub h] + ring + +theorem addWithWork_value (a b : SignedBinary) : + (a.addWithWork b).1.value = a.value + b.value := by + by_cases hsign : a.negative = b.negative + · simp only [addWithWork, hsign, ↓reduceIte, value, bitAddWithWork_value, + Bool.toNat_false, Nat.add_zero] + rw [← hsign] + cases a.negative <;> simp [signedMagnitude, add_comm] + · simp only [addWithWork, hsign, ↓reduceIte] + have hcomparison := bitCompareWithWork_matches a.bits b.bits + rcases hcomparison with ⟨hcompare, hlt⟩ | ⟨hcompare, heq⟩ | ⟨hcompare, hgt⟩ + · rw [hcompare] + change signedMagnitude b.negative (bitWordValue (bitSubtractWithWork b.bits a.bits false).1) = _ + rw [subtract_signed_value b.negative b.bits a.bits hlt.le] + cases ha : a.negative <;> cases hb : b.negative <;> + simp_all [value, signedMagnitude] + all_goals ring + · rw [hcompare] + cases ha : a.negative <;> cases hb : b.negative <;> + simp_all [value, signedMagnitude, bitWordValue] + · rw [hcompare] + change signedMagnitude a.negative (bitWordValue (bitSubtractWithWork a.bits b.bits false).1) = _ + rw [subtract_signed_value a.negative a.bits b.bits hgt.le] + cases ha : a.negative <;> cases hb : b.negative <;> + simp_all [value, signedMagnitude] + all_goals ring + +theorem mulWithWork_value (a b : SignedBinary) : + (a.mulWithWork b).1.value = a.value * b.value := by + simp only [mulWithWork, value, bitMulWithWork_value] + cases a.negative <;> cases b.negative <;> simp [signedMagnitude] + +theorem addWithWork_cost (a b : SignedBinary) : + (a.addWithWork b).2 ≤ 20 * (a.bits.length + b.bits.length + 1) := by + have hadd := bitAddWithWork_cost a.bits b.bits false + have hcompare := bitCompareWithWork_cost a.bits b.bits + have hsub1 := bitSubtractWithWork_cost a.bits b.bits false + have hsub2 := bitSubtractWithWork_cost b.bits a.bits false + unfold addWithWork + split_ifs + · change (bitAddWithWork a.bits b.bits false).2 + 4 ≤ _ + omega + · dsimp only + cases (bitCompareWithWork a.bits b.bits).1 <;> simp only [] <;> omega + +theorem mulWithWork_cost (a b : SignedBinary) : + (a.mulWithWork b).2 ≤ 24 * (a.bits.length + b.bits.length + 1) ^ 2 := by + have hmul := bitMulWithWork_cost a.bits b.bits + change (bitMulWithWork a.bits b.bits).2 + 4 ≤ _ + nlinarith only [hmul] + +theorem addWithWork_length (a b : SignedBinary) : + (a.addWithWork b).1.bits.length ≤ max a.bits.length b.bits.length + 1 := by + have hadd := bitAddWithWork_length a.bits b.bits false + have hsub1 := bitSubtractWithWork_length a.bits b.bits false + have hsub2 := bitSubtractWithWork_length b.bits a.bits false + unfold addWithWork + split_ifs + · exact hadd + · dsimp only + cases (bitCompareWithWork a.bits b.bits).1 <;> simp only [List.length_nil] <;> omega + +theorem mulWithWork_length (a b : SignedBinary) : + (a.mulWithWork b).1.bits.length ≤ 2 * a.bits.length + b.bits.length + 1 := + bitMulWithWork_length a.bits b.bits + +end SignedBinary +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/UnreducedNumerics.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/UnreducedNumerics.lean new file mode 100644 index 0000000000000000000000000000000000000000..5e98a395263125146e3bae32f56538683a721464 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/UnreducedNumerics.lean @@ -0,0 +1,150 @@ +import OAI.Combinatorics.EditApproximation.Binary.UnreducedRational +import OAI.Combinatorics.EditApproximation.Numerics.Numerics +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! The numerical primitives executed on unreduced fractions. Their exact +values agree with the rational routines; their stored denominators +have polynomial bit length without cancellation or Euclidean normalization. -/ + +namespace EditApproximation + +open Finset +namespace UnreducedRational + +def one : UnreducedRational := ofRat 1 + + + +def sub (a b : UnreducedRational) : UnreducedRational := a.add b.neg + +def pow (a : UnreducedRational) : ℕ → UnreducedRational + | 0 => one + | n + 1 => (pow a n).mul a + +@[simp] theorem value_one : one.value = 1 := value_ofRat _ +@[simp] theorem value_nat (n : ℕ) : (nat n).value = n := by simp [nat, value] +@[simp] theorem value_sub (a b : UnreducedRational) : (a.sub b).value = a.value - b.value := by + simp [sub, sub_eq_add_neg] + +@[simp] theorem value_pow (a : UnreducedRational) (n : ℕ) : (a.pow n).value = a.value ^ n := by + induction n with + | zero => simp [pow] + | succ n ih => simp [pow, ih, pow_succ] + +theorem pow_den (a : UnreducedRational) (n : ℕ) : (a.pow n).den = a.den ^ n := by + induction n with + | zero => simp [pow, one, ofRat] + | succ n ih => simp [pow, mul, ih, pow_succ] + +theorem pow_den_bits (a : UnreducedRational) (n : ℕ) : + Nat.size (a.pow n).den ≤ n * Nat.size a.den + 1 := by + rw [pow_den] + exact natural_power_bit_length _ _ + +theorem nat_inv_den (n : ℕ) (hn : 0 < n) : (nat n).inv.den = n := by + simp [nat, inv, hn.ne'] + +def logarithmPartial (b : UnreducedRational) : ℕ → UnreducedRational + | 0 => zero + | K + 1 => (logarithmPartial b K).add ((b.pow (2 * K + 1)).div (nat (2 * K + 1))) + +def logarithm (r : UnreducedRational) (K : ℕ) : UnreducedRational := + (nat 2).mul (logarithmPartial ((r.sub one).div (r.add one)) K) + +theorem logarithmPartial_value (b : UnreducedRational) (K : ℕ) : + (logarithmPartial b K).value = + ∑ k ∈ range K, b.value ^ (2 * k + 1) / (2 * k + 1 : ℕ) := by + induction K with + | zero => simp [logarithmPartial] + | succ K ih => simp [logarithmPartial, ih, sum_range_succ] + +@[simp] theorem logarithm_value (r : UnreducedRational) (K : ℕ) : + (logarithm r K).value = rationalLogApproximation r.value K := by + simp [logarithm, logarithmPartial_value, rationalLogApproximation] + +theorem logarithmPartial_den_bits (b : UnreducedRational) (K : ℕ) : + Nat.size (logarithmPartial b K).den ≤ + K * K * Nat.size b.den + K * (Nat.size (2 * K + 1) + 1) + 1 := by + induction K with + | zero => simp [logarithmPartial, zero] + | succ K ih => + have hp := pow_den_bits b (2 * K + 1) + have ht := mul_den_bits (b.pow (2 * K + 1)) (nat (2 * K + 1)).inv + rw [nat_inv_den _ (by omega)] at ht + have ha := add_den_bits (logarithmPartial b K) + ((b.pow (2 * K + 1)).div (nat (2 * K + 1))) + have hs := Nat.size_le_size (by omega : 2 * K + 1 ≤ 2 * (K + 1) + 1) + change Nat.size ((logarithmPartial b K).add + ((b.pow (2 * K + 1)).div (nat (2 * K + 1)))).den ≤ _ + change Nat.size ((b.pow (2 * K + 1)).div (nat (2 * K + 1))).den ≤ _ at ht + have hweighted := Nat.mul_le_mul_left K hs + nlinarith only [ih, hp, ht, ha, hweighted, hs] + +theorem logarithm_storageBits (r : UnreducedRational) (K : ℕ) (hr : 0 ≤ r.value) : + (logarithm r K).storageBits ≤ Nat.size (2 * K) + + 2 * (K * K * Nat.size ((r.sub one).div (r.add one)).den + + K * (Nat.size (2 * K + 1) + 1) + 1) + 1 := by + apply storageBits_le + · rw [logarithm_value] + simpa only [Nat.cast_mul, Nat.cast_ofNat] using rationalLogApproximation_abs_bound r.value K hr + · simpa only [logarithm, mul, nat, Nat.one_mul] using + logarithmPartial_den_bits ((r.sub one).div (r.add one)) K + +def optimizerStep (j : ℕ) : UnreducedRational := (nat 2).div (nat (j + 2)) + +def optimizerIterate {ι : Type*} (initial : ι → UnreducedRational) + (selected : ℕ → ι → UnreducedRational) : ℕ → ι → UnreducedRational + | 0 => initial + | j + 1 => fun i => ((one.sub (optimizerStep j)).mul (optimizerIterate initial selected j i)).add + ((optimizerStep j).mul (selected j i)) + +@[simp] theorem optimizerStep_value (j : ℕ) : + (optimizerStep j).value = 2 / ((j : ℚ) + 2) := by + simp [optimizerStep] + +theorem optimizerIterate_value {ι : Type*} (initial : ι → UnreducedRational) + (selected : ℕ → ι → UnreducedRational) (K : ℕ) (i : ι) : + (optimizerIterate initial selected K i).value = + rationalOptimizerIterate (fun i => (initial i).value) (fun j i => (selected j i).value) K i := by + induction K with + | zero => rfl + | succ K ih => simp [optimizerIterate, rationalOptimizerIterate, ih] + +theorem optimizerStep_den (j : ℕ) : (optimizerStep j).den = j + 2 := by + change (nat 2).den * (nat (j + 2)).inv.den = j + 2 + rw [nat_inv_den _ (by omega)] + simp [nat] + +theorem optimizerIterate_den_bits {ι : Type*} (initial : ι → UnreducedRational) + (selected : ℕ → ι → UnreducedRational) (K B : ℕ) (i : ι) + (hinitial : Nat.size (initial i).den ≤ B) + (hselected : ∀ j < K, Nat.size (selected j i).den ≤ B) : + Nat.size (optimizerIterate initial selected K i).den ≤ + B + K * (2 * Nat.size (K + 1) + B) := by + induction K with + | zero => simpa [optimizerIterate] using hinitial + | succ K ih => + have hp := ih (fun j hj => hselected j (by omega)) + have hs := hselected K (by omega) + have hsize := Nat.size_le_size (by omega : K + 1 ≤ K + 1 + 1) + have hfirst := mul_den_bits (one.sub (optimizerStep K)) (optimizerIterate initial selected K i) + have hsecond := mul_den_bits (optimizerStep K) (selected K i) + have hsum := add_den_bits + ((one.sub (optimizerStep K)).mul (optimizerIterate initial selected K i)) + ((optimizerStep K).mul (selected K i)) + have hcomplement : (one.sub (optimizerStep K)).den = K + 2 := by + simp only [sub, add, neg, one, ofRat, Rat.den_one, Nat.one_mul, optimizerStep_den] + rw [hcomplement] at hfirst + rw [optimizerStep_den] at hsecond + change Nat.size (((one.sub (optimizerStep K)).mul (optimizerIterate initial selected K i)).add + ((optimizerStep K).mul (selected K i))).den ≤ _ + have hweighted := Nat.mul_le_mul_left K hsize + nlinarith only [hp, hs, hfirst, hsecond, hsum, hweighted] + +end UnreducedRational +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/UnreducedOptimizer.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/UnreducedOptimizer.lean new file mode 100644 index 0000000000000000000000000000000000000000..10bebdf6e61399bc594cd50af623cbcc3b4e9b5e --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/UnreducedOptimizer.lean @@ -0,0 +1,180 @@ +import OAI.Combinatorics.EditApproximation.Binary.UnreducedNumerics +import OAI.Combinatorics.EditApproximation.Numerics.VectorOptimizerWork +import OAI.Combinatorics.EditApproximation.Numerics.OptimizerBits + +namespace OAI + +/-! A fraction-only implementation of the actual finite optimizer. None of +its arithmetic or score comparisons requires reduced rational numbers. -/ + +namespace EditApproximation + +open Finset +namespace UnreducedRational + +def scoredArgmax {α : Type*} (score : α → UnreducedRational) : List α → Option (α × UnreducedRational) + | [] => none + | a :: rest => + let current := score a + match scoredArgmax score rest with + | none => some (a, current) + | some best => if current.lt best.2 then some best else some (a, current) + +theorem scoredArgmax_spec {α : Type*} (score : α → UnreducedRational) (values : List α) : + scoredArgmax score values = + (values.argmax (fun a => (score a).value)).map (fun a => (a, score a)) := by + induction values with + | nil => rfl + | cons a rest ih => + simp only [scoredArgmax, ih, List.argmax_cons] + cases h : rest.argmax (fun a => (score a).value) with + | none => rfl + | some best => simp only [Option.map_some, lt_eq_true]; split_ifs <;> rfl + +def dotList {d : ℕ} (left right : Vector UnreducedRational d) : List (Fin d) → UnreducedRational + | [] => zero + | i :: rest => ((left.get i).mul (right.get i)).add (dotList left right rest) + +def dot {d : ℕ} (left right : Vector UnreducedRational d) : UnreducedRational := + dotList left right (List.finRange d) + +theorem dotList_value {d : ℕ} (left right : Vector UnreducedRational d) (indices : List (Fin d)) : + (dotList left right indices).value = + (indices.map fun i => (left.get i).value * (right.get i).value).sum := by + induction indices with + | nil => simp [dotList] + | cons i rest ih => simp [dotList, ih] + +theorem dot_value {d : ℕ} (left right : Vector UnreducedRational d) : + (dot left right).value = ∑ i, (left.get i).value * (right.get i).value := by + simp only [dot, dotList_value] + rw [← List.ofFn_eq_map, List.sum_ofFn] + +def gradientCell {d : ℕ} (G : ℕ) (linear point : Vector UnreducedRational d) (i : Fin d) : UnreducedRational := + ((logarithm ((point.get i).add ((nat G).pow 50).inv) (G ^ 60)).neg.sub one).add (linear.get i) + +def gradient {d : ℕ} (G : ℕ) (linear point : Vector UnreducedRational d) : Vector UnreducedRational d := + Vector.ofFn (gradientCell G linear point) + +theorem gradient_value {d : ℕ} (G : ℕ) (linear point : Vector UnreducedRational d) (i : Fin d) : + ((gradient G linear point).get i).value = + rationalSmoothedGradient G (fun i => (linear.get i).value) (fun i => (point.get i).value) i := by + simp [gradient, gradientCell, rationalSmoothedGradient, one_div] + +def maximizer {d : ℕ} (gradient : Vector UnreducedRational d) + (vertices : List (Vector UnreducedRational d)) : Vector UnreducedRational d := + ((scoredArgmax (dot gradient) vertices).map Prod.fst).getD (Vector.replicate d zero) + +theorem maximizer_value {d : ℕ} (gradient : Vector UnreducedRational d) + (vertices : List (Vector UnreducedRational d)) : + (fun i => ((maximizer gradient vertices).get i).value) = + rationalLinearizationMaximizer univ + (vertices.map fun vertex i => (vertex.get i).value) (fun i => (gradient.get i).value) := by + have hmap := argmax_map_commutes (fun vertex : Vector UnreducedRational d => fun i => (vertex.get i).value) + (fun vertex => ∑ i, (gradient.get i).value * vertex i) vertices + simp only [maximizer, scoredArgmax_spec, dot_value, Option.map_map, Function.comp_def] + unfold rationalLinearizationMaximizer + rw [hmap] + cases h : vertices.argmax (fun vertex => ∑ i, (gradient.get i).value * (vertex.get i).value) with + | none => funext i; simp [value_zero] + | some vertex => rfl + +def finiteOptimizer {d : ℕ} (vertices : List (Vector UnreducedRational d)) + (linear : Vector UnreducedRational d) (G : ℕ) : ℕ → Vector UnreducedRational d + | 0 => vertices.headD (Vector.replicate d zero) + | j + 1 => + let previous := finiteOptimizer vertices linear G j + let selected := maximizer (gradient G linear previous) vertices + Vector.ofFn fun i => ((one.sub (optimizerStep j)).mul (previous.get i)).add + ((optimizerStep j).mul (selected.get i)) + +theorem finiteOptimizer_value {d : ℕ} (vertices : List (Vector UnreducedRational d)) + (linear : Vector UnreducedRational d) (G K : ℕ) : + (fun i => ((finiteOptimizer vertices linear G K).get i).value) = + finiteRationalOptimizer univ (vertices.map fun vertex i => (vertex.get i).value) + (fun i => (linear.get i).value) G K := by + induction K with + | zero => + cases vertices with + | nil => funext i; simp [finiteOptimizer, finiteRationalOptimizer] + | cons vertex rest => rfl + | succ K ih => + funext i + simp only [finiteOptimizer, vector_get_ofFn, value_add, value_mul, value_sub, value_one, + optimizerStep_value, finiteRationalOptimizer] + rw [congrFun ih i] + have hm := maximizer_value (gradient G linear (finiteOptimizer vertices linear G K)) vertices + have hg : (fun i => ((gradient G linear (finiteOptimizer vertices linear G K)).get i).value) = + rationalSmoothedGradient G (fun i => (linear.get i).value) + (finiteRationalOptimizer univ (vertices.map fun vertex i => (vertex.get i).value) + (fun i => (linear.get i).value) G K) := by + funext i + rw [gradient_value] + rw [ih] + rw [hg] at hm + rw [congrFun hm i] + +theorem maximizer_mem {d : ℕ} (gradient : Vector UnreducedRational d) + (vertices : List (Vector UnreducedRational d)) (hvertices : vertices ≠ []) : + maximizer gradient vertices ∈ vertices := by + unfold maximizer + rw [scoredArgmax_spec] + cases h : vertices.argmax (fun vertex => (dot gradient vertex).value) with + | none => exact False.elim (hvertices (List.argmax_eq_none.mp h)) + | some vertex => + simp only [Option.map_some, Option.getD_some] + exact List.argmax_mem (by rw [h]; simp) + +theorem finiteOptimizer_eq_iterate {d : ℕ} (vertices : List (Vector UnreducedRational d)) + (linear : Vector UnreducedRational d) (G K : ℕ) (i : Fin d) : + (finiteOptimizer vertices linear G K).get i = + optimizerIterate (vertices.headD (Vector.replicate d zero)).get + (fun j => (maximizer (gradient G linear (finiteOptimizer vertices linear G j)) vertices).get) K i := by + induction K with + | zero => rfl + | succ K ih => simp only [finiteOptimizer, vector_get_ofFn, optimizerIterate, ih] + +theorem finiteOptimizer_den_bits {d : ℕ} (vertices : List (Vector UnreducedRational d)) + (linear : Vector UnreducedRational d) (G K B : ℕ) (i : Fin d) + (hvertices : vertices ≠ []) + (hinput : ∀ vertex ∈ vertices, Nat.size (vertex.get i).den ≤ B) : + Nat.size ((finiteOptimizer vertices linear G K).get i).den ≤ + B + K * (2 * Nat.size (K + 1) + B) := by + rw [finiteOptimizer_eq_iterate] + apply optimizerIterate_den_bits + · apply hinput + cases vertices with + | nil => exact False.elim (hvertices rfl) + | cons vertex rest => exact List.mem_cons_self + · intro j _ + exact hinput _ (maximizer_mem _ vertices hvertices) + +theorem finiteOptimizer_storageBits {d : ℕ} (vertices : List (Vector UnreducedRational d)) + (linear : Vector UnreducedRational d) (G K B : ℕ) (i : Fin d) + (hvertices : vertices ≠ []) + (hinput : ∀ vertex ∈ vertices, + (0 ≤ (vertex.get i).value ∧ (vertex.get i).value ≤ 1) ∧ Nat.size (vertex.get i).den ≤ B) : + ((finiteOptimizer vertices linear G K).get i).storageBits ≤ + 2 * (B + K * (2 * Nat.size (K + 1) + B)) + 2 := by + have hlist : (vertices.map fun vertex j => (vertex.get j).value) ≠ [] := by + intro h + exact hvertices (List.map_eq_nil_iff.mp h) + have hpoint := finiteRationalOptimizer_coordinate_bounds univ + (vertices.map fun vertex j => (vertex.get j).value) (fun j => (linear.get j).value) + G K hlist i (by + intro vertex hv + obtain ⟨stored, hs, rfl⟩ := List.mem_map.mp hv + exact (hinput stored hs).1) + rw [← congrFun (finiteOptimizer_value vertices linear G K) i] at hpoint + have h := storageBits_le ((finiteOptimizer vertices linear G K).get i) 1 + (B + K * (2 * Nat.size (K + 1) + B)) (by + rw [abs_of_nonneg hpoint.1] + exact hpoint.2) (finiteOptimizer_den_bits vertices linear G K B i hvertices + (fun vertex hv => (hinput vertex hv).2)) + simp only [Nat.size_one] at h + omega + +end UnreducedRational +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/UnreducedRational.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/UnreducedRational.lean new file mode 100644 index 0000000000000000000000000000000000000000..6a4aae1023abeef0c2e3e3f3779972eaed48f55d --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/UnreducedRational.lean @@ -0,0 +1,127 @@ +import OAI.Combinatorics.EditApproximation.Numerics.RationalIntermediateBits +import OAI.Combinatorics.EditApproximation.Binary.BinaryArithmeticWork +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Exact fractions with positive, unreduced denominators. These operations +perform no greatest-common-divisor computation. The representation lemmas +apply to the intermediate fractions, not merely their reduced Rat values. -/ + +namespace EditApproximation + + + +namespace UnreducedRational + +theorem eq_of_num_den {a b : UnreducedRational} (hnum : a.num = b.num) (hden : a.den = b.den) : a = b := by + cases a + cases b + cases hnum + cases hden + rfl + + + +def ofRat (a : ℚ) : UnreducedRational := ⟨a.num, a.den, a.den_pos⟩ + + + +def add (a b : UnreducedRational) : UnreducedRational := + ⟨a.num * b.den + b.num * a.den, a.den * b.den, Nat.mul_pos a.den_pos b.den_pos⟩ + +def neg (a : UnreducedRational) : UnreducedRational := ⟨-a.num, a.den, a.den_pos⟩ + + + + + + + +def le (a b : UnreducedRational) : Bool := decide (a.num * b.den ≤ b.num * a.den) + + + +def storageBits (a : UnreducedRational) : ℕ := Nat.size a.num.natAbs + Nat.size a.den + 1 + +@[simp] theorem value_ofRat (a : ℚ) : (ofRat a).value = a := by + exact a.num_div_den + +@[simp] theorem value_zero : zero.value = 0 := by simp [zero, value] + +@[simp] theorem value_add (a b : UnreducedRational) : (a.add b).value = a.value + b.value := by + unfold add value + push_cast + have ha : (a.den : ℚ) ≠ 0 := by exact_mod_cast a.den_pos.ne' + have hb : (b.den : ℚ) ≠ 0 := by exact_mod_cast b.den_pos.ne' + field_simp [ha, hb] + +@[simp] theorem value_neg (a : UnreducedRational) : a.neg.value = -a.value := by + simp [neg, value, neg_div] + +@[simp] theorem value_mul (a b : UnreducedRational) : (a.mul b).value = a.value * b.value := by + simp [mul, value, mul_div_mul_comm] + +@[simp] theorem value_inv (a : UnreducedRational) : a.inv.value = a.value⁻¹ := by + by_cases h : a.num = 0 + · simp [inv, h, value, zero] + · have hn : (a.num.natAbs : ℚ) ≠ 0 := by exact_mod_cast (Int.natAbs_pos.mpr h).ne' + have hd : (a.den : ℚ) ≠ 0 := by exact_mod_cast a.den_pos.ne' + have hsign : ((a.num.sign : ℤ) : ℚ) * a.num = (a.num.natAbs : ℚ) := by + simpa only [Int.cast_mul, Int.cast_natCast] using + congrArg (fun z : ℤ => (z : ℚ)) (Int.sign_mul_self_eq_natAbs a.num) + simp only [inv, h, ↓reduceDIte, value] + push_cast + apply eq_inv_of_mul_eq_one_left + field_simp [hn, hd] + exact hsign + +@[simp] theorem value_div (a b : UnreducedRational) : (a.div b).value = a.value / b.value := by + simp [div, div_eq_mul_inv] + +@[simp] theorem le_eq_true (a b : UnreducedRational) : a.le b = true ↔ a.value ≤ b.value := by + simp only [le, decide_eq_true_eq, value] + rw [div_le_div_iff₀ (by exact_mod_cast a.den_pos : (0 : ℚ) < a.den) + (by exact_mod_cast b.den_pos : (0 : ℚ) < b.den)] + exact_mod_cast (Iff.rfl : a.num * (b.den : ℤ) ≤ b.num * (a.den : ℤ) ↔ _) + +@[simp] theorem lt_eq_true (a b : UnreducedRational) : a.lt b = true ↔ a.value < b.value := by + simp only [lt, decide_eq_true_eq, value] + rw [div_lt_div_iff₀ (by exact_mod_cast a.den_pos : (0 : ℚ) < a.den) + (by exact_mod_cast b.den_pos : (0 : ℚ) < b.den)] + exact_mod_cast (Iff.rfl : a.num * (b.den : ℤ) < b.num * (a.den : ℤ) ↔ _) + +theorem add_den_bits (a b : UnreducedRational) : + Nat.size (a.add b).den ≤ Nat.size a.den + Nat.size b.den := + natural_product_bit_length _ _ + +theorem mul_den_bits (a b : UnreducedRational) : + Nat.size (a.mul b).den ≤ Nat.size a.den + Nat.size b.den := + natural_product_bit_length _ _ + +theorem num_abs_le (a : UnreducedRational) (V : ℕ) (hvalue : |a.value| ≤ V) : + a.num.natAbs ≤ V * a.den := by + have hscaled := mul_le_mul_of_nonneg_right hvalue + (show (0 : ℚ) ≤ a.den by exact_mod_cast a.den_pos.le) + have hnum : |a.value| * (a.den : ℚ) = (a.num.natAbs : ℚ) := by + unfold value + rw [abs_div, abs_of_pos (by exact_mod_cast a.den_pos : (0 : ℚ) < a.den)] + rw [div_mul_cancel₀ _ (by exact_mod_cast a.den_pos.ne' : (a.den : ℚ) ≠ 0)] + simp [Int.cast_abs] + rw [hnum] at hscaled + exact_mod_cast hscaled + +theorem storageBits_le (a : UnreducedRational) (V D : ℕ) + (hvalue : |a.value| ≤ V) (hden : Nat.size a.den ≤ D) : + a.storageBits ≤ Nat.size V + 2 * D + 1 := by + have hnum := (Nat.size_le_size (a.num_abs_le V hvalue)).trans + (natural_product_bit_length V a.den) + unfold storageBits + omega + +end UnreducedRational + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Binary/UnreducedStorage.lean b/lean/OAI/Combinatorics/EditApproximation/Binary/UnreducedStorage.lean new file mode 100644 index 0000000000000000000000000000000000000000..30006fd96cb8b87efa7e95eb2796a5e81ca3232a --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Binary/UnreducedStorage.lean @@ -0,0 +1,217 @@ +import OAI.Combinatorics.EditApproximation.Binary.UnreducedOptimizer + +namespace OAI + +/-! Polynomial raw storage bounds used by the Boolean numerical loops. -/ + +namespace EditApproximation +namespace UnreducedRational + +open Finset + +theorem storageBits_nat (n : ℕ) : (nat n).storageBits = Nat.size n + 2 := by + simp [nat, storageBits] + +theorem storageBits_one : one.storageBits = 3 := by decide + +theorem storageBits_zero : zero.storageBits = 2 := by decide + +theorem storageBits_neg (a : UnreducedRational) : a.neg.storageBits = a.storageBits := by + simp [neg, storageBits] + +theorem storageBits_add (a b : UnreducedRational) : + (a.add b).storageBits ≤ 2 * a.storageBits + 2 * b.storageBits + 2 := by + have hnum := (Nat.size_le_size (Int.natAbs_add_le (a.num * b.den) (b.num * a.den))).trans + (natural_sum_bit_length (a.num * b.den).natAbs (b.num * a.den).natAbs) + simp only [Int.natAbs_mul, Int.natAbs_natCast] at hnum + have hleft := natural_product_bit_length a.num.natAbs b.den + have hright := natural_product_bit_length b.num.natAbs a.den + have hden := add_den_bits a b + dsimp only [add, storageBits] at * + omega + +theorem storageBits_mul (a b : UnreducedRational) : + (a.mul b).storageBits ≤ a.storageBits + b.storageBits := by + have hnum := natural_product_bit_length a.num.natAbs b.num.natAbs + have hden := mul_den_bits a b + simp only [mul, storageBits, Int.natAbs_mul] at * + omega + +theorem storageBits_sub (a b : UnreducedRational) : + (a.sub b).storageBits ≤ 2 * a.storageBits + 2 * b.storageBits + 2 := by + simpa only [sub, storageBits_neg] using storageBits_add a b.neg + +theorem storageBits_inv (a : UnreducedRational) : a.inv.storageBits ≤ a.storageBits + 2 := by + by_cases h : a.num = 0 + · simp only [inv, h, ↓reduceDIte, storageBits_zero] + omega + · simp only [inv, h, ↓reduceDIte, storageBits, Int.natAbs_mul, + Int.natAbs_sign_of_ne_zero h, Int.natAbs_natCast, Nat.one_mul] + omega + +theorem storageBits_div (a b : UnreducedRational) : + (a.div b).storageBits ≤ a.storageBits + b.storageBits + 2 := by + exact (storageBits_mul a b.inv).trans (by have h := storageBits_inv b; omega) + +theorem logarithmRatio_storageBits (r : UnreducedRational) : + ((r.sub one).div (r.add one)).storageBits ≤ 4 * r.storageBits + 18 := by + have hsub := storageBits_sub r one + have hadd := storageBits_add r one + have hdiv := storageBits_div (r.sub one) (r.add one) + rw [storageBits_one] at hsub hadd + omega + +theorem logarithm_storageBits_poly (r : UnreducedRational) (K : ℕ) (hr : 0 ≤ r.value) : + (logarithm r K).storageBits ≤ + Nat.size (2 * K) + 2 * (K * K * (4 * r.storageBits + 18) + + K * (Nat.size (2 * K + 1) + 1) + 1) + 1 := by + have h := logarithm_storageBits r K hr + have hratio := logarithmRatio_storageBits r + have hd : Nat.size ((r.sub one).div (r.add one)).den ≤ 4 * r.storageBits + 18 := by + exact (by dsimp only [storageBits]; omega : + Nat.size ((r.sub one).div (r.add one)).den ≤ ((r.sub one).div (r.add one)).storageBits).trans hratio + have hm := Nat.mul_le_mul_left (K * K) hd + omega + +theorem logarithmPartial_abs_le (b : UnreducedRational) (K : ℕ) (hb : |b.value| ≤ 1) : + |(logarithmPartial b K).value| ≤ K := by + rw [logarithmPartial_value] + calc + _ ≤ ∑ k ∈ range K, |b.value ^ (2 * k + 1) / (2 * k + 1 : ℕ)| := abs_sum_le_sum_abs _ _ + _ ≤ ∑ _ ∈ range K, (1 : ℚ) := by + apply sum_le_sum + intro k _ + have hd : (0 : ℚ) < (2 * k + 1 : ℕ) := by positivity + have hd1 : (1 : ℚ) ≤ (2 * k + 1 : ℕ) := by norm_cast; omega + rw [abs_div, abs_pow, abs_of_pos hd] + exact (div_le_div_of_nonneg_right (pow_le_one₀ (abs_nonneg _) hb) hd.le).trans + ((div_le_one₀ hd).mpr hd1) + _ = K := by simp + +theorem logarithmPartial_storageBits (b : UnreducedRational) (K : ℕ) (hb : |b.value| ≤ 1) : + (logarithmPartial b K).storageBits ≤ Nat.size K + + 2 * (K * K * Nat.size b.den + K * (Nat.size (2 * K + 1) + 1) + 1) + 1 := + storageBits_le _ K _ (logarithmPartial_abs_le b K hb) (logarithmPartial_den_bits b K) + +theorem pow_storageBits_abs_le_one (b : UnreducedRational) (K : ℕ) (hb : |b.value| ≤ 1) : + (b.pow K).storageBits ≤ 2 * (K * Nat.size b.den + 1) + 2 := by + have hv : |(b.pow K).value| ≤ (1 : ℕ) := by + rw [value_pow, abs_pow] + exact pow_le_one₀ (abs_nonneg _) hb + have h := storageBits_le (b.pow K) 1 _ hv (pow_den_bits b K) + simp only [Nat.size_one] at h + omega + +theorem pow_storageBits (a : UnreducedRational) (n : ℕ) : + (a.pow n).storageBits ≤ 3 + n * a.storageBits := by + induction n with + | zero => simpa only [pow, Nat.zero_mul, Nat.add_zero] using storageBits_one.le + | succ n ih => + have hm := storageBits_mul (a.pow n) a + simp only [pow] + nlinarith only [ih, hm] + +def logarithmStorageBudget (B K : ℕ) : ℕ := + Nat.size (2 * K) + 2 * (K * K * (4 * B + 18) + + K * (Nat.size (2 * K + 1) + 1) + 1) + 1 + +theorem logarithmStorageBudget_mono {A B : ℕ} (h : A ≤ B) (K : ℕ) : + logarithmStorageBudget A K ≤ logarithmStorageBudget B K := by + have hm := Nat.mul_le_mul_left (K * K) (show 4 * A + 18 ≤ 4 * B + 18 by omega) + unfold logarithmStorageBudget + omega + +def gradientStorageBudget (G pointBits linearBits : ℕ) : ℕ := + 4 * logarithmStorageBudget (2 * pointBits + 2 * (5 + 50 * (Nat.size G + 2)) + 2) (G ^ 60) + + 2 * linearBits + 18 + +theorem gradientCell_storageBits {d : ℕ} (G : ℕ) (linear point : Vector UnreducedRational d) + (i : Fin d) (hpoint : 0 ≤ (point.get i).value) : + (gradientCell G linear point i).storageBits ≤ + gradientStorageBudget G (point.get i).storageBits (linear.get i).storageBits := by + let smoothing := (nat G).pow 50 + let shifted := (point.get i).add smoothing.inv + have hs : smoothing.storageBits ≤ 3 + 50 * (Nat.size G + 2) := by + simpa only [smoothing, storageBits_nat] using pow_storageBits (nat G) 50 + have hi := storageBits_inv smoothing + have ha := storageBits_add (point.get i) smoothing.inv + have hshift : shifted.storageBits ≤ 2 * (point.get i).storageBits + + 2 * (5 + 50 * (Nat.size G + 2)) + 2 := by + dsimp only [shifted] + omega + have hpositive : 0 ≤ shifted.value := by + dsimp only [shifted, smoothing] + simp only [value_add, value_inv, value_pow, value_nat] + exact add_nonneg hpoint (inv_nonneg.mpr (pow_nonneg (Nat.cast_nonneg G) _)) + have hlog := (logarithm_storageBits_poly shifted (G ^ 60) hpositive).trans + (logarithmStorageBudget_mono hshift (G ^ 60)) + have hsub := storageBits_sub (logarithm shifted (G ^ 60)).neg one + rw [storageBits_neg, storageBits_one] at hsub + have hadd := storageBits_add ((logarithm shifted (G ^ 60)).neg.sub one) (linear.get i) + change (((logarithm shifted (G ^ 60)).neg.sub one).add (linear.get i)).storageBits ≤ _ + unfold gradientStorageBudget + omega + +theorem dotList_den_bits {d : ℕ} (left right : Vector UnreducedRational d) + (indices : List (Fin d)) (L R : ℕ) + (hl : ∀ i ∈ indices, Nat.size (left.get i).den ≤ L) + (hr : ∀ i ∈ indices, Nat.size (right.get i).den ≤ R) : + Nat.size (dotList left right indices).den ≤ 1 + indices.length * (L + R) := by + induction indices with + | nil => simp [dotList, zero] + | cons i rest ih => + have ht := ih (fun i hi => hl i (List.mem_cons_of_mem _ hi)) + (fun i hi => hr i (List.mem_cons_of_mem _ hi)) + have hi := mul_den_bits (left.get i) (right.get i) + have hs := add_den_bits ((left.get i).mul (right.get i)) (dotList left right rest) + have hil := hl i List.mem_cons_self + have hir := hr i List.mem_cons_self + change Nat.size (((left.get i).mul (right.get i)).add (dotList left right rest)).den ≤ _ + simp only [List.length_cons] + nlinarith only [ht, hi, hs, hil, hir] + +theorem dotList_abs_le {d : ℕ} (left right : Vector UnreducedRational d) + (indices : List (Fin d)) (L R : ℕ) + (hl : ∀ i ∈ indices, |(left.get i).value| ≤ L) + (hr : ∀ i ∈ indices, |(right.get i).value| ≤ R) : + |(dotList left right indices).value| ≤ indices.length * L * R := by + induction indices with + | nil => simp [dotList] + | cons i rest ih => + have ht := ih (fun i hi => hl i (List.mem_cons_of_mem _ hi)) + (fun i hi => hr i (List.mem_cons_of_mem _ hi)) + have hi := mul_le_mul (hl i List.mem_cons_self) (hr i List.mem_cons_self) + (abs_nonneg _) (Nat.cast_nonneg L) + simp only [dotList, value_add, value_mul] + calc + _ ≤ |(left.get i).value * (right.get i).value| + |(dotList left right rest).value| := abs_add_le _ _ + _ ≤ (L : ℚ) * R + rest.length * L * R := by rw [abs_mul]; exact add_le_add hi ht + _ = (i :: rest).length * L * R := by simp only [List.length_cons, Nat.cast_add, Nat.cast_one]; ring + +theorem dotList_storageBits {d : ℕ} (left right : Vector UnreducedRational d) + (indices : List (Fin d)) (BL BR VL VR : ℕ) + (hlbits : ∀ i ∈ indices, Nat.size (left.get i).den ≤ BL) + (hrbits : ∀ i ∈ indices, Nat.size (right.get i).den ≤ BR) + (hlvalue : ∀ i ∈ indices, |(left.get i).value| ≤ VL) + (hrvalue : ∀ i ∈ indices, |(right.get i).value| ≤ VR) : + (dotList left right indices).storageBits ≤ Nat.size (indices.length * VL * VR) + + 2 * (1 + indices.length * (BL + BR)) + 1 := by + apply storageBits_le + · simpa only [Nat.cast_mul] using dotList_abs_le left right indices VL VR hlvalue hrvalue + · exact dotList_den_bits left right indices BL BR hlbits hrbits + +theorem logarithmPartial_storageBits_uniform (b : UnreducedRational) (j K : ℕ) + (hj : j ≤ K) (hb : |b.value| ≤ 1) : + (logarithmPartial b j).storageBits ≤ Nat.size K + + 2 * (K * K * Nat.size b.den + K * (Nat.size (2 * K + 1) + 1) + 1) + 1 := by + have h := logarithmPartial_storageBits b j hb + have hs := Nat.size_le_size hj + have hsodd := Nat.size_le_size (show 2 * j + 1 ≤ 2 * K + 1 by omega) + have hquad := Nat.mul_le_mul_right (Nat.size b.den) (Nat.mul_le_mul hj hj) + have hlinear := Nat.mul_le_mul hj (Nat.add_le_add_right hsodd 1) + omega + +end UnreducedRational +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseAccessAllocation.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseAccessAllocation.lean new file mode 100644 index 0000000000000000000000000000000000000000..3a4df42bb7dd6fd822c39bef4198dc51023676c0 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseAccessAllocation.lean @@ -0,0 +1,88 @@ +import OAI.Combinatorics.EditApproximation.Numerics.ScalarAllocation +import OAI.Combinatorics.EditApproximation.Coarse.CoarseReadAccess +import OAI.Combinatorics.EditApproximation.Coarse.CoarseReadLeafWork + +namespace OAI + +namespace EditApproximation + +/-- Comparisons and minimum reuse their input bit arrays. -/ +def coarseSaturatingSubtractAllocation (a b : ℕ) : ℕ := + if (binaryNaturalCompareWithWork a b).1 = .lt then 0 + else bitSubtractAllocation a.bits b.bits false + +theorem coarseSaturatingSubtractAllocation_le_work (a b : ℕ) : + coarseSaturatingSubtractAllocation a b ≤ (saturatingSubtractWithWork a b).2 := by + have hs := bitSubtractAllocation_le_work a.bits b.bits false + unfold coarseSaturatingSubtractAllocation saturatingSubtractWithWork + dsimp only + split_ifs <;> simp only [binaryNaturalSubtractWithWork] <;> omega + +def coarseDescriptorAllocation (B d n start : ℕ) : ℕ := + bitPowerAllocation B.bits d + coarseSaturatingSubtractAllocation n start + + Nat.size B + Nat.size d + Nat.size n + Nat.size start + +theorem coarseDescriptorAllocation_le_work (B d n start : ℕ) : + coarseDescriptorAllocation B d n start ≤ (coarseDescriptorWithWork B d n start).2 := by + have hp := bitPowerAllocation_le_work B.bits d + have hs := coarseSaturatingSubtractAllocation_le_work n start + unfold coarseDescriptorAllocation coarseDescriptorWithWork + dsimp only + omega + +def coarseChildOffsetAllocation (offset capacity index : ℕ) : ℕ := + bitMulAllocation index.bits capacity.bits + + bitAddAllocation offset.bits (bitWordValue (binaryNaturalMulWithWork index capacity).1).bits false + + Nat.size index + Nat.size capacity + Nat.size offset + +theorem coarseChildOffsetAllocation_le_work (offset capacity index : ℕ) : + coarseChildOffsetAllocation offset capacity index ≤ (coarseChildOffsetWithWork offset capacity index).2 := by + have hm := bitMulAllocation_le_work index.bits capacity.bits + have ha := bitAddAllocation_le_work offset.bits + (bitWordValue (binaryNaturalMulWithWork index capacity).1).bits false + unfold coarseChildOffsetAllocation coarseChildOffsetWithWork + simp only [binaryNaturalMulWithWork, binaryNaturalAddWithWork] at ha ⊢ + omega + +def coarseFramedReadAllocation (k n i : ℕ) : ℕ := + Nat.size k + Nat.size n + Nat.size i + + if (binaryNaturalCompareWithWork i k).1 = .lt then 0 else + bitAddAllocation k.bits n.bits false + + if (binaryNaturalCompareWithWork i (bitWordValue (binaryNaturalAddWithWork k n).1)).1 = .lt + then coarseSaturatingSubtractAllocation i k else 0 + +theorem coarseFramedReadAllocation_le_work {α : Type*} (k n : ℕ) (word : List α) (i : ℕ) : + coarseFramedReadAllocation k n i ≤ (coarseFramedReadWithWork k n word i).2 := by + have ha := bitAddAllocation_le_work k.bits n.bits false + have hs := coarseSaturatingSubtractAllocation_le_work i k + unfold coarseFramedReadAllocation coarseFramedReadWithWork + dsimp only + split_ifs <;> simp only [binaryNaturalAddWithWork] at * <;> omega + +namespace BinaryFraction + +def coarseReadShiftAllocation (k n : ℕ) (letter : Option (Option ℕ)) + (start : ℕ) (shift : Fin (2 * k + 1)) : ℕ := + match letter with + | none => 0 + | some _ => + bitAddAllocation start.bits shift.val.bits false + + coarseFramedReadAllocation k n (bitWordValue (binaryNaturalAddWithWork start shift.val).1) + +theorem coarseReadShiftAllocation_le_work (k n : ℕ) (target : List ℕ) + (letter : Option (Option ℕ)) (start : ℕ) (shift : Fin (2 * k + 1)) : + coarseReadShiftAllocation k n letter start shift ≤ (coarseReadShiftWithWork k n target letter start shift).2 := by + cases letter with + | none => exact Nat.zero_le _ + | some letter => + have ha := bitAddAllocation_le_work start.bits shift.val.bits false + have hf := coarseFramedReadAllocation_le_work k n target + (bitWordValue (binaryNaturalAddWithWork start shift.val).1) + unfold coarseReadShiftAllocation coarseReadShiftWithWork + simp only [binaryNaturalAddWithWork] at hf ⊢ + omega + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseAccessControlSpace.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseAccessControlSpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..71e808780f7e3caac66c94215607a6cb4910988e --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseAccessControlSpace.lean @@ -0,0 +1,124 @@ +import OAI.Combinatorics.EditApproximation.Numerics.ScalarControlSpace +import OAI.Combinatorics.EditApproximation.Coarse.CoarseReadAccess +import OAI.Combinatorics.EditApproximation.Coarse.CoarseReadLeafWork + +namespace OAI + +namespace EditApproximation + +def saturatingSubtractInvocations (a b : ℕ) : ℕ := + bitCompareInvocations a.bits b.bits + 1 + + if (binaryNaturalCompareWithWork a b).1 = .lt then 0 + else bitSubtractInvocations a.bits b.bits false + +theorem saturatingSubtractInvocations_le_work (a b : ℕ) : + saturatingSubtractInvocations a b ≤ (saturatingSubtractWithWork a b).2 := by + have hc := bitCompareInvocations_le_work a.bits b.bits + have hs := bitSubtractInvocations_le_work a.bits b.bits false + unfold saturatingSubtractInvocations saturatingSubtractWithWork + dsimp only + split_ifs <;> simp only [binaryNaturalSubtractWithWork, binaryNaturalCompareWithWork] at * <;> omega + +def coarseDescriptorInvocations (B d n start : ℕ) : ℕ := + bitPowerInvocations B.bits d + saturatingSubtractInvocations n start + + bitCompareInvocations (saturatingSubtractWithWork n start).1 (bitPowerWithWork B.bits d).1 + 3 + +theorem coarseDescriptorInvocations_le_work (B d n start : ℕ) : + coarseDescriptorInvocations B d n start ≤ (coarseDescriptorWithWork B d n start).2 := by + have hp := bitPowerInvocations_le_work B.bits d + have hs := saturatingSubtractInvocations_le_work n start + have hc := bitCompareInvocations_le_work (saturatingSubtractWithWork n start).1 + (bitPowerWithWork B.bits d).1 + unfold coarseDescriptorInvocations coarseDescriptorWithWork + simp only [wordMinWithWork, wordLEWithWork] + omega + +def coarseChildOffsetInvocations (offset capacity index : ℕ) : ℕ := + bitMulInvocations index.bits capacity.bits + + bitAddInvocations offset.bits (bitWordValue (binaryNaturalMulWithWork index capacity).1).bits false + 1 + +theorem coarseChildOffsetInvocations_le_work (offset capacity index : ℕ) : + coarseChildOffsetInvocations offset capacity index ≤ (coarseChildOffsetWithWork offset capacity index).2 := by + have hm := bitMulInvocations_le_work index.bits capacity.bits + have ha := bitAddInvocations_le_work offset.bits + (bitWordValue (binaryNaturalMulWithWork index capacity).1).bits false + unfold coarseChildOffsetInvocations coarseChildOffsetWithWork + simp only [binaryNaturalMulWithWork, binaryNaturalAddWithWork] at ha ⊢ + omega + +def coarsePaddedReadInvocations (n offset : ℕ) : ℕ := bitCompareInvocations offset.bits n.bits + 1 + +theorem coarsePaddedReadInvocations_le_work {α : Type*} (n : ℕ) (source : List α) (offset : ℕ) : + coarsePaddedReadInvocations n offset ≤ (coarsePaddedReadWithWork n source offset).2 := by + have hc := bitCompareInvocations_le_work offset.bits n.bits + unfold coarsePaddedReadInvocations coarsePaddedReadWithWork binaryNaturalCompareWithWork + dsimp only + omega + +def coarseFramedReadInvocations (k n i : ℕ) : ℕ := + bitCompareInvocations i.bits k.bits + 1 + + if (binaryNaturalCompareWithWork i k).1 = .lt then 0 else + bitAddInvocations k.bits n.bits false + + bitCompareInvocations i.bits (bitWordValue (binaryNaturalAddWithWork k n).1).bits + + if (binaryNaturalCompareWithWork i (bitWordValue (binaryNaturalAddWithWork k n).1)).1 = .lt + then saturatingSubtractInvocations i k else 0 + +theorem coarseFramedReadInvocations_le_work {α : Type*} (k n : ℕ) (word : List α) (i : ℕ) : + coarseFramedReadInvocations k n i ≤ (coarseFramedReadWithWork k n word i).2 := by + have hl := bitCompareInvocations_le_work i.bits k.bits + have ha := bitAddInvocations_le_work k.bits n.bits false + have hu := bitCompareInvocations_le_work i.bits (bitWordValue (binaryNaturalAddWithWork k n).1).bits + have hs := saturatingSubtractInvocations_le_work i k + unfold coarseFramedReadInvocations coarseFramedReadWithWork + dsimp only + split_ifs <;> simp only [binaryNaturalAddWithWork, binaryNaturalCompareWithWork] at * <;> omega + +def coarseLetterMatchInvocations : Option (Option ℕ) → Option ℕ → ℕ + | some (some a), some b => bitCompareInvocations a.bits b.bits + 1 + | _, _ => 1 + +theorem coarseLetterMatchInvocations_le_work (actual : Option (Option ℕ)) (wanted : Option ℕ) : + coarseLetterMatchInvocations actual wanted ≤ (coarseLetterMatchWithWork actual wanted).2 := by + cases actual with + | none => cases wanted <;> exact Nat.le_refl 1 + | some actual => + cases actual with + | none => cases wanted <;> exact Nat.le_refl 1 + | some a => + cases wanted with + | none => exact Nat.le_refl 1 + | some b => + have h := bitCompareInvocations_le_work a.bits b.bits + exact Nat.add_le_add_right h 1 + +namespace BinaryFraction + +def coarseReadShiftInvocations (k n : ℕ) (target : List ℕ) (letter : Option (Option ℕ)) + (start : ℕ) (shift : Fin (2 * k + 1)) : ℕ := + match letter with + | none => 1 + | some wanted => + let position := binaryNaturalAddWithWork start shift.val + bitAddInvocations start.bits shift.val.bits false + + coarseFramedReadInvocations k n (bitWordValue position.1) + + coarseLetterMatchInvocations (coarseFramedReadWithWork k n target (bitWordValue position.1)).1 wanted + 1 + +theorem coarseReadShiftInvocations_le_work (k n : ℕ) (target : List ℕ) + (letter : Option (Option ℕ)) (start : ℕ) (shift : Fin (2 * k + 1)) : + coarseReadShiftInvocations k n target letter start shift ≤ (coarseReadShiftWithWork k n target letter start shift).2 := by + cases letter with + | none => exact Nat.le_refl 1 + | some letter => + have ha := bitAddInvocations_le_work start.bits shift.val.bits false + have hf := coarseFramedReadInvocations_le_work k n target + (bitWordValue (binaryNaturalAddWithWork start shift.val).1) + have hm := coarseLetterMatchInvocations_le_work + (coarseFramedReadWithWork k n target (bitWordValue (binaryNaturalAddWithWork start shift.val).1)).1 letter + unfold coarseReadShiftInvocations coarseReadShiftWithWork + simp only [binaryNaturalAddWithWork] at hf hm ⊢ + omega + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseAccuracy.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseAccuracy.lean new file mode 100644 index 0000000000000000000000000000000000000000..a62069af7c89ed0cb698fa407fbe06aa8daf6193 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseAccuracy.lean @@ -0,0 +1,280 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseEstimator + +namespace OAI + +/-! +# Pathwise accuracy of the concrete coarse recurrence + +The events concern only fixed true child minima sampled with independent +labels. The deterministic reconstruction requires no independence of +approximate child costs. +-/ + +namespace EditApproximation + +open Finset + +universe u + +/-- The true-cost threshold sum appearing in the simultaneous event. -/ +noncomputable def coarseTrueThresholdSum {B D : ℕ} {α : Type u} + (k : ℕ) (Q : ℚ) + (trueValue : CoarseSourceTree B α D → ℕ → Fin (2 * k + 1) → ℕ) + (allowance : ℚ) (transform : ℝ → ℝ) : + List (CoarseSourceTree B α D × Fin B × CoarseThresholdDraws B D) → + ℕ → Fin (2 * k + 1) → ℝ + | [], _, _ => 0 + | (child, draw, _) :: rest, start, shift => + thresholdContribution (coarseChildThreshold B Q allowance draw) (allowance / Q) + (transform ((univ.inf' univ_nonempty + (fun next => trueValue child start next + 2 * Nat.dist shift.val next.val) : ℕ) : ℝ)) + + coarseTrueThresholdSum k Q trueValue allowance transform rest (start + child.word.length) shift + +/-- Child accuracy at precisely the source positions visited by the +actual traversal, with its actual per-child allowance. -/ +noncomputable def CoarseChildAccuracy {B D : ℕ} {α : Type u} + (k : ℕ) (Q lam : ℚ) + (trueValue : CoarseSourceTree B α D → ℕ → Fin (2 * k + 1) → ℕ) + (value : CoarseSourceTree B α D → CoarseThresholdDraws B D → ℚ → ℕ → Fin (2 * k + 1) → ℚ) + (allowance : ℚ) (f : ℝ) : + List (CoarseSourceTree B α D × Fin B × CoarseThresholdDraws B D) → ℕ → Prop + | [], _ => True + | (child, draw, below) :: rest, start => + (∀ shift, + (trueValue child start shift : ℝ) / f - + ((lam * coarseChildThreshold B Q allowance draw : ℚ) : ℝ) ≤ + value child below (lam * coarseChildThreshold B Q allowance draw) start shift ∧ + (value child below (lam * coarseChildThreshold B Q allowance draw) start shift : ℝ) ≤ + f * trueValue child start shift + ((lam * coarseChildThreshold B Q allowance draw : ℚ) : ℝ)) ∧ + CoarseChildAccuracy k Q lam trueValue value allowance f rest (start + child.word.length) + +/-- The actual rational estimator is trapped between two sums of fixed +true costs, even when each child estimate depends on its threshold. -/ +theorem coarseThresholdChildrenCost_sandwich {B D : ℕ} {α : Type u} + (k : ℕ) (Q lam : ℚ) + (trueValue : CoarseSourceTree B α D → ℕ → Fin (2 * k + 1) → ℕ) + (value : CoarseSourceTree B α D → CoarseThresholdDraws B D → ℚ → ℕ → Fin (2 * k + 1) → ℚ) + (children : List (CoarseSourceTree B α D × Fin B × CoarseThresholdDraws B D)) + (allowance : ℚ) (f : ℝ) + (hQ : 0 ≤ Q) (ha : 0 ≤ allowance) (hf : 1 ≤ f) + (hlam : 0 ≤ lam) (hlamone : lam < 1) + (start : ℕ) (shift : Fin (2 * k + 1)) + (hchild : CoarseChildAccuracy k Q lam trueValue value allowance f children start) : + coarseTrueThresholdSum k Q trueValue allowance + (fun cost => cost / (f * (1 + (lam : ℝ)))) children start shift ≤ + ((coarseThresholdChildrenCost k Q lam value allowance children start shift : ℚ) : ℝ) ∧ + ((coarseThresholdChildrenCost k Q lam value allowance children start shift : ℚ) : ℝ) ≤ + coarseTrueThresholdSum k Q trueValue allowance + (fun cost => f * cost / (1 - (lam : ℝ))) children start shift := by + induction children generalizing start with + | nil => simp only [coarseTrueThresholdSum, coarseThresholdChildrenCost, Rat.cast_zero]; exact ⟨le_rfl, le_rfl⟩ + | cons data rest ih => + obtain ⟨child, draw, below⟩ := data + have hminimum := coarse_penalty_minimum_error (trueValue child start) + (fun next => 2 * Nat.dist shift.val next.val) + (value child below (lam * coarseChildThreshold B Q allowance draw) start) + f ((lam * coarseChildThreshold B Q allowance draw : ℚ) : ℝ) hf + (fun next => (hchild.1 next).1) + (fun next => (hchild.1 next).2) + have hfpos : 0 < f := lt_of_lt_of_le zero_lt_one hf + have hscale : (0 : ℝ) ≤ ((allowance / Q : ℚ) : ℝ) := by exact_mod_cast div_nonneg ha hQ + have hstep := coarse_threshold_sandwich hscale hfpos + (by exact_mod_cast hlam : (0 : ℝ) ≤ lam) + (by exact_mod_cast hlamone : (lam : ℝ) < 1) + (by simpa only [Rat.cast_mul] using hminimum.1) + (by simpa only [Rat.cast_mul] using hminimum.2) + have hrest := ih (start + child.word.length) hchild.2 + simp only [coarseThresholdChildrenCost, coarseTrueThresholdSum, + Rat.cast_add, coarseThresholdContribution_cast, Rat.cast_div] + simp only [Rat.cast_div] at hstep + exact ⟨add_le_add hstep.1 hrest.1, add_le_add hstep.2 hrest.2⟩ + +/-- Combining the true-cost concentration events gives the exact +structural-factor update for the executable rational child traversal. -/ +theorem coarseThresholdChildrenCost_reconstruction {B D : ℕ} {α : Type u} + (k : ℕ) (Q lam : ℚ) + (trueValue : CoarseSourceTree B α D → ℕ → Fin (2 * k + 1) → ℕ) + (value : CoarseSourceTree B α D → CoarseThresholdDraws B D → ℚ → ℕ → Fin (2 * k + 1) → ℚ) + (children : List (CoarseSourceTree B α D × Fin B × CoarseThresholdDraws B D)) + (allowance : ℚ) (f : ℝ) + (hQ : 0 ≤ Q) (ha : 0 ≤ allowance) (hf : 1 ≤ f) + (hlam : 0 ≤ lam) (hlamone : lam < 1) + (start : ℕ) (shift : Fin (2 * k + 1)) + (hchild : CoarseChildAccuracy k Q lam trueValue value allowance f children start) + (hconcentrationLower : + (1 - (lam : ℝ)) * + (((coarseChildrenCost k trueValue (children.map Prod.fst) start shift : ℕ) : ℝ) / + (f * (1 + (lam : ℝ)))) - allowance ≤ + coarseTrueThresholdSum k Q trueValue allowance + (fun cost => cost / (f * (1 + (lam : ℝ)))) children start shift) + (hconcentrationUpper : + coarseTrueThresholdSum k Q trueValue allowance + (fun cost => f * cost / (1 - (lam : ℝ))) children start shift ≤ + (1 + (lam : ℝ)) * + (f * ((coarseChildrenCost k trueValue (children.map Prod.fst) start shift : ℕ) : ℝ) / + (1 - (lam : ℝ))) + allowance) : + ((coarseChildrenCost k trueValue (children.map Prod.fst) start shift : ℕ) : ℝ) / + (f * (1 + (lam : ℝ)) / (1 - (lam : ℝ))) - allowance ≤ + ((coarseThresholdChildrenCost k Q lam value allowance children start shift : ℚ) : ℝ) ∧ + ((coarseThresholdChildrenCost k Q lam value allowance children start shift : ℚ) : ℝ) ≤ + (f * (1 + (lam : ℝ)) / (1 - (lam : ℝ))) * + ((coarseChildrenCost k trueValue (children.map Prod.fst) start shift : ℕ) : ℝ) + allowance := by + have hsandwich := coarseThresholdChildrenCost_sandwich k Q lam trueValue value children allowance f + hQ ha hf hlam hlamone start shift hchild + have hfpos : 0 < f := lt_of_lt_of_le zero_lt_one hf + have hl : (lam : ℝ) < 1 := by exact_mod_cast hlamone + have hlnonnegative : (0 : ℝ) ≤ lam := by exact_mod_cast hlam + have hlower := hconcentrationLower.trans hsandwich.1 + have hupper := hsandwich.2.trans hconcentrationUpper + constructor + · convert hlower using 1 + field_simp + · convert hupper using 1 + ring + +/-- The exact depth factor in Section 3. -/ +noncomputable def coarseStructuralFactor (lam : ℚ) (D : ℕ) : ℝ := + ((1 + (lam : ℝ)) / (1 - (lam : ℝ))) ^ D + +theorem coarseStructuralFactor_one_le (lam : ℚ) (D : ℕ) + (hlam : 0 ≤ lam) (hlamone : lam < 1) : 1 ≤ coarseStructuralFactor lam D := by + have hl : (0 : ℝ) ≤ lam := by exact_mod_cast hlam + have hlone : (lam : ℝ) < 1 := by exact_mod_cast hlamone + apply one_le_pow₀ + apply (le_div_iff₀ (sub_pos.mpr hlone)).2 + nlinarith + +theorem coarseStructuralFactor_succ (lam : ℚ) (D : ℕ) : + coarseStructuralFactor lam (D + 1) = + coarseStructuralFactor lam D * (1 + (lam : ℝ)) / (1 - (lam : ℝ)) := by + simp only [coarseStructuralFactor, pow_succ] + ring + +/-- Events for all children, including children below a pruned node. -/ +def CoarseDescendantEvents {B D : ℕ} {α : Type u} (Q lam allowance : ℚ) + (event : CoarseSourceTree B α D → CoarseThresholdDraws B D → ℚ → ℕ → Prop) : + List (CoarseSourceTree B α D × Fin B × CoarseThresholdDraws B D) → ℕ → Prop + | [], _ => True + | (child, draw, below) :: rest, start => + event child below (lam * coarseChildThreshold B Q allowance draw) start ∧ + CoarseDescendantEvents Q lam allowance event rest (start + child.word.length) + +/-- The actual finite-tree event. At every node it uses only deterministic +true-cost minima and the node's current child threshold labels. -/ +noncomputable def CoarseAccuracyEvent {B : ℕ} {α : Type u} [DecidableEq α] + (k : ℕ) (Q lam : ℚ) (frame : List (Option α)) : + {D : ℕ} → CoarseSourceTree B α D → CoarseThresholdDraws B D → ℚ → ℕ → Prop + | _, .leaf _, _, _, _ => True + | D + 1, .branch children, (draws, below), allowance, start => + let data := List.ofFn (fun i => (children i, draws i, below i)) + let trueValue := fun child => coarseShiftCost k frame child + let f := coarseStructuralFactor lam D + CoarseDescendantEvents Q lam allowance + (fun child => CoarseAccuracyEvent k Q lam frame child) data start ∧ + ∀ shift, + (1 - (lam : ℝ)) * + (((coarseChildrenCost k trueValue (data.map Prod.fst) start shift : ℕ) : ℝ) / + (f * (1 + (lam : ℝ)))) - allowance ≤ + coarseTrueThresholdSum k Q trueValue allowance + (fun cost => cost / (f * (1 + (lam : ℝ)))) data start shift ∧ + coarseTrueThresholdSum k Q trueValue allowance + (fun cost => f * cost / (1 - (lam : ℝ))) data start shift ≤ + (1 + (lam : ℝ)) * + (f * ((coarseChildrenCost k trueValue (data.map Prod.fst) start shift : ℕ) : ℝ) / + (1 - (lam : ℝ))) + allowance + +theorem CoarseDescendantEvents.to_accuracy {B D : ℕ} {α : Type u} + (k : ℕ) (Q lam allowance : ℚ) (f : ℝ) + (trueValue : CoarseSourceTree B α D → ℕ → Fin (2 * k + 1) → ℕ) + (value : CoarseSourceTree B α D → CoarseThresholdDraws B D → ℚ → ℕ → Fin (2 * k + 1) → ℚ) + (event : CoarseSourceTree B α D → CoarseThresholdDraws B D → ℚ → ℕ → Prop) + (children : List (CoarseSourceTree B α D × Fin B × CoarseThresholdDraws B D)) + (hchild : ∀ child draw below, (child, draw, below) ∈ children → ∀ start, + event child below (lam * coarseChildThreshold B Q allowance draw) start → ∀ shift, + (trueValue child start shift : ℝ) / f - + ((lam * coarseChildThreshold B Q allowance draw : ℚ) : ℝ) ≤ + value child below (lam * coarseChildThreshold B Q allowance draw) start shift ∧ + (value child below (lam * coarseChildThreshold B Q allowance draw) start shift : ℝ) ≤ + f * trueValue child start shift + ((lam * coarseChildThreshold B Q allowance draw : ℚ) : ℝ)) + (start : ℕ) (hevent : CoarseDescendantEvents Q lam allowance event children start) : + CoarseChildAccuracy k Q lam trueValue value allowance f children start := by + induction children generalizing start with + | nil => trivial + | cons data rest ih => + obtain ⟨child, draw, below⟩ := data + exact ⟨hchild child draw below (by simp) start hevent.1, + ih (fun child draw below hmem => hchild child draw below (by simp [hmem])) + (start + child.word.length) hevent.2⟩ + +/-- On the concrete true-cost event, the literal rational pruned +estimator has exactly the claimed depth-dependent error at every shift. -/ +theorem coarseThresholdEstimate_accurate {B D : ℕ} {α : Type u} [DecidableEq α] + (k : ℕ) (Q lam : ℚ) (frame : List (Option α)) + (tree : CoarseSourceTree B α D) (draws : CoarseThresholdDraws B D) + (allowance : ℚ) (start : ℕ) + (hQ : 0 ≤ Q) (hlam : 0 ≤ lam) (hlamone : lam < 1) (ha : 0 ≤ allowance) + (hevent : CoarseAccuracyEvent k Q lam frame tree draws allowance start) : + ∀ shift : Fin (2 * k + 1), + (coarseShiftCost k frame tree start shift : ℝ) / coarseStructuralFactor lam D - allowance ≤ + coarseThresholdEstimate k Q lam frame tree draws allowance start shift ∧ + (coarseThresholdEstimate k Q lam frame tree draws allowance start shift : ℝ) ≤ + coarseStructuralFactor lam D * coarseShiftCost k frame tree start shift + allowance := by + induction tree generalizing allowance start with + | leaf letter => + intro shift + have haReal : (0 : ℝ) ≤ allowance := by exact_mod_cast ha + simp only [coarseThresholdEstimate, coarseStructuralFactor, pow_zero, div_one, one_mul] + split_ifs with hprune + · have hwidth := coarseShiftCost_le_width k frame (.leaf (B := B) letter) start shift + have hwidthQ : (coarseShiftCost k frame (.leaf (B := B) letter) start shift : ℚ) ≤ + (CoarseSourceTree.leaf (B := B) letter).word.length := by exact_mod_cast hwidth + have hwidthReal : (coarseShiftCost k frame (.leaf (B := B) letter) start shift : ℝ) ≤ allowance := by + exact_mod_cast hwidthQ.trans hprune + simp only [Rat.cast_zero] + constructor <;> linarith [show (0 : ℝ) ≤ coarseShiftCost k frame (.leaf (B := B) letter) start shift by positivity] + · simp only [Rat.cast_natCast] + constructor <;> linarith + | @branch D children ih => + obtain ⟨draws, below⟩ := draws + have hfactor := coarseStructuralFactor_one_le lam (D + 1) hlam hlamone + have hfactorPos : 0 < coarseStructuralFactor lam (D + 1) := lt_of_lt_of_le zero_lt_one hfactor + have haReal : (0 : ℝ) ≤ allowance := by exact_mod_cast ha + intro shift + by_cases hprune : ((CoarseSourceTree.branch children).word.length : ℚ) ≤ allowance + · simp only [coarseThresholdEstimate, hprune, ↓reduceIte, Rat.cast_zero] + have hwidth := coarseShiftCost_le_width k frame (.branch children) start shift + have hwidthQ : (coarseShiftCost k frame (.branch children) start shift : ℚ) ≤ + (CoarseSourceTree.branch children).word.length := by exact_mod_cast hwidth + have hwidthReal : (coarseShiftCost k frame (.branch children) start shift : ℝ) ≤ allowance := by + exact_mod_cast hwidthQ.trans hprune + have htrueNonnegative : (0 : ℝ) ≤ coarseShiftCost k frame (.branch children) start shift := by positivity + have hdiv : (coarseShiftCost k frame (.branch children) start shift : ℝ) / + coarseStructuralFactor lam (D + 1) ≤ coarseShiftCost k frame (.branch children) start shift := by + apply (div_le_iff₀ hfactorPos).2 + nlinarith + exact ⟨by linarith, by positivity⟩ + · have hdescendant := hevent.1 + have hchildAccuracy := CoarseDescendantEvents.to_accuracy k Q lam allowance + (coarseStructuralFactor lam D) (fun child => coarseShiftCost k frame child) + (fun child => coarseThresholdEstimate k Q lam frame child) + (fun child => CoarseAccuracyEvent k Q lam frame child) + (List.ofFn fun i => (children i, draws i, below i)) + (by + intro child draw childBelow hmem childStart hchildEvent + obtain ⟨i, hi⟩ := List.mem_ofFn.mp hmem + cases hi + exact ih i (below i) _ childStart + (mul_nonneg hlam (coarseChildThreshold_nonneg (draws i) hQ ha)) hchildEvent) + start hdescendant + have hstep := coarseThresholdChildrenCost_reconstruction k Q lam + (fun child => coarseShiftCost k frame child) + (fun child => coarseThresholdEstimate k Q lam frame child) + (List.ofFn fun i => (children i, draws i, below i)) allowance + (coarseStructuralFactor lam D) hQ ha (coarseStructuralFactor_one_le lam D hlam hlamone) + hlam hlamone start shift hchildAccuracy (hevent.2 shift).1 (hevent.2 shift).2 + simpa only [coarseThresholdEstimate, hprune, ↓reduceIte, List.map_ofFn, + Function.comp_def, coarseShiftCost, coarseStructuralFactor_succ] using hstep + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseArrayAllocation.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseArrayAllocation.lean new file mode 100644 index 0000000000000000000000000000000000000000..6407f2ab4ab7a17b8d58e28d8e2784da4e8acf8e --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseArrayAllocation.lean @@ -0,0 +1,155 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseScalarAllocation +import OAI.Combinatorics.EditApproximation.Coarse.CoarseArrayRepresentation + +namespace OAI + +namespace EditApproximation + +/-- The same map trace, allowing a uniform factor two for callback allocation. -/ +theorem arithmeticMapAllocation_le_twice_work {α β : Type*} (f : α → β × ℕ) + (allocation : α → ℕ) (values : List α) + (h : ∀ a ∈ values, allocation a ≤ 2 * (f a).2) : + arithmeticMapAllocation allocation values ≤ 2 * (arithmeticMapWithWork f values).2 := by + induction values with + | nil => rfl + | cons a rest ih => + have hh := h a List.mem_cons_self + have ht := ih (fun b hb => h b (List.mem_cons_of_mem _ hb)) + simp only [arithmeticMapAllocation, arithmeticMapWithWork] + omega + +namespace BinaryFraction + +def coarseGridScanAllocation (two previous : BinaryFraction) : List BinaryFraction → ℕ + | [] => 1 + | head :: rest => + let added := coarseGridAddWithWork previous two + let next := minWithWork head added.1 + coarseGridAddAllocation previous two + head.ltAllocation added.1 + + coarseGridScanAllocation two next.1 rest + 1 + +theorem coarseGridScanAllocation_le_work (two previous : BinaryFraction) (source : List BinaryFraction) : + coarseGridScanAllocation two previous source ≤ (coarseGridScanWithWork two previous source).2 + 1 := by + induction source generalizing previous with + | nil => rfl + | cons head rest ih => + have ha := coarseGridAddAllocation_le_work previous two + have hm := ltAllocation_le_work head (coarseGridAddWithWork previous two).1 + have ht := ih (minWithWork head (coarseGridAddWithWork previous two).1).1 + simp only [coarseGridScanAllocation, coarseGridScanWithWork] + simp only [minWithWork] at ht ⊢ + omega + +def coarseGridLeftAllocation (two : BinaryFraction) : List BinaryFraction → ℕ + | [] => 0 + | head :: rest => coarseGridScanAllocation two head rest + +theorem coarseGridLeftAllocation_le_work (two : BinaryFraction) (source : List BinaryFraction) : + coarseGridLeftAllocation two source ≤ (coarseGridLeftWithWork two source).2 + source.length := by + cases source with + | nil => simp [coarseGridLeftAllocation, coarseGridLeftWithWork] + | cons head rest => + have h := coarseGridScanAllocation_le_work two head rest + simp only [coarseGridLeftAllocation, coarseGridLeftWithWork, List.length_cons] + omega + +theorem coarseGridLeftWithWork_length (two : BinaryFraction) (source : List BinaryFraction) : + (coarseGridLeftWithWork two source).1.length = source.length := by + have scan (previous : BinaryFraction) (values : List BinaryFraction) : + (coarseGridScanWithWork two previous values).1.length = values.length + 1 := by + induction values generalizing previous with + | nil => rfl + | cons head rest ih => simp only [coarseGridScanWithWork, List.length_cons, ih] + cases source with + | nil => rfl + | cons head rest => exact scan head rest + +def coarseGridZipMinimumAllocation : List BinaryFraction → List BinaryFraction → ℕ + | a :: left, b :: right => a.ltAllocation b + coarseGridZipMinimumAllocation left right + 1 + | _, _ => 0 + +theorem coarseGridZipMinimumAllocation_le_work (left right : List BinaryFraction) : + coarseGridZipMinimumAllocation left right ≤ (coarseGridZipMinimumWithWork left right).2 := by + induction left generalizing right with + | nil => rfl + | cons a left ih => + cases right with + | nil => exact Nat.le_refl 0 + | cons b right => + have hh := ltAllocation_le_work a b + have ht := ih right + simp only [coarseGridZipMinimumAllocation, coarseGridZipMinimumWithWork, minWithWork] + omega + +/-- Both reverse operations allocate their list spines; the element words +are shared. Includes both sweeps, their discarded arrays and the final zip. -/ +def coarseGridPenaltyAllocation (two : BinaryFraction) (source : List BinaryFraction) : ℕ := + let left := coarseGridLeftWithWork two source + let right := coarseGridLeftWithWork two source.reverse + coarseGridLeftAllocation two source + coarseGridLeftAllocation two source.reverse + + source.length + right.1.length + coarseGridZipMinimumAllocation left.1 right.1.reverse + +theorem coarseGridPenaltyAllocation_le_work (two : BinaryFraction) (source : List BinaryFraction) : + coarseGridPenaltyAllocation two source ≤ 2 * (coarseGridPenaltyWithWork two source).2 := by + have hl := coarseGridLeftAllocation_le_work two source + have hr := coarseGridLeftAllocation_le_work two source.reverse + have hz := coarseGridZipMinimumAllocation_le_work + (coarseGridLeftWithWork two source).1 (coarseGridLeftWithWork two source.reverse).1.reverse + have hlen := coarseGridLeftWithWork_length two source.reverse + simp only [List.length_reverse] at hr hlen + unfold coarseGridPenaltyAllocation coarseGridPenaltyWithWork + dsimp only + rw [hlen] + omega + +def coarseGridZipAddAllocation : List BinaryFraction → List BinaryFraction → ℕ + | a :: left, b :: right => coarseGridAddAllocation a b + coarseGridZipAddAllocation left right + 1 + | _, _ => 0 + +theorem coarseGridZipAddAllocation_le_work (left right : List BinaryFraction) : + coarseGridZipAddAllocation left right ≤ (coarseGridZipAddWithWork left right).2 := by + induction left generalizing right with + | nil => rfl + | cons a left ih => + cases right with + | nil => exact Nat.le_refl 0 + | cons b right => + have hh := coarseGridAddAllocation_le_work a b + have ht := ih right + simp only [coarseGridZipAddAllocation, coarseGridZipAddWithWork] + omega + +def coarseBinaryAddAllocation : CoarseBinaryArray → CoarseBinaryArray → ℕ + | some left, some right => coarseGridZipAddAllocation left right + | _, _ => 0 + +theorem coarseBinaryAddAllocation_le_work (left right : CoarseBinaryArray) : + coarseBinaryAddAllocation left right ≤ (coarseBinaryAddWithWork left right).2 := by + cases left <;> cases right + all_goals first | exact Nat.le_refl 0 | exact coarseGridZipAddAllocation_le_work _ _ + +def coarseBinaryPenaltyAllocation (two : BinaryFraction) : CoarseBinaryArray → ℕ + | none => 0 + | some values => coarseGridPenaltyAllocation two values + +theorem coarseBinaryPenaltyAllocation_le_work (two : BinaryFraction) (array : CoarseBinaryArray) : + coarseBinaryPenaltyAllocation two array ≤ 2 * (coarseBinaryPenaltyWithWork two array).2 := by + cases array with + | none => exact Nat.le_refl 0 + | some values => exact coarseGridPenaltyAllocation_le_work two values + +def coarseBinaryMapAllocation (allocation : BinaryFraction → ℕ) : CoarseBinaryArray → ℕ + | none => 0 + | some values => arithmeticMapAllocation allocation values + +theorem coarseBinaryMapAllocation_le_work (f : BinaryFraction → BinaryFraction × ℕ) + (allocation : BinaryFraction → ℕ) (h : ∀ a, allocation a ≤ (f a).2) (array : CoarseBinaryArray) : + coarseBinaryMapAllocation allocation array ≤ (coarseBinaryMapWithWork f array).2 := by + cases array with + | none => exact Nat.le_refl 0 + | some values => exact arithmeticMapAllocation_le_work f allocation values (fun a _ => h a) + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseArrayArithmetic.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseArrayArithmetic.lean new file mode 100644 index 0000000000000000000000000000000000000000..499ebb62a6dd26826319af3ba5d40634ad5ba815 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseArrayArithmetic.lean @@ -0,0 +1,113 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseThresholdArithmetic +import OAI.Combinatorics.EditApproximation.Coarse.CoarseTransforms +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! The coarse penalty sweep executed on shared-denominator Boolean cells. +Each transition performs a numerator addition and a rational comparison. -/ + +namespace EditApproximation +namespace BinaryFraction + +private theorem coarseMin_den (a b : BinaryFraction) + (hden : a.representation.den = b.representation.den) : + (minWithWork a b).1.representation.den = a.representation.den := by + unfold minWithWork + dsimp only + split_ifs + · rfl + · exact hden.symm + +private theorem coarseMin_den_length (a b : BinaryFraction) (D : ℕ) + (ha : a.denominator.length ≤ D) (hb : b.denominator.length ≤ D) : + (minWithWork a b).1.denominator.length ≤ D := by + unfold minWithWork + dsimp only + split_ifs <;> assumption + +private theorem coarseGridAdd_den_length (a b : BinaryFraction) : + (coarseGridAddWithWork a b).1.denominator.length ≤ a.denominator.length := by + change (trimBitWordWithWork a.denominator).1.length ≤ a.denominator.length + rw [trimBitWordWithWork_length] + exact Nat.size_le.mpr (bitWordValue_lt_pow_length _) + +/-- The complete left sweep, including writes and traversal. -/ + + + theorem coarseGridScanWithWork_value (two previous : BinaryFraction) + (source : List BinaryFraction) (htwo : two.value = 2) + (hp : previous.representation.den = two.representation.den) + (hs : ∀ a ∈ source, a.representation.den = two.representation.den) : + (coarseGridScanWithWork two previous source).1.map value = + (source.map value).scanl (fun old a => min a (old + 2)) previous.value := by + induction source generalizing previous with + | nil => rfl + | cons head rest ih => + have hh := hs head List.mem_cons_self + have ha : (coarseGridAddWithWork previous two).1.representation.den = two.representation.den := + (coarseGridAddWithWork_den previous two).trans hp + have hn : (minWithWork head (coarseGridAddWithWork previous two).1).1.representation.den = + two.representation.den := + (coarseMin_den head _ (hh.trans ha.symm)).trans hh + have hv := coarseGridAddWithWork_value previous two hp + simp only [coarseGridScanWithWork, List.map_cons, List.scanl_cons] + rw [ih _ hn (fun a ha => hs a (List.mem_cons_of_mem _ ha)), minWithWork_value, hv, htwo] + +/-- Invariant of a stored coarse cell on the common denominator. -/ +def CoarseGridCell (two a : BinaryFraction) (V D B : ℕ) : Prop := + a.representation.den = two.representation.den ∧ a.denominator.length ≤ D ∧ + 0 ≤ a.value ∧ a.value ≤ V ∧ a.width ≤ B + + theorem coarseGridScanWithWork_bounds (two previous : BinaryFraction) + (source : List BinaryFraction) (V D B : ℕ) (htwo : two.value = 2) + (htw : two.width ≤ B) (hbound : Nat.size (V + 2) + 2 * D + 1 ≤ B) + (hp : CoarseGridCell two previous V D B) + (hs : ∀ a ∈ source, CoarseGridCell two a V D B) : + (∀ a ∈ (coarseGridScanWithWork two previous source).1, CoarseGridCell two a V D B) ∧ + (coarseGridScanWithWork two previous source).2 ≤ + source.length * (1200 * (B + 1) ^ 2 + 3) := by + induction source generalizing previous with + | nil => + constructor + · simpa only [coarseGridScanWithWork, List.mem_singleton] using + (fun a (ha : a = previous) => ha ▸ hp) + · simp only [coarseGridScanWithWork, List.length_nil, Nat.zero_mul, le_refl] + | cons head rest ih => + have hh := hs head List.mem_cons_self + have hav : |previous.value + two.value| ≤ (V + 2 : ℕ) := by + rw [htwo, abs_of_nonneg (by linarith only [hp.2.2.1])] + push_cast + linarith only [hp.2.2.2.1] + have haw := (coarseGridAddWithWork_width previous two (V + 2) D hp.1 hav hp.2.1).trans hbound + have had := (coarseGridAddWithWork_den previous two).trans hp.1 + have hv := coarseGridAddWithWork_value previous two hp.1 + have hn : CoarseGridCell two (minWithWork head (coarseGridAddWithWork previous two).1).1 V D B := by + refine ⟨(coarseMin_den head _ (hh.1.trans had.symm)).trans hh.1, + coarseMin_den_length head _ D hh.2.1 + ((coarseGridAdd_den_length previous two).trans hp.2.1), ?_, ?_, ?_⟩ + · rw [minWithWork_value, hv, htwo] + exact le_min hh.2.2.1 (by linarith only [hp.2.2.1]) + · rw [minWithWork_value] + exact (min_le_left _ _).trans hh.2.2.2.1 + · exact (minWithWork_width head _).trans (max_le hh.2.2.2.2 haw) + have ht := ih _ hn (fun a ha => hs a (List.mem_cons_of_mem _ ha)) + constructor + · intro a ha + change a ∈ previous :: _ at ha + rcases List.mem_cons.mp ha with rfl | ha + · exact hp + · exact ht.1 a ha + · have hc := coarseGridAddWithWork_cost previous two B hp.2.2.2.2 htw + have hm := minWithWork_cost head _ B hh.2.2.2.2 haw + change (coarseGridAddWithWork previous two).2 + + (minWithWork head (coarseGridAddWithWork previous two).1).2 + + (coarseGridScanWithWork two (minWithWork head (coarseGridAddWithWork previous two).1).1 rest).2 + 3 ≤ _ + rw [List.length_cons, Nat.add_mul, Nat.one_mul] + nlinarith only [hc, hm, ht.2, Nat.zero_le B] + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseArrayControlSpace.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseArrayControlSpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..0642138e5ffaeaa355cdf53f371ed380b21468f3 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseArrayControlSpace.lean @@ -0,0 +1,133 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseScalarControlSpace +import OAI.Combinatorics.EditApproximation.Coarse.CoarseArrayAllocation + +namespace OAI + +namespace EditApproximation +namespace BinaryFraction + +def coarseGridScanInvocations (two previous : BinaryFraction) : List BinaryFraction → ℕ + | [] => 1 + | head :: rest => + let added := coarseGridAddWithWork previous two + let next := minWithWork head added.1 + coarseGridAddInvocations previous two + compareInvocations head added.1 + + coarseGridScanInvocations two next.1 rest + 2 + +theorem coarseGridScanInvocations_le_work (two previous : BinaryFraction) (source : List BinaryFraction) : + coarseGridScanInvocations two previous source ≤ (coarseGridScanWithWork two previous source).2 + 1 := by + induction source generalizing previous with + | nil => rfl + | cons head rest ih => + have ha := coarseGridAddInvocations_le_work previous two + have hm := compareInvocations_le_work head (coarseGridAddWithWork previous two).1 + have ht := ih (minWithWork head (coarseGridAddWithWork previous two).1).1 + simp only [coarseGridScanInvocations, coarseGridScanWithWork] + simp only [minWithWork] at ht ⊢ + omega + +def coarseGridLeftInvocations (two : BinaryFraction) : List BinaryFraction → ℕ + | [] => 1 + | head :: rest => coarseGridScanInvocations two head rest + 1 + +theorem coarseGridLeftInvocations_le_work (two : BinaryFraction) (source : List BinaryFraction) : + coarseGridLeftInvocations two source ≤ (coarseGridLeftWithWork two source).2 + 2 := by + cases source with + | nil => simp [coarseGridLeftInvocations, coarseGridLeftWithWork] + | cons head rest => + have h := coarseGridScanInvocations_le_work two head rest + simp only [coarseGridLeftInvocations, coarseGridLeftWithWork] + omega + +def coarseGridZipMinimumInvocations : List BinaryFraction → List BinaryFraction → ℕ + | a :: left, b :: right => compareInvocations a b + coarseGridZipMinimumInvocations left right + 2 + | _, _ => 1 + +theorem coarseGridZipMinimumInvocations_le_work (left right : List BinaryFraction) : + coarseGridZipMinimumInvocations left right ≤ (coarseGridZipMinimumWithWork left right).2 + 1 := by + induction left generalizing right with + | nil => exact Nat.le_refl 1 + | cons a left ih => + cases right with + | nil => exact Nat.le_refl 1 + | cons b right => + have hh := compareInvocations_le_work a b + have ht := ih right + simp only [coarseGridZipMinimumInvocations, coarseGridZipMinimumWithWork, minWithWork] + omega + +/-- Includes one invocation per reverse-list step, even if implemented with +an iterative constant-stack loop. -/ +def coarseGridPenaltyInvocations (two : BinaryFraction) (source : List BinaryFraction) : ℕ := + let left := coarseGridLeftWithWork two source + let right := coarseGridLeftWithWork two source.reverse + coarseGridLeftInvocations two source + coarseGridLeftInvocations two source.reverse + + source.length + right.1.length + coarseGridZipMinimumInvocations left.1 right.1.reverse + 3 + +theorem coarseGridPenaltyInvocations_le_work (two : BinaryFraction) (source : List BinaryFraction) : + coarseGridPenaltyInvocations two source ≤ 2 * (coarseGridPenaltyWithWork two source).2 + 8 := by + have hl := coarseGridLeftInvocations_le_work two source + have hr := coarseGridLeftInvocations_le_work two source.reverse + have hz := coarseGridZipMinimumInvocations_le_work + (coarseGridLeftWithWork two source).1 (coarseGridLeftWithWork two source.reverse).1.reverse + have hlen := coarseGridLeftWithWork_length two source.reverse + simp only [List.length_reverse] at hr hlen + unfold coarseGridPenaltyInvocations coarseGridPenaltyWithWork + dsimp only + rw [hlen] + omega + +def coarseGridZipAddInvocations : List BinaryFraction → List BinaryFraction → ℕ + | a :: left, b :: right => coarseGridAddInvocations a b + coarseGridZipAddInvocations left right + 1 + | _, _ => 1 + +theorem coarseGridZipAddInvocations_le_work (left right : List BinaryFraction) : + coarseGridZipAddInvocations left right ≤ (coarseGridZipAddWithWork left right).2 + 1 := by + induction left generalizing right with + | nil => exact Nat.le_refl 1 + | cons a left ih => + cases right with + | nil => exact Nat.le_refl 1 + | cons b right => + have hh := coarseGridAddInvocations_le_work a b + have ht := ih right + simp only [coarseGridZipAddInvocations, coarseGridZipAddWithWork] + omega + +def coarseBinaryAddInvocations : CoarseBinaryArray → CoarseBinaryArray → ℕ + | some left, some right => coarseGridZipAddInvocations left right + 1 + | _, _ => 1 + +theorem coarseBinaryAddInvocations_le_work (left right : CoarseBinaryArray) : + coarseBinaryAddInvocations left right ≤ (coarseBinaryAddWithWork left right).2 + 2 := by + cases left <;> cases right + all_goals first | exact (by decide : 1 ≤ 2) | + exact Nat.add_le_add_right (coarseGridZipAddInvocations_le_work _ _) 1 + +def coarseBinaryPenaltyInvocations (two : BinaryFraction) : CoarseBinaryArray → ℕ + | none => 1 + | some values => coarseGridPenaltyInvocations two values + 1 + +theorem coarseBinaryPenaltyInvocations_le_work (two : BinaryFraction) (array : CoarseBinaryArray) : + coarseBinaryPenaltyInvocations two array ≤ 2 * (coarseBinaryPenaltyWithWork two array).2 + 9 := by + cases array with + | none => exact (by decide : 1 ≤ 9) + | some values => exact Nat.add_le_add_right (coarseGridPenaltyInvocations_le_work two values) 1 + +def coarseBinaryMapInvocations (invocations : BinaryFraction → ℕ) : CoarseBinaryArray → ℕ + | none => 1 + | some values => arithmeticMapInvocations invocations values + 1 + +theorem coarseBinaryMapInvocations_le_work (f : BinaryFraction → BinaryFraction × ℕ) + (invocations : BinaryFraction → ℕ) (h : ∀ a, invocations a ≤ (f a).2) (array : CoarseBinaryArray) : + coarseBinaryMapInvocations invocations array ≤ (coarseBinaryMapWithWork f array).2 + 2 := by + cases array with + | none => exact (by decide : 1 ≤ 2) + | some values => + exact Nat.add_le_add_right + (arithmeticMapInvocations_le_work f invocations values (fun a _ => h a)) 1 + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseArrayEval.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseArrayEval.lean new file mode 100644 index 0000000000000000000000000000000000000000..762f3ab738a02842d3058039d55c32f26bed793f --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseArrayEval.lean @@ -0,0 +1,298 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseTransforms +import OAI.Combinatorics.EditApproximation.Coarse.CoarseWork + +namespace OAI + +/-! +# Shared coarse array evaluation + +A missing array is a constant-zero marker. An expanded child is evaluated +once, then transformed by the two linear sweeps, thresholded, and added +to its siblings. The instrumented counter charges rational arithmetic and +comparisons; allocation, source-width preprocessing and integer addressing +are separate parts of the machine implementation. +-/ + +namespace EditApproximation + +open Finset MeasureTheory + +universe u + +/-- Stored cells have the complete shift-domain length; `none` is zero. -/ +abbrev CoarseStoredArray (n : ℕ) := Option {cells : List ℚ // cells.length = n} + +def coarseStoredRead {n : ℕ} (array : CoarseStoredArray n) (v : Fin n) : ℚ := + match array with + | none => 0 + | some cells => cells.1[v.val]'(by rw [cells.2]; exact v.isLt) + +def coarseStoredOfFn {n : ℕ} (value : Fin n → ℚ) : CoarseStoredArray n := + some ⟨List.ofFn value, List.length_ofFn⟩ + +theorem coarseStoredRead_ofFn {n : ℕ} (value : Fin n → ℚ) (v : Fin n) : + coarseStoredRead (coarseStoredOfFn value) v = value v := by + simp only [coarseStoredRead, coarseStoredOfFn, List.getElem_ofFn] + +def coarseStoredMap {n : ℕ} (f : ℚ → ℚ) : CoarseStoredArray n → CoarseStoredArray n × ℕ + | none => (none, 0) + | some cells => (some ⟨cells.1.map f, by simp only [List.length_map, cells.2]⟩, 2 * n) + +theorem coarseStoredMap_read {n : ℕ} (f : ℚ → ℚ) (hzero : f 0 = 0) + (array : CoarseStoredArray n) (v : Fin n) : + coarseStoredRead (coarseStoredMap f array).1 v = f (coarseStoredRead array v) := by + cases array with + | none => exact hzero.symm + | some cells => simp only [coarseStoredMap, coarseStoredRead, List.getElem_map] + +theorem coarseStoredMap_cost {n : ℕ} (f : ℚ → ℚ) (array : CoarseStoredArray n) : + (coarseStoredMap f array).2 ≤ 2 * n := by + cases array <;> simp only [coarseStoredMap] <;> omega + +def coarseStoredAdd {n : ℕ} : CoarseStoredArray n → CoarseStoredArray n → CoarseStoredArray n × ℕ + | none, right => (right, 0) + | left, none => (left, 0) + | some left, some right => + (some ⟨List.zipWith (· + ·) left.1 right.1, + by simp only [List.length_zipWith, left.2, right.2, min_self]⟩, n) + +theorem coarseStoredAdd_read {n : ℕ} (left right : CoarseStoredArray n) (v : Fin n) : + coarseStoredRead (coarseStoredAdd left right).1 v = + coarseStoredRead left v + coarseStoredRead right v := by + cases left with + | none => simp only [coarseStoredAdd, coarseStoredRead, zero_add] + | some left => + cases right with + | none => simp only [coarseStoredAdd, coarseStoredRead, add_zero] + | some right => simp only [coarseStoredAdd, coarseStoredRead, List.getElem_zipWith] + +theorem coarseStoredAdd_cost {n : ℕ} (left right : CoarseStoredArray n) : + (coarseStoredAdd left right).2 ≤ n := by + cases left <;> cases right <;> simp only [coarseStoredAdd] <;> omega + +/-- The costed linear sweeps operate on the stored cells. -/ +def coarseStoredPenalty {n : ℕ} : CoarseStoredArray n → CoarseStoredArray n × ℕ + | none => (none, 0) + | some cells => + let result := coarseCostedPenaltyTransform cells.1 + (some ⟨result.1, by rw [(coarseCostedPenaltyTransform_result cells.1).1, + coarsePenaltyTransform_length, cells.2]⟩, result.2) + +theorem coarseStoredPenalty_cost {n : ℕ} (array : CoarseStoredArray n) : + (coarseStoredPenalty array).2 ≤ 5 * n := by + cases array with + | none => simp only [coarseStoredPenalty]; omega + | some cells => + exact (coarseCostedPenaltyTransform_result cells.1).2.trans_eq (by rw [cells.2]) + +theorem coarseStoredPenalty_read {n : ℕ} [NeZero n] + (array : CoarseStoredArray n) (v : Fin n) : + coarseStoredRead (coarseStoredPenalty array).1 v = + univ.inf' univ_nonempty (fun next => + coarseStoredRead array next + (2 * Nat.dist v.val next.val : ℕ)) := by + cases array with + | none => + simp only [coarseStoredPenalty, coarseStoredRead, zero_add] + apply le_antisymm + · apply le_inf' + intro next hnext + positivity + · simpa only [Nat.dist_self, mul_zero, Nat.cast_zero] using + inf'_le (fun next : Fin n => ((2 * Nat.dist v.val next.val : ℕ) : ℚ)) (mem_univ v) + | some cells => + rcases cells with ⟨cells, hlength⟩ + subst n + simp only [coarseStoredPenalty, coarseStoredRead, + (coarseCostedPenaltyTransform_result cells).1] + exact coarsePenaltyTransform_getElem cells v + +/-- Each list member is evaluated once and its whole array is reused. -/ +def coarseArrayEvalChildren {B D : ℕ} {α : Type u} + (k : ℕ) (Q lam : ℚ) + (evaluate : CoarseSourceTree B α D → CoarseThresholdDraws B D → ℚ → ℕ → + CoarseStoredArray (2 * k + 1) × ℕ) (allowance : ℚ) : + List (CoarseSourceTree B α D × Fin B × CoarseThresholdDraws B D) → ℕ → + CoarseStoredArray (2 * k + 1) × ℕ + | [], _ => (none, 0) + | (child, draw, below) :: rest, start => + let threshold := coarseChildThreshold B Q allowance draw + let evaluated := evaluate child below (lam * threshold) start + let penalty := coarseStoredPenalty evaluated.1 + let contribution := coarseStoredMap + (coarseThresholdContribution threshold (allowance / Q)) penalty.1 + let remainder := coarseArrayEvalChildren k Q lam evaluate allowance rest + (start + child.word.length) + let total := coarseStoredAdd contribution.1 remainder.1 + (total.1, evaluated.2 + penalty.2 + contribution.2 + remainder.2 + total.2 + 7) + +/-- Actual shared-array recursion. Pruning creates a zero marker and does +not traverse any descendants. -/ +def coarseArrayEval {B : ℕ} {α : Type u} [DecidableEq α] + (k : ℕ) (Q lam : ℚ) (frame : List (Option α)) : + {D : ℕ} → CoarseSourceTree B α D → CoarseThresholdDraws B D → ℚ → ℕ → + CoarseStoredArray (2 * k + 1) × ℕ + | _, tree, draws, allowance, start => + if (tree.word.length : ℚ) ≤ allowance then (none, 1) else + match tree, draws with + | .leaf letter, _ => + (coarseStoredOfFn (fun shift => + (coarseShiftCost k frame (.leaf (B := B) letter) start shift : ℚ)), + 1 + 3 * (2 * k + 1)) + | .branch children, (draws, below) => + let result := coarseArrayEvalChildren k Q lam + (fun child => coarseArrayEval k Q lam frame child) allowance + (List.ofFn fun i => (children i, draws i, below i)) start + (result.1, result.2 + 1) + +theorem coarseArrayEvalChildren_read {B D : ℕ} {α : Type u} + (k : ℕ) (Q lam : ℚ) + (evaluate : CoarseSourceTree B α D → CoarseThresholdDraws B D → ℚ → ℕ → + CoarseStoredArray (2 * k + 1) × ℕ) + (value : CoarseSourceTree B α D → CoarseThresholdDraws B D → ℚ → ℕ → Fin (2 * k + 1) → ℚ) + (children : List (CoarseSourceTree B α D × Fin B × CoarseThresholdDraws B D)) + (hchild : ∀ child draw below, (child, draw, below) ∈ children → + ∀ a start shift, 0 < a → coarseStoredRead (evaluate child below a start).1 shift = + value child below a start shift) + (allowance : ℚ) (start : ℕ) (shift : Fin (2 * k + 1)) + (hQ : 0 < Q) (hlam : 0 < lam) (ha : 0 < allowance) : + coarseStoredRead (coarseArrayEvalChildren k Q lam evaluate allowance children start).1 shift = + coarseThresholdChildrenCost k Q lam value allowance children start shift := by + induction children generalizing start with + | nil => rfl + | cons data rest ih => + obtain ⟨child, draw, below⟩ := data + have ht : 0 < coarseChildThreshold B Q allowance draw := coarseChildThreshold_pos draw hQ ha + have hc := hchild child draw below (by simp) + have hrest := ih (fun child draw below hmem => hchild child draw below (by simp [hmem])) + (start + child.word.length) + simp only [coarseArrayEvalChildren, coarseThresholdChildrenCost] + rw [coarseStoredAdd_read, coarseStoredMap_read] + · rw [coarseStoredPenalty_read, hrest] + congr 2 + apply congrArg + funext next + rw [hc _ start next (mul_pos hlam ht)] + · simp only [coarseThresholdContribution, not_le_of_gt ht, ↓reduceIte] + +theorem coarseArrayEval_read {B D : ℕ} {α : Type u} [DecidableEq α] + (k : ℕ) (Q lam : ℚ) (frame : List (Option α)) + (tree : CoarseSourceTree B α D) (draws : CoarseThresholdDraws B D) + (allowance : ℚ) (start : ℕ) (shift : Fin (2 * k + 1)) + (hQ : 0 < Q) (hlam : 0 < lam) (ha : 0 < allowance) : + coarseStoredRead (coarseArrayEval k Q lam frame tree draws allowance start).1 shift = + coarseThresholdEstimate k Q lam frame tree draws allowance start shift := by + induction tree generalizing allowance start shift with + | leaf letter => + simp only [coarseArrayEval, coarseThresholdEstimate] + split_ifs + · rfl + · exact coarseStoredRead_ofFn _ shift + | branch children ih => + obtain ⟨draws, below⟩ := draws + simp only [coarseArrayEval, coarseThresholdEstimate] + split_ifs + · rfl + · apply coarseArrayEvalChildren_read k Q lam _ _ _ _ allowance start shift hQ hlam ha + intro child draw below hmem a start shift ha + obtain ⟨i, hi⟩ := List.mem_ofFn.mp hmem + cases hi + exact ih i _ a start shift ha + +/-- The instrumented child traversal charges the once-evaluated child plus +at most sixteen parent shift-array units for each list member. -/ +theorem coarseArrayEvalChildren_cost {B D : ℕ} {α : Type u} + (k : ℕ) (Q lam : ℚ) + (evaluate : CoarseSourceTree B α D → CoarseThresholdDraws B D → ℚ → ℕ → + CoarseStoredArray (2 * k + 1) × ℕ) + (work : CoarseSourceTree B α D → CoarseThresholdDraws B D → ℚ → ℕ) + (children : List (CoarseSourceTree B α D × Fin B × CoarseThresholdDraws B D)) + (hchild : ∀ child draw below, (child, draw, below) ∈ children → + ∀ a start, (evaluate child below a start).2 ≤ 32 * work child below a + 1) + (allowance : ℚ) (start : ℕ) : + (coarseArrayEvalChildren k Q lam evaluate allowance children start).2 ≤ + 32 * coarseActiveChildrenWork Q lam allowance work children + + 16 * children.length * (2 * k + 1) := by + induction children generalizing start with + | nil => simp only [coarseArrayEvalChildren, coarseActiveChildrenWork, List.length_nil, + mul_zero, zero_mul, zero_add, le_refl] + | cons data rest ih => + obtain ⟨child, draw, below⟩ := data + have hc := hchild child draw below (by simp) + (lam * coarseChildThreshold B Q allowance draw) start + have hr := ih (fun child draw below hmem => hchild child draw below (by simp [hmem])) + (start + child.word.length) + have hp := coarseStoredPenalty_cost + (evaluate child below (lam * coarseChildThreshold B Q allowance draw) start).1 + have hm := coarseStoredMap_cost + (coarseThresholdContribution (coarseChildThreshold B Q allowance draw) (allowance / Q)) + (coarseStoredPenalty (evaluate child below (lam * coarseChildThreshold B Q allowance draw) start).1).1 + have hs := coarseStoredAdd_cost + (coarseStoredMap (coarseThresholdContribution (coarseChildThreshold B Q allowance draw) (allowance / Q)) + (coarseStoredPenalty (evaluate child below (lam * coarseChildThreshold B Q allowance draw) start).1).1).1 + (coarseArrayEvalChildren k Q lam evaluate allowance rest (start + child.word.length)).1 + simp only [coarseArrayEvalChildren, coarseActiveChildrenWork, List.length_cons] + nlinarith + +/-- Every execution's shared evaluation has the rational-operation cost +bounded by the very same pruning-stopped counter used in expectation. -/ +theorem coarseArrayEval_cost {B D : ℕ} [NeZero B] {α : Type u} [DecidableEq α] + (k : ℕ) (Q lam : ℚ) (frame : List (Option α)) + (tree : CoarseSourceTree B α D) (draws : CoarseThresholdDraws B D) + (allowance : ℚ) (start : ℕ) : + (coarseArrayEval k Q lam frame tree draws allowance start).2 ≤ + 32 * coarseActiveArrayWork k Q lam tree draws allowance + 1 := by + have hB : 1 ≤ B := Nat.pos_of_ne_zero (NeZero.ne B) + induction tree generalizing allowance start with + | leaf letter => + simp only [coarseArrayEval, coarseActiveArrayWork] + split_ifs + · omega + · nlinarith + | branch children ih => + obtain ⟨draws, below⟩ := draws + simp only [coarseArrayEval, coarseActiveArrayWork] + split_ifs + · omega + · have hc := coarseArrayEvalChildren_cost k Q lam + (fun child => coarseArrayEval k Q lam frame child) + (fun child => coarseActiveArrayWork k Q lam child) + (List.ofFn fun i => (children i, draws i, below i)) + (by + intro child draw below hmem a start + obtain ⟨i, hi⟩ := List.mem_ofFn.mp hmem + cases hi + exact ih i _ a start) + allowance start + simp only [List.length_ofFn] at hc + nlinarith + +/-- Expected rational-operation count for the actual shared-array evaluator. +This estimate holds on every execution, including inaccurate ones. -/ +theorem coarseArrayEval_expected_bound {B D : ℕ} [NeZero B] {α : Type u} [DecidableEq α] + [MeasurableSpace (Fin B)] [MeasurableSingletonClass (Fin B)] + (k : ℕ) (Q lam : ℚ) (frame : List (Option α)) + (tree : CoarseSourceTree B α D) (allowance : ℚ) (start : ℕ) + (hQ : 0 < Q) (hlam : 0 < lam) (ha : 0 < allowance) : + (∫ draws, ((coarseArrayEval k Q lam frame tree draws allowance start).2 : ℝ) + ∂coarseDrawMeasure B D) ≤ + 32 * ((B * (2 * k + 1) : ℕ) * (tree.word.length : ℝ) / allowance * + coarseWorkMultiplier (coarseInverseAllowanceFactor B Q lam) D) + 1 := by + calc + _ ≤ ∫ draws, 32 * (coarseActiveArrayWork k Q lam tree draws allowance : ℝ) + 1 + ∂coarseDrawMeasure B D := by + apply MeasureTheory.integral_mono (.of_finite) (.of_finite) + intro draws + dsimp only + exact_mod_cast coarseArrayEval_cost k Q lam frame tree draws allowance start + _ = 32 * (∫ draws, (coarseActiveArrayWork k Q lam tree draws allowance : ℝ) + ∂coarseDrawMeasure B D) + 1 := by + rw [MeasureTheory.integral_add (.of_finite) (.of_finite), + MeasureTheory.integral_const_mul] + simp only [MeasureTheory.integral_const, MeasureTheory.probReal_univ, + smul_eq_mul, one_mul] + _ ≤ _ := add_le_add (mul_le_mul_of_nonneg_left + (coarseActiveArrayWork_expected_bound k Q lam tree allowance hQ hlam ha) (by norm_num)) le_rfl + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseArrayHistory.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseArrayHistory.lean new file mode 100644 index 0000000000000000000000000000000000000000..1af7571085ef000cedd274e62bbb02fb3cd5d353 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseArrayHistory.lean @@ -0,0 +1,152 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseArrayStorage + +namespace OAI + +namespace EditApproximation +namespace BinaryFraction + +/-- Sum the stored bits of the four array results at each child step, +including every recursive child's array history. This allows all these +arrays to remain allocated instead of assuming prompt reclamation. -/ +def coarseChildrenArrayHistory {B d : ℕ} {α : Type*} (k q L : ℕ) (two : BinaryFraction) + (evaluate : CoarseSourceTree B α d → CoarseThresholdDraws B d → BinaryFraction → ℕ → + CoarseBinaryArray × ℕ) + (history : CoarseSourceTree B α d → CoarseThresholdDraws B d → BinaryFraction → ℕ → ℕ) + (allowance : BinaryFraction) : + List (CoarseSourceTree B α d × Fin B × CoarseThresholdDraws B d) → ℕ → ℕ + | [], _ => 0 + | (child, draw, below) :: rest, start => + let threshold := (coarseChildThresholdWithWork B q allowance draw).1 + let childAllowance := (coarseChildAllowanceWithWork L threshold).1 + let evaluated := (evaluate child below childAllowance start).1 + let penalty := (coarseBinaryPenaltyWithWork two evaluated).1 + let scale := (coarseChildAllowanceWithWork q allowance).1 + let contribution := (coarseBinaryMapWithWork (coarseContributionWithWork threshold scale) penalty).1 + let remainder := coarseBinaryChildren k q L two evaluate allowance rest (start + child.word.length) + let total := (coarseBinaryAddWithWork contribution remainder.1).1 + history child below childAllowance start + + coarseChildrenArrayHistory k q L two evaluate history allowance rest (start + child.word.length) + + coarseArrayStorage evaluated + coarseArrayStorage penalty + + coarseArrayStorage contribution + coarseArrayStorage total + +def coarseBinaryArrayHistory {B : ℕ} {α : Type*} [DecidableEq α] + (k q L : ℕ) (frame : List (Option α)) (two : BinaryFraction) : + {d : ℕ} → CoarseSourceTree B α d → CoarseThresholdDraws B d → BinaryFraction → ℕ → ℕ + | _, tree, draws, allowance, start => + if (leWithWork (nat tree.word.length) allowance).1 then 1 else + match tree, draws with + | .leaf letter, leafDraw => + coarseArrayStorage (coarseBinaryEval k q L frame two (.leaf letter) leafDraw allowance start).1 + | .branch children, (draws, below) => + coarseArrayStorage (coarseBinaryEval k q L frame two (.branch children) (draws, below) allowance start).1 + + coarseChildrenArrayHistory k q L two + (fun child => coarseBinaryEval k q L frame two child) + (fun child => coarseBinaryArrayHistory k q L frame two child) + allowance (List.ofFn fun i => (children i, draws i, below i)) start + +theorem coarseChildrenArrayHistory_bound {B d : ℕ} {α : Type*} + (k q L N V D A C : ℕ) (two allowance : BinaryFraction) + (evaluate : CoarseSourceTree B α d → CoarseThresholdDraws B d → BinaryFraction → ℕ → + CoarseBinaryArray × ℕ) + (history : CoarseSourceTree B α d → CoarseThresholdDraws B d → BinaryFraction → ℕ → ℕ) + (weight : CoarseSourceTree B α d → CoarseThresholdDraws B d → BinaryFraction → ℕ) + (children : List (CoarseSourceTree B α d × Fin B × CoarseThresholdDraws B d)) + (hB : 0 < B) (hlen : children.length ≤ B) (htwo : two.value = 2) (htw : two.width ≤ A) + (ha : allowance.width ≤ A) (hBbits : Nat.size B + 2 ≤ A) + (hqbits : Nat.size q + 2 ≤ A) (hLbits : Nat.size L + 2 ≤ A) (hNbits : Nat.size N ≤ A) + (ht : ∀ draw : Fin B, (coarseChildThresholdWithWork B q allowance draw).1.width ≤ A) + (hs : CoarseGridCell two (coarseChildAllowanceWithWork q allowance).1 k D A) + (hbound : Nat.size (B * (V + k) + 2) + 2 * D + 1 ≤ A) + (he : ∀ child draw below, (child, draw, below) ∈ children → ∀ s, + s + child.word.length ≤ N → + CoarseBinaryBox two (2 * k + 1) V D A + (evaluate child below (coarseChildAllowanceWithWork L + (coarseChildThresholdWithWork B q allowance draw).1).1 s).1 ∧ + (evaluate child below (coarseChildAllowanceWithWork L + (coarseChildThresholdWithWork B q allowance draw).1).1 s).2 ≤ + (100000000 * (A + 1) ^ 2) * weight child below + (coarseChildAllowanceWithWork L (coarseChildThresholdWithWork B q allowance draw).1).1) + (hh : ∀ child draw below, (child, draw, below) ∈ children → ∀ s, + s + child.word.length ≤ N → + history child below (coarseChildAllowanceWithWork L + (coarseChildThresholdWithWork B q allowance draw).1).1 s ≤ + C * weight child below (coarseChildAllowanceWithWork L + (coarseChildThresholdWithWork B q allowance draw).1).1) + (start : ℕ) (hstart : start + coarseChildrenSpan children ≤ N) : + coarseChildrenArrayHistory k q L two evaluate history allowance children start ≤ + C * coarseBinaryChildrenWeight q L weight allowance children + + 4 * (1 + (2 * k + 1) * (2 * A + 3)) * children.length := by + have hvbound : Nat.size (V + 2) + 2 * D + 1 ≤ A := + (Nat.add_le_add_right (Nat.add_le_add_right (Nat.size_le_size + (by nlinarith : V + 2 ≤ B * (V + k) + 2)) _) _).trans hbound + have hmapped : Nat.size (V + k) + 2 * D + 1 ≤ A := + (Nat.add_le_add_right (Nat.add_le_add_right (Nat.size_le_size + (by nlinarith : V + k ≤ B * (V + k) + 2)) _) _).trans hbound + induction children generalizing start with + | nil => simp only [coarseChildrenArrayHistory, coarseBinaryChildrenWeight, List.length_nil, + Nat.mul_zero, Nat.add_zero, le_refl] + | cons data rest ih => + obtain ⟨child, draw, below⟩ := data + have hspan : start + (child.word.length + coarseChildrenSpan rest) ≤ N := hstart + have hc := he child draw below List.mem_cons_self start (by omega) + have hhistory := hh child draw below List.mem_cons_self start (by omega) + have hrest := ih (by simp only [List.length_cons] at hlen; omega) + (fun child draw below hmem => he child draw below (List.mem_cons_of_mem _ hmem)) + (fun child draw below hmem => hh child draw below (List.mem_cons_of_mem _ hmem)) + (start + child.word.length) (by omega) + have hr := coarseBinaryChildren_bounds k q L N V D A two allowance evaluate weight rest + hB (by simp only [List.length_cons] at hlen; omega) htwo htw ha hBbits hqbits hLbits hNbits ht hs hbound + (fun child draw below hmem => he child draw below (List.mem_cons_of_mem _ hmem)) + (start + child.word.length) (by omega) + let threshold := (coarseChildThresholdWithWork B q allowance draw).1 + let childAllowance := (coarseChildAllowanceWithWork L threshold).1 + let evaluated := (evaluate child below childAllowance start).1 + let penalty := (coarseBinaryPenaltyWithWork two evaluated).1 + let scale := (coarseChildAllowanceWithWork q allowance).1 + let contribution := (coarseBinaryMapWithWork (coarseContributionWithWork threshold scale) penalty).1 + let remainder := (coarseBinaryChildren k q L two evaluate allowance rest (start + child.word.length)).1 + have hpen : CoarseBinaryBox two (2 * k + 1) V D A penalty := + coarseBinaryPenaltyWithWork_box two _ V D A evaluated hc.1 htwo htw hvbound + have hcon : CoarseBinaryBox two (2 * k + 1) (V + k) D A contribution := + coarseBinaryMapWithWork_box two _ V (V + k) D A _ penalty hpen + (fun a ha => coarseContributionWithWork_bounds two threshold scale a V k D A ha hs hmapped) + have habound : Nat.size ((V + k) + rest.length * (V + k)) + 2 * D + 1 ≤ A := by + apply le_trans _ hbound + apply Nat.add_le_add_right + apply Nat.add_le_add_right + apply Nat.size_le_size + simp only [List.length_cons] at hlen + nlinarith + have htotal := coarseBinaryAddWithWork_box two (2 * k + 1) (V + k) + (rest.length * (V + k)) D A contribution remainder hcon hr.1 habound + have hevalBits := coarseArrayStorage_le two _ _ D A evaluated hc.1 + have hpenBits := coarseArrayStorage_le two _ _ D A penalty hpen + have hconBits := coarseArrayStorage_le two _ _ D A contribution hcon + have htotalBits := coarseArrayStorage_le two _ _ D A _ htotal + let F := 1 + (2 * k + 1) * (2 * A + 3) + change history child below childAllowance start ≤ C * weight child below childAllowance at hhistory + change coarseChildrenArrayHistory k q L two evaluate history allowance rest (start + child.word.length) ≤ + C * coarseBinaryChildrenWeight q L weight allowance rest + 4 * F * rest.length at hrest + have hfour : coarseArrayStorage evaluated + coarseArrayStorage penalty + + coarseArrayStorage contribution + + coarseArrayStorage (coarseBinaryAddWithWork contribution remainder).1 ≤ 4 * F := by + dsimp only [F] + omega + calc + _ ≤ C * weight child below childAllowance + + (C * coarseBinaryChildrenWeight q L weight allowance rest + 4 * F * rest.length) + + 4 * F := by + change history child below childAllowance start + + coarseChildrenArrayHistory k q L two evaluate history allowance rest (start + child.word.length) + + coarseArrayStorage evaluated + coarseArrayStorage penalty + coarseArrayStorage contribution + + coarseArrayStorage (coarseBinaryAddWithWork contribution remainder).1 ≤ _ + omega + _ = _ := by + simp only [coarseBinaryChildrenWeight, List.length_cons] + dsimp only [F, childAllowance, threshold] + ring + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseArrayRepresentation.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseArrayRepresentation.lean new file mode 100644 index 0000000000000000000000000000000000000000..1c5394988719f55d890e27c35a83a6baca0c6827 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseArrayRepresentation.lean @@ -0,0 +1,84 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarsePenaltyArithmetic +import OAI.Combinatorics.EditApproximation.Coarse.CoarseArrayEval +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Binary storage operations used by the shared coarse-array recursion. +A missing array is the same zero marker as in the rational specification. -/ + +namespace EditApproximation +namespace BinaryFraction + + + +def coarseBinaryContents (array : CoarseBinaryArray) : Option (List ℚ) := + array.map (List.map value) + +def coarseRationalContents {n : ℕ} (array : CoarseStoredArray n) : Option (List ℚ) := + array.map Subtype.val + + + + theorem coarseBinaryPenaltyWithWork_value (two : BinaryFraction) (values : List BinaryFraction) + (htwo : two.value = 2) + (hs : ∀ a ∈ values, a.representation.den = two.representation.den) : + coarseBinaryContents (coarseBinaryPenaltyWithWork two (some values)).1 = + some (coarsePenaltyTransform (values.map value)) := by + exact congrArg some (coarseGridPenaltyWithWork_value two values htwo hs) + +/-- Both input lists are visited once; the same denominator is retained. -/ + + + theorem coarseGridZipAddWithWork_value (left right : List BinaryFraction) + (hden : ∀ a ∈ left, ∀ b ∈ right, a.representation.den = b.representation.den) : + (coarseGridZipAddWithWork left right).1.map value = + List.zipWith (· + ·) (left.map value) (right.map value) := by + induction left generalizing right with + | nil => rfl + | cons a left ih => + cases right with + | nil => rfl + | cons b right => + simp only [coarseGridZipAddWithWork, List.map_cons, List.zipWith_cons_cons] + rw [coarseGridAddWithWork_value a b (hden a List.mem_cons_self b List.mem_cons_self), + ih right (fun x hx y hy => hden x (List.mem_cons_of_mem _ hx) y (List.mem_cons_of_mem _ hy))] + + theorem coarseGridZipAddWithWork_cost (left right : List BinaryFraction) + (B : ℕ) (hl : ∀ a ∈ left, a.width ≤ B) (hr : ∀ a ∈ right, a.width ≤ B) : + (coarseGridZipAddWithWork left right).2 ≤ + min left.length right.length * (100 * (B + 1) + 3) := by + induction left generalizing right with + | nil => simp only [coarseGridZipAddWithWork, List.length_nil, Nat.zero_min, Nat.zero_mul, le_refl] + | cons a left ih => + cases right with + | nil => simp only [coarseGridZipAddWithWork, List.length_nil, Nat.min_zero, Nat.zero_mul, le_refl] + | cons b right => + have hh := coarseGridAddWithWork_cost a b B (hl a List.mem_cons_self) (hr b List.mem_cons_self) + have ht := ih right (fun a ha => hl a (List.mem_cons_of_mem _ ha)) + (fun b hb => hr b (List.mem_cons_of_mem _ hb)) + change (coarseGridAddWithWork a b).2 + (coarseGridZipAddWithWork left right).2 + 3 ≤ _ + simp only [List.length_cons] + rw [show min (left.length + 1) (right.length + 1) = min left.length right.length + 1 by omega, + Nat.add_mul, Nat.one_mul] + omega + + + + + + theorem coarseBinaryMapWithWork_value (f : BinaryFraction → BinaryFraction × ℕ) + (spec : ℚ → ℚ) (hf : ∀ a, (f a).1.value = spec a.value) (array : CoarseBinaryArray) : + coarseBinaryContents (coarseBinaryMapWithWork f array).1 = + (coarseBinaryContents array).map (List.map spec) := by + cases array with + | none => rfl + | some values => + simp only [coarseBinaryMapWithWork, coarseBinaryContents, Option.map_some, + arithmeticMapWithWork_value, List.map_map, Function.comp_def, hf] + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseArraySimulation.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseArraySimulation.lean new file mode 100644 index 0000000000000000000000000000000000000000..9583ceefd470a9793b9052f0270dd5aeee5b990e --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseArraySimulation.lean @@ -0,0 +1,199 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseArrayRepresentation + +namespace OAI + +namespace EditApproximation +namespace BinaryFraction + +private theorem coarseMin_result (a b : BinaryFraction) : + (minWithWork a b).1 = a ∨ (minWithWork a b).1 = b := by + unfold minWithWork + dsimp only + split_ifs <;> simp only [true_or, or_true] + + theorem coarseGridScan_den (two previous : BinaryFraction) (source : List BinaryFraction) + (hp : previous.representation.den = two.representation.den) + (hs : ∀ a ∈ source, a.representation.den = two.representation.den) : + ∀ a ∈ (coarseGridScanWithWork two previous source).1, + a.representation.den = two.representation.den := by + induction source generalizing previous with + | nil => simpa only [coarseGridScanWithWork, List.mem_singleton] using + (fun a (ha : a = previous) => ha ▸ hp) + | cons head rest ih => + have hh := hs head List.mem_cons_self + have ha := (coarseGridAddWithWork_den previous two).trans hp + have hn : (minWithWork head (coarseGridAddWithWork previous two).1).1.representation.den = + two.representation.den := by + rcases coarseMin_result head (coarseGridAddWithWork previous two).1 with h | h + · simpa only [h] using hh + · simpa only [h] using ha + intro a hmem + change a ∈ previous :: _ at hmem + rcases List.mem_cons.mp hmem with rfl | hmem + · exact hp + · exact ih _ hn (fun a ha => hs a (List.mem_cons_of_mem _ ha)) a hmem + + theorem coarseGridLeft_den (two : BinaryFraction) (source : List BinaryFraction) + (hs : ∀ a ∈ source, a.representation.den = two.representation.den) : + ∀ a ∈ (coarseGridLeftWithWork two source).1, + a.representation.den = two.representation.den := by + cases source with + | nil => simp only [coarseGridLeftWithWork, List.not_mem_nil, false_implies, implies_true] + | cons head rest => + exact coarseGridScan_den two head rest (hs head List.mem_cons_self) + (fun a ha => hs a (List.mem_cons_of_mem _ ha)) + + theorem coarseGridZipMinimum_den (left right : List BinaryFraction) (D : ℕ) + (hl : ∀ a ∈ left, a.representation.den = D) + (hr : ∀ a ∈ right, a.representation.den = D) : + ∀ a ∈ (coarseGridZipMinimumWithWork left right).1, a.representation.den = D := by + induction left generalizing right with + | nil => simp only [coarseGridZipMinimumWithWork, List.not_mem_nil, false_implies, implies_true] + | cons a left ih => + cases right with + | nil => simp only [coarseGridZipMinimumWithWork, List.not_mem_nil, false_implies, implies_true] + | cons b right => + intro c hc + change c ∈ (minWithWork a b).1 :: _ at hc + rcases List.mem_cons.mp hc with rfl | hc + · rcases coarseMin_result a b with h | h + · simpa only [h] using hl a List.mem_cons_self + · simpa only [h] using hr b List.mem_cons_self + · exact ih right (fun a ha => hl a (List.mem_cons_of_mem _ ha)) + (fun b hb => hr b (List.mem_cons_of_mem _ hb)) c hc + + theorem coarseGridPenalty_den (two : BinaryFraction) (source : List BinaryFraction) + (hs : ∀ a ∈ source, a.representation.den = two.representation.den) : + ∀ a ∈ (coarseGridPenaltyWithWork two source).1, + a.representation.den = two.representation.den := by + apply coarseGridZipMinimum_den + · exact coarseGridLeft_den two source hs + · intro a ha + exact coarseGridLeft_den two source.reverse + (fun b hb => hs b (List.mem_reverse.mp hb)) a (List.mem_reverse.mp ha) + + theorem coarseGridZipAdd_den (left right : List BinaryFraction) (D : ℕ) + (hl : ∀ a ∈ left, a.representation.den = D) : + ∀ a ∈ (coarseGridZipAddWithWork left right).1, a.representation.den = D := by + induction left generalizing right with + | nil => simp only [coarseGridZipAddWithWork, List.not_mem_nil, false_implies, implies_true] + | cons a left ih => + cases right with + | nil => simp only [coarseGridZipAddWithWork, List.not_mem_nil, false_implies, implies_true] + | cons b right => + intro c hc + change c ∈ (coarseGridAddWithWork a b).1 :: _ at hc + rcases List.mem_cons.mp hc with rfl | hc + · exact (coarseGridAddWithWork_den a b).trans (hl a List.mem_cons_self) + · exact ih right (fun a ha => hl a (List.mem_cons_of_mem _ ha)) c hc + +/-- The array relation ignores proof fields and keeps exact stored values. -/ +def CoarseArrayRep {n : ℕ} (actual : CoarseBinaryArray) (spec : CoarseStoredArray n) : Prop := + coarseBinaryContents actual = coarseRationalContents spec + +def CoarseArrayOnGrid (D : ℕ) (actual : CoarseBinaryArray) : Prop := + ∀ values, actual = some values → ∀ a ∈ values, a.representation.den = D + + theorem coarseBinaryAdd_grid (a b : CoarseBinaryArray) (D : ℕ) + (ha : CoarseArrayOnGrid D a) (hb : CoarseArrayOnGrid D b) : + CoarseArrayOnGrid D (coarseBinaryAddWithWork a b).1 := by + cases a with + | none => exact hb + | some a => + cases b with + | none => exact ha + | some b => + intro values hv + have heq : (coarseGridZipAddWithWork a b).1 = values := Option.some.inj hv + rw [← heq] + exact coarseGridZipAdd_den a b D (ha a rfl) + + theorem coarseBinaryPenalty_grid (two : BinaryFraction) (a : CoarseBinaryArray) + (ha : CoarseArrayOnGrid two.representation.den a) : + CoarseArrayOnGrid two.representation.den (coarseBinaryPenaltyWithWork two a).1 := by + cases a with + | none => intro values hv; cases hv + | some a => + intro values hv + have heq : (coarseGridPenaltyWithWork two a).1 = values := Option.some.inj hv + rw [← heq] + exact coarseGridPenalty_den two a (ha a rfl) + + theorem coarseBinaryMap_grid (f : BinaryFraction → BinaryFraction × ℕ) (a : CoarseBinaryArray) + (D : ℕ) (ha : CoarseArrayOnGrid D a) + (hf : ∀ z, z.representation.den = D → (f z).1.representation.den = D) : + CoarseArrayOnGrid D (coarseBinaryMapWithWork f a).1 := by + cases a with + | none => intro values hv; cases hv + | some a => + intro values hv z hz + have heq : (arithmeticMapWithWork f a).1 = values := Option.some.inj hv + rw [← heq, arithmeticMapWithWork_value] at hz + obtain ⟨x, hx, rfl⟩ := List.mem_map.mp hz + exact hf x (ha a rfl x hx) + +def coarseContentsAdd : Option (List ℚ) → Option (List ℚ) → Option (List ℚ) + | none, b => b + | a, none => a + | some a, some b => some (List.zipWith (· + ·) a b) + + theorem coarseStoredAdd_contents {n : ℕ} (a b : CoarseStoredArray n) : + coarseRationalContents (coarseStoredAdd a b).1 = + coarseContentsAdd (coarseRationalContents a) (coarseRationalContents b) := by + cases a <;> cases b <;> rfl + + theorem coarseBinaryAdd_contents (a b : CoarseBinaryArray) (D : ℕ) + (ha : ∀ values, a = some values → ∀ x ∈ values, x.representation.den = D) + (hb : ∀ values, b = some values → ∀ x ∈ values, x.representation.den = D) : + coarseBinaryContents (coarseBinaryAddWithWork a b).1 = + coarseContentsAdd (coarseBinaryContents a) (coarseBinaryContents b) := by + cases a with + | none => rfl + | some a => + cases b with + | none => rfl + | some b => + exact congrArg some (coarseGridZipAddWithWork_value a b + (fun x hx y hy => (ha a rfl x hx).trans (hb b rfl y hy).symm)) + + theorem coarseBinaryAdd_rep {n : ℕ} (a b : CoarseBinaryArray) (x y : CoarseStoredArray n) + (D : ℕ) (hx : CoarseArrayRep a x) (hy : CoarseArrayRep b y) + (ha : ∀ values, a = some values → ∀ z ∈ values, z.representation.den = D) + (hb : ∀ values, b = some values → ∀ z ∈ values, z.representation.den = D) : + CoarseArrayRep (coarseBinaryAddWithWork a b).1 (coarseStoredAdd x y).1 := by + change coarseBinaryContents _ = coarseRationalContents _ + rw [coarseBinaryAdd_contents a b D ha hb, coarseStoredAdd_contents, hx, hy] + + theorem coarseStoredPenalty_contents {n : ℕ} (a : CoarseStoredArray n) : + coarseRationalContents (coarseStoredPenalty a).1 = + (coarseRationalContents a).map coarsePenaltyTransform := by + cases a with + | none => rfl + | some a => + exact congrArg some (coarseCostedPenaltyTransform_result a.1).1 + + theorem coarseBinaryPenalty_rep {n : ℕ} (two : BinaryFraction) (a : CoarseBinaryArray) + (x : CoarseStoredArray n) (htwo : two.value = 2) (hx : CoarseArrayRep a x) + (ha : ∀ values, a = some values → ∀ z ∈ values, z.representation.den = two.representation.den) : + CoarseArrayRep (coarseBinaryPenaltyWithWork two a).1 (coarseStoredPenalty x).1 := by + change coarseBinaryContents _ = coarseRationalContents _ + rw [coarseStoredPenalty_contents, ← hx] + cases a with + | none => rfl + | some a => exact coarseBinaryPenaltyWithWork_value two a htwo (ha a rfl) + + theorem coarseStoredMap_contents {n : ℕ} (f : ℚ → ℚ) (a : CoarseStoredArray n) : + coarseRationalContents (coarseStoredMap f a).1 = (coarseRationalContents a).map (List.map f) := by + cases a <;> rfl + + theorem coarseBinaryMap_rep {n : ℕ} (f : BinaryFraction → BinaryFraction × ℕ) (g : ℚ → ℚ) + (hf : ∀ a, (f a).1.value = g a.value) (a : CoarseBinaryArray) (x : CoarseStoredArray n) + (hx : CoarseArrayRep a x) : + CoarseArrayRep (coarseBinaryMapWithWork f a).1 (coarseStoredMap g x).1 := by + change coarseBinaryContents _ = coarseRationalContents _ + rw [coarseBinaryMapWithWork_value f g hf, coarseStoredMap_contents, hx] + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseArrayStorage.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseArrayStorage.lean new file mode 100644 index 0000000000000000000000000000000000000000..86df2bb09087399cb8e4ac5bcb9fb0652068f2af --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseArrayStorage.lean @@ -0,0 +1,116 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseRootBounds +import OAI.Combinatorics.EditApproximation.Coarse.CoarseIndexedInitial + +namespace OAI + +namespace EditApproximation +namespace BinaryFraction + +/-- The stored numerator bits, denominator bits, sign and list links. -/ +def coarseArrayStorage : CoarseBinaryArray → ℕ + | none => 1 + | some cells => 1 + (cells.map fun a => a.numerator.bits.length + a.denominator.length + 3).sum + +theorem coarseArrayStorage_le (two : BinaryFraction) (n V D A : ℕ) + (array : CoarseBinaryArray) (h : CoarseBinaryBox two n V D A array) : + coarseArrayStorage array ≤ 1 + n * (2 * A + 3) := by + cases array with + | none => simp only [coarseArrayStorage]; omega + | some cells => + have hw (a : BinaryFraction) (ha : a ∈ cells) : + a.numerator.bits.length + a.denominator.length + 3 ≤ 2 * A + 3 := by + have hab := ((h cells rfl).2 a ha).2.2.2.2 + unfold width at hab + omega + have hsum (values : List BinaryFraction) + (hv : ∀ a ∈ values, a.numerator.bits.length + a.denominator.length + 3 ≤ 2 * A + 3) : + (values.map fun a => a.numerator.bits.length + a.denominator.length + 3).sum ≤ + values.length * (2 * A + 3) := by + induction values with + | nil => simp + | cons a values ih => + have ha := hv a List.mem_cons_self + have ht := ih (fun b hb => hv b (List.mem_cons_of_mem _ hb)) + simp only [List.map_cons, List.sum_cons, List.length_cons, Nat.add_mul, Nat.one_mul] + omega + have hs := hsum cells hw + rw [(h cells rfl).1] at hs + exact Nat.add_le_add_left hs 1 + +/-- The actual array immediately before the root lookup. -/ +def coarseRootArray {B d : ℕ} {α : Type*} [DecidableEq α] + (k q L : ℕ) (hB : 0 < B) (hq : 0 < q) (hL : 0 < L) + (frame : List (Option α)) (tree : CoarseSourceTree B α d) + (draws : CoarseThresholdDraws B d) (start : ℕ) : CoarseBinaryArray := + let den := coarseRootDenominator B q L d + let denPos := coarseRootDenominator_pos B q L d hB hq hL + let two := (coarseGridNatWithWork den.1 denPos 2).1 + let allowance := (coarseGridNatWithWork den.1 denPos k).1 + (coarseBinaryEval k q L frame two tree draws allowance start).1 + +theorem coarseRootArray_storage {B d : ℕ} {α : Type*} [DecidableEq α] + (k q L N D A : ℕ) (hB : 0 < B) (hq : 0 < q) (hL : 0 < L) + (frame : List (Option α)) (tree : CoarseSourceTree B α d) + (draws : CoarseThresholdDraws B d) (start : ℕ) + (hBbits : Nat.size B + 2 ≤ A) (hqbits : Nat.size q + 2 ≤ A) + (hLbits : Nat.size L + 2 ≤ A) (hNbits : Nat.size N + 2 ≤ A) + (hd : Nat.size (coarseCommonDenominator 1 q L B d) ≤ D) + (hbound : Nat.size (coarseLevelMagnitude N k B d + 2) + 2 * D + 1 ≤ A) + (hstart : start + tree.word.length ≤ N) : + coarseArrayStorage (coarseRootArray k q L hB hq hL frame tree draws start) ≤ + 1 + (2 * k + 1) * (2 * A + 3) := by + let den := coarseRootDenominator B q L d + let denPos := coarseRootDenominator_pos B q L d hB hq hL + let two := (coarseGridNatWithWork den.1 denPos 2).1 + let allowance := (coarseGridNatWithWork den.1 denPos k).1 + have hden := coarseRootDenominator_value B q L d + have hdenLen : den.1.length ≤ D := (coarseRootDenominator_length B q L d).trans_le hd + have htwo : two.value = 2 := coarseGridNatWithWork_value _ _ 2 + have htwoDen : two.representation.den = coarseCommonDenominator 1 q L B d := + (coarseGridNatWithWork_den _ _ 2).trans hden + have hkwidth : Nat.size k + 2 * D + 1 ≤ A := + (Nat.add_le_add_right (Nat.add_le_add_right (Nat.size_le_size + ((coarseLevelMagnitude_ge N k B d).trans (by omega))) _) _).trans hbound + have h2width : Nat.size 2 + 2 * D + 1 ≤ A := + (Nat.add_le_add_right (Nat.add_le_add_right (Nat.size_le_size + (by omega : 2 ≤ coarseLevelMagnitude N k B d + 2)) _) _).trans hbound + have htwocell : CoarseGridCell two two 2 D A := + coarseGridNatWithWork_bounds two den.1 denPos 2 2 D A + (coarseGridNatWithWork_den _ _ 2).symm hdenLen le_rfl h2width + have hacell : CoarseGridCell two allowance k D A := + coarseGridNatWithWork_bounds two den.1 denPos k k D A + (coarseGridNatWithWork_den _ _ 2).symm hdenLen le_rfl hkwidth + have hav : allowance.value = k := coarseGridNatWithWork_value _ _ k + have hpath : allowance.value.den ∣ (L * B * q) ^ 0 := by + simp only [hav, Rat.den_natCast, one_dvd] + have hc := (coarseBinaryEval_bitWork k q L N d D A frame two tree draws hB hq hL htwo + htwocell.2.2.2.2 (by rw [htwoDen]; exact hd) htwoDen hBbits hqbits hLbits hNbits hbound + 0 (by omega) allowance start hacell hpath hstart).1 + exact coarseArrayStorage_le two _ _ D A _ hc + +def coarseIndexedRootArray {B d : ℕ} (k q L : ℕ) + (hB : 0 < B) (hq : 0 < q) (hL : 0 < L) (x y : List ℕ) + (draws : CoarseThresholdDraws B d) : CoarseBinaryArray := + let den := coarseRootDenominator B q L d + let denPos := coarseRootDenominator_pos B q L d hB hq hL + let two := (coarseGridNatWithWork den.1 denPos 2).1 + let allowance := (coarseGridNatWithWork den.1 denPos k).1 + (coarseIndexedWithWork k q L (coarseEntryWidth x y) x y two d 0 draws allowance 0).1 + +theorem coarseIndexedRootArray_eq {B d : ℕ} (k q L : ℕ) + (hB : 0 < B) (hq : 0 < q) (hL : 0 < L) (x y : List ℕ) + (draws : CoarseThresholdDraws B d) : + coarseIndexedRootArray k q L hB hq hL x y draws = + coarseRootArray k q L hB hq hL + (coarseTargetFrame k (coarsePadTo (coarseEntryWidth x y) y)) + (coarseEntryTree B d x y) draws 0 := by + unfold coarseIndexedRootArray coarseRootArray + dsimp only + rw [coarseIndexedWithWork_value, coarseReadCore_eq k q L (coarseEntryWidth x y) x y + (le_max_left _ _) (le_max_right _ _)] + simp only [Nat.zero_add, coarseReadTree_entry] + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseBinaryBitWork.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseBinaryBitWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..e36e13df6e6755a1fe4a11c27faca64f3353600b --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseBinaryBitWork.lean @@ -0,0 +1,154 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseLevelMagnitude + +namespace OAI + +namespace EditApproximation +namespace BinaryFraction + +/-- Actual Boolean work of the complete pruning-stopped evaluator. The +hypotheses bound input registers and the common grid, not execution cost. -/ + theorem coarseBinaryEval_bitWork {B d : ℕ} {α : Type*} [DecidableEq α] + (k q L N R D A : ℕ) (frame : List (Option α)) (two : BinaryFraction) + (tree : CoarseSourceTree B α d) (draws : CoarseThresholdDraws B d) + (hB : 0 < B) (hq : 0 < q) (hL : 0 < L) (htwo : two.value = 2) + (htw : two.width ≤ A) (hd : Nat.size two.representation.den ≤ D) + (hroot : two.representation.den = coarseCommonDenominator 1 q L B R) + (hBbits : Nat.size B + 2 ≤ A) (hqbits : Nat.size q + 2 ≤ A) + (hLbits : Nat.size L + 2 ≤ A) (hNbits : Nat.size N + 2 ≤ A) + (hbound : Nat.size (coarseLevelMagnitude N k B R + 2) + 2 * D + 1 ≤ A) + (j : ℕ) (hdepth : j + d = R) (allowance : BinaryFraction) (start : ℕ) + (ha : CoarseGridCell two allowance k D A) + (hpath : allowance.value.den ∣ (L * B * q) ^ j) + (hstart : start + tree.word.length ≤ N) : + CoarseBinaryBox two (2 * k + 1) (coarseLevelMagnitude N k B d) D A + (coarseBinaryEval k q L frame two tree draws allowance start).1 ∧ + (coarseBinaryEval k q L frame two tree draws allowance start).2 ≤ + (100000000 * (A + 1) ^ 2) * coarseBinaryWeight k q L tree draws allowance := by + have hkbound : Nat.size k + 2 * D + 1 ≤ A := + (Nat.add_le_add_right (Nat.add_le_add_right (Nat.size_le_size + ((coarseLevelMagnitude_ge N k B R).trans (by omega))) _) _).trans hbound + induction tree generalizing j allowance start with + | leaf letter => + have hnat : (nat (CoarseSourceTree.leaf (B := B) letter).word.length).width ≤ A := + (nat_width_le _).trans ((Nat.add_le_add_right (Nat.size_le_size (by omega)) 2).trans hNbits) + have hp := leWithWork_cost (nat (CoarseSourceTree.leaf (B := B) letter).word.length) allowance A hnat ha.2.2.2.2 + have hs : Nat.size (CoarseSourceTree.leaf (B := B) letter).word.length ≤ A := + (Nat.size_le_size (show (CoarseSourceTree.leaf (B := B) letter).word.length ≤ N by omega)).trans (by omega) + rw [coarseBinaryEval, coarseBinaryWeight] + split_ifs + · exact ⟨coarseBinaryBox_none _ _ _ _ _, by dsimp only; nlinarith only [hp, hs, Nat.zero_le A]⟩ + · have hvbound : Nat.size (coarseLevelMagnitude N k B 0) + 2 * D + 1 ≤ A := + (Nat.add_le_add_right (Nat.add_le_add_right (Nat.size_le_size + ((coarseLevelMagnitude_mono N k B 0 R (by omega)).trans (by omega))) _) _).trans hbound + have hcell (shift : Fin (2 * k + 1)) : + CoarseGridCell two (coarseGridNatWithWork allowance.denominator allowance.denominator_pos + (coarseShiftCost k frame (.leaf (B := B) letter) start shift)).1 + (coarseLevelMagnitude N k B 0) D A := by + apply coarseGridNatWithWork_bounds two _ _ _ _ _ _ ha.1 ha.2.1 _ hvbound + have hcost : coarseShiftCost k frame (.leaf (B := B) letter) start shift ≤ 1 := by + cases letter <;> simp only [coarseShiftCost] <;> (try split_ifs) <;> omega + exact hcost.trans (coarseLevelMagnitude_pos N k B 0) + constructor + · intro cells hc + have heq : (arithmeticMapWithWork (fun shift : Fin (2 * k + 1) => + coarseGridNatWithWork allowance.denominator allowance.denominator_pos + (coarseShiftCost k frame (.leaf (B := B) letter) start shift)) + (List.finRange (2 * k + 1))).1 = cells := Option.some.inj hc + rw [← heq, arithmeticMapWithWork_value] + refine ⟨by simp, ?_⟩ + intro a hamem + obtain ⟨shift, _, rfl⟩ := List.mem_map.mp hamem + exact hcell shift + · have hc := arithmeticMapWithWork_cost (fun shift : Fin (2 * k + 1) => + coarseGridNatWithWork allowance.denominator allowance.denominator_pos + (coarseShiftCost k frame (.leaf (B := B) letter) start shift)) + (List.finRange (2 * k + 1)) (100 * (A + 1) ^ 2) (by + intro shift _ + apply coarseGridNatWithWork_cost _ _ _ A _ ((le_max_right _ _).trans ha.2.2.2.2) + have hcost : coarseShiftCost k frame (.leaf (B := B) letter) start shift ≤ 1 := by + cases letter <;> simp only [coarseShiftCost] <;> (try split_ifs) <;> omega + exact (Nat.size_le_size hcost).trans (by norm_num; omega)) + simp only [List.length_finRange] at hc + have hBn : 2 * k + 1 ≤ B * (2 * k + 1) := by nlinarith + have hbudget := Nat.mul_le_mul_left ((A + 1) ^ 2) hBn + have hunit : 1 ≤ (A + 1) ^ 2 := by + have hz : 0 < (A + 1) ^ 2 := by positivity + omega + have hnscale := Nat.mul_le_mul_right (2 * k + 1) hunit + dsimp only + nlinarith only [hp, hs, hc, hbudget, hnscale, Nat.zero_le A, Nat.zero_le k] + | @branch d children ih => + obtain ⟨draws, below⟩ := draws + have hnat : (nat (CoarseSourceTree.branch children).word.length).width ≤ A := + (nat_width_le _).trans ((Nat.add_le_add_right (Nat.size_le_size (by omega)) 2).trans hNbits) + have hp := leWithWork_cost (nat (CoarseSourceTree.branch children).word.length) allowance A hnat ha.2.2.2.2 + have hslen : Nat.size (CoarseSourceTree.branch children).word.length ≤ A := + (Nat.size_le_size (show (CoarseSourceTree.branch children).word.length ≤ N by omega)).trans (by omega) + rw [coarseBinaryEval, coarseBinaryWeight] + split_ifs + · exact ⟨coarseBinaryBox_none _ _ _ _ _, by dsimp only; nlinarith only [hp, hslen, Nat.zero_le A]⟩ + · have htval (draw : Fin B) : (coarseChildThresholdWithWork B q allowance draw).1.value = + coarseChildThreshold B q allowance.value draw := by + apply coarseChildThresholdWithWork_value + rw [ha.1, hroot, ← hdepth] + exact coarseThreshold_root_grid B q L j d allowance.value draw hB hq hpath + have htgrid (draw : Fin B) : CoarseGridCell two + (coarseChildThresholdWithWork B q allowance draw).1 k D A := by + apply coarseChildThresholdWithWork_bounds two allowance B q k D A draw hq ha hd _ hkbound + rw [ha.1, hroot, ← hdepth] + exact coarseThreshold_root_grid B q L j d allowance.value draw hB hq hpath + have hscale : CoarseGridCell two (coarseChildAllowanceWithWork q allowance).1 k D A := by + apply coarseChildAllowanceWithWork_bounds two allowance q k D A hq ha hd _ hkbound + rw [ha.1, hroot, ← hdepth] + exact coarseScale_root_grid B q L j (d + 1) allowance.value hq hpath + have hstep (draw : Fin B) : + CoarseGridCell two (coarseChildAllowanceWithWork L + (coarseChildThresholdWithWork B q allowance draw).1).1 k D A ∧ + (coarseChildAllowanceWithWork L (coarseChildThresholdWithWork B q allowance draw).1).1.value.den ∣ + (L * B * q) ^ (j + 1) := by + let threshold := (coarseChildThresholdWithWork B q allowance draw).1 + have hden : (threshold.value / L).den ∣ threshold.representation.den := by + rw [htval draw, (htgrid draw).1, hroot, ← hdepth] + rw [show coarseChildThreshold B q allowance.value draw / (L : ℚ) = + (1 / (L : ℚ)) * coarseChildThreshold B q allowance.value draw by ring] + exact coarseChildAllowance_root_grid B q L j d allowance.value draw hB hq hL hpath + refine ⟨coarseChildAllowanceWithWork_bounds two threshold L k D A hL (htgrid draw) hd hden hkbound, ?_⟩ + rw [coarseChildAllowanceWithWork_value L threshold hden, htval draw] + convert coarseChildAllowance_grid B q L j allowance.value draw hB hq hL hpath using 1 + congr 1 + ring + have hchildbound : Nat.size (B * (coarseLevelMagnitude N k B d + k) + 2) + 2 * D + 1 ≤ A := by + apply le_trans _ hbound + apply Nat.add_le_add_right + apply Nat.add_le_add_right + apply Nat.size_le_size + exact (coarseLevelMagnitude_succ N k B d).trans + ((coarseLevelMagnitude_mono N k B (d + 1) R (by omega)).trans (by omega)) + have hc := coarseBinaryChildren_bounds k q L N (coarseLevelMagnitude N k B d) D A two allowance + (fun child => coarseBinaryEval k q L frame two child) + (fun child => coarseBinaryWeight k q L child) + (List.ofFn fun i => (children i, draws i, below i)) hB (by simp) htwo htw ha.2.2.2.2 + hBbits hqbits hLbits (by omega) (fun draw => (htgrid draw).2.2.2.2) hscale hchildbound (by + intro child draw childBelow hmem s hs + obtain ⟨i, hi⟩ := List.mem_ofFn.mp hmem + cases hi + exact ih i (below i) (j + 1) (by omega) _ s (hstep (draws i)).1 (hstep (draws i)).2 hs) + start (by rwa [coarseChildrenSpan_ofFn]) + constructor + · have hm : (List.ofFn fun i => (children i, draws i, below i)).length * + (coarseLevelMagnitude N k B d + k) ≤ coarseLevelMagnitude N k B (d + 1) := by + simp only [List.length_ofFn] + exact (Nat.le_add_right _ 2).trans (coarseLevelMagnitude_succ N k B d) + exact coarseBinaryBox_mono two (2 * k + 1) _ _ D A _ hc.1 hm + · have hcost := hc.2 + simp only [List.length_ofFn] at hcost + have hprune : (leWithWork (nat (CoarseSourceTree.branch children).word.length) allowance).2 + + Nat.size (CoarseSourceTree.branch children).word.length + 1 ≤ 100000000 * (A + 1) ^ 2 := by + nlinarith only [hp, hslen, Nat.zero_le A] + dsimp only + nlinarith only [hcost, hprune] + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseBinaryBox.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseBinaryBox.lean new file mode 100644 index 0000000000000000000000000000000000000000..488b67b200abc7a46e7d061ef0f7f7f9ca337c9a --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseBinaryBox.lean @@ -0,0 +1,145 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseCellBounds + +namespace OAI + +namespace EditApproximation +namespace BinaryFraction + +/-- A zero marker or one full shift array on the execution's common grid. -/ +def CoarseBinaryBox (two : BinaryFraction) (n V D A : ℕ) (array : CoarseBinaryArray) : Prop := + ∀ cells, array = some cells → cells.length = n ∧ ∀ a ∈ cells, CoarseGridCell two a V D A + + theorem coarseBinaryBox_none (two : BinaryFraction) (n V D A : ℕ) : + CoarseBinaryBox two n V D A none := by + intro cells h; cases h + + theorem coarseBinaryBox_mono (two : BinaryFraction) (n V W D A : ℕ) + (array : CoarseBinaryArray) (h : CoarseBinaryBox two n V D A array) (hle : V ≤ W) : + CoarseBinaryBox two n W D A array := by + intro cells hc + exact ⟨(h cells hc).1, fun a ha => coarseGridCell_mono two a V W D A ((h cells hc).2 a ha) hle⟩ + + theorem coarseGridZipAddWithWork_bounds (two : BinaryFraction) (left right : List BinaryFraction) + (V W D A : ℕ) (hl : ∀ a ∈ left, CoarseGridCell two a V D A) + (hr : ∀ a ∈ right, CoarseGridCell two a W D A) + (hbound : Nat.size (V + W) + 2 * D + 1 ≤ A) : + ∀ a ∈ (coarseGridZipAddWithWork left right).1, CoarseGridCell two a (V + W) D A := by + induction left generalizing right with + | nil => simp only [coarseGridZipAddWithWork, List.not_mem_nil, false_implies, implies_true] + | cons a left ih => + cases right with + | nil => simp only [coarseGridZipAddWithWork, List.not_mem_nil, false_implies, implies_true] + | cons b right => + intro z hz + change z ∈ (coarseGridAddWithWork a b).1 :: _ at hz + rcases List.mem_cons.mp hz with rfl | hz + · exact coarseGridAddWithWork_bounds two a b V W D A (hl a List.mem_cons_self) + (hr b List.mem_cons_self) hbound + · exact ih right (fun a ha => hl a (List.mem_cons_of_mem _ ha)) + (fun b hb => hr b (List.mem_cons_of_mem _ hb)) z hz + + theorem coarseGridZipAddWithWork_length (left right : List BinaryFraction) : + (coarseGridZipAddWithWork left right).1.length = min left.length right.length := by + induction left generalizing right with + | nil => simp only [coarseGridZipAddWithWork, List.length_nil, Nat.zero_min] + | cons a left ih => + cases right with + | nil => simp only [coarseGridZipAddWithWork, List.length_nil, Nat.min_zero] + | cons b right => + change _ + 1 = min _ _ + rw [ih] + simp only [List.length_cons] + omega + + theorem coarseBinaryAddWithWork_box (two : BinaryFraction) (n V W D A : ℕ) + (left right : CoarseBinaryArray) (hl : CoarseBinaryBox two n V D A left) + (hr : CoarseBinaryBox two n W D A right) + (hbound : Nat.size (V + W) + 2 * D + 1 ≤ A) : + CoarseBinaryBox two n (V + W) D A (coarseBinaryAddWithWork left right).1 := by + cases left with + | none => exact coarseBinaryBox_mono two n W (V + W) D A right hr (by omega) + | some left => + cases right with + | none => exact coarseBinaryBox_mono two n V (V + W) D A (some left) hl (by omega) + | some right => + intro cells hc + have heq : (coarseGridZipAddWithWork left right).1 = cells := Option.some.inj hc + rw [← heq] + refine ⟨?_, coarseGridZipAddWithWork_bounds two left right V W D A + (hl left rfl).2 (hr right rfl).2 hbound⟩ + rw [coarseGridZipAddWithWork_length, (hl left rfl).1, (hr right rfl).1, min_self] + + theorem coarseBinaryAddWithWork_cost (two : BinaryFraction) (n V W D A : ℕ) + (left right : CoarseBinaryArray) (hl : CoarseBinaryBox two n V D A left) + (hr : CoarseBinaryBox two n W D A right) : + (coarseBinaryAddWithWork left right).2 ≤ n * (100 * (A + 1) + 3) := by + cases left with + | none => change 0 ≤ _; omega + | some left => + cases right with + | none => change 0 ≤ _; omega + | some right => + have h := coarseGridZipAddWithWork_cost left right A + (fun a ha => ((hl left rfl).2 a ha).2.2.2.2) + (fun b hb => ((hr right rfl).2 b hb).2.2.2.2) + simpa only [coarseBinaryAddWithWork, (hl left rfl).1, (hr right rfl).1, min_self] using h + + theorem coarseBinaryPenaltyWithWork_box (two : BinaryFraction) (n V D A : ℕ) + (array : CoarseBinaryArray) (h : CoarseBinaryBox two n V D A array) + (htwo : two.value = 2) (htw : two.width ≤ A) + (hbound : Nat.size (V + 2) + 2 * D + 1 ≤ A) : + CoarseBinaryBox two n V D A (coarseBinaryPenaltyWithWork two array).1 := by + cases array with + | none => exact coarseBinaryBox_none two n V D A + | some source => + intro cells hc + have heq : (coarseGridPenaltyWithWork two source).1 = cells := Option.some.inj hc + rw [← heq] + refine ⟨?_, coarseGridPenaltyWithWork_bounds two source V D A htwo htw hbound (h source rfl).2⟩ + have hv := congrArg List.length (coarseGridPenaltyWithWork_value two source htwo + (fun a ha => ((h source rfl).2 a ha).1)) + simpa only [List.length_map, coarsePenaltyTransform_length, (h source rfl).1] using hv + + theorem coarseBinaryPenaltyWithWork_cost (two : BinaryFraction) (n V D A : ℕ) + (array : CoarseBinaryArray) (h : CoarseBinaryBox two n V D A array) + (htwo : two.value = 2) (htw : two.width ≤ A) + (hbound : Nat.size (V + 2) + 2 * D + 1 ≤ A) : + (coarseBinaryPenaltyWithWork two array).2 ≤ n * (3500 * (A + 1) ^ 2 + 20) := by + cases array with + | none => change 0 ≤ _; omega + | some source => + have hc := coarseGridPenaltyWithWork_cost two source V D A htwo htw hbound (h source rfl).2 + simpa only [coarseBinaryPenaltyWithWork, (h source rfl).1] using hc + + theorem coarseBinaryMapWithWork_box (two : BinaryFraction) (n V W D A : ℕ) + (f : BinaryFraction → BinaryFraction × ℕ) (array : CoarseBinaryArray) + (h : CoarseBinaryBox two n V D A array) + (hf : ∀ a, CoarseGridCell two a V D A → CoarseGridCell two (f a).1 W D A) : + CoarseBinaryBox two n W D A (coarseBinaryMapWithWork f array).1 := by + cases array with + | none => exact coarseBinaryBox_none two n W D A + | some source => + intro cells hc + have heq : (arithmeticMapWithWork f source).1 = cells := Option.some.inj hc + rw [← heq, arithmeticMapWithWork_value] + refine ⟨?_, ?_⟩ + · simpa only [List.length_map] using (h source rfl).1 + · intro a ha + obtain ⟨b, hb, rfl⟩ := List.mem_map.mp ha + exact hf b ((h source rfl).2 b hb) + + theorem coarseBinaryMapWithWork_cost (two : BinaryFraction) (n V D A C : ℕ) + (f : BinaryFraction → BinaryFraction × ℕ) (array : CoarseBinaryArray) + (h : CoarseBinaryBox two n V D A array) + (hf : ∀ a, CoarseGridCell two a V D A → (f a).2 ≤ C) : + (coarseBinaryMapWithWork f array).2 ≤ n * (C + 3) := by + cases array with + | none => change 0 ≤ _; omega + | some source => + have hc := arithmeticMapWithWork_cost f source C (fun a ha => hf a ((h source rfl).2 a ha)) + simpa only [coarseBinaryMapWithWork, (h source rfl).1] using hc + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseBinaryCorrectness.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseBinaryCorrectness.lean new file mode 100644 index 0000000000000000000000000000000000000000..f6c85af6944dea70a5f7342731ec3055f97383ae --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseBinaryCorrectness.lean @@ -0,0 +1,86 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseChildrenSimulation + +namespace OAI + +namespace EditApproximation +namespace BinaryFraction + +/-- Every binary array cell equals the rational shared evaluator, including +all pruning outcomes. The sole invariant is the explicitly constructed root +denominator and the literal path's allowance denominator. -/ + theorem coarseBinaryEval_rep {B d : ℕ} {α : Type*} [DecidableEq α] + (k q L D : ℕ) (frame : List (Option α)) (two : BinaryFraction) + (tree : CoarseSourceTree B α d) (draws : CoarseThresholdDraws B d) + (hB : 0 < B) (hq : 0 < q) (hL : 0 < L) (htwo : two.value = 2) + (hroot : two.representation.den = coarseCommonDenominator 1 q L B D) + (j : ℕ) (hdepth : j + d = D) (allowance : BinaryFraction) (start : ℕ) + (ha : allowance.representation.den = two.representation.den) + (hpath : allowance.value.den ∣ (L * B * q) ^ j) : + CoarseArrayRep (coarseBinaryEval k q L frame two tree draws allowance start).1 + (coarseArrayEval k q (1 / L) frame tree draws allowance.value start).1 := by + induction tree generalizing j allowance start with + | leaf letter => + have hp := leWithWork_value (nat (CoarseSourceTree.leaf (B := B) letter).word.length) allowance + rw [nat_value] at hp + rw [coarseBinaryEval, coarseArrayEval] + by_cases hprune : ((CoarseSourceTree.leaf (B := B) letter).word.length : ℚ) ≤ allowance.value + · rw [ite_eq_left (hp.mpr hprune), ite_eq_left hprune] + rfl + · have hb : ¬ (leWithWork (nat (CoarseSourceTree.leaf (B := B) letter).word.length) allowance).1 = true := + fun h => hprune (hp.mp h) + rw [ite_eq_right hb, ite_eq_right hprune] + simp only [CoarseArrayRep, coarseBinaryContents, coarseRationalContents, Option.map_some, + arithmeticMapWithWork_value, List.map_map, Function.comp_def, + coarseGridNatWithWork_value, coarseStoredOfFn, List.ofFn_eq_map] + | @branch d children ih => + obtain ⟨draws, below⟩ := draws + have hp := leWithWork_value (nat (CoarseSourceTree.branch children).word.length) allowance + rw [nat_value] at hp + rw [coarseBinaryEval, coarseArrayEval] + by_cases hprune : ((CoarseSourceTree.branch children).word.length : ℚ) ≤ allowance.value + · rw [ite_eq_left (hp.mpr hprune), ite_eq_left hprune] + rfl + · have hb : ¬ (leWithWork (nat (CoarseSourceTree.branch children).word.length) allowance).1 = true := + fun h => hprune (hp.mp h) + rw [ite_eq_right hb, ite_eq_right hprune] + have ht (draw : Fin B) : (coarseChildThresholdWithWork B q allowance draw).1.value = + coarseChildThreshold B q allowance.value draw := by + apply coarseChildThresholdWithWork_value + rw [ha, hroot, ← hdepth] + exact coarseThreshold_root_grid B q L j d allowance.value draw hB hq hpath + have hs : (coarseChildAllowanceWithWork q allowance).1.value = allowance.value / q := by + apply coarseChildAllowanceWithWork_value + rw [ha, hroot, ← hdepth] + exact coarseScale_root_grid B q L j (d + 1) allowance.value hq hpath + apply coarseBinaryChildren_rep k q L frame two allowance _ htwo ha ht hs + intro child draw childBelow hmem s + obtain ⟨i, hi⟩ := List.mem_ofFn.mp hmem + cases hi + let threshold := coarseChildThresholdWithWork B q allowance (draws i) + let childAllowance := coarseChildAllowanceWithWork L threshold.1 + have htd : threshold.1.representation.den = two.representation.den := + (coarseChildThresholdWithWork_den B q allowance (draws i)).trans ha + have had : childAllowance.1.representation.den = two.representation.den := + (coarseChildAllowanceWithWork_den L threshold.1).trans htd + have hav : childAllowance.1.value = (1 / (L : ℚ)) * + coarseChildThreshold B q allowance.value (draws i) := by + have hg : (threshold.1.value / L).den ∣ threshold.1.representation.den := by + rw [ht (draws i), htd, hroot, ← hdepth] + rw [show coarseChildThreshold B q allowance.value (draws i) / (L : ℚ) = + (1 / (L : ℚ)) * coarseChildThreshold B q allowance.value (draws i) by ring] + exact coarseChildAllowance_root_grid B q L j d allowance.value (draws i) hB hq hL hpath + have hv := coarseChildAllowanceWithWork_value L threshold.1 hg + change childAllowance.1.value = _ at hv ⊢ + rw [hv, ht (draws i)] + ring + have hap : childAllowance.1.value.den ∣ (L * B * q) ^ (j + 1) := by + rw [hav] + exact coarseChildAllowance_grid B q L j allowance.value (draws i) hB hq hL hpath + have hrec := ih i (below i) (j + 1) (by omega) childAllowance.1 s had hap + rw [hav] at hrec + exact hrec + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseBinaryEvaluation.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseBinaryEvaluation.lean new file mode 100644 index 0000000000000000000000000000000000000000..f3b9c65345ce061f8b7de57b49c6dd796a608263 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseBinaryEvaluation.lean @@ -0,0 +1,54 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseArrayRepresentation +import OAI.Combinatorics.EditApproximation.Coarse.CoarseThresholdStep +import OAI.Combinatorics.EditApproximation.Coarse.CoarseGridTransfers + +namespace OAI + +namespace EditApproximation +namespace BinaryFraction + +/-- Shared evaluation of each child, followed by its exact two-pass +penalty transform, threshold contribution and fixed-grid addition. -/ +def coarseBinaryChildren {B d : ℕ} {α : Type*} (k q L : ℕ) (two : BinaryFraction) + (evaluate : CoarseSourceTree B α d → CoarseThresholdDraws B d → BinaryFraction → ℕ → + CoarseBinaryArray × ℕ) (allowance : BinaryFraction) : + List (CoarseSourceTree B α d × Fin B × CoarseThresholdDraws B d) → ℕ → CoarseBinaryArray × ℕ + | [], _ => (none, 0) + | (child, draw, below) :: rest, start => + let threshold := coarseChildThresholdWithWork B q allowance draw + let childAllowance := coarseChildAllowanceWithWork L threshold.1 + let evaluated := evaluate child below childAllowance.1 start + let penalty := coarseBinaryPenaltyWithWork two evaluated.1 + let scale := coarseChildAllowanceWithWork q allowance + let contribution := coarseBinaryMapWithWork (coarseContributionWithWork threshold.1 scale.1) penalty.1 + let remainder := coarseBinaryChildren k q L two evaluate allowance rest (start + child.word.length) + let total := coarseBinaryAddWithWork contribution.1 remainder.1 + (total.1, threshold.2 + childAllowance.2 + evaluated.2 + penalty.2 + scale.2 + contribution.2 + + remainder.2 + total.2 + Nat.size start + Nat.size child.word.length + 9) + +/-- Binary implementation of the pruning-stopped shared-array evaluator. +The complete tree is a semantic indexed source; visited child descriptors +carry their source offset and length, charged in `coarseBinaryChildren`. -/ +def coarseBinaryEval {B : ℕ} {α : Type*} [DecidableEq α] + (k q L : ℕ) (frame : List (Option α)) (two : BinaryFraction) : + {d : ℕ} → CoarseSourceTree B α d → CoarseThresholdDraws B d → BinaryFraction → ℕ → + CoarseBinaryArray × ℕ + | _, tree, draws, allowance, start => + let prune := leWithWork (nat tree.word.length) allowance + if prune.1 then (none, prune.2 + Nat.size tree.word.length + 1) else + match tree, draws with + | .leaf letter, _ => + let cells := arithmeticMapWithWork (fun shift : Fin (2 * k + 1) => + coarseGridNatWithWork allowance.denominator allowance.denominator_pos + (coarseShiftCost k frame (.leaf (B := B) letter) start shift)) (List.finRange (2 * k + 1)) + (some cells.1, prune.2 + cells.2 + Nat.size tree.word.length + 3 * (2 * k + 1) + 1) + | .branch children, (draws, below) => + let result := coarseBinaryChildren k q L two + (fun child => coarseBinaryEval k q L frame two child) allowance + (List.ofFn fun i => (children i, draws i, below i)) start + (result.1, result.2 + prune.2 + Nat.size tree.word.length + B + 1) + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseBinaryGrid.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseBinaryGrid.lean new file mode 100644 index 0000000000000000000000000000000000000000..b8933fd2874d4301b00602573bdc72524f546024 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseBinaryGrid.lean @@ -0,0 +1,76 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseBinaryEvaluation +import OAI.Combinatorics.EditApproximation.Coarse.CoarseArraySimulation + +namespace OAI + +namespace EditApproximation +namespace BinaryFraction + + theorem coarseBinaryChildren_grid {B d : ℕ} {α : Type*} (k q L : ℕ) (two : BinaryFraction) + (evaluate : CoarseSourceTree B α d → CoarseThresholdDraws B d → BinaryFraction → ℕ → + CoarseBinaryArray × ℕ) (allowance : BinaryFraction) + (children : List (CoarseSourceTree B α d × Fin B × CoarseThresholdDraws B d)) (start : ℕ) + (ha : allowance.representation.den = two.representation.den) + (he : ∀ child draw below, (child, draw, below) ∈ children → ∀ (a : BinaryFraction) (s : ℕ), + a.representation.den = two.representation.den → CoarseArrayOnGrid two.representation.den + (evaluate child below a s).1) : + CoarseArrayOnGrid two.representation.den + (coarseBinaryChildren k q L two evaluate allowance children start).1 := by + induction children generalizing start with + | nil => intro values hv; cases hv + | cons data rest ih => + obtain ⟨child, draw, below⟩ := data + have ht := (coarseChildThresholdWithWork_den B q allowance draw).trans ha + have hc := (coarseChildAllowanceWithWork_den L (coarseChildThresholdWithWork B q allowance draw).1).trans ht + have hev := he child draw below List.mem_cons_self + (coarseChildAllowanceWithWork L (coarseChildThresholdWithWork B q allowance draw).1).1 start hc + have hp := coarseBinaryPenalty_grid two _ hev + have hs := (coarseChildAllowanceWithWork_den q allowance).trans ha + have hm := coarseBinaryMap_grid + (coarseContributionWithWork (coarseChildThresholdWithWork B q allowance draw).1 + (coarseChildAllowanceWithWork q allowance).1) + (coarseBinaryPenaltyWithWork two + (evaluate child below (coarseChildAllowanceWithWork L + (coarseChildThresholdWithWork B q allowance draw).1).1 start).1).1 + two.representation.den hp (by + intro z hz + exact (coarseContributionWithWork_den _ _ z (hs.trans hz.symm)).trans hz) + have hr := ih (start + child.word.length) + (fun child draw below hmem => he child draw below (List.mem_cons_of_mem _ hmem)) + exact coarseBinaryAdd_grid _ _ _ hm hr + + theorem coarseBinaryEval_grid {B d : ℕ} {α : Type*} [DecidableEq α] + (k q L : ℕ) (frame : List (Option α)) (two : BinaryFraction) + (tree : CoarseSourceTree B α d) (draws : CoarseThresholdDraws B d) + (allowance : BinaryFraction) (start : ℕ) + (ha : allowance.representation.den = two.representation.den) : + CoarseArrayOnGrid two.representation.den + (coarseBinaryEval k q L frame two tree draws allowance start).1 := by + induction tree generalizing allowance start with + | leaf letter => + rw [coarseBinaryEval] + split_ifs + · intro values hv; cases hv + · intro values hv a hamem + have heq : (arithmeticMapWithWork (fun shift : Fin (2 * k + 1) => + coarseGridNatWithWork allowance.denominator allowance.denominator_pos + (coarseShiftCost k frame (.leaf (B := B) letter) start shift)) + (List.finRange (2 * k + 1))).1 = values := Option.some.inj hv + rw [← heq, arithmeticMapWithWork_value] at hamem + obtain ⟨shift, _, rfl⟩ := List.mem_map.mp hamem + exact (coarseGridNatWithWork_den _ _ _).trans ha + | branch children ih => + obtain ⟨draws, below⟩ := draws + rw [coarseBinaryEval] + split_ifs + · intro values hv; cases hv + · apply coarseBinaryChildren_grid k q L two _ allowance _ start ha + intro child draw childBelow hmem a s hag + obtain ⟨i, hi⟩ := List.mem_ofFn.mp hmem + cases hi + exact ih i (below i) a s hag + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseBinaryRead.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseBinaryRead.lean new file mode 100644 index 0000000000000000000000000000000000000000..8379d866dece3bdebc9ee837fee78737b60ea4e8 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseBinaryRead.lean @@ -0,0 +1,38 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseArraySimulation +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation +namespace BinaryFraction + +/-- Read one array cell; absent arrays represent exact zero. -/ + + + theorem coarseBinaryRead_value (array : CoarseBinaryArray) (i : ℕ) : + (coarseBinaryRead array i).value = ((coarseBinaryContents array).getD [])[i]?.getD 0 := by + cases array with + | none => simp only [coarseBinaryRead, nat_value, Nat.cast_zero, coarseBinaryContents, + Option.map_none, Option.getD_none, List.getElem?_nil] + | some cells => + simp only [coarseBinaryRead, coarseBinaryContents, Option.map_some, Option.getD_some, + List.getElem?_map] + cases cells[i]? <;> simp only [ Option.getD_none, Option.map_none, nat_value, + Nat.cast_zero, Option.getD_some, Option.map_some] + + theorem coarseBinaryRead_rep {n : ℕ} (array : CoarseBinaryArray) (spec : CoarseStoredArray n) + (h : CoarseArrayRep array spec) (i : Fin n) : + (coarseBinaryRead array i.val).value = coarseStoredRead spec i := by + rw [coarseBinaryRead_value, h] + cases spec with + | none => rfl + | some cells => + have hi : i.val < cells.1.length := by rw [cells.2]; exact i.isLt + simp only [coarseRationalContents, Option.map_some, Option.getD_some, List.getElem?_eq_getElem hi, + Option.getD_some, coarseStoredRead] + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseBinaryWeight.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseBinaryWeight.lean new file mode 100644 index 0000000000000000000000000000000000000000..b86d5b20cd46848b89ea9833e980ea989b7cab35 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseBinaryWeight.lean @@ -0,0 +1,56 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseBinaryEvaluation +import OAI.Combinatorics.EditApproximation.Coarse.CoarseLabelWork + +namespace OAI + +namespace EditApproximation +namespace BinaryFraction + +/-- Sum the weights of exactly those child calls made by the binary loop. -/ +def coarseBinaryChildrenWeight {B d : ℕ} {α : Type*} (q L : ℕ) + (weight : CoarseSourceTree B α d → CoarseThresholdDraws B d → BinaryFraction → ℕ) + (allowance : BinaryFraction) : + List (CoarseSourceTree B α d × Fin B × CoarseThresholdDraws B d) → ℕ + | [] => 0 + | (child, draw, below) :: rest => + weight child below (coarseChildAllowanceWithWork L + (coarseChildThresholdWithWork B q allowance draw).1).1 + + coarseBinaryChildrenWeight q L weight allowance rest + +/-- One array unit per expanded child shift and one unit per visited node. +This counter follows the executed pruning and threshold branches. -/ +def coarseBinaryWeight {B : ℕ} {α : Type*} (k q L : ℕ) : + {d : ℕ} → CoarseSourceTree B α d → CoarseThresholdDraws B d → BinaryFraction → ℕ + | _, tree, draws, allowance => + if (leWithWork (nat tree.word.length) allowance).1 then 1 else + match tree, draws with + | .leaf _, _ => B * (2 * k + 1) + 1 + | .branch children, (draws, below) => B * (2 * k + 1) + 1 + + coarseBinaryChildrenWeight q L (fun child => coarseBinaryWeight k q L child) allowance + (List.ofFn fun i => (children i, draws i, below i)) + +def coarseChildrenSpan {B d : ℕ} {α : Type*} : + List (CoarseSourceTree B α d × Fin B × CoarseThresholdDraws B d) → ℕ + | [] => 0 + | (child, _, _) :: rest => child.word.length + coarseChildrenSpan rest + + theorem coarseChildrenSpan_eq {B d : ℕ} {α : Type*} + (children : List (CoarseSourceTree B α d × Fin B × CoarseThresholdDraws B d)) : + coarseChildrenSpan children = (children.map (fun data => data.1.word)).flatten.length := by + induction children with + | nil => rfl + | cons data rest ih => + simp only [coarseChildrenSpan, List.map_cons, List.flatten_cons, List.length_append, ih] + + theorem coarseChildrenSpan_ofFn {B d : ℕ} {α : Type*} + (children : Fin B → CoarseSourceTree B α d) (draws : Fin B → Fin B) + (below : Fin B → CoarseThresholdDraws B d) : + coarseChildrenSpan (List.ofFn fun i => (children i, draws i, below i)) = + (CoarseSourceTree.branch children).word.length := by + rw [coarseChildrenSpan_eq] + simp only [List.map_ofFn, Function.comp_def, CoarseSourceTree.word] + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseBitParameters.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseBitParameters.lean new file mode 100644 index 0000000000000000000000000000000000000000..241b945e44cf367fc2f0334e5f7ef6a50a8c86a1 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseBitParameters.lean @@ -0,0 +1,41 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseLevelMagnitude + +namespace OAI + +namespace EditApproximation +namespace BinaryFraction + + theorem coarseBitParameters_grid (H N k B q L d : ℕ) + (hH : 100 ≤ H) (hd : d ≤ H) + (hN : Nat.size N ≤ 2 * H) (hk : Nat.size k ≤ 2 * H) + (hB : Nat.size B ≤ 2 * H) (hq : Nat.size q ≤ 2 * H) (hL : Nat.size L ≤ 2 * H) : + Nat.size (coarseCommonDenominator 1 q L B d) ≤ 10 * H ^ 2 ∧ + Nat.size (coarseLevelMagnitude N k B d + 2) + 2 * (10 * H ^ 2) + 1 ≤ H ^ 3 := by + have hsum : Nat.size L + Nat.size B + Nat.size q ≤ 6 * H := by omega + have hcoeff := Nat.mul_le_mul hd hsum + have hden := coarseCommonDenominator_bits 1 q L B d + rw [Nat.size_one] at hden + have hbaseprod := natural_product_bit_length 2 B + have hbasesum := natural_sum_bit_length (2 * B) 2 + rw [show Nat.size 2 = 2 by decide] at hbaseprod hbasesum + have hbase : Nat.size (2 * B + 2) ≤ 2 * H + 5 := by omega + have hsumNk := natural_sum_bit_length N k + have hsumone := natural_sum_bit_length (N + k) 1 + rw [Nat.size_one] at hsumone + have hnk : Nat.size (N + k + 1) ≤ 4 * H + 3 := by omega + have hmag := coarseLevelMagnitude_bits N k B d + have hmag2 := natural_sum_bit_length (coarseLevelMagnitude N k B d) 2 + rw [show Nat.size 2 = 2 by decide] at hmag2 + have hprod := Nat.mul_le_mul (show d + 1 ≤ H + 1 by omega) hbase + have hsq : H ≤ H ^ 2 := Nat.le_pow (by decide) + have hcube : 100 * H ^ 2 ≤ H ^ 3 := by + have hh := Nat.mul_le_mul_right (H ^ 2) hH + nlinarith only [hh] + constructor + · nlinarith only [hden, hq, hcoeff, hH, hsq] + · nlinarith only [hmag, hmag2, hnk, hprod, hsq, hcube, hH] + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseCellBounds.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseCellBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..68b0f4b8a08bc07861e28b8d319c6465c6c1b031 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseCellBounds.lean @@ -0,0 +1,98 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseCompactCells + +namespace OAI + +namespace EditApproximation +namespace BinaryFraction + + theorem coarseGridNatWithWork_bounds (two : BinaryFraction) (den : List Bool) + (hden : 0 < bitWordValue den) (n V D A : ℕ) + (hd : bitWordValue den = two.representation.den) (hdl : den.length ≤ D) + (hn : n ≤ V) (hb : Nat.size V + 2 * D + 1 ≤ A) : + CoarseGridCell two (coarseGridNatWithWork den hden n).1 V D A := by + have hv := coarseGridNatWithWork_value den hden n + have hrd := (coarseGridNatWithWork_den den hden n).trans hd + have hdl' : (coarseGridNatWithWork den hden n).1.denominator.length ≤ D := by + change (trimBitWordWithWork den).1.length ≤ D + rw [trimBitWordWithWork_length] + exact (Nat.size_le.mpr (bitWordValue_lt_pow_length den)).trans hdl + refine ⟨hrd, hdl', ?_, ?_, ?_⟩ + · rw [hv]; positivity + · rw [hv]; exact_mod_cast hn + · apply (coarseCompact_width _ V D (coarseCompact_gridNat den hden n) ?_ ?_).trans hb + · rw [hv, abs_of_nonneg (by positivity : (0 : ℚ) ≤ n)]; exact_mod_cast hn + · rw [coarseGridNatWithWork_den] + exact (Nat.size_le.mpr (bitWordValue_lt_pow_length den)).trans hdl + + theorem coarseGridAddWithWork_bounds (two a b : BinaryFraction) (V W D A : ℕ) + (ha : CoarseGridCell two a V D A) (hb : CoarseGridCell two b W D A) + (hbound : Nat.size (V + W) + 2 * D + 1 ≤ A) : + CoarseGridCell two (coarseGridAddWithWork a b).1 (V + W) D A := by + have hd : a.representation.den = b.representation.den := ha.1.trans hb.1.symm + have hv := coarseGridAddWithWork_value a b hd + have hnonneg : 0 ≤ a.value + b.value := add_nonneg ha.2.2.1 hb.2.2.1 + have hvalue : a.value + b.value ≤ ((V + W : ℕ) : ℚ) := by + push_cast; exact add_le_add ha.2.2.2.1 hb.2.2.2.1 + refine ⟨(coarseGridAddWithWork_den a b).trans ha.1, ?_, ?_, ?_, ?_⟩ + · change (trimBitWordWithWork a.denominator).1.length ≤ D + rw [trimBitWordWithWork_length] + exact (Nat.size_le.mpr (bitWordValue_lt_pow_length a.denominator)).trans ha.2.1 + · rw [hv]; exact hnonneg + · rw [hv]; exact hvalue + · exact (coarseGridAddWithWork_width a b (V + W) D hd + (by rw [abs_of_nonneg hnonneg]; exact hvalue) ha.2.1).trans hbound + + theorem coarseGridCell_mono (two a : BinaryFraction) (V W D A : ℕ) + (h : CoarseGridCell two a V D A) (hle : V ≤ W) : CoarseGridCell two a W D A := by + exact ⟨h.1, h.2.1, h.2.2.1, h.2.2.2.1.trans (by exact_mod_cast hle), h.2.2.2.2⟩ + + theorem coarseGridZipMinimum_property (P : BinaryFraction → Prop) + (left right : List BinaryFraction) (hl : ∀ a ∈ left, P a) (hr : ∀ a ∈ right, P a) : + ∀ a ∈ (coarseGridZipMinimumWithWork left right).1, P a := by + induction left generalizing right with + | nil => simp only [coarseGridZipMinimumWithWork, List.not_mem_nil, false_implies, implies_true] + | cons a left ih => + cases right with + | nil => simp only [coarseGridZipMinimumWithWork, List.not_mem_nil, false_implies, implies_true] + | cons b right => + intro z hz + change z ∈ (minWithWork a b).1 :: _ at hz + rcases List.mem_cons.mp hz with rfl | hz + · unfold minWithWork + dsimp only + split_ifs + · exact hl a List.mem_cons_self + · exact hr b List.mem_cons_self + · exact ih right (fun a ha => hl a (List.mem_cons_of_mem _ ha)) + (fun b hb => hr b (List.mem_cons_of_mem _ hb)) z hz + + theorem coarseGridPenaltyWithWork_bounds (two : BinaryFraction) (source : List BinaryFraction) + (V D A : ℕ) (htwo : two.value = 2) (htw : two.width ≤ A) + (hbound : Nat.size (V + 2) + 2 * D + 1 ≤ A) + (hs : ∀ a ∈ source, CoarseGridCell two a V D A) : + ∀ a ∈ (coarseGridPenaltyWithWork two source).1, CoarseGridCell two a V D A := by + have hl := (coarseGridLeftWithWork_bounds two source V D A htwo htw hbound hs).1 + have hr := (coarseGridLeftWithWork_bounds two source.reverse V D A htwo htw hbound + (fun a ha => hs a (List.mem_reverse.mp ha))).1 + exact coarseGridZipMinimum_property _ _ _ hl + (fun a ha => hr a (List.mem_reverse.mp ha)) + + theorem coarseContributionWithWork_bounds (two threshold scale a : BinaryFraction) (V W D A : ℕ) + (ha : CoarseGridCell two a V D A) (hs : CoarseGridCell two scale W D A) + (hbound : Nat.size (V + W) + 2 * D + 1 ≤ A) : + CoarseGridCell two (coarseContributionWithWork threshold scale a).1 (V + W) D A := by + unfold coarseContributionWithWork + dsimp only + split_ifs + · unfold maxWithWork + dsimp only + split_ifs + · exact coarseGridCell_mono two scale W (V + W) D A hs (by omega) + · exact coarseGridCell_mono two a V (V + W) D A ha (by omega) + · exact coarseGridNatWithWork_bounds two a.denominator a.denominator_pos 0 (V + W) D A + ha.1 ha.2.1 (by omega) hbound + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseChildAllocation.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseChildAllocation.lean new file mode 100644 index 0000000000000000000000000000000000000000..431e14672452d637582f89ce5f5ad6a83e90e54f --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseChildAllocation.lean @@ -0,0 +1,95 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseArrayAllocation +import OAI.Combinatorics.EditApproximation.Coarse.CoarseIndexedChildren + +namespace OAI + +namespace EditApproximation +namespace BinaryFraction + +/-- Allocation follows the same child sequence, thresholds, recursive calls, +penalty sweeps and accumulated array as the indexed evaluator. -/ +def coarseIndexChildrenAllocation {B : ℕ} (q L : ℕ) (two : BinaryFraction) + (width : Fin B → ℕ) + (evaluate : Fin B → BinaryFraction → ℕ → CoarseBinaryArray × ℕ) + (allocation : Fin B → BinaryFraction → ℕ → ℕ) + (draw : Fin B → Fin B) (allowance : BinaryFraction) : List (Fin B) → ℕ → ℕ + | [], _ => 0 + | i :: rest, start => + let threshold := coarseChildThresholdWithWork B q allowance (draw i) + let childAllowance := coarseChildAllowanceWithWork L threshold.1 + let evaluated := evaluate i childAllowance.1 start + let penalty := coarseBinaryPenaltyWithWork two evaluated.1 + let scale := coarseChildAllowanceWithWork q allowance + let contribution := coarseBinaryMapWithWork (coarseContributionWithWork threshold.1 scale.1) penalty.1 + let remainder := coarseIndexChildren 0 q L two width evaluate draw allowance rest (start + width i) + coarseChildThresholdAllocation B q allowance (draw i) + + coarseChildAllowanceAllocation L threshold.1 + allocation i childAllowance.1 start + + coarseBinaryPenaltyAllocation two evaluated.1 + coarseChildAllowanceAllocation q allowance + + coarseBinaryMapAllocation (coarseContributionAllocation threshold.1 scale.1) penalty.1 + + coarseIndexChildrenAllocation q L two width evaluate allocation draw allowance rest (start + width i) + + coarseBinaryAddAllocation contribution.1 remainder.1 + +/-- The loop's first argument does not contribute to its runtime allocation. -/ +private theorem coarseIndexChildren_unused_k {B : ℕ} (k q L : ℕ) (two : BinaryFraction) + (width : Fin B → ℕ) (evaluate : Fin B → BinaryFraction → ℕ → CoarseBinaryArray × ℕ) + (draw : Fin B → Fin B) (allowance : BinaryFraction) (indices : List (Fin B)) (start : ℕ) : + coarseIndexChildren k q L two width evaluate draw allowance indices start = + coarseIndexChildren 0 q L two width evaluate draw allowance indices start := by + induction indices generalizing start with + | nil => rfl + | cons i rest ih => simp only [coarseIndexChildren, ih] + +theorem coarseIndexChildrenAllocation_le_work {B : ℕ} (k q L : ℕ) (two : BinaryFraction) + (width : Fin B → ℕ) + (evaluate : Fin B → BinaryFraction → ℕ → CoarseBinaryArray × ℕ) + (allocation : Fin B → BinaryFraction → ℕ → ℕ) + (hallocation : ∀ i a start, allocation i a start ≤ 2 * (evaluate i a start).2) + (draw : Fin B → Fin B) (allowance : BinaryFraction) (indices : List (Fin B)) (start : ℕ) : + coarseIndexChildrenAllocation q L two width evaluate allocation draw allowance indices start ≤ + 2 * (coarseIndexChildren k q L two width evaluate draw allowance indices start).2 := by + rw [coarseIndexChildren_unused_k] + induction indices generalizing start with + | nil => exact Nat.le_refl 0 + | cons i rest ih => + let threshold := coarseChildThresholdWithWork B q allowance (draw i) + let childAllowance := coarseChildAllowanceWithWork L threshold.1 + let evaluated := evaluate i childAllowance.1 start + let penalty := coarseBinaryPenaltyWithWork two evaluated.1 + let scale := coarseChildAllowanceWithWork q allowance + let contribution := coarseBinaryMapWithWork (coarseContributionWithWork threshold.1 scale.1) penalty.1 + let remainder := coarseIndexChildren 0 q L two width evaluate draw allowance rest (start + width i) + have ht := coarseChildThresholdAllocation_le_work B q allowance (draw i) + have ha := coarseChildAllowanceAllocation_le_work L threshold.1 + have he := hallocation i childAllowance.1 start + have hp := coarseBinaryPenaltyAllocation_le_work two evaluated.1 + have hs := coarseChildAllowanceAllocation_le_work q allowance + have hm := coarseBinaryMapAllocation_le_work + (coarseContributionWithWork threshold.1 scale.1) + (coarseContributionAllocation threshold.1 scale.1) + (coarseContributionAllocation_le_work threshold.1 scale.1) penalty.1 + have hr := ih (start + width i) + have had := coarseBinaryAddAllocation_le_work contribution.1 remainder.1 + change coarseChildThresholdAllocation B q allowance (draw i) + + coarseChildAllowanceAllocation L threshold.1 + allocation i childAllowance.1 start + + coarseBinaryPenaltyAllocation two evaluated.1 + coarseChildAllowanceAllocation q allowance + + coarseBinaryMapAllocation (coarseContributionAllocation threshold.1 scale.1) penalty.1 + + coarseIndexChildrenAllocation q L two width evaluate allocation draw allowance rest (start + width i) + + coarseBinaryAddAllocation contribution.1 remainder.1 ≤ + 2 * (threshold.2 + childAllowance.2 + evaluated.2 + penalty.2 + scale.2 + contribution.2 + + remainder.2 + (coarseBinaryAddWithWork contribution.1 remainder.1).2 + + Nat.size start + Nat.size (width i) + 9) + change coarseChildThresholdAllocation B q allowance (draw i) ≤ threshold.2 at ht + change coarseChildAllowanceAllocation L threshold.1 ≤ childAllowance.2 at ha + change allocation i childAllowance.1 start ≤ 2 * evaluated.2 at he + change coarseBinaryPenaltyAllocation two evaluated.1 ≤ 2 * penalty.2 at hp + change coarseChildAllowanceAllocation q allowance ≤ scale.2 at hs + change coarseBinaryMapAllocation (coarseContributionAllocation threshold.1 scale.1) penalty.1 ≤ + contribution.2 at hm + change coarseIndexChildrenAllocation q L two width evaluate allocation draw allowance rest (start + width i) ≤ + 2 * remainder.2 at hr + omega + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseChildControlSpace.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseChildControlSpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..7f1f3108e2fc124f76d37ff57bdb19becbfd1f4b --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseChildControlSpace.lean @@ -0,0 +1,95 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseArrayControlSpace +import OAI.Combinatorics.EditApproximation.Coarse.CoarseIndexedChildren + +namespace OAI + +namespace EditApproximation +namespace BinaryFraction + +/-- Invocation count follows the same child sequence, thresholds, recursive calls, +penalty sweeps and accumulated array as the indexed evaluator. -/ +def coarseIndexChildrenInvocations {B : ℕ} (q L : ℕ) (two : BinaryFraction) + (width : Fin B → ℕ) + (evaluate : Fin B → BinaryFraction → ℕ → CoarseBinaryArray × ℕ) + (allocation : Fin B → BinaryFraction → ℕ → ℕ) + (draw : Fin B → Fin B) (allowance : BinaryFraction) : List (Fin B) → ℕ → ℕ + | [], _ => 1 + | i :: rest, start => + let threshold := coarseChildThresholdWithWork B q allowance (draw i) + let childAllowance := coarseChildAllowanceWithWork L threshold.1 + let evaluated := evaluate i childAllowance.1 start + let penalty := coarseBinaryPenaltyWithWork two evaluated.1 + let scale := coarseChildAllowanceWithWork q allowance + let contribution := coarseBinaryMapWithWork (coarseContributionWithWork threshold.1 scale.1) penalty.1 + let remainder := coarseIndexChildren 0 q L two width evaluate draw allowance rest (start + width i) + coarseChildThresholdInvocations B q allowance (draw i) + + coarseChildAllowanceInvocations L threshold.1 + allocation i childAllowance.1 start + + coarseBinaryPenaltyInvocations two evaluated.1 + coarseChildAllowanceInvocations q allowance + + coarseBinaryMapInvocations (coarseContributionInvocations threshold.1 scale.1) penalty.1 + + coarseIndexChildrenInvocations q L two width evaluate allocation draw allowance rest (start + width i) + + coarseBinaryAddInvocations contribution.1 remainder.1 + 1 + +/-- The loop's first argument does not contribute to its runtime control space. -/ +private theorem coarseIndexChildren_unused_k {B : ℕ} (k q L : ℕ) (two : BinaryFraction) + (width : Fin B → ℕ) (evaluate : Fin B → BinaryFraction → ℕ → CoarseBinaryArray × ℕ) + (draw : Fin B → Fin B) (allowance : BinaryFraction) (indices : List (Fin B)) (start : ℕ) : + coarseIndexChildren k q L two width evaluate draw allowance indices start = + coarseIndexChildren 0 q L two width evaluate draw allowance indices start := by + induction indices generalizing start with + | nil => rfl + | cons i rest ih => simp only [coarseIndexChildren, ih] + +theorem coarseIndexChildrenInvocations_le_work {B : ℕ} (k q L : ℕ) (two : BinaryFraction) + (width : Fin B → ℕ) + (evaluate : Fin B → BinaryFraction → ℕ → CoarseBinaryArray × ℕ) + (allocation : Fin B → BinaryFraction → ℕ → ℕ) + (hallocation : ∀ i a start, allocation i a start ≤ 2 * (evaluate i a start).2 + 1) + (draw : Fin B → Fin B) (allowance : BinaryFraction) (indices : List (Fin B)) (start : ℕ) : + coarseIndexChildrenInvocations q L two width evaluate allocation draw allowance indices start ≤ + 2 * (coarseIndexChildren k q L two width evaluate draw allowance indices start).2 + 1 := by + rw [coarseIndexChildren_unused_k] + induction indices generalizing start with + | nil => exact Nat.le_refl 1 + | cons i rest ih => + let threshold := coarseChildThresholdWithWork B q allowance (draw i) + let childAllowance := coarseChildAllowanceWithWork L threshold.1 + let evaluated := evaluate i childAllowance.1 start + let penalty := coarseBinaryPenaltyWithWork two evaluated.1 + let scale := coarseChildAllowanceWithWork q allowance + let contribution := coarseBinaryMapWithWork (coarseContributionWithWork threshold.1 scale.1) penalty.1 + let remainder := coarseIndexChildren 0 q L two width evaluate draw allowance rest (start + width i) + have ht := coarseChildThresholdInvocations_le_work B q allowance (draw i) + have ha := coarseChildAllowanceInvocations_le_work L threshold.1 + have he := hallocation i childAllowance.1 start + have hp := coarseBinaryPenaltyInvocations_le_work two evaluated.1 + have hs := coarseChildAllowanceInvocations_le_work q allowance + have hm := coarseBinaryMapInvocations_le_work + (coarseContributionWithWork threshold.1 scale.1) + (coarseContributionInvocations threshold.1 scale.1) + (coarseContributionInvocations_le_work threshold.1 scale.1) penalty.1 + have hr := ih (start + width i) + have had := coarseBinaryAddInvocations_le_work contribution.1 remainder.1 + change coarseChildThresholdInvocations B q allowance (draw i) + + coarseChildAllowanceInvocations L threshold.1 + allocation i childAllowance.1 start + + coarseBinaryPenaltyInvocations two evaluated.1 + coarseChildAllowanceInvocations q allowance + + coarseBinaryMapInvocations (coarseContributionInvocations threshold.1 scale.1) penalty.1 + + coarseIndexChildrenInvocations q L two width evaluate allocation draw allowance rest (start + width i) + + coarseBinaryAddInvocations contribution.1 remainder.1 + 1 ≤ + 2 * (threshold.2 + childAllowance.2 + evaluated.2 + penalty.2 + scale.2 + contribution.2 + + remainder.2 + (coarseBinaryAddWithWork contribution.1 remainder.1).2 + + Nat.size start + Nat.size (width i) + 9) + 1 + change coarseChildThresholdInvocations B q allowance (draw i) ≤ threshold.2 at ht + change coarseChildAllowanceInvocations L threshold.1 ≤ childAllowance.2 at ha + change allocation i childAllowance.1 start ≤ 2 * evaluated.2 + 1 at he + change coarseBinaryPenaltyInvocations two evaluated.1 ≤ 2 * penalty.2 + 9 at hp + change coarseChildAllowanceInvocations q allowance ≤ scale.2 at hs + change coarseBinaryMapInvocations (coarseContributionInvocations threshold.1 scale.1) penalty.1 ≤ + contribution.2 + 2 at hm + change coarseIndexChildrenInvocations q L two width evaluate allocation draw allowance rest (start + width i) ≤ + 2 * remainder.2 + 1 at hr + omega + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseChildrenBitWork.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseChildrenBitWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..ecd4ffc61873c379f6a8b208218db928d066f32c --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseChildrenBitWork.lean @@ -0,0 +1,111 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseBinaryBox +import OAI.Combinatorics.EditApproximation.Coarse.CoarseScalarBounds +import OAI.Combinatorics.EditApproximation.Coarse.CoarseBinaryWeight + +namespace OAI + +namespace EditApproximation +namespace BinaryFraction + + theorem coarseBinaryChildren_bounds {B d : ℕ} {α : Type*} (k q L N V D A : ℕ) + (two allowance : BinaryFraction) + (evaluate : CoarseSourceTree B α d → CoarseThresholdDraws B d → BinaryFraction → ℕ → + CoarseBinaryArray × ℕ) + (weight : CoarseSourceTree B α d → CoarseThresholdDraws B d → BinaryFraction → ℕ) + (children : List (CoarseSourceTree B α d × Fin B × CoarseThresholdDraws B d)) + (hB : 0 < B) (hlen : children.length ≤ B) (htwo : two.value = 2) (htw : two.width ≤ A) + (ha : allowance.width ≤ A) (hBbits : Nat.size B + 2 ≤ A) + (hqbits : Nat.size q + 2 ≤ A) (hLbits : Nat.size L + 2 ≤ A) + (hNbits : Nat.size N ≤ A) + (ht : ∀ draw : Fin B, (coarseChildThresholdWithWork B q allowance draw).1.width ≤ A) + (hs : CoarseGridCell two (coarseChildAllowanceWithWork q allowance).1 k D A) + (hbound : Nat.size (B * (V + k) + 2) + 2 * D + 1 ≤ A) + (he : ∀ child draw below, (child, draw, below) ∈ children → ∀ s, + s + child.word.length ≤ N → + CoarseBinaryBox two (2 * k + 1) V D A + (evaluate child below (coarseChildAllowanceWithWork L + (coarseChildThresholdWithWork B q allowance draw).1).1 s).1 ∧ + (evaluate child below (coarseChildAllowanceWithWork L + (coarseChildThresholdWithWork B q allowance draw).1).1 s).2 ≤ + (100000000 * (A + 1) ^ 2) * weight child below + (coarseChildAllowanceWithWork L (coarseChildThresholdWithWork B q allowance draw).1).1) + (start : ℕ) (hstart : start + coarseChildrenSpan children ≤ N) : + CoarseBinaryBox two (2 * k + 1) (children.length * (V + k)) D A + (coarseBinaryChildren k q L two evaluate allowance children start).1 ∧ + (coarseBinaryChildren k q L two evaluate allowance children start).2 + children.length ≤ + (100000000 * (A + 1) ^ 2) * + (coarseBinaryChildrenWeight q L weight allowance children + (2 * k + 1) * children.length) := by + have hvsmall : V + 2 ≤ B * (V + k) + 2 := by nlinarith + have hvbound : Nat.size (V + 2) + 2 * D + 1 ≤ A := + (Nat.add_le_add_right (Nat.add_le_add_right (Nat.size_le_size hvsmall) _) _).trans hbound + have hmapbound : Nat.size (V + k) + 2 * D + 1 ≤ A := + (Nat.add_le_add_right (Nat.add_le_add_right (Nat.size_le_size (by nlinarith : V + k ≤ B * (V + k) + 2)) _) _).trans hbound + induction children generalizing start with + | nil => + constructor + · exact coarseBinaryBox_none _ _ _ _ _ + · simp only [coarseBinaryChildren, coarseBinaryChildrenWeight, List.length_nil, mul_zero, add_zero, le_refl] + | cons data rest ih => + obtain ⟨child, draw, below⟩ := data + have hspan : start + (child.word.length + coarseChildrenSpan rest) ≤ N := hstart + have hchild := he child draw below List.mem_cons_self start (by omega) + have hrest := ih (by simp only [List.length_cons] at hlen; omega) + (fun child draw below hmem => he child draw below (List.mem_cons_of_mem _ hmem)) + (start + child.word.length) (by omega) + let threshold := coarseChildThresholdWithWork B q allowance draw + let childAllowance := coarseChildAllowanceWithWork L threshold.1 + let evaluated := evaluate child below childAllowance.1 start + let penalty := coarseBinaryPenaltyWithWork two evaluated.1 + let scale := coarseChildAllowanceWithWork q allowance + let contribution := coarseBinaryMapWithWork (coarseContributionWithWork threshold.1 scale.1) penalty.1 + let remainder := coarseBinaryChildren k q L two evaluate allowance rest (start + child.word.length) + have hpen : CoarseBinaryBox two (2 * k + 1) V D A penalty.1 := + coarseBinaryPenaltyWithWork_box two _ V D A evaluated.1 hchild.1 htwo htw hvbound + have hcon : CoarseBinaryBox two (2 * k + 1) (V + k) D A contribution.1 := + coarseBinaryMapWithWork_box two _ V (V + k) D A _ penalty.1 hpen + (fun a ha => coarseContributionWithWork_bounds two threshold.1 scale.1 a V k D A ha hs hmapbound) + have habound : Nat.size ((V + k) + rest.length * (V + k)) + 2 * D + 1 ≤ A := by + apply le_trans _ hbound + apply Nat.add_le_add_right + apply Nat.add_le_add_right + apply Nat.size_le_size + simp only [List.length_cons] at hlen + nlinarith + constructor + · have hh := coarseBinaryAddWithWork_box two (2 * k + 1) (V + k) (rest.length * (V + k)) D A + contribution.1 remainder.1 hcon hrest.1 habound + change CoarseBinaryBox two (2 * k + 1) ((rest.length + 1) * (V + k)) D A + (coarseBinaryAddWithWork contribution.1 remainder.1).1 + simpa only [Nat.add_mul, Nat.one_mul, Nat.add_comm] using hh + · have htc := coarseChildThresholdWithWork_cost B q A allowance draw ha hBbits hqbits + have hlc := coarseChildAllowanceWithWork_cost L A threshold.1 (ht draw) hLbits + have hsc := coarseChildAllowanceWithWork_cost q A allowance ha hqbits + have hpc := coarseBinaryPenaltyWithWork_cost two (2 * k + 1) V D A evaluated.1 hchild.1 htwo htw hvbound + have hmc := coarseBinaryMapWithWork_cost two (2 * k + 1) V D A (2200 * (A + 1) ^ 2) + (coarseContributionWithWork threshold.1 scale.1) penalty.1 hpen + (fun a ha => coarseContributionWithWork_cost threshold.1 scale.1 a A + (ht draw) hs.2.2.2.2 ha.2.2.2.2) + have hac := coarseBinaryAddWithWork_cost two (2 * k + 1) (V + k) (rest.length * (V + k)) D A + contribution.1 remainder.1 hcon hrest.1 + have haddr : Nat.size start ≤ A := (Nat.size_le_size (by omega)).trans hNbits + have hchildlen : Nat.size child.word.length ≤ A := (Nat.size_le_size (by omega)).trans hNbits + have hstep : threshold.2 + childAllowance.2 + penalty.2 + scale.2 + contribution.2 + + (coarseBinaryAddWithWork contribution.1 remainder.1).2 + + Nat.size start + Nat.size child.word.length + 10 ≤ + 100000000 * (A + 1) ^ 2 * (2 * k + 1) := by + nlinarith only [htc, hlc, hsc, hpc, hmc, hac, haddr, hchildlen, + Nat.zero_le A, Nat.zero_le k] + change threshold.2 + childAllowance.2 + evaluated.2 + penalty.2 + scale.2 + contribution.2 + + remainder.2 + (coarseBinaryAddWithWork contribution.1 remainder.1).2 + + Nat.size start + Nat.size child.word.length + 9 + (rest.length + 1) ≤ _ + have heval := hchild.2 + change evaluated.2 ≤ _ at heval + have hrec := hrest.2 + change remainder.2 + rest.length ≤ _ at hrec + simp only [coarseBinaryChildrenWeight, List.length_cons] + nlinarith only [hstep, heval, hrec] + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseChildrenSimulation.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseChildrenSimulation.lean new file mode 100644 index 0000000000000000000000000000000000000000..33107e7e438598dcd59633e14152e67d494cd432 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseChildrenSimulation.lean @@ -0,0 +1,72 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseBinaryGrid + +namespace OAI + +namespace EditApproximation +namespace BinaryFraction + +/-- Child arrays are reused exactly as in the shared rational evaluator. +This composition lemma isolates the inductive recursive-call hypothesis. -/ + theorem coarseBinaryChildren_rep {B d : ℕ} {α : Type*} [DecidableEq α] + (k q L : ℕ) (frame : List (Option α)) (two allowance : BinaryFraction) + (children : List (CoarseSourceTree B α d × Fin B × CoarseThresholdDraws B d)) + (htwo : two.value = 2) (ha : allowance.representation.den = two.representation.den) + (ht : ∀ draw : Fin B, + (coarseChildThresholdWithWork B q allowance draw).1.value = + coarseChildThreshold B q allowance.value draw) + (hs : (coarseChildAllowanceWithWork q allowance).1.value = allowance.value / q) + (he : ∀ child draw below, (child, draw, below) ∈ children → ∀ start, + CoarseArrayRep (coarseBinaryEval k q L frame two child below + (coarseChildAllowanceWithWork L (coarseChildThresholdWithWork B q allowance draw).1).1 start).1 + (coarseArrayEval k q (1 / L) frame child below + ((1 / L) * coarseChildThreshold B q allowance.value draw) start).1) + (start : ℕ) : + CoarseArrayRep (coarseBinaryChildren k q L two + (fun child => coarseBinaryEval k q L frame two child) allowance children start).1 + (coarseArrayEvalChildren k q (1 / L) (fun child => coarseArrayEval k q (1 / L) frame child) + allowance.value children start).1 := by + induction children generalizing start with + | nil => rfl + | cons data rest ih => + obtain ⟨child, draw, below⟩ := data + let threshold := coarseChildThresholdWithWork B q allowance draw + let childAllowance := coarseChildAllowanceWithWork L threshold.1 + let evaluated := coarseBinaryEval k q L frame two child below childAllowance.1 start + let ratEvaluated := coarseArrayEval k q (1 / L) frame child below + ((1 / L) * coarseChildThreshold B q allowance.value draw) start + have hthreshold : threshold.1.representation.den = two.representation.den := + (coarseChildThresholdWithWork_den B q allowance draw).trans ha + have hchild : childAllowance.1.representation.den = two.representation.den := + (coarseChildAllowanceWithWork_den L threshold.1).trans hthreshold + have hev : CoarseArrayRep evaluated.1 ratEvaluated.1 := he child draw below List.mem_cons_self start + have hg : CoarseArrayOnGrid two.representation.den evaluated.1 := + coarseBinaryEval_grid k q L frame two child below childAllowance.1 start hchild + have hp := coarseBinaryPenalty_rep two evaluated.1 ratEvaluated.1 htwo hev hg + have hpg := coarseBinaryPenalty_grid two evaluated.1 hg + have hmap := coarseBinaryMap_rep + (coarseContributionWithWork threshold.1 (coarseChildAllowanceWithWork q allowance).1) + (coarseThresholdContribution (coarseChildThreshold B q allowance.value draw) (allowance.value / q)) + (by + intro a + rw [coarseContributionWithWork_value, hs] + exact congrArg (fun t => coarseThresholdContribution t (allowance.value / q) a.value) (ht draw)) + (coarseBinaryPenaltyWithWork two evaluated.1).1 (coarseStoredPenalty ratEvaluated.1).1 hp + have hmg := coarseBinaryMap_grid + (coarseContributionWithWork threshold.1 (coarseChildAllowanceWithWork q allowance).1) + (coarseBinaryPenaltyWithWork two evaluated.1).1 two.representation.den hpg (by + intro a hden + exact (coarseContributionWithWork_den _ _ a + (((coarseChildAllowanceWithWork_den q allowance).trans ha).trans hden.symm)).trans hden) + have hr := ih (fun child draw below hmem => he child draw below (List.mem_cons_of_mem _ hmem)) + (start + child.word.length) + have hrg := coarseBinaryChildren_grid k q L two + (fun child => coarseBinaryEval k q L frame two child) allowance rest + (start + child.word.length) ha (by + intro child draw below _ a s had + exact coarseBinaryEval_grid k q L frame two child below a s had) + exact coarseBinaryAdd_rep _ _ _ _ two.representation.den hmap hr hmg hrg + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseCompactCells.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseCompactCells.lean new file mode 100644 index 0000000000000000000000000000000000000000..d5f693a1e5d2cee456faa35d7970561fe25d6039 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseCompactCells.lean @@ -0,0 +1,66 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseArraySimulation + +namespace OAI + +namespace EditApproximation +namespace BinaryFraction + +/-- Leading-zero removal is enough: this property does not assert that a +stored rational is reduced by a gcd. -/ +def CoarseCompact (a : BinaryFraction) : Prop := + a.width ≤ a.representation.storageBits + + theorem coarseCompact_canonical (a : BinaryFraction) : + CoarseCompact (canonicalizeWithWork a).1 := by + change (canonicalizeWithWork a).1.width ≤ _ + rw [canonicalizeWithWork_representation] + exact canonicalizeWithWork_width_le_storageBits a + + theorem coarseCompact_gridNat (den : List Bool) (hden : 0 < bitWordValue den) (n : ℕ) : + CoarseCompact (coarseGridNatWithWork den hden n).1 := by + unfold coarseGridNatWithWork + exact coarseCompact_canonical _ + + theorem coarseCompact_gridAdd (a b : BinaryFraction) : + CoarseCompact (coarseGridAddWithWork a b).1 := by + unfold coarseGridAddWithWork + exact coarseCompact_canonical _ + + theorem coarseCompact_min (a b : BinaryFraction) (ha : CoarseCompact a) (hb : CoarseCompact b) : + CoarseCompact (minWithWork a b).1 := by + unfold minWithWork + dsimp only + split_ifs <;> assumption + + theorem coarseCompact_max (a b : BinaryFraction) (ha : CoarseCompact a) (hb : CoarseCompact b) : + CoarseCompact (maxWithWork a b).1 := by + unfold maxWithWork + dsimp only + split_ifs <;> assumption + + theorem coarseCompact_divide (a b : BinaryFraction) : + CoarseCompact (coarseDivideWithWork a b).1 := by + unfold coarseDivideWithWork fixedDenominatorWithWork + exact coarseCompact_canonical _ + + theorem coarseCompact_contribution (threshold scale a : BinaryFraction) + (hs : CoarseCompact scale) (ha : CoarseCompact a) : + CoarseCompact (coarseContributionWithWork threshold scale a).1 := by + unfold coarseContributionWithWork + dsimp only + split_ifs + · exact coarseCompact_max a scale ha hs + · exact coarseCompact_gridNat _ _ 0 + + theorem coarseCompact_width (a : BinaryFraction) (V D : ℕ) + (ha : CoarseCompact a) (hv : |a.value| ≤ V) + (hd : Nat.size a.representation.den ≤ D) : + a.width ≤ Nat.size V + 2 * D + 1 := by + apply ha.trans + exact UnreducedRational.storageBits_le a.representation V D + (by simpa only [representation_value] using hv) hd + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseCompleteArrayWork.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseCompleteArrayWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..8243e673423ca701a253f27459efe3a778372f5a --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseCompleteArrayWork.lean @@ -0,0 +1,53 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseCompleteWork + +namespace OAI + +namespace EditApproximation +namespace BinaryFraction + +theorem coarseActiveChildrenWork_const_bound {B d : ℕ} {α : Type*} (Q lam allowance : ℚ) (C : ℕ) + (work : CoarseSourceTree B α d → CoarseThresholdDraws B d → ℚ → ℕ) + (children : List (CoarseSourceTree B α d × Fin B × CoarseThresholdDraws B d)) + (hc : ∀ child draw below, (child, draw, below) ∈ children → + work child below (lam * coarseChildThreshold B Q allowance draw) ≤ C) : + coarseActiveChildrenWork Q lam allowance work children ≤ children.length * C := by + induction children with + | nil => simp only [coarseActiveChildrenWork, List.length_nil, Nat.zero_mul, le_refl] + | cons data rest ih => + obtain ⟨child, draw, below⟩ := data + have hi := hc child draw below List.mem_cons_self + have hr := ih (fun c r b h => hc c r b (List.mem_cons_of_mem _ h)) + rw [coarseActiveChildrenWork, List.length_cons, Nat.add_mul, Nat.one_mul] + omega + +attribute [local irreducible] coarseActiveArrayWork + +theorem coarseActiveArrayWork_le_complete {B d : ℕ} {α : Type*} (k : ℕ) (Q lam : ℚ) + (tree : CoarseSourceTree B α d) (draws : CoarseThresholdDraws B d) (allowance : ℚ) : + coarseActiveArrayWork k Q lam tree draws allowance ≤ + (B * (2 * k + 1)) * coarseCompleteNodes B d := by + induction tree generalizing allowance with + | leaf letter => + rw [coarseActiveArrayWork] + split_ifs <;> simp only [coarseCompleteNodes, Nat.mul_one] <;> omega + | @branch d children ih => + obtain ⟨draws, below⟩ := draws + have hr := coarseActiveChildrenWork_const_bound Q lam allowance + ((B * (2 * k + 1)) * coarseCompleteNodes B d) + (fun child => coarseActiveArrayWork k Q lam child) + (List.ofFn fun i => (children i, draws i, below i)) (by + intro child draw b hb + obtain ⟨i, hi⟩ := List.mem_ofFn.mp hb + cases hi + exact ih i (below i) _) + simp only [List.length_ofFn] at hr + rw [coarseActiveArrayWork] + split_ifs + · exact Nat.zero_le _ + · rw [coarseCompleteNodes] + nlinarith only [hr] + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseCompletePolynomial.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseCompletePolynomial.lean new file mode 100644 index 0000000000000000000000000000000000000000..a5c35093e6ce51ae3378d37d907af06cc6cb2de6 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseCompletePolynomial.lean @@ -0,0 +1,61 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseCompleteArrayWork +import OAI.Combinatorics.EditApproximation.Geometry.TreeParameters + +namespace OAI + +namespace EditApproximation +namespace BinaryFraction + +theorem coarseCompleteNodes_polynomial (N B n : ℕ) (hB : 2 ≤ B) + (hn : n ≤ N) (hBP : B ≤ (N + 2) ^ 4) : + coarseCompleteNodes B (intervalTreeDepth B n) ≤ (N + 2) ^ 6 := by + have hc := coarseCompleteNodes_le B (intervalTreeDepth B n) hB + have hp := intervalTreeDepth_power_le B n hB + have hm : B * max 1 n ≤ (N + 2) ^ 4 * (N + 2) := + Nat.mul_le_mul hBP (max_le (by omega) (by omega)) + calc + _ ≤ 2 * (B * max 1 n) := by omega + _ ≤ 2 * ((N + 2) ^ 4 * (N + 2)) := Nat.mul_le_mul_left 2 hm + _ = 2 * (N + 2) ^ 5 := by ring + _ ≤ (N + 2) ^ 6 := by + have h := Nat.mul_le_mul_right ((N + 2) ^ 5) (show 2 ≤ N + 2 by omega) + nlinarith only [h] + +theorem coarseRootWidth_polynomial (N B k : ℕ) (hBP : B ≤ (N + 2) ^ 4) + (hk : k ≤ 2 * (N + 2)) : B * (2 * k + 1) + 1 ≤ (N + 2) ^ 8 := by + let X := N + 2 + have hx : 2 ≤ X := by dsimp only [X]; omega + have hw : 2 * k + 1 ≤ 5 * X := by dsimp only [X]; omega + have hm := Nat.mul_le_mul hBP hw + change B * (2 * k + 1) ≤ X ^ 4 * (5 * X) at hm + have hp : 1 ≤ X ^ 5 := one_le_pow₀ (by omega) + have h8 : 6 * X ^ 5 ≤ X ^ 8 := by + have hX3 : 6 ≤ X ^ 3 := by + have h := Nat.pow_le_pow_left hx 3 + norm_num at h + omega + calc + _ ≤ X ^ 3 * X ^ 5 := Nat.mul_le_mul_right _ hX3 + _ = _ := by rw [← pow_add] + change B * (2 * k + 1) + 1 ≤ X ^ 8 + nlinarith only [hm, hp, h8] + +theorem coarseActiveArrayWork_polynomial {α : Type*} (N B n k : ℕ) (Q lam allowance : ℚ) + (hB : 2 ≤ B) (hn : n ≤ N) (hBP : B ≤ (N + 2) ^ 4) (hk : k ≤ 2 * (N + 2)) + (tree : CoarseSourceTree B α (intervalTreeDepth B n)) + (draws : CoarseThresholdDraws B (intervalTreeDepth B n)) : + coarseActiveArrayWork k Q lam tree draws allowance ≤ (N + 2) ^ 14 := by + have hc := coarseActiveArrayWork_le_complete k Q lam tree draws allowance + have hn' := coarseCompleteNodes_polynomial N B n hB hn hBP + have hw : B * (2 * k + 1) ≤ (N + 2) ^ 8 := by + have h := coarseRootWidth_polynomial N B k hBP hk + omega + calc + _ ≤ _ := hc + _ ≤ (N + 2) ^ 8 * (N + 2) ^ 6 := Nat.mul_le_mul hw hn' + _ = _ := by rw [← pow_add] + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseCompleteWork.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseCompleteWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..dc052199098ea02a31e79a772aa5ea1f2c897e82 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseCompleteWork.lean @@ -0,0 +1,72 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseBinaryWeight + +namespace OAI + +namespace EditApproximation +namespace BinaryFraction + +def coarseCompleteNodes (B : ℕ) : ℕ → ℕ + | 0 => 1 + | d + 1 => 1 + B * coarseCompleteNodes B d + +theorem coarseCompleteNodes_pos (B d : ℕ) : 1 ≤ coarseCompleteNodes B d := by + cases d <;> simp only [coarseCompleteNodes] <;> omega + +theorem coarseCompleteNodes_le (B d : ℕ) (hB : 2 ≤ B) : + coarseCompleteNodes B d + 1 ≤ 2 * B ^ d := by + induction d with + | zero => simp only [coarseCompleteNodes, pow_zero]; omega + | succ d ih => + have hm := Nat.mul_le_mul_left B ih + rw [coarseCompleteNodes, pow_succ] + nlinarith only [hm, hB] + +theorem coarseBinaryChildrenWeight_const_bound {B d : ℕ} {α : Type*} (q L C : ℕ) + (weight : CoarseSourceTree B α d → CoarseThresholdDraws B d → BinaryFraction → ℕ) + (allowance : BinaryFraction) (children : List (CoarseSourceTree B α d × Fin B × CoarseThresholdDraws B d)) + (hc : ∀ child draw below, (child, draw, below) ∈ children → + weight child below (coarseChildAllowanceWithWork L + (coarseChildThresholdWithWork B q allowance draw).1).1 ≤ C) : + coarseBinaryChildrenWeight q L weight allowance children ≤ children.length * C := by + induction children with + | nil => simp only [coarseBinaryChildrenWeight, List.length_nil, Nat.zero_mul, le_refl] + | cons data rest ih => + obtain ⟨child, draw, below⟩ := data + have hi := hc child draw below List.mem_cons_self + have hr := ih (fun c r b h => hc c r b (List.mem_cons_of_mem _ h)) + rw [coarseBinaryChildrenWeight, List.length_cons, Nat.add_mul, Nat.one_mul] + omega + +attribute [local irreducible] coarseBinaryWeight + +theorem coarseBinaryWeight_le_complete {B d : ℕ} {α : Type*} (k q L : ℕ) + (tree : CoarseSourceTree B α d) (draws : CoarseThresholdDraws B d) (allowance : BinaryFraction) : + coarseBinaryWeight k q L tree draws allowance ≤ + (B * (2 * k + 1) + 1) * coarseCompleteNodes B d := by + induction tree generalizing allowance with + | leaf letter => + rw [coarseBinaryWeight] + split_ifs <;> simp only [coarseCompleteNodes, Nat.mul_one] <;> omega + | @branch d children ih => + obtain ⟨draws, below⟩ := draws + have hr := coarseBinaryChildrenWeight_const_bound q L + ((B * (2 * k + 1) + 1) * coarseCompleteNodes B d) + (fun child => coarseBinaryWeight k q L child) allowance + (List.ofFn fun i => (children i, draws i, below i)) (by + intro child draw b hb + obtain ⟨i, hi⟩ := List.mem_ofFn.mp hb + cases hi + exact ih i (below i) _) + simp only [List.length_ofFn] at hr + rw [coarseBinaryWeight] + split_ifs + · have hc := coarseCompleteNodes_pos B (d + 1) + have hp := Nat.mul_le_mul (show 1 ≤ B * (2 * k + 1) + 1 by omega) hc + simpa only [Nat.one_mul] using hp + · rw [coarseCompleteNodes] + nlinarith only [hr] + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseDenominatorArithmetic.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseDenominatorArithmetic.lean new file mode 100644 index 0000000000000000000000000000000000000000..a23b1a17fabbb74562172efe097bd0d94ad535f6 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseDenominatorArithmetic.lean @@ -0,0 +1,103 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryPowerStorage +import OAI.Combinatorics.EditApproximation.Coarse.CoarsePrecision +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation + +/-- Construct the common denominator by Boolean products and binary +exponentiation, charging all intermediate bit operations. -/ + + + theorem coarseDenominatorWithWork_value (allowanceDen q L branching : List Bool) (D : ℕ) : + bitWordValue (coarseDenominatorWithWork allowanceDen q L branching D).1 = + coarseCommonDenominator (bitWordValue allowanceDen) (bitWordValue q) + (bitWordValue L) (bitWordValue branching) D := by + simp only [coarseDenominatorWithWork, trimBitWordWithWork_value, + bitMulWithWork_value, bitPowerWithWork_value, coarseCommonDenominator] + + theorem coarseDenominatorWithWork_length (allowanceDen q L branching : List Bool) (D : ℕ) : + (coarseDenominatorWithWork allowanceDen q L branching D).1.length = + Nat.size (coarseCommonDenominator (bitWordValue allowanceDen) (bitWordValue q) + (bitWordValue L) (bitWordValue branching) D) := by + simp only [coarseDenominatorWithWork, trimBitWordWithWork_length, + bitMulWithWork_value, bitPowerWithWork_value, trimBitWordWithWork_value, + coarseCommonDenominator] + + theorem coarseDenominatorWithWork_cost (allowanceDen q L branching : List Bool) (D A : ℕ) + (ha : allowanceDen.length ≤ A) (hq : q.length ≤ A) (hL : L.length ≤ A) + (hb : branching.length ≤ A) : + (coarseDenominatorWithWork allowanceDen q L branching D).2 ≤ + bitPowerBitBudget D (7 * A + 3) + 1000 * (10 * (D + 2) * (A + 1) + 1) ^ 2 := by + let first := bitMulWithWork L branching + let base := bitMulWithWork first.1 q + let trimmed := trimBitWordWithWork base.1 + let power := bitPowerWithWork trimmed.1 D + let initial := bitMulWithWork allowanceDen q + let product := bitMulWithWork initial.1 power.1 + let W := 10 * (D + 2) * (A + 1) + have hf := bitMulWithWork_cost L branching + have hfl := bitMulWithWork_length L branching + have hbc := bitMulWithWork_cost first.1 q + have hbl := bitMulWithWork_length first.1 q + have ht := (trimBitWordWithWork_cost base.1).le + have htl : trimmed.1.length ≤ 7 * A + 3 := by + have hh : trimmed.1.length ≤ base.1.length := by + rw [trimBitWordWithWork_length] + exact Nat.size_le.mpr (bitWordValue_lt_pow_length _) + change base.1.length ≤ 2 * first.1.length + q.length + 1 at hbl + change first.1.length ≤ 2 * L.length + branching.length + 1 at hfl + omega + have hp := bitPowerWithWork_cost trimmed.1 D (7 * A + 3) htl + have hpl := bitPowerWithWork_length_le trimmed.1 D (7 * A + 3) htl + have hi := bitMulWithWork_cost allowanceDen q + have hil := bitMulWithWork_length allowanceDen q + have hprod := bitMulWithWork_cost initial.1 power.1 + have hprodl := bitMulWithWork_length initial.1 power.1 + have htrim := trimBitWordWithWork_cost product.1 + have hfirst : first.1.length ≤ W := by + change first.1.length ≤ 2 * L.length + branching.length + 1 at hfl + dsimp only [W] + nlinarith only [hfl, hL, hb, Nat.zero_le D, Nat.zero_le A] + have hbase : base.1.length ≤ W := by + change base.1.length ≤ 2 * first.1.length + q.length + 1 at hbl + change first.1.length ≤ 2 * L.length + branching.length + 1 at hfl + dsimp only [W] + nlinarith only [hbl, hfl, hq, hL, hb, Nat.zero_le D, Nat.zero_le A] + have hinitial : initial.1.length ≤ W := by + change initial.1.length ≤ 2 * allowanceDen.length + q.length + 1 at hil + dsimp only [W] + nlinarith only [hil, ha, hq, Nat.zero_le D, Nat.zero_le A] + have hpower : power.1.length ≤ W := by + dsimp only [W] + nlinarith only [hpl, Nat.zero_le D, Nat.zero_le A] + have hAW : A ≤ W := by dsimp only [W]; nlinarith only [Nat.zero_le D, Nat.zero_le A] + have bound (x y : List Bool) (hx : x.length ≤ W) (hy : y.length ≤ W) : + (bitMulWithWork x y).2 ≤ 40 * (W + 1) ^ 2 := by + apply (bitMulWithWork_cost x y).trans + have hm := Nat.mul_le_mul (show x.length + 1 ≤ W + 1 by omega) + (show x.length + y.length + 1 ≤ 2 * (W + 1) by omega) + nlinarith only [hm] + have hf' := bound L branching (hL.trans hAW) (hb.trans hAW) + have hb' := bound first.1 q hfirst (hq.trans hAW) + have hi' := bound allowanceDen q (ha.trans hAW) (hq.trans hAW) + have hprod' := bound initial.1 power.1 hinitial hpower + change base.1.length ≤ 2 * first.1.length + q.length + 1 at hbl + change product.1.length ≤ 2 * initial.1.length + power.1.length + 1 at hprodl + change first.2 + base.2 + trimmed.2 + power.2 + initial.2 + product.2 + + (trimBitWordWithWork product.1).2 + 7 ≤ _ + change trimmed.2 ≤ 3 * base.1.length + 1 at ht + change first.2 ≤ _ at hf' + change base.2 ≤ _ at hb' + change initial.2 ≤ _ at hi' + change product.2 ≤ _ at hprod' + change power.2 ≤ _ at hp + change _ ≤ bitPowerBitBudget D (7 * A + 3) + 1000 * (W + 1) ^ 2 + nlinarith only [hf', hb', hi', hprod', hp, ht, htrim, hbase, hprodl, hinitial, + hpower, Nat.zero_le W] + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseDescriptorWork.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseDescriptorWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..faed8b4823f471f8f436b12e5881b722e8ba5851 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseDescriptorWork.lean @@ -0,0 +1,47 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseReadTree +import OAI.Combinatorics.EditApproximation.Coarse.CoarseIndexedFrameWork +import OAI.Combinatorics.EditApproximation.Binary.BinaryPowerStorage +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation + +theorem saturatingSubtractWithWork_length (a b : ℕ) : + (saturatingSubtractWithWork a b).1.length ≤ max (Nat.size a) (Nat.size b) := by + unfold saturatingSubtractWithWork + dsimp only + split_ifs + · exact Nat.zero_le _ + · simpa only [binaryNaturalSubtractWithWork, bitSubtractWithWork_length, + Nat.size_eq_bits_len] using (le_refl (max (Nat.size a) (Nat.size b))) + +/-- Construct a descriptor's clipped length by Boolean exponentiation, +subtraction and minimum, retaining the resulting bits. -/ + + +theorem coarseDescriptorWithWork_value (B d n start : ℕ) : + bitWordValue (coarseDescriptorWithWork B d n start).1 = coarseDescriptorLength B d n start := by + simp only [coarseDescriptorWithWork, wordMinWithWork_value, + bitPowerWithWork_value, bitWordValue_bits, saturatingSubtractWithWork_value, + coarseDescriptorLength] + +theorem coarseDescriptorWithWork_cost (B d n start A : ℕ) + (hB : Nat.size B ≤ A) (hn : Nat.size n ≤ A) (hs : Nat.size start ≤ A) : + (coarseDescriptorWithWork B d n start).2 ≤ + bitPowerBitBudget d A + 100 * (d + 2) * (A + 1) := by + have hp := bitPowerWithWork_cost B.bits d A (by simpa only [Nat.size_eq_bits_len] using hB) + have hpl := bitPowerWithWork_length_le B.bits d A (by simpa only [Nat.size_eq_bits_len] using hB) + have hr := saturatingSubtractWithWork_cost n start + have hrl := saturatingSubtractWithWork_length n start + have hm := wordLEWithWork_cost (bitPowerWithWork B.bits d).1 + (saturatingSubtractWithWork n start).1 + have hd : Nat.size d ≤ d := Nat.size_le.mpr (Nat.lt_pow_self (by decide : 1 < (2 : ℕ))) + simp only [coarseDescriptorWithWork, wordMinWithWork] + nlinarith only [hp, hpl, hr, hrl, hm, hd, hB, hn, hs, + max_le hn hs, Nat.zero_le d, Nat.zero_le A] + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseEntryCostSum.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseEntryCostSum.lean new file mode 100644 index 0000000000000000000000000000000000000000..4097dcb33451793f9f3c529b609a4a327cc451c6 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseEntryCostSum.lean @@ -0,0 +1,68 @@ +import OAI.Combinatorics.EditApproximation.Refinement.ComputedCoarseInitialWork +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalCoarseSeedLaw +import OAI.Combinatorics.EditApproximation.Probability.FreshCoordinateCost + +namespace OAI + +namespace EditApproximation + +/-- Keep the branch dimensions symbolic when forming the finite source sum. -/ +def coarseEntryBinaryCost (N B d : ℕ) [NeZero B] (x y : List ℕ) + (draws : CoarseGuessIndex (coarseEntryWidth x y) → CoarseThresholdDraws B d) : ℕ := + (BinaryFraction.coarseInitialWithWork (inputHeight N ^ 4) (64 * inputHeight N) N + (Nat.pos_of_neZero B) (pow_pos (Nat.two_pow_pos _) _) + (Nat.mul_pos (by decide) (Nat.two_pow_pos _)) x y draws).2 + +theorem coarseEntryBinaryCost_computed_bound : + ∀ᶠ N : ℕ in Filter.atTop, ∀ B d : ℕ, ∀ x y : List ℕ, + B = (integerParameters N).B → d = computedCoarseDepth N (coarseEntryWidth x y) → + coarseEntryWidth x y ≤ N → (∀ a ∈ x ++ y, Nat.size a ≤ inputHeight N ^ 3) → + ∀ (_hB : NeZero B) (draw : CoarseGuessIndex (coarseEntryWidth x y) → CoarseThresholdDraws B d), + (coarseEntryBinaryCost N B d x y draw : ℝ) ≤ (inputHeight N : ℝ) ^ 36 * + ((coarseInitialArrayWork B d (initialThresholdQ N) (initialLambda N) x y draw : ℝ) + + (x.length + 1 : ℕ)) := by + filter_upwards [BinaryFraction.computedCoarseInitialWithWork_bound] with N hN + intro B d x y hB hd hxy hsymbols hinstance draw + have hb := hN B d x y hB hd hxy hsymbols + (Nat.pos_of_neZero _) (pow_pos (Nat.two_pow_pos _) _) + (Nat.mul_pos (by decide) (Nat.two_pow_pos _)) draw + exact_mod_cast hb + +noncomputable def coarseEntryCostSum {M J B : ℕ} [NeZero B] (source target : List ℕ) + (N : ℕ) (depth : PhysicalEntry M J target.length → ℕ) + (draw : PhysicalCoarseDraw source target B depth) + (selected : PhysicalEntry M J target.length → Prop) : ℝ := by + classical + exact ∑ entry : PhysicalEntry M J target.length, selectionIndicator (selected entry) * + (coarseEntryBinaryCost N B (depth entry) (physicalSource source entry.1) + (substring target entry.2.lo entry.2.hi) (draw entry) : ℝ) + +theorem coarseEntryCostSum_bound {M J B : ℕ} [NeZero B] (source target : List ℕ) + (N : ℕ) (depth : PhysicalEntry M J target.length → ℕ) + (draw : PhysicalCoarseDraw source target B depth) + (selected : PhysicalEntry M J target.length → Prop) (C : ℝ) + (hc : ∀ entry : PhysicalEntry M J target.length, + (coarseEntryBinaryCost N B (depth entry) (physicalSource source entry.1) + (substring target entry.2.lo entry.2.hi) (draw entry) : ℝ) ≤ + C * ((coarseInitialArrayWork B (depth entry) (initialThresholdQ N) (initialLambda N) + (physicalSource source entry.1) (substring target entry.2.lo entry.2.hi) (draw entry) : ℝ) + + ((physicalSource source entry.1).length + 1 : ℕ))) : + coarseEntryCostSum source target N depth draw selected ≤ C * + ((∑ entry : PhysicalEntry M J target.length, selectionIndicator (selected entry) * + (coarseInitialArrayWork B (depth entry) (initialThresholdQ N) (initialLambda N) + (physicalSource source entry.1) (substring target entry.2.lo entry.2.hi) (draw entry) : ℝ)) + + ∑ entry : PhysicalEntry M J target.length, selectionIndicator (selected entry) * + ((physicalSource source entry.1).length + 1 : ℕ)) := by + classical + rw [← Finset.sum_add_distrib, Finset.mul_sum] + unfold coarseEntryCostSum + apply Finset.sum_le_sum + intro entry _ + have hs : 0 ≤ selectionIndicator (selected entry) := by + unfold selectionIndicator + split <;> norm_num + exact (mul_le_mul_of_nonneg_left (hc entry) hs).trans_eq (by ring) + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseEstimator.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseEstimator.lean new file mode 100644 index 0000000000000000000000000000000000000000..2c7493e157960705c63843f26afa6dae5f9fa1dd --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseEstimator.lean @@ -0,0 +1,236 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseSeed +import OAI.Combinatorics.EditApproximation.Geometry.Seed +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! +# The concrete pruned coarse estimator + +The random labels are a finite complete tree of integers in `1,...,B`. +Every execution below uses rational arithmetic and literal finite minima; +pruned arrays are represented by the zero function. Accuracy events are +kept separate from this executable definition. +-/ + +namespace EditApproximation + +open Finset + +universe u + +/- All threshold labels, including labels below nodes which may be pruned. -/ + + +/-- Rational version of the literal threshold contribution. -/ + + +theorem coarseThresholdContribution_cast (threshold scale value : ℚ) : + (coarseThresholdContribution threshold scale value : ℝ) = + thresholdContribution threshold scale value := by + by_cases h : threshold ≤ value + · have hreal : (threshold : ℝ) ≤ value := by exact_mod_cast h + simp only [coarseThresholdContribution, thresholdContribution, h, hreal, + ↓reduceIte, Rat.cast_max] + · have hreal : ¬(threshold : ℝ) ≤ value := by exact_mod_cast h + simp only [coarseThresholdContribution, thresholdContribution, h, hreal, + ↓reduceIte, Rat.cast_zero] + +theorem coarseThresholdContribution_nonneg {threshold scale value : ℚ} + (hscale : 0 ≤ scale) : 0 ≤ coarseThresholdContribution threshold scale value := by + unfold coarseThresholdContribution + split_ifs + · exact hscale.trans (le_max_right _ _) + · rfl + +/- Exact finite threshold selected by a child label. -/ + + +/- Internal child traversal, retaining actual source starts. -/ + + +/-- Section 3's pruned rational recurrence. All labels are supplied +beforehand; execution exposes a label only when its parent is expanded. -/ + + +theorem coarseChildThreshold_nonneg {B : ℕ} {Q allowance : ℚ} (draw : Fin B) + (hQ : 0 ≤ Q) (ha : 0 ≤ allowance) : 0 ≤ coarseChildThreshold B Q allowance draw := by + unfold coarseChildThreshold + positivity + +theorem coarseChildThreshold_pos {B : ℕ} {Q allowance : ℚ} (draw : Fin B) + (hQ : 0 < Q) (ha : 0 < allowance) : 0 < coarseChildThreshold B Q allowance draw := by + have hB : 0 < B := Nat.zero_lt_of_lt draw.isLt + unfold coarseChildThreshold + positivity + +theorem coarseThresholdChildrenCost_nonneg {B D : ℕ} {α : Type u} + (k : ℕ) (Q lam : ℚ) + (value : CoarseSourceTree B α D → CoarseThresholdDraws B D → ℚ → ℕ → Fin (2 * k + 1) → ℚ) + (children : List (CoarseSourceTree B α D × Fin B × CoarseThresholdDraws B D)) + (allowance : ℚ) (start : ℕ) (shift : Fin (2 * k + 1)) + (hQ : 0 ≤ Q) (ha : 0 ≤ allowance) : + 0 ≤ coarseThresholdChildrenCost k Q lam value allowance children start shift := by + induction children generalizing start with + | nil => rfl + | cons data rest ih => + obtain ⟨child, draw, below⟩ := data + simp only [coarseThresholdChildrenCost] + exact add_nonneg (coarseThresholdContribution_nonneg (div_nonneg ha hQ)) + (ih (start + child.word.length)) + +theorem coarseThresholdEstimate_nonneg {B D : ℕ} {α : Type u} [DecidableEq α] + (k : ℕ) (Q lam : ℚ) (frame : List (Option α)) + (tree : CoarseSourceTree B α D) (draws : CoarseThresholdDraws B D) + (allowance : ℚ) (start : ℕ) (shift : Fin (2 * k + 1)) + (hQ : 0 ≤ Q) (ha : 0 ≤ allowance) : + 0 ≤ coarseThresholdEstimate k Q lam frame tree draws allowance start shift := by + cases tree with + | leaf letter => + simp only [coarseThresholdEstimate] + split_ifs + · rfl + · positivity + | branch children => + obtain ⟨draws, below⟩ := draws + simp only [coarseThresholdEstimate] + split_ifs + · rfl + · exact coarseThresholdChildrenCost_nonneg k Q lam _ _ allowance start shift hQ ha + +/-- Adding a nonnegative connection penalty and taking the actual +finite minimum preserves the multiplicative/additive child guarantee. -/ +theorem coarse_penalty_minimum_error {ι : Type*} [Fintype ι] [Nonempty ι] + (trueCost penalty : ι → ℕ) (estimate : ι → ℚ) (f error : ℝ) + (hf : 1 ≤ f) + (hlower : ∀ i, (trueCost i : ℝ) / f - error ≤ estimate i) + (hupper : ∀ i, (estimate i : ℝ) ≤ f * trueCost i + error) : + ((univ.inf' univ_nonempty (fun i => trueCost i + penalty i) : ℕ) : ℝ) / f - error ≤ + ((univ.inf' univ_nonempty (fun i => estimate i + (penalty i : ℚ)) : ℚ) : ℝ) ∧ + ((univ.inf' univ_nonempty (fun i => estimate i + (penalty i : ℚ)) : ℚ) : ℝ) ≤ + f * ((univ.inf' univ_nonempty (fun i => trueCost i + penalty i) : ℕ) : ℝ) + error := by + have hfpos : 0 < f := lt_of_lt_of_le zero_lt_one hf + constructor + · obtain ⟨i, hi, hmin⟩ := exists_mem_eq_inf' (s := univ) univ_nonempty + (fun i => estimate i + (penalty i : ℚ)) + rw [hmin] + have htrue : ((univ.inf' univ_nonempty (fun i => trueCost i + penalty i) : ℕ) : ℝ) ≤ + (trueCost i : ℝ) + penalty i := by + exact_mod_cast inf'_le (fun i => trueCost i + penalty i) hi + have hpen : (penalty i : ℝ) / f ≤ penalty i := by + apply (div_le_iff₀ hfpos).2 + nlinarith [show (0 : ℝ) ≤ penalty i by positivity] + simp only [Rat.cast_add, Rat.cast_natCast] + calc + _ ≤ ((trueCost i : ℝ) + penalty i) / f - error := + sub_le_sub_right (div_le_div_of_nonneg_right htrue hfpos.le) _ + _ = (trueCost i : ℝ) / f - error + (penalty i : ℝ) / f := by ring + _ ≤ _ := add_le_add (hlower i) hpen + · obtain ⟨i, hi, hmin⟩ := exists_mem_eq_inf' (s := univ) univ_nonempty + (fun i => trueCost i + penalty i) + rw [hmin] + have hestimate : ((univ.inf' univ_nonempty (fun i => estimate i + (penalty i : ℚ)) : ℚ) : ℝ) ≤ + (estimate i : ℝ) + penalty i := by + exact_mod_cast inf'_le (fun i => estimate i + (penalty i : ℚ)) hi + simp only [Nat.cast_add] + exact hestimate.trans (by nlinarith [hupper i, show (0 : ℝ) ≤ penalty i by positivity]) + +/-- A zero literal penalty minimum forces the zero-cost child to use +the parent's same shift. -/ +theorem coarse_penalty_minimum_zero (k : ℕ) (value : Fin (2 * k + 1) → ℕ) + (shift : Fin (2 * k + 1)) + (hzero : univ.inf' univ_nonempty + (fun next => value next + 2 * Nat.dist shift.val next.val) = 0) : value shift = 0 := by + obtain ⟨next, _, hmin⟩ := exists_mem_eq_inf' (s := univ) univ_nonempty + (fun next => value next + 2 * Nat.dist shift.val next.val) + have hdistance : Nat.dist shift.val next.val = 0 := by omega + have hequal : shift = next := Fin.ext (Nat.eq_of_dist_eq_zero hdistance) + rw [← hequal] at hmin + simp only [Nat.dist_self, mul_zero, add_zero] at hmin + omega + +/-- If the same-shift child estimate is zero, its actual minimum is zero. -/ +theorem coarse_estimated_minimum_zero (k : ℕ) (value : Fin (2 * k + 1) → ℚ) + (shift : Fin (2 * k + 1)) (hnonnegative : ∀ next, 0 ≤ value next) + (hzero : value shift = 0) : + univ.inf' univ_nonempty (fun next => value next + (2 * Nat.dist shift.val next.val : ℕ)) = 0 := by + apply le_antisymm + · have hminimum := inf'_le + (fun next => value next + (2 * Nat.dist shift.val next.val : ℕ)) (mem_univ shift) + simpa only [Nat.dist_self, mul_zero, Nat.cast_zero, hzero, add_zero] using hminimum + · apply le_inf' + intro next hnext + exact add_nonneg (hnonnegative next) (by positivity) + +theorem coarseThresholdChildrenCost_zero {B D : ℕ} {α : Type u} + (k : ℕ) (Q lam : ℚ) + (trueValue : CoarseSourceTree B α D → ℕ → Fin (2 * k + 1) → ℕ) + (value : CoarseSourceTree B α D → CoarseThresholdDraws B D → ℚ → ℕ → Fin (2 * k + 1) → ℚ) + (children : List (CoarseSourceTree B α D × Fin B × CoarseThresholdDraws B D)) + (hchildNonnegative : ∀ child draw below, (child, draw, below) ∈ children → + ∀ allowance start shift, 0 < allowance → 0 ≤ value child below allowance start shift) + (hchildZero : ∀ child draw below, (child, draw, below) ∈ children → + ∀ allowance start shift, 0 < allowance → trueValue child start shift = 0 → + value child below allowance start shift = 0) + (allowance : ℚ) (start : ℕ) (shift : Fin (2 * k + 1)) + (hQ : 0 < Q) (hlam : 0 < lam) (ha : 0 < allowance) + (hzero : coarseChildrenCost k trueValue (children.map Prod.fst) start shift = 0) : + coarseThresholdChildrenCost k Q lam value allowance children start shift = 0 := by + induction children generalizing start with + | nil => rfl + | cons data rest ih => + obtain ⟨child, draw, below⟩ := data + simp only [List.map_cons, coarseChildrenCost] at hzero + have hfirstTrue : trueValue child start shift = 0 := + coarse_penalty_minimum_zero k (trueValue child start) shift (by omega) + have hthreshold : 0 < coarseChildThreshold B Q allowance draw := + coarseChildThreshold_pos draw hQ ha + have hchildAllowance : 0 < lam * coarseChildThreshold B Q allowance draw := + mul_pos hlam hthreshold + have hminimum := coarse_estimated_minimum_zero k + (value child below (lam * coarseChildThreshold B Q allowance draw) start) shift + (fun next => hchildNonnegative child draw below (by simp) _ start next hchildAllowance) + (hchildZero child draw below (by simp) _ start shift hchildAllowance hfirstTrue) + have hrest := ih + (fun child draw below hmem => hchildNonnegative child draw below (by simp [hmem])) + (fun child draw below hmem => hchildZero child draw below (by simp [hmem])) + (start + child.word.length) (by omega) + simp only [coarseThresholdChildrenCost, hminimum, hrest, add_zero, + coarseThresholdContribution, not_le_of_gt hthreshold, ↓reduceIte] + +/-- Exact zero states remain zero on every label realization, without +conditioning on any accuracy event. -/ +theorem coarseThresholdEstimate_zero {B D : ℕ} {α : Type u} [DecidableEq α] + (k : ℕ) (Q lam : ℚ) (frame : List (Option α)) + (tree : CoarseSourceTree B α D) (draws : CoarseThresholdDraws B D) + (allowance : ℚ) (start : ℕ) (shift : Fin (2 * k + 1)) + (hQ : 0 < Q) (hlam : 0 < lam) (ha : 0 < allowance) + (hzero : coarseShiftCost k frame tree start shift = 0) : + coarseThresholdEstimate k Q lam frame tree draws allowance start shift = 0 := by + induction tree generalizing allowance start shift with + | leaf letter => + simp only [coarseThresholdEstimate] + split_ifs + · rfl + · exact_mod_cast hzero + | branch children ih => + obtain ⟨draws, below⟩ := draws + simp only [coarseThresholdEstimate] + split_ifs + · rfl + · refine coarseThresholdChildrenCost_zero k Q lam + (fun child => coarseShiftCost k frame child) + (fun child => coarseThresholdEstimate k Q lam frame child) _ + (fun child _ childBelow _ allowance start shift ha => + coarseThresholdEstimate_nonneg k Q lam frame child childBelow allowance start shift hQ.le ha.le) + ?_ allowance start shift hQ hlam ha ?_ + · intro child draw childBelow hmem allowance start shift ha hzero + obtain ⟨i, hi⟩ := List.mem_ofFn.mp hmem + cases hi + exact ih i (below i) allowance start shift ha hzero + · simpa only [List.map_ofFn, Function.comp_def, coarseShiftCost] using hzero + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseFirstRequestCost.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseFirstRequestCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..c5cc01974b07fe3d45fa16ca968426636a5720fc --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseFirstRequestCost.lean @@ -0,0 +1,64 @@ +import OAI.Combinatorics.EditApproximation.Refinement.ComputedCoarseWidthCost +import OAI.Combinatorics.EditApproximation.Probability.FreshCoordinateCost +import OAI.Combinatorics.EditApproximation.Coarse.CoarseGlobalSeed + +namespace OAI + +/-! First-request work for a complete independent coarse source. The +query is adaptive; each entry is charged only on its first appearance. +No conditioning on seed correctness occurs in this estimate. -/ + +namespace EditApproximation + +open MeasureTheory + +section FirstRequest + +variable {ι α : Type*} [Fintype ι] [DecidableEq ι] [DecidableEq α] + (N B : ℕ) [NeZero B] [MeasurableSpace (Fin B)] [MeasurableSingletonClass (Fin B)] + (depth : ι → ℕ) (x y : ι → List α) (query : FiniteQuery ι) + +noncomputable def coarseFirstRequestWork (draw : CoarseFullSeedDraws B depth x y) : ℝ := + ∑ i, selectionIndicator (i ∈ query.keys + (fun j => (coarseFullSeedTable N B depth x y draw j : ℚ))) * + (coarseInitialArrayWork B (depth i) (initialThresholdQ N) (initialLambda N) (x i) (y i) (draw i) : ℝ) + +theorem coarseFirstRequestWork_expected_le + (hB : B = (integerParameters N).B) (hN : 0 < N) (hell : 200 ≤ inputSmallLog N) + (hdepth : ∀ i, depth i = computedCoarseDepth N (coarseEntryWidth (x i) (y i))) + (hsize : ∀ i, coarseEntryWidth (x i) (y i) ≤ N) + (hinverse : coarseInverseAllowanceFactor B (initialThresholdQ N) (initialLambda N) ≤ + (inputHeight N : ℝ) ^ 8) + (budget : ℝ) + (hbudget : ∀ draw : CoarseFullSeedDraws B depth x y, + ((query.cost (fun i => (coarseFullSeedTable N B depth x y draw i : ℚ)) + (fun i => (x i).length) : ℕ) : ℝ) ≤ budget) : + (∫ draw, coarseFirstRequestWork N B depth x y query draw + ∂coarseFullSeedMeasure B depth x y) ≤ budget * computedCoarseWidthOverhead N := by + let μ := fun i => coarseInitialMeasure B (depth i) (coarseEntryWidth (x i) (y i)) + let answer := fun i draw => + (coarseInitialValue B (depth i) (initialThresholdQ N) (initialLambda N) N (x i) (y i) draw : ℚ) + let cost := fun i draw => + (coarseInitialArrayWork B (depth i) (initialThresholdQ N) (initialLambda N) (x i) (y i) draw : ℝ) + have hcost (i) : (∫ value, cost i value ∂μ i) ≤ + ((x i).length : ℝ) * computedCoarseWidthOverhead N := + computed_coarse_expected_source_width N B hB hN hell hinverse (x i) (y i) + (depth i) (hdepth i) (hsize i) + have hselected (draw : CoarseFullSeedDraws B depth x y) : + (∑ i, selectionIndicator (i ∈ query.keys (fun j => answer j (draw j))) * + ((x i).length : ℝ)) ≤ budget := by + have hs := sum_selected_nat_weights_le (query.keys (fun j => answer j (draw j))) + (fun i => (x i).length) + have hb := hbudget draw + rw [FiniteQuery.cost_eq_sum] at hb + exact hs.trans hb + have h := finiteQuery_fresh_expected_cost_le μ query answer cost + (fun i => ((x i).length : ℝ)) (computedCoarseWidthOverhead N) budget + (Nat.cast_nonneg _) hcost hselected + exact h + +end FirstRequest + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseGlobalSeed.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseGlobalSeed.lean new file mode 100644 index 0000000000000000000000000000000000000000..0524d1dc533bb6073780212b30deef8836e7c111 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseGlobalSeed.lean @@ -0,0 +1,317 @@ +import OAI.Combinatorics.EditApproximation.Refinement.ComputedSeed +import OAI.Combinatorics.EditApproximation.Geometry.DomainCounts +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! +# Simultaneous seed failure with the computed parameters + +The count includes every dyadic guess, complete coarse-tree node and shift. +Independent finite entry streams realize the actual full table law. +Symbolic recursion indices carry exact equalities to the computed parameters. +-/ + +namespace EditApproximation + +open Finset MeasureTheory ProbabilityTheory + +theorem twice_square_le_two_pow (r : ℕ) (hr : 8 ≤ r) : 2 * r ^ 2 ≤ 2 ^ r := by + induction r, hr using Nat.le_induction with + | base => norm_num + | succ r hr ih => + rw [pow_succ 2 r] + nlinarith + +theorem computed_coarse_B_upper (N : ℕ) (hN : 0 < N) (hell : 200 ≤ inputSmallLog N) : + (integerParameters N).B ≤ 2 ^ inputHeight N := by + have hlogs := inputSmallLog_bounds N hN + have hr : 8 ≤ heightExponent N := by omega + have hp : coarseExponent (inputSmallLog N) ≤ 2 * heightExponent N := by + have hsqrt := (Nat.sqrt_le_self (Nat.sqrt (Nat.log 2 (inputSmallLog N)))).trans + (Nat.sqrt_le_self (Nat.log 2 (inputSmallLog N))) + exact hsqrt.trans ((Nat.log_le_self _ _).trans (by omega)) + have hpoly := twice_square_le_two_pow (heightExponent N) hr + have hexponent : heightExponent N * coarseExponent (inputSmallLog N) ≤ inputHeight N := by + have hmul := Nat.mul_le_mul_left (heightExponent N) hp + change _ ≤ 2 ^ heightExponent N + nlinarith + change (2 ^ heightExponent N) ^ coarseExponent (inputSmallLog N) ≤ 2 ^ inputHeight N + rw [← pow_mul] + exact Nat.pow_le_pow_right (by decide : 0 < 2) hexponent + +theorem computed_coarse_height_large (N : ℕ) (hN : 0 < N) (hell : 200 ≤ inputSmallLog N) : + 256 ≤ inputHeight N := by + have hlogs := inputSmallLog_bounds N hN + have hr : 8 ≤ heightExponent N := by omega + change 2 ^ 8 ≤ 2 ^ heightExponent N + exact Nat.pow_le_pow_right (by decide : 0 < 2) hr + +theorem coarseInternalNodes_add_one_le_pow (B D : ℕ) (hB : 2 ≤ B) : + coarseInternalNodes B D + 1 ≤ B ^ D := by + induction D with + | zero => simp only [coarseInternalNodes, zero_add, pow_zero, le_refl] + | succ D ih => + have hmul := Nat.mul_le_mul_left B ih + simp only [coarseInternalNodes, pow_succ] + nlinarith + +/-- Multiplicity of all local Bernstein tails for one complete entry. -/ +def coarseEntryTailCount (B D n : ℕ) : ℕ := + (Nat.clog 2 n + 1) * coarseInternalNodes B D * (4 * (2 * 2 ^ Nat.clog 2 n + 1)) + +theorem computed_coarseEntryTailCount (N n : ℕ) (hN : 0 < N) (hn : n ≤ N) + (hell : 200 ≤ inputSmallLog N) : + coarseEntryTailCount (integerParameters N).B (computedCoarseDepth N n) n ≤ + 2 ^ (4 * inputHeight N + 4) := by + let H := inputHeight N + let B := (integerParameters N).B + have hBtwo : 2 ≤ B := by + have hbranch := computed_coarse_branching N hN hell + dsimp [B] + omega + have hBupper : B ≤ 2 ^ H := computed_coarse_B_upper N hN hell + have hnmax : max 1 n ≤ 2 ^ H := by + apply max_le Nat.one_le_two_pow + exact hn.trans ((Nat.le_add_right N 2).trans (inputHeight_covers_length N)) + have hnupper : n ≤ 2 ^ H := (le_max_right 1 n).trans hnmax + have hlog : Nat.clog 2 n ≤ H := (Nat.clog_le_iff_le_pow (by decide : 1 < 2)).2 hnupper + have hguesses : Nat.clog 2 n + 1 ≤ 2 ^ H := by + have hself := Nat.lt_pow_self (by decide : 1 < 2) (n := H) + omega + have hnodes : coarseInternalNodes B (computedCoarseDepth N n) ≤ 2 ^ (2 * H) := by + have hcount := coarseInternalNodes_add_one_le_pow B (computedCoarseDepth N n) hBtwo + have hpower := intervalTreeDepth_power_le B n hBtwo + have hproduct : B * max 1 n ≤ 2 ^ H * 2 ^ H := Nat.mul_le_mul hBupper hnmax + rw [← pow_add] at hproduct + change B ^ computedCoarseDepth N n ≤ B * max 1 n at hpower + have hsum : H + H = 2 * H := by omega + rw [hsum] at hproduct + omega + have hguessPower : 2 ^ Nat.clog 2 n ≤ 2 ^ H := Nat.pow_le_pow_right (by decide : 0 < 2) hlog + have hshift : 4 * (2 * 2 ^ Nat.clog 2 n + 1) ≤ 2 ^ (H + 4) := by + have hone := Nat.one_le_two_pow (n := H) + rw [pow_add] + norm_num only [show (2 : ℕ) ^ 4 = 16 by norm_num] + nlinarith + have hproduct := Nat.mul_le_mul (Nat.mul_le_mul hguesses hnodes) hshift + apply hproduct.trans_eq + rw [← pow_add, ← pow_add] + congr 1 + omega + +theorem computed_coarse_tail_exponent (N : ℕ) : + -(initialLambda N : ℝ) * initialThresholdQ N / 12 = -(inputHeight N : ℝ) ^ 3 / 768 := by + have hH : (inputHeight N : ℝ) ≠ 0 := by + have hpos : 0 < inputHeight N := by unfold inputHeight; positivity + exact_mod_cast hpos.ne' + simp only [initialLambda, initialThresholdQ, Rat.cast_div, Rat.cast_mul, + Rat.cast_one, Rat.cast_ofNat, Rat.cast_natCast, Rat.cast_pow] + field_simp [hH] + ring + +theorem coarse_global_exponential_failure (H : ℕ) (hH : 256 ≤ H) : + (2 : ℝ) ^ (10 * H) * Real.exp (-(H : ℝ) ^ 3 / 768) < 1 / 100 := by + have hHr : (256 : ℝ) ≤ H := by exact_mod_cast hH + have htwo : (2 : ℝ) ≤ Real.exp 1 := by + have h := Real.add_one_le_exp (1 : ℝ) + norm_num at h + exact h + have hpower := pow_le_pow_left₀ (by norm_num : (0 : ℝ) ≤ 2) htwo (10 * H) + rw [← Real.exp_nat_mul, mul_one] at hpower + have hexponent : (10 * H : ℕ) - (H : ℝ) ^ 3 / 768 ≤ -7 := by + have hsq : (65536 : ℝ) ≤ (H : ℝ) ^ 2 := by nlinarith + have hcube := mul_le_mul_of_nonneg_right hsq (show (0 : ℝ) ≤ H by positivity) + push_cast + nlinarith + have hseven : (128 : ℝ) ≤ Real.exp 7 := by + have h := pow_le_pow_left₀ (by norm_num : (0 : ℝ) ≤ 2) htwo 7 + simpa only [← Real.exp_nat_mul, Nat.cast_ofNat, mul_one, + show (2 : ℝ) ^ 7 = 128 by norm_num] using h + have hnegative : Real.exp (-7) ≤ (1 : ℝ) / 128 := by + rw [Real.exp_neg, ← one_div] + exact div_le_div_of_nonneg_left (by norm_num) (by norm_num) hseven + calc + _ ≤ Real.exp (10 * H : ℕ) * Real.exp (-(H : ℝ) ^ 3 / 768) := + mul_le_mul_of_nonneg_right hpower (Real.exp_nonneg _) + _ = Real.exp ((10 * H : ℕ) - (H : ℝ) ^ 3 / 768) := by rw [← Real.exp_add]; congr 1; ring + _ ≤ Real.exp (-7) := Real.exp_le_exp.mpr hexponent + _ ≤ 1 / 128 := hnegative + _ < 1 / 100 := by norm_num + +/-- Symbolic recursion indices prevent irrelevant normalization of integer +logarithms in dependent draw types. The equalities retain the exact computed +algorithm, rather than replacing it with a larger or assumed seed contract. -/ +theorem computed_initialAccuracy_failure (N B D : ℕ) + [NeZero B] [MeasurableSpace (Fin B)] [MeasurableSingletonClass (Fin B)] + (hB : B = (integerParameters N).B) + {α : Type*} [DecidableEq α] (x y : List α) + (hD : D = computedCoarseDepth N (coarseEntryWidth x y)) + (hN : 0 < N) (hwidth : coarseEntryWidth x y ≤ N) + (hell : 200 ≤ inputSmallLog N) + (bernstein : FiniteBernsteinInput (Measure.pi fun _ : Fin B => + (PMF.uniformOfFintype (Fin B)).toMeasure)) : + (coarseInitialMeasure B D (coarseEntryWidth x y)).real + {draws | ¬ CoarseInitialAccuracyEvent B D (initialThresholdQ N) (initialLambda N) x y draws} ≤ + (2 : ℝ) ^ (4 * inputHeight N + 4) * Real.exp (-(inputHeight N : ℝ) ^ 3 / 768) := by + have hH : (256 : ℚ) ≤ inputHeight N := by exact_mod_cast computed_coarse_height_large N hN hell + have hQ : (2 : ℚ) ≤ initialThresholdQ N := by + unfold initialThresholdQ + exact (by norm_num : (2 : ℚ) ≤ 256 ^ 4).trans + (pow_le_pow_left₀ (by norm_num : (0 : ℚ) ≤ 256) hH 4) + have hden : (0 : ℚ) < 64 * inputHeight N := + mul_pos (by norm_num) (lt_of_lt_of_le (by norm_num : (0 : ℚ) < 256) hH) + have hlam : (0 : ℚ) < initialLambda N := by + unfold initialLambda + exact div_pos (by norm_num) hden + have hlamone : initialLambda N < 1 := by + unfold initialLambda + apply (div_lt_one hden).2 + linarith only [hH] + have hfailure := coarseInitialAccuracyEvent_failure (B := B) (D := D) + (initialThresholdQ N) (initialLambda N) x y hQ hlam hlamone bernstein + rw [computed_coarse_tail_exponent] at hfailure + have hcount : coarseEntryTailCount B D (coarseEntryWidth x y) ≤ + 2 ^ (4 * inputHeight N + 4) := by + rw [hB, hD] + exact computed_coarseEntryTailCount N (coarseEntryWidth x y) hN hwidth hell + have hcountReal : (coarseEntryTailCount B D (coarseEntryWidth x y) : ℝ) ≤ + (2 : ℝ) ^ (4 * inputHeight N + 4) := by exact_mod_cast hcount + have hfailureCount : (coarseInitialMeasure B D (coarseEntryWidth x y)).real + {draws | ¬ CoarseInitialAccuracyEvent B D + (initialThresholdQ N) (initialLambda N) x y draws} ≤ + (coarseEntryTailCount B D (coarseEntryWidth x y) : ℝ) * + Real.exp (-(inputHeight N : ℝ) ^ 3 / 768) := by + convert hfailure using 1 + simp only [coarseEntryTailCount, Nat.cast_mul, Nat.cast_ofNat] + ring + exact hfailureCount.trans (mul_le_mul_of_nonneg_right hcountReal (Real.exp_nonneg _)) + + + + + +instance coarseFullSeedMeasure_isProbabilityMeasure (B : ℕ) [NeZero B] + {I α : Type*} [Fintype I] (depth : I → ℕ) (x y : I → List α) + [MeasurableSpace (Fin B)] [MeasurableSingletonClass (Fin B)] : + IsProbabilityMeasure (coarseFullSeedMeasure B depth x y) := by + unfold coarseFullSeedMeasure + infer_instance + +noncomputable def CoarseFullSeedAccuracyEvent (N B : ℕ) {I α : Type*} [DecidableEq α] + (depth : I → ℕ) (x y : I → List α) (draws : CoarseFullSeedDraws B depth x y) : Prop := + ∀ i, CoarseInitialAccuracyEvent B (depth i) + (initialThresholdQ N) (initialLambda N) (x i) (y i) (draws i) + +/-- The full finite table law fails with probability below one percent. +The cardinal bound is supplied by the actual labeled state-domain count. -/ +theorem computed_fullSeed_failure (N B : ℕ) [NeZero B] + [MeasurableSpace (Fin B)] [MeasurableSingletonClass (Fin B)] + {I α : Type*} [Fintype I] [DecidableEq α] (depth : I → ℕ) + (x y : I → List α) (hB : B = (integerParameters N).B) + (hD : ∀ i, depth i = computedCoarseDepth N (coarseEntryWidth (x i) (y i))) + (hN : 0 < N) (hwidth : ∀ i, coarseEntryWidth (x i) (y i) ≤ N) + (hcount : Fintype.card I ≤ 2 ^ (5 * inputHeight N)) + (hell : 200 ≤ inputSmallLog N) + (bernstein : FiniteBernsteinInput (Measure.pi fun _ : Fin B => + (PMF.uniformOfFintype (Fin B)).toMeasure)) : + (coarseFullSeedMeasure B depth x y).real + {draws | ¬ CoarseFullSeedAccuracyEvent N B depth x y draws} < 1 / 100 := by + classical + let μ := coarseFullSeedMeasure B depth x y + let ν (i : I) := coarseInitialMeasure B (depth i) (coarseEntryWidth (x i) (y i)) + let bad (i : I) : Set (CoarseGuessIndex (coarseEntryWidth (x i) (y i)) → + CoarseThresholdDraws B (depth i)) := + {draws | ¬ CoarseInitialAccuracyEvent B (depth i) + (initialThresholdQ N) (initialLambda N) (x i) (y i) draws} + have hsubset : {draws | ¬ CoarseFullSeedAccuracyEvent N B depth x y draws} ⊆ + ⋃ i, {draws | draws i ∈ bad i} := by + intro draws hdraws + obtain ⟨i, hi⟩ := not_forall.mp hdraws + exact Set.mem_iUnion.mpr ⟨i, hi⟩ + have hprojection (i : I) : μ.real {draws | draws i ∈ bad i} = (ν i).real (bad i) := by + have hmap := (measurePreserving_eval (μ := ν) i).map_eq + have hpreimage := Measure.map_apply (μ := Measure.pi ν) (measurable_pi_apply i) + (Set.toFinite (bad i)).measurableSet + rw [hmap] at hpreimage + exact congrArg ENNReal.toReal hpreimage.symm + have hpoint (i : I) : μ.real {draws | draws i ∈ bad i} ≤ + (2 : ℝ) ^ (4 * inputHeight N + 4) * Real.exp (-(inputHeight N : ℝ) ^ 3 / 768) := by + rw [hprojection] + exact computed_initialAccuracy_failure N B (depth i) hB (x i) (y i) (hD i) + hN (hwidth i) hell bernstein + have hH : 256 ≤ inputHeight N := computed_coarse_height_large N hN hell + have htotal : Fintype.card I * 2 ^ (4 * inputHeight N + 4) ≤ 2 ^ (10 * inputHeight N) := by + calc + _ ≤ 2 ^ (5 * inputHeight N) * 2 ^ (4 * inputHeight N + 4) := Nat.mul_le_mul_right _ hcount + _ = 2 ^ (9 * inputHeight N + 4) := by rw [← pow_add]; congr 1; omega + _ ≤ _ := Nat.pow_le_pow_right (by decide : 0 < 2) (by omega) + have htotalReal : (Fintype.card I : ℝ) * (2 : ℝ) ^ (4 * inputHeight N + 4) ≤ + (2 : ℝ) ^ (10 * inputHeight N) := by exact_mod_cast htotal + calc + _ ≤ μ.real (⋃ i, {draws | draws i ∈ bad i}) := measureReal_mono hsubset + _ ≤ ∑ i, μ.real {draws | draws i ∈ bad i} := measureReal_iUnion_fintype_le _ + _ ≤ ∑ _ : I, (2 : ℝ) ^ (4 * inputHeight N + 4) * Real.exp (-(inputHeight N : ℝ) ^ 3 / 768) := + sum_le_sum (fun i _ => hpoint i) + _ = ((Fintype.card I : ℝ) * (2 : ℝ) ^ (4 * inputHeight N + 4)) * + Real.exp (-(inputHeight N : ℝ) ^ 3 / 768) := by simp only [sum_const, card_univ, nsmul_eq_mul, mul_assoc] + _ ≤ (2 : ℝ) ^ (10 * inputHeight N) * Real.exp (-(inputHeight N : ℝ) ^ 3 / 768) := + mul_le_mul_of_nonneg_right htotalReal (Real.exp_nonneg _) + _ < 1 / 100 := coarse_global_exponential_failure _ hH + +/-- The executable full integer table uses exactly the supplied recursion +indices. Computed-parameter equalities appear only in its correctness proofs. -/ + + +theorem computed_fullSeedTable_pathwise (N B : ℕ) {I α : Type*} [DecidableEq α] + (depth : I → ℕ) (x y : I → List α) (hB : B = (integerParameters N).B) + (hD : ∀ i, depth i = computedCoarseDepth N (coarseEntryWidth (x i) (y i))) + (hN : 0 < N) (hwidth : ∀ i, coarseEntryWidth (x i) (y i) ≤ N) + (hell : 200 ≤ inputSmallLog N) (draws : CoarseFullSeedDraws B depth x y) + (hevent : CoarseFullSeedAccuracyEvent N B depth x y draws) : + ∀ i, EditDistortion.edit (x i) (y i) ≤ coarseFullSeedTable N B depth x y draws i ∧ + coarseFullSeedTable N B depth x y draws i ≤ + (integerParameters N).initialFactor * EditDistortion.edit (x i) (y i) := by + intro i + exact computed_initialSeed_bounds N B (depth i) (x i) (y i) hB (hD i) + hN (hwidth i) hell (draws i) (hevent i) + +/-- Every actual table value is clamped, and all zero-cost entries remain +zero even on executions outside the simultaneous accuracy event. -/ +theorem computed_fullSeedTable_range_zero (N B : ℕ) {I α : Type*} [DecidableEq α] + (depth : I → ℕ) (x y : I → List α) (draws : CoarseFullSeedDraws B depth x y) : + ∀ i, coarseFullSeedTable N B depth x y draws i ≤ N ∧ + (EditDistortion.edit (x i) (y i) = 0 → coarseFullSeedTable N B depth x y draws i = 0) := by + intro i + exact ⟨coarseInitialValue_le_length _ _ _ _ _ _ _ _, + coarseInitialValue_zero _ _ _ _ _ _ _ _⟩ + +/-- Simultaneous finite table accuracy under the scalar Bernstein hypothesis. -/ +theorem computed_fullSeedTable_accuracy (N B : ℕ) [NeZero B] + [MeasurableSpace (Fin B)] [MeasurableSingletonClass (Fin B)] + {I α : Type*} [Fintype I] [DecidableEq α] (depth : I → ℕ) (x y : I → List α) + (hB : B = (integerParameters N).B) + (hD : ∀ i, depth i = computedCoarseDepth N (coarseEntryWidth (x i) (y i))) + (hN : 0 < N) (hwidth : ∀ i, coarseEntryWidth (x i) (y i) ≤ N) + (hcount : Fintype.card I ≤ 2 ^ (5 * inputHeight N)) + (hell : 200 ≤ inputSmallLog N) + (bernstein : FiniteBernsteinInput (Measure.pi fun _ : Fin B => + (PMF.uniformOfFintype (Fin B)).toMeasure)) : + (coarseFullSeedMeasure B depth x y).real {draws | ¬ ∀ i, + EditDistortion.edit (x i) (y i) ≤ coarseFullSeedTable N B depth x y draws i ∧ + coarseFullSeedTable N B depth x y draws i ≤ + (integerParameters N).initialFactor * EditDistortion.edit (x i) (y i)} < 1 / 100 := by + have hsubset : {draws | ¬ ∀ i, + EditDistortion.edit (x i) (y i) ≤ coarseFullSeedTable N B depth x y draws i ∧ + coarseFullSeedTable N B depth x y draws i ≤ + (integerParameters N).initialFactor * EditDistortion.edit (x i) (y i)} ⊆ + {draws | ¬ CoarseFullSeedAccuracyEvent N B depth x y draws} := by + intro draws hdraws hevent + exact hdraws (computed_fullSeedTable_pathwise N B depth x y hB hD hN hwidth hell draws hevent) + exact (measureReal_mono hsubset).trans_lt + (computed_fullSeed_failure N B depth x y hB hD hN hwidth hcount hell bernstein) + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseGridArithmetic.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseGridArithmetic.lean new file mode 100644 index 0000000000000000000000000000000000000000..447094251153d4d1e929be8ff19e7ec48c9e9d22 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseGridArithmetic.lean @@ -0,0 +1,118 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryFixedDenominator +import OAI.Combinatorics.EditApproximation.Binary.BinaryFiniteLoops +import OAI.Combinatorics.EditApproximation.Coarse.CoarsePrecision +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Exact arithmetic on a shared coarse-array denominator. Addition touches +only the signed numerators and keeps the denominator, preventing denominator +growth across the child-array sums. All counters run Boolean primitives. -/ + +namespace EditApproximation +namespace BinaryFraction + +/-- Store an integer on the common denominator by a literal bit product. -/ + + + theorem coarseGridNatWithWork_value (denominator : List Bool) + (hden : 0 < bitWordValue denominator) (n : ℕ) : + (coarseGridNatWithWork denominator hden n).1.value = n := by + unfold coarseGridNatWithWork + dsimp only + rw [← representation_value, canonicalizeWithWork_representation, representation_value] + simp only [value, SignedBinary.value, signedMagnitude, Bool.false_eq_true, ↓reduceIte, + bitMulWithWork_value, bitWordValue_bits] + push_cast + exact mul_div_cancel_right₀ _ (by exact_mod_cast hden.ne') + + theorem coarseGridNatWithWork_den (denominator : List Bool) + (hden : 0 < bitWordValue denominator) (n : ℕ) : + (coarseGridNatWithWork denominator hden n).1.representation.den = + bitWordValue denominator := by + unfold coarseGridNatWithWork + dsimp only + rw [canonicalizeWithWork_representation] + rfl + + theorem coarseGridNatWithWork_cost (denominator : List Bool) + (hden : 0 < bitWordValue denominator) (n B : ℕ) + (hn : Nat.size n ≤ B) (hd : denominator.length ≤ B) : + (coarseGridNatWithWork denominator hden n).2 ≤ 100 * (B + 1) ^ 2 := by + have hc := bitMulWithWork_cost n.bits denominator + have hl := bitMulWithWork_length n.bits denominator + have hnb : n.bits.length ≤ B := by simpa only [← Nat.size_eq_bits_len] using hn + have hw : (⟨⟨false, (bitMulWithWork n.bits denominator).1⟩, denominator, + hden⟩ : BinaryFraction).width ≤ 3 * B + 1 := by + change max (bitMulWithWork n.bits denominator).1.length denominator.length ≤ _ + apply max_le <;> omega + have ht := canonicalizeWithWork_cost + (⟨⟨false, (bitMulWithWork n.bits denominator).1⟩, denominator, hden⟩ : BinaryFraction) + have hp : (bitMulWithWork n.bits denominator).2 ≤ 40 * (B + 1) ^ 2 := by + apply hc.trans + have hm := Nat.mul_le_mul (show n.bits.length + 1 ≤ B + 1 by omega) + (show n.bits.length + denominator.length + 1 ≤ 2 * (B + 1) by omega) + nlinarith only [hm] + change (bitMulWithWork n.bits denominator).2 + _ + 3 ≤ _ + nlinarith only [hp, ht, hw, Nat.zero_le B] + +/-- Add two stored cells after their denominators have been made identical. -/ + + + theorem coarseGridAddWithWork_value (a b : BinaryFraction) + (hden : bitWordValue a.denominator = bitWordValue b.denominator) : + (coarseGridAddWithWork a b).1.value = a.value + b.value := by + unfold coarseGridAddWithWork + dsimp only + rw [← representation_value, canonicalizeWithWork_representation, representation_value] + simp only [value, SignedBinary.addWithWork_value, Int.cast_add, ← hden] + ring + + theorem coarseGridAddWithWork_den (a b : BinaryFraction) : + (coarseGridAddWithWork a b).1.representation.den = a.representation.den := by + unfold coarseGridAddWithWork + dsimp only + rw [canonicalizeWithWork_representation] + rfl + + theorem coarseGridAddWithWork_cost (a b : BinaryFraction) (B : ℕ) + (ha : a.width ≤ B) (hb : b.width ≤ B) : + (coarseGridAddWithWork a b).2 ≤ 100 * (B + 1) := by + have han : a.numerator.bits.length ≤ B := (le_max_left _ _).trans ha + have hbn : b.numerator.bits.length ≤ B := (le_max_left _ _).trans hb + have had : a.denominator.length ≤ B := (le_max_right _ _).trans ha + have hc := SignedBinary.addWithWork_cost a.numerator b.numerator + have hl := SignedBinary.addWithWork_length a.numerator b.numerator + have hw : (⟨(a.numerator.addWithWork b.numerator).1, a.denominator, + a.denominator_pos⟩ : BinaryFraction).width ≤ B + 1 := by + change max (a.numerator.addWithWork b.numerator).1.bits.length a.denominator.length ≤ _ + apply max_le <;> omega + have ht := canonicalizeWithWork_cost + (⟨(a.numerator.addWithWork b.numerator).1, a.denominator, a.denominator_pos⟩ : BinaryFraction) + change (a.numerator.addWithWork b.numerator).2 + _ + 3 ≤ _ + omega + + theorem coarseGridAddWithWork_width (a b : BinaryFraction) (V B : ℕ) + (hden : bitWordValue a.denominator = bitWordValue b.denominator) + (hvalue : |a.value + b.value| ≤ V) (hbits : a.denominator.length ≤ B) : + (coarseGridAddWithWork a b).1.width ≤ Nat.size V + 2 * B + 1 := by + let answer := (coarseGridAddWithWork a b).1 + have hv : |answer.representation.value| ≤ V := by + rw [representation_value] + exact (coarseGridAddWithWork_value a b hden) ▸ hvalue + have hd : Nat.size answer.representation.den ≤ B := by + rw [coarseGridAddWithWork_den] + exact (Nat.size_le.mpr (bitWordValue_lt_pow_length a.denominator)).trans hbits + have hs := UnreducedRational.storageBits_le answer.representation V B hv hd + have hw : answer.width ≤ answer.representation.storageBits := by + unfold answer coarseGridAddWithWork + dsimp only + rw [canonicalizeWithWork_representation] + exact canonicalizeWithWork_width_le_storageBits _ + exact hw.trans hs + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseGridInvariant.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseGridInvariant.lean new file mode 100644 index 0000000000000000000000000000000000000000..3a313ebe5e256c20267ed8c67d839e79fb62d911 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseGridInvariant.lean @@ -0,0 +1,72 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarsePrecision +import OAI.Combinatorics.EditApproximation.Coarse.CoarseGlobalSeed + +namespace OAI + +namespace EditApproximation + +/-- One descended allowance acquires only one factor of the fixed root +base in its denominator. This includes the literal sampled child label. -/ + theorem coarseChildAllowance_grid (B q L j : ℕ) (allowance : ℚ) (draw : Fin B) + (hB : 0 < B) (hq : 0 < q) (hL : 0 < L) + (ha : allowance.den ∣ (L * B * q) ^ j) : + ((1 / (L : ℚ)) * coarseChildThreshold B q allowance draw).den ∣ + (L * B * q) ^ (j + 1) := by + have ht : (coarseChildThreshold B q allowance draw).den ∣ + (L * B * q) ^ j * (B * q) := by + simpa only [coarseChildThreshold, Nat.cast_mul] using + coarse_rat_div_nat_den_dvd (allowance * ((draw.val + 1 : ℕ) : ℚ)) (B * q) ((L * B * q) ^ j) + (Nat.mul_pos hB hq) (coarse_rat_mul_nat_den_dvd allowance (draw.val + 1) _ ha) + have heq : (1 / (L : ℚ)) * coarseChildThreshold B q allowance draw = + coarseChildThreshold B q allowance draw / L := by ring + rw [heq] + convert coarse_rat_div_nat_den_dvd _ L _ hL ht using 1 + rw [pow_succ] + ring + +/-- Every descendant array lives on the same denominator constructed for +its root; it is unnecessary to normalize any array sum by a gcd. -/ + theorem coarseDescendant_grid {B d : ℕ} {α : Type*} [DecidableEq α] + (k q L j : ℕ) (frame : List (Option α)) (tree : CoarseSourceTree B α d) + (draws : CoarseThresholdDraws B d) (allowance : ℚ) + (hB : 0 < B) (hq : 0 < q) (hL : 0 < L) + (ha : allowance.den ∣ (L * B * q) ^ j) (start : ℕ) (shift : Fin (2 * k + 1)) : + (coarseThresholdEstimate k q (1 / L) frame tree draws allowance start shift).den ∣ + coarseCommonDenominator 1 q L B (j + d) := by + have h := coarseThresholdEstimate_den_dvd k q L frame tree draws allowance + ((L * B * q) ^ j) hB hq hL (pow_pos (by positivity) _) ha start shift + convert h using 1 + simp only [coarseCommonDenominator, one_mul, pow_add] + ring + +/-- Uniform root magnitude for every descendant and pruning outcome. -/ + theorem coarseDescendant_magnitude {B d : ℕ} {α : Type*} [DecidableEq α] + (k q L D n : ℕ) (frame : List (Option α)) (tree : CoarseSourceTree B α d) + (draws : CoarseThresholdDraws B d) (allowance : ℚ) + (hB : 2 ≤ B) (hq : 0 < q) (hL : 0 < L) (hd : d ≤ D) + (hn : tree.word.length ≤ n) (ha : 0 ≤ allowance) (hak : allowance ≤ k) + (start : ℕ) (shift : Fin (2 * k + 1)) : + |coarseThresholdEstimate k q (1 / L) frame tree draws allowance start shift| ≤ + ((n + B * k * B ^ D : ℕ) : ℚ) := by + have hqQ : (1 : ℚ) ≤ q := by exact_mod_cast hq + have hLQ : (1 : ℚ) ≤ L := by exact_mod_cast hL + have hLpos : (0 : ℚ) < L := by exact_mod_cast hL + have hnode : coarseInternalNodes B d ≤ B ^ D := + (Nat.le_of_succ_le (coarseInternalNodes_add_one_le_pow B d hB)).trans + (Nat.pow_le_pow_right (by omega) hd) + have hm := coarseThresholdEstimate_magnitude k q (1 / L) frame tree draws allowance hqQ + (by positivity) ((div_le_one hLpos).mpr hLQ) ha start shift + rw [abs_of_nonneg (coarseThresholdEstimate_nonneg k q (1 / L) frame tree draws allowance start shift + (by positivity) ha)] + apply hm.trans + have hs : (B : ℚ) * allowance / q ≤ B * k := by + exact (div_le_self (by positivity) hqQ).trans + (mul_le_mul_of_nonneg_left hak (by positivity)) + have hh := mul_le_mul hs (by exact_mod_cast hnode : (coarseInternalNodes B d : ℚ) ≤ B ^ D) + (by positivity) (by positivity : (0 : ℚ) ≤ B * k) + push_cast + exact add_le_add (by exact_mod_cast hn) hh + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseGridTransfers.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseGridTransfers.lean new file mode 100644 index 0000000000000000000000000000000000000000..037eb241be7deb9d6926d0212085f697a6434026 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseGridTransfers.lean @@ -0,0 +1,41 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseGridInvariant + +namespace OAI + +namespace EditApproximation + + theorem coarseScale_root_grid (B q L j d : ℕ) (allowance : ℚ) (hq : 0 < q) + (ha : allowance.den ∣ (L * B * q) ^ j) : + (allowance / q).den ∣ coarseCommonDenominator 1 q L B (j + d) := by + apply (coarse_rat_div_nat_den_dvd allowance q _ hq ha).trans + refine ⟨(L * B * q) ^ d, ?_⟩ + simp only [coarseCommonDenominator, one_mul, pow_add] + ring + + theorem coarseThreshold_root_grid (B q L j d : ℕ) (allowance : ℚ) (draw : Fin B) + (hB : 0 < B) (hq : 0 < q) + (ha : allowance.den ∣ (L * B * q) ^ j) : + (coarseChildThreshold B q allowance draw).den ∣ + coarseCommonDenominator 1 q L B (j + (d + 1)) := by + have ht : (coarseChildThreshold B q allowance draw).den ∣ (L * B * q) ^ j * (B * q) := by + simpa only [coarseChildThreshold, Nat.cast_mul] using + coarse_rat_div_nat_den_dvd (allowance * ((draw.val + 1 : ℕ) : ℚ)) (B * q) ((L * B * q) ^ j) + (Nat.mul_pos hB hq) (coarse_rat_mul_nat_den_dvd allowance (draw.val + 1) _ ha) + apply ht.trans + refine ⟨q * L * (L * B * q) ^ d, ?_⟩ + simp only [coarseCommonDenominator, one_mul, pow_add, pow_succ] + ring + + theorem coarseChildAllowance_root_grid (B q L j d : ℕ) (allowance : ℚ) (draw : Fin B) + (hB : 0 < B) (hq : 0 < q) (hL : 0 < L) + (ha : allowance.den ∣ (L * B * q) ^ j) : + ((1 / (L : ℚ)) * coarseChildThreshold B q allowance draw).den ∣ + coarseCommonDenominator 1 q L B (j + (d + 1)) := by + apply (coarseChildAllowance_grid B q L j allowance draw hB hq hL ha).trans + refine ⟨q * (L * B * q) ^ d, ?_⟩ + simp only [coarseCommonDenominator, one_mul, pow_add, pow_succ] + ring + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseHistoryBound.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseHistoryBound.lean new file mode 100644 index 0000000000000000000000000000000000000000..8fdbdd2ccf4565ac2d63efb5a6fd27952f7265f5 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseHistoryBound.lean @@ -0,0 +1,138 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseArrayHistory + +namespace OAI + +namespace EditApproximation +namespace BinaryFraction + +private theorem history_step_bound (A B k : ℕ) (hB : 0 < B) : + (1 + (2 * k + 1) * (2 * A + 3)) + + 4 * (1 + (2 * k + 1) * (2 * A + 3)) * B ≤ + (32 * (A + 1)) * (B * (2 * k + 1) + 1) := by + let F := 1 + (2 * k + 1) * (2 * A + 3) + have hf : F ≤ 4 * (A + 1) * (2 * k + 1) := by + dsimp only [F] + nlinarith only [Nat.zero_le (A * k), Nat.zero_le A, Nat.zero_le k] + have hn : 2 * k + 1 ≤ B * (2 * k + 1) := Nat.le_mul_of_pos_left _ hB + have hm := Nat.mul_le_mul_left (4 * (A + 1)) hn + change F + 4 * F * B ≤ _ + calc + _ ≤ 4 * (A + 1) * (2 * k + 1) + + 4 * (4 * (A + 1) * (2 * k + 1)) * B := by + exact Nat.add_le_add hf (Nat.mul_le_mul_right B (Nat.mul_le_mul_left 4 hf)) + _ ≤ 4 * (A + 1) * (B * (2 * k + 1)) + + 4 * (4 * (A + 1) * (2 * k + 1)) * B := Nat.add_le_add_right hm _ + _ = 20 * (A + 1) * (B * (2 * k + 1)) := by ring + _ ≤ (32 * (A + 1)) * (B * (2 * k + 1) + 1) := by gcongr <;> omega + +theorem coarseBinaryArrayHistory_bound {B d : ℕ} {α : Type*} [DecidableEq α] + (k q L N R D A : ℕ) (frame : List (Option α)) (two : BinaryFraction) + (tree : CoarseSourceTree B α d) (draws : CoarseThresholdDraws B d) + (hB : 0 < B) (hq : 0 < q) (hL : 0 < L) (htwo : two.value = 2) + (htw : two.width ≤ A) (hd : Nat.size two.representation.den ≤ D) + (hroot : two.representation.den = coarseCommonDenominator 1 q L B R) + (hBbits : Nat.size B + 2 ≤ A) (hqbits : Nat.size q + 2 ≤ A) + (hLbits : Nat.size L + 2 ≤ A) (hNbits : Nat.size N + 2 ≤ A) + (hbound : Nat.size (coarseLevelMagnitude N k B R + 2) + 2 * D + 1 ≤ A) + (j : ℕ) (hdepth : j + d = R) (allowance : BinaryFraction) (start : ℕ) + (ha : CoarseGridCell two allowance k D A) + (hpath : allowance.value.den ∣ (L * B * q) ^ j) + (hstart : start + tree.word.length ≤ N) : + coarseBinaryArrayHistory k q L frame two tree draws allowance start ≤ + (32 * (A + 1)) * coarseBinaryWeight k q L tree draws allowance := by + have hkbound : Nat.size k + 2 * D + 1 ≤ A := + (Nat.add_le_add_right (Nat.add_le_add_right (Nat.size_le_size + ((coarseLevelMagnitude_ge N k B R).trans (by omega))) _) _).trans hbound + induction tree generalizing j allowance start with + | leaf letter => + have hb := (coarseBinaryEval_bitWork k q L N R D A frame two (.leaf letter) draws + hB hq hL htwo htw hd hroot hBbits hqbits hLbits hNbits hbound + j hdepth allowance start ha hpath hstart).1 + have hs := coarseArrayStorage_le two _ _ D A _ hb + rw [coarseBinaryArrayHistory, coarseBinaryWeight] + split_ifs + · omega + · have hn : 2 * k + 1 ≤ B * (2 * k + 1) := Nat.le_mul_of_pos_left _ hB + nlinarith only [hs, hn, Nat.zero_le A, Nat.zero_le k] + | @branch d children ih => + obtain ⟨draws, below⟩ := draws + have hb := (coarseBinaryEval_bitWork k q L N R D A frame two (.branch children) (draws, below) + hB hq hL htwo htw hd hroot hBbits hqbits hLbits hNbits hbound + j hdepth allowance start ha hpath hstart).1 + have hsarray := coarseArrayStorage_le two _ _ D A _ hb + rw [coarseBinaryArrayHistory, coarseBinaryWeight] + split_ifs + · omega + · have htval (draw : Fin B) : (coarseChildThresholdWithWork B q allowance draw).1.value = + coarseChildThreshold B q allowance.value draw := by + apply coarseChildThresholdWithWork_value + rw [ha.1, hroot, ← hdepth] + exact coarseThreshold_root_grid B q L j d allowance.value draw hB hq hpath + have htgrid (draw : Fin B) : CoarseGridCell two + (coarseChildThresholdWithWork B q allowance draw).1 k D A := by + apply coarseChildThresholdWithWork_bounds two allowance B q k D A draw hq ha hd _ hkbound + rw [ha.1, hroot, ← hdepth] + exact coarseThreshold_root_grid B q L j d allowance.value draw hB hq hpath + have hscale : CoarseGridCell two (coarseChildAllowanceWithWork q allowance).1 k D A := by + apply coarseChildAllowanceWithWork_bounds two allowance q k D A hq ha hd _ hkbound + rw [ha.1, hroot, ← hdepth] + exact coarseScale_root_grid B q L j (d + 1) allowance.value hq hpath + have hstep (draw : Fin B) : + CoarseGridCell two (coarseChildAllowanceWithWork L + (coarseChildThresholdWithWork B q allowance draw).1).1 k D A ∧ + (coarseChildAllowanceWithWork L (coarseChildThresholdWithWork B q allowance draw).1).1.value.den ∣ + (L * B * q) ^ (j + 1) := by + let threshold := (coarseChildThresholdWithWork B q allowance draw).1 + have hden : (threshold.value / L).den ∣ threshold.representation.den := by + rw [htval draw, (htgrid draw).1, hroot, ← hdepth] + rw [show coarseChildThreshold B q allowance.value draw / (L : ℚ) = + (1 / (L : ℚ)) * coarseChildThreshold B q allowance.value draw by ring] + exact coarseChildAllowance_root_grid B q L j d allowance.value draw hB hq hL hpath + refine ⟨coarseChildAllowanceWithWork_bounds two threshold L k D A hL (htgrid draw) hd hden hkbound, ?_⟩ + rw [coarseChildAllowanceWithWork_value L threshold hden, htval draw] + convert coarseChildAllowance_grid B q L j allowance.value draw hB hq hL hpath using 1 + congr 1 + ring + have hchildbound : Nat.size (B * (coarseLevelMagnitude N k B d + k) + 2) + 2 * D + 1 ≤ A := by + apply le_trans _ hbound + apply Nat.add_le_add_right + apply Nat.add_le_add_right + apply Nat.size_le_size + exact (coarseLevelMagnitude_succ N k B d).trans + ((coarseLevelMagnitude_mono N k B (d + 1) R (by omega)).trans (by omega)) + have hc := coarseChildrenArrayHistory_bound k q L N (coarseLevelMagnitude N k B d) D A + (32 * (A + 1)) two allowance + (fun child => coarseBinaryEval k q L frame two child) + (fun child => coarseBinaryArrayHistory k q L frame two child) + (fun child => coarseBinaryWeight k q L child) + (List.ofFn fun i => (children i, draws i, below i)) hB (by simp) htwo htw ha.2.2.2.2 + hBbits hqbits hLbits (by omega) (fun draw => (htgrid draw).2.2.2.2) hscale hchildbound (by + intro child draw childBelow hmem s hs + obtain ⟨i, hi⟩ := List.mem_ofFn.mp hmem + cases hi + exact coarseBinaryEval_bitWork k q L N R D A frame two (children i) (below i) + hB hq hL htwo htw hd hroot hBbits hqbits hLbits hNbits hbound + (j + 1) (by omega) _ s (hstep (draws i)).1 (hstep (draws i)).2 hs) (by + intro child draw childBelow hmem s hs + obtain ⟨i, hi⟩ := List.mem_ofFn.mp hmem + cases hi + exact ih i (below i) (j + 1) (by omega) _ s (hstep (draws i)).1 (hstep (draws i)).2 hs) + start (by rwa [coarseChildrenSpan_ofFn]) + simp only [List.length_ofFn] at hc + have hstepCost := history_step_bound A B k hB + calc + _ ≤ (1 + (2 * k + 1) * (2 * A + 3)) + + ((32 * (A + 1)) * coarseBinaryChildrenWeight q L + (fun child => coarseBinaryWeight k q L child) allowance + (List.ofFn fun i => (children i, draws i, below i)) + + 4 * (1 + (2 * k + 1) * (2 * A + 3)) * B) := Nat.add_le_add hsarray hc + _ ≤ (32 * (A + 1)) * coarseBinaryChildrenWeight q L + (fun child => coarseBinaryWeight k q L child) allowance + (List.ofFn fun i => (children i, draws i, below i)) + + (32 * (A + 1)) * (B * (2 * k + 1) + 1) := by omega + _ = _ := by ring + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseIndexBudget.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseIndexBudget.lean new file mode 100644 index 0000000000000000000000000000000000000000..9555fab7fcc3563315fa2f4b82c8052baabab7e2 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseIndexBudget.lean @@ -0,0 +1,66 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseIndexedCompare +import OAI.Combinatorics.EditApproximation.Coarse.CoarseBinaryWeight + +namespace OAI + +namespace EditApproximation +namespace BinaryFraction + +def coarseIndexSpan {B : ℕ} (width : Fin B → ℕ) : List (Fin B) → ℕ + | [] => 0 + | i :: rest => width i + coarseIndexSpan width rest + +def coarseIndexWeight {B : ℕ} (q L : ℕ) (draw : Fin B → Fin B) + (weight : Fin B → BinaryFraction → ℕ) (allowance : BinaryFraction) : List (Fin B) → ℕ + | [] => 0 + | i :: rest => weight i (coarseChildAllowanceWithWork L + (coarseChildThresholdWithWork B q allowance (draw i)).1).1 + + coarseIndexWeight q L draw weight allowance rest + +theorem coarseIndexSpan_eq {B d : ℕ} {α : Type*} (width : Fin B → ℕ) + (children : Fin B → CoarseSourceTree B α d) (draw : Fin B → Fin B) + (below : Fin B → CoarseThresholdDraws B d) (hw : ∀ i, width i = (children i).word.length) + (indices : List (Fin B)) : + coarseIndexSpan width indices = + coarseChildrenSpan (indices.map fun i => (children i, draw i, below i)) := by + induction indices with + | nil => rfl + | cons i rest ih => simp only [coarseIndexSpan, List.map_cons, coarseChildrenSpan, hw, ih] + +theorem coarseIndexWeight_eq {B d : ℕ} {α : Type*} (k q L : ℕ) + (children : Fin B → CoarseSourceTree B α d) (draw : Fin B → Fin B) + (below : Fin B → CoarseThresholdDraws B d) (allowance : BinaryFraction) (indices : List (Fin B)) : + coarseIndexWeight q L draw (fun i => coarseBinaryWeight k q L (children i) (below i)) allowance indices = + coarseBinaryChildrenWeight q L (fun child => coarseBinaryWeight k q L child) allowance + (indices.map fun i => (children i, draw i, below i)) := by + induction indices with + | nil => rfl + | cons i rest ih => simp only [coarseIndexWeight, List.map_cons, coarseBinaryChildrenWeight, ih] + +theorem coarseIndexAdditionalWork_bound {B : ℕ} (q L N C K : ℕ) + (width : Fin B → ℕ) (draw : Fin B → Fin B) + (extra : Fin B → BinaryFraction → ℕ → ℕ) (weight : Fin B → BinaryFraction → ℕ) + (allowance : BinaryFraction) (indices : List (Fin B)) + (hc : ∀ i ∈ indices, ∀ s, s + width i ≤ N → + extra i (coarseChildAllowanceWithWork L + (coarseChildThresholdWithWork B q allowance (draw i)).1).1 s ≤ + C * weight i (coarseChildAllowanceWithWork L + (coarseChildThresholdWithWork B q allowance (draw i)).1).1 + K) + (start : ℕ) (hstart : start + coarseIndexSpan width indices ≤ N) : + coarseIndexAdditionalWork q L width draw extra allowance indices start ≤ + C * coarseIndexWeight q L draw weight allowance indices + K * indices.length := by + induction indices generalizing start with + | nil => simp only [coarseIndexAdditionalWork, coarseIndexWeight, List.length_nil, + Nat.mul_zero, Nat.zero_add, le_refl] + | cons i rest ih => + have hs : start + (width i + coarseIndexSpan width rest) ≤ N := hstart + have hi := hc i List.mem_cons_self start (by omega) + have hr := ih (fun j hj => hc j (List.mem_cons_of_mem i hj)) (start + width i) (by omega) + simp only [coarseIndexAdditionalWork, coarseIndexWeight, List.length_cons, + Nat.mul_add, Nat.mul_one] + omega + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseIndexedAllocation.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseIndexedAllocation.lean new file mode 100644 index 0000000000000000000000000000000000000000..7be2a8c564423d1a243bb129c5d8cfe6a94259ed --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseIndexedAllocation.lean @@ -0,0 +1,147 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseAccessAllocation +import OAI.Combinatorics.EditApproximation.Coarse.CoarseChildAllocation +import OAI.Combinatorics.EditApproximation.Coarse.CoarseIndexedExecution + +namespace OAI + +namespace EditApproximation +namespace BinaryFraction + +/-- Fresh bit and list cells in the actual indexed coarse evaluator. +Input arrays and random draws are shared; virtual source trees are never +materialized. Child offsets/descriptors follow the repeated reads charged +by the executable evaluator. -/ +def coarseIndexedAllocation {B : ℕ} (k q L n : ℕ) (source target : List ℕ) + (two : BinaryFraction) : (d offset : ℕ) → CoarseThresholdDraws B d → + BinaryFraction → ℕ → ℕ + | 0, offset, _, allowance, start => + let descriptor := coarseDescriptorWithWork B 0 n offset + let size := bitWordValue descriptor.1 + let prune := leWithWork (nat size) allowance + let setup := coarseDescriptorAllocation B 0 n offset + allowance.ltAllocation (nat size) + + Nat.size size + 1 + if prune.1 then setup else + let letter := coarsePaddedReadWithWork n source offset + setup + Nat.size n + Nat.size offset + + arithmeticMapAllocation (fun shift : Fin (2 * k + 1) => + let mismatch := coarseReadShiftWithWork k n target letter.1 start shift + coarseReadShiftAllocation k n letter.1 start shift + + coarseGridNatAllocation allowance.denominator allowance.denominator_pos mismatch.1) + (List.finRange (2 * k + 1)) + 2 * (2 * k + 1) + | d + 1, offset, (draws, below), allowance, start => + let descriptor := coarseDescriptorWithWork B (d + 1) n offset + let size := bitWordValue descriptor.1 + let prune := leWithWork (nat size) allowance + let setup := coarseDescriptorAllocation B (d + 1) n offset + allowance.ltAllocation (nat size) + + Nat.size size + 1 + if prune.1 then setup else + let capacity := bitPowerWithWork B.bits d + let childOffset := fun i : Fin B => + coarseChildOffsetWithWork offset (bitWordValue capacity.1) i.val + let childSize := fun i : Fin B => + coarseDescriptorWithWork B d n (bitWordValue (childOffset i).1) + let evaluate := fun (i : Fin B) a s => + let evaluated := coarseIndexedWithWork k q L n source target two d + (bitWordValue (childOffset i).1) (below i) a s + let next := binaryNaturalAddWithWork s (bitWordValue (childSize i).1) + (evaluated.1, evaluated.2 + 3 * ((childOffset i).2 + (childSize i).2 + next.2 + 3)) + let allocation := fun (i : Fin B) a s => + coarseIndexedAllocation k q L n source target two d + (bitWordValue (childOffset i).1) (below i) a s + + 3 * (coarseChildOffsetAllocation offset (bitWordValue capacity.1) i.val + + coarseDescriptorAllocation B d n (bitWordValue (childOffset i).1) + + bitAddAllocation s.bits (bitWordValue (childSize i).1).bits false) + setup + bitPowerAllocation B.bits d + + coarseIndexChildrenAllocation q L two (fun i => bitWordValue (childSize i).1) + evaluate allocation draws allowance (List.finRange B) start + B + +theorem coarseIndexedAllocation_le_work {B : ℕ} (k q L n : ℕ) (source target : List ℕ) + (two : BinaryFraction) (d offset : ℕ) (draws : CoarseThresholdDraws B d) + (allowance : BinaryFraction) (start : ℕ) : + coarseIndexedAllocation k q L n source target two d offset draws allowance start ≤ + 2 * (coarseIndexedWithWork k q L n source target two d offset draws allowance start).2 := by + induction d generalizing offset allowance start with + | zero => + have hd := coarseDescriptorAllocation_le_work B 0 n offset + have hp := ltAllocation_le_work allowance (nat (bitWordValue (coarseDescriptorWithWork B 0 n offset).1)) + simp only [coarseIndexedAllocation, coarseIndexedWithWork] + split_ifs + · simp only [leWithWork] + omega + · have hmap := arithmeticMapAllocation_le_work + (fun shift : Fin (2 * k + 1) => + let mismatch := coarseReadShiftWithWork k n target (coarsePaddedReadWithWork n source offset).1 start shift + let value := coarseGridNatWithWork allowance.denominator allowance.denominator_pos mismatch.1 + (value.1, value.2 + mismatch.2)) + (fun shift : Fin (2 * k + 1) => + let mismatch := coarseReadShiftWithWork k n target (coarsePaddedReadWithWork n source offset).1 start shift + coarseReadShiftAllocation k n (coarsePaddedReadWithWork n source offset).1 start shift + + coarseGridNatAllocation allowance.denominator allowance.denominator_pos mismatch.1) + (List.finRange (2 * k + 1)) (by + intro shift _ + have hs := coarseReadShiftAllocation_le_work k n target + (coarsePaddedReadWithWork n source offset).1 start shift + have hg := coarseGridNatAllocation_le_work allowance.denominator allowance.denominator_pos + (coarseReadShiftWithWork k n target (coarsePaddedReadWithWork n source offset).1 start shift).1 + dsimp only + omega) + simp only [leWithWork, coarsePaddedReadWithWork] + simp only [coarsePaddedReadWithWork] at hmap + omega + | succ d ih => + obtain ⟨draw, below⟩ := draws + let capacity := bitPowerWithWork B.bits d + let childOffset := fun i : Fin B => coarseChildOffsetWithWork offset (bitWordValue capacity.1) i.val + let childSize := fun i : Fin B => coarseDescriptorWithWork B d n (bitWordValue (childOffset i).1) + let evaluate := fun (i : Fin B) a s => + let evaluated := coarseIndexedWithWork k q L n source target two d + (bitWordValue (childOffset i).1) (below i) a s + let next := binaryNaturalAddWithWork s (bitWordValue (childSize i).1) + (evaluated.1, evaluated.2 + 3 * ((childOffset i).2 + (childSize i).2 + next.2 + 3)) + let allocation := fun (i : Fin B) a s => + coarseIndexedAllocation k q L n source target two d + (bitWordValue (childOffset i).1) (below i) a s + + 3 * (coarseChildOffsetAllocation offset (bitWordValue capacity.1) i.val + + coarseDescriptorAllocation B d n (bitWordValue (childOffset i).1) + + bitAddAllocation s.bits (bitWordValue (childSize i).1).bits false) + have he : ∀ i a s, allocation i a s ≤ 2 * (evaluate i a s).2 := by + intro i a s + have hr := ih (bitWordValue (childOffset i).1) (below i) a s + have ho := coarseChildOffsetAllocation_le_work offset (bitWordValue capacity.1) i.val + have hs := coarseDescriptorAllocation_le_work B d n (bitWordValue (childOffset i).1) + have ha := bitAddAllocation_le_work s.bits (bitWordValue (childSize i).1).bits false + change bitAddAllocation s.bits (bitWordValue (childSize i).1).bits false ≤ + (binaryNaturalAddWithWork s (bitWordValue (childSize i).1)).2 at ha + change coarseChildOffsetAllocation offset (bitWordValue capacity.1) i.val ≤ (childOffset i).2 at ho + change coarseDescriptorAllocation B d n (bitWordValue (childOffset i).1) ≤ (childSize i).2 at hs + dsimp only [allocation, evaluate] + omega + have hc := coarseIndexChildrenAllocation_le_work k q L two (fun i => bitWordValue (childSize i).1) + evaluate allocation he draw allowance (List.finRange B) start + have hd := coarseDescriptorAllocation_le_work B (d + 1) n offset + have hp := ltAllocation_le_work allowance + (nat (bitWordValue (coarseDescriptorWithWork B (d + 1) n offset).1)) + have hb := bitPowerAllocation_le_work B.bits d + simp only [coarseIndexedAllocation, coarseIndexedWithWork] + split_ifs + · simp only [leWithWork] + omega + · change coarseDescriptorAllocation B (d + 1) n offset + + allowance.ltAllocation (nat (bitWordValue (coarseDescriptorWithWork B (d + 1) n offset).1)) + + Nat.size (bitWordValue (coarseDescriptorWithWork B (d + 1) n offset).1) + 1 + + bitPowerAllocation B.bits d + + coarseIndexChildrenAllocation q L two (fun i => bitWordValue (childSize i).1) + evaluate allocation draw allowance (List.finRange B) start + B ≤ + 2 * ((coarseDescriptorWithWork B (d + 1) n offset).2 + capacity.2 + + (coarseIndexChildren k q L two (fun i => bitWordValue (childSize i).1) + evaluate draw allowance (List.finRange B) start).2 + + (leWithWork (nat (bitWordValue (coarseDescriptorWithWork B (d + 1) n offset).1)) allowance).2 + + Nat.size (bitWordValue (coarseDescriptorWithWork B (d + 1) n offset).1) + B + 1) + change bitPowerAllocation B.bits d ≤ capacity.2 at hb + simp only [leWithWork] + omega + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseIndexedArrayHistory.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseIndexedArrayHistory.lean new file mode 100644 index 0000000000000000000000000000000000000000..920bb0a4f314a62c4949ec60a33c3a1eca0429bc --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseIndexedArrayHistory.lean @@ -0,0 +1,132 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseArrayHistory + +namespace OAI + +namespace EditApproximation +namespace BinaryFraction + +def coarseIndexArrayHistory {B : ℕ} (k q L : ℕ) (two : BinaryFraction) + (width : Fin B → ℕ) (evaluate : Fin B → BinaryFraction → ℕ → CoarseBinaryArray × ℕ) + (history : Fin B → BinaryFraction → ℕ → ℕ) + (draw : Fin B → Fin B) (allowance : BinaryFraction) : List (Fin B) → ℕ → ℕ + | [], _ => 0 + | i :: rest, start => + let threshold := (coarseChildThresholdWithWork B q allowance (draw i)).1 + let childAllowance := (coarseChildAllowanceWithWork L threshold).1 + let evaluated := (evaluate i childAllowance start).1 + let penalty := (coarseBinaryPenaltyWithWork two evaluated).1 + let scale := (coarseChildAllowanceWithWork q allowance).1 + let contribution := (coarseBinaryMapWithWork (coarseContributionWithWork threshold scale) penalty).1 + let remainder := (coarseIndexChildren k q L two width evaluate draw allowance rest (start + width i)).1 + let total := (coarseBinaryAddWithWork contribution remainder).1 + history i childAllowance start + + coarseIndexArrayHistory k q L two width evaluate history draw allowance rest (start + width i) + + coarseArrayStorage evaluated + coarseArrayStorage penalty + + coarseArrayStorage contribution + coarseArrayStorage total + +theorem coarseIndexArrayHistory_eq {B d : ℕ} {α : Type*} + (k q L : ℕ) (two : BinaryFraction) (width : Fin B → ℕ) + (children : Fin B → CoarseSourceTree B α d) + (evaluate : CoarseSourceTree B α d → CoarseThresholdDraws B d → BinaryFraction → ℕ → + CoarseBinaryArray × ℕ) + (history : CoarseSourceTree B α d → CoarseThresholdDraws B d → BinaryFraction → ℕ → ℕ) + (indexed : Fin B → BinaryFraction → ℕ → CoarseBinaryArray × ℕ) + (indexedHistory : Fin B → BinaryFraction → ℕ → ℕ) + (draw : Fin B → Fin B) (below : Fin B → CoarseThresholdDraws B d) + (hw : ∀ i, width i = (children i).word.length) + (he : ∀ i a s, (indexed i a s).1 = (evaluate (children i) (below i) a s).1) + (hh : ∀ i a s, indexedHistory i a s = history (children i) (below i) a s) + (allowance : BinaryFraction) (indices : List (Fin B)) (start : ℕ) : + coarseIndexArrayHistory k q L two width indexed indexedHistory draw allowance indices start = + coarseChildrenArrayHistory k q L two evaluate history allowance + (indices.map fun i => (children i, draw i, below i)) start := by + have harray (indices : List (Fin B)) (start : ℕ) : + (coarseIndexChildren k q L two width indexed draw allowance indices start).1 = + (coarseBinaryChildren k q L two evaluate allowance + (indices.map fun i => (children i, draw i, below i)) start).1 := by + calc + _ = (coarseIndexChildren k q L two width + (fun i => evaluate (children i) (below i)) draw allowance indices start).1 := + coarseIndexChildren_value_congr k q L two width draw indexed + (fun i => evaluate (children i) (below i)) he allowance indices start + _ = _ := congrArg Prod.fst (coarseIndexChildren_eq k q L two width children evaluate + (fun i => evaluate (children i) (below i)) draw below hw (fun _ _ _ => rfl) allowance indices start) + induction indices generalizing start with + | nil => rfl + | cons i rest ih => + simp only [coarseIndexArrayHistory, coarseChildrenArrayHistory, List.map_cons, he, hh, harray, hw, ih] + +/-- Every array footprint of the literal indexed recursion. Descriptor +and address words are charged separately by the indexed bit counter. -/ +def coarseIndexedArrayHistory {B : ℕ} (k q L n : ℕ) (source target : List ℕ) + (two : BinaryFraction) : (d offset : ℕ) → CoarseThresholdDraws B d → BinaryFraction → ℕ → ℕ + | 0, offset, draws, allowance, start => + if (leWithWork (nat (coarseDescriptorLength B 0 n offset)) allowance).1 then 1 else + coarseArrayStorage (coarseIndexedWithWork k q L n source target two 0 offset draws allowance start).1 + | d + 1, offset, (draws, below), allowance, start => + if (leWithWork (nat (coarseDescriptorLength B (d + 1) n offset)) allowance).1 then 1 else + coarseArrayStorage (coarseIndexedWithWork k q L n source target two (d + 1) offset + (draws, below) allowance start).1 + + coarseIndexArrayHistory k q L two + (fun i => coarseDescriptorLength B d n (offset + i.val * B ^ d)) + (fun i => coarseIndexedWithWork k q L n source target two d (offset + i.val * B ^ d) (below i)) + (fun i => coarseIndexedArrayHistory k q L n source target two d (offset + i.val * B ^ d) (below i)) + draws allowance (List.finRange B) start + +attribute [local irreducible] coarseIndexedArrayHistory coarseBinaryArrayHistory + +theorem coarseIndexedArrayHistory_eq {B : ℕ} (k q L n : ℕ) (source target : List ℕ) + (hs : source.length ≤ n) (ht : target.length ≤ n) (two : BinaryFraction) + (d offset : ℕ) (draws : CoarseThresholdDraws B d) (allowance : BinaryFraction) (start : ℕ) : + coarseIndexedArrayHistory k q L n source target two d offset draws allowance start = + coarseBinaryArrayHistory k q L (coarseTargetFrame k (coarsePadTo n target)) two + (coarseReadTree B d (fun i => coarsePaddedRead n source (offset + i))) draws allowance start := by + have hvalue (d offset : ℕ) (draws : CoarseThresholdDraws B d) (a : BinaryFraction) (s : ℕ) : + (coarseIndexedWithWork k q L n source target two d offset draws a s).1 = + (coarseBinaryEval k q L (coarseTargetFrame k (coarsePadTo n target)) two + (coarseReadTree B d (fun i => coarsePaddedRead n source (offset + i))) draws a s).1 := by + rw [coarseIndexedWithWork_value, coarseReadCore_eq k q L n source target hs ht] + induction d generalizing offset allowance start with + | zero => + have hlen := coarseReadTree_padded_length B 0 n offset source hs + rw [coarseIndexedArrayHistory] + simp only [coarseReadTree, Nat.add_zero] at hlen ⊢ + rw [coarseBinaryArrayHistory, hlen] + split_ifs + · rfl + · simpa only [coarseReadTree, Nat.add_zero] using + congrArg coarseArrayStorage (hvalue 0 offset draws allowance start) + | succ d ih => + obtain ⟨draws, below⟩ := draws + let children := fun i : Fin B => coarseReadTree B d + (fun j => coarsePaddedRead n source (offset + i.val * B ^ d + j)) + have htree : coarseReadTree B (d + 1) (fun i => coarsePaddedRead n source (offset + i)) = + CoarseSourceTree.branch children := by + simp only [coarseReadTree, children, Nat.add_assoc] + have hlen : (CoarseSourceTree.branch children).word.length = + coarseDescriptorLength B (d + 1) n offset := by + rw [← htree] + exact coarseReadTree_padded_length B (d + 1) n offset source hs + have hloop := coarseIndexArrayHistory_eq k q L two + (fun i => coarseDescriptorLength B d n (offset + i.val * B ^ d)) children + (fun child => coarseBinaryEval k q L (coarseTargetFrame k (coarsePadTo n target)) two child) + (fun child => coarseBinaryArrayHistory k q L (coarseTargetFrame k (coarsePadTo n target)) two child) + (fun i => coarseIndexedWithWork k q L n source target two d (offset + i.val * B ^ d) (below i)) + (fun i => coarseIndexedArrayHistory k q L n source target two d (offset + i.val * B ^ d) (below i)) + draws below + (fun i => (coarseReadTree_padded_length B d n (offset + i.val * B ^ d) source hs).symm) + (fun i a s => hvalue d (offset + i.val * B ^ d) (below i) a s) + (fun i a s => ih (offset + i.val * B ^ d) (below i) a s) + allowance (List.finRange B) start + rw [htree, coarseIndexedArrayHistory, coarseBinaryArrayHistory, hlen] + split_ifs + · rfl + · have hroot := congrArg coarseArrayStorage + (hvalue (d + 1) offset (draws, below) allowance start) + rw [htree] at hroot + exact congrArg₂ Nat.add hroot (by simpa only [List.ofFn_eq_map] using hloop) + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseIndexedChildren.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseIndexedChildren.lean new file mode 100644 index 0000000000000000000000000000000000000000..612e87609f0a4cf637bc830ddbc661e50ce0c0f6 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseIndexedChildren.lean @@ -0,0 +1,34 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseBinaryEvaluation +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation +namespace BinaryFraction + +/-- The executable child loop carries indices and cached subtree lengths. +In particular it never flattens a semantic source tree to obtain its length. -/ + + +theorem coarseIndexChildren_eq {B d : ℕ} {α : Type*} (k q L : ℕ) (two : BinaryFraction) + (width : Fin B → ℕ) (children : Fin B → CoarseSourceTree B α d) + (evaluate : CoarseSourceTree B α d → CoarseThresholdDraws B d → BinaryFraction → ℕ → + CoarseBinaryArray × ℕ) + (indexed : Fin B → BinaryFraction → ℕ → CoarseBinaryArray × ℕ) + (draw : Fin B → Fin B) (below : Fin B → CoarseThresholdDraws B d) + (hw : ∀ i, width i = (children i).word.length) + (he : ∀ i a start, indexed i a start = evaluate (children i) (below i) a start) + (allowance : BinaryFraction) (indices : List (Fin B)) (start : ℕ) : + coarseIndexChildren k q L two width indexed draw allowance indices start = + coarseBinaryChildren k q L two evaluate allowance + (indices.map fun i => (children i, draw i, below i)) start := by + induction indices generalizing start with + | nil => rfl + | cons i rest ih => + simp only [coarseIndexChildren, List.map_cons, coarseBinaryChildren, he, hw, ih] + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseIndexedCompare.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseIndexedCompare.lean new file mode 100644 index 0000000000000000000000000000000000000000..dd837cfeb0e77e4a865b7d286f21c28a38bb09b5 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseIndexedCompare.lean @@ -0,0 +1,71 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseIndexedChildren + +namespace OAI + +namespace EditApproximation +namespace BinaryFraction + +def coarseIndexAdditionalWork {B : ℕ} (q L : ℕ) (width : Fin B → ℕ) (draw : Fin B → Fin B) + (extra : Fin B → BinaryFraction → ℕ → ℕ) (allowance : BinaryFraction) : + List (Fin B) → ℕ → ℕ + | [], _ => 0 + | i :: rest, start => + extra i (coarseChildAllowanceWithWork L (coarseChildThresholdWithWork B q allowance (draw i)).1).1 start + + coarseIndexAdditionalWork q L width draw extra allowance rest (start + width i) + +/-- Local arithmetic depends only on returned arrays, so replacing a child +by a representation-equivalent implementation preserves every parent array. -/ +theorem coarseIndexChildren_value_congr {B : ℕ} (k q L : ℕ) (two : BinaryFraction) + (width : Fin B → ℕ) (draw : Fin B → Fin B) + (evaluate other : Fin B → BinaryFraction → ℕ → CoarseBinaryArray × ℕ) + (he : ∀ i a start, (evaluate i a start).1 = (other i a start).1) + (allowance : BinaryFraction) (indices : List (Fin B)) (start : ℕ) : + (coarseIndexChildren k q L two width evaluate draw allowance indices start).1 = + (coarseIndexChildren k q L two width other draw allowance indices start).1 := by + induction indices generalizing start with + | nil => rfl + | cons i rest ih => simp only [coarseIndexChildren, he, ih] + + +/-- Extra costs compose along the same child traversal; no child arithmetic +or array allocation is charged twice by this comparison. -/ +theorem coarseIndexChildren_cost_compare {B : ℕ} (k q L : ℕ) (two : BinaryFraction) + (width : Fin B → ℕ) (draw : Fin B → Fin B) + (evaluate other : Fin B → BinaryFraction → ℕ → CoarseBinaryArray × ℕ) + (extra : Fin B → BinaryFraction → ℕ → ℕ) + (he : ∀ i a start, (evaluate i a start).1 = (other i a start).1) + (hc : ∀ i a start, (evaluate i a start).2 ≤ (other i a start).2 + extra i a start) + (allowance : BinaryFraction) (indices : List (Fin B)) (start : ℕ) : + (coarseIndexChildren k q L two width evaluate draw allowance indices start).2 ≤ + (coarseIndexChildren k q L two width other draw allowance indices start).2 + + coarseIndexAdditionalWork q L width draw extra allowance indices start := by + induction indices generalizing start with + | nil => simp only [coarseIndexChildren, coarseIndexAdditionalWork, Nat.add_zero, le_refl] + | cons i rest ih => + let childAllowance := (coarseChildAllowanceWithWork L + (coarseChildThresholdWithWork B q allowance (draw i)).1).1 + have hi := hc i childAllowance start + have hr := ih (start + width i) + have hechild := he i childAllowance start + have herest := coarseIndexChildren_value_congr k q L two width draw evaluate other he + allowance rest (start + width i) + simp only [coarseIndexChildren, coarseIndexAdditionalWork] + dsimp only [childAllowance] at hi hechild + rw [hechild, herest] + omega + + +theorem arithmeticMapWithWork_add_cost {α β : Type*} (f : α → β × ℕ) + (extra : α → ℕ) (xs : List α) : + (arithmeticMapWithWork (fun x => ((f x).1, (f x).2 + extra x)) xs).2 = + (arithmeticMapWithWork f xs).2 + (xs.map extra).sum := by + induction xs with + | nil => rfl + | cons a xs ih => + simp only [arithmeticMapWithWork, List.map_cons, List.sum_cons, ih] + omega + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseIndexedControlSpace.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseIndexedControlSpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..dbb433ef271a824911b98767007e1f659bec0557 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseIndexedControlSpace.lean @@ -0,0 +1,157 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseAccessControlSpace +import OAI.Combinatorics.EditApproximation.Coarse.CoarseChildControlSpace +import OAI.Combinatorics.EditApproximation.Coarse.CoarseIndexedExecution + +namespace OAI + +namespace EditApproximation +namespace BinaryFraction + +/-- Conservative recursive invocation count for the indexed evaluator, +including scalar callees, index traversals and repeated descriptor reads. -/ +def coarseIndexedInvocations {B : ℕ} (k q L n : ℕ) (source target : List ℕ) + (two : BinaryFraction) : (d offset : ℕ) → CoarseThresholdDraws B d → + BinaryFraction → ℕ → ℕ + | 0, offset, _, allowance, start => + let descriptor := coarseDescriptorWithWork B 0 n offset + let size := bitWordValue descriptor.1 + let prune := leWithWork (nat size) allowance + let setup := coarseDescriptorInvocations B 0 n offset + compareInvocations allowance (nat size) + 2 + if prune.1 then setup else + let letter := coarsePaddedReadWithWork n source offset + setup + coarsePaddedReadInvocations n offset + + arithmeticMapInvocations (fun shift : Fin (2 * k + 1) => + let mismatch := coarseReadShiftWithWork k n target letter.1 start shift + coarseReadShiftInvocations k n target letter.1 start shift + + coarseGridNatInvocations allowance.denominator allowance.denominator_pos mismatch.1 + 1) + (List.finRange (2 * k + 1)) + (2 * k + 1) + 1 + | d + 1, offset, (draws, below), allowance, start => + let descriptor := coarseDescriptorWithWork B (d + 1) n offset + let size := bitWordValue descriptor.1 + let prune := leWithWork (nat size) allowance + let setup := coarseDescriptorInvocations B (d + 1) n offset + compareInvocations allowance (nat size) + 2 + if prune.1 then setup else + let capacity := bitPowerWithWork B.bits d + let childOffset := fun i : Fin B => + coarseChildOffsetWithWork offset (bitWordValue capacity.1) i.val + let childSize := fun i : Fin B => + coarseDescriptorWithWork B d n (bitWordValue (childOffset i).1) + let evaluate := fun (i : Fin B) a s => + let evaluated := coarseIndexedWithWork k q L n source target two d + (bitWordValue (childOffset i).1) (below i) a s + let next := binaryNaturalAddWithWork s (bitWordValue (childSize i).1) + (evaluated.1, evaluated.2 + 3 * ((childOffset i).2 + (childSize i).2 + next.2 + 3)) + let allocation := fun (i : Fin B) a s => + coarseIndexedInvocations k q L n source target two d + (bitWordValue (childOffset i).1) (below i) a s + + 3 * (coarseChildOffsetInvocations offset (bitWordValue capacity.1) i.val + + coarseDescriptorInvocations B d n (bitWordValue (childOffset i).1) + + bitAddInvocations s.bits (bitWordValue (childSize i).1).bits false) + 1 + setup + bitPowerInvocations B.bits d + + coarseIndexChildrenInvocations q L two (fun i => bitWordValue (childSize i).1) + evaluate allocation draws allowance (List.finRange B) start + B + 1 + +theorem arithmeticMapInvocations_with_indices_le_work {α β : Type*} (f : α → β × ℕ) + (invocations : α → ℕ) (values : List α) + (h : ∀ a ∈ values, invocations a ≤ 2 * (f a).2 + 1) : + arithmeticMapInvocations invocations values + values.length + 1 ≤ + 2 * (arithmeticMapWithWork f values).2 + 2 := by + induction values with + | nil => exact Nat.le_refl 2 + | cons a rest ih => + have hh := h a List.mem_cons_self + have ht := ih (fun b hb => h b (List.mem_cons_of_mem _ hb)) + simp only [arithmeticMapInvocations, arithmeticMapWithWork, List.length_cons] + omega + +theorem coarseIndexedInvocations_le_work {B : ℕ} (k q L n : ℕ) (source target : List ℕ) + (two : BinaryFraction) (d offset : ℕ) (draws : CoarseThresholdDraws B d) + (allowance : BinaryFraction) (start : ℕ) : + coarseIndexedInvocations k q L n source target two d offset draws allowance start ≤ + 2 * (coarseIndexedWithWork k q L n source target two d offset draws allowance start).2 + 1 := by + induction d generalizing offset allowance start with + | zero => + have hd := coarseDescriptorInvocations_le_work B 0 n offset + have hp := compareInvocations_le_work allowance (nat (bitWordValue (coarseDescriptorWithWork B 0 n offset).1)) + simp only [coarseIndexedInvocations, coarseIndexedWithWork] + split_ifs + · simp only [leWithWork] + omega + · have hmap := arithmeticMapInvocations_with_indices_le_work + (fun shift : Fin (2 * k + 1) => + let mismatch := coarseReadShiftWithWork k n target (coarsePaddedReadWithWork n source offset).1 start shift + let value := coarseGridNatWithWork allowance.denominator allowance.denominator_pos mismatch.1 + (value.1, value.2 + mismatch.2)) + (fun shift : Fin (2 * k + 1) => + let mismatch := coarseReadShiftWithWork k n target (coarsePaddedReadWithWork n source offset).1 start shift + coarseReadShiftInvocations k n target (coarsePaddedReadWithWork n source offset).1 start shift + + coarseGridNatInvocations allowance.denominator allowance.denominator_pos mismatch.1 + 1) + (List.finRange (2 * k + 1)) (by + intro shift _ + have hs := coarseReadShiftInvocations_le_work k n target + (coarsePaddedReadWithWork n source offset).1 start shift + have hg := coarseGridNatInvocations_le_work allowance.denominator allowance.denominator_pos + (coarseReadShiftWithWork k n target (coarsePaddedReadWithWork n source offset).1 start shift).1 + dsimp only + omega) + have hpadded := coarsePaddedReadInvocations_le_work n source offset + simp only [List.length_finRange] at hmap + simp only [leWithWork, coarsePaddedReadWithWork] at hpadded ⊢ + simp only [coarsePaddedReadWithWork] at hmap + omega + | succ d ih => + obtain ⟨draw, below⟩ := draws + let capacity := bitPowerWithWork B.bits d + let childOffset := fun i : Fin B => coarseChildOffsetWithWork offset (bitWordValue capacity.1) i.val + let childSize := fun i : Fin B => coarseDescriptorWithWork B d n (bitWordValue (childOffset i).1) + let evaluate := fun (i : Fin B) a s => + let evaluated := coarseIndexedWithWork k q L n source target two d + (bitWordValue (childOffset i).1) (below i) a s + let next := binaryNaturalAddWithWork s (bitWordValue (childSize i).1) + (evaluated.1, evaluated.2 + 3 * ((childOffset i).2 + (childSize i).2 + next.2 + 3)) + let allocation := fun (i : Fin B) a s => + coarseIndexedInvocations k q L n source target two d + (bitWordValue (childOffset i).1) (below i) a s + + 3 * (coarseChildOffsetInvocations offset (bitWordValue capacity.1) i.val + + coarseDescriptorInvocations B d n (bitWordValue (childOffset i).1) + + bitAddInvocations s.bits (bitWordValue (childSize i).1).bits false) + 1 + have he : ∀ i a s, allocation i a s ≤ 2 * (evaluate i a s).2 + 1 := by + intro i a s + have hr := ih (bitWordValue (childOffset i).1) (below i) a s + have ho := coarseChildOffsetInvocations_le_work offset (bitWordValue capacity.1) i.val + have hs := coarseDescriptorInvocations_le_work B d n (bitWordValue (childOffset i).1) + have ha := bitAddInvocations_le_work s.bits (bitWordValue (childSize i).1).bits false + change bitAddInvocations s.bits (bitWordValue (childSize i).1).bits false ≤ + (binaryNaturalAddWithWork s (bitWordValue (childSize i).1)).2 at ha + change coarseChildOffsetInvocations offset (bitWordValue capacity.1) i.val ≤ (childOffset i).2 at ho + change coarseDescriptorInvocations B d n (bitWordValue (childOffset i).1) ≤ (childSize i).2 at hs + dsimp only [allocation, evaluate] + omega + have hc := coarseIndexChildrenInvocations_le_work k q L two (fun i => bitWordValue (childSize i).1) + evaluate allocation he draw allowance (List.finRange B) start + have hd := coarseDescriptorInvocations_le_work B (d + 1) n offset + have hp := compareInvocations_le_work allowance + (nat (bitWordValue (coarseDescriptorWithWork B (d + 1) n offset).1)) + have hb := bitPowerInvocations_le_work B.bits d + simp only [coarseIndexedInvocations, coarseIndexedWithWork] + split_ifs + · simp only [leWithWork] + omega + · change coarseDescriptorInvocations B (d + 1) n offset + + compareInvocations allowance (nat (bitWordValue (coarseDescriptorWithWork B (d + 1) n offset).1)) + 2 + + bitPowerInvocations B.bits d + + coarseIndexChildrenInvocations q L two (fun i => bitWordValue (childSize i).1) + evaluate allocation draw allowance (List.finRange B) start + B + 1 ≤ + 2 * ((coarseDescriptorWithWork B (d + 1) n offset).2 + capacity.2 + + (coarseIndexChildren k q L two (fun i => bitWordValue (childSize i).1) + evaluate draw allowance (List.finRange B) start).2 + + (leWithWork (nat (bitWordValue (coarseDescriptorWithWork B (d + 1) n offset).1)) allowance).2 + + Nat.size (bitWordValue (coarseDescriptorWithWork B (d + 1) n offset).1) + B + 1) + 1 + change bitPowerInvocations B.bits d ≤ capacity.2 at hb + simp only [leWithWork] + omega + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseIndexedCostComparison.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseIndexedCostComparison.lean new file mode 100644 index 0000000000000000000000000000000000000000..56412c86fb9f3ce8fc34d6ddcda93e8ed3321872 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseIndexedCostComparison.lean @@ -0,0 +1,73 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseIndexedExtra + +namespace OAI + +namespace EditApproximation +namespace BinaryFraction + +attribute [local irreducible] coarseIndexedWithWork coarseReadCore coarseIndexedExtra + +theorem coarseIndexedWithWork_cost_compare {B : ℕ} (k q L n : ℕ) (source target : List ℕ) + (two : BinaryFraction) (d offset : ℕ) (draws : CoarseThresholdDraws B d) + (allowance : BinaryFraction) (start : ℕ) : + (coarseIndexedWithWork k q L n source target two d offset draws allowance start).2 ≤ + (coarseReadCore k q L n source target two d offset draws allowance start).2 + + coarseIndexedExtra k q L n source target two d offset draws allowance start := by + induction d generalizing offset allowance start with + | zero => + let f := fun shift : Fin (2 * k + 1) => + coarseGridNatWithWork allowance.denominator allowance.denominator_pos + (coarseReadShiftCost k n target (coarsePaddedRead n source offset) start shift) + let extra := fun shift : Fin (2 * k + 1) => + (coarseReadShiftWithWork k n target (coarsePaddedRead n source offset) start shift).2 + have hc := arithmeticMapWithWork_add_cost f extra (List.finRange (2 * k + 1)) + rw [coarseIndexedWithWork, coarseReadCore, coarseIndexedExtra] + simp only [coarseDescriptorWithWork_value, coarsePaddedReadWithWork_value] + split_ifs + · omega + · simp only [f, extra] at hc + simp only [coarseReadShiftWithWork_value] + omega + | succ d ih => + obtain ⟨draws, below⟩ := draws + let capacity := bitPowerWithWork B.bits d + let childOffset := fun i : Fin B => coarseChildOffsetWithWork offset (bitWordValue capacity.1) i.val + let childSize := fun i : Fin B => coarseDescriptorWithWork B d n (bitWordValue (childOffset i).1) + let overhead := fun i : Fin B => fun s : ℕ => + 3 * ((childOffset i).2 + (childSize i).2 + + (binaryNaturalAddWithWork s (bitWordValue (childSize i).1)).2 + 3) + let actual := fun i : Fin B => fun a s => + let evaluated := coarseIndexedWithWork k q L n source target two d + (bitWordValue (childOffset i).1) (below i) a s + (evaluated.1, evaluated.2 + overhead i s) + let reference := fun i : Fin B => + coarseReadCore k q L n source target two d (offset + i.val * B ^ d) (below i) + let extra := fun i : Fin B => fun a s => + coarseIndexedExtra k q L n source target two d (offset + i.val * B ^ d) (below i) a s + overhead i s + have hv : ∀ i a s, (actual i a s).1 = (reference i a s).1 := by + intro i a s + simp only [actual, reference, childOffset, capacity, coarseChildOffsetWithWork_value, + bitPowerWithWork_value, bitWordValue_bits] + exact coarseIndexedWithWork_value k q L n source target two d _ _ a s + have hw : ∀ i a s, (actual i a s).2 ≤ (reference i a s).2 + extra i a s := by + intro i a s + simp only [actual, reference, extra, childOffset, capacity, coarseChildOffsetWithWork_value, + bitPowerWithWork_value, bitWordValue_bits] + have h := ih (offset + i.val * B ^ d) (below i) a s + omega + have hloop := coarseIndexChildren_cost_compare k q L two + (fun i => coarseDescriptorLength B d n (offset + i.val * B ^ d)) draws actual reference extra + hv hw allowance (List.finRange B) start + erw [coarseIndexedWithWork, coarseReadCore, coarseIndexedExtra] + simp only [coarseDescriptorWithWork_value] + split_ifs + · omega + · simp only [actual, reference, extra, overhead, childOffset, childSize, capacity, + coarseDescriptorWithWork_value, coarseChildOffsetWithWork_value, + bitPowerWithWork_value, bitWordValue_bits] at hloop ⊢ + omega + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseIndexedEntryCost.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseIndexedEntryCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..d83b4d8b2a3f2ac3b546315eec9d90499f7cd20b --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseIndexedEntryCost.lean @@ -0,0 +1,59 @@ +import OAI.Combinatorics.EditApproximation.Refinement.ComputedCoarseIndexedWork +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalCoarseSeedLaw +import OAI.Combinatorics.EditApproximation.Probability.FreshCoordinateCost +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation + +/-- Keep the branch dimensions symbolic when forming the finite source sum. -/ + + +theorem coarseIndexedEntryBinaryCost_computed_bound : + ∀ᶠ N : ℕ in Filter.atTop, ∀ B d : ℕ, ∀ x y : List ℕ, + B = (integerParameters N).B → d = computedCoarseDepth N (coarseEntryWidth x y) → + coarseEntryWidth x y ≤ N → (∀ a ∈ x ++ y, Nat.size a ≤ inputHeight N ^ 3) → + ∀ (_hB : NeZero B) (draw : CoarseGuessIndex (coarseEntryWidth x y) → CoarseThresholdDraws B d), + (coarseIndexedEntryBinaryCost N B d x y draw : ℝ) ≤ (inputHeight N : ℝ) ^ 40 * + ((coarseInitialArrayWork B d (initialThresholdQ N) (initialLambda N) x y draw : ℝ) + + (x.length + 1 : ℕ)) := by + filter_upwards [BinaryFraction.computedCoarseIndexedInitialWithWork_bound] with N hN + intro B d x y hB hd hxy hsymbols hinstance draw + have hb := hN B d x y hB hd hxy hsymbols + (Nat.pos_of_neZero _) (pow_pos (Nat.two_pow_pos _) _) + (Nat.mul_pos (by decide) (Nat.two_pow_pos _)) draw + exact_mod_cast hb + + + +theorem coarseIndexedEntryCostSum_bound {M J B : ℕ} [NeZero B] (source target : List ℕ) + (N : ℕ) (depth : PhysicalEntry M J target.length → ℕ) + (draw : PhysicalCoarseDraw source target B depth) + (selected : PhysicalEntry M J target.length → Prop) (C : ℝ) + (hc : ∀ entry : PhysicalEntry M J target.length, + (coarseIndexedEntryBinaryCost N B (depth entry) (physicalSource source entry.1) + (substring target entry.2.lo entry.2.hi) (draw entry) : ℝ) ≤ + C * ((coarseInitialArrayWork B (depth entry) (initialThresholdQ N) (initialLambda N) + (physicalSource source entry.1) (substring target entry.2.lo entry.2.hi) (draw entry) : ℝ) + + ((physicalSource source entry.1).length + 1 : ℕ))) : + coarseIndexedEntryCostSum source target N depth draw selected ≤ C * + ((∑ entry : PhysicalEntry M J target.length, selectionIndicator (selected entry) * + (coarseInitialArrayWork B (depth entry) (initialThresholdQ N) (initialLambda N) + (physicalSource source entry.1) (substring target entry.2.lo entry.2.hi) (draw entry) : ℝ)) + + ∑ entry : PhysicalEntry M J target.length, selectionIndicator (selected entry) * + ((physicalSource source entry.1).length + 1 : ℕ)) := by + classical + rw [← Finset.sum_add_distrib, Finset.mul_sum] + unfold coarseIndexedEntryCostSum + apply Finset.sum_le_sum + intro entry _ + have hs : 0 ≤ selectionIndicator (selected entry) := by + unfold selectionIndicator + split <;> norm_num + exact (mul_le_mul_of_nonneg_left (hc entry) hs).trans_eq (by ring) + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseIndexedExecution.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseIndexedExecution.lean new file mode 100644 index 0000000000000000000000000000000000000000..d4adb3030023bb443d56aa8aa20e1f7d8a4f7e23 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseIndexedExecution.lean @@ -0,0 +1,21 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseReadAccess +import OAI.Combinatorics.EditApproximation.Coarse.CoarseReadEvaluation +import OAI.Combinatorics.EditApproximation.Coarse.CoarseReadLeafWork +import OAI.Combinatorics.EditApproximation.Coarse.CoarseIndexedCompare +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation +namespace BinaryFraction + +/- The indexed evaluator with all representation operations charged: +Boolean descriptor lengths, original-array reads, exact symbol comparisons +and the source/target offset arithmetic. -/ + + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseIndexedExtra.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseIndexedExtra.lean new file mode 100644 index 0000000000000000000000000000000000000000..3833b329715a8e1442398e06873116ac20084a4e --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseIndexedExtra.lean @@ -0,0 +1,35 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseIndexedValue + +namespace OAI + +namespace EditApproximation +namespace BinaryFraction + +/-- All descriptor and original-input operations alongside the core +arithmetic. Threshold decisions are exactly those of the evaluated call. -/ +def coarseIndexedExtra {B : ℕ} (k q L n : ℕ) (source target : List ℕ) + (two : BinaryFraction) : (d offset : ℕ) → CoarseThresholdDraws B d → + BinaryFraction → ℕ → ℕ + | 0, offset, _, allowance, start => + let descriptor := coarseDescriptorWithWork B 0 n offset + if (leWithWork (nat (coarseDescriptorLength B 0 n offset)) allowance).1 then descriptor.2 else + let letter := coarsePaddedReadWithWork n source offset + descriptor.2 + letter.2 + ((List.finRange (2 * k + 1)).map fun shift => + (coarseReadShiftWithWork k n target letter.1 start shift).2).sum + | d + 1, offset, (draws, below), allowance, start => + let descriptor := coarseDescriptorWithWork B (d + 1) n offset + if (leWithWork (nat (coarseDescriptorLength B (d + 1) n offset)) allowance).1 then descriptor.2 else + let capacity := bitPowerWithWork B.bits d + let childOffset := fun i : Fin B => coarseChildOffsetWithWork offset (bitWordValue capacity.1) i.val + let childSize := fun i : Fin B => coarseDescriptorWithWork B d n (bitWordValue (childOffset i).1) + descriptor.2 + capacity.2 + coarseIndexAdditionalWork q L + (fun i => coarseDescriptorLength B d n (offset + i.val * B ^ d)) draws + (fun i a s => coarseIndexedExtra k q L n source target two d (offset + i.val * B ^ d) (below i) a s + + 3 * ((childOffset i).2 + (childSize i).2 + + (binaryNaturalAddWithWork s (bitWordValue (childSize i).1)).2 + 3)) + allowance (List.finRange B) start + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseIndexedFrameWork.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseIndexedFrameWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..f82774d070fe43ea964ef3fb98589f181b7f1404 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseIndexedFrameWork.lean @@ -0,0 +1,54 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseIndexedRead +import OAI.Combinatorics.EditApproximation.Binary.BinaryLocalGridWork +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation + +/-- Read the framed target from its original array and three integer indices. -/ + + +theorem coarseFramedReadWithWork_value {α : Type*} (k n : ℕ) (word : List α) (i : ℕ) : + (coarseFramedReadWithWork k n word i).1 = coarseFramedRead k n word i := by + unfold coarseFramedReadWithWork coarseFramedRead + dsimp only + by_cases hlo : i < k + · rw [ite_eq_left ((binaryNaturalCompareWithWork_lt i k).mpr hlo), ite_eq_right (by omega)] + · rw [ite_eq_right (fun h => hlo ((binaryNaturalCompareWithWork_lt i k).mp h))] + simp only [binaryNaturalAddWithWork_value] + by_cases hhi : i < k + n + · rw [ite_eq_left ((binaryNaturalCompareWithWork_lt i (k + n)).mpr hhi), + ite_eq_left (by omega)] + simp only [saturatingSubtractWithWork_value] + · rw [ite_eq_right (fun h => hhi ((binaryNaturalCompareWithWork_lt i (k + n)).mp h)), + ite_eq_right (by omega)] + +theorem coarseFramedReadWithWork_cost {α : Type*} (k n : ℕ) (word : List α) (i A : ℕ) + (hk : Nat.size k ≤ A) (hn : Nat.size n ≤ A) (hi : Nat.size i ≤ A) : + (coarseFramedReadWithWork k n word i).2 ≤ 100 * (A + 1) := by + have hl := binaryNaturalCompareWithWork_cost i k + have ha := binaryNaturalAddWithWork_cost k n + have hs := binaryNaturalAdd_size_le k n + have hmax : max (Nat.size k) (Nat.size n) ≤ A := max_le hk hn + have hu := binaryNaturalCompareWithWork_cost i (bitWordValue (binaryNaturalAddWithWork k n).1) + rw [binaryNaturalAddWithWork_value] at hu + have hd := saturatingSubtractWithWork_cost i k + unfold coarseFramedReadWithWork + dsimp only + simp only [binaryNaturalAddWithWork_value] + split_ifs <;> dsimp only <;> omega + +theorem coarseIndexed_leaf_cost {α : Type*} [DecidableEq α] {B : ℕ} + (k n : ℕ) (word : List α) (hn : word.length ≤ n) (letter : Option α) + (start : ℕ) (shift : Fin (2 * k + 1)) : + coarseShiftCost k (coarseTargetFrame k (coarsePadTo n word)) + (.leaf (B := B) (some letter)) start shift = + if (coarseFramedReadWithWork k n word (start + shift.val)).1 = some letter then 0 else 1 := by + rw [coarseFramedReadWithWork_value, coarseFramedRead_value k n word hn] + rfl + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseIndexedHistory.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseIndexedHistory.lean new file mode 100644 index 0000000000000000000000000000000000000000..1b3dfaf216bfd1d5b33c58e7d3ed840220fd8f95 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseIndexedHistory.lean @@ -0,0 +1,66 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseIndexedArrayHistory +import OAI.Combinatorics.EditApproximation.Coarse.CoarseInitialStorage + +namespace OAI + +namespace EditApproximation +namespace BinaryFraction +open Filter + +def coarseIndexedRootArrayHistory {B d : ℕ} (k q L : ℕ) + (hB : 0 < B) (hq : 0 < q) (hL : 0 < L) (x y : List ℕ) + (draws : CoarseThresholdDraws B d) : ℕ := + let den := coarseRootDenominator B q L d + let denPos := coarseRootDenominator_pos B q L d hB hq hL + let two := (coarseGridNatWithWork den.1 denPos 2).1 + let allowance := (coarseGridNatWithWork den.1 denPos k).1 + coarseIndexedArrayHistory k q L (coarseEntryWidth x y) x y two d 0 draws allowance 0 + +theorem coarseIndexedRootArrayHistory_eq {B d : ℕ} (k q L : ℕ) + (hB : 0 < B) (hq : 0 < q) (hL : 0 < L) (x y : List ℕ) + (draws : CoarseThresholdDraws B d) : + coarseIndexedRootArrayHistory k q L hB hq hL x y draws = + coarseRootArrayHistory k q L hB hq hL + (coarseTargetFrame k (coarsePadTo (coarseEntryWidth x y) y)) + (coarseEntryTree B d x y) draws 0 := by + unfold coarseIndexedRootArrayHistory coarseRootArrayHistory + dsimp only + rw [coarseIndexedArrayHistory_eq k q L (coarseEntryWidth x y) x y + (le_max_left _ _) (le_max_right _ _)] + simp only [Nat.zero_add, coarseReadTree_entry] + +def coarseIndexedInitialArrayHistory (N B d : ℕ) [NeZero B] (x y : List ℕ) + (draws : CoarseGuessIndex (coarseEntryWidth x y) → CoarseThresholdDraws B d) : ℕ := + if 2 * x.length < y.length then 0 else if x = y then 0 else + ∑ i : CoarseGuessIndex (coarseEntryWidth x y), + coarseIndexedRootArrayHistory (coarseGuess (coarseEntryWidth x y) i) + (inputHeight N ^ 4) (64 * inputHeight N) (Nat.pos_of_neZero B) + (pow_pos (Nat.two_pow_pos _) _) (Nat.mul_pos (by decide) (Nat.two_pow_pos _)) x y (draws i) + +theorem coarseIndexedInitialArrayHistory_eq (N B d : ℕ) [NeZero B] (x y : List ℕ) + (draws : CoarseGuessIndex (coarseEntryWidth x y) → CoarseThresholdDraws B d) : + coarseIndexedInitialArrayHistory N B d x y draws = coarseInitialArrayHistory N B d x y draws := by + unfold coarseIndexedInitialArrayHistory coarseInitialArrayHistory + split + · rfl + · split + · rfl + · apply Finset.sum_congr rfl + intro i _ + exact coarseIndexedRootArrayHistory_eq _ _ _ _ _ _ x y (draws i) + +theorem coarseIndexedInitialArrayHistory_polynomial : + ∀ᶠ N : ℕ in atTop, ∀ B d : ℕ, ∀ x y : List ℕ, + B = (integerParameters N).B → d = computedCoarseDepth N (coarseEntryWidth x y) → + coarseEntryWidth x y ≤ N → ∀ (_hB : NeZero B) + (draws : CoarseGuessIndex (coarseEntryWidth x y) → CoarseThresholdDraws B d), + coarseIndexedInitialArrayHistory N B d x y draws ≤ (N + 2) ^ 37 := by + filter_upwards [coarseInitialArrayHistory_polynomial] with N hN + intro B d x y hB hd hsize inst draws + rw [coarseIndexedInitialArrayHistory_eq] + exact hN B d x y hB hd hsize inst draws + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseIndexedInitial.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseIndexedInitial.lean new file mode 100644 index 0000000000000000000000000000000000000000..07816efef8ee07baa4e8f35273d61d6c4694ce1c --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseIndexedInitial.lean @@ -0,0 +1,52 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseIndexedValue +import OAI.Combinatorics.EditApproximation.Coarse.CoarseInitialExecution +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation +namespace BinaryFraction + + + +theorem coarseIndexedRootWithWork_value {B d : ℕ} (k q L : ℕ) + (hB : 0 < B) (hq : 0 < q) (hL : 0 < L) (x y : List ℕ) + (draws : CoarseThresholdDraws B d) : + (coarseIndexedRootWithWork k q L hB hq hL x y draws).1 = + (coarseRootWithWork k q L hB hq hL + (coarseTargetFrame k (coarsePadTo (coarseEntryWidth x y) y)) + (coarseEntryTree B d x y) draws 0 (coarseRootShift k)).1 := by + unfold coarseIndexedRootWithWork coarseRootWithWork + dsimp only + rw [coarseIndexedWithWork_value, coarseReadCore_eq k q L (coarseEntryWidth x y) x y + (le_max_left _ _) (le_max_right _ _)] + simp only [Nat.zero_add, coarseReadTree_entry] + + + +theorem coarseIndexedCandidateWithWork_value {B d : ℕ} (q L : ℕ) + (hB : 0 < B) (hq : 0 < q) (hL : 0 < L) (x y : List ℕ) + (i : CoarseGuessIndex (coarseEntryWidth x y)) (draws : CoarseThresholdDraws B d) : + (coarseIndexedCandidateWithWork q L hB hq hL x y i draws).1 = + (coarseCandidateWithWork q L hB hq hL x y i draws).1 := by + simp only [coarseIndexedCandidateWithWork, coarseCandidateWithWork, coarseIndexedRootWithWork_value] + +/-- The final coarse initializer executes the indexed roots and retains +only their integer-clamped minimum. -/ + + +theorem coarseIndexedInitialWithWork_value {B d : ℕ} (q L N : ℕ) + (hB : 0 < B) (hq : 0 < q) (hL : 0 < L) (x y : List ℕ) + (draws : CoarseGuessIndex (coarseEntryWidth x y) → CoarseThresholdDraws B d) : + (coarseIndexedInitialWithWork q L N hB hq hL x y draws).1 = + coarseInitialValue B d q (1 / L) N x y draws := by + rw [← coarseInitialWithWork_value q L N hB hq hL x y draws] + unfold coarseIndexedInitialWithWork coarseInitialWithWork + dsimp only + split_ifs <;> simp only [arithmeticMapWithWork_value, coarseIndexedCandidateWithWork_value] + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseIndexedInitialCost.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseIndexedInitialCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..5aa67b4936819d89d7528a36e2c49632b109d3eb --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseIndexedInitialCost.lean @@ -0,0 +1,56 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseIndexedRootCost + +namespace OAI + +namespace EditApproximation +namespace BinaryFraction + +attribute [local irreducible] coarseIndexedCandidateWithWork coarseCandidateWithWork coarseRootReadExtra + arithmeticMapWithWork coarseMinimumWithWork naturalCeilingWithWork wordMinWithWork + +theorem arithmeticMapWithWork_cost_compare {α β : Type*} (f g : α → β × ℕ) + (extra : α → ℕ) (xs : List α) (hc : ∀ a ∈ xs, (f a).2 ≤ (g a).2 + extra a) : + (arithmeticMapWithWork f xs).2 ≤ (arithmeticMapWithWork g xs).2 + (xs.map extra).sum := by + induction xs with + | nil => simp only [arithmeticMapWithWork, List.map_nil, List.sum_nil, Nat.add_zero, le_refl] + | cons a xs ih => + have ha := hc a List.mem_cons_self + have hr := ih (fun a ha => hc a (List.mem_cons_of_mem _ ha)) + simp only [arithmeticMapWithWork, List.map_cons, List.sum_cons] + omega + +def coarseInitialReadExtra {B d : ℕ} (q L : ℕ) (hB : 0 < B) (hq : 0 < q) (hL : 0 < L) + (x y : List ℕ) (draws : CoarseGuessIndex (coarseEntryWidth x y) → CoarseThresholdDraws B d) : ℕ := + if (binaryNaturalCompareWithWork (2 * x.length) y.length).1 = .lt then 0 else + if (naturalListEqualWithWork x y).1 then 0 else + ((List.finRange (Nat.clog 2 (coarseEntryWidth x y) + 1)).map fun i => + coarseRootReadExtra (coarseGuess (coarseEntryWidth x y) i) q L hB hq hL x y (draws i)).sum + +theorem coarseIndexedInitialWithWork_cost_compare {B d : ℕ} (q L N : ℕ) + (hB : 0 < B) (hq : 0 < q) (hL : 0 < L) (x y : List ℕ) + (draws : CoarseGuessIndex (coarseEntryWidth x y) → CoarseThresholdDraws B d) : + (coarseIndexedInitialWithWork q L N hB hq hL x y draws).2 ≤ + (coarseInitialWithWork q L N hB hq hL x y draws).2 + + coarseInitialReadExtra q L hB hq hL x y draws := by + let indices := List.finRange (Nat.clog 2 (coarseEntryWidth x y) + 1) + let f := fun i => coarseIndexedCandidateWithWork q L hB hq hL x y i (draws i) + let g := fun i => coarseCandidateWithWork q L hB hq hL x y i (draws i) + let extra := fun i => coarseRootReadExtra (coarseGuess (coarseEntryWidth x y) i) + q L hB hq hL x y (draws i) + have hc := arithmeticMapWithWork_cost_compare f g extra indices + (fun i _ => coarseIndexedCandidateWithWork_cost_compare q L hB hq hL x y i (draws i)) + have hv : (arithmeticMapWithWork f indices).1 = (arithmeticMapWithWork g indices).1 := by + simp only [arithmeticMapWithWork_value, f, g, coarseIndexedCandidateWithWork_value] + unfold coarseIndexedInitialWithWork coarseInitialWithWork coarseInitialReadExtra + dsimp only + split_ifs + · omega + · omega + · dsimp only [f, g, extra, indices] at hc hv + rw [hv] + omega + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseIndexedOverhead.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseIndexedOverhead.lean new file mode 100644 index 0000000000000000000000000000000000000000..39bbc1c954d938c23d6093939b903d20ad850f25 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseIndexedOverhead.lean @@ -0,0 +1,108 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseReadBudget +import OAI.Combinatorics.EditApproximation.Coarse.CoarseIndexedCostComparison +import OAI.Combinatorics.EditApproximation.Coarse.CoarseIndexBudget + +namespace OAI + +namespace EditApproximation +namespace BinaryFraction + +attribute [local irreducible] coarseIndexedExtra coarseBinaryWeight + +theorem coarseIndexedExtra_bound {B : ℕ} (R k q L n K : ℕ) (source target : List ℕ) + (two : BinaryFraction) (hB : 0 < B) (hK : 1 ≤ K) + (hs : source.length ≤ n) (budget : CoarseReadBudget B R k n source target K) + (d offset : ℕ) (draws : CoarseThresholdDraws B d) (allowance : BinaryFraction) + (start : ℕ) (hd : d ≤ R) (hoff : offset + B ^ d ≤ B ^ R) + (hstart : start + coarseDescriptorLength B d n offset ≤ n) : + coarseIndexedExtra k q L n source target two d offset draws allowance start ≤ + (32 * K) * coarseBinaryWeight k q L + (coarseReadTree B d (fun j => coarsePaddedRead n source (offset + j))) draws allowance := by + induction d generalizing offset allowance start with + | zero => + have ho : offset ≤ B ^ R := by omega + have hdesc := budget.descriptor 0 hd offset ho + have hread := budget.sourceRead offset ho + have hsum : ((List.finRange (2 * k + 1)).map fun shift => + (coarseReadShiftWithWork k n target (coarsePaddedRead n source offset) start shift).2).sum ≤ + (2 * k + 1) * K := by + calc + _ ≤ ((List.finRange (2 * k + 1)).map fun _ => K).sum := + List.sum_le_sum (fun shift _ => budget.mismatch offset ho start (by omega) shift) + _ = (2 * k + 1) * K := by simp + have hlen := coarseReadTree_padded_length B 0 n offset source hs + simp only [coarseReadTree, Nat.add_zero] at hlen ⊢ + rw [coarseIndexedExtra, coarseBinaryWeight, hlen] + split_ifs + · nlinarith only [hdesc, hK] + · simp only [coarsePaddedReadWithWork_value] + have hb : 2 * k + 1 ≤ B * (2 * k + 1) := Nat.le_mul_of_pos_left _ hB + nlinarith only [hdesc, hread, hsum, hK, Nat.mul_le_mul_right K hb] + | succ d ih => + obtain ⟨draws, below⟩ := draws + have ho : offset ≤ B ^ R := by omega + let children := fun i : Fin B => coarseReadTree B d + (fun j => coarsePaddedRead n source (offset + i.val * B ^ d + j)) + let width := fun i : Fin B => coarseDescriptorLength B d n (offset + i.val * B ^ d) + let weight := fun i : Fin B => coarseBinaryWeight k q L (children i) (below i) + have htree : coarseReadTree B (d + 1) (fun j => coarsePaddedRead n source (offset + j)) = + CoarseSourceTree.branch children := by + simp only [coarseReadTree, children, Nat.add_assoc] + have hlen : (CoarseSourceTree.branch children).word.length = + coarseDescriptorLength B (d + 1) n offset := by + rw [← htree] + exact coarseReadTree_padded_length B (d + 1) n offset source hs + have hwidth (i : Fin B) : width i = (children i).word.length := + (coarseReadTree_padded_length B d n (offset + i.val * B ^ d) source hs).symm + have hchild (i : Fin B) : offset + i.val * B ^ d + B ^ d ≤ B ^ R := by + have hm := Nat.mul_le_mul_right (B ^ d) (Nat.succ_le_of_lt i.isLt) + rw [pow_succ] at hoff + nlinarith only [hm, hoff] + let extra := fun i : Fin B => fun a s => + coarseIndexedExtra k q L n source target two d (offset + i.val * B ^ d) (below i) a s + + 3 * ((coarseChildOffsetWithWork offset (B ^ d) i.val).2 + + (coarseDescriptorWithWork B d n (offset + i.val * B ^ d)).2 + + (binaryNaturalAddWithWork s (width i)).2 + 3) + have hc : ∀ i ∈ List.finRange B, ∀ s, s + width i ≤ n → + extra i (coarseChildAllowanceWithWork L + (coarseChildThresholdWithWork B q allowance (draws i)).1).1 s ≤ + (32 * K) * weight i (coarseChildAllowanceWithWork L + (coarseChildThresholdWithWork B q allowance (draws i)).1).1 + 18 * K := by + intro i _ s hsi + have hc := ih (offset + i.val * B ^ d) (below i) + (coarseChildAllowanceWithWork L (coarseChildThresholdWithWork B q allowance (draws i)).1).1 s (by omega) (hchild i) hsi + have h1 := budget.offset offset ho i d (by omega) + have h2 := budget.descriptor d (by omega) (offset + i.val * B ^ d) (by have := hchild i; omega) + have h3 := budget.advance s (by omega) (width i) (by omega) + change _ ≤ (32 * K) * weight i _ at hc + dsimp only [extra] + omega + have hspan : coarseIndexSpan width (List.finRange B) = + coarseDescriptorLength B (d + 1) n offset := by + rw [coarseIndexSpan_eq width children draws below hwidth, ← List.ofFn_eq_map, + coarseChildrenSpan_ofFn, hlen] + have hloop := coarseIndexAdditionalWork_bound q L n (32 * K) (18 * K) width draws extra weight + allowance (List.finRange B) hc start (by rw [hspan]; exact hstart) + have hw := coarseIndexWeight_eq k q L children draws below allowance (List.finRange B) + have hdesc := budget.descriptor (d + 1) hd offset ho + have hpower := budget.power d (by omega) + erw [htree, coarseIndexedExtra, coarseBinaryWeight, hlen] + split_ifs + · nlinarith only [hdesc, hK] + · simp only [bitPowerWithWork_value, bitWordValue_bits, coarseChildOffsetWithWork_value, + coarseDescriptorWithWork_value] + change _ ≤ (32 * K) * (B * (2 * k + 1) + 1 + _) + simp only [List.length_finRange] at hloop + dsimp only [extra, width, weight] at hloop + rw [hw, ← List.ofFn_eq_map] at hloop + have hbase : 18 * K * B ≤ (32 * K) * (B * (2 * k + 1)) := by + calc + _ ≤ (32 * K) * B := by nlinarith only [Nat.zero_le (K * B)] + _ ≤ _ := Nat.mul_le_mul_left (32 * K) + (Nat.le_mul_of_pos_right B (by omega)) + nlinarith only [hloop, hdesc, hpower, hbase, hK] + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseIndexedRead.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseIndexedRead.lean new file mode 100644 index 0000000000000000000000000000000000000000..de7afe9fb2a5f504a04f46a9543b8a133a59fc8a --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseIndexedRead.lean @@ -0,0 +1,50 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseInitialBinary + +namespace OAI + +namespace EditApproximation + +/-- Padding and framing are index calculations over the original stored +input. These views do not allocate a padded string. -/ +def coarsePaddedRead {α : Type*} (n : ℕ) (word : List α) (i : ℕ) : Option (Option α) := + if i < n then some word[i]? else none + +def coarseFramedRead {α : Type*} (k n : ℕ) (word : List α) (i : ℕ) : Option (Option α) := + if k ≤ i ∧ i < k + n then some word[i - k]? else none + +theorem coarsePaddedRead_value {α : Type*} (n : ℕ) (word : List α) (hn : word.length ≤ n) (i : ℕ) : + coarsePaddedRead n word i = (coarsePadTo n word)[i]? := by + unfold coarsePaddedRead coarsePadTo + by_cases hi : i < word.length + · rw [ite_eq_left (hi.trans_le hn), List.getElem?_append_left (by simpa using hi), + List.getElem?_map, List.getElem?_eq_getElem hi] + rfl + · rw [List.getElem?_append_right (by simpa using Nat.le_of_not_gt hi), List.length_map, + List.getElem?_replicate, List.getElem?_eq_none (Nat.le_of_not_gt hi)] + by_cases hin : i < n + · rw [ite_eq_left hin, ite_eq_left (by omega)] + · rw [ite_eq_right hin, ite_eq_right (by omega)] + +theorem coarseFramedRead_value {α : Type*} (k n : ℕ) (word : List α) (hn : word.length ≤ n) (i : ℕ) : + coarseFramedRead k n word i = + (coarseTargetFrame k (coarsePadTo n word))[i]?.getD none := by + have hl : (List.replicate k (none : Option (Option α)) ++ + (coarsePadTo n word).map some).length = k + n := by + simp only [List.length_append, List.length_replicate, List.length_map, coarsePadTo_length n word hn] + unfold coarseFramedRead coarseTargetFrame + by_cases hi : i < k + n + · rw [List.getElem?_append_left (by simpa only [hl] using hi)] + by_cases hk : i < k + · rw [List.getElem?_append_left (by simpa only [List.length_replicate] using hk), + List.getElem?_replicate_of_lt hk, Option.getD_some, ite_eq_right (by omega)] + · rw [List.getElem?_append_right (by simpa only [List.length_replicate] using Nat.le_of_not_gt hk), + List.length_replicate, List.getElem?_map, ← coarsePaddedRead_value n word hn (i - k)] + simp only [coarsePaddedRead, ite_eq_left (by omega : i - k < n), Option.map_some, + Option.getD_some, ite_eq_left (by omega : k ≤ i ∧ i < k + n)] + · rw [List.getElem?_append_right (by simpa only [hl] using Nat.le_of_not_gt hi), hl, + List.getElem?_replicate, ite_eq_right (by omega : ¬ (k ≤ i ∧ i < k + n))] + split_ifs <;> rfl + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseIndexedRootBound.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseIndexedRootBound.lean new file mode 100644 index 0000000000000000000000000000000000000000..ba0c8035aed647629e4a77af70aca010619ecf38 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseIndexedRootBound.lean @@ -0,0 +1,39 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseIndexedRootCost +import OAI.Combinatorics.EditApproximation.Coarse.CoarseWeightSimulation + +namespace OAI + +namespace EditApproximation +namespace BinaryFraction + +theorem coarseRootReadExtra_bound {B d : ℕ} (k q L K : ℕ) + (hB : 0 < B) (hq : 0 < q) (hL : 0 < L) (hK : 1 ≤ K) (x y : List ℕ) + (draws : CoarseThresholdDraws B d) + (budget : CoarseReadBudget B d k (coarseEntryWidth x y) x y K) : + coarseRootReadExtra k q L hB hq hL x y draws ≤ + (32 * K) * (2 * coarseActiveArrayWork k q (1 / L) + (coarseEntryTree B d x y) draws k + 1) := by + let den := coarseRootDenominator B q L d + let denPos := coarseRootDenominator_pos B q L d hB hq hL + let two := coarseGridNatWithWork den.1 denPos 2 + let allowance := coarseGridNatWithWork den.1 denPos k + have he := coarseIndexedExtra_bound d k q L (coarseEntryWidth x y) K x y two.1 hB hK + (le_max_left _ _) budget d 0 draws allowance.1 0 le_rfl (by omega) + (by simp only [coarseDescriptorLength, Nat.sub_zero, Nat.zero_add]; exact min_le_right _ _) + simp only [Nat.zero_add, coarseReadTree_entry] at he + have ha : allowance.1.representation.den = coarseCommonDenominator 1 q L B d := + (coarseGridNatWithWork_den _ _ k).trans (coarseRootDenominator_value B q L d) + have hv : allowance.1.value = k := coarseGridNatWithWork_value _ _ k + have hp : allowance.1.value.den ∣ (L * B * q) ^ 0 := by + rw [hv, Rat.den_natCast] + exact one_dvd _ + have hw := coarseBinaryWeight_le k q L d (coarseEntryTree B d x y) draws hB hq hL + 0 (by omega) allowance.1 ha hp + rw [hv] at hw + change coarseIndexedExtra k q L (coarseEntryWidth x y) x y two.1 d 0 draws allowance.1 0 ≤ _ + exact he.trans (Nat.mul_le_mul_left (32 * K) hw) + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseIndexedRootCost.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseIndexedRootCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..ef1e80395df07fc73821f5730f8a8efb9488042e --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseIndexedRootCost.lean @@ -0,0 +1,53 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseIndexedInitial +import OAI.Combinatorics.EditApproximation.Coarse.CoarseIndexedOverhead + +namespace OAI + +namespace EditApproximation +namespace BinaryFraction + +def coarseRootReadExtra {B d : ℕ} (k q L : ℕ) (hB : 0 < B) (hq : 0 < q) (hL : 0 < L) + (x y : List ℕ) (draws : CoarseThresholdDraws B d) : ℕ := + let den := coarseRootDenominator B q L d + let denPos := coarseRootDenominator_pos B q L d hB hq hL + let two := coarseGridNatWithWork den.1 denPos 2 + let allowance := coarseGridNatWithWork den.1 denPos k + coarseIndexedExtra k q L (coarseEntryWidth x y) x y two.1 d 0 draws allowance.1 0 + +theorem coarseIndexedRootWithWork_cost_compare {B d : ℕ} (k q L : ℕ) + (hB : 0 < B) (hq : 0 < q) (hL : 0 < L) (x y : List ℕ) + (draws : CoarseThresholdDraws B d) : + (coarseIndexedRootWithWork k q L hB hq hL x y draws).2 ≤ + (coarseRootWithWork k q L hB hq hL + (coarseTargetFrame k (coarsePadTo (coarseEntryWidth x y) y)) + (coarseEntryTree B d x y) draws 0 (coarseRootShift k)).2 + + coarseRootReadExtra k q L hB hq hL x y draws := by + let den := coarseRootDenominator B q L d + let denPos := coarseRootDenominator_pos B q L d hB hq hL + let two := coarseGridNatWithWork den.1 denPos 2 + let allowance := coarseGridNatWithWork den.1 denPos k + have h := coarseIndexedWithWork_cost_compare k q L (coarseEntryWidth x y) x y + two.1 d 0 draws allowance.1 0 + rw [coarseReadCore_eq k q L (coarseEntryWidth x y) x y (le_max_left _ _) (le_max_right _ _)] at h + simp only [Nat.zero_add, coarseReadTree_entry] at h + unfold coarseIndexedRootWithWork coarseRootWithWork coarseRootReadExtra + change den.2 + two.2 + allowance.2 + _ + 1 ≤ den.2 + two.2 + allowance.2 + _ + 1 + _ + dsimp only [den, denPos, two, allowance] at h ⊢ + omega + +theorem coarseIndexedCandidateWithWork_cost_compare {B d : ℕ} (q L : ℕ) + (hB : 0 < B) (hq : 0 < q) (hL : 0 < L) (x y : List ℕ) + (i : CoarseGuessIndex (coarseEntryWidth x y)) (draws : CoarseThresholdDraws B d) : + (coarseIndexedCandidateWithWork q L hB hq hL x y i draws).2 ≤ + (coarseCandidateWithWork q L hB hq hL x y i draws).2 + + coarseRootReadExtra (coarseGuess (coarseEntryWidth x y) i) q L hB hq hL x y draws := by + have h := coarseIndexedRootWithWork_cost_compare + (coarseGuess (coarseEntryWidth x y) i) q L hB hq hL x y draws + unfold coarseIndexedCandidateWithWork coarseCandidateWithWork + simp only [coarseIndexedRootWithWork_value] + omega + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseIndexedValue.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseIndexedValue.lean new file mode 100644 index 0000000000000000000000000000000000000000..25808129ed37d20173ca67c027ca449159f62077 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseIndexedValue.lean @@ -0,0 +1,52 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseIndexedExecution + +namespace OAI + +namespace EditApproximation +namespace BinaryFraction + +attribute [local irreducible] coarseIndexedWithWork coarseReadCore + +/-- Charging descriptor/read operations leaves the indexed arithmetic +result unchanged, on every draw and every pruning branch. -/ +theorem coarseIndexedWithWork_value {B : ℕ} (k q L n : ℕ) (source target : List ℕ) + (two : BinaryFraction) (d offset : ℕ) (draws : CoarseThresholdDraws B d) + (allowance : BinaryFraction) (start : ℕ) : + (coarseIndexedWithWork k q L n source target two d offset draws allowance start).1 = + (coarseReadCore k q L n source target two d offset draws allowance start).1 := by + induction d generalizing offset allowance start with + | zero => + rw [coarseIndexedWithWork, coarseReadCore] + simp only [coarseDescriptorWithWork_value, coarsePaddedReadWithWork_value] + split_ifs + · rfl + · simp only [arithmeticMapWithWork_value, coarseReadShiftWithWork_value] + | succ d ih => + obtain ⟨draws, below⟩ := draws + have hloop := coarseIndexChildren_value_congr k q L two + (fun i : Fin B => coarseDescriptorLength B d n (offset + i.val * B ^ d)) draws + (fun i a s => + let childOffset := coarseChildOffsetWithWork offset (bitWordValue (bitPowerWithWork B.bits d).1) i.val + let childSize := coarseDescriptorWithWork B d n (bitWordValue childOffset.1) + let evaluated := coarseIndexedWithWork k q L n source target two d + (bitWordValue childOffset.1) (below i) a s + let next := binaryNaturalAddWithWork s (bitWordValue childSize.1) + (evaluated.1, evaluated.2 + 3 * (childOffset.2 + childSize.2 + next.2 + 3))) + (fun i => coarseReadCore k q L n source target two d (offset + i.val * B ^ d) (below i)) + (by + intro i a s + simp only [coarseChildOffsetWithWork_value, bitPowerWithWork_value, bitWordValue_bits] + exact ih (offset + i.val * B ^ d) (below i) a s) + allowance (List.finRange B) start + erw [coarseIndexedWithWork, coarseReadCore] + simp only [coarseDescriptorWithWork_value, coarseChildOffsetWithWork_value, + bitPowerWithWork_value, bitWordValue_bits] + split_ifs + · rfl + · simpa only [coarseChildOffsetWithWork_value, bitPowerWithWork_value, bitWordValue_bits, + coarseDescriptorWithWork_value] using hloop + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseInitial.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseInitial.lean new file mode 100644 index 0000000000000000000000000000000000000000..c3db9a000a490d836318e097e90dd73999d9c65e --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseInitial.lean @@ -0,0 +1,312 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarsePadding +import OAI.Combinatorics.EditApproximation.Coarse.CoarseProbability +import OAI.Combinatorics.EditApproximation.Probability.ExactSampling +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! +# The executable initial integer estimate + +The direct branches handle long targets and equality. The remaining branch +evaluates the concrete coarse recurrence at every dyadic guess, takes the +rational minimum, rounds up and clamps to the input length. +-/ + +namespace EditApproximation + +open EditDistortion Finset MeasureTheory ProbabilityTheory + +universe u + +/-- A finite Bernoulli-inequality bound for the exact structural factor. +The paper's `lam = 1/(64H)` and `D ≤ H` satisfy these loose conditions. -/ +theorem coarseStructuralFactor_le_two (lam : ℚ) (D : ℕ) + (hlam : 0 ≤ lam) (hsmall : lam ≤ 1 / 4) + (hdepth : 4 * (D : ℚ) * lam ≤ 1) : coarseStructuralFactor lam D ≤ 2 := by + have hl : (0 : ℝ) ≤ lam := by exact_mod_cast hlam + have hs : (lam : ℝ) ≤ 1 / 4 := by + have hcast : (lam : ℝ) ≤ ((1 / 4 : ℚ) : ℝ) := Rat.cast_le.mpr hsmall + norm_num at hcast + exact hcast + have hd : 4 * (D : ℝ) * lam ≤ 1 := by exact_mod_cast hdepth + have hden : 0 < 1 - (lam : ℝ) := by linarith + have hdenTwo : 0 < 1 - 2 * (lam : ℝ) := by linarith + have hbase : (1 + (lam : ℝ)) / (1 - (lam : ℝ)) ≤ 1 / (1 - 2 * (lam : ℝ)) := by + apply (div_le_div_iff₀ hden hdenTwo).2 + nlinarith + have hpower := pow_le_pow_left₀ (div_nonneg (by linarith) hden.le) hbase D + rw [one_div_pow] at hpower + have hbernoulli := one_add_mul_le_pow (a := -(2 * (lam : ℝ))) (by linarith) D + have hlower : (1 : ℝ) / 2 ≤ (1 - 2 * (lam : ℝ)) ^ D := by + simp only [mul_neg, ← sub_eq_add_neg] at hbernoulli + nlinarith + have hreciprocal : 1 / (1 - 2 * (lam : ℝ)) ^ D ≤ 2 := by + apply (div_le_iff₀ (lt_of_lt_of_le (by norm_num : (0 : ℝ) < 1 / 2) hlower)).2 + linarith + exact hpower.trans hreciprocal + + + + + + + + + + + + + + + +noncomputable def CoarseInitialAccuracyEvent {α : Type u} [DecidableEq α] + (B D : ℕ) (Q lam : ℚ) (x y : List α) + (draws : CoarseGuessIndex (coarseEntryWidth x y) → CoarseThresholdDraws B D) : Prop := + ∀ i, let k := coarseGuess (coarseEntryWidth x y) i + CoarseAccuracyEvent k Q lam + (coarseTargetFrame k (coarsePadTo (coarseEntryWidth x y) y)) + (coarseEntryTree B D x y) (draws i) k 0 + +theorem coarseEntryTree_word {α : Type u} (B D : ℕ) (x y : List α) + (hcapacity : coarseEntryWidth x y ≤ B ^ D) : + (coarseEntryTree B D x y).word = coarsePadTo (coarseEntryWidth x y) x := by + apply coarseSourceTreeOfList_word_eq + rw [coarsePadTo_length _ _ (le_max_left _ _)] + exact hcapacity + +theorem coarse_good_dyadic_guess (n d : ℕ) (hd : 0 < d) (hdn : d ≤ n) : + ∃ i : CoarseGuessIndex n, d ≤ coarseGuess n i ∧ coarseGuess n i < 2 * d := by + refine ⟨⟨Nat.clog 2 d, Nat.lt_succ_of_le (Nat.clog_mono_right 2 hdn)⟩, ?_⟩ + exact rejectionWord_range d hd + +theorem coarseInitialValue_le_length {α : Type u} [DecidableEq α] + (B D : ℕ) (Q lam : ℚ) (N : ℕ) (x y : List α) + (draws : CoarseGuessIndex (coarseEntryWidth x y) → CoarseThresholdDraws B D) : + coarseInitialValue B D Q lam N x y draws ≤ N := by + unfold coarseInitialValue + split_ifs + · exact min_le_left _ _ + · exact Nat.zero_le _ + · exact min_le_left _ _ + +/-- Every original zero-cost instance returns zero on every execution. -/ +theorem coarseInitialValue_zero {α : Type u} [DecidableEq α] + (B D : ℕ) (Q lam : ℚ) (N : ℕ) (x y : List α) + (draws : CoarseGuessIndex (coarseEntryWidth x y) → CoarseThresholdDraws B D) + (hzero : edit x y = 0) : coarseInitialValue B D Q lam N x y draws = 0 := by + have hxy : x = y := (cost_eq_zero_iff (s := true)).mp hzero + subst y + simp only [coarseInitialValue, ite_eq_right (by omega : ¬ 2 * x.length < x.length), ite_true] + +/-- Every dyadic candidate lies above the original edit cost on its +literal pathwise event, even when the guess is below the true distance. -/ +theorem coarseInitialCandidate_lower {α : Type u} [DecidableEq α] + (B D : ℕ) (Q lam : ℚ) (x y : List α) + (i : CoarseGuessIndex (coarseEntryWidth x y)) (draws : CoarseThresholdDraws B D) + (hcapacity : coarseEntryWidth x y ≤ B ^ D) + (hQ : 0 ≤ Q) (hlam : 0 ≤ lam) (hlamone : lam < 1) + (hfactor : coarseStructuralFactor lam D ≤ 2) + (hevent : let k := coarseGuess (coarseEntryWidth x y) i + CoarseAccuracyEvent k Q lam + (coarseTargetFrame k (coarsePadTo (coarseEntryWidth x y) y)) + (coarseEntryTree B D x y) draws k 0) : + (edit x y : ℚ) ≤ coarseInitialCandidate B D Q lam x y i draws := by + let k := coarseGuess (coarseEntryWidth x y) i + let tree := coarseEntryTree B D x y + let target := coarsePadTo (coarseEntryWidth x y) y + have hword := coarseEntryTree_word B D x y hcapacity + have hlength : tree.word.length = target.length := by + dsimp [tree, target] + rw [hword, coarsePadTo_length _ _ (le_max_left _ _), + coarsePadTo_length _ _ (le_max_right _ _)] + have htrue := coarseTreeValue_edit_lower tree target k hlength + have hpadding := (coarsePadding_distance_bounds x y).1 + rw [← hword] at hpadding + have hcost : edit x y ≤ coarseTreeValue tree target k := hpadding.trans htrue + have hcostReal : (edit x y : ℝ) ≤ coarseTreeValue tree target k := by exact_mod_cast hcost + have haccuracy := (coarseThresholdEstimate_accurate k Q lam (coarseTargetFrame k target) + tree draws k 0 hQ hlam hlamone (by positivity) hevent (coarseRootShift k)).1 + have hfpos : 0 < coarseStructuralFactor lam D := + lt_of_lt_of_le zero_lt_one (coarseStructuralFactor_one_le lam D hlam hlamone) + have hdivide : (coarseTreeValue tree target k : ℝ) / 2 ≤ + coarseTreeValue tree target k / coarseStructuralFactor lam D := + div_le_div_of_nonneg_left (by positivity) hfpos hfactor + have hcandidateReal : (edit x y : ℝ) ≤ (coarseInitialCandidate B D Q lam x y i draws : ℝ) := by + simp only [coarseInitialCandidate, Rat.cast_mul, Rat.cast_add, Rat.cast_ofNat, Rat.cast_natCast] + change (edit x y : ℝ) ≤ 2 * + ((coarseThresholdEstimate k Q lam (coarseTargetFrame k target) tree draws k 0 + (coarseRootShift k) : ℝ) + k) + change (coarseTreeValue tree target k : ℝ) / coarseStructuralFactor lam D - k ≤ _ at haccuracy + linarith + exact_mod_cast hcandidateReal + +/-- A dyadic guess in `[d,2d)` has the manuscript's coarse polynomial +distortion after actual threshold reconstruction and fresh padding. -/ +theorem coarseInitialCandidate_upper {α : Type u} [DecidableEq α] + (B D : ℕ) (Q lam : ℚ) (x y : List α) + (i : CoarseGuessIndex (coarseEntryWidth x y)) (draws : CoarseThresholdDraws B D) + (hcapacity : coarseEntryWidth x y ≤ B ^ D) + (hQ : 0 ≤ Q) (hlam : 0 ≤ lam) (hlamone : lam < 1) + (hfactor : coarseStructuralFactor lam D ≤ 2) + (hevent : let k := coarseGuess (coarseEntryWidth x y) i + CoarseAccuracyEvent k Q lam + (coarseTargetFrame k (coarsePadTo (coarseEntryWidth x y) y)) + (coarseEntryTree B D x y) draws k 0) + (hguess : edit (coarsePadTo (coarseEntryWidth x y) x) + (coarsePadTo (coarseEntryWidth x y) y) ≤ coarseGuess (coarseEntryWidth x y) i) + (hguessUpper : coarseGuess (coarseEntryWidth x y) i < + 2 * edit (coarsePadTo (coarseEntryWidth x y) x) (coarsePadTo (coarseEntryWidth x y) y)) : + coarseInitialCandidate B D Q lam x y i draws ≤ ((25 + 16 * B * D) * edit x y : ℕ) := by + let k := coarseGuess (coarseEntryWidth x y) i + let tree := coarseEntryTree B D x y + let target := coarsePadTo (coarseEntryWidth x y) y + have hword := coarseEntryTree_word B D x y hcapacity + have htrue := coarseTreeValue_edit_upper tree target k (by simpa only [tree, target, k, hword] using hguess) + have hpadding := (coarsePadding_distance_bounds x y).2 + rw [← hword] at hpadding hguessUpper + have htrueReal : (coarseTreeValue tree target k : ℝ) ≤ + (1 + 2 * (B : ℝ) * D) * edit tree.word target := by exact_mod_cast htrue + have hpaddingReal : (edit tree.word target : ℝ) ≤ 2 * edit x y := by exact_mod_cast hpadding + have hguessReal : (k : ℝ) < 2 * edit tree.word target := by exact_mod_cast hguessUpper + have haccuracy := (coarseThresholdEstimate_accurate k Q lam (coarseTargetFrame k target) + tree draws k 0 hQ hlam hlamone (by positivity) hevent (coarseRootShift k)).2 + change _ ≤ coarseStructuralFactor lam D * (coarseTreeValue tree target k : ℝ) + k at haccuracy + have hfactorBound : coarseStructuralFactor lam D * (coarseTreeValue tree target k : ℝ) ≤ + 2 * coarseTreeValue tree target k := mul_le_mul_of_nonneg_right hfactor (by positivity) + have hdistortion := mul_le_mul_of_nonneg_left hpaddingReal + (show (0 : ℝ) ≤ 12 + 8 * (B : ℝ) * D by positivity) + have hcandidateReal : (coarseInitialCandidate B D Q lam x y i draws : ℝ) ≤ + ((25 + 16 * B * D) * edit x y : ℕ) := by + simp only [coarseInitialCandidate, Rat.cast_mul, Rat.cast_add, Rat.cast_ofNat, Rat.cast_natCast] + change 2 * ((coarseThresholdEstimate k Q lam (coarseTargetFrame k target) + tree draws k 0 (coarseRootShift k) : ℝ) + k) ≤ _ + push_cast + nlinarith [show (0 : ℝ) ≤ edit x y by positivity] + exact_mod_cast hcandidateReal + +/-- On the proved finite-tree events, the executable initial table entry +is an integer between the actual edit cost and its stated coarse factor. -/ +theorem coarseInitialValue_bounds {α : Type u} [DecidableEq α] + (B D : ℕ) (Q lam : ℚ) (N : ℕ) (x y : List α) + (draws : CoarseGuessIndex (coarseEntryWidth x y) → CoarseThresholdDraws B D) + (hcapacity : coarseEntryWidth x y ≤ B ^ D) (hN : coarseEntryWidth x y ≤ N) + (hQ : 0 ≤ Q) (hlam : 0 ≤ lam) (hlamone : lam < 1) + (hfactor : coarseStructuralFactor lam D ≤ 2) + (hevent : CoarseInitialAccuracyEvent B D Q lam x y draws) : + edit x y ≤ coarseInitialValue B D Q lam N x y draws ∧ + coarseInitialValue B D Q lam N x y draws ≤ (25 + 16 * B * D) * edit x y := by + have hcN : edit x y ≤ N := (edit_le_max_length x y).trans hN + by_cases hlong : 2 * x.length < y.length + · have hlength := (cost_length_bounds (s := true) x y).2 + change y.length ≤ x.length + edit x y at hlength + have hcost : edit x y ≤ y.length := + (edit_le_max_length x y).trans_eq (max_eq_right (by omega)) + simp only [coarseInitialValue, hlong, ↓reduceIte] + have hlongUpper : y.length ≤ 2 * edit x y := by omega + have hfactorNat : 2 ≤ 25 + 16 * B * D := by omega + exact ⟨le_min hcN hcost, (min_le_right _ _).trans + (hlongUpper.trans (Nat.mul_le_mul_right _ hfactorNat))⟩ + · by_cases hxy : x = y + · subst y + have hrefl : edit x x = 0 := cost_refl x + simp only [coarseInitialValue, hlong, ↓reduceIte, hrefl, mul_zero, le_refl, and_self] + · let d := edit (coarsePadTo (coarseEntryWidth x y) x) (coarsePadTo (coarseEntryWidth x y) y) + have hc : 0 < edit x y := Nat.pos_of_ne_zero + (fun hz => hxy ((cost_eq_zero_iff (s := true)).mp hz)) + have hpadding := (coarsePadding_distance_bounds x y).1 + have hd : 0 < d := lt_of_lt_of_le hc hpadding + have hdn : d ≤ coarseEntryWidth x y := by + have h := edit_le_max_length (coarsePadTo (coarseEntryWidth x y) x) + (coarsePadTo (coarseEntryWidth x y) y) + rw [coarsePadTo_length _ _ (le_max_left _ _), + coarsePadTo_length _ _ (le_max_right _ _), max_self] at h + exact h + obtain ⟨i, hi, hiUpper⟩ := coarse_good_dyadic_guess (coarseEntryWidth x y) d hd hdn + have hminimumLower : (edit x y : ℚ) ≤ coarseInitialMinimum B D Q lam x y draws := by + unfold coarseInitialMinimum + apply le_inf' + intro j hj + exact coarseInitialCandidate_lower B D Q lam x y j (draws j) hcapacity + hQ hlam hlamone hfactor (hevent j) + have hminimumUpper : coarseInitialMinimum B D Q lam x y draws ≤ + ((25 + 16 * B * D) * edit x y : ℕ) := by + unfold coarseInitialMinimum + exact (inf'_le (fun j => coarseInitialCandidate B D Q lam x y j (draws j)) (mem_univ i)).trans + (coarseInitialCandidate_upper B D Q lam x y i (draws i) hcapacity + hQ hlam hlamone hfactor (hevent i) hi hiUpper) + have hceilLower : edit x y ≤ ⌈coarseInitialMinimum B D Q lam x y draws⌉₊ := by + exact_mod_cast hminimumLower.trans (Nat.le_ceil _) + have hceilUpper : ⌈coarseInitialMinimum B D Q lam x y draws⌉₊ ≤ + (25 + 16 * B * D) * edit x y := Nat.ceil_le.mpr hminimumUpper + simp only [coarseInitialValue, hlong, hxy, ↓reduceIte] + exact ⟨le_min hcN hceilLower, (min_le_right _ _).trans hceilUpper⟩ + +/-- Independent finite coarse streams for the listed dyadic guesses. -/ + + +instance coarseInitialMeasure_isProbabilityMeasure (B D n : ℕ) [NeZero B] + [MeasurableSpace (Fin B)] [MeasurableSingletonClass (Fin B)] : + IsProbabilityMeasure (coarseInitialMeasure B D n) := by + unfold coarseInitialMeasure + infer_instance + +/-- The dyadic seed event has an explicit finite failure bound under +the scalar Bernstein hypothesis. -/ +theorem coarseInitialAccuracyEvent_failure {B D : ℕ} [NeZero B] {α : Type u} [DecidableEq α] + [MeasurableSpace (Fin B)] [MeasurableSingletonClass (Fin B)] + (Q lam : ℚ) (x y : List α) + (hQ : 2 ≤ Q) (hlam : 0 < lam) (hlamone : lam < 1) + (bernstein : FiniteBernsteinInput (Measure.pi fun _ : Fin B => + (PMF.uniformOfFintype (Fin B)).toMeasure)) : + (coarseInitialMeasure B D (coarseEntryWidth x y)).real + {draws | ¬ CoarseInitialAccuracyEvent B D Q lam x y draws} ≤ + (Nat.clog 2 (coarseEntryWidth x y) + 1 : ℕ) * (coarseInternalNodes B D : ℝ) * + (4 * (2 * 2 ^ Nat.clog 2 (coarseEntryWidth x y) + 1 : ℕ) * + Real.exp (-(lam : ℝ) * Q / 12)) := by + classical + let n := coarseEntryWidth x y + let μ := coarseInitialMeasure B D n + let bad (i : CoarseGuessIndex n) : Set (CoarseThresholdDraws B D) := + {draws | ¬ CoarseAccuracyEvent (coarseGuess n i) Q lam + (coarseTargetFrame (coarseGuess n i) (coarsePadTo n y)) + (coarseEntryTree B D x y) draws (coarseGuess n i) 0} + have hsubset : {draws | ¬ CoarseInitialAccuracyEvent B D Q lam x y draws} ⊆ + ⋃ i, {draws | draws i ∈ bad i} := by + intro draws hdraws + obtain ⟨i, hi⟩ := not_forall.mp hdraws + exact Set.mem_iUnion.mpr ⟨i, hi⟩ + have hprojection (i : CoarseGuessIndex n) : + μ.real {draws | draws i ∈ bad i} = (coarseDrawMeasure B D).real (bad i) := by + have hmap := (measurePreserving_eval (μ := fun _ : CoarseGuessIndex n => coarseDrawMeasure B D) i).map_eq + have hpreimage := Measure.map_apply (μ := Measure.pi fun _ : CoarseGuessIndex n => coarseDrawMeasure B D) + (measurable_pi_apply i) (Set.toFinite (bad i)).measurableSet + rw [hmap] at hpreimage + exact congrArg ENNReal.toReal hpreimage.symm + have hpoint (i : CoarseGuessIndex n) : μ.real {draws | draws i ∈ bad i} ≤ + (coarseInternalNodes B D : ℝ) * + (4 * (2 * 2 ^ Nat.clog 2 n + 1 : ℕ) * Real.exp (-(lam : ℝ) * Q / 12)) := by + rw [hprojection] + have hfailure := coarseAccuracyEvent_failure (coarseGuess n i) Q lam + (coarseTargetFrame (coarseGuess n i) (coarsePadTo n y)) + (coarseEntryTree B D x y) (coarseGuess n i) 0 hQ hlam hlamone (by dsimp [coarseGuess]; positivity) + bernstein + have hk : coarseGuess n i ≤ 2 ^ Nat.clog 2 n := + Nat.pow_le_pow_right (by decide : 0 < 2) (by exact Nat.le_of_lt_succ i.isLt) + apply hfailure.trans + gcongr + calc + _ ≤ μ.real (⋃ i, {draws | draws i ∈ bad i}) := measureReal_mono hsubset + _ ≤ ∑ i, μ.real {draws | draws i ∈ bad i} := measureReal_iUnion_fintype_le _ + _ ≤ ∑ _ : CoarseGuessIndex n, (coarseInternalNodes B D : ℝ) * + (4 * (2 * 2 ^ Nat.clog 2 n + 1 : ℕ) * Real.exp (-(lam : ℝ) * Q / 12)) := + sum_le_sum (fun i _ => hpoint i) + _ = _ := by + simp only [sum_const, card_univ, nsmul_eq_mul, CoarseGuessIndex, Fintype.card_fin] + dsimp [n] + ring + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseInitialAllocation.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseInitialAllocation.lean new file mode 100644 index 0000000000000000000000000000000000000000..786a111ccdd4705e575300f4e1520201c4fdcf17 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseInitialAllocation.lean @@ -0,0 +1,182 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseIndexedAllocation +import OAI.Combinatorics.EditApproximation.Coarse.CoarseIndexedInitial +import OAI.Combinatorics.EditApproximation.Refinement.ComputedCoarsePolynomial + +namespace OAI + +namespace EditApproximation + +/-- Besides each result cell, reserve one index-list cell for each callback. -/ +theorem arithmeticMapAllocation_with_indices_le_work {α β : Type*} (f : α → β × ℕ) + (allocation : α → ℕ) (values : List α) + (h : ∀ a ∈ values, allocation a ≤ 2 * (f a).2) : + arithmeticMapAllocation allocation values + values.length ≤ + 2 * (arithmeticMapWithWork f values).2 := by + induction values with + | nil => rfl + | cons a rest ih => + have hh := h a List.mem_cons_self + have ht := ih (fun b hb => h b (List.mem_cons_of_mem _ hb)) + simp only [arithmeticMapAllocation, arithmeticMapWithWork, List.length_cons] + omega + +namespace BinaryFraction + +def coarseIndexedRootAllocation {B d : ℕ} (k q L : ℕ) + (hB : 0 < B) (hq : 0 < q) (hL : 0 < L) (x y : List ℕ) + (draws : CoarseThresholdDraws B d) : ℕ := + let den := coarseRootDenominator B q L d + let denPos := coarseRootDenominator_pos B q L d hB hq hL + let two := coarseGridNatWithWork den.1 denPos 2 + let allowance := coarseGridNatWithWork den.1 denPos k + coarseDenominatorAllocation (1 : ℕ).bits q.bits L.bits B.bits d + + coarseGridNatAllocation den.1 denPos 2 + coarseGridNatAllocation den.1 denPos k + + coarseIndexedAllocation k q L (coarseEntryWidth x y) x y two.1 d 0 draws allowance.1 0 + +theorem coarseIndexedRootAllocation_le_work {B d : ℕ} (k q L : ℕ) + (hB : 0 < B) (hq : 0 < q) (hL : 0 < L) (x y : List ℕ) + (draws : CoarseThresholdDraws B d) : + coarseIndexedRootAllocation k q L hB hq hL x y draws ≤ + 2 * (coarseIndexedRootWithWork k q L hB hq hL x y draws).2 := by + let den := coarseRootDenominator B q L d + let denPos := coarseRootDenominator_pos B q L d hB hq hL + have hd := coarseDenominatorAllocation_le_work (1 : ℕ).bits q.bits L.bits B.bits d + have ht := coarseGridNatAllocation_le_work den.1 denPos 2 + have ha := coarseGridNatAllocation_le_work den.1 denPos k + have he := coarseIndexedAllocation_le_work k q L (coarseEntryWidth x y) x y + (coarseGridNatWithWork den.1 denPos 2).1 d 0 draws + (coarseGridNatWithWork den.1 denPos k).1 0 + change coarseDenominatorAllocation (1 : ℕ).bits q.bits L.bits B.bits d ≤ den.2 at hd + unfold coarseIndexedRootAllocation coarseIndexedRootWithWork + change coarseDenominatorAllocation (1 : ℕ).bits q.bits L.bits B.bits d + + coarseGridNatAllocation den.1 denPos 2 + coarseGridNatAllocation den.1 denPos k + + coarseIndexedAllocation k q L (coarseEntryWidth x y) x y + (coarseGridNatWithWork den.1 denPos 2).1 d 0 draws + (coarseGridNatWithWork den.1 denPos k).1 0 ≤ + 2 * (den.2 + (coarseGridNatWithWork den.1 denPos 2).2 + + (coarseGridNatWithWork den.1 denPos k).2 + + (coarseIndexedWithWork k q L (coarseEntryWidth x y) x y + (coarseGridNatWithWork den.1 denPos 2).1 d 0 draws + (coarseGridNatWithWork den.1 denPos k).1 0).2 + 1) + omega + +def coarseIndexedCandidateAllocation {B d : ℕ} (q L : ℕ) + (hB : 0 < B) (hq : 0 < q) (hL : 0 < L) (x y : List ℕ) + (i : CoarseGuessIndex (coarseEntryWidth x y)) (draws : CoarseThresholdDraws B d) : ℕ := + let k := coarseGuess (coarseEntryWidth x y) i + let root := coarseIndexedRootWithWork k q L hB hq hL x y draws + let shifted := canonicalAddWithWork root.1 (nat k) + coarseIndexedRootAllocation k q L hB hq hL x y draws + + canonicalAddAllocation root.1 (nat k) + canonicalMulAllocation (nat 2) shifted.1 + Nat.size k + +theorem coarseIndexedCandidateAllocation_le_work {B d : ℕ} (q L : ℕ) + (hB : 0 < B) (hq : 0 < q) (hL : 0 < L) (x y : List ℕ) + (i : CoarseGuessIndex (coarseEntryWidth x y)) (draws : CoarseThresholdDraws B d) : + coarseIndexedCandidateAllocation q L hB hq hL x y i draws ≤ + 2 * (coarseIndexedCandidateWithWork q L hB hq hL x y i draws).2 := by + let k := coarseGuess (coarseEntryWidth x y) i + let root := coarseIndexedRootWithWork k q L hB hq hL x y draws + have hr := coarseIndexedRootAllocation_le_work k q L hB hq hL x y draws + have ha := canonicalAddAllocation_le_work root.1 (nat k) + have hm := canonicalMulAllocation_le_work (nat 2) (canonicalAddWithWork root.1 (nat k)).1 + change coarseIndexedRootAllocation k q L hB hq hL x y draws + + canonicalAddAllocation root.1 (nat k) + + canonicalMulAllocation (nat 2) (canonicalAddWithWork root.1 (nat k)).1 + Nat.size k ≤ + 2 * (root.2 + (canonicalAddWithWork root.1 (nat k)).2 + + (canonicalMulWithWork (nat 2) (canonicalAddWithWork root.1 (nat k)).1).2 + Nat.size k + 3) + change coarseIndexedRootAllocation k q L hB hq hL x y draws ≤ 2 * root.2 at hr + omega + +def coarseMinimumListAllocation (fallback : BinaryFraction) : List BinaryFraction → ℕ + | [] => 0 + | head :: rest => coarseMinimumListAllocation fallback rest + head.ltAllocation (minimumWithWork fallback rest).1 + +theorem coarseMinimumListAllocation_le_work (fallback : BinaryFraction) (values : List BinaryFraction) : + coarseMinimumListAllocation fallback values ≤ (minimumWithWork fallback values).2 := by + induction values with + | nil => exact Nat.zero_le _ + | cons head rest ih => + have h := ltAllocation_le_work head (minimumWithWork fallback rest).1 + simp only [coarseMinimumListAllocation, minimumWithWork, minWithWork] + omega + +def coarseMinimumAllocation : List BinaryFraction → ℕ + | [] => 0 + | a :: rest => coarseMinimumListAllocation a rest + +theorem coarseMinimumAllocation_le_work (values : List BinaryFraction) : + coarseMinimumAllocation values ≤ (coarseMinimumWithWork values).2 := by + cases values with + | nil => exact Nat.zero_le _ + | cons a rest => exact coarseMinimumListAllocation_le_work a rest + +/-- Fresh arithmetic cells and root/index list spines. Constant words and +preexisting input/cached words are shared. The retained input and output +words are counted separately by the global storage capacity. -/ +def coarseIndexedInitialAllocation {B d : ℕ} (q L N : ℕ) + (hB : 0 < B) (hq : 0 < q) (hL : 0 < L) (x y : List ℕ) + (draws : CoarseGuessIndex (coarseEntryWidth x y) → CoarseThresholdDraws B d) : ℕ := + let long := binaryNaturalCompareWithWork (2 * x.length) y.length + if long.1 = .lt then 0 else + let equal := naturalListEqualWithWork x y + if equal.1 then 0 else + let indices := List.finRange (Nat.clog 2 (coarseEntryWidth x y) + 1) + let roots := arithmeticMapWithWork (fun i => coarseIndexedCandidateWithWork q L hB hq hL x y i (draws i)) indices + let smallest := coarseMinimumWithWork roots.1 + arithmeticMapAllocation (fun i => coarseIndexedCandidateAllocation q L hB hq hL x y i (draws i)) indices + + indices.length + coarseMinimumAllocation roots.1 + naturalCeilingAllocation smallest.1 + Nat.size N + +theorem coarseIndexedInitialAllocation_le_work {B d : ℕ} (q L N : ℕ) + (hB : 0 < B) (hq : 0 < q) (hL : 0 < L) (x y : List ℕ) + (draws : CoarseGuessIndex (coarseEntryWidth x y) → CoarseThresholdDraws B d) : + coarseIndexedInitialAllocation q L N hB hq hL x y draws ≤ + 2 * (coarseIndexedInitialWithWork q L N hB hq hL x y draws).2 := by + let indices := List.finRange (Nat.clog 2 (coarseEntryWidth x y) + 1) + let roots := arithmeticMapWithWork (fun i => coarseIndexedCandidateWithWork q L hB hq hL x y i (draws i)) indices + have hr := arithmeticMapAllocation_with_indices_le_work + (fun i => coarseIndexedCandidateWithWork q L hB hq hL x y i (draws i)) + (fun i => coarseIndexedCandidateAllocation q L hB hq hL x y i (draws i)) indices + (fun i _ => coarseIndexedCandidateAllocation_le_work q L hB hq hL x y i (draws i)) + have hm := coarseMinimumAllocation_le_work roots.1 + have hc := naturalCeilingAllocation_le_work (coarseMinimumWithWork roots.1).1 + unfold coarseIndexedInitialAllocation coarseIndexedInitialWithWork + dsimp only + split_ifs + · exact Nat.zero_le _ + · exact Nat.zero_le _ + · change arithmeticMapAllocation + (fun i => coarseIndexedCandidateAllocation q L hB hq hL x y i (draws i)) indices + + indices.length + coarseMinimumAllocation roots.1 + + naturalCeilingAllocation (coarseMinimumWithWork roots.1).1 + Nat.size N ≤ + 2 * ((binaryNaturalCompareWithWork (2 * x.length) y.length).2 + + (naturalListEqualWithWork x y).2 + roots.2 + (coarseMinimumWithWork roots.1).2 + + (naturalCeilingWithWork (coarseMinimumWithWork roots.1).1).2 + + (wordMinWithWork N.bits (naturalCeilingWithWork (coarseMinimumWithWork roots.1).1).1).2 + Nat.size N + 6) + change arithmeticMapAllocation + (fun i => coarseIndexedCandidateAllocation q L hB hq hL x y i (draws i)) indices + + indices.length ≤ 2 * roots.2 at hr + omega + +open Filter in +/-- Every draw has polynomial scratch, including outcomes outside the success event. -/ +theorem computedCoarseIndexedInitialAllocation_polynomial : + ∀ᶠ N : ℕ in atTop, ∀ B d : ℕ, ∀ x y : List ℕ, + B = (integerParameters N).B → d = computedCoarseDepth N (coarseEntryWidth x y) → + coarseEntryWidth x y ≤ N → (∀ a ∈ x ++ y, Nat.size a ≤ inputHeight N ^ 3) → + ∀ (hB : 0 < B) (hq : 0 < inputHeight N ^ 4) (hL : 0 < 64 * inputHeight N) + (draws : CoarseGuessIndex (coarseEntryWidth x y) → CoarseThresholdDraws B d), + coarseIndexedInitialAllocation (inputHeight N ^ 4) (64 * inputHeight N) N + hB hq hL x y draws ≤ (N + 2) ^ 181 := by + filter_upwards [computedCoarseIndexedInitialWithWork_polynomial] with N hN + intro B d x y hBdef hddef hsize hsymbols hB hq hL draws + have hw := hN B d x y hBdef hddef hsize hsymbols hB hq hL draws + have ha := coarseIndexedInitialAllocation_le_work (inputHeight N ^ 4) (64 * inputHeight N) N hB hq hL x y draws + calc + _ ≤ 2 * (N + 2) ^ 180 := ha.trans (Nat.mul_le_mul_left 2 hw) + _ ≤ (N + 2) * (N + 2) ^ 180 := Nat.mul_le_mul_right _ (by omega) + _ = _ := (pow_succ' (N + 2) 180).symm + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseInitialBinary.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseInitialBinary.lean new file mode 100644 index 0000000000000000000000000000000000000000..4bba8bc00e27e0762fbb21efdabd06e32e58dfa8 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseInitialBinary.lean @@ -0,0 +1,96 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseRootExecution +import OAI.Combinatorics.EditApproximation.Binary.BinaryMedianKernel +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation +namespace BinaryFraction + +/-- The empty case is unreachable for the dyadic guess list. The fallback +is its already computed first entry, so no coarse call is repeated. -/ + + +private theorem rationalMinimum_lower (fallback : ℚ) (values : List ℚ) (z : ℚ) + (hf : z ≤ fallback) (hv : ∀ a ∈ values, z ≤ a) : z ≤ rationalMinimum fallback values := by + induction values with + | nil => exact hf + | cons a rest ih => + exact le_min (hv a List.mem_cons_self) + (ih (fun b hb => hv b (List.mem_cons_of_mem _ hb))) + +private theorem rationalMinimum_le_mem (fallback : ℚ) (values : List ℚ) (z : ℚ) + (hz : z ∈ values) : rationalMinimum fallback values ≤ z := by + induction values with + | nil => cases hz + | cons a rest ih => + rcases List.mem_cons.mp hz with rfl | hz + · exact min_le_left _ _ + · exact (min_le_right _ _).trans (ih hz) + +private theorem rationalMinimum_le_fallback (fallback : ℚ) (values : List ℚ) : + rationalMinimum fallback values ≤ fallback := by + induction values with + | nil => exact le_rfl + | cons a rest ih => exact (min_le_right _ _).trans ih + + theorem coarseMinimumWithWork_ofFn {n : ℕ} [NeZero n] (f : Fin n → BinaryFraction) : + (coarseMinimumWithWork (List.ofFn f)).1.value = + Finset.univ.inf' Finset.univ_nonempty (fun i => (f i).value) := by + have hn : 0 < n := Nat.pos_of_neZero n + have hne : List.ofFn f ≠ [] := by + intro h + have := congrArg List.length h + simp only [List.length_ofFn, List.length_nil] at this + omega + obtain ⟨a, rest, heq⟩ := List.exists_cons_of_ne_nil hne + rw [heq, coarseMinimumWithWork, minimumWithWork_value] + apply le_antisymm + · apply Finset.le_inf' + intro i _ + have hm : f i ∈ a :: rest := heq ▸ List.mem_ofFn.mpr ⟨i, rfl⟩ + rcases List.mem_cons.mp hm with h | h + · rw [h] + exact rationalMinimum_le_fallback _ _ + · exact rationalMinimum_le_mem _ _ _ (List.mem_map.mpr ⟨f i, h, rfl⟩) + · apply rationalMinimum_lower + · obtain ⟨i, hi⟩ := List.mem_ofFn.mp (heq.symm ▸ List.mem_cons_self (a := a) (l := rest)) + rw [← hi] + exact Finset.inf'_le _ (Finset.mem_univ i) + · intro z hz + obtain ⟨b, hb, rfl⟩ := List.mem_map.mp hz + obtain ⟨i, hi⟩ := List.mem_ofFn.mp (heq.symm ▸ List.mem_cons_of_mem a hb) + rw [← hi] + exact Finset.inf'_le _ (Finset.mem_univ i) + +/-- A candidate executes the whole root recurrence, then adds its literal +guess and doubles the result using Boolean arithmetic. -/ +def coarseCandidateWithWork {B d : ℕ} {α : Type*} [DecidableEq α] + (q L : ℕ) (hB : 0 < B) (hq : 0 < q) (hL : 0 < L) (x y : List α) + (i : CoarseGuessIndex (coarseEntryWidth x y)) (draws : CoarseThresholdDraws B d) : + BinaryFraction × ℕ := + let k := coarseGuess (coarseEntryWidth x y) i + let root := coarseRootWithWork k q L hB hq hL + (coarseTargetFrame k (coarsePadTo (coarseEntryWidth x y) y)) + (coarseEntryTree B d x y) draws 0 (coarseRootShift k) + let shifted := canonicalAddWithWork root.1 (nat k) + let doubled := canonicalMulWithWork (nat 2) shifted.1 + (doubled.1, root.2 + shifted.2 + doubled.2 + Nat.size k + 3) + + theorem coarseCandidateWithWork_value {B d : ℕ} {α : Type*} [DecidableEq α] + (q L : ℕ) (hB : 0 < B) (hq : 0 < q) (hL : 0 < L) (x y : List α) + (i : CoarseGuessIndex (coarseEntryWidth x y)) (draws : CoarseThresholdDraws B d) : + (coarseCandidateWithWork q L hB hq hL x y i draws).1.value = + coarseInitialCandidate B d q (1 / L) x y i draws := by + unfold coarseCandidateWithWork + dsimp only + rw [canonicalMulWithWork_value, canonicalAddWithWork_value, nat_value, nat_value, + coarseRootWithWork_value] + · rfl + · unfold coarseGuess; positivity + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseInitialControlSpace.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseInitialControlSpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..678a8e721a82914ab473a20682c290c35b4be4d5 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseInitialControlSpace.lean @@ -0,0 +1,203 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseIndexedControlSpace +import OAI.Combinatorics.EditApproximation.Coarse.CoarseIndexedInitial +import OAI.Combinatorics.EditApproximation.Refinement.ComputedCoarsePolynomial + +namespace OAI + +namespace EditApproximation + +namespace BinaryFraction + +def coarseIndexedRootInvocations {B d : ℕ} (k q L : ℕ) + (hB : 0 < B) (hq : 0 < q) (hL : 0 < L) (x y : List ℕ) + (draws : CoarseThresholdDraws B d) : ℕ := + let den := coarseRootDenominator B q L d + let denPos := coarseRootDenominator_pos B q L d hB hq hL + let two := coarseGridNatWithWork den.1 denPos 2 + let allowance := coarseGridNatWithWork den.1 denPos k + coarseDenominatorInvocations (1 : ℕ).bits q.bits L.bits B.bits d + + coarseGridNatInvocations den.1 denPos 2 + coarseGridNatInvocations den.1 denPos k + + coarseIndexedInvocations k q L (coarseEntryWidth x y) x y two.1 d 0 draws allowance.1 0 + 1 + +theorem coarseIndexedRootInvocations_le_work {B d : ℕ} (k q L : ℕ) + (hB : 0 < B) (hq : 0 < q) (hL : 0 < L) (x y : List ℕ) + (draws : CoarseThresholdDraws B d) : + coarseIndexedRootInvocations k q L hB hq hL x y draws ≤ + 2 * (coarseIndexedRootWithWork k q L hB hq hL x y draws).2 := by + let den := coarseRootDenominator B q L d + let denPos := coarseRootDenominator_pos B q L d hB hq hL + have hd := coarseDenominatorInvocations_le_work (1 : ℕ).bits q.bits L.bits B.bits d + have ht := coarseGridNatInvocations_le_work den.1 denPos 2 + have ha := coarseGridNatInvocations_le_work den.1 denPos k + have he := coarseIndexedInvocations_le_work k q L (coarseEntryWidth x y) x y + (coarseGridNatWithWork den.1 denPos 2).1 d 0 draws + (coarseGridNatWithWork den.1 denPos k).1 0 + change coarseDenominatorInvocations (1 : ℕ).bits q.bits L.bits B.bits d ≤ den.2 at hd + unfold coarseIndexedRootInvocations coarseIndexedRootWithWork + change coarseDenominatorInvocations (1 : ℕ).bits q.bits L.bits B.bits d + + coarseGridNatInvocations den.1 denPos 2 + coarseGridNatInvocations den.1 denPos k + + coarseIndexedInvocations k q L (coarseEntryWidth x y) x y + (coarseGridNatWithWork den.1 denPos 2).1 d 0 draws + (coarseGridNatWithWork den.1 denPos k).1 0 + 1 ≤ + 2 * (den.2 + (coarseGridNatWithWork den.1 denPos 2).2 + + (coarseGridNatWithWork den.1 denPos k).2 + + (coarseIndexedWithWork k q L (coarseEntryWidth x y) x y + (coarseGridNatWithWork den.1 denPos 2).1 d 0 draws + (coarseGridNatWithWork den.1 denPos k).1 0).2 + 1) + omega + +def coarseIndexedCandidateInvocations {B d : ℕ} (q L : ℕ) + (hB : 0 < B) (hq : 0 < q) (hL : 0 < L) (x y : List ℕ) + (i : CoarseGuessIndex (coarseEntryWidth x y)) (draws : CoarseThresholdDraws B d) : ℕ := + let k := coarseGuess (coarseEntryWidth x y) i + let root := coarseIndexedRootWithWork k q L hB hq hL x y draws + let shifted := canonicalAddWithWork root.1 (nat k) + coarseIndexedRootInvocations k q L hB hq hL x y draws + + canonicalAddInvocations root.1 (nat k) + canonicalMulInvocations (nat 2) shifted.1 + 1 + +theorem coarseIndexedCandidateInvocations_le_work {B d : ℕ} (q L : ℕ) + (hB : 0 < B) (hq : 0 < q) (hL : 0 < L) (x y : List ℕ) + (i : CoarseGuessIndex (coarseEntryWidth x y)) (draws : CoarseThresholdDraws B d) : + coarseIndexedCandidateInvocations q L hB hq hL x y i draws ≤ + 2 * (coarseIndexedCandidateWithWork q L hB hq hL x y i draws).2 := by + let k := coarseGuess (coarseEntryWidth x y) i + let root := coarseIndexedRootWithWork k q L hB hq hL x y draws + have hr := coarseIndexedRootInvocations_le_work k q L hB hq hL x y draws + have ha := canonicalAddInvocations_le_work root.1 (nat k) + have hm := canonicalMulInvocations_le_work (nat 2) (canonicalAddWithWork root.1 (nat k)).1 + change coarseIndexedRootInvocations k q L hB hq hL x y draws + + canonicalAddInvocations root.1 (nat k) + + canonicalMulInvocations (nat 2) (canonicalAddWithWork root.1 (nat k)).1 + 1 ≤ + 2 * (root.2 + (canonicalAddWithWork root.1 (nat k)).2 + + (canonicalMulWithWork (nat 2) (canonicalAddWithWork root.1 (nat k)).1).2 + Nat.size k + 3) + change coarseIndexedRootInvocations k q L hB hq hL x y draws ≤ 2 * root.2 at hr + omega + +def coarseMinimumListInvocations (fallback : BinaryFraction) : List BinaryFraction → ℕ + | [] => 1 + | head :: rest => coarseMinimumListInvocations fallback rest + compareInvocations head (minimumWithWork fallback rest).1 + 2 + +theorem coarseMinimumListInvocations_le_work (fallback : BinaryFraction) (values : List BinaryFraction) : + coarseMinimumListInvocations fallback values ≤ (minimumWithWork fallback values).2 := by + induction values with + | nil => exact Nat.le_refl 1 + | cons head rest ih => + have h := compareInvocations_le_work head (minimumWithWork fallback rest).1 + simp only [coarseMinimumListInvocations, minimumWithWork, minWithWork] + omega + +def coarseMinimumInvocations : List BinaryFraction → ℕ + | [] => 1 + | a :: rest => coarseMinimumListInvocations a rest + 1 + +theorem coarseMinimumInvocations_le_work (values : List BinaryFraction) : + coarseMinimumInvocations values ≤ 2 * (coarseMinimumWithWork values).2 := by + cases values with + | nil => exact (by decide : 1 ≤ 2) + | cons a rest => + have h := coarseMinimumListInvocations_le_work a rest + have hp : 1 ≤ (minimumWithWork a rest).2 := by + cases rest <;> simp only [minimumWithWork] <;> omega + change coarseMinimumListInvocations a rest + 1 ≤ 2 * (minimumWithWork a rest).2 + omega + + +def naturalListEqualInvocations : List ℕ → List ℕ → ℕ + | [], [] => 1 + | a :: left, b :: right => + bitCompareInvocations a.bits b.bits + 2 + + if (naturalEqualWithWork a b).1 then naturalListEqualInvocations left right else 0 + | _, _ => 1 + +theorem naturalListEqualInvocations_le_work (x y : List ℕ) : + naturalListEqualInvocations x y ≤ (naturalListEqualWithWork x y).2 := by + induction x generalizing y with + | nil => cases y <;> exact Nat.le_refl 1 + | cons a left ih => + cases y with + | nil => exact Nat.le_refl 1 + | cons b right => + have ht := ih right + have hc := bitCompareInvocations_le_work a.bits b.bits + simp only [naturalListEqualInvocations, naturalListEqualWithWork] + split_ifs <;> simp only [naturalEqualWithWork, binaryNaturalCompareWithWork] <;> omega + +def coarseIndexedInitialInvocations {B d : ℕ} (q L N : ℕ) + (hB : 0 < B) (hq : 0 < q) (hL : 0 < L) (x y : List ℕ) + (draws : CoarseGuessIndex (coarseEntryWidth x y) → CoarseThresholdDraws B d) : ℕ := + let long := binaryNaturalCompareWithWork (2 * x.length) y.length + let longCalls := bitCompareInvocations (2 * x.length).bits y.length.bits + if long.1 = .lt then longCalls + 1 else + let equal := naturalListEqualWithWork x y + if equal.1 then longCalls + naturalListEqualInvocations x y + 1 else + let indices := List.finRange (Nat.clog 2 (coarseEntryWidth x y) + 1) + let roots := arithmeticMapWithWork (fun i => coarseIndexedCandidateWithWork q L hB hq hL x y i (draws i)) indices + let smallest := coarseMinimumWithWork roots.1 + let rounded := naturalCeilingWithWork smallest.1 + longCalls + naturalListEqualInvocations x y + + arithmeticMapInvocations (fun i => coarseIndexedCandidateInvocations q L hB hq hL x y i (draws i)) indices + + indices.length + 1 + coarseMinimumInvocations roots.1 + naturalCeilingInvocations smallest.1 + + bitCompareInvocations rounded.1 N.bits + 3 + +theorem coarseIndexedInitialInvocations_le_work {B d : ℕ} (q L N : ℕ) + (hB : 0 < B) (hq : 0 < q) (hL : 0 < L) (x y : List ℕ) + (draws : CoarseGuessIndex (coarseEntryWidth x y) → CoarseThresholdDraws B d) : + coarseIndexedInitialInvocations q L N hB hq hL x y draws ≤ + 2 * (coarseIndexedInitialWithWork q L N hB hq hL x y draws).2 := by + let indices := List.finRange (Nat.clog 2 (coarseEntryWidth x y) + 1) + let roots := arithmeticMapWithWork (fun i => coarseIndexedCandidateWithWork q L hB hq hL x y i (draws i)) indices + have hr := arithmeticMapInvocations_with_indices_le_work + (fun i => coarseIndexedCandidateWithWork q L hB hq hL x y i (draws i)) + (fun i => coarseIndexedCandidateInvocations q L hB hq hL x y i (draws i)) indices + (fun i _ => (coarseIndexedCandidateInvocations_le_work q L hB hq hL x y i (draws i)).trans (Nat.le_succ _)) + have hm := coarseMinimumInvocations_le_work roots.1 + have hc := naturalCeilingInvocations_le_work (coarseMinimumWithWork roots.1).1 + have hl := bitCompareInvocations_le_work (2 * x.length).bits y.length.bits + have he := naturalListEqualInvocations_le_work x y + have hf := bitCompareInvocations_le_work + (naturalCeilingWithWork (coarseMinimumWithWork roots.1).1).1 N.bits + unfold coarseIndexedInitialInvocations coarseIndexedInitialWithWork + dsimp only + split_ifs + · simp only [binaryNaturalCompareWithWork] at * + omega + · simp only [binaryNaturalCompareWithWork] at * + omega + · change bitCompareInvocations (2 * x.length).bits y.length.bits + naturalListEqualInvocations x y + + arithmeticMapInvocations + (fun i => coarseIndexedCandidateInvocations q L hB hq hL x y i (draws i)) indices + + indices.length + 1 + coarseMinimumInvocations roots.1 + + naturalCeilingInvocations (coarseMinimumWithWork roots.1).1 + + bitCompareInvocations (naturalCeilingWithWork (coarseMinimumWithWork roots.1).1).1 N.bits + 3 ≤ + 2 * ((binaryNaturalCompareWithWork (2 * x.length) y.length).2 + + (naturalListEqualWithWork x y).2 + roots.2 + (coarseMinimumWithWork roots.1).2 + + (naturalCeilingWithWork (coarseMinimumWithWork roots.1).1).2 + + (wordMinWithWork N.bits (naturalCeilingWithWork (coarseMinimumWithWork roots.1).1).1).2 + Nat.size N + 6) + change arithmeticMapInvocations + (fun i => coarseIndexedCandidateInvocations q L hB hq hL x y i (draws i)) indices + + indices.length + 1 ≤ 2 * roots.2 + 2 at hr + simp only [binaryNaturalCompareWithWork, wordMinWithWork, wordLEWithWork] + omega + +open Filter in +theorem computedCoarseIndexedInitialInvocations_polynomial : + ∀ᶠ N : ℕ in atTop, ∀ B d : ℕ, ∀ x y : List ℕ, + B = (integerParameters N).B → d = computedCoarseDepth N (coarseEntryWidth x y) → + coarseEntryWidth x y ≤ N → (∀ a ∈ x ++ y, Nat.size a ≤ inputHeight N ^ 3) → + ∀ (hB : 0 < B) (hq : 0 < inputHeight N ^ 4) (hL : 0 < 64 * inputHeight N) + (draws : CoarseGuessIndex (coarseEntryWidth x y) → CoarseThresholdDraws B d), + coarseIndexedInitialInvocations (inputHeight N ^ 4) (64 * inputHeight N) N + hB hq hL x y draws ≤ (N + 2) ^ 181 := by + filter_upwards [computedCoarseIndexedInitialWithWork_polynomial] with N hN + intro B d x y hBdef hddef hsize hsymbols hB hq hL draws + have hw := hN B d x y hBdef hddef hsize hsymbols hB hq hL draws + have ha := coarseIndexedInitialInvocations_le_work (inputHeight N ^ 4) (64 * inputHeight N) N hB hq hL x y draws + calc + _ ≤ 2 * (N + 2) ^ 180 := ha.trans (Nat.mul_le_mul_left 2 hw) + _ ≤ (N + 2) * (N + 2) ^ 180 := Nat.mul_le_mul_right _ (by omega) + _ = _ := (pow_succ' (N + 2) 180).symm + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseInitialCost.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseInitialCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..d28e365bead5edd7ebb401e443838f67857dc307 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseInitialCost.lean @@ -0,0 +1,78 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseInitialWorkBounds + +namespace OAI + +namespace EditApproximation +namespace BinaryFraction + +/-- The dyadic wrapper adds only comparisons, a scan, ceiling, and clamp +beyond the sum of the actually executed candidate counters. -/ +theorem coarseInitialWithWork_cost {B d : ℕ} (q L N A S : ℕ) + (hB : 0 < B) (hq : 0 < q) (hL : 0 < L) (x y : List ℕ) + (draws : CoarseGuessIndex (coarseEntryWidth x y) → CoarseThresholdDraws B d) + (hA : 2 ≤ A) (hN : Nat.size N ≤ A) + (hx : Nat.size x.length ≤ A) (hy : Nat.size y.length ≤ A) + (hs : ∀ a ∈ x ++ y, Nat.size a ≤ S) + (hc : ∀ i, (coarseCandidateWithWork q L hB hq hL x y i (draws i)).1.width ≤ A) : + (coarseInitialWithWork q L N hB hq hL x y draws).2 ≤ + ((List.finRange (Nat.clog 2 (coarseEntryWidth x y) + 1)).map + (fun i => (coarseCandidateWithWork q L hB hq hL x y i (draws i)).2)).sum + + (x.length + y.length + 1) * (8 * S + 4) + + 10000 * (Nat.clog 2 (coarseEntryWidth x y) + 2) * (A + 2) ^ 2 := by + let f := fun i => coarseCandidateWithWork q L hB hq hL x y i (draws i) + let indices := List.finRange (Nat.clog 2 (coarseEntryWidth x y) + 1) + let roots := arithmeticMapWithWork f indices + have hl := binaryNaturalCompareWithWork_cost (2 * x.length) y.length + have hxl := natural_product_bit_length 2 x.length + rw [show Nat.size 2 = 2 by decide] at hxl + have hlong : (binaryNaturalCompareWithWork (2 * x.length) y.length).2 ≤ 8 * A + 9 := by omega + have hequal := naturalListEqualWithWork_cost x y S hs + have hw : ∀ a ∈ roots.1, a.width ≤ A := by + intro a ha + rw [arithmeticMapWithWork_value] at ha + obtain ⟨i, _, rfl⟩ := List.mem_map.mp ha + exact hc i + have hm := coarseMinimumWithWork_bounds roots.1 A hA hw + have hlen : roots.1.length = Nat.clog 2 (coarseEntryWidth x y) + 1 := by + simp only [roots, arithmeticMapWithWork_value, List.length_map, indices, List.length_finRange] + rw [hlen] at hm + have hr := naturalCeilingWithWork_cost (coarseMinimumWithWork roots.1).1 + have hrw := naturalCeilingWithWork_length (coarseMinimumWithWork roots.1).1 + have hr' : (naturalCeilingWithWork (coarseMinimumWithWork roots.1).1).2 ≤ 500 * (A + 1) ^ 2 := + hr.trans (Nat.mul_le_mul_left 500 (Nat.pow_le_pow_left (by omega) 2)) + have hcmp := wordLEWithWork_cost N.bits (naturalCeilingWithWork (coarseMinimumWithWork roots.1).1).1 + rw [Nat.size_eq_bits_len] at hcmp + have hclamp : (wordMinWithWork N.bits (naturalCeilingWithWork (coarseMinimumWithWork roots.1).1).1).2 ≤ + 8 * A + 11 := by + change (wordLEWithWork _ _).2 + 1 ≤ _ + omega + have hmap := arithmeticMapWithWork_total f indices + change roots.2 = _ at hmap + have hmap' : roots.2 = (indices.map (fun i => (f i).2)).sum + + 3 * (Nat.clog 2 (coarseEntryWidth x y) + 1) := by + simpa only [indices, List.length_finRange] using hmap + change _ ≤ (indices.map (fun i => (f i).2)).sum + _ + _ + unfold coarseInitialWithWork + dsimp only + split_ifs + · dsimp only + nlinarith only [hlong, hA, hN, hy, + Nat.zero_le ((indices.map (fun i => (f i).2)).sum), + Nat.zero_le ((x.length + y.length + 1) * (8 * S + 4)), + Nat.zero_le (Nat.clog 2 (coarseEntryWidth x y))] + · dsimp only + nlinarith only [hlong, hequal, hA, + Nat.zero_le ((indices.map (fun i => (f i).2)).sum), + Nat.zero_le (Nat.clog 2 (coarseEntryWidth x y))] + · change _ + _ + roots.2 + (coarseMinimumWithWork roots.1).2 + + (naturalCeilingWithWork (coarseMinimumWithWork roots.1).1).2 + + (wordMinWithWork N.bits (naturalCeilingWithWork (coarseMinimumWithWork roots.1).1).1).2 + + Nat.size N + 6 ≤ _ + rw [hmap'] + nlinarith only [hlong, hequal, hm.2, hr', hclamp, hA, hN, + Nat.zero_le (Nat.clog 2 (coarseEntryWidth x y))] + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseInitialExecution.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseInitialExecution.lean new file mode 100644 index 0000000000000000000000000000000000000000..7dfab79722f63e21aede0c43c9963340661ea117 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseInitialExecution.lean @@ -0,0 +1,76 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseInitialBinary +import OAI.Combinatorics.EditApproximation.Binary.BinaryBandGuardWork +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation +namespace BinaryFraction + + + + theorem naturalListEqualWithWork_value (x y : List ℕ) : + (naturalListEqualWithWork x y).1 = true ↔ x = y := by + induction x generalizing y with + | nil => cases y <;> simp [naturalListEqualWithWork] + | cons a left ih => + cases y with + | nil => simp [naturalListEqualWithWork] + | cons b right => + simp only [naturalListEqualWithWork] + by_cases hab : a = b + · rw [ite_eq_left ((naturalEqualWithWork_value a b).mpr hab), ih] + simp only [List.cons.injEq, hab, true_and] + · have ht : ¬ (naturalEqualWithWork a b).1 = true := + fun h => hab ((naturalEqualWithWork_value a b).mp h) + simp only [ite_eq_right ht, Bool.false_eq_true, List.cons.injEq, hab, false_and] + +/-- Entire dyadic initial estimator, including direct cases, every root +execution, binary minimum, ceiling, and final integer clamp. -/ +def coarseInitialWithWork {B d : ℕ} (q L N : ℕ) + (hB : 0 < B) (hq : 0 < q) (hL : 0 < L) (x y : List ℕ) + (draws : CoarseGuessIndex (coarseEntryWidth x y) → CoarseThresholdDraws B d) : ℕ × ℕ := + let long := binaryNaturalCompareWithWork (2 * x.length) y.length + if long.1 = .lt then (min N y.length, long.2 + Nat.size N + Nat.size y.length + 4) else + let equal := naturalListEqualWithWork x y + if equal.1 then (0, long.2 + equal.2 + 3) else + let roots := arithmeticMapWithWork (fun i => coarseCandidateWithWork q L hB hq hL x y i (draws i)) + (List.finRange (Nat.clog 2 (coarseEntryWidth x y) + 1)) + let smallest := coarseMinimumWithWork roots.1 + let rounded := naturalCeilingWithWork smallest.1 + let result := wordMinWithWork N.bits rounded.1 + (bitWordValue result.1, long.2 + equal.2 + roots.2 + smallest.2 + rounded.2 + result.2 + + Nat.size N + 6) + + theorem coarseInitialWithWork_value {B d : ℕ} (q L N : ℕ) + (hB : 0 < B) (hq : 0 < q) (hL : 0 < L) (x y : List ℕ) + (draws : CoarseGuessIndex (coarseEntryWidth x y) → CoarseThresholdDraws B d) : + (coarseInitialWithWork q L N hB hq hL x y draws).1 = + coarseInitialValue B d q (1 / L) N x y draws := by + unfold coarseInitialWithWork coarseInitialValue + by_cases hl : 2 * x.length < y.length + · have hb : (binaryNaturalCompareWithWork (2 * x.length) y.length).1 = Ordering.lt := by + exact (binaryNaturalCompareWithWork_lt _ _).mpr hl + simp only [hb, ite_true, ite_eq_left hl] + · have hb : ¬ (binaryNaturalCompareWithWork (2 * x.length) y.length).1 = Ordering.lt := by + exact fun h => hl ((binaryNaturalCompareWithWork_lt _ _).mp h) + rw [ite_eq_right hb, ite_eq_right hl] + by_cases he : x = y + · rw [ite_eq_left ((naturalListEqualWithWork_value x y).mpr he), ite_eq_left he] + · rw [ite_eq_right (fun h => he ((naturalListEqualWithWork_value x y).mp h)), ite_eq_right he] + dsimp only + rw [wordMinWithWork_value, bitWordValue_bits, naturalCeilingWithWork_value] + congr 2 + rw [arithmeticMapWithWork_value] + have hm : (List.finRange (Nat.clog 2 (coarseEntryWidth x y) + 1)).map + (fun i => (coarseCandidateWithWork q L hB hq hL x y i (draws i)).1) = + List.ofFn (fun i => (coarseCandidateWithWork q L hB hq hL x y i (draws i)).1) := by + rw [List.ofFn_eq_map] + rw [hm, coarseMinimumWithWork_ofFn] + simp only [coarseInitialMinimum, coarseCandidateWithWork_value] + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseInitialLabels.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseInitialLabels.lean new file mode 100644 index 0000000000000000000000000000000000000000..d36a775085936e21f972372e3f419a82b9971257 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseInitialLabels.lean @@ -0,0 +1,38 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseLabelWork +import OAI.Combinatorics.EditApproximation.Coarse.CoarseInitialWork +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation + +/-- Only labels in roots actually reached by the dyadic initializer are drawn. -/ + + +theorem coarseInitialLabelCount_le_arrayWork {α : Type*} [DecidableEq α] + (B d : ℕ) (Q lam : ℚ) (x y : List α) + (draws : CoarseGuessIndex (coarseEntryWidth x y) → CoarseThresholdDraws B d) : + coarseInitialLabelCount B d Q lam x y draws ≤ coarseInitialArrayWork B d Q lam x y draws := by + unfold coarseInitialLabelCount coarseInitialArrayWork + split_ifs + · exact le_rfl + · exact le_rfl + · exact Finset.sum_le_sum (fun i _ => coarseLabelCount_le_arrayWork + (coarseGuess (coarseEntryWidth x y) i) Q lam (coarseEntryTree B d x y) (draws i) _) + +def coarseInitialSamplingBits {α : Type*} [DecidableEq α] + (r d : ℕ) (Q lam : ℚ) (x y : List α) + (draws : CoarseGuessIndex (coarseEntryWidth x y) → CoarseThresholdDraws (2 ^ r) d) : ℕ := + r * coarseInitialLabelCount (2 ^ r) d Q lam x y draws + +theorem coarseInitialSamplingBits_le {α : Type*} [DecidableEq α] + (r d : ℕ) (Q lam : ℚ) (x y : List α) + (draws : CoarseGuessIndex (coarseEntryWidth x y) → CoarseThresholdDraws (2 ^ r) d) : + coarseInitialSamplingBits r d Q lam x y draws ≤ + r * coarseInitialArrayWork (2 ^ r) d Q lam x y draws := + Nat.mul_le_mul_left r (coarseInitialLabelCount_le_arrayWork (2 ^ r) d Q lam x y draws) + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseInitialScalar.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseInitialScalar.lean new file mode 100644 index 0000000000000000000000000000000000000000..1af94317e312be731aa04fa21d61b62e07492e39 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseInitialScalar.lean @@ -0,0 +1,56 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseInitialCost + +namespace OAI + +namespace EditApproximation +namespace BinaryFraction + +/-- Scalar envelope used only after summing the executed dyadic roots. -/ +theorem coarseInitial_aggregate_scalar (H x a g roots work : ℕ) (hH : 100 ≤ H) + (hg : g ≤ H + 1) + (hr : roots ≤ H ^ 32 * (a + g)) + (hw : work ≤ roots + (3 * x + 1) * (8 * H ^ 3 + 4) + + 10000 * (g + 1) * (H ^ 4 + 2) ^ 2) : + work ≤ H ^ 36 * (a + x + 1) := by + have hpos : 0 < H := by omega + have hpow (i j : ℕ) (hij : i ≤ j) : H ^ i ≤ H ^ j := Nat.pow_le_pow_right hpos hij + have hone : 1 ≤ H := by omega + have hthree : 3 ≤ H := by omega + have hhundred : 10000 ≤ H ^ 2 := by nlinarith + have hgp : g + 1 ≤ H ^ 2 := by nlinarith + have hp3 : 1 ≤ H ^ 3 := one_le_pow₀ hone + have hp4 : H ^ 4 + 2 ≤ H ^ 5 := by + have hh := Nat.mul_le_mul_right (H ^ 4) (show 2 ≤ H by omega) + have h4 : 2 ≤ H ^ 4 := (show 2 ≤ H by omega).trans (by simpa only [pow_one] using hpow 1 4 (by decide)) + nlinarith only [hh, h4] + have hwrap : 10000 * (g + 1) * (H ^ 4 + 2) ^ 2 ≤ H ^ 14 := by + calc + _ ≤ H ^ 2 * H ^ 2 * (H ^ 5) ^ 2 := by gcongr + _ = _ := by ring + have hscale : 3 * (8 * H ^ 3 + 4) ≤ H ^ 5 := by + have hh := Nat.mul_le_mul_right (H ^ 3) (show 36 ≤ H ^ 2 by nlinarith) + nlinarith only [hh, hp3] + have hscan : (3 * x + 1) * (8 * H ^ 3 + 4) ≤ (x + 1) * H ^ 5 := by + calc + _ ≤ (x + 1) * (3 * (8 * H ^ 3 + 4)) := by nlinarith + _ ≤ _ := Nat.mul_le_mul_left _ hscale + have hroot : roots ≤ H ^ 34 * (a + 1) := by + have hga : a + g ≤ H ^ 2 * (a + 1) := by + have ha := Nat.mul_le_mul_right a (show 1 ≤ H ^ 2 from one_le_pow₀ hone) + nlinarith only [ha, hgp] + calc + roots ≤ H ^ 32 * (a + g) := hr + _ ≤ H ^ 32 * (H ^ 2 * (a + 1)) := Nat.mul_le_mul_left _ hga + _ = _ := by ring + have hscan' := hscan.trans (Nat.mul_le_mul_left (x + 1) (hpow 5 34 (by decide))) + have hwrap' := hwrap.trans (hpow 14 34 (by decide)) + have hfinal : 3 * H ^ 34 ≤ H ^ 36 := by + have hh := Nat.mul_le_mul_left (H ^ 34) (show 3 ≤ H ^ 2 by nlinarith) + nlinarith only [hh] + have hfinal' := Nat.mul_le_mul_right (a + x + 1) hfinal + nlinarith only [hw, hroot, hscan', hwrap', hfinal', Nat.zero_le a, Nat.zero_le x] + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseInitialStorage.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseInitialStorage.lean new file mode 100644 index 0000000000000000000000000000000000000000..3037b3da70406d6871c89278e93294dd82805803 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseInitialStorage.lean @@ -0,0 +1,60 @@ +import OAI.Combinatorics.EditApproximation.Refinement.ComputedCoarseHistory +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation +namespace BinaryFraction +open Filter + +def coarseInitialArrayHistory (N B d : ℕ) [NeZero B] (x y : List ℕ) + (draws : CoarseGuessIndex (coarseEntryWidth x y) → CoarseThresholdDraws B d) : ℕ := + if 2 * x.length < y.length then 0 else if x = y then 0 else + ∑ i : CoarseGuessIndex (coarseEntryWidth x y), + coarseRootArrayHistory (coarseGuess (coarseEntryWidth x y) i) + (inputHeight N ^ 4) (64 * inputHeight N) (Nat.pos_of_neZero B) + (pow_pos (Nat.two_pow_pos _) _) (Nat.mul_pos (by decide) (Nat.two_pow_pos _)) + (coarseTargetFrame (coarseGuess (coarseEntryWidth x y) i) + (coarsePadTo (coarseEntryWidth x y) y)) (coarseEntryTree B d x y) (draws i) 0 + +theorem coarseInitialArrayHistory_polynomial : + ∀ᶠ N : ℕ in atTop, ∀ B d : ℕ, ∀ x y : List ℕ, + B = (integerParameters N).B → d = computedCoarseDepth N (coarseEntryWidth x y) → + coarseEntryWidth x y ≤ N → ∀ (_hB : NeZero B) + (draws : CoarseGuessIndex (coarseEntryWidth x y) → CoarseThresholdDraws B d), + coarseInitialArrayHistory N B d x y draws ≤ (N + 2) ^ 37 := by + filter_upwards [computedCoarseAllHistories_polynomial] with N hN + intro B d x y hBdef hddef hsize inst draws + unfold coarseInitialArrayHistory + split_ifs + · exact Nat.zero_le _ + · exact Nat.zero_le _ + · exact hN B d x y hBdef hddef hsize (Nat.pos_of_neZero B) + (pow_pos (Nat.two_pow_pos _) _) (Nat.mul_pos (by decide) (Nat.two_pow_pos _)) draws + +end BinaryFraction + + + +theorem coarseHistoryKeyCost_le {α β ι : Type*} (cost : ι → ℕ) (C : ℕ) + (hcost : ∀ entry, cost entry ≤ C) (key : Sum α (Sum ι β)) : + coarseHistoryKeyCost cost key ≤ C := by + rcases key with scalar | entry | table + · exact Nat.zero_le _ + · exact hcost entry + · exact Nat.zero_le _ + +theorem coarseHistoryKeysSum_le {α β ι : Type*} (cost : ι → ℕ) (C : ℕ) + (hcost : ∀ entry, cost entry ≤ C) (keys : List (Sum α (Sum ι β))) : + (keys.map (coarseHistoryKeyCost cost)).sum ≤ C * keys.length := by + induction keys with + | nil => simp + | cons key keys ih => + have hk := coarseHistoryKeyCost_le cost C hcost key + simp only [List.map_cons, List.sum_cons, List.length_cons, Nat.mul_add, Nat.mul_one] + omega + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseInitialWork.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseInitialWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..deab9da9032b93e929b745e9ddaeee23db90f6e8 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseInitialWork.lean @@ -0,0 +1,127 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseInitial +import OAI.Combinatorics.EditApproximation.Coarse.CoarseWork +import Mathlib.NumberTheory.Harmonic.Bounds +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! +# Expected array work of the actual dyadic initial estimator + +These are expectations of the concrete pruning-stopped counters. The +linear penalty sweeps and representation bounds separately convert the +array units into arithmetic and RAM work. +-/ + +namespace EditApproximation + +open Finset MeasureTheory ProbabilityTheory + +universe u + +theorem coarseInverseAllowanceFactor_nonneg (B : ℕ) (Q lam : ℚ) + (hQ : 0 ≤ Q) (hlam : 0 ≤ lam) : 0 ≤ coarseInverseAllowanceFactor B Q lam := by + unfold coarseInverseAllowanceFactor + exact mul_nonneg (div_nonneg (by exact_mod_cast hQ) (by exact_mod_cast hlam)) + (sum_nonneg (fun _ _ => by positivity)) + +theorem coarseInverseAllowanceFactor_log_bound (B : ℕ) (Q lam : ℚ) + (hQ : 0 ≤ Q) (hlam : 0 ≤ lam) : + coarseInverseAllowanceFactor B Q lam ≤ (Q : ℝ) / lam * (1 + Real.log B) := by + have hharmonic : (∑ r ∈ Icc 1 B, (1 : ℝ) / r) = harmonic B := by + simp only [harmonic_eq_sum_Icc, Rat.cast_sum, Rat.cast_inv, Rat.cast_natCast, one_div] + unfold coarseInverseAllowanceFactor + rw [hharmonic] + exact mul_le_mul_of_nonneg_left (harmonic_le_one_add_log B) + (div_nonneg (by exact_mod_cast hQ) (by exact_mod_cast hlam)) + +theorem coarseWorkMultiplier_mono (first second : ℝ) (D : ℕ) + (hfirst : 0 ≤ first) (hle : first ≤ second) : + coarseWorkMultiplier first D ≤ coarseWorkMultiplier second D := by + exact sum_le_sum (fun _ _ => pow_le_pow_left₀ hfirst hle _) + +/-- Root allowance equals the actual guessed distance. It cancels the +array width `2k+1` in expectation, uniformly over every positive guess. -/ +theorem coarseRootArrayWork_expected_bound {B D : ℕ} [NeZero B] {α : Type u} + [MeasurableSpace (Fin B)] [MeasurableSingletonClass (Fin B)] + (k : ℕ) (Q lam : ℚ) (tree : CoarseSourceTree B α D) + (hk : 0 < k) (hQ : 0 < Q) (hlam : 0 < lam) + (factor : ℝ) (hfactor : 1 ≤ factor) + (hinverse : coarseInverseAllowanceFactor B Q lam ≤ factor) : + (∫ draws, (coarseActiveArrayWork k Q lam tree draws k : ℝ) + ∂coarseDrawMeasure B D) ≤ + 3 * B * tree.word.length * (D + 1 : ℕ) * factor ^ D := by + have hcounter := coarseActiveArrayWork_expected_bound k Q lam tree k hQ hlam (by exact_mod_cast hk) + have hkReal : (0 : ℝ) < k := by exact_mod_cast hk + have hkOne : (1 : ℝ) ≤ k := by exact_mod_cast hk + have hcoefficient : (B * (2 * k + 1) : ℕ) * (tree.word.length : ℝ) / k ≤ + 3 * B * tree.word.length := by + apply (div_le_iff₀ hkReal).2 + push_cast + have hnonnegative : (0 : ℝ) ≤ (B : ℝ) * tree.word.length := by positivity + nlinarith + have hmultiplier := (coarseWorkMultiplier_mono _ factor D + (coarseInverseAllowanceFactor_nonneg B Q lam hQ.le hlam.le) hinverse).trans + (coarseWorkMultiplier_le factor D hfactor) + apply hcounter.trans + exact (mul_le_mul_of_nonneg_right hcoefficient + (coarseWorkMultiplier_nonneg _ D (coarseInverseAllowanceFactor_nonneg B Q lam hQ.le hlam.le))).trans + (by + have hmul := mul_le_mul_of_nonneg_left hmultiplier + (show (0 : ℝ) ≤ 3 * B * tree.word.length by positivity) + simpa only [mul_assoc] using hmul) + +/- The initial estimator's actual sum of active array units, with zero +array work in its two direct branches. -/ + + +/-- The actual complete initial computation has the paper's expected +array-work shape, on every execution and without conditioning on accuracy. -/ +theorem coarseInitialArrayWork_expected_bound {B D : ℕ} [NeZero B] {α : Type u} [DecidableEq α] + [MeasurableSpace (Fin B)] [MeasurableSingletonClass (Fin B)] + (Q lam : ℚ) (x y : List α) (hcapacity : coarseEntryWidth x y ≤ B ^ D) + (hQ : 0 < Q) (hlam : 0 < lam) + (factor : ℝ) (hfactor : 1 ≤ factor) + (hinverse : coarseInverseAllowanceFactor B Q lam ≤ factor) : + (∫ draws, (coarseInitialArrayWork B D Q lam x y draws : ℝ) + ∂coarseInitialMeasure B D (coarseEntryWidth x y)) ≤ + 3 * B * coarseEntryWidth x y * (Nat.clog 2 (coarseEntryWidth x y) + 1 : ℕ) * + (D + 1 : ℕ) * factor ^ D := by + classical + have hnonnegative : (0 : ℝ) ≤ + 3 * B * coarseEntryWidth x y * (Nat.clog 2 (coarseEntryWidth x y) + 1 : ℕ) * + (D + 1 : ℕ) * factor ^ D := by positivity + by_cases hlong : 2 * x.length < y.length + · simpa only [coarseInitialArrayWork, hlong, ↓reduceIte, Nat.cast_zero, integral_zero] using hnonnegative + by_cases hxy : x = y + · have hzero (draws) : coarseInitialArrayWork B D Q lam x y draws = 0 := by + unfold coarseInitialArrayWork + rw [ite_eq_right hlong, ite_eq_left hxy] + simp_rw [hzero, Nat.cast_zero, integral_zero] + exact hnonnegative + simp only [coarseInitialArrayWork, hlong, hxy, ↓reduceIte, Nat.cast_sum] + rw [integral_finsetSum univ (by intro i hi; exact .of_finite)] + have hpoint (i : CoarseGuessIndex (coarseEntryWidth x y)) : + (∫ draws, (coarseActiveArrayWork (coarseGuess (coarseEntryWidth x y) i) Q lam + (coarseEntryTree B D x y) (draws i) (coarseGuess (coarseEntryWidth x y) i) : ℝ) + ∂coarseInitialMeasure B D (coarseEntryWidth x y)) ≤ + 3 * B * coarseEntryWidth x y * (D + 1 : ℕ) * factor ^ D := by + unfold coarseInitialMeasure + rw [integral_comp_eval (μ := fun _ : CoarseGuessIndex (coarseEntryWidth x y) => coarseDrawMeasure B D) + (i := i) (f := fun draws => (coarseActiveArrayWork (coarseGuess (coarseEntryWidth x y) i) Q lam + (coarseEntryTree B D x y) draws (coarseGuess (coarseEntryWidth x y) i) : ℝ)) + (measurable_of_finite _).aestronglyMeasurable] + have hbound := coarseRootArrayWork_expected_bound (coarseGuess (coarseEntryWidth x y) i) + Q lam (coarseEntryTree B D x y) (by dsimp [coarseGuess]; positivity) hQ hlam factor hfactor hinverse + rw [coarseEntryTree_word B D x y hcapacity, + coarsePadTo_length _ _ (le_max_left _ _)] at hbound + exact hbound + have hsum := sum_le_sum (s := univ) (fun i _ => hpoint i) + apply hsum.trans_eq + simp only [sum_const, card_univ, Fintype.card_fin, nsmul_eq_mul] + ring + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseInitialWorkBounds.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseInitialWorkBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..52a02b05685391c1a5eabad4f942b1a1750b4fb5 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseInitialWorkBounds.lean @@ -0,0 +1,59 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseInitialExecution + +namespace OAI + +namespace EditApproximation + + theorem arithmeticMapWithWork_total {α β : Type*} (f : α → β × ℕ) (values : List α) : + (arithmeticMapWithWork f values).2 = (values.map (fun a => (f a).2)).sum + 3 * values.length := by + induction values with + | nil => rfl + | cons a rest ih => + simp only [arithmeticMapWithWork, List.map_cons, List.sum_cons, List.length_cons, ih] + omega + +namespace BinaryFraction + + theorem coarseMinimumWithWork_bounds (values : List BinaryFraction) (A : ℕ) + (hA : 2 ≤ A) (hv : ∀ a ∈ values, a.width ≤ A) : + (coarseMinimumWithWork values).1.width ≤ A ∧ + (coarseMinimumWithWork values).2 ≤ 1 + values.length * (1000 * (A + 1) ^ 2 + 2) := by + cases values with + | nil => + constructor + · exact (nat_width_le 0).trans (by simpa using hA) + · simp only [coarseMinimumWithWork, List.length_nil, zero_mul, add_zero, le_refl] + | cons a rest => + have ha := hv a List.mem_cons_self + have hr := fun b hb => hv b (List.mem_cons_of_mem _ hb) + exact ⟨minimumWithWork_width a rest A ha hr, + (minimumWithWork_cost a rest A ha hr).trans (by simp only [List.length_cons]; nlinarith)⟩ + + theorem naturalListEqualWithWork_cost (x y : List ℕ) (S : ℕ) + (hs : ∀ a ∈ x ++ y, Nat.size a ≤ S) : + (naturalListEqualWithWork x y).2 ≤ (x.length + y.length + 1) * (8 * S + 4) := by + induction x generalizing y with + | nil => cases y <;> simp only [naturalListEqualWithWork] <;> nlinarith [Nat.zero_le S] + | cons a left ih => + cases y with + | nil => simp only [naturalListEqualWithWork]; nlinarith [Nat.zero_le S] + | cons b right => + have ha : Nat.size a ≤ S := hs a (by simp) + have hb : Nat.size b ≤ S := hs b (by simp) + have ht := naturalEqualWithWork_cost a b S ha hb + have hr := ih right (by + intro z hz + rcases List.mem_append.mp hz with hz | hz + · exact hs z (List.mem_append.mpr (Or.inl (List.mem_cons_of_mem _ hz))) + · exact hs z (List.mem_append.mpr (Or.inr (List.mem_cons_of_mem _ hz)))) + simp only [naturalListEqualWithWork] + split_ifs <;> dsimp only + · simp only [List.length_cons] at * + nlinarith only [ht, hr, Nat.zero_le S] + · simp only [List.length_cons] + nlinarith only [ht, Nat.zero_le S, Nat.zero_le left.length, Nat.zero_le right.length] + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseInputGuard.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseInputGuard.lean new file mode 100644 index 0000000000000000000000000000000000000000..de91be9b90e39a029a7388768df0d9b066e3f11b --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseInputGuard.lean @@ -0,0 +1,54 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseSliceCopy +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation + +/-- This guard uses interval endpoints before either input slice is copied. -/ + + +theorem coarseInputGuardWithWork_value (sourceLo sourceHi targetLo targetHi : ℕ) : + (coarseInputGuardWithWork sourceLo sourceHi targetLo targetHi).1 = + decide (2 * (sourceHi - sourceLo) < targetHi - targetLo) := by + apply Bool.eq_iff_iff.mpr + simp only [coarseInputGuardWithWork, saturatingSubtractWithWork_value, + binaryNaturalMulWithWork_value, decide_eq_true_eq, binaryNaturalCompareWithWork_lt] + +theorem coarseInputGuardWithWork_cost (sourceLo sourceHi targetLo targetHi A : ℕ) + (hslo : Nat.size sourceLo ≤ A) (hshi : Nat.size sourceHi ≤ A) + (htlo : Nat.size targetLo ≤ A) (hthi : Nat.size targetHi ≤ A) : + (coarseInputGuardWithWork sourceLo sourceHi targetLo targetHi).2 ≤ 1000 * (A + 1) := by + have hs := saturatingSubtractWithWork_cost sourceHi sourceLo + have ht := saturatingSubtractWithWork_cost targetHi targetLo + have hsw : Nat.size (sourceHi - sourceLo) ≤ A := + (Nat.size_le_size (Nat.sub_le _ _)).trans hshi + have htw : Nat.size (targetHi - targetLo) ≤ A := + (Nat.size_le_size (Nat.sub_le _ _)).trans hthi + have hm := binaryNaturalMulWithWork_cost 2 (sourceHi - sourceLo) + have hmw := natural_product_bit_length 2 (sourceHi - sourceLo) + have hc := binaryNaturalCompareWithWork_cost (2 * (sourceHi - sourceLo)) (targetHi - targetLo) + rw [show Nat.size 2 = 2 by decide] at hm hmw + simp only [coarseInputGuardWithWork, saturatingSubtractWithWork_value, binaryNaturalMulWithWork_value] + omega + +/-- The optional copied pair is absent on the long-target branch. -/ + + +theorem coarsePreparedSlicesWithWork_value (source target : List ℕ) + (sourceLo sourceHi targetLo targetHi : ℕ) + (hslo : sourceLo ≤ sourceHi) (hshi : sourceHi ≤ source.length) + (htlo : targetLo ≤ targetHi) (hthi : targetHi ≤ target.length) : + (coarsePreparedSlicesWithWork source target sourceLo sourceHi targetLo targetHi).1 = + if 2 * (sourceHi - sourceLo) < targetHi - targetLo then none else + some (substring source sourceLo sourceHi, substring target targetLo targetHi) := by + simp only [coarsePreparedSlicesWithWork, coarseInputGuardWithWork_value, decide_eq_true_eq] + split_ifs + · rfl + · simp only [coarseRangeCopyWithWork_slice source sourceLo sourceHi hslo hshi, + coarseRangeCopyWithWork_slice target targetLo targetHi htlo hthi] + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseInputPreparation.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseInputPreparation.lean new file mode 100644 index 0000000000000000000000000000000000000000..aff06f7ed67d6a721f246883f2e96109b9e411b4 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseInputPreparation.lean @@ -0,0 +1,56 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseInputGuard + +namespace OAI + +namespace EditApproximation + +theorem coarsePreparedSlicesWithWork_cost (source target : List ℕ) + (sourceLo sourceHi targetLo targetHi A S : ℕ) + (hslo : sourceLo ≤ sourceHi) (hshi : sourceHi ≤ source.length) + (htlo : targetLo ≤ targetHi) (hthi : targetHi ≤ target.length) + (hsbits : Nat.size source.length ≤ A) (htbits : Nat.size target.length ≤ A) + (hsymbol : ∀ a ∈ source ++ target, Nat.size a ≤ S) : + (coarsePreparedSlicesWithWork source target sourceLo sourceHi targetLo targetHi).2 ≤ + 1000 * (A + 1) + (3 * (sourceHi - sourceLo) + 2) * (40 * (A + 1) + S) := by + have hg := coarseInputGuardWithWork_cost sourceLo sourceHi targetLo targetHi A + ((Nat.size_le_size (hslo.trans hshi)).trans hsbits) ((Nat.size_le_size hshi).trans hsbits) + ((Nat.size_le_size (htlo.trans hthi)).trans htbits) ((Nat.size_le_size hthi).trans htbits) + by_cases hlong : 2 * (sourceHi - sourceLo) < targetHi - targetLo + · simp only [coarsePreparedSlicesWithWork, coarseInputGuardWithWork_value, hlong, decide_true, ite_true] + exact hg.trans (Nat.le_add_right _ _) + · have hs := coarseRangeCopyWithWork_input_cost source sourceLo sourceHi A S hslo hshi hsbits + (fun a ha => hsymbol a (List.mem_append_left target ha)) + have ht := coarseRangeCopyWithWork_input_cost target targetLo targetHi A S htlo hthi htbits + (fun a ha => hsymbol a (List.mem_append_right source ha)) + simp only [coarsePreparedSlicesWithWork, coarseInputGuardWithWork_value, hlong, decide_false, Bool.false_eq_true, ite_false] + have hm := Nat.mul_le_mul_right (40 * (A + 1) + S) + (show (sourceHi - sourceLo + 1) + (targetHi - targetLo + 1) ≤ + 3 * (sourceHi - sourceLo) + 2 by omega) + nlinarith only [hg, hs, ht, hm] + +theorem coarsePreparedSlicesWithWork_height_bound (source target : List ℕ) + (sourceLo sourceHi targetLo targetHi H : ℕ) + (hslo : sourceLo ≤ sourceHi) (hshi : sourceHi ≤ source.length) + (htlo : targetLo ≤ targetHi) (hthi : targetHi ≤ target.length) + (hH : 100 ≤ H) (hsbits : Nat.size source.length ≤ H ^ 3) + (htbits : Nat.size target.length ≤ H ^ 3) + (hsymbol : ∀ a ∈ source ++ target, Nat.size a ≤ H ^ 3) : + (coarsePreparedSlicesWithWork source target sourceLo sourceHi targetLo targetHi).2 ≤ + H ^ 6 * (sourceHi - sourceLo + 1) := by + have hc := coarsePreparedSlicesWithWork_cost source target sourceLo sourceHi targetLo targetHi + (H ^ 3) (H ^ 3) hslo hshi htlo hthi hsbits htbits hsymbol + have hp : 1 ≤ H ^ 3 := one_le_pow₀ (by omega) + have hs : 5000 ≤ H ^ 3 := by + have h := Nat.pow_le_pow_left hH 3 + norm_num at h + omega + have hm : 5000 * H ^ 3 ≤ H ^ 6 := by + calc + _ ≤ H ^ 3 * H ^ 3 := Nat.mul_le_mul_right _ hs + _ = _ := by rw [← pow_add] + have hmul := Nat.mul_le_mul_right (sourceHi - sourceLo + 1) hm + nlinarith only [hc, hp, hmul, Nat.zero_le (sourceHi - sourceLo)] + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseInputStorage.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseInputStorage.lean new file mode 100644 index 0000000000000000000000000000000000000000..c80859db5b1743c47a5d43d9597cbcde5d42365f --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseInputStorage.lean @@ -0,0 +1,83 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseInputGuard +import OAI.Combinatorics.EditApproximation.Refinement.ComputedRetainedValues +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation + + + +theorem storedNaturalBits_le (values : List ℕ) (A : ℕ) + (h : ∀ a ∈ values, Nat.size a ≤ A) : + storedNaturalBits values ≤ 1 + values.length * (A + 1) := by + have hs : (values.map fun a => Nat.size a + 1).sum ≤ values.length * (A + 1) := by + induction values with + | nil => simp + | cons a values ih => + have ha := h a List.mem_cons_self + have ht := ih (fun a ha => h a (List.mem_cons_of_mem _ ha)) + simp only [List.map_cons, List.sum_cons, List.length_cons, Nat.add_mul, Nat.one_mul] + omega + exact Nat.add_le_add_left hs 1 + + + +theorem coarsePreparedInputStorage_le (source target : List ℕ) + (sourceLo sourceHi targetLo targetHi A : ℕ) + (hslo : sourceLo ≤ sourceHi) (hshi : sourceHi ≤ source.length) + (htlo : targetLo ≤ targetHi) (hthi : targetHi ≤ target.length) + (hsymbol : ∀ a ∈ source ++ target, Nat.size a ≤ A) : + coarsePreparedInputStorage source target sourceLo sourceHi targetLo targetHi ≤ + 3 + (source.length + target.length) * (A + 1) := by + have hs : storedNaturalBits (substring source sourceLo sourceHi) ≤ 1 + source.length * (A + 1) := by + apply (storedNaturalBits_le _ A (by + intro a ha + exact hsymbol a (List.mem_append_left _ (List.mem_of_mem_take (List.mem_of_mem_drop ha))))).trans + apply Nat.add_le_add_left + apply Nat.mul_le_mul_right + simp only [substring, List.length_drop, List.length_take] + exact (Nat.sub_le _ _).trans (min_le_right _ _) + have ht : storedNaturalBits (substring target targetLo targetHi) ≤ 1 + target.length * (A + 1) := by + apply (storedNaturalBits_le _ A (by + intro a ha + exact hsymbol a (List.mem_append_right _ (List.mem_of_mem_take (List.mem_of_mem_drop ha))))).trans + apply Nat.add_le_add_left + apply Nat.mul_le_mul_right + simp only [substring, List.length_drop, List.length_take] + exact (Nat.sub_le _ _).trans (min_le_right _ _) + unfold coarsePreparedInputStorage + rw [coarsePreparedSlicesWithWork_value source target sourceLo sourceHi targetLo targetHi hslo hshi htlo hthi] + split_ifs + · simp only; omega + · simp only + nlinarith only [hs, ht] + +theorem coarsePreparedInputStorage_polynomial (source target : List ℕ) + (N sourceLo sourceHi targetLo targetHi : ℕ) + (hslo : sourceLo ≤ sourceHi) (hshi : sourceHi ≤ source.length) + (htlo : targetLo ≤ targetHi) (hthi : targetHi ≤ target.length) + (hsize : source.length + target.length ≤ N) + (hsymbol : ∀ a ∈ source ++ target, Nat.size a ≤ inputHeight N ^ 3) : + coarsePreparedInputStorage source target sourceLo sourceHi targetLo targetHi ≤ (N + 2) ^ 16 := by + have h := coarsePreparedInputStorage_le source target sourceLo sourceHi targetLo targetHi + (inputHeight N ^ 3) hslo hshi htlo hthi hsymbol + let X := N + 2 + have hX : 2 ≤ X := by dsimp only [X]; omega + have hH := Nat.pow_le_pow_left (computed_height_polynomial N) 3 + rw [← pow_mul] at hH + change inputHeight N ^ 3 ≤ X ^ 12 at hH + have h1 : 1 ≤ X ^ 12 := one_le_pow₀ (by omega) + have hm := Nat.mul_le_mul (show source.length + target.length ≤ X by dsimp only [X]; omega) + (show inputHeight N ^ 3 + 1 ≤ 2 * X ^ 12 by omega) + have hp : 1 ≤ X ^ 13 := one_le_pow₀ (by omega) + have hc : 5 ≤ X ^ 3 := (by decide : 5 ≤ (2 : ℕ) ^ 3).trans (Nat.pow_le_pow_left hX 3) + calc + _ ≤ 5 * X ^ 13 := by nlinarith only [h, hm, hp] + _ ≤ X ^ 3 * X ^ 13 := Nat.mul_le_mul_right _ hc + _ = _ := by rw [← pow_add] + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseLabelWork.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseLabelWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..938292debd8ddb5671c813f2044a5a4f54c3c8d3 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseLabelWork.lean @@ -0,0 +1,67 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseWork +import OAI.Combinatorics.EditApproximation.Probability.ExactSampling +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation + +/-- Only expanded internal nodes request their child thresholds. The full +product seed is a specification; labels below a pruned node are never read. -/ + + + + +private theorem coarseLabelChildren_le {B d : ℕ} {α : Type*} (Q lam allowance : ℚ) + (labels arrays : CoarseSourceTree B α d → CoarseThresholdDraws B d → ℚ → ℕ) + (children : List (CoarseSourceTree B α d × Fin B × CoarseThresholdDraws B d)) + (hle : ∀ child draw below, (child, draw, below) ∈ children → ∀ a, labels child below a ≤ arrays child below a) : + coarseLabelChildren Q lam allowance labels children ≤ + coarseActiveChildrenWork Q lam allowance arrays children := by + induction children with + | nil => exact le_rfl + | cons data rest ih => + obtain ⟨child, draw, below⟩ := data + exact Nat.add_le_add (hle child draw below List.mem_cons_self _) + (ih (fun child draw below hmem => hle child draw below (List.mem_cons_of_mem _ hmem))) + + theorem coarseLabelCount_le_arrayWork {B d : ℕ} {α : Type*} (k : ℕ) (Q lam : ℚ) + (tree : CoarseSourceTree B α d) (draws : CoarseThresholdDraws B d) (allowance : ℚ) : + coarseLabelCount Q lam tree draws allowance ≤ coarseActiveArrayWork k Q lam tree draws allowance := by + induction tree generalizing allowance with + | leaf letter => + simp only [coarseLabelCount, coarseActiveArrayWork] + split_ifs <;> omega + | branch children ih => + obtain ⟨draws, below⟩ := draws + simp only [coarseLabelCount, coarseActiveArrayWork] + split_ifs + · exact le_rfl + · have hc := coarseLabelChildren_le Q lam allowance + (fun child => coarseLabelCount Q lam child) + (fun child => coarseActiveArrayWork k Q lam child) + (List.ofFn fun i => (children i, draws i, below i)) (by + intro child draw childBelow hmem a + obtain ⟨i, hi⟩ := List.mem_ofFn.mp hmem + cases hi + exact ih i (below i) a) + have hunit : B ≤ B * (2 * k + 1) := by nlinarith + exact Nat.add_le_add hunit hc + +/-- Power-of-two threshold sampling consumes exactly the fixed word length +per used label. `binaryWord_uniform` proves the output law of every draw. -/ +def coarseThresholdBitWork {d : ℕ} {α : Type*} (r : ℕ) (Q lam : ℚ) + (tree : CoarseSourceTree (2 ^ r) α d) (draws : CoarseThresholdDraws (2 ^ r) d) + (allowance : ℚ) : ℕ := r * coarseLabelCount Q lam tree draws allowance + + theorem coarseThresholdBitWork_le {d : ℕ} {α : Type*} (r k : ℕ) (Q lam : ℚ) + (tree : CoarseSourceTree (2 ^ r) α d) (draws : CoarseThresholdDraws (2 ^ r) d) + (allowance : ℚ) : + coarseThresholdBitWork r Q lam tree draws allowance ≤ + r * coarseActiveArrayWork k Q lam tree draws allowance := + Nat.mul_le_mul_left r (coarseLabelCount_le_arrayWork k Q lam tree draws allowance) + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseLevelMagnitude.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseLevelMagnitude.lean new file mode 100644 index 0000000000000000000000000000000000000000..1657bb434cd0a6c12597ba73fc096a001b383696 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseLevelMagnitude.lean @@ -0,0 +1,53 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseChildrenBitWork + +namespace OAI + +namespace EditApproximation +namespace BinaryFraction + +/-- Loose magnitude bound for all partial child sums. Its bit length is +linear in the depth and parameter bit lengths. -/ +def coarseLevelMagnitude (N k B d : ℕ) : ℕ := + (N + k + 1) * (2 * B + 2) ^ (d + 1) + + theorem coarseLevelMagnitude_pos (N k B d : ℕ) : 0 < coarseLevelMagnitude N k B d := by + unfold coarseLevelMagnitude + positivity + + theorem coarseLevelMagnitude_ge (N k B d : ℕ) : k ≤ coarseLevelMagnitude N k B d := by + have hp : 1 ≤ (2 * B + 2) ^ (d + 1) := by + have hz : 0 < (2 * B + 2) ^ (d + 1) := by positivity + omega + unfold coarseLevelMagnitude + nlinarith + + theorem coarseLevelMagnitude_mono (N k B d e : ℕ) (h : d ≤ e) : + coarseLevelMagnitude N k B d ≤ coarseLevelMagnitude N k B e := by + unfold coarseLevelMagnitude + apply Nat.mul_le_mul_left + exact Nat.pow_le_pow_right (by omega) (by omega) + + theorem coarseLevelMagnitude_succ (N k B d : ℕ) : + B * (coarseLevelMagnitude N k B d + k) + 2 ≤ coarseLevelMagnitude N k B (d + 1) := by + have hk := coarseLevelMagnitude_ge N k B d + have hp := coarseLevelMagnitude_pos N k B d + have heq : coarseLevelMagnitude N k B (d + 1) = + coarseLevelMagnitude N k B d * (2 * B + 2) := by + unfold coarseLevelMagnitude + rw [show d + 1 + 1 = (d + 1) + 1 by omega, pow_succ] + ring + rw [heq] + nlinarith + + theorem coarseLevelMagnitude_bits (N k B d : ℕ) : + Nat.size (coarseLevelMagnitude N k B d) ≤ + Nat.size (N + k + 1) + (d + 1) * Nat.size (2 * B + 2) + 1 := by + have hm := natural_product_bit_length (N + k + 1) ((2 * B + 2) ^ (d + 1)) + have hp := natural_power_bit_length (2 * B + 2) (d + 1) + unfold coarseLevelMagnitude + omega + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseNumericalUnit.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseNumericalUnit.lean new file mode 100644 index 0000000000000000000000000000000000000000..08465a80c113b799d5cd403581b5a09038585b52 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseNumericalUnit.lean @@ -0,0 +1,80 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseRootWork +import OAI.Combinatorics.EditApproximation.Geometry.HeightPowerWork + +namespace OAI + +namespace EditApproximation +namespace BinaryFraction + + theorem bitPowerBitBudget_mono (d e A C : ℕ) (hd : d ≤ e) (hA : A ≤ C) : + bitPowerBitBudget d A ≤ bitPowerBitBudget e C := by + have hw : (d + 1) * (A + 1) + 1 ≤ (e + 1) * (C + 1) + 1 := + Nat.add_le_add_right (Nat.mul_le_mul (by omega) (by omega)) 1 + have hp := Nat.pow_le_pow_left hw 2 + have hc := Nat.mul_le_mul hd (Nat.mul_le_mul_left 200 hp) + simpa only [bitPowerBitBudget] using Nat.add_le_add_left hc 1 + +def coarseNumericalUnit (H : ℕ) : ℕ := + bitPowerBitBudget H (7 * H ^ 3 + 3) + + 1000 * (10 * (H + 2) * (H ^ 3 + 1) + 1) ^ 2 + + 100001000 * (H ^ 3 + 1) ^ 2 + + theorem coarseNumericalUnit_polynomial (H : ℕ) : + coarseNumericalUnit H ≤ 10000000000 * (H + 1) ^ 10 := by + have hp (j : ℕ) (hj : j ≤ 10) : H ^ j ≤ (H + 1) ^ 10 := + (Nat.pow_le_pow_left (Nat.le_succ H) j).trans + (Nat.pow_le_pow_right (by omega) hj) + have h0 := hp 0 (by decide) + have h1 := hp 1 (by decide) + have h2 := hp 2 (by decide) + have h3 := hp 3 (by decide) + have h4 := hp 4 (by decide) + have h5 := hp 5 (by decide) + have h6 := hp 6 (by decide) + have h7 := hp 7 (by decide) + have h8 := hp 8 (by decide) + have h9 := hp 9 (by decide) + unfold coarseNumericalUnit bitPowerBitBudget + nlinarith only [h0, h1, h2, h3, h4, h5, h6, h7, h8, h9] + + theorem coarseNumericalUnit_le_power (H : ℕ) (hH : 10 ≤ H) : + coarseNumericalUnit H ≤ H ^ 30 := by + have hc : 10000000000 ≤ H ^ 10 := by + have h := Nat.pow_le_pow_left hH 10 + norm_num at h ⊢ + exact h + have hh : H + 1 ≤ H ^ 2 := by nlinarith + have hp := Nat.pow_le_pow_left hh 10 + calc + coarseNumericalUnit H ≤ 10000000000 * (H + 1) ^ 10 := coarseNumericalUnit_polynomial H + _ ≤ H ^ 10 * (H ^ 2) ^ 10 := Nat.mul_le_mul hc hp + _ = H ^ 30 := by rw [← pow_mul, ← pow_add] + + theorem coarseRootWithWork_height_bound {B d : ℕ} {α : Type*} [DecidableEq α] + (k q L N D H : ℕ) (hB : 0 < B) (hq : 0 < q) (hL : 0 < L) + (frame : List (Option α)) (tree : CoarseSourceTree B α d) + (draws : CoarseThresholdDraws B d) (start : ℕ) (shift : Fin (2 * k + 1)) + (hBbits : Nat.size B + 2 ≤ H ^ 3) (hqbits : Nat.size q + 2 ≤ H ^ 3) + (hLbits : Nat.size L + 2 ≤ H ^ 3) (hNbits : Nat.size N + 2 ≤ H ^ 3) + (hd : Nat.size (coarseCommonDenominator 1 q L B d) ≤ D) (hD : D ≤ H ^ 3) + (hdepth : d ≤ H) + (hbound : Nat.size (coarseLevelMagnitude N k B d + 2) + 2 * D + 1 ≤ H ^ 3) + (hstart : start + tree.word.length ≤ N) : + (coarseRootWithWork k q L hB hq hL frame tree draws start shift).2 ≤ + coarseNumericalUnit H * (2 * coarseActiveArrayWork k q (1 / L) tree draws k + 1) := by + have h := coarseRootWithWork_cost k q L N D (H ^ 3) hB hq hL frame tree draws start shift + hBbits hqbits hLbits hNbits hd hD hbound hstart + have hp := bitPowerBitBudget_mono d H (7 * H ^ 3 + 3) (7 * H ^ 3 + 3) hdepth le_rfl + have hm : 10 * (d + 2) * (H ^ 3 + 1) + 1 ≤ 10 * (H + 2) * (H ^ 3 + 1) + 1 := by + nlinarith only [Nat.mul_le_mul_right (10 * (H ^ 3 + 1)) hdepth] + have hc := Nat.mul_le_mul_left 1000 (Nat.pow_le_pow_left hm 2) + have hf := Nat.mul_le_mul_left + (bitPowerBitBudget H (7 * H ^ 3 + 3) + 1000 * (10 * (H + 2) * (H ^ 3 + 1) + 1) ^ 2) + (show 1 ≤ 2 * coarseActiveArrayWork k q (1 / L) tree draws k + 1 by omega) + unfold coarseNumericalUnit + nlinarith only [h, hp, hc, hf] + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarsePadding.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarsePadding.lean new file mode 100644 index 0000000000000000000000000000000000000000..7709bf4bbd31dfad9fdfa9a83f0cf54110c993f5 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarsePadding.lean @@ -0,0 +1,111 @@ +import OAI.Combinatorics.EditApproximation.Geometry.Geometry +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! +# Fresh-symbol right padding + +Padding uses `none`, while original letters are tagged by `some`. Removing +the fresh symbols contracts every unrestricted unit-cost edit script. +-/ + +namespace EditApproximation + +open EditDistortion + +universe u v + +/-- Removing or relabeling letters replaces each edit by at most one edit. -/ +theorem step_filterMap_script {α : Type u} {β : Type v} {s : Bool} + (f : α → Option β) {x y : List α} (step : Step s x y) : + ∃ n ≤ 1, Script s n (x.filterMap f) (y.filterMap f) := by + cases step with + | insert before after letter => + cases hletter : f letter with + | none => exact ⟨0, by omega, by simpa [hletter] using Script.nil ((before ++ after).filterMap f)⟩ + | some b => exact ⟨1, le_rfl, by simpa [hletter] using (Script.single (Step.insert (substitutions := s) (before.filterMap f) (after.filterMap f) b))⟩ + | delete before after letter => + cases hletter : f letter with + | none => exact ⟨0, by omega, by simpa [hletter] using Script.nil ((before ++ after).filterMap f)⟩ + | some b => exact ⟨1, le_rfl, by simpa [hletter] using (Script.single (Step.delete (substitutions := s) (before.filterMap f) (after.filterMap f) b))⟩ + | substitute hs before after a b => + cases ha : f a with + | none => + cases hb : f b with + | none => exact ⟨0, by omega, by simpa [ha, hb] using Script.nil ((before ++ after).filterMap f)⟩ + | some b' => exact ⟨1, le_rfl, by simpa [ha, hb] using (Script.single (Step.insert (substitutions := s) (before.filterMap f) (after.filterMap f) b'))⟩ + | some a' => + cases hb : f b with + | none => exact ⟨1, le_rfl, by simpa [ha, hb] using (Script.single (Step.delete (substitutions := s) (before.filterMap f) (after.filterMap f) a'))⟩ + | some b' => exact ⟨1, le_rfl, by simpa [ha, hb] using (Script.single (Step.substitute hs (before.filterMap f) (after.filterMap f) a' b'))⟩ + +theorem script_filterMap {α : Type u} {β : Type v} {s : Bool} + (f : α → Option β) {n : ℕ} {x y : List α} (script : Script s n x y) : + ∃ m ≤ n, Script s m (x.filterMap f) (y.filterMap f) := by + induction script with + | nil word => exact ⟨0, le_rfl, .nil _⟩ + | cons step script ih => + obtain ⟨m, hm, hscript⟩ := ih + obtain ⟨l, hl, hstep⟩ := step_filterMap_script f step + exact ⟨l + m, by omega, hstep.trans hscript⟩ + +theorem edit_filterMap_le {α : Type u} {β : Type v} + (f : α → Option β) (x y : List α) : + edit (x.filterMap f) (y.filterMap f) ≤ edit x y := by + obtain ⟨m, hm, hscript⟩ := script_filterMap f (cost_spec (s := true) x y) + exact (cost_le hscript).trans hm + +/-- Right padding to a prescribed common width with a fresh tagged letter. -/ + + +theorem coarsePadTo_length {α : Type u} (n : ℕ) (word : List α) (h : word.length ≤ n) : + (coarsePadTo n word).length = n := by + simp only [coarsePadTo, List.length_append, List.length_map, List.length_replicate] + omega + +theorem coarsePadTo_remove {α : Type u} (n : ℕ) (word : List α) : + (coarsePadTo n word).filterMap id = word := by + simp [coarsePadTo, List.filterMap_map] + +/-- The actual padded instance has distance between the original distance +and twice that distance, including empty and unequal-length inputs. -/ +theorem coarsePadding_distance_bounds {α : Type u} (x y : List α) : + edit x y ≤ edit (coarsePadTo (max x.length y.length) x) + (coarsePadTo (max x.length y.length) y) ∧ + edit (coarsePadTo (max x.length y.length) x) + (coarsePadTo (max x.length y.length) y) ≤ 2 * edit x y := by + constructor + · have h := edit_filterMap_le id (coarsePadTo (max x.length y.length) x) + (coarsePadTo (max x.length y.length) y) + simpa only [coarsePadTo_remove] using h + · have hlength := cost_length_bounds (s := true) x y + change x.length ≤ y.length + edit x y ∧ y.length ≤ x.length + edit x y at hlength + have htail : edit + (List.replicate (max x.length y.length - x.length) (none : Option α)) + (List.replicate (max x.length y.length - y.length) none) ≤ edit x y := by + have h := edit_le_max_length + (List.replicate (max x.length y.length - x.length) (none : Option α)) + (List.replicate (max x.length y.length - y.length) none) + simp only [List.length_replicate] at h + rcases le_total x.length y.length with hxy | hyx + · rw [max_eq_right hxy] at h ⊢ + omega + · rw [max_eq_left hyx] at h ⊢ + omega + have hmap := cost_map_le (s := true) some x y + change edit (x.map some) (y.map some) ≤ edit x y at hmap + have happend := cost_append_le (s := true) (x.map some) (y.map some) + (List.replicate (max x.length y.length - x.length) none) + (List.replicate (max x.length y.length - y.length) none) + change edit (coarsePadTo (max x.length y.length) x) + (coarsePadTo (max x.length y.length) y) ≤ + edit (x.map some) (y.map some) + + edit (List.replicate (max x.length y.length - x.length) none) + (List.replicate (max x.length y.length - y.length) none) at happend + exact happend.trans (by omega) + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseParameters.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseParameters.lean new file mode 100644 index 0000000000000000000000000000000000000000..598706bca2e80522240f128b8cc0fb91bb542222 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseParameters.lean @@ -0,0 +1,93 @@ +import OAI.Combinatorics.EditApproximation.Geometry.Parameters +import OAI.Combinatorics.EditApproximation.Coarse.CoarseInitial +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! +# Computed numerical premises of the initial seed + +The literal dyadic estimator uses the input-computed branching factor, +threshold and precision. Its depth and distortion bounds follow from +those integer parameters. +-/ + +namespace EditApproximation + + + + + +theorem computed_coarse_branching (N : ℕ) (hN : 0 < N) + (hell : 200 ≤ inputSmallLog N) : + 4 ≤ inputHeight N ∧ inputHeight N ≤ (integerParameters N).B := by + have hlogs := inputSmallLog_bounds N hN + have hexp : 2 ≤ heightExponent N := by omega + have hH : 4 ≤ inputHeight N := by + change 2 ^ 2 ≤ 2 ^ heightExponent N + exact pow_le_pow_right₀ (by decide : 1 ≤ (2 : ℕ)) hexp + have hlog : 1 ^ 4 ≤ Nat.log 2 (inputSmallLog N) := by + apply Nat.le_log_of_pow_le (by decide : 1 < 2) + norm_num + omega + have hp := coarseExponent_maximal (inputSmallLog N) 1 hlog + have hB : inputHeight N ≤ inputHeight N ^ coarseExponent (inputSmallLog N) := by + simpa only [pow_one] using pow_le_pow_right₀ (by omega : 1 ≤ inputHeight N) hp + exact ⟨hH, hB⟩ + +theorem computed_coarse_depth (N n : ℕ) (hN : 0 < N) (hn : n ≤ N) + (hell : 200 ≤ inputSmallLog N) : + n ≤ (integerParameters N).B ^ computedCoarseDepth N n ∧ + computedCoarseDepth N n ≤ inputHeight N := by + have hB := computed_coarse_branching N hN hell + have hBtwo : 2 ≤ (integerParameters N).B := by omega + constructor + · exact (le_max_right 1 n).trans (Nat.le_pow_clog hBtwo (max 1 n)) + · have hanti := Nat.clog_anti_left (by decide : 1 < 2) hBtwo (n := max 1 n) + have hlength : max 1 n ≤ 2 ^ inputHeight N := by + apply max_le Nat.one_le_two_pow + exact hn.trans ((Nat.le_add_right N 2).trans (inputHeight_covers_length N)) + exact hanti.trans ((Nat.clog_le_iff_le_pow (by decide : 1 < 2)).2 hlength) + +theorem computed_coarse_structuralFactor (N n : ℕ) (hN : 0 < N) (hn : n ≤ N) + (hell : 200 ≤ inputSmallLog N) : + coarseStructuralFactor (initialLambda N) (computedCoarseDepth N n) ≤ 2 := by + have hH := (computed_coarse_branching N hN hell).1 + have hHQ : (4 : ℚ) ≤ inputHeight N := by exact_mod_cast hH + have hD : (computedCoarseDepth N n : ℚ) ≤ inputHeight N := by + exact_mod_cast (computed_coarse_depth N n hN hn hell).2 + apply coarseStructuralFactor_le_two + · unfold initialLambda + positivity + · unfold initialLambda + apply (div_le_iff₀ (by positivity : (0 : ℚ) < 64 * inputHeight N)).2 + nlinarith + · unfold initialLambda + rw [← mul_div_assoc, mul_one] + apply (div_le_iff₀ (by positivity : (0 : ℚ) < 64 * inputHeight N)).2 + nlinarith + +theorem computed_coarse_distortion (N n : ℕ) (hN : 0 < N) (hn : n ≤ N) + (hell : 200 ≤ inputSmallLog N) : + 25 + 16 * (integerParameters N).B * computedCoarseDepth N n ≤ + (integerParameters N).initialFactor := by + let H := inputHeight N + let B := (integerParameters N).B + have hH : 4 ≤ H := (computed_coarse_branching N hN hell).1 + have hB : 1 ≤ B := by have h := (computed_coarse_branching N hN hell).2; omega + have hD : computedCoarseDepth N n ≤ H := (computed_coarse_depth N n hN hn hell).2 + have hpoly : 25 + 16 * H ≤ H ^ 4 := by + have hsq : 16 ≤ H ^ 2 := by nlinarith + have hmul := Nat.mul_le_mul_left (H ^ 2) hsq + nlinarith + have hscaled := Nat.mul_le_mul_left B hpoly + have hdepth := Nat.mul_le_mul_left (16 * B) hD + have hfactor : (integerParameters N).initialFactor = B * H ^ 4 := by + exact pow_add H (coarseExponent (inputSmallLog N)) 4 + rw [hfactor] + nlinarith + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarsePenaltyArithmetic.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarsePenaltyArithmetic.lean new file mode 100644 index 0000000000000000000000000000000000000000..4b68eec5651f96eae721c373d26f543ebc0ac6f7 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarsePenaltyArithmetic.lean @@ -0,0 +1,114 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseArrayArithmetic +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation +namespace BinaryFraction + + + + theorem coarseGridLeftWithWork_value (two : BinaryFraction) (source : List BinaryFraction) + (htwo : two.value = 2) + (hs : ∀ a ∈ source, a.representation.den = two.representation.den) : + (coarseGridLeftWithWork two source).1.map value = coarseLeftSweep (source.map value) := by + cases source with + | nil => rfl + | cons head rest => + exact coarseGridScanWithWork_value two head rest htwo (hs head List.mem_cons_self) + (fun a ha => hs a (List.mem_cons_of_mem _ ha)) + + theorem coarseGridLeftWithWork_bounds (two : BinaryFraction) + (source : List BinaryFraction) (V D B : ℕ) (htwo : two.value = 2) + (htw : two.width ≤ B) (hbound : Nat.size (V + 2) + 2 * D + 1 ≤ B) + (hs : ∀ a ∈ source, CoarseGridCell two a V D B) : + (∀ a ∈ (coarseGridLeftWithWork two source).1, CoarseGridCell two a V D B) ∧ + (coarseGridLeftWithWork two source).2 ≤ source.length * (1200 * (B + 1) ^ 2 + 3) := by + cases source with + | nil => simp only [coarseGridLeftWithWork, List.not_mem_nil, false_implies, + implies_true, List.length_nil, Nat.zero_mul, le_refl, and_self] + | cons head rest => + have h := coarseGridScanWithWork_bounds two head rest V D B htwo htw hbound + (hs head List.mem_cons_self) (fun a ha => hs a (List.mem_cons_of_mem _ ha)) + refine ⟨h.1, h.2.trans ?_⟩ + simp only [List.length_cons, Nat.add_mul, Nat.one_mul] + omega + + + + theorem coarseGridZipMinimumWithWork_value (left right : List BinaryFraction) : + (coarseGridZipMinimumWithWork left right).1.map value = + List.zipWith min (left.map value) (right.map value) := by + induction left generalizing right with + | nil => rfl + | cons a left ih => + cases right with + | nil => rfl + | cons b right => + simp only [coarseGridZipMinimumWithWork, List.map_cons, List.zipWith_cons_cons, + minWithWork_value, ih] + + theorem coarseGridZipMinimumWithWork_cost (left right : List BinaryFraction) + (B : ℕ) (hl : ∀ a ∈ left, a.width ≤ B) (hr : ∀ a ∈ right, a.width ≤ B) : + (coarseGridZipMinimumWithWork left right).2 ≤ + min left.length right.length * (1000 * (B + 1) ^ 2 + 4) := by + induction left generalizing right with + | nil => simp only [coarseGridZipMinimumWithWork, List.length_nil, Nat.zero_min, Nat.zero_mul, le_refl] + | cons a left ih => + cases right with + | nil => simp only [coarseGridZipMinimumWithWork, List.length_nil, Nat.min_zero, Nat.zero_mul, le_refl] + | cons b right => + have hh := minWithWork_cost a b B (hl a List.mem_cons_self) (hr b List.mem_cons_self) + have ht := ih right (fun a ha => hl a (List.mem_cons_of_mem _ ha)) + (fun b hb => hr b (List.mem_cons_of_mem _ hb)) + change (minWithWork a b).2 + (coarseGridZipMinimumWithWork left right).2 + 3 ≤ _ + simp only [List.length_cons] + rw [show min (left.length + 1) (right.length + 1) = min left.length right.length + 1 by omega, + Nat.add_mul, Nat.one_mul] + omega + +/-- The two sweeps and final comparison, with every list pass charged. -/ + + + theorem coarseGridPenaltyWithWork_value (two : BinaryFraction) (source : List BinaryFraction) + (htwo : two.value = 2) + (hs : ∀ a ∈ source, a.representation.den = two.representation.den) : + (coarseGridPenaltyWithWork two source).1.map value = coarsePenaltyTransform (source.map value) := by + have hl := coarseGridLeftWithWork_value two source htwo hs + have hr := coarseGridLeftWithWork_value two source.reverse htwo + (fun a ha => hs a (List.mem_reverse.mp ha)) + simp only [List.map_reverse] at hr + simp only [coarseGridPenaltyWithWork, coarseGridZipMinimumWithWork_value, + coarsePenaltyTransform, List.map_reverse, hl, hr] + + theorem coarseGridPenaltyWithWork_cost (two : BinaryFraction) (source : List BinaryFraction) + (V D B : ℕ) (htwo : two.value = 2) (htw : two.width ≤ B) + (hbound : Nat.size (V + 2) + 2 * D + 1 ≤ B) + (hs : ∀ a ∈ source, CoarseGridCell two a V D B) : + (coarseGridPenaltyWithWork two source).2 ≤ source.length * (3500 * (B + 1) ^ 2 + 20) := by + have hl := coarseGridLeftWithWork_bounds two source V D B htwo htw hbound hs + have hr := coarseGridLeftWithWork_bounds two source.reverse V D B htwo htw hbound + (fun a ha => hs a (List.mem_reverse.mp ha)) + have hv := congrArg List.length (coarseGridLeftWithWork_value two source htwo + (fun a ha => (hs a ha).1)) + simp only [List.length_map, coarseLeftSweep_length] at hv + have hz := coarseGridZipMinimumWithWork_cost (coarseGridLeftWithWork two source).1 + (coarseGridLeftWithWork two source.reverse).1.reverse B + (fun a ha => (hl.1 a ha).2.2.2.2) + (fun a ha => (hr.1 a (List.mem_reverse.mp ha)).2.2.2.2) + have hm : min (coarseGridLeftWithWork two source).1.length + (coarseGridLeftWithWork two source.reverse).1.reverse.length ≤ source.length := by + exact (min_le_left _ _).trans_eq hv + have hz' := hz.trans (Nat.mul_le_mul_right _ hm) + simp only [List.length_reverse] at hr + change (coarseGridLeftWithWork two source).2 + (coarseGridLeftWithWork two source.reverse).2 + + (coarseGridZipMinimumWithWork (coarseGridLeftWithWork two source).1 + (coarseGridLeftWithWork two source.reverse).1.reverse).2 + 3 * source.length ≤ _ + nlinarith only [hl.2, hr.2, hz', Nat.zero_le (source.length * (B + 1) ^ 2), + Nat.zero_le source.length] + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarsePrecision.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarsePrecision.lean new file mode 100644 index 0000000000000000000000000000000000000000..fbffa6792cdd8640c51fd324e646b9a78e6b0ad4 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarsePrecision.lean @@ -0,0 +1,291 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseProbability +import OAI.Combinatorics.EditApproximation.Numerics.NumericalWork +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! +# Exact common precision of the coarse recurrence + +Minima and threshold maxima select existing rationals. All computed arrays +therefore share one denominator whose bit length grows linearly with depth. +-/ + +namespace EditApproximation + +open Finset + +universe u + +theorem coarse_rat_add_den_dvd (x y : ℚ) (common : ℕ) + (hx : x.den ∣ common) (hy : y.den ∣ common) : (x + y).den ∣ common := + (Rat.add_den_dvd_lcm x y).trans (Nat.lcm_dvd hx hy) + +theorem coarse_rat_mul_nat_den_dvd (x : ℚ) (n common : ℕ) + (hx : x.den ∣ common) : (x * n).den ∣ common := by + have h := Rat.mul_den_dvd x (n : ℚ) + simp only [Rat.den_natCast, mul_one] at h + exact h.trans hx + +theorem coarse_rat_div_nat_den_dvd (x : ℚ) (n common : ℕ) + (hn : 0 < n) (hx : x.den ∣ common) : (x / n).den ∣ common * n := by + have hnq : (n : ℚ) ≠ 0 := by exact_mod_cast hn.ne' + rw [div_eq_mul_inv] + have h := Rat.mul_den_dvd x ((n : ℚ)⁻¹) + simp only [Rat.den_inv_of_ne_zero hnq, Rat.num_natCast, Int.natAbs_natCast] at h + exact h.trans (Nat.mul_dvd_mul hx (dvd_refl n)) + +theorem coarseThresholdContribution_den_dvd (threshold scale value : ℚ) (common : ℕ) + (hscale : scale.den ∣ common) (hvalue : value.den ∣ common) : + (coarseThresholdContribution threshold scale value).den ∣ common := by + unfold coarseThresholdContribution + split_ifs + · rcases le_total value scale with h | h + · simpa only [max_eq_right h] using hscale + · simpa only [max_eq_left h] using hvalue + · simp only [Rat.den_zero, one_dvd] + +/-- A complete transformed child minimum retains the common precision. -/ +theorem coarsePenaltyMinimum_den_dvd (k : ℕ) (value : Fin (2 * k + 1) → ℚ) + (shift : Fin (2 * k + 1)) (common : ℕ) (hvalue : ∀ next, (value next).den ∣ common) : + (univ.inf' univ_nonempty (fun next => value next + 2 * Nat.dist shift.val next.val)).den ∣ common := by + obtain ⟨next, hnext, hminimum⟩ := exists_mem_eq_inf' (s := univ) univ_nonempty + (fun next => value next + 2 * Nat.dist shift.val next.val) + rw [hminimum] + apply coarse_rat_add_den_dvd _ _ common (hvalue next) + have hnat : (2 * (Nat.dist shift.val next.val : ℚ)).den = 1 := by + exact_mod_cast (Rat.den_natCast (2 * Nat.dist shift.val next.val)) + simp only [hnat, one_dvd] + +theorem coarseThresholdChildrenCost_den_dvd {B D : ℕ} {α : Type u} + (k : ℕ) (Q lam allowance : ℚ) + (value : CoarseSourceTree B α D → CoarseThresholdDraws B D → ℚ → ℕ → Fin (2 * k + 1) → ℚ) + (children : List (CoarseSourceTree B α D × Fin B × CoarseThresholdDraws B D)) + (common : ℕ) (hscale : (allowance / Q).den ∣ common) + (hchild : ∀ child draw below, (child, draw, below) ∈ children → ∀ start shift, + (value child below (lam * coarseChildThreshold B Q allowance draw) start shift).den ∣ common) + (start : ℕ) (shift : Fin (2 * k + 1)) : + (coarseThresholdChildrenCost k Q lam value allowance children start shift).den ∣ common := by + induction children generalizing start with + | nil => simp only [coarseThresholdChildrenCost, Rat.den_zero, one_dvd] + | cons data rest ih => + obtain ⟨child, draw, below⟩ := data + simp only [coarseThresholdChildrenCost] + apply coarse_rat_add_den_dvd _ _ common + · apply coarseThresholdContribution_den_dvd _ _ _ common hscale + simpa only [Nat.cast_mul, Nat.cast_ofNat] using + coarsePenaltyMinimum_den_dvd k _ shift common (hchild child draw below (by simp) start) + · exact ih (fun child draw below hmem => hchild child draw below (by simp [hmem])) _ + + + +/-- The literal rational coarse estimator has a single common denominator, +including every pruning outcome and every choice of threshold labels. -/ +theorem coarseThresholdEstimate_den_dvd {B D : ℕ} {α : Type u} [DecidableEq α] + (k q L : ℕ) (frame : List (Option α)) (tree : CoarseSourceTree B α D) + (draws : CoarseThresholdDraws B D) (allowance : ℚ) (allowanceDen : ℕ) + (hB : 0 < B) (hq : 0 < q) (hL : 0 < L) (hden : 0 < allowanceDen) + (hallowance : allowance.den ∣ allowanceDen) (start : ℕ) (shift : Fin (2 * k + 1)) : + (coarseThresholdEstimate k q (1 / L) frame tree draws allowance start shift).den ∣ + coarseCommonDenominator allowanceDen q L B D := by + induction tree generalizing allowance allowanceDen start shift with + | leaf letter => + simp only [coarseThresholdEstimate] + split_ifs + · simp only [Rat.den_zero, one_dvd] + · simp only [Rat.den_natCast, one_dvd] + | @branch D children ih => + obtain ⟨draws, below⟩ := draws + simp only [coarseThresholdEstimate] + split_ifs + · simp only [Rat.den_zero, one_dvd] + · apply coarseThresholdChildrenCost_den_dvd + · exact (coarse_rat_div_nat_den_dvd allowance q allowanceDen hq hallowance).trans + (dvd_mul_right _ _) + · intro child draw childBelow hmem childStart childShift + obtain ⟨i, hi⟩ := List.mem_ofFn.mp hmem + cases hi + have hthreshold : (coarseChildThreshold B q allowance (draws i)).den ∣ allowanceDen * (B * q) := by + simpa only [coarseChildThreshold, Nat.cast_mul] using + coarse_rat_div_nat_den_dvd (allowance * (draws i).val.succ) (B * q) allowanceDen + (Nat.mul_pos hB hq) (coarse_rat_mul_nat_den_dvd allowance _ allowanceDen hallowance) + have hchildDen : ((1 / (L : ℚ)) * coarseChildThreshold B q allowance (draws i)).den ∣ + allowanceDen * (L * B * q) := by + have heq : (1 / (L : ℚ)) * coarseChildThreshold B q allowance (draws i) = + coarseChildThreshold B q allowance (draws i) / L := by ring + rw [heq] + convert coarse_rat_div_nat_den_dvd _ L (allowanceDen * (B * q)) hL hthreshold using 1 + ring + have hchild := ih i (below i) _ (allowanceDen * (L * B * q)) (by positivity) hchildDen + childStart childShift + convert hchild using 1 + simp only [coarseCommonDenominator, pow_succ] + ring + +/-- The common-denominator representation needs only linearly many +factor bit lengths per coarse depth. -/ +theorem coarseCommonDenominator_bits (allowanceDen q L B D : ℕ) : + Nat.size (coarseCommonDenominator allowanceDen q L B D) ≤ + Nat.size allowanceDen + Nat.size q + D * (Nat.size L + Nat.size B + Nat.size q) + 1 := by + have hfirst := natural_product_bit_length allowanceDen q + have hbase := natural_product_bit_length L B + have hbaseSecond := natural_product_bit_length (L * B) q + have hpower := natural_power_bit_length (L * B * q) D + have htotal := natural_product_bit_length (allowanceDen * q) ((L * B * q) ^ D) + unfold coarseCommonDenominator + nlinarith + +theorem coarseChildThreshold_le_scale {B : ℕ} (draw : Fin B) + (Q allowance : ℚ) (hQ : 0 < Q) (ha : 0 ≤ allowance) : + coarseChildThreshold B Q allowance draw ≤ allowance / Q := by + have hB : (0 : ℚ) < B := by exact_mod_cast Nat.zero_lt_of_lt draw.isLt + have hlabel : (draw.val + 1 : ℕ) ≤ B := by omega + have hlabelQ : ((draw.val + 1 : ℕ) : ℚ) ≤ B := by exact_mod_cast hlabel + unfold coarseChildThreshold + apply (div_le_iff₀ (mul_pos hB hQ)).2 + calc + _ ≤ allowance * B := mul_le_mul_of_nonneg_left hlabelQ ha + _ = _ := by field_simp + +theorem coarseChildAllowance_le {B : ℕ} (draw : Fin B) + (Q lam allowance : ℚ) (hQ : 1 ≤ Q) (hlamone : lam ≤ 1) + (ha : 0 ≤ allowance) : lam * coarseChildThreshold B Q allowance draw ≤ allowance := by + have hthreshold := coarseChildThreshold_le_scale draw Q allowance (by linarith) ha + have hthresholdNonneg := coarseChildThreshold_nonneg (Q := Q) (allowance := allowance) draw (by linarith) ha + have hscale : allowance / Q ≤ allowance := (div_le_self ha hQ) + exact (mul_le_of_le_one_left hthresholdNonneg hlamone).trans (hthreshold.trans hscale) + +theorem coarseThresholdContribution_le_candidate (threshold scale value candidate : ℚ) + (hscale : 0 ≤ scale) (hcandidate : 0 ≤ candidate) (hle : value ≤ candidate) : + coarseThresholdContribution threshold scale value ≤ candidate + scale := by + unfold coarseThresholdContribution + split_ifs + · exact max_le (by linarith) (by linarith) + · exact add_nonneg hcandidate hscale + +theorem coarseThresholdChildrenCost_le_width {B D : ℕ} {α : Type u} + (k : ℕ) (Q lam allowance C : ℚ) + (value : CoarseSourceTree B α D → CoarseThresholdDraws B D → ℚ → ℕ → Fin (2 * k + 1) → ℚ) + (children : List (CoarseSourceTree B α D × Fin B × CoarseThresholdDraws B D)) + (hscale : 0 ≤ allowance / Q) + (hchild : ∀ child draw below, (child, draw, below) ∈ children → ∀ start shift, + 0 ≤ value child below (lam * coarseChildThreshold B Q allowance draw) start shift ∧ + value child below (lam * coarseChildThreshold B Q allowance draw) start shift ≤ child.word.length + C) + (start : ℕ) (shift : Fin (2 * k + 1)) : + coarseThresholdChildrenCost k Q lam value allowance children start shift ≤ + ((children.map (fun data => data.1.word)).flatten.length : ℚ) + + children.length * (C + allowance / Q) := by + induction children generalizing start with + | nil => simp only [coarseThresholdChildrenCost, List.map_nil, List.flatten_nil, List.length_nil, + Nat.cast_zero, zero_mul, zero_add, le_refl] + | cons data rest ih => + obtain ⟨child, draw, below⟩ := data + have hminimum := inf'_le + (fun next => value child below (lam * coarseChildThreshold B Q allowance draw) start next + + (2 * Nat.dist shift.val next.val : ℕ)) (mem_univ shift) + simp only [Nat.dist_self, mul_zero, Nat.cast_zero, add_zero] at hminimum + have hchildBound := hchild child draw below (by simp) start shift + have hstep := (coarseThresholdContribution_le_candidate (coarseChildThreshold B Q allowance draw) _ _ _ hscale + hchildBound.1 hminimum).trans (add_le_add hchildBound.2 le_rfl) + have hrest := ih (fun child draw below hmem => hchild child draw below (by simp [hmem])) + (start + child.word.length) + simp only [coarseThresholdChildrenCost, List.map_cons, List.flatten_cons, List.length_append, + List.length_cons, Nat.cast_add, Nat.cast_one] + linarith + +/-- All actual coarse estimates have polynomial magnitude, independently +of all accuracy events and all pruning outcomes. -/ +theorem coarseThresholdEstimate_magnitude {B D : ℕ} {α : Type u} [DecidableEq α] + (k : ℕ) (Q lam : ℚ) (frame : List (Option α)) + (tree : CoarseSourceTree B α D) (draws : CoarseThresholdDraws B D) + (allowance : ℚ) (hQ : 1 ≤ Q) (hlam : 0 ≤ lam) (hlamone : lam ≤ 1) + (ha : 0 ≤ allowance) (start : ℕ) (shift : Fin (2 * k + 1)) : + coarseThresholdEstimate k Q lam frame tree draws allowance start shift ≤ + tree.word.length + B * allowance / Q * coarseInternalNodes B D := by + have hQzero : 0 ≤ Q := by linarith + induction tree generalizing allowance start shift with + | leaf letter => + simp only [coarseThresholdEstimate] + split_ifs + · positivity + · have hwidth := coarseShiftCost_le_width k frame (.leaf (B := B) letter) start shift + simp only [coarseInternalNodes, Nat.cast_zero, mul_zero, add_zero] + exact_mod_cast hwidth + | @branch D children ih => + obtain ⟨draws, below⟩ := draws + simp only [coarseThresholdEstimate] + split_ifs + · positivity + · have hsum := coarseThresholdChildrenCost_le_width k Q lam allowance + (B * allowance / Q * coarseInternalNodes B D) + (fun child => coarseThresholdEstimate k Q lam frame child) + (List.ofFn fun i => (children i, draws i, below i)) (div_nonneg ha (by linarith)) + (by + intro child draw childBelow hmem childStart childShift + obtain ⟨i, hi⟩ := List.mem_ofFn.mp hmem + cases hi + have hchildAllowanceNonneg := mul_nonneg hlam (coarseChildThreshold_nonneg (Q := Q) (allowance := allowance) (draws i) (by linarith) ha) + have hchildAllowance := coarseChildAllowance_le (draws i) Q lam allowance hQ hlamone ha + have hbound := ih i (below i) _ hchildAllowanceNonneg childStart childShift + have hprecision : (B : ℚ) * (lam * coarseChildThreshold B Q allowance (draws i)) / Q * + coarseInternalNodes B D ≤ B * allowance / Q * coarseInternalNodes B D := + mul_le_mul_of_nonneg_right + (div_le_div_of_nonneg_right (mul_le_mul_of_nonneg_left hchildAllowance + (show (0 : ℚ) ≤ B by positivity)) + (show (0 : ℚ) ≤ Q by linarith)) + (show (0 : ℚ) ≤ coarseInternalNodes B D by positivity) + exact ⟨coarseThresholdEstimate_nonneg k Q lam frame (children i) (below i) _ + childStart childShift (by linarith) hchildAllowanceNonneg, + hbound.trans (add_le_add le_rfl hprecision)⟩) + start shift + convert hsum using 1 + simp only [List.length_ofFn, List.map_ofFn, Function.comp_def, CoarseSourceTree.word, + coarseInternalNodes, Nat.cast_add, Nat.cast_mul, Nat.cast_one] + ring + +theorem coarse_rational_encoding_bits (value : ℚ) (M common : ℕ) + (hcommon : 0 < common) (hden : value.den ∣ common) (hvalue : |value| ≤ M) : + rationalEncodingBits value ≤ Nat.size M + 2 * Nat.size common + 1 := by + have hnum := Nat.size_le_size (rational_numerator_bound value M hvalue) + have hmul := natural_product_bit_length M value.den + have hdenSize := Nat.size_le_size (Nat.le_of_dvd hcommon hden) + unfold rationalEncodingBits + omega + +/-- Every root array cell actually produced at an integer allowance has +an explicit magnitude and denominator bit bound, regardless of accuracy. -/ +theorem coarseThresholdEstimate_encoding_bits {B D : ℕ} {α : Type u} [DecidableEq α] + (k q L : ℕ) (frame : List (Option α)) (tree : CoarseSourceTree B α D) + (draws : CoarseThresholdDraws B D) (hB : 0 < B) (hq : 0 < q) (hL : 0 < L) + (start : ℕ) (shift : Fin (2 * k + 1)) : + rationalEncodingBits (coarseThresholdEstimate k q (1 / L) frame tree draws k start shift) ≤ + Nat.size (tree.word.length + B * k * coarseInternalNodes B D) + + 2 * (Nat.size q + D * (Nat.size L + Nat.size B + Nat.size q) + 2) + 1 := by + have hqQ : (1 : ℚ) ≤ q := by exact_mod_cast hq + have hLQ : (1 : ℚ) ≤ L := by exact_mod_cast hL + have hLpos : (0 : ℚ) < L := by exact_mod_cast hL + have hlam : (0 : ℚ) ≤ 1 / L := by positivity + have hlamOne : (1 : ℚ) / L ≤ 1 := (div_le_one hLpos).2 hLQ + have hmagnitude := coarseThresholdEstimate_magnitude k q (1 / L) frame tree draws k hqQ + hlam hlamOne (by positivity) start shift + have hscaled : (B : ℚ) * k / q * coarseInternalNodes B D ≤ B * k * coarseInternalNodes B D := + mul_le_mul_of_nonneg_right (div_le_self (by positivity) hqQ) (by positivity) + have habsolute : |coarseThresholdEstimate k q (1 / L) frame tree draws k start shift| ≤ + ((tree.word.length + B * k * coarseInternalNodes B D : ℕ) : ℚ) := by + rw [abs_of_nonneg (coarseThresholdEstimate_nonneg k q (1 / L) frame tree draws k start shift + (by positivity) (by positivity))] + push_cast + exact hmagnitude.trans (add_le_add le_rfl hscaled) + have hden := coarseThresholdEstimate_den_dvd k q L frame tree draws k 1 hB hq hL (by decide) + (by simp) start shift + have hbits := coarse_rational_encoding_bits _ + (tree.word.length + B * k * coarseInternalNodes B D) + (coarseCommonDenominator 1 q L B D) (by unfold coarseCommonDenominator; positivity) hden habsolute + have hcommon := coarseCommonDenominator_bits 1 q L B D + norm_num only [Nat.size_one] at hcommon + omega + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseProbability.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseProbability.lean new file mode 100644 index 0000000000000000000000000000000000000000..7283ab1f14444ef4b36e252b6b6343853a60c174 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseProbability.lean @@ -0,0 +1,503 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseAccuracy +import OAI.Combinatorics.EditApproximation.Coarse.CoarseSampling +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! +# The actual finite coarse randomness + +At each internal node, the child thresholds are independent uniform labels. +Recursive subtrees are independent of these labels. This complete probability +space also includes labels below pruned nodes. +-/ + +namespace EditApproximation + +open Finset MeasureTheory ProbabilityTheory + +universe u + +instance coarseDrawsFintype (B D : ℕ) : Fintype (CoarseThresholdDraws B D) := by + induction D with + | zero => exact inferInstanceAs (Fintype PUnit) + | succ D ih => + letI := ih + exact inferInstanceAs (Fintype ((Fin B → Fin B) × (Fin B → CoarseThresholdDraws B D))) + +def coarseCanonicalDraws (B : ℕ) : (D : ℕ) → CoarseThresholdDraws B D + | 0 => PUnit.unit + | D + 1 => (id, fun _ => coarseCanonicalDraws B D) + +instance coarseDrawsInhabited (B D : ℕ) : Inhabited (CoarseThresholdDraws B D) := + ⟨coarseCanonicalDraws B D⟩ + + + +instance coarseDrawsMeasurableSingletonClass (B D : ℕ) + [MeasurableSpace (Fin B)] [MeasurableSingletonClass (Fin B)] : + MeasurableSingletonClass (CoarseThresholdDraws B D) := by + induction D with + | zero => exact inferInstanceAs (MeasurableSingletonClass PUnit) + | succ D ih => + let := ih + exact inferInstanceAs + (MeasurableSingletonClass ((Fin B → Fin B) × (Fin B → CoarseThresholdDraws B D))) + +/-- Literal recursive independent label law, with a deterministic leaf. -/ + + +instance coarseDrawMeasure_isProbabilityMeasure (B D : ℕ) [NeZero B] + [MeasurableSpace (Fin B)] [MeasurableSingletonClass (Fin B)] : + IsProbabilityMeasure (coarseDrawMeasure B D) := by + induction D with + | zero => + change IsProbabilityMeasure (Measure.dirac (α := PUnit) PUnit.unit) + exact Measure.dirac.isProbabilityMeasure + | succ D ih => + let := ih + change IsProbabilityMeasure + ((Measure.pi fun _ : Fin B => (PMF.uniformOfFintype (Fin B)).toMeasure).prod + (Measure.pi fun _ : Fin B => coarseDrawMeasure B D)) + exact Measure.prod.instIsProbabilityMeasure _ _ + +/-- Symbolic number of internal nodes in a complete coarse tree. -/ +def coarseInternalNodes (B : ℕ) : ℕ → ℕ + | 0 => 0 + | D + 1 => 1 + B * coarseInternalNodes B D + +theorem coarseInternalNodes_eq_sum (B D : ℕ) : + coarseInternalNodes B D = ∑ r ∈ range D, B ^ r := by + induction D with + | zero => simp [coarseInternalNodes] + | succ D ih => + rw [coarseInternalNodes, ih, sum_range_succ'] + simp only [pow_zero, pow_succ', ← mul_sum] + omega + +/-- Actual source starts of all children of a literal list traversal. -/ +def coarseChildListStart {B D : ℕ} {α : Type u} + (children : List (CoarseSourceTree B α D)) (start : ℕ) (i : Fin children.length) : ℕ := + start + ((children.take i.val).map CoarseSourceTree.word).flatten.length + +/-- The literal list recurrence equals its finite sum at the actual starts. -/ +theorem coarseChildrenCost_eq_sum {B D : ℕ} {α : Type u} + (k : ℕ) (value : CoarseSourceTree B α D → ℕ → Fin (2 * k + 1) → ℕ) + (children : List (CoarseSourceTree B α D)) (start : ℕ) (shift : Fin (2 * k + 1)) : + coarseChildrenCost k value children start shift = + ∑ i : Fin children.length, univ.inf' univ_nonempty + (fun next => value children[i.val] (coarseChildListStart children start i) next + + 2 * Nat.dist shift.val next.val) := by + induction children generalizing start with + | nil => simp [coarseChildrenCost] + | cons child rest ih => + simp only [List.length_cons] + rw [coarseChildrenCost, Fin.sum_univ_succ] + simp only [Fin.val_zero, List.getElem_cons_zero, coarseChildListStart, List.take_zero, + List.map_nil, List.flatten_nil, List.length_nil, add_zero, Fin.val_succ, + List.getElem_cons_succ, List.take_succ_cons, List.map_cons, List.flatten_cons, + List.length_append] + rw [ih] + congr 1 + apply sum_congr rfl + intro i hi + simp only [coarseChildListStart, Nat.add_assoc] + +/-- Integrating a uniform conditional failure bound over the ancestor +labels does not add a union over the possible allowance values. -/ +theorem coarse_product_section_bound {X Y : Type*} + [MeasurableSpace X] [MeasurableSpace Y] + (μ : Measure X) (ν : Measure Y) [IsProbabilityMeasure μ] [IsProbabilityMeasure ν] + (bad : Set (X × Y)) (hbad : MeasurableSet bad) (failure : ℝ) (hfailure : 0 ≤ failure) + (hsection : ∀ x, ν.real {y | (x, y) ∈ bad} ≤ failure) : + (μ.prod ν).real bad ≤ failure := by + have hENN (x : X) : ν {y | (x, y) ∈ bad} ≤ ENNReal.ofReal failure := by + rw [← ENNReal.ofReal_toReal (measure_ne_top ν {y | (x, y) ∈ bad})] + exact ENNReal.ofReal_le_ofReal (hsection x) + have hproduct : μ.prod ν bad ≤ ENNReal.ofReal failure := by + rw [Measure.prod_apply hbad] + apply (lintegral_mono (fun x => hENN x)).trans_eq + simp + exact ENNReal.toReal_le_of_le_ofReal hfailure hproduct + +/-- The recursive child coordinates have precisely their own subtree law. -/ +theorem coarse_child_projection_probability (B D : ℕ) [NeZero B] + [MeasurableSpace (Fin B)] [MeasurableSingletonClass (Fin B)] + (i : Fin B) (bad : Set (CoarseThresholdDraws B D)) : + (Measure.pi fun _ : Fin B => coarseDrawMeasure B D).real {below | below i ∈ bad} = + (coarseDrawMeasure B D).real bad := by + have hbad : MeasurableSet bad := (Set.toFinite bad).measurableSet + have hmap := (measurePreserving_eval (μ := fun _ : Fin B => coarseDrawMeasure B D) i).map_eq + have hpreimage := Measure.map_apply (μ := Measure.pi fun _ : Fin B => coarseDrawMeasure B D) + (measurable_pi_apply i) hbad + rw [hmap] at hpreimage + exact congrArg ENNReal.toReal hpreimage.symm + +/-- Source starts attached to the full child metadata list. -/ +def coarseDataListStart {B D : ℕ} {α : Type u} + (children : List (CoarseSourceTree B α D × Fin B × CoarseThresholdDraws B D)) + (start : ℕ) (i : Fin children.length) : ℕ := + start + ((children.take i.val).map (fun data => data.1.word)).flatten.length + +theorem coarseDescendantEvents_iff {B D : ℕ} {α : Type u} + (Q lam allowance : ℚ) + (event : CoarseSourceTree B α D → CoarseThresholdDraws B D → ℚ → ℕ → Prop) + (children : List (CoarseSourceTree B α D × Fin B × CoarseThresholdDraws B D)) (start : ℕ) : + CoarseDescendantEvents Q lam allowance event children start ↔ + ∀ i : Fin children.length, event children[i.val].1 children[i.val].2.2 + (lam * coarseChildThreshold B Q allowance children[i.val].2.1) + (coarseDataListStart children start i) := by + induction children generalizing start with + | nil => simp [CoarseDescendantEvents] + | cons data rest ih => + obtain ⟨child, draw, below⟩ := data + simp only [List.length_cons] + rw [Fin.forall_fin_succ] + simp only [CoarseDescendantEvents, Fin.val_zero, List.getElem_cons_zero, + coarseDataListStart, List.take_zero, List.map_nil, List.flatten_nil, List.length_nil, + add_zero, Fin.val_succ, List.getElem_cons_succ, List.take_succ_cons, + List.map_cons, List.flatten_cons, List.length_append] + rw [ih] + simp only [coarseDataListStart, Nat.add_assoc] + +theorem coarseTrueThresholdSum_eq_sum {B D : ℕ} {α : Type u} + (k : ℕ) (Q allowance : ℚ) (transform : ℝ → ℝ) + (trueValue : CoarseSourceTree B α D → ℕ → Fin (2 * k + 1) → ℕ) + (children : List (CoarseSourceTree B α D × Fin B × CoarseThresholdDraws B D)) + (start : ℕ) (shift : Fin (2 * k + 1)) : + coarseTrueThresholdSum k Q trueValue allowance transform children start shift = + ∑ i : Fin children.length, + thresholdContribution (coarseChildThreshold B Q allowance children[i.val].2.1) + (allowance / Q) + (transform ((univ.inf' univ_nonempty (fun next => + trueValue children[i.val].1 (coarseDataListStart children start i) next + + 2 * Nat.dist shift.val next.val) : ℕ) : ℝ)) := by + induction children generalizing start with + | nil => simp [coarseTrueThresholdSum] + | cons data rest ih => + obtain ⟨child, draw, below⟩ := data + simp only [List.length_cons] + rw [coarseTrueThresholdSum, Fin.sum_univ_succ] + simp only [Fin.val_zero, List.getElem_cons_zero, coarseDataListStart, List.take_zero, + List.map_nil, List.flatten_nil, List.length_nil, add_zero, Fin.val_succ, + List.getElem_cons_succ, List.take_succ_cons, List.map_cons, List.flatten_cons, + List.length_append] + rw [ih] + congr 1 + apply sum_congr rfl + intro i hi + simp only [coarseDataListStart, Nat.add_assoc] + +def coarseNodeChildStart {B D : ℕ} {α : Type u} + (children : Fin B → CoarseSourceTree B α D) (start : ℕ) (i : Fin B) : ℕ := + start + (((List.ofFn children).take i.val).map CoarseSourceTree.word).flatten.length + +def coarseNodeChildCost {B D : ℕ} {α : Type u} + (k : ℕ) (value : CoarseSourceTree B α D → ℕ → Fin (2 * k + 1) → ℕ) + (children : Fin B → CoarseSourceTree B α D) (start : ℕ) + (shift : Fin (2 * k + 1)) (i : Fin B) : ℕ := + univ.inf' univ_nonempty (fun next => value (children i) (coarseNodeChildStart children start i) next + + 2 * Nat.dist shift.val next.val) + +theorem coarseChildrenCost_ofFn {B D : ℕ} {α : Type u} + (k : ℕ) (value : CoarseSourceTree B α D → ℕ → Fin (2 * k + 1) → ℕ) + (children : Fin B → CoarseSourceTree B α D) (start : ℕ) (shift : Fin (2 * k + 1)) : + coarseChildrenCost k value (List.ofFn children) start shift = + ∑ i : Fin B, coarseNodeChildCost k value children start shift i := by + rw [coarseChildrenCost_eq_sum] + apply Fintype.sum_equiv (finCongr (List.length_ofFn (f := children))) + intro i + simp only [List.getElem_ofFn, coarseChildListStart, coarseNodeChildCost, coarseNodeChildStart] + rfl + +theorem coarseDataListStart_ofFn {B D : ℕ} {α : Type u} + (children : Fin B → CoarseSourceTree B α D) + (draws : Fin B → Fin B) (below : Fin B → CoarseThresholdDraws B D) + (start : ℕ) (i : Fin B) : + coarseDataListStart (List.ofFn fun i => (children i, draws i, below i)) start + ⟨i.val, by simpa only [List.length_ofFn] using i.isLt⟩ = + coarseNodeChildStart children start i := by + simp only [coarseDataListStart, coarseNodeChildStart, List.map_take, List.map_ofFn, + Function.comp_def] + +theorem coarseTrueThresholdSum_ofFn {B D : ℕ} {α : Type u} + (k : ℕ) (Q allowance : ℚ) (transform : ℝ → ℝ) + (value : CoarseSourceTree B α D → ℕ → Fin (2 * k + 1) → ℕ) + (children : Fin B → CoarseSourceTree B α D) + (draws : Fin B → Fin B) (below : Fin B → CoarseThresholdDraws B D) + (start : ℕ) (shift : Fin (2 * k + 1)) : + coarseTrueThresholdSum k Q value allowance transform + (List.ofFn fun i => (children i, draws i, below i)) start shift = + ∑ i : Fin B, thresholdContribution (coarseChildThreshold B Q allowance (draws i)) + (allowance / Q) (transform (coarseNodeChildCost k value children start shift i)) := by + rw [coarseTrueThresholdSum_eq_sum] + apply Fintype.sum_equiv (finCongr (List.length_ofFn + (f := fun i => (children i, draws i, below i)))) + intro i + simp only [List.getElem_ofFn, coarseDataListStart, coarseNodeChildCost, + coarseNodeChildStart, List.map_take, List.map_ofFn, Function.comp_def] + rfl + +theorem coarseChildThreshold_cast (B : ℕ) [NeZero B] (Q allowance : ℚ) + (hQ : Q ≠ 0) (draw : Fin B) : + (coarseChildThreshold B Q allowance draw : ℝ) = + ((allowance : ℝ) / Q) * (draw.val + 1 : ℕ) / B := by + have hQr : (Q : ℝ) ≠ 0 := by exact_mod_cast hQ + have hBr : (B : ℝ) ≠ 0 := by exact_mod_cast NeZero.ne B + simp only [coarseChildThreshold, Rat.cast_div, Rat.cast_mul, Rat.cast_natCast] + field_simp + +theorem coarseTrueThresholdSum_sample {B D : ℕ} [NeZero B] {α : Type u} + (k : ℕ) (Q allowance : ℚ) (hQ : Q ≠ 0) (transform : ℝ → ℝ) + (value : CoarseSourceTree B α D → ℕ → Fin (2 * k + 1) → ℕ) + (children : Fin B → CoarseSourceTree B α D) + (draws : Fin B → Fin B) (below : Fin B → CoarseThresholdDraws B D) + (start : ℕ) (shift : Fin (2 * k + 1)) : + coarseTrueThresholdSum k Q value allowance transform + (List.ofFn fun i => (children i, draws i, below i)) start shift = + ∑ i : Fin B, coarseThresholdSample ((allowance : ℝ) / Q) + (transform (coarseNodeChildCost k value children start shift i)) (draws i) := by + rw [coarseTrueThresholdSum_ofFn] + apply sum_congr rfl + intro i hi + rw [coarseChildThreshold_cast B Q allowance hQ] + rfl + +/-- A finite family of fixed child-cost lists shares the same independent +threshold labels. A union bound needs no independence between the lists. -/ +theorem coarse_finite_threshold_simultaneous {B : ℕ} [NeZero B] + [MeasurableSpace (Fin B)] [MeasurableSingletonClass (Fin B)] + {I : Type*} [Fintype I] + (value : I → Fin B → ℝ) (scale allowance Q lam : ℝ) + (hvalue : ∀ i j, 0 ≤ value i j) (hu : 0 < scale) (ha : 0 < allowance) + (hQ : Q * scale = allowance) (hscale : scale ≤ allowance / 2) + (hlam : 0 ≤ lam) (hlamone : lam ≤ 1) + (bernstein : FiniteBernsteinInput (Measure.pi fun _ : Fin B => + (PMF.uniformOfFintype (Fin B)).toMeasure)) : + (Measure.pi fun _ : Fin B => (PMF.uniformOfFintype (Fin B)).toMeasure).real + {draws | ¬ ∀ i, |(∑ j, coarseThresholdSample scale (value i j) (draws j)) - + ∑ j, value i j| ≤ lam * (∑ j, value i j) + allowance} ≤ + Fintype.card I * (2 * Real.exp (-lam * Q / 12)) := by + classical + let μ := Measure.pi fun _ : Fin B => (PMF.uniformOfFintype (Fin B)).toMeasure + let bad (i : I) : Set (Fin B → Fin B) := + {draws | lam * (∑ j, value i j) + allowance < + |(∑ j, coarseThresholdSample scale (value i j) (draws j)) - ∑ j, value i j|} + have hsubset : {draws | ¬ ∀ i, |(∑ j, coarseThresholdSample scale (value i j) (draws j)) - + ∑ j, value i j| ≤ lam * (∑ j, value i j) + allowance} ⊆ ⋃ i, bad i := by + intro draws hdraws + obtain ⟨i, hi⟩ := not_forall.mp hdraws + exact Set.mem_iUnion.mpr ⟨i, lt_of_not_ge hi⟩ + calc + _ ≤ μ.real (⋃ i, bad i) := measureReal_mono hsubset + _ ≤ ∑ i, μ.real (bad i) := measureReal_iUnion_fintype_le bad + _ ≤ ∑ _ : I, 2 * Real.exp (-lam * Q / 12) := by + apply sum_le_sum + intro i hi + exact coarse_product_threshold_concentration (value i) scale allowance Q lam + (hvalue i) hu ha hQ hscale hlam hlamone bernstein + _ = _ := by simp only [sum_const, card_univ, nsmul_eq_mul] + +/-- The two deterministic cost lists used at a node, simultaneously for +all shifts. The Boolean coordinate selects the lower or upper list. -/ +noncomputable def coarseNodeSamplingValue {B D : ℕ} {α : Type u} + (k : ℕ) (lam : ℚ) (f : ℝ) + (value : CoarseSourceTree B α D → ℕ → Fin (2 * k + 1) → ℕ) + (children : Fin B → CoarseSourceTree B α D) (start : ℕ) + (index : Fin (2 * k + 1) × Bool) (i : Fin B) : ℝ := + if index.2 then + (coarseNodeChildCost k value children start index.1 i : ℝ) / (f * (1 + (lam : ℝ))) + else f * coarseNodeChildCost k value children start index.1 i / (1 - (lam : ℝ)) + +noncomputable def CoarseNodeDeviationEvent {B D : ℕ} {α : Type u} + (k : ℕ) (Q lam allowance : ℚ) (f : ℝ) + (value : CoarseSourceTree B α D → ℕ → Fin (2 * k + 1) → ℕ) + (children : Fin B → CoarseSourceTree B α D) (start : ℕ) + (draws : Fin B → Fin B) : Prop := + ∀ index : Fin (2 * k + 1) × Bool, + |(∑ i, coarseThresholdSample ((allowance : ℝ) / Q) + (coarseNodeSamplingValue k lam f value children start index i) (draws i)) - + ∑ i, coarseNodeSamplingValue k lam f value children start index i| ≤ + (lam : ℝ) * (∑ i, coarseNodeSamplingValue k lam f value children start index i) + allowance + +/-- One complete node event costs four scalar Bernstein tails per shift. -/ +theorem coarseNodeDeviationEvent_probability {B D : ℕ} [NeZero B] {α : Type u} + [MeasurableSpace (Fin B)] [MeasurableSingletonClass (Fin B)] + (k : ℕ) (Q lam allowance : ℚ) (f : ℝ) + (value : CoarseSourceTree B α D → ℕ → Fin (2 * k + 1) → ℕ) + (children : Fin B → CoarseSourceTree B α D) (start : ℕ) + (hQ : 2 ≤ Q) (hlam : 0 ≤ lam) (hlamone : lam < 1) + (ha : 0 < allowance) (hf : 0 < f) + (bernstein : FiniteBernsteinInput (Measure.pi fun _ : Fin B => + (PMF.uniformOfFintype (Fin B)).toMeasure)) : + (Measure.pi fun _ : Fin B => (PMF.uniformOfFintype (Fin B)).toMeasure).real + {draws | ¬ CoarseNodeDeviationEvent k Q lam allowance f value children start draws} ≤ + 4 * (2 * k + 1 : ℕ) * Real.exp (-(lam : ℝ) * Q / 12) := by + have hQr : (2 : ℝ) ≤ Q := by exact_mod_cast hQ + have hQpos : (0 : ℝ) < Q := by linarith + have har : (0 : ℝ) < allowance := by exact_mod_cast ha + have hlr : (0 : ℝ) ≤ lam := by exact_mod_cast hlam + have hlone : (lam : ℝ) < 1 := by exact_mod_cast hlamone + have hvalue (index : Fin (2 * k + 1) × Bool) (i : Fin B) : + 0 ≤ coarseNodeSamplingValue k lam f value children start index i := by + simp only [coarseNodeSamplingValue] + split_ifs <;> positivity + have hscale : (allowance : ℝ) / Q ≤ allowance / 2 := by + apply div_le_div_of_nonneg_left har.le (by norm_num) hQr + have hbound := coarse_finite_threshold_simultaneous + (coarseNodeSamplingValue k lam f value children start) + ((allowance : ℝ) / Q) allowance Q lam hvalue (div_pos har hQpos) har + (by field_simp) hscale hlr hlone.le bernstein + simp only [Fintype.card_prod, Fintype.card_fin, Fintype.card_bool, + Nat.cast_mul, Nat.cast_ofNat] at hbound + unfold CoarseNodeDeviationEvent + apply hbound.trans_eq + ring + +/-- The deviation event is expressed using only the root labels, yet it +implies the literal true-cost inequalities for every subtree realization. -/ +theorem coarseNodeDeviationEvent_bounds {B D : ℕ} [NeZero B] {α : Type u} + (k : ℕ) (Q lam allowance : ℚ) (f : ℝ) (hQ : Q ≠ 0) + (value : CoarseSourceTree B α D → ℕ → Fin (2 * k + 1) → ℕ) + (children : Fin B → CoarseSourceTree B α D) + (draws : Fin B → Fin B) (below : Fin B → CoarseThresholdDraws B D) (start : ℕ) + (hevent : CoarseNodeDeviationEvent k Q lam allowance f value children start draws) : + ∀ shift, + (1 - (lam : ℝ)) * + ((coarseChildrenCost k value (List.ofFn children) start shift : ℝ) / + (f * (1 + (lam : ℝ)))) - allowance ≤ + coarseTrueThresholdSum k Q value allowance + (fun cost => cost / (f * (1 + (lam : ℝ)))) + (List.ofFn fun i => (children i, draws i, below i)) start shift ∧ + coarseTrueThresholdSum k Q value allowance + (fun cost => f * cost / (1 - (lam : ℝ))) + (List.ofFn fun i => (children i, draws i, below i)) start shift ≤ + (1 + (lam : ℝ)) * + (f * (coarseChildrenCost k value (List.ofFn children) start shift : ℝ) / + (1 - (lam : ℝ))) + allowance := by + intro shift + have hlower := (abs_le.mp (hevent (shift, true))).1 + have hupper := (abs_le.mp (hevent (shift, false))).2 + simp only [coarseNodeSamplingValue, Bool.false_eq_true, ↓reduceIte] at hlower hupper + have hlowerSum : (∑ i : Fin B, + (coarseNodeChildCost k value children start shift i : ℝ) / (f * (1 + (lam : ℝ)))) = + (coarseChildrenCost k value (List.ofFn children) start shift : ℝ) / + (f * (1 + (lam : ℝ))) := by + rw [← sum_div, coarseChildrenCost_ofFn, Nat.cast_sum] + have hupperSum : (∑ i : Fin B, + f * (coarseNodeChildCost k value children start shift i : ℝ) / (1 - (lam : ℝ))) = + f * (coarseChildrenCost k value (List.ofFn children) start shift : ℝ) / + (1 - (lam : ℝ)) := by + rw [← sum_div, ← mul_sum, coarseChildrenCost_ofFn, Nat.cast_sum] + rw [hlowerSum] at hlower + rw [hupperSum] at hupper + rw [coarseTrueThresholdSum_sample k Q allowance hQ, + coarseTrueThresholdSum_sample k Q allowance hQ] + constructor <;> linarith + +/-- Root and actual descendant events suffice for the complete-tree +accuracy event; no approximate child value occurs in the root event. -/ +theorem coarseAccuracyEvent_of_node {B D : ℕ} [NeZero B] {α : Type u} [DecidableEq α] + (k : ℕ) (Q lam allowance : ℚ) (frame : List (Option α)) + (children : Fin B → CoarseSourceTree B α D) + (draws : Fin B → Fin B) (below : Fin B → CoarseThresholdDraws B D) + (start : ℕ) (hQ : Q ≠ 0) + (hchild : ∀ i, CoarseAccuracyEvent k Q lam frame (children i) (below i) + (lam * coarseChildThreshold B Q allowance (draws i)) (coarseNodeChildStart children start i)) + (hnode : CoarseNodeDeviationEvent k Q lam allowance (coarseStructuralFactor lam D) + (fun child => coarseShiftCost k frame child) children start draws) : + CoarseAccuracyEvent k Q lam frame (.branch children) (draws, below) allowance start := by + constructor + · rw [coarseDescendantEvents_iff] + intro i + simpa only [List.getElem_ofFn, coarseDataListStart, coarseNodeChildStart, + List.map_take, List.map_ofFn, Function.comp_def] using + hchild ⟨i.val, by simpa only [List.length_ofFn] using i.isLt⟩ + · simpa only [List.map_ofFn, Function.comp_def] using + coarseNodeDeviationEvent_bounds k Q lam allowance (coarseStructuralFactor lam D) hQ + (fun child => coarseShiftCost k frame child) children draws below start hnode + +/-- Simultaneous accuracy for the literal finite recursive estimator. +Every descendant is integrated conditional on its ancestor labels, with a +bound uniform in its resulting positive allowance. -/ +theorem coarseAccuracyEvent_failure {B D : ℕ} [NeZero B] {α : Type u} [DecidableEq α] + [MeasurableSpace (Fin B)] [MeasurableSingletonClass (Fin B)] + (k : ℕ) (Q lam : ℚ) (frame : List (Option α)) + (tree : CoarseSourceTree B α D) (allowance : ℚ) (start : ℕ) + (hQ : 2 ≤ Q) (hlam : 0 < lam) (hlamone : lam < 1) (ha : 0 < allowance) + (bernstein : FiniteBernsteinInput (Measure.pi fun _ : Fin B => + (PMF.uniformOfFintype (Fin B)).toMeasure)) : + (coarseDrawMeasure B D).real + {draws | ¬ CoarseAccuracyEvent k Q lam frame tree draws allowance start} ≤ + (coarseInternalNodes B D : ℝ) * + (4 * (2 * k + 1 : ℕ) * Real.exp (-(lam : ℝ) * Q / 12)) := by + classical + have hQpos : 0 < Q := by linarith + induction tree generalizing allowance start with + | leaf letter => simp only [CoarseAccuracyEvent, not_true_eq_false, Set.ofPred_false, + measureReal_empty, coarseInternalNodes, Nat.cast_zero, zero_mul, le_refl] + | @branch D children ih => + let μ := Measure.pi fun _ : Fin B => (PMF.uniformOfFintype (Fin B)).toMeasure + let ν := Measure.pi fun _ : Fin B => coarseDrawMeasure B D + let oneFailure := 4 * (2 * k + 1 : ℕ) * Real.exp (-(lam : ℝ) * Q / 12) + let childFailure := (coarseInternalNodes B D : ℝ) * oneFailure + let nodeBad : Set ((Fin B → Fin B) × (Fin B → CoarseThresholdDraws B D)) := + {data | ¬ CoarseNodeDeviationEvent k Q lam allowance (coarseStructuralFactor lam D) + (fun child => coarseShiftCost k frame child) children start data.1} + let childBad (i : Fin B) : Set ((Fin B → Fin B) × (Fin B → CoarseThresholdDraws B D)) := + {data | ¬ CoarseAccuracyEvent k Q lam frame (children i) (data.2 i) + (lam * coarseChildThreshold B Q allowance (data.1 i)) (coarseNodeChildStart children start i)} + have hsubset : {data : (Fin B → Fin B) × (Fin B → CoarseThresholdDraws B D) | + ¬ CoarseAccuracyEvent k Q lam frame (.branch children) data allowance start} ⊆ + nodeBad ∪ ⋃ i, childBad i := by + intro data hdata + by_cases hnode : data ∈ nodeBad + · exact Or.inl hnode + · right + by_contra hchildren + apply hdata + obtain ⟨draws, below⟩ := data + apply coarseAccuracyEvent_of_node k Q lam allowance frame children draws below start hQpos.ne' + · intro i + by_contra hi + exact hchildren (Set.mem_iUnion.mpr ⟨i, hi⟩) + · exact of_not_not hnode + have hnodeProbability : (μ.prod ν).real nodeBad ≤ oneFailure := by + have hnodeSet : nodeBad = + {draws | ¬ CoarseNodeDeviationEvent k Q lam allowance (coarseStructuralFactor lam D) + (fun child => coarseShiftCost k frame child) children start draws} ×ˢ Set.univ := by + ext data + simp only [nodeBad, Set.mem_ofPred_eq, Set.mem_prod, Set.mem_univ, and_true] + rw [hnodeSet, measureReal_prod_prod, probReal_univ, mul_one] + exact coarseNodeDeviationEvent_probability k Q lam allowance (coarseStructuralFactor lam D) + (fun child => coarseShiftCost k frame child) children start hQ hlam.le hlamone ha + (lt_of_lt_of_le zero_lt_one (coarseStructuralFactor_one_le lam D hlam.le hlamone)) bernstein + have hchildProbability (i : Fin B) : (μ.prod ν).real (childBad i) ≤ childFailure := by + apply coarse_product_section_bound μ ν (childBad i) (Set.toFinite _).measurableSet + childFailure (by dsimp [childFailure, oneFailure]; positivity) + intro draws + change ν.real {below | below i ∈ {childDraws | + ¬ CoarseAccuracyEvent k Q lam frame (children i) childDraws + (lam * coarseChildThreshold B Q allowance (draws i)) + (coarseNodeChildStart children start i)}} ≤ childFailure + rw [coarse_child_projection_probability] + exact ih i _ _ (mul_pos hlam (coarseChildThreshold_pos (draws i) hQpos ha)) + change (μ.prod ν).real _ ≤ _ + calc + _ ≤ (μ.prod ν).real (nodeBad ∪ ⋃ i, childBad i) := measureReal_mono hsubset + _ ≤ (μ.prod ν).real nodeBad + (μ.prod ν).real (⋃ i, childBad i) := measureReal_union_le _ _ + _ ≤ oneFailure + ∑ i, (μ.prod ν).real (childBad i) := + add_le_add hnodeProbability (measureReal_iUnion_fintype_le childBad) + _ ≤ oneFailure + ∑ _ : Fin B, childFailure := + add_le_add_right (sum_le_sum (fun i _ => hchildProbability i)) _ + _ = _ := by + simp only [sum_const, card_univ, Fintype.card_fin, nsmul_eq_mul, coarseInternalNodes, + Nat.cast_add, Nat.cast_mul, Nat.cast_one] + dsimp [childFailure, oneFailure] + push_cast + ring + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseRangeCopy.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseRangeCopy.lean new file mode 100644 index 0000000000000000000000000000000000000000..2d532444c3180ab393e7cd159ac484506ae818a6 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseRangeCopy.lean @@ -0,0 +1,40 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseReadAccess +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation + +/-- Copy a range from an indexed immutable input. Each step charges the +source read, copied symbol bits, and literal binary address increment. -/ + + +theorem coarseRangeCopyWithWork_value (read : ℕ → ℕ) (start length : ℕ) : + (coarseRangeCopyWithWork read start length).1 = + List.ofFn (fun i : Fin length => read (start + i.val)) := by + induction length generalizing start with + | zero => simp only [coarseRangeCopyWithWork, List.ofFn_zero] + | succ length ih => + simp only [coarseRangeCopyWithWork, binaryNaturalAddWithWork_value, ih, List.ofFn_succ, + Fin.val_zero, Nat.add_zero, Fin.val_succ, Nat.add_comm, Nat.add_left_comm] + +theorem coarseRangeCopyWithWork_cost (read : ℕ → ℕ) (limit A S start length : ℕ) + (hbits : ∀ i ≤ limit, Nat.size i ≤ A) + (hsymbol : ∀ i < limit, Nat.size (read i) ≤ S) (hspan : start + length ≤ limit) : + (coarseRangeCopyWithWork read start length).2 ≤ (length + 1) * (40 * (A + 1) + S) := by + induction length generalizing start with + | zero => simp only [coarseRangeCopyWithWork]; omega + | succ length ih => + have hstart : start < limit := by omega + have ha := hbits start (by omega) + have hs := hsymbol start hstart + have hc := binaryNaturalAddWithWork_cost start 1 + rw [show Nat.size 1 = 1 by decide] at hc + have hr := ih (start + 1) (by omega) + simp only [coarseRangeCopyWithWork, binaryNaturalAddWithWork_value] + nlinarith only [ha, hs, hc, hr, Nat.zero_le A, Nat.zero_le S] + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseReadAccess.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseReadAccess.lean new file mode 100644 index 0000000000000000000000000000000000000000..a05c8a9f42ce4d454e640f40341d926a3af7e795 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseReadAccess.lean @@ -0,0 +1,52 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseDescriptorWork +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation + +/-- A padded-source lookup tests its virtual endpoint and then reads the +original symbol array. Padding is represented by `none`. -/ + + +theorem coarsePaddedReadWithWork_value {α : Type*} (n : ℕ) (source : List α) (offset : ℕ) : + (coarsePaddedReadWithWork n source offset).1 = coarsePaddedRead n source offset := by + unfold coarsePaddedReadWithWork coarsePaddedRead + dsimp only + simp only [binaryNaturalCompareWithWork_lt] + +theorem coarsePaddedReadWithWork_cost {α : Type*} (n : ℕ) (source : List α) + (offset A : ℕ) (hn : Nat.size n ≤ A) (ho : Nat.size offset ≤ A) : + (coarsePaddedReadWithWork n source offset).2 ≤ 12 * (A + 1) := by + have h := binaryNaturalCompareWithWork_cost offset n + change (binaryNaturalCompareWithWork offset n).2 + Nat.size n + Nat.size offset + 2 ≤ _ + omega + +theorem coarsePaddedRead_symbol_mem (n : ℕ) (source : List ℕ) (offset a : ℕ) + (h : coarsePaddedRead n source offset = some (some a)) : a ∈ source := by + unfold coarsePaddedRead at h + split_ifs at h + exact List.mem_of_getElem? (Option.some.inj h) + +/-- Child offsets are formed by literal multiplication and addition. -/ + + +theorem coarseChildOffsetWithWork_value (offset capacity index : ℕ) : + bitWordValue (coarseChildOffsetWithWork offset capacity index).1 = offset + index * capacity := by + simp only [coarseChildOffsetWithWork, binaryNaturalAddWithWork_value, binaryNaturalMulWithWork_value] + +theorem coarseChildOffsetWithWork_cost (offset capacity index A : ℕ) + (ho : Nat.size offset ≤ A) (hc : Nat.size capacity ≤ A) (hi : Nat.size index ≤ A) : + (coarseChildOffsetWithWork offset capacity index).2 ≤ 200 * (A + 1) ^ 2 := by + have hm := binaryNaturalMulWithWork_cost index capacity + have ha := binaryNaturalAddWithWork_cost offset (index * capacity) + have hp := natural_product_bit_length index capacity + simp only [coarseChildOffsetWithWork, binaryNaturalMulWithWork_value] + have hmax : max (Nat.size offset) (Nat.size (index * capacity)) ≤ 2 * A + 1 := by + apply max_le <;> omega + nlinarith only [hm, ha, hp, ho, hc, hi, hmax, Nat.zero_le A] + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseReadBudget.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseReadBudget.lean new file mode 100644 index 0000000000000000000000000000000000000000..2bc66dd03dd707ea95bad97be6468da5dfe85f40 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseReadBudget.lean @@ -0,0 +1,68 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseReadNumericalBounds + +namespace OAI + +namespace EditApproximation + +/-- A finite uniform bound on the actually executed source-index operations. +The depth and offset ranges are the original padded source capacity. -/ +structure CoarseReadBudget (B R k n : ℕ) (source target : List ℕ) (K : ℕ) : Prop where + descriptor : ∀ d ≤ R, ∀ offset ≤ B ^ R, (coarseDescriptorWithWork B d n offset).2 ≤ K + power : ∀ d ≤ R, (bitPowerWithWork B.bits d).2 ≤ K + offset : ∀ offset ≤ B ^ R, ∀ i : Fin B, + ∀ d ≤ R, (coarseChildOffsetWithWork offset (B ^ d) i.val).2 ≤ K + advance : ∀ s ≤ n, ∀ width ≤ n, (binaryNaturalAddWithWork s width).2 ≤ K + sourceRead : ∀ offset ≤ B ^ R, (coarsePaddedReadWithWork n source offset).2 ≤ K + mismatch : ∀ offset ≤ B ^ R, ∀ s ≤ n, ∀ shift : Fin (2 * k + 1), + (BinaryFraction.coarseReadShiftWithWork k n target + (coarsePaddedRead n source offset) s shift).2 ≤ K + +theorem coarseReadBudget_height (B R k n H : ℕ) (source target : List ℕ) + (hH : 10 ≤ H) (hR : R ≤ H) (hBpos : 1 ≤ B) + (hB : Nat.size B ≤ H ^ 3) (hcap : Nat.size (B ^ R) ≤ H ^ 3) + (hn : Nat.size n ≤ H ^ 3) (hk : Nat.size (2 * k + 1) ≤ H ^ 3) + (hsymbol : ∀ a ∈ source ++ target, Nat.size a ≤ H ^ 3) : + CoarseReadBudget B R k n source target (H ^ 30) := by + have hoff (offset : ℕ) (ho : offset ≤ B ^ R) : Nat.size offset ≤ H ^ 3 := + (Nat.size_le_size ho).trans hcap + have hpow (d : ℕ) (hd : d ≤ R) : Nat.size (B ^ d) ≤ H ^ 3 := + (Nat.size_le_size (Nat.pow_le_pow_right hBpos hd)).trans hcap + have hsmall : 20 * (H ^ 3 + 1) ≤ H ^ 30 := by + have hu : 20 * (H ^ 3 + 1) ≤ BinaryFraction.coarseNumericalUnit H := by + unfold BinaryFraction.coarseNumericalUnit + nlinarith only [Nat.zero_le (bitPowerBitBudget H (7 * H ^ 3 + 3)), + Nat.zero_le (1000 * (10 * (H + 2) * (H ^ 3 + 1) + 1) ^ 2), + Nat.zero_le (H ^ 3)] + exact hu.trans (BinaryFraction.coarseNumericalUnit_le_power H hH) + refine ⟨?_, ?_, ?_, ?_, ?_, ?_⟩ + · intro d hd offset ho + exact coarseDescriptorWithWork_height_bound B d n offset H hH (hd.trans hR) hB hn (hoff _ ho) + · intro d hd + have hc := bitPowerWithWork_cost B.bits d (H ^ 3) (by simpa only [← Nat.size_eq_bits_len] using hB) + have hm := BinaryFraction.bitPowerBitBudget_mono d H (H ^ 3) (7 * H ^ 3 + 3) + (hd.trans hR) (by omega) + have hu : bitPowerBitBudget H (7 * H ^ 3 + 3) ≤ BinaryFraction.coarseNumericalUnit H := by + unfold BinaryFraction.coarseNumericalUnit + omega + exact hc.trans (hm.trans (hu.trans (BinaryFraction.coarseNumericalUnit_le_power H hH))) + · intro offset ho i d hd + exact coarseChildOffsetWithWork_height_bound offset (B ^ d) i.val H hH (hoff _ ho) + (hpow _ hd) ((Nat.size_le_size (Nat.le_of_lt i.isLt)).trans hB) + · intro s hs width hw + have hc := binaryNaturalAddWithWork_cost s width + have hb1 := (Nat.size_le_size hs).trans hn + have hb2 := (Nat.size_le_size hw).trans hn + omega + · intro offset ho + have hc := coarsePaddedReadWithWork_cost n source offset (H ^ 3) hn (hoff _ ho) + omega + · intro offset ho s hs shift + exact coarseReadShiftWithWork_height_bound k n target (coarsePaddedRead n source offset) + s shift H hH ((Nat.size_le_size (by omega : k ≤ 2 * k + 1)).trans hk) hn + ((Nat.size_le_size hs).trans hn) ((Nat.size_le_size (Nat.le_of_lt shift.isLt)).trans hk) + (fun a ha => hsymbol a (List.mem_append_right source ha)) + (fun a ha => hsymbol a (List.mem_append_left target (coarsePaddedRead_symbol_mem n source offset a ha))) + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseReadCore.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseReadCore.lean new file mode 100644 index 0000000000000000000000000000000000000000..64a049a9d852fc75eea042f2418008fbbf365749 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseReadCore.lean @@ -0,0 +1,54 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseIndexedChildren +import OAI.Combinatorics.EditApproximation.Coarse.CoarseDescriptorWork + +namespace OAI + +namespace EditApproximation +namespace BinaryFraction + +def coarseReadShiftCost {α : Type*} [DecidableEq α] (k n : ℕ) (target : List α) + (letter : Option (Option α)) (start : ℕ) (shift : Fin (2 * k + 1)) : ℕ := + match letter with + | none => 0 + | some letter => if coarseFramedRead k n target (start + shift.val) = some letter then 0 else 1 + +theorem coarseReadShiftCost_eq {B : ℕ} {α : Type*} [DecidableEq α] + (k n : ℕ) (target : List α) (hn : target.length ≤ n) + (letter : Option (Option α)) (start : ℕ) (shift : Fin (2 * k + 1)) : + coarseShiftCost k (coarseTargetFrame k (coarsePadTo n target)) + (.leaf (B := B) letter) start shift = coarseReadShiftCost k n target letter start shift := by + cases letter with + | none => rfl + | some letter => + unfold coarseShiftCost coarseReadShiftCost + rw [coarseFramedRead_value k n target hn] + +/-- Core arithmetic over source descriptors. The separate descriptor/read +counter charges address arithmetic and original-array accesses. -/ +def coarseReadCore {B : ℕ} {α : Type*} [DecidableEq α] + (k q L n : ℕ) (source target : List α) (two : BinaryFraction) : + (d : ℕ) → (offset : ℕ) → CoarseThresholdDraws B d → BinaryFraction → ℕ → + CoarseBinaryArray × ℕ + | 0, offset, _, allowance, start => + let size := coarseDescriptorLength B 0 n offset + let prune := leWithWork (nat size) allowance + if prune.1 then (none, prune.2 + Nat.size size + 1) else + let cells := arithmeticMapWithWork (fun shift : Fin (2 * k + 1) => + coarseGridNatWithWork allowance.denominator allowance.denominator_pos + (coarseReadShiftCost k n target (coarsePaddedRead n source offset) start shift)) + (List.finRange (2 * k + 1)) + (some cells.1, prune.2 + cells.2 + Nat.size size + 3 * (2 * k + 1) + 1) + | d + 1, offset, (draws, below), allowance, start => + let size := coarseDescriptorLength B (d + 1) n offset + let prune := leWithWork (nat size) allowance + if prune.1 then (none, prune.2 + Nat.size size + 1) else + let result := coarseIndexChildren k q L two + (fun i => coarseDescriptorLength B d n (offset + i.val * B ^ d)) + (fun i => coarseReadCore k q L n source target two d (offset + i.val * B ^ d) (below i)) + draws allowance (List.finRange B) start + (result.1, result.2 + prune.2 + Nat.size size + B + 1) + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseReadEvaluation.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseReadEvaluation.lean new file mode 100644 index 0000000000000000000000000000000000000000..eb5f45a69513c19876263ad81d5719b8b4da92e9 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseReadEvaluation.lean @@ -0,0 +1,50 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseReadCore + +namespace OAI + +namespace EditApproximation +namespace BinaryFraction + +attribute [local irreducible] coarseReadCore coarseBinaryEval + +theorem coarseReadCore_eq {B : ℕ} {α : Type*} [DecidableEq α] + (k q L n : ℕ) (source target : List α) (hs : source.length ≤ n) (ht : target.length ≤ n) + (two : BinaryFraction) (d offset : ℕ) (draws : CoarseThresholdDraws B d) + (allowance : BinaryFraction) (start : ℕ) : + coarseReadCore k q L n source target two d offset draws allowance start = + coarseBinaryEval k q L (coarseTargetFrame k (coarsePadTo n target)) two + (coarseReadTree B d (fun i => coarsePaddedRead n source (offset + i))) draws allowance start := by + induction d generalizing offset allowance start with + | zero => + have hlen := coarseReadTree_padded_length B 0 n offset source hs + simp only [coarseReadTree, Nat.add_zero] at hlen ⊢ + rw [coarseReadCore, coarseBinaryEval, hlen] + simp only [coarseReadShiftCost_eq k n target ht] + | succ d ih => + obtain ⟨draws, below⟩ := draws + let children := fun i : Fin B => coarseReadTree B d + (fun j => coarsePaddedRead n source (offset + i.val * B ^ d + j)) + have htree : coarseReadTree B (d + 1) (fun i => coarsePaddedRead n source (offset + i)) = + CoarseSourceTree.branch children := by + simp only [coarseReadTree, children, Nat.add_assoc] + have hlen : (CoarseSourceTree.branch children).word.length = + coarseDescriptorLength B (d + 1) n offset := by + rw [← htree] + exact coarseReadTree_padded_length B (d + 1) n offset source hs + have hloop : coarseIndexChildren k q L two + (fun i => coarseDescriptorLength B d n (offset + i.val * B ^ d)) + (fun i => coarseReadCore k q L n source target two d (offset + i.val * B ^ d) (below i)) + draws allowance (List.finRange B) start = + coarseBinaryChildren k q L two + (fun child => coarseBinaryEval k q L (coarseTargetFrame k (coarsePadTo n target)) two child) + allowance (List.ofFn fun i => (children i, draws i, below i)) start := by + simpa only [List.ofFn_eq_map] using coarseIndexChildren_eq k q L two _ children _ _ draws below + (fun i => (coarseReadTree_padded_length B d n (offset + i.val * B ^ d) source hs).symm) + (fun i a s => ih (offset + i.val * B ^ d) (below i) a s) allowance (List.finRange B) start + erw [htree, coarseReadCore, coarseBinaryEval, hlen] + simp only [hloop] + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseReadLeafWork.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseReadLeafWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..29c73c2ea21399dbc85cb83dcacc69b1f730ec39 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseReadLeafWork.lean @@ -0,0 +1,84 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseReadCore +import OAI.Combinatorics.EditApproximation.Binary.BinaryBandGuardWork +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation + +/-- Compare one tagged source letter with a framed target lookup. -/ + + +theorem coarseLetterMatchWithWork_value (actual : Option (Option ℕ)) (wanted : Option ℕ) : + (coarseLetterMatchWithWork actual wanted).1 = true ↔ actual = some wanted := by + cases actual with + | none => cases wanted <;> simp only [coarseLetterMatchWithWork, Bool.false_eq_true, reduceCtorEq] + | some actual => + cases actual <;> cases wanted <;> + simp only [coarseLetterMatchWithWork, naturalEqualWithWork_value, Option.some.injEq, + Bool.false_eq_true, reduceCtorEq, iff_self] + +theorem coarseLetterMatchWithWork_cost (actual : Option (Option ℕ)) (wanted : Option ℕ) + (S : ℕ) (ha : ∀ a, actual = some (some a) → Nat.size a ≤ S) + (hw : ∀ b, wanted = some b → Nat.size b ≤ S) : + (coarseLetterMatchWithWork actual wanted).2 ≤ 8 * S + 2 := by + cases actual with + | none => cases wanted <;> simp only [coarseLetterMatchWithWork] <;> omega + | some actual => + cases actual with + | none => cases wanted <;> simp only [coarseLetterMatchWithWork] <;> omega + | some a => + cases wanted with + | none => simp only [coarseLetterMatchWithWork]; omega + | some b => exact naturalEqualWithWork_cost a b S (ha a rfl) (hw b rfl) + +theorem coarseFramedRead_symbol_mem (k n : ℕ) (target : List ℕ) (i a : ℕ) + (h : coarseFramedRead k n target i = some (some a)) : a ∈ target := by + unfold coarseFramedRead at h + split_ifs at h + · exact List.mem_of_getElem? (Option.some.inj h) + +namespace BinaryFraction + +/-- The leaf lookup explicitly adds the shift, reads the indexed frame and +compares the stored symbol bits. -/ + + +theorem coarseReadShiftWithWork_value (k n : ℕ) (target : List ℕ) + (letter : Option (Option ℕ)) (start : ℕ) (shift : Fin (2 * k + 1)) : + (coarseReadShiftWithWork k n target letter start shift).1 = + coarseReadShiftCost k n target letter start shift := by + cases letter with + | none => rfl + | some letter => + simp only [coarseReadShiftWithWork, binaryNaturalAddWithWork_value, + coarseFramedReadWithWork_value, coarseReadShiftCost, + coarseLetterMatchWithWork_value] + +theorem coarseReadShiftWithWork_cost (k n : ℕ) (target : List ℕ) + (letter : Option (Option ℕ)) (start : ℕ) (shift : Fin (2 * k + 1)) (A S : ℕ) + (hk : Nat.size k ≤ A) (hn : Nat.size n ≤ A) (hs : Nat.size start ≤ A) + (hi : Nat.size shift.val ≤ A) (ht : ∀ a ∈ target, Nat.size a ≤ S) + (hl : ∀ a, letter = some (some a) → Nat.size a ≤ S) : + (coarseReadShiftWithWork k n target letter start shift).2 ≤ 200 * (A + 3) + 8 * S := by + cases letter with + | none => simp only [coarseReadShiftWithWork]; omega + | some letter => + have hp := binaryNaturalAdd_size_le start shift.val + have hpos : Nat.size (start + shift.val) ≤ A + 2 := hp.trans (Nat.add_le_add_right (max_le hs hi) 2) + have hf := coarseFramedReadWithWork_cost k n target (start + shift.val) (A + 2) + (by omega) (by omega) hpos + have hm := coarseLetterMatchWithWork_cost + (coarseFramedReadWithWork k n target (start + shift.val)).1 letter S + (fun a ha => ht a (coarseFramedRead_symbol_mem k n target (start + shift.val) a + ((coarseFramedReadWithWork_value k n target _).symm.trans ha))) + (fun a ha => hl a (congrArg some ha)) + have ha := binaryNaturalAddWithWork_cost start shift.val + simp only [coarseReadShiftWithWork, binaryNaturalAddWithWork_value] + omega + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseReadNumericalBounds.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseReadNumericalBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..7fd68843c296569ca00daf45686e7717e98e20f2 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseReadNumericalBounds.lean @@ -0,0 +1,59 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseReadAccess +import OAI.Combinatorics.EditApproximation.Coarse.CoarseReadLeafWork +import OAI.Combinatorics.EditApproximation.Coarse.CoarseNumericalUnit + +namespace OAI + +namespace EditApproximation + +/-- The same small numerical envelope covers constructing a node's length. -/ +theorem coarseDescriptorWithWork_height_bound (B d n offset H : ℕ) + (hH : 10 ≤ H) (hd : d ≤ H) (hB : Nat.size B ≤ H ^ 3) + (hn : Nat.size n ≤ H ^ 3) (ho : Nat.size offset ≤ H ^ 3) : + (coarseDescriptorWithWork B d n offset).2 ≤ H ^ 30 := by + have hc := coarseDescriptorWithWork_cost B d n offset (H ^ 3) hB hn ho + have hp := BinaryFraction.bitPowerBitBudget_mono d H (H ^ 3) (7 * H ^ 3 + 3) hd (by omega) + let W := 10 * (H + 2) * (H ^ 3 + 1) + 1 + have hw : (d + 2) * (H ^ 3 + 1) ≤ W := by + have hm := Nat.mul_le_mul_right (H ^ 3 + 1) (show d + 2 ≤ H + 2 by omega) + dsimp only [W] + nlinarith only [hm, Nat.zero_le ((H + 2) * (H ^ 3 + 1))] + have hl : 100 * (d + 2) * (H ^ 3 + 1) ≤ 1000 * W ^ 2 := by + have hW : 1 ≤ W := by dsimp only [W]; omega + nlinarith only [hw, hW] + have hunit : (coarseDescriptorWithWork B d n offset).2 ≤ BinaryFraction.coarseNumericalUnit H := by + unfold BinaryFraction.coarseNumericalUnit + change _ ≤ bitPowerBitBudget H (7 * H ^ 3 + 3) + 1000 * W ^ 2 + _ + omega + exact hunit.trans (BinaryFraction.coarseNumericalUnit_le_power H hH) + +theorem coarseChildOffsetWithWork_height_bound (offset capacity index H : ℕ) + (hH : 10 ≤ H) (ho : Nat.size offset ≤ H ^ 3) + (hc : Nat.size capacity ≤ H ^ 3) (hi : Nat.size index ≤ H ^ 3) : + (coarseChildOffsetWithWork offset capacity index).2 ≤ H ^ 30 := by + have h := coarseChildOffsetWithWork_cost offset capacity index (H ^ 3) ho hc hi + have hu : 200 * (H ^ 3 + 1) ^ 2 ≤ BinaryFraction.coarseNumericalUnit H := by + unfold BinaryFraction.coarseNumericalUnit + omega + exact h.trans (hu.trans (BinaryFraction.coarseNumericalUnit_le_power H hH)) + +theorem coarseReadShiftWithWork_height_bound (k n : ℕ) (target : List ℕ) + (letter : Option (Option ℕ)) (start : ℕ) (shift : Fin (2 * k + 1)) (H : ℕ) + (hH : 10 ≤ H) (hk : Nat.size k ≤ H ^ 3) (hn : Nat.size n ≤ H ^ 3) + (hs : Nat.size start ≤ H ^ 3) (hi : Nat.size shift.val ≤ H ^ 3) + (ht : ∀ a ∈ target, Nat.size a ≤ H ^ 3) + (hl : ∀ a, letter = some (some a) → Nat.size a ≤ H ^ 3) : + (BinaryFraction.coarseReadShiftWithWork k n target letter start shift).2 ≤ H ^ 30 := by + have h := BinaryFraction.coarseReadShiftWithWork_cost k n target letter start shift + (H ^ 3) (H ^ 3) hk hn hs hi ht hl + have hh : 1 ≤ H ^ 3 := one_le_pow₀ (by omega) + have hc : 200 * (H ^ 3 + 3) + 8 * H ^ 3 ≤ 100001000 * (H ^ 3 + 1) ^ 2 := by + nlinarith only [hh] + have hu : 100001000 * (H ^ 3 + 1) ^ 2 ≤ BinaryFraction.coarseNumericalUnit H := by + unfold BinaryFraction.coarseNumericalUnit + omega + exact h.trans (hc.trans (hu.trans (BinaryFraction.coarseNumericalUnit_le_power H hH))) + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseReadTree.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseReadTree.lean new file mode 100644 index 0000000000000000000000000000000000000000..bc997a8a6ae46d1b8e26a6bdb8cb0cecc110524c --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseReadTree.lean @@ -0,0 +1,82 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseIndexedRead + +namespace OAI + +namespace EditApproximation + +/-- A source descriptor is expanded by index arithmetic. No sliced or padded +list is allocated. The function is the original stored input's read operation. -/ +def coarseReadTree (B : ℕ) {α : Type*} : + (d : ℕ) → (ℕ → Option α) → CoarseSourceTree B α d + | 0, read => .leaf (read 0) + | d + 1, read => .branch (fun i => + coarseReadTree B d (fun j => read (i.val * B ^ d + j))) + +theorem coarseReadTree_ext (B d : ℕ) {α : Type*} (read other : ℕ → Option α) + (heq : ∀ i < B ^ d, read i = other i) : + coarseReadTree B d read = coarseReadTree B d other := by + induction d generalizing read other with + | zero => exact congrArg CoarseSourceTree.leaf (heq 0 (by simp)) + | succ d ih => + apply congrArg CoarseSourceTree.branch + funext i + apply ih + intro j hj + apply heq + rw [pow_succ] + have hmul := Nat.mul_le_mul_right (B ^ d) (Nat.succ_le_of_lt i.isLt) + have hpos : 0 < B ^ d := by omega + nlinarith + +theorem coarseReadTree_list (B d : ℕ) {α : Type*} (source : List α) : + coarseReadTree B d (fun i => source[i]?) = coarseSourceTreeOfList B d source := by + induction d generalizing source with + | zero => simp only [coarseReadTree, coarseSourceTreeOfList, List.head?_eq_getElem?] + | succ d ih => + apply congrArg CoarseSourceTree.branch + funext i + rw [← ih] + apply coarseReadTree_ext + intro j hj + simp only [List.getElem?_take_of_lt hj, List.getElem?_drop, Nat.add_comm] + +theorem coarseReadTree_shift (B d start : ℕ) {α : Type*} (source : List α) : + coarseReadTree B d (fun i => source[start + i]?) = + coarseSourceTreeOfList B d (source.drop start) := by + rw [← coarseReadTree_list] + congr 1 + funext i + simp only [List.getElem?_drop] + +theorem coarseReadTree_shift_length (B d start : ℕ) {α : Type*} (source : List α) : + (coarseReadTree B d (fun i => source[start + i]?)).word.length = + min (B ^ d) (source.length - start) := by + rw [coarseReadTree_shift, coarseSourceTreeOfList_word, List.length_take, List.length_drop] + +/-- Cached length of a descriptor into a virtually padded source. -/ +def coarseDescriptorLength (B d n start : ℕ) : ℕ := min (B ^ d) (n - start) + +theorem coarseReadTree_padded_length (B d n start : ℕ) {α : Type*} + (source : List α) (hn : source.length ≤ n) : + (coarseReadTree B d (fun i => coarsePaddedRead n source (start + i))).word.length = + coarseDescriptorLength B d n start := by + have heq : (fun i => coarsePaddedRead n source (start + i)) = + (fun i => (coarsePadTo n source)[start + i]?) := by + funext i + exact coarsePaddedRead_value n source hn _ + rw [heq, coarseReadTree_shift_length, coarsePadTo_length n source hn] + rfl + +theorem coarseReadTree_entry (B d : ℕ) {α : Type*} (source target : List α) : + coarseReadTree B d (coarsePaddedRead (coarseEntryWidth source target) source) = + coarseEntryTree B d source target := by + have heq : coarsePaddedRead (coarseEntryWidth source target) source = + (fun i => (coarsePadTo (coarseEntryWidth source target) source)[i]?) := by + funext i + exact coarsePaddedRead_value _ _ (le_max_left _ _) i + rw [heq, coarseReadTree_list] + rfl + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseRootBounds.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseRootBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..207070c8096c10f5ebda0a7fa9007eee06687cae --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseRootBounds.lean @@ -0,0 +1,63 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseRootWork + +namespace OAI + +namespace EditApproximation +namespace BinaryFraction + + theorem coarseBinaryRead_width (array : CoarseBinaryArray) (i A : ℕ) + (hA : 2 ≤ A) (hw : ∀ cells, array = some cells → ∀ a ∈ cells, a.width ≤ A) : + (coarseBinaryRead array i).width ≤ A := by + cases array with + | none => exact (nat_width_le 0).trans (by simpa using hA) + | some cells => + simp only [coarseBinaryRead] + cases h : cells[i]? with + | none => exact (nat_width_le 0).trans (by simpa using hA) + | some a => exact hw cells rfl a (List.mem_of_getElem? h) + + theorem coarseRootWithWork_width {B d : ℕ} {α : Type*} [DecidableEq α] + (k q L N D A : ℕ) (hB : 0 < B) (hq : 0 < q) (hL : 0 < L) + (frame : List (Option α)) (tree : CoarseSourceTree B α d) + (draws : CoarseThresholdDraws B d) (start : ℕ) (shift : Fin (2 * k + 1)) + (hBbits : Nat.size B + 2 ≤ A) (hqbits : Nat.size q + 2 ≤ A) + (hLbits : Nat.size L + 2 ≤ A) (hNbits : Nat.size N + 2 ≤ A) + (hd : Nat.size (coarseCommonDenominator 1 q L B d) ≤ D) + (hbound : Nat.size (coarseLevelMagnitude N k B d + 2) + 2 * D + 1 ≤ A) + (hstart : start + tree.word.length ≤ N) : + (coarseRootWithWork k q L hB hq hL frame tree draws start shift).1.width ≤ A := by + let den := coarseRootDenominator B q L d + let denPos := coarseRootDenominator_pos B q L d hB hq hL + let two := (coarseGridNatWithWork den.1 denPos 2).1 + let allowance := (coarseGridNatWithWork den.1 denPos k).1 + have hden := coarseRootDenominator_value B q L d + have hdenLen : den.1.length ≤ D := (coarseRootDenominator_length B q L d).trans_le hd + have htwo : two.value = 2 := coarseGridNatWithWork_value _ _ 2 + have htwoDen : two.representation.den = coarseCommonDenominator 1 q L B d := + (coarseGridNatWithWork_den _ _ 2).trans hden + have hkwidth : Nat.size k + 2 * D + 1 ≤ A := + (Nat.add_le_add_right (Nat.add_le_add_right (Nat.size_le_size + ((coarseLevelMagnitude_ge N k B d).trans (by omega))) _) _).trans hbound + have h2width : Nat.size 2 + 2 * D + 1 ≤ A := + (Nat.add_le_add_right (Nat.add_le_add_right (Nat.size_le_size + (by omega : 2 ≤ coarseLevelMagnitude N k B d + 2)) _) _).trans hbound + have htwocell : CoarseGridCell two two 2 D A := + coarseGridNatWithWork_bounds two den.1 denPos 2 2 D A + (coarseGridNatWithWork_den _ _ 2).symm hdenLen le_rfl h2width + have hacell : CoarseGridCell two allowance k D A := + coarseGridNatWithWork_bounds two den.1 denPos k k D A + (coarseGridNatWithWork_den _ _ 2).symm hdenLen le_rfl hkwidth + have hav : allowance.value = k := coarseGridNatWithWork_value _ _ k + have hpath : allowance.value.den ∣ (L * B * q) ^ 0 := by + simp only [hav, Rat.den_natCast, one_dvd] + have hc := (coarseBinaryEval_bitWork k q L N d D A frame two tree draws hB hq hL htwo + htwocell.2.2.2.2 (by rw [htwoDen]; exact hd) htwoDen hBbits hqbits hLbits hNbits hbound + 0 (by omega) allowance start hacell hpath hstart).1 + apply coarseBinaryRead_width _ _ A (by omega) + intro cells heq a ha + exact ((hc cells heq).2 a ha).2.2.2.2 + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseRootExecution.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseRootExecution.lean new file mode 100644 index 0000000000000000000000000000000000000000..d9718ac441e89dac773cfc38bb7834c98fc71e30 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseRootExecution.lean @@ -0,0 +1,72 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseBinaryCorrectness +import OAI.Combinatorics.EditApproximation.Coarse.CoarseBinaryRead +import OAI.Combinatorics.EditApproximation.Coarse.CoarseDenominatorArithmetic +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation +namespace BinaryFraction + + + + theorem coarseRootDenominator_value (B q L d : ℕ) : + bitWordValue (coarseRootDenominator B q L d).1 = coarseCommonDenominator 1 q L B d := by + simp only [coarseRootDenominator, coarseDenominatorWithWork_value, bitWordValue_bits] + + theorem coarseRootDenominator_length (B q L d : ℕ) : + (coarseRootDenominator B q L d).1.length = Nat.size (coarseCommonDenominator 1 q L B d) := by + simp only [coarseRootDenominator, coarseDenominatorWithWork_length, bitWordValue_bits] + + theorem coarseRootDenominator_pos (B q L d : ℕ) (hB : 0 < B) (hq : 0 < q) (hL : 0 < L) : + 0 < bitWordValue (coarseRootDenominator B q L d).1 := by + rw [coarseRootDenominator_value] + unfold coarseCommonDenominator + positivity + +/-- Counted root setup and array lookup around the complete binary coarse +recursion. The common denominator is built from bits, not a free conversion. -/ +def coarseRootWithWork {B d : ℕ} {α : Type*} [DecidableEq α] + (k q L : ℕ) (hB : 0 < B) (hq : 0 < q) (hL : 0 < L) + (frame : List (Option α)) (tree : CoarseSourceTree B α d) + (draws : CoarseThresholdDraws B d) (start : ℕ) (shift : Fin (2 * k + 1)) : + BinaryFraction × ℕ := + let den := coarseRootDenominator B q L d + let denPos := coarseRootDenominator_pos B q L d hB hq hL + let two := coarseGridNatWithWork den.1 denPos 2 + let allowance := coarseGridNatWithWork den.1 denPos k + let evaluated := coarseBinaryEval k q L frame two.1 tree draws allowance.1 start + (coarseBinaryRead evaluated.1 shift.val, + den.2 + two.2 + allowance.2 + evaluated.2 + 1) + + theorem coarseRootWithWork_value {B d : ℕ} {α : Type*} [DecidableEq α] + (k q L : ℕ) (hk : 0 < k) (hB : 0 < B) (hq : 0 < q) (hL : 0 < L) + (frame : List (Option α)) (tree : CoarseSourceTree B α d) + (draws : CoarseThresholdDraws B d) (start : ℕ) (shift : Fin (2 * k + 1)) : + (coarseRootWithWork k q L hB hq hL frame tree draws start shift).1.value = + coarseThresholdEstimate k q (1 / L) frame tree draws k start shift := by + let den := coarseRootDenominator B q L d + let denPos := coarseRootDenominator_pos B q L d hB hq hL + let two := (coarseGridNatWithWork den.1 denPos 2).1 + let allowance := (coarseGridNatWithWork den.1 denPos k).1 + have ht : two.value = 2 := coarseGridNatWithWork_value _ _ 2 + have hd : two.representation.den = coarseCommonDenominator 1 q L B d := + (coarseGridNatWithWork_den _ _ 2).trans (coarseRootDenominator_value B q L d) + have had : allowance.representation.den = two.representation.den := by + rw [coarseGridNatWithWork_den, coarseGridNatWithWork_den] + have hav : allowance.value = k := coarseGridNatWithWork_value _ _ k + have hp : allowance.value.den ∣ (L * B * q) ^ 0 := by simp only [hav, Rat.den_natCast, one_dvd] + have hr := coarseBinaryEval_rep k q L d frame two tree draws hB hq hL ht hd 0 + (by omega) allowance start had hp + change (coarseBinaryRead (coarseBinaryEval k q L frame two tree draws allowance start).1 shift.val).value = _ + rw [coarseBinaryRead_rep _ _ hr, coarseArrayEval_read] + · rw [hav] + · exact_mod_cast hq + · exact one_div_pos.mpr (by exact_mod_cast hL) + · rw [hav]; exact_mod_cast hk + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseRootHistory.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseRootHistory.lean new file mode 100644 index 0000000000000000000000000000000000000000..6873376fcdfe61727b80ea2bfc5faf94dc417729 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseRootHistory.lean @@ -0,0 +1,62 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseHistoryBound +import OAI.Combinatorics.EditApproximation.Coarse.CoarseCompleteWork + +namespace OAI + +namespace EditApproximation +namespace BinaryFraction + +def coarseRootArrayHistory {B d : ℕ} {α : Type*} [DecidableEq α] + (k q L : ℕ) (hB : 0 < B) (hq : 0 < q) (hL : 0 < L) + (frame : List (Option α)) (tree : CoarseSourceTree B α d) + (draws : CoarseThresholdDraws B d) (start : ℕ) : ℕ := + let den := coarseRootDenominator B q L d + let denPos := coarseRootDenominator_pos B q L d hB hq hL + let two := (coarseGridNatWithWork den.1 denPos 2).1 + let allowance := (coarseGridNatWithWork den.1 denPos k).1 + coarseBinaryArrayHistory k q L frame two tree draws allowance start + +theorem coarseRootArrayHistory_bound {B d : ℕ} {α : Type*} [DecidableEq α] + (k q L N D A : ℕ) (hB : 0 < B) (hq : 0 < q) (hL : 0 < L) + (frame : List (Option α)) (tree : CoarseSourceTree B α d) + (draws : CoarseThresholdDraws B d) (start : ℕ) + (hBbits : Nat.size B + 2 ≤ A) (hqbits : Nat.size q + 2 ≤ A) + (hLbits : Nat.size L + 2 ≤ A) (hNbits : Nat.size N + 2 ≤ A) + (hd : Nat.size (coarseCommonDenominator 1 q L B d) ≤ D) + (hbound : Nat.size (coarseLevelMagnitude N k B d + 2) + 2 * D + 1 ≤ A) + (hstart : start + tree.word.length ≤ N) : + coarseRootArrayHistory k q L hB hq hL frame tree draws start ≤ + (32 * (A + 1)) * ((B * (2 * k + 1) + 1) * coarseCompleteNodes B d) := by + let den := coarseRootDenominator B q L d + let denPos := coarseRootDenominator_pos B q L d hB hq hL + let two := (coarseGridNatWithWork den.1 denPos 2).1 + let allowance := (coarseGridNatWithWork den.1 denPos k).1 + have hden := coarseRootDenominator_value B q L d + have hdenLen : den.1.length ≤ D := (coarseRootDenominator_length B q L d).trans_le hd + have htwo : two.value = 2 := coarseGridNatWithWork_value _ _ 2 + have htwoDen : two.representation.den = coarseCommonDenominator 1 q L B d := + (coarseGridNatWithWork_den _ _ 2).trans hden + have hkwidth : Nat.size k + 2 * D + 1 ≤ A := + (Nat.add_le_add_right (Nat.add_le_add_right (Nat.size_le_size + ((coarseLevelMagnitude_ge N k B d).trans (by omega))) _) _).trans hbound + have h2width : Nat.size 2 + 2 * D + 1 ≤ A := + (Nat.add_le_add_right (Nat.add_le_add_right (Nat.size_le_size + (by omega : 2 ≤ coarseLevelMagnitude N k B d + 2)) _) _).trans hbound + have htwocell : CoarseGridCell two two 2 D A := + coarseGridNatWithWork_bounds two den.1 denPos 2 2 D A + (coarseGridNatWithWork_den _ _ 2).symm hdenLen le_rfl h2width + have hacell : CoarseGridCell two allowance k D A := + coarseGridNatWithWork_bounds two den.1 denPos k k D A + (coarseGridNatWithWork_den _ _ 2).symm hdenLen le_rfl hkwidth + have hav : allowance.value = k := coarseGridNatWithWork_value _ _ k + have hpath : allowance.value.den ∣ (L * B * q) ^ 0 := by + simp only [hav, Rat.den_natCast, one_dvd] + have hh := coarseBinaryArrayHistory_bound k q L N d D A frame two tree draws hB hq hL htwo + htwocell.2.2.2.2 (by rw [htwoDen]; exact hd) htwoDen hBbits hqbits hLbits hNbits hbound + 0 (by omega) allowance start hacell hpath hstart + exact hh.trans (Nat.mul_le_mul_left _ (coarseBinaryWeight_le_complete k q L tree draws allowance)) + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseRootWork.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseRootWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..b23ccc73e1da37f7a1e00fe0fe62dbb900f77656 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseRootWork.lean @@ -0,0 +1,72 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseRootExecution +import OAI.Combinatorics.EditApproximation.Coarse.CoarseBinaryBitWork +import OAI.Combinatorics.EditApproximation.Coarse.CoarseWeightSimulation + +namespace OAI + +namespace EditApproximation +namespace BinaryFraction + + theorem coarseRootWithWork_cost {B d : ℕ} {α : Type*} [DecidableEq α] + (k q L N D A : ℕ) (hB : 0 < B) (hq : 0 < q) (hL : 0 < L) + (frame : List (Option α)) (tree : CoarseSourceTree B α d) + (draws : CoarseThresholdDraws B d) (start : ℕ) (shift : Fin (2 * k + 1)) + (hBbits : Nat.size B + 2 ≤ A) (hqbits : Nat.size q + 2 ≤ A) + (hLbits : Nat.size L + 2 ≤ A) (hNbits : Nat.size N + 2 ≤ A) + (hd : Nat.size (coarseCommonDenominator 1 q L B d) ≤ D) (hD : D ≤ A) + (hbound : Nat.size (coarseLevelMagnitude N k B d + 2) + 2 * D + 1 ≤ A) + (hstart : start + tree.word.length ≤ N) : + (coarseRootWithWork k q L hB hq hL frame tree draws start shift).2 ≤ + bitPowerBitBudget d (7 * A + 3) + 1000 * (10 * (d + 2) * (A + 1) + 1) ^ 2 + + 100001000 * (A + 1) ^ 2 * (2 * coarseActiveArrayWork k q (1 / L) tree draws k + 1) := by + let den := coarseRootDenominator B q L d + let denPos := coarseRootDenominator_pos B q L d hB hq hL + let two := (coarseGridNatWithWork den.1 denPos 2).1 + let allowance := (coarseGridNatWithWork den.1 denPos k).1 + have hden := coarseRootDenominator_value B q L d + have hdenLen : den.1.length ≤ D := (coarseRootDenominator_length B q L d).trans_le hd + have htwo : two.value = 2 := coarseGridNatWithWork_value _ _ 2 + have htwoDen : two.representation.den = coarseCommonDenominator 1 q L B d := + (coarseGridNatWithWork_den _ _ 2).trans hden + have hkwidth : Nat.size k + 2 * D + 1 ≤ A := + (Nat.add_le_add_right (Nat.add_le_add_right (Nat.size_le_size + ((coarseLevelMagnitude_ge N k B d).trans (by omega))) _) _).trans hbound + have h2width : Nat.size 2 + 2 * D + 1 ≤ A := + (Nat.add_le_add_right (Nat.add_le_add_right (Nat.size_le_size (by omega : 2 ≤ coarseLevelMagnitude N k B d + 2)) _) _).trans hbound + have htwocell : CoarseGridCell two two 2 D A := + coarseGridNatWithWork_bounds two den.1 denPos 2 2 D A + (coarseGridNatWithWork_den _ _ 2).symm hdenLen le_rfl h2width + have hacell : CoarseGridCell two allowance k D A := + coarseGridNatWithWork_bounds two den.1 denPos k k D A + (coarseGridNatWithWork_den _ _ 2).symm hdenLen le_rfl hkwidth + have hav : allowance.value = k := coarseGridNatWithWork_value _ _ k + have hpath : allowance.value.den ∣ (L * B * q) ^ 0 := by + simp only [hav, Rat.den_natCast, one_dvd] + have hc := (coarseBinaryEval_bitWork k q L N d D A frame two tree draws hB hq hL htwo + htwocell.2.2.2.2 (by rw [htwoDen]; exact hd) htwoDen hBbits hqbits hLbits hNbits hbound + 0 (by omega) allowance start hacell hpath hstart).2 + have hw := coarseBinaryWeight_le k q L d tree draws hB hq hL 0 (by omega) allowance + (hacell.1.trans htwoDen) hpath + rw [hav] at hw + have heval := hc.trans (Nat.mul_le_mul_left (100000000 * (A + 1) ^ 2) hw) + have htwoCost := coarseGridNatWithWork_cost den.1 denPos 2 A (by omega) + (hdenLen.trans hD) + have haCost := coarseGridNatWithWork_cost den.1 denPos k A (by omega) (hdenLen.trans hD) + have hdenCost := coarseDenominatorWithWork_cost (1 : ℕ).bits q.bits L.bits B.bits d A + (by simp only [Nat.size_eq_bits_len, Nat.size_one]; omega) + (by rw [Nat.size_eq_bits_len]; omega) + (by rw [Nat.size_eq_bits_len]; omega) + (by rw [Nat.size_eq_bits_len]; omega) + change den.2 ≤ _ at hdenCost + have hfactor := Nat.mul_le_mul_left ((A + 1) ^ 2) + (show 1 ≤ 2 * coarseActiveArrayWork k q (1 / L) tree draws k + 1 by omega) + change den.2 + (coarseGridNatWithWork den.1 denPos 2).2 + + (coarseGridNatWithWork den.1 denPos k).2 + + (coarseBinaryEval k q L frame two tree draws allowance start).2 + 1 ≤ _ + nlinarith only [heval, htwoCost, haCost, hdenCost, hfactor, Nat.zero_le A, + Nat.zero_le (coarseActiveArrayWork k q (1 / L) tree draws k)] + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseSampling.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseSampling.lean new file mode 100644 index 0000000000000000000000000000000000000000..e79a79a7b56d68347c21b790ac3f8bcf4386bffb --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseSampling.lean @@ -0,0 +1,194 @@ +import OAI.Combinatorics.EditApproximation.Probability.ThresholdMoments +import OAI.Combinatorics.EditApproximation.Probability.FiniteSampling +import OAI.Combinatorics.EditApproximation.Probability.Concentration + +namespace OAI + +/-! +# Independent heterogeneous coarse threshold samples + +Every child has its own fixed true cost and an independent uniform label +in `1,...,B`. The child estimates are absent from this probability space: +they enter only the pathwise reconstruction proved separately. +-/ + +namespace EditApproximation + +open Finset MeasureTheory ProbabilityTheory + +theorem coarse_sum_labels (B : ℕ) (value : ℕ → ℝ) : + (∑ draw : Fin B, value (draw.val + 1)) = ∑ r ∈ Icc 1 B, value r := by + refine sum_bij (fun draw _ => draw.val + 1) ?_ ?_ ?_ ?_ + · intro draw hdraw + exact mem_Icc.mpr ⟨by omega, by have := draw.isLt; omega⟩ + · intro first hfirst second hsecond hequal + exact Fin.ext (by omega) + · intro r hr + obtain ⟨hlower, hupper⟩ := mem_Icc.mp hr + refine ⟨⟨r - 1, by omega⟩, mem_univ _, ?_⟩ + change r - 1 + 1 = r + omega + · intro draw hdraw + rfl + +noncomputable def coarseThresholdSample {B : ℕ} (scale value : ℝ) (draw : Fin B) : ℝ := + thresholdContribution (scale * (draw.val + 1 : ℕ) / B) scale value + +theorem coarseThresholdSample_large {B : ℕ} [NeZero B] (scale value : ℝ) + (hscale : 0 ≤ scale) (hvalue : scale ≤ value) (draw : Fin B) : + coarseThresholdSample scale value draw = value := by + have hB : (0 : ℝ) < B := by exact_mod_cast Nat.pos_of_ne_zero (NeZero.ne B) + have hdraw : (draw.val + 1 : ℝ) ≤ B := by exact_mod_cast Nat.succ_le_of_lt draw.isLt + have hthreshold : scale * (draw.val + 1 : ℕ) / B ≤ value := by + apply le_trans _ hvalue + apply (div_le_iff₀ hB).2 + exact mul_le_mul_of_nonneg_left (by simpa only [Nat.cast_add, Nat.cast_one] using hdraw) hscale + simp only [coarseThresholdSample, thresholdContribution, hthreshold, ↓reduceIte, + max_eq_left hvalue] + +/-- The mean, centered range and variance proxy are established for each +fixed cost, including the deterministic range above the threshold scale. -/ +theorem coarseThresholdSample_moments {B : ℕ} [NeZero B] + [MeasurableSpace (Fin B)] [MeasurableSingletonClass (Fin B)] + (scale value : ℝ) (hscale : 0 < scale) (hvalue : 0 ≤ value) : + (0 ≤ value - uniformMean (coarseThresholdSample (B := B) scale value) ∧ + value - uniformMean (coarseThresholdSample (B := B) scale value) ≤ scale / B) ∧ + (∀ draw : Fin B, |coarseThresholdSample scale value draw - + uniformMean (coarseThresholdSample (B := B) scale value)| ≤ scale) ∧ + (∫ draw, (coarseThresholdSample scale value draw - + uniformMean (coarseThresholdSample (B := B) scale value)) ^ 2 + ∂(PMF.uniformOfFintype (Fin B)).toMeasure) ≤ scale * value := by + have hB : 0 < B := Nat.pos_of_ne_zero (NeZero.ne B) + have hBr : (0 : ℝ) < B := by exact_mod_cast hB + by_cases hlarge : scale ≤ value + · have hconstant : coarseThresholdSample (B := B) scale value = fun _ => value := by + funext draw + exact coarseThresholdSample_large scale value hscale.le hlarge draw + rw [hconstant] + have hmean : uniformMean (fun _ : Fin B => value) = value := by + simp only [uniformMean, sum_const, card_univ, Fintype.card_fin, nsmul_eq_mul] + field_simp + simp only [hmean, sub_self, abs_zero, zero_pow (by decide : 2 ≠ 0), integral_zero] + exact ⟨⟨le_rfl, div_nonneg hscale.le hBr.le⟩, fun _ => hscale.le, + mul_nonneg hscale.le hvalue⟩ + · have hsmall : value < scale := lt_of_not_ge hlarge + have hmean : uniformMean (coarseThresholdSample (B := B) scale value) = + (∑ r ∈ Icc 1 B, thresholdContribution (scale * r / B) scale value) / B := by + simp only [uniformMean, Fintype.card_fin, coarseThresholdSample] + rw [coarse_sum_labels B (fun r => thresholdContribution (scale * r / B) scale value)] + refine ⟨?_, ?_, ?_⟩ + · rw [hmean] + exact threshold_bias B scale value hB hscale hvalue hsmall + · apply uniform_centered_bound + intro draw + unfold coarseThresholdSample thresholdContribution + split_ifs + · exact ⟨hscale.le.trans (le_max_right _ _), by rw [max_eq_right hsmall.le]⟩ + · exact ⟨le_rfl, hscale.le⟩ + · rw [uniform_integral] + simp only [uniformMean, Fintype.card_fin, coarseThresholdSample] + rw [coarse_sum_labels B (fun r => thresholdContribution (scale * r / B) scale value)] + rw [coarse_sum_labels B (fun r => + (thresholdContribution (scale * r / B) scale value - + (∑ s ∈ Icc 1 B, thresholdContribution (scale * s / B) scale value) / B) ^ 2)] + exact threshold_variance_bound B scale value hB hscale hvalue hsmall + +/-- Actual product-uniform child labels satisfy the manuscript's coarse +Bernstein tail bound for every fixed heterogeneous true-cost list. -/ +theorem coarse_product_threshold_concentration_positive {B : ℕ} [NeZero B] + [MeasurableSpace (Fin B)] [MeasurableSingletonClass (Fin B)] + (value : Fin B → ℝ) (scale allowance Q lam : ℝ) + (hvalue : ∀ i, 0 ≤ value i) (hu : 0 < scale) (ha : 0 < allowance) + (hQ : Q * scale = allowance) (hscale : scale ≤ allowance / 2) + (hlam : 0 ≤ lam) (hlamone : lam ≤ 1) + (hV : 0 < ∑ i, value i) + (bernstein : FiniteBernsteinInput (Measure.pi fun _ : Fin B => + (PMF.uniformOfFintype (Fin B)).toMeasure)) : + (Measure.pi fun _ : Fin B => (PMF.uniformOfFintype (Fin B)).toMeasure).real + {draws | lam * (∑ i, value i) + allowance < + |(∑ i, coarseThresholdSample scale (value i) (draws i)) - ∑ i, value i|} ≤ + 2 * Real.exp (-lam * Q / 12) := by + let μ := (PMF.uniformOfFintype (Fin B)).toMeasure + let sample := fun i => coarseThresholdSample (B := B) scale (value i) + let mean := ∑ i, uniformMean (sample i) + let X : Fin B → (Fin B → Fin B) → ℝ := + fun i draws => sample i (draws i) - uniformMean (sample i) + have hmoments (i : Fin B) := coarseThresholdSample_moments (B := B) scale (value i) hu (hvalue i) + have hindep : iIndepFun X (Measure.pi fun _ : Fin B => μ) := + iIndepFun_pi (μ := fun _ : Fin B => μ) + (X := fun i draw => sample i draw - uniformMean (sample i)) + (fun _ => (measurable_of_finite _).aemeasurable) + have hcenter (i : Fin B) : (∫ draws, X i draws ∂Measure.pi (fun _ : Fin B => μ)) = 0 := by + dsimp [X] + rw [integral_comp_eval (μ := fun _ : Fin B => μ) (i := i) + (f := fun draw => sample i draw - uniformMean (sample i)) + (measurable_of_finite _).aestronglyMeasurable] + exact uniform_centered_integral (sample i) + have hbound (i : Fin B) : ∀ᵐ draws ∂Measure.pi (fun _ : Fin B => μ), |X i draws| ≤ scale := by + filter_upwards [] with draws + exact (hmoments i).2.1 (draws i) + have hvariance : (∑ i, ∫ draws, (X i draws) ^ 2 ∂Measure.pi (fun _ : Fin B => μ)) ≤ + scale * (∑ i, value i) := by + rw [mul_sum] + apply sum_le_sum + intro i hi + dsimp [X] + rw [integral_comp_eval (μ := fun _ : Fin B => μ) (i := i) + (f := fun draw => (sample i draw - uniformMean (sample i)) ^ 2) + (measurable_of_finite _).aestronglyMeasurable] + exact (hmoments i).2.2 + have hbias : |mean - ∑ i, value i| ≤ scale := by + have hnonnegative := sum_nonneg (s := univ) (fun i _ => (hmoments i).1.1) + have hsum := sum_le_sum (s := univ) (fun i _ => (hmoments i).1.2) + have hB : (0 : ℝ) < B := by exact_mod_cast Nat.pos_of_ne_zero (NeZero.ne B) + simp only [sum_sub_distrib, sum_const, card_univ, Fintype.card_fin, nsmul_eq_mul] at hnonnegative hsum + have hequal : (B : ℝ) * (scale / B) = scale := by field_simp + rw [hequal] at hsum + dsimp [mean] + rw [abs_of_nonpos (by linarith)] + linarith + exact coarse_threshold_concentration (Measure.pi fun _ : Fin B => μ) bernstein X + (fun draws => ∑ i, sample i (draws i)) mean (∑ i, value i) lam allowance scale Q + hlam hlamone hV ha hu hQ hscale hindep + (fun _ => measurable_of_finite _) (fun _ => .of_finite) hcenter hbound hvariance + (by intro draws; simp only [X, mean, sum_sub_distrib]) hbias + +/-- The same exact product-uniform law, including zero total true cost. -/ +theorem coarse_product_threshold_concentration {B : ℕ} [NeZero B] + [MeasurableSpace (Fin B)] [MeasurableSingletonClass (Fin B)] + (value : Fin B → ℝ) (scale allowance Q lam : ℝ) + (hvalue : ∀ i, 0 ≤ value i) (hu : 0 < scale) (ha : 0 < allowance) + (hQ : Q * scale = allowance) (hscale : scale ≤ allowance / 2) + (hlam : 0 ≤ lam) (hlamone : lam ≤ 1) + (bernstein : FiniteBernsteinInput (Measure.pi fun _ : Fin B => + (PMF.uniformOfFintype (Fin B)).toMeasure)) : + (Measure.pi fun _ : Fin B => (PMF.uniformOfFintype (Fin B)).toMeasure).real + {draws | lam * (∑ i, value i) + allowance < + |(∑ i, coarseThresholdSample scale (value i) (draws i)) - ∑ i, value i|} ≤ + 2 * Real.exp (-lam * Q / 12) := by + by_cases hV : 0 < ∑ i, value i + · exact coarse_product_threshold_concentration_positive value scale allowance Q lam + hvalue hu ha hQ hscale hlam hlamone hV bernstein + · have htotal : (∑ i, value i) = 0 := by + have hnonnegative := sum_nonneg (s := univ) (fun i _ => hvalue i) + linarith + have hzero (i : Fin B) : value i = 0 := by + have hi := single_le_sum (s := univ) (fun i _ => hvalue i) (mem_univ i) + rw [htotal] at hi + exact le_antisymm hi (hvalue i) + have hsample (draw : Fin B) : coarseThresholdSample scale 0 draw = 0 := by + have hB : (0 : ℝ) < B := by exact_mod_cast Nat.pos_of_ne_zero (NeZero.ne B) + have hdraw : (0 : ℝ) < (draw.val + 1 : ℕ) := by positivity + have hthreshold : 0 < scale * (draw.val + 1 : ℕ) / B := by positivity + simp only [coarseThresholdSample, thresholdContribution, not_le_of_gt hthreshold, ↓reduceIte] + have hempty : {draws : Fin B → Fin B | lam * (∑ i, value i) + allowance < + |(∑ i, coarseThresholdSample scale (value i) (draws i)) - ∑ i, value i|} = ∅ := by + ext draws + simp only [hzero, hsample, sum_const_zero, mul_zero, zero_add, sub_self, abs_zero, + not_lt_of_ge ha.le, Set.mem_ofPred_eq, Set.mem_empty_iff_false] + rw [hempty, measureReal_empty] + positivity + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseScalarAllocation.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseScalarAllocation.lean new file mode 100644 index 0000000000000000000000000000000000000000..24175c4dc47d447577b7257d0614912f2f2a334b --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseScalarAllocation.lean @@ -0,0 +1,99 @@ +import OAI.Combinatorics.EditApproximation.Numerics.ScalarAllocation +import OAI.Combinatorics.EditApproximation.Coarse.CoarseThresholdStep + +namespace OAI + +namespace EditApproximation +namespace BinaryFraction + +/-- Arithmetic-only allocation; the caller owns the input words. -/ +def coarseGridNatAllocation (denominator : List Bool) + (hden : 0 < bitWordValue denominator) (n : ℕ) : ℕ := + let raw : BinaryFraction := + ⟨⟨false, (bitMulWithWork n.bits denominator).1⟩, denominator, hden⟩ + bitMulAllocation n.bits denominator + canonicalizeAllocation raw + +theorem coarseGridNatAllocation_le_work (denominator : List Bool) + (hden : 0 < bitWordValue denominator) (n : ℕ) : + coarseGridNatAllocation denominator hden n ≤ (coarseGridNatWithWork denominator hden n).2 := by + have hm := bitMulAllocation_le_work n.bits denominator + have hc := canonicalizeAllocation_le_work + (⟨⟨false, (bitMulWithWork n.bits denominator).1⟩, denominator, hden⟩ : BinaryFraction) + unfold coarseGridNatAllocation coarseGridNatWithWork + dsimp only + omega + +def coarseGridAddAllocation (a b : BinaryFraction) : ℕ := + a.numerator.addAllocation b.numerator + canonicalizeAllocation + ⟨(a.numerator.addWithWork b.numerator).1, a.denominator, a.denominator_pos⟩ + +theorem coarseGridAddAllocation_le_work (a b : BinaryFraction) : + coarseGridAddAllocation a b ≤ (coarseGridAddWithWork a b).2 := by + have ha := SignedBinary.addAllocation_le_work a.numerator b.numerator + have hc := canonicalizeAllocation_le_work + ⟨(a.numerator.addWithWork b.numerator).1, a.denominator, a.denominator_pos⟩ + unfold coarseGridAddAllocation coarseGridAddWithWork + dsimp only + omega + +def coarseDivideAllocation (a divisor : BinaryFraction) : ℕ := + divAllocation a divisor + + fixedDenominatorAllocation (divWithWork a divisor).1 a.denominator a.denominator_pos + +theorem coarseDivideAllocation_le_work (a divisor : BinaryFraction) : + coarseDivideAllocation a divisor ≤ (coarseDivideWithWork a divisor).2 := by + have hd := divAllocation_le_work a divisor + have hf := fixedDenominatorAllocation_le_work (divWithWork a divisor).1 + a.denominator a.denominator_pos + unfold coarseDivideAllocation coarseDivideWithWork + dsimp only + omega + +def coarseContributionAllocation (threshold scale a : BinaryFraction) : ℕ := + a.ltAllocation threshold + + if (leWithWork threshold a).1 then a.ltAllocation scale + else coarseGridNatAllocation a.denominator a.denominator_pos 0 + +theorem coarseContributionAllocation_le_work (threshold scale a : BinaryFraction) : + coarseContributionAllocation threshold scale a ≤ (coarseContributionWithWork threshold scale a).2 := by + have ht := ltAllocation_le_work a threshold + have hm := ltAllocation_le_work a scale + have hz := coarseGridNatAllocation_le_work a.denominator a.denominator_pos 0 + unfold coarseContributionAllocation coarseContributionWithWork + dsimp only + split_ifs <;> simp only [leWithWork, maxWithWork] <;> omega + +/-- Includes all three natural literal numerators and their unit denominators. -/ +def coarseChildThresholdAllocation (B q : ℕ) (allowance : BinaryFraction) (draw : Fin B) : ℕ := + let numerator := canonicalMulWithWork allowance (nat (draw.val + 1)) + let divisor := canonicalMulWithWork (nat B) (nat q) + canonicalMulAllocation allowance (nat (draw.val + 1)) + + canonicalMulAllocation (nat B) (nat q) + coarseDivideAllocation numerator.1 divisor.1 + + Nat.size (draw.val + 1) + Nat.size B + Nat.size q + 3 + +theorem coarseChildThresholdAllocation_le_work (B q : ℕ) (allowance : BinaryFraction) (draw : Fin B) : + coarseChildThresholdAllocation B q allowance draw ≤ + (coarseChildThresholdWithWork B q allowance draw).2 := by + have hn := canonicalMulAllocation_le_work allowance (nat (draw.val + 1)) + have hd := canonicalMulAllocation_le_work (nat B) (nat q) + have hr := coarseDivideAllocation_le_work + (canonicalMulWithWork allowance (nat (draw.val + 1))).1 + (canonicalMulWithWork (nat B) (nat q)).1 + unfold coarseChildThresholdAllocation coarseChildThresholdWithWork + dsimp only + omega + +def coarseChildAllowanceAllocation (L : ℕ) (threshold : BinaryFraction) : ℕ := + coarseDivideAllocation threshold (nat L) + Nat.size L + 1 + +theorem coarseChildAllowanceAllocation_le_work (L : ℕ) (threshold : BinaryFraction) : + coarseChildAllowanceAllocation L threshold ≤ (coarseChildAllowanceWithWork L threshold).2 := by + have h := coarseDivideAllocation_le_work threshold (nat L) + unfold coarseChildAllowanceAllocation coarseChildAllowanceWithWork + dsimp only + omega + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseScalarBounds.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseScalarBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..89343188dff9dfa3bf91fb57868655cf2885e97e --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseScalarBounds.lean @@ -0,0 +1,72 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseCellBounds +import OAI.Combinatorics.EditApproximation.Coarse.CoarseThresholdStepWork + +namespace OAI + +namespace EditApproximation +namespace BinaryFraction + + theorem coarseDivideWithWork_den_length (a b : BinaryFraction) : + (coarseDivideWithWork a b).1.denominator.length = Nat.size a.representation.den := by + change (trimBitWordWithWork a.denominator).1.length = _ + exact trimBitWordWithWork_length a.denominator + + theorem coarseDivideWithWork_bounds (two a b : BinaryFraction) (V D A : ℕ) + (hden : a.representation.den = two.representation.den) + (hd : Nat.size two.representation.den ≤ D) + (hgrid : (a.value / b.value).den ∣ a.representation.den) + (hn : 0 ≤ a.value / b.value) (hv : a.value / b.value ≤ V) + (hA : Nat.size V + 2 * D + 1 ≤ A) : + CoarseGridCell two (coarseDivideWithWork a b).1 V D A := by + have hd' : Nat.size a.representation.den ≤ D := by simpa only [hden] using hd + have hval := coarseDivideWithWork_value a b hgrid + refine ⟨(coarseDivideWithWork_den a b).trans hden, + (coarseDivideWithWork_den_length a b).trans_le hd', ?_, ?_, ?_⟩ + · rw [hval]; exact hn + · rw [hval]; exact hv + · apply (coarseCompact_width _ V D (coarseCompact_divide a b) ?_ ?_).trans hA + · rw [hval, abs_of_nonneg hn]; exact hv + · rw [coarseDivideWithWork_den]; exact hd' + + theorem coarseChildThresholdWithWork_bounds (two allowance : BinaryFraction) + (B q V D A : ℕ) (draw : Fin B) (hq : 0 < q) + (ha : CoarseGridCell two allowance V D A) + (hd : Nat.size two.representation.den ≤ D) + (hgrid : (coarseChildThreshold B q allowance.value draw).den ∣ allowance.representation.den) + (hA : Nat.size V + 2 * D + 1 ≤ A) : + CoarseGridCell two (coarseChildThresholdWithWork B q allowance draw).1 V D A := by + let num := (canonicalMulWithWork allowance (nat (draw.val + 1))).1 + let den := (canonicalMulWithWork (nat B) (nat q)).1 + have hn : num.representation.den = allowance.representation.den := by + change (canonicalMulWithWork allowance (nat (draw.val + 1))).1.representation.den = _ + rw [canonicalMulWithWork_representation, nat_representation] + simp only [UnreducedRational.mul, UnreducedRational.nat, mul_one] + have hv : num.value / den.value = coarseChildThreshold B q allowance.value draw := by + simp only [num, den, canonicalMulWithWork_value, nat_value, coarseChildThreshold] + have hq' : (0 : ℚ) < q := by exact_mod_cast hq + have hu := (coarseChildThreshold_le_scale draw (q : ℚ) allowance.value hq' ha.2.2.1).trans + ((div_le_self ha.2.2.1 (by exact_mod_cast hq)).trans ha.2.2.2.1) + change CoarseGridCell two (coarseDivideWithWork num den).1 V D A + exact coarseDivideWithWork_bounds two num den V D A (hn.trans ha.1) hd + (by rw [hv, hn]; exact hgrid) + (by rw [hv]; exact coarseChildThreshold_nonneg draw hq'.le ha.2.2.1) + (by rw [hv]; exact hu) hA + + theorem coarseChildAllowanceWithWork_bounds (two threshold : BinaryFraction) + (L V D A : ℕ) (hL : 0 < L) (ht : CoarseGridCell two threshold V D A) + (hd : Nat.size two.representation.den ≤ D) + (hgrid : (threshold.value / L).den ∣ threshold.representation.den) + (hA : Nat.size V + 2 * D + 1 ≤ A) : + CoarseGridCell two (coarseChildAllowanceWithWork L threshold).1 V D A := by + change CoarseGridCell two (coarseDivideWithWork threshold (nat L)).1 V D A + apply coarseDivideWithWork_bounds two threshold (nat L) V D A ht.1 hd + · simpa only [nat_value] using hgrid + · rw [nat_value]; exact div_nonneg ht.2.2.1 (by positivity) + · rw [nat_value] + exact (div_le_self ht.2.2.1 (by exact_mod_cast hL)).trans ht.2.2.2.1 + · exact hA + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseScalarControlSpace.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseScalarControlSpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..ed408ad24d874bcdc6dd1821901055357c9ed1b9 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseScalarControlSpace.lean @@ -0,0 +1,99 @@ +import OAI.Combinatorics.EditApproximation.Numerics.ScalarControlSpace +import OAI.Combinatorics.EditApproximation.Coarse.CoarseThresholdStep + +namespace OAI + +namespace EditApproximation +namespace BinaryFraction + +/-- Control invocations of the shared-denominator scalar construction. -/ +def coarseGridNatInvocations (denominator : List Bool) + (hden : 0 < bitWordValue denominator) (n : ℕ) : ℕ := + let raw : BinaryFraction := + ⟨⟨false, (bitMulWithWork n.bits denominator).1⟩, denominator, hden⟩ + bitMulInvocations n.bits denominator + canonicalizeInvocations raw + 1 + +theorem coarseGridNatInvocations_le_work (denominator : List Bool) + (hden : 0 < bitWordValue denominator) (n : ℕ) : + coarseGridNatInvocations denominator hden n ≤ (coarseGridNatWithWork denominator hden n).2 := by + have hm := bitMulInvocations_le_work n.bits denominator + have hc := canonicalizeInvocations_le_work + (⟨⟨false, (bitMulWithWork n.bits denominator).1⟩, denominator, hden⟩ : BinaryFraction) + unfold coarseGridNatInvocations coarseGridNatWithWork + dsimp only + omega + +def coarseGridAddInvocations (a b : BinaryFraction) : ℕ := + a.numerator.addInvocations b.numerator + canonicalizeInvocations + ⟨(a.numerator.addWithWork b.numerator).1, a.denominator, a.denominator_pos⟩ + 1 + +theorem coarseGridAddInvocations_le_work (a b : BinaryFraction) : + coarseGridAddInvocations a b ≤ (coarseGridAddWithWork a b).2 := by + have ha := SignedBinary.addInvocations_le_work a.numerator b.numerator + have hc := canonicalizeInvocations_le_work + ⟨(a.numerator.addWithWork b.numerator).1, a.denominator, a.denominator_pos⟩ + unfold coarseGridAddInvocations coarseGridAddWithWork + dsimp only + omega + +def coarseDivideInvocations (a divisor : BinaryFraction) : ℕ := + divInvocations a divisor + + fixedDenominatorInvocations (divWithWork a divisor).1 a.denominator a.denominator_pos + 1 + +theorem coarseDivideInvocations_le_work (a divisor : BinaryFraction) : + coarseDivideInvocations a divisor ≤ (coarseDivideWithWork a divisor).2 := by + have hd := divInvocations_le_work a divisor + have hf := fixedDenominatorInvocations_le_work (divWithWork a divisor).1 + a.denominator a.denominator_pos + unfold coarseDivideInvocations coarseDivideWithWork + dsimp only + omega + +def coarseContributionInvocations (threshold scale a : BinaryFraction) : ℕ := + (compareInvocations a threshold + 1) + + (if (leWithWork threshold a).1 then (compareInvocations a scale + 1) + else coarseGridNatInvocations a.denominator a.denominator_pos 0) + 1 + +theorem coarseContributionInvocations_le_work (threshold scale a : BinaryFraction) : + coarseContributionInvocations threshold scale a ≤ (coarseContributionWithWork threshold scale a).2 := by + have ht := compareInvocations_le_work a threshold + have hm := compareInvocations_le_work a scale + have hz := coarseGridNatInvocations_le_work a.denominator a.denominator_pos 0 + unfold coarseContributionInvocations coarseContributionWithWork + dsimp only + split_ifs <;> simp only [leWithWork, maxWithWork] <;> omega + +/-- Includes a conservative allowance for the three literal constructors. -/ +def coarseChildThresholdInvocations (B q : ℕ) (allowance : BinaryFraction) (draw : Fin B) : ℕ := + let numerator := canonicalMulWithWork allowance (nat (draw.val + 1)) + let divisor := canonicalMulWithWork (nat B) (nat q) + canonicalMulInvocations allowance (nat (draw.val + 1)) + + canonicalMulInvocations (nat B) (nat q) + coarseDivideInvocations numerator.1 divisor.1 + + Nat.size (draw.val + 1) + Nat.size B + Nat.size q + 4 + +theorem coarseChildThresholdInvocations_le_work (B q : ℕ) (allowance : BinaryFraction) (draw : Fin B) : + coarseChildThresholdInvocations B q allowance draw ≤ + (coarseChildThresholdWithWork B q allowance draw).2 := by + have hn := canonicalMulInvocations_le_work allowance (nat (draw.val + 1)) + have hd := canonicalMulInvocations_le_work (nat B) (nat q) + have hr := coarseDivideInvocations_le_work + (canonicalMulWithWork allowance (nat (draw.val + 1))).1 + (canonicalMulWithWork (nat B) (nat q)).1 + unfold coarseChildThresholdInvocations coarseChildThresholdWithWork + dsimp only + omega + +def coarseChildAllowanceInvocations (L : ℕ) (threshold : BinaryFraction) : ℕ := + coarseDivideInvocations threshold (nat L) + Nat.size L + 1 + +theorem coarseChildAllowanceInvocations_le_work (L : ℕ) (threshold : BinaryFraction) : + coarseChildAllowanceInvocations L threshold ≤ (coarseChildAllowanceWithWork L threshold).2 := by + have h := coarseDivideInvocations_le_work threshold (nat L) + unfold coarseChildAllowanceInvocations coarseChildAllowanceWithWork + dsimp only + omega + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseSeed.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseSeed.lean new file mode 100644 index 0000000000000000000000000000000000000000..af8253cb0eb0c72bec68386c0ec4b425ad75f4cf --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseSeed.lean @@ -0,0 +1,444 @@ +import OAI.Combinatorics.EditApproximation.Geometry.Connections +import OAI.Combinatorics.EditApproximation.Geometry.AlignmentSplitting +import OAI.Combinatorics.EditApproximation.Geometry.Leaves +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! +# The actual bounded-shift coarse tree + +Section 3's deterministic shift representation uses a complete finite +branching tree with empty/singleton source leaves. Bounded integer shifts +are encoded by `Fin (2k+1)`; code `k` is shift zero. Virtual target positions +are represented by fresh `none` symbols in a finite surrounding frame. +-/ + +namespace EditApproximation + +open Finset EditDistortion + +universe u + + + +namespace CoarseSourceTree + + + +end CoarseSourceTree + +/- Finite virtual frame, wide enough for every permitted shift. -/ + + +/- Node values are the literal finite minima in the manuscript's +recurrence, with every child visited at its actual source start. -/ + + + + +/-- The zero root shift is the middle integer code. -/ + + +def coarseTreeValue {B D : ℕ} {α : Type u} [DecidableEq α] + (tree : CoarseSourceTree B α D) (target : List α) (k : ℕ) : ℕ := + coarseShiftCost k (coarseTargetFrame k target) tree 0 (coarseRootShift k) + +theorem substring_split {α : Type u} (word : List α) (lo mid hi : ℕ) + (hlo : lo ≤ mid) (hhi : mid ≤ hi) : + substring word lo hi = substring word lo mid ++ substring word mid hi := by + have hindex : lo + (mid - lo) = mid := by omega + calc + _ = ((substring word lo hi).take (mid - lo)) ++ + ((substring word lo hi).drop (mid - lo)) := (List.take_append_drop _ _).symm + _ = _ := by + simp only [substring, List.take_drop, List.take_take, List.drop_drop, hindex, + Nat.min_eq_left hhi] + +theorem substring_one {α : Type u} (word : List α) (position : ℕ) : + substring word position (position + 1) = word[position]?.toList := by + rw [substring, ← List.take_drop, List.take_one, List.head?_drop] + +/-- Leaf editing costs are at most the literal mismatch/virtual-position +value, including positions outside the finite frame. -/ +theorem coarse_leaf_edit_le {B : ℕ} {α : Type u} [DecidableEq α] + (k : ℕ) (frame : List (Option α)) (letter : Option α) (start : ℕ) + (shift : Fin (2 * k + 1)) : + edit ((CoarseSourceTree.leaf (B := B) letter).word.map some) + (substring frame (start + shift.val) + (start + shift.val + (CoarseSourceTree.leaf (B := B) letter).word.length)) ≤ + coarseShiftCost k frame (.leaf (B := B) letter) start shift := by + cases letter with + | none => + simp only [CoarseSourceTree.word, Option.toList_none, List.map_nil, List.length_nil, + add_zero, coarseShiftCost, substring, List.drop_take_self] + exact (cost_refl []).le + | some letter => + simp only [CoarseSourceTree.word, Option.toList_some, List.map_cons, List.map_nil, + List.length_cons, List.length_nil, zero_add, coarseShiftCost] + rw [substring_one] + cases hentry : frame[start + shift.val]? with + | none => + simp only [Option.toList_none, Option.getD_none, reduceCtorEq, ↓reduceIte] + exact (edit_le_max_length [some letter] []).trans (by simp) + | some entry => + simp only [Option.toList_some, Option.getD_some] + split_ifs with hequal + · subst entry + exact (cost_refl [some letter]).le + · exact (edit_le_max_length [some letter] [entry]).trans (by simp) + +/-- Moving both endpoints by a shift change costs at most twice the +absolute difference of their bounded integer codes. -/ +theorem coarse_child_shift_edit_le {α : Type u} (frame : List α) (source : List α) + (start shift next : ℕ) : + edit source (substring frame (start + shift) (start + shift + source.length)) ≤ + edit source (substring frame (start + next) (start + next + source.length)) + + 2 * Nat.dist shift next := by + have hmove := edit_substring_endpoints_le frame + (start + next) (start + next + source.length) + (start + shift) (start + shift + source.length) + have hstart : Nat.dist (start + next) (start + shift) = Nat.dist shift next := by + rw [Nat.dist_add_add_left, Nat.dist_comm] + have hfinish : Nat.dist (start + next + source.length) (start + shift + source.length) = + Nat.dist shift next := by rw [Nat.dist_add_add_right, hstart] + rw [hstart, hfinish] at hmove + have htriangle := cost_triangle (s := true) source + (substring frame (start + next) (start + next + source.length)) + (substring frame (start + shift) (start + shift + source.length)) + change edit source (substring frame (start + shift) (start + shift + source.length)) ≤ + edit source (substring frame (start + next) (start + next + source.length)) + + edit (substring frame (start + next) (start + next + source.length)) + (substring frame (start + shift) (start + shift + source.length)) at htriangle + exact htriangle.trans (by omega) + +/-- Actual child editing and endpoint movement give the recurrence's +lower invariant, proved directly on concatenated source strings. -/ +theorem coarseChildrenCost_edit_lower {B D : ℕ} {α : Type u} + (k : ℕ) (frame : List (Option α)) + (value : CoarseSourceTree B α D → ℕ → Fin (2 * k + 1) → ℕ) + (children : List (CoarseSourceTree B α D)) + (hchild : ∀ child ∈ children, ∀ start shift, + edit (child.word.map some) + (substring frame (start + shift.val) (start + shift.val + child.word.length)) ≤ + value child start shift) (start : ℕ) (shift : Fin (2 * k + 1)) : + edit ((children.map CoarseSourceTree.word).flatten.map some) + (substring frame (start + shift.val) + (start + shift.val + (children.map CoarseSourceTree.word).flatten.length)) ≤ + coarseChildrenCost k value children start shift := by + induction children generalizing start with + | nil => + simp only [List.map_nil, List.flatten_nil, List.length_nil, add_zero, substring, + List.drop_take_self, coarseChildrenCost] + exact (cost_refl []).le + | cons child rest ih => + have hfirst : edit (child.word.map some) + (substring frame (start + shift.val) (start + shift.val + child.word.length)) ≤ + univ.inf' univ_nonempty (fun next => value child start next + 2 * Nat.dist shift.val next.val) := by + apply le_inf' + intro next hnext + have hmove := coarse_child_shift_edit_le frame (child.word.map some) start shift.val next.val + simp only [List.length_map] at hmove + exact hmove.trans (Nat.add_le_add_right (hchild child (by simp) start next) _) + have hrest := ih (fun next hnext => hchild next (by simp [hnext])) + (start + child.word.length) + have hsplit := substring_split frame (start + shift.val) + (start + shift.val + child.word.length) + (start + shift.val + (child.word ++ (rest.map CoarseSourceTree.word).flatten).length) + (by omega) (by simp only [List.length_append]; omega) + simp only [List.map_cons, List.flatten_cons, List.map_append, List.length_append, + coarseChildrenCost] + simp only [List.length_append] at hsplit + rw [hsplit] + have happend := cost_append_le (s := true) (child.word.map some) + (substring frame (start + shift.val) (start + shift.val + child.word.length)) + ((rest.map CoarseSourceTree.word).flatten.map some) + (substring frame (start + shift.val + child.word.length) + (start + shift.val + child.word.length + (rest.map CoarseSourceTree.word).flatten.length)) + have hrest' : edit ((rest.map CoarseSourceTree.word).flatten.map some) + (substring frame (start + shift.val + child.word.length) + (start + shift.val + child.word.length + (rest.map CoarseSourceTree.word).flatten.length)) ≤ + coarseChildrenCost k value rest (start + child.word.length) shift := by + simpa only [Nat.add_assoc, Nat.add_comm, Nat.add_left_comm] using hrest + have hresult := happend.trans (Nat.add_le_add hfirst hrest') + change edit _ _ ≤ _ at hresult + simpa only [Nat.add_assoc] using hresult + +/-- The literal bounded-shift tree always dominates edit distance to its +corresponding shifted equal-width target interval. -/ +theorem coarseShiftCost_edit_lower {B D : ℕ} {α : Type u} [DecidableEq α] + (k : ℕ) (frame : List (Option α)) (tree : CoarseSourceTree B α D) + (start : ℕ) (shift : Fin (2 * k + 1)) : + edit (tree.word.map some) + (substring frame (start + shift.val) (start + shift.val + tree.word.length)) ≤ + coarseShiftCost k frame tree start shift := by + induction tree generalizing start shift with + | leaf letter => exact coarse_leaf_edit_le k frame letter start shift + | branch children ih => + simp only [CoarseSourceTree.word, coarseShiftCost] + have hword : (List.ofFn children).map CoarseSourceTree.word = + List.ofFn (fun i => (children i).word) := by + simp only [List.map_ofFn, Function.comp_def] + rw [← hword] + apply coarseChildrenCost_edit_lower k frame + (fun child => coarseShiftCost k frame child) (List.ofFn children) + intro child hchild start shift + obtain ⟨i, rfl⟩ := List.mem_ofFn.mp hchild + exact ih i start shift + +/-- The central equal-width target interval excludes all virtual symbols. -/ +theorem coarseTargetFrame_center {α : Type u} (k : ℕ) (target : List α) : + substring (coarseTargetFrame k target) k (k + target.length) = target.map some := by + have hprefix : (List.replicate k (none : Option α) ++ target.map some).length = k + target.length := by simp + rw [substring, coarseTargetFrame, ← hprefix, List.take_append_length] + simpa only [List.length_replicate] using + (List.drop_append_length (l₁ := List.replicate k (none : Option α)) (l₂ := target.map some)) + +/-- First deterministic shift-tree distortion inequality, for the actual +unrestricted unit-cost edit distance and actual finite recurrence. -/ +theorem coarseTreeValue_edit_lower {B D : ℕ} {α : Type u} [DecidableEq α] [Inhabited α] + (tree : CoarseSourceTree B α D) (target : List α) (k : ℕ) + (hlength : tree.word.length = target.length) : + edit tree.word target ≤ coarseTreeValue tree target k := by + have h := coarseShiftCost_edit_lower k (coarseTargetFrame k target) tree 0 (coarseRootShift k) + simp only [coarseRootShift, zero_add, hlength, coarseTargetFrame_center] at h + have hmap := cost_map_eq_of_leftInverse (s := true) some + (fun entry : Option α => entry.getD default) (by intro letter; rfl) tree.word target + change edit (tree.word.map some) (target.map some) = edit tree.word target at hmap + rw [hmap] at h + exact h + +theorem coarseChildrenCost_le_width {B D : ℕ} {α : Type u} (k : ℕ) + (value : CoarseSourceTree B α D → ℕ → Fin (2 * k + 1) → ℕ) + (children : List (CoarseSourceTree B α D)) + (hchild : ∀ child ∈ children, ∀ start shift, value child start shift ≤ child.word.length) + (start : ℕ) (shift : Fin (2 * k + 1)) : + coarseChildrenCost k value children start shift ≤ (children.map CoarseSourceTree.word).flatten.length := by + induction children generalizing start with + | nil => simp [coarseChildrenCost] + | cons child rest ih => + have hmin := inf'_le (fun next => value child start next + 2 * Nat.dist shift.val next.val) + (mem_univ shift) + simp only [Nat.dist_self, mul_zero, add_zero] at hmin + have hfirst := hchild child (by simp) start shift + have hrest := ih (fun next hnext => hchild next (by simp [hnext])) + (start + child.word.length) + simp only [coarseChildrenCost, List.map_cons, List.flatten_cons, List.length_append] + omega + +/-- Constant shifts give the exact node-width bound used by pruning. -/ +theorem coarseShiftCost_le_width {B D : ℕ} {α : Type u} [DecidableEq α] + (k : ℕ) (frame : List (Option α)) (tree : CoarseSourceTree B α D) + (start : ℕ) (shift : Fin (2 * k + 1)) : + coarseShiftCost k frame tree start shift ≤ tree.word.length := by + induction tree generalizing start shift with + | leaf letter => + cases letter with + | none => simp [coarseShiftCost, CoarseSourceTree.word] + | some letter => + simp only [coarseShiftCost, CoarseSourceTree.word, Option.toList_some, + List.length_cons, List.length_nil] + split_ifs <;> omega + | branch children ih => + simp only [CoarseSourceTree.word, coarseShiftCost] + have hword : (List.ofFn children).map CoarseSourceTree.word = + List.ofFn (fun i => (children i).word) := by + simp only [List.map_ofFn, Function.comp_def] + rw [← hword] + apply coarseChildrenCost_le_width k (fun child => coarseShiftCost k frame child) (List.ofFn children) + intro child hchild start shift + obtain ⟨i, rfl⟩ := List.mem_ofFn.mp hchild + exact ih i start shift + +/-- The literal consecutive capacity chunks cover exactly the permitted +before; zero capacity and empty trailing chunks are included. -/ +theorem coarse_capacity_chunks {α : Type u} (source : List α) (B capacity : ℕ) : + (List.ofFn fun i : Fin B => (source.drop (i.val * capacity)).take capacity).flatten = + source.take (B * capacity) := by + induction B generalizing source with + | zero => simp + | succ B ih => + rw [List.ofFn_succ, List.flatten_cons] + simp only [Fin.val_zero, zero_mul, List.drop_zero, Fin.val_succ] + have hchunks : (List.ofFn fun i : Fin B => + (source.drop ((i.val + 1) * capacity)).take capacity) = + List.ofFn (fun i : Fin B => ((source.drop capacity).drop (i.val * capacity)).take capacity) := by + congr 1 + funext i + simp only [List.drop_drop, Nat.add_mul, one_mul, Nat.add_comm] + rw [hchunks, ih, ← List.take_add] + simp only [Nat.succ_mul, Nat.add_comm] + +/-- A concrete complete source tree with empty/singleton leaves. Its +recursive child chunks have the capacity prescribed by the remaining depth. -/ + + +theorem coarseSourceTreeOfList_word {α : Type u} (B D : ℕ) (source : List α) : + (coarseSourceTreeOfList B D source).word = source.take (B ^ D) := by + induction D generalizing source with + | zero => simp only [coarseSourceTreeOfList, CoarseSourceTree.word, pow_zero, List.take_one] + | succ D ih => + simp only [coarseSourceTreeOfList, CoarseSourceTree.word, ih, List.take_take, min_self] + rw [coarse_capacity_chunks, pow_succ, Nat.mul_comm] + +theorem coarseSourceTreeOfList_word_eq {α : Type u} (B D : ℕ) (source : List α) + (hcapacity : source.length ≤ B ^ D) : + (coarseSourceTreeOfList B D source).word = source := by + rw [coarseSourceTreeOfList_word, List.take_of_length_le hcapacity] + +/-- A real target character is present at its framed before index. -/ +theorem coarseTargetFrame_prefix_get {α : Type u} (k : ℕ) + (before suffix : List α) (letter : α) : + (coarseTargetFrame k (before ++ letter :: suffix))[k + before.length]?.getD none = some letter := by + rw [coarseTargetFrame, List.getElem?_append_left (by simp)] + rw [List.getElem?_append_right (by simp)] + simp only [List.length_replicate, Nat.add_sub_cancel_left, List.getElem?_map] + rw [List.getElem?_append_right (by omega)] + simp + +/-- Advancing an actual alignment cut gives a legal bounded shift. The +only budget is its preceding displacement plus its remaining edit cost. -/ +theorem coarse_anchor_advance (k start before : ℕ) (shift : Fin (2 * k + 1)) + (sourceWidth targetWidth cutCost remaining : ℕ) + (hanchor : start + shift.val = k + before) + (hbudget : Nat.dist start before + (cutCost + remaining) ≤ k) + (hsource : sourceWidth ≤ targetWidth + cutCost) + (htarget : targetWidth ≤ sourceWidth + cutCost) : + ∃ next : Fin (2 * k + 1), + start + sourceWidth + next.val = k + (before + targetWidth) ∧ + Nat.dist shift.val next.val ≤ cutCost ∧ + Nat.dist (start + sourceWidth) (before + targetWidth) + remaining ≤ k := by + let code := k + (before + targetWidth) - (start + sourceWidth) + have hcode : code < 2 * k + 1 := by + dsimp [code] + simp only [Nat.dist] at hbudget + omega + refine ⟨⟨code, hcode⟩, ?_, ?_, ?_⟩ + all_goals + simp only [Nat.dist, code] at * + omega + +/-- Exact first-child alignment cost controls every actual shift-tree +leaf; no leaf correspondence oracle is assumed. -/ +theorem coarse_leaf_edit_upper {B : ℕ} {α : Type u} [DecidableEq α] + (k : ℕ) (target before piece suffix : List α) (letter : Option α) + (start : ℕ) (shift : Fin (2 * k + 1)) + (htarget : target = before ++ piece ++ suffix) + (hanchor : start + shift.val = k + before.length) : + coarseShiftCost k (coarseTargetFrame k target) (.leaf (B := B) letter) start shift ≤ + edit (CoarseSourceTree.leaf (B := B) letter).word piece := by + cases letter with + | none => simp only [coarseShiftCost]; exact Nat.zero_le _ + | some letter => + by_cases hzero : edit [letter] piece = 0 + · have heq : [letter] = piece := (cost_eq_zero_iff (s := true)).mp hzero + rw [← heq] at htarget + subst target + simp only [List.append_assoc, List.singleton_append, coarseShiftCost, hanchor, + coarseTargetFrame_prefix_get, ↓reduceIte] + exact Nat.zero_le _ + · have hpositive : 1 ≤ edit [letter] piece := by omega + simp only [coarseShiftCost, CoarseSourceTree.word, Option.toList_some] + split_ifs <;> omega + +/-- Recursive actual optimal cuts bound child minima. The explicit +before allowance accounts for the displacement from the parent's shift. -/ +theorem coarseChildrenCost_edit_upper {B D : ℕ} {α : Type u} + (k : ℕ) (target : List α) (C : ℕ) + (value : CoarseSourceTree B α D → ℕ → Fin (2 * k + 1) → ℕ) + (children : List (CoarseSourceTree B α D)) + (hchild : ∀ child ∈ children, ∀ (before piece suffix : List α) start shift, + target = before ++ piece ++ suffix → + start + shift.val = k + before.length → + Nat.dist start before.length + edit child.word piece ≤ k → + value child start shift ≤ C * edit child.word piece) + (before piece suffix : List α) (start : ℕ) + (parent anchor : Fin (2 * k + 1)) (allowance : ℕ) + (htarget : target = before ++ piece ++ suffix) + (hanchor : start + anchor.val = k + before.length) + (hbudget : Nat.dist start before.length + + edit (children.map CoarseSourceTree.word).flatten piece ≤ k) + (hallowance : Nat.dist parent.val anchor.val ≤ allowance) : + coarseChildrenCost k value children start parent ≤ + C * edit (children.map CoarseSourceTree.word).flatten piece + + 2 * children.length * (allowance + edit (children.map CoarseSourceTree.word).flatten piece) := by + induction children generalizing before piece suffix start anchor allowance with + | nil => simp only [coarseChildrenCost, List.length_nil, mul_zero, zero_mul, add_zero]; exact Nat.zero_le _ + | cons child rest ih => + obtain ⟨left, right, hlocal, hsplit⟩ := edit_append_split child.word + (rest.map CoarseSourceTree.word).flatten piece + have hsplit' : edit ((child :: rest).map CoarseSourceTree.word).flatten piece = + edit child.word left + edit (rest.map CoarseSourceTree.word).flatten right := by + simpa only [List.map_cons, List.flatten_cons] using hsplit + have hfirst := hchild child (by simp) before left (right ++ suffix) start anchor + (by simpa only [hlocal, List.append_assoc] using htarget) hanchor + (by rw [hsplit'] at hbudget; omega) + obtain ⟨hsource, htargetWidth⟩ := cost_length_bounds (s := true) child.word left + change child.word.length ≤ left.length + edit child.word left at hsource + change left.length ≤ child.word.length + edit child.word left at htargetWidth + obtain ⟨next, hnext, hmove, hremaining⟩ := coarse_anchor_advance k start before.length anchor + child.word.length left.length (edit child.word left) + (edit (rest.map CoarseSourceTree.word).flatten right) hanchor + (by simpa only [hsplit'] using hbudget) hsource htargetWidth + have hnextAllowance : Nat.dist parent.val next.val ≤ allowance + edit child.word left := + (Nat.dist.triangle_inequality parent.val anchor.val next.val).trans + (Nat.add_le_add hallowance hmove) + have hrest := ih (fun next hnext => hchild next (by simp [hnext])) + (before ++ left) right suffix (start + child.word.length) next + (allowance + edit child.word left) + (by simpa only [hlocal, List.append_assoc] using htarget) + (by simpa only [List.length_append] using hnext) + (by simpa only [List.length_append] using hremaining) hnextAllowance + have hminimum := inf'_le (fun next => value child start next + 2 * Nat.dist parent.val next.val) + (mem_univ anchor) + have hfirstBound : univ.inf' univ_nonempty + (fun next => value child start next + 2 * Nat.dist parent.val next.val) ≤ + C * edit child.word left + 2 * allowance := + hminimum.trans (Nat.add_le_add hfirst (Nat.mul_le_mul_left 2 hallowance)) + simp only [coarseChildrenCost, List.length_cons, hsplit'] + have hsum := Nat.add_le_add hfirstBound hrest + nlinarith + +/-- The actual bounded-shift recurrence is at most the manuscript's +linear-in-depth distortion, using optimal unrestricted edit scripts. -/ +theorem coarseShiftCost_edit_upper {B D : ℕ} {α : Type u} [DecidableEq α] + (k : ℕ) (target : List α) (tree : CoarseSourceTree B α D) + (before piece suffix : List α) (start : ℕ) (shift : Fin (2 * k + 1)) + (htarget : target = before ++ piece ++ suffix) + (hanchor : start + shift.val = k + before.length) + (hbudget : Nat.dist start before.length + edit tree.word piece ≤ k) : + coarseShiftCost k (coarseTargetFrame k target) tree start shift ≤ + (1 + 2 * B * D) * edit tree.word piece := by + induction tree generalizing before piece suffix start shift with + | leaf letter => + simpa only [mul_zero, add_zero, one_mul] using + coarse_leaf_edit_upper k target before piece suffix letter start shift htarget hanchor + | @branch D children ih => + have hword : (List.ofFn children).map CoarseSourceTree.word = + List.ofFn (fun i => (children i).word) := by + simp only [List.map_ofFn, Function.comp_def] + have hbound := coarseChildrenCost_edit_upper k target (1 + 2 * B * D) + (fun child => coarseShiftCost k (coarseTargetFrame k target) child) (List.ofFn children) + (by + intro child hchild before piece suffix start shift htarget hanchor hbudget + obtain ⟨i, rfl⟩ := List.mem_ofFn.mp hchild + exact ih i before piece suffix start shift htarget hanchor hbudget) + before piece suffix start shift shift 0 htarget hanchor + (by simpa only [hword, CoarseSourceTree.word] using hbudget) (by simp) + simp only [CoarseSourceTree.word, coarseShiftCost, hword, List.length_ofFn, + zero_add] at hbound ⊢ + nlinarith + +/-- Section 3's second deterministic distortion inequality for the +executable finite coarse tree, conditional only on the guessed distance. -/ +theorem coarseTreeValue_edit_upper {B D : ℕ} {α : Type u} [DecidableEq α] + (tree : CoarseSourceTree B α D) (target : List α) (k : ℕ) + (hguess : edit tree.word target ≤ k) : + coarseTreeValue tree target k ≤ (1 + 2 * B * D) * edit tree.word target := by + exact coarseShiftCost_edit_upper k target tree [] target [] 0 (coarseRootShift k) + (by simp) (by simp [coarseRootShift]) (by simpa using hguess) + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseSliceCopy.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseSliceCopy.lean new file mode 100644 index 0000000000000000000000000000000000000000..1a34c1e1d9508337721a1f2d731fb4f07118e517 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseSliceCopy.lean @@ -0,0 +1,36 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseRangeCopy +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalLeaves + +namespace OAI + +namespace EditApproximation + +theorem coarseRangeCopyWithWork_slice (input : List ℕ) (lo hi : ℕ) + (hlo : lo ≤ hi) (hhi : hi ≤ input.length) : + (coarseRangeCopyWithWork (fun i => input[i]?.getD 0) lo (hi - lo)).1 = substring input lo hi := by + rw [coarseRangeCopyWithWork_value] + apply List.ext_getElem + · simp only [List.length_ofFn, substring, List.length_take, List.length_drop] + rw [min_eq_left hhi] + · intro i hi1 hi2 + have hil : i < hi - lo := by simpa only [List.length_ofFn] using hi1 + have hip : lo + i < input.length := by omega + simp only [List.getElem_ofFn, substring, List.getElem_take, List.getElem_drop, + List.getElem?_eq_getElem hip, Option.getD_some] + +theorem coarseRangeCopyWithWork_input_cost (input : List ℕ) (lo hi A S : ℕ) + (hlo : lo ≤ hi) (hhi : hi ≤ input.length) (haddress : Nat.size input.length ≤ A) + (hsymbol : ∀ a ∈ input, Nat.size a ≤ S) : + (coarseRangeCopyWithWork (fun i => input[i]?.getD 0) lo (hi - lo)).2 ≤ + (hi - lo + 1) * (40 * (A + 1) + S) := by + apply coarseRangeCopyWithWork_cost _ input.length A S + · intro i hi + exact (Nat.size_le_size hi).trans haddress + · intro i hi + simp only [List.getElem?_eq_getElem hi, Option.getD_some] + exact hsymbol _ (List.getElem_mem hi) + · omega + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseThresholdArithmetic.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseThresholdArithmetic.lean new file mode 100644 index 0000000000000000000000000000000000000000..7ae463b5073284b21797efddd3fd9712aa1ffe53 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseThresholdArithmetic.lean @@ -0,0 +1,88 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseGridArithmetic +import OAI.Combinatorics.EditApproximation.Binary.BinaryAffineGuard +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Boolean threshold arithmetic on the fixed denominator of one coarse +execution. Quotients use actual long division when compressed to that grid. -/ + +namespace EditApproximation +namespace BinaryFraction + + + + theorem coarseDivideWithWork_value (a divisor : BinaryFraction) + (hden : (a.value / divisor.value).den ∣ bitWordValue a.denominator) : + (coarseDivideWithWork a divisor).1.value = a.value / divisor.value := by + unfold coarseDivideWithWork + dsimp only + rw [fixedDenominatorWithWork_value, divWithWork_value] + simpa only [divWithWork_value] using hden + + theorem coarseDivideWithWork_den (a divisor : BinaryFraction) : + (coarseDivideWithWork a divisor).1.representation.den = a.representation.den := by + exact fixedDenominatorWithWork_den _ _ _ + + theorem coarseDivideWithWork_cost (a divisor : BinaryFraction) (B : ℕ) + (ha : a.width ≤ B) (hd : divisor.width ≤ B) : + (coarseDivideWithWork a divisor).2 ≤ 1000000 * (B + 1) ^ 2 := by + have hq := divWithWork_cost a divisor B ha hd + have hqw := divWithWork_width_uniform a divisor B ha hd + have had : a.denominator.length ≤ B := (le_max_right _ _).trans ha + have hc := fixedDenominatorWithWork_cost (divWithWork a divisor).1 a.denominator + a.denominator_pos (4 * B + 4) B hqw had + change (divWithWork a divisor).2 + _ + 2 ≤ _ + nlinarith only [hq, hc, Nat.zero_le B] + + theorem coarseDivideWithWork_width (a divisor : BinaryFraction) (V B : ℕ) + (hden : (a.value / divisor.value).den ∣ bitWordValue a.denominator) + (hv : |a.value / divisor.value| ≤ V) (hb : a.denominator.length ≤ B) : + (coarseDivideWithWork a divisor).1.width ≤ Nat.size V + 2 * B + 1 := by + exact fixedDenominatorWithWork_width (divWithWork a divisor).1 a.denominator + a.denominator_pos (by simpa only [divWithWork_value] using hden) V B + (by simpa only [divWithWork_value] using hv) hb + +/-- The exact branch and maximum used for each transformed child cell. -/ + + + theorem coarseContributionWithWork_value (threshold scale a : BinaryFraction) : + (coarseContributionWithWork threshold scale a).1.value = + coarseThresholdContribution threshold.value scale.value a.value := by + by_cases h : threshold.value ≤ a.value + · simp only [coarseContributionWithWork, (leWithWork_value _ _).mpr h, ite_true, + maxWithWork_value, coarseThresholdContribution, h] + · have ht : (leWithWork threshold a).1 = false := + Bool.eq_false_iff.mpr (fun hh => h ((leWithWork_value _ _).mp hh)) + simp only [coarseContributionWithWork, ht, Bool.false_eq_true, ite_false, + coarseGridNatWithWork_value, Nat.cast_zero, coarseThresholdContribution, h] + + theorem coarseContributionWithWork_den (threshold scale a : BinaryFraction) + (hden : scale.representation.den = a.representation.den) : + (coarseContributionWithWork threshold scale a).1.representation.den = a.representation.den := by + unfold coarseContributionWithWork + dsimp only + split_ifs + · unfold maxWithWork + dsimp only + split_ifs + · exact hden + · rfl + · exact coarseGridNatWithWork_den _ _ _ + + theorem coarseContributionWithWork_cost (threshold scale a : BinaryFraction) (B : ℕ) + (ht : threshold.width ≤ B) (hs : scale.width ≤ B) (ha : a.width ≤ B) : + (coarseContributionWithWork threshold scale a).2 ≤ 2200 * (B + 1) ^ 2 := by + have htest := leWithWork_cost threshold a B ht ha + have hmax := maxWithWork_cost a scale B ha hs + have hzero := coarseGridNatWithWork_cost a.denominator a.denominator_pos 0 B + (by simp) ((le_max_right _ _).trans ha) + unfold coarseContributionWithWork + dsimp only + split_ifs <;> nlinarith only [htest, hmax, hzero, Nat.zero_le B] + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseThresholdStep.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseThresholdStep.lean new file mode 100644 index 0000000000000000000000000000000000000000..fd22d6cac728ba8a873efbb759601f6df38ee7bc --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseThresholdStep.lean @@ -0,0 +1,60 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseThresholdArithmetic +import OAI.Combinatorics.EditApproximation.Coarse.CoarseGridInvariant +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation +namespace BinaryFraction + +/-- Literal threshold numerator multiplication and denominator division. +The fixed-denominator quotient retains a root's common array grid. -/ + + +private theorem coarseMultiply_nat_den (a : BinaryFraction) (n : ℕ) : + (canonicalMulWithWork a (nat n)).1.representation.den = a.representation.den := by + rw [canonicalMulWithWork_representation, nat_representation] + simp only [UnreducedRational.mul, UnreducedRational.nat, mul_one] + + theorem coarseChildThresholdWithWork_value (B q : ℕ) (allowance : BinaryFraction) (draw : Fin B) + (hgrid : (coarseChildThreshold B q allowance.value draw).den ∣ allowance.representation.den) : + (coarseChildThresholdWithWork B q allowance draw).1.value = + coarseChildThreshold B q allowance.value draw := by + unfold coarseChildThresholdWithWork + dsimp only + rw [coarseDivideWithWork_value] + · simp only [canonicalMulWithWork_value, nat_value, coarseChildThreshold, Nat.cast_add, + Nat.cast_one] + · change Rat.den ((canonicalMulWithWork allowance (nat (draw.val + 1))).1.value / + (canonicalMulWithWork (nat B) (nat q)).1.value) ∣ + (canonicalMulWithWork allowance (nat (draw.val + 1))).1.representation.den + rw [coarseMultiply_nat_den] + simpa only [canonicalMulWithWork_value, nat_value, + coarseChildThreshold, Nat.cast_add, Nat.cast_one] using hgrid + + theorem coarseChildThresholdWithWork_den (B q : ℕ) (allowance : BinaryFraction) (draw : Fin B) : + (coarseChildThresholdWithWork B q allowance draw).1.representation.den = allowance.representation.den := by + exact (coarseDivideWithWork_den _ _).trans (coarseMultiply_nat_den allowance _) + +/-- Local allowance division uses the same Boolean division and +compression primitive as threshold construction. -/ + + + theorem coarseChildAllowanceWithWork_value (L : ℕ) (threshold : BinaryFraction) + (hgrid : (threshold.value / L).den ∣ threshold.representation.den) : + (coarseChildAllowanceWithWork L threshold).1.value = threshold.value / L := by + have hd : (threshold.value / (nat L).value).den ∣ bitWordValue threshold.denominator := by + change (threshold.value / (nat L).value).den ∣ threshold.representation.den + simpa only [nat_value] using hgrid + simpa only [coarseChildAllowanceWithWork, nat_value] using + coarseDivideWithWork_value threshold (nat L) hd + + theorem coarseChildAllowanceWithWork_den (L : ℕ) (threshold : BinaryFraction) : + (coarseChildAllowanceWithWork L threshold).1.representation.den = threshold.representation.den := + coarseDivideWithWork_den _ _ + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseThresholdStepWork.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseThresholdStepWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..c7e330072fbc1f0d38437ada79fab204ad6439d1 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseThresholdStepWork.lean @@ -0,0 +1,42 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseThresholdStep + +namespace OAI + +namespace EditApproximation +namespace BinaryFraction + + theorem coarseChildThresholdWithWork_cost (B q A : ℕ) (allowance : BinaryFraction) + (draw : Fin B) (ha : allowance.width ≤ A) + (hB : Nat.size B + 2 ≤ A) (hq : Nat.size q + 2 ≤ A) : + (coarseChildThresholdWithWork B q allowance draw).2 ≤ + 30000000 * (A + 1) ^ 2 := by + have hdraw : Nat.size (draw.val + 1) + 2 ≤ A := + (Nat.add_le_add_right (Nat.size_le_size (show draw.val + 1 ≤ B by omega)) 2).trans hB + have hn := (nat_width_le (draw.val + 1)).trans hdraw + have hb := (nat_width_le B).trans hB + have hq' := (nat_width_le q).trans hq + have hnc := canonicalMulWithWork_cost allowance (nat (draw.val + 1)) A ha hn + have hdc := canonicalMulWithWork_cost (nat B) (nat q) A hb hq' + have hnw := canonicalMulWithWork_width allowance (nat (draw.val + 1)) A ha hn + have hdw := canonicalMulWithWork_width (nat B) (nat q) A hb hq' + have hc := coarseDivideWithWork_cost + (canonicalMulWithWork allowance (nat (draw.val + 1))).1 + (canonicalMulWithWork (nat B) (nat q)).1 (4 * A + 2) hnw hdw + change (canonicalMulWithWork allowance (nat (draw.val + 1))).2 + + (canonicalMulWithWork (nat B) (nat q)).2 + + (coarseDivideWithWork (canonicalMulWithWork allowance (nat (draw.val + 1))).1 + (canonicalMulWithWork (nat B) (nat q)).1).2 + + Nat.size (draw.val + 1) + Nat.size B + Nat.size q + 4 ≤ _ + nlinarith only [hnc, hdc, hc, hdraw, hB, hq, Nat.zero_le A] + + theorem coarseChildAllowanceWithWork_cost (L A : ℕ) (threshold : BinaryFraction) + (ha : threshold.width ≤ A) (hL : Nat.size L + 2 ≤ A) : + (coarseChildAllowanceWithWork L threshold).2 ≤ 1000002 * (A + 1) ^ 2 := by + have hc := coarseDivideWithWork_cost threshold (nat L) A ha ((nat_width_le L).trans hL) + change (coarseDivideWithWork threshold (nat L)).2 + Nat.size L + 1 ≤ _ + nlinarith only [hc, hL, Nat.zero_le A] + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseTransforms.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseTransforms.lean new file mode 100644 index 0000000000000000000000000000000000000000..b9febed1f6840f7d142389cc38e5b525f638a0d9 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseTransforms.lean @@ -0,0 +1,242 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseEstimator + +namespace OAI + +/-! +# Linear sweeps for the coarse penalty transform + +The finite minima define the semantic arrays. These sweeps compute them +with one rational addition and one comparison per scan transition. +-/ + +namespace EditApproximation + +open Finset + +def coarsePrefixMinimum (value : ℕ → ℚ) : ℕ → ℚ + | 0 => value 0 + | v + 1 => min (value (v + 1)) (coarsePrefixMinimum value v + 2) + +theorem coarsePrefixMinimum_le (value : ℕ → ℚ) (v u : ℕ) (hu : u ≤ v) : + coarsePrefixMinimum value v ≤ value u + 2 * (v - u : ℕ) := by + induction v with + | zero => + have hu0 : u = 0 := by omega + subst u + simp [coarsePrefixMinimum] + | succ v ih => + by_cases hequal : u = v + 1 + · subst u + simpa only [coarsePrefixMinimum, Nat.sub_self, Nat.cast_zero, mul_zero, add_zero] using + (min_le_left (value (v + 1)) (coarsePrefixMinimum value v + 2)) + · have hule : u ≤ v := by omega + have hdiff : v + 1 - u = (v - u) + 1 := by omega + calc + _ ≤ coarsePrefixMinimum value v + 2 := min_le_right _ _ + _ ≤ value u + 2 * (v - u : ℕ) + 2 := by linarith [ih hule] + _ = _ := by rw [hdiff]; push_cast; ring + +theorem coarsePrefixMinimum_attained (value : ℕ → ℚ) (v : ℕ) : + ∃ u ≤ v, coarsePrefixMinimum value v = value u + 2 * (v - u : ℕ) := by + induction v with + | zero => exact ⟨0, le_rfl, by simp [coarsePrefixMinimum]⟩ + | succ v ih => + by_cases hnew : value (v + 1) ≤ coarsePrefixMinimum value v + 2 + · exact ⟨v + 1, le_rfl, by simp only [coarsePrefixMinimum, min_eq_left hnew, + Nat.sub_self, Nat.cast_zero, mul_zero, add_zero]⟩ + · obtain ⟨u, hu, hequal⟩ := ih + refine ⟨u, by omega, ?_⟩ + rw [coarsePrefixMinimum, min_eq_right (le_of_not_ge hnew), hequal] + have hdiff : v + 1 - u = (v - u) + 1 := by omega + rw [hdiff] + push_cast + ring + +/-- The executable left sweep; Lean's `scanl` traverses its input once. -/ +def coarseLeftSweep : List ℚ → List ℚ + | [] => [] + | first :: rest => rest.scanl (fun previous value => min value (previous + 2)) first + +theorem coarseLeftSweep_length (source : List ℚ) : + (coarseLeftSweep source).length = source.length := by + cases source <;> simp only [coarseLeftSweep, List.length_nil, List.length_cons, List.length_scanl] + +theorem coarseLeftSweep_getElem (source : List ℚ) (v : ℕ) (hv : v < source.length) : + (coarseLeftSweep source)[v]'(by rw [coarseLeftSweep_length]; exact hv) = + coarsePrefixMinimum (fun i => source[i]?.getD 0) v := by + cases source with + | nil => simp at hv + | cons first rest => + induction v with + | zero => simp only [coarseLeftSweep, List.getElem_scanl_zero, coarsePrefixMinimum, + List.getElem?_cons_zero, Option.getD_some] + | succ v ih => + simp only [coarseLeftSweep] + rw [List.getElem_succ_scanl] + rw [coarsePrefixMinimum] + have hvprev : v < (first :: rest).length := by simp only [List.length_cons] at hv ⊢; omega + have hprevious := ih hvprev + simp only [coarseLeftSweep] at hprevious + rw [hprevious] + have hrestIndex : v < rest.length := by simp only [List.length_cons] at hv; omega + simp only [List.getElem?_cons_succ] + rw [List.getElem?_eq_getElem hrestIndex, Option.getD_some] + +/-- A costed scan records the addition and comparison actually performed +at each transition; list traversal is charged separately by the RAM model. -/ +def coarseCostedScan (previous : ℚ) : List ℚ → List ℚ × ℕ + | [] => ([previous], 0) + | value :: rest => + let next := min value (previous + 2) + let result := coarseCostedScan next rest + (previous :: result.1, result.2 + 2) + +theorem coarseCostedScan_result (previous : ℚ) (source : List ℚ) : + (coarseCostedScan previous source).1 = + source.scanl (fun previous value => min value (previous + 2)) previous ∧ + (coarseCostedScan previous source).2 = 2 * source.length := by + induction source generalizing previous with + | nil => simp [coarseCostedScan] + | cons value rest ih => + have hnext := ih (min value (previous + 2)) + simp only [coarseCostedScan, List.scanl_cons, List.length_cons, hnext.1, hnext.2] + exact ⟨trivial, by omega⟩ + +def coarseArrayLookup {n : ℕ} (value : Fin n → ℚ) (i : ℕ) : ℚ := + if h : i < n then value ⟨i, h⟩ else 0 + +def coarseReverseLookup {n : ℕ} (value : Fin n → ℚ) (i : ℕ) : ℚ := + if h : i < n then value ⟨n - 1 - i, by omega⟩ else 0 + +/-- Two one-sided recurrences equal the complete literal penalty minimum. -/ +theorem coarse_two_prefix_minimum {n : ℕ} [NeZero n] (value : Fin n → ℚ) (v : Fin n) : + min (coarsePrefixMinimum (coarseArrayLookup value) v.val) + (coarsePrefixMinimum (coarseReverseLookup value) (n - 1 - v.val)) = + univ.inf' univ_nonempty (fun u => value u + (2 * Nat.dist v.val u.val : ℕ)) := by + apply le_antisymm + · apply le_inf' + intro u hu + by_cases hleft : u.val ≤ v.val + · have hprefix := coarsePrefixMinimum_le (coarseArrayLookup value) v.val u.val hleft + have hdistance := Nat.dist_eq_sub_of_le_right hleft + apply (min_le_left _ _).trans + simpa only [coarseArrayLookup, dite_eq_left u.isLt, Nat.cast_mul, Nat.cast_ofNat, + hdistance] using hprefix + · have hright : v.val ≤ u.val := by omega + have hindex : n - 1 - u.val ≤ n - 1 - v.val := by omega + have hun : n - 1 - u.val < n := by have := u.isLt; omega + have hprefix := coarsePrefixMinimum_le (coarseReverseLookup value) + (n - 1 - v.val) (n - 1 - u.val) hindex + have hdouble : (⟨n - 1 - (n - 1 - u.val), by omega⟩ : Fin n) = u := by + apply Fin.ext + change n - 1 - (n - 1 - u.val) = u.val + have := u.isLt + omega + have hgap : n - 1 - v.val - (n - 1 - u.val) = u.val - v.val := by + have := u.isLt + have := v.isLt + omega + apply (min_le_right _ _).trans + simpa only [coarseReverseLookup, dite_eq_left hun, hdouble, hgap, + Nat.dist_eq_sub_of_le hright, Nat.cast_mul, Nat.cast_ofNat] using hprefix + · apply le_min + · obtain ⟨u, hu, hequal⟩ := coarsePrefixMinimum_attained (coarseArrayLookup value) v.val + have hun : u < n := lt_of_le_of_lt hu v.isLt + have hminimum := inf'_le (fun u => value u + (2 * Nat.dist v.val u.val : ℕ)) + (mem_univ (⟨u, hun⟩ : Fin n)) + rw [hequal] + simpa only [coarseArrayLookup, dite_eq_left hun, Nat.dist_eq_sub_of_le_right hu, + Nat.cast_mul, Nat.cast_ofNat] using hminimum + · obtain ⟨u, hu, hequal⟩ := coarsePrefixMinimum_attained + (coarseReverseLookup value) (n - 1 - v.val) + have hun : u < n := by have := v.isLt; omega + let next : Fin n := ⟨n - 1 - u, by omega⟩ + have hright : v.val ≤ next.val := by dsimp [next]; have := v.isLt; omega + have hgap : n - 1 - v.val - u = next.val - v.val := by + dsimp [next] + have := v.isLt + omega + have hminimum := inf'_le (fun u => value u + (2 * Nat.dist v.val u.val : ℕ)) (mem_univ next) + rw [hequal] + simpa only [coarseReverseLookup, dite_eq_left hun, Nat.dist_eq_sub_of_le hright, + hgap, Nat.cast_mul, Nat.cast_ofNat] using hminimum + +/-- Literal array output of the two linear sweeps. -/ +def coarsePenaltyTransform (source : List ℚ) : List ℚ := + List.zipWith min (coarseLeftSweep source) (coarseLeftSweep source.reverse).reverse + +theorem coarsePenaltyTransform_length (source : List ℚ) : + (coarsePenaltyTransform source).length = source.length := by + simp only [coarsePenaltyTransform, List.length_zipWith, List.length_reverse, + coarseLeftSweep_length, min_self] + +theorem coarseArrayLookup_list (source : List ℚ) : + coarseArrayLookup (fun i : Fin source.length => source[i.val]) = + fun i => source[i]?.getD 0 := by + funext i + by_cases hi : i < source.length + · simp only [coarseArrayLookup, dite_eq_left hi, List.getElem?_eq_getElem hi, Option.getD_some] + · have hge : source.length ≤ i := by omega + simp only [coarseArrayLookup, dite_eq_right hi, List.getElem?_eq_none hge, Option.getD_none] + +theorem coarseReverseLookup_list (source : List ℚ) : + coarseReverseLookup (fun i : Fin source.length => source[i.val]) = + fun i => source.reverse[i]?.getD 0 := by + funext i + by_cases hi : i < source.length + · have hir : i < source.reverse.length := by simpa only [List.length_reverse] using hi + simp only [coarseReverseLookup, dite_eq_left hi, List.getElem?_eq_getElem hir, + Option.getD_some, List.getElem_reverse] + · have hir : source.reverse.length ≤ i := by simp only [List.length_reverse]; omega + simp only [coarseReverseLookup, dite_eq_right hi, List.getElem?_eq_none hir, Option.getD_none] + +/-- Every returned array cell equals the complete finite semantic minimum. -/ +theorem coarsePenaltyTransform_getElem (source : List ℚ) [NeZero source.length] + (v : Fin source.length) : + (coarsePenaltyTransform source)[v.val]'(by rw [coarsePenaltyTransform_length]; exact v.isLt) = + univ.inf' univ_nonempty (fun u : Fin source.length => + source[u.val] + (2 * Nat.dist v.val u.val : ℕ)) := by + have hreverse : source.length - 1 - v.val < source.reverse.length := by + simp only [List.length_reverse] + have := v.isLt + omega + simp only [coarsePenaltyTransform] + rw [List.getElem_zipWith, List.getElem_reverse] + simp only [coarseLeftSweep_length, List.length_reverse] + rw [coarseLeftSweep_getElem source v.val v.isLt, + coarseLeftSweep_getElem source.reverse (source.length - 1 - v.val) hreverse] + rw [← coarseArrayLookup_list, ← coarseReverseLookup_list] + exact coarse_two_prefix_minimum (fun i => source[i.val]) v + +def coarseCostedLeftSweep : List ℚ → List ℚ × ℕ + | [] => ([], 0) + | first :: rest => coarseCostedScan first rest + +theorem coarseCostedLeftSweep_result (source : List ℚ) : + (coarseCostedLeftSweep source).1 = coarseLeftSweep source ∧ + (coarseCostedLeftSweep source).2 = 2 * (source.length - 1) := by + cases source with + | nil => simp [coarseCostedLeftSweep, coarseLeftSweep] + | cons first rest => + simpa only [coarseCostedLeftSweep, coarseLeftSweep, List.length_cons, + Nat.add_sub_cancel] using coarseCostedScan_result first rest + +/-- Instrumented actual sweeps plus the final cellwise comparisons. -/ +def coarseCostedPenaltyTransform (source : List ℚ) : List ℚ × ℕ := + let left := coarseCostedLeftSweep source + let right := coarseCostedLeftSweep source.reverse + (List.zipWith min left.1 right.1.reverse, + left.2 + right.2 + min left.1.length right.1.length) + +theorem coarseCostedPenaltyTransform_result (source : List ℚ) : + (coarseCostedPenaltyTransform source).1 = coarsePenaltyTransform source ∧ + (coarseCostedPenaltyTransform source).2 ≤ 5 * source.length := by + have hleft := coarseCostedLeftSweep_result source + have hright := coarseCostedLeftSweep_result source.reverse + simp only [coarseCostedPenaltyTransform, coarsePenaltyTransform, hleft.1, hright.1, + hleft.2, hright.2, coarseLeftSweep_length, List.length_reverse, min_self] + exact ⟨trivial, by omega⟩ + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseWeightSimulation.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseWeightSimulation.lean new file mode 100644 index 0000000000000000000000000000000000000000..1d5e7144dad59cb87c848c19a776dbb755015dc4 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseWeightSimulation.lean @@ -0,0 +1,116 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseBinaryWeight + +namespace OAI + +namespace EditApproximation +namespace BinaryFraction + + theorem coarseBinaryChildrenWeight_eq {B d : ℕ} {α : Type*} (q L : ℕ) + (weight : CoarseSourceTree B α d → CoarseThresholdDraws B d → BinaryFraction → ℕ) + (arrays labels : CoarseSourceTree B α d → CoarseThresholdDraws B d → ℚ → ℕ) + (allowance : BinaryFraction) + (children : List (CoarseSourceTree B α d × Fin B × CoarseThresholdDraws B d)) + (he : ∀ child draw below, (child, draw, below) ∈ children → + weight child below (coarseChildAllowanceWithWork L + (coarseChildThresholdWithWork B q allowance draw).1).1 = + arrays child below ((1 / L) * coarseChildThreshold B q allowance.value draw) + + labels child below ((1 / L) * coarseChildThreshold B q allowance.value draw) + 1) : + coarseBinaryChildrenWeight q L weight allowance children = + coarseActiveChildrenWork q (1 / L) allowance.value arrays children + + coarseLabelChildren q (1 / L) allowance.value labels children + children.length := by + induction children with + | nil => rfl + | cons data rest ih => + obtain ⟨child, draw, below⟩ := data + rw [coarseBinaryChildrenWeight, he child draw below List.mem_cons_self, + ih (fun child draw below hmem => he child draw below (List.mem_cons_of_mem _ hmem))] + simp only [coarseActiveChildrenWork, coarseLabelChildren, List.length_cons] + omega + + theorem coarseBinaryWeight_eq {B d : ℕ} {α : Type*} + (k q L R : ℕ) (tree : CoarseSourceTree B α d) (draws : CoarseThresholdDraws B d) + (hB : 0 < B) (hq : 0 < q) (hL : 0 < L) + (j : ℕ) (hdepth : j + d = R) (allowance : BinaryFraction) + (ha : allowance.representation.den = coarseCommonDenominator 1 q L B R) + (hpath : allowance.value.den ∣ (L * B * q) ^ j) : + coarseBinaryWeight k q L tree draws allowance = + coarseActiveArrayWork k q (1 / L) tree draws allowance.value + + coarseLabelCount q (1 / L) tree draws allowance.value + 1 := by + induction tree generalizing j allowance with + | leaf letter => + have hp := leWithWork_value (nat (CoarseSourceTree.leaf (B := B) letter).word.length) allowance + rw [nat_value] at hp + rw [coarseBinaryWeight, coarseActiveArrayWork, coarseLabelCount] + by_cases h : ((CoarseSourceTree.leaf (B := B) letter).word.length : ℚ) ≤ allowance.value + · simp only [ite_eq_left (hp.mpr h), ite_eq_left h] + · simp only [ite_eq_right (fun hh => h (hp.mp hh)), ite_eq_right h] + | @branch d children ih => + obtain ⟨draws, below⟩ := draws + have hp := leWithWork_value (nat (CoarseSourceTree.branch children).word.length) allowance + rw [nat_value] at hp + rw [coarseBinaryWeight, coarseActiveArrayWork, coarseLabelCount] + by_cases h : ((CoarseSourceTree.branch children).word.length : ℚ) ≤ allowance.value + · simp only [ite_eq_left (hp.mpr h), ite_eq_left h] + · simp only [ite_eq_right (fun hh => h (hp.mp hh)), ite_eq_right h] + have he : coarseBinaryChildrenWeight q L (fun child => coarseBinaryWeight k q L child) + allowance (List.ofFn fun i => (children i, draws i, below i)) = + coarseActiveChildrenWork q (1 / L) allowance.value + (fun child => coarseActiveArrayWork k q (1 / L) child) + (List.ofFn fun i => (children i, draws i, below i)) + + coarseLabelChildren q (1 / L) allowance.value + (fun child => coarseLabelCount q (1 / L) child) + (List.ofFn fun i => (children i, draws i, below i)) + B := by + refine (coarseBinaryChildrenWeight_eq q L (fun child => coarseBinaryWeight k q L child) + (fun child => coarseActiveArrayWork k q (1 / L) child) + (fun child => coarseLabelCount q (1 / L) child) allowance + (List.ofFn fun i => (children i, draws i, below i)) ?_).trans ?_ + · intro child draw childBelow hmem + obtain ⟨i, hi⟩ := List.mem_ofFn.mp hmem + cases hi + let threshold := (coarseChildThresholdWithWork B q allowance (draws i)).1 + let childAllowance := (coarseChildAllowanceWithWork L threshold).1 + have ht : threshold.value = coarseChildThreshold B q allowance.value (draws i) := by + apply coarseChildThresholdWithWork_value + rw [ha, ← hdepth] + exact coarseThreshold_root_grid B q L j d allowance.value (draws i) hB hq hpath + have htd : threshold.representation.den = coarseCommonDenominator 1 q L B R := + (coarseChildThresholdWithWork_den B q allowance (draws i)).trans ha + have hcd : childAllowance.representation.den = coarseCommonDenominator 1 q L B R := + (coarseChildAllowanceWithWork_den L threshold).trans htd + have hv : childAllowance.value = (1 / (L : ℚ)) * + coarseChildThreshold B q allowance.value (draws i) := by + have hg : (threshold.value / L).den ∣ threshold.representation.den := by + rw [ht, htd, ← hdepth] + rw [show coarseChildThreshold B q allowance.value (draws i) / (L : ℚ) = + (1 / (L : ℚ)) * coarseChildThreshold B q allowance.value (draws i) by ring] + exact coarseChildAllowance_root_grid B q L j d allowance.value (draws i) hB hq hL hpath + have hz := coarseChildAllowanceWithWork_value L threshold hg + change childAllowance.value = _ at hz + rw [hz, ht] + ring + have hcp : childAllowance.value.den ∣ (L * B * q) ^ (j + 1) := by + rw [hv] + exact coarseChildAllowance_grid B q L j allowance.value (draws i) hB hq hL hpath + have hc := ih i (below i) (j + 1) (by omega) childAllowance hcd hcp + rw [hv] at hc + exact hc + · simp only [List.length_ofFn] + rw [he] + omega + + theorem coarseBinaryWeight_le {B d : ℕ} {α : Type*} + (k q L R : ℕ) (tree : CoarseSourceTree B α d) (draws : CoarseThresholdDraws B d) + (hB : 0 < B) (hq : 0 < q) (hL : 0 < L) + (j : ℕ) (hdepth : j + d = R) (allowance : BinaryFraction) + (ha : allowance.representation.den = coarseCommonDenominator 1 q L B R) + (hpath : allowance.value.den ∣ (L * B * q) ^ j) : + coarseBinaryWeight k q L tree draws allowance ≤ + 2 * coarseActiveArrayWork k q (1 / L) tree draws allowance.value + 1 := by + rw [coarseBinaryWeight_eq k q L R tree draws hB hq hL j hdepth allowance ha hpath] + have h := coarseLabelCount_le_arrayWork k (q : ℚ) (1 / L) tree draws allowance.value + omega + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseWidthWork.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseWidthWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..1f1a6e65ce09b57ff6892bbb38a59f24bf6eb641 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseWidthWork.lean @@ -0,0 +1,44 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseInitialWork + +namespace OAI + +/-! The direct long-target branch removes dependence of initial-entry +work on the target interval width. This is the source-width charge used +when coarse leaves are summed over the physical dependency tree. -/ + +namespace EditApproximation + +open MeasureTheory + +theorem coarseInitialArrayWork_expected_source_width {α : Type*} [DecidableEq α] + {B D : ℕ} [NeZero B] [MeasurableSpace (Fin B)] [MeasurableSingletonClass (Fin B)] + (Q lam : ℚ) (x y : List α) (N : ℕ) + (hsize : coarseEntryWidth x y ≤ N) (hcapacity : coarseEntryWidth x y ≤ B ^ D) + (hQ : 0 < Q) (hlam : 0 < lam) (factor : ℝ) (hfactor : 1 ≤ factor) + (hinverse : coarseInverseAllowanceFactor B Q lam ≤ factor) : + (∫ draws, (coarseInitialArrayWork B D Q lam x y draws : ℝ) + ∂coarseInitialMeasure B D (coarseEntryWidth x y)) ≤ + 6 * B * x.length * (Nat.clog 2 N + 1 : ℕ) * (D + 1 : ℕ) * factor ^ D := by + have hnonneg : 0 ≤ factor := le_trans (by norm_num) hfactor + by_cases hlong : 2 * x.length < y.length + · have hzero (draws) : coarseInitialArrayWork B D Q lam x y draws = 0 := by + simp only [coarseInitialArrayWork, ite_eq_left hlong] + simp only [hzero, Nat.cast_zero, integral_zero] + positivity + · have hwidth : coarseEntryWidth x y ≤ 2 * x.length := by + unfold coarseEntryWidth + omega + have hlog := Nat.clog_mono_right 2 hsize + have h := coarseInitialArrayWork_expected_bound Q lam x y hcapacity hQ hlam factor hfactor hinverse + apply h.trans + calc + 3 * B * coarseEntryWidth x y * (Nat.clog 2 (coarseEntryWidth x y) + 1 : ℕ) * + (D + 1 : ℕ) * factor ^ D ≤ + 3 * B * (2 * (x.length : ℝ)) * (Nat.clog 2 N + 1 : ℕ) * (D + 1 : ℕ) * factor ^ D := by + gcongr + · exact_mod_cast hwidth + _ = _ := by ring + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseWork.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..0fcbd3570fd6f2ccb1f5c2b4d910ed091a254a7a --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseWork.lean @@ -0,0 +1,290 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseProbability +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! +# Expected active work in the concrete pruned coarse tree + +The counter records the array units of the actual execution; pruning stops +all descendant visits. Constant child overhead is charged to its expanded +parent. The linear-sweep proof converts these units to rational operations; +bit/RAM charging is separate. +-/ + +namespace EditApproximation + +open Finset MeasureTheory ProbabilityTheory + +universe u + + + +/- Array units actually incurred before pruning terminates a subtree. -/ + + +/-- Finite conditional expectation recurrence for the same active work. +The root labels are independent uniforms, and each child uses its own +independent recursive label tree. -/ +noncomputable def coarseExpectedArrayWork {B : ℕ} {α : Type u} (k : ℕ) (Q lam : ℚ) : + {D : ℕ} → CoarseSourceTree B α D → ℚ → ℝ + | _, tree, allowance => + if (tree.word.length : ℚ) ≤ allowance then 0 else + match tree with + | .leaf _ => (B * (2 * k + 1) : ℕ) + | .branch children => + (B * (2 * k + 1) : ℕ) + + ∑ i : Fin B, uniformMean (fun draw : Fin B => + coarseExpectedArrayWork k Q lam (children i) + (lam * coarseChildThreshold B Q allowance draw)) + +noncomputable def coarseInverseAllowanceFactor (B : ℕ) (Q lam : ℚ) : ℝ := + (Q : ℝ) / lam * ∑ r ∈ Icc 1 B, (1 : ℝ) / r + +noncomputable def coarseWorkMultiplier (factor : ℝ) (D : ℕ) : ℝ := + ∑ r ∈ range (D + 1), factor ^ r + +theorem coarseWorkMultiplier_nonneg (factor : ℝ) (D : ℕ) (hfactor : 0 ≤ factor) : + 0 ≤ coarseWorkMultiplier factor D := + sum_nonneg (fun _ _ => pow_nonneg hfactor _) + +theorem coarseWorkMultiplier_succ (factor : ℝ) (D : ℕ) : + coarseWorkMultiplier factor (D + 1) = 1 + factor * coarseWorkMultiplier factor D := by + simp only [coarseWorkMultiplier] + rw [sum_range_succ'] + simp only [pow_zero, pow_succ', ← mul_sum] + ring + +theorem coarseWorkMultiplier_le (factor : ℝ) (D : ℕ) (hfactor : 1 ≤ factor) : + coarseWorkMultiplier factor D ≤ (D + 1 : ℕ) * factor ^ D := by + have hpoint : ∀ r ∈ range (D + 1), factor ^ r ≤ factor ^ D := by + intro r hr + exact pow_le_pow_right₀ hfactor (by obtain := mem_range.mp hr; omega) + have hsum := sum_le_sum hpoint + simpa only [coarseWorkMultiplier, sum_const, card_range, nsmul_eq_mul] using hsum + +theorem uniformMean_mono {ι : Type*} [Fintype ι] (first second : ι → ℝ) + (hle : ∀ i, first i ≤ second i) : uniformMean first ≤ uniformMean second := by + exact div_le_div_of_nonneg_right (sum_le_sum (fun i _ => hle i)) (by positivity) + +theorem uniformMean_const_mul {ι : Type*} [Fintype ι] (constant : ℝ) (value : ι → ℝ) : + uniformMean (fun i => constant * value i) = constant * uniformMean value := by + simp only [uniformMean, ← mul_sum] + ring + +/-- Exact expected inverse allowance under the literal integer threshold +law. This identity is independent of all estimated arrays and accuracy. -/ +theorem coarse_inverse_allowance_mean (B : ℕ) [NeZero B] (Q lam allowance : ℚ) + (hQ : 0 < Q) (hlam : 0 < lam) (ha : 0 < allowance) : + uniformMean (fun draw : Fin B => + 1 / ((lam * coarseChildThreshold B Q allowance draw : ℚ) : ℝ)) = + coarseInverseAllowanceFactor B Q lam / allowance := by + have hBr : (0 : ℝ) < B := by exact_mod_cast Nat.pos_of_ne_zero (NeZero.ne B) + have hQr : (0 : ℝ) < Q := by exact_mod_cast hQ + have hlr : (0 : ℝ) < lam := by exact_mod_cast hlam + have har : (0 : ℝ) < allowance := by exact_mod_cast ha + have hpoint (draw : Fin B) : + 1 / ((lam * coarseChildThreshold B Q allowance draw : ℚ) : ℝ) = + ((B : ℝ) * Q / (lam * allowance)) * (1 / (draw.val + 1 : ℕ)) := by + have hr : (0 : ℝ) < (draw.val + 1 : ℕ) := by positivity + simp only [coarseChildThreshold, Rat.cast_mul, Rat.cast_div, Rat.cast_natCast] + field_simp + simp_rw [hpoint] + rw [uniformMean_const_mul] + simp only [uniformMean, Fintype.card_fin] + rw [coarse_sum_labels B (fun r => (1 : ℝ) / r)] + unfold coarseInverseAllowanceFactor + field_simp + +theorem coarseBranch_word_length {B D : ℕ} {α : Type u} + (children : Fin B → CoarseSourceTree B α D) : + (CoarseSourceTree.branch children).word.length = ∑ i, (children i).word.length := by + simp only [CoarseSourceTree.word, List.length_flatten, List.map_ofFn, + Function.comp_def, List.sum_ofFn] + +/-- The expected active work has the paper's inverse-allowance bound. +The inequality holds regardless of every coarse accuracy event. -/ +theorem coarseExpectedArrayWork_bound {B D : ℕ} [NeZero B] {α : Type u} + (k : ℕ) (Q lam : ℚ) (tree : CoarseSourceTree B α D) (allowance : ℚ) + (hQ : 0 < Q) (hlam : 0 < lam) (ha : 0 < allowance) : + coarseExpectedArrayWork k Q lam tree allowance ≤ + (B * (2 * k + 1) : ℕ) * (tree.word.length : ℝ) / allowance * + coarseWorkMultiplier (coarseInverseAllowanceFactor B Q lam) D := by + have hfactor : 0 ≤ coarseInverseAllowanceFactor B Q lam := by + unfold coarseInverseAllowanceFactor + apply mul_nonneg + · exact div_nonneg (by exact_mod_cast hQ.le) (by exact_mod_cast hlam.le) + · exact sum_nonneg (fun _ _ => by positivity) + have haReal : (0 : ℝ) < allowance := by exact_mod_cast ha + induction tree generalizing allowance with + | leaf letter => + simp only [coarseExpectedArrayWork] + split_ifs with hprune + · exact mul_nonneg (div_nonneg (by positivity) haReal.le) + (coarseWorkMultiplier_nonneg _ 0 hfactor) + · have hwidth : (allowance : ℝ) < (CoarseSourceTree.leaf (B := B) letter).word.length := by + exact_mod_cast lt_of_not_ge hprune + simp only [coarseWorkMultiplier, zero_add, sum_range_one, pow_zero, mul_one] + apply (le_div_iff₀ haReal).2 + nlinarith [show (0 : ℝ) ≤ (B * (2 * k + 1) : ℕ) by positivity] + | @branch D children ih => + simp only [coarseExpectedArrayWork] + split_ifs with hprune + · exact mul_nonneg (div_nonneg (by positivity) haReal.le) + (coarseWorkMultiplier_nonneg _ (D + 1) hfactor) + · let charge : ℝ := (B * (2 * k + 1) : ℕ) + let factor := coarseInverseAllowanceFactor B Q lam + let multiplier := coarseWorkMultiplier factor D + have hmeanBound (i : Fin B) : + uniformMean (fun draw : Fin B => coarseExpectedArrayWork k Q lam (children i) + (lam * coarseChildThreshold B Q allowance draw)) ≤ + charge * (children i).word.length * multiplier * (factor / allowance) := by + have hpoint (draw : Fin B) : + coarseExpectedArrayWork k Q lam (children i) + (lam * coarseChildThreshold B Q allowance draw) ≤ + (charge * (children i).word.length * multiplier) * + (1 / ((lam * coarseChildThreshold B Q allowance draw : ℚ) : ℝ)) := by + have hchildAllowance := mul_pos hlam (coarseChildThreshold_pos draw hQ ha) + have hbound := ih i _ hchildAllowance (by exact_mod_cast hchildAllowance) + convert hbound using 1 + dsimp [charge, multiplier, factor] + ring + have hmean := uniformMean_mono _ _ hpoint + rw [uniformMean_const_mul, coarse_inverse_allowance_mean B Q lam allowance hQ hlam ha] at hmean + exact hmean + have hmeanSum := sum_le_sum (s := univ) (fun i _ => hmeanBound i) + have hlength : (∑ i, ((children i).word.length : ℝ)) = + (CoarseSourceTree.branch children).word.length := by + exact_mod_cast (coarseBranch_word_length children).symm + have hsum : (∑ i, charge * (children i).word.length * multiplier * (factor / allowance)) = + charge * (CoarseSourceTree.branch children).word.length / allowance * (factor * multiplier) := by + calc + _ = (charge * multiplier * (factor / allowance)) * ∑ i, ((children i).word.length : ℝ) := by + rw [mul_sum] + apply sum_congr rfl + intro i hi + ring + _ = _ := by rw [hlength]; ring + rw [hsum] at hmeanSum + have hwidth : (allowance : ℝ) < (CoarseSourceTree.branch children).word.length := by + exact_mod_cast lt_of_not_ge hprune + have hcharge : charge ≤ charge * (CoarseSourceTree.branch children).word.length / allowance := by + apply (le_div_iff₀ haReal).2 + dsimp [charge] + nlinarith [show (0 : ℝ) ≤ (B * (2 * k + 1) : ℕ) by positivity] + have htotal := add_le_add hcharge hmeanSum + rw [coarseWorkMultiplier_succ] + dsimp [charge, multiplier, factor] at htotal ⊢ + nlinarith + +theorem coarseActiveChildrenWork_eq_sum {B D : ℕ} {α : Type u} + (Q lam allowance : ℚ) + (work : CoarseSourceTree B α D → CoarseThresholdDraws B D → ℚ → ℕ) + (children : List (CoarseSourceTree B α D × Fin B × CoarseThresholdDraws B D)) : + coarseActiveChildrenWork Q lam allowance work children = + (children.map (fun data => + work data.1 data.2.2 (lam * coarseChildThreshold B Q allowance data.2.1))).sum := by + induction children with + | nil => rfl + | cons data rest ih => + obtain ⟨child, draw, below⟩ := data + simp only [coarseActiveChildrenWork, List.map_cons, List.sum_cons, ih] + +theorem coarseActiveChildrenWork_ofFn {B D : ℕ} {α : Type u} + (Q lam allowance : ℚ) + (work : CoarseSourceTree B α D → CoarseThresholdDraws B D → ℚ → ℕ) + (children : Fin B → CoarseSourceTree B α D) + (draws : Fin B → Fin B) (below : Fin B → CoarseThresholdDraws B D) : + coarseActiveChildrenWork Q lam allowance work + (List.ofFn fun i => (children i, draws i, below i)) = + ∑ i : Fin B, work (children i) (below i) (lam * coarseChildThreshold B Q allowance (draws i)) := by + rw [coarseActiveChildrenWork_eq_sum] + simp only [List.map_ofFn, Function.comp_def, List.sum_ofFn] + +/-- The finite expectation recurrence is exactly the expectation of the +actual pruning-stopped execution counter under the concrete recursive law. -/ +theorem coarseActiveArrayWork_integral {B D : ℕ} [NeZero B] {α : Type u} + [MeasurableSpace (Fin B)] [MeasurableSingletonClass (Fin B)] + (k : ℕ) (Q lam : ℚ) (tree : CoarseSourceTree B α D) (allowance : ℚ) : + (∫ draws, (coarseActiveArrayWork k Q lam tree draws allowance : ℝ) + ∂coarseDrawMeasure B D) = coarseExpectedArrayWork k Q lam tree allowance := by + induction tree generalizing allowance with + | leaf letter => + simp only [coarseActiveArrayWork, coarseExpectedArrayWork] + split_ifs <;> simp + | @branch D children ih => + by_cases hprune : ((CoarseSourceTree.branch children).word.length : ℚ) ≤ allowance + · have hzero : (fun draws : CoarseThresholdDraws B (D + 1) => + (coarseActiveArrayWork k Q lam (.branch children) draws allowance : ℝ)) = fun _ => 0 := by + funext draws + obtain ⟨draws, below⟩ := draws + simp only [coarseActiveArrayWork, hprune, ↓reduceIte, Nat.cast_zero] + rw [hzero] + simp only [integral_zero, coarseExpectedArrayWork, hprune, ↓reduceIte] + · let μ := (PMF.uniformOfFintype (Fin B)).toMeasure + let ν := coarseDrawMeasure B D + change (∫ data : (Fin B → Fin B) × (Fin B → CoarseThresholdDraws B D), + (coarseActiveArrayWork k Q lam (.branch children) data allowance : ℝ) + ∂((Measure.pi fun _ : Fin B => μ).prod (Measure.pi fun _ : Fin B => ν))) = _ + have hpoint (data : (Fin B → Fin B) × (Fin B → CoarseThresholdDraws B D)) : + (coarseActiveArrayWork k Q lam (.branch children) data allowance : ℝ) = + (B * (2 * k + 1) : ℕ) + ∑ i : Fin B, + (coarseActiveArrayWork k Q lam (children i) (data.2 i) + (lam * coarseChildThreshold B Q allowance (data.1 i)) : ℝ) := by + obtain ⟨draws, below⟩ := data + simp only [coarseActiveArrayWork, hprune, ↓reduceIte, + coarseActiveChildrenWork_ofFn, Nat.cast_add, Nat.cast_sum] + simp_rw [hpoint] + rw [integral_prod _ (.of_finite)] + have hinner (draws : Fin B → Fin B) : + (∫ below : Fin B → CoarseThresholdDraws B D, + ((B * (2 * k + 1) : ℕ) + ∑ i : Fin B, + (coarseActiveArrayWork k Q lam (children i) (below i) + (lam * coarseChildThreshold B Q allowance (draws i)) : ℝ)) + ∂Measure.pi (fun _ : Fin B => ν)) = + (B * (2 * k + 1) : ℕ) + ∑ i : Fin B, + coarseExpectedArrayWork k Q lam (children i) + (lam * coarseChildThreshold B Q allowance (draws i)) := by + rw [integral_add (integrable_const _) (.of_finite), integral_const, probReal_univ, one_smul, + integral_finsetSum] + · congr 1 + apply sum_congr rfl + intro i hi + rw [integral_comp_eval (μ := fun _ : Fin B => ν) (i := i) + (f := fun below => (coarseActiveArrayWork k Q lam (children i) below + (lam * coarseChildThreshold B Q allowance (draws i)) : ℝ)) + (measurable_of_finite _).aestronglyMeasurable] + exact ih i _ + · intro i hi + exact .of_finite + simp_rw [hinner] + rw [integral_add (integrable_const _) (.of_finite), integral_const, probReal_univ, one_smul, + integral_finsetSum] + · simp only [coarseExpectedArrayWork, hprune, ↓reduceIte] + congr 1 + apply sum_congr rfl + intro i hi + rw [integral_comp_eval (μ := fun _ : Fin B => μ) (i := i) + (f := fun draw => coarseExpectedArrayWork k Q lam (children i) + (lam * coarseChildThreshold B Q allowance draw)) + (measurable_of_finite _).aestronglyMeasurable, uniform_integral] + · intro i hi + exact .of_finite + +/-- Expected active work, stated directly for the actual execution law, +without any conditioning on accuracy. -/ +theorem coarseActiveArrayWork_expected_bound {B D : ℕ} [NeZero B] {α : Type u} + [MeasurableSpace (Fin B)] [MeasurableSingletonClass (Fin B)] + (k : ℕ) (Q lam : ℚ) (tree : CoarseSourceTree B α D) (allowance : ℚ) + (hQ : 0 < Q) (hlam : 0 < lam) (ha : 0 < allowance) : + (∫ draws, (coarseActiveArrayWork k Q lam tree draws allowance : ℝ) + ∂coarseDrawMeasure B D) ≤ + (B * (2 * k + 1) : ℕ) * (tree.word.length : ℝ) / allowance * + coarseWorkMultiplier (coarseInverseAllowanceFactor B Q lam) D := by + rw [coarseActiveArrayWork_integral] + exact coarseExpectedArrayWork_bound k Q lam tree allowance hQ hlam ha + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseWorkAsymptotics.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseWorkAsymptotics.lean new file mode 100644 index 0000000000000000000000000000000000000000..9831cfa5fd237f4a7abfb0d9ab8a53872048fa3f --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseWorkAsymptotics.lean @@ -0,0 +1,145 @@ +import OAI.Combinatorics.EditApproximation.Geometry.ParameterLocalAsymptotics +import OAI.Combinatorics.EditApproximation.Coarse.CoarseParameters +import OAI.Combinatorics.EditApproximation.Coarse.CoarseInitialWork + +namespace OAI + +/-! The depth-dependent scalar overhead of the actual initial estimator. +The expected array-counter bound includes every pruning outcome. -/ + +namespace EditApproximation + +open Filter +open scoped Topology + +def computedMaxCoarseDepth (N : ℕ) : ℕ := computedCoarseDepth N N + +theorem computedCoarseDepth_le_max (N n : ℕ) (hn : n ≤ N) : + computedCoarseDepth N n ≤ computedMaxCoarseDepth N := by + change Nat.clog (integerParameters N).B (max 1 n) ≤ Nat.clog (integerParameters N).B (max 1 N) + exact Nat.clog_mono_right (integerParameters N).B (max_le_max le_rfl hn) + +theorem coarse_depth_mul_exponent_bound (N : ℕ) : + computedMaxCoarseDepth N * (heightExponent N * coarseExponent (inputSmallLog N)) ≤ + inputHeight N + heightExponent N * coarseExponent (inputSmallLog N) := by + let e := heightExponent N * coarseExponent (inputSmallLog N) + have hB : (integerParameters N).B = 2 ^ e := by + simp only [integerParameters, inputHeight, ← pow_mul, e] + have hdepth : computedMaxCoarseDepth N = (Nat.clog 2 (max 1 N) + (e - 1)) / e := by + unfold computedMaxCoarseDepth computedCoarseDepth + rw [hB, Nat.clog_pow_left] + have hlength : max 1 N ≤ 2 ^ inputHeight N := by + apply max_le Nat.one_le_two_pow + exact (Nat.le_add_right N 2).trans (inputHeight_covers_length N) + have hlog : Nat.clog 2 (max 1 N) ≤ inputHeight N := + (Nat.clog_le_iff_le_pow (by decide : 1 < 2)).2 hlength + have hprod := Nat.div_mul_le_self (Nat.clog 2 (max 1 N) + (e - 1)) e + rw [← hdepth] at hprod + exact hprod.trans (Nat.add_le_add hlog (Nat.sub_le _ _)) + +theorem scalar_coarse_depth_log_bound (D e p H c : ℝ) + (hp : 0 < p) (hH : 0 < H) (hc : 0 ≤ c) + (hbound : D * (e * p) ≤ H + e * p) : + D * (e * c) / H ≤ e * c / H + c / p := by + have hDe : D * e ≤ H / p + e := by + calc + D * e ≤ (H + e * p) / p := (le_div_iff₀ hp).2 (by nlinarith only [hbound]) + _ = H / p + e := by field_simp [hp.ne'] + have hmul := mul_le_mul_of_nonneg_right hDe hc + have hdiv := div_le_div_of_nonneg_right hmul hH.le + calc + D * (e * c) / H = (D * e) * c / H := by ring + _ ≤ (H / p + e) * c / H := hdiv + _ = e * c / H + c / p := by field_simp [hp.ne', hH.ne']; ring + +theorem coarse_depth_log_height_div_height_tendsto : + Tendsto (fun N => (computedMaxCoarseDepth N : ℝ) * + Real.log (inputHeight N : ℝ) / inputHeight N) atTop (𝓝 0) := by + have hlog : Tendsto (fun N => Real.log (inputHeight N : ℝ) / inputHeight N) + atTop (𝓝 0) := + Real.isLittleO_log_id_atTop.tendsto_div_nhds_zero.comp inputHeight_real_tendsto + have hinv : Tendsto (fun N => Real.log 2 / (coarseExponent (inputSmallLog N) : ℝ)) + atTop (𝓝 0) := by + simpa only [Pi.inv_apply, mul_zero, div_eq_mul_inv] using + coarseExponent_real_tendsto.inv_tendsto_atTop.const_mul (Real.log 2) + have hupper := hlog.add hinv + simp only [zero_add] at hupper + apply squeeze_zero' (Eventually.of_forall fun N => by + apply div_nonneg + · apply mul_nonneg (Nat.cast_nonneg _) + apply Real.log_nonneg + exact_mod_cast Nat.one_le_two_pow (n := heightExponent N) + · exact Nat.cast_nonneg _) _ hupper + filter_upwards [coarseExponent_tendsto.eventually (eventually_ge_atTop 1)] with N hp + have hbound : (computedMaxCoarseDepth N : ℝ) * + ((heightExponent N : ℝ) * coarseExponent (inputSmallLog N)) ≤ + (inputHeight N : ℝ) + (heightExponent N : ℝ) * coarseExponent (inputSmallLog N) := by + exact_mod_cast coarse_depth_mul_exponent_bound N + rw [inputHeight_real_log] + exact scalar_coarse_depth_log_bound _ _ _ _ _ + (by exact_mod_cast (show 0 < coarseExponent (inputSmallLog N) by omega)) + (by exact_mod_cast Nat.two_pow_pos (heightExponent N)) + (Real.log_nonneg (by norm_num)) hbound + +noncomputable def computedCoarseOverheadExponent (C : ℝ) (N : ℕ) : ℝ := + C * ((computedMaxCoarseDepth N : ℝ) + coarseExponent (inputSmallLog N) + 1) * + Real.log (inputHeight N : ℝ) + +theorem computedCoarseOverheadExponent_tendsto (C : ℝ) : + Tendsto (fun N => computedCoarseOverheadExponent C N / inputHeight N) atTop (𝓝 0) := by + have h := (coarse_depth_log_height_div_height_tendsto.add + encoding_exponent_div_height_tendsto).const_mul C + simp only [zero_add, mul_zero] at h + convert h using 1 + ext N + unfold computedCoarseOverheadExponent + ring + +theorem coarse_branching_log_div_height_tendsto : + Tendsto (fun N => Real.log ((integerParameters N).B : ℝ) / inputHeight N) + atTop (𝓝 0) := by + have hlog : Tendsto (fun N => Real.log (inputHeight N : ℝ) / inputHeight N) + atTop (𝓝 0) := + Real.isLittleO_log_id_atTop.tendsto_div_nhds_zero.comp inputHeight_real_tendsto + have h := encoding_exponent_div_height_tendsto.sub hlog + simp only [sub_zero] at h + convert h using 1 + ext N + simp only [integerParameters, Nat.cast_pow, Real.log_pow] + ring + +/-- The literal coarse threshold law has the paper's `H^8` inverse-allowance +factor, for all sufficiently large inputs and without any accuracy event. -/ +theorem coarse_inverse_allowance_le_height_eight_eventually : + ∀ᶠ N in atTop, coarseInverseAllowanceFactor (integerParameters N).B + (initialThresholdQ N) (initialLambda N) ≤ (inputHeight N : ℝ) ^ 8 := by + have hratio := coarse_branching_log_div_height_tendsto.eventually + (gt_mem_nhds (by norm_num : (0 : ℝ) < 1)) + filter_upwards [hratio, inputHeight_real_tendsto.eventually (eventually_ge_atTop 128)] with N hratio hlarge + have hH : (0 : ℝ) < inputHeight N := by exact_mod_cast Nat.two_pow_pos (heightExponent N) + have hlog : Real.log ((integerParameters N).B : ℝ) ≤ inputHeight N := + ((div_lt_one hH).1 hratio).le + have hraw := coarseInverseAllowanceFactor_log_bound (integerParameters N).B + (initialThresholdQ N) (initialLambda N) + (by unfold initialThresholdQ; positivity) (by unfold initialLambda; positivity) + have hfactor : ((initialThresholdQ N : ℚ) : ℝ) / ((initialLambda N : ℚ) : ℝ) = + 64 * (inputHeight N : ℝ) ^ 5 := by + simp only [initialThresholdQ, initialLambda, Rat.cast_pow, Rat.cast_natCast, + Rat.cast_div, Rat.cast_one, Rat.cast_mul, Rat.cast_ofNat] + field_simp [hH.ne'] + rw [hfactor] at hraw + have hstep : 1 + Real.log ((integerParameters N).B : ℝ) ≤ 2 * (inputHeight N : ℝ) := by + linarith + calc + _ ≤ 64 * (inputHeight N : ℝ) ^ 5 * (1 + Real.log ((integerParameters N).B : ℝ)) := hraw + _ ≤ 64 * (inputHeight N : ℝ) ^ 5 * (2 * (inputHeight N : ℝ)) := + mul_le_mul_of_nonneg_left hstep (by positivity) + _ = 128 * (inputHeight N : ℝ) ^ 6 := by ring + _ ≤ (inputHeight N : ℝ) ^ 2 * (inputHeight N : ℝ) ^ 6 := by + apply mul_le_mul_of_nonneg_right _ (by positivity) + nlinarith + _ = (inputHeight N : ℝ) ^ 8 := by ring + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseWorkEnvelope.lean b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseWorkEnvelope.lean new file mode 100644 index 0000000000000000000000000000000000000000..2fed2843ad11ec66ba99cee4c4d1af09d22dcd31 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Coarse/CoarseWorkEnvelope.lean @@ -0,0 +1,38 @@ +import OAI.Combinatorics.EditApproximation.Geometry.ChargedQueryAsymptotics +import OAI.Combinatorics.EditApproximation.Refinement.ComputedCoarseWidthCost + +namespace OAI + +/-! The actual coarse first-request factor times the width budget remains +almost linear. This bound does not assume any seed-correctness event. -/ + +namespace EditApproximation + +open Filter + +theorem computed_coarse_widthWork_near_linear (epsilon : ℝ) (hepsilon : 0 < epsilon) : + ∀ᶠ N in atTop, ∀ n ≤ N, ∀ tree : DependencyExpansion, + tree.Valid ((integerParameters N).M * inputSmallLog N ^ 257) + (inputHeight N ^ (512 * (coarseExponent (inputSmallLog N) + 1))) → + tree.depth = intervalTreeDepth (integerParameters N).M n → + tree.rank ≤ computedDependencyIndexCount N → + (tree.widthWork (integerParameters N).M n : ℝ) * computedCoarseWidthOverhead N ≤ + (N + 2 : ℝ) ^ (1 + epsilon) := by + filter_upwards [computed_weighted_widthWork_near_linear 0 (epsilon / 2) (by linarith), + subexponential_height_to_input _ (computedCoarseOverheadExponent_tendsto 10) + (epsilon / 2) (by linarith), eventually_ge_atTop 1] with N hw hc hN + intro n hn tree hv hd hk + have hwidth := hw n hn tree hv hd hk + simp only [pow_zero, mul_one] at hwidth + have hoverhead := (computedCoarseWidthOverhead_exp_le N (by omega)).trans hc + calc + _ ≤ (N + 2 : ℝ) ^ (1 + epsilon / 2) * (N + 2 : ℝ) ^ (epsilon / 2) := + mul_le_mul hwidth hoverhead (Nat.cast_nonneg _) (by positivity) + _ = (N + 2 : ℝ) ^ (1 + epsilon) := by + rw [← Real.rpow_add (by positivity : (0 : ℝ) < N + 2)] + congr 1 + ring + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Definitions.lean b/lean/OAI/Combinatorics/EditApproximation/Definitions.lean new file mode 100644 index 0000000000000000000000000000000000000000..c916f2f630276efc28faa4ce0bc9e371b1a18cfa --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Definitions.lean @@ -0,0 +1,19149 @@ +import Mathlib + +namespace OAI.EditDistortion +end OAI.EditDistortion + +/-! A uniform almost-linear approximation scheme for edit distance. +The statement retains the concrete binary algorithm and its exact resource accounting. -/ + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation + + +def bitWordValue : List Bool → ℕ + | [] => 0 + | bit :: bits => bit.toNat + 2 * bitWordValue bits + +def bitSum (a b carry : Bool) : Bool := xor (xor a b) carry + +def bitCarry (a b carry : Bool) : Bool := (a && b) || (a && carry) || (b && carry) + +structure UnreducedRational where + num : ℤ + den : ℕ + den_pos : 0 < den + +def orderingMatches (o : Ordering) (a b : ℕ) : Prop := + (o = .lt ∧ a < b) ∨ (o = .eq ∧ a = b) ∨ (o = .gt ∧ b < a) + +def bitOrdering (high : Ordering) (a b : Bool) : Ordering := + match high with + | .lt => .lt + | .gt => .gt + | .eq => if a = b then .eq else if a then .gt else .lt + +def bitDifference (a b borrow : Bool) : Bool := xor (xor a b) borrow + +def bitBorrow (a b borrow : Bool) : Bool := ((!a) && (b || borrow)) || (b && borrow) + +structure SignedBinary where + negative : Bool + bits : List Bool + +def signedMagnitude (negative : Bool) (magnitude : ℕ) : ℤ := + if negative then -(magnitude : ℤ) else magnitude + +def trimBitWordWithWork : List Bool → List Bool × ℕ + | [] => ([], 1) + | bit :: bits => + let tail := trimBitWordWithWork bits + (if tail.1 = [] ∧ bit = false then [] else bit :: tail.1, tail.2 + 3) + +def balancedCut (lo width M i : ℕ) : ℕ := lo + i * width / M + +def gridRound (spacing position : ℕ) : ℕ := spacing * (position / spacing) + +def rationalMinimum (fallback : ℚ) : List ℚ → ℚ + | [] => fallback + | value :: rest => min value (rationalMinimum fallback rest) + +structure RationalBellmanAction (Parent : Type u_1) (Child : Type u_2) (M : ℕ) where + center : Parent + connection : ℚ + childState : Fin M → Child + +def rationalRefinementUpdate (δ cone : ℚ) : Option ℚ → ℚ + | none => cone + | some online => min cone (max (cone / (1 + δ)) online) + +def heightExponent (N : ℕ) : ℕ := Nat.clog 2 (Nat.clog 2 (N + 2)) + +def coarseExponent (ell : ℕ) : ℕ := Nat.sqrt (Nat.sqrt (Nat.log 2 ell)) + +structure IntegerParameters where + H : ℕ + ell : ℕ + p : ℕ + B : ℕ + initialFactor : ℕ + M : ℕ + P : ℕ + T : ℕ + S : ℕ + +structure RationalParameters where + F : ℚ + initialSlope : ℚ + coneSlope : ℚ + delta : ℚ + kappa : ℚ + tau : ℚ + theta : ℚ + gamma : ℚ + eta : ℚ + +def gridPointsBetween (g lo hi : ℕ) : List ℕ := + (List.range' (lo ⌈/⌉ g) ((hi / g + 1) - lo ⌈/⌉ g)).map fun i => g * i + +def scaledSeedValue (U : ℕ) (a gap : ℚ) : ℚ := + max (⌈(U : ℚ) / a⌉₊ : ℚ) |gap| + +def dyadicScales (N : ℕ) : List ℕ := + (List.range (Nat.log 2 N + 1)).map fun k => 2 ^ k + +def seedGridSpacing (b P : ℕ) : ℕ := max 1 (b / P) + +def finiteAssignments {α : Type u_1} : (M : ℕ) → (Fin M → List α) → List (Fin M → α) + | 0, _ => [Fin.elim0] + | M + 1, choices => + (choices 0).flatMap fun head => + (finiteAssignments M (fun i => choices i.succ)).map fun tail => Fin.cons head tail + +def powerTwoWord (n : ℕ) : List Bool := List.replicate n false ++ [true] + +def filterWithWork {α : Type u_1} (test : α → Bool × ℕ) : List α → List α × ℕ + | [] => ([], 0) + | a :: rest => + let current := test a + let tail := filterWithWork test rest + (if current.1 then a :: tail.1 else tail.1, current.2 + tail.2 + 3) + +def allWithWork {α : Type u_1} (test : α → Bool × ℕ) : List α → Bool × ℕ + | [] => (true, 0) + | a :: rest => + let current := test a + let tail := allWithWork test rest + (current.1 && tail.1, current.2 + tail.2 + 3) + +def arithmeticMapWithWork {α : Type u_1} {β : Type u_2} (f : α → β × ℕ) : List α → List β × ℕ + | [] => ([], 0) + | a :: rest => + let current := f a + let tail := arithmeticMapWithWork f rest + (current.1 :: tail.1, current.2 + tail.2 + 3) + +def arithmeticFlatMapWithWork {α : Type u_1} {β : Type u_2} (f : α → List β × ℕ) : List α → List β × ℕ + | [] => ([], 0) + | a :: rest => + let current := f a + let tail := arithmeticFlatMapWithWork f rest + (current.1 ++ tail.1, current.2 + tail.2 + current.1.length + 3) + +def upperMedian (values : List ℕ) : ℕ := + (values.mergeSort (· ≤ ·)).getD (values.length / 2) 0 + +def filterMapWithWork {α : Type u_1} {β : Type u_2} (f : α → Option β × ℕ) : List α → List β × ℕ + | [] => ([], 0) + | a :: rest => + let first := f a + let tail := filterMapWithWork f rest + (match first.1 with | none => tail.1 | some b => b :: tail.1, first.2 + tail.2 + 3) + +def cellGridPoints (side : ℚ) (g cell : ℕ) : List ℕ := + (List.range' ⌈(cell : ℚ) * side / g⌉₊ + (⌈((cell : ℚ) + 1) * side / g⌉₊ - ⌈(cell : ℚ) * side / g⌉₊)).map fun i => g * i + +def groupRoundSpacing (exponent : ℕ) (h : ℚ) : ℕ := + ⌈max 1 ((2 : ℚ) ^ (-(exponent : ℤ)) * h)⌉₊ + +def refinementFactor (A : ℚ) (F : ℕ) : ℚ := max 1 (A / F) + +def localCellCoordinates (side : ℚ) (p radius : ℕ) : List ℕ := + let first := ⌊((p - radius : ℕ) : ℚ) / side⌋₊ + let last := ⌊((p + radius : ℕ) : ℚ) / side⌋₊ + List.range' first (last + 1 - first) + +def dyadicSeedPassCount (f initial : ℕ) : ℕ := (initial - f) ⌈/⌉ (f - 2) + +def dyadicSeedExponent (f initial pass : ℕ) : ℕ := initial - pass * (f - 2) + +def memberByWithWork {α : Type u_1} (equal : α → α → Bool × ℕ) (a : α) : List α → Bool × ℕ + | [] => (false, 1) + | b :: rest => + let test := equal a b + let tail := memberByWithWork equal a rest + (test.1 || tail.1, test.2 + tail.2 + 1) + +inductive BinaryMemo (α : Type u_1) where + | empty + | node (value : Option α) (left right : BinaryMemo α) + +def binaryMemoKey : ℕ → ℕ → List Bool + | 0, _ => [] + | d + 1, n => decide (n % 2 = 1) :: binaryMemoKey d (n / 2) + +inductive FiniteQuery (ι : Type u_1) where + | done (value : ℚ) + | read (key : ι) (next : ℚ → FiniteQuery ι) + +def finiteAnswerTable {κ : Type u_1} [DecidableEq κ] : List κ → List ℚ → κ → ℚ + | key :: keys, value :: values, query => + if query = key then value else finiteAnswerTable keys values query + | _, _, _ => 0 + +def queryFinRange (n m : ℕ) (h : n = m) : List (Fin m) := + (List.finRange n).map fun i => ⟨i.val, by simpa only [← h] using i.isLt⟩ + +def queryInsertWithWork {α : Type u_1} (le : α → α → Bool × ℕ) (a : α) : List α → List α × ℕ + | [] => ([a], 1) + | b :: rest => + let test := le a b + if test.1 then (a :: b :: rest, test.2 + 2) + else + let tail := queryInsertWithWork le a rest + (b :: tail.1, test.2 + tail.2 + 2) + +def integerSymbolCode : ℤ → ℕ + | .ofNat n => 2 * n + | .negSucc n => 2 * n + 1 + +inductive PositionCounts where + | empty + | node (count : ℕ) (left right : PositionCounts) + +def integerMagnitude : List ℤ → ℕ + | [] => 0 + | z :: zs => max z.natAbs (integerMagnitude zs) + +def integerInputPositionBits (target : List ℤ) : ℕ := Nat.size target.length + +def dpLength {α : Type u_1} : List α → ℕ × ℕ + | [] => (0, 1) + | _ :: rest => let result := dpLength rest; (result.1 + 1, result.2 + 1) + +def dpDrop {α : Type u_1} : ℕ → List α → List α × ℕ + | 0, word => (word, 1) + | _ + 1, [] => ([], 1) + | n + 1, _ :: rest => let result := dpDrop n rest; (result.1, result.2 + 1) + +def dpTake {α : Type u_1} : ℕ → List α → List α × ℕ + | 0, _ => ([], 1) + | _ + 1, [] => ([], 1) + | n + 1, first :: rest => let result := dpTake n rest; (first :: result.1, result.2 + 1) + +def dpGetD : List ℕ → ℕ → ℕ × ℕ + | [], _ => (0, 1) + | first :: _, 0 => (first, 1) + | _ :: rest, n + 1 => let result := dpGetD rest n; (result.1, result.2 + 1) + +def dpMember {α : Type u_1} [DecidableEq α] (a : α) : List α → Bool × ℕ + | [] => (false, 1) + | first :: rest => if a = first then (true, 1) else + let result := dpMember a rest; (result.1, result.2 + 1) + +def dpMinimum (fallback : ℕ) : List ℕ → ℕ × ℕ + | [] => (fallback, 1) + | first :: rest => let result := dpMinimum fallback rest; (min first result.1, result.2 + 1) + +def integerMagnitudeWithWork : List ℤ → ℕ × ℕ + | [] => (0, 0) + | z :: rest => + let tail := integerMagnitudeWithWork rest + (max z.natAbs tail.1, tail.2 + 2) + +def inputBitLengthWithWork (n : ℕ) : ℕ × ℕ := + if h : n = 0 then (0, 1) else + let tail := inputBitLengthWithWork (n / 2) + (tail.1 + 1, tail.2 + 2) +termination_by n +decreasing_by exact Nat.div_lt_self (by omega) (by decide) + +def naturalPairWithWork (a b : ℕ) : ℕ × ℕ := + if a < b then (b * b + a, 4) else (a * a + a + b, 5) + +def inspectBitPrefix : ℕ → List Bool → Bool × ℕ + | 0, [] => (true, 1) + | 0, _ :: _ => (false, 1) + | _ + 1, [] => (true, 1) + | n + 1, _ :: rest => + let result := inspectBitPrefix n rest + (result.1, result.2 + 1) + +def memoRequestCells (bits addressCells : ℕ) : ℕ := addressCells + 8 * (bits + 1) + 64 + +def arithmeticMapAllocation {α : Type u_1} (allocation : α → ℕ) : List α → ℕ + | [] => 0 + | a :: rest => allocation a + arithmeticMapAllocation allocation rest + 1 + +def arithmeticFlatMapAllocation {α : Type u_1} {β : Type u_2} (f : α → List β × ℕ) + (allocation : α → ℕ) : List α → ℕ + | [] => 0 + | x :: xs => allocation x + arithmeticFlatMapAllocation f allocation xs + (f x).1.length + +def filterAllocation {α : Type u_1} (test : α → Bool × ℕ) (allocation : α → ℕ) : List α → ℕ + | [] => 0 + | x :: xs => allocation x + filterAllocation test allocation xs + if (test x).1 then 1 else 0 + +def filterMapAllocation {α : Type u_1} {β : Type u_2} (f : α → Option β × ℕ) + (allocation : α → ℕ) : List α → ℕ + | [] => 0 + | x :: xs => allocation x + filterMapAllocation f allocation xs + if (f x).1.isSome then 1 else 0 + +def naturalEqualAllocation (a b : ℕ) : ℕ := a.bits.length + b.bits.length + 1 + +def memberByAllocation {α : Type u_1} (allocation : α → α → ℕ) (a : α) : List α → ℕ + | [] => 0 + | b :: rest => allocation a b + memberByAllocation allocation a rest + 1 + +def naturalWordLEAllocation (a b : List Bool) : ℕ := a.length + b.length + 1 + +def vectorMapAllocation (d : ℕ) (allocation : Fin d → ℕ) : ℕ := + (∑ i, allocation i) + 3 * d + +def allAllocation {α : Type u_1} (allocation : α → ℕ) : List α → ℕ + | [] => 0 + | x :: xs => allocation x + allAllocation allocation xs + 1 + +def queryInsertAllocation {α : Type u_1} (le : α → α → Bool × ℕ) + (allocation : α → α → ℕ) (a : α) : List α → ℕ + | [] => 1 + | b :: rest => allocation a b + if (le a b).1 then 2 else queryInsertAllocation le allocation a rest + 1 + +def wordLEAllocation (_a _b : List Bool) : ℕ := 0 + +def indexedLeafAllocation (symbolBits positionBits : ℕ) (symbol : Option ℕ) (lo hi : ℕ) : ℕ := + match symbol with + | none => 1 + | some _ => if lo = hi then 1 else symbolBits + 2 * positionBits + 4 + +def storedNaturalBits (values : List ℕ) : ℕ := + 1 + (values.map fun a => Nat.size a + 1).sum + +def coarseHistoryKeyCost {α : Type u_1} {β : Type u_2} {ι : Type u_3} (cost : ι → ℕ) : Sum α (Sum ι β) → ℕ + | .inr (.inl entry) => cost entry + | _ => 0 + +def bitAddNilLeftWithWork (right : List Bool) (carry : Bool) : List Bool × ℕ := + match right with + | [] => (if carry then [true] else [], 1) + | b :: bs => + let rest := bitAddNilLeftWithWork bs (OAI.EditApproximation.bitCarry false b carry) + (OAI.EditApproximation.bitSum false b carry :: rest.1, rest.2 + 9) +termination_by structural right + +def bitCompareNilLeftWithWork (right : List Bool) : Ordering × ℕ := + match right with + | [] => (.eq, 1) + | b :: bs => + let high := bitCompareNilLeftWithWork bs + (OAI.EditApproximation.bitOrdering high.1 false b, high.2 + 4) +termination_by structural right + +def bitSubtractNilLeftWithWork (right : List Bool) (borrow : Bool) : List Bool × Bool × ℕ := + match right with + | [] => ([], borrow, 1) + | b :: bs => + let rest := bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow) + (OAI.EditApproximation.bitDifference false b borrow :: rest.1, rest.2.1, rest.2.2 + 9) +termination_by structural right + +structure BinaryFraction where + numerator : OAI.EditApproximation.SignedBinary + denominator : List Bool + denominator_pos : 0 < OAI.EditApproximation.bitWordValue denominator + +def rationalActionValue {Parent : Type u_1} {Child : Type u_2} {M : ℕ} + (distance : Parent → Parent → ℚ) (L : ℚ) (child : Child → ℚ) + (query : Parent) (action : OAI.EditApproximation.RationalBellmanAction Parent Child M) : ℚ := + L * distance query action.center + action.connection + ∑ i, child (action.childState i) + +def inputHeight (N : ℕ) : ℕ := 2 ^ OAI.EditApproximation.heightExponent N + +def smallLogExponent (N : ℕ) : ℕ := Nat.clog 2 (max 1 (OAI.EditApproximation.heightExponent N)) + +def rationalParameters (ell : ℕ) : OAI.EditApproximation.RationalParameters := + { F := ell, initialSlope := 32 * ell, coneSlope := 128 * ell, + delta := 1 / (ell : ℚ) ^ 10, kappa := 1 / (ell : ℚ) ^ 4, + tau := 1 / (ell : ℚ) ^ 4, theta := 1 / (ell : ℚ) ^ 40, + gamma := 1 / (ell : ℚ) ^ 20, eta := (ell : ℚ) ^ 5 } + +def materializedAssignmentsWithWork {α : Type u_1} : + (M : ℕ) → (Fin M → List α) → List (Vector α M) × ℕ + | 0, _ => ([Vector.ofFn Fin.elim0], 1) + | M + 1, choices => + let previous := materializedAssignmentsWithWork M (fun i => choices i.succ) + let expanded := OAI.EditApproximation.arithmeticFlatMapWithWork (fun head => + OAI.EditApproximation.arithmeticMapWithWork (fun tail : Vector α M => + (Vector.ofFn (Fin.cons head tail.get), 3 * (M + 1))) previous.1) (choices 0) + (expanded.1, previous.2 + expanded.2 + 1) + +def dyadicScalesWithWork (N : ℕ) : List ℕ × ℕ := + let count := max 1 N.bits.length + let values := OAI.EditApproximation.arithmeticMapWithWork (fun e => + let word := OAI.EditApproximation.powerTwoWord e + (OAI.EditApproximation.bitWordValue word, e + 3)) (List.range count) + (values.1, values.2 + N.bits.length + count + 2) + +def dedupByWithWork {α : Type u_1} (equal : α → α → Bool × ℕ) : List α → List α × ℕ + | [] => ([], 1) + | a :: rest => + let tail := dedupByWithWork equal rest + let member := OAI.EditApproximation.memberByWithWork equal a rest + (if member.1 then tail.1 else a :: tail.1, tail.2 + member.2 + 2) + +def queryEraseLoopWithWork {α : Type u_1} (equal : α → α → Bool × ℕ) : + List α → List α → List α × ℕ + | [], seen => (seen.reverse, seen.length + 1) + | a :: rest, seen => + let test := OAI.EditApproximation.memberByWithWork equal a seen + let tail := queryEraseLoopWithWork equal rest (if test.1 then seen else a :: seen) + (tail.1, test.2 + tail.2 + 2) + +structure RecursiveMemoResult (κ : Type u_1) where + value : ℚ + memory : OAI.EditApproximation.BinaryMemo ℚ + freshKeys : List κ + dictionaryVisits : ℕ + requests : ℕ + +def querySortWithWork {α : Type u_1} (le : α → α → Bool × ℕ) : List α → List α × ℕ + | [] => ([], 1) + | a :: rest => + let tail := querySortWithWork le rest + let inserted := OAI.EditApproximation.queryInsertWithWork le a tail.1 + (inserted.1, tail.2 + inserted.2 + 1) + +def encodeIntegerSymbolsWithWork : List ℤ → List ℕ × ℕ + | [] => ([], 0) + | z :: zs => + let rest := encodeIntegerSymbolsWithWork zs + (OAI.EditApproximation.integerSymbolCode z :: rest.1, rest.2 + 3) + +def integerInputSymbolBits (source target : List ℤ) : ℕ := + Nat.size (2 * OAI.EditApproximation.integerMagnitude (source ++ target)) + +def dpSingleton {α : Type u_1} [DecidableEq α] (a : α) (word : List α) : ℕ × ℕ := + if word = [] then (1, 1) else + let count := OAI.EditApproximation.dpLength word + let found := OAI.EditApproximation.dpMember a word + (count.1 - if found.1 then 1 else 0, count.2 + found.2 + 2) + +def dpCandidateAllocation {α : Type u_1} (target : List α) (j k : ℕ) : ℕ := + (OAI.EditApproximation.dpTake k (OAI.EditApproximation.dpDrop j target).1).1.length + +def integerInputInspectionWithWork (source target : List ℤ) : (ℕ × ℕ) × ℕ := + let left := OAI.EditApproximation.integerMagnitudeWithWork source + let right := OAI.EditApproximation.integerMagnitudeWithWork target + let lengths := (OAI.EditApproximation.dpLength source, OAI.EditApproximation.dpLength target) + let symbols := OAI.EditApproximation.inputBitLengthWithWork (2 * max left.1 right.1) + let positions := OAI.EditApproximation.inputBitLengthWithWork lengths.2.1 + ((symbols.1, positions.1), + left.2 + right.2 + lengths.1.2 + lengths.2.2 + symbols.2 + positions.2 + 4) + +def bitAddNilLeftAllocation (right : List Bool) (carry : Bool) : ℕ := + match right with + | [] => if carry then 1 else 0 + | b :: bs => bitAddNilLeftAllocation bs (OAI.EditApproximation.bitCarry false b carry) + 1 +termination_by structural right + +def bitSubtractNilLeftAllocation (right : List Bool) (borrow : Bool) : ℕ := + match right with + | [] => 0 + | b :: bs => bitSubtractNilLeftAllocation bs (OAI.EditApproximation.bitBorrow false b borrow) + 1 +termination_by structural right + +def trimBitWordAllocation : List Bool → ℕ + | [] => 0 + | bit :: bits => trimBitWordAllocation bits + + if (OAI.EditApproximation.trimBitWordWithWork bits).1 = [] ∧ bit = false then 0 else 1 + +def dedupByAllocation {α : Type u_1} (equal : α → α → Bool × ℕ) + (allocation : α → α → ℕ) : List α → ℕ + | [] => 0 + | a :: rest => dedupByAllocation equal allocation rest + OAI.EditApproximation.memberByAllocation allocation a rest + + if (OAI.EditApproximation.memberByWithWork equal a rest).1 then 0 else 1 + +def dyadicScalesAllocation (N : ℕ) : ℕ := + OAI.EditApproximation.arithmeticMapAllocation (fun e => e + 1) (List.range (max 1 N.bits.length)) + N.bits.length + max 1 N.bits.length + +def queryRangeValidAllocation (B range : ℕ) : ℕ := + (0 : ℕ).bits.length + range.bits.length + OAI.EditApproximation.naturalWordLEAllocation range.bits B.bits + +def queryEraseLoopAllocation {α : Type u_1} (equal : α → α → Bool × ℕ) + (allocation : α → α → ℕ) : List α → List α → ℕ + | [], seen => seen.length + | a :: rest, seen => + OAI.EditApproximation.memberByAllocation allocation a seen + + queryEraseLoopAllocation equal allocation rest (if (OAI.EditApproximation.memberByWithWork equal a seen).1 then seen else a :: seen) + + if (OAI.EditApproximation.memberByWithWork equal a seen).1 then 0 else 1 + +def queryEncodedLEAllocation {α : Type u_1} (code : α → ℕ × ℕ) (allocation : α → ℕ) (a b : α) : ℕ := + allocation a + allocation b + OAI.EditApproximation.naturalWordLEAllocation (code a).1.bits (code b).1.bits + + Nat.size (code a).1 + Nat.size (code b).1 + +def bitAddWithWork (left right : List Bool) (carry : Bool) : List Bool × ℕ := + match left with + | [] => OAI.EditApproximation.bitAddNilLeftWithWork right carry + | a :: as => + match right with + | [] => + let rest := bitAddWithWork as [] (OAI.EditApproximation.bitCarry a false carry) + (OAI.EditApproximation.bitSum a false carry :: rest.1, rest.2 + 9) + | b :: bs => + let rest := bitAddWithWork as bs (OAI.EditApproximation.bitCarry a b carry) + (OAI.EditApproximation.bitSum a b carry :: rest.1, rest.2 + 9) +termination_by structural left + +def bitCompareWithWork (left right : List Bool) : Ordering × ℕ := + match left with + | [] => OAI.EditApproximation.bitCompareNilLeftWithWork right + | a :: as => + match right with + | [] => + let high := bitCompareWithWork as [] + (OAI.EditApproximation.bitOrdering high.1 a false, high.2 + 4) + | b :: bs => + let high := bitCompareWithWork as bs + (OAI.EditApproximation.bitOrdering high.1 a b, high.2 + 4) +termination_by structural left + +def bitSubtractWithWork (left right : List Bool) (borrow : Bool) : List Bool × Bool × ℕ := + match left with + | [] => OAI.EditApproximation.bitSubtractNilLeftWithWork right borrow + | a :: as => + match right with + | [] => + let rest := bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow) + (OAI.EditApproximation.bitDifference a false borrow :: rest.1, rest.2.1, rest.2.2 + 9) + | b :: bs => + let rest := bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow) + (OAI.EditApproximation.bitDifference a b borrow :: rest.1, rest.2.1, rest.2.2 + 9) +termination_by structural left + +def rationalBellman {Parent : Type u_1} {Child : Type u_2} {M : ℕ} + (fallback : Parent → ℚ) (distance : Parent → Parent → ℚ) (L : ℚ) + (actions : List (OAI.EditApproximation.RationalBellmanAction Parent Child M)) (child : Child → ℚ) (query : Parent) : ℚ := + OAI.EditApproximation.rationalMinimum (fallback query) (actions.map (OAI.EditApproximation.rationalActionValue distance L child query)) + +def inputSmallLog (N : ℕ) : ℕ := 2 ^ OAI.EditApproximation.smallLogExponent N + +structure BinaryBellmanAction (Parent : Type u_1) (Child : Type u_2) (M : ℕ) where + center : Parent + connection : OAI.EditApproximation.BinaryFraction + childState : Fin M → Child + +def queryEraseWithWork {α : Type u_1} (equal : α → α → Bool × ℕ) (xs : List α) : + List α × ℕ := OAI.EditApproximation.queryEraseLoopWithWork equal xs [] + +inductive BitQuery (ι : Type u_1) (β : Type u_2) where + | done (value : β) + | read (key : ι) (next : OAI.EditApproximation.BinaryFraction → BitQuery ι β) + | charge (work : ℕ) (next : BitQuery ι β) + +def dpCandidate {α : Type u_1} [DecidableEq α] (a : α) (target : List α) + (previous : List ℕ) (j k : ℕ) : ℕ × ℕ := + let suffix := OAI.EditApproximation.dpDrop j target + let piece := OAI.EditApproximation.dpTake k suffix.1 + let one := OAI.EditApproximation.dpSingleton a piece.1 + let old := OAI.EditApproximation.dpGetD previous (j + k) + (one.1 + old.1, suffix.2 + piece.2 + one.2 + old.2 + 3) + +def dpCellAllocation {α : Type u_1} (target : List α) (j : ℕ) : ℕ := + OAI.EditApproximation.dpCandidateAllocation target j 0 + + ((List.range (target.length - j + 1)).map (OAI.EditApproximation.dpCandidateAllocation target j)).sum + + 4 * (target.length - j + 1) + +def initialThresholdQ (N : ℕ) : ℚ := (OAI.EditApproximation.inputHeight N : ℚ) ^ 4 + +def initialLambda (N : ℕ) : ℚ := 1 / (64 * OAI.EditApproximation.inputHeight N) + +structure BitRecursiveMemoResult (κ : Type u_1) where + value : OAI.EditApproximation.BinaryFraction + memory : OAI.EditApproximation.BinaryMemo OAI.EditApproximation.BinaryFraction + freshKeys : List κ + dictionaryVisits : ℕ + requests : ℕ + localWork : ℕ + +structure RefinementParameterWords where + tau : OAI.EditApproximation.BinaryFraction + factor : OAI.EditApproximation.BinaryFraction + eta : OAI.EditApproximation.BinaryFraction + kappa : OAI.EditApproximation.BinaryFraction + delta : OAI.EditApproximation.BinaryFraction + +def inspectAccuracyWithWork (budget : ℕ) (epsilon : OAI.EditApproximation.BinaryFraction) : Option OAI.EditApproximation.BinaryFraction × ℕ := + let numerator := OAI.EditApproximation.inspectBitPrefix budget epsilon.numerator.bits + let denominator := OAI.EditApproximation.inspectBitPrefix budget epsilon.denominator + (if numerator.1 && denominator.1 then some epsilon else none, + numerator.2 + denominator.2 + 2) + +local instance queryRoundsNeZero (N : ℕ) : NeZero (OAI.EditApproximation.inputHeight N ^ 2) := + ⟨pow_ne_zero _ (Nat.ne_of_gt (Nat.two_pow_pos _))⟩ + +def bitAddAllocation (left right : List Bool) (carry : Bool) : ℕ := + match left with + | [] => OAI.EditApproximation.bitAddNilLeftAllocation right carry + | a :: as => + match right with + | [] => bitAddAllocation as [] (OAI.EditApproximation.bitCarry a false carry) + 1 + | b :: bs => bitAddAllocation as bs (OAI.EditApproximation.bitCarry a b carry) + 1 +termination_by structural left + +def bitSubtractAllocation (left right : List Bool) (borrow : Bool) : ℕ := + match left with + | [] => OAI.EditApproximation.bitSubtractNilLeftAllocation right borrow + | a :: as => + match right with + | [] => bitSubtractAllocation as [] (OAI.EditApproximation.bitBorrow a false borrow) + 1 + | b :: bs => bitSubtractAllocation as bs (OAI.EditApproximation.bitBorrow a b borrow) + 1 +termination_by structural left + +def materializedAssignmentsAllocation {α : Type u_1} : + (M : ℕ) → (Fin M → List α) → ℕ + | 0, _ => 1 + | M + 1, choices => + let previous := (OAI.EditApproximation.materializedAssignmentsWithWork M (fun i => choices i.succ)).1 + let build := fun head => OAI.EditApproximation.arithmeticMapWithWork (fun tail : Vector α M => + (Vector.ofFn (Fin.cons head tail.get), 3 * (M + 1))) previous + materializedAssignmentsAllocation M (fun i => choices i.succ) + + OAI.EditApproximation.arithmeticFlatMapAllocation build + (fun _ => OAI.EditApproximation.arithmeticMapAllocation (fun _ : Vector α M => M + 1) previous) (choices 0) + +def queryEraseAllocation {α : Type u_1} (equal : α → α → Bool × ℕ) + (allocation : α → α → ℕ) (xs : List α) : ℕ := OAI.EditApproximation.queryEraseLoopAllocation equal allocation xs [] + +def querySortAllocation {α : Type u_1} (le : α → α → Bool × ℕ) + (allocation : α → α → ℕ) : List α → ℕ + | [] => 0 + | a :: rest => querySortAllocation le allocation rest + + OAI.EditApproximation.queryInsertAllocation le allocation a (OAI.EditApproximation.querySortWithWork le rest).1 + +def binaryNaturalAddWithWork (a b : ℕ) : List Bool × ℕ := + OAI.EditApproximation.bitAddWithWork a.bits b.bits false + +def bitMulWithWork : List Bool → List Bool → List Bool × ℕ + | [], _ => ([], 1) + | bit :: bits, right => + let rest := bitMulWithWork bits right + if bit then + let total := OAI.EditApproximation.bitAddWithWork (false :: rest.1) right false + (total.1, rest.2 + total.2 + 2) + else (false :: rest.1, rest.2 + 2) + +def binaryNaturalCompareWithWork (a b : ℕ) : Ordering × ℕ := OAI.EditApproximation.bitCompareWithWork a.bits b.bits + +def binaryNaturalSubtractWithWork (a b : ℕ) : List Bool × ℕ := + let result := OAI.EditApproximation.bitSubtractWithWork a.bits b.bits false + (result.1, result.2.2) + +def integerParameters (N : ℕ) : OAI.EditApproximation.IntegerParameters := + let H := OAI.EditApproximation.inputHeight N + let ell := OAI.EditApproximation.inputSmallLog N + let p := OAI.EditApproximation.coarseExponent ell + { H, ell, p, B := H ^ p, initialFactor := H ^ (p + 4), + M := 2 ^ (OAI.EditApproximation.heightExponent N / 20), P := H ^ (p + 20), + T := 2 ^ ((3 * OAI.EditApproximation.heightExponent N + 3) / 4), S := H / ell ^ 2 } + +def bitDivModWithWork (divisor : List Bool) : List Bool → List Bool × List Bool × ℕ + | [] => ([], [], 1) + | bit :: bits => + let previous := bitDivModWithWork divisor bits + let candidate := bit :: previous.2.1 + let comparison := OAI.EditApproximation.bitCompareWithWork candidate divisor + if comparison.1 = .lt then + (false :: previous.1, candidate, previous.2.2 + comparison.2 + 4) + else + let reduced := OAI.EditApproximation.bitSubtractWithWork candidate divisor false + (true :: previous.1, reduced.1, previous.2.2 + comparison.2 + reduced.2.2 + 5) + +def wordLEWithWork (a b : List Bool) : Bool × ℕ := + let compared := OAI.EditApproximation.bitCompareWithWork b a + (!(decide (compared.1 = .lt)), compared.2 + 1) + +def computedSeedInitialExponent (N : ℕ) : ℕ := + (OAI.EditApproximation.coarseExponent (OAI.EditApproximation.inputSmallLog N) + 4) * OAI.EditApproximation.heightExponent N + +def queryOrderedInputsWithWork {α : Type u_1} (equal le : α → α → Bool × ℕ) + (xs : List α) : List α × ℕ := + let unique := OAI.EditApproximation.queryEraseWithWork equal xs + let sorted := OAI.EditApproximation.querySortWithWork le unique.1 + (sorted.1, unique.2 + sorted.2 + 1) + +def queryActionInputsWithWork {Parent : Type u_1} {Child : Type u_2} {M : ℕ} + (actions : List (OAI.EditApproximation.BinaryBellmanAction Parent Child M)) : List Child × ℕ := + let inputs := OAI.EditApproximation.arithmeticFlatMapWithWork (fun action => + OAI.EditApproximation.arithmeticMapWithWork (fun i : Fin M => (action.childState i, 1)) (List.finRange M)) actions + (inputs.1, inputs.2 + M + 1) + +def largeAccuracyInput (N : ℕ) (epsilon : ℚ) : Prop := + 2 ^ 1000 ≤ OAI.EditApproximation.inputSmallLog N ∧ 10 ≤ (OAI.EditApproximation.inputSmallLog N : ℚ) * epsilon + +def dpCell {α : Type u_1} [DecidableEq α] (a : α) (target : List α) + (previous : List ℕ) (j : ℕ) : ℕ × ℕ := + let fallback := OAI.EditApproximation.dpCandidate a target previous j 0 + let candidates := (List.range (target.length - j + 1)).map (OAI.EditApproximation.dpCandidate a target previous j) + let minimum := OAI.EditApproximation.dpMinimum fallback.1 (candidates.map Prod.fst) + (minimum.1, fallback.2 + (candidates.map Prod.snd).sum + minimum.2 + + (OAI.EditApproximation.dpLength target).2 + 3 * candidates.length + 4) + +def suffixDPAllocation {α : Type u_1} : List α → List α → ℕ + | [], target => target.length + 1 + | _ :: rest, target => suffixDPAllocation rest target + + (List.ofFn fun j : Fin (target.length + 1) => OAI.EditApproximation.dpCellAllocation target j.val).sum + + 3 * (target.length + 1) + +def binaryNaturalAddAllocation (a b : ℕ) : ℕ := OAI.EditApproximation.bitAddAllocation a.bits b.bits false + +def queryOrderedInputsAllocation {α : Type u_1} (equal le : α → α → Bool × ℕ) + (equalAllocation leAllocation : α → α → ℕ) (xs : List α) : ℕ := + OAI.EditApproximation.queryEraseAllocation equal equalAllocation xs + + OAI.EditApproximation.querySortAllocation le leAllocation (OAI.EditApproximation.queryEraseWithWork equal xs).1 + +def queryActionInputsAllocation {Parent : Type u_1} {Child : Type u_2} {M : ℕ} + (actions : List (OAI.EditApproximation.BinaryBellmanAction Parent Child M)) : ℕ := + OAI.EditApproximation.arithmeticFlatMapAllocation (fun action => + OAI.EditApproximation.arithmeticMapWithWork (fun i : Fin M => (action.childState i, 1)) (List.finRange M)) + (fun _ => OAI.EditApproximation.arithmeticMapAllocation (fun _ : Fin M => 1) (List.finRange M) + M) actions + +def binaryNaturalMulWithWork (a b : ℕ) : List Bool × ℕ := OAI.EditApproximation.bitMulWithWork a.bits b.bits + +def binaryNaturalDivModWithWork (n d : ℕ) : List Bool × List Bool × ℕ := + OAI.EditApproximation.bitDivModWithWork d.bits n.bits + +def bitCeilDivWithWork (divisor bits : List Bool) : List Bool × ℕ := + let divided := OAI.EditApproximation.bitDivModWithWork divisor bits + let zeroCheck := OAI.EditApproximation.bitCompareWithWork divided.2.1 [] + if zeroCheck.1 = .eq then (divided.1, divided.2.2 + zeroCheck.2 + 3) + else + let rounded := OAI.EditApproximation.bitAddWithWork divided.1 [true] false + (rounded.1, divided.2.2 + zeroCheck.2 + rounded.2 + 3) + +def wordMinWithWork (a b : List Bool) : List Bool × ℕ := + let compared := OAI.EditApproximation.wordLEWithWork a b + (if compared.1 then a else b, compared.2 + 1) + +def wordInsertWithWork (a : List Bool) : List (List Bool) → List (List Bool) × ℕ + | [] => ([a], 1) + | b :: rest => + let compared := OAI.EditApproximation.wordLEWithWork a b + if compared.1 then (a :: b :: rest, compared.2 + 2) else + let tail := wordInsertWithWork a rest + (b :: tail.1, compared.2 + tail.2 + 2) + +def saturatingSubtractWithWork (a b : ℕ) : List Bool × ℕ := + let test := OAI.EditApproximation.binaryNaturalCompareWithWork a b + if test.1 = .lt then ([], test.2 + 1) else + let result := OAI.EditApproximation.binaryNaturalSubtractWithWork a b + (result.1, test.2 + result.2 + 2) + +def computedSeedPassCount (N : ℕ) : ℕ := + OAI.EditApproximation.dyadicSeedPassCount (OAI.EditApproximation.smallLogExponent N) (OAI.EditApproximation.computedSeedInitialExponent N) + +def bitPowerWithWork (base : List Bool) : ℕ → List Bool × ℕ + | 0 => ([true], 1) + | n + 1 => + let previous := bitPowerWithWork base n + let product := OAI.EditApproximation.bitMulWithWork previous.1 base + let answer := OAI.EditApproximation.trimBitWordWithWork product.1 + (answer.1, previous.2 + product.2 + answer.2 + 2) + +def queryEncodedLEWithWork {α : Type u_1} (code : α → ℕ × ℕ) (a b : α) : Bool × ℕ := + let left := code a + let right := code b + let comparison := OAI.EditApproximation.wordLEWithWork left.1.bits right.1.bits + (comparison.1, left.2 + right.2 + comparison.2 + Nat.size left.1 + Nat.size right.1 + 3) + +instance largeAccuracyInput_decidable (N : ℕ) (epsilon : ℚ) : Decidable (OAI.EditApproximation.largeAccuracyInput N epsilon) := + inferInstanceAs (Decidable (2 ^ 1000 ≤ OAI.EditApproximation.inputSmallLog N ∧ 10 ≤ (OAI.EditApproximation.inputSmallLog N : ℚ) * epsilon)) + +def chargedSuffixDP {α : Type u_1} [DecidableEq α] : List α → List α → List ℕ × ℕ + | [], target => + (List.ofFn (fun j : Fin (target.length + 1) => target.length - j.val), + 4 * (target.length + 1)) + | a :: rest, target => + let previous := chargedSuffixDP rest target + let cells := List.ofFn fun j : Fin (target.length + 1) => OAI.EditApproximation.dpCell a target previous.1 j.val + (cells.map Prod.fst, previous.2 + (cells.map Prod.snd).sum + + 2 * (OAI.EditApproximation.dpLength target).2 + 2 * cells.length + 3) + +def computedCoarseDepth (N n : ℕ) : ℕ := Nat.clog (OAI.EditApproximation.integerParameters N).B (max 1 n) + +def queryRangeValidWithWork (B range : ℕ) : Bool × ℕ := + let positive := OAI.EditApproximation.binaryNaturalCompareWithWork 0 range + let bounded := OAI.EditApproximation.wordLEWithWork range.bits B.bits + (decide (positive.1 = .lt) && bounded.1, positive.2 + bounded.2 + 2) + +def coarsePaddedReadWithWork {α : Type u_1} (n : ℕ) (source : List α) (offset : ℕ) : + Option (Option α) × ℕ := + let inside := OAI.EditApproximation.binaryNaturalCompareWithWork offset n + (if inside.1 = .lt then some source[offset]? else none, + inside.2 + Nat.size n + Nat.size offset + 2) + +def coarseRangeCopyWithWork (read : ℕ → ℕ) : ℕ → ℕ → List ℕ × ℕ + | _, 0 => ([], 1) + | start, length + 1 => + let next := OAI.EditApproximation.binaryNaturalAddWithWork start 1 + let tail := coarseRangeCopyWithWork read (OAI.EditApproximation.bitWordValue next.1) length + (read start :: tail.1, tail.2 + next.2 + Nat.size start + Nat.size (read start) + 3) + +def bitMulAllocation : List Bool → List Bool → ℕ + | [], _ => 0 + | bit :: bits, right => + bitMulAllocation bits right + 1 + + if bit then OAI.EditApproximation.bitAddAllocation (false :: (OAI.EditApproximation.bitMulWithWork bits right).1) right false else 0 + +def bitDivModAllocation (divisor : List Bool) : List Bool → ℕ + | [] => 0 + | bit :: bits => + let candidate := bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 + bitDivModAllocation divisor bits + 2 + + if (OAI.EditApproximation.bitCompareWithWork candidate divisor).1 = .lt then 0 + else OAI.EditApproximation.bitSubtractAllocation candidate divisor false + +def saturatingSubtractAllocation (a b : ℕ) : ℕ := + a.bits.length + b.bits.length + + if (OAI.EditApproximation.binaryNaturalCompareWithWork a b).1 = .lt then 0 else OAI.EditApproximation.bitSubtractAllocation a.bits b.bits false + +def makeStateAllocation (n lo hi : ℕ) : ℕ := + OAI.EditApproximation.naturalWordLEAllocation lo.bits hi.bits + OAI.EditApproximation.naturalWordLEAllocation hi.bits n.bits + + if ((OAI.EditApproximation.wordLEWithWork lo.bits hi.bits).1 && (OAI.EditApproximation.wordLEWithWork hi.bits n.bits).1) = true then 2 else 0 + +def translatedEndpointAllocation (reference root endpoint : ℕ) : ℕ := + OAI.EditApproximation.bitSubtractAllocation endpoint.bits root.bits false + + OAI.EditApproximation.binaryNaturalAddAllocation reference (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalSubtractWithWork endpoint root).1) + +def wordInsertAllocation (a : List Bool) : List (List Bool) → ℕ + | [] => 1 + | b :: rest => OAI.EditApproximation.wordLEAllocation a b + + if (OAI.EditApproximation.wordLEWithWork a b).1 then 2 else wordInsertAllocation a rest + 1 + +def wordSortWithWork : List (List Bool) → List (List Bool) × ℕ + | [] => ([], 1) + | a :: rest => + let tail := wordSortWithWork rest + let inserted := OAI.EditApproximation.wordInsertWithWork a tail.1 + (inserted.1, tail.2 + inserted.2 + 2) + +def binaryGridRoundWithWork (spacing position : ℕ) : List Bool × ℕ := + let quotient := OAI.EditApproximation.binaryNaturalDivModWithWork position spacing + let rounded := OAI.EditApproximation.bitMulWithWork spacing.bits quotient.1 + (rounded.1, quotient.2.2 + rounded.2 + 2) + +def gridPointsWithWork (g lo hi : ℕ) : List ℕ × ℕ := + let lower := OAI.EditApproximation.bitCeilDivWithWork g.bits lo.bits + let upper := OAI.EditApproximation.binaryNaturalDivModWithWork hi g + let stop := OAI.EditApproximation.binaryNaturalAddWithWork (OAI.EditApproximation.bitWordValue upper.1) 1 + let count := OAI.EditApproximation.saturatingSubtractWithWork (OAI.EditApproximation.bitWordValue stop.1) (OAI.EditApproximation.bitWordValue lower.1) + let indices := List.range' (OAI.EditApproximation.bitWordValue lower.1) (OAI.EditApproximation.bitWordValue count.1) + let points := OAI.EditApproximation.arithmeticMapWithWork (fun i => + let product := OAI.EditApproximation.binaryNaturalMulWithWork g i + (OAI.EditApproximation.bitWordValue product.1, product.2 + Nat.size i + 2)) indices + (points.1, lower.2 + upper.2.2 + stop.2 + count.2 + points.2 + + Nat.size g + Nat.size lo + Nat.size hi + 5) + +def seedGridSpacingWithWork (b P : ℕ) : List Bool × ℕ := + let quotient := OAI.EditApproximation.binaryNaturalDivModWithWork b P + let test := OAI.EditApproximation.wordLEWithWork quotient.1 [true] + (if test.1 then [true] else quotient.1, quotient.2.2 + test.2 + 2) + +def balancedCutWithWork (lo width M i : ℕ) : List Bool × ℕ := + let product := OAI.EditApproximation.binaryNaturalMulWithWork i width + let quotient := OAI.EditApproximation.binaryNaturalDivModWithWork (OAI.EditApproximation.bitWordValue product.1) M + let result := OAI.EditApproximation.binaryNaturalAddWithWork lo (OAI.EditApproximation.bitWordValue quotient.1) + (result.1, product.2 + quotient.2.2 + result.2 + 2) + +def triangularMassWithWork (K : ℕ) : List Bool × ℕ := + let next := OAI.EditApproximation.binaryNaturalAddWithWork K 1 + let product := OAI.EditApproximation.binaryNaturalMulWithWork K (OAI.EditApproximation.bitWordValue next.1) + let quotient := OAI.EditApproximation.binaryNaturalDivModWithWork (OAI.EditApproximation.bitWordValue product.1) 2 + (quotient.1, next.2 + product.2 + quotient.2.2 + 3) + +def refinementBaseWithWork (ell : List Bool) : List Bool × ℕ := + let power := OAI.EditApproximation.bitPowerWithWork ell 10 + let increment := OAI.EditApproximation.bitAddWithWork power.1 [true] false + let result := OAI.EditApproximation.trimBitWordWithWork increment.1 + (result.1, power.2 + increment.2 + result.2 + 2) + +def queryPairWithWork (a b : ℕ) : ℕ × ℕ := + let test := OAI.EditApproximation.binaryNaturalCompareWithWork a b + if test.1 = .lt then + let square := OAI.EditApproximation.binaryNaturalMulWithWork b b + let result := OAI.EditApproximation.binaryNaturalAddWithWork (OAI.EditApproximation.bitWordValue square.1) a + (OAI.EditApproximation.bitWordValue result.1, test.2 + square.2 + result.2 + 3) + else + let square := OAI.EditApproximation.binaryNaturalMulWithWork a a + let linear := OAI.EditApproximation.binaryNaturalAddWithWork (OAI.EditApproximation.bitWordValue square.1) a + let result := OAI.EditApproximation.binaryNaturalAddWithWork (OAI.EditApproximation.bitWordValue linear.1) b + (OAI.EditApproximation.bitWordValue result.1, test.2 + square.2 + linear.2 + result.2 + 4) + +def queryCellValidWithWork (n exponent : ℕ) (cell : ℕ × ℕ) : Bool × ℕ := + let cap := OAI.EditApproximation.binaryNaturalMulWithWork n (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.powerTwoWord exponent)) + let left := OAI.EditApproximation.wordLEWithWork cell.1.bits cap.1 + let right := OAI.EditApproximation.wordLEWithWork cell.2.bits cap.1 + (left.1 && right.1, cap.2 + left.2 + right.2 + exponent + 4) + +def queryFinOfNatWithWork (bound value : ℕ) (hb : 0 < bound) : Fin bound × ℕ := by + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_bitSubtractor_value_17 (a : Bool) (b : Bool) (borrow : Bool) : + a.toNat + 2 * (OAI.EditApproximation.bitBorrow a b borrow).toNat = + b.toNat + borrow.toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat := by + cases a <;> cases b <;> cases borrow <;> decide + have proof_bitSubtractionRippleEquation_18 (a : ℕ) (b : ℕ) (borrow : ℕ) (nextBorrow : ℕ) (difference : ℕ) (left : ℕ) (right : ℕ) (result : ℕ) (tail : ℕ) (htail : Eq.{1} (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} result right) nextBorrow) (HAdd.hAdd.{0, 0, 0} left tail)) (hbit : Eq.{1} (HAdd.hAdd.{0, 0, 0} a (HMul.hMul.{0, 0, 0} 2 nextBorrow)) + (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} b borrow) difference)) : + (difference + 2 * result) + (b + 2 * right) + borrow = + (a + 2 * left) + 2 * tail := by + omega + have proof_bitSubtractWithWork_value_19 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right borrow).1 + OAI.EditApproximation.bitWordValue right + borrow.toNat = + OAI.EditApproximation.bitWordValue left + 2 ^ max left.length right.length * + (OAI.EditApproximation.bitSubtractWithWork left right borrow).2.1.toNat := by + induction left generalizing right borrow with + | nil => + induction right generalizing borrow with + | nil => (simp [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + have h := ih (OAI.EditApproximation.bitBorrow false b borrow) + have hb := proof_bitSubtractor_value_17 false b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue, + List.length_nil, List.length_cons, Nat.zero_max, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 0 b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow false b borrow).toNat + (OAI.EditApproximation.bitDifference false b borrow).toNat 0 (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).1) + (2 ^ bs.length * (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons a as ih => + cases right with + | nil => + have h := ih [] (OAI.EditApproximation.bitBorrow a false borrow) + have hb := proof_bitSubtractor_value_17 a false borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_nil, List.length_cons, + Nat.max_zero, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat 0 borrow.toNat (OAI.EditApproximation.bitBorrow a false borrow).toNat + (OAI.EditApproximation.bitDifference a false borrow).toNat (OAI.EditApproximation.bitWordValue as) 0 + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).1) + (2 ^ as.length * (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons b bs => + have h := ih bs (OAI.EditApproximation.bitBorrow a b borrow) + have hb := proof_bitSubtractor_value_17 a b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_cons, Nat.succ_max_succ, + pow_succ] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow a b borrow).toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).1) + (2 ^ max as.length bs.length * (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_assoc, Nat.mul_left_comm] using hs + have proof_bitWordValue_lt_pow_length_20 (bits : List.{0} Bool) : OAI.EditApproximation.bitWordValue bits < 2 ^ bits.length := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitWordValue]) + | cons bit bits ih => + cases bit <;> (simp only [OAI.EditApproximation.bitWordValue, List.length_cons, pow_succ, Bool.toNat_false, Bool.toNat_true]) <;> omega + have proof_bitSubtractWithWork_length_21 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + (OAI.EditApproximation.bitSubtractWithWork left right borrow).1.length = max left.length right.length := by + induction left generalizing right borrow with + | nil => + simp only [OAI.EditApproximation.bitSubtractWithWork] + induction right generalizing borrow with + | nil => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork] + | cons b bs ih => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork, ih] + | cons a as ih => + cases right with + | nil => simp [OAI.EditApproximation.bitSubtractWithWork, ih] + | cons b bs => simp [OAI.EditApproximation.bitSubtractWithWork, ih, Nat.succ_max_succ] + have proof_bitSubtractWithWork_sub_22 (left : List.{0} Bool) (right : List.{0} Bool) (h : LE.le.{0} (OAI.EditApproximation.bitWordValue right) (OAI.EditApproximation.bitWordValue left)) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right false).1 = OAI.EditApproximation.bitWordValue left - OAI.EditApproximation.bitWordValue right := by + have hvalue := proof_bitSubtractWithWork_value_19 left right false + have hlt := proof_bitWordValue_lt_pow_length_20 (OAI.EditApproximation.bitSubtractWithWork left right false).1 + rw [proof_bitSubtractWithWork_length_21] at hlt + cases hb : (OAI.EditApproximation.bitSubtractWithWork left right false).2.1 + · simp only [hb, Bool.toNat_false, Nat.mul_zero, Nat.add_zero] at hvalue + omega + · simp only [hb, Bool.toNat_true, Bool.toNat_false, Nat.mul_one, Nat.add_zero] at hvalue + omega + have proof_bitDivModWithWork_value_23 (divisor : List.{0} Bool) (bits : List.{0} Bool) (hd : LT.lt.{0} 0 (OAI.EditApproximation.bitWordValue divisor)) : + OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).1 + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 < OAI.EditApproximation.bitWordValue divisor := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitDivModWithWork, OAI.EditApproximation.bitWordValue, hd]) + | cons bit bits ih => + let previous := OAI.EditApproximation.bitDivModWithWork divisor bits + let candidate := bit :: previous.2.1 + have hp : OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue previous.1 + + OAI.EditApproximation.bitWordValue previous.2.1 := ih.1 + have hr : OAI.EditApproximation.bitWordValue previous.2.1 < OAI.EditApproximation.bitWordValue divisor := ih.2 + have hc : OAI.EditApproximation.bitWordValue candidate < 2 * OAI.EditApproximation.bitWordValue divisor := by + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + cases bit <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega + by_cases hlt : (OAI.EditApproximation.bitCompareWithWork candidate divisor).1 = .lt + · have hv := (proof_bitCompareWithWork_lt_16 candidate divisor).1 hlt + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 = .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * + OAI.EditApproximation.bitWordValue (false :: previous.1) + OAI.EditApproximation.bitWordValue candidate ∧ OAI.EditApproximation.bitWordValue candidate < _ + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_false]) + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + nlinarith only [hp] + · exact hv + · have hv : OAI.EditApproximation.bitWordValue divisor ≤ OAI.EditApproximation.bitWordValue candidate := by + exact Nat.le_of_not_gt (fun h => hlt ((proof_bitCompareWithWork_lt_16 candidate divisor).2 h)) + have hs := proof_bitSubtractWithWork_sub_22 candidate divisor hv + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 ≠ .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (true :: previous.1) + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 < _ + rw [hs] + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_true]) + have he := Nat.sub_add_cancel hv + dsimp only [candidate, OAI.EditApproximation.bitWordValue] at he ⊢ + nlinarith only [hp, he] + · omega + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_binaryNaturalDivModWithWork_spec_24 (n : ℕ) (d : ℕ) (hd : LT.lt.{0} 0 d) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalDivModWithWork n d).1 = n / d ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalDivModWithWork n d).2.1 = n % d := by + have h := proof_bitDivModWithWork_value_23 d.bits n.bits (by simpa only [proof_bitWordValue_bits_15] using hd) + simp only [proof_bitWordValue_bits_15] at h + have hmod : n % d = OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork d.bits n.bits).2.1 := by + conv_lhs => rw [h.1] + simp only [Nat.add_mod, Nat.mul_mod_right, Nat.zero_add, Nat.mod_eq_of_lt h.2] + have hdiv : n / d = OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork d.bits n.bits).1 := by + conv_lhs => rw [h.1] + rw [Nat.mul_add_div hd, Nat.div_eq_of_lt h.2, Nat.add_zero] + exact ⟨hdiv.symm, hmod.symm⟩ + exact + let result := OAI.EditApproximation.binaryNaturalDivModWithWork value bound + (⟨OAI.EditApproximation.bitWordValue result.2.1, by + rw [(proof_binaryNaturalDivModWithWork_spec_24 value bound hb).2] + exact Nat.mod_lt value hb⟩, result.2.2 + 1) + +def coarseDenominatorWithWork (allowanceDen q L branching : List Bool) (D : ℕ) : + List Bool × ℕ := + let first := OAI.EditApproximation.bitMulWithWork L branching + let base := OAI.EditApproximation.bitMulWithWork first.1 q + let trimmedBase := OAI.EditApproximation.trimBitWordWithWork base.1 + let power := OAI.EditApproximation.bitPowerWithWork trimmedBase.1 D + let initial := OAI.EditApproximation.bitMulWithWork allowanceDen q + let product := OAI.EditApproximation.bitMulWithWork initial.1 power.1 + let result := OAI.EditApproximation.trimBitWordWithWork product.1 + (result.1, first.2 + base.2 + trimmedBase.2 + power.2 + initial.2 + product.2 + result.2 + 7) + +def coarseFramedReadWithWork {α : Type u_1} (k n : ℕ) (word : List α) (i : ℕ) : + Option (Option α) × ℕ := + let lower := OAI.EditApproximation.binaryNaturalCompareWithWork i k + if lower.1 = .lt then (none, lower.2 + Nat.size k + Nat.size n + Nat.size i + 2) else + let finish := OAI.EditApproximation.binaryNaturalAddWithWork k n + let upper := OAI.EditApproximation.binaryNaturalCompareWithWork i (OAI.EditApproximation.bitWordValue finish.1) + if upper.1 = .lt then + let offset := OAI.EditApproximation.saturatingSubtractWithWork i k + (some word[OAI.EditApproximation.bitWordValue offset.1]?, lower.2 + finish.2 + upper.2 + offset.2 + + Nat.size k + Nat.size n + Nat.size i + 4) + else (none, lower.2 + finish.2 + upper.2 + Nat.size k + Nat.size n + Nat.size i + 3) + +def coarseDescriptorWithWork (B d n start : ℕ) : List Bool × ℕ := + let capacity := OAI.EditApproximation.bitPowerWithWork B.bits d + let remaining := OAI.EditApproximation.saturatingSubtractWithWork n start + let clipped := OAI.EditApproximation.wordMinWithWork capacity.1 remaining.1 + (clipped.1, capacity.2 + remaining.2 + clipped.2 + + Nat.size B + Nat.size d + Nat.size n + Nat.size start + 4) + +def coarseChildOffsetWithWork (offset capacity index : ℕ) : List Bool × ℕ := + let displacement := OAI.EditApproximation.binaryNaturalMulWithWork index capacity + let result := OAI.EditApproximation.binaryNaturalAddWithWork offset (OAI.EditApproximation.bitWordValue displacement.1) + (result.1, displacement.2 + result.2 + Nat.size index + Nat.size capacity + Nat.size offset + 3) + +def coarseInputGuardWithWork (sourceLo sourceHi targetLo targetHi : ℕ) : Bool × ℕ := + let sourceWidth := OAI.EditApproximation.saturatingSubtractWithWork sourceHi sourceLo + let targetWidth := OAI.EditApproximation.saturatingSubtractWithWork targetHi targetLo + let twice := OAI.EditApproximation.binaryNaturalMulWithWork 2 (OAI.EditApproximation.bitWordValue sourceWidth.1) + let compared := OAI.EditApproximation.binaryNaturalCompareWithWork (OAI.EditApproximation.bitWordValue twice.1) (OAI.EditApproximation.bitWordValue targetWidth.1) + (decide (compared.1 = .lt), sourceWidth.2 + targetWidth.2 + twice.2 + compared.2 + 6) + +def bitPowerAllocation (base : List Bool) : ℕ → ℕ + | 0 => 1 + | n + 1 => + let previous := (OAI.EditApproximation.bitPowerWithWork base n).1 + bitPowerAllocation base n + OAI.EditApproximation.bitMulAllocation previous base + + OAI.EditApproximation.trimBitWordAllocation (OAI.EditApproximation.bitMulWithWork previous base).1 + +def bitCeilDivAllocation (divisor bits : List Bool) : ℕ := + let divided := OAI.EditApproximation.bitDivModWithWork divisor bits + OAI.EditApproximation.bitDivModAllocation divisor bits + + if (OAI.EditApproximation.bitCompareWithWork divided.2.1 []).1 = .eq then 0 + else 1 + OAI.EditApproximation.bitAddAllocation divided.1 [true] false + +def binaryNaturalMulAllocation (a b : ℕ) : ℕ := OAI.EditApproximation.bitMulAllocation a.bits b.bits + +def binaryNaturalDivAllocation (a b : ℕ) : ℕ := OAI.EditApproximation.bitDivModAllocation b.bits a.bits + +def triangularMassAllocation (K : ℕ) : ℕ := + let next := (OAI.EditApproximation.binaryNaturalAddWithWork K 1).1 + let product := (OAI.EditApproximation.binaryNaturalMulWithWork K (OAI.EditApproximation.bitWordValue next)).1 + OAI.EditApproximation.bitAddAllocation K.bits (1 : ℕ).bits false + + OAI.EditApproximation.bitMulAllocation K.bits (OAI.EditApproximation.bitWordValue next).bits + + OAI.EditApproximation.bitDivModAllocation (2 : ℕ).bits (OAI.EditApproximation.bitWordValue product).bits + +def binaryIntervalRoundWithWork (spacing lo hi : ℕ) : (List Bool × List Bool) × ℕ := + let left := OAI.EditApproximation.binaryGridRoundWithWork spacing lo + let right := OAI.EditApproximation.binaryGridRoundWithWork spacing hi + ((left.1, right.1), left.2 + right.2 + 1) + +def computedQueryBase (N : ℕ) : List Bool := + (OAI.EditApproximation.refinementBaseWithWork (OAI.EditApproximation.inputSmallLog N).bits).1 + +def coarsePreparedSlicesWithWork (source target : List ℕ) + (sourceLo sourceHi targetLo targetHi : ℕ) : Option (List ℕ × List ℕ) × ℕ := + let guard := OAI.EditApproximation.coarseInputGuardWithWork sourceLo sourceHi targetLo targetHi + if guard.1 then (none, guard.2) else + let copiedSource := OAI.EditApproximation.coarseRangeCopyWithWork (fun i => source[i]?.getD 0) sourceLo (sourceHi - sourceLo) + let copiedTarget := OAI.EditApproximation.coarseRangeCopyWithWork (fun i => target[i]?.getD 0) targetLo (targetHi - targetLo) + (some (copiedSource.1, copiedTarget.1), guard.2 + copiedSource.2 + copiedTarget.2) + +def gridPointsAllocation (g lo hi : ℕ) : ℕ := + let lower := (OAI.EditApproximation.bitCeilDivWithWork g.bits lo.bits).1 + let upper := (OAI.EditApproximation.binaryNaturalDivModWithWork hi g).1 + let stop := (OAI.EditApproximation.binaryNaturalAddWithWork (OAI.EditApproximation.bitWordValue upper) 1).1 + let count := (OAI.EditApproximation.saturatingSubtractWithWork (OAI.EditApproximation.bitWordValue stop) (OAI.EditApproximation.bitWordValue lower)).1 + let indices := List.range' (OAI.EditApproximation.bitWordValue lower) (OAI.EditApproximation.bitWordValue count) + OAI.EditApproximation.bitCeilDivAllocation g.bits lo.bits + OAI.EditApproximation.binaryNaturalDivAllocation hi g + + OAI.EditApproximation.binaryNaturalAddAllocation (OAI.EditApproximation.bitWordValue upper) 1 + + OAI.EditApproximation.saturatingSubtractAllocation (OAI.EditApproximation.bitWordValue stop) (OAI.EditApproximation.bitWordValue lower) + + indices.length + OAI.EditApproximation.arithmeticMapAllocation (fun i => OAI.EditApproximation.binaryNaturalMulAllocation g i) indices + +def balancedCutAllocation (lo width M i : ℕ) : ℕ := + let product := (OAI.EditApproximation.binaryNaturalMulWithWork i width).1 + let quotient := (OAI.EditApproximation.binaryNaturalDivModWithWork (OAI.EditApproximation.bitWordValue product) M).1 + OAI.EditApproximation.binaryNaturalMulAllocation i width + OAI.EditApproximation.binaryNaturalDivAllocation (OAI.EditApproximation.bitWordValue product) M + + OAI.EditApproximation.binaryNaturalAddAllocation lo (OAI.EditApproximation.bitWordValue quotient) + +def seedGridSpacingAllocation (b P : ℕ) : ℕ := + OAI.EditApproximation.binaryNaturalDivAllocation b P + OAI.EditApproximation.naturalWordLEAllocation (OAI.EditApproximation.binaryNaturalDivModWithWork b P).1 [true] + 1 + +def queryCellValidAllocation (n exponent : ℕ) (cell : ℕ × ℕ) : ℕ := + let cap := (OAI.EditApproximation.binaryNaturalMulWithWork n (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.powerTwoWord exponent))).1 + OAI.EditApproximation.binaryNaturalMulAllocation n (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.powerTwoWord exponent)) + + OAI.EditApproximation.naturalWordLEAllocation cell.1.bits cap + OAI.EditApproximation.naturalWordLEAllocation cell.2.bits cap + exponent + 1 + +def queryPairAllocation (a b : ℕ) : ℕ := + a.bits.length + b.bits.length + + if (OAI.EditApproximation.binaryNaturalCompareWithWork a b).1 = .lt then + OAI.EditApproximation.binaryNaturalMulAllocation b b + OAI.EditApproximation.binaryNaturalAddAllocation (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalMulWithWork b b).1) a + else + OAI.EditApproximation.binaryNaturalMulAllocation a a + OAI.EditApproximation.binaryNaturalAddAllocation (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalMulWithWork a a).1) a + + OAI.EditApproximation.binaryNaturalAddAllocation + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalAddWithWork (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalMulWithWork a a).1) a).1) b + +def binaryGridRoundAllocation (spacing position : ℕ) : ℕ := + OAI.EditApproximation.binaryNaturalDivAllocation position spacing + + OAI.EditApproximation.bitMulAllocation spacing.bits (OAI.EditApproximation.binaryNaturalDivModWithWork position spacing).1 + +def wordSortAllocation : List (List Bool) → ℕ + | [] => 0 + | a :: rest => wordSortAllocation rest + + OAI.EditApproximation.wordInsertAllocation a (OAI.EditApproximation.wordSortWithWork rest).1 + 0 + +def reduceOnlineIntegerAllocation (K integer : ℕ) : ℕ := + OAI.EditApproximation.triangularMassAllocation K + + OAI.EditApproximation.bitDivModAllocation (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.triangularMassWithWork K).1).bits integer.bits + Nat.size integer + +def coarsePreparedInputStorage (source target : List ℕ) + (sourceLo sourceHi targetLo targetHi : ℕ) : ℕ := + match (OAI.EditApproximation.coarsePreparedSlicesWithWork source target sourceLo sourceHi targetLo targetHi).1 with + | none => 1 + | some (x, y) => 1 + OAI.EditApproximation.storedNaturalBits x + OAI.EditApproximation.storedNaturalBits y + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open Finset + +def optimizerTriangularMass (K : ℕ) : ℕ := ∑ j ∈ range K, (j + 1) + +def rationalLogApproximation (r : ℚ) (K : ℕ) : ℚ := + 2 * ∑ k ∈ range K, (((r - 1) / (r + 1)) ^ (2 * k + 1) / (2 * k + 1)) + +def rationalLinearizationMaximizer {ι : Type u_1} (coordinates : Finset ι) + (vertices : List (ι → ℚ)) (gradient : ι → ℚ) : ι → ℚ := + (vertices.argmax fun p => ∑ i ∈ coordinates, gradient i * p i).getD (fun _ => 0) + +def bandCoordinates {β : Type u_1} {σ : Type u_2} [Fintype β] [DecidableEq β] [DecidableEq σ] + (band : Finset (β → σ)) : Finset (β × σ) := + band.biUnion fun action => univ.image fun child => (child, action child) + +def actionVector {β : Type u_1} {σ : Type u_2} [Fintype β] [DecidableEq σ] + (mass : β → ℚ) (action : β → σ) (coordinate : β × σ) : ℚ := + if coordinate.2 = action coordinate.1 then mass coordinate.1 / (∑ child, mass child) else 0 + +def rationalOptimisticHistory {ι : Type u_1} (κ : ℚ) + (gain decrement : ℕ → ι → ℚ) (t : ℕ) (i : ι) : ℚ := + ∑ j ∈ range t, (gain j i + (1 - 2 * κ) * decrement j i) + +def rejectionBitCount (N : ℕ) : ℕ := Nat.clog 2 N + +def vectorMapWithWork {α : Type u_1} (d : ℕ) (f : Fin d → α × ℕ) : Vector α d × ℕ := + let cells := Vector.ofFn f + (cells.map Prod.fst, (cells.map Prod.snd).toList.sum + 6 * d) + +def TreeLayer (M : ℕ) : ℕ → Type + | 0 => PUnit + | d + 1 => TreeLayer M d × Fin M + +def intervalTreeDepth (M nx : ℕ) : ℕ := Nat.clog M (max 1 nx) + +def rationalMaximum (fallback : ℚ) : List ℚ → ℚ + | [] => fallback + | value :: rest => max value (rationalMaximum fallback rest) + +def rationalDyadicCeiling (value : ℚ) : ℚ := (2 : ℚ) ^ Int.clog 2 value + +def listedBandCoordinates {M : ℕ} {σ : Type u_1} [DecidableEq σ] + (band : List (Fin M → σ)) : List (Fin M × σ) := + (band.flatMap fun action => List.ofFn fun child => (child, action child)).dedup + +def childGain {β : Type u_1} {σ : Type u_2} (mass : β → ℚ) (table : ℕ → β × σ → ℚ) + (t : ℕ) (i : β × σ) : ℚ := -table t i / mass i.1 + +def childDecrement {β : Type u_1} {σ : Type u_2} (mass : β → ℚ) (table : ℕ → β × σ → ℚ) + (t : ℕ) (i : β × σ) : ℚ := (table t i - table (t + 1) i) / mass i.1 + +def naturalEqualWithWork (a b : ℕ) : Bool × ℕ := + let result := OAI.EditApproximation.binaryNaturalCompareWithWork a b + (decide (result.1 = .eq), result.2 + 1) + +def translatedEndpointWithWork (reference root endpoint : ℕ) : ℕ × ℕ := + let difference := OAI.EditApproximation.binaryNaturalSubtractWithWork endpoint root + let result := OAI.EditApproximation.binaryNaturalAddWithWork reference (OAI.EditApproximation.bitWordValue difference.1) + (OAI.EditApproximation.bitWordValue result.1, difference.2 + result.2 + 2) + +def rationalOnlineMinimum : List ℚ → Option ℚ + | [] => none + | first :: rest => some (OAI.EditApproximation.rationalMinimum first rest) + +def dyadicQueryWindow (N : ℕ) (w a F : ℚ) : List ℕ := + (OAI.EditApproximation.dyadicScales N).filter fun (b : ℕ) => decide (w / (16 * F) ≤ b ∧ (b : ℚ) ≤ 8 * a * w) + +def actionCurrentInputCover {Parent : Type u_1} {Child : Type u_2} [DecidableEq Child] {M : ℕ} + (actions : List (OAI.EditApproximation.RationalBellmanAction Parent Child M)) : Finset Child := + (List.finRange actions.length).toFinset.biUnion fun index => + Finset.univ.image (actions.get index).childState + +def boundedOnlineInteger (n : ℕ) (hn : 0 < n) (integer : ℕ) : Fin n := + ⟨integer % n, Nat.mod_lt _ hn⟩ + +def orderedInputs {ι : Type u_1} [DecidableEq ι] (encode : ι → ℕ) + (hinjective : Function.Injective encode) (inputs : Finset ι) : List ι := + let _ : LinearOrder ι := LinearOrder.lift' encode hinjective + inputs.sort (· ≤ ·) + +def CoarseThresholdDraws (B : ℕ) : ℕ → Type + | 0 => PUnit + | D + 1 => (Fin B → Fin B) × (Fin B → CoarseThresholdDraws B D) + +def coarseThresholdContribution (threshold scale value : ℚ) : ℚ := + if threshold ≤ value then max value scale else 0 + +def coarseChildThreshold (B : ℕ) (Q allowance : ℚ) (draw : Fin B) : ℚ := + allowance * (draw.val + 1 : ℕ) / ((B : ℚ) * Q) + +def coarseCommonDenominator (allowanceDen q L B D : ℕ) : ℕ := + allowanceDen * q * (L * B * q) ^ D + +def rationalSmoothedGradient {ι : Type u_1} (G : ℕ) (linear p : ι → ℚ) (i : ι) : ℚ := + -OAI.EditApproximation.rationalLogApproximation (p i + 1 / (G : ℚ) ^ 50) (G ^ 60) - 1 + linear i + +def rationalOnlineLinear {ι : Type u_1} (η κ : ℚ) + (gain decrement : ℕ → ι → ℚ) (t : ℕ) (i : ι) : ℚ := + η * (OAI.EditApproximation.rationalOptimisticHistory κ gain decrement t i + gain t i) + +def triangularChoice : (K : ℕ) → Fin (OAI.EditApproximation.optimizerTriangularMass K) → Fin K + | 0, integer => Fin.elim0 integer + | K + 1, integer => + if h : integer.val < OAI.EditApproximation.optimizerTriangularMass K then + (triangularChoice K ⟨integer.val, h⟩).castSucc + else ⟨K, by omega⟩ + +instance treeLayerFintype (M : ℕ) : (d : ℕ) → Fintype (OAI.EditApproximation.TreeLayer M d) + | 0 => inferInstanceAs (Fintype PUnit) + | d + 1 => + letI := treeLayerFintype M d + inferInstanceAs (Fintype (OAI.EditApproximation.TreeLayer M d × Fin M)) + +abbrev PhysicalNode (M J : ℕ) := Σ d : Fin (J + 1), OAI.EditApproximation.TreeLayer M d.val + +def finiteRationalOptimizer {ι : Type u_1} (coordinates : Finset ι) + (vertices : List (ι → ℚ)) (linear : ι → ℚ) (G : ℕ) : ℕ → ι → ℚ + | 0 => vertices.headD (fun _ => 0) + | j + 1 => + let p := finiteRationalOptimizer coordinates vertices linear G j + let selected := OAI.EditApproximation.rationalLinearizationMaximizer coordinates vertices + (OAI.EditApproximation.rationalSmoothedGradient G linear p) + fun i => (1 - 2 / ((j : ℚ) + 2)) * p i + (2 / ((j : ℚ) + 2)) * selected i + +instance physicalNodeFintype (M J : ℕ) : Fintype (OAI.EditApproximation.PhysicalNode M J) := inferInstance + +abbrev PhysicalInternalNode (M J : ℕ) := {node : OAI.EditApproximation.PhysicalNode M J // node.1.val < J} + +def finiteOptimizerAction {β : Type u_1} {σ : Type u_2} [Fintype β] [DecidableEq β] [DecidableEq σ] + (band : List (β → σ)) (hband : band ≠ []) (mass : β → ℚ) + (linear : β × σ → ℚ) (G j : ℕ) : β → σ := + let coordinates := OAI.EditApproximation.bandCoordinates band.toFinset + let vertices := band.map (OAI.EditApproximation.actionVector mass) + let gradient := OAI.EditApproximation.rationalSmoothedGradient G linear (OAI.EditApproximation.finiteRationalOptimizer coordinates vertices linear G j) + (band.argmax fun action => ∑ coordinate ∈ coordinates, + gradient coordinate * OAI.EditApproximation.actionVector mass action coordinate).getD (band.head hband) + +def finiteOptimizerActionDraw {β : Type u_1} {σ : Type u_2} [Fintype β] [DecidableEq β] [DecidableEq σ] + (band : List (β → σ)) (hband : band ≠ []) (mass : β → ℚ) + (linear : β × σ → ℚ) (G K : ℕ) (integer : Fin (OAI.EditApproximation.optimizerTriangularMass K)) : β → σ := + OAI.EditApproximation.finiteOptimizerAction band hband mass linear G (OAI.EditApproximation.triangularChoice K integer).val + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BinaryFraction + + +def width (a : OAI.EditApproximation.BinaryFraction) : ℕ := max a.numerator.bits.length a.denominator.length + +def denominatorInteger (a : OAI.EditApproximation.BinaryFraction) : OAI.EditApproximation.SignedBinary := ⟨false, a.denominator⟩ + +def zero : OAI.EditApproximation.BinaryFraction := ⟨⟨false, []⟩, [true], by decide⟩ + +def canonicalizeWithWork (a : OAI.EditApproximation.BinaryFraction) : OAI.EditApproximation.BinaryFraction × ℕ := by + have proof_trimBitWordWithWork_value_6 (bits : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.trimBitWordWithWork bits).1 = OAI.EditApproximation.bitWordValue bits := by + induction bits with + | nil => rfl + | cons bit bits ih => + simp only [OAI.EditApproximation.trimBitWordWithWork] + split_ifs with h + · have ht : OAI.EditApproximation.bitWordValue bits = 0 := by rw [← ih, h.1]; rfl + simp [h.2, OAI.EditApproximation.bitWordValue, ht] + · (simp only [OAI.EditApproximation.bitWordValue, ih]) + exact + let numerator := OAI.EditApproximation.trimBitWordWithWork a.numerator.bits + let denominator := OAI.EditApproximation.trimBitWordWithWork a.denominator + (⟨⟨a.numerator.negative, numerator.1⟩, denominator.1, by + rw [proof_trimBitWordWithWork_value_6] + exact a.denominator_pos⟩, numerator.2 + denominator.2 + 2) + +def inversePowerTwo (n : ℕ) : OAI.EditApproximation.BinaryFraction := by + have proof_powerTwoWord_value_13 (n : ℕ) : OAI.EditApproximation.bitWordValue (OAI.EditApproximation.powerTwoWord n) = 2 ^ n := by + induction n with + | zero => (simp [OAI.EditApproximation.powerTwoWord, OAI.EditApproximation.bitWordValue]) + | succ n ih => + (simp only [OAI.EditApproximation.powerTwoWord, List.replicate_succ, List.cons_append, OAI.EditApproximation.bitWordValue, + Bool.toNat_false, zero_add] at *) + rw [ih, pow_succ] + omega + exact + ⟨⟨false, [true]⟩, OAI.EditApproximation.powerTwoWord n, by rw [proof_powerTwoWord_value_13]; positivity⟩ + +def doubleFraction (a : OAI.EditApproximation.BinaryFraction) : OAI.EditApproximation.BinaryFraction := + ⟨⟨a.numerator.negative, false :: a.numerator.bits⟩, a.denominator, a.denominator_pos⟩ + +def absolute (a : OAI.EditApproximation.BinaryFraction) : OAI.EditApproximation.BinaryFraction := + ⟨⟨false, a.numerator.bits⟩, a.denominator, a.denominator_pos⟩ + +def naturalCeilingWithWork (a : OAI.EditApproximation.BinaryFraction) : List Bool × ℕ := + if a.numerator.negative then ([], 1) + else + let result := OAI.EditApproximation.bitCeilDivWithWork a.denominator a.numerator.bits + (result.1, result.2 + 1) + +def ofNaturalWord (bits : List Bool) : OAI.EditApproximation.BinaryFraction := + ⟨⟨false, bits⟩, [true], by decide⟩ + +def naturalFloorWithWork (a : OAI.EditApproximation.BinaryFraction) : List Bool × ℕ := + if a.numerator.negative then ([], 1) else + let quotient := OAI.EditApproximation.bitDivModWithWork a.denominator a.numerator.bits + (quotient.1, quotient.2.2 + 1) + +def queryDataReadBudget (M n : ℕ) {κ : Type u_1} (keys : List κ) : ℕ := + 1 + keys.length * (24 * max (Nat.size M) (Nat.size n) + 9) + +def onlineParametersWithWork (ell : List Bool) (hell : 0 < OAI.EditApproximation.bitWordValue ell) : + (OAI.EditApproximation.BinaryFraction × OAI.EditApproximation.BinaryFraction) × ℕ := by + have proof_trimBitWordWithWork_value_6 (bits : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.trimBitWordWithWork bits).1 = OAI.EditApproximation.bitWordValue bits := by + induction bits with + | nil => rfl + | cons bit bits ih => + simp only [OAI.EditApproximation.trimBitWordWithWork] + split_ifs with h + · have ht : OAI.EditApproximation.bitWordValue bits = 0 := by rw [← ih, h.1]; rfl + simp [h.2, OAI.EditApproximation.bitWordValue, ht] + · (simp only [OAI.EditApproximation.bitWordValue, ih]) + have proof_bitAdder_value_1 (a : Bool) (b : Bool) (carry : Bool) : + (OAI.EditApproximation.bitSum a b carry).toNat + 2 * (OAI.EditApproximation.bitCarry a b carry).toNat = + a.toNat + b.toNat + carry.toNat := by + cases a <;> cases b <;> cases carry <;> decide + have proof_bitAddWithWork_value_2 (left : List.{0} Bool) (right : List.{0} Bool) (carry : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitAddWithWork left right carry).1 = + OAI.EditApproximation.bitWordValue left + OAI.EditApproximation.bitWordValue right + carry.toNat := by + induction left generalizing right carry with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork] + induction right generalizing carry with + | nil => cases carry <;> simp [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue] + | cons b bs ih => + simp only [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 false b carry + simp only [Bool.toNat_false] at h + omega + | cons a as ih => + cases right with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a false carry + simp only [Bool.toNat_false] at h + omega + | cons b bs => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a b carry + omega + have proof_bitMulWithWork_value_0 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitMulWithWork left right).1 = OAI.EditApproximation.bitWordValue left * OAI.EditApproximation.bitWordValue right := by + induction left with + | nil => simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue] + | cons bit bits ih => + cases bit <;> simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue, proof_bitAddWithWork_value_2, ih] <;> ring + have proof_bitPowerWithWork_value_76 (base : List.{0} Bool) (n : ℕ) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitPowerWithWork base n).1 = OAI.EditApproximation.bitWordValue base ^ n := by + induction n with + | zero => (simp [OAI.EditApproximation.bitPowerWithWork, OAI.EditApproximation.bitWordValue]) + | succ n ih => + simp only [OAI.EditApproximation.bitPowerWithWork, proof_trimBitWordWithWork_value_6, proof_bitMulWithWork_value_0, ih, pow_succ] + exact + let etaPower := OAI.EditApproximation.bitPowerWithWork ell 5 + let kappaPower := OAI.EditApproximation.bitPowerWithWork ell 4 + let eta : OAI.EditApproximation.BinaryFraction := ⟨⟨false, etaPower.1⟩, [true], by decide⟩ + let kappa : OAI.EditApproximation.BinaryFraction := ⟨⟨false, [true]⟩, kappaPower.1, by + rw [proof_bitPowerWithWork_value_76] + exact Nat.pow_pos hell⟩ + ((eta, kappa), etaPower.2 + kappaPower.2 + 2) + +def refinementDecrementWithWork (ell : List Bool) (hell : 0 < OAI.EditApproximation.bitWordValue ell) : OAI.EditApproximation.BinaryFraction × ℕ := by + have proof_trimBitWordWithWork_value_6 (bits : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.trimBitWordWithWork bits).1 = OAI.EditApproximation.bitWordValue bits := by + induction bits with + | nil => rfl + | cons bit bits ih => + simp only [OAI.EditApproximation.trimBitWordWithWork] + split_ifs with h + · have ht : OAI.EditApproximation.bitWordValue bits = 0 := by rw [← ih, h.1]; rfl + simp [h.2, OAI.EditApproximation.bitWordValue, ht] + · (simp only [OAI.EditApproximation.bitWordValue, ih]) + have proof_bitAdder_value_1 (a : Bool) (b : Bool) (carry : Bool) : + (OAI.EditApproximation.bitSum a b carry).toNat + 2 * (OAI.EditApproximation.bitCarry a b carry).toNat = + a.toNat + b.toNat + carry.toNat := by + cases a <;> cases b <;> cases carry <;> decide + have proof_bitAddWithWork_value_2 (left : List.{0} Bool) (right : List.{0} Bool) (carry : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitAddWithWork left right carry).1 = + OAI.EditApproximation.bitWordValue left + OAI.EditApproximation.bitWordValue right + carry.toNat := by + induction left generalizing right carry with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork] + induction right generalizing carry with + | nil => cases carry <;> simp [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue] + | cons b bs ih => + simp only [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 false b carry + simp only [Bool.toNat_false] at h + omega + | cons a as ih => + cases right with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a false carry + simp only [Bool.toNat_false] at h + omega + | cons b bs => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a b carry + omega + have proof_bitMulWithWork_value_0 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitMulWithWork left right).1 = OAI.EditApproximation.bitWordValue left * OAI.EditApproximation.bitWordValue right := by + induction left with + | nil => simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue] + | cons bit bits ih => + cases bit <;> simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue, proof_bitAddWithWork_value_2, ih] <;> ring + have proof_bitPowerWithWork_value_76 (base : List.{0} Bool) (n : ℕ) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitPowerWithWork base n).1 = OAI.EditApproximation.bitWordValue base ^ n := by + induction n with + | zero => (simp [OAI.EditApproximation.bitPowerWithWork, OAI.EditApproximation.bitWordValue]) + | succ n ih => + simp only [OAI.EditApproximation.bitPowerWithWork, proof_trimBitWordWithWork_value_6, proof_bitMulWithWork_value_0, ih, pow_succ] + exact + let denominator := OAI.EditApproximation.bitPowerWithWork ell 10 + (⟨⟨false, [true]⟩, denominator.1, by + rw [proof_bitPowerWithWork_value_76] + exact Nat.pow_pos hell⟩, denominator.2 + 1) + +abbrev CoarseBinaryArray := Option (List OAI.EditApproximation.BinaryFraction) + +def coarseRootDenominator (B q L d : ℕ) : List Bool × ℕ := + OAI.EditApproximation.coarseDenominatorWithWork (1 : ℕ).bits q.bits L.bits B.bits d + +def naturalListEqualWithWork : List ℕ → List ℕ → Bool × ℕ + | [], [] => (true, 1) + | a :: left, b :: right => + let test := OAI.EditApproximation.naturalEqualWithWork a b + if test.1 then + let tail := naturalListEqualWithWork left right + (tail.1, test.2 + tail.2 + 2) + else (false, test.2 + 2) + | _, _ => (false, 1) + +def canonicalizeAllocation (a : OAI.EditApproximation.BinaryFraction) : ℕ := + OAI.EditApproximation.trimBitWordAllocation a.numerator.bits + OAI.EditApproximation.trimBitWordAllocation a.denominator + +def invAllocation (a : OAI.EditApproximation.BinaryFraction) : ℕ := + if (OAI.EditApproximation.bitCompareWithWork a.numerator.bits []).1 = .eq then 1 else 0 + +def naturalCeilingAllocation (a : OAI.EditApproximation.BinaryFraction) : ℕ := + if a.numerator.negative then 0 else OAI.EditApproximation.bitCeilDivAllocation a.denominator a.numerator.bits + +def gatheredLookupAllocation {κ : Type u_1} (equal : κ → κ → Bool × ℕ) + (allocation : κ → κ → ℕ) : List κ → List OAI.EditApproximation.BinaryFraction → κ → ℕ + | key :: keys, _value :: values, query => + allocation query key + if (equal query key).1 then 0 + else gatheredLookupAllocation equal allocation keys values query + | _, _, _ => 0 + +def naturalFloorAllocation (a : OAI.EditApproximation.BinaryFraction) : ℕ := + if a.numerator.negative then 0 else OAI.EditApproximation.bitDivModAllocation a.denominator a.numerator.bits + +def signedPowerTwoAllocation (e : ℤ) : ℕ := + if 0 ≤ e then e.toNat + 2 else (-e).toNat + 2 + +def invWithWork (a : OAI.EditApproximation.BinaryFraction) : OAI.EditApproximation.BinaryFraction × ℕ := by + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_eq_3 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .eq ↔ OAI.EditApproximation.bitWordValue left = OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + exact + let comparison := OAI.EditApproximation.bitCompareWithWork a.numerator.bits [] + if h : comparison.1 = .eq then (OAI.EditApproximation.BinaryFraction.zero, comparison.2 + 2) else + (⟨⟨a.numerator.negative, a.denominator⟩, a.numerator.bits, by + have hnonzero : OAI.EditApproximation.bitWordValue a.numerator.bits ≠ 0 := by + intro hzero + exact h ((proof_bitCompareWithWork_eq_3 a.numerator.bits []).2 hzero) + omega⟩, comparison.2 + 2) + +def signedPowerTwoWithWork (e : ℤ) : OAI.EditApproximation.BinaryFraction × ℕ := + if 0 ≤ e then + (⟨⟨false, OAI.EditApproximation.powerTwoWord e.toNat⟩, [true], by decide⟩, e.toNat + 3) + else (OAI.EditApproximation.BinaryFraction.inversePowerTwo (-e).toNat, (-e).toNat + 3) + +def fixedDenominatorWithWork (a : OAI.EditApproximation.BinaryFraction) (denominator : List Bool) + (hden : 0 < OAI.EditApproximation.bitWordValue denominator) : OAI.EditApproximation.BinaryFraction × ℕ := + let product := OAI.EditApproximation.bitMulWithWork a.numerator.bits denominator + let quotient := OAI.EditApproximation.bitDivModWithWork a.denominator product.1 + let raw : OAI.EditApproximation.BinaryFraction := ⟨⟨a.numerator.negative, quotient.1⟩, denominator, hden⟩ + let answer := OAI.EditApproximation.BinaryFraction.canonicalizeWithWork raw + (answer.1, product.2 + quotient.2.2 + answer.2 + 4) + +def finalAnswerWithWork (N : ℕ) (a : OAI.EditApproximation.BinaryFraction) : List Bool × ℕ := + let floor := OAI.EditApproximation.BinaryFraction.naturalFloorWithWork a + let clamped := OAI.EditApproximation.wordMinWithWork N.bits floor.1 + (clamped.1, floor.2 + clamped.2 + Nat.size N + 2) + +def coarseGridNatWithWork (denominator : List Bool) + (hden : 0 < OAI.EditApproximation.bitWordValue denominator) (n : ℕ) : OAI.EditApproximation.BinaryFraction × ℕ := + let product := OAI.EditApproximation.bitMulWithWork n.bits denominator + let raw : OAI.EditApproximation.BinaryFraction := ⟨⟨false, product.1⟩, denominator, hden⟩ + let answer := OAI.EditApproximation.BinaryFraction.canonicalizeWithWork raw + (answer.1, product.2 + answer.2 + 3) + +def coarseBinaryMapWithWork (f : OAI.EditApproximation.BinaryFraction → OAI.EditApproximation.BinaryFraction × ℕ) : + OAI.EditApproximation.BinaryFraction.CoarseBinaryArray → OAI.EditApproximation.BinaryFraction.CoarseBinaryArray × ℕ + | none => (none, 0) + | some values => + let result := OAI.EditApproximation.arithmeticMapWithWork f values + (some result.1, result.2) + +def fixedDenominatorAllocation (a : OAI.EditApproximation.BinaryFraction) (denominator : List Bool) + (hden : 0 < OAI.EditApproximation.bitWordValue denominator) : ℕ := + let product := OAI.EditApproximation.bitMulWithWork a.numerator.bits denominator + let quotient := OAI.EditApproximation.bitDivModWithWork a.denominator product.1 + let raw : OAI.EditApproximation.BinaryFraction := ⟨⟨a.numerator.negative, quotient.1⟩, denominator, hden⟩ + OAI.EditApproximation.bitMulAllocation a.numerator.bits denominator + OAI.EditApproximation.bitDivModAllocation a.denominator product.1 + + OAI.EditApproximation.BinaryFraction.canonicalizeAllocation raw + +def finalAnswerAllocation (N : ℕ) (a : OAI.EditApproximation.BinaryFraction) : ℕ := + OAI.EditApproximation.BinaryFraction.naturalFloorAllocation a + OAI.EditApproximation.naturalWordLEAllocation N.bits (OAI.EditApproximation.BinaryFraction.naturalFloorWithWork a).1 + Nat.size N + 1 + +def powerDenominatorWithWork (a : OAI.EditApproximation.BinaryFraction) (base : List Bool) + (hbase : 0 < OAI.EditApproximation.bitWordValue base) (n : ℕ) : OAI.EditApproximation.BinaryFraction × ℕ := by + have proof_trimBitWordWithWork_value_6 (bits : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.trimBitWordWithWork bits).1 = OAI.EditApproximation.bitWordValue bits := by + induction bits with + | nil => rfl + | cons bit bits ih => + simp only [OAI.EditApproximation.trimBitWordWithWork] + split_ifs with h + · have ht : OAI.EditApproximation.bitWordValue bits = 0 := by rw [← ih, h.1]; rfl + simp [h.2, OAI.EditApproximation.bitWordValue, ht] + · (simp only [OAI.EditApproximation.bitWordValue, ih]) + have proof_bitAdder_value_1 (a : Bool) (b : Bool) (carry : Bool) : + (OAI.EditApproximation.bitSum a b carry).toNat + 2 * (OAI.EditApproximation.bitCarry a b carry).toNat = + a.toNat + b.toNat + carry.toNat := by + cases a <;> cases b <;> cases carry <;> decide + have proof_bitAddWithWork_value_2 (left : List.{0} Bool) (right : List.{0} Bool) (carry : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitAddWithWork left right carry).1 = + OAI.EditApproximation.bitWordValue left + OAI.EditApproximation.bitWordValue right + carry.toNat := by + induction left generalizing right carry with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork] + induction right generalizing carry with + | nil => cases carry <;> simp [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue] + | cons b bs ih => + simp only [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 false b carry + simp only [Bool.toNat_false] at h + omega + | cons a as ih => + cases right with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a false carry + simp only [Bool.toNat_false] at h + omega + | cons b bs => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a b carry + omega + have proof_bitMulWithWork_value_0 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitMulWithWork left right).1 = OAI.EditApproximation.bitWordValue left * OAI.EditApproximation.bitWordValue right := by + induction left with + | nil => simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue] + | cons bit bits ih => + cases bit <;> simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue, proof_bitAddWithWork_value_2, ih] <;> ring + have proof_bitPowerWithWork_value_76 (base : List.{0} Bool) (n : ℕ) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitPowerWithWork base n).1 = OAI.EditApproximation.bitWordValue base ^ n := by + induction n with + | zero => (simp [OAI.EditApproximation.bitPowerWithWork, OAI.EditApproximation.bitWordValue]) + | succ n ih => + simp only [OAI.EditApproximation.bitPowerWithWork, proof_trimBitWordWithWork_value_6, proof_bitMulWithWork_value_0, ih, pow_succ] + exact + let denominator := OAI.EditApproximation.bitPowerWithWork base n + let answer := OAI.EditApproximation.BinaryFraction.fixedDenominatorWithWork a denominator.1 (by + rw [proof_bitPowerWithWork_value_76] + exact Nat.pow_pos hbase) + (answer.1, denominator.2 + answer.2 + 1) + +def powerDenominatorAllocation (a : OAI.EditApproximation.BinaryFraction) (base : List Bool) + (hbase : 0 < OAI.EditApproximation.bitWordValue base) (n : ℕ) : ℕ := by + have proof_trimBitWordWithWork_value_6 (bits : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.trimBitWordWithWork bits).1 = OAI.EditApproximation.bitWordValue bits := by + induction bits with + | nil => rfl + | cons bit bits ih => + simp only [OAI.EditApproximation.trimBitWordWithWork] + split_ifs with h + · have ht : OAI.EditApproximation.bitWordValue bits = 0 := by rw [← ih, h.1]; rfl + simp [h.2, OAI.EditApproximation.bitWordValue, ht] + · (simp only [OAI.EditApproximation.bitWordValue, ih]) + have proof_bitAdder_value_1 (a : Bool) (b : Bool) (carry : Bool) : + (OAI.EditApproximation.bitSum a b carry).toNat + 2 * (OAI.EditApproximation.bitCarry a b carry).toNat = + a.toNat + b.toNat + carry.toNat := by + cases a <;> cases b <;> cases carry <;> decide + have proof_bitAddWithWork_value_2 (left : List.{0} Bool) (right : List.{0} Bool) (carry : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitAddWithWork left right carry).1 = + OAI.EditApproximation.bitWordValue left + OAI.EditApproximation.bitWordValue right + carry.toNat := by + induction left generalizing right carry with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork] + induction right generalizing carry with + | nil => cases carry <;> simp [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue] + | cons b bs ih => + simp only [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 false b carry + simp only [Bool.toNat_false] at h + omega + | cons a as ih => + cases right with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a false carry + simp only [Bool.toNat_false] at h + omega + | cons b bs => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a b carry + omega + have proof_bitMulWithWork_value_0 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitMulWithWork left right).1 = OAI.EditApproximation.bitWordValue left * OAI.EditApproximation.bitWordValue right := by + induction left with + | nil => simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue] + | cons bit bits ih => + cases bit <;> simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue, proof_bitAddWithWork_value_2, ih] <;> ring + have proof_bitPowerWithWork_value_76 (base : List.{0} Bool) (n : ℕ) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitPowerWithWork base n).1 = OAI.EditApproximation.bitWordValue base ^ n := by + induction n with + | zero => (simp [OAI.EditApproximation.bitPowerWithWork, OAI.EditApproximation.bitWordValue]) + | succ n ih => + simp only [OAI.EditApproximation.bitPowerWithWork, proof_trimBitWordWithWork_value_6, proof_bitMulWithWork_value_0, ih, pow_succ] + exact + OAI.EditApproximation.bitPowerAllocation base n + OAI.EditApproximation.BinaryFraction.fixedDenominatorAllocation a (OAI.EditApproximation.bitPowerWithWork base n).1 + (by rw [proof_bitPowerWithWork_value_76]; exact Nat.pow_pos hbase) + +def finishCachedWithWork (raw : OAI.EditApproximation.BinaryFraction × ℕ) (base : List Bool) + (hbase : 0 < OAI.EditApproximation.bitWordValue base) (remaining : ℕ) : OAI.EditApproximation.BinaryFraction × ℕ := + let result := OAI.EditApproximation.BinaryFraction.powerDenominatorWithWork raw.1 base hbase remaining + (result.1, raw.2 + result.2 + 1) + +def finishCachedAllocation (raw : OAI.EditApproximation.BinaryFraction × ℕ) (allocation : ℕ) + (base : List Bool) (hbase : 0 < OAI.EditApproximation.bitWordValue base) (remaining : ℕ) : ℕ := + allocation + OAI.EditApproximation.BinaryFraction.powerDenominatorAllocation raw.1 base hbase remaining + + +end OAI.EditApproximation.BinaryFraction +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation + + +def physicalChild {M J : ℕ} (node : OAI.EditApproximation.PhysicalNode M J) (hbelow : node.1.val < J) + (i : Fin M) : OAI.EditApproximation.PhysicalNode M J := + ⟨⟨node.1.val + 1, by omega⟩, (node.2, i)⟩ + +instance treeLayerDecidableEq (M : ℕ) : (d : ℕ) → DecidableEq (OAI.EditApproximation.TreeLayer M d) + | 0 => inferInstanceAs (DecidableEq PUnit) + | d + 1 => + letI := treeLayerDecidableEq M d + inferInstanceAs (DecidableEq (OAI.EditApproximation.TreeLayer M d × Fin M)) + +def treeLayerCode (M : ℕ) : (d : ℕ) → OAI.EditApproximation.TreeLayer M d → ℕ + | 0, _ => 0 + | d + 1, path => path.2.val + M * treeLayerCode M d path.1 + +def localOnlineMassBound (M P H : ℕ) : ℕ := + OAI.EditApproximation.optimizerTriangularMass ((H + M * (40 * P + 2) ^ 2 + 2) ^ 80) + +def treeLayerCodeWithWork (M : ℕ) : (d : ℕ) → OAI.EditApproximation.TreeLayer M d → ℕ × ℕ + | 0, _ => (0, 1) + | d + 1, path => let previous := treeLayerCodeWithWork M d path.1 + (path.2.val + M * previous.1, previous.2 + 3) + +def queryNaturalIndexWithWork (a : ℕ) : List ℕ → ℕ × ℕ + | [] => (0, 1) + | b :: rest => + let test := OAI.EditApproximation.naturalEqualWithWork a b + if test.1 then (0, test.2 + 1) + else + let tail := queryNaturalIndexWithWork a rest + (tail.1 + 1, test.2 + tail.2 + 2) + +def scheduledSeedWordWithWork (N pass : ℕ) : OAI.EditApproximation.BinaryFraction × ℕ := + OAI.EditApproximation.BinaryFraction.signedPowerTwoWithWork + ((OAI.EditApproximation.dyadicSeedExponent (OAI.EditApproximation.smallLogExponent N) (OAI.EditApproximation.computedSeedInitialExponent N) pass : ℕ) : ℤ) + +def coarseLetterMatchWithWork : Option (Option ℕ) → Option ℕ → Bool × ℕ + | none, _ => (false, 1) + | some none, none => (true, 1) + | some (some a), some b => OAI.EditApproximation.naturalEqualWithWork a b + | _, _ => (false, 1) + +def queryNaturalIndexAllocation (a : ℕ) : List ℕ → ℕ + | [] => 0 + | b :: rest => OAI.EditApproximation.naturalEqualAllocation a b + + if (OAI.EditApproximation.naturalEqualWithWork a b).1 then 1 else queryNaturalIndexAllocation a rest + 1 + +def physicalNodeCode {M J : ℕ} (node : OAI.EditApproximation.PhysicalNode M J) : ℕ := + OAI.EditApproximation.treeLayerCode M node.1.val node.2 + M ^ J * node.1.val + +def queryScaleDispatchWithWork (N b : ℕ) : ℕ × ℕ := + let scales := OAI.EditApproximation.dyadicScalesWithWork N + let index := OAI.EditApproximation.queryNaturalIndexWithWork b scales.1 + (index.1, scales.2 + index.2 + scales.1.length + 2) + +def queryScaleDispatchAllocation (N b : ℕ) : ℕ := + OAI.EditApproximation.dyadicScalesAllocation N + OAI.EditApproximation.queryNaturalIndexAllocation b (OAI.EditApproximation.dyadicScalesWithWork N).1 + + (OAI.EditApproximation.dyadicScalesWithWork N).1.length + +def queryScalePresentWithWork (N b : ℕ) : Bool × ℕ := + let found := OAI.EditApproximation.queryScaleDispatchWithWork N b + let test := OAI.EditApproximation.binaryNaturalCompareWithWork found.1 (max 1 N.bits.length) + (decide (test.1 = .lt), found.2 + test.2 + 2) + +def queryScalePresentAllocation (N b : ℕ) : ℕ := + OAI.EditApproximation.queryScaleDispatchAllocation N b + (OAI.EditApproximation.queryScaleDispatchWithWork N b).1.bits.length + (max 1 N.bits.length).bits.length + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open MeasureTheory ProbabilityTheory + +def physicalScaleIndex (N b : ℕ) (hb : b ∈ OAI.EditApproximation.dyadicScales N) : + Fin (OAI.EditApproximation.dyadicScales N).length := + ⟨(OAI.EditApproximation.dyadicScales N).idxOf b, List.idxOf_lt_length_of_mem hb⟩ + +abbrev PositiveDrawRange (B : ℕ) := {n : Fin (B + 1) // 0 < n.val} + +abbrev PhysicalLocalGroupKey (M J N n exponent : ℕ) := + OAI.EditApproximation.PhysicalInternalNode M J × Fin (OAI.EditApproximation.dyadicScales N).length × + Fin (n * 2 ^ exponent + 1) × Fin (n * 2 ^ exponent + 1) + +noncomputable def rejectionSuccessParameter (N R : ℕ) (hN : 0 < N) (hNR : N ≤ R) : unitInterval := + ⟨(N : ℝ) / R, div_nonneg (Nat.cast_nonneg _) (Nat.cast_nonneg _), + (div_le_one₀ (by exact_mod_cast hN.trans_le hNR : (0 : ℝ) < R)).mpr (by exact_mod_cast hNR)⟩ + +def scheduledSeedFactor (N pass : ℕ) : ℚ := + (2 : ℚ) ^ OAI.EditApproximation.dyadicSeedExponent (OAI.EditApproximation.smallLogExponent N) (OAI.EditApproximation.computedSeedInitialExponent N) pass + +def scheduledSeedMultiplier (N pass : ℕ) : ℕ := + 2 ^ (OAI.EditApproximation.dyadicSeedExponent (OAI.EditApproximation.smallLogExponent N) (OAI.EditApproximation.computedSeedInitialExponent N) pass - OAI.EditApproximation.smallLogExponent N) + +instance computedBranching_neZero (N : ℕ) : NeZero (OAI.EditApproximation.integerParameters N).M := + ⟨pow_ne_zero _ (by decide : (2 : ℕ) ≠ 0)⟩ + +instance computedCoarseBranching_neZero (N : ℕ) : NeZero (OAI.EditApproximation.integerParameters N).B := + ⟨pow_ne_zero _ (pow_ne_zero _ (by decide : (2 : ℕ) ≠ 0))⟩ + +instance computedSourceTime_neZero (N : ℕ) : NeZero (OAI.EditApproximation.inputHeight N ^ 2) := + ⟨pow_ne_zero _ (pow_ne_zero _ (by decide : (2 : ℕ) ≠ 0))⟩ + +abbrev CommonRangeKey (ι : Type u_1) (B : ℕ) := ι × OAI.EditApproximation.PositiveDrawRange B + +def positiveDrawRangeOfLE (B n : ℕ) (hn : 0 < n) (hB : n ≤ B) : OAI.EditApproximation.PositiveDrawRange B := + ⟨⟨n, Nat.lt_succ_of_le hB⟩, hn⟩ + +instance positiveDrawRange_nezero {B : ℕ} (n : OAI.EditApproximation.PositiveDrawRange B) : NeZero n.val.val := + ⟨Nat.ne_of_gt n.property⟩ + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.SignedBinary + + +def value (a : OAI.EditApproximation.SignedBinary) : ℤ := OAI.EditApproximation.signedMagnitude a.negative (OAI.EditApproximation.bitWordValue a.bits) + +def ofInt (a : ℤ) : OAI.EditApproximation.SignedBinary := ⟨decide (a < 0), a.natAbs.bits⟩ + +def neg (a : OAI.EditApproximation.SignedBinary) : OAI.EditApproximation.SignedBinary := ⟨!a.negative, a.bits⟩ + +def addWithWork (a b : OAI.EditApproximation.SignedBinary) : OAI.EditApproximation.SignedBinary × ℕ := + if a.negative = b.negative then + let total := OAI.EditApproximation.bitAddWithWork a.bits b.bits false + (⟨a.negative, total.1⟩, total.2 + 4) + else + let comparison := OAI.EditApproximation.bitCompareWithWork a.bits b.bits + match comparison.1 with + | .eq => (⟨false, []⟩, comparison.2 + 4) + | .lt => + let difference := OAI.EditApproximation.bitSubtractWithWork b.bits a.bits false + (⟨b.negative, difference.1⟩, comparison.2 + difference.2.2 + 4) + | .gt => + let difference := OAI.EditApproximation.bitSubtractWithWork a.bits b.bits false + (⟨a.negative, difference.1⟩, comparison.2 + difference.2.2 + 4) + +def mulWithWork (a b : OAI.EditApproximation.SignedBinary) : OAI.EditApproximation.SignedBinary × ℕ := + let product := OAI.EditApproximation.bitMulWithWork a.bits b.bits + (⟨xor a.negative b.negative, product.1⟩, product.2 + 4) + +def nonzeroWithWork (bits : List Bool) : Bool × ℕ := + let comparison := OAI.EditApproximation.bitCompareWithWork bits [] + (if comparison.1 = .eq then false else true, comparison.2 + 1) + +def addAllocation (a b : OAI.EditApproximation.SignedBinary) : ℕ := + if a.negative = b.negative then OAI.EditApproximation.bitAddAllocation a.bits b.bits false + else match (OAI.EditApproximation.bitCompareWithWork a.bits b.bits).1 with + | .eq => 0 + | .lt => OAI.EditApproximation.bitSubtractAllocation b.bits a.bits false + | .gt => OAI.EditApproximation.bitSubtractAllocation a.bits b.bits false + +def mulAllocation (a b : OAI.EditApproximation.SignedBinary) : ℕ := OAI.EditApproximation.bitMulAllocation a.bits b.bits + +def ltWithWork (a b : OAI.EditApproximation.SignedBinary) : Bool × ℕ := + if a.negative then + if b.negative then + let comparison := OAI.EditApproximation.bitCompareWithWork b.bits a.bits + (comparison.1 == .lt, comparison.2 + 2) + else + let left := OAI.EditApproximation.SignedBinary.nonzeroWithWork a.bits + let right := OAI.EditApproximation.SignedBinary.nonzeroWithWork b.bits + (left.1 || right.1, left.2 + right.2 + 4) + else + if b.negative then (false, 2) + else + let comparison := OAI.EditApproximation.bitCompareWithWork a.bits b.bits + (comparison.1 == .lt, comparison.2 + 2) + + +end OAI.EditApproximation.SignedBinary +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BinaryFraction + + +def value (a : OAI.EditApproximation.BinaryFraction) : ℚ := (a.numerator.value : ℚ) / OAI.EditApproximation.bitWordValue a.denominator + +def representation (a : OAI.EditApproximation.BinaryFraction) : OAI.EditApproximation.UnreducedRational := + ⟨a.numerator.value, OAI.EditApproximation.bitWordValue a.denominator, a.denominator_pos⟩ + +def addWithWork (a b : OAI.EditApproximation.BinaryFraction) : OAI.EditApproximation.BinaryFraction × ℕ := by + have proof_bitAdder_value_1 (a : Bool) (b : Bool) (carry : Bool) : + (OAI.EditApproximation.bitSum a b carry).toNat + 2 * (OAI.EditApproximation.bitCarry a b carry).toNat = + a.toNat + b.toNat + carry.toNat := by + cases a <;> cases b <;> cases carry <;> decide + have proof_bitAddWithWork_value_2 (left : List.{0} Bool) (right : List.{0} Bool) (carry : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitAddWithWork left right carry).1 = + OAI.EditApproximation.bitWordValue left + OAI.EditApproximation.bitWordValue right + carry.toNat := by + induction left generalizing right carry with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork] + induction right generalizing carry with + | nil => cases carry <;> simp [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue] + | cons b bs ih => + simp only [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 false b carry + simp only [Bool.toNat_false] at h + omega + | cons a as ih => + cases right with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a false carry + simp only [Bool.toNat_false] at h + omega + | cons b bs => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a b carry + omega + have proof_bitMulWithWork_value_0 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitMulWithWork left right).1 = OAI.EditApproximation.bitWordValue left * OAI.EditApproximation.bitWordValue right := by + induction left with + | nil => simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue] + | cons bit bits ih => + cases bit <;> simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue, proof_bitAddWithWork_value_2, ih] <;> ring + exact + let first := a.numerator.mulWithWork b.denominatorInteger + let second := b.numerator.mulWithWork a.denominatorInteger + let numerator := first.1.addWithWork second.1 + let denominator := OAI.EditApproximation.bitMulWithWork a.denominator b.denominator + (⟨numerator.1, denominator.1, by + change 0 < OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitMulWithWork a.denominator b.denominator).1 + rw [proof_bitMulWithWork_value_0] + exact Nat.mul_pos a.denominator_pos b.denominator_pos⟩, + first.2 + second.2 + numerator.2 + denominator.2 + 8) + +def mulWithWork (a b : OAI.EditApproximation.BinaryFraction) : OAI.EditApproximation.BinaryFraction × ℕ := by + have proof_bitAdder_value_1 (a : Bool) (b : Bool) (carry : Bool) : + (OAI.EditApproximation.bitSum a b carry).toNat + 2 * (OAI.EditApproximation.bitCarry a b carry).toNat = + a.toNat + b.toNat + carry.toNat := by + cases a <;> cases b <;> cases carry <;> decide + have proof_bitAddWithWork_value_2 (left : List.{0} Bool) (right : List.{0} Bool) (carry : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitAddWithWork left right carry).1 = + OAI.EditApproximation.bitWordValue left + OAI.EditApproximation.bitWordValue right + carry.toNat := by + induction left generalizing right carry with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork] + induction right generalizing carry with + | nil => cases carry <;> simp [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue] + | cons b bs ih => + simp only [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 false b carry + simp only [Bool.toNat_false] at h + omega + | cons a as ih => + cases right with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a false carry + simp only [Bool.toNat_false] at h + omega + | cons b bs => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a b carry + omega + have proof_bitMulWithWork_value_0 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitMulWithWork left right).1 = OAI.EditApproximation.bitWordValue left * OAI.EditApproximation.bitWordValue right := by + induction left with + | nil => simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue] + | cons bit bits ih => + cases bit <;> simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue, proof_bitAddWithWork_value_2, ih] <;> ring + exact + let numerator := a.numerator.mulWithWork b.numerator + let denominator := OAI.EditApproximation.bitMulWithWork a.denominator b.denominator + (⟨numerator.1, denominator.1, by + change 0 < OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitMulWithWork a.denominator b.denominator).1 + rw [proof_bitMulWithWork_value_0] + exact Nat.mul_pos a.denominator_pos b.denominator_pos⟩, + numerator.2 + denominator.2 + 4) + +def neg (a : OAI.EditApproximation.BinaryFraction) : OAI.EditApproximation.BinaryFraction := + ⟨a.numerator.neg, a.denominator, a.denominator_pos⟩ + +def ltWithWork (a b : OAI.EditApproximation.BinaryFraction) : Bool × ℕ := + let left := a.numerator.mulWithWork b.denominatorInteger + let right := b.numerator.mulWithWork a.denominatorInteger + let compared := left.1.ltWithWork right.1 + (compared.1, left.2 + right.2 + compared.2 + 4) + +def nat (n : ℕ) : OAI.EditApproximation.BinaryFraction := + ⟨OAI.EditApproximation.SignedBinary.ofInt n, [true], by decide⟩ + +def coarseGridAddWithWork (a b : OAI.EditApproximation.BinaryFraction) : OAI.EditApproximation.BinaryFraction × ℕ := + let total := a.numerator.addWithWork b.numerator + let raw : OAI.EditApproximation.BinaryFraction := ⟨total.1, a.denominator, a.denominator_pos⟩ + let answer := OAI.EditApproximation.BinaryFraction.canonicalizeWithWork raw + (answer.1, total.2 + answer.2 + 3) + +def coarseReadShiftWithWork (k n : ℕ) (target : List ℕ) (letter : Option (Option ℕ)) + (start : ℕ) (shift : Fin (2 * k + 1)) : ℕ × ℕ := + match letter with + | none => (0, 1) + | some letter => + let position := OAI.EditApproximation.binaryNaturalAddWithWork start shift.val + let actual := OAI.EditApproximation.coarseFramedReadWithWork k n target (OAI.EditApproximation.bitWordValue position.1) + let matched := OAI.EditApproximation.coarseLetterMatchWithWork actual.1 letter + (if matched.1 then 0 else 1, position.2 + actual.2 + matched.2 + 3) + +def addAllocation (a b : OAI.EditApproximation.BinaryFraction) : ℕ := + a.numerator.mulAllocation b.denominatorInteger + + b.numerator.mulAllocation a.denominatorInteger + + ((a.numerator.mulWithWork b.denominatorInteger).1.addAllocation + (b.numerator.mulWithWork a.denominatorInteger).1) + + OAI.EditApproximation.bitMulAllocation a.denominator b.denominator + +def mulAllocation (a b : OAI.EditApproximation.BinaryFraction) : ℕ := + a.numerator.mulAllocation b.numerator + OAI.EditApproximation.bitMulAllocation a.denominator b.denominator + +def ltAllocation (a b : OAI.EditApproximation.BinaryFraction) : ℕ := + a.numerator.mulAllocation b.denominatorInteger + + b.numerator.mulAllocation a.denominatorInteger + +def canonicalAddWithWork (a b : OAI.EditApproximation.BinaryFraction) : OAI.EditApproximation.BinaryFraction × ℕ := + let raw := a.addWithWork b + let result := OAI.EditApproximation.BinaryFraction.canonicalizeWithWork raw.1 + (result.1, raw.2 + result.2) + +def canonicalMulWithWork (a b : OAI.EditApproximation.BinaryFraction) : OAI.EditApproximation.BinaryFraction × ℕ := + let raw := a.mulWithWork b + let result := OAI.EditApproximation.BinaryFraction.canonicalizeWithWork raw.1 + (result.1, raw.2 + result.2) + +def one : OAI.EditApproximation.BinaryFraction := OAI.EditApproximation.BinaryFraction.nat 1 + +def dyadicScanWithWork (a candidate : OAI.EditApproximation.BinaryFraction) : ℕ → OAI.EditApproximation.BinaryFraction × ℕ + | 0 => (candidate, 1) + | n + 1 => + let comparison := candidate.ltWithWork a + if comparison.1 then + let next := dyadicScanWithWork a (OAI.EditApproximation.BinaryFraction.doubleFraction candidate) n + (next.1, comparison.2 + next.2 + 2) + else (candidate, comparison.2 + 1) + +def maxWithWork (a b : OAI.EditApproximation.BinaryFraction) : OAI.EditApproximation.BinaryFraction × ℕ := + let comparison := a.ltWithWork b + (if comparison.1 then b else a, comparison.2 + 1) + +def leWithWork (a b : OAI.EditApproximation.BinaryFraction) : Bool × ℕ := + let result := b.ltWithWork a + (!result.1, result.2 + 1) + +def minWithWork (a b : OAI.EditApproximation.BinaryFraction) : OAI.EditApproximation.BinaryFraction × ℕ := + let comparison := a.ltWithWork b + (if comparison.1 then a else b, comparison.2 + 1) + +def queryScaleAt (words : List OAI.EditApproximation.BinaryFraction) (scales : List ℚ) + (h : words.map OAI.EditApproximation.BinaryFraction.value = scales) (i : Fin scales.length) : OAI.EditApproximation.BinaryFraction := + words[i.val]'(by have hl := congrArg List.length h; simp only [List.length_map] at hl; omega) + +def gatheredWordLookupWithWork {κ : Type u_1} (equal : κ → κ → Bool × ℕ) : + List κ → List OAI.EditApproximation.BinaryFraction → κ → OAI.EditApproximation.BinaryFraction × ℕ + | key :: keys, value :: values, query => + let test := equal query key + if test.1 then (value, test.2 + 1) + else + let rest := gatheredWordLookupWithWork equal keys values query + (rest.1, test.2 + rest.2 + 1) + | _, _, _ => (OAI.EditApproximation.BinaryFraction.nat 0, 1) + +def coarseGridZipAddWithWork : List OAI.EditApproximation.BinaryFraction → List OAI.EditApproximation.BinaryFraction → List OAI.EditApproximation.BinaryFraction × ℕ + | a :: left, b :: right => + let here := OAI.EditApproximation.BinaryFraction.coarseGridAddWithWork a b + let tail := coarseGridZipAddWithWork left right + (here.1 :: tail.1, here.2 + tail.2 + 3) + | _, _ => ([], 0) + +def coarseBinaryRead (array : OAI.EditApproximation.BinaryFraction.CoarseBinaryArray) (i : ℕ) : OAI.EditApproximation.BinaryFraction := + match array with + | none => OAI.EditApproximation.BinaryFraction.nat 0 + | some cells => cells[i]?.getD (OAI.EditApproximation.BinaryFraction.nat 0) + +def canonicalAddAllocation (a b : OAI.EditApproximation.BinaryFraction) : ℕ := + a.addAllocation b + OAI.EditApproximation.BinaryFraction.canonicalizeAllocation (a.addWithWork b).1 + +def canonicalMulAllocation (a b : OAI.EditApproximation.BinaryFraction) : ℕ := + a.mulAllocation b + OAI.EditApproximation.BinaryFraction.canonicalizeAllocation (a.mulWithWork b).1 + +def minAllocation (a b : OAI.EditApproximation.BinaryFraction) : ℕ := OAI.EditApproximation.BinaryFraction.ltAllocation a b + +def maxAllocation (a b : OAI.EditApproximation.BinaryFraction) : ℕ := OAI.EditApproximation.BinaryFraction.ltAllocation a b + +def leAllocation (a b : OAI.EditApproximation.BinaryFraction) : ℕ := OAI.EditApproximation.BinaryFraction.ltAllocation b a + +def dyadicScanAllocation (a candidate : OAI.EditApproximation.BinaryFraction) : ℕ → ℕ + | 0 => 0 + | n + 1 => + OAI.EditApproximation.BinaryFraction.ltAllocation candidate a + if (candidate.ltWithWork a).1 then + dyadicScanAllocation a (OAI.EditApproximation.BinaryFraction.doubleFraction candidate) n + 1 else 0 + +def equalAllocation (a b : OAI.EditApproximation.BinaryFraction) : ℕ := + OAI.EditApproximation.BinaryFraction.ltAllocation b a + OAI.EditApproximation.BinaryFraction.ltAllocation a b + 0 + +def subWithWork (a b : OAI.EditApproximation.BinaryFraction) : OAI.EditApproximation.BinaryFraction × ℕ := + let result := OAI.EditApproximation.BinaryFraction.canonicalAddWithWork a b.neg + (result.1, result.2 + 1) + +def divWithWork (a b : OAI.EditApproximation.BinaryFraction) : OAI.EditApproximation.BinaryFraction × ℕ := + let inverse := b.invWithWork + let result := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork a inverse.1 + (result.1, inverse.2 + result.2 + 1) + +def powWithWork (a : OAI.EditApproximation.BinaryFraction) : ℕ → OAI.EditApproximation.BinaryFraction × ℕ + | 0 => (OAI.EditApproximation.BinaryFraction.one, 1) + | k + 1 => + let previous := powWithWork a k + let result := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork previous.1 a + (result.1, previous.2 + result.2 + 1) + +def dotListWithWork {d : ℕ} (left right : Vector OAI.EditApproximation.BinaryFraction d) : List (Fin d) → OAI.EditApproximation.BinaryFraction × ℕ + | [] => (OAI.EditApproximation.BinaryFraction.zero, 1) + | i :: rest => + let tail := dotListWithWork left right rest + let product := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (left.get i) (right.get i) + let result := OAI.EditApproximation.BinaryFraction.canonicalAddWithWork product.1 tail.1 + (result.1, tail.2 + product.2 + result.2 + 5) + +def dyadicCeilingWithWork (a : OAI.EditApproximation.BinaryFraction) : OAI.EditApproximation.BinaryFraction × ℕ := + let result := OAI.EditApproximation.BinaryFraction.dyadicScanWithWork a (OAI.EditApproximation.BinaryFraction.inversePowerTwo a.width) (2 * a.width) + (result.1, result.2 + 3 * a.width + 5) + +def maximumWithWork (fallback : OAI.EditApproximation.BinaryFraction) : List OAI.EditApproximation.BinaryFraction → OAI.EditApproximation.BinaryFraction × ℕ + | [] => (fallback, 1) + | head :: rest => + let tail := maximumWithWork fallback rest + let result := OAI.EditApproximation.BinaryFraction.maxWithWork head tail.1 + (result.1, tail.2 + result.2 + 1) + +def minimumWithWork (fallback : OAI.EditApproximation.BinaryFraction) : List OAI.EditApproximation.BinaryFraction → OAI.EditApproximation.BinaryFraction × ℕ + | [] => (fallback, 1) + | head :: rest => + let tail := minimumWithWork fallback rest + let result := OAI.EditApproximation.BinaryFraction.minWithWork head tail.1 + (result.1, tail.2 + result.2 + 1) + +def scaledCeilingWithWork (multiplier : ℕ) (a : OAI.EditApproximation.BinaryFraction) : List Bool × ℕ := + let product := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat multiplier) a + let result := OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork product.1 + (result.1, product.2 + result.2 + Nat.size multiplier + 3) + +def coarseContributionWithWork (threshold scale a : OAI.EditApproximation.BinaryFraction) : OAI.EditApproximation.BinaryFraction × ℕ := + let test := OAI.EditApproximation.BinaryFraction.leWithWork threshold a + if test.1 then + let result := OAI.EditApproximation.BinaryFraction.maxWithWork a scale + (result.1, test.2 + result.2 + 2) + else + let result := OAI.EditApproximation.BinaryFraction.coarseGridNatWithWork a.denominator a.denominator_pos 0 + (result.1, test.2 + result.2 + 2) + +def coarseGridScanWithWork (two previous : OAI.EditApproximation.BinaryFraction) : + List OAI.EditApproximation.BinaryFraction → List OAI.EditApproximation.BinaryFraction × ℕ + | [] => ([previous], 0) + | head :: rest => + let added := OAI.EditApproximation.BinaryFraction.coarseGridAddWithWork previous two + let next := OAI.EditApproximation.BinaryFraction.minWithWork head added.1 + let tail := coarseGridScanWithWork two next.1 rest + (previous :: tail.1, added.2 + next.2 + tail.2 + 3) + +def coarseGridZipMinimumWithWork : List OAI.EditApproximation.BinaryFraction → List OAI.EditApproximation.BinaryFraction → List OAI.EditApproximation.BinaryFraction × ℕ + | a :: left, b :: right => + let here := OAI.EditApproximation.BinaryFraction.minWithWork a b + let tail := coarseGridZipMinimumWithWork left right + (here.1 :: tail.1, here.2 + tail.2 + 3) + | _, _ => ([], 0) + +def coarseBinaryAddWithWork : OAI.EditApproximation.BinaryFraction.CoarseBinaryArray → OAI.EditApproximation.BinaryFraction.CoarseBinaryArray → OAI.EditApproximation.BinaryFraction.CoarseBinaryArray × ℕ + | none, right => (right, 0) + | left, none => (left, 0) + | some left, some right => + let result := OAI.EditApproximation.BinaryFraction.coarseGridZipAddWithWork left right + (some result.1, result.2) + +def divAllocation (a b : OAI.EditApproximation.BinaryFraction) : ℕ := + OAI.EditApproximation.BinaryFraction.invAllocation b + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation a b.invWithWork.1 + +def subAllocation (a b : OAI.EditApproximation.BinaryFraction) : ℕ := OAI.EditApproximation.BinaryFraction.canonicalAddAllocation a b.neg + +def optimizerUpdateCellAllocation {d : ℕ} (step complement : OAI.EditApproximation.BinaryFraction) + (previous selected : Vector OAI.EditApproximation.BinaryFraction d) (i : Fin d) : ℕ := + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation complement (previous.get i) + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation step (selected.get i) + + OAI.EditApproximation.BinaryFraction.canonicalAddAllocation (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork complement (previous.get i)).1 + (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork step (selected.get i)).1 + +def dyadicCeilingAllocation (a : OAI.EditApproximation.BinaryFraction) : ℕ := + OAI.EditApproximation.BinaryFraction.dyadicScanAllocation a (OAI.EditApproximation.BinaryFraction.inversePowerTwo a.width) (2 * a.width) + a.width + 2 + +def roundedSpacingAllocation (theta envelope : OAI.EditApproximation.BinaryFraction) : ℕ := + let product := (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork theta envelope).1 + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation theta envelope + OAI.EditApproximation.BinaryFraction.maxAllocation OAI.EditApproximation.BinaryFraction.one product + + OAI.EditApproximation.BinaryFraction.naturalCeilingAllocation (OAI.EditApproximation.BinaryFraction.maxWithWork OAI.EditApproximation.BinaryFraction.one product).1 + +def scaledCeilingAllocation (multiplier : ℕ) (a : OAI.EditApproximation.BinaryFraction) : ℕ := + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation (OAI.EditApproximation.BinaryFraction.nat multiplier) a + + OAI.EditApproximation.BinaryFraction.naturalCeilingAllocation (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat multiplier) a).1 + Nat.size multiplier + 1 + +def groupTermsAllocation {M : ℕ} (h : OAI.EditApproximation.BinaryFraction) (envelope : Vector OAI.EditApproximation.BinaryFraction M) + (indices : List (Fin M)) : ℕ := + OAI.EditApproximation.arithmeticMapAllocation (fun i => OAI.EditApproximation.BinaryFraction.equalAllocation (envelope.get i) h + 2) indices + +def logarithmPartialWithWork (b : OAI.EditApproximation.BinaryFraction) : ℕ → OAI.EditApproximation.BinaryFraction × ℕ + | 0 => (OAI.EditApproximation.BinaryFraction.zero, 1) + | k + 1 => + let previous := logarithmPartialWithWork b k + let power := OAI.EditApproximation.BinaryFraction.powWithWork b (2 * k + 1) + let term := OAI.EditApproximation.BinaryFraction.divWithWork power.1 (OAI.EditApproximation.BinaryFraction.nat (2 * k + 1)) + let result := OAI.EditApproximation.BinaryFraction.canonicalAddWithWork previous.1 term.1 + (result.1, previous.2 + power.2 + term.2 + result.2 + Nat.size (2 * k + 1) + 5) + +def dotWithWork {d : ℕ} (left right : Vector OAI.EditApproximation.BinaryFraction d) : OAI.EditApproximation.BinaryFraction × ℕ := + OAI.EditApproximation.BinaryFraction.dotListWithWork left right (List.finRange d) + +def distanceWithWork (a b : OAI.EditApproximation.BinaryFraction) : OAI.EditApproximation.BinaryFraction × ℕ := + let difference := a.subWithWork b + (difference.1.absolute, difference.2 + 1) + +def affineErrorWithWork (position offset velocity prediction tolerance : OAI.EditApproximation.BinaryFraction) : + Bool × ℕ := + let displacement := position.subWithWork offset + let product := velocity.canonicalMulWithWork prediction + let error := displacement.1.subWithWork product.1 + let comparison := error.1.absolute.leWithWork tolerance + (comparison.1, displacement.2 + product.2 + error.2 + comparison.2 + 4) + +def bandToleranceWithWork (tau theta : OAI.EditApproximation.BinaryFraction) (b M : ℕ) : OAI.EditApproximation.BinaryFraction × ℕ := + let product := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork tau theta + let scale := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork product.1 (OAI.EditApproximation.BinaryFraction.nat b) + let result := OAI.EditApproximation.BinaryFraction.divWithWork scale.1 (OAI.EditApproximation.BinaryFraction.nat M) + (result.1, product.2 + scale.2 + result.2 + Nat.size b + Nat.size M + 3) + +def medianSeedWithWork (N multiplier : ℕ) (values : List OAI.EditApproximation.BinaryFraction) : List Bool × ℕ := + let rounded := OAI.EditApproximation.arithmeticMapWithWork (OAI.EditApproximation.BinaryFraction.scaledCeilingWithWork multiplier) values + let sorted := OAI.EditApproximation.wordSortWithWork rounded.1 + let middle := sorted.1.getD (values.length / 2) [] + let clamped := OAI.EditApproximation.wordMinWithWork N.bits middle + (clamped.1, rounded.2 + sorted.2 + values.length + clamped.2 + Nat.size N + 3) + +def groupSampleCountWithWork (M Q b : ℕ) (h : OAI.EditApproximation.BinaryFraction) : List Bool × ℕ := + let qm := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat Q) (OAI.EditApproximation.BinaryFraction.nat M) + let numerator := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork qm.1 h + let ratio := OAI.EditApproximation.BinaryFraction.divWithWork numerator.1 (OAI.EditApproximation.BinaryFraction.nat b) + let ceiling := OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork ratio.1 + let result := OAI.EditApproximation.wordMinWithWork M.bits ceiling.1 + (result.1, qm.2 + numerator.2 + ratio.2 + ceiling.2 + result.2 + + Nat.size M + Nat.size Q + Nat.size b + 5) + +def gainReadWithWork {β : Type u_1} {σ : Type u_2} (mass : β → OAI.EditApproximation.BinaryFraction) + (read : ℕ → β × σ → OAI.EditApproximation.BinaryFraction × ℕ) (s : ℕ) (i : β × σ) : OAI.EditApproximation.BinaryFraction × ℕ := + let word := read s i + let result := OAI.EditApproximation.BinaryFraction.divWithWork word.1.neg (mass i.1) + (result.1, word.2 + result.2 + 1) + +def decrementReadWithWork {β : Type u_1} {σ : Type u_2} (mass : β → OAI.EditApproximation.BinaryFraction) + (read : ℕ → β × σ → OAI.EditApproximation.BinaryFraction × ℕ) (s : ℕ) (i : β × σ) : OAI.EditApproximation.BinaryFraction × ℕ := + let first := read s i + let second := read (s + 1) i + let difference := OAI.EditApproximation.BinaryFraction.subWithWork first.1 second.1 + let result := OAI.EditApproximation.BinaryFraction.divWithWork difference.1 (mass i.1) + (result.1, first.2 + second.2 + difference.2 + result.2 + 1) + +def scaledSeedWithWork (U : ℕ) (a gap : OAI.EditApproximation.BinaryFraction) : OAI.EditApproximation.BinaryFraction × ℕ := + let ratio := OAI.EditApproximation.BinaryFraction.divWithWork (OAI.EditApproximation.BinaryFraction.nat U) a + let rounded := OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork ratio.1 + let result := OAI.EditApproximation.BinaryFraction.maxWithWork (OAI.EditApproximation.BinaryFraction.ofNaturalWord rounded.1) gap.absolute + (result.1, ratio.2 + rounded.2 + result.2 + Nat.size U + 3) + +def initialScaleGuardWithWork (U b : ℕ) (A : OAI.EditApproximation.BinaryFraction) : Bool × ℕ := + let square := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork A A + let denominator := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 16) square.1 + let lower := OAI.EditApproximation.BinaryFraction.divWithWork (OAI.EditApproximation.BinaryFraction.nat U) denominator.1 + let factor := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 4) A + let upper := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork factor.1 (OAI.EditApproximation.BinaryFraction.nat U) + let low := OAI.EditApproximation.BinaryFraction.leWithWork lower.1 (OAI.EditApproximation.BinaryFraction.nat b) + let high := OAI.EditApproximation.BinaryFraction.leWithWork (OAI.EditApproximation.BinaryFraction.nat b) upper.1 + (low.1 && high.1, square.2 + denominator.2 + lower.2 + factor.2 + upper.2 + low.2 + high.2 + + Nat.size U + Nat.size b + 7) + +def initialCenterGuardWithWork (b U : ℕ) (A : OAI.EditApproximation.BinaryFraction) : Bool × ℕ := + let lower := OAI.EditApproximation.BinaryFraction.divWithWork (OAI.EditApproximation.BinaryFraction.nat b) (OAI.EditApproximation.BinaryFraction.nat 2) + let factor := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 4) A + let upper := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork factor.1 (OAI.EditApproximation.BinaryFraction.nat b) + let low := OAI.EditApproximation.BinaryFraction.leWithWork lower.1 (OAI.EditApproximation.BinaryFraction.nat U) + let high := OAI.EditApproximation.BinaryFraction.leWithWork (OAI.EditApproximation.BinaryFraction.nat U) upper.1 + (low.1 && high.1, lower.2 + factor.2 + upper.2 + low.2 + high.2 + Nat.size b + Nat.size U + 5) + +def cellCoordinatesWithWork (side : OAI.EditApproximation.BinaryFraction) (p radius : ℕ) : List ℕ × ℕ := + let lower := OAI.EditApproximation.saturatingSubtractWithWork p radius + let upper := OAI.EditApproximation.binaryNaturalAddWithWork p radius + let firstQ := OAI.EditApproximation.BinaryFraction.divWithWork (OAI.EditApproximation.BinaryFraction.nat (OAI.EditApproximation.bitWordValue lower.1)) side + let lastQ := OAI.EditApproximation.BinaryFraction.divWithWork (OAI.EditApproximation.BinaryFraction.nat (OAI.EditApproximation.bitWordValue upper.1)) side + let first := OAI.EditApproximation.BinaryFraction.naturalFloorWithWork firstQ.1 + let last := OAI.EditApproximation.BinaryFraction.naturalFloorWithWork lastQ.1 + let stop := OAI.EditApproximation.binaryNaturalAddWithWork (OAI.EditApproximation.bitWordValue last.1) 1 + let count := OAI.EditApproximation.saturatingSubtractWithWork (OAI.EditApproximation.bitWordValue stop.1) (OAI.EditApproximation.bitWordValue first.1) + let values := List.range' (OAI.EditApproximation.bitWordValue first.1) (OAI.EditApproximation.bitWordValue count.1) + (values, lower.2 + upper.2 + firstQ.2 + lastQ.2 + first.2 + last.2 + stop.2 + count.2 + + values.length + Nat.size p + Nat.size radius + 9) + +def cellGridPointsWithWork (side : OAI.EditApproximation.BinaryFraction) (g cell : ℕ) : List ℕ × ℕ := + let next := OAI.EditApproximation.binaryNaturalAddWithWork cell 1 + let lower := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat cell) side + let upper := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat (OAI.EditApproximation.bitWordValue next.1)) side + let firstQ := OAI.EditApproximation.BinaryFraction.divWithWork lower.1 (OAI.EditApproximation.BinaryFraction.nat g) + let lastQ := OAI.EditApproximation.BinaryFraction.divWithWork upper.1 (OAI.EditApproximation.BinaryFraction.nat g) + let first := OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork firstQ.1 + let last := OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork lastQ.1 + let count := OAI.EditApproximation.saturatingSubtractWithWork (OAI.EditApproximation.bitWordValue last.1) (OAI.EditApproximation.bitWordValue first.1) + let indices := List.range' (OAI.EditApproximation.bitWordValue first.1) (OAI.EditApproximation.bitWordValue count.1) + let points := OAI.EditApproximation.arithmeticMapWithWork (fun i => + let product := OAI.EditApproximation.binaryNaturalMulWithWork g i + (OAI.EditApproximation.bitWordValue product.1, product.2 + Nat.size i + 2)) indices + (points.1, next.2 + lower.2 + upper.2 + firstQ.2 + lastQ.2 + first.2 + last.2 + count.2 + + points.2 + indices.length + Nat.size cell + Nat.size g + 10) + +def centerEligibilityWithWork (b F : ℕ) (a initial : OAI.EditApproximation.BinaryFraction) : Bool × ℕ := + let denominator := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 4) a + let lower := OAI.EditApproximation.BinaryFraction.divWithWork (OAI.EditApproximation.BinaryFraction.nat b) denominator.1 + let factor := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 8) (OAI.EditApproximation.BinaryFraction.nat F) + let upper := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork factor.1 (OAI.EditApproximation.BinaryFraction.nat b) + let low := OAI.EditApproximation.BinaryFraction.leWithWork lower.1 initial + let high := OAI.EditApproximation.BinaryFraction.leWithWork initial upper.1 + (low.1 && high.1, denominator.2 + lower.2 + factor.2 + upper.2 + low.2 + high.2 + + Nat.size b + Nat.size F + 8) + +def refinementScaleGuardWithWork (F b : ℕ) (a w : OAI.EditApproximation.BinaryFraction) : Bool × ℕ := + let denominator := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 16) (OAI.EditApproximation.BinaryFraction.nat F) + let lower := OAI.EditApproximation.BinaryFraction.divWithWork w denominator.1 + let factor := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 8) a + let upper := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork factor.1 w + let low := OAI.EditApproximation.BinaryFraction.leWithWork lower.1 (OAI.EditApproximation.BinaryFraction.nat b) + let high := OAI.EditApproximation.BinaryFraction.leWithWork (OAI.EditApproximation.BinaryFraction.nat b) upper.1 + (low.1 && high.1, denominator.2 + lower.2 + factor.2 + upper.2 + low.2 + high.2 + + Nat.size b + Nat.size F + 8) + +def coarseDivideWithWork (a divisor : OAI.EditApproximation.BinaryFraction) : OAI.EditApproximation.BinaryFraction × ℕ := + let quotient := OAI.EditApproximation.BinaryFraction.divWithWork a divisor + let result := OAI.EditApproximation.BinaryFraction.fixedDenominatorWithWork quotient.1 a.denominator a.denominator_pos + (result.1, quotient.2 + result.2 + 2) + +def coarseGridLeftWithWork (two : OAI.EditApproximation.BinaryFraction) : List OAI.EditApproximation.BinaryFraction → List OAI.EditApproximation.BinaryFraction × ℕ + | [] => ([], 0) + | head :: rest => OAI.EditApproximation.BinaryFraction.coarseGridScanWithWork two head rest + +def coarseMinimumWithWork : List OAI.EditApproximation.BinaryFraction → OAI.EditApproximation.BinaryFraction × ℕ + | [] => (OAI.EditApproximation.BinaryFraction.nat 0, 1) + | a :: rest => OAI.EditApproximation.BinaryFraction.minimumWithWork a rest + +def powAllocation (a : OAI.EditApproximation.BinaryFraction) : ℕ → ℕ + | 0 => 0 + | n + 1 => powAllocation a n + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation (OAI.EditApproximation.BinaryFraction.powWithWork a n).1 a + +def dotListAllocation {d : ℕ} (left right : Vector OAI.EditApproximation.BinaryFraction d) : List (Fin d) → ℕ + | [] => 0 + | i :: rest => dotListAllocation left right rest + + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation (left.get i) (right.get i) + + OAI.EditApproximation.BinaryFraction.canonicalAddAllocation (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (left.get i) (right.get i)).1 (OAI.EditApproximation.BinaryFraction.dotListWithWork left right rest).1 + +def minimumAllocation (fallback : OAI.EditApproximation.BinaryFraction) : List OAI.EditApproximation.BinaryFraction → ℕ + | [] => 0 + | head :: rest => minimumAllocation fallback rest + + OAI.EditApproximation.BinaryFraction.minAllocation head (OAI.EditApproximation.BinaryFraction.minimumWithWork fallback rest).1 + +def maximumAllocation (fallback : OAI.EditApproximation.BinaryFraction) : List OAI.EditApproximation.BinaryFraction → ℕ + | [] => 0 + | head :: rest => maximumAllocation fallback rest + + OAI.EditApproximation.BinaryFraction.maxAllocation head (OAI.EditApproximation.BinaryFraction.maximumWithWork fallback rest).1 + +def distanceAllocation (a b : OAI.EditApproximation.BinaryFraction) : ℕ := OAI.EditApproximation.BinaryFraction.subAllocation a b + 0 + +def optimizerUpdateAllocation {d : ℕ} (j : ℕ) (previous selected : Vector OAI.EditApproximation.BinaryFraction d) : ℕ := + let step := (OAI.EditApproximation.BinaryFraction.divWithWork (OAI.EditApproximation.BinaryFraction.nat 2) (OAI.EditApproximation.BinaryFraction.nat (j + 2))).1 + let complement := (OAI.EditApproximation.BinaryFraction.subWithWork OAI.EditApproximation.BinaryFraction.one step).1 + OAI.EditApproximation.BinaryFraction.divAllocation (OAI.EditApproximation.BinaryFraction.nat 2) (OAI.EditApproximation.BinaryFraction.nat (j + 2)) + OAI.EditApproximation.BinaryFraction.subAllocation OAI.EditApproximation.BinaryFraction.one step + + OAI.EditApproximation.vectorMapAllocation d (OAI.EditApproximation.BinaryFraction.optimizerUpdateCellAllocation step complement previous selected) + + Nat.size (j + 2) + 1 + +def affineErrorAllocation (position offset velocity prediction tolerance : OAI.EditApproximation.BinaryFraction) : ℕ := + let displacement := (OAI.EditApproximation.BinaryFraction.subWithWork position offset).1 + let product := (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork velocity prediction).1 + OAI.EditApproximation.BinaryFraction.subAllocation position offset + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation velocity prediction + + OAI.EditApproximation.BinaryFraction.subAllocation displacement product + OAI.EditApproximation.BinaryFraction.leAllocation (OAI.EditApproximation.BinaryFraction.subWithWork displacement product).1.absolute tolerance + +def bandToleranceAllocation (tau theta : OAI.EditApproximation.BinaryFraction) (b M : ℕ) : ℕ := + let product := (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork tau theta).1 + let scale := (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork product (OAI.EditApproximation.BinaryFraction.nat b)).1 + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation tau theta + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation product (OAI.EditApproximation.BinaryFraction.nat b) + + OAI.EditApproximation.BinaryFraction.divAllocation scale (OAI.EditApproximation.BinaryFraction.nat M) + Nat.size b + Nat.size M + +def initialScaleGuardAllocation (U b : ℕ) (A : OAI.EditApproximation.BinaryFraction) : ℕ := + let square := (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork A A).1 + let denominator := (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 16) square).1 + let lower := (OAI.EditApproximation.BinaryFraction.divWithWork (OAI.EditApproximation.BinaryFraction.nat U) denominator).1 + let factor := (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 4) A).1 + let upper := (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork factor (OAI.EditApproximation.BinaryFraction.nat U)).1 + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation A A + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation (OAI.EditApproximation.BinaryFraction.nat 16) square + OAI.EditApproximation.BinaryFraction.divAllocation (OAI.EditApproximation.BinaryFraction.nat U) denominator + + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation (OAI.EditApproximation.BinaryFraction.nat 4) A + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation factor (OAI.EditApproximation.BinaryFraction.nat U) + + OAI.EditApproximation.BinaryFraction.leAllocation lower (OAI.EditApproximation.BinaryFraction.nat b) + OAI.EditApproximation.BinaryFraction.leAllocation (OAI.EditApproximation.BinaryFraction.nat b) upper + Nat.size U + Nat.size b + +def initialCenterGuardAllocation (b U : ℕ) (A : OAI.EditApproximation.BinaryFraction) : ℕ := + let lower := (OAI.EditApproximation.BinaryFraction.divWithWork (OAI.EditApproximation.BinaryFraction.nat b) (OAI.EditApproximation.BinaryFraction.nat 2)).1 + let factor := (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 4) A).1 + let upper := (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork factor (OAI.EditApproximation.BinaryFraction.nat b)).1 + OAI.EditApproximation.BinaryFraction.divAllocation (OAI.EditApproximation.BinaryFraction.nat b) (OAI.EditApproximation.BinaryFraction.nat 2) + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation (OAI.EditApproximation.BinaryFraction.nat 4) A + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation factor (OAI.EditApproximation.BinaryFraction.nat b) + + OAI.EditApproximation.BinaryFraction.leAllocation lower (OAI.EditApproximation.BinaryFraction.nat U) + OAI.EditApproximation.BinaryFraction.leAllocation (OAI.EditApproximation.BinaryFraction.nat U) upper + Nat.size b + Nat.size U + +def scaledSeedAllocation (U : ℕ) (a gap : OAI.EditApproximation.BinaryFraction) : ℕ := + let ratio := (OAI.EditApproximation.BinaryFraction.divWithWork (OAI.EditApproximation.BinaryFraction.nat U) a).1 + let rounded := (OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork ratio).1 + OAI.EditApproximation.BinaryFraction.divAllocation (OAI.EditApproximation.BinaryFraction.nat U) a + OAI.EditApproximation.BinaryFraction.naturalCeilingAllocation ratio + + OAI.EditApproximation.BinaryFraction.maxAllocation (OAI.EditApproximation.BinaryFraction.ofNaturalWord rounded) gap.absolute + Nat.size U + 2 + +def centerEligibilityAllocation (b F : ℕ) (a initial : OAI.EditApproximation.BinaryFraction) : ℕ := + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation (OAI.EditApproximation.BinaryFraction.nat 4) a + + OAI.EditApproximation.BinaryFraction.divAllocation (OAI.EditApproximation.BinaryFraction.nat b) (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 4) a).1 + + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation (OAI.EditApproximation.BinaryFraction.nat 8) (OAI.EditApproximation.BinaryFraction.nat F) + + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 8) (OAI.EditApproximation.BinaryFraction.nat F)).1 (OAI.EditApproximation.BinaryFraction.nat b) + + OAI.EditApproximation.BinaryFraction.leAllocation (OAI.EditApproximation.BinaryFraction.divWithWork (OAI.EditApproximation.BinaryFraction.nat b) (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 4) a).1).1 initial + + OAI.EditApproximation.BinaryFraction.leAllocation initial (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 8) (OAI.EditApproximation.BinaryFraction.nat F)).1 (OAI.EditApproximation.BinaryFraction.nat b)).1 + Nat.size b + Nat.size F + +def refinementScaleGuardAllocation (F b : ℕ) (a w : OAI.EditApproximation.BinaryFraction) : ℕ := + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation (OAI.EditApproximation.BinaryFraction.nat 16) (OAI.EditApproximation.BinaryFraction.nat F) + + OAI.EditApproximation.BinaryFraction.divAllocation w (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 16) (OAI.EditApproximation.BinaryFraction.nat F)).1 + + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation (OAI.EditApproximation.BinaryFraction.nat 8) a + + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 8) a).1 w + + OAI.EditApproximation.BinaryFraction.leAllocation (OAI.EditApproximation.BinaryFraction.divWithWork w (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 16) (OAI.EditApproximation.BinaryFraction.nat F)).1).1 (OAI.EditApproximation.BinaryFraction.nat b) + + OAI.EditApproximation.BinaryFraction.leAllocation (OAI.EditApproximation.BinaryFraction.nat b) (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 8) a).1 w).1 + Nat.size b + Nat.size F + +def cellCoordinatesAllocation (side : OAI.EditApproximation.BinaryFraction) (p radius : ℕ) : ℕ := + let lower := (OAI.EditApproximation.saturatingSubtractWithWork p radius).1 + let upper := (OAI.EditApproximation.binaryNaturalAddWithWork p radius).1 + let firstQ := (OAI.EditApproximation.BinaryFraction.divWithWork (OAI.EditApproximation.BinaryFraction.nat (OAI.EditApproximation.bitWordValue lower)) side).1 + let lastQ := (OAI.EditApproximation.BinaryFraction.divWithWork (OAI.EditApproximation.BinaryFraction.nat (OAI.EditApproximation.bitWordValue upper)) side).1 + let first := (OAI.EditApproximation.BinaryFraction.naturalFloorWithWork firstQ).1 + let last := (OAI.EditApproximation.BinaryFraction.naturalFloorWithWork lastQ).1 + let stop := (OAI.EditApproximation.binaryNaturalAddWithWork (OAI.EditApproximation.bitWordValue last) 1).1 + let count := (OAI.EditApproximation.saturatingSubtractWithWork (OAI.EditApproximation.bitWordValue stop) (OAI.EditApproximation.bitWordValue first)).1 + OAI.EditApproximation.saturatingSubtractAllocation p radius + OAI.EditApproximation.binaryNaturalAddAllocation p radius + + OAI.EditApproximation.BinaryFraction.divAllocation (OAI.EditApproximation.BinaryFraction.nat (OAI.EditApproximation.bitWordValue lower)) side + OAI.EditApproximation.BinaryFraction.divAllocation (OAI.EditApproximation.BinaryFraction.nat (OAI.EditApproximation.bitWordValue upper)) side + + OAI.EditApproximation.BinaryFraction.naturalFloorAllocation firstQ + OAI.EditApproximation.BinaryFraction.naturalFloorAllocation lastQ + + OAI.EditApproximation.binaryNaturalAddAllocation (OAI.EditApproximation.bitWordValue last) 1 + + OAI.EditApproximation.saturatingSubtractAllocation (OAI.EditApproximation.bitWordValue stop) (OAI.EditApproximation.bitWordValue first) + OAI.EditApproximation.bitWordValue count + + Nat.size p + Nat.size radius + +def cellGridPointsAllocation (side : OAI.EditApproximation.BinaryFraction) (g cell : ℕ) : ℕ := + let next := (OAI.EditApproximation.binaryNaturalAddWithWork cell 1).1 + let lower := (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat cell) side).1 + let upper := (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat (OAI.EditApproximation.bitWordValue next)) side).1 + let firstQ := (OAI.EditApproximation.BinaryFraction.divWithWork lower (OAI.EditApproximation.BinaryFraction.nat g)).1 + let lastQ := (OAI.EditApproximation.BinaryFraction.divWithWork upper (OAI.EditApproximation.BinaryFraction.nat g)).1 + let first := (OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork firstQ).1 + let last := (OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork lastQ).1 + let count := (OAI.EditApproximation.saturatingSubtractWithWork (OAI.EditApproximation.bitWordValue last) (OAI.EditApproximation.bitWordValue first)).1 + let indices := List.range' (OAI.EditApproximation.bitWordValue first) (OAI.EditApproximation.bitWordValue count) + OAI.EditApproximation.binaryNaturalAddAllocation cell 1 + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation (OAI.EditApproximation.BinaryFraction.nat cell) side + + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation (OAI.EditApproximation.BinaryFraction.nat (OAI.EditApproximation.bitWordValue next)) side + OAI.EditApproximation.BinaryFraction.divAllocation lower (OAI.EditApproximation.BinaryFraction.nat g) + OAI.EditApproximation.BinaryFraction.divAllocation upper (OAI.EditApproximation.BinaryFraction.nat g) + + OAI.EditApproximation.BinaryFraction.naturalCeilingAllocation firstQ + OAI.EditApproximation.BinaryFraction.naturalCeilingAllocation lastQ + + OAI.EditApproximation.saturatingSubtractAllocation (OAI.EditApproximation.bitWordValue last) (OAI.EditApproximation.bitWordValue first) + + OAI.EditApproximation.arithmeticMapAllocation (fun i => OAI.EditApproximation.binaryNaturalMulAllocation g i + Nat.size i) indices + + indices.length + Nat.size cell + Nat.size g + +def medianSeedAllocation (N multiplier : ℕ) (values : List OAI.EditApproximation.BinaryFraction) : ℕ := + let rounded := (OAI.EditApproximation.arithmeticMapWithWork (OAI.EditApproximation.BinaryFraction.scaledCeilingWithWork multiplier) values).1 + let sorted := (OAI.EditApproximation.wordSortWithWork rounded).1 + OAI.EditApproximation.arithmeticMapAllocation (OAI.EditApproximation.BinaryFraction.scaledCeilingAllocation multiplier) values + OAI.EditApproximation.wordSortAllocation rounded + + OAI.EditApproximation.wordLEAllocation N.bits (sorted.getD (values.length / 2) []) + + Nat.size N + +def groupSampleCountAllocation (M Q b : ℕ) (h : OAI.EditApproximation.BinaryFraction) : ℕ := + let qm := (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat Q) (OAI.EditApproximation.BinaryFraction.nat M)).1 + let numerator := (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork qm h).1 + let ratio := (OAI.EditApproximation.BinaryFraction.divWithWork numerator (OAI.EditApproximation.BinaryFraction.nat b)).1 + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation (OAI.EditApproximation.BinaryFraction.nat Q) (OAI.EditApproximation.BinaryFraction.nat M) + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation qm h + + OAI.EditApproximation.BinaryFraction.divAllocation numerator (OAI.EditApproximation.BinaryFraction.nat b) + OAI.EditApproximation.BinaryFraction.naturalCeilingAllocation ratio + + OAI.EditApproximation.wordLEAllocation M.bits (OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork ratio).1 + + Nat.size M + Nat.size Q + Nat.size b + +def refinementUpdateAllocation (delta cone : OAI.EditApproximation.BinaryFraction) : Option OAI.EditApproximation.BinaryFraction → ℕ + | none => 0 + | some online => + let denominator := (OAI.EditApproximation.BinaryFraction.canonicalAddWithWork OAI.EditApproximation.BinaryFraction.one delta).1 + let lower := (OAI.EditApproximation.BinaryFraction.divWithWork cone denominator).1 + let clipped := (OAI.EditApproximation.BinaryFraction.maxWithWork lower online).1 + OAI.EditApproximation.BinaryFraction.canonicalAddAllocation OAI.EditApproximation.BinaryFraction.one delta + OAI.EditApproximation.BinaryFraction.divAllocation cone denominator + + OAI.EditApproximation.BinaryFraction.maxAllocation lower online + OAI.EditApproximation.BinaryFraction.minAllocation cone clipped + +def coefficientAllocation (kappa : OAI.EditApproximation.BinaryFraction) : ℕ := + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation (OAI.EditApproximation.BinaryFraction.nat 2) kappa + OAI.EditApproximation.BinaryFraction.subAllocation OAI.EditApproximation.BinaryFraction.one (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 2) kappa).1 + 0 + +def gainReadAllocation {β : Type u_1} {σ : Type u_2} (mass : β → OAI.EditApproximation.BinaryFraction) + (read : ℕ → β × σ → OAI.EditApproximation.BinaryFraction × ℕ) (footprint : ℕ → β × σ → ℕ) + (s : ℕ) (i : β × σ) : ℕ := + footprint s i + OAI.EditApproximation.BinaryFraction.divAllocation (read s i).1.neg (mass i.1) + 0 + +def decrementReadAllocation {β : Type u_1} {σ : Type u_2} (mass : β → OAI.EditApproximation.BinaryFraction) + (read : ℕ → β × σ → OAI.EditApproximation.BinaryFraction × ℕ) (footprint : ℕ → β × σ → ℕ) + (s : ℕ) (i : β × σ) : ℕ := + footprint s i + footprint (s + 1) i + OAI.EditApproximation.BinaryFraction.subAllocation (read s i).1 (read (s + 1) i).1 + + OAI.EditApproximation.BinaryFraction.divAllocation (OAI.EditApproximation.BinaryFraction.subWithWork (read s i).1 (read (s + 1) i).1).1 (mass i.1) + 0 + +def logarithmWithWork (r : OAI.EditApproximation.BinaryFraction) (k : ℕ) : OAI.EditApproximation.BinaryFraction × ℕ := + let numerator := OAI.EditApproximation.BinaryFraction.subWithWork r OAI.EditApproximation.BinaryFraction.one + let denominator := OAI.EditApproximation.BinaryFraction.canonicalAddWithWork r OAI.EditApproximation.BinaryFraction.one + let ratio := OAI.EditApproximation.BinaryFraction.divWithWork numerator.1 denominator.1 + let subtotal := OAI.EditApproximation.BinaryFraction.logarithmPartialWithWork ratio.1 k + let result := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 2) subtotal.1 + (result.1, numerator.2 + denominator.2 + ratio.2 + subtotal.2 + result.2 + 5) + +def optimisticTermReadWithWork {β : Type u_1} {σ : Type u_2} (mass : β → OAI.EditApproximation.BinaryFraction) + (read : ℕ → β × σ → OAI.EditApproximation.BinaryFraction × ℕ) (coefficient : OAI.EditApproximation.BinaryFraction) + (s : ℕ) (i : β × σ) : OAI.EditApproximation.BinaryFraction × ℕ := + let gain := OAI.EditApproximation.BinaryFraction.gainReadWithWork mass read s i + let decrement := OAI.EditApproximation.BinaryFraction.decrementReadWithWork mass read s i + let scaled := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork coefficient decrement.1 + let total := OAI.EditApproximation.BinaryFraction.canonicalAddWithWork gain.1 scaled.1 + (total.1, gain.2 + decrement.2 + scaled.2 + total.2 + 2) + +def queryExponentsWithWork (N F : ℕ) (a w : OAI.EditApproximation.BinaryFraction) : List ℕ × ℕ := + let count := max 1 N.bits.length + let selected := OAI.EditApproximation.filterWithWork (fun e => + let guard := OAI.EditApproximation.BinaryFraction.refinementScaleGuardWithWork F (2 ^ e) a w + (guard.1, guard.2 + e + 2)) (List.range count) + (selected.1, selected.2 + count + N.bits.length + 2) + +def seedMedianWithWork (N multiplier : ℕ) (values : List OAI.EditApproximation.BinaryFraction) : List Bool × ℕ := + let median := OAI.EditApproximation.BinaryFraction.medianSeedWithWork N multiplier values + let trimmed := OAI.EditApproximation.trimBitWordWithWork median.1 + (trimmed.1, median.2 + trimmed.2 + 1) + +def coarseGridPenaltyWithWork (two : OAI.EditApproximation.BinaryFraction) (source : List OAI.EditApproximation.BinaryFraction) : + List OAI.EditApproximation.BinaryFraction × ℕ := + let left := OAI.EditApproximation.BinaryFraction.coarseGridLeftWithWork two source + let right := OAI.EditApproximation.BinaryFraction.coarseGridLeftWithWork two source.reverse + let result := OAI.EditApproximation.BinaryFraction.coarseGridZipMinimumWithWork left.1 right.1.reverse + (result.1, left.2 + right.2 + result.2 + 3 * source.length) + +def coarseChildThresholdWithWork (B q : ℕ) (allowance : OAI.EditApproximation.BinaryFraction) (draw : Fin B) : + OAI.EditApproximation.BinaryFraction × ℕ := + let numerator := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork allowance (OAI.EditApproximation.BinaryFraction.nat (draw.val + 1)) + let divisor := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat B) (OAI.EditApproximation.BinaryFraction.nat q) + let result := OAI.EditApproximation.BinaryFraction.coarseDivideWithWork numerator.1 divisor.1 + (result.1, numerator.2 + divisor.2 + result.2 + Nat.size (draw.val + 1) + Nat.size B + Nat.size q + 4) + +def coarseChildAllowanceWithWork (L : ℕ) (threshold : OAI.EditApproximation.BinaryFraction) : OAI.EditApproximation.BinaryFraction × ℕ := + let result := OAI.EditApproximation.BinaryFraction.coarseDivideWithWork threshold (OAI.EditApproximation.BinaryFraction.nat L) + (result.1, result.2 + Nat.size L + 1) + +def logarithmPartialAllocation (b : OAI.EditApproximation.BinaryFraction) : ℕ → ℕ + | 0 => 0 + | n + 1 => + let previous := (OAI.EditApproximation.BinaryFraction.logarithmPartialWithWork b n).1 + let power := (OAI.EditApproximation.BinaryFraction.powWithWork b (2 * n + 1)).1 + let term := (OAI.EditApproximation.BinaryFraction.divWithWork power (OAI.EditApproximation.BinaryFraction.nat (2 * n + 1))).1 + logarithmPartialAllocation b n + OAI.EditApproximation.BinaryFraction.powAllocation b (2 * n + 1) + + OAI.EditApproximation.BinaryFraction.divAllocation power (OAI.EditApproximation.BinaryFraction.nat (2 * n + 1)) + OAI.EditApproximation.BinaryFraction.canonicalAddAllocation previous term + Nat.size (2 * n + 1) + 1 + +def bandMassAllocation {M : ℕ} (mass : Vector OAI.EditApproximation.BinaryFraction M) : ℕ := + OAI.EditApproximation.BinaryFraction.dotListAllocation mass (Vector.replicate M OAI.EditApproximation.BinaryFraction.one) (List.finRange M) + 2 * M + +def sumListAllocation (values : List OAI.EditApproximation.BinaryFraction) : ℕ := + OAI.EditApproximation.BinaryFraction.dotListAllocation (Vector.ofFn values.get) (Vector.replicate values.length OAI.EditApproximation.BinaryFraction.one) + (List.finRange values.length) + 3 * values.length + +def naturalDistanceLeAllocation (a b radius : ℕ) : ℕ := + OAI.EditApproximation.BinaryFraction.distanceAllocation (OAI.EditApproximation.BinaryFraction.nat a) (OAI.EditApproximation.BinaryFraction.nat b) + OAI.EditApproximation.BinaryFraction.leAllocation (OAI.EditApproximation.BinaryFraction.distanceWithWork (OAI.EditApproximation.BinaryFraction.nat a) (OAI.EditApproximation.BinaryFraction.nat b)).1 (OAI.EditApproximation.BinaryFraction.nat radius) + + Nat.size a + Nat.size b + Nat.size radius + +def queryExponentsAllocation (N F : ℕ) (a w : OAI.EditApproximation.BinaryFraction) : ℕ := + let count := max 1 N.bits.length + OAI.EditApproximation.filterAllocation (fun e => ((OAI.EditApproximation.BinaryFraction.refinementScaleGuardWithWork F (2 ^ e) a w).1, + (OAI.EditApproximation.BinaryFraction.refinementScaleGuardWithWork F (2 ^ e) a w).2 + e + 2)) + (fun e => OAI.EditApproximation.BinaryFraction.refinementScaleGuardAllocation F (2 ^ e) a w + e + 1) (List.range count) + + count + N.bits.length + +def seedMedianAllocation (N multiplier : ℕ) (values : List OAI.EditApproximation.BinaryFraction) : ℕ := + OAI.EditApproximation.BinaryFraction.medianSeedAllocation N multiplier values + + OAI.EditApproximation.trimBitWordAllocation (OAI.EditApproximation.BinaryFraction.medianSeedWithWork N multiplier values).1 + 0 + +def onlineMinimumAllocation : List OAI.EditApproximation.BinaryFraction → ℕ + | [] => 0 + | first :: rest => OAI.EditApproximation.BinaryFraction.minimumAllocation first rest + +def optimisticTermReadAllocation {β : Type u_1} {σ : Type u_2} (mass : β → OAI.EditApproximation.BinaryFraction) + (read : ℕ → β × σ → OAI.EditApproximation.BinaryFraction × ℕ) (footprint : ℕ → β × σ → ℕ) + (coefficient : OAI.EditApproximation.BinaryFraction) (s : ℕ) (i : β × σ) : ℕ := + let gain := (OAI.EditApproximation.BinaryFraction.gainReadWithWork mass read s i).1 + let decrement := (OAI.EditApproximation.BinaryFraction.decrementReadWithWork mass read s i).1 + OAI.EditApproximation.BinaryFraction.gainReadAllocation mass read footprint s i + OAI.EditApproximation.BinaryFraction.decrementReadAllocation mass read footprint s i + + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation coefficient decrement + + OAI.EditApproximation.BinaryFraction.canonicalAddAllocation gain (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork coefficient decrement).1 + 0 + +def gradientCellWithWork {d : ℕ} (G : ℕ) (linear point : Vector OAI.EditApproximation.BinaryFraction d) + (i : Fin d) : OAI.EditApproximation.BinaryFraction × ℕ := + let smoothing := OAI.EditApproximation.BinaryFraction.powWithWork (OAI.EditApproximation.BinaryFraction.nat G) 50 + let inverse := smoothing.1.invWithWork + let shifted := OAI.EditApproximation.BinaryFraction.canonicalAddWithWork (point.get i) inverse.1 + let logarithm := OAI.EditApproximation.BinaryFraction.logarithmWithWork shifted.1 (G ^ 60) + let deficit := OAI.EditApproximation.BinaryFraction.subWithWork logarithm.1.neg OAI.EditApproximation.BinaryFraction.one + let result := OAI.EditApproximation.BinaryFraction.canonicalAddWithWork deficit.1 (linear.get i) + (result.1, smoothing.2 + inverse.2 + shifted.2 + logarithm.2 + deficit.2 + result.2 + + Nat.size G + 70) + +def queryScalesWithWork (N F : ℕ) (a value : OAI.EditApproximation.BinaryFraction) : List ℕ × ℕ := + let exponents := OAI.EditApproximation.BinaryFraction.queryExponentsWithWork N F a value + let scales := OAI.EditApproximation.arithmeticMapWithWork (fun e => (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.powerTwoWord e), e + 3)) exponents.1 + (scales.1, exponents.2 + scales.2 + 1) + +def querySeedMedianWithWork (N multiplier : ℕ) (words : List OAI.EditApproximation.BinaryFraction) : OAI.EditApproximation.BinaryFraction × ℕ := + let result := OAI.EditApproximation.BinaryFraction.seedMedianWithWork N multiplier words + (OAI.EditApproximation.BinaryFraction.ofNaturalWord result.1, result.2 + result.1.length + 1) + +def coarseBinaryPenaltyWithWork (two : OAI.EditApproximation.BinaryFraction) : OAI.EditApproximation.BinaryFraction.CoarseBinaryArray → OAI.EditApproximation.BinaryFraction.CoarseBinaryArray × ℕ + | none => (none, 0) + | some values => + let result := OAI.EditApproximation.BinaryFraction.coarseGridPenaltyWithWork two values + (some result.1, result.2) + +def logarithmAllocation (r : OAI.EditApproximation.BinaryFraction) (n : ℕ) : ℕ := + let numerator := (OAI.EditApproximation.BinaryFraction.subWithWork r OAI.EditApproximation.BinaryFraction.one).1 + let denominator := (OAI.EditApproximation.BinaryFraction.canonicalAddWithWork r OAI.EditApproximation.BinaryFraction.one).1 + let ratio := (OAI.EditApproximation.BinaryFraction.divWithWork numerator denominator).1 + OAI.EditApproximation.BinaryFraction.subAllocation r OAI.EditApproximation.BinaryFraction.one + OAI.EditApproximation.BinaryFraction.canonicalAddAllocation r OAI.EditApproximation.BinaryFraction.one + OAI.EditApproximation.BinaryFraction.divAllocation numerator denominator + + OAI.EditApproximation.BinaryFraction.logarithmPartialAllocation ratio n + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation (OAI.EditApproximation.BinaryFraction.nat 2) (OAI.EditApproximation.BinaryFraction.logarithmPartialWithWork ratio n).1 + +def queryScalesAllocation (N F : ℕ) (a value : OAI.EditApproximation.BinaryFraction) : ℕ := + OAI.EditApproximation.BinaryFraction.queryExponentsAllocation N F a value + + OAI.EditApproximation.arithmeticMapAllocation (fun e => e + 1) (OAI.EditApproximation.BinaryFraction.queryExponentsWithWork N F a value).1 + +def coarseIndexChildren {B : ℕ} (k q L : ℕ) (two : OAI.EditApproximation.BinaryFraction) + (width : Fin B → ℕ) + (evaluate : Fin B → OAI.EditApproximation.BinaryFraction → ℕ → OAI.EditApproximation.BinaryFraction.CoarseBinaryArray × ℕ) + (draw : Fin B → Fin B) (allowance : OAI.EditApproximation.BinaryFraction) : + List (Fin B) → ℕ → OAI.EditApproximation.BinaryFraction.CoarseBinaryArray × ℕ + | [], _ => (none, 0) + | i :: rest, start => + let threshold := OAI.EditApproximation.BinaryFraction.coarseChildThresholdWithWork B q allowance (draw i) + let childAllowance := OAI.EditApproximation.BinaryFraction.coarseChildAllowanceWithWork L threshold.1 + let evaluated := evaluate i childAllowance.1 start + let penalty := OAI.EditApproximation.BinaryFraction.coarseBinaryPenaltyWithWork two evaluated.1 + let scale := OAI.EditApproximation.BinaryFraction.coarseChildAllowanceWithWork q allowance + let contribution := OAI.EditApproximation.BinaryFraction.coarseBinaryMapWithWork (OAI.EditApproximation.BinaryFraction.coarseContributionWithWork threshold.1 scale.1) penalty.1 + let remainder := coarseIndexChildren k q L two width evaluate draw allowance rest (start + width i) + let total := OAI.EditApproximation.BinaryFraction.coarseBinaryAddWithWork contribution.1 remainder.1 + (total.1, threshold.2 + childAllowance.2 + evaluated.2 + penalty.2 + scale.2 + contribution.2 + + remainder.2 + total.2 + Nat.size start + Nat.size (width i) + 9) + +def gradientCellAllocation {d : ℕ} (G : ℕ) (linear point : Vector OAI.EditApproximation.BinaryFraction d) + (i : Fin d) : ℕ := + let smoothing := (OAI.EditApproximation.BinaryFraction.powWithWork (OAI.EditApproximation.BinaryFraction.nat G) 50).1 + let inverse := smoothing.invWithWork.1 + let shifted := (OAI.EditApproximation.BinaryFraction.canonicalAddWithWork (point.get i) inverse).1 + let logarithm := (OAI.EditApproximation.BinaryFraction.logarithmWithWork shifted (G ^ 60)).1 + let deficit := (OAI.EditApproximation.BinaryFraction.subWithWork logarithm.neg OAI.EditApproximation.BinaryFraction.one).1 + OAI.EditApproximation.BinaryFraction.powAllocation (OAI.EditApproximation.BinaryFraction.nat G) 50 + OAI.EditApproximation.BinaryFraction.invAllocation smoothing + + OAI.EditApproximation.BinaryFraction.canonicalAddAllocation (point.get i) inverse + OAI.EditApproximation.BinaryFraction.logarithmAllocation shifted (G ^ 60) + + OAI.EditApproximation.BinaryFraction.subAllocation logarithm.neg OAI.EditApproximation.BinaryFraction.one + OAI.EditApproximation.BinaryFraction.canonicalAddAllocation deficit (linear.get i) + Nat.size G + 1 + +def coarseIndexedWithWork {B : ℕ} (k q L n : ℕ) (source target : List ℕ) + (two : OAI.EditApproximation.BinaryFraction) : (d offset : ℕ) → OAI.EditApproximation.CoarseThresholdDraws B d → + OAI.EditApproximation.BinaryFraction → ℕ → OAI.EditApproximation.BinaryFraction.CoarseBinaryArray × ℕ + | 0, offset, _, allowance, start => + let descriptor := OAI.EditApproximation.coarseDescriptorWithWork B 0 n offset + let size := OAI.EditApproximation.bitWordValue descriptor.1 + let prune := OAI.EditApproximation.BinaryFraction.leWithWork (OAI.EditApproximation.BinaryFraction.nat size) allowance + if prune.1 then (none, descriptor.2 + prune.2 + Nat.size size + 1) else + let letter := OAI.EditApproximation.coarsePaddedReadWithWork n source offset + let cells := OAI.EditApproximation.arithmeticMapWithWork (fun shift : Fin (2 * k + 1) => + let mismatch := OAI.EditApproximation.BinaryFraction.coarseReadShiftWithWork k n target letter.1 start shift + let value := OAI.EditApproximation.BinaryFraction.coarseGridNatWithWork allowance.denominator allowance.denominator_pos mismatch.1 + (value.1, value.2 + mismatch.2)) (List.finRange (2 * k + 1)) + (some cells.1, descriptor.2 + letter.2 + prune.2 + cells.2 + + Nat.size size + 3 * (2 * k + 1) + 1) + | d + 1, offset, (draws, below), allowance, start => + let descriptor := OAI.EditApproximation.coarseDescriptorWithWork B (d + 1) n offset + let size := OAI.EditApproximation.bitWordValue descriptor.1 + let prune := OAI.EditApproximation.BinaryFraction.leWithWork (OAI.EditApproximation.BinaryFraction.nat size) allowance + if prune.1 then (none, descriptor.2 + prune.2 + Nat.size size + 1) else + let capacity := OAI.EditApproximation.bitPowerWithWork B.bits d + let childOffset := fun i : Fin B => + OAI.EditApproximation.coarseChildOffsetWithWork offset (OAI.EditApproximation.bitWordValue capacity.1) i.val + let childSize := fun i : Fin B => + OAI.EditApproximation.coarseDescriptorWithWork B d n (OAI.EditApproximation.bitWordValue (childOffset i).1) + let result := OAI.EditApproximation.BinaryFraction.coarseIndexChildren k q L two + (fun i => OAI.EditApproximation.bitWordValue (childSize i).1) + (fun i a s => + let evaluated := coarseIndexedWithWork k q L n source target two d + (OAI.EditApproximation.bitWordValue (childOffset i).1) (below i) a s + let next := OAI.EditApproximation.binaryNaturalAddWithWork s (OAI.EditApproximation.bitWordValue (childSize i).1) + (evaluated.1, evaluated.2 + 3 * ((childOffset i).2 + (childSize i).2 + next.2 + 3))) + draws allowance (List.finRange B) start + (result.1, descriptor.2 + capacity.2 + result.2 + prune.2 + Nat.size size + B + 1) + +def gradientAllocation {d : ℕ} (G : ℕ) (linear point : Vector OAI.EditApproximation.BinaryFraction d) : ℕ := + OAI.EditApproximation.vectorMapAllocation d (OAI.EditApproximation.BinaryFraction.gradientCellAllocation G linear point) + + +end OAI.EditApproximation.BinaryFraction +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BinaryFraction +open Finset + +def gradientWithWork {d : ℕ} (G : ℕ) (linear point : Vector OAI.EditApproximation.BinaryFraction d) : + Vector OAI.EditApproximation.BinaryFraction d × ℕ := + OAI.EditApproximation.vectorMapWithWork d (OAI.EditApproximation.BinaryFraction.gradientCellWithWork G linear point) + +def scoredArgmaxWithWork {α : Type u_1} (score : α → OAI.EditApproximation.BinaryFraction × ℕ) : + List α → Option (α × OAI.EditApproximation.BinaryFraction) × ℕ + | [] => (none, 0) + | a :: rest => + let tail := scoredArgmaxWithWork score rest + let current := score a + match tail.1 with + | none => (some (a, current.1), tail.2 + current.2 + 1) + | some best => + let comparison := current.1.ltWithWork best.2 + (if comparison.1 then some best else some (a, current.1), + tail.2 + current.2 + comparison.2 + 2) + +def optimizerUpdateWithWork {d : ℕ} (j : ℕ) (previous selected : Vector OAI.EditApproximation.BinaryFraction d) : + Vector OAI.EditApproximation.BinaryFraction d × ℕ := + let step := OAI.EditApproximation.BinaryFraction.divWithWork (OAI.EditApproximation.BinaryFraction.nat 2) (OAI.EditApproximation.BinaryFraction.nat (j + 2)) + let complement := OAI.EditApproximation.BinaryFraction.subWithWork OAI.EditApproximation.BinaryFraction.one step.1 + let result := OAI.EditApproximation.vectorMapWithWork d fun i => + let first := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork complement.1 (previous.get i) + let second := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork step.1 (selected.get i) + let total := OAI.EditApproximation.BinaryFraction.canonicalAddWithWork first.1 second.1 + (total.1, first.2 + second.2 + total.2 + 4) + (result.1, step.2 + complement.2 + result.2 + Nat.size (j + 2) + 4) + +def bandMassTotalWithWork {M : ℕ} (mass : Vector OAI.EditApproximation.BinaryFraction M) : OAI.EditApproximation.BinaryFraction × ℕ := + OAI.EditApproximation.BinaryFraction.dotWithWork mass (Vector.replicate M OAI.EditApproximation.BinaryFraction.one) + +def coefficientWithWork (kappa : OAI.EditApproximation.BinaryFraction) : OAI.EditApproximation.BinaryFraction × ℕ := + let scaled := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 2) kappa + let difference := OAI.EditApproximation.BinaryFraction.subWithWork OAI.EditApproximation.BinaryFraction.one scaled.1 + (difference.1, scaled.2 + difference.2 + 1) + +def naturalDistanceLeWithWork (a b radius : ℕ) : Bool × ℕ := + let distance := OAI.EditApproximation.BinaryFraction.distanceWithWork (OAI.EditApproximation.BinaryFraction.nat a) (OAI.EditApproximation.BinaryFraction.nat b) + let result := distance.1.leWithWork (OAI.EditApproximation.BinaryFraction.nat radius) + (result.1, distance.2 + result.2 + Nat.size a + Nat.size b + Nat.size radius + 3) + +def onlineMinimumWithWork : List OAI.EditApproximation.BinaryFraction → Option OAI.EditApproximation.BinaryFraction × ℕ + | [] => (none, 1) + | first :: rest => + let result := OAI.EditApproximation.BinaryFraction.minimumWithWork first rest + (some result.1, result.2 + 1) + +def refinementUpdateWithWork (delta cone : OAI.EditApproximation.BinaryFraction) : Option OAI.EditApproximation.BinaryFraction → OAI.EditApproximation.BinaryFraction × ℕ + | none => (cone, 1) + | some online => + let denominator := OAI.EditApproximation.BinaryFraction.canonicalAddWithWork OAI.EditApproximation.BinaryFraction.one delta + let lower := OAI.EditApproximation.BinaryFraction.divWithWork cone denominator.1 + let clipped := OAI.EditApproximation.BinaryFraction.maxWithWork lower.1 online + let result := OAI.EditApproximation.BinaryFraction.minWithWork cone clipped.1 + (result.1, denominator.2 + lower.2 + clipped.2 + result.2 + 2) + +def equalWithWork (a b : OAI.EditApproximation.BinaryFraction) : Bool × ℕ := + let left := a.leWithWork b + let right := b.leWithWork a + (left.1 && right.1, left.2 + right.2 + 1) + +def roundedSpacingWithWork (theta envelope : OAI.EditApproximation.BinaryFraction) : List Bool × ℕ := + let product := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork theta envelope + let clipped := OAI.EditApproximation.BinaryFraction.maxWithWork OAI.EditApproximation.BinaryFraction.one product.1 + let rounded := OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork clipped.1 + (rounded.1, product.2 + clipped.2 + rounded.2 + 2) + +def maximizerWithWork {d : ℕ} (gradient : Vector OAI.EditApproximation.BinaryFraction d) + (vertices : List (Vector OAI.EditApproximation.BinaryFraction d)) : Vector OAI.EditApproximation.BinaryFraction d × ℕ := + let selected := OAI.EditApproximation.BinaryFraction.scoredArgmaxWithWork (OAI.EditApproximation.BinaryFraction.dotWithWork gradient) vertices + ((selected.1.map Prod.fst).getD (Vector.replicate d OAI.EditApproximation.BinaryFraction.zero), selected.2 + d + 1) + +def groupTermsWithWork {M : ℕ} (h : OAI.EditApproximation.BinaryFraction) (envelope values : Vector OAI.EditApproximation.BinaryFraction M) + (indices : List (Fin M)) : List OAI.EditApproximation.BinaryFraction × ℕ := + OAI.EditApproximation.arithmeticMapWithWork (fun i => + let test := OAI.EditApproximation.BinaryFraction.equalWithWork (envelope.get i) h + (if test.1 then values.get i else OAI.EditApproximation.BinaryFraction.zero, test.2 + 2)) indices + +def selectGroupWithWork {ι : Type u_1} (members : List ι) (hne : members ≠ []) + (estimate : ι → OAI.EditApproximation.BinaryFraction × ℕ) : ι × ℕ := + let selected := OAI.EditApproximation.BinaryFraction.scoredArgmaxWithWork (fun member => + let result := estimate member + (result.1.neg, result.2 + 1)) members + ((selected.1.map Prod.fst).getD (members.head hne), selected.2 + 1) + +def finiteOptimizerWithWork {d : ℕ} (vertices : List (Vector OAI.EditApproximation.BinaryFraction d)) + (linear : Vector OAI.EditApproximation.BinaryFraction d) (G : ℕ) : ℕ → Vector OAI.EditApproximation.BinaryFraction d × ℕ + | 0 => (vertices.headD (Vector.replicate d OAI.EditApproximation.BinaryFraction.zero), d + 1) + | j + 1 => + let previous := finiteOptimizerWithWork vertices linear G j + let gradient := OAI.EditApproximation.BinaryFraction.gradientWithWork G linear previous.1 + let selected := OAI.EditApproximation.BinaryFraction.maximizerWithWork gradient.1 vertices + let updated := OAI.EditApproximation.BinaryFraction.optimizerUpdateWithWork j previous.1 selected.1 + (updated.1, previous.2 + gradient.2 + selected.2 + updated.2 + 3) + +def selectionWithWork {α : Type u_1} {d : ℕ} + (vertices : List (α × Vector OAI.EditApproximation.BinaryFraction d)) (linear : Vector OAI.EditApproximation.BinaryFraction d) (G j : ℕ) : + Option α × ℕ := + let iterate := OAI.EditApproximation.BinaryFraction.finiteOptimizerWithWork (vertices.map Prod.snd) linear G j + let gradient := OAI.EditApproximation.BinaryFraction.gradientWithWork G linear iterate.1 + let selected := OAI.EditApproximation.BinaryFraction.scoredArgmaxWithWork (fun vertex => OAI.EditApproximation.BinaryFraction.dotWithWork gradient.1 vertex.2) vertices + (selected.1.map fun chosen => chosen.1.1, iterate.2 + gradient.2 + selected.2 + 1) + + +end OAI.EditApproximation.BinaryFraction +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BitQuery + + +def value {ι : Type u_1} {β : Type u_2} (oracle : ι → OAI.EditApproximation.BinaryFraction) : OAI.EditApproximation.BitQuery ι β → β + | .done result => result + | .read key next => value oracle (next (oracle key)) + | .charge _ next => value oracle next + +def work {ι : Type u_1} {β : Type u_2} (oracle : ι → OAI.EditApproximation.BinaryFraction) (readWork : ι → ℕ) : OAI.EditApproximation.BitQuery ι β → ℕ + | .done _ => 0 + | .read key next => readWork key + work oracle readWork (next (oracle key)) + | .charge steps next => steps + work oracle readWork next + +def bind {ι : Type u_1} {α : Type u_2} {β : Type u_3} : OAI.EditApproximation.BitQuery ι α → (α → OAI.EditApproximation.BitQuery ι β) → OAI.EditApproximation.BitQuery ι β + | .done result, next => next result + | .read key continuation, next => .read key (fun word => bind (continuation word) next) + | .charge steps continuation, next => .charge steps (bind continuation next) + +def compute {ι : Type u_1} {α : Type u_2} (execution : α × ℕ) : OAI.EditApproximation.BitQuery ι α := + .charge execution.2 (.done execution.1) + +def mapKeysWithWork {ι : Type u_1} {κ : Type u_2} {β : Type u_3} (f : ι → κ × ℕ) : OAI.EditApproximation.BitQuery ι β → OAI.EditApproximation.BitQuery κ β + | .done result => .done result + | .read key next => .charge (f key).2 + (.read (f key).1 (fun word => mapKeysWithWork f (next word))) + | .charge steps next => .charge steps (mapKeysWithWork f next) + +def restrictWithWork {ι : Type u_1} (P : ι → Prop) + (test : ι → Bool × ℕ) (htest : ∀ key, (test key).1 = true ↔ P key) : + OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction → OAI.EditApproximation.BitQuery {key // P key} OAI.EditApproximation.BinaryFraction + | .done result => .done result + | .charge steps next => .charge steps (restrictWithWork P test htest next) + | .read key next => .charge (test key).2 + (if h : (test key).1 = true then + .read ⟨key, (htest key).mp h⟩ (fun word => restrictWithWork P test htest (next word)) + else restrictWithWork P test htest (next (OAI.EditApproximation.BinaryFraction.nat 0))) + +def runMemo {ι : Type u_1} {κ : Type u_2} + (ask : ι → OAI.EditApproximation.BinaryMemo OAI.EditApproximation.BinaryFraction → OAI.EditApproximation.BitRecursiveMemoResult κ) : + OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction → OAI.EditApproximation.BinaryMemo OAI.EditApproximation.BinaryFraction → OAI.EditApproximation.BitRecursiveMemoResult κ + | .done result, memory => ⟨result, memory, [], 0, 0, 0⟩ + | .read key next, memory => + let first := ask key memory + let rest := runMemo ask (next first.value) first.memory + ⟨rest.value, rest.memory, first.freshKeys ++ rest.freshKeys, + first.dictionaryVisits + rest.dictionaryVisits, first.requests + rest.requests, + first.localWork + rest.localWork⟩ + | .charge steps next, memory => + let rest := runMemo ask next memory + {rest with localWork := steps + rest.localWork} + +inductive Footprint {ι : Type u_1} {β : Type u_2} : OAI.EditApproximation.BitQuery ι β → Type _ where + | done (value : β) : Footprint (.done value) + | read (key : ι) (next : OAI.EditApproximation.BinaryFraction → OAI.EditApproximation.BitQuery ι β) + (continuation : ∀ word, Footprint (next word)) : Footprint (.read key next) + | charge {steps : ℕ} {next : OAI.EditApproximation.BitQuery ι β} (cells : ℕ) + (continuation : Footprint next) : Footprint (.charge steps next) + +def collect {ι : Type u_1} {κ : Type u_2} {β : Type u_3} (reader : κ → OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) : + List κ → (List OAI.EditApproximation.BinaryFraction → OAI.EditApproximation.BitQuery ι β) → OAI.EditApproximation.BitQuery ι β + | [], next => next [] + | key :: rest, next => (reader key).bind (fun word => + .charge 3 (collect reader rest (fun words => next (word :: words)))) + +def normalize {ι : Type u_1} (program : OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (base : List Bool) (hbase : 0 < OAI.EditApproximation.bitWordValue base) (remaining : ℕ) : + OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction := + program.bind fun word => OAI.EditApproximation.BitQuery.compute (OAI.EditApproximation.BinaryFraction.finishCachedWithWork (word, 0) base hbase remaining) + + +end OAI.EditApproximation.BitQuery +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open EditDistortion + +def substring {α : Type u} (word : List α) (lo hi : ℕ) : List α := + (word.take hi).drop lo + +structure TargetInterval (length : ℕ) where + lo : ℕ + hi : ℕ + ordered : lo ≤ hi + valid : hi ≤ length + +def occurrenceDeficit {α : Type u} [DecidableEq α] (a : α) (word : List α) : ℕ := + word.length - if a ∈ word then 1 else 0 + +def natListMinimum (fallback : ℕ) : List ℕ → ℕ + | [] => fallback + | first :: rest => min first (natListMinimum fallback rest) + +def coarsePadTo {α : Type u} (n : ℕ) (word : List α) : List (Option α) := + word.map some ++ List.replicate (n - word.length) none + +def connectionBudget {n : ℕ} (start : ℕ) (states : List (OAI.EditApproximation.TargetInterval n)) + (finish : ℕ) : ℕ := + match states with + | [] => Nat.dist start finish + | state :: rest => Nat.dist start state.lo + connectionBudget state.hi rest finish + +def singletonCost {α : Type u} [DecidableEq α] (a : α) (word : List α) : ℕ := + if word = [] then 1 else OAI.EditApproximation.occurrenceDeficit a word + +def makeTargetState (n lo hi : ℕ) : Option (OAI.EditApproximation.TargetInterval n) := + if h : lo ≤ hi ∧ hi ≤ n then some ⟨lo, hi, h.1, h.2⟩ else none + +def targetEndpointDistance {n : ℕ} (q r : OAI.EditApproximation.TargetInterval n) : ℕ := + Nat.dist q.lo r.lo + Nat.dist q.hi r.hi + +def targetStates (n : ℕ) : List (OAI.EditApproximation.TargetInterval n) := + (List.range (n + 1)).flatMap fun lo => + (List.range (n + 1)).filterMap fun hi => OAI.EditApproximation.makeTargetState n lo hi + +def shortSourceCost {α : Type u_1} [DecidableEq α] (source target : List α) : ℕ := + match source with + | [] => target.length + | a :: _ => OAI.EditApproximation.singletonCost a target + +def exactSuffixDP {α : Type u_1} [DecidableEq α] : List α → List α → List ℕ + | [], target => List.ofFn fun j : Fin (target.length + 1) => target.length - j.val + | a :: rest, target => + let previous := exactSuffixDP rest target + List.ofFn fun j : Fin (target.length + 1) => + OAI.EditApproximation.natListMinimum (OAI.EditApproximation.singletonCost a [] + previous.getD j.val 0) + ((List.range (target.length - j.val + 1)).map fun k => + OAI.EditApproximation.singletonCost a ((target.drop j.val).take k) + previous.getD (j.val + k) 0) + +def exactSuffixAnswer {α : Type u_1} [DecidableEq α] (source target : List α) : ℕ := + (OAI.EditApproximation.exactSuffixDP source target).getD 0 0 + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation + + +def sourceChild {n M : ℕ} (parent : OAI.EditApproximation.TargetInterval n) (child : Fin M) : OAI.EditApproximation.TargetInterval n := by + have proof_balancedCut_monotone_7 (lo : ℕ) (width : ℕ) (M : ℕ) : Monotone (OAI.EditApproximation.balancedCut lo width M) := by + intro i j hij + exact Nat.add_le_add_left (Nat.div_le_div_right (Nat.mul_le_mul_right width hij)) lo + have proof_balancedCut_last_9 (lo : ℕ) (width : ℕ) (M : ℕ) (hM : LT.lt.{0} 0 M) : + OAI.EditApproximation.balancedCut lo width M M = lo + width := by + simp only [OAI.EditApproximation.balancedCut, Nat.mul_div_cancel_left _ hM] + have proof_balancedCut_bounds_8 (lo : ℕ) (width : ℕ) (M : ℕ) (i : ℕ) (hM : LT.lt.{0} 0 M) (hi : LE.le.{0} i M) : + lo ≤ OAI.EditApproximation.balancedCut lo width M i ∧ OAI.EditApproximation.balancedCut lo width M i ≤ lo + width := by + constructor + · exact Nat.le_add_right _ _ + · rw [← proof_balancedCut_last_9 lo width M hM] + exact proof_balancedCut_monotone_7 lo width M hi + exact + { lo := OAI.EditApproximation.balancedCut parent.lo (parent.hi - parent.lo) M child.val + hi := OAI.EditApproximation.balancedCut parent.lo (parent.hi - parent.lo) M (child.val + 1) + ordered := proof_balancedCut_monotone_7 _ _ _ (Nat.le_succ _) + valid := by + have hM : 0 < M := Nat.zero_lt_of_lt child.isLt + have hbound := (proof_balancedCut_bounds_8 parent.lo (parent.hi - parent.lo) M (child.val + 1) + hM (by omega)).2 + rw [Nat.add_sub_of_le parent.ordered] at hbound + exact hbound.trans parent.valid } + +def roundInterval {n : ℕ} (spacing : ℕ) (state : OAI.EditApproximation.TargetInterval n) : OAI.EditApproximation.TargetInterval n := by + have proof_gridRound_mono_10 (spacing : ℕ) : Monotone (OAI.EditApproximation.gridRound spacing) := by + intro p q hpq + exact Nat.mul_le_mul_left spacing (Nat.div_le_div_right hpq) + have proof_gridRound_le_11 (spacing : ℕ) (position : ℕ) : OAI.EditApproximation.gridRound spacing position ≤ position := + Nat.mul_div_le _ _ + exact { + lo := OAI.EditApproximation.gridRound spacing state.lo + hi := OAI.EditApproximation.gridRound spacing state.hi + ordered := proof_gridRound_mono_10 spacing state.ordered + valid := (proof_gridRound_le_11 spacing state.hi).trans state.valid + } + +def localTargetStates (n g radius : ℕ) (q : OAI.EditApproximation.TargetInterval n) : List (OAI.EditApproximation.TargetInterval n) := + (OAI.EditApproximation.gridPointsBetween g (q.lo - radius) (q.lo + radius)).flatMap fun lo => + (OAI.EditApproximation.gridPointsBetween g (q.hi - radius) (q.hi + radius)).filterMap fun hi => + OAI.EditApproximation.makeTargetState n lo hi + +def rationalStateGap {α : Type u_1} (source target : List α) (q : OAI.EditApproximation.TargetInterval target.length) : ℚ := + (q.hi : ℚ) - q.lo - source.length + +def gridStateBox (n g radius lo hi : ℕ) : List (OAI.EditApproximation.TargetInterval n) := + (OAI.EditApproximation.gridPointsBetween g (lo - radius) (lo + radius)).flatMap fun s => + (OAI.EditApproximation.gridPointsBetween g (hi - radius) (hi + radius)).filterMap fun t => + OAI.EditApproximation.makeTargetState n s t + +abbrev PhysicalEntry (M J ny : ℕ) := OAI.EditApproximation.PhysicalNode M J × OAI.EditApproximation.TargetInterval ny + +def makeStateWithWork (n lo hi : ℕ) : Option (OAI.EditApproximation.TargetInterval n) × ℕ := by + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_wordLEWithWork_value_26 (a : List.{0} Bool) (b : List.{0} Bool) : + (OAI.EditApproximation.wordLEWithWork a b).1 = true ↔ OAI.EditApproximation.bitWordValue a ≤ OAI.EditApproximation.bitWordValue b := by + simp only [OAI.EditApproximation.wordLEWithWork, Bool.not_eq_true', decide_eq_false_iff_not, + proof_bitCompareWithWork_lt_16, not_lt] + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + exact + let first := OAI.EditApproximation.wordLEWithWork lo.bits hi.bits + let second := OAI.EditApproximation.wordLEWithWork hi.bits n.bits + if h : (first.1 && second.1) = true then + (some ⟨lo, hi, + by have hp : first.1 = true ∧ second.1 = true := by simpa only [Bool.and_eq_true] using h + simpa only [first, proof_wordLEWithWork_value_26, proof_bitWordValue_bits_15] using hp.1, + by have hp : first.1 = true ∧ second.1 = true := by simpa only [Bool.and_eq_true] using h + simpa only [second, proof_wordLEWithWork_value_26, proof_bitWordValue_bits_15] using hp.2⟩, + first.2 + second.2 + 4) + else (none, first.2 + second.2 + 2) + +def cellTargetStates (n g : ℕ) (side : ℚ) (cell : ℕ × ℕ) : List (OAI.EditApproximation.TargetInterval n) := + (OAI.EditApproximation.cellGridPoints side g cell.1).flatMap fun lo => + (OAI.EditApproximation.cellGridPoints side g cell.2).filterMap fun hi => OAI.EditApproximation.makeTargetState n lo hi + +def gridGapStates (n g anchor radius sourceLength gapRadius : ℕ) : List (OAI.EditApproximation.TargetInterval n) := + (OAI.EditApproximation.gridPointsBetween g (anchor - radius) (anchor + radius)).flatMap fun lo => + (OAI.EditApproximation.gridPointsBetween g (lo + sourceLength - gapRadius) (lo + sourceLength + gapRadius)).filterMap + fun hi => OAI.EditApproximation.makeTargetState n lo hi + +abbrev PhysicalChildTables (M ny : ℕ) := Fin M → ℕ → OAI.EditApproximation.TargetInterval ny → ℚ + +abbrev PhysicalRationalAction (M ny : ℕ) := + OAI.EditApproximation.RationalBellmanAction (OAI.EditApproximation.TargetInterval ny) (Fin M × OAI.EditApproximation.TargetInterval ny) M + +def localTargetCells {n : ℕ} (side : ℚ) (radius : ℕ) (q : OAI.EditApproximation.TargetInterval n) : List (ℕ × ℕ) := + (OAI.EditApproximation.localCellCoordinates side q.lo radius).flatMap fun lo => + (OAI.EditApproximation.localCellCoordinates side q.hi radius).map fun hi => (lo, hi) + +def coordinateEqualWithWork {M n : ℕ} (a b : Fin M × OAI.EditApproximation.TargetInterval n) : Bool × ℕ := + let child := OAI.EditApproximation.naturalEqualWithWork a.1.val b.1.val + let lo := OAI.EditApproximation.naturalEqualWithWork a.2.lo b.2.lo + let hi := OAI.EditApproximation.naturalEqualWithWork a.2.hi b.2.hi + (child.1 && lo.1 && hi.1, child.2 + lo.2 + hi.2 + 2) + +def queryIntervalEqualWithWork {n : ℕ} (a b : OAI.EditApproximation.TargetInterval n) : Bool × ℕ := + let lo := OAI.EditApproximation.naturalEqualWithWork a.lo b.lo + let hi := OAI.EditApproximation.naturalEqualWithWork a.hi b.hi + (lo.1 && hi.1, lo.2 + hi.2 + 1) + +def childInputCode {M n : ℕ} (input : Fin M × OAI.EditApproximation.TargetInterval n) : ℕ := + input.1.val + M * (input.2.lo + (n + 1) * input.2.hi) + +def queryChildCodeWithWork {M n : ℕ} (input : Fin M × OAI.EditApproximation.TargetInterval n) : ℕ × ℕ := + let width := OAI.EditApproximation.binaryNaturalAddWithWork n 1 + let high := OAI.EditApproximation.binaryNaturalMulWithWork (OAI.EditApproximation.bitWordValue width.1) input.2.hi + let coordinate := OAI.EditApproximation.binaryNaturalAddWithWork input.2.lo (OAI.EditApproximation.bitWordValue high.1) + let scaled := OAI.EditApproximation.binaryNaturalMulWithWork M (OAI.EditApproximation.bitWordValue coordinate.1) + let result := OAI.EditApproximation.binaryNaturalAddWithWork input.1.val (OAI.EditApproximation.bitWordValue scaled.1) + (OAI.EditApproximation.bitWordValue result.1, width.2 + high.2 + coordinate.2 + scaled.2 + result.2 + 5) + +def querySliceHeadWithWork {α : Type u_1} (source : List α) + (interval : OAI.EditApproximation.TargetInterval source.length) : Option α × ℕ := + let test := OAI.EditApproximation.binaryNaturalCompareWithWork interval.lo interval.hi + (if test.1 = .lt then source[interval.lo]? else none, + test.2 + Nat.size interval.lo + Nat.size interval.hi + 3) + +def rankedBitProgramValue {κ : Type u_1} (rank : κ → ℕ) + (program : (key : κ) → OAI.EditApproximation.BitQuery {child : κ // rank child < rank key} OAI.EditApproximation.BinaryFraction) + (key : κ) : OAI.EditApproximation.BinaryFraction := + (program key).value (fun child => rankedBitProgramValue rank program child.val) +termination_by rank key +decreasing_by exact child.property + +def scheduledRefinementWordWithWork (N pass : ℕ) : OAI.EditApproximation.BinaryFraction × ℕ := + if pass < OAI.EditApproximation.computedSeedPassCount N then + let e := OAI.EditApproximation.dyadicSeedExponent (OAI.EditApproximation.smallLogExponent N) (OAI.EditApproximation.computedSeedInitialExponent N) pass - + OAI.EditApproximation.smallLogExponent N + let value := OAI.EditApproximation.BinaryFraction.signedPowerTwoWithWork (e : ℤ) + (value.1, value.2 + 5) + else (OAI.EditApproximation.BinaryFraction.nat 1, 3) + +def coordinateEqualAllocation {M n : ℕ} (a b : Fin M × OAI.EditApproximation.TargetInterval n) : ℕ := + OAI.EditApproximation.naturalEqualAllocation a.1.val b.1.val + OAI.EditApproximation.naturalEqualAllocation a.2.lo b.2.lo + + OAI.EditApproximation.naturalEqualAllocation a.2.hi b.2.hi + 2 + +def queryIntervalEqualAllocation {n : ℕ} (a b : OAI.EditApproximation.TargetInterval n) : ℕ := + OAI.EditApproximation.naturalEqualAllocation a.lo b.lo + OAI.EditApproximation.naturalEqualAllocation a.hi b.hi + 1 + +def sourceChildAllocation {n M : ℕ} (parent : OAI.EditApproximation.TargetInterval n) (i : Fin M) : ℕ := + let width := (OAI.EditApproximation.saturatingSubtractWithWork parent.hi parent.lo).1 + let next := (OAI.EditApproximation.binaryNaturalAddWithWork i.val 1).1 + OAI.EditApproximation.saturatingSubtractAllocation parent.hi parent.lo + OAI.EditApproximation.binaryNaturalAddAllocation i.val 1 + + OAI.EditApproximation.balancedCutAllocation parent.lo (OAI.EditApproximation.bitWordValue width) M i.val + + OAI.EditApproximation.balancedCutAllocation parent.lo (OAI.EditApproximation.bitWordValue width) M (OAI.EditApproximation.bitWordValue next) + 2 + +def zeroConnectionAllocation {n : ℕ} (start : ℕ) : List (OAI.EditApproximation.TargetInterval n) → ℕ → ℕ + | [], finish => OAI.EditApproximation.naturalEqualAllocation start finish + | state :: rest, finish => OAI.EditApproximation.naturalEqualAllocation start state.lo + + zeroConnectionAllocation state.hi rest finish + 1 + +def queryChildCodeAllocation {M n : ℕ} (input : Fin M × OAI.EditApproximation.TargetInterval n) : ℕ := + let width := (OAI.EditApproximation.binaryNaturalAddWithWork n 1).1 + let high := (OAI.EditApproximation.binaryNaturalMulWithWork (OAI.EditApproximation.bitWordValue width) input.2.hi).1 + let coordinate := (OAI.EditApproximation.binaryNaturalAddWithWork input.2.lo (OAI.EditApproximation.bitWordValue high)).1 + let scaled := (OAI.EditApproximation.binaryNaturalMulWithWork M (OAI.EditApproximation.bitWordValue coordinate)).1 + OAI.EditApproximation.binaryNaturalAddAllocation n 1 + OAI.EditApproximation.binaryNaturalMulAllocation (OAI.EditApproximation.bitWordValue width) input.2.hi + + OAI.EditApproximation.binaryNaturalAddAllocation input.2.lo (OAI.EditApproximation.bitWordValue high) + + OAI.EditApproximation.binaryNaturalMulAllocation M (OAI.EditApproximation.bitWordValue coordinate) + + OAI.EditApproximation.binaryNaturalAddAllocation input.1.val (OAI.EditApproximation.bitWordValue scaled) + +def roundStateAllocation {n : ℕ} (spacing : ℕ) (q : OAI.EditApproximation.TargetInterval n) : ℕ := + OAI.EditApproximation.binaryGridRoundAllocation spacing q.lo + OAI.EditApproximation.binaryGridRoundAllocation spacing q.hi + 2 + +def actionEqualAllocation {n M : ℕ} (a b : Fin M → OAI.EditApproximation.TargetInterval n) : ℕ := + OAI.EditApproximation.allAllocation (fun i => OAI.EditApproximation.naturalEqualAllocation (a i).lo (b i).lo + + OAI.EditApproximation.naturalEqualAllocation (a i).hi (b i).hi) (List.finRange M) + +structure RawUnskippedBand (M ny : ℕ) where + center : OAI.EditApproximation.TargetInterval ny + actions : List (Fin M → OAI.EditApproximation.TargetInterval ny) + nonempty : actions ≠ [] + +def sourceIntervalAt (M n : ℕ) : (d : ℕ) → OAI.EditApproximation.TreeLayer M d → OAI.EditApproximation.TargetInterval n + | 0, _ => ⟨0, n, Nat.zero_le _, le_rfl⟩ + | d + 1, node => OAI.EditApproximation.sourceChild (sourceIntervalAt M n d node.1) node.2 + +def initialConeValue {α : Type u_1} (source target : List α) + (U : OAI.EditApproximation.TargetInterval target.length → ℕ) (a L0 : ℚ) + (query center : OAI.EditApproximation.TargetInterval target.length) : ℚ := + OAI.EditApproximation.scaledSeedValue (U center) a (OAI.EditApproximation.rationalStateGap source target center) + + L0 * OAI.EditApproximation.targetEndpointDistance query center + +def wideChildStateList {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (r : OAI.EditApproximation.TargetInterval ny) (b P : ℕ) (i : Fin M) : List (OAI.EditApproximation.TargetInterval ny) := + OAI.EditApproximation.gridStateBox ny (OAI.EditApproximation.seedGridSpacing b P) (10 * b) + (r.lo + ((OAI.EditApproximation.sourceChild parent i).lo - parent.lo)) + (r.lo + ((OAI.EditApproximation.sourceChild parent i).hi - parent.lo)) + +def bandCutShift {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (states : Fin M → OAI.EditApproximation.TargetInterval ny) (j : Fin M) : ℚ := + (states j).lo - ((OAI.EditApproximation.sourceChild parent j).lo : ℚ) + +def localInitialConeCenters {n : ℕ} (N P : ℕ) (A : ℚ) + (U : OAI.EditApproximation.TargetInterval n → ℕ) (q : OAI.EditApproximation.TargetInterval n) : List (OAI.EditApproximation.TargetInterval n) := + ((OAI.EditApproximation.dyadicScales N).filter (fun (b : ℕ) => decide + ((U q : ℚ) / (16 * A ^ 2) ≤ (b : ℚ) ∧ (b : ℚ) ≤ 4 * A * U q))).flatMap fun b => + (OAI.EditApproximation.localTargetStates n (OAI.EditApproximation.seedGridSpacing b P) (U q) q).filter fun r => + decide ((b : ℚ) / 2 ≤ U r ∧ (U r : ℚ) ≤ 4 * A * b) + +def gridStateBoxWithWork (n g radius lo hi : ℕ) : List (OAI.EditApproximation.TargetInterval n) × ℕ := + let leftLow := OAI.EditApproximation.saturatingSubtractWithWork lo radius + let leftHigh := OAI.EditApproximation.binaryNaturalAddWithWork lo radius + let rightLow := OAI.EditApproximation.saturatingSubtractWithWork hi radius + let rightHigh := OAI.EditApproximation.binaryNaturalAddWithWork hi radius + let left := OAI.EditApproximation.gridPointsWithWork g (OAI.EditApproximation.bitWordValue leftLow.1) (OAI.EditApproximation.bitWordValue leftHigh.1) + let right := OAI.EditApproximation.gridPointsWithWork g (OAI.EditApproximation.bitWordValue rightLow.1) (OAI.EditApproximation.bitWordValue rightHigh.1) + let states := OAI.EditApproximation.arithmeticFlatMapWithWork (fun s => OAI.EditApproximation.filterMapWithWork (OAI.EditApproximation.makeStateWithWork n s) right.1) left.1 + (states.1, leftLow.2 + leftHigh.2 + rightLow.2 + rightHigh.2 + left.2 + right.2 + states.2 + 6) + +def sourceChildWithWork {n M : ℕ} (parent : OAI.EditApproximation.TargetInterval n) (i : Fin M) : OAI.EditApproximation.TargetInterval n × ℕ := by + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_binaryNaturalCompareWithWork_lt_53 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.binaryNaturalCompareWithWork a b).1 = .lt ↔ a < b := by + simpa only [OAI.EditApproximation.binaryNaturalCompareWithWork, proof_bitWordValue_bits_15] using proof_bitCompareWithWork_lt_16 a.bits b.bits + have proof_bitSubtractor_value_17 (a : Bool) (b : Bool) (borrow : Bool) : + a.toNat + 2 * (OAI.EditApproximation.bitBorrow a b borrow).toNat = + b.toNat + borrow.toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat := by + cases a <;> cases b <;> cases borrow <;> decide + have proof_bitSubtractionRippleEquation_18 (a : ℕ) (b : ℕ) (borrow : ℕ) (nextBorrow : ℕ) (difference : ℕ) (left : ℕ) (right : ℕ) (result : ℕ) (tail : ℕ) (htail : Eq.{1} (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} result right) nextBorrow) (HAdd.hAdd.{0, 0, 0} left tail)) (hbit : Eq.{1} (HAdd.hAdd.{0, 0, 0} a (HMul.hMul.{0, 0, 0} 2 nextBorrow)) + (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} b borrow) difference)) : + (difference + 2 * result) + (b + 2 * right) + borrow = + (a + 2 * left) + 2 * tail := by + omega + have proof_bitSubtractWithWork_value_19 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right borrow).1 + OAI.EditApproximation.bitWordValue right + borrow.toNat = + OAI.EditApproximation.bitWordValue left + 2 ^ max left.length right.length * + (OAI.EditApproximation.bitSubtractWithWork left right borrow).2.1.toNat := by + induction left generalizing right borrow with + | nil => + induction right generalizing borrow with + | nil => (simp [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + have h := ih (OAI.EditApproximation.bitBorrow false b borrow) + have hb := proof_bitSubtractor_value_17 false b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue, + List.length_nil, List.length_cons, Nat.zero_max, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 0 b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow false b borrow).toNat + (OAI.EditApproximation.bitDifference false b borrow).toNat 0 (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).1) + (2 ^ bs.length * (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons a as ih => + cases right with + | nil => + have h := ih [] (OAI.EditApproximation.bitBorrow a false borrow) + have hb := proof_bitSubtractor_value_17 a false borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_nil, List.length_cons, + Nat.max_zero, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat 0 borrow.toNat (OAI.EditApproximation.bitBorrow a false borrow).toNat + (OAI.EditApproximation.bitDifference a false borrow).toNat (OAI.EditApproximation.bitWordValue as) 0 + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).1) + (2 ^ as.length * (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons b bs => + have h := ih bs (OAI.EditApproximation.bitBorrow a b borrow) + have hb := proof_bitSubtractor_value_17 a b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_cons, Nat.succ_max_succ, + pow_succ] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow a b borrow).toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).1) + (2 ^ max as.length bs.length * (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_assoc, Nat.mul_left_comm] using hs + have proof_bitWordValue_lt_pow_length_20 (bits : List.{0} Bool) : OAI.EditApproximation.bitWordValue bits < 2 ^ bits.length := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitWordValue]) + | cons bit bits ih => + cases bit <;> (simp only [OAI.EditApproximation.bitWordValue, List.length_cons, pow_succ, Bool.toNat_false, Bool.toNat_true]) <;> omega + have proof_bitSubtractWithWork_length_21 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + (OAI.EditApproximation.bitSubtractWithWork left right borrow).1.length = max left.length right.length := by + induction left generalizing right borrow with + | nil => + simp only [OAI.EditApproximation.bitSubtractWithWork] + induction right generalizing borrow with + | nil => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork] + | cons b bs ih => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork, ih] + | cons a as ih => + cases right with + | nil => simp [OAI.EditApproximation.bitSubtractWithWork, ih] + | cons b bs => simp [OAI.EditApproximation.bitSubtractWithWork, ih, Nat.succ_max_succ] + have proof_bitSubtractWithWork_sub_22 (left : List.{0} Bool) (right : List.{0} Bool) (h : LE.le.{0} (OAI.EditApproximation.bitWordValue right) (OAI.EditApproximation.bitWordValue left)) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right false).1 = OAI.EditApproximation.bitWordValue left - OAI.EditApproximation.bitWordValue right := by + have hvalue := proof_bitSubtractWithWork_value_19 left right false + have hlt := proof_bitWordValue_lt_pow_length_20 (OAI.EditApproximation.bitSubtractWithWork left right false).1 + rw [proof_bitSubtractWithWork_length_21] at hlt + cases hb : (OAI.EditApproximation.bitSubtractWithWork left right false).2.1 + · simp only [hb, Bool.toNat_false, Nat.mul_zero, Nat.add_zero] at hvalue + omega + · simp only [hb, Bool.toNat_true, Bool.toNat_false, Nat.mul_one, Nat.add_zero] at hvalue + omega + have proof_binaryNaturalSubtractWithWork_value_54 (a : ℕ) (b : ℕ) (h : LE.le.{0} b a) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalSubtractWithWork a b).1 = a - b := by + simpa only [OAI.EditApproximation.binaryNaturalSubtractWithWork, proof_bitWordValue_bits_15] using + proof_bitSubtractWithWork_sub_22 a.bits b.bits (by simpa only [proof_bitWordValue_bits_15] using h) + have proof_saturatingSubtractWithWork_value_50 (a : ℕ) (b : ℕ) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.saturatingSubtractWithWork a b).1 = a - b := by + unfold OAI.EditApproximation.saturatingSubtractWithWork + dsimp only + split_ifs with h + · have hlt := (proof_binaryNaturalCompareWithWork_lt_53 a b).mp h + simp only [OAI.EditApproximation.bitWordValue, Nat.sub_eq_zero_of_le hlt.le] + · exact proof_binaryNaturalSubtractWithWork_value_54 a b (le_of_not_gt (fun hab => + h ((proof_binaryNaturalCompareWithWork_lt_53 a b).mpr hab))) + have proof_bitAdder_value_1 (a : Bool) (b : Bool) (carry : Bool) : + (OAI.EditApproximation.bitSum a b carry).toNat + 2 * (OAI.EditApproximation.bitCarry a b carry).toNat = + a.toNat + b.toNat + carry.toNat := by + cases a <;> cases b <;> cases carry <;> decide + have proof_bitAddWithWork_value_2 (left : List.{0} Bool) (right : List.{0} Bool) (carry : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitAddWithWork left right carry).1 = + OAI.EditApproximation.bitWordValue left + OAI.EditApproximation.bitWordValue right + carry.toNat := by + induction left generalizing right carry with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork] + induction right generalizing carry with + | nil => cases carry <;> simp [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue] + | cons b bs ih => + simp only [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 false b carry + simp only [Bool.toNat_false] at h + omega + | cons a as ih => + cases right with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a false carry + simp only [Bool.toNat_false] at h + omega + | cons b bs => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a b carry + omega + have proof_bitMulWithWork_value_0 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitMulWithWork left right).1 = OAI.EditApproximation.bitWordValue left * OAI.EditApproximation.bitWordValue right := by + induction left with + | nil => simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue] + | cons bit bits ih => + cases bit <;> simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue, proof_bitAddWithWork_value_2, ih] <;> ring + have proof_binaryNaturalMulWithWork_value_55 (a : ℕ) (b : ℕ) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalMulWithWork a b).1 = a * b := by + simp [OAI.EditApproximation.binaryNaturalMulWithWork, proof_bitMulWithWork_value_0, proof_bitWordValue_bits_15] + have proof_bitDivModWithWork_value_23 (divisor : List.{0} Bool) (bits : List.{0} Bool) (hd : LT.lt.{0} 0 (OAI.EditApproximation.bitWordValue divisor)) : + OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).1 + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 < OAI.EditApproximation.bitWordValue divisor := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitDivModWithWork, OAI.EditApproximation.bitWordValue, hd]) + | cons bit bits ih => + let previous := OAI.EditApproximation.bitDivModWithWork divisor bits + let candidate := bit :: previous.2.1 + have hp : OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue previous.1 + + OAI.EditApproximation.bitWordValue previous.2.1 := ih.1 + have hr : OAI.EditApproximation.bitWordValue previous.2.1 < OAI.EditApproximation.bitWordValue divisor := ih.2 + have hc : OAI.EditApproximation.bitWordValue candidate < 2 * OAI.EditApproximation.bitWordValue divisor := by + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + cases bit <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega + by_cases hlt : (OAI.EditApproximation.bitCompareWithWork candidate divisor).1 = .lt + · have hv := (proof_bitCompareWithWork_lt_16 candidate divisor).1 hlt + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 = .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * + OAI.EditApproximation.bitWordValue (false :: previous.1) + OAI.EditApproximation.bitWordValue candidate ∧ OAI.EditApproximation.bitWordValue candidate < _ + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_false]) + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + nlinarith only [hp] + · exact hv + · have hv : OAI.EditApproximation.bitWordValue divisor ≤ OAI.EditApproximation.bitWordValue candidate := by + exact Nat.le_of_not_gt (fun h => hlt ((proof_bitCompareWithWork_lt_16 candidate divisor).2 h)) + have hs := proof_bitSubtractWithWork_sub_22 candidate divisor hv + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 ≠ .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (true :: previous.1) + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 < _ + rw [hs] + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_true]) + have he := Nat.sub_add_cancel hv + dsimp only [candidate, OAI.EditApproximation.bitWordValue] at he ⊢ + nlinarith only [hp, he] + · omega + have proof_binaryNaturalDivModWithWork_spec_24 (n : ℕ) (d : ℕ) (hd : LT.lt.{0} 0 d) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalDivModWithWork n d).1 = n / d ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalDivModWithWork n d).2.1 = n % d := by + have h := proof_bitDivModWithWork_value_23 d.bits n.bits (by simpa only [proof_bitWordValue_bits_15] using hd) + simp only [proof_bitWordValue_bits_15] at h + have hmod : n % d = OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork d.bits n.bits).2.1 := by + conv_lhs => rw [h.1] + simp only [Nat.add_mod, Nat.mul_mod_right, Nat.zero_add, Nat.mod_eq_of_lt h.2] + have hdiv : n / d = OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork d.bits n.bits).1 := by + conv_lhs => rw [h.1] + rw [Nat.mul_add_div hd, Nat.div_eq_of_lt h.2, Nat.add_zero] + exact ⟨hdiv.symm, hmod.symm⟩ + have proof_binaryNaturalAddWithWork_value_52 (a : ℕ) (b : ℕ) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalAddWithWork a b).1 = a + b := by + simp [OAI.EditApproximation.binaryNaturalAddWithWork, proof_bitAddWithWork_value_2, proof_bitWordValue_bits_15] + have proof_balancedCutWithWork_value_51 (lo : ℕ) (width : ℕ) (M : ℕ) (i : ℕ) (hM : LT.lt.{0} 0 M) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.balancedCutWithWork lo width M i).1 = OAI.EditApproximation.balancedCut lo width M i := by + simp only [OAI.EditApproximation.balancedCutWithWork, proof_binaryNaturalAddWithWork_value_52, + (proof_binaryNaturalDivModWithWork_spec_24 _ M hM).1, proof_binaryNaturalMulWithWork_value_55, OAI.EditApproximation.balancedCut] + exact + let width := OAI.EditApproximation.saturatingSubtractWithWork parent.hi parent.lo + let next := OAI.EditApproximation.binaryNaturalAddWithWork i.val 1 + let left := OAI.EditApproximation.balancedCutWithWork parent.lo (OAI.EditApproximation.bitWordValue width.1) M i.val + let right := OAI.EditApproximation.balancedCutWithWork parent.lo (OAI.EditApproximation.bitWordValue width.1) M (OAI.EditApproximation.bitWordValue next.1) + let heql : OAI.EditApproximation.bitWordValue left.1 = (OAI.EditApproximation.sourceChild parent i).lo := by + simp only [left, width, proof_balancedCutWithWork_value_51 _ _ _ _ (Nat.zero_lt_of_lt i.isLt), + proof_saturatingSubtractWithWork_value_50, OAI.EditApproximation.sourceChild] + let heqh : OAI.EditApproximation.bitWordValue right.1 = (OAI.EditApproximation.sourceChild parent i).hi := by + simp only [right, width, next, proof_balancedCutWithWork_value_51 _ _ _ _ (Nat.zero_lt_of_lt i.isLt), + proof_saturatingSubtractWithWork_value_50, proof_binaryNaturalAddWithWork_value_52, OAI.EditApproximation.sourceChild] + (⟨OAI.EditApproximation.bitWordValue left.1, OAI.EditApproximation.bitWordValue right.1, + by rw [heql, heqh]; exact (OAI.EditApproximation.sourceChild parent i).ordered, + by rw [heqh]; exact (OAI.EditApproximation.sourceChild parent i).valid⟩, + width.2 + next.2 + left.2 + right.2 + 4) + +def cellRepresentativeStates (n P F b : ℕ) (a : ℚ) (initial : OAI.EditApproximation.TargetInterval n → ℚ) + (theta : ℚ) (cell : ℕ × ℕ) : List (OAI.EditApproximation.TargetInterval n) := + (OAI.EditApproximation.cellTargetStates n (OAI.EditApproximation.seedGridSpacing b P) (theta * b) cell).filter fun r => decide + ((b : ℚ) / (4 * a) ≤ initial r ∧ initial r ≤ 8 * F * b) + +def groupRoundedStateList {α : Type u_1} (source target : List α) {M : ℕ} + (parent : OAI.EditApproximation.TargetInterval source.length) (b exponent : ℕ) (cell : ℕ × ℕ) + (i : Fin M) (h : ℚ) : List (OAI.EditApproximation.TargetInterval target.length) := + OAI.EditApproximation.gridGapStates target.length (OAI.EditApproximation.groupRoundSpacing exponent h) + (⌊(cell.1 : ℚ) * ((2 : ℚ) ^ (-(exponent : ℤ)) * b)⌋₊ + + ((OAI.EditApproximation.sourceChild parent i).lo - parent.lo)) (12 * b) + (OAI.EditApproximation.substring source (OAI.EditApproximation.sourceChild parent i).lo (OAI.EditApproximation.sourceChild parent i).hi).length ⌈2 * h⌉₊ + +def rawInitialConeCenters {n : ℕ} (N P : ℕ) (A : ℚ) (value : ℕ) + (q : OAI.EditApproximation.TargetInterval n) : List (OAI.EditApproximation.TargetInterval n) := + ((OAI.EditApproximation.dyadicScales N).filter fun (b : ℕ) => decide + ((value : ℚ) / (16 * A ^ 2) ≤ b ∧ (b : ℚ) ≤ 4 * A * value)).flatMap fun b => + OAI.EditApproximation.localTargetStates n (OAI.EditApproximation.seedGridSpacing b P) value q + +def historyInputCode {M n : ℕ} (input : Fin M × ℕ × OAI.EditApproximation.TargetInterval n) : ℕ := + Nat.pair input.2.1 (OAI.EditApproximation.childInputCode (input.1, input.2.2)) + +def localOnlineSourceKeys {n : ℕ} (N P F : ℕ) (a : ℚ) + (initial : OAI.EditApproximation.TargetInterval n → ℚ) (q : OAI.EditApproximation.TargetInterval n) : + List (ℕ × OAI.EditApproximation.TargetInterval n) := + (OAI.EditApproximation.dyadicQueryWindow N (initial q) a F).map fun b => (b, OAI.EditApproximation.roundInterval (OAI.EditApproximation.seedGridSpacing b P) q) + +def queryHistoryCodeWithWork {M n : ℕ} (input : Fin M × ℕ × OAI.EditApproximation.TargetInterval n) : ℕ × ℕ := + let child := OAI.EditApproximation.queryChildCodeWithWork (input.1, input.2.2) + let pair := OAI.EditApproximation.queryPairWithWork input.2.1 child.1 + (pair.1, child.2 + pair.2 + 1) + +def queryOrderedChildInputsWithWork {M n : ℕ} (inputs : List (Fin M × OAI.EditApproximation.TargetInterval n)) : + List (Fin M × OAI.EditApproximation.TargetInterval n) × ℕ := + OAI.EditApproximation.queryOrderedInputsWithWork OAI.EditApproximation.coordinateEqualWithWork + (OAI.EditApproximation.queryEncodedLEWithWork OAI.EditApproximation.queryChildCodeWithWork) inputs + +def queryHistoryEqualWithWork {M n : ℕ} (a b : Fin M × ℕ × OAI.EditApproximation.TargetInterval n) : Bool × ℕ := + let child := OAI.EditApproximation.coordinateEqualWithWork (a.1, a.2.2) (b.1, b.2.2) + let time := OAI.EditApproximation.naturalEqualWithWork a.2.1 b.2.1 + (child.1 && time.1, child.2 + time.2 + 1) + +def queryGapStatesWithWork (n g anchor radius sourceLength gapRadius : ℕ) : + List (OAI.EditApproximation.TargetInterval n) × ℕ := + let lo := OAI.EditApproximation.saturatingSubtractWithWork anchor radius + let hi := OAI.EditApproximation.binaryNaturalAddWithWork anchor radius + let left := OAI.EditApproximation.gridPointsWithWork g (OAI.EditApproximation.bitWordValue lo.1) (OAI.EditApproximation.bitWordValue hi.1) + let states := OAI.EditApproximation.arithmeticFlatMapWithWork (fun first => + let center := OAI.EditApproximation.binaryNaturalAddWithWork first sourceLength + let lower := OAI.EditApproximation.saturatingSubtractWithWork (OAI.EditApproximation.bitWordValue center.1) gapRadius + let upper := OAI.EditApproximation.binaryNaturalAddWithWork (OAI.EditApproximation.bitWordValue center.1) gapRadius + let right := OAI.EditApproximation.gridPointsWithWork g (OAI.EditApproximation.bitWordValue lower.1) (OAI.EditApproximation.bitWordValue upper.1) + let valid := OAI.EditApproximation.filterMapWithWork (OAI.EditApproximation.makeStateWithWork n first) right.1 + (valid.1, center.2 + lower.2 + upper.2 + right.2 + valid.2 + 4)) left.1 + (states.1, lo.2 + hi.2 + left.2 + states.2 + 3) + +def queryOnlineKeyEqualWithWork {n : ℕ} (a b : ℕ × OAI.EditApproximation.TargetInterval n) : Bool × ℕ := + let scale := OAI.EditApproximation.naturalEqualWithWork a.1 b.1 + let state := OAI.EditApproximation.queryIntervalEqualWithWork a.2 b.2 + (scale.1 && state.1, scale.2 + state.2 + 1) + +def physicalEntryCode {M J n : ℕ} (state : OAI.EditApproximation.PhysicalEntry M J n) : ℕ := + OAI.EditApproximation.childInputCode ((0 : Fin 1), state.2) + (n + 1) ^ 2 * OAI.EditApproximation.physicalNodeCode state.1 + +def rankedBitLocalWork {κ : Type u_1} (rank : κ → ℕ) + (program : (key : κ) → OAI.EditApproximation.BitQuery {child : κ // rank child < rank key} OAI.EditApproximation.BinaryFraction) + (key : κ) : ℕ := + (program key).work (fun child => OAI.EditApproximation.rankedBitProgramValue rank program child.val) (fun _ => 0) + +def refinementParameterWordsWithWork (N pass : ℕ) (word : List Bool) + (hpositive : 0 < OAI.EditApproximation.bitWordValue word) : OAI.EditApproximation.RefinementParameterWords × ℕ := + let online := OAI.EditApproximation.BinaryFraction.onlineParametersWithWork word hpositive + let factor := OAI.EditApproximation.scheduledRefinementWordWithWork N pass + let decrement := OAI.EditApproximation.BinaryFraction.refinementDecrementWithWork word hpositive + (⟨online.1.2, factor.1, online.1.1, online.1.2, decrement.1⟩, + online.2 + factor.2 + decrement.2 + 5) + +def queryHistoryEqualAllocation {M n : ℕ} (a b : Fin M × ℕ × OAI.EditApproximation.TargetInterval n) : ℕ := + OAI.EditApproximation.coordinateEqualAllocation (a.1, a.2.2) (b.1, b.2.2) + OAI.EditApproximation.naturalEqualAllocation a.2.1 b.2.1 + 1 + +def queryOnlineKeyEqualAllocation {n : ℕ} (a b : ℕ × OAI.EditApproximation.TargetInterval n) : ℕ := + OAI.EditApproximation.naturalEqualAllocation a.1 b.1 + OAI.EditApproximation.queryIntervalEqualAllocation a.2 b.2 + 1 + +def gridStateBoxAllocation (n g radius lo hi : ℕ) : ℕ := + let leftLow := (OAI.EditApproximation.saturatingSubtractWithWork lo radius).1 + let leftHigh := (OAI.EditApproximation.binaryNaturalAddWithWork lo radius).1 + let rightLow := (OAI.EditApproximation.saturatingSubtractWithWork hi radius).1 + let rightHigh := (OAI.EditApproximation.binaryNaturalAddWithWork hi radius).1 + let left := (OAI.EditApproximation.gridPointsWithWork g (OAI.EditApproximation.bitWordValue leftLow) (OAI.EditApproximation.bitWordValue leftHigh)).1 + let right := (OAI.EditApproximation.gridPointsWithWork g (OAI.EditApproximation.bitWordValue rightLow) (OAI.EditApproximation.bitWordValue rightHigh)).1 + OAI.EditApproximation.saturatingSubtractAllocation lo radius + OAI.EditApproximation.binaryNaturalAddAllocation lo radius + + OAI.EditApproximation.saturatingSubtractAllocation hi radius + OAI.EditApproximation.binaryNaturalAddAllocation hi radius + + OAI.EditApproximation.gridPointsAllocation g (OAI.EditApproximation.bitWordValue leftLow) (OAI.EditApproximation.bitWordValue leftHigh) + + OAI.EditApproximation.gridPointsAllocation g (OAI.EditApproximation.bitWordValue rightLow) (OAI.EditApproximation.bitWordValue rightHigh) + + OAI.EditApproximation.arithmeticFlatMapAllocation (fun s => OAI.EditApproximation.filterMapWithWork (OAI.EditApproximation.makeStateWithWork n s) right) + (fun s => OAI.EditApproximation.filterMapAllocation (OAI.EditApproximation.makeStateWithWork n s) (OAI.EditApproximation.makeStateAllocation n s) right) left + +def queryHistoryCodeAllocation {M n : ℕ} (input : Fin M × ℕ × OAI.EditApproximation.TargetInterval n) : ℕ := + OAI.EditApproximation.queryChildCodeAllocation (input.1, input.2.2) + + OAI.EditApproximation.queryPairAllocation input.2.1 (OAI.EditApproximation.queryChildCodeWithWork (input.1, input.2.2)).1 + +def queryOrderedChildInputsAllocation {M n : ℕ} (inputs : List (Fin M × OAI.EditApproximation.TargetInterval n)) : ℕ := + OAI.EditApproximation.queryOrderedInputsAllocation OAI.EditApproximation.coordinateEqualWithWork (OAI.EditApproximation.queryEncodedLEWithWork OAI.EditApproximation.queryChildCodeWithWork) + OAI.EditApproximation.coordinateEqualAllocation (OAI.EditApproximation.queryEncodedLEAllocation OAI.EditApproximation.queryChildCodeWithWork OAI.EditApproximation.queryChildCodeAllocation) inputs + +def actionMemberAllocation {n M : ℕ} (a : Fin M → OAI.EditApproximation.TargetInterval n) : List (Fin M → OAI.EditApproximation.TargetInterval n) → ℕ + | [] => 0 + | b :: rest => OAI.EditApproximation.actionEqualAllocation a b + actionMemberAllocation a rest + +def queryGapStatesAllocation (n g anchor radius sourceLength gapRadius : ℕ) : ℕ := + let lo := (OAI.EditApproximation.saturatingSubtractWithWork anchor radius).1 + let hi := (OAI.EditApproximation.binaryNaturalAddWithWork anchor radius).1 + let left := (OAI.EditApproximation.gridPointsWithWork g (OAI.EditApproximation.bitWordValue lo) (OAI.EditApproximation.bitWordValue hi)).1 + let build := fun first => + let center := OAI.EditApproximation.binaryNaturalAddWithWork first sourceLength + let lower := OAI.EditApproximation.saturatingSubtractWithWork (OAI.EditApproximation.bitWordValue center.1) gapRadius + let upper := OAI.EditApproximation.binaryNaturalAddWithWork (OAI.EditApproximation.bitWordValue center.1) gapRadius + let right := OAI.EditApproximation.gridPointsWithWork g (OAI.EditApproximation.bitWordValue lower.1) (OAI.EditApproximation.bitWordValue upper.1) + let valid := OAI.EditApproximation.filterMapWithWork (OAI.EditApproximation.makeStateWithWork n first) right.1 + (valid.1, center.2 + lower.2 + upper.2 + right.2 + valid.2 + 4) + let allocation := fun first => + let center := (OAI.EditApproximation.binaryNaturalAddWithWork first sourceLength).1 + let lower := (OAI.EditApproximation.saturatingSubtractWithWork (OAI.EditApproximation.bitWordValue center) gapRadius).1 + let upper := (OAI.EditApproximation.binaryNaturalAddWithWork (OAI.EditApproximation.bitWordValue center) gapRadius).1 + let right := (OAI.EditApproximation.gridPointsWithWork g (OAI.EditApproximation.bitWordValue lower) (OAI.EditApproximation.bitWordValue upper)).1 + OAI.EditApproximation.binaryNaturalAddAllocation first sourceLength + OAI.EditApproximation.saturatingSubtractAllocation (OAI.EditApproximation.bitWordValue center) gapRadius + + OAI.EditApproximation.binaryNaturalAddAllocation (OAI.EditApproximation.bitWordValue center) gapRadius + OAI.EditApproximation.gridPointsAllocation g (OAI.EditApproximation.bitWordValue lower) (OAI.EditApproximation.bitWordValue upper) + + OAI.EditApproximation.filterMapAllocation (OAI.EditApproximation.makeStateWithWork n first) (OAI.EditApproximation.makeStateAllocation n first) right + OAI.EditApproximation.saturatingSubtractAllocation anchor radius + OAI.EditApproximation.binaryNaturalAddAllocation anchor radius + + OAI.EditApproximation.gridPointsAllocation g (OAI.EditApproximation.bitWordValue lo) (OAI.EditApproximation.bitWordValue hi) + OAI.EditApproximation.arithmeticFlatMapAllocation build allocation left + +def wideActionList {nx ny : ℕ} (M : ℕ) (parent : OAI.EditApproximation.TargetInterval nx) + (r : OAI.EditApproximation.TargetInterval ny) (b P : ℕ) : List (Fin M → OAI.EditApproximation.TargetInterval ny) := + OAI.EditApproximation.finiteAssignments M (OAI.EditApproximation.wideChildStateList parent r b P) + +def physicalSourceInterval {M J : ℕ} (nx : ℕ) (node : OAI.EditApproximation.PhysicalNode M J) : OAI.EditApproximation.TargetInterval nx := + OAI.EditApproximation.sourceIntervalAt M nx node.1.val node.2 + +def localInitialConeTable {α : Type u_1} (source target : List α) + (U : OAI.EditApproximation.TargetInterval target.length → ℕ) (N P F : ℕ) (A a : ℚ) + (q : OAI.EditApproximation.TargetInterval target.length) : ℚ := + if U q = 0 then 0 else + OAI.EditApproximation.rationalMinimum ((32 * F + 1) * N) + ((OAI.EditApproximation.localInitialConeCenters N P A U q).map + (OAI.EditApproximation.initialConeValue source target U a (32 * F) q)) + +def wideChildGridWithWork {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (r : OAI.EditApproximation.TargetInterval ny) (b P : ℕ) (i : Fin M) : List (OAI.EditApproximation.TargetInterval ny) × ℕ := + let child := OAI.EditApproximation.sourceChildWithWork parent i + let spacing := OAI.EditApproximation.seedGridSpacingWithWork b P + let radius := OAI.EditApproximation.binaryNaturalMulWithWork 10 b + let leftOffset := OAI.EditApproximation.saturatingSubtractWithWork child.1.lo parent.lo + let rightOffset := OAI.EditApproximation.saturatingSubtractWithWork child.1.hi parent.lo + let left := OAI.EditApproximation.binaryNaturalAddWithWork r.lo (OAI.EditApproximation.bitWordValue leftOffset.1) + let right := OAI.EditApproximation.binaryNaturalAddWithWork r.lo (OAI.EditApproximation.bitWordValue rightOffset.1) + let grid := OAI.EditApproximation.gridStateBoxWithWork ny (OAI.EditApproximation.bitWordValue spacing.1) (OAI.EditApproximation.bitWordValue radius.1) + (OAI.EditApproximation.bitWordValue left.1) (OAI.EditApproximation.bitWordValue right.1) + (grid.1, child.2 + spacing.2 + radius.2 + leftOffset.2 + rightOffset.2 + left.2 + right.2 + grid.2 + 8) + +def queryOrderedHistoryInputsWithWork {M n : ℕ} (inputs : List (Fin M × ℕ × OAI.EditApproximation.TargetInterval n)) : + List (Fin M × ℕ × OAI.EditApproximation.TargetInterval n) × ℕ := + OAI.EditApproximation.queryOrderedInputsWithWork OAI.EditApproximation.queryHistoryEqualWithWork + (OAI.EditApproximation.queryEncodedLEWithWork OAI.EditApproximation.queryHistoryCodeWithWork) inputs + +def queryNeededInputsWithWork {n M : ℕ} + (selected online : List (OAI.EditApproximation.BinaryBellmanAction (OAI.EditApproximation.TargetInterval n) (Fin M × OAI.EditApproximation.TargetInterval n) M)) : + List (Fin M × OAI.EditApproximation.TargetInterval n) × ℕ := + let first := OAI.EditApproximation.queryActionInputsWithWork selected + let second := OAI.EditApproximation.queryActionInputsWithWork online + let sorted := OAI.EditApproximation.queryOrderedChildInputsWithWork (first.1 ++ second.1) + (sorted.1, first.2 + second.2 + first.1.length + sorted.2 + 2) + +def computedQueryParameters (N pass : ℕ) : OAI.EditApproximation.RefinementParameterWords := by + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_computed_small_word_pos_125 (N : ℕ) : 0 < OAI.EditApproximation.bitWordValue (OAI.EditApproximation.inputSmallLog N).bits := by + rw [proof_bitWordValue_bits_15] + exact Nat.two_pow_pos _ + exact + (OAI.EditApproximation.refinementParameterWordsWithWork N pass (OAI.EditApproximation.inputSmallLog N).bits (proof_computed_small_word_pos_125 N)).1 + +def wideChildGridAllocation {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (r : OAI.EditApproximation.TargetInterval ny) (b P : ℕ) (i : Fin M) : ℕ := + let child := (OAI.EditApproximation.sourceChildWithWork parent i).1 + let spacing := (OAI.EditApproximation.seedGridSpacingWithWork b P).1 + let radius := (OAI.EditApproximation.binaryNaturalMulWithWork 10 b).1 + let leftOffset := (OAI.EditApproximation.saturatingSubtractWithWork child.lo parent.lo).1 + let rightOffset := (OAI.EditApproximation.saturatingSubtractWithWork child.hi parent.lo).1 + let left := (OAI.EditApproximation.binaryNaturalAddWithWork r.lo (OAI.EditApproximation.bitWordValue leftOffset)).1 + let right := (OAI.EditApproximation.binaryNaturalAddWithWork r.lo (OAI.EditApproximation.bitWordValue rightOffset)).1 + OAI.EditApproximation.sourceChildAllocation parent i + OAI.EditApproximation.seedGridSpacingAllocation b P + OAI.EditApproximation.binaryNaturalMulAllocation 10 b + + OAI.EditApproximation.saturatingSubtractAllocation child.lo parent.lo + OAI.EditApproximation.saturatingSubtractAllocation child.hi parent.lo + + OAI.EditApproximation.binaryNaturalAddAllocation r.lo (OAI.EditApproximation.bitWordValue leftOffset) + + OAI.EditApproximation.binaryNaturalAddAllocation r.lo (OAI.EditApproximation.bitWordValue rightOffset) + + OAI.EditApproximation.gridStateBoxAllocation ny (OAI.EditApproximation.bitWordValue spacing) (OAI.EditApproximation.bitWordValue radius) (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) + +def queryOrderedHistoryInputsAllocation {M n : ℕ} (inputs : List (Fin M × ℕ × OAI.EditApproximation.TargetInterval n)) : ℕ := + OAI.EditApproximation.queryOrderedInputsAllocation OAI.EditApproximation.queryHistoryEqualWithWork (OAI.EditApproximation.queryEncodedLEWithWork OAI.EditApproximation.queryHistoryCodeWithWork) + OAI.EditApproximation.queryHistoryEqualAllocation (OAI.EditApproximation.queryEncodedLEAllocation OAI.EditApproximation.queryHistoryCodeWithWork OAI.EditApproximation.queryHistoryCodeAllocation) inputs + +def queryNeededInputsAllocation {n M : ℕ} + (selected online : List (OAI.EditApproximation.BinaryBellmanAction (OAI.EditApproximation.TargetInterval n) (Fin M × OAI.EditApproximation.TargetInterval n) M)) : ℕ := + let first := (OAI.EditApproximation.queryActionInputsWithWork selected).1 + let second := (OAI.EditApproximation.queryActionInputsWithWork online).1 + OAI.EditApproximation.queryActionInputsAllocation selected + OAI.EditApproximation.queryActionInputsAllocation online + first.length + + OAI.EditApproximation.queryOrderedChildInputsAllocation (first ++ second) + +def physicalSource {α : Type u_1} {M J : ℕ} (source : List α) (node : OAI.EditApproximation.PhysicalNode M J) : List α := + OAI.EditApproximation.substring source (OAI.EditApproximation.physicalSourceInterval source.length node).lo (OAI.EditApproximation.physicalSourceInterval source.length node).hi + +def wideActionGridWithWork {nx ny : ℕ} (M : ℕ) (parent : OAI.EditApproximation.TargetInterval nx) + (r : OAI.EditApproximation.TargetInterval ny) (b P : ℕ) : List (Vector (OAI.EditApproximation.TargetInterval ny) M) × ℕ := + let choices := OAI.EditApproximation.vectorMapWithWork M (OAI.EditApproximation.wideChildGridWithWork parent r b P) + let product := OAI.EditApproximation.materializedAssignmentsWithWork M choices.1.get + (product.1, choices.2 + product.2 + 1) + +def physicalCoarsePreparationCost {M J : ℕ} (source target : List ℕ) + (entry : OAI.EditApproximation.PhysicalEntry M J target.length) : ℕ := + let interval := OAI.EditApproximation.physicalSourceInterval source.length entry.1 + (OAI.EditApproximation.coarsePreparedSlicesWithWork source target interval.lo interval.hi entry.2.lo entry.2.hi).2 + +def wideActionGridAllocation {nx ny : ℕ} (M : ℕ) (parent : OAI.EditApproximation.TargetInterval nx) + (r : OAI.EditApproximation.TargetInterval ny) (b P : ℕ) : ℕ := + let choices := (OAI.EditApproximation.vectorMapWithWork M (OAI.EditApproximation.wideChildGridWithWork parent r b P)).1 + OAI.EditApproximation.vectorMapAllocation M (OAI.EditApproximation.wideChildGridAllocation parent r b P) + OAI.EditApproximation.materializedAssignmentsAllocation M choices.get + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BinaryFraction + + +def sumListWithWork (values : List OAI.EditApproximation.BinaryFraction) : OAI.EditApproximation.BinaryFraction × ℕ := + let result := OAI.EditApproximation.BinaryFraction.bandMassTotalWithWork (Vector.ofFn values.get) + (result.1, result.2 + 6 * values.length) + +def connectionTermsWithWork {n : ℕ} (start : OAI.EditApproximation.BinaryFraction) : + List (OAI.EditApproximation.TargetInterval n) → OAI.EditApproximation.BinaryFraction → List OAI.EditApproximation.BinaryFraction × ℕ + | [], finish => + let result := OAI.EditApproximation.BinaryFraction.distanceWithWork start finish + ([result.1], result.2 + 2) + | state :: rest, finish => + let current := OAI.EditApproximation.BinaryFraction.distanceWithWork start (OAI.EditApproximation.BinaryFraction.nat state.lo) + let tail := connectionTermsWithWork (OAI.EditApproximation.BinaryFraction.nat state.hi) rest finish + (current.1 :: tail.1, + current.2 + tail.2 + Nat.size state.lo + Nat.size state.hi + 6) + +def bandEnvelopeReadWithWork {M n : ℕ} (b : ℕ) (band : List (Fin M → OAI.EditApproximation.TargetInterval n)) + (read : Fin M → OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) (i : Fin M) : OAI.EditApproximation.BinaryFraction × ℕ := + let values := OAI.EditApproximation.arithmeticMapWithWork (fun action => read i (action i)) band + let floor := OAI.EditApproximation.BinaryFraction.divWithWork (OAI.EditApproximation.BinaryFraction.nat b) (OAI.EditApproximation.BinaryFraction.nat M) + let maximum := OAI.EditApproximation.BinaryFraction.maximumWithWork OAI.EditApproximation.BinaryFraction.zero values.1 + let input := OAI.EditApproximation.BinaryFraction.maxWithWork floor.1 maximum.1 + let result := OAI.EditApproximation.BinaryFraction.dyadicCeilingWithWork input.1 + (result.1, values.2 + floor.2 + maximum.2 + input.2 + result.2 + band.length + 4) + +def onlineLinearReadWithWork {β : Type u_1} {σ : Type u_2} (mass : β → OAI.EditApproximation.BinaryFraction) + (read : ℕ → β × σ → OAI.EditApproximation.BinaryFraction × ℕ) (eta kappa : OAI.EditApproximation.BinaryFraction) + (t : ℕ) (i : β × σ) : OAI.EditApproximation.BinaryFraction × ℕ := + let coefficient := OAI.EditApproximation.BinaryFraction.coefficientWithWork kappa + let terms := OAI.EditApproximation.vectorMapWithWork t fun s => OAI.EditApproximation.BinaryFraction.optimisticTermReadWithWork mass read coefficient.1 s.val i + let history := OAI.EditApproximation.BinaryFraction.bandMassTotalWithWork terms.1 + let current := OAI.EditApproximation.BinaryFraction.gainReadWithWork mass read t i + let total := OAI.EditApproximation.BinaryFraction.canonicalAddWithWork history.1 current.1 + let result := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork eta total.1 + (result.1, coefficient.2 + terms.2 + history.2 + current.2 + total.2 + result.2 + 3) + +def targetCellsWithWork {n : ℕ} (side : OAI.EditApproximation.BinaryFraction) (radius : ℕ) + (q : OAI.EditApproximation.TargetInterval n) : List (ℕ × ℕ) × ℕ := + let left := OAI.EditApproximation.BinaryFraction.cellCoordinatesWithWork side q.lo radius + let right := OAI.EditApproximation.BinaryFraction.cellCoordinatesWithWork side q.hi radius + let cells := OAI.EditApproximation.arithmeticFlatMapWithWork (fun lo => + OAI.EditApproximation.arithmeticMapWithWork (fun hi => ((lo, hi), 1)) right.1) left.1 + (cells.1, left.2 + right.2 + cells.2 + 2) + +def cellStatesWithWork (n g : ℕ) (side : OAI.EditApproximation.BinaryFraction) (cell : ℕ × ℕ) : + List (OAI.EditApproximation.TargetInterval n) × ℕ := + let left := OAI.EditApproximation.BinaryFraction.cellGridPointsWithWork side g cell.1 + let right := OAI.EditApproximation.BinaryFraction.cellGridPointsWithWork side g cell.2 + let states := OAI.EditApproximation.arithmeticFlatMapWithWork (fun lo => + OAI.EditApproximation.filterMapWithWork (OAI.EditApproximation.makeStateWithWork n lo) right.1) left.1 + (states.1, left.2 + right.2 + states.2 + 2) + +def bandCoordinatesWithWork {M n : ℕ} (band : List (Fin M → OAI.EditApproximation.TargetInterval n)) : + List (Fin M × OAI.EditApproximation.TargetInterval n) × ℕ := + let raw := OAI.EditApproximation.arithmeticFlatMapWithWork (fun action => + OAI.EditApproximation.arithmeticMapWithWork (fun i : Fin M => ((i, action i), 1)) (List.finRange M)) band + let unique := OAI.EditApproximation.dedupByWithWork OAI.EditApproximation.coordinateEqualWithWork raw.1 + (unique.1, raw.2 + unique.2 + 1) + +def countedBandCoordinateWithWork {M n : ℕ} (mass : Vector OAI.EditApproximation.BinaryFraction M) + (total : OAI.EditApproximation.BinaryFraction) (action : Fin M → OAI.EditApproximation.TargetInterval n) + (coordinate : Fin M × OAI.EditApproximation.TargetInterval n) : OAI.EditApproximation.BinaryFraction × ℕ := + let test := OAI.EditApproximation.coordinateEqualWithWork coordinate (coordinate.1, action coordinate.1) + let result := if test.1 then OAI.EditApproximation.BinaryFraction.divWithWork (mass.get coordinate.1) total else (OAI.EditApproximation.BinaryFraction.zero, 1) + (result.1, test.2 + result.2 + 1) + +def representativeScaleReadWithWork {n : ℕ} (P F : ℕ) (a : OAI.EditApproximation.BinaryFraction) + (read : OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) (radius : List Bool) + (query : OAI.EditApproximation.TargetInterval n) (e : ℕ) : List (ℕ × OAI.EditApproximation.TargetInterval n) × ℕ := + let b := 2 ^ e + let spacing := OAI.EditApproximation.seedGridSpacingWithWork b P + let points := OAI.EditApproximation.gridStateBoxWithWork n (OAI.EditApproximation.bitWordValue spacing.1) (OAI.EditApproximation.bitWordValue radius) query.lo query.hi + let selected := OAI.EditApproximation.filterWithWork (fun r => + let word := read r + let guard := OAI.EditApproximation.BinaryFraction.centerEligibilityWithWork b F a word.1 + (guard.1, guard.2 + word.2)) points.1 + let labeled := OAI.EditApproximation.arithmeticMapWithWork (fun r => ((b, r), 1)) selected.1 + (labeled.1, spacing.2 + points.2 + selected.2 + labeled.2 + e + 5) + +def queryRawCentersWithWork {n : ℕ} (N P F : ℕ) (a value : OAI.EditApproximation.BinaryFraction) + (q : OAI.EditApproximation.TargetInterval n) : List (OAI.EditApproximation.TargetInterval n) × ℕ := + let scales := OAI.EditApproximation.BinaryFraction.queryScalesWithWork N F a value + let radius := OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork value + let centers := OAI.EditApproximation.arithmeticFlatMapWithWork (fun b => + let spacing := OAI.EditApproximation.seedGridSpacingWithWork b P + let states := OAI.EditApproximation.gridStateBoxWithWork n (OAI.EditApproximation.bitWordValue spacing.1) (OAI.EditApproximation.bitWordValue radius.1) q.lo q.hi + (states.1, spacing.2 + states.2 + 1)) scales.1 + let unique := OAI.EditApproximation.queryEraseWithWork OAI.EditApproximation.queryIntervalEqualWithWork centers.1 + (unique.1, scales.2 + radius.2 + centers.2 + unique.2 + 3) + +def queryWideInputsWithWork {nx ny : ℕ} (M : ℕ) (parent : OAI.EditApproximation.TargetInterval nx) (P : ℕ) + (representatives : List (ℕ × OAI.EditApproximation.TargetInterval ny)) : List (Fin M × OAI.EditApproximation.TargetInterval ny) × ℕ := + let raw := OAI.EditApproximation.arithmeticFlatMapWithWork (fun br => + OAI.EditApproximation.arithmeticFlatMapWithWork (fun i : Fin M => + let states := OAI.EditApproximation.wideChildGridWithWork parent br.2 br.1 P i + let labeled := OAI.EditApproximation.arithmeticMapWithWork (fun r => ((i, r), 1)) states.1 + (labeled.1, states.2 + labeled.2 + 1)) (List.finRange M)) representatives + let unique := OAI.EditApproximation.queryEraseWithWork OAI.EditApproximation.coordinateEqualWithWork raw.1 + (unique.1, raw.2 + unique.2 + M + 2) + +def queryRawHistoryInputsWithWork {nx ny : ℕ} (M : ℕ) (parent : OAI.EditApproximation.TargetInterval nx) + (P history : ℕ) (representatives : List (ℕ × OAI.EditApproximation.TargetInterval ny)) : + List (Fin M × ℕ × OAI.EditApproximation.TargetInterval ny) × ℕ := + let inputs := OAI.EditApproximation.arithmeticFlatMapWithWork (fun br => + OAI.EditApproximation.arithmeticFlatMapWithWork (fun i : Fin M => + let states := OAI.EditApproximation.wideChildGridWithWork parent br.2 br.1 P i + let times := OAI.EditApproximation.arithmeticFlatMapWithWork (fun t => + OAI.EditApproximation.arithmeticMapWithWork (fun r => ((i, t, r), 1)) states.1) (List.range history) + (times.1, states.2 + times.2 + history + 2)) (List.finRange M)) representatives + (inputs.1, inputs.2 + M + 1) + +def queryGroupRoundedStatesWithWork {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (b exponent : ℕ) (cell : ℕ × ℕ) (i : Fin M) (h : OAI.EditApproximation.BinaryFraction) : + List (OAI.EditApproximation.TargetInterval ny) × ℕ := + let theta := OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent + let spacing := OAI.EditApproximation.BinaryFraction.roundedSpacingWithWork theta h + let child := OAI.EditApproximation.sourceChildWithWork parent i + let offset := OAI.EditApproximation.saturatingSubtractWithWork child.1.lo parent.lo + let base := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat cell.1) theta + let position := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork base.1 (OAI.EditApproximation.BinaryFraction.nat b) + let floor := OAI.EditApproximation.BinaryFraction.naturalFloorWithWork position.1 + let anchor := OAI.EditApproximation.binaryNaturalAddWithWork (OAI.EditApproximation.bitWordValue floor.1) (OAI.EditApproximation.bitWordValue offset.1) + let radius := OAI.EditApproximation.binaryNaturalMulWithWork 12 b + let length := OAI.EditApproximation.saturatingSubtractWithWork child.1.hi child.1.lo + let twice := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 2) h + let gap := OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork twice.1 + let states := OAI.EditApproximation.queryGapStatesWithWork ny (OAI.EditApproximation.bitWordValue spacing.1) (OAI.EditApproximation.bitWordValue anchor.1) + (OAI.EditApproximation.bitWordValue radius.1) (OAI.EditApproximation.bitWordValue length.1) (OAI.EditApproximation.bitWordValue gap.1) + (states.1, spacing.2 + child.2 + offset.2 + base.2 + position.2 + floor.2 + anchor.2 + + radius.2 + length.2 + twice.2 + gap.2 + states.2 + exponent + 12) + +def queryOnlineIntegerReadWithWork {n : ℕ} (keys : List (ℕ × OAI.EditApproximation.TargetInterval n)) + (values : List OAI.EditApproximation.BinaryFraction) (b : ℕ) (q : OAI.EditApproximation.TargetInterval n) : ℕ × ℕ := + let word := OAI.EditApproximation.BinaryFraction.gatheredWordLookupWithWork OAI.EditApproximation.queryOnlineKeyEqualWithWork keys values (b, q) + let floor := OAI.EditApproximation.BinaryFraction.naturalFloorWithWork word.1 + (OAI.EditApproximation.bitWordValue floor.1, word.2 + floor.2 + 1) + +def queryChildReadWithWork {M n : ℕ} (keys : List (Fin M × OAI.EditApproximation.TargetInterval n)) + (values : List OAI.EditApproximation.BinaryFraction) (i : Fin M) (q : OAI.EditApproximation.TargetInterval n) : OAI.EditApproximation.BinaryFraction × ℕ := + OAI.EditApproximation.BinaryFraction.gatheredWordLookupWithWork OAI.EditApproximation.coordinateEqualWithWork keys values (i, q) + +def queryHistoryReadWithWork {M n : ℕ} (keys : List (Fin M × ℕ × OAI.EditApproximation.TargetInterval n)) + (values : List OAI.EditApproximation.BinaryFraction) (s : ℕ) (input : Fin M × OAI.EditApproximation.TargetInterval n) : OAI.EditApproximation.BinaryFraction × ℕ := + OAI.EditApproximation.BinaryFraction.gatheredWordLookupWithWork OAI.EditApproximation.queryHistoryEqualWithWork keys values (input.1, s, input.2) + +def queryParentReadWithWork {n : ℕ} (keys : List (OAI.EditApproximation.TargetInterval n)) + (words : List OAI.EditApproximation.BinaryFraction) (r : OAI.EditApproximation.TargetInterval n) : OAI.EditApproximation.BinaryFraction × ℕ := + OAI.EditApproximation.BinaryFraction.gatheredWordLookupWithWork OAI.EditApproximation.queryIntervalEqualWithWork keys words r + +def initialGridReadWithWork {n : ℕ} (P : ℕ) (A : OAI.EditApproximation.BinaryFraction) + (read : OAI.EditApproximation.TargetInterval n → List Bool × ℕ) (radius : ℕ) (q : OAI.EditApproximation.TargetInterval n) (b : ℕ) : + List (OAI.EditApproximation.TargetInterval n) × ℕ := + let spacing := OAI.EditApproximation.seedGridSpacingWithWork b P + let points := OAI.EditApproximation.gridStateBoxWithWork n (OAI.EditApproximation.bitWordValue spacing.1) radius q.lo q.hi + let selected := OAI.EditApproximation.filterWithWork (fun r => + let word := read r + let guard := OAI.EditApproximation.BinaryFraction.initialCenterGuardWithWork b (OAI.EditApproximation.bitWordValue word.1) A + (guard.1, guard.2 + word.2)) points.1 + (selected.1, spacing.2 + points.2 + selected.2 + 2) + +def queryInitialConeCentersWithWork {n : ℕ} (N P : ℕ) (A value : OAI.EditApproximation.BinaryFraction) + (q : OAI.EditApproximation.TargetInterval n) : List (OAI.EditApproximation.TargetInterval n) × ℕ := + let radius := OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork value + let scales := OAI.EditApproximation.dyadicScalesWithWork N + let active := OAI.EditApproximation.filterWithWork (fun b => OAI.EditApproximation.BinaryFraction.initialScaleGuardWithWork (OAI.EditApproximation.bitWordValue radius.1) b A) scales.1 + let centers := OAI.EditApproximation.arithmeticFlatMapWithWork (fun b => + let spacing := OAI.EditApproximation.seedGridSpacingWithWork b P + let states := OAI.EditApproximation.gridStateBoxWithWork n (OAI.EditApproximation.bitWordValue spacing.1) (OAI.EditApproximation.bitWordValue radius.1) q.lo q.hi + (states.1, spacing.2 + states.2 + 1)) active.1 + (centers.1, radius.2 + scales.2 + active.2 + centers.2 + 2) + +def connectionTermsAllocation {n : ℕ} (start : OAI.EditApproximation.BinaryFraction) : + List (OAI.EditApproximation.TargetInterval n) → OAI.EditApproximation.BinaryFraction → ℕ + | [], finish => OAI.EditApproximation.BinaryFraction.distanceAllocation start finish + 1 + | state :: rest, finish => OAI.EditApproximation.BinaryFraction.distanceAllocation start (OAI.EditApproximation.BinaryFraction.nat state.lo) + + connectionTermsAllocation (OAI.EditApproximation.BinaryFraction.nat state.hi) rest finish + Nat.size state.lo + Nat.size state.hi + 3 + +def endpointDistanceAllocation {n : ℕ} (q r : OAI.EditApproximation.TargetInterval n) : ℕ := + OAI.EditApproximation.BinaryFraction.distanceAllocation (OAI.EditApproximation.BinaryFraction.nat q.lo) (OAI.EditApproximation.BinaryFraction.nat r.lo) + OAI.EditApproximation.BinaryFraction.distanceAllocation (OAI.EditApproximation.BinaryFraction.nat q.hi) (OAI.EditApproximation.BinaryFraction.nat r.hi) + + OAI.EditApproximation.BinaryFraction.canonicalAddAllocation (OAI.EditApproximation.BinaryFraction.distanceWithWork (OAI.EditApproximation.BinaryFraction.nat q.lo) (OAI.EditApproximation.BinaryFraction.nat r.lo)).1 + (OAI.EditApproximation.BinaryFraction.distanceWithWork (OAI.EditApproximation.BinaryFraction.nat q.hi) (OAI.EditApproximation.BinaryFraction.nat r.hi)).1 + Nat.size q.lo + Nat.size q.hi + Nat.size r.lo + Nat.size r.hi + +def stateGapAllocation {n : ℕ} (sourceLength : ℕ) (r : OAI.EditApproximation.TargetInterval n) : ℕ := + OAI.EditApproximation.BinaryFraction.subAllocation (OAI.EditApproximation.BinaryFraction.nat r.hi) (OAI.EditApproximation.BinaryFraction.nat r.lo) + + OAI.EditApproximation.BinaryFraction.subAllocation (OAI.EditApproximation.BinaryFraction.subWithWork (OAI.EditApproximation.BinaryFraction.nat r.hi) (OAI.EditApproximation.BinaryFraction.nat r.lo)).1 (OAI.EditApproximation.BinaryFraction.nat sourceLength) + Nat.size r.hi + Nat.size r.lo + Nat.size sourceLength + +def queryChildReadAllocation {M n : ℕ} (keys : List (Fin M × OAI.EditApproximation.TargetInterval n)) + (values : List OAI.EditApproximation.BinaryFraction) (i : Fin M) (q : OAI.EditApproximation.TargetInterval n) : ℕ := + OAI.EditApproximation.BinaryFraction.gatheredLookupAllocation OAI.EditApproximation.coordinateEqualWithWork OAI.EditApproximation.coordinateEqualAllocation keys values (i, q) + +def queryHistoryReadAllocation {M n : ℕ} (keys : List (Fin M × ℕ × OAI.EditApproximation.TargetInterval n)) + (values : List OAI.EditApproximation.BinaryFraction) (s : ℕ) (input : Fin M × OAI.EditApproximation.TargetInterval n) : ℕ := + OAI.EditApproximation.BinaryFraction.gatheredLookupAllocation OAI.EditApproximation.queryHistoryEqualWithWork OAI.EditApproximation.queryHistoryEqualAllocation keys values (input.1, s, input.2) + +def queryOnlineIntegerReadAllocation {n : ℕ} (keys : List (ℕ × OAI.EditApproximation.TargetInterval n)) + (values : List OAI.EditApproximation.BinaryFraction) (b : ℕ) (q : OAI.EditApproximation.TargetInterval n) : ℕ := + let word := (OAI.EditApproximation.BinaryFraction.gatheredWordLookupWithWork OAI.EditApproximation.queryOnlineKeyEqualWithWork keys values (b, q)).1 + OAI.EditApproximation.BinaryFraction.gatheredLookupAllocation OAI.EditApproximation.queryOnlineKeyEqualWithWork OAI.EditApproximation.queryOnlineKeyEqualAllocation keys values (b, q) + + OAI.EditApproximation.BinaryFraction.naturalFloorAllocation word + +def bandCoordinatesAllocation {M n : ℕ} (band : List (Fin M → OAI.EditApproximation.TargetInterval n)) : ℕ := + let build := fun action : Fin M → OAI.EditApproximation.TargetInterval n => + OAI.EditApproximation.arithmeticMapWithWork (fun i : Fin M => ((i, action i), 1)) (List.finRange M) + let raw := (OAI.EditApproximation.arithmeticFlatMapWithWork build band).1 + OAI.EditApproximation.arithmeticFlatMapAllocation build + (fun _ => OAI.EditApproximation.arithmeticMapAllocation (fun _ : Fin M => 1) (List.finRange M) + M) band + + OAI.EditApproximation.dedupByAllocation OAI.EditApproximation.coordinateEqualWithWork OAI.EditApproximation.coordinateEqualAllocation raw + +def scoredArgmaxAllocation {α : Type u_1} (score : α → OAI.EditApproximation.BinaryFraction × ℕ) + (allocation : α → ℕ) : List α → ℕ + | [] => 0 + | a :: rest => + scoredArgmaxAllocation score allocation rest + allocation a + + match (OAI.EditApproximation.BinaryFraction.scoredArgmaxWithWork score rest).1 with + | none => 1 + | some best => OAI.EditApproximation.BinaryFraction.ltAllocation (score a).1 best.2 + 1 + +def anchorGuardAllocation {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) (r : OAI.EditApproximation.TargetInterval ny) + (b : ℕ) (states : Fin M → OAI.EditApproximation.TargetInterval ny) (i : Fin M) : ℕ := + let left := (OAI.EditApproximation.translatedEndpointWithWork r.lo parent.lo (OAI.EditApproximation.sourceChild parent i).lo).1 + let right := (OAI.EditApproximation.translatedEndpointWithWork r.lo parent.lo (OAI.EditApproximation.sourceChild parent i).hi).1 + let radius := OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalMulWithWork 6 b).1 + OAI.EditApproximation.translatedEndpointAllocation r.lo parent.lo (OAI.EditApproximation.sourceChild parent i).lo + + OAI.EditApproximation.translatedEndpointAllocation r.lo parent.lo (OAI.EditApproximation.sourceChild parent i).hi + OAI.EditApproximation.binaryNaturalMulAllocation 6 b + + OAI.EditApproximation.BinaryFraction.naturalDistanceLeAllocation left (states i).lo radius + OAI.EditApproximation.BinaryFraction.naturalDistanceLeAllocation right (states i).hi radius + +def bandEnvelopeReadAllocation {M n : ℕ} (b : ℕ) (band : List (Fin M → OAI.EditApproximation.TargetInterval n)) + (read : Fin M → OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) + (footprint : Fin M → OAI.EditApproximation.TargetInterval n → ℕ) (i : Fin M) : ℕ := + let values := (OAI.EditApproximation.arithmeticMapWithWork (fun action => read i (action i)) band).1 + let floor := (OAI.EditApproximation.BinaryFraction.divWithWork (OAI.EditApproximation.BinaryFraction.nat b) (OAI.EditApproximation.BinaryFraction.nat M)).1 + let maximum := (OAI.EditApproximation.BinaryFraction.maximumWithWork OAI.EditApproximation.BinaryFraction.zero values).1 + OAI.EditApproximation.arithmeticMapAllocation (fun action => footprint i (action i)) band + + OAI.EditApproximation.BinaryFraction.divAllocation (OAI.EditApproximation.BinaryFraction.nat b) (OAI.EditApproximation.BinaryFraction.nat M) + OAI.EditApproximation.BinaryFraction.maximumAllocation OAI.EditApproximation.BinaryFraction.zero values + OAI.EditApproximation.BinaryFraction.maxAllocation floor maximum + + OAI.EditApproximation.BinaryFraction.dyadicCeilingAllocation (OAI.EditApproximation.BinaryFraction.maxWithWork floor maximum).1 + 0 + +def targetCellsAllocation {n : ℕ} (side : OAI.EditApproximation.BinaryFraction) (radius : ℕ) (q : OAI.EditApproximation.TargetInterval n) : ℕ := + let left := (OAI.EditApproximation.BinaryFraction.cellCoordinatesWithWork side q.lo radius).1 + let right := (OAI.EditApproximation.BinaryFraction.cellCoordinatesWithWork side q.hi radius).1 + OAI.EditApproximation.BinaryFraction.cellCoordinatesAllocation side q.lo radius + OAI.EditApproximation.BinaryFraction.cellCoordinatesAllocation side q.hi radius + + OAI.EditApproximation.arithmeticFlatMapAllocation (fun lo => OAI.EditApproximation.arithmeticMapWithWork (fun hi => ((lo, hi), 1)) right) + (fun _ => OAI.EditApproximation.arithmeticMapAllocation (fun _ => 1) right) left + +def cellStatesAllocation (n g : ℕ) (side : OAI.EditApproximation.BinaryFraction) (cell : ℕ × ℕ) : ℕ := + let left := (OAI.EditApproximation.BinaryFraction.cellGridPointsWithWork side g cell.1).1 + let right := (OAI.EditApproximation.BinaryFraction.cellGridPointsWithWork side g cell.2).1 + OAI.EditApproximation.BinaryFraction.cellGridPointsAllocation side g cell.1 + OAI.EditApproximation.BinaryFraction.cellGridPointsAllocation side g cell.2 + + OAI.EditApproximation.arithmeticFlatMapAllocation (fun lo => OAI.EditApproximation.filterMapWithWork (OAI.EditApproximation.makeStateWithWork n lo) right) + (fun lo => OAI.EditApproximation.filterMapAllocation (OAI.EditApproximation.makeStateWithWork n lo) (OAI.EditApproximation.makeStateAllocation n lo) right) left + +def queryRawCentersAllocation {n : ℕ} (N P F : ℕ) (a value : OAI.EditApproximation.BinaryFraction) (q : OAI.EditApproximation.TargetInterval n) : ℕ := + let build := fun b => + let spacing := OAI.EditApproximation.seedGridSpacingWithWork b P + let states := OAI.EditApproximation.gridStateBoxWithWork n (OAI.EditApproximation.bitWordValue spacing.1) (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork value).1) q.lo q.hi + (states.1, spacing.2 + states.2 + 1) + let allocation := fun b => OAI.EditApproximation.seedGridSpacingAllocation b P + + OAI.EditApproximation.gridStateBoxAllocation n (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.seedGridSpacingWithWork b P).1) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork value).1) q.lo q.hi + let centers := (OAI.EditApproximation.arithmeticFlatMapWithWork build (OAI.EditApproximation.BinaryFraction.queryScalesWithWork N F a value).1).1 + OAI.EditApproximation.BinaryFraction.queryScalesAllocation N F a value + OAI.EditApproximation.BinaryFraction.naturalCeilingAllocation value + + OAI.EditApproximation.arithmeticFlatMapAllocation build allocation (OAI.EditApproximation.BinaryFraction.queryScalesWithWork N F a value).1 + + OAI.EditApproximation.queryEraseAllocation OAI.EditApproximation.queryIntervalEqualWithWork OAI.EditApproximation.queryIntervalEqualAllocation centers + +def queryOnlineKeysAllocation {n : ℕ} (N P F : ℕ) (_hP : 0 < P) + (a value : OAI.EditApproximation.BinaryFraction) (q : OAI.EditApproximation.TargetInterval n) : ℕ := + OAI.EditApproximation.BinaryFraction.queryScalesAllocation N F a value + OAI.EditApproximation.arithmeticMapAllocation (fun b => + OAI.EditApproximation.seedGridSpacingAllocation b P + OAI.EditApproximation.roundStateAllocation (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.seedGridSpacingWithWork b P).1) q + 1) + (OAI.EditApproximation.BinaryFraction.queryScalesWithWork N F a value).1 + +def representativeScaleReadAllocation {n : ℕ} (P F : ℕ) (a : OAI.EditApproximation.BinaryFraction) + (read : OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) (allocation : OAI.EditApproximation.TargetInterval n → ℕ) + (radius : List Bool) (query : OAI.EditApproximation.TargetInterval n) (e : ℕ) : ℕ := + let b := 2 ^ e + let spacing := (OAI.EditApproximation.seedGridSpacingWithWork b P).1 + let points := (OAI.EditApproximation.gridStateBoxWithWork n (OAI.EditApproximation.bitWordValue spacing) (OAI.EditApproximation.bitWordValue radius) query.lo query.hi).1 + let test := fun r => ((OAI.EditApproximation.BinaryFraction.centerEligibilityWithWork b F a (read r).1).1, + (OAI.EditApproximation.BinaryFraction.centerEligibilityWithWork b F a (read r).1).2 + (read r).2) + let selected := (OAI.EditApproximation.filterWithWork test points).1 + OAI.EditApproximation.seedGridSpacingAllocation b P + OAI.EditApproximation.gridStateBoxAllocation n (OAI.EditApproximation.bitWordValue spacing) (OAI.EditApproximation.bitWordValue radius) query.lo query.hi + + OAI.EditApproximation.filterAllocation test (fun r => OAI.EditApproximation.BinaryFraction.centerEligibilityAllocation b F a (read r).1 + allocation r) points + + OAI.EditApproximation.arithmeticMapAllocation (fun _ => 1) selected + e + 1 + +def queryWideInputsAllocation {nx ny : ℕ} (M : ℕ) (parent : OAI.EditApproximation.TargetInterval nx) (P : ℕ) + (representatives : List (ℕ × OAI.EditApproximation.TargetInterval ny)) : ℕ := + let build := fun br : ℕ × OAI.EditApproximation.TargetInterval ny => + OAI.EditApproximation.arithmeticFlatMapWithWork (fun i : Fin M => + let states := OAI.EditApproximation.wideChildGridWithWork parent br.2 br.1 P i + let labeled := OAI.EditApproximation.arithmeticMapWithWork (fun r => ((i, r), 1)) states.1 + (labeled.1, states.2 + labeled.2 + 1)) (List.finRange M) + let one := fun (br : ℕ × OAI.EditApproximation.TargetInterval ny) (i : Fin M) => + OAI.EditApproximation.wideChildGridAllocation parent br.2 br.1 P i + + OAI.EditApproximation.arithmeticMapAllocation (fun _ => 1) (OAI.EditApproximation.wideChildGridWithWork parent br.2 br.1 P i).1 + OAI.EditApproximation.arithmeticFlatMapAllocation build + (fun br => OAI.EditApproximation.arithmeticFlatMapAllocation (fun i : Fin M => + let states := OAI.EditApproximation.wideChildGridWithWork parent br.2 br.1 P i + let labeled := OAI.EditApproximation.arithmeticMapWithWork (fun r => ((i, r), 1)) states.1 + (labeled.1, states.2 + labeled.2 + 1)) (one br) (List.finRange M)) representatives + + OAI.EditApproximation.queryEraseAllocation OAI.EditApproximation.coordinateEqualWithWork OAI.EditApproximation.coordinateEqualAllocation (OAI.EditApproximation.arithmeticFlatMapWithWork build representatives).1 + M + +def queryRawHistoryInputsAllocation {nx ny : ℕ} (M : ℕ) (parent : OAI.EditApproximation.TargetInterval nx) + (P history : ℕ) (representatives : List (ℕ × OAI.EditApproximation.TargetInterval ny)) : ℕ := + let child := fun (br : ℕ × OAI.EditApproximation.TargetInterval ny) (i : Fin M) => + let states := OAI.EditApproximation.wideChildGridWithWork parent br.2 br.1 P i + let times := OAI.EditApproximation.arithmeticFlatMapWithWork (fun t => + OAI.EditApproximation.arithmeticMapWithWork (fun r => ((i, t, r), 1)) states.1) (List.range history) + (times.1, states.2 + times.2 + history + 2) + let one := fun (br : ℕ × OAI.EditApproximation.TargetInterval ny) (i : Fin M) => + OAI.EditApproximation.wideChildGridAllocation parent br.2 br.1 P i + history + + OAI.EditApproximation.arithmeticFlatMapAllocation (fun t => OAI.EditApproximation.arithmeticMapWithWork (fun r => ((i, t, r), 1)) + (OAI.EditApproximation.wideChildGridWithWork parent br.2 br.1 P i).1) + (fun _ => OAI.EditApproximation.arithmeticMapAllocation (fun _ => 1) (OAI.EditApproximation.wideChildGridWithWork parent br.2 br.1 P i).1) + (List.range history) + OAI.EditApproximation.arithmeticFlatMapAllocation (fun br => OAI.EditApproximation.arithmeticFlatMapWithWork (child br) (List.finRange M)) + (fun br => OAI.EditApproximation.arithmeticFlatMapAllocation (child br) (one br) (List.finRange M)) representatives + M + +def queryGroupRoundedStatesAllocation {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (b exponent : ℕ) (cell : ℕ × ℕ) (i : Fin M) (h : OAI.EditApproximation.BinaryFraction) : ℕ := + let theta := OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent + let spacing := (OAI.EditApproximation.BinaryFraction.roundedSpacingWithWork theta h).1 + let child := (OAI.EditApproximation.sourceChildWithWork parent i).1 + let offset := (OAI.EditApproximation.saturatingSubtractWithWork child.lo parent.lo).1 + let base := (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat cell.1) theta).1 + let position := (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork base (OAI.EditApproximation.BinaryFraction.nat b)).1 + let floor := (OAI.EditApproximation.BinaryFraction.naturalFloorWithWork position).1 + let anchor := (OAI.EditApproximation.binaryNaturalAddWithWork (OAI.EditApproximation.bitWordValue floor) (OAI.EditApproximation.bitWordValue offset)).1 + let radius := (OAI.EditApproximation.binaryNaturalMulWithWork 12 b).1 + let length := (OAI.EditApproximation.saturatingSubtractWithWork child.hi child.lo).1 + let twice := (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 2) h).1 + let gap := (OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork twice).1 + OAI.EditApproximation.BinaryFraction.roundedSpacingAllocation theta h + OAI.EditApproximation.sourceChildAllocation parent i + OAI.EditApproximation.saturatingSubtractAllocation child.lo parent.lo + + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation (OAI.EditApproximation.BinaryFraction.nat cell.1) theta + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation base (OAI.EditApproximation.BinaryFraction.nat b) + OAI.EditApproximation.BinaryFraction.naturalFloorAllocation position + + OAI.EditApproximation.binaryNaturalAddAllocation (OAI.EditApproximation.bitWordValue floor) (OAI.EditApproximation.bitWordValue offset) + OAI.EditApproximation.binaryNaturalMulAllocation 12 b + + OAI.EditApproximation.saturatingSubtractAllocation child.hi child.lo + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation (OAI.EditApproximation.BinaryFraction.nat 2) h + OAI.EditApproximation.BinaryFraction.naturalCeilingAllocation twice + + OAI.EditApproximation.queryGapStatesAllocation ny (OAI.EditApproximation.bitWordValue spacing) (OAI.EditApproximation.bitWordValue anchor) (OAI.EditApproximation.bitWordValue radius) + (OAI.EditApproximation.bitWordValue length) (OAI.EditApproximation.bitWordValue gap) + exponent + 2 + +def groupIndexAllocation {M : ℕ} (h : OAI.EditApproximation.BinaryFraction) (envelope values : Vector OAI.EditApproximation.BinaryFraction M) + (indices : List (Fin M)) : ℕ := + OAI.EditApproximation.BinaryFraction.groupTermsAllocation h envelope indices + + OAI.EditApproximation.BinaryFraction.sumListAllocation (OAI.EditApproximation.BinaryFraction.groupTermsWithWork h envelope values indices).1 + 0 + +def queryParentReadAllocation {n : ℕ} (keys : List (OAI.EditApproximation.TargetInterval n)) + (words : List OAI.EditApproximation.BinaryFraction) (r : OAI.EditApproximation.TargetInterval n) : ℕ := + OAI.EditApproximation.BinaryFraction.gatheredLookupAllocation OAI.EditApproximation.queryIntervalEqualWithWork OAI.EditApproximation.queryIntervalEqualAllocation keys words r + +def onlineLinearReadAllocation {β : Type u_1} {σ : Type u_2} (mass : β → OAI.EditApproximation.BinaryFraction) + (read : ℕ → β × σ → OAI.EditApproximation.BinaryFraction × ℕ) (footprint : ℕ → β × σ → ℕ) + (eta kappa : OAI.EditApproximation.BinaryFraction) (t : ℕ) (i : β × σ) : ℕ := + let coefficient := (OAI.EditApproximation.BinaryFraction.coefficientWithWork kappa).1 + let terms := (OAI.EditApproximation.vectorMapWithWork t fun s => OAI.EditApproximation.BinaryFraction.optimisticTermReadWithWork mass read coefficient s.val i).1 + let history := (OAI.EditApproximation.BinaryFraction.bandMassTotalWithWork terms).1 + let current := (OAI.EditApproximation.BinaryFraction.gainReadWithWork mass read t i).1 + OAI.EditApproximation.BinaryFraction.coefficientAllocation kappa + + OAI.EditApproximation.vectorMapAllocation t (fun s => OAI.EditApproximation.BinaryFraction.optimisticTermReadAllocation mass read footprint coefficient s.val i) + + OAI.EditApproximation.BinaryFraction.bandMassAllocation terms + OAI.EditApproximation.BinaryFraction.gainReadAllocation mass read footprint t i + OAI.EditApproximation.BinaryFraction.canonicalAddAllocation history current + + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation eta (OAI.EditApproximation.BinaryFraction.canonicalAddWithWork history current).1 + 0 + +def countedBandCoordinateAllocation {M n : ℕ} (mass : Vector OAI.EditApproximation.BinaryFraction M) + (total : OAI.EditApproximation.BinaryFraction) (action : Fin M → OAI.EditApproximation.TargetInterval n) (coordinate : Fin M × OAI.EditApproximation.TargetInterval n) : ℕ := + OAI.EditApproximation.coordinateEqualAllocation coordinate (coordinate.1, action coordinate.1) + + if (OAI.EditApproximation.coordinateEqualWithWork coordinate (coordinate.1, action coordinate.1)).1 then + OAI.EditApproximation.BinaryFraction.divAllocation (mass.get coordinate.1) total else 0 + +def queryInitialConeCentersAllocation {n : ℕ} (N P : ℕ) (A value : OAI.EditApproximation.BinaryFraction) + (q : OAI.EditApproximation.TargetInterval n) : ℕ := + let radius := (OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork value).1 + let active := (OAI.EditApproximation.filterWithWork (fun b => OAI.EditApproximation.BinaryFraction.initialScaleGuardWithWork (OAI.EditApproximation.bitWordValue radius) b A) (OAI.EditApproximation.dyadicScalesWithWork N).1).1 + let build := fun b => + let spacing := (OAI.EditApproximation.seedGridSpacingWithWork b P).1 + let states := OAI.EditApproximation.gridStateBoxWithWork n (OAI.EditApproximation.bitWordValue spacing) (OAI.EditApproximation.bitWordValue radius) q.lo q.hi + (states.1, (OAI.EditApproximation.seedGridSpacingWithWork b P).2 + states.2 + 1) + OAI.EditApproximation.BinaryFraction.naturalCeilingAllocation value + OAI.EditApproximation.dyadicScalesAllocation N + + OAI.EditApproximation.filterAllocation (fun b => OAI.EditApproximation.BinaryFraction.initialScaleGuardWithWork (OAI.EditApproximation.bitWordValue radius) b A) + (fun b => OAI.EditApproximation.BinaryFraction.initialScaleGuardAllocation (OAI.EditApproximation.bitWordValue radius) b A) (OAI.EditApproximation.dyadicScalesWithWork N).1 + + OAI.EditApproximation.arithmeticFlatMapAllocation build + (fun b => OAI.EditApproximation.seedGridSpacingAllocation b P + OAI.EditApproximation.gridStateBoxAllocation n + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.seedGridSpacingWithWork b P).1) (OAI.EditApproximation.bitWordValue radius) q.lo q.hi) active + +def connectionWithWork {n : ℕ} (start finish : OAI.EditApproximation.BinaryFraction) + (states : List (OAI.EditApproximation.TargetInterval n)) : OAI.EditApproximation.BinaryFraction × ℕ := + let terms := OAI.EditApproximation.BinaryFraction.connectionTermsWithWork start states finish + let result := OAI.EditApproximation.BinaryFraction.sumListWithWork terms.1 + (result.1, terms.2 + result.2 + 1) + +def envelopeVectorReadWithWork {M n : ℕ} (b : ℕ) (band : List (Fin M → OAI.EditApproximation.TargetInterval n)) + (read : Fin M → OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) : Vector OAI.EditApproximation.BinaryFraction M × ℕ := + OAI.EditApproximation.vectorMapWithWork M (OAI.EditApproximation.BinaryFraction.bandEnvelopeReadWithWork b band read) + +def bellmanActionReadWithWork {Parent : Type u_1} {Child : Type u_2} {M : ℕ} + (distance : Parent → Parent → OAI.EditApproximation.BinaryFraction × ℕ) (L : OAI.EditApproximation.BinaryFraction) + (read : Child → OAI.EditApproximation.BinaryFraction × ℕ) (query : Parent) + (action : OAI.EditApproximation.BinaryBellmanAction Parent Child M) : OAI.EditApproximation.BinaryFraction × ℕ := + let words := OAI.EditApproximation.arithmeticMapWithWork (fun i => read (action.childState i)) (List.finRange M) + let dist := distance query action.center + let spatial := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork L dist.1 + let connection := OAI.EditApproximation.BinaryFraction.canonicalAddWithWork spatial.1 action.connection + let children := OAI.EditApproximation.BinaryFraction.sumListWithWork words.1 + let result := OAI.EditApproximation.BinaryFraction.canonicalAddWithWork connection.1 children.1 + (result.1, words.2 + dist.2 + spatial.2 + connection.2 + children.2 + result.2 + 3) + +def cellCentersReadWithWork {n : ℕ} (P F b : ℕ) (a theta : OAI.EditApproximation.BinaryFraction) + (initial : OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) (cell : ℕ × ℕ) : + List (OAI.EditApproximation.TargetInterval n) × ℕ := + let spacing := OAI.EditApproximation.seedGridSpacingWithWork b P + let side := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork theta (OAI.EditApproximation.BinaryFraction.nat b) + let states := OAI.EditApproximation.BinaryFraction.cellStatesWithWork n (OAI.EditApproximation.bitWordValue spacing.1) side.1 cell + let selected := OAI.EditApproximation.filterWithWork (fun r => + let word := initial r + let tested := OAI.EditApproximation.BinaryFraction.centerEligibilityWithWork b F a word.1 + (tested.1, word.2 + tested.2)) states.1 + (selected.1, spacing.2 + side.2 + states.2 + selected.2 + 3) + +def countedBandVerticesWithWork {M n d : ℕ} (coordinates : Vector (Fin M × OAI.EditApproximation.TargetInterval n) d) + (mass : Vector OAI.EditApproximation.BinaryFraction M) (band : List (Fin M → OAI.EditApproximation.TargetInterval n)) : + List ((Fin M → OAI.EditApproximation.TargetInterval n) × Vector OAI.EditApproximation.BinaryFraction d) × ℕ := + let total := OAI.EditApproximation.BinaryFraction.bandMassTotalWithWork mass + let vertices := band.map fun action => + let vertex := OAI.EditApproximation.vectorMapWithWork d fun i => + OAI.EditApproximation.BinaryFraction.countedBandCoordinateWithWork mass total.1 action (coordinates.get i) + ((action, vertex.1), vertex.2) + (vertices.map Prod.fst, total.2 + (vertices.map Prod.snd).sum + 8 * band.length) + +def onlineIndexSetupWithWork {M n : ℕ} (H : ℕ) (band : List (Fin M → OAI.EditApproximation.TargetInterval n)) : + ℕ × ℕ := + let coordinates := OAI.EditApproximation.BinaryFraction.bandCoordinatesWithWork band + let sum := OAI.EditApproximation.binaryNaturalAddWithWork H coordinates.1.length + let offset := OAI.EditApproximation.binaryNaturalAddWithWork (OAI.EditApproximation.bitWordValue sum.1) 2 + let power := OAI.EditApproximation.bitPowerWithWork offset.1 80 + (OAI.EditApproximation.bitWordValue offset.1, coordinates.2 + sum.2 + offset.2 + power.2 + 3) + +def localRepresentativeReadWithWork {n : ℕ} (N P F : ℕ) (a : OAI.EditApproximation.BinaryFraction) + (read : OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) (query : OAI.EditApproximation.TargetInterval n) : + List (ℕ × OAI.EditApproximation.TargetInterval n) × ℕ := + let queryWord := read query + let scales := OAI.EditApproximation.BinaryFraction.queryExponentsWithWork N F a queryWord.1 + let radius := OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork queryWord.1 + let result := OAI.EditApproximation.arithmeticFlatMapWithWork + (OAI.EditApproximation.BinaryFraction.representativeScaleReadWithWork P F a read radius.1 query) scales.1 + (result.1, queryWord.2 + scales.2 + radius.2 + result.2 + 3) + +def queryGroupKeysWithWork {n : ℕ} (N F exponent : ℕ) (a value : OAI.EditApproximation.BinaryFraction) + (q : OAI.EditApproximation.TargetInterval n) : List (ℕ × (ℕ × ℕ)) × ℕ := + let scales := OAI.EditApproximation.BinaryFraction.queryScalesWithWork N F a value + let radius := OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork value + let keys := OAI.EditApproximation.arithmeticFlatMapWithWork (fun b => + let side := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) (OAI.EditApproximation.BinaryFraction.nat b) + let cells := OAI.EditApproximation.BinaryFraction.targetCellsWithWork side.1 (OAI.EditApproximation.bitWordValue radius.1) q + let labeled := OAI.EditApproximation.arithmeticMapWithWork (fun cell => ((b, cell), 1)) cells.1 + (labeled.1, side.2 + cells.2 + labeled.2 + 2)) scales.1 + (keys.1, scales.2 + radius.2 + keys.2 + exponent + 4) + +def queryMeanWithWork (count : ℕ) (words : List OAI.EditApproximation.BinaryFraction) : OAI.EditApproximation.BinaryFraction × ℕ := + let total := OAI.EditApproximation.BinaryFraction.sumListWithWork words + let result := OAI.EditApproximation.BinaryFraction.divWithWork total.1 (OAI.EditApproximation.BinaryFraction.nat count) + (result.1, total.2 + result.2 + Nat.size count + 2) + +def initialCentersReadWithWork {n : ℕ} (N P : ℕ) (A : OAI.EditApproximation.BinaryFraction) + (read : OAI.EditApproximation.TargetInterval n → List Bool × ℕ) (q : OAI.EditApproximation.TargetInterval n) : + List (OAI.EditApproximation.TargetInterval n) × ℕ := + let queryWord := read q + let Uq := OAI.EditApproximation.bitWordValue queryWord.1 + let scales := OAI.EditApproximation.dyadicScalesWithWork N + let active := OAI.EditApproximation.filterWithWork (fun b => OAI.EditApproximation.BinaryFraction.initialScaleGuardWithWork Uq b A) scales.1 + let centers := OAI.EditApproximation.arithmeticFlatMapWithWork (OAI.EditApproximation.BinaryFraction.initialGridReadWithWork P A read Uq q) active.1 + (centers.1, queryWord.2 + scales.2 + active.2 + centers.2 + 3) + +def queryInitialSeedReadWithWork {n : ℕ} (value : OAI.EditApproximation.BinaryFraction) (q : OAI.EditApproximation.TargetInterval n) + (keys : List (OAI.EditApproximation.TargetInterval n)) (words : List OAI.EditApproximation.BinaryFraction) (r : OAI.EditApproximation.TargetInterval n) : List Bool × ℕ := + let test := OAI.EditApproximation.queryIntervalEqualWithWork r q + if test.1 then + let result := OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork value + (result.1, test.2 + result.2 + 1) + else + let found := OAI.EditApproximation.BinaryFraction.queryParentReadWithWork keys words r + let result := OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork found.1 + (result.1, test.2 + found.2 + result.2 + 1) + +def queryOverrideParentReadWithWork {n : ℕ} (value : OAI.EditApproximation.BinaryFraction) (q : OAI.EditApproximation.TargetInterval n) + (keys : List (OAI.EditApproximation.TargetInterval n)) (words : List OAI.EditApproximation.BinaryFraction) (r : OAI.EditApproximation.TargetInterval n) : + OAI.EditApproximation.BinaryFraction × ℕ := + let test := OAI.EditApproximation.queryIntervalEqualWithWork r q + if test.1 then (value, test.2 + 1) + else + let found := OAI.EditApproximation.BinaryFraction.queryParentReadWithWork keys words r + (found.1, test.2 + found.2 + 1) + +def connectionAllocation {n : ℕ} (start finish : OAI.EditApproximation.BinaryFraction) + (states : List (OAI.EditApproximation.TargetInterval n)) : ℕ := + OAI.EditApproximation.BinaryFraction.connectionTermsAllocation start states finish + + OAI.EditApproximation.BinaryFraction.sumListAllocation (OAI.EditApproximation.BinaryFraction.connectionTermsWithWork start states finish).1 + 0 + +def coordinateVectorAllocation {M n : ℕ} (band : List (Fin M → OAI.EditApproximation.TargetInterval n)) : ℕ := + OAI.EditApproximation.BinaryFraction.bandCoordinatesAllocation band + (OAI.EditApproximation.BinaryFraction.bandCoordinatesWithWork band).1.length + +def maximizerAllocation {d : ℕ} (gradient : Vector OAI.EditApproximation.BinaryFraction d) + (vertices : List (Vector OAI.EditApproximation.BinaryFraction d)) : ℕ := + OAI.EditApproximation.BinaryFraction.scoredArgmaxAllocation (OAI.EditApproximation.BinaryFraction.dotWithWork gradient) + (fun v => OAI.EditApproximation.BinaryFraction.dotListAllocation gradient v (List.finRange d)) vertices + d + +def onlineIndexSetupAllocation {M n : ℕ} (H : ℕ) (band : List (Fin M → OAI.EditApproximation.TargetInterval n)) : ℕ := + let coordinates := (OAI.EditApproximation.BinaryFraction.bandCoordinatesWithWork band).1 + let sum := (OAI.EditApproximation.binaryNaturalAddWithWork H coordinates.length).1 + let offset := (OAI.EditApproximation.binaryNaturalAddWithWork (OAI.EditApproximation.bitWordValue sum) 2).1 + OAI.EditApproximation.BinaryFraction.bandCoordinatesAllocation band + OAI.EditApproximation.binaryNaturalAddAllocation H coordinates.length + + OAI.EditApproximation.binaryNaturalAddAllocation (OAI.EditApproximation.bitWordValue sum) 2 + OAI.EditApproximation.bitPowerAllocation offset 80 + +def envelopeVectorReadAllocation {M n : ℕ} (b : ℕ) (band : List (Fin M → OAI.EditApproximation.TargetInterval n)) + (read : Fin M → OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) + (footprint : Fin M → OAI.EditApproximation.TargetInterval n → ℕ) : ℕ := + OAI.EditApproximation.vectorMapAllocation M (OAI.EditApproximation.BinaryFraction.bandEnvelopeReadAllocation b band read footprint) + +def roundedBandReadAllocation {n M : ℕ} (exponent b : ℕ) (band : List (Fin M → OAI.EditApproximation.TargetInterval n)) + (hne : band ≠ []) (read : Fin M → OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) + (allocation : Fin M → OAI.EditApproximation.TargetInterval n → ℕ) : ℕ := + OAI.EditApproximation.vectorMapAllocation M fun i => + let envelope := (OAI.EditApproximation.BinaryFraction.bandEnvelopeReadWithWork b band read i).1 + let spacing := OAI.EditApproximation.bitWordValue (OAI.EditApproximation.BinaryFraction.roundedSpacingWithWork (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) envelope).1 + OAI.EditApproximation.BinaryFraction.bandEnvelopeReadAllocation b band read allocation i + + OAI.EditApproximation.BinaryFraction.roundedSpacingAllocation (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) envelope + + OAI.EditApproximation.roundStateAllocation spacing (band.head hne i) + exponent + 2 + +def queryGroupKeysAllocation {n : ℕ} (N F exponent : ℕ) (a value : OAI.EditApproximation.BinaryFraction) (q : OAI.EditApproximation.TargetInterval n) : ℕ := + let radius := (OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork value).1 + let build := fun b => + let side := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) (OAI.EditApproximation.BinaryFraction.nat b) + let cells := OAI.EditApproximation.BinaryFraction.targetCellsWithWork side.1 (OAI.EditApproximation.bitWordValue radius) q + let labeled := OAI.EditApproximation.arithmeticMapWithWork (fun cell => ((b, cell), 1)) cells.1 + (labeled.1, side.2 + cells.2 + labeled.2 + 2) + OAI.EditApproximation.BinaryFraction.queryScalesAllocation N F a value + OAI.EditApproximation.BinaryFraction.naturalCeilingAllocation value + + OAI.EditApproximation.arithmeticFlatMapAllocation build (fun b => + let side := (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) (OAI.EditApproximation.BinaryFraction.nat b)).1 + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) (OAI.EditApproximation.BinaryFraction.nat b) + OAI.EditApproximation.BinaryFraction.targetCellsAllocation side (OAI.EditApproximation.bitWordValue radius) q + + OAI.EditApproximation.arithmeticMapAllocation (fun _ => 1) (OAI.EditApproximation.BinaryFraction.targetCellsWithWork side (OAI.EditApproximation.bitWordValue radius) q).1) + (OAI.EditApproximation.BinaryFraction.queryScalesWithWork N F a value).1 + exponent + 2 + +def initialCellAllocation (n P exponent : ℕ) (key : ℕ × ℕ × ℕ) : ℕ := + OAI.EditApproximation.seedGridSpacingAllocation key.1 P + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) (OAI.EditApproximation.BinaryFraction.nat key.1) + + OAI.EditApproximation.BinaryFraction.cellStatesAllocation n (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.seedGridSpacingWithWork key.1 P).1) + (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) (OAI.EditApproximation.BinaryFraction.nat key.1)).1 key.2 + exponent + 2 + +def localRepresentativeReadAllocation {n : ℕ} (N P F : ℕ) (a : OAI.EditApproximation.BinaryFraction) + (read : OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) (allocation : OAI.EditApproximation.TargetInterval n → ℕ) + (query : OAI.EditApproximation.TargetInterval n) : ℕ := + allocation query + OAI.EditApproximation.BinaryFraction.queryExponentsAllocation N F a (read query).1 + OAI.EditApproximation.BinaryFraction.naturalCeilingAllocation (read query).1 + + OAI.EditApproximation.arithmeticFlatMapAllocation + (OAI.EditApproximation.BinaryFraction.representativeScaleReadWithWork P F a read (OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork (read query).1).1 query) + (OAI.EditApproximation.BinaryFraction.representativeScaleReadAllocation P F a read allocation (OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork (read query).1).1 query) + (OAI.EditApproximation.BinaryFraction.queryExponentsWithWork N F a (read query).1).1 + +def cellCentersReadAllocation {n : ℕ} (P F b : ℕ) (a theta : OAI.EditApproximation.BinaryFraction) + (initial : OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) (allocation : OAI.EditApproximation.TargetInterval n → ℕ) + (cell : ℕ × ℕ) : ℕ := + let spacing := (OAI.EditApproximation.seedGridSpacingWithWork b P).1 + let side := (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork theta (OAI.EditApproximation.BinaryFraction.nat b)).1 + let states := (OAI.EditApproximation.BinaryFraction.cellStatesWithWork n (OAI.EditApproximation.bitWordValue spacing) side cell).1 + let test := fun r => ((OAI.EditApproximation.BinaryFraction.centerEligibilityWithWork b F a (initial r).1).1, + (initial r).2 + (OAI.EditApproximation.BinaryFraction.centerEligibilityWithWork b F a (initial r).1).2) + OAI.EditApproximation.seedGridSpacingAllocation b P + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation theta (OAI.EditApproximation.BinaryFraction.nat b) + + OAI.EditApproximation.BinaryFraction.cellStatesAllocation n (OAI.EditApproximation.bitWordValue spacing) side cell + + OAI.EditApproximation.filterAllocation test (fun r => allocation r + OAI.EditApproximation.BinaryFraction.centerEligibilityAllocation b F a (initial r).1) states + +def selectGroupAllocation {ι : Type u_1} (members : List ι) (estimate : ι → OAI.EditApproximation.BinaryFraction × ℕ) + (allocation : ι → ℕ) : ℕ := + OAI.EditApproximation.BinaryFraction.scoredArgmaxAllocation (fun member => ((estimate member).1.neg, (estimate member).2 + 1)) allocation members + +def bellmanActionReadAllocation {Parent : Type u_1} {Child : Type u_2} {M : ℕ} + (distance : Parent → Parent → OAI.EditApproximation.BinaryFraction × ℕ) (distanceAllocation : Parent → Parent → ℕ) + (L : OAI.EditApproximation.BinaryFraction) (read : Child → OAI.EditApproximation.BinaryFraction × ℕ) (footprint : Child → ℕ) + (query : Parent) (action : OAI.EditApproximation.BinaryBellmanAction Parent Child M) : ℕ := + let words := (OAI.EditApproximation.arithmeticMapWithWork (fun i => read (action.childState i)) (List.finRange M)).1 + let dist := (distance query action.center).1 + let spatial := (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork L dist).1 + let connection := (OAI.EditApproximation.BinaryFraction.canonicalAddWithWork spatial action.connection).1 + let children := (OAI.EditApproximation.BinaryFraction.sumListWithWork words).1 + OAI.EditApproximation.arithmeticMapAllocation (fun i => footprint (action.childState i)) (List.finRange M) + + distanceAllocation query action.center + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation L dist + + OAI.EditApproximation.BinaryFraction.canonicalAddAllocation spatial action.connection + OAI.EditApproximation.BinaryFraction.sumListAllocation words + + OAI.EditApproximation.BinaryFraction.canonicalAddAllocation connection children + +def countedBandVerticesAllocation {M n d : ℕ} (coordinates : Vector (Fin M × OAI.EditApproximation.TargetInterval n) d) + (mass : Vector OAI.EditApproximation.BinaryFraction M) (band : List (Fin M → OAI.EditApproximation.TargetInterval n)) : ℕ := + OAI.EditApproximation.BinaryFraction.bandMassAllocation mass + + (band.map fun action => OAI.EditApproximation.vectorMapAllocation d fun i => + OAI.EditApproximation.BinaryFraction.countedBandCoordinateAllocation mass (OAI.EditApproximation.BinaryFraction.bandMassTotalWithWork mass).1 action (coordinates.get i)).sum + + 4 * band.length + +def queryInitialSeedReadAllocation {n : ℕ} (value : OAI.EditApproximation.BinaryFraction) (q : OAI.EditApproximation.TargetInterval n) + (keys : List (OAI.EditApproximation.TargetInterval n)) (words : List OAI.EditApproximation.BinaryFraction) (r : OAI.EditApproximation.TargetInterval n) : ℕ := + OAI.EditApproximation.queryIntervalEqualAllocation r q + + if (OAI.EditApproximation.queryIntervalEqualWithWork r q).1 then OAI.EditApproximation.BinaryFraction.naturalCeilingAllocation value + else OAI.EditApproximation.BinaryFraction.queryParentReadAllocation keys words r + OAI.EditApproximation.BinaryFraction.naturalCeilingAllocation (OAI.EditApproximation.BinaryFraction.queryParentReadWithWork keys words r).1 + +def queryOverrideParentReadAllocation {n : ℕ} (q : OAI.EditApproximation.TargetInterval n) + (keys : List (OAI.EditApproximation.TargetInterval n)) (words : List OAI.EditApproximation.BinaryFraction) (r : OAI.EditApproximation.TargetInterval n) : ℕ := + OAI.EditApproximation.queryIntervalEqualAllocation r q + + if (OAI.EditApproximation.queryIntervalEqualWithWork r q).1 then 0 else OAI.EditApproximation.BinaryFraction.queryParentReadAllocation keys words r + +def prefixReadWithWork {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) (r : OAI.EditApproximation.TargetInterval ny) + (states : Fin M → OAI.EditApproximation.TargetInterval ny) (read : Fin M → OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) + (j : ℕ) (p : OAI.EditApproximation.BinaryFraction) : OAI.EditApproximation.BinaryFraction × ℕ := + let words := OAI.EditApproximation.arithmeticMapWithWork (fun i : Fin M => + if i.val < j then read i (states i) else (OAI.EditApproximation.BinaryFraction.zero, 1)) (List.finRange M) + let finish := OAI.EditApproximation.BinaryFraction.canonicalAddWithWork (OAI.EditApproximation.BinaryFraction.nat (OAI.EditApproximation.balancedCut parent.lo (parent.hi - parent.lo) M j)) p + let connection := OAI.EditApproximation.BinaryFraction.connectionWithWork (OAI.EditApproximation.BinaryFraction.nat r.lo) finish.1 ((List.ofFn states).take j) + let total := OAI.EditApproximation.BinaryFraction.sumListWithWork words.1 + let result := OAI.EditApproximation.BinaryFraction.canonicalAddWithWork connection.1 total.1 + (result.1, words.2 + finish.2 + connection.2 + total.2 + result.2 + + Nat.size (OAI.EditApproximation.balancedCut parent.lo (parent.hi - parent.lo) M j) + Nat.size r.lo + 6 * M + 5) + +def bellmanReadWithWork {Parent : Type u_1} {Child : Type u_2} {M : ℕ} + (distance : Parent → Parent → OAI.EditApproximation.BinaryFraction × ℕ) (L fallback : OAI.EditApproximation.BinaryFraction) + (read : Child → OAI.EditApproximation.BinaryFraction × ℕ) (query : Parent) + (actions : List (OAI.EditApproximation.BinaryBellmanAction Parent Child M)) : OAI.EditApproximation.BinaryFraction × ℕ := + let scores := OAI.EditApproximation.arithmeticMapWithWork (OAI.EditApproximation.BinaryFraction.bellmanActionReadWithWork distance L read query) actions + let result := OAI.EditApproximation.BinaryFraction.minimumWithWork fallback scores.1 + (result.1, scores.2 + result.2 + 1) + +def queryWarmupInputsWithWork {nx ny : ℕ} (M : ℕ) (parent : OAI.EditApproximation.TargetInterval nx) + (N P F : ℕ) (a : OAI.EditApproximation.BinaryFraction) (initial : OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) + (q : OAI.EditApproximation.TargetInterval ny) : List (Fin M × OAI.EditApproximation.TargetInterval ny) × ℕ := + let representatives := OAI.EditApproximation.BinaryFraction.localRepresentativeReadWithWork N P F a initial q + let inputs := OAI.EditApproximation.BinaryFraction.queryWideInputsWithWork M parent P representatives.1 + (inputs.1, representatives.2 + inputs.2 + 1) + +def endpointConnectionAllocation {n M : ℕ} (r : OAI.EditApproximation.TargetInterval n) + (states : Fin M → OAI.EditApproximation.TargetInterval n) : ℕ := + OAI.EditApproximation.BinaryFraction.connectionAllocation (OAI.EditApproximation.BinaryFraction.nat r.lo) (OAI.EditApproximation.BinaryFraction.nat r.hi) (List.ofFn states) + Nat.size r.lo + Nat.size r.hi + M + +def prefixReadAllocation {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) (r : OAI.EditApproximation.TargetInterval ny) + (states : Fin M → OAI.EditApproximation.TargetInterval ny) (read : Fin M → OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) + (allocation : Fin M → OAI.EditApproximation.TargetInterval ny → ℕ) (j : ℕ) (p : OAI.EditApproximation.BinaryFraction) : ℕ := + let words := (OAI.EditApproximation.arithmeticMapWithWork (fun i : Fin M => + if i.val < j then read i (states i) else (OAI.EditApproximation.BinaryFraction.zero, 1)) (List.finRange M)).1 + let finish := (OAI.EditApproximation.BinaryFraction.canonicalAddWithWork (OAI.EditApproximation.BinaryFraction.nat (OAI.EditApproximation.balancedCut parent.lo (parent.hi - parent.lo) M j)) p).1 + OAI.EditApproximation.arithmeticMapAllocation (fun i : Fin M => if i.val < j then allocation i (states i) else 0) + (List.finRange M) + + OAI.EditApproximation.BinaryFraction.canonicalAddAllocation (OAI.EditApproximation.BinaryFraction.nat (OAI.EditApproximation.balancedCut parent.lo (parent.hi - parent.lo) M j)) p + + OAI.EditApproximation.BinaryFraction.connectionAllocation (OAI.EditApproximation.BinaryFraction.nat r.lo) finish ((List.ofFn states).take j) + OAI.EditApproximation.BinaryFraction.sumListAllocation words + + OAI.EditApproximation.BinaryFraction.canonicalAddAllocation (OAI.EditApproximation.BinaryFraction.connectionWithWork (OAI.EditApproximation.BinaryFraction.nat r.lo) finish ((List.ofFn states).take j)).1 + (OAI.EditApproximation.BinaryFraction.sumListWithWork words).1 + + Nat.size (OAI.EditApproximation.balancedCut parent.lo (parent.hi - parent.lo) M j) + Nat.size r.lo + 2 * M + +def optimizerAllocation {d : ℕ} (vertices : List (Vector OAI.EditApproximation.BinaryFraction d)) + (linear : Vector OAI.EditApproximation.BinaryFraction d) (G : ℕ) : ℕ → ℕ + | 0 => d + | j + 1 => + let previous := (OAI.EditApproximation.BinaryFraction.finiteOptimizerWithWork vertices linear G j).1 + let gradient := (OAI.EditApproximation.BinaryFraction.gradientWithWork G linear previous).1 + let selected := (OAI.EditApproximation.BinaryFraction.maximizerWithWork gradient vertices).1 + optimizerAllocation vertices linear G j + OAI.EditApproximation.BinaryFraction.gradientAllocation G linear previous + + OAI.EditApproximation.BinaryFraction.maximizerAllocation gradient vertices + OAI.EditApproximation.BinaryFraction.optimizerUpdateAllocation j previous selected + +def queryEarlierRepresentativesAllocation {n : ℕ} (N P F exponent : ℕ) (hP : 0 < P) + (a : OAI.EditApproximation.BinaryFraction) (initial : OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) + (allocation : OAI.EditApproximation.TargetInterval n → ℕ) (q : OAI.EditApproximation.TargetInterval n) : ℕ := + let groups := (OAI.EditApproximation.BinaryFraction.queryGroupKeysWithWork N F exponent a (initial q).1 q).1 + let build := fun key : ℕ × ℕ × ℕ => + let centers := OAI.EditApproximation.BinaryFraction.cellCentersReadWithWork P F key.1 a (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) initial key.2 + let labeled := OAI.EditApproximation.arithmeticMapWithWork (fun r => ((key.1, r), 1)) centers.1 + (labeled.1, centers.2 + labeled.2 + 1) + allocation q + OAI.EditApproximation.BinaryFraction.localRepresentativeReadAllocation N P F a initial allocation q + + OAI.EditApproximation.BinaryFraction.queryGroupKeysAllocation N F exponent a (initial q).1 q + + OAI.EditApproximation.arithmeticFlatMapAllocation build (fun key => + OAI.EditApproximation.BinaryFraction.cellCentersReadAllocation P F key.1 a (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) initial allocation key.2 + + OAI.EditApproximation.arithmeticMapAllocation (fun _ => 1) + (OAI.EditApproximation.BinaryFraction.cellCentersReadWithWork P F key.1 a (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) initial key.2).1) groups + + OAI.EditApproximation.BinaryFraction.queryOnlineKeysAllocation N P F hP a (initial q).1 q + + 2 * (OAI.EditApproximation.BinaryFraction.localRepresentativeReadWithWork N P F a initial q).1.length + + (OAI.EditApproximation.arithmeticFlatMapWithWork build groups).1.length + +def queryWarmupInputsAllocation {nx ny : ℕ} (M : ℕ) (parent : OAI.EditApproximation.TargetInterval nx) + (N P F : ℕ) (a : OAI.EditApproximation.BinaryFraction) + (initial : OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) (allocation : OAI.EditApproximation.TargetInterval ny → ℕ) + (q : OAI.EditApproximation.TargetInterval ny) : ℕ := + OAI.EditApproximation.BinaryFraction.localRepresentativeReadAllocation N P F a initial allocation q + + OAI.EditApproximation.BinaryFraction.queryWideInputsAllocation M parent P (OAI.EditApproximation.BinaryFraction.localRepresentativeReadWithWork N P F a initial q).1 + +def bellmanReadAllocation {Parent : Type u_1} {Child : Type u_2} {M : ℕ} + (distance : Parent → Parent → OAI.EditApproximation.BinaryFraction × ℕ) (distanceAllocation : Parent → Parent → ℕ) + (L fallback : OAI.EditApproximation.BinaryFraction) (read : Child → OAI.EditApproximation.BinaryFraction × ℕ) (footprint : Child → ℕ) + (query : Parent) (actions : List (OAI.EditApproximation.BinaryBellmanAction Parent Child M)) : ℕ := + let scores := (OAI.EditApproximation.arithmeticMapWithWork (OAI.EditApproximation.BinaryFraction.bellmanActionReadWithWork distance L read query) actions).1 + OAI.EditApproximation.arithmeticMapAllocation (OAI.EditApproximation.BinaryFraction.bellmanActionReadAllocation distance distanceAllocation L read footprint query) actions + + OAI.EditApproximation.BinaryFraction.minimumAllocation fallback scores + +def prefixMinimumReadWithWork {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) (r : OAI.EditApproximation.TargetInterval ny) + (actions : List (Fin M → OAI.EditApproximation.TargetInterval ny)) (hne : actions ≠ []) + (read : Fin M → OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) (j : ℕ) (p : OAI.EditApproximation.BinaryFraction) : + OAI.EditApproximation.BinaryFraction × ℕ := + let fallback := OAI.EditApproximation.BinaryFraction.prefixReadWithWork parent r (actions.head hne) read j p + let scores := OAI.EditApproximation.arithmeticMapWithWork (fun action => OAI.EditApproximation.BinaryFraction.prefixReadWithWork parent r action read j p) actions + let result := OAI.EditApproximation.BinaryFraction.minimumWithWork fallback.1 scores.1 + (result.1, fallback.2 + scores.2 + result.2 + 1) + +def localContinuationReadWithWork {Parent : Type u_1} {Child : Type u_2} {M : ℕ} + (distance : Parent → Parent → OAI.EditApproximation.BinaryFraction × ℕ) (L delta fallback : OAI.EditApproximation.BinaryFraction) + (old current : Child → OAI.EditApproximation.BinaryFraction × ℕ) (query : Parent) + (wide groups online : List (OAI.EditApproximation.BinaryBellmanAction Parent Child M)) : OAI.EditApproximation.BinaryFraction × ℕ := + let warm := OAI.EditApproximation.BinaryFraction.bellmanReadWithWork distance L fallback old query wide + let cone := OAI.EditApproximation.BinaryFraction.bellmanReadWithWork distance L warm.1 current query groups + let scores := OAI.EditApproximation.arithmeticMapWithWork (OAI.EditApproximation.BinaryFraction.bellmanActionReadWithWork distance L current query) online + let onlineMin := OAI.EditApproximation.BinaryFraction.onlineMinimumWithWork scores.1 + let result := OAI.EditApproximation.BinaryFraction.refinementUpdateWithWork delta cone.1 onlineMin.1 + (result.1, warm.2 + cone.2 + scores.2 + onlineMin.2 + result.2 + 3) + +def prefixMinimumReadAllocation {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) (r : OAI.EditApproximation.TargetInterval ny) + (actions : List (Fin M → OAI.EditApproximation.TargetInterval ny)) (hne : actions ≠ []) + (read : Fin M → OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) + (allocation : Fin M → OAI.EditApproximation.TargetInterval ny → ℕ) (j : ℕ) (p : OAI.EditApproximation.BinaryFraction) : ℕ := + let fallback := (OAI.EditApproximation.BinaryFraction.prefixReadWithWork parent r (actions.head hne) read j p).1 + let scores := (OAI.EditApproximation.arithmeticMapWithWork (fun action => OAI.EditApproximation.BinaryFraction.prefixReadWithWork parent r action read j p) actions).1 + OAI.EditApproximation.BinaryFraction.prefixReadAllocation parent r (actions.head hne) read allocation j p + + OAI.EditApproximation.arithmeticMapAllocation (fun action => OAI.EditApproximation.BinaryFraction.prefixReadAllocation parent r action read allocation j p) actions + + OAI.EditApproximation.BinaryFraction.minimumAllocation fallback scores + +def localContinuationReadAllocation {Parent : Type u_1} {Child : Type u_2} {M : ℕ} + (distance : Parent → Parent → OAI.EditApproximation.BinaryFraction × ℕ) (distanceAllocation : Parent → Parent → ℕ) + (L delta fallback : OAI.EditApproximation.BinaryFraction) (old current : Child → OAI.EditApproximation.BinaryFraction × ℕ) + (oldAllocation currentAllocation : Child → ℕ) (query : Parent) + (wide groups online : List (OAI.EditApproximation.BinaryBellmanAction Parent Child M)) : ℕ := + let warm := (OAI.EditApproximation.BinaryFraction.bellmanReadWithWork distance L fallback old query wide).1 + let cone := (OAI.EditApproximation.BinaryFraction.bellmanReadWithWork distance L warm current query groups).1 + let scores := (OAI.EditApproximation.arithmeticMapWithWork (OAI.EditApproximation.BinaryFraction.bellmanActionReadWithWork distance L current query) online).1 + let onlineMin := (OAI.EditApproximation.BinaryFraction.onlineMinimumWithWork scores).1 + OAI.EditApproximation.BinaryFraction.bellmanReadAllocation distance distanceAllocation L fallback old oldAllocation query wide + + OAI.EditApproximation.BinaryFraction.bellmanReadAllocation distance distanceAllocation L warm current currentAllocation query groups + + OAI.EditApproximation.arithmeticMapAllocation (OAI.EditApproximation.BinaryFraction.bellmanActionReadAllocation distance distanceAllocation L current currentAllocation query) online + + OAI.EditApproximation.BinaryFraction.onlineMinimumAllocation scores + OAI.EditApproximation.BinaryFraction.refinementUpdateAllocation delta cone onlineMin + +def endpointActionAllocation {ny M : ℕ} (center : OAI.EditApproximation.TargetInterval ny) + (states : Fin M → OAI.EditApproximation.TargetInterval ny) : ℕ := OAI.EditApproximation.BinaryFraction.endpointConnectionAllocation center states + M + 1 + +def selectionAllocation {α : Type u_1} {d : ℕ} + (vertices : List (α × Vector OAI.EditApproximation.BinaryFraction d)) (linear : Vector OAI.EditApproximation.BinaryFraction d) (G j : ℕ) : ℕ := + let iterate := (OAI.EditApproximation.BinaryFraction.finiteOptimizerWithWork (vertices.map Prod.snd) linear G j).1 + let gradient := (OAI.EditApproximation.BinaryFraction.gradientWithWork G linear iterate).1 + vertices.length + OAI.EditApproximation.BinaryFraction.optimizerAllocation (vertices.map Prod.snd) linear G j + + OAI.EditApproximation.BinaryFraction.gradientAllocation G linear iterate + + OAI.EditApproximation.BinaryFraction.scoredArgmaxAllocation (fun vertex => OAI.EditApproximation.BinaryFraction.dotWithWork gradient vertex.2) + (fun vertex => OAI.EditApproximation.BinaryFraction.dotListAllocation gradient vertex.2 (List.finRange d)) vertices + +def cutGuardReadWithWork {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) (r : OAI.EditApproximation.TargetInterval ny) + (actions : List (Fin M → OAI.EditApproximation.TargetInterval ny)) (hne : actions ≠ []) + (read : Fin M → OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) (states : Fin M → OAI.EditApproximation.TargetInterval ny) + (velocity tolerance : OAI.EditApproximation.BinaryFraction) (j : Fin M) : Bool × ℕ := + if j.val = 0 then (true, 1) else + let shift := OAI.EditApproximation.BinaryFraction.subWithWork (OAI.EditApproximation.BinaryFraction.nat (states j).lo) (OAI.EditApproximation.BinaryFraction.nat (OAI.EditApproximation.sourceChild parent j).lo) + let offset := OAI.EditApproximation.BinaryFraction.subWithWork (OAI.EditApproximation.BinaryFraction.nat r.lo) (OAI.EditApproximation.BinaryFraction.nat parent.lo) + let prediction := OAI.EditApproximation.BinaryFraction.prefixMinimumReadWithWork parent r actions hne read j.val shift.1 + let result := OAI.EditApproximation.BinaryFraction.affineErrorWithWork shift.1 offset.1 velocity prediction.1 tolerance + (result.1, shift.2 + offset.2 + prediction.2 + result.2 + + Nat.size (states j).lo + Nat.size (OAI.EditApproximation.sourceChild parent j).lo + Nat.size r.lo + Nat.size parent.lo + 5) + +def cutGuardReadAllocation {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) (r : OAI.EditApproximation.TargetInterval ny) + (actions : List (Fin M → OAI.EditApproximation.TargetInterval ny)) (hne : actions ≠ []) + (read : Fin M → OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) + (allocation : Fin M → OAI.EditApproximation.TargetInterval ny → ℕ) (states : Fin M → OAI.EditApproximation.TargetInterval ny) + (velocity tolerance : OAI.EditApproximation.BinaryFraction) (j : Fin M) : ℕ := + if j.val = 0 then 0 else + let shift := (OAI.EditApproximation.BinaryFraction.subWithWork (OAI.EditApproximation.BinaryFraction.nat (states j).lo) (OAI.EditApproximation.BinaryFraction.nat (OAI.EditApproximation.sourceChild parent j).lo)).1 + let offset := (OAI.EditApproximation.BinaryFraction.subWithWork (OAI.EditApproximation.BinaryFraction.nat r.lo) (OAI.EditApproximation.BinaryFraction.nat parent.lo)).1 + OAI.EditApproximation.BinaryFraction.subAllocation (OAI.EditApproximation.BinaryFraction.nat (states j).lo) (OAI.EditApproximation.BinaryFraction.nat (OAI.EditApproximation.sourceChild parent j).lo) + + OAI.EditApproximation.BinaryFraction.subAllocation (OAI.EditApproximation.BinaryFraction.nat r.lo) (OAI.EditApproximation.BinaryFraction.nat parent.lo) + + OAI.EditApproximation.BinaryFraction.prefixMinimumReadAllocation parent r actions hne read allocation j.val shift + + OAI.EditApproximation.BinaryFraction.affineErrorAllocation shift offset velocity + (OAI.EditApproximation.BinaryFraction.prefixMinimumReadWithWork parent r actions hne read j.val shift).1 tolerance + + Nat.size (states j).lo + Nat.size (OAI.EditApproximation.sourceChild parent j).lo + Nat.size r.lo + Nat.size parent.lo + +def bandPredicateReadAllocation {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) (r : OAI.EditApproximation.TargetInterval ny) + (b : ℕ) (tau theta velocity : OAI.EditApproximation.BinaryFraction) + (actions : List (Fin M → OAI.EditApproximation.TargetInterval ny)) (hne : actions ≠ []) + (read : Fin M → OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) + (allocation : Fin M → OAI.EditApproximation.TargetInterval ny → ℕ) (states : Fin M → OAI.EditApproximation.TargetInterval ny) : ℕ := + OAI.EditApproximation.zeroConnectionAllocation r.lo (List.ofFn states) r.hi + M + + OAI.EditApproximation.allAllocation (OAI.EditApproximation.BinaryFraction.anchorGuardAllocation parent r b states) (List.finRange M) + + OAI.EditApproximation.BinaryFraction.bandToleranceAllocation tau theta b M + + OAI.EditApproximation.allAllocation (OAI.EditApproximation.BinaryFraction.cutGuardReadAllocation parent r actions hne read allocation states velocity + (OAI.EditApproximation.BinaryFraction.bandToleranceWithWork tau theta b M).1) (List.finRange M) + + +end OAI.EditApproximation.BinaryFraction +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open Finset + +def rationalConnectionBudget {n : ℕ} (start : ℚ) : List (OAI.EditApproximation.TargetInterval n) → ℚ → ℚ + | [], finish => |start - finish| + | state :: rest, finish => |start - state.lo| + rationalConnectionBudget state.hi rest finish + +def bandChildEnvelope {ny M : ℕ} (b : ℕ) + (band : List (Fin M → OAI.EditApproximation.TargetInterval ny)) + (initial : Fin M → OAI.EditApproximation.TargetInterval ny → ℚ) (i : Fin M) : ℚ := + OAI.EditApproximation.rationalDyadicCeiling (max ((b : ℚ) / M) + (OAI.EditApproximation.rationalMaximum 0 (band.map fun action => initial i (action i)))) + +def bandEnvelopeExponent {ny M : ℕ} (b : ℕ) (band : List (Fin M → OAI.EditApproximation.TargetInterval ny)) + (initial : Fin M → OAI.EditApproximation.TargetInterval ny → ℚ) (i : Fin M) : ℤ := + Int.clog 2 (max ((b : ℚ) / M) (OAI.EditApproximation.rationalMaximum 0 (band.map fun action => initial i (action i)))) + +deriving instance DecidableEq for OAI.EditApproximation.TargetInterval + +def zeroConnectionWithWork {n : ℕ} (start : ℕ) : List (OAI.EditApproximation.TargetInterval n) → ℕ → Bool × ℕ + | [], finish => OAI.EditApproximation.naturalEqualWithWork start finish + | state :: rest, finish => + let current := OAI.EditApproximation.naturalEqualWithWork start state.lo + let tail := zeroConnectionWithWork state.hi rest finish + (current.1 && tail.1, current.2 + tail.2 + 1) + +def roundStateWithWork {n : ℕ} (spacing : ℕ) (hspacing : 0 < spacing) + (q : OAI.EditApproximation.TargetInterval n) : OAI.EditApproximation.TargetInterval n × ℕ := by + have proof_bitAdder_value_1 (a : Bool) (b : Bool) (carry : Bool) : + (OAI.EditApproximation.bitSum a b carry).toNat + 2 * (OAI.EditApproximation.bitCarry a b carry).toNat = + a.toNat + b.toNat + carry.toNat := by + cases a <;> cases b <;> cases carry <;> decide + have proof_bitAddWithWork_value_2 (left : List.{0} Bool) (right : List.{0} Bool) (carry : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitAddWithWork left right carry).1 = + OAI.EditApproximation.bitWordValue left + OAI.EditApproximation.bitWordValue right + carry.toNat := by + induction left generalizing right carry with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork] + induction right generalizing carry with + | nil => cases carry <;> simp [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue] + | cons b bs ih => + simp only [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 false b carry + simp only [Bool.toNat_false] at h + omega + | cons a as ih => + cases right with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a false carry + simp only [Bool.toNat_false] at h + omega + | cons b bs => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a b carry + omega + have proof_bitMulWithWork_value_0 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitMulWithWork left right).1 = OAI.EditApproximation.bitWordValue left * OAI.EditApproximation.bitWordValue right := by + induction left with + | nil => simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue] + | cons bit bits ih => + cases bit <;> simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue, proof_bitAddWithWork_value_2, ih] <;> ring + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_bitSubtractor_value_17 (a : Bool) (b : Bool) (borrow : Bool) : + a.toNat + 2 * (OAI.EditApproximation.bitBorrow a b borrow).toNat = + b.toNat + borrow.toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat := by + cases a <;> cases b <;> cases borrow <;> decide + have proof_bitSubtractionRippleEquation_18 (a : ℕ) (b : ℕ) (borrow : ℕ) (nextBorrow : ℕ) (difference : ℕ) (left : ℕ) (right : ℕ) (result : ℕ) (tail : ℕ) (htail : Eq.{1} (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} result right) nextBorrow) (HAdd.hAdd.{0, 0, 0} left tail)) (hbit : Eq.{1} (HAdd.hAdd.{0, 0, 0} a (HMul.hMul.{0, 0, 0} 2 nextBorrow)) + (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} b borrow) difference)) : + (difference + 2 * result) + (b + 2 * right) + borrow = + (a + 2 * left) + 2 * tail := by + omega + have proof_bitSubtractWithWork_value_19 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right borrow).1 + OAI.EditApproximation.bitWordValue right + borrow.toNat = + OAI.EditApproximation.bitWordValue left + 2 ^ max left.length right.length * + (OAI.EditApproximation.bitSubtractWithWork left right borrow).2.1.toNat := by + induction left generalizing right borrow with + | nil => + induction right generalizing borrow with + | nil => (simp [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + have h := ih (OAI.EditApproximation.bitBorrow false b borrow) + have hb := proof_bitSubtractor_value_17 false b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue, + List.length_nil, List.length_cons, Nat.zero_max, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 0 b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow false b borrow).toNat + (OAI.EditApproximation.bitDifference false b borrow).toNat 0 (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).1) + (2 ^ bs.length * (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons a as ih => + cases right with + | nil => + have h := ih [] (OAI.EditApproximation.bitBorrow a false borrow) + have hb := proof_bitSubtractor_value_17 a false borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_nil, List.length_cons, + Nat.max_zero, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat 0 borrow.toNat (OAI.EditApproximation.bitBorrow a false borrow).toNat + (OAI.EditApproximation.bitDifference a false borrow).toNat (OAI.EditApproximation.bitWordValue as) 0 + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).1) + (2 ^ as.length * (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons b bs => + have h := ih bs (OAI.EditApproximation.bitBorrow a b borrow) + have hb := proof_bitSubtractor_value_17 a b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_cons, Nat.succ_max_succ, + pow_succ] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow a b borrow).toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).1) + (2 ^ max as.length bs.length * (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_assoc, Nat.mul_left_comm] using hs + have proof_bitWordValue_lt_pow_length_20 (bits : List.{0} Bool) : OAI.EditApproximation.bitWordValue bits < 2 ^ bits.length := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitWordValue]) + | cons bit bits ih => + cases bit <;> (simp only [OAI.EditApproximation.bitWordValue, List.length_cons, pow_succ, Bool.toNat_false, Bool.toNat_true]) <;> omega + have proof_bitSubtractWithWork_length_21 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + (OAI.EditApproximation.bitSubtractWithWork left right borrow).1.length = max left.length right.length := by + induction left generalizing right borrow with + | nil => + simp only [OAI.EditApproximation.bitSubtractWithWork] + induction right generalizing borrow with + | nil => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork] + | cons b bs ih => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork, ih] + | cons a as ih => + cases right with + | nil => simp [OAI.EditApproximation.bitSubtractWithWork, ih] + | cons b bs => simp [OAI.EditApproximation.bitSubtractWithWork, ih, Nat.succ_max_succ] + have proof_bitSubtractWithWork_sub_22 (left : List.{0} Bool) (right : List.{0} Bool) (h : LE.le.{0} (OAI.EditApproximation.bitWordValue right) (OAI.EditApproximation.bitWordValue left)) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right false).1 = OAI.EditApproximation.bitWordValue left - OAI.EditApproximation.bitWordValue right := by + have hvalue := proof_bitSubtractWithWork_value_19 left right false + have hlt := proof_bitWordValue_lt_pow_length_20 (OAI.EditApproximation.bitSubtractWithWork left right false).1 + rw [proof_bitSubtractWithWork_length_21] at hlt + cases hb : (OAI.EditApproximation.bitSubtractWithWork left right false).2.1 + · simp only [hb, Bool.toNat_false, Nat.mul_zero, Nat.add_zero] at hvalue + omega + · simp only [hb, Bool.toNat_true, Bool.toNat_false, Nat.mul_one, Nat.add_zero] at hvalue + omega + have proof_bitDivModWithWork_value_23 (divisor : List.{0} Bool) (bits : List.{0} Bool) (hd : LT.lt.{0} 0 (OAI.EditApproximation.bitWordValue divisor)) : + OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).1 + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 < OAI.EditApproximation.bitWordValue divisor := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitDivModWithWork, OAI.EditApproximation.bitWordValue, hd]) + | cons bit bits ih => + let previous := OAI.EditApproximation.bitDivModWithWork divisor bits + let candidate := bit :: previous.2.1 + have hp : OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue previous.1 + + OAI.EditApproximation.bitWordValue previous.2.1 := ih.1 + have hr : OAI.EditApproximation.bitWordValue previous.2.1 < OAI.EditApproximation.bitWordValue divisor := ih.2 + have hc : OAI.EditApproximation.bitWordValue candidate < 2 * OAI.EditApproximation.bitWordValue divisor := by + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + cases bit <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega + by_cases hlt : (OAI.EditApproximation.bitCompareWithWork candidate divisor).1 = .lt + · have hv := (proof_bitCompareWithWork_lt_16 candidate divisor).1 hlt + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 = .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * + OAI.EditApproximation.bitWordValue (false :: previous.1) + OAI.EditApproximation.bitWordValue candidate ∧ OAI.EditApproximation.bitWordValue candidate < _ + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_false]) + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + nlinarith only [hp] + · exact hv + · have hv : OAI.EditApproximation.bitWordValue divisor ≤ OAI.EditApproximation.bitWordValue candidate := by + exact Nat.le_of_not_gt (fun h => hlt ((proof_bitCompareWithWork_lt_16 candidate divisor).2 h)) + have hs := proof_bitSubtractWithWork_sub_22 candidate divisor hv + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 ≠ .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (true :: previous.1) + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 < _ + rw [hs] + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_true]) + have he := Nat.sub_add_cancel hv + dsimp only [candidate, OAI.EditApproximation.bitWordValue] at he ⊢ + nlinarith only [hp, he] + · omega + have proof_binaryNaturalDivModWithWork_spec_24 (n : ℕ) (d : ℕ) (hd : LT.lt.{0} 0 d) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalDivModWithWork n d).1 = n / d ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalDivModWithWork n d).2.1 = n % d := by + have h := proof_bitDivModWithWork_value_23 d.bits n.bits (by simpa only [proof_bitWordValue_bits_15] using hd) + simp only [proof_bitWordValue_bits_15] at h + have hmod : n % d = OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork d.bits n.bits).2.1 := by + conv_lhs => rw [h.1] + simp only [Nat.add_mod, Nat.mul_mod_right, Nat.zero_add, Nat.mod_eq_of_lt h.2] + have hdiv : n / d = OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork d.bits n.bits).1 := by + conv_lhs => rw [h.1] + rw [Nat.mul_add_div hd, Nat.div_eq_of_lt h.2, Nat.add_zero] + exact ⟨hdiv.symm, hmod.symm⟩ + have proof_binaryGridRoundWithWork_value_25 (spacing : ℕ) (position : ℕ) (hspacing : LT.lt.{0} 0 spacing) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryGridRoundWithWork spacing position).1 = OAI.EditApproximation.gridRound spacing position := by + simp only [OAI.EditApproximation.binaryGridRoundWithWork, proof_bitMulWithWork_value_0, proof_bitWordValue_bits_15, + (proof_binaryNaturalDivModWithWork_spec_24 position spacing hspacing).1, OAI.EditApproximation.gridRound] + have proof_binaryIntervalRoundWithWork_value_14 {n : ℕ} (spacing : ℕ) (hspacing : LT.lt.{0} 0 spacing) (q : OAI.EditApproximation.TargetInterval n) : + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryIntervalRoundWithWork spacing q.lo q.hi).1.1, + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryIntervalRoundWithWork spacing q.lo q.hi).1.2) = + ((OAI.EditApproximation.roundInterval spacing q).lo, (OAI.EditApproximation.roundInterval spacing q).hi) := by + simp only [OAI.EditApproximation.binaryIntervalRoundWithWork, proof_binaryGridRoundWithWork_value_25 _ _ hspacing, + OAI.EditApproximation.roundInterval] + exact + let output := OAI.EditApproximation.binaryIntervalRoundWithWork spacing q.lo q.hi + let heq := proof_binaryIntervalRoundWithWork_value_14 spacing hspacing q + (⟨OAI.EditApproximation.bitWordValue output.1.1, OAI.EditApproximation.bitWordValue output.1.2, + by exact (congrArg Prod.fst heq).le.trans ((OAI.EditApproximation.roundInterval spacing q).ordered.trans + (congrArg Prod.snd heq).symm.le), + by exact (congrArg Prod.snd heq).le.trans (OAI.EditApproximation.roundInterval spacing q).valid⟩, output.2 + 1) + +def actionEqualWithWork {n M : ℕ} (a b : Fin M → OAI.EditApproximation.TargetInterval n) : Bool × ℕ := + OAI.EditApproximation.allWithWork (fun i => + let left := OAI.EditApproximation.naturalEqualWithWork (a i).lo (b i).lo + let right := OAI.EditApproximation.naturalEqualWithWork (a i).hi (b i).hi + (left.1 && right.1, left.2 + right.2 + 1)) (List.finRange M) + +def localRefinementRepresentatives {n : ℕ} (N P F : ℕ) (a : ℚ) + (initial : OAI.EditApproximation.TargetInterval n → ℚ) (q : OAI.EditApproximation.TargetInterval n) : List (ℕ × OAI.EditApproximation.TargetInterval n) := + ((OAI.EditApproximation.dyadicScales N).filter fun (b : ℕ) => decide + (initial q / (16 * F) ≤ b ∧ (b : ℚ) ≤ 8 * a * initial q)).flatMap fun b => + ((OAI.EditApproximation.localTargetStates n (OAI.EditApproximation.seedGridSpacing b P) ⌈initial q⌉₊ q).filter fun r => decide + ((b : ℚ) / (4 * a) ≤ initial r ∧ initial r ≤ 8 * F * b)).map fun r => (b, r) + +def sharedBandRationalAction {ny M : ℕ} (center : OAI.EditApproximation.TargetInterval ny) + (states : Fin M → OAI.EditApproximation.TargetInterval ny) : OAI.EditApproximation.PhysicalRationalAction M ny := + ⟨center, 0, fun i => (i, states i)⟩ + +def localGroupQueryKeys {n : ℕ} (N F exponent : ℕ) (a : ℚ) + (initial : OAI.EditApproximation.TargetInterval n → ℚ) (q : OAI.EditApproximation.TargetInterval n) : List (ℕ × (ℕ × ℕ)) := + (OAI.EditApproximation.dyadicQueryWindow N (initial q) a F).flatMap fun (b : ℕ) => + (OAI.EditApproximation.localTargetCells ((2 : ℚ) ^ (-(exponent : ℤ)) * b) ⌈initial q⌉₊ q).map fun cell => (b, cell) + +def rationalWidePrefixCost {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (r : OAI.EditApproximation.TargetInterval ny) (states : Fin M → OAI.EditApproximation.TargetInterval ny) + (child : Fin M → OAI.EditApproximation.TargetInterval ny → ℚ) (j : ℕ) (p : ℚ) : ℚ := + OAI.EditApproximation.rationalConnectionBudget r.lo ((List.ofFn states).take j) + ((OAI.EditApproximation.balancedCut parent.lo (parent.hi - parent.lo) M j : ℚ) + p) + + ∑ i, if i.val < j then child i (states i) else 0 + +def bandRoundSpacing {ny M : ℕ} (thetaExponent b : ℕ) (band : List (Fin M → OAI.EditApproximation.TargetInterval ny)) + (initial : Fin M → OAI.EditApproximation.TargetInterval ny → ℚ) (i : Fin M) : ℕ := + 2 ^ (OAI.EditApproximation.bandEnvelopeExponent b band initial i - thetaExponent).toNat + +def actionMemberWithWork {n M : ℕ} (a : Fin M → OAI.EditApproximation.TargetInterval n) : + List (Fin M → OAI.EditApproximation.TargetInterval n) → Bool × ℕ + | [] => (false, 1) + | b :: rest => + let test := OAI.EditApproximation.actionEqualWithWork a b + let tail := actionMemberWithWork a rest + (test.1 || tail.1, test.2 + tail.2 + 1) + +def wideEarlierInputCover {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) (P history : ℕ) + (representatives : List (ℕ × OAI.EditApproximation.TargetInterval ny)) : Finset (Fin M × ℕ × OAI.EditApproximation.TargetInterval ny) := + representatives.toFinset.biUnion fun br => + Finset.univ.biUnion fun i : Fin M => + (Finset.range history).biUnion fun t => + ((OAI.EditApproximation.wideChildStateList parent br.2 br.1 P i).toFinset).image fun r => (i, t, r) + +def queryEarlierRepresentatives {n : ℕ} (N P F exponent : ℕ) (a : ℚ) + (initial : OAI.EditApproximation.TargetInterval n → ℚ) (q : OAI.EditApproximation.TargetInterval n) : List (ℕ × OAI.EditApproximation.TargetInterval n) := + OAI.EditApproximation.localRefinementRepresentatives N P F a initial q ++ + (OAI.EditApproximation.localGroupQueryKeys N F exponent a initial q).flatMap (fun key => + (OAI.EditApproximation.cellRepresentativeStates n P F key.1 a initial ((2 : ℚ) ^ (-(exponent : ℤ))) key.2).map + fun r => (key.1, r)) ++ + (OAI.EditApproximation.dyadicQueryWindow N (initial q) a F).map + fun b => (b, OAI.EditApproximation.roundInterval (OAI.EditApproximation.seedGridSpacing b P) q) + +def rationalWidePrefixMinimum {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (r : OAI.EditApproximation.TargetInterval ny) (actions : List (Fin M → OAI.EditApproximation.TargetInterval ny)) (hnonempty : actions ≠ []) + (child : Fin M → OAI.EditApproximation.TargetInterval ny → ℚ) (j : ℕ) (p : ℚ) : ℚ := + OAI.EditApproximation.rationalMinimum (OAI.EditApproximation.rationalWidePrefixCost parent r (actions.head hnonempty) child j p) + (actions.map fun action => OAI.EditApproximation.rationalWidePrefixCost parent r action child j p) + +def roundedBandAction {ny M : ℕ} (thetaExponent b : ℕ) + (band : List (Fin M → OAI.EditApproximation.TargetInterval ny)) + (initial : Fin M → OAI.EditApproximation.TargetInterval ny → ℚ) (action : Fin M → OAI.EditApproximation.TargetInterval ny) : + Fin M → OAI.EditApproximation.TargetInterval ny := + fun i => OAI.EditApproximation.roundInterval (OAI.EditApproximation.bandRoundSpacing thetaExponent b band initial i) (action i) + +def queryEarlierInputCover {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (N P F exponent history : ℕ) (a : ℚ) + (initial : OAI.EditApproximation.TargetInterval ny → ℚ) (q : OAI.EditApproximation.TargetInterval ny) : + Finset (Fin M × ℕ × OAI.EditApproximation.TargetInterval ny) := + OAI.EditApproximation.wideEarlierInputCover parent P history (OAI.EditApproximation.queryEarlierRepresentatives N P F exponent a initial q) + +def canonicalRoundedBandAction {ny M : ℕ} (thetaExponent b : ℕ) + (band : List (Fin M → OAI.EditApproximation.TargetInterval ny)) (hnonempty : band ≠ []) + (initial : Fin M → OAI.EditApproximation.TargetInterval ny → ℚ) : Fin M → OAI.EditApproximation.TargetInterval ny := + OAI.EditApproximation.roundedBandAction thetaExponent b band initial (band.head hnonempty) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open Filter + +def parameterClogWithWork (n : ℕ) : ℕ × ℕ := + let result := OAI.EditApproximation.inputBitLengthWithWork (n - 1) + (result.1, result.2 + 2) + +def parameterLogWithWork (n : ℕ) : ℕ × ℕ := + let result := OAI.EditApproximation.inputBitLengthWithWork n + (result.1 - 1, result.2 + 1) + +def parameterRootSearch (n : ℕ) : ℕ → ℕ × ℕ + | 0 => (0, 1) + | k + 1 => if (k + 1) * (k + 1) ≤ n then (k + 1, 3) else + let result := parameterRootSearch n k + (result.1, result.2 + 3) + +def parameterPowerWithWork (a : ℕ) : ℕ → ℕ × ℕ + | 0 => (1, 1) + | k + 1 => let result := parameterPowerWithWork a k + (result.1 * a, result.2 + 2) + +def physicalCoarseInputStorage {M J : ℕ} (source target : List ℕ) + (entry : OAI.EditApproximation.PhysicalEntry M J target.length) : ℕ := + let interval := OAI.EditApproximation.physicalSourceInterval source.length entry.1 + OAI.EditApproximation.coarsePreparedInputStorage source target interval.lo interval.hi entry.2.lo entry.2.hi + +def computedQueryPassWithWork (N pass : ℕ) : (OAI.EditApproximation.BinaryFraction × OAI.EditApproximation.RefinementParameterWords) × ℕ := by + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + exact + let seed := OAI.EditApproximation.scheduledSeedWordWithWork N pass + let parameters := OAI.EditApproximation.refinementParameterWordsWithWork N pass (OAI.EditApproximation.inputSmallLog N).bits + (by rw [proof_bitWordValue_bits_15]; exact Nat.two_pow_pos _) + ((seed.1, parameters.1), seed.2 + parameters.2 + 2) + +def storedIntegerBits (values : List ℤ) : ℕ := + 1 + (values.map fun z => Nat.size z.natAbs + 2).sum + +def parameterSqrtWithWork (n : ℕ) : ℕ × ℕ := OAI.EditApproximation.parameterRootSearch n n + +def computedQuerySetupWithWork (N : ℕ) := + let parameters := OAI.EditApproximation.vectorMapWithWork (OAI.EditApproximation.computedSeedPassCount N + 1) + (fun i => OAI.EditApproximation.computedQueryPassWithWork N i.val) + let base := OAI.EditApproximation.refinementBaseWithWork (OAI.EditApproximation.inputSmallLog N).bits + ((parameters.1, base.1), parameters.2 + base.2 + 5) + +def integerParametersWithWork (N : ℕ) : OAI.EditApproximation.IntegerParameters × ℕ := + let first := OAI.EditApproximation.parameterClogWithWork (N + 2) + let heightExponent := OAI.EditApproximation.parameterClogWithWork first.1 + let height := OAI.EditApproximation.parameterPowerWithWork 2 heightExponent.1 + let smallExponent := OAI.EditApproximation.parameterClogWithWork (max 1 heightExponent.1) + let small := OAI.EditApproximation.parameterPowerWithWork 2 smallExponent.1 + let logarithm := OAI.EditApproximation.parameterLogWithWork small.1 + let firstRoot := OAI.EditApproximation.parameterSqrtWithWork logarithm.1 + let secondRoot := OAI.EditApproximation.parameterSqrtWithWork firstRoot.1 + let branching := OAI.EditApproximation.parameterPowerWithWork 2 (heightExponent.1 / 20) + let coarseBranching := OAI.EditApproximation.parameterPowerWithWork height.1 secondRoot.1 + let factor := OAI.EditApproximation.parameterPowerWithWork height.1 (secondRoot.1 + 4) + let grid := OAI.EditApproximation.parameterPowerWithWork height.1 (secondRoot.1 + 20) + let rounds := OAI.EditApproximation.parameterPowerWithWork 2 ((3 * heightExponent.1 + 3) / 4) + let spacingDenominator := OAI.EditApproximation.parameterPowerWithWork small.1 2 + ({ H := height.1, ell := small.1, p := secondRoot.1, B := coarseBranching.1, + initialFactor := factor.1, M := branching.1, P := grid.1, + T := rounds.1, S := height.1 / spacingDenominator.1 }, + first.2 + heightExponent.2 + height.2 + smallExponent.2 + small.2 + logarithm.2 + + firstRoot.2 + secondRoot.2 + branching.2 + coarseBranching.2 + factor.2 + grid.2 + + rounds.2 + spacingDenominator.2 + 15) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation + + +structure PhysicalTableRequest (M J ny : ℕ) where + pass : ℕ + copy : ℕ + node : OAI.EditApproximation.PhysicalNode M J + index : ℕ + state : OAI.EditApproximation.TargetInterval ny + +deriving DecidableEq + +def rawRefinementCenters {n : ℕ} (N P F : ℕ) (a value : ℚ) (q : OAI.EditApproximation.TargetInterval n) : + List (OAI.EditApproximation.TargetInterval n) := + ((OAI.EditApproximation.dyadicQueryWindow N value a F).flatMap fun b => + OAI.EditApproximation.localTargetStates n (OAI.EditApproximation.seedGridSpacing b P) ⌈value⌉₊ q).eraseDups + +def wideWarmupInputs {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) (P : ℕ) + (representatives : List (ℕ × OAI.EditApproximation.TargetInterval ny)) : List (Fin M × OAI.EditApproximation.TargetInterval ny) := + (representatives.flatMap fun br => (List.finRange M).flatMap fun i => + (OAI.EditApproximation.wideChildStateList parent br.2 br.1 P i).map fun r => (i, r)).eraseDups + +def queryMeanRead {ι : Type u_1} (count : ℕ) (reader : Fin count → OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) : + OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction := + .charge (count + 1) (OAI.EditApproximation.BitQuery.collect reader (List.ofFn fun i : Fin count => i) + (fun words => OAI.EditApproximation.BitQuery.compute (OAI.EditApproximation.BinaryFraction.queryMeanWithWork count words))) + +def physicalNodeCodeWithWork {M J : ℕ} (node : OAI.EditApproximation.PhysicalNode M J) : ℕ × ℕ := + let path := OAI.EditApproximation.treeLayerCodeWithWork M node.1.val node.2 + let power := OAI.EditApproximation.parameterPowerWithWork M J + (path.1 + power.1 * node.1.val, path.2 + power.2 + 3) + +def rationalParametersWithWork (ell : ℕ) : OAI.EditApproximation.RationalParameters × ℕ := + let fourth := OAI.EditApproximation.parameterPowerWithWork ell 4 + let fifth := OAI.EditApproximation.parameterPowerWithWork ell 5 + let tenth := OAI.EditApproximation.parameterPowerWithWork ell 10 + let twentieth := OAI.EditApproximation.parameterPowerWithWork ell 20 + let fortieth := OAI.EditApproximation.parameterPowerWithWork ell 40 + ({ F := ell, initialSlope := 32 * ell, coneSlope := 128 * ell, + delta := 1 / (tenth.1 : ℚ), kappa := 1 / (fourth.1 : ℚ), tau := 1 / (fourth.1 : ℚ), + theta := 1 / (fortieth.1 : ℚ), gamma := 1 / (twentieth.1 : ℚ), eta := fifth.1 }, + fourth.2 + fifth.2 + tenth.2 + twentieth.2 + fortieth.2 + 20) + +def onlineMassWithWork (M P H : ℕ) : ℕ × ℕ := + let width := 40 * P + 2 + let square := OAI.EditApproximation.parameterPowerWithWork width 2 + let dimension := H + M * square.1 + 2 + let rounds := OAI.EditApproximation.parameterPowerWithWork dimension 80 + (rounds.1 * (rounds.1 + 1) / 2, square.2 + rounds.2 + 9) + +def refinementInitialSupport {n : ℕ} (N P F exponent : ℕ) (a value : ℚ) + (q : OAI.EditApproximation.TargetInterval n) : List (OAI.EditApproximation.TargetInterval n) := + q :: (OAI.EditApproximation.rawRefinementCenters N P F a value q ++ + (OAI.EditApproximation.localGroupQueryKeys N F exponent a (fun _ => value) q).flatMap (fun key => + OAI.EditApproximation.cellTargetStates n (OAI.EditApproximation.seedGridSpacing key.1 P) + ((2 : ℚ) ^ (-(exponent : ℤ)) * key.1) key.2) ++ + (OAI.EditApproximation.dyadicQueryWindow N value a F).map (fun b => OAI.EditApproximation.roundInterval (OAI.EditApproximation.seedGridSpacing b P) q)) + +def refinementBandInputList {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (N P F exponent : ℕ) (a : ℚ) (initial : OAI.EditApproximation.TargetInterval ny → ℚ) (q : OAI.EditApproximation.TargetInterval ny) : + List (Fin M × OAI.EditApproximation.TargetInterval ny) := + OAI.EditApproximation.wideWarmupInputs parent P (OAI.EditApproximation.queryEarlierRepresentatives N P F exponent a initial q) + +def previousPassRequest {M J ny : ℕ} (T S copy : ℕ) + (parent : OAI.EditApproximation.PhysicalTableRequest M J ny) (state : OAI.EditApproximation.TargetInterval ny) : OAI.EditApproximation.PhysicalTableRequest M J ny := + ⟨parent.pass - 1, copy, parent.node, T + S, state⟩ + +def physicalEntryCodeWithWork {M J n : ℕ} (entry : OAI.EditApproximation.PhysicalEntry M J n) : ℕ × ℕ := + let node := OAI.EditApproximation.physicalNodeCodeWithWork entry.1 + let width := n + 1 + (entry.2.lo + width * entry.2.hi + width * width * node.1, node.2 + 8) + +def queryPhysicalBoundedWithWork {M J n : ℕ} (passes copies T S : ℕ) + (request : OAI.EditApproximation.PhysicalTableRequest M J n) : Bool × ℕ := + let pass := OAI.EditApproximation.binaryNaturalCompareWithWork request.pass passes + let copy := OAI.EditApproximation.binaryNaturalCompareWithWork request.copy copies + let cap := OAI.EditApproximation.binaryNaturalAddWithWork T S + let index := OAI.EditApproximation.wordLEWithWork request.index.bits cap.1 + (decide (pass.1 = .lt) && decide (copy.1 = .lt) && index.1, + pass.2 + copy.2 + cap.2 + index.2 + 4) + +def globalParameterWork (N : ℕ) : ℕ := + (OAI.EditApproximation.integerParametersWithWork N).2 + (OAI.EditApproximation.rationalParametersWithWork (OAI.EditApproximation.inputSmallLog N)).2 + + (OAI.EditApproximation.onlineMassWithWork (OAI.EditApproximation.integerParameters N).M (OAI.EditApproximation.integerParameters N).P (OAI.EditApproximation.inputHeight N)).2 + +def physicalLargeInputWithWork (N : ℕ) (epsilon : OAI.EditApproximation.BinaryFraction) : Bool × ℕ := + let inspected := OAI.EditApproximation.inspectAccuracyWithWork (OAI.EditApproximation.inputHeight N) epsilon + if inspected.1.isSome = true then + let product := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat (OAI.EditApproximation.inputSmallLog N)) epsilon + let accuracy := OAI.EditApproximation.BinaryFraction.ltWithWork product.1 (OAI.EditApproximation.BinaryFraction.nat 10) + let threshold := OAI.EditApproximation.binaryNaturalCompareWithWork (OAI.EditApproximation.inputSmallLog N) (2 ^ 1000) + let mass := OAI.EditApproximation.onlineMassWithWork (OAI.EditApproximation.integerParameters N).M (OAI.EditApproximation.integerParameters N).P (OAI.EditApproximation.inputHeight N) + let width := OAI.EditApproximation.inputBitLengthWithWork mass.1 + let capacity := OAI.EditApproximation.binaryNaturalCompareWithWork (OAI.EditApproximation.inputHeight N) width.1 + (decide (threshold.1 ≠ .lt ∧ accuracy.1 ≠ true ∧ capacity.1 ≠ .lt), + inspected.2 + product.2 + accuracy.2 + threshold.2 + mass.2 + width.2 + capacity.2 + 10) + else (false, inspected.2 + 1) + +def physicalTableCodeAllocation {M J n : ℕ} (request : OAI.EditApproximation.PhysicalTableRequest M J n) : ℕ := + 2 * request.node.1.val + 2 * J + 20 + +def queryPhysicalBoundedAllocation {M J n : ℕ} (passes copies T S : ℕ) + (request : OAI.EditApproximation.PhysicalTableRequest M J n) : ℕ := + request.pass.bits.length + passes.bits.length + request.copy.bits.length + copies.bits.length + + OAI.EditApproximation.binaryNaturalAddAllocation T S + OAI.EditApproximation.naturalWordLEAllocation request.index.bits (OAI.EditApproximation.binaryNaturalAddWithWork T S).1 + +def physicalTableCodeWithWork {M J n : ℕ} (copies T S : ℕ) + (request : OAI.EditApproximation.PhysicalTableRequest M J n) : ℕ × ℕ := + let entry := OAI.EditApproximation.physicalEntryCodeWithWork (request.node, request.state) + let power := OAI.EditApproximation.parameterPowerWithWork M J + let capacity := (n + 1) * (n + 1) * (power.1 * (J + 1)) + (request.index + (T + S + 1) * (request.copy + copies * (entry.1 + capacity * request.pass)), + entry.2 + power.2 + 15) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.PhysicalTableRequest +variable {M J ny : ℕ} + +def remainingDepth (request : OAI.EditApproximation.PhysicalTableRequest M J ny) : ℕ := + J - request.node.1.val + +def rank (T S : ℕ) (request : OAI.EditApproximation.PhysicalTableRequest M J ny) : ℕ := + request.pass * (T + S + 1) + request.index + +def Bounded (passes copies T S : ℕ) (request : OAI.EditApproximation.PhysicalTableRequest M J ny) : Prop := + request.pass < passes ∧ request.copy < copies ∧ request.index ≤ T + S + +def warmup (pass copy : ℕ) (node : OAI.EditApproximation.PhysicalNode M J) (j : ℕ) (state : OAI.EditApproximation.TargetInterval ny) : + OAI.EditApproximation.PhysicalTableRequest M J ny := + ⟨pass, copy, node, j, state⟩ + +def refinement (pass copy : ℕ) (node : OAI.EditApproximation.PhysicalNode M J) (T t : ℕ) (state : OAI.EditApproximation.TargetInterval ny) : + OAI.EditApproximation.PhysicalTableRequest M J ny := + ⟨pass, copy, node, T + t, state⟩ + +def sameIndexChild (request : OAI.EditApproximation.PhysicalTableRequest M J ny) + (hbelow : request.node.1.val < J) (i : Fin M) (state : OAI.EditApproximation.TargetInterval ny) : + OAI.EditApproximation.PhysicalTableRequest M J ny := + { request with node := OAI.EditApproximation.physicalChild request.node hbelow i, state := state } + +def combinedRank (T S : ℕ) (request : OAI.EditApproximation.PhysicalTableRequest M J ny) : ℕ := + request.remainingDepth + request.rank T S + + +end OAI.EditApproximation.PhysicalTableRequest +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation + + +def physicalWarmupChildQuery {M J ny : ℕ} (pass copy T S t : ℕ) + (node : OAI.EditApproximation.PhysicalNode M J) (hbelow : node.1.val < J) (q : OAI.EditApproximation.TargetInterval ny) + (input : Fin M × OAI.EditApproximation.TargetInterval ny) : + OAI.EditApproximation.FiniteQuery {child : OAI.EditApproximation.PhysicalTableRequest M J ny // + child.combinedRank T S < (OAI.EditApproximation.PhysicalTableRequest.warmup pass copy node (t + 1) q).combinedRank T S} := by + have proof_combinedRank_lt_of_progress_80 {M : ℕ} {J : ℕ} {ny : ℕ} (T : ℕ) (S : ℕ) (first : OAI.EditApproximation.PhysicalTableRequest M J ny) (second : OAI.EditApproximation.PhysicalTableRequest M J ny) (hprogress : LT.lt.{0} second.remainingDepth first.remainingDepth ∧ + LE.le.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first) ∨ + LE.le.{0} second.remainingDepth first.remainingDepth ∧ + LT.lt.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first)) : + OAI.EditApproximation.PhysicalTableRequest.combinedRank T S second < OAI.EditApproximation.PhysicalTableRequest.combinedRank T S first := by + unfold OAI.EditApproximation.PhysicalTableRequest.combinedRank + rcases hprogress with h | h + · exact Nat.add_lt_add_of_lt_of_le h.1 h.2 + · exact Nat.add_lt_add_of_le_of_lt h.1 h.2 + have proof_warmup_previous_child_progress_81 {M : ℕ} {J : ℕ} {ny : ℕ} (pass : ℕ) (copy : ℕ) (T : ℕ) (S : ℕ) (j : ℕ) (node : OAI.EditApproximation.PhysicalNode M J) (hbelow : LT.lt.{0} (↑(Sigma.fst.{0, 0} node)) J) (i : Fin M) (state : OAI.EditApproximation.TargetInterval ny) (previousState : OAI.EditApproximation.TargetInterval ny) (hj : LT.lt.{0} 0 j) : + (OAI.EditApproximation.PhysicalTableRequest.warmup pass copy (OAI.EditApproximation.physicalChild node hbelow i) (j - 1) previousState).remainingDepth < + (OAI.EditApproximation.PhysicalTableRequest.warmup pass copy node j state).remainingDepth ∧ + OAI.EditApproximation.PhysicalTableRequest.rank T S (OAI.EditApproximation.PhysicalTableRequest.warmup pass copy (OAI.EditApproximation.physicalChild node hbelow i) (j - 1) previousState) < + OAI.EditApproximation.PhysicalTableRequest.rank T S (OAI.EditApproximation.PhysicalTableRequest.warmup pass copy node j state) := by + constructor + · unfold OAI.EditApproximation.PhysicalTableRequest.remainingDepth OAI.EditApproximation.PhysicalTableRequest.warmup OAI.EditApproximation.physicalChild + dsimp only + omega + · dsimp only [OAI.EditApproximation.PhysicalTableRequest.rank, OAI.EditApproximation.PhysicalTableRequest.warmup] + omega + have proof_combinedRank_warmup_child_79 {M : ℕ} {J : ℕ} {ny : ℕ} (pass : ℕ) (copy : ℕ) (T : ℕ) (S : ℕ) (j : ℕ) (node : OAI.EditApproximation.PhysicalNode M J) (hbelow : LT.lt.{0} (↑(Sigma.fst.{0, 0} node)) J) (i : Fin M) (state : OAI.EditApproximation.TargetInterval ny) (previousState : OAI.EditApproximation.TargetInterval ny) (hj : LT.lt.{0} 0 j) : + OAI.EditApproximation.PhysicalTableRequest.combinedRank T S (OAI.EditApproximation.PhysicalTableRequest.warmup pass copy (OAI.EditApproximation.physicalChild node hbelow i) (j - 1) previousState) < + OAI.EditApproximation.PhysicalTableRequest.combinedRank T S (OAI.EditApproximation.PhysicalTableRequest.warmup pass copy node j state) := + proof_combinedRank_lt_of_progress_80 T S _ _ (Or.inr + ⟨(proof_warmup_previous_child_progress_81 pass copy T S j node hbelow i state previousState hj).1.le, + (proof_warmup_previous_child_progress_81 pass copy T S j node hbelow i state previousState hj).2⟩) + exact + .read ⟨OAI.EditApproximation.PhysicalTableRequest.warmup pass copy (OAI.EditApproximation.physicalChild node hbelow input.1) t input.2, + by simpa only [Nat.add_sub_cancel] using + proof_combinedRank_warmup_child_79 pass copy T S (t + 1) + node hbelow input.1 q input.2 (Nat.zero_lt_succ t)⟩ .done + +def physicalRefinementCurrentQuery {M J ny : ℕ} (pass copy T S t : ℕ) + (node : OAI.EditApproximation.PhysicalNode M J) (hbelow : node.1.val < J) (q : OAI.EditApproximation.TargetInterval ny) + (input : Fin M × OAI.EditApproximation.TargetInterval ny) : + OAI.EditApproximation.FiniteQuery {child : OAI.EditApproximation.PhysicalTableRequest M J ny // + child.combinedRank T S < (OAI.EditApproximation.PhysicalTableRequest.refinement pass copy node T t q).combinedRank T S} := by + have proof_combinedRank_lt_of_progress_80 {M : ℕ} {J : ℕ} {ny : ℕ} (T : ℕ) (S : ℕ) (first : OAI.EditApproximation.PhysicalTableRequest M J ny) (second : OAI.EditApproximation.PhysicalTableRequest M J ny) (hprogress : LT.lt.{0} second.remainingDepth first.remainingDepth ∧ + LE.le.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first) ∨ + LE.le.{0} second.remainingDepth first.remainingDepth ∧ + LT.lt.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first)) : + OAI.EditApproximation.PhysicalTableRequest.combinedRank T S second < OAI.EditApproximation.PhysicalTableRequest.combinedRank T S first := by + unfold OAI.EditApproximation.PhysicalTableRequest.combinedRank + rcases hprogress with h | h + · exact Nat.add_lt_add_of_lt_of_le h.1 h.2 + · exact Nat.add_lt_add_of_le_of_lt h.1 h.2 + have proof_sameIndexChild_progress_95 {M : ℕ} {J : ℕ} {ny : ℕ} (T : ℕ) (S : ℕ) (request : OAI.EditApproximation.PhysicalTableRequest M J ny) (hbelow : LT.lt.{0} (↑(Sigma.fst.{0, 0} request.node)) J) (i : Fin M) (state : OAI.EditApproximation.TargetInterval ny) : + (OAI.EditApproximation.PhysicalTableRequest.sameIndexChild request hbelow i state).remainingDepth < request.remainingDepth ∧ + OAI.EditApproximation.PhysicalTableRequest.rank T S (OAI.EditApproximation.PhysicalTableRequest.sameIndexChild request hbelow i state) ≤ OAI.EditApproximation.PhysicalTableRequest.rank T S request := by + constructor + · unfold OAI.EditApproximation.PhysicalTableRequest.remainingDepth OAI.EditApproximation.PhysicalTableRequest.sameIndexChild OAI.EditApproximation.physicalChild + dsimp only + omega + · exact le_rfl + have proof_combinedRank_sameIndexChild_94 {M : ℕ} {J : ℕ} {ny : ℕ} (T : ℕ) (S : ℕ) (request : OAI.EditApproximation.PhysicalTableRequest M J ny) (hbelow : LT.lt.{0} (↑(Sigma.fst.{0, 0} request.node)) J) (i : Fin M) (state : OAI.EditApproximation.TargetInterval ny) : + OAI.EditApproximation.PhysicalTableRequest.combinedRank T S (OAI.EditApproximation.PhysicalTableRequest.sameIndexChild request hbelow i state) < OAI.EditApproximation.PhysicalTableRequest.combinedRank T S request := + proof_combinedRank_lt_of_progress_80 T S request _ (Or.inl (proof_sameIndexChild_progress_95 T S request hbelow i state)) + exact + .read ⟨OAI.EditApproximation.PhysicalTableRequest.refinement pass copy (OAI.EditApproximation.physicalChild node hbelow input.1) T t input.2, + proof_combinedRank_sameIndexChild_94 T S + (OAI.EditApproximation.PhysicalTableRequest.refinement pass copy node T t q) hbelow input.1 input.2⟩ .done + +def physicalRefinementEarlierQuery {M J ny : ℕ} (pass copy T S t : ℕ) + (node : OAI.EditApproximation.PhysicalNode M J) (hbelow : node.1.val < J) (q : OAI.EditApproximation.TargetInterval ny) + (input : Fin M × ℕ × OAI.EditApproximation.TargetInterval ny) : + OAI.EditApproximation.FiniteQuery {child : OAI.EditApproximation.PhysicalTableRequest M J ny // + child.combinedRank T S < (OAI.EditApproximation.PhysicalTableRequest.refinement pass copy node T t q).combinedRank T S} := by + have proof_combinedRank_lt_of_progress_80 {M : ℕ} {J : ℕ} {ny : ℕ} (T : ℕ) (S : ℕ) (first : OAI.EditApproximation.PhysicalTableRequest M J ny) (second : OAI.EditApproximation.PhysicalTableRequest M J ny) (hprogress : LT.lt.{0} second.remainingDepth first.remainingDepth ∧ + LE.le.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first) ∨ + LE.le.{0} second.remainingDepth first.remainingDepth ∧ + LT.lt.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first)) : + OAI.EditApproximation.PhysicalTableRequest.combinedRank T S second < OAI.EditApproximation.PhysicalTableRequest.combinedRank T S first := by + unfold OAI.EditApproximation.PhysicalTableRequest.combinedRank + rcases hprogress with h | h + · exact Nat.add_lt_add_of_lt_of_le h.1 h.2 + · exact Nat.add_lt_add_of_le_of_lt h.1 h.2 + have proof_refinement_history_child_progress_96 {M : ℕ} {J : ℕ} {ny : ℕ} (pass : ℕ) (copy : ℕ) (T : ℕ) (S : ℕ) (t : ℕ) (s : ℕ) (node : OAI.EditApproximation.PhysicalNode M J) (hbelow : LT.lt.{0} (↑(Sigma.fst.{0, 0} node)) J) (i : Fin M) (state : OAI.EditApproximation.TargetInterval ny) (previousState : OAI.EditApproximation.TargetInterval ny) (hs : LT.lt.{0} s t) : + (OAI.EditApproximation.PhysicalTableRequest.refinement pass copy (OAI.EditApproximation.physicalChild node hbelow i) T s previousState).remainingDepth < + (OAI.EditApproximation.PhysicalTableRequest.refinement pass copy node T t state).remainingDepth ∧ + OAI.EditApproximation.PhysicalTableRequest.rank T S (OAI.EditApproximation.PhysicalTableRequest.refinement pass copy (OAI.EditApproximation.physicalChild node hbelow i) T s previousState) < + OAI.EditApproximation.PhysicalTableRequest.rank T S (OAI.EditApproximation.PhysicalTableRequest.refinement pass copy node T t state) := by + constructor + · unfold OAI.EditApproximation.PhysicalTableRequest.remainingDepth OAI.EditApproximation.PhysicalTableRequest.refinement OAI.EditApproximation.physicalChild + dsimp only + omega + · dsimp only [OAI.EditApproximation.PhysicalTableRequest.rank, OAI.EditApproximation.PhysicalTableRequest.refinement] + omega + exact + if hs : input.2.1 < t then + .read ⟨OAI.EditApproximation.PhysicalTableRequest.refinement pass copy (OAI.EditApproximation.physicalChild node hbelow input.1) T input.2.1 input.2.2, + proof_combinedRank_lt_of_progress_80 T S _ _ (Or.inr + ⟨(proof_refinement_history_child_progress_96 pass copy T S t input.2.1 + node hbelow input.1 q input.2.2 hs).1.le, + (proof_refinement_history_child_progress_96 pass copy T S t input.2.1 + node hbelow input.1 q input.2.2 hs).2⟩)⟩ .done + else .done 0 + +def physicalRefinementWarmupRead {M J ny : ℕ} (pass copy T S t : ℕ) (ht : 0 < t) + (node : OAI.EditApproximation.PhysicalNode M J) (q : OAI.EditApproximation.TargetInterval ny) + (otherNode : OAI.EditApproximation.PhysicalNode M J) (hnode : node.1.val ≤ otherNode.1.val) + (j : ℕ) (hj : j ≤ T) (r : OAI.EditApproximation.TargetInterval ny) : + OAI.EditApproximation.FiniteQuery {child : OAI.EditApproximation.PhysicalTableRequest M J ny // + child.combinedRank T S < (OAI.EditApproximation.PhysicalTableRequest.refinement pass copy node T t q).combinedRank T S} := by + have proof_combinedRank_lt_of_progress_80 {M : ℕ} {J : ℕ} {ny : ℕ} (T : ℕ) (S : ℕ) (first : OAI.EditApproximation.PhysicalTableRequest M J ny) (second : OAI.EditApproximation.PhysicalTableRequest M J ny) (hprogress : LT.lt.{0} second.remainingDepth first.remainingDepth ∧ + LE.le.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first) ∨ + LE.le.{0} second.remainingDepth first.remainingDepth ∧ + LT.lt.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first)) : + OAI.EditApproximation.PhysicalTableRequest.combinedRank T S second < OAI.EditApproximation.PhysicalTableRequest.combinedRank T S first := by + unfold OAI.EditApproximation.PhysicalTableRequest.combinedRank + rcases hprogress with h | h + · exact Nat.add_lt_add_of_lt_of_le h.1 h.2 + · exact Nat.add_lt_add_of_le_of_lt h.1 h.2 + exact + .read ⟨OAI.EditApproximation.PhysicalTableRequest.warmup pass copy otherNode j r, by + apply proof_combinedRank_lt_of_progress_80 T S _ _ + apply Or.inr + constructor + · exact Nat.sub_le_sub_left hnode J + · change pass * (T + S + 1) + j < pass * (T + S + 1) + (T + t) + omega⟩ .done + +def previousPassRead {M J ny : ℕ} (T S : ℕ) + (parent : OAI.EditApproximation.PhysicalTableRequest M J ny) (hpass : 0 < parent.pass) + (state : OAI.EditApproximation.TargetInterval ny) (copy : ℕ) : + OAI.EditApproximation.FiniteQuery {child : OAI.EditApproximation.PhysicalTableRequest M J ny // + child.combinedRank T S < parent.combinedRank T S} := by + have proof_combinedRank_lt_of_progress_80 {M : ℕ} {J : ℕ} {ny : ℕ} (T : ℕ) (S : ℕ) (first : OAI.EditApproximation.PhysicalTableRequest M J ny) (second : OAI.EditApproximation.PhysicalTableRequest M J ny) (hprogress : LT.lt.{0} second.remainingDepth first.remainingDepth ∧ + LE.le.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first) ∨ + LE.le.{0} second.remainingDepth first.remainingDepth ∧ + LT.lt.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first)) : + OAI.EditApproximation.PhysicalTableRequest.combinedRank T S second < OAI.EditApproximation.PhysicalTableRequest.combinedRank T S first := by + unfold OAI.EditApproximation.PhysicalTableRequest.combinedRank + rcases hprogress with h | h + · exact Nat.add_lt_add_of_lt_of_le h.1 h.2 + · exact Nat.add_lt_add_of_le_of_lt h.1 h.2 + have proof_rank_lt_previous_pass_98 {M : ℕ} {J : ℕ} {ny : ℕ} (T : ℕ) (S : ℕ) (first : OAI.EditApproximation.PhysicalTableRequest M J ny) (second : OAI.EditApproximation.PhysicalTableRequest M J ny) (hpass : LT.lt.{0} second.pass first.pass) (hindex : LE.le.{0} second.index (HAdd.hAdd.{0, 0, 0} T S)) : + OAI.EditApproximation.PhysicalTableRequest.rank T S second < OAI.EditApproximation.PhysicalTableRequest.rank T S first := by + have hblock : second.pass * (T + S + 1) + second.index < + (second.pass + 1) * (T + S + 1) := by + nlinarith only [hindex] + have hnext := Nat.mul_le_mul_right (T + S + 1) (Nat.succ_le_of_lt hpass) + exact hblock.trans_le (hnext.trans (Nat.le_add_right _ _)) + have proof_previousPassRequest_progress_97 {M : ℕ} {J : ℕ} {ny : ℕ} (T : ℕ) (S : ℕ) (copy : ℕ) (parent : OAI.EditApproximation.PhysicalTableRequest M J ny) (hpass : LT.lt.{0} 0 parent.pass) (state : OAI.EditApproximation.TargetInterval ny) : + (OAI.EditApproximation.previousPassRequest T S copy parent state).remainingDepth = parent.remainingDepth ∧ + (OAI.EditApproximation.previousPassRequest T S copy parent state).rank T S < parent.rank T S := by + refine ⟨rfl, ?_⟩ + exact proof_rank_lt_previous_pass_98 T S parent _ (by + change parent.pass - 1 < parent.pass + omega) le_rfl + exact + .read ⟨OAI.EditApproximation.previousPassRequest T S copy parent state, + proof_combinedRank_lt_of_progress_80 T S parent _ (Or.inr + ⟨(proof_previousPassRequest_progress_97 T S copy parent hpass state).1.le, + (proof_previousPassRequest_progress_97 T S copy parent hpass state).2⟩)⟩ .done + +abbrev ChargedPhysicalRequest (M J ny passes copies T S : ℕ) := + Sum (OAI.EditApproximation.PhysicalEntry M J ny) + {request : OAI.EditApproximation.PhysicalTableRequest M J ny // request.Bounded passes copies T S} + +def chargedPreviousPass {M J ny passes copies T S : ℕ} + (parent : {r : OAI.EditApproximation.PhysicalTableRequest M J ny // r.Bounded passes copies T S}) + (state : OAI.EditApproximation.TargetInterval ny) (copy : Fin copies) : + {r : OAI.EditApproximation.PhysicalTableRequest M J ny // r.Bounded passes copies T S} := + ⟨OAI.EditApproximation.previousPassRequest T S copy.val parent.val state, + Nat.lt_of_le_of_lt (Nat.sub_le _ _) parent.property.1, copy.isLt, le_rfl⟩ + +def queryPhysicalTableRead {M J n : ℕ} (copies T S : ℕ) + (parent : OAI.EditApproximation.PhysicalTableRequest M J n) + (child : {r : OAI.EditApproximation.PhysicalTableRequest M J n // r.combinedRank T S < parent.combinedRank T S}) : + OAI.EditApproximation.BitQuery {r : OAI.EditApproximation.PhysicalTableRequest M J n // r.combinedRank T S < parent.combinedRank T S} + OAI.EditApproximation.BinaryFraction := + .charge ((OAI.EditApproximation.physicalTableCodeWithWork copies T S child.val).2 + 1) (.read child .done) + +abbrev ComputedFamilyTableKey (source target : List ℕ) (N : ℕ) := + OAI.EditApproximation.ChargedPhysicalRequest (OAI.EditApproximation.integerParameters N).M + (OAI.EditApproximation.intervalTreeDepth (OAI.EditApproximation.integerParameters N).M source.length) target.length + (OAI.EditApproximation.computedSeedPassCount N + 1) (OAI.EditApproximation.inputHeight N ^ 2) (OAI.EditApproximation.integerParameters N).T (OAI.EditApproximation.integerParameters N).S + +def chargedPhysicalCodeWithWork {M J n passes copies T S : ℕ} : + OAI.EditApproximation.ChargedPhysicalRequest M J n passes copies T S → ℕ × ℕ + | .inl entry => let result := OAI.EditApproximation.physicalEntryCodeWithWork entry + (2 * result.1, result.2 + 2) + | .inr request => let result := OAI.EditApproximation.physicalTableCodeWithWork copies T S request.val + (2 * result.1 + 1, result.2 + 3) + +def queryPhysicalWarmupRead {M J n : ℕ} (copies pass copy T S t : ℕ) (ht : 0 < t) + (node : OAI.EditApproximation.PhysicalNode M J) (q : OAI.EditApproximation.TargetInterval n) + (otherNode : OAI.EditApproximation.PhysicalNode M J) (hnode : node.1.val ≤ otherNode.1.val) + (j : ℕ) (hj : j ≤ T) (r : OAI.EditApproximation.TargetInterval n) : + OAI.EditApproximation.BitQuery {child : OAI.EditApproximation.PhysicalTableRequest M J n // child.combinedRank T S < + (OAI.EditApproximation.PhysicalTableRequest.refinement pass copy node T t q).combinedRank T S} OAI.EditApproximation.BinaryFraction := by + have proof_combinedRank_lt_of_progress_80 {M : ℕ} {J : ℕ} {ny : ℕ} (T : ℕ) (S : ℕ) (first : OAI.EditApproximation.PhysicalTableRequest M J ny) (second : OAI.EditApproximation.PhysicalTableRequest M J ny) (hprogress : LT.lt.{0} second.remainingDepth first.remainingDepth ∧ + LE.le.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first) ∨ + LE.le.{0} second.remainingDepth first.remainingDepth ∧ + LT.lt.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first)) : + OAI.EditApproximation.PhysicalTableRequest.combinedRank T S second < OAI.EditApproximation.PhysicalTableRequest.combinedRank T S first := by + unfold OAI.EditApproximation.PhysicalTableRequest.combinedRank + rcases hprogress with h | h + · exact Nat.add_lt_add_of_lt_of_le h.1 h.2 + · exact Nat.add_lt_add_of_le_of_lt h.1 h.2 + exact + OAI.EditApproximation.queryPhysicalTableRead copies T S (OAI.EditApproximation.PhysicalTableRequest.refinement pass copy node T t q) + ⟨OAI.EditApproximation.PhysicalTableRequest.warmup pass copy otherNode j r, by + apply proof_combinedRank_lt_of_progress_80 T S _ _ + apply Or.inr + constructor + · exact Nat.sub_le_sub_left hnode J + · change pass * (T + S + 1) + j < pass * (T + S + 1) + (T + t) + omega⟩ + +def queryPhysicalCurrentRead {M J n : ℕ} (copies pass copy T S t : ℕ) + (node : OAI.EditApproximation.PhysicalNode M J) (hbelow : node.1.val < J) (q : OAI.EditApproximation.TargetInterval n) + (input : Fin M × OAI.EditApproximation.TargetInterval n) : + OAI.EditApproximation.BitQuery {child : OAI.EditApproximation.PhysicalTableRequest M J n // child.combinedRank T S < + (OAI.EditApproximation.PhysicalTableRequest.refinement pass copy node T t q).combinedRank T S} OAI.EditApproximation.BinaryFraction := by + have proof_combinedRank_lt_of_progress_80 {M : ℕ} {J : ℕ} {ny : ℕ} (T : ℕ) (S : ℕ) (first : OAI.EditApproximation.PhysicalTableRequest M J ny) (second : OAI.EditApproximation.PhysicalTableRequest M J ny) (hprogress : LT.lt.{0} second.remainingDepth first.remainingDepth ∧ + LE.le.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first) ∨ + LE.le.{0} second.remainingDepth first.remainingDepth ∧ + LT.lt.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first)) : + OAI.EditApproximation.PhysicalTableRequest.combinedRank T S second < OAI.EditApproximation.PhysicalTableRequest.combinedRank T S first := by + unfold OAI.EditApproximation.PhysicalTableRequest.combinedRank + rcases hprogress with h | h + · exact Nat.add_lt_add_of_lt_of_le h.1 h.2 + · exact Nat.add_lt_add_of_le_of_lt h.1 h.2 + have proof_sameIndexChild_progress_95 {M : ℕ} {J : ℕ} {ny : ℕ} (T : ℕ) (S : ℕ) (request : OAI.EditApproximation.PhysicalTableRequest M J ny) (hbelow : LT.lt.{0} (↑(Sigma.fst.{0, 0} request.node)) J) (i : Fin M) (state : OAI.EditApproximation.TargetInterval ny) : + (OAI.EditApproximation.PhysicalTableRequest.sameIndexChild request hbelow i state).remainingDepth < request.remainingDepth ∧ + OAI.EditApproximation.PhysicalTableRequest.rank T S (OAI.EditApproximation.PhysicalTableRequest.sameIndexChild request hbelow i state) ≤ OAI.EditApproximation.PhysicalTableRequest.rank T S request := by + constructor + · unfold OAI.EditApproximation.PhysicalTableRequest.remainingDepth OAI.EditApproximation.PhysicalTableRequest.sameIndexChild OAI.EditApproximation.physicalChild + dsimp only + omega + · exact le_rfl + have proof_combinedRank_sameIndexChild_94 {M : ℕ} {J : ℕ} {ny : ℕ} (T : ℕ) (S : ℕ) (request : OAI.EditApproximation.PhysicalTableRequest M J ny) (hbelow : LT.lt.{0} (↑(Sigma.fst.{0, 0} request.node)) J) (i : Fin M) (state : OAI.EditApproximation.TargetInterval ny) : + OAI.EditApproximation.PhysicalTableRequest.combinedRank T S (OAI.EditApproximation.PhysicalTableRequest.sameIndexChild request hbelow i state) < OAI.EditApproximation.PhysicalTableRequest.combinedRank T S request := + proof_combinedRank_lt_of_progress_80 T S request _ (Or.inl (proof_sameIndexChild_progress_95 T S request hbelow i state)) + exact + OAI.EditApproximation.queryPhysicalTableRead copies T S (OAI.EditApproximation.PhysicalTableRequest.refinement pass copy node T t q) + ⟨OAI.EditApproximation.PhysicalTableRequest.refinement pass copy (OAI.EditApproximation.physicalChild node hbelow input.1) T t input.2, + proof_combinedRank_sameIndexChild_94 T S + (OAI.EditApproximation.PhysicalTableRequest.refinement pass copy node T t q) hbelow input.1 input.2⟩ + +def queryPhysicalEarlierRead {M J n : ℕ} (copies pass copy T S t : ℕ) + (node : OAI.EditApproximation.PhysicalNode M J) (hbelow : node.1.val < J) (q : OAI.EditApproximation.TargetInterval n) + (input : Fin M × ℕ × OAI.EditApproximation.TargetInterval n) : + OAI.EditApproximation.BitQuery {child : OAI.EditApproximation.PhysicalTableRequest M J n // child.combinedRank T S < + (OAI.EditApproximation.PhysicalTableRequest.refinement pass copy node T t q).combinedRank T S} OAI.EditApproximation.BinaryFraction := by + have proof_combinedRank_lt_of_progress_80 {M : ℕ} {J : ℕ} {ny : ℕ} (T : ℕ) (S : ℕ) (first : OAI.EditApproximation.PhysicalTableRequest M J ny) (second : OAI.EditApproximation.PhysicalTableRequest M J ny) (hprogress : LT.lt.{0} second.remainingDepth first.remainingDepth ∧ + LE.le.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first) ∨ + LE.le.{0} second.remainingDepth first.remainingDepth ∧ + LT.lt.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first)) : + OAI.EditApproximation.PhysicalTableRequest.combinedRank T S second < OAI.EditApproximation.PhysicalTableRequest.combinedRank T S first := by + unfold OAI.EditApproximation.PhysicalTableRequest.combinedRank + rcases hprogress with h | h + · exact Nat.add_lt_add_of_lt_of_le h.1 h.2 + · exact Nat.add_lt_add_of_le_of_lt h.1 h.2 + have proof_refinement_history_child_progress_96 {M : ℕ} {J : ℕ} {ny : ℕ} (pass : ℕ) (copy : ℕ) (T : ℕ) (S : ℕ) (t : ℕ) (s : ℕ) (node : OAI.EditApproximation.PhysicalNode M J) (hbelow : LT.lt.{0} (↑(Sigma.fst.{0, 0} node)) J) (i : Fin M) (state : OAI.EditApproximation.TargetInterval ny) (previousState : OAI.EditApproximation.TargetInterval ny) (hs : LT.lt.{0} s t) : + (OAI.EditApproximation.PhysicalTableRequest.refinement pass copy (OAI.EditApproximation.physicalChild node hbelow i) T s previousState).remainingDepth < + (OAI.EditApproximation.PhysicalTableRequest.refinement pass copy node T t state).remainingDepth ∧ + OAI.EditApproximation.PhysicalTableRequest.rank T S (OAI.EditApproximation.PhysicalTableRequest.refinement pass copy (OAI.EditApproximation.physicalChild node hbelow i) T s previousState) < + OAI.EditApproximation.PhysicalTableRequest.rank T S (OAI.EditApproximation.PhysicalTableRequest.refinement pass copy node T t state) := by + constructor + · unfold OAI.EditApproximation.PhysicalTableRequest.remainingDepth OAI.EditApproximation.PhysicalTableRequest.refinement OAI.EditApproximation.physicalChild + dsimp only + omega + · dsimp only [OAI.EditApproximation.PhysicalTableRequest.rank, OAI.EditApproximation.PhysicalTableRequest.refinement] + omega + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_binaryNaturalCompareWithWork_lt_53 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.binaryNaturalCompareWithWork a b).1 = .lt ↔ a < b := by + simpa only [OAI.EditApproximation.binaryNaturalCompareWithWork, proof_bitWordValue_bits_15] using proof_bitCompareWithWork_lt_16 a.bits b.bits + exact + .charge ((OAI.EditApproximation.binaryNaturalCompareWithWork input.2.1 t).2 + 1) + (if hs : (OAI.EditApproximation.binaryNaturalCompareWithWork input.2.1 t).1 = .lt then + OAI.EditApproximation.queryPhysicalTableRead copies T S (OAI.EditApproximation.PhysicalTableRequest.refinement pass copy node T t q) + ⟨OAI.EditApproximation.PhysicalTableRequest.refinement pass copy (OAI.EditApproximation.physicalChild node hbelow input.1) T input.2.1 input.2.2, + proof_combinedRank_lt_of_progress_80 T S _ _ (Or.inr + ⟨(proof_refinement_history_child_progress_96 pass copy T S t input.2.1 + node hbelow input.1 q input.2.2 ((proof_binaryNaturalCompareWithWork_lt_53 _ _).mp hs)).1.le, + (proof_refinement_history_child_progress_96 pass copy T S t input.2.1 + node hbelow input.1 q input.2.2 ((proof_binaryNaturalCompareWithWork_lt_53 _ _).mp hs)).2⟩)⟩ + else .done (OAI.EditApproximation.BinaryFraction.nat 0)) + +def chargedPhysicalRemaining {M J n passes copies T S : ℕ} : + OAI.EditApproximation.ChargedPhysicalRequest M J n passes copies T S → ℕ + | .inl _ => 0 + | .inr request => request.val.remainingDepth + +def chargedPhysicalCodeAllocation {M J n passes copies T S : ℕ} : + OAI.EditApproximation.ChargedPhysicalRequest M J n passes copies T S → ℕ + | .inl entry => 2 * entry.1.1.val + J + 12 + | .inr request => OAI.EditApproximation.physicalTableCodeAllocation request.val + 2 + +def queryPhysicalMassRead {M J n : ℕ} (copies pass copy T S t : ℕ) (ht : 0 < t) + (node : OAI.EditApproximation.PhysicalNode M J) (hbelow : node.1.val < J) (q : OAI.EditApproximation.TargetInterval n) + (input : Fin M × OAI.EditApproximation.TargetInterval n) : + OAI.EditApproximation.BitQuery {child : OAI.EditApproximation.PhysicalTableRequest M J n // child.combinedRank T S < + (OAI.EditApproximation.PhysicalTableRequest.refinement pass copy node T t q).combinedRank T S} OAI.EditApproximation.BinaryFraction := + OAI.EditApproximation.queryMeanRead T (fun j => OAI.EditApproximation.queryPhysicalWarmupRead copies pass copy T S t ht node q + (OAI.EditApproximation.physicalChild node hbelow input.1) (by change node.1.val ≤ node.1.val + 1; omega) + j.val j.isLt.le input.2) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open Finset MeasureTheory ProbabilityTheory + +def integerClosedRange (lo hi : ℤ) : List ℤ := + (List.range (hi - lo + 1).toNat).map fun i : ℕ => lo + (i : ℤ) + +def groupSampleCount (M Q b : ℕ) (h : ℚ) : ℕ := min M ⌈(Q : ℚ) * M * h / b⌉₊ + +def groupScaleTrueCost {M : ℕ} (h : ℚ) (envelope value : Fin M → ℚ) : ℚ := + ∑ i, if envelope i = h then value i else 0 + +def selectGroupMember {ι : Type u_1} (members : List ι) (hnonempty : members ≠ []) + (estimate : ι → ℚ) : ι := + (members.argmax fun member => -estimate member).getD (members.head hnonempty) + +instance coarseDrawsMeasurableSpace (B D : ℕ) [MeasurableSpace (Fin B)] : + MeasurableSpace (OAI.EditApproximation.CoarseThresholdDraws B D) := by + induction D with + | zero => exact inferInstanceAs (MeasurableSpace PUnit) + | succ D ih => + letI := ih + exact inferInstanceAs + (MeasurableSpace ((Fin B → Fin B) × (Fin B → OAI.EditApproximation.CoarseThresholdDraws B D))) + +def groupDyadicScales (M b : ℕ) (F : ℚ) : List ℚ := + (OAI.EditApproximation.integerClosedRange (Int.clog 2 ((b : ℚ) / M)) (Int.log 2 (64 * F * b))).map + fun exponent => (2 : ℚ) ^ exponent + +def groupScaleEstimate {M : ℕ} (k : ℕ) (h : ℚ) (envelope value : Fin M → ℚ) + (draw : Fin k → Fin M) : ℚ := + if k = M then OAI.EditApproximation.groupScaleTrueCost h envelope value + else (M : ℚ) / k * ∑ j, if envelope (draw j) = h then value (draw j) else 0 + +noncomputable def coarseDrawMeasure (B : ℕ) [NeZero B] + [MeasurableSpace (Fin B)] [MeasurableSingletonClass (Fin B)] : + (D : ℕ) → Measure (OAI.EditApproximation.CoarseThresholdDraws B D) + | 0 => Measure.dirac PUnit.unit + | D + 1 => + (Measure.pi fun _ : Fin B => (PMF.uniformOfFintype (Fin B)).toMeasure).prod + (Measure.pi fun _ : Fin B => coarseDrawMeasure B D) + +def groupMemberEstimate {M T : ℕ} (scales : Fin T → ℚ) (count : Fin T → ℕ) + (connection : ℚ) (envelope value : Fin M → ℚ) + (draw : ∀ scale : Fin T, Fin (count scale) → Fin M) : ℚ := + connection + ∑ scale, OAI.EditApproximation.groupScaleEstimate (count scale) (scales scale) envelope value (draw scale) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BinaryFraction + + +def groupScalesWithWork (eM eb eF : ℕ) : List OAI.EditApproximation.BinaryFraction × ℕ := + let exponents := OAI.EditApproximation.integerClosedRange ((eb : ℤ) - eM) ((6 + eF + eb : ℕ) : ℤ) + let values := OAI.EditApproximation.arithmeticMapWithWork OAI.EditApproximation.BinaryFraction.signedPowerTwoWithWork exponents + (values.1, values.2 + exponents.length + Nat.size eM + Nat.size eb + Nat.size eF + 8) + +def bandPredicateReadWithWork {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) (r : OAI.EditApproximation.TargetInterval ny) + (b : ℕ) (tau theta velocity : OAI.EditApproximation.BinaryFraction) + (actions : List (Fin M → OAI.EditApproximation.TargetInterval ny)) (hne : actions ≠ []) + (read : Fin M → OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) (states : Fin M → OAI.EditApproximation.TargetInterval ny) : + Bool × ℕ := + let connection := OAI.EditApproximation.zeroConnectionWithWork r.lo (List.ofFn states) r.hi + let anchors := OAI.EditApproximation.allWithWork (fun i : Fin M => + let leftAnchor := OAI.EditApproximation.translatedEndpointWithWork r.lo parent.lo (OAI.EditApproximation.sourceChild parent i).lo + let rightAnchor := OAI.EditApproximation.translatedEndpointWithWork r.lo parent.lo (OAI.EditApproximation.sourceChild parent i).hi + let radius := OAI.EditApproximation.binaryNaturalMulWithWork 6 b + let left := OAI.EditApproximation.BinaryFraction.naturalDistanceLeWithWork leftAnchor.1 (states i).lo (OAI.EditApproximation.bitWordValue radius.1) + let right := OAI.EditApproximation.BinaryFraction.naturalDistanceLeWithWork rightAnchor.1 (states i).hi (OAI.EditApproximation.bitWordValue radius.1) + (left.1 && right.1, leftAnchor.2 + rightAnchor.2 + radius.2 + left.2 + right.2 + 3)) (List.finRange M) + let tolerance := OAI.EditApproximation.BinaryFraction.bandToleranceWithWork tau theta b M + let cuts := OAI.EditApproximation.allWithWork (OAI.EditApproximation.BinaryFraction.cutGuardReadWithWork parent r actions hne read states velocity tolerance.1) + (List.finRange M) + (connection.1 && anchors.1 && cuts.1, connection.2 + anchors.2 + tolerance.2 + cuts.2 + 4) + +def indexedGroupScales (raw : List OAI.EditApproximation.BinaryFraction) (M b : ℕ) (F : ℚ) + (h : raw.map OAI.EditApproximation.BinaryFraction.value = OAI.EditApproximation.groupDyadicScales M b F) : + Fin (OAI.EditApproximation.groupDyadicScales M b F).length → OAI.EditApproximation.BinaryFraction := + fun i => raw.get ⟨i.val, by + have hlen := congrArg List.length h + simp only [List.length_map] at hlen + omega⟩ + +def queryOnlineKeysWithWork {n : ℕ} (N P F : ℕ) (hP : 0 < P) + (a value : OAI.EditApproximation.BinaryFraction) (q : OAI.EditApproximation.TargetInterval n) : List (ℕ × OAI.EditApproximation.TargetInterval n) × ℕ := by + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_bitSubtractor_value_17 (a : Bool) (b : Bool) (borrow : Bool) : + a.toNat + 2 * (OAI.EditApproximation.bitBorrow a b borrow).toNat = + b.toNat + borrow.toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat := by + cases a <;> cases b <;> cases borrow <;> decide + have proof_bitSubtractionRippleEquation_18 (a : ℕ) (b : ℕ) (borrow : ℕ) (nextBorrow : ℕ) (difference : ℕ) (left : ℕ) (right : ℕ) (result : ℕ) (tail : ℕ) (htail : Eq.{1} (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} result right) nextBorrow) (HAdd.hAdd.{0, 0, 0} left tail)) (hbit : Eq.{1} (HAdd.hAdd.{0, 0, 0} a (HMul.hMul.{0, 0, 0} 2 nextBorrow)) + (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} b borrow) difference)) : + (difference + 2 * result) + (b + 2 * right) + borrow = + (a + 2 * left) + 2 * tail := by + omega + have proof_bitSubtractWithWork_value_19 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right borrow).1 + OAI.EditApproximation.bitWordValue right + borrow.toNat = + OAI.EditApproximation.bitWordValue left + 2 ^ max left.length right.length * + (OAI.EditApproximation.bitSubtractWithWork left right borrow).2.1.toNat := by + induction left generalizing right borrow with + | nil => + induction right generalizing borrow with + | nil => (simp [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + have h := ih (OAI.EditApproximation.bitBorrow false b borrow) + have hb := proof_bitSubtractor_value_17 false b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue, + List.length_nil, List.length_cons, Nat.zero_max, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 0 b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow false b borrow).toNat + (OAI.EditApproximation.bitDifference false b borrow).toNat 0 (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).1) + (2 ^ bs.length * (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons a as ih => + cases right with + | nil => + have h := ih [] (OAI.EditApproximation.bitBorrow a false borrow) + have hb := proof_bitSubtractor_value_17 a false borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_nil, List.length_cons, + Nat.max_zero, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat 0 borrow.toNat (OAI.EditApproximation.bitBorrow a false borrow).toNat + (OAI.EditApproximation.bitDifference a false borrow).toNat (OAI.EditApproximation.bitWordValue as) 0 + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).1) + (2 ^ as.length * (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons b bs => + have h := ih bs (OAI.EditApproximation.bitBorrow a b borrow) + have hb := proof_bitSubtractor_value_17 a b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_cons, Nat.succ_max_succ, + pow_succ] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow a b borrow).toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).1) + (2 ^ max as.length bs.length * (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_assoc, Nat.mul_left_comm] using hs + have proof_bitWordValue_lt_pow_length_20 (bits : List.{0} Bool) : OAI.EditApproximation.bitWordValue bits < 2 ^ bits.length := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitWordValue]) + | cons bit bits ih => + cases bit <;> (simp only [OAI.EditApproximation.bitWordValue, List.length_cons, pow_succ, Bool.toNat_false, Bool.toNat_true]) <;> omega + have proof_bitSubtractWithWork_length_21 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + (OAI.EditApproximation.bitSubtractWithWork left right borrow).1.length = max left.length right.length := by + induction left generalizing right borrow with + | nil => + simp only [OAI.EditApproximation.bitSubtractWithWork] + induction right generalizing borrow with + | nil => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork] + | cons b bs ih => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork, ih] + | cons a as ih => + cases right with + | nil => simp [OAI.EditApproximation.bitSubtractWithWork, ih] + | cons b bs => simp [OAI.EditApproximation.bitSubtractWithWork, ih, Nat.succ_max_succ] + have proof_bitSubtractWithWork_sub_22 (left : List.{0} Bool) (right : List.{0} Bool) (h : LE.le.{0} (OAI.EditApproximation.bitWordValue right) (OAI.EditApproximation.bitWordValue left)) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right false).1 = OAI.EditApproximation.bitWordValue left - OAI.EditApproximation.bitWordValue right := by + have hvalue := proof_bitSubtractWithWork_value_19 left right false + have hlt := proof_bitWordValue_lt_pow_length_20 (OAI.EditApproximation.bitSubtractWithWork left right false).1 + rw [proof_bitSubtractWithWork_length_21] at hlt + cases hb : (OAI.EditApproximation.bitSubtractWithWork left right false).2.1 + · simp only [hb, Bool.toNat_false, Nat.mul_zero, Nat.add_zero] at hvalue + omega + · simp only [hb, Bool.toNat_true, Bool.toNat_false, Nat.mul_one, Nat.add_zero] at hvalue + omega + have proof_bitDivModWithWork_value_23 (divisor : List.{0} Bool) (bits : List.{0} Bool) (hd : LT.lt.{0} 0 (OAI.EditApproximation.bitWordValue divisor)) : + OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).1 + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 < OAI.EditApproximation.bitWordValue divisor := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitDivModWithWork, OAI.EditApproximation.bitWordValue, hd]) + | cons bit bits ih => + let previous := OAI.EditApproximation.bitDivModWithWork divisor bits + let candidate := bit :: previous.2.1 + have hp : OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue previous.1 + + OAI.EditApproximation.bitWordValue previous.2.1 := ih.1 + have hr : OAI.EditApproximation.bitWordValue previous.2.1 < OAI.EditApproximation.bitWordValue divisor := ih.2 + have hc : OAI.EditApproximation.bitWordValue candidate < 2 * OAI.EditApproximation.bitWordValue divisor := by + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + cases bit <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega + by_cases hlt : (OAI.EditApproximation.bitCompareWithWork candidate divisor).1 = .lt + · have hv := (proof_bitCompareWithWork_lt_16 candidate divisor).1 hlt + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 = .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * + OAI.EditApproximation.bitWordValue (false :: previous.1) + OAI.EditApproximation.bitWordValue candidate ∧ OAI.EditApproximation.bitWordValue candidate < _ + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_false]) + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + nlinarith only [hp] + · exact hv + · have hv : OAI.EditApproximation.bitWordValue divisor ≤ OAI.EditApproximation.bitWordValue candidate := by + exact Nat.le_of_not_gt (fun h => hlt ((proof_bitCompareWithWork_lt_16 candidate divisor).2 h)) + have hs := proof_bitSubtractWithWork_sub_22 candidate divisor hv + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 ≠ .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (true :: previous.1) + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 < _ + rw [hs] + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_true]) + have he := Nat.sub_add_cancel hv + dsimp only [candidate, OAI.EditApproximation.bitWordValue] at he ⊢ + nlinarith only [hp, he] + · omega + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_binaryNaturalDivModWithWork_spec_24 (n : ℕ) (d : ℕ) (hd : LT.lt.{0} 0 d) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalDivModWithWork n d).1 = n / d ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalDivModWithWork n d).2.1 = n % d := by + have h := proof_bitDivModWithWork_value_23 d.bits n.bits (by simpa only [proof_bitWordValue_bits_15] using hd) + simp only [proof_bitWordValue_bits_15] at h + have hmod : n % d = OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork d.bits n.bits).2.1 := by + conv_lhs => rw [h.1] + simp only [Nat.add_mod, Nat.mul_mod_right, Nat.zero_add, Nat.mod_eq_of_lt h.2] + have hdiv : n / d = OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork d.bits n.bits).1 := by + conv_lhs => rw [h.1] + rw [Nat.mul_add_div hd, Nat.div_eq_of_lt h.2, Nat.add_zero] + exact ⟨hdiv.symm, hmod.symm⟩ + have proof_wordLEWithWork_value_26 (a : List.{0} Bool) (b : List.{0} Bool) : + (OAI.EditApproximation.wordLEWithWork a b).1 = true ↔ OAI.EditApproximation.bitWordValue a ≤ OAI.EditApproximation.bitWordValue b := by + simp only [OAI.EditApproximation.wordLEWithWork, Bool.not_eq_true', decide_eq_false_iff_not, + proof_bitCompareWithWork_lt_16, not_lt] + have proof_seedGridSpacingWithWork_value_86 (b : ℕ) (P : ℕ) (hP : LT.lt.{0} 0 P) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.seedGridSpacingWithWork b P).1 = OAI.EditApproximation.seedGridSpacing b P := by + have hv := (proof_binaryNaturalDivModWithWork_spec_24 b P hP).1 + unfold OAI.EditApproximation.seedGridSpacingWithWork OAI.EditApproximation.seedGridSpacing + dsimp only + split_ifs with ht + · have hq : b / P ≤ 1 := by + have h := (proof_wordLEWithWork_value_26 _ _).mp ht + change OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalDivModWithWork b P).1 ≤ 1 at h + rwa [hv] at h + rw [max_eq_left hq] + rfl + · have hq : 1 ≤ b / P := by + have h := mt (proof_wordLEWithWork_value_26 _ _).mpr ht + change ¬ OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalDivModWithWork b P).1 ≤ 1 at h + rw [hv] at h + exact Nat.le_of_lt (Nat.lt_of_not_ge h) + rw [max_eq_right hq] + exact hv + have proof_seedGridSpacingWithWork_pos_85 (b : ℕ) (P : ℕ) (hP : LT.lt.{0} 0 P) : + 0 < OAI.EditApproximation.bitWordValue (OAI.EditApproximation.seedGridSpacingWithWork b P).1 := by + rw [proof_seedGridSpacingWithWork_value_86 b P hP] + unfold OAI.EditApproximation.seedGridSpacing + omega + exact + let scales := OAI.EditApproximation.BinaryFraction.queryScalesWithWork N F a value + let keys := OAI.EditApproximation.arithmeticMapWithWork (fun b => + let spacing := OAI.EditApproximation.seedGridSpacingWithWork b P + let center := OAI.EditApproximation.roundStateWithWork (OAI.EditApproximation.bitWordValue spacing.1) (proof_seedGridSpacingWithWork_pos_85 b P hP) q + ((b, center.1), spacing.2 + center.2 + 2)) scales.1 + (keys.1, scales.2 + keys.2 + 1) + +def groupScalesAllocation (eM eb eF : ℕ) : ℕ := + let exponents := OAI.EditApproximation.integerClosedRange ((eb : ℤ) - eM) ((6 + eF + eb : ℕ) : ℤ) + OAI.EditApproximation.arithmeticMapAllocation OAI.EditApproximation.BinaryFraction.signedPowerTwoAllocation exponents + exponents.length + + Nat.size eM + Nat.size eb + Nat.size eF + +def bandFromActionsReadWithWork {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (r : OAI.EditApproximation.TargetInterval ny) (b : ℕ) (tau theta velocity : OAI.EditApproximation.BinaryFraction) + (read : Fin M → OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) + (actions : List (Fin M → OAI.EditApproximation.TargetInterval ny)) (hne : actions ≠ []) : + List (Fin M → OAI.EditApproximation.TargetInterval ny) × ℕ := + let margin := OAI.EditApproximation.BinaryFraction.subWithWork OAI.EditApproximation.BinaryFraction.one tau + let guard := OAI.EditApproximation.BinaryFraction.leWithWork velocity.absolute margin.1 + if guard.1 then + let filtered := OAI.EditApproximation.filterWithWork + (OAI.EditApproximation.BinaryFraction.bandPredicateReadWithWork parent r b tau theta velocity actions hne read) actions + (filtered.1, margin.2 + guard.2 + filtered.2 + 2) + else ([], margin.2 + guard.2 + 1) + +def queryInitialSupportWithWork {n : ℕ} (N P F exponent : ℕ) (hP : 0 < P) + (a value : OAI.EditApproximation.BinaryFraction) (q : OAI.EditApproximation.TargetInterval n) : List (OAI.EditApproximation.TargetInterval n) × ℕ := + let raw := OAI.EditApproximation.BinaryFraction.queryRawCentersWithWork N P F a value q + let groups := OAI.EditApproximation.BinaryFraction.queryGroupKeysWithWork N F exponent a value q + let cells := OAI.EditApproximation.arithmeticFlatMapWithWork (fun key => + let spacing := OAI.EditApproximation.seedGridSpacingWithWork key.1 P + let side := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) (OAI.EditApproximation.BinaryFraction.nat key.1) + let states := OAI.EditApproximation.BinaryFraction.cellStatesWithWork n (OAI.EditApproximation.bitWordValue spacing.1) side.1 key.2 + (states.1, spacing.2 + side.2 + states.2 + exponent + 3)) groups.1 + let online := OAI.EditApproximation.BinaryFraction.queryOnlineKeysWithWork N P F hP a value q + let onlineStates := OAI.EditApproximation.arithmeticMapWithWork (fun key => (key.2, 1)) online.1 + (q :: (raw.1 ++ cells.1 ++ onlineStates.1), + raw.2 + groups.2 + cells.2 + online.2 + onlineStates.2 + 2 * raw.1.length + cells.1.length + 5) + +def queryEarlierRepresentativesWithWork {n : ℕ} (N P F exponent : ℕ) (hP : 0 < P) + (a : OAI.EditApproximation.BinaryFraction) (initial : OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) + (q : OAI.EditApproximation.TargetInterval n) : List (ℕ × OAI.EditApproximation.TargetInterval n) × ℕ := + let query := initial q + let reps := OAI.EditApproximation.BinaryFraction.localRepresentativeReadWithWork N P F a initial q + let groups := OAI.EditApproximation.BinaryFraction.queryGroupKeysWithWork N F exponent a query.1 q + let cells := OAI.EditApproximation.arithmeticFlatMapWithWork (fun key => + let centers := OAI.EditApproximation.BinaryFraction.cellCentersReadWithWork P F key.1 a (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) initial key.2 + let labeled := OAI.EditApproximation.arithmeticMapWithWork (fun r => ((key.1, r), 1)) centers.1 + (labeled.1, centers.2 + labeled.2 + 1)) groups.1 + let online := OAI.EditApproximation.BinaryFraction.queryOnlineKeysWithWork N P F hP a query.1 q + (reps.1 ++ cells.1 ++ online.1, + query.2 + reps.2 + groups.2 + cells.2 + online.2 + 2 * reps.1.length + cells.1.length + 4) + +def bandFromActionsReadAllocation {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (r : OAI.EditApproximation.TargetInterval ny) (b : ℕ) (tau theta velocity : OAI.EditApproximation.BinaryFraction) + (read : Fin M → OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) + (allocation : Fin M → OAI.EditApproximation.TargetInterval ny → ℕ) + (actions : List (Fin M → OAI.EditApproximation.TargetInterval ny)) (hne : actions ≠ []) : ℕ := + let margin := (OAI.EditApproximation.BinaryFraction.subWithWork OAI.EditApproximation.BinaryFraction.one tau).1 + OAI.EditApproximation.BinaryFraction.subAllocation OAI.EditApproximation.BinaryFraction.one tau + OAI.EditApproximation.BinaryFraction.leAllocation velocity.absolute margin + + if (OAI.EditApproximation.BinaryFraction.leWithWork velocity.absolute margin).1 then + OAI.EditApproximation.filterAllocation (OAI.EditApproximation.BinaryFraction.bandPredicateReadWithWork parent r b tau theta velocity actions hne read) + (OAI.EditApproximation.BinaryFraction.bandPredicateReadAllocation parent r b tau theta velocity actions hne read allocation) actions + else 0 + +def queryInitialSupportAllocation {n : ℕ} (N P F exponent : ℕ) (hP : 0 < P) + (a value : OAI.EditApproximation.BinaryFraction) (q : OAI.EditApproximation.TargetInterval n) : ℕ := + let raw := (OAI.EditApproximation.BinaryFraction.queryRawCentersWithWork N P F a value q).1 + let groups := (OAI.EditApproximation.BinaryFraction.queryGroupKeysWithWork N F exponent a value q).1 + let build := fun key => + let spacing := OAI.EditApproximation.seedGridSpacingWithWork key.1 P + let side := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) (OAI.EditApproximation.BinaryFraction.nat key.1) + let states := OAI.EditApproximation.BinaryFraction.cellStatesWithWork n (OAI.EditApproximation.bitWordValue spacing.1) side.1 key.2 + (states.1, spacing.2 + side.2 + states.2 + exponent + 3) + let cells := (OAI.EditApproximation.arithmeticFlatMapWithWork build groups).1 + let online := (OAI.EditApproximation.BinaryFraction.queryOnlineKeysWithWork N P F hP a value q).1 + OAI.EditApproximation.BinaryFraction.queryRawCentersAllocation N P F a value q + OAI.EditApproximation.BinaryFraction.queryGroupKeysAllocation N F exponent a value q + + OAI.EditApproximation.arithmeticFlatMapAllocation build (OAI.EditApproximation.BinaryFraction.initialCellAllocation n P exponent) groups + + OAI.EditApproximation.BinaryFraction.queryOnlineKeysAllocation N P F hP a value q + OAI.EditApproximation.arithmeticMapAllocation (fun _ => 1) online + + 2 * raw.length + cells.length + 1 + +def queryBandInputsWithWork {nx ny : ℕ} (M : ℕ) (parent : OAI.EditApproximation.TargetInterval nx) + (N P F exponent : ℕ) (hP : 0 < P) (a : OAI.EditApproximation.BinaryFraction) + (initial : OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) (q : OAI.EditApproximation.TargetInterval ny) : + List (Fin M × OAI.EditApproximation.TargetInterval ny) × ℕ := + let representatives := OAI.EditApproximation.BinaryFraction.queryEarlierRepresentativesWithWork N P F exponent hP a initial q + let inputs := OAI.EditApproximation.BinaryFraction.queryWideInputsWithWork M parent P representatives.1 + (inputs.1, representatives.2 + inputs.2 + 1) + +def queryEarlierInputsWithWork {nx ny : ℕ} (M : ℕ) (parent : OAI.EditApproximation.TargetInterval nx) + (N P F exponent history : ℕ) (hP : 0 < P) (a : OAI.EditApproximation.BinaryFraction) + (initial : OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) (q : OAI.EditApproximation.TargetInterval ny) : + List (Fin M × ℕ × OAI.EditApproximation.TargetInterval ny) × ℕ := + let representatives := OAI.EditApproximation.BinaryFraction.queryEarlierRepresentativesWithWork N P F exponent hP a initial q + let raw := OAI.EditApproximation.BinaryFraction.queryRawHistoryInputsWithWork M parent P history representatives.1 + let ordered := OAI.EditApproximation.queryOrderedHistoryInputsWithWork raw.1 + (ordered.1, representatives.2 + raw.2 + ordered.2 + 2) + +def queryEarlierInputsAllocation {nx ny : ℕ} (M : ℕ) (parent : OAI.EditApproximation.TargetInterval nx) + (N P F exponent history : ℕ) (hP : 0 < P) (a : OAI.EditApproximation.BinaryFraction) + (initial : OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) (allocation : OAI.EditApproximation.TargetInterval ny → ℕ) + (q : OAI.EditApproximation.TargetInterval ny) : ℕ := + let reps := (OAI.EditApproximation.BinaryFraction.queryEarlierRepresentativesWithWork N P F exponent hP a initial q).1 + OAI.EditApproximation.BinaryFraction.queryEarlierRepresentativesAllocation N P F exponent hP a initial allocation q + + OAI.EditApproximation.BinaryFraction.queryRawHistoryInputsAllocation M parent P history reps + + OAI.EditApproximation.queryOrderedHistoryInputsAllocation (OAI.EditApproximation.BinaryFraction.queryRawHistoryInputsWithWork M parent P history reps).1 + +def queryBandInputsAllocation {nx ny : ℕ} (M : ℕ) (parent : OAI.EditApproximation.TargetInterval nx) + (N P F exponent : ℕ) (hP : 0 < P) (a : OAI.EditApproximation.BinaryFraction) + (initial : OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) (allocation : OAI.EditApproximation.TargetInterval ny → ℕ) + (q : OAI.EditApproximation.TargetInterval ny) : ℕ := + OAI.EditApproximation.BinaryFraction.queryEarlierRepresentativesAllocation N P F exponent hP a initial allocation q + + OAI.EditApproximation.BinaryFraction.queryWideInputsAllocation M parent P (OAI.EditApproximation.BinaryFraction.queryEarlierRepresentativesWithWork N P F exponent hP a initial q).1 + + +end OAI.EditApproximation.BinaryFraction +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.FiniteQuery + + +def run {ι : Type u_1} {κ : Type u_2} (ask : ι → OAI.EditApproximation.BinaryMemo ℚ → OAI.EditApproximation.RecursiveMemoResult κ) : + OAI.EditApproximation.FiniteQuery ι → OAI.EditApproximation.BinaryMemo ℚ → OAI.EditApproximation.RecursiveMemoResult κ + | .done result, memory => ⟨result, memory, [], 0, 0⟩ + | .read key next, memory => + let first := ask key memory + let rest := run ask (next first.value) first.memory + ⟨rest.value, rest.memory, first.freshKeys ++ rest.freshKeys, + first.dictionaryVisits + rest.dictionaryVisits, first.requests + rest.requests⟩ + +def bind {ι : Type u_1} : OAI.EditApproximation.FiniteQuery ι → (ℚ → OAI.EditApproximation.FiniteQuery ι) → OAI.EditApproximation.FiniteQuery ι + | .done result, next => next result + | .read key continuation, next => .read key (fun result => bind (continuation result) next) + +def mapKeys {ι : Type u_1} {κ : Type u_2} (f : ι → κ) : OAI.EditApproximation.FiniteQuery ι → OAI.EditApproximation.FiniteQuery κ + | .done result => .done result + | .read key next => .read (f key) (fun answer => mapKeys f (next answer)) + +def restrict {ι : Type u_1} (P : ι → Prop) [DecidablePred P] : OAI.EditApproximation.FiniteQuery ι → OAI.EditApproximation.FiniteQuery {key // P key} + | .done result => .done result + | .read key next => if h : P key then + .read ⟨key, h⟩ (fun answer => restrict P (next answer)) + else restrict P (next 0) + +def requestWork {ι : Type u_1} {κ : Type u_2} (ask : ι → OAI.EditApproximation.BinaryMemo ℚ → OAI.EditApproximation.RecursiveMemoResult κ) + (cost : ι → OAI.EditApproximation.BinaryMemo ℚ → ℕ) : OAI.EditApproximation.FiniteQuery ι → OAI.EditApproximation.BinaryMemo ℚ → ℕ + | .done _, _ => 0 + | .read key next, memory => + let first := ask key memory + cost key memory + requestWork ask cost (next first.value) first.memory + +def collect {ι : Type u_1} {κ : Type u_2} (reader : κ → OAI.EditApproximation.FiniteQuery ι) : + List κ → (List ℚ → OAI.EditApproximation.FiniteQuery ι) → OAI.EditApproximation.FiniteQuery ι + | [], next => next [] + | key :: keys, next => OAI.EditApproximation.FiniteQuery.bind (reader key) fun result => + collect reader keys (fun results => next (result :: results)) + + +end OAI.EditApproximation.FiniteQuery +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation + + +def physicalInitialQuery {ι : Type u_1} {α : Type u_2} [DecidableEq α] {M J : ℕ} + (source target : List α) (N P F : ℕ) (A : ℚ) + (seedRead : OAI.EditApproximation.PhysicalEntry M J target.length → OAI.EditApproximation.FiniteQuery ι) + (state : OAI.EditApproximation.PhysicalEntry M J target.length) : OAI.EditApproximation.FiniteQuery ι := + let piece := OAI.EditApproximation.physicalSource source state.1 + if piece.length ≤ 1 then .done (OAI.EditApproximation.shortSourceCost piece (OAI.EditApproximation.substring target state.2.lo state.2.hi)) + else OAI.EditApproximation.FiniteQuery.bind (seedRead state) fun answer => + let value := ⌈answer⌉₊ + let keys := OAI.EditApproximation.rawInitialConeCenters N P A value state.2 + OAI.EditApproximation.FiniteQuery.collect (fun q => seedRead (state.1, q)) keys fun answers => + let localTable := fun q => if q = state.2 then value + else ⌈OAI.EditApproximation.finiteAnswerTable keys answers q⌉₊ + .done (OAI.EditApproximation.localInitialConeTable piece target localTable N P F A (OAI.EditApproximation.refinementFactor A F) state.2) + +def queryInitialGather {ι : Type u_1} {β : Type u_2} {n : ℕ} (N P F exponent : ℕ) (hP : 0 < P) + (a : OAI.EditApproximation.BinaryFraction) (q : OAI.EditApproximation.TargetInterval n) + (reader : OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (next : List (OAI.EditApproximation.TargetInterval n) → List OAI.EditApproximation.BinaryFraction → OAI.EditApproximation.BitQuery ι β) : OAI.EditApproximation.BitQuery ι β := + (reader q).bind fun value => + (OAI.EditApproximation.BitQuery.compute (OAI.EditApproximation.BinaryFraction.queryInitialSupportWithWork N P F exponent hP a value q)).bind + fun keys => OAI.EditApproximation.BitQuery.collect reader keys (next keys) + +def queryBandGather {ι : Type u_1} {β : Type u_2} {nx ny : ℕ} (M : ℕ) (parent : OAI.EditApproximation.TargetInterval nx) + (N P F exponent : ℕ) (hP : 0 < P) (a : OAI.EditApproximation.BinaryFraction) + (initial : OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) (q : OAI.EditApproximation.TargetInterval ny) + (massReader initialReader : (Fin M × OAI.EditApproximation.TargetInterval ny) → OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (next : List (Fin M × OAI.EditApproximation.TargetInterval ny) → List OAI.EditApproximation.BinaryFraction → List OAI.EditApproximation.BinaryFraction → + OAI.EditApproximation.BitQuery ι β) : OAI.EditApproximation.BitQuery ι β := + (OAI.EditApproximation.BitQuery.compute (OAI.EditApproximation.BinaryFraction.queryBandInputsWithWork M parent N P F exponent hP a initial q)).bind + fun keys => OAI.EditApproximation.BitQuery.collect massReader keys fun mass => + OAI.EditApproximation.BitQuery.collect initialReader keys (next keys mass) + +def physicalRefinementMassQuery {M J ny : ℕ} (pass copy T S t : ℕ) (ht : 0 < t) + (node : OAI.EditApproximation.PhysicalNode M J) (hbelow : node.1.val < J) (q : OAI.EditApproximation.TargetInterval ny) + (input : Fin M × OAI.EditApproximation.TargetInterval ny) : + OAI.EditApproximation.FiniteQuery {child : OAI.EditApproximation.PhysicalTableRequest M J ny // + child.combinedRank T S < (OAI.EditApproximation.PhysicalTableRequest.refinement pass copy node T t q).combinedRank T S} := + OAI.EditApproximation.FiniteQuery.collect (fun j : Fin T => OAI.EditApproximation.physicalRefinementWarmupRead pass copy T S t ht node q + (OAI.EditApproximation.physicalChild node hbelow input.1) (by change node.1.val ≤ node.1.val + 1; omega) + j.val (Nat.le_of_lt j.isLt) input.2) (List.ofFn fun j : Fin T => j) + (fun values => .done (values.sum / T)) + +def physicalMedianSeedQuery {M J ny : ℕ} (N T S copies multiplier : ℕ) + (parent : OAI.EditApproximation.PhysicalTableRequest M J ny) (hpass : 0 < parent.pass) (state : OAI.EditApproximation.TargetInterval ny) : + OAI.EditApproximation.FiniteQuery {child : OAI.EditApproximation.PhysicalTableRequest M J ny // + child.combinedRank T S < parent.combinedRank T S} := + OAI.EditApproximation.FiniteQuery.collect (fun copy : Fin copies => OAI.EditApproximation.previousPassRead T S parent hpass state copy.val) + (List.finRange copies) fun values => + .done (min N (OAI.EditApproximation.upperMedian (values.map fun value => ⌈(multiplier : ℚ) * value⌉₊)) : ℕ) + +def globalSeedRead {M J ny : ℕ} (N T S copies : ℕ) (multiplier : ℕ → ℕ) + (initial : OAI.EditApproximation.PhysicalEntry M J ny → ℕ) (parent : OAI.EditApproximation.PhysicalTableRequest M J ny) + (state : OAI.EditApproximation.PhysicalEntry M J ny) : + OAI.EditApproximation.FiniteQuery {child : OAI.EditApproximation.PhysicalTableRequest M J ny // + child.combinedRank T S < parent.combinedRank T S} := + if state.1 = parent.node then + if hp : parent.pass = 0 then .done (initial state : ℚ) + else OAI.EditApproximation.physicalMedianSeedQuery N T S copies (multiplier (parent.pass - 1)) parent + (Nat.pos_of_ne_zero hp) state.2 + else .done 0 + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.UnreducedRational + + +def value (a : OAI.EditApproximation.UnreducedRational) : ℚ := (a.num : ℚ) / a.den + +def zero : OAI.EditApproximation.UnreducedRational := ⟨0, 1, by decide⟩ + +def mul (a b : OAI.EditApproximation.UnreducedRational) : OAI.EditApproximation.UnreducedRational := + ⟨a.num * b.num, a.den * b.den, Nat.mul_pos a.den_pos b.den_pos⟩ + +def lt (a b : OAI.EditApproximation.UnreducedRational) : Bool := decide (a.num * b.den < b.num * a.den) + +def inv (a : OAI.EditApproximation.UnreducedRational) : OAI.EditApproximation.UnreducedRational := + if h : a.num = 0 then OAI.EditApproximation.UnreducedRational.zero else + ⟨a.num.sign * a.den, a.num.natAbs, Int.natAbs_pos.mpr h⟩ + +def div (a b : OAI.EditApproximation.UnreducedRational) : OAI.EditApproximation.UnreducedRational := a.mul b.inv + + +end OAI.EditApproximation.UnreducedRational +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open Finset EditDistortion + +inductive CoarseSourceTree (B : ℕ) (α : Type u) : ℕ → Type u + | leaf (letter : Option α) : CoarseSourceTree B α 0 + | branch {D : ℕ} (children : Fin B → CoarseSourceTree B α D) : CoarseSourceTree B α (D + 1) + +def coarseTargetFrame {α : Type u} (k : ℕ) (target : List α) : List (Option α) := + (List.replicate k none ++ target.map some) ++ List.replicate k none + +def coarseRootShift (k : ℕ) : Fin (2 * k + 1) := ⟨k, by omega⟩ + +def endpointActionConnection {n M : ℕ} (q : OAI.EditApproximation.TargetInterval n) + (states : Fin M → OAI.EditApproximation.TargetInterval n) : ℕ := + OAI.EditApproximation.connectionBudget q.lo (List.ofFn states) q.hi + +def coarseSourceTreeOfList (B : ℕ) {α : Type u} : + (D : ℕ) → List α → OAI.EditApproximation.CoarseSourceTree B α D + | 0, source => .leaf source.head? + | D + 1, source => .branch (fun i => + coarseSourceTreeOfList B D ((source.drop (i.val * B ^ D)).take (B ^ D))) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BinaryFraction +open Finset + +def groupIndexWithWork {M : ℕ} (h : OAI.EditApproximation.BinaryFraction) (envelope values : Vector OAI.EditApproximation.BinaryFraction M) + (indices : List (Fin M)) : OAI.EditApproximation.BinaryFraction × ℕ := + let terms := OAI.EditApproximation.BinaryFraction.groupTermsWithWork h envelope values indices + let total := OAI.EditApproximation.BinaryFraction.sumListWithWork terms.1 + (total.1, terms.2 + total.2 + 1) + +def endpointDistanceWithWork {n : ℕ} (q r : OAI.EditApproximation.TargetInterval n) : OAI.EditApproximation.BinaryFraction × ℕ := + let left := OAI.EditApproximation.BinaryFraction.distanceWithWork (OAI.EditApproximation.BinaryFraction.nat q.lo) (OAI.EditApproximation.BinaryFraction.nat r.lo) + let right := OAI.EditApproximation.BinaryFraction.distanceWithWork (OAI.EditApproximation.BinaryFraction.nat q.hi) (OAI.EditApproximation.BinaryFraction.nat r.hi) + let result := OAI.EditApproximation.BinaryFraction.canonicalAddWithWork left.1 right.1 + (result.1, left.2 + right.2 + result.2 + Nat.size q.lo + Nat.size q.hi + + Nat.size r.lo + Nat.size r.hi + 3) + +def endpointConnectionWithWork {n M : ℕ} (r : OAI.EditApproximation.TargetInterval n) + (states : Fin M → OAI.EditApproximation.TargetInterval n) : OAI.EditApproximation.BinaryFraction × ℕ := + let result := OAI.EditApproximation.BinaryFraction.connectionWithWork (OAI.EditApproximation.BinaryFraction.nat r.lo) (OAI.EditApproximation.BinaryFraction.nat r.hi) (List.ofFn states) + (result.1, result.2 + Nat.size r.lo + Nat.size r.hi + M + 2) + +def stateGapWithWork {n : ℕ} (sourceLength : ℕ) (r : OAI.EditApproximation.TargetInterval n) : OAI.EditApproximation.BinaryFraction × ℕ := + let targetLength := OAI.EditApproximation.BinaryFraction.subWithWork (OAI.EditApproximation.BinaryFraction.nat r.hi) (OAI.EditApproximation.BinaryFraction.nat r.lo) + let result := OAI.EditApproximation.BinaryFraction.subWithWork targetLength.1 (OAI.EditApproximation.BinaryFraction.nat sourceLength) + (result.1, targetLength.2 + result.2 + Nat.size r.hi + Nat.size r.lo + Nat.size sourceLength + 2) + + +end OAI.EditApproximation.BinaryFraction +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BinaryFraction + + +def groupScaleSourceWithWork {M : ℕ} (k : ℕ) (h : OAI.EditApproximation.BinaryFraction) + (envelope values : Vector OAI.EditApproximation.BinaryFraction M) (draw : Fin k → Fin M × ℕ) : OAI.EditApproximation.BinaryFraction × ℕ := + let indices := if k = M then (List.finRange M, 0) else OAI.EditApproximation.arithmeticMapWithWork draw (List.finRange k) + let subtotal := OAI.EditApproximation.BinaryFraction.groupIndexWithWork h envelope values indices.1 + let factor := if k = M then (OAI.EditApproximation.BinaryFraction.one, 1) else OAI.EditApproximation.BinaryFraction.divWithWork (OAI.EditApproximation.BinaryFraction.nat M) (OAI.EditApproximation.BinaryFraction.nat k) + let result := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork factor.1 subtotal.1 + (result.1, indices.2 + subtotal.2 + factor.2 + result.2 + Nat.size M + Nat.size k + 3) + +def endpointScoreReadWithWork {n M : ℕ} (r : OAI.EditApproximation.TargetInterval n) + (read : Fin M → OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) (states : Fin M → OAI.EditApproximation.TargetInterval n) : + OAI.EditApproximation.BinaryFraction × ℕ := + let words := OAI.EditApproximation.arithmeticMapWithWork (fun i => read i (states i)) (List.finRange M) + let connection := OAI.EditApproximation.BinaryFraction.endpointConnectionWithWork r states + let children := OAI.EditApproximation.BinaryFraction.sumListWithWork words.1 + let result := OAI.EditApproximation.BinaryFraction.canonicalAddWithWork connection.1 children.1 + (result.1, words.2 + connection.2 + children.2 + result.2 + 2) + +def initialConeWithWork {n : ℕ} (sourceLength : ℕ) (U : OAI.EditApproximation.TargetInterval n → ℕ) + (a L : OAI.EditApproximation.BinaryFraction) (query center : OAI.EditApproximation.TargetInterval n) : OAI.EditApproximation.BinaryFraction × ℕ := + let gap := OAI.EditApproximation.BinaryFraction.stateGapWithWork sourceLength center + let seed := OAI.EditApproximation.BinaryFraction.scaledSeedWithWork (U center) a gap.1 + let distance := OAI.EditApproximation.BinaryFraction.endpointDistanceWithWork query center + let spatial := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork L distance.1 + let result := OAI.EditApproximation.BinaryFraction.canonicalAddWithWork seed.1 spatial.1 + (result.1, gap.2 + seed.2 + distance.2 + spatial.2 + result.2 + 4) + +def endpointActionWithWork {ny M : ℕ} (center : OAI.EditApproximation.TargetInterval ny) + (states : Fin M → OAI.EditApproximation.TargetInterval ny) : + OAI.EditApproximation.BinaryBellmanAction (OAI.EditApproximation.TargetInterval ny) (Fin M × OAI.EditApproximation.TargetInterval ny) M × ℕ := + let connection := OAI.EditApproximation.BinaryFraction.endpointConnectionWithWork center states + (⟨center, connection.1, fun i => (i, states i)⟩, connection.2 + M + 1) + +def endpointScoreReadAllocation {n M : ℕ} (r : OAI.EditApproximation.TargetInterval n) + (read : Fin M → OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) + (footprint : Fin M → OAI.EditApproximation.TargetInterval n → ℕ) (states : Fin M → OAI.EditApproximation.TargetInterval n) : ℕ := + let words := (OAI.EditApproximation.arithmeticMapWithWork (fun i => read i (states i)) (List.finRange M)).1 + OAI.EditApproximation.arithmeticMapAllocation (fun i => footprint i (states i)) (List.finRange M) + + OAI.EditApproximation.BinaryFraction.endpointConnectionAllocation r states + OAI.EditApproximation.BinaryFraction.sumListAllocation words + + OAI.EditApproximation.BinaryFraction.canonicalAddAllocation (OAI.EditApproximation.BinaryFraction.endpointConnectionWithWork r states).1 (OAI.EditApproximation.BinaryFraction.sumListWithWork words).1 + 0 + +def initialConeAllocation {n : ℕ} (sourceLength U : ℕ) (a L : OAI.EditApproximation.BinaryFraction) + (query center : OAI.EditApproximation.TargetInterval n) : ℕ := + let gap := (OAI.EditApproximation.BinaryFraction.stateGapWithWork sourceLength center).1 + let seed := (OAI.EditApproximation.BinaryFraction.scaledSeedWithWork U a gap).1 + let distance := (OAI.EditApproximation.BinaryFraction.endpointDistanceWithWork query center).1 + let spatial := (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork L distance).1 + OAI.EditApproximation.BinaryFraction.stateGapAllocation sourceLength center + OAI.EditApproximation.BinaryFraction.scaledSeedAllocation U a gap + + OAI.EditApproximation.BinaryFraction.endpointDistanceAllocation query center + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation L distance + OAI.EditApproximation.BinaryFraction.canonicalAddAllocation seed spatial + +def groupScaleSourceAllocation {M : ℕ} (k : ℕ) (h : OAI.EditApproximation.BinaryFraction) + (envelope values : Vector OAI.EditApproximation.BinaryFraction M) (draw : Fin k → Fin M × ℕ) + (allocation : Fin k → ℕ) : ℕ := + let indices := if k = M then (List.finRange M, 0) else OAI.EditApproximation.arithmeticMapWithWork draw (List.finRange k) + let factor := if k = M then (OAI.EditApproximation.BinaryFraction.one, 1) else OAI.EditApproximation.BinaryFraction.divWithWork (OAI.EditApproximation.BinaryFraction.nat M) (OAI.EditApproximation.BinaryFraction.nat k) + (if k = M then 0 else OAI.EditApproximation.arithmeticMapAllocation allocation (List.finRange k)) + + OAI.EditApproximation.BinaryFraction.groupIndexAllocation h envelope values indices.1 + + (if k = M then 0 else OAI.EditApproximation.BinaryFraction.divAllocation (OAI.EditApproximation.BinaryFraction.nat M) (OAI.EditApproximation.BinaryFraction.nat k)) + + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation factor.1 (OAI.EditApproximation.BinaryFraction.groupIndexWithWork h envelope values indices.1).1 + + Nat.size M + Nat.size k + +def gapGuardAllocation {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (envelope : Vector OAI.EditApproximation.BinaryFraction M) (rounded : Vector (OAI.EditApproximation.TargetInterval ny) M) (i : Fin M) : ℕ := + let sourceLength := (OAI.EditApproximation.binaryNaturalSubtractWithWork (OAI.EditApproximation.sourceChild parent i).hi (OAI.EditApproximation.sourceChild parent i).lo).1 + let gap := (OAI.EditApproximation.BinaryFraction.stateGapWithWork (OAI.EditApproximation.bitWordValue sourceLength) (rounded.get i)).1 + let bound := (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 2) (envelope.get i)).1 + OAI.EditApproximation.bitSubtractAllocation (OAI.EditApproximation.sourceChild parent i).hi.bits (OAI.EditApproximation.sourceChild parent i).lo.bits false + + OAI.EditApproximation.BinaryFraction.stateGapAllocation (OAI.EditApproximation.bitWordValue sourceLength) (rounded.get i) + + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation (OAI.EditApproximation.BinaryFraction.nat 2) (envelope.get i) + OAI.EditApproximation.BinaryFraction.leAllocation gap.absolute bound + +def wideMinimumReadWithWork {n M : ℕ} (r : OAI.EditApproximation.TargetInterval n) + (read : Fin M → OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) + (actions : List (Fin M → OAI.EditApproximation.TargetInterval n)) (hne : actions ≠ []) : OAI.EditApproximation.BinaryFraction × ℕ := + let fallback := OAI.EditApproximation.BinaryFraction.endpointScoreReadWithWork r read (actions.head hne) + let scores := OAI.EditApproximation.arithmeticMapWithWork (OAI.EditApproximation.BinaryFraction.endpointScoreReadWithWork r read) actions + let result := OAI.EditApproximation.BinaryFraction.minimumWithWork fallback.1 scores.1 + (result.1, fallback.2 + scores.2 + result.2 + 2) + +def groupMemberSourceWithWork {M T : ℕ} (scales : Fin T → OAI.EditApproximation.BinaryFraction) (count : Fin T → ℕ) + (connection : OAI.EditApproximation.BinaryFraction) (envelope values : Vector OAI.EditApproximation.BinaryFraction M) + (draw : ∀ s : Fin T, Fin (count s) → Fin M × ℕ) : OAI.EditApproximation.BinaryFraction × ℕ := + let terms := OAI.EditApproximation.arithmeticMapWithWork (fun s => OAI.EditApproximation.BinaryFraction.groupScaleSourceWithWork (count s) (scales s) + envelope values (draw s)) (List.finRange T) + let subtotal := OAI.EditApproximation.BinaryFraction.sumListWithWork terms.1 + let result := OAI.EditApproximation.BinaryFraction.canonicalAddWithWork connection subtotal.1 + (result.1, terms.2 + subtotal.2 + result.2 + 1) + +def wideActionsFromRepresentativesWithWork {nx ny : ℕ} (M : ℕ) + (parent : OAI.EditApproximation.TargetInterval nx) (representatives : List (ℕ × OAI.EditApproximation.TargetInterval ny)) (P : ℕ) : + List (OAI.EditApproximation.BinaryBellmanAction (OAI.EditApproximation.TargetInterval ny) (Fin M × OAI.EditApproximation.TargetInterval ny) M) × ℕ := + OAI.EditApproximation.arithmeticFlatMapWithWork (fun br => + let grids := OAI.EditApproximation.wideActionGridWithWork M parent br.2 br.1 P + let actions := OAI.EditApproximation.arithmeticMapWithWork (fun states => OAI.EditApproximation.BinaryFraction.endpointActionWithWork br.2 states.get) grids.1 + (actions.1, grids.2 + actions.2 + 1)) representatives + +def initialConeReadWithWork {n : ℕ} (sourceLength : ℕ) + (read : OAI.EditApproximation.TargetInterval n → List Bool × ℕ) (a L : OAI.EditApproximation.BinaryFraction) + (query center : OAI.EditApproximation.TargetInterval n) : OAI.EditApproximation.BinaryFraction × ℕ := + let seed := read center + let result := OAI.EditApproximation.BinaryFraction.initialConeWithWork sourceLength (fun _ => OAI.EditApproximation.bitWordValue seed.1) a L query center + (result.1, seed.2 + result.2) + +def wideMinimumReadAllocation {n M : ℕ} (r : OAI.EditApproximation.TargetInterval n) + (read : Fin M → OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) + (footprint : Fin M → OAI.EditApproximation.TargetInterval n → ℕ) + (actions : List (Fin M → OAI.EditApproximation.TargetInterval n)) (hne : actions ≠ []) : ℕ := + let fallback := (OAI.EditApproximation.BinaryFraction.endpointScoreReadWithWork r read (actions.head hne)).1 + let scores := (OAI.EditApproximation.arithmeticMapWithWork (OAI.EditApproximation.BinaryFraction.endpointScoreReadWithWork r read) actions).1 + OAI.EditApproximation.BinaryFraction.endpointScoreReadAllocation r read footprint (actions.head hne) + + OAI.EditApproximation.arithmeticMapAllocation (OAI.EditApproximation.BinaryFraction.endpointScoreReadAllocation r read footprint) actions + + OAI.EditApproximation.BinaryFraction.minimumAllocation fallback scores + 0 + +def groupMemberSourceAllocation {M T : ℕ} (scales : Fin T → OAI.EditApproximation.BinaryFraction) (count : Fin T → ℕ) + (connection : OAI.EditApproximation.BinaryFraction) (envelope values : Vector OAI.EditApproximation.BinaryFraction M) + (draw : ∀ s : Fin T, Fin (count s) → Fin M × ℕ) + (allocation : ∀ s : Fin T, Fin (count s) → ℕ) : ℕ := + let terms := (OAI.EditApproximation.arithmeticMapWithWork (fun s => OAI.EditApproximation.BinaryFraction.groupScaleSourceWithWork (count s) (scales s) + envelope values (draw s)) (List.finRange T)).1 + OAI.EditApproximation.arithmeticMapAllocation (fun s => OAI.EditApproximation.BinaryFraction.groupScaleSourceAllocation (count s) (scales s) envelope values (draw s) (allocation s)) (List.finRange T) + + OAI.EditApproximation.BinaryFraction.sumListAllocation terms + OAI.EditApproximation.BinaryFraction.canonicalAddAllocation connection (OAI.EditApproximation.BinaryFraction.sumListWithWork terms).1 + +def wideActionsFromRepresentativesAllocation {nx ny : ℕ} (M : ℕ) (parent : OAI.EditApproximation.TargetInterval nx) + (representatives : List (ℕ × OAI.EditApproximation.TargetInterval ny)) (P : ℕ) : ℕ := + OAI.EditApproximation.arithmeticFlatMapAllocation (fun br => + let grids := OAI.EditApproximation.wideActionGridWithWork M parent br.2 br.1 P + let actions := OAI.EditApproximation.arithmeticMapWithWork (fun states => OAI.EditApproximation.BinaryFraction.endpointActionWithWork br.2 states.get) grids.1 + (actions.1, grids.2 + actions.2 + 1)) + (fun br => OAI.EditApproximation.wideActionGridAllocation M parent br.2 br.1 P + + OAI.EditApproximation.arithmeticMapAllocation (fun states => OAI.EditApproximation.BinaryFraction.endpointActionAllocation br.2 states.get) + (OAI.EditApproximation.wideActionGridWithWork M parent br.2 br.1 P).1) representatives + +def representativeFromActionsReadWithWork {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (r : OAI.EditApproximation.TargetInterval ny) (sourceLength b : ℕ) (tau theta : OAI.EditApproximation.BinaryFraction) + (read : Fin M → OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) + (actions : List (Fin M → OAI.EditApproximation.TargetInterval ny)) : List (Fin M → OAI.EditApproximation.TargetInterval ny) × ℕ := + if hne : actions = [] then ([], 1) else + let Z := OAI.EditApproximation.BinaryFraction.wideMinimumReadWithWork r read actions hne + let positive := OAI.EditApproximation.BinaryFraction.ltWithWork OAI.EditApproximation.BinaryFraction.zero Z.1 + if positive.1 then + let gap := OAI.EditApproximation.BinaryFraction.stateGapWithWork sourceLength r + let velocity := OAI.EditApproximation.BinaryFraction.divWithWork gap.1 Z.1 + let result := OAI.EditApproximation.BinaryFraction.bandFromActionsReadWithWork parent r b tau theta velocity.1 read actions hne + (result.1, Z.2 + positive.2 + gap.2 + velocity.2 + result.2 + 3) + else ([], Z.2 + positive.2 + 2) + +def physicalContinuationReadWithWork {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (representatives : List (ℕ × OAI.EditApproximation.TargetInterval ny)) (P F : ℕ) + (delta fallback : OAI.EditApproximation.BinaryFraction) + (old current : Fin M × OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) + (groups online : List (OAI.EditApproximation.BinaryBellmanAction (OAI.EditApproximation.TargetInterval ny) (Fin M × OAI.EditApproximation.TargetInterval ny) M)) + (query : OAI.EditApproximation.TargetInterval ny) : OAI.EditApproximation.BinaryFraction × ℕ := + let wide := OAI.EditApproximation.BinaryFraction.wideActionsFromRepresentativesWithWork M parent representatives P + let L := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 128) (OAI.EditApproximation.BinaryFraction.nat F) + let result := OAI.EditApproximation.BinaryFraction.localContinuationReadWithWork OAI.EditApproximation.BinaryFraction.endpointDistanceWithWork L.1 delta fallback + old current query wide.1 groups online + (result.1, wide.2 + L.2 + result.2 + 1) + +def initialMinimumReadWithWork {n : ℕ} (sourceLength : ℕ) + (read : OAI.EditApproximation.TargetInterval n → List Bool × ℕ) (N F : ℕ) (a : OAI.EditApproximation.BinaryFraction) + (query : OAI.EditApproximation.TargetInterval n) (centers : List (OAI.EditApproximation.TargetInterval n)) : OAI.EditApproximation.BinaryFraction × ℕ := + let queryWord := read query + let zeroTest := OAI.EditApproximation.naturalEqualWithWork (OAI.EditApproximation.bitWordValue queryWord.1) 0 + if zeroTest.1 then (OAI.EditApproximation.BinaryFraction.zero, queryWord.2 + zeroTest.2 + 1) else + let L := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 32) (OAI.EditApproximation.BinaryFraction.nat F) + let coefficient := OAI.EditApproximation.BinaryFraction.canonicalAddWithWork L.1 OAI.EditApproximation.BinaryFraction.one + let fallback := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork coefficient.1 (OAI.EditApproximation.BinaryFraction.nat N) + let scores := OAI.EditApproximation.arithmeticMapWithWork (OAI.EditApproximation.BinaryFraction.initialConeReadWithWork sourceLength read a L.1 query) centers + let result := OAI.EditApproximation.BinaryFraction.minimumWithWork fallback.1 scores.1 + (result.1, queryWord.2 + zeroTest.2 + L.2 + coefficient.2 + fallback.2 + scores.2 + result.2 + + Nat.size F + Nat.size N + 6) + +def localWarmupReadKernelWithWork {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (N P F : ℕ) (a : OAI.EditApproximation.BinaryFraction) (initial : OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) + (child : Fin M × OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) (query : OAI.EditApproximation.TargetInterval ny) : + OAI.EditApproximation.BinaryFraction × ℕ := + let fallback := initial query + let representatives := OAI.EditApproximation.BinaryFraction.localRepresentativeReadWithWork N P F a initial query + let actions := OAI.EditApproximation.BinaryFraction.wideActionsFromRepresentativesWithWork M parent representatives.1 P + let L := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 128) (OAI.EditApproximation.BinaryFraction.nat F) + let result := OAI.EditApproximation.BinaryFraction.bellmanReadWithWork OAI.EditApproximation.BinaryFraction.endpointDistanceWithWork L.1 fallback.1 child query actions.1 + (result.1, fallback.2 + representatives.2 + actions.2 + L.2 + result.2 + 3) + +def representativeFromActionsReadAllocation {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (r : OAI.EditApproximation.TargetInterval ny) (sourceLength b : ℕ) (tau theta : OAI.EditApproximation.BinaryFraction) + (read : Fin M → OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) + (allocation : Fin M → OAI.EditApproximation.TargetInterval ny → ℕ) + (actions : List (Fin M → OAI.EditApproximation.TargetInterval ny)) : ℕ := + if hne : actions = [] then 0 else + let Z := (OAI.EditApproximation.BinaryFraction.wideMinimumReadWithWork r read actions hne).1 + OAI.EditApproximation.BinaryFraction.wideMinimumReadAllocation r read allocation actions hne + OAI.EditApproximation.BinaryFraction.ltAllocation OAI.EditApproximation.BinaryFraction.zero Z + + if (OAI.EditApproximation.BinaryFraction.ltWithWork OAI.EditApproximation.BinaryFraction.zero Z).1 then + OAI.EditApproximation.BinaryFraction.stateGapAllocation sourceLength r + OAI.EditApproximation.BinaryFraction.divAllocation (OAI.EditApproximation.BinaryFraction.stateGapWithWork sourceLength r).1 Z + + OAI.EditApproximation.BinaryFraction.bandFromActionsReadAllocation parent r b tau theta + (OAI.EditApproximation.BinaryFraction.divWithWork (OAI.EditApproximation.BinaryFraction.stateGapWithWork sourceLength r).1 Z).1 read allocation actions hne + else 0 + +def physicalContinuationReadAllocation {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (representatives : List (ℕ × OAI.EditApproximation.TargetInterval ny)) (P F : ℕ) (delta fallback : OAI.EditApproximation.BinaryFraction) + (old current : Fin M × OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) + (oldAllocation currentAllocation : Fin M × OAI.EditApproximation.TargetInterval ny → ℕ) + (groups online : List (OAI.EditApproximation.BinaryBellmanAction (OAI.EditApproximation.TargetInterval ny) (Fin M × OAI.EditApproximation.TargetInterval ny) M)) + (query : OAI.EditApproximation.TargetInterval ny) : ℕ := + OAI.EditApproximation.BinaryFraction.wideActionsFromRepresentativesAllocation M parent representatives P + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation (OAI.EditApproximation.BinaryFraction.nat 128) (OAI.EditApproximation.BinaryFraction.nat F) + + OAI.EditApproximation.BinaryFraction.localContinuationReadAllocation OAI.EditApproximation.BinaryFraction.endpointDistanceWithWork OAI.EditApproximation.BinaryFraction.endpointDistanceAllocation + (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 128) (OAI.EditApproximation.BinaryFraction.nat F)).1 delta fallback old current oldAllocation currentAllocation query + (OAI.EditApproximation.BinaryFraction.wideActionsFromRepresentativesWithWork M parent representatives P).1 groups online + +def localWarmupReadAllocation {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (N P F : ℕ) (a : OAI.EditApproximation.BinaryFraction) (initial : OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) + (initialAllocation : OAI.EditApproximation.TargetInterval ny → ℕ) (child : Fin M × OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) + (childAllocation : Fin M × OAI.EditApproximation.TargetInterval ny → ℕ) (query : OAI.EditApproximation.TargetInterval ny) : ℕ := + let representatives := (OAI.EditApproximation.BinaryFraction.localRepresentativeReadWithWork N P F a initial query).1 + let actions := (OAI.EditApproximation.BinaryFraction.wideActionsFromRepresentativesWithWork M parent representatives P).1 + initialAllocation query + OAI.EditApproximation.BinaryFraction.localRepresentativeReadAllocation N P F a initial initialAllocation query + + OAI.EditApproximation.BinaryFraction.wideActionsFromRepresentativesAllocation M parent representatives P + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation (OAI.EditApproximation.BinaryFraction.nat 128) (OAI.EditApproximation.BinaryFraction.nat F) + + OAI.EditApproximation.BinaryFraction.bellmanReadAllocation OAI.EditApproximation.BinaryFraction.endpointDistanceWithWork OAI.EditApproximation.BinaryFraction.endpointDistanceAllocation + (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 128) (OAI.EditApproximation.BinaryFraction.nat F)).1 (initial query).1 child childAllocation query actions + +def preparedRepresentativeReadWithWork {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (center : OAI.EditApproximation.TargetInterval ny) (sourceLength b P : ℕ) (tau theta : OAI.EditApproximation.BinaryFraction) + (read : Fin M → OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) : List (Fin M → OAI.EditApproximation.TargetInterval ny) × ℕ := + let wide := OAI.EditApproximation.wideActionGridWithWork M parent center b P + let result := OAI.EditApproximation.BinaryFraction.representativeFromActionsReadWithWork parent center sourceLength b tau theta read + (wide.1.map Vector.get) + (result.1, wide.2 + result.2 + wide.1.length + 1) + +def initialProgramReadWithWork {n : ℕ} (sourceLength N P F : ℕ) (A a : OAI.EditApproximation.BinaryFraction) + (read : OAI.EditApproximation.TargetInterval n → List Bool × ℕ) (query : OAI.EditApproximation.TargetInterval n) : OAI.EditApproximation.BinaryFraction × ℕ := + let centers := OAI.EditApproximation.BinaryFraction.initialCentersReadWithWork N P A read query + let result := OAI.EditApproximation.BinaryFraction.initialMinimumReadWithWork sourceLength read N F a query centers.1 + (result.1, centers.2 + result.2 + 1) + +def preparedRepresentativeReadAllocation {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (center : OAI.EditApproximation.TargetInterval ny) (sourceLength b P : ℕ) (tau theta : OAI.EditApproximation.BinaryFraction) + (read : Fin M → OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) + (allocation : Fin M → OAI.EditApproximation.TargetInterval ny → ℕ) : ℕ := + let wide := (OAI.EditApproximation.wideActionGridWithWork M parent center b P).1 + OAI.EditApproximation.wideActionGridAllocation M parent center b P + wide.length + + OAI.EditApproximation.BinaryFraction.representativeFromActionsReadAllocation parent center sourceLength b tau theta read allocation (wide.map Vector.get) + +def queryRefinementFinishAllocation {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) (N P F : ℕ) + (a delta : OAI.EditApproximation.BinaryFraction) (initial : OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) + (initialAllocation : OAI.EditApproximation.TargetInterval ny → ℕ) (t : ℕ) + (earlierKeys : List (Fin M × ℕ × OAI.EditApproximation.TargetInterval ny)) (earlierWords : List OAI.EditApproximation.BinaryFraction) + (groups online : List (OAI.EditApproximation.BinaryBellmanAction (OAI.EditApproximation.TargetInterval ny) (Fin M × OAI.EditApproximation.TargetInterval ny) M)) + (currentKeys : List (Fin M × OAI.EditApproximation.TargetInterval ny)) (currentWords : List OAI.EditApproximation.BinaryFraction) + (query : OAI.EditApproximation.TargetInterval ny) : ℕ := + initialAllocation query + OAI.EditApproximation.BinaryFraction.localRepresentativeReadAllocation N P F a initial initialAllocation query + + OAI.EditApproximation.BinaryFraction.physicalContinuationReadAllocation parent (OAI.EditApproximation.BinaryFraction.localRepresentativeReadWithWork N P F a initial query).1 P F delta (initial query).1 + (OAI.EditApproximation.BinaryFraction.queryHistoryReadWithWork earlierKeys earlierWords (t - 1)) + (fun input => OAI.EditApproximation.BinaryFraction.queryChildReadWithWork currentKeys currentWords input.1 input.2) + (OAI.EditApproximation.BinaryFraction.queryHistoryReadAllocation earlierKeys earlierWords (t - 1)) + (fun input => OAI.EditApproximation.BinaryFraction.queryChildReadAllocation currentKeys currentWords input.1 input.2) groups online query + +def queryOnlineRangeWithWork {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (P exponent H : ℕ) (tau : OAI.EditApproximation.BinaryFraction) + (child : Fin M → OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) + (key : ℕ × OAI.EditApproximation.TargetInterval ny) : ℕ × ℕ := + let width := OAI.EditApproximation.saturatingSubtractWithWork parent.hi parent.lo + let band := OAI.EditApproximation.BinaryFraction.preparedRepresentativeReadWithWork parent key.2 (OAI.EditApproximation.bitWordValue width.1) key.1 P + tau (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) child + let setup := OAI.EditApproximation.BinaryFraction.onlineIndexSetupWithWork H band.1 + let power := OAI.EditApproximation.bitPowerWithWork setup.1.bits 80 + let mass := OAI.EditApproximation.triangularMassWithWork (OAI.EditApproximation.bitWordValue power.1) + (OAI.EditApproximation.bitWordValue mass.1, width.2 + band.2 + setup.2 + power.2 + mass.2 + 4) + +def cachedInitialProgramReadWithWork {n : ℕ} (sourceLength N P F : ℕ) (A a : OAI.EditApproximation.BinaryFraction) + (read : OAI.EditApproximation.TargetInterval n → List Bool × ℕ) (query : OAI.EditApproximation.TargetInterval n) : OAI.EditApproximation.BinaryFraction × ℕ := + OAI.EditApproximation.BinaryFraction.finishCachedWithWork (OAI.EditApproximation.BinaryFraction.initialProgramReadWithWork sourceLength N P F A a read query) + [true] (by decide) 0 + +def queryOnlineRangeAllocation {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (P exponent H : ℕ) (tau : OAI.EditApproximation.BinaryFraction) + (child : Fin M → OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) + (allocation : Fin M → OAI.EditApproximation.TargetInterval ny → ℕ) (key : ℕ × OAI.EditApproximation.TargetInterval ny) : ℕ := + let width := (OAI.EditApproximation.saturatingSubtractWithWork parent.hi parent.lo).1 + let band := (OAI.EditApproximation.BinaryFraction.preparedRepresentativeReadWithWork parent key.2 (OAI.EditApproximation.bitWordValue width) key.1 P + tau (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) child).1 + let setup := (OAI.EditApproximation.BinaryFraction.onlineIndexSetupWithWork H band).1 + let power := (OAI.EditApproximation.bitPowerWithWork setup.bits 80).1 + OAI.EditApproximation.saturatingSubtractAllocation parent.hi parent.lo + + OAI.EditApproximation.BinaryFraction.preparedRepresentativeReadAllocation parent key.2 (OAI.EditApproximation.bitWordValue width) key.1 P + tau (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) child allocation + OAI.EditApproximation.BinaryFraction.onlineIndexSetupAllocation H band + + OAI.EditApproximation.bitPowerAllocation setup.bits 80 + OAI.EditApproximation.triangularMassAllocation (OAI.EditApproximation.bitWordValue power) + + +end OAI.EditApproximation.BinaryFraction +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.PositionCounts + + +def count : OAI.EditApproximation.PositionCounts → ℕ + | .empty => 0 + | .node n _ _ => n + +def left : OAI.EditApproximation.PositionCounts → OAI.EditApproximation.PositionCounts + | .empty => .empty + | .node _ l _ => l + +def right : OAI.EditApproximation.PositionCounts → OAI.EditApproximation.PositionCounts + | .empty => .empty + | .node _ _ r => r + +def storageBits : OAI.EditApproximation.PositionCounts → ℕ + | .empty => 0 + | .node n l r => Nat.size n + 3 + l.storageBits + r.storageBits + +def add (tree : OAI.EditApproximation.PositionCounts) : ℕ → ℕ → OAI.EditApproximation.PositionCounts + | 0, _ => .node (tree.count + 1) tree.left tree.right + | d + 1, i => + if i < 2 ^ d then + .node (tree.count + 1) (tree.left.add d i) tree.right + else .node (tree.count + 1) tree.left (tree.right.add d (i - 2 ^ d)) + +def addWithWork (tree : OAI.EditApproximation.PositionCounts) : ℕ → ℕ → OAI.EditApproximation.PositionCounts × ℕ + | 0, _ => (.node (tree.count + 1) tree.left tree.right, 1) + | d + 1, i => + if i < 2 ^ d then + let result := tree.left.addWithWork d i + (.node (tree.count + 1) result.1 tree.right, result.2 + 2) + else + let result := tree.right.addWithWork d (i - 2 ^ d) + (.node (tree.count + 1) tree.left result.1, result.2 + 2) + +def prefixWithWork (tree : OAI.EditApproximation.PositionCounts) : ℕ → ℕ → ℕ × ℕ + | 0, t => (if t = 0 then 0 else tree.count, 1) + | d + 1, t => + if t ≤ 2 ^ d then + let result := tree.left.prefixWithWork d t + (result.1, result.2 + 2) + else + let result := tree.right.prefixWithWork d (t - 2 ^ d) + (tree.left.count + result.1, result.2 + 2) + + +end OAI.EditApproximation.PositionCounts +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BitQuery.Footprint + + +def bind {ι : Type u_1} {α : Type u_2} {β : Type u_3} {program : OAI.EditApproximation.BitQuery ι α} (heap : OAI.EditApproximation.BitQuery.Footprint program) + (next : α → OAI.EditApproximation.BitQuery ι β) (allocation : ∀ value, OAI.EditApproximation.BitQuery.Footprint (next value)) : + OAI.EditApproximation.BitQuery.Footprint (program.bind next) := + match heap with + | .done result => allocation result + | .read key continuation stored => .read key _ (fun word => (stored word).bind next allocation) + | .charge localCells tail => .charge localCells (tail.bind next allocation) + +def compute {ι : Type u_1} {β : Type u_2} (execution : β × ℕ) (allocation : ℕ) : + OAI.EditApproximation.BitQuery.Footprint (OAI.EditApproximation.BitQuery.compute (ι := ι) execution) := + .charge allocation (.done execution.1) + +def chargeOf {ι : Type u_1} {β : Type u_2} {steps : ℕ} {program : OAI.EditApproximation.BitQuery ι β} (allocation : ℕ) + (tail : OAI.EditApproximation.BitQuery.Footprint program) : OAI.EditApproximation.BitQuery.Footprint (.charge steps program) := + .charge allocation tail + +def runCells {ι : Type u_1} {κ : Type u_2} + (ask : ι → OAI.EditApproximation.BinaryMemo OAI.EditApproximation.BinaryFraction → OAI.EditApproximation.BitRecursiveMemoResult κ) + (childCells : ι → OAI.EditApproximation.BinaryMemo OAI.EditApproximation.BinaryFraction → ℕ) + {program : OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction} : OAI.EditApproximation.BitQuery.Footprint program → OAI.EditApproximation.BinaryMemo OAI.EditApproximation.BinaryFraction → ℕ + | .done _, _ => 0 + | .read key _ continuation, memory => + let first := ask key memory + 3 + childCells key memory + (continuation first.value).runCells ask childCells first.memory + | .charge cells next, memory => cells + next.runCells ask childCells memory + +def computeOf {ι : Type u_1} {β : Type u_2} (execution : β × ℕ) (allocation : ℕ) : + OAI.EditApproximation.BitQuery.Footprint (OAI.EditApproximation.BitQuery.compute (ι := ι) execution) := + OAI.EditApproximation.BitQuery.Footprint.compute execution allocation + +def collect {ι : Type u_1} {κ : Type u_2} {β : Type u_3} (reader : κ → OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (allocation : ∀ key, OAI.EditApproximation.BitQuery.Footprint (reader key)) : + (inputs : List κ) → (next : List OAI.EditApproximation.BinaryFraction → OAI.EditApproximation.BitQuery ι β) → + (∀ words, OAI.EditApproximation.BitQuery.Footprint (next words)) → OAI.EditApproximation.BitQuery.Footprint (OAI.EditApproximation.BitQuery.collect reader inputs next) + | [], _, continuation => continuation [] + | key :: rest, next, continuation => + (allocation key).bind _ fun word => .charge 1 + (collect reader allocation rest (fun words => next (word :: words)) + (fun words => continuation (word :: words))) + +def mapKeysWithWork {ι : Type u_1} {κ : Type u_2} {β : Type u_3} (f : ι → κ × ℕ) (allocation : ι → ℕ) + {program : OAI.EditApproximation.BitQuery ι β} (heap : OAI.EditApproximation.BitQuery.Footprint program) : OAI.EditApproximation.BitQuery.Footprint (program.mapKeysWithWork f) := + match heap with + | .done result => .done result + | .read key next continuation => + OAI.EditApproximation.BitQuery.Footprint.chargeOf (allocation key) + (.read (f key).1 _ (fun word => (continuation word).mapKeysWithWork f allocation)) + | .charge localCells next => .charge localCells (next.mapKeysWithWork f allocation) + +def restrictWithWork {ι : Type u_1} (P : ι → Prop) + (test : ι → Bool × ℕ) (htest : ∀ key, (test key).1 = true ↔ P key) + (allocation : ι → ℕ) + {program : OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction} (heap : OAI.EditApproximation.BitQuery.Footprint program) : + OAI.EditApproximation.BitQuery.Footprint (program.restrictWithWork P test htest) := + match heap with + | .done result => .done result + | .charge localCells next => .charge localCells (next.restrictWithWork P test htest allocation) + | .read key next continuation => + OAI.EditApproximation.BitQuery.Footprint.chargeOf (allocation key) + (by + split + · exact .read _ _ (fun word => (continuation word).restrictWithWork P test htest allocation) + · exact (continuation (OAI.EditApproximation.BinaryFraction.nat 0)).restrictWithWork P test htest allocation) + +def normalize {ι : Type u_1} {program : OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction} (heap : OAI.EditApproximation.BitQuery.Footprint program) + (base : List Bool) (hbase : 0 < OAI.EditApproximation.bitWordValue base) (remaining : ℕ) : + OAI.EditApproximation.BitQuery.Footprint (program.normalize base hbase remaining) := + heap.bind _ fun word => OAI.EditApproximation.BitQuery.Footprint.computeOf (OAI.EditApproximation.BinaryFraction.finishCachedWithWork (word, 0) base hbase remaining) + (OAI.EditApproximation.BinaryFraction.finishCachedAllocation (word, 0) 0 base hbase remaining) + + +end OAI.EditApproximation.BitQuery.Footprint +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation + + +def bandActionPredicate {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (r : OAI.EditApproximation.TargetInterval ny) (b : ℕ) (tau theta velocity : ℚ) + (actions : List (Fin M → OAI.EditApproximation.TargetInterval ny)) (hnonempty : actions ≠ []) + (child : Fin M → OAI.EditApproximation.TargetInterval ny → ℚ) (states : Fin M → OAI.EditApproximation.TargetInterval ny) : Prop := + OAI.EditApproximation.endpointActionConnection r states = 0 ∧ + (∀ i, Nat.dist (r.lo + ((OAI.EditApproximation.sourceChild parent i).lo - parent.lo)) (states i).lo ≤ 6 * b ∧ + Nat.dist (r.lo + ((OAI.EditApproximation.sourceChild parent i).hi - parent.lo)) (states i).hi ≤ 6 * b) ∧ + ∀ j : Fin M, 0 < j.val → + |bandCutShift parent states j - ((r.lo : ℚ) - parent.lo) - velocity * + OAI.EditApproximation.rationalWidePrefixMinimum parent r actions hnonempty child j.val (OAI.EditApproximation.bandCutShift parent states j)| ≤ + tau * theta * b / M + +def queryOnlineSourceGather {ι : Type u_1} {β : Type u_2} {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (N P F exponent H : ℕ) (hP : 0 < P) (tau a : OAI.EditApproximation.BinaryFraction) + (initial : OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) + (child : Fin M → OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) (q : OAI.EditApproximation.TargetInterval ny) + (reader : (ℕ × OAI.EditApproximation.TargetInterval ny) → ℕ → OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (next : List (ℕ × OAI.EditApproximation.TargetInterval ny) → List OAI.EditApproximation.BinaryFraction → OAI.EditApproximation.BitQuery ι β) : OAI.EditApproximation.BitQuery ι β := + let query := initial q + .charge query.2 ((OAI.EditApproximation.BitQuery.compute (OAI.EditApproximation.BinaryFraction.queryOnlineKeysWithWork N P F hP a query.1 q)).bind + fun keys => OAI.EditApproximation.BitQuery.collect (fun key => + (OAI.EditApproximation.BitQuery.compute (OAI.EditApproximation.BinaryFraction.queryOnlineRangeWithWork parent P exponent H tau child key)).bind + (reader key)) keys (next keys)) + +def coarseLabelChildren {B d : ℕ} {α : Type u_1} (Q lam allowance : ℚ) + (work : OAI.EditApproximation.CoarseSourceTree B α d → OAI.EditApproximation.CoarseThresholdDraws B d → ℚ → ℕ) : + List (OAI.EditApproximation.CoarseSourceTree B α d × Fin B × OAI.EditApproximation.CoarseThresholdDraws B d) → ℕ + | [] => 0 + | (child, draw, below) :: rest => + work child below (lam * OAI.EditApproximation.coarseChildThreshold B Q allowance draw) + + coarseLabelChildren Q lam allowance work rest + +instance bandActionPredicateDecidable {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (r : OAI.EditApproximation.TargetInterval ny) (b : ℕ) (tau theta velocity : ℚ) + (actions : List (Fin M → OAI.EditApproximation.TargetInterval ny)) (hnonempty : actions ≠ []) + (child : Fin M → OAI.EditApproximation.TargetInterval ny → ℚ) (states : Fin M → OAI.EditApproximation.TargetInterval ny) : + Decidable (OAI.EditApproximation.bandActionPredicate parent r b tau theta velocity actions hnonempty child states) := by + unfold OAI.EditApproximation.bandActionPredicate + infer_instance + +def computedBandActions {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (r : OAI.EditApproximation.TargetInterval ny) (b P : ℕ) (tau theta velocity : ℚ) + (child : Fin M → OAI.EditApproximation.TargetInterval ny → ℚ) : List (Fin M → OAI.EditApproximation.TargetInterval ny) := + let actions := OAI.EditApproximation.wideActionList M parent r b P + if h : actions = [] then [] else + if |velocity| ≤ 1 - tau then + actions.filter (fun states => decide (OAI.EditApproximation.bandActionPredicate parent r b tau theta velocity actions h child states)) + else [] + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open Finset + +def rationalEndpointActionValue {ny M : ℕ} (r : OAI.EditApproximation.TargetInterval ny) + (states : Fin M → OAI.EditApproximation.TargetInterval ny) (child : Fin M → OAI.EditApproximation.TargetInterval ny → ℚ) : ℚ := + OAI.EditApproximation.endpointActionConnection r states + ∑ i, child i (states i) + +def rationalActualWideActions {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (representatives : List (ℕ × OAI.EditApproximation.TargetInterval ny)) (P : ℕ) : + List (OAI.EditApproximation.RationalBellmanAction (OAI.EditApproximation.TargetInterval ny) (Fin M × OAI.EditApproximation.TargetInterval ny) M) := + representatives.flatMap fun br => (OAI.EditApproximation.wideActionList M parent br.2 br.1 P).map fun states => + ⟨br.2, OAI.EditApproximation.endpointActionConnection br.2 states, fun i => (i, states i)⟩ + +def groupQueriedChildLabels (M Q b : ℕ) (h : ℚ) + (draw : Fin (OAI.EditApproximation.groupSampleCount M Q b h) → Fin M) : Finset (Fin M) := + if OAI.EditApproximation.groupSampleCount M Q b h = M then univ else univ.image draw + +def rationalWideActionMinimum {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (r : OAI.EditApproximation.TargetInterval ny) (b P : ℕ) (hnonempty : OAI.EditApproximation.wideActionList M parent r b P ≠ []) + (child : Fin M → OAI.EditApproximation.TargetInterval ny → ℚ) : ℚ := + OAI.EditApproximation.rationalMinimum (OAI.EditApproximation.rationalEndpointActionValue r ((OAI.EditApproximation.wideActionList M parent r b P).head hnonempty) child) + ((OAI.EditApproximation.wideActionList M parent r b P).map fun states => OAI.EditApproximation.rationalEndpointActionValue r states child) + +def groupCurrentInputCover {α : Type u_1} (source target : List α) {M : ℕ} + (parent : OAI.EditApproximation.TargetInterval source.length) (b exponent Q : ℕ) (cell : ℕ × ℕ) (h : ℚ) + (draw : Fin (OAI.EditApproximation.groupSampleCount M Q b h) → Fin M) : Finset (Fin M × OAI.EditApproximation.TargetInterval target.length) := + (OAI.EditApproximation.groupQueriedChildLabels M Q b h draw).biUnion fun i => + (OAI.EditApproximation.groupRoundedStateList source target parent b exponent cell i h).toFinset.image fun r => (i, r) + +def representativeBandActions {α : Type u_1} (source target : List α) + {M : ℕ} (parent : OAI.EditApproximation.TargetInterval source.length) (r : OAI.EditApproximation.TargetInterval target.length) + (b P : ℕ) (tau theta : ℚ) (child : Fin M → OAI.EditApproximation.TargetInterval target.length → ℚ) : + List (Fin M → OAI.EditApproximation.TargetInterval target.length) := + if h : OAI.EditApproximation.wideActionList M parent r b P = [] then [] else + let Z := OAI.EditApproximation.rationalWideActionMinimum parent r b P h child + if 0 < Z then + OAI.EditApproximation.computedBandActions parent r b P tau theta + (OAI.EditApproximation.rationalStateGap (OAI.EditApproximation.substring source parent.lo parent.hi) target r / Z) child + else [] + +structure UnskippedBand {α : Type u_1} (source target : List α) {M : ℕ} + (parent : OAI.EditApproximation.TargetInterval source.length) (b P thetaExponent : ℕ) + (tau F : ℚ) (child initial : Fin M → OAI.EditApproximation.TargetInterval target.length → ℚ) where + center : OAI.EditApproximation.TargetInterval target.length + nonempty : OAI.EditApproximation.representativeBandActions source target parent center b P tau + ((2 : ℚ) ^ (-(thetaExponent : ℤ))) child ≠ [] + sum_guard : (∑ i, OAI.EditApproximation.bandChildEnvelope b (OAI.EditApproximation.representativeBandActions source target parent center b P tau + ((2 : ℚ) ^ (-(thetaExponent : ℤ))) child) initial i) ≤ 64 * F * b + wide_guard : OAI.EditApproximation.canonicalRoundedBandAction thetaExponent b + (OAI.EditApproximation.representativeBandActions source target parent center b P tau + ((2 : ℚ) ^ (-(thetaExponent : ℤ))) child) nonempty initial ∈ OAI.EditApproximation.wideActionList M parent center b P + imbalance_guard : ∀ i, |rationalStateGap + (OAI.EditApproximation.substring source (OAI.EditApproximation.sourceChild parent i).lo (OAI.EditApproximation.sourceChild parent i).hi) target + (OAI.EditApproximation.canonicalRoundedBandAction thetaExponent b + (OAI.EditApproximation.representativeBandActions source target parent center b P tau + ((2 : ℚ) ^ (-(thetaExponent : ℤ))) child) nonempty initial i)| ≤ + 2 * OAI.EditApproximation.bandChildEnvelope b (OAI.EditApproximation.representativeBandActions source target parent center b P tau + ((2 : ℚ) ^ (-(thetaExponent : ℤ))) child) initial i + +def keyedOnlineBandG {α : Type u_1} (source target : List α) {M : ℕ} + (parent : OAI.EditApproximation.TargetInterval source.length) (P exponent H b : ℕ) (tau : ℚ) + (child : Fin M → OAI.EditApproximation.TargetInterval target.length → ℚ) (r : OAI.EditApproximation.TargetInterval target.length) : ℕ := + H + (OAI.EditApproximation.bandCoordinates (OAI.EditApproximation.representativeBandActions source target parent r b P tau + ((2 : ℚ) ^ (-(exponent : ℤ))) child).toFinset).card + 2 + +def testUnskippedBand {α : Type u_1} (source target : List α) {M : ℕ} + (parent : OAI.EditApproximation.TargetInterval source.length) (b P thetaExponent : ℕ) + (tau F : ℚ) (child initial : Fin M → OAI.EditApproximation.TargetInterval target.length → ℚ) + (center : OAI.EditApproximation.TargetInterval target.length) : + Option (OAI.EditApproximation.UnskippedBand source target parent b P thetaExponent tau F child initial) := + let band := OAI.EditApproximation.representativeBandActions source target parent center b P tau + ((2 : ℚ) ^ (-(thetaExponent : ℤ))) child + if hband : band = [] then none else + if hsum : (∑ i, OAI.EditApproximation.bandChildEnvelope b band initial i) ≤ 64 * F * b then + let rounded := OAI.EditApproximation.canonicalRoundedBandAction thetaExponent b band hband initial + if hwide : rounded ∈ OAI.EditApproximation.wideActionList M parent center b P then + if hgap : ∀ i, |rationalStateGap + (OAI.EditApproximation.substring source (OAI.EditApproximation.sourceChild parent i).lo (OAI.EditApproximation.sourceChild parent i).hi) target (rounded i)| ≤ + 2 * OAI.EditApproximation.bandChildEnvelope b band initial i then + some ⟨center, hband, hsum, hwide, hgap⟩ + else none + else none + else none + +def unskippedBandList {α : Type u_1} (source target : List α) {M : ℕ} + (parent : OAI.EditApproximation.TargetInterval source.length) (b P thetaExponent : ℕ) + (tau F : ℚ) (child initial : Fin M → OAI.EditApproximation.TargetInterval target.length → ℚ) + (centers : List (OAI.EditApproximation.TargetInterval target.length)) : + List (OAI.EditApproximation.UnskippedBand source target parent b P thetaExponent tau F child initial) := + centers.filterMap (OAI.EditApproximation.testUnskippedBand source target parent b P thetaExponent tau F child initial) + +def keyedOnlineCandidate {α : Type u_1} (source target : List α) {M : ℕ} + (parent : OAI.EditApproximation.TargetInterval source.length) (P F exponent H b : ℕ) (tau eta kappa : ℚ) + (child initial : Fin M → OAI.EditApproximation.TargetInterval target.length → ℚ) + (children : OAI.EditApproximation.PhysicalChildTables M target.length) (t : ℕ) + (r : OAI.EditApproximation.TargetInterval target.length) (integer : ℕ) : + Option (OAI.EditApproximation.PhysicalRationalAction M target.length) := by + have proof_optimizerTriangularMass_succ_66 (K : ℕ) : + OAI.EditApproximation.optimizerTriangularMass (K + 1) = OAI.EditApproximation.optimizerTriangularMass K + (K + 1) := by + unfold OAI.EditApproximation.optimizerTriangularMass + rw [sum_range_succ] + have proof_optimizerTriangularMass_twice_67 (K : ℕ) : + 2 * OAI.EditApproximation.optimizerTriangularMass K = K * (K + 1) := by + induction K with + | zero => simp [OAI.EditApproximation.optimizerTriangularMass] + | succ K ih => + rw [proof_optimizerTriangularMass_succ_66] + nlinarith + have proof_optimizerTriangularMass_positive_77 (K : ℕ) (hK : LT.lt.{0} 0 K) : + 0 < OAI.EditApproximation.optimizerTriangularMass K := by + have hproduct : 0 < K * (K + 1) := Nat.mul_pos hK (by omega) + rw [← proof_optimizerTriangularMass_twice_67 K] at hproduct + omega + have proof_keyedOnlineBandG_positive_78 {α : Type u_1} (source : List.{u_1} α) (target : List.{u_1} α) {M : ℕ} (parent : OAI.EditApproximation.TargetInterval (List.length.{u_1} source)) (P : ℕ) (exponent : ℕ) (H : ℕ) (b : ℕ) (tau : ℚ) (child : Fin M → OAI.EditApproximation.TargetInterval (List.length.{u_1} target) → ℚ) (r : OAI.EditApproximation.TargetInterval (List.length.{u_1} target)) : + 0 < OAI.EditApproximation.keyedOnlineBandG source target parent P exponent H b tau child r := by + unfold OAI.EditApproximation.keyedOnlineBandG + omega + exact + let band := OAI.EditApproximation.representativeBandActions source target parent r b P tau + ((2 : ℚ) ^ (-(exponent : ℤ))) child + let envelope := OAI.EditApproximation.bandChildEnvelope b band initial + let G := OAI.EditApproximation.keyedOnlineBandG source target parent P exponent H b tau child r + let K := G ^ 80 + let accepted := OAI.EditApproximation.boundedOnlineInteger (OAI.EditApproximation.optimizerTriangularMass K) + (proof_optimizerTriangularMass_positive_77 _ + (pow_pos (proof_keyedOnlineBandG_positive_78 source target parent P exponent H b tau child r) 80)) integer + if hband : band = [] then none else + match OAI.EditApproximation.testUnskippedBand source target parent b P exponent tau F child initial r with + | none => none + | some _ => some (OAI.EditApproximation.sharedBandRationalAction r + (OAI.EditApproximation.finiteOptimizerActionDraw band hband envelope + (OAI.EditApproximation.rationalOnlineLinear eta kappa + (OAI.EditApproximation.childGain envelope (fun s coordinate => children coordinate.1 s coordinate.2)) + (OAI.EditApproximation.childDecrement envelope (fun s coordinate => children coordinate.1 s coordinate.2)) t) + G K accepted)) + +def cellUnskippedBands {α : Type u_1} (source target : List α) {M : ℕ} + (parent : OAI.EditApproximation.TargetInterval source.length) (b P F thetaExponent : ℕ) (tau a : ℚ) + (parentInitial : OAI.EditApproximation.TargetInterval target.length → ℚ) + (child initial : Fin M → OAI.EditApproximation.TargetInterval target.length → ℚ) (cell : ℕ × ℕ) := + OAI.EditApproximation.unskippedBandList source target parent b P thetaExponent tau F child initial + (OAI.EditApproximation.cellRepresentativeStates target.length P F b a parentInitial + ((2 : ℚ) ^ (-(thetaExponent : ℤ))) cell) + +def localOnlineCandidates {α : Type u_1} (source target : List α) {M : ℕ} + (parent : OAI.EditApproximation.TargetInterval source.length) (N P F exponent H : ℕ) (tau a eta kappa : ℚ) + (parentInitial : OAI.EditApproximation.TargetInterval target.length → ℚ) + (child initial : Fin M → OAI.EditApproximation.TargetInterval target.length → ℚ) + (children : OAI.EditApproximation.PhysicalChildTables M target.length) (t : ℕ) + (integer : ℕ → OAI.EditApproximation.TargetInterval target.length → ℕ) + (q : OAI.EditApproximation.TargetInterval target.length) : List (OAI.EditApproximation.PhysicalRationalAction M target.length) := + (OAI.EditApproximation.dyadicQueryWindow N (parentInitial q) a F).filterMap fun b => + let r := OAI.EditApproximation.roundInterval (OAI.EditApproximation.seedGridSpacing b P) q + if (b : ℚ) / (4 * a) ≤ parentInitial r ∧ parentInitial r ≤ 8 * F * b then + OAI.EditApproximation.keyedOnlineCandidate source target parent P F exponent H b tau eta kappa + child initial children t r (integer b r) + else none + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BinaryMemo +variable {α : Type u_1} + +def value : OAI.EditApproximation.BinaryMemo α → Option α + | .empty => none + | .node v _ _ => v + +def left : OAI.EditApproximation.BinaryMemo α → OAI.EditApproximation.BinaryMemo α + | .empty => .empty + | .node _ l _ => l + +def right : OAI.EditApproximation.BinaryMemo α → OAI.EditApproximation.BinaryMemo α + | .empty => .empty + | .node _ _ r => r + +def lookup (tree : OAI.EditApproximation.BinaryMemo α) : List Bool → Option α + | [] => tree.value + | false :: rest => tree.left.lookup rest + | true :: rest => tree.right.lookup rest + +def insert (tree : OAI.EditApproximation.BinaryMemo α) : List Bool → α → OAI.EditApproximation.BinaryMemo α + | [], a => .node (some a) tree.left tree.right + | false :: rest, a => .node tree.value (tree.left.insert rest a) tree.right + | true :: rest, a => .node tree.value tree.left (tree.right.insert rest a) + +def lookupCosted (tree : OAI.EditApproximation.BinaryMemo α) : List Bool → Option α × ℕ + | [] => (tree.value, 1) + | false :: rest => + let result := tree.left.lookupCosted rest + (result.1, result.2 + 1) + | true :: rest => + let result := tree.right.lookupCosted rest + (result.1, result.2 + 1) + +def insertCosted (tree : OAI.EditApproximation.BinaryMemo α) : List Bool → α → OAI.EditApproximation.BinaryMemo α × ℕ + | [], a => (.node (some a) tree.left tree.right, 1) + | false :: rest, a => + let result := tree.left.insertCosted rest a + (.node tree.value result.1 tree.right, result.2 + 1) + | true :: rest, a => + let result := tree.right.insertCosted rest a + (.node tree.value tree.left result.1, result.2 + 1) + + +end OAI.EditApproximation.BinaryMemo +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation + + +def rankedMemoEvaluate {κ : Type u_1} (rank : κ → ℕ) + (program : (key : κ) → OAI.EditApproximation.FiniteQuery {child : κ // rank child < rank key}) + (bits : ℕ) (encode : κ → ℕ) (key : κ) (memory : OAI.EditApproximation.BinaryMemo ℚ) : OAI.EditApproximation.RecursiveMemoResult κ := + let found := memory.lookupCosted (OAI.EditApproximation.binaryMemoKey bits (encode key)) + match found.1 with + | some result => ⟨result, memory, [], found.2, 1⟩ + | none => + let result := OAI.EditApproximation.FiniteQuery.run (fun child previous => + rankedMemoEvaluate rank program bits encode child.val previous) (program key) memory + let stored := result.memory.insertCosted (OAI.EditApproximation.binaryMemoKey bits (encode key)) result.value + ⟨result.value, stored.1, key :: result.freshKeys, + found.2 + result.dictionaryVisits + stored.2, result.requests + 1⟩ +termination_by rank key +decreasing_by exact child.property + +def localWarmupStepQuery {ι : Type u_1} {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (N P F : ℕ) (a : ℚ) (initialRead : OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.FiniteQuery ι) + (childRead : Fin M × OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.FiniteQuery ι) (q : OAI.EditApproximation.TargetInterval ny) : + OAI.EditApproximation.FiniteQuery ι := + OAI.EditApproximation.FiniteQuery.bind (initialRead q) fun value => + let centers := OAI.EditApproximation.rawRefinementCenters N P F a value q + OAI.EditApproximation.FiniteQuery.collect initialRead centers fun answers => + let initial := fun r => if r = q then value else OAI.EditApproximation.finiteAnswerTable centers answers r + let representatives := OAI.EditApproximation.localRefinementRepresentatives N P F a initial q + let inputs := OAI.EditApproximation.wideWarmupInputs (M := M) parent P representatives + OAI.EditApproximation.FiniteQuery.collect childRead inputs fun values => + .done (OAI.EditApproximation.rationalBellman initial (fun q r => OAI.EditApproximation.targetEndpointDistance q r) (128 * F) + (OAI.EditApproximation.rationalActualWideActions parent representatives P) (OAI.EditApproximation.finiteAnswerTable inputs values) q) + +def keyedOnlineSourceRange {α : Type u_1} (source target : List α) {M : ℕ} + (parent : OAI.EditApproximation.TargetInterval source.length) (P exponent H : ℕ) (tau : ℚ) + (child : Fin M → OAI.EditApproximation.TargetInterval target.length → ℚ) (key : ℕ × OAI.EditApproximation.TargetInterval target.length) : ℕ := + OAI.EditApproximation.optimizerTriangularMass (OAI.EditApproximation.keyedOnlineBandG source target parent P exponent H key.1 tau child key.2 ^ 80) + +def occurrenceBuild (symbolBits positionBits : ℕ) : List (ℕ × ℕ) → OAI.EditApproximation.BinaryMemo OAI.EditApproximation.PositionCounts + | [] => .empty + | e :: es => + let table := occurrenceBuild symbolBits positionBits es + let key := OAI.EditApproximation.binaryMemoKey symbolBits e.1 + let old := (table.lookup key).getD .empty + table.insert key (old.add positionBits e.2) + +def occurrenceBuildWithWork (symbolBits positionBits : ℕ) : + List (ℕ × ℕ) → OAI.EditApproximation.BinaryMemo OAI.EditApproximation.PositionCounts × ℕ + | [] => (.empty, 0) + | e :: es => + let previous := occurrenceBuildWithWork symbolBits positionBits es + let key := OAI.EditApproximation.binaryMemoKey symbolBits e.1 + let found := previous.1.lookupCosted key + let inserted := (found.1.getD .empty).addWithWork positionBits e.2 + let updated := previous.1.insertCosted key inserted.1 + (updated.1, previous.2 + symbolBits + found.2 + inserted.2 + updated.2 + 2) + +def occurrenceQueryWithWork (table : OAI.EditApproximation.BinaryMemo OAI.EditApproximation.PositionCounts) + (symbolBits positionBits a lo hi : ℕ) : Bool × ℕ := + let key := OAI.EditApproximation.binaryMemoKey symbolBits a + let found := table.lookupCosted key + let tree := found.1.getD .empty + let first := tree.prefixWithWork positionBits lo + let last := tree.prefixWithWork positionBits hi + (decide (first.1 < last.1), symbolBits + found.2 + first.2 + last.2 + 2) + +def rankedBitMemoEvaluate {κ : Type u_1} (rank : κ → ℕ) + (program : (key : κ) → OAI.EditApproximation.BitQuery {child : κ // rank child < rank key} OAI.EditApproximation.BinaryFraction) + (bits : ℕ) (encode : κ → ℕ) (key : κ) (memory : OAI.EditApproximation.BinaryMemo OAI.EditApproximation.BinaryFraction) : + OAI.EditApproximation.BitRecursiveMemoResult κ := + let found := memory.lookupCosted (OAI.EditApproximation.binaryMemoKey bits (encode key)) + match found.1 with + | some result => ⟨result, memory, [], found.2, 1, 0⟩ + | none => + let result := OAI.EditApproximation.BitQuery.runMemo (fun child previous => + rankedBitMemoEvaluate rank program bits encode child.val previous) (program key) memory + let stored := result.memory.insertCosted (OAI.EditApproximation.binaryMemoKey bits (encode key)) result.value + ⟨result.value, stored.1, key :: result.freshKeys, + found.2 + result.dictionaryVisits + stored.2, result.requests + 1, result.localWork⟩ +termination_by rank key +decreasing_by exact child.property + +def physicalWarmupStepQuery {ι : Type u_1} {α : Type u_2} [DecidableEq α] {M J : ℕ} + (source target : List α) (N P F : ℕ) (A : ℚ) + (seedRead : OAI.EditApproximation.PhysicalEntry M J target.length → OAI.EditApproximation.FiniteQuery ι) + (childRead : Fin M × OAI.EditApproximation.TargetInterval target.length → OAI.EditApproximation.FiniteQuery ι) + (node : OAI.EditApproximation.PhysicalNode M J) (q : OAI.EditApproximation.TargetInterval target.length) : OAI.EditApproximation.FiniteQuery ι := + OAI.EditApproximation.localWarmupStepQuery (OAI.EditApproximation.physicalSourceInterval source.length node) N P F (OAI.EditApproximation.refinementFactor A F) + (fun r => OAI.EditApproximation.physicalInitialQuery source target N P F A seedRead (node, r)) childRead q + +def indexedSingletonCostWithWork (table : OAI.EditApproximation.BinaryMemo OAI.EditApproximation.PositionCounts) + (symbolBits positionBits a lo hi : ℕ) : ℕ × ℕ := + if lo = hi then (1, 1) else + let query := OAI.EditApproximation.occurrenceQueryWithWork table symbolBits positionBits a lo hi + (hi - lo - if query.1 = true then 1 else 0, query.2 + 4) + +def integerOccurrenceIndex (source target : List ℤ) : OAI.EditApproximation.BinaryMemo OAI.EditApproximation.PositionCounts := + OAI.EditApproximation.occurrenceBuild (OAI.EditApproximation.integerInputSymbolBits source target) (OAI.EditApproximation.integerInputPositionBits target) + (target.map OAI.EditApproximation.integerSymbolCode).zipIdx + +def integerOccurrenceBuildWithWork (source target : List ℤ) : OAI.EditApproximation.BinaryMemo OAI.EditApproximation.PositionCounts × ℕ := + OAI.EditApproximation.occurrenceBuildWithWork (OAI.EditApproximation.integerInputSymbolBits source target) (OAI.EditApproximation.integerInputPositionBits target) + (target.map OAI.EditApproximation.integerSymbolCode).zipIdx + +def rankedMemoAddressWork {κ : Type u_1} (rank : κ → ℕ) + (program : (key : κ) → OAI.EditApproximation.FiniteQuery {child : κ // rank child < rank key}) + (bits : ℕ) (encode cost : κ → ℕ) (key : κ) (memory : OAI.EditApproximation.BinaryMemo ℚ) : ℕ := + match (memory.lookupCosted (OAI.EditApproximation.binaryMemoKey bits (encode key))).1 with + | some _ => cost key + | none => cost key + OAI.EditApproximation.FiniteQuery.requestWork + (fun child previous => OAI.EditApproximation.rankedMemoEvaluate rank program bits encode child.val previous) + (fun child previous => rankedMemoAddressWork rank program bits encode cost child.val previous) + (program key) memory + cost key +termination_by rank key +decreasing_by exact child.property + +def rankedMemoKernelWork {κ : Type u_1} (rank : κ → ℕ) + (program : (key : κ) → OAI.EditApproximation.FiniteQuery {child : κ // rank child < rank key}) + (bits : ℕ) (encode cost : κ → ℕ) (key : κ) (memory : OAI.EditApproximation.BinaryMemo ℚ) : ℕ := + match (memory.lookupCosted (OAI.EditApproximation.binaryMemoKey bits (encode key))).1 with + | some _ => 0 + | none => cost key + OAI.EditApproximation.FiniteQuery.requestWork + (fun child previous => OAI.EditApproximation.rankedMemoEvaluate rank program bits encode child.val previous) + (fun child previous => rankedMemoKernelWork rank program bits encode cost child.val previous) + (program key) memory +termination_by rank key +decreasing_by exact child.property + +def physicalWarmupRequestQuery {α : Type u_1} [DecidableEq α] {M J : ℕ} + (source target : List α) (N P F : ℕ) (A : ℚ) + (pass copy T S j : ℕ) (node : OAI.EditApproximation.PhysicalNode M J) (q : OAI.EditApproximation.TargetInterval target.length) + (seedRead : OAI.EditApproximation.PhysicalEntry M J target.length → + OAI.EditApproximation.FiniteQuery {child : OAI.EditApproximation.PhysicalTableRequest M J target.length // + child.combinedRank T S < (OAI.EditApproximation.PhysicalTableRequest.warmup pass copy node j q).combinedRank T S}) : + OAI.EditApproximation.FiniteQuery {child : OAI.EditApproximation.PhysicalTableRequest M J target.length // + child.combinedRank T S < (OAI.EditApproximation.PhysicalTableRequest.warmup pass copy node j q).combinedRank T S} := + match j with + | 0 => OAI.EditApproximation.physicalInitialQuery source target N P F A seedRead (node, q) + | t + 1 => + if hbelow : node.1.val < J then + if (OAI.EditApproximation.physicalSourceInterval source.length node).hi - + (OAI.EditApproximation.physicalSourceInterval source.length node).lo ≤ 1 then + OAI.EditApproximation.physicalInitialQuery source target N P F A seedRead (node, q) + else OAI.EditApproximation.physicalWarmupStepQuery source target N P F A seedRead + (OAI.EditApproximation.physicalWarmupChildQuery pass copy T S t node hbelow q) node q + else OAI.EditApproximation.physicalInitialQuery source target N P F A seedRead (node, q) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open MeasureTheory ProbabilityTheory + +abbrev PhysicalLocalOnlineKey (M J N n : ℕ) := + OAI.EditApproximation.PhysicalInternalNode M J × Fin (OAI.EditApproximation.dyadicScales N).length × OAI.EditApproximation.TargetInterval n + +abbrev ClampedPhysicalSeed (M J ny N : ℕ) := OAI.EditApproximation.PhysicalEntry M J ny → Fin (N + 1) + +def finalTargetState (n : ℕ) : OAI.EditApproximation.TargetInterval n := ⟨0, n, Nat.zero_le _, le_rfl⟩ + +abbrev PhysicalCommonKey (M J N n exponent B : ℕ) := + Sum (OAI.EditApproximation.CommonRangeKey (OAI.EditApproximation.PhysicalLocalOnlineKey M J N n) B) + (OAI.EditApproximation.PhysicalLocalGroupKey M J N n exponent) + +def clampedSeedNat {M J ny N : ℕ} (seed : OAI.EditApproximation.ClampedPhysicalSeed M J ny N) + (state : OAI.EditApproximation.PhysicalEntry M J ny) : ℕ := (seed state).val + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation + +open Finset + +def triangularChoiceWithWork (K : ℕ) : Fin (OAI.EditApproximation.optimizerTriangularMass K) → Fin K × ℕ:= by + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_binaryNaturalCompareWithWork_lt_53 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.binaryNaturalCompareWithWork a b).1 = .lt ↔ a < b := by + simpa only [OAI.EditApproximation.binaryNaturalCompareWithWork, proof_bitWordValue_bits_15] using proof_bitCompareWithWork_lt_16 a.bits b.bits + have proof_bitAdder_value_1 (a : Bool) (b : Bool) (carry : Bool) : + (OAI.EditApproximation.bitSum a b carry).toNat + 2 * (OAI.EditApproximation.bitCarry a b carry).toNat = + a.toNat + b.toNat + carry.toNat := by + cases a <;> cases b <;> cases carry <;> decide + have proof_bitAddWithWork_value_2 (left : List.{0} Bool) (right : List.{0} Bool) (carry : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitAddWithWork left right carry).1 = + OAI.EditApproximation.bitWordValue left + OAI.EditApproximation.bitWordValue right + carry.toNat := by + induction left generalizing right carry with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork] + induction right generalizing carry with + | nil => cases carry <;> simp [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue] + | cons b bs ih => + simp only [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 false b carry + simp only [Bool.toNat_false] at h + omega + | cons a as ih => + cases right with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a false carry + simp only [Bool.toNat_false] at h + omega + | cons b bs => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a b carry + omega + have proof_binaryNaturalAddWithWork_value_52 (a : ℕ) (b : ℕ) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalAddWithWork a b).1 = a + b := by + simp [OAI.EditApproximation.binaryNaturalAddWithWork, proof_bitAddWithWork_value_2, proof_bitWordValue_bits_15] + have proof_bitMulWithWork_value_0 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitMulWithWork left right).1 = OAI.EditApproximation.bitWordValue left * OAI.EditApproximation.bitWordValue right := by + induction left with + | nil => simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue] + | cons bit bits ih => + cases bit <;> simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue, proof_bitAddWithWork_value_2, ih] <;> ring + have proof_binaryNaturalMulWithWork_value_55 (a : ℕ) (b : ℕ) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalMulWithWork a b).1 = a * b := by + simp [OAI.EditApproximation.binaryNaturalMulWithWork, proof_bitMulWithWork_value_0, proof_bitWordValue_bits_15] + have proof_bitSubtractor_value_17 (a : Bool) (b : Bool) (borrow : Bool) : + a.toNat + 2 * (OAI.EditApproximation.bitBorrow a b borrow).toNat = + b.toNat + borrow.toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat := by + cases a <;> cases b <;> cases borrow <;> decide + have proof_bitSubtractionRippleEquation_18 (a : ℕ) (b : ℕ) (borrow : ℕ) (nextBorrow : ℕ) (difference : ℕ) (left : ℕ) (right : ℕ) (result : ℕ) (tail : ℕ) (htail : Eq.{1} (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} result right) nextBorrow) (HAdd.hAdd.{0, 0, 0} left tail)) (hbit : Eq.{1} (HAdd.hAdd.{0, 0, 0} a (HMul.hMul.{0, 0, 0} 2 nextBorrow)) + (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} b borrow) difference)) : + (difference + 2 * result) + (b + 2 * right) + borrow = + (a + 2 * left) + 2 * tail := by + omega + have proof_bitSubtractWithWork_value_19 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right borrow).1 + OAI.EditApproximation.bitWordValue right + borrow.toNat = + OAI.EditApproximation.bitWordValue left + 2 ^ max left.length right.length * + (OAI.EditApproximation.bitSubtractWithWork left right borrow).2.1.toNat := by + induction left generalizing right borrow with + | nil => + induction right generalizing borrow with + | nil => (simp [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + have h := ih (OAI.EditApproximation.bitBorrow false b borrow) + have hb := proof_bitSubtractor_value_17 false b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue, + List.length_nil, List.length_cons, Nat.zero_max, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 0 b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow false b borrow).toNat + (OAI.EditApproximation.bitDifference false b borrow).toNat 0 (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).1) + (2 ^ bs.length * (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons a as ih => + cases right with + | nil => + have h := ih [] (OAI.EditApproximation.bitBorrow a false borrow) + have hb := proof_bitSubtractor_value_17 a false borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_nil, List.length_cons, + Nat.max_zero, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat 0 borrow.toNat (OAI.EditApproximation.bitBorrow a false borrow).toNat + (OAI.EditApproximation.bitDifference a false borrow).toNat (OAI.EditApproximation.bitWordValue as) 0 + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).1) + (2 ^ as.length * (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons b bs => + have h := ih bs (OAI.EditApproximation.bitBorrow a b borrow) + have hb := proof_bitSubtractor_value_17 a b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_cons, Nat.succ_max_succ, + pow_succ] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow a b borrow).toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).1) + (2 ^ max as.length bs.length * (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_assoc, Nat.mul_left_comm] using hs + have proof_bitWordValue_lt_pow_length_20 (bits : List.{0} Bool) : OAI.EditApproximation.bitWordValue bits < 2 ^ bits.length := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitWordValue]) + | cons bit bits ih => + cases bit <;> (simp only [OAI.EditApproximation.bitWordValue, List.length_cons, pow_succ, Bool.toNat_false, Bool.toNat_true]) <;> omega + have proof_bitSubtractWithWork_length_21 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + (OAI.EditApproximation.bitSubtractWithWork left right borrow).1.length = max left.length right.length := by + induction left generalizing right borrow with + | nil => + simp only [OAI.EditApproximation.bitSubtractWithWork] + induction right generalizing borrow with + | nil => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork] + | cons b bs ih => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork, ih] + | cons a as ih => + cases right with + | nil => simp [OAI.EditApproximation.bitSubtractWithWork, ih] + | cons b bs => simp [OAI.EditApproximation.bitSubtractWithWork, ih, Nat.succ_max_succ] + have proof_bitSubtractWithWork_sub_22 (left : List.{0} Bool) (right : List.{0} Bool) (h : LE.le.{0} (OAI.EditApproximation.bitWordValue right) (OAI.EditApproximation.bitWordValue left)) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right false).1 = OAI.EditApproximation.bitWordValue left - OAI.EditApproximation.bitWordValue right := by + have hvalue := proof_bitSubtractWithWork_value_19 left right false + have hlt := proof_bitWordValue_lt_pow_length_20 (OAI.EditApproximation.bitSubtractWithWork left right false).1 + rw [proof_bitSubtractWithWork_length_21] at hlt + cases hb : (OAI.EditApproximation.bitSubtractWithWork left right false).2.1 + · simp only [hb, Bool.toNat_false, Nat.mul_zero, Nat.add_zero] at hvalue + omega + · simp only [hb, Bool.toNat_true, Bool.toNat_false, Nat.mul_one, Nat.add_zero] at hvalue + omega + have proof_bitDivModWithWork_value_23 (divisor : List.{0} Bool) (bits : List.{0} Bool) (hd : LT.lt.{0} 0 (OAI.EditApproximation.bitWordValue divisor)) : + OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).1 + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 < OAI.EditApproximation.bitWordValue divisor := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitDivModWithWork, OAI.EditApproximation.bitWordValue, hd]) + | cons bit bits ih => + let previous := OAI.EditApproximation.bitDivModWithWork divisor bits + let candidate := bit :: previous.2.1 + have hp : OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue previous.1 + + OAI.EditApproximation.bitWordValue previous.2.1 := ih.1 + have hr : OAI.EditApproximation.bitWordValue previous.2.1 < OAI.EditApproximation.bitWordValue divisor := ih.2 + have hc : OAI.EditApproximation.bitWordValue candidate < 2 * OAI.EditApproximation.bitWordValue divisor := by + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + cases bit <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega + by_cases hlt : (OAI.EditApproximation.bitCompareWithWork candidate divisor).1 = .lt + · have hv := (proof_bitCompareWithWork_lt_16 candidate divisor).1 hlt + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 = .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * + OAI.EditApproximation.bitWordValue (false :: previous.1) + OAI.EditApproximation.bitWordValue candidate ∧ OAI.EditApproximation.bitWordValue candidate < _ + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_false]) + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + nlinarith only [hp] + · exact hv + · have hv : OAI.EditApproximation.bitWordValue divisor ≤ OAI.EditApproximation.bitWordValue candidate := by + exact Nat.le_of_not_gt (fun h => hlt ((proof_bitCompareWithWork_lt_16 candidate divisor).2 h)) + have hs := proof_bitSubtractWithWork_sub_22 candidate divisor hv + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 ≠ .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (true :: previous.1) + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 < _ + rw [hs] + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_true]) + have he := Nat.sub_add_cancel hv + dsimp only [candidate, OAI.EditApproximation.bitWordValue] at he ⊢ + nlinarith only [hp, he] + · omega + have proof_binaryNaturalDivModWithWork_spec_24 (n : ℕ) (d : ℕ) (hd : LT.lt.{0} 0 d) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalDivModWithWork n d).1 = n / d ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalDivModWithWork n d).2.1 = n % d := by + have h := proof_bitDivModWithWork_value_23 d.bits n.bits (by simpa only [proof_bitWordValue_bits_15] using hd) + simp only [proof_bitWordValue_bits_15] at h + have hmod : n % d = OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork d.bits n.bits).2.1 := by + conv_lhs => rw [h.1] + simp only [Nat.add_mod, Nat.mul_mod_right, Nat.zero_add, Nat.mod_eq_of_lt h.2] + have hdiv : n / d = OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork d.bits n.bits).1 := by + conv_lhs => rw [h.1] + rw [Nat.mul_add_div hd, Nat.div_eq_of_lt h.2, Nat.add_zero] + exact ⟨hdiv.symm, hmod.symm⟩ + have proof_optimizerTriangularMass_succ_66 (K : ℕ) : + OAI.EditApproximation.optimizerTriangularMass (K + 1) = OAI.EditApproximation.optimizerTriangularMass K + (K + 1) := by + unfold OAI.EditApproximation.optimizerTriangularMass + rw [sum_range_succ] + have proof_optimizerTriangularMass_twice_67 (K : ℕ) : + 2 * OAI.EditApproximation.optimizerTriangularMass K = K * (K + 1) := by + induction K with + | zero => simp [OAI.EditApproximation.optimizerTriangularMass] + | succ K ih => + rw [proof_optimizerTriangularMass_succ_66] + nlinarith + have proof_triangularMassWithWork_value_65 (K : ℕ) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.triangularMassWithWork K).1 = OAI.EditApproximation.optimizerTriangularMass K := by + simp only [OAI.EditApproximation.triangularMassWithWork, proof_binaryNaturalAddWithWork_value_52, proof_binaryNaturalMulWithWork_value_55, + (proof_binaryNaturalDivModWithWork_spec_24 _ 2 (by decide)).1] + rw [← proof_optimizerTriangularMass_twice_67 K, Nat.mul_div_cancel_left _ (by decide : 0 < 2)] + exact fun integer => match K, integer with + | 0, integer => Fin.elim0 integer + | K + 1, integer => + let threshold := OAI.EditApproximation.triangularMassWithWork K + let test := OAI.EditApproximation.binaryNaturalCompareWithWork integer.val (OAI.EditApproximation.bitWordValue threshold.1) + if h : test.1 = .lt then + let hsmall : integer.val < OAI.EditApproximation.optimizerTriangularMass K := by + have ht := (proof_binaryNaturalCompareWithWork_lt_53 _ _).mp h + simpa only [threshold, proof_triangularMassWithWork_value_65] using ht + let chosen := triangularChoiceWithWork K ⟨integer.val, hsmall⟩ + (chosen.1.castSucc, threshold.2 + test.2 + chosen.2 + 2) + else (⟨K, by omega⟩, threshold.2 + test.2 + 1) + +def triangularChoiceAllocation (K : ℕ) : Fin (OAI.EditApproximation.optimizerTriangularMass K) → ℕ:= by + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_binaryNaturalCompareWithWork_lt_53 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.binaryNaturalCompareWithWork a b).1 = .lt ↔ a < b := by + simpa only [OAI.EditApproximation.binaryNaturalCompareWithWork, proof_bitWordValue_bits_15] using proof_bitCompareWithWork_lt_16 a.bits b.bits + have proof_bitAdder_value_1 (a : Bool) (b : Bool) (carry : Bool) : + (OAI.EditApproximation.bitSum a b carry).toNat + 2 * (OAI.EditApproximation.bitCarry a b carry).toNat = + a.toNat + b.toNat + carry.toNat := by + cases a <;> cases b <;> cases carry <;> decide + have proof_bitAddWithWork_value_2 (left : List.{0} Bool) (right : List.{0} Bool) (carry : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitAddWithWork left right carry).1 = + OAI.EditApproximation.bitWordValue left + OAI.EditApproximation.bitWordValue right + carry.toNat := by + induction left generalizing right carry with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork] + induction right generalizing carry with + | nil => cases carry <;> simp [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue] + | cons b bs ih => + simp only [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 false b carry + simp only [Bool.toNat_false] at h + omega + | cons a as ih => + cases right with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a false carry + simp only [Bool.toNat_false] at h + omega + | cons b bs => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a b carry + omega + have proof_binaryNaturalAddWithWork_value_52 (a : ℕ) (b : ℕ) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalAddWithWork a b).1 = a + b := by + simp [OAI.EditApproximation.binaryNaturalAddWithWork, proof_bitAddWithWork_value_2, proof_bitWordValue_bits_15] + have proof_bitMulWithWork_value_0 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitMulWithWork left right).1 = OAI.EditApproximation.bitWordValue left * OAI.EditApproximation.bitWordValue right := by + induction left with + | nil => simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue] + | cons bit bits ih => + cases bit <;> simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue, proof_bitAddWithWork_value_2, ih] <;> ring + have proof_binaryNaturalMulWithWork_value_55 (a : ℕ) (b : ℕ) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalMulWithWork a b).1 = a * b := by + simp [OAI.EditApproximation.binaryNaturalMulWithWork, proof_bitMulWithWork_value_0, proof_bitWordValue_bits_15] + have proof_bitSubtractor_value_17 (a : Bool) (b : Bool) (borrow : Bool) : + a.toNat + 2 * (OAI.EditApproximation.bitBorrow a b borrow).toNat = + b.toNat + borrow.toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat := by + cases a <;> cases b <;> cases borrow <;> decide + have proof_bitSubtractionRippleEquation_18 (a : ℕ) (b : ℕ) (borrow : ℕ) (nextBorrow : ℕ) (difference : ℕ) (left : ℕ) (right : ℕ) (result : ℕ) (tail : ℕ) (htail : Eq.{1} (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} result right) nextBorrow) (HAdd.hAdd.{0, 0, 0} left tail)) (hbit : Eq.{1} (HAdd.hAdd.{0, 0, 0} a (HMul.hMul.{0, 0, 0} 2 nextBorrow)) + (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} b borrow) difference)) : + (difference + 2 * result) + (b + 2 * right) + borrow = + (a + 2 * left) + 2 * tail := by + omega + have proof_bitSubtractWithWork_value_19 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right borrow).1 + OAI.EditApproximation.bitWordValue right + borrow.toNat = + OAI.EditApproximation.bitWordValue left + 2 ^ max left.length right.length * + (OAI.EditApproximation.bitSubtractWithWork left right borrow).2.1.toNat := by + induction left generalizing right borrow with + | nil => + induction right generalizing borrow with + | nil => (simp [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + have h := ih (OAI.EditApproximation.bitBorrow false b borrow) + have hb := proof_bitSubtractor_value_17 false b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue, + List.length_nil, List.length_cons, Nat.zero_max, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 0 b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow false b borrow).toNat + (OAI.EditApproximation.bitDifference false b borrow).toNat 0 (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).1) + (2 ^ bs.length * (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons a as ih => + cases right with + | nil => + have h := ih [] (OAI.EditApproximation.bitBorrow a false borrow) + have hb := proof_bitSubtractor_value_17 a false borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_nil, List.length_cons, + Nat.max_zero, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat 0 borrow.toNat (OAI.EditApproximation.bitBorrow a false borrow).toNat + (OAI.EditApproximation.bitDifference a false borrow).toNat (OAI.EditApproximation.bitWordValue as) 0 + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).1) + (2 ^ as.length * (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons b bs => + have h := ih bs (OAI.EditApproximation.bitBorrow a b borrow) + have hb := proof_bitSubtractor_value_17 a b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_cons, Nat.succ_max_succ, + pow_succ] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow a b borrow).toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).1) + (2 ^ max as.length bs.length * (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_assoc, Nat.mul_left_comm] using hs + have proof_bitWordValue_lt_pow_length_20 (bits : List.{0} Bool) : OAI.EditApproximation.bitWordValue bits < 2 ^ bits.length := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitWordValue]) + | cons bit bits ih => + cases bit <;> (simp only [OAI.EditApproximation.bitWordValue, List.length_cons, pow_succ, Bool.toNat_false, Bool.toNat_true]) <;> omega + have proof_bitSubtractWithWork_length_21 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + (OAI.EditApproximation.bitSubtractWithWork left right borrow).1.length = max left.length right.length := by + induction left generalizing right borrow with + | nil => + simp only [OAI.EditApproximation.bitSubtractWithWork] + induction right generalizing borrow with + | nil => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork] + | cons b bs ih => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork, ih] + | cons a as ih => + cases right with + | nil => simp [OAI.EditApproximation.bitSubtractWithWork, ih] + | cons b bs => simp [OAI.EditApproximation.bitSubtractWithWork, ih, Nat.succ_max_succ] + have proof_bitSubtractWithWork_sub_22 (left : List.{0} Bool) (right : List.{0} Bool) (h : LE.le.{0} (OAI.EditApproximation.bitWordValue right) (OAI.EditApproximation.bitWordValue left)) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right false).1 = OAI.EditApproximation.bitWordValue left - OAI.EditApproximation.bitWordValue right := by + have hvalue := proof_bitSubtractWithWork_value_19 left right false + have hlt := proof_bitWordValue_lt_pow_length_20 (OAI.EditApproximation.bitSubtractWithWork left right false).1 + rw [proof_bitSubtractWithWork_length_21] at hlt + cases hb : (OAI.EditApproximation.bitSubtractWithWork left right false).2.1 + · simp only [hb, Bool.toNat_false, Nat.mul_zero, Nat.add_zero] at hvalue + omega + · simp only [hb, Bool.toNat_true, Bool.toNat_false, Nat.mul_one, Nat.add_zero] at hvalue + omega + have proof_bitDivModWithWork_value_23 (divisor : List.{0} Bool) (bits : List.{0} Bool) (hd : LT.lt.{0} 0 (OAI.EditApproximation.bitWordValue divisor)) : + OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).1 + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 < OAI.EditApproximation.bitWordValue divisor := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitDivModWithWork, OAI.EditApproximation.bitWordValue, hd]) + | cons bit bits ih => + let previous := OAI.EditApproximation.bitDivModWithWork divisor bits + let candidate := bit :: previous.2.1 + have hp : OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue previous.1 + + OAI.EditApproximation.bitWordValue previous.2.1 := ih.1 + have hr : OAI.EditApproximation.bitWordValue previous.2.1 < OAI.EditApproximation.bitWordValue divisor := ih.2 + have hc : OAI.EditApproximation.bitWordValue candidate < 2 * OAI.EditApproximation.bitWordValue divisor := by + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + cases bit <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega + by_cases hlt : (OAI.EditApproximation.bitCompareWithWork candidate divisor).1 = .lt + · have hv := (proof_bitCompareWithWork_lt_16 candidate divisor).1 hlt + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 = .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * + OAI.EditApproximation.bitWordValue (false :: previous.1) + OAI.EditApproximation.bitWordValue candidate ∧ OAI.EditApproximation.bitWordValue candidate < _ + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_false]) + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + nlinarith only [hp] + · exact hv + · have hv : OAI.EditApproximation.bitWordValue divisor ≤ OAI.EditApproximation.bitWordValue candidate := by + exact Nat.le_of_not_gt (fun h => hlt ((proof_bitCompareWithWork_lt_16 candidate divisor).2 h)) + have hs := proof_bitSubtractWithWork_sub_22 candidate divisor hv + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 ≠ .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (true :: previous.1) + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 < _ + rw [hs] + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_true]) + have he := Nat.sub_add_cancel hv + dsimp only [candidate, OAI.EditApproximation.bitWordValue] at he ⊢ + nlinarith only [hp, he] + · omega + have proof_binaryNaturalDivModWithWork_spec_24 (n : ℕ) (d : ℕ) (hd : LT.lt.{0} 0 d) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalDivModWithWork n d).1 = n / d ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalDivModWithWork n d).2.1 = n % d := by + have h := proof_bitDivModWithWork_value_23 d.bits n.bits (by simpa only [proof_bitWordValue_bits_15] using hd) + simp only [proof_bitWordValue_bits_15] at h + have hmod : n % d = OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork d.bits n.bits).2.1 := by + conv_lhs => rw [h.1] + simp only [Nat.add_mod, Nat.mul_mod_right, Nat.zero_add, Nat.mod_eq_of_lt h.2] + have hdiv : n / d = OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork d.bits n.bits).1 := by + conv_lhs => rw [h.1] + rw [Nat.mul_add_div hd, Nat.div_eq_of_lt h.2, Nat.add_zero] + exact ⟨hdiv.symm, hmod.symm⟩ + have proof_optimizerTriangularMass_succ_66 (K : ℕ) : + OAI.EditApproximation.optimizerTriangularMass (K + 1) = OAI.EditApproximation.optimizerTriangularMass K + (K + 1) := by + unfold OAI.EditApproximation.optimizerTriangularMass + rw [sum_range_succ] + have proof_optimizerTriangularMass_twice_67 (K : ℕ) : + 2 * OAI.EditApproximation.optimizerTriangularMass K = K * (K + 1) := by + induction K with + | zero => simp [OAI.EditApproximation.optimizerTriangularMass] + | succ K ih => + rw [proof_optimizerTriangularMass_succ_66] + nlinarith + have proof_triangularMassWithWork_value_65 (K : ℕ) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.triangularMassWithWork K).1 = OAI.EditApproximation.optimizerTriangularMass K := by + simp only [OAI.EditApproximation.triangularMassWithWork, proof_binaryNaturalAddWithWork_value_52, proof_binaryNaturalMulWithWork_value_55, + (proof_binaryNaturalDivModWithWork_spec_24 _ 2 (by decide)).1] + rw [← proof_optimizerTriangularMass_twice_67 K, Nat.mul_div_cancel_left _ (by decide : 0 < 2)] + exact fun integer => match K, integer with + | 0, integer => Fin.elim0 integer + | K + 1, integer => + let threshold := OAI.EditApproximation.triangularMassWithWork K + let test := OAI.EditApproximation.binaryNaturalCompareWithWork integer.val (OAI.EditApproximation.bitWordValue threshold.1) + let localCells := OAI.EditApproximation.triangularMassAllocation K + integer.val.bits.length + + (OAI.EditApproximation.bitWordValue threshold.1).bits.length + if h : test.1 = .lt then + let hsmall : integer.val < OAI.EditApproximation.optimizerTriangularMass K := by + have ht := (proof_binaryNaturalCompareWithWork_lt_53 _ _).mp h + simpa only [threshold, proof_triangularMassWithWork_value_65] using ht + localCells + triangularChoiceAllocation K ⟨integer.val, hsmall⟩ + else localCells + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BinaryFraction + +open Finset + +def coordinateVectorWithWork {M n : ℕ} (band : List (Fin M → OAI.EditApproximation.TargetInterval n)) : + Vector (Fin M × OAI.EditApproximation.TargetInterval n) (OAI.EditApproximation.listedBandCoordinates band).length × ℕ := by + have proof_arithmeticFlatMapWithWork_value_69 {α : Type 0} {β : Type 0} (f : α → Prod.{0, 0} (List.{0} β) ℕ) (values : List.{0} α) : + (OAI.EditApproximation.arithmeticFlatMapWithWork f values).1 = values.flatMap (fun a => (f a).1) := by + induction values with + | nil => rfl + | cons a rest ih => simp only [OAI.EditApproximation.arithmeticFlatMapWithWork, ih, List.flatMap_cons] + have proof_arithmeticMapWithWork_value_70 {α : Type 0} {β : Type 0} (f : α → Prod.{0, 0} β ℕ) (values : List.{0} α) : + (OAI.EditApproximation.arithmeticMapWithWork f values).1 = values.map (fun a => (f a).1) := by + induction values with + | nil => rfl + | cons a rest ih => simp only [OAI.EditApproximation.arithmeticMapWithWork, ih, List.map_cons] + have proof_memberByWithWork_value_71 {α : Type 0} (equal : α → α → Prod.{0, 0} Bool ℕ) (heq : ∀ (a b : α), Eq.{1} (equal a b).1 Bool.true ↔ Eq.{0 + 1} a b) (a : α) (xs : List.{0} α) : + (OAI.EditApproximation.memberByWithWork equal a xs).1 = true ↔ a ∈ xs := by + induction xs with + | nil => simp only [OAI.EditApproximation.memberByWithWork, Bool.false_eq_true, List.not_mem_nil] + | cons b xs ih => simp only [OAI.EditApproximation.memberByWithWork, Bool.or_eq_true, heq, ih, List.mem_cons] + have proof_dedupByWithWork_value_72 {α : Type 0} [instLocal1 : DecidableEq.{0 + 1} α] (equal : α → α → Prod.{0, 0} Bool ℕ) (heq : ∀ (a b : α), Eq.{1} (equal a b).1 Bool.true ↔ Eq.{0 + 1} a b) (xs : List.{0} α) : + (OAI.EditApproximation.dedupByWithWork equal xs).1 = xs.dedup := by + induction xs with + | nil => rfl + | cons a rest ih => + have hm := proof_memberByWithWork_value_71 equal heq a rest + have ht : (OAI.EditApproximation.memberByWithWork equal a rest).1 = decide (a ∈ rest) := + Bool.eq_iff_iff.mpr (by simpa only [decide_eq_true_eq] using hm) + simp only [OAI.EditApproximation.dedupByWithWork, ht, ih, List.dedup_cons, decide_eq_true_eq] + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_eq_3 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .eq ↔ OAI.EditApproximation.bitWordValue left = OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_binaryNaturalCompareWithWork_eq_73 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.binaryNaturalCompareWithWork a b).1 = .eq ↔ a = b := by + simpa only [OAI.EditApproximation.binaryNaturalCompareWithWork, proof_bitWordValue_bits_15] using proof_bitCompareWithWork_eq_3 a.bits b.bits + have proof_naturalEqualWithWork_value_74 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.naturalEqualWithWork a b).1 = true ↔ a = b := by + simp only [OAI.EditApproximation.naturalEqualWithWork, decide_eq_true_eq, proof_binaryNaturalCompareWithWork_eq_73] + have proof_coordinateEqualWithWork_value_75 {M : ℕ} {n : ℕ} (a : Prod.{0, 0} (Fin M) (OAI.EditApproximation.TargetInterval n)) (b : Prod.{0, 0} (Fin M) (OAI.EditApproximation.TargetInterval n)) : + (OAI.EditApproximation.coordinateEqualWithWork a b).1 = true ↔ a = b := by + simp only [OAI.EditApproximation.coordinateEqualWithWork, Bool.and_eq_true, proof_naturalEqualWithWork_value_74] + constructor + · rintro ⟨⟨hc, hl⟩, hh⟩ + have hi : a.1 = b.1 := Fin.ext hc + have hq : a.2 = b.2 := by + rcases a with ⟨i, q⟩ + rcases b with ⟨j, r⟩ + cases q + cases r + cases hl + cases hh + rfl + exact Prod.ext hi hq + · intro h + subst b + exact ⟨⟨rfl, rfl⟩, rfl⟩ + have proof_bandCoordinatesWithWork_value_68 {M : ℕ} {n : ℕ} (band : List.{0} (Fin M → OAI.EditApproximation.TargetInterval n)) : + (OAI.EditApproximation.BinaryFraction.bandCoordinatesWithWork band).1 = OAI.EditApproximation.listedBandCoordinates band := by + simp only [OAI.EditApproximation.BinaryFraction.bandCoordinatesWithWork, proof_dedupByWithWork_value_72 _ proof_coordinateEqualWithWork_value_75, + proof_arithmeticFlatMapWithWork_value_69, proof_arithmeticMapWithWork_value_70, OAI.EditApproximation.listedBandCoordinates, + List.ofFn_eq_map] + exact + let coordinates := OAI.EditApproximation.BinaryFraction.bandCoordinatesWithWork band + (Vector.ofFn (fun i => coordinates.1.get ⟨i.val, by + rw [proof_bandCoordinatesWithWork_value_68] + exact i.isLt⟩), coordinates.2 + coordinates.1.length + 1) + +def reduceOnlineIntegerWithWork (K : ℕ) (hK : 0 < K) (integer : ℕ) : + Fin (OAI.EditApproximation.optimizerTriangularMass K) × ℕ := by + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_bitSubtractor_value_17 (a : Bool) (b : Bool) (borrow : Bool) : + a.toNat + 2 * (OAI.EditApproximation.bitBorrow a b borrow).toNat = + b.toNat + borrow.toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat := by + cases a <;> cases b <;> cases borrow <;> decide + have proof_bitSubtractionRippleEquation_18 (a : ℕ) (b : ℕ) (borrow : ℕ) (nextBorrow : ℕ) (difference : ℕ) (left : ℕ) (right : ℕ) (result : ℕ) (tail : ℕ) (htail : Eq.{1} (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} result right) nextBorrow) (HAdd.hAdd.{0, 0, 0} left tail)) (hbit : Eq.{1} (HAdd.hAdd.{0, 0, 0} a (HMul.hMul.{0, 0, 0} 2 nextBorrow)) + (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} b borrow) difference)) : + (difference + 2 * result) + (b + 2 * right) + borrow = + (a + 2 * left) + 2 * tail := by + omega + have proof_bitSubtractWithWork_value_19 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right borrow).1 + OAI.EditApproximation.bitWordValue right + borrow.toNat = + OAI.EditApproximation.bitWordValue left + 2 ^ max left.length right.length * + (OAI.EditApproximation.bitSubtractWithWork left right borrow).2.1.toNat := by + induction left generalizing right borrow with + | nil => + induction right generalizing borrow with + | nil => (simp [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + have h := ih (OAI.EditApproximation.bitBorrow false b borrow) + have hb := proof_bitSubtractor_value_17 false b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue, + List.length_nil, List.length_cons, Nat.zero_max, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 0 b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow false b borrow).toNat + (OAI.EditApproximation.bitDifference false b borrow).toNat 0 (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).1) + (2 ^ bs.length * (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons a as ih => + cases right with + | nil => + have h := ih [] (OAI.EditApproximation.bitBorrow a false borrow) + have hb := proof_bitSubtractor_value_17 a false borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_nil, List.length_cons, + Nat.max_zero, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat 0 borrow.toNat (OAI.EditApproximation.bitBorrow a false borrow).toNat + (OAI.EditApproximation.bitDifference a false borrow).toNat (OAI.EditApproximation.bitWordValue as) 0 + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).1) + (2 ^ as.length * (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons b bs => + have h := ih bs (OAI.EditApproximation.bitBorrow a b borrow) + have hb := proof_bitSubtractor_value_17 a b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_cons, Nat.succ_max_succ, + pow_succ] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow a b borrow).toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).1) + (2 ^ max as.length bs.length * (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_assoc, Nat.mul_left_comm] using hs + have proof_bitWordValue_lt_pow_length_20 (bits : List.{0} Bool) : OAI.EditApproximation.bitWordValue bits < 2 ^ bits.length := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitWordValue]) + | cons bit bits ih => + cases bit <;> (simp only [OAI.EditApproximation.bitWordValue, List.length_cons, pow_succ, Bool.toNat_false, Bool.toNat_true]) <;> omega + have proof_bitSubtractWithWork_length_21 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + (OAI.EditApproximation.bitSubtractWithWork left right borrow).1.length = max left.length right.length := by + induction left generalizing right borrow with + | nil => + simp only [OAI.EditApproximation.bitSubtractWithWork] + induction right generalizing borrow with + | nil => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork] + | cons b bs ih => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork, ih] + | cons a as ih => + cases right with + | nil => simp [OAI.EditApproximation.bitSubtractWithWork, ih] + | cons b bs => simp [OAI.EditApproximation.bitSubtractWithWork, ih, Nat.succ_max_succ] + have proof_bitSubtractWithWork_sub_22 (left : List.{0} Bool) (right : List.{0} Bool) (h : LE.le.{0} (OAI.EditApproximation.bitWordValue right) (OAI.EditApproximation.bitWordValue left)) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right false).1 = OAI.EditApproximation.bitWordValue left - OAI.EditApproximation.bitWordValue right := by + have hvalue := proof_bitSubtractWithWork_value_19 left right false + have hlt := proof_bitWordValue_lt_pow_length_20 (OAI.EditApproximation.bitSubtractWithWork left right false).1 + rw [proof_bitSubtractWithWork_length_21] at hlt + cases hb : (OAI.EditApproximation.bitSubtractWithWork left right false).2.1 + · simp only [hb, Bool.toNat_false, Nat.mul_zero, Nat.add_zero] at hvalue + omega + · simp only [hb, Bool.toNat_true, Bool.toNat_false, Nat.mul_one, Nat.add_zero] at hvalue + omega + have proof_bitDivModWithWork_value_23 (divisor : List.{0} Bool) (bits : List.{0} Bool) (hd : LT.lt.{0} 0 (OAI.EditApproximation.bitWordValue divisor)) : + OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).1 + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 < OAI.EditApproximation.bitWordValue divisor := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitDivModWithWork, OAI.EditApproximation.bitWordValue, hd]) + | cons bit bits ih => + let previous := OAI.EditApproximation.bitDivModWithWork divisor bits + let candidate := bit :: previous.2.1 + have hp : OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue previous.1 + + OAI.EditApproximation.bitWordValue previous.2.1 := ih.1 + have hr : OAI.EditApproximation.bitWordValue previous.2.1 < OAI.EditApproximation.bitWordValue divisor := ih.2 + have hc : OAI.EditApproximation.bitWordValue candidate < 2 * OAI.EditApproximation.bitWordValue divisor := by + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + cases bit <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega + by_cases hlt : (OAI.EditApproximation.bitCompareWithWork candidate divisor).1 = .lt + · have hv := (proof_bitCompareWithWork_lt_16 candidate divisor).1 hlt + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 = .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * + OAI.EditApproximation.bitWordValue (false :: previous.1) + OAI.EditApproximation.bitWordValue candidate ∧ OAI.EditApproximation.bitWordValue candidate < _ + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_false]) + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + nlinarith only [hp] + · exact hv + · have hv : OAI.EditApproximation.bitWordValue divisor ≤ OAI.EditApproximation.bitWordValue candidate := by + exact Nat.le_of_not_gt (fun h => hlt ((proof_bitCompareWithWork_lt_16 candidate divisor).2 h)) + have hs := proof_bitSubtractWithWork_sub_22 candidate divisor hv + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 ≠ .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (true :: previous.1) + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 < _ + rw [hs] + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_true]) + have he := Nat.sub_add_cancel hv + dsimp only [candidate, OAI.EditApproximation.bitWordValue] at he ⊢ + nlinarith only [hp, he] + · omega + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_binaryNaturalDivModWithWork_spec_24 (n : ℕ) (d : ℕ) (hd : LT.lt.{0} 0 d) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalDivModWithWork n d).1 = n / d ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalDivModWithWork n d).2.1 = n % d := by + have h := proof_bitDivModWithWork_value_23 d.bits n.bits (by simpa only [proof_bitWordValue_bits_15] using hd) + simp only [proof_bitWordValue_bits_15] at h + have hmod : n % d = OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork d.bits n.bits).2.1 := by + conv_lhs => rw [h.1] + simp only [Nat.add_mod, Nat.mul_mod_right, Nat.zero_add, Nat.mod_eq_of_lt h.2] + have hdiv : n / d = OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork d.bits n.bits).1 := by + conv_lhs => rw [h.1] + rw [Nat.mul_add_div hd, Nat.div_eq_of_lt h.2, Nat.add_zero] + exact ⟨hdiv.symm, hmod.symm⟩ + have proof_bitAdder_value_1 (a : Bool) (b : Bool) (carry : Bool) : + (OAI.EditApproximation.bitSum a b carry).toNat + 2 * (OAI.EditApproximation.bitCarry a b carry).toNat = + a.toNat + b.toNat + carry.toNat := by + cases a <;> cases b <;> cases carry <;> decide + have proof_bitAddWithWork_value_2 (left : List.{0} Bool) (right : List.{0} Bool) (carry : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitAddWithWork left right carry).1 = + OAI.EditApproximation.bitWordValue left + OAI.EditApproximation.bitWordValue right + carry.toNat := by + induction left generalizing right carry with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork] + induction right generalizing carry with + | nil => cases carry <;> simp [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue] + | cons b bs ih => + simp only [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 false b carry + simp only [Bool.toNat_false] at h + omega + | cons a as ih => + cases right with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a false carry + simp only [Bool.toNat_false] at h + omega + | cons b bs => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a b carry + omega + have proof_binaryNaturalAddWithWork_value_52 (a : ℕ) (b : ℕ) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalAddWithWork a b).1 = a + b := by + simp [OAI.EditApproximation.binaryNaturalAddWithWork, proof_bitAddWithWork_value_2, proof_bitWordValue_bits_15] + have proof_bitMulWithWork_value_0 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitMulWithWork left right).1 = OAI.EditApproximation.bitWordValue left * OAI.EditApproximation.bitWordValue right := by + induction left with + | nil => simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue] + | cons bit bits ih => + cases bit <;> simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue, proof_bitAddWithWork_value_2, ih] <;> ring + have proof_binaryNaturalMulWithWork_value_55 (a : ℕ) (b : ℕ) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalMulWithWork a b).1 = a * b := by + simp [OAI.EditApproximation.binaryNaturalMulWithWork, proof_bitMulWithWork_value_0, proof_bitWordValue_bits_15] + have proof_optimizerTriangularMass_succ_66 (K : ℕ) : + OAI.EditApproximation.optimizerTriangularMass (K + 1) = OAI.EditApproximation.optimizerTriangularMass K + (K + 1) := by + unfold OAI.EditApproximation.optimizerTriangularMass + rw [sum_range_succ] + have proof_optimizerTriangularMass_twice_67 (K : ℕ) : + 2 * OAI.EditApproximation.optimizerTriangularMass K = K * (K + 1) := by + induction K with + | zero => simp [OAI.EditApproximation.optimizerTriangularMass] + | succ K ih => + rw [proof_optimizerTriangularMass_succ_66] + nlinarith + have proof_triangularMassWithWork_value_65 (K : ℕ) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.triangularMassWithWork K).1 = OAI.EditApproximation.optimizerTriangularMass K := by + simp only [OAI.EditApproximation.triangularMassWithWork, proof_binaryNaturalAddWithWork_value_52, proof_binaryNaturalMulWithWork_value_55, + (proof_binaryNaturalDivModWithWork_spec_24 _ 2 (by decide)).1] + rw [← proof_optimizerTriangularMass_twice_67 K, Nat.mul_div_cancel_left _ (by decide : 0 < 2)] + have proof_optimizerTriangularMass_positive_77 (K : ℕ) (hK : LT.lt.{0} 0 K) : + 0 < OAI.EditApproximation.optimizerTriangularMass K := by + have hproduct : 0 < K * (K + 1) := Nat.mul_pos hK (by omega) + rw [← proof_optimizerTriangularMass_twice_67 K] at hproduct + omega + exact + let mass := OAI.EditApproximation.triangularMassWithWork K + let divided := OAI.EditApproximation.binaryNaturalDivModWithWork integer (OAI.EditApproximation.bitWordValue mass.1) + (⟨OAI.EditApproximation.bitWordValue divided.2.1, by + rw [(proof_binaryNaturalDivModWithWork_spec_24 integer (OAI.EditApproximation.bitWordValue mass.1) + (by rw [proof_triangularMassWithWork_value_65]; exact proof_optimizerTriangularMass_positive_77 K hK)).2] + rw [proof_triangularMassWithWork_value_65] + exact Nat.mod_lt _ (proof_optimizerTriangularMass_positive_77 K hK)⟩, + mass.2 + divided.2.2 + Nat.size integer + 2) + + +end OAI.EditApproximation.BinaryFraction +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BinaryFraction + + +def countedPreparedActionReadWithWork {M n : ℕ} (mass : Vector OAI.EditApproximation.BinaryFraction M) + (read : ℕ → Fin M × OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) + (eta kappa : OAI.EditApproximation.BinaryFraction) (band : List (Fin M → OAI.EditApproximation.TargetInterval n)) (G j t : ℕ) : + Option (Fin M → OAI.EditApproximation.TargetInterval n) × ℕ := + let coordinates := OAI.EditApproximation.BinaryFraction.coordinateVectorWithWork band + let vertices := OAI.EditApproximation.BinaryFraction.countedBandVerticesWithWork coordinates.1 mass band + let linear := OAI.EditApproximation.vectorMapWithWork _ fun i => + OAI.EditApproximation.BinaryFraction.onlineLinearReadWithWork (fun child => mass.get child) read eta kappa t (coordinates.1.get i) + let selected := OAI.EditApproximation.BinaryFraction.selectionWithWork vertices.1 linear.1 G j + (selected.1, coordinates.2 + vertices.2 + linear.2 + selected.2 + 3) + +def countedPreparedActionKernelAllocation {M n : ℕ} (mass : Vector OAI.EditApproximation.BinaryFraction M) + (read : ℕ → Fin M × OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) + (footprint : ℕ → Fin M × OAI.EditApproximation.TargetInterval n → ℕ) + (eta kappa : OAI.EditApproximation.BinaryFraction) (band : List (Fin M → OAI.EditApproximation.TargetInterval n)) (G j t : ℕ) : ℕ := + let coordinates := (OAI.EditApproximation.BinaryFraction.coordinateVectorWithWork band).1 + let vertices := (OAI.EditApproximation.BinaryFraction.countedBandVerticesWithWork coordinates mass band).1 + let linear := (OAI.EditApproximation.vectorMapWithWork _ fun i => + OAI.EditApproximation.BinaryFraction.onlineLinearReadWithWork (fun child => mass.get child) read eta kappa t (coordinates.get i)).1 + OAI.EditApproximation.BinaryFraction.countedBandVerticesAllocation coordinates mass band + + OAI.EditApproximation.vectorMapAllocation _ (fun i => OAI.EditApproximation.BinaryFraction.onlineLinearReadAllocation (fun child => mass.get child) + read footprint eta kappa t (coordinates.get i)) + OAI.EditApproximation.BinaryFraction.selectionAllocation vertices linear G j + +def countedBandActionReadWithWork {M n : ℕ} (b : ℕ) + (initial : Fin M → OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) + (read : ℕ → Fin M × OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) + (eta kappa : OAI.EditApproximation.BinaryFraction) (band : List (Fin M → OAI.EditApproximation.TargetInterval n)) (G j t : ℕ) : + Option (Fin M → OAI.EditApproximation.TargetInterval n) × ℕ := + let mass := OAI.EditApproximation.BinaryFraction.envelopeVectorReadWithWork b band initial + let selected := OAI.EditApproximation.BinaryFraction.countedPreparedActionReadWithWork mass.1 read eta kappa band G j t + (selected.1, mass.2 + selected.2 + 1) + +def countedPreparedActionAllocation {M n : ℕ} (mass : Vector OAI.EditApproximation.BinaryFraction M) + (read : ℕ → Fin M × OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) + (footprint : ℕ → Fin M × OAI.EditApproximation.TargetInterval n → ℕ) + (eta kappa : OAI.EditApproximation.BinaryFraction) (band : List (Fin M → OAI.EditApproximation.TargetInterval n)) (G j t : ℕ) : ℕ := + OAI.EditApproximation.BinaryFraction.coordinateVectorAllocation band + OAI.EditApproximation.BinaryFraction.countedPreparedActionKernelAllocation mass read footprint eta kappa band G j t + +def countedSampledOnlineReadWithWork {n M : ℕ} (center : OAI.EditApproximation.TargetInterval n) (b : ℕ) + (initial : Fin M → OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) + (read : ℕ → Fin M × OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) + (eta kappa : OAI.EditApproximation.BinaryFraction) (band : List (Fin M → OAI.EditApproximation.TargetInterval n)) (hne : band ≠ []) + (G K t : ℕ) (integer : Fin (OAI.EditApproximation.optimizerTriangularMass K)) : + OAI.EditApproximation.BinaryBellmanAction (OAI.EditApproximation.TargetInterval n) (Fin M × OAI.EditApproximation.TargetInterval n) M × ℕ := + let chosen := OAI.EditApproximation.triangularChoiceWithWork K integer + let selected := OAI.EditApproximation.BinaryFraction.countedBandActionReadWithWork b initial read eta kappa band G chosen.1.val t + let states := selected.1.getD (band.head hne) + (⟨center, OAI.EditApproximation.BinaryFraction.zero, fun i => (i, states i)⟩, chosen.2 + selected.2 + M + 2) + +def countedBandActionAllocation {M n : ℕ} (b : ℕ) + (initial : Fin M → OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) + (initialAllocation : Fin M → OAI.EditApproximation.TargetInterval n → ℕ) + (read : ℕ → Fin M × OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) + (footprint : ℕ → Fin M × OAI.EditApproximation.TargetInterval n → ℕ) + (eta kappa : OAI.EditApproximation.BinaryFraction) (band : List (Fin M → OAI.EditApproximation.TargetInterval n)) (G j t : ℕ) : ℕ := + OAI.EditApproximation.BinaryFraction.envelopeVectorReadAllocation b band initial initialAllocation + + OAI.EditApproximation.BinaryFraction.countedPreparedActionAllocation (OAI.EditApproximation.BinaryFraction.envelopeVectorReadWithWork b band initial).1 + read footprint eta kappa band G j t + +def countedSampledOnlineAllocation {n M : ℕ} (_center : OAI.EditApproximation.TargetInterval n) (b : ℕ) + (initial : Fin M → OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) + (initialAllocation : Fin M → OAI.EditApproximation.TargetInterval n → ℕ) + (read : ℕ → Fin M × OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) + (readAllocation : ℕ → Fin M × OAI.EditApproximation.TargetInterval n → ℕ) + (eta kappa : OAI.EditApproximation.BinaryFraction) (band : List (Fin M → OAI.EditApproximation.TargetInterval n)) (_hne : band ≠ []) + (G K t : ℕ) (integer : Fin (OAI.EditApproximation.optimizerTriangularMass K)) : ℕ := + let chosen := (OAI.EditApproximation.triangularChoiceWithWork K integer).1 + OAI.EditApproximation.triangularChoiceAllocation K integer + + OAI.EditApproximation.BinaryFraction.countedBandActionAllocation b initial initialAllocation read readAllocation eta kappa band G chosen.val t + M + 1 + + +end OAI.EditApproximation.BinaryFraction +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.SourceRanked +variable {σ : Type u_1} {κ : Type u_2} + +def rank (tableRank : κ → ℕ) : Sum σ κ → ℕ + | .inl _ => 0 + | .inr key => tableRank key + 1 + +def keyCode (sourceCode : σ → ℕ) (tableCode : κ → ℕ) : Sum σ κ → ℕ + | .inl source => 2 * sourceCode source + | .inr table => 2 * tableCode table + 1 + +def child (tableRank : κ → ℕ) (parent : κ) : + Sum σ {key : κ // tableRank key < tableRank parent} → + {key : Sum σ κ // OAI.EditApproximation.SourceRanked.rank tableRank key < OAI.EditApproximation.SourceRanked.rank (σ := σ) tableRank (.inr parent)} + | .inl source => ⟨.inl source, Nat.zero_lt_succ _⟩ + | .inr table => ⟨.inr table.val, Nat.add_lt_add_right table.property 1⟩ + +def body (tableRank : κ → ℕ) + (tableBody : (parent : κ) → OAI.EditApproximation.FiniteQuery (Sum σ {key : κ // tableRank key < tableRank parent})) + (sourceValue : σ → ℚ) (key : Sum σ κ) : + OAI.EditApproximation.FiniteQuery {next : Sum σ κ // OAI.EditApproximation.SourceRanked.rank tableRank next < OAI.EditApproximation.SourceRanked.rank tableRank key} := + match key with + | .inl source => .done (sourceValue source) + | .inr table => OAI.EditApproximation.FiniteQuery.mapKeys (OAI.EditApproximation.SourceRanked.child tableRank table) (tableBody table) + +def bitBody (tableRank : κ → ℕ) + (tableBody : (parent : κ) → OAI.EditApproximation.BitQuery (Sum σ {key : κ // tableRank key < tableRank parent}) OAI.EditApproximation.BinaryFraction) + (sourceValue : σ → OAI.EditApproximation.BinaryFraction × ℕ) (key : Sum σ κ) : + OAI.EditApproximation.BitQuery {next : Sum σ κ // OAI.EditApproximation.SourceRanked.rank tableRank next < OAI.EditApproximation.SourceRanked.rank tableRank key} OAI.EditApproximation.BinaryFraction := + match key with + | .inl source => OAI.EditApproximation.BitQuery.compute (sourceValue source) + | .inr table => OAI.EditApproximation.BitQuery.mapKeysWithWork (fun key => (OAI.EditApproximation.SourceRanked.child tableRank table key, 1)) (tableBody table) + + +end OAI.EditApproximation.SourceRanked +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.ChargedPhysicalRequest + + +def depth {M J ny passes copies T S : ℕ} : OAI.EditApproximation.ChargedPhysicalRequest M J ny passes copies T S → ℕ + | .inl entry => J - entry.1.1.val + | .inr request => request.val.remainingDepth + +def index {M J ny passes copies T S : ℕ} : OAI.EditApproximation.ChargedPhysicalRequest M J ny passes copies T S → ℕ + | .inl _ => 0 + | .inr request => request.val.rank T S + 1 + +def rank {M J ny passes copies T S : ℕ} + (request : OAI.EditApproximation.ChargedPhysicalRequest M J ny passes copies T S) : ℕ := + request.depth + request.index + + +end OAI.EditApproximation.ChargedPhysicalRequest +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation + + +def chargedPreviousRead {M J ny passes copies T S : ℕ} + (parent : {r : OAI.EditApproximation.PhysicalTableRequest M J ny // r.Bounded passes copies T S}) + (hpass : 0 < parent.val.pass) (state : OAI.EditApproximation.TargetInterval ny) (copy : Fin copies) : + OAI.EditApproximation.FiniteQuery {child : OAI.EditApproximation.ChargedPhysicalRequest M J ny passes copies T S // + child.rank < OAI.EditApproximation.ChargedPhysicalRequest.rank (Sum.inr parent)} := by + have proof_table_rank_lt_99 {M : ℕ} {J : ℕ} {ny : ℕ} {passes : ℕ} {copies : ℕ} {T : ℕ} {S : ℕ} (parent : Subtype.{1} fun request => OAI.EditApproximation.PhysicalTableRequest.Bounded (M := M) (J := J) (ny := ny) passes copies T S request) (child : Subtype.{1} fun request => OAI.EditApproximation.PhysicalTableRequest.Bounded (M := M) (J := J) (ny := ny) passes copies T S request) (h : LT.lt.{0} (OAI.EditApproximation.PhysicalTableRequest.combinedRank T S child.val) + (OAI.EditApproximation.PhysicalTableRequest.combinedRank T S parent.val)) : + OAI.EditApproximation.ChargedPhysicalRequest.rank (Sum.inr child : OAI.EditApproximation.ChargedPhysicalRequest M J ny passes copies T S) < OAI.EditApproximation.ChargedPhysicalRequest.rank (Sum.inr parent) := by + simpa only [OAI.EditApproximation.ChargedPhysicalRequest.rank, OAI.EditApproximation.ChargedPhysicalRequest.depth, OAI.EditApproximation.ChargedPhysicalRequest.index, ← Nat.add_assoc, OAI.EditApproximation.PhysicalTableRequest.combinedRank] using + Nat.add_lt_add_right h 1 + have proof_combinedRank_lt_of_progress_80 {M : ℕ} {J : ℕ} {ny : ℕ} (T : ℕ) (S : ℕ) (first : OAI.EditApproximation.PhysicalTableRequest M J ny) (second : OAI.EditApproximation.PhysicalTableRequest M J ny) (hprogress : LT.lt.{0} second.remainingDepth first.remainingDepth ∧ + LE.le.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first) ∨ + LE.le.{0} second.remainingDepth first.remainingDepth ∧ + LT.lt.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first)) : + OAI.EditApproximation.PhysicalTableRequest.combinedRank T S second < OAI.EditApproximation.PhysicalTableRequest.combinedRank T S first := by + unfold OAI.EditApproximation.PhysicalTableRequest.combinedRank + rcases hprogress with h | h + · exact Nat.add_lt_add_of_lt_of_le h.1 h.2 + · exact Nat.add_lt_add_of_le_of_lt h.1 h.2 + have proof_rank_lt_previous_pass_98 {M : ℕ} {J : ℕ} {ny : ℕ} (T : ℕ) (S : ℕ) (first : OAI.EditApproximation.PhysicalTableRequest M J ny) (second : OAI.EditApproximation.PhysicalTableRequest M J ny) (hpass : LT.lt.{0} second.pass first.pass) (hindex : LE.le.{0} second.index (HAdd.hAdd.{0, 0, 0} T S)) : + OAI.EditApproximation.PhysicalTableRequest.rank T S second < OAI.EditApproximation.PhysicalTableRequest.rank T S first := by + have hblock : second.pass * (T + S + 1) + second.index < + (second.pass + 1) * (T + S + 1) := by + nlinarith only [hindex] + have hnext := Nat.mul_le_mul_right (T + S + 1) (Nat.succ_le_of_lt hpass) + exact hblock.trans_le (hnext.trans (Nat.le_add_right _ _)) + have proof_previousPassRequest_progress_97 {M : ℕ} {J : ℕ} {ny : ℕ} (T : ℕ) (S : ℕ) (copy : ℕ) (parent : OAI.EditApproximation.PhysicalTableRequest M J ny) (hpass : LT.lt.{0} 0 parent.pass) (state : OAI.EditApproximation.TargetInterval ny) : + (OAI.EditApproximation.previousPassRequest T S copy parent state).remainingDepth = parent.remainingDepth ∧ + (OAI.EditApproximation.previousPassRequest T S copy parent state).rank T S < parent.rank T S := by + refine ⟨rfl, ?_⟩ + exact proof_rank_lt_previous_pass_98 T S parent _ (by + change parent.pass - 1 < parent.pass + omega) le_rfl + exact + .read ⟨Sum.inr (OAI.EditApproximation.chargedPreviousPass parent state copy), by + apply proof_table_rank_lt_99 + apply proof_combinedRank_lt_of_progress_80 T S parent.val _ + exact Or.inr ⟨(proof_previousPassRequest_progress_97 T S copy.val parent.val hpass state).1.le, + (proof_previousPassRequest_progress_97 T S copy.val parent.val hpass state).2⟩⟩ .done + +def chargedWarmupChild {M J ny passes copies T S : ℕ} + (parent : {r : OAI.EditApproximation.PhysicalTableRequest M J ny // r.Bounded passes copies T S}) + (hbelow : parent.val.node.1.val < J) (hindex : 0 < parent.val.index) + (input : Fin M × OAI.EditApproximation.TargetInterval ny) : + OAI.EditApproximation.FiniteQuery {child : OAI.EditApproximation.ChargedPhysicalRequest M J ny passes copies T S // + child.rank < OAI.EditApproximation.ChargedPhysicalRequest.rank (Sum.inr parent)} := by + have proof_table_rank_lt_99 {M : ℕ} {J : ℕ} {ny : ℕ} {passes : ℕ} {copies : ℕ} {T : ℕ} {S : ℕ} (parent : Subtype.{1} fun request => OAI.EditApproximation.PhysicalTableRequest.Bounded (M := M) (J := J) (ny := ny) passes copies T S request) (child : Subtype.{1} fun request => OAI.EditApproximation.PhysicalTableRequest.Bounded (M := M) (J := J) (ny := ny) passes copies T S request) (h : LT.lt.{0} (OAI.EditApproximation.PhysicalTableRequest.combinedRank T S child.val) + (OAI.EditApproximation.PhysicalTableRequest.combinedRank T S parent.val)) : + OAI.EditApproximation.ChargedPhysicalRequest.rank (Sum.inr child : OAI.EditApproximation.ChargedPhysicalRequest M J ny passes copies T S) < OAI.EditApproximation.ChargedPhysicalRequest.rank (Sum.inr parent) := by + simpa only [OAI.EditApproximation.ChargedPhysicalRequest.rank, OAI.EditApproximation.ChargedPhysicalRequest.depth, OAI.EditApproximation.ChargedPhysicalRequest.index, ← Nat.add_assoc, OAI.EditApproximation.PhysicalTableRequest.combinedRank] using + Nat.add_lt_add_right h 1 + have proof_combinedRank_lt_of_progress_80 {M : ℕ} {J : ℕ} {ny : ℕ} (T : ℕ) (S : ℕ) (first : OAI.EditApproximation.PhysicalTableRequest M J ny) (second : OAI.EditApproximation.PhysicalTableRequest M J ny) (hprogress : LT.lt.{0} second.remainingDepth first.remainingDepth ∧ + LE.le.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first) ∨ + LE.le.{0} second.remainingDepth first.remainingDepth ∧ + LT.lt.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first)) : + OAI.EditApproximation.PhysicalTableRequest.combinedRank T S second < OAI.EditApproximation.PhysicalTableRequest.combinedRank T S first := by + unfold OAI.EditApproximation.PhysicalTableRequest.combinedRank + rcases hprogress with h | h + · exact Nat.add_lt_add_of_lt_of_le h.1 h.2 + · exact Nat.add_lt_add_of_le_of_lt h.1 h.2 + have proof_warmup_previous_child_progress_81 {M : ℕ} {J : ℕ} {ny : ℕ} (pass : ℕ) (copy : ℕ) (T : ℕ) (S : ℕ) (j : ℕ) (node : OAI.EditApproximation.PhysicalNode M J) (hbelow : LT.lt.{0} (↑(Sigma.fst.{0, 0} node)) J) (i : Fin M) (state : OAI.EditApproximation.TargetInterval ny) (previousState : OAI.EditApproximation.TargetInterval ny) (hj : LT.lt.{0} 0 j) : + (OAI.EditApproximation.PhysicalTableRequest.warmup pass copy (OAI.EditApproximation.physicalChild node hbelow i) (j - 1) previousState).remainingDepth < + (OAI.EditApproximation.PhysicalTableRequest.warmup pass copy node j state).remainingDepth ∧ + OAI.EditApproximation.PhysicalTableRequest.rank T S (OAI.EditApproximation.PhysicalTableRequest.warmup pass copy (OAI.EditApproximation.physicalChild node hbelow i) (j - 1) previousState) < + OAI.EditApproximation.PhysicalTableRequest.rank T S (OAI.EditApproximation.PhysicalTableRequest.warmup pass copy node j state) := by + constructor + · unfold OAI.EditApproximation.PhysicalTableRequest.remainingDepth OAI.EditApproximation.PhysicalTableRequest.warmup OAI.EditApproximation.physicalChild + dsimp only + omega + · dsimp only [OAI.EditApproximation.PhysicalTableRequest.rank, OAI.EditApproximation.PhysicalTableRequest.warmup] + omega + have proof_combinedRank_warmup_child_79 {M : ℕ} {J : ℕ} {ny : ℕ} (pass : ℕ) (copy : ℕ) (T : ℕ) (S : ℕ) (j : ℕ) (node : OAI.EditApproximation.PhysicalNode M J) (hbelow : LT.lt.{0} (↑(Sigma.fst.{0, 0} node)) J) (i : Fin M) (state : OAI.EditApproximation.TargetInterval ny) (previousState : OAI.EditApproximation.TargetInterval ny) (hj : LT.lt.{0} 0 j) : + OAI.EditApproximation.PhysicalTableRequest.combinedRank T S (OAI.EditApproximation.PhysicalTableRequest.warmup pass copy (OAI.EditApproximation.physicalChild node hbelow i) (j - 1) previousState) < + OAI.EditApproximation.PhysicalTableRequest.combinedRank T S (OAI.EditApproximation.PhysicalTableRequest.warmup pass copy node j state) := + proof_combinedRank_lt_of_progress_80 T S _ _ (Or.inr + ⟨(proof_warmup_previous_child_progress_81 pass copy T S j node hbelow i state previousState hj).1.le, + (proof_warmup_previous_child_progress_81 pass copy T S j node hbelow i state previousState hj).2⟩) + exact + .read ⟨Sum.inr ⟨OAI.EditApproximation.PhysicalTableRequest.warmup parent.val.pass parent.val.copy + (OAI.EditApproximation.physicalChild parent.val.node hbelow input.1) (parent.val.index - 1) input.2, + parent.property.1, parent.property.2.1, + (Nat.sub_le _ _).trans parent.property.2.2⟩, by + apply proof_table_rank_lt_99 + exact proof_combinedRank_warmup_child_79 parent.val.pass parent.val.copy T S + parent.val.index parent.val.node hbelow input.1 parent.val.state input.2 hindex⟩ .done + +def chargedSeedQuery {M J ny passes copies T S : ℕ} (N : ℕ) (multiplier : ℕ → ℕ) + (parent : {r : OAI.EditApproximation.PhysicalTableRequest M J ny // r.Bounded passes copies T S}) + (state : OAI.EditApproximation.PhysicalEntry M J ny) : + OAI.EditApproximation.FiniteQuery {child : OAI.EditApproximation.ChargedPhysicalRequest M J ny passes copies T S // + child.rank < OAI.EditApproximation.ChargedPhysicalRequest.rank (Sum.inr parent)} := by + have proof_coarse_rank_lt_100 {M : ℕ} {J : ℕ} {ny : ℕ} {passes : ℕ} {copies : ℕ} {T : ℕ} {S : ℕ} (entry : OAI.EditApproximation.PhysicalEntry M J ny) (request : Subtype.{1} fun request => OAI.EditApproximation.PhysicalTableRequest.Bounded (M := M) (J := J) (ny := ny) passes copies T S request) (hnode : Eq.{1} entry.1 request.val.node) : + OAI.EditApproximation.ChargedPhysicalRequest.rank (Sum.inl entry : OAI.EditApproximation.ChargedPhysicalRequest M J ny passes copies T S) < OAI.EditApproximation.ChargedPhysicalRequest.rank (Sum.inr request) := by + change J - entry.1.1.val + 0 < request.val.remainingDepth + (request.val.rank T S + 1) + rw [hnode] + unfold OAI.EditApproximation.PhysicalTableRequest.remainingDepth + omega + exact + if hn : state.1 = parent.val.node then + if hp : parent.val.pass = 0 then + .read ⟨Sum.inl state, proof_coarse_rank_lt_100 state parent hn⟩ .done + else OAI.EditApproximation.FiniteQuery.collect (OAI.EditApproximation.chargedPreviousRead parent (Nat.pos_of_ne_zero hp) state.2) + (List.finRange copies) fun values => + .done (min N (OAI.EditApproximation.upperMedian (values.map fun value => + ⌈(multiplier (parent.val.pass - 1) : ℚ) * value⌉₊)) : ℕ) + else .done 0 + +def chargedWarmupQuery {α : Type u_1} [DecidableEq α] {M J passes copies T S : ℕ} + (source target : List α) (N P F : ℕ) (factor : ℕ → ℚ) (multiplier : ℕ → ℕ) + (parent : {r : OAI.EditApproximation.PhysicalTableRequest M J target.length // r.Bounded passes copies T S}) : + OAI.EditApproximation.FiniteQuery {child : OAI.EditApproximation.ChargedPhysicalRequest M J target.length passes copies T S // + child.rank < OAI.EditApproximation.ChargedPhysicalRequest.rank (Sum.inr parent)} := + if hz : parent.val.index = 0 then + OAI.EditApproximation.physicalInitialQuery source target N P F (factor parent.val.pass) + (OAI.EditApproximation.chargedSeedQuery N multiplier parent) (parent.val.node, parent.val.state) + else if hbelow : parent.val.node.1.val < J then + if (OAI.EditApproximation.physicalSourceInterval source.length parent.val.node).hi - + (OAI.EditApproximation.physicalSourceInterval source.length parent.val.node).lo ≤ 1 then + OAI.EditApproximation.physicalInitialQuery source target N P F (factor parent.val.pass) + (OAI.EditApproximation.chargedSeedQuery N multiplier parent) (parent.val.node, parent.val.state) + else OAI.EditApproximation.physicalWarmupStepQuery source target N P F (factor parent.val.pass) + (OAI.EditApproximation.chargedSeedQuery N multiplier parent) + (OAI.EditApproximation.chargedWarmupChild parent hbelow (Nat.pos_of_ne_zero hz)) parent.val.node parent.val.state + else OAI.EditApproximation.physicalInitialQuery source target N P F (factor parent.val.pass) + (OAI.EditApproximation.chargedSeedQuery N multiplier parent) (parent.val.node, parent.val.state) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open EditDistortion Finset MeasureTheory ProbabilityTheory + +abbrev coarseEntryWidth {α : Type u} (x y : List α) : ℕ := max x.length y.length + +abbrev CoarseGuessIndex (n : ℕ) := Fin (Nat.clog 2 n + 1) + +def coarseGuess (n : ℕ) (i : OAI.EditApproximation.CoarseGuessIndex n) : ℕ := 2 ^ i.val + +def coarseEntryTree (B D : ℕ) {α : Type u} (x y : List α) : OAI.EditApproximation.CoarseSourceTree B (Option α) D := + OAI.EditApproximation.coarseSourceTreeOfList B D (OAI.EditApproximation.coarsePadTo (OAI.EditApproximation.coarseEntryWidth x y) x) + +noncomputable def coarseInitialMeasure (B D n : ℕ) [NeZero B] + [MeasurableSpace (Fin B)] [MeasurableSingletonClass (Fin B)] : + Measure (OAI.EditApproximation.CoarseGuessIndex n → OAI.EditApproximation.CoarseThresholdDraws B D) := + Measure.pi fun _ => OAI.EditApproximation.coarseDrawMeasure B D + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open Finset MeasureTheory ProbabilityTheory + +def coarseActiveChildrenWork {B D : ℕ} {α : Type u} + (Q lam allowance : ℚ) + (work : OAI.EditApproximation.CoarseSourceTree B α D → OAI.EditApproximation.CoarseThresholdDraws B D → ℚ → ℕ) : + List (OAI.EditApproximation.CoarseSourceTree B α D × Fin B × OAI.EditApproximation.CoarseThresholdDraws B D) → ℕ + | [] => 0 + | (child, draw, below) :: rest => + work child below (lam * OAI.EditApproximation.coarseChildThreshold B Q allowance draw) + + coarseActiveChildrenWork Q lam allowance work rest + +abbrev CoarseFullSeedDraws (B : ℕ) {I : Type u_1} {α : Type u_2} (depth : I → ℕ) (x y : I → List α) := + ∀ i, OAI.EditApproximation.CoarseGuessIndex (OAI.EditApproximation.coarseEntryWidth (x i) (y i)) → OAI.EditApproximation.CoarseThresholdDraws B (depth i) + +noncomputable def coarseFullSeedMeasure (B : ℕ) [NeZero B] + {I : Type u_1} {α : Type u_2} [Fintype I] (depth : I → ℕ) (x y : I → List α) + [MeasurableSpace (Fin B)] [MeasurableSingletonClass (Fin B)] : + Measure (OAI.EditApproximation.CoarseFullSeedDraws B depth x y) := + Measure.pi fun i => OAI.EditApproximation.coarseInitialMeasure B (depth i) (OAI.EditApproximation.coarseEntryWidth (x i) (y i)) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open MeasureTheory ProbabilityTheory +variable {ι : Type u_1} [Fintype ι] (range : ι → ℕ) [∀ i, NeZero (range i)] + +noncomputable def rejectionAcceptedLaw : Measure (∀ i, Fin (range i)) := + Measure.pi fun i => (PMF.uniformOfFintype (Fin (range i))).toMeasure + +abbrev RejectionRuntimeArray := (ι → ℕ) × (∀ i, Fin (range i)) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BinaryMemo + + +def fractionStorage : OAI.EditApproximation.BinaryMemo OAI.EditApproximation.BinaryFraction → ℕ + | .empty => 0 + | .node value left right => + 3 + (value.map fun word => word.numerator.bits.length + word.denominator.length + 1).getD 0 + + left.fractionStorage + right.fractionStorage + +def valueStorage {α : Type u_1} (bits : α → ℕ) : OAI.EditApproximation.BinaryMemo α → ℕ + | .empty => 0 + | .node value l r => 3 + (value.map bits).getD 0 + valueStorage bits l + valueStorage bits r + + +end OAI.EditApproximation.BinaryMemo +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open Filter + +def indexedLeafWithWork (table : OAI.EditApproximation.BinaryMemo OAI.EditApproximation.PositionCounts) (symbolBits positionBits : ℕ) + (symbol : Option ℕ) (lo hi : ℕ) : ℕ × ℕ := + match symbol with + | none => (hi - lo, 2) + | some a => OAI.EditApproximation.indexedSingletonCostWithWork table symbolBits positionBits a lo hi + +def integerOccurrenceStorage (source target : List ℤ) : ℕ := + OAI.EditApproximation.BinaryMemo.valueStorage OAI.EditApproximation.PositionCounts.storageBits (OAI.EditApproximation.integerOccurrenceIndex source target) + +def integerStoredDataSpace (source target : List ℤ) : ℕ := + OAI.EditApproximation.storedIntegerBits source + OAI.EditApproximation.storedIntegerBits target + + OAI.EditApproximation.storedNaturalBits (source.map OAI.EditApproximation.integerSymbolCode) + OAI.EditApproximation.storedNaturalBits (target.map OAI.EditApproximation.integerSymbolCode) + + OAI.EditApproximation.integerOccurrenceStorage source target + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation + + +def binaryIndexedLeafWithWork (table : OAI.EditApproximation.BinaryMemo OAI.EditApproximation.PositionCounts) (symbolBits positionBits : ℕ) + (symbol : Option ℕ) (lo hi : ℕ) : OAI.EditApproximation.BinaryFraction × ℕ := + let result := OAI.EditApproximation.indexedLeafWithWork table symbolBits positionBits symbol lo hi + (OAI.EditApproximation.BinaryFraction.nat result.1, result.2 + Nat.size result.1 + 2) + +def binaryIndexedLeafAllocation (table : OAI.EditApproximation.BinaryMemo OAI.EditApproximation.PositionCounts) (symbolBits positionBits : ℕ) + (symbol : Option ℕ) (lo hi : ℕ) : ℕ := + OAI.EditApproximation.indexedLeafAllocation symbolBits positionBits symbol lo hi + + Nat.size (OAI.EditApproximation.indexedLeafWithWork table symbolBits positionBits symbol lo hi).1 + 2 + +def queryIndexedSliceWithWork (source : List ℕ) (interval : OAI.EditApproximation.TargetInterval source.length) + (targetLength : ℕ) (q : OAI.EditApproximation.TargetInterval targetLength) + (occurrence : OAI.EditApproximation.BinaryMemo OAI.EditApproximation.PositionCounts) (symbolBits positionBits : ℕ) : OAI.EditApproximation.BinaryFraction × ℕ := + let symbol := OAI.EditApproximation.querySliceHeadWithWork source interval + let result := OAI.EditApproximation.binaryIndexedLeafWithWork occurrence symbolBits positionBits symbol.1 q.lo q.hi + (result.1, symbol.2 + result.2 + 1) + +def queryIndexedSliceAllocation (source : List ℕ) (interval : OAI.EditApproximation.TargetInterval source.length) + (targetLength : ℕ) (q : OAI.EditApproximation.TargetInterval targetLength) + (occurrence : OAI.EditApproximation.BinaryMemo OAI.EditApproximation.PositionCounts) (symbolBits positionBits : ℕ) : ℕ := + interval.lo.bits.length + interval.hi.bits.length + 1 + + OAI.EditApproximation.binaryIndexedLeafAllocation occurrence symbolBits positionBits (OAI.EditApproximation.querySliceHeadWithWork source interval).1 q.lo q.hi + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BinaryFraction +variable {n : ℕ} (read : TargetInterval n → List Bool × ℕ) (allocation : TargetInterval n → ℕ) + +def initialGridReadAllocation (P : ℕ) (A : OAI.EditApproximation.BinaryFraction) (radius : ℕ) (q : OAI.EditApproximation.TargetInterval n) (b : ℕ) : ℕ := + let spacing := (OAI.EditApproximation.seedGridSpacingWithWork b P).1 + let points := (OAI.EditApproximation.gridStateBoxWithWork n (OAI.EditApproximation.bitWordValue spacing) radius q.lo q.hi).1 + OAI.EditApproximation.seedGridSpacingAllocation b P + OAI.EditApproximation.gridStateBoxAllocation n (OAI.EditApproximation.bitWordValue spacing) radius q.lo q.hi + + OAI.EditApproximation.filterAllocation (fun r => ((OAI.EditApproximation.BinaryFraction.initialCenterGuardWithWork b (OAI.EditApproximation.bitWordValue (read r).1) A).1, + (OAI.EditApproximation.BinaryFraction.initialCenterGuardWithWork b (OAI.EditApproximation.bitWordValue (read r).1) A).2 + (read r).2)) + (fun r => OAI.EditApproximation.BinaryFraction.initialCenterGuardAllocation b (OAI.EditApproximation.bitWordValue (read r).1) A + allocation r) points + +def initialConeReadAllocation (sourceLength : ℕ) (a L : OAI.EditApproximation.BinaryFraction) (query center : OAI.EditApproximation.TargetInterval n) : ℕ := + allocation center + OAI.EditApproximation.BinaryFraction.initialConeAllocation sourceLength (OAI.EditApproximation.bitWordValue (read center).1) a L query center + +def initialCentersReadAllocation (N P : ℕ) (A : OAI.EditApproximation.BinaryFraction) (q : OAI.EditApproximation.TargetInterval n) : ℕ := + let Uq := OAI.EditApproximation.bitWordValue (read q).1 + let scales := (OAI.EditApproximation.dyadicScalesWithWork N).1 + let active := (OAI.EditApproximation.filterWithWork (fun b => OAI.EditApproximation.BinaryFraction.initialScaleGuardWithWork Uq b A) scales).1 + allocation q + OAI.EditApproximation.dyadicScalesAllocation N + + OAI.EditApproximation.filterAllocation (fun b => OAI.EditApproximation.BinaryFraction.initialScaleGuardWithWork Uq b A) (fun b => OAI.EditApproximation.BinaryFraction.initialScaleGuardAllocation Uq b A) scales + + OAI.EditApproximation.arithmeticFlatMapAllocation (OAI.EditApproximation.BinaryFraction.initialGridReadWithWork P A read Uq q) + (OAI.EditApproximation.BinaryFraction.initialGridReadAllocation read allocation P A Uq q) active + +def initialMinimumReadAllocation (sourceLength N F : ℕ) (a : OAI.EditApproximation.BinaryFraction) + (query : OAI.EditApproximation.TargetInterval n) (centers : List (OAI.EditApproximation.TargetInterval n)) : ℕ := + let Uq := OAI.EditApproximation.bitWordValue (read query).1 + allocation query + OAI.EditApproximation.naturalEqualAllocation Uq 0 + + if (OAI.EditApproximation.naturalEqualWithWork Uq 0).1 then 0 else + let L := (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 32) (OAI.EditApproximation.BinaryFraction.nat F)).1 + let coefficient := (OAI.EditApproximation.BinaryFraction.canonicalAddWithWork L OAI.EditApproximation.BinaryFraction.one).1 + let fallback := (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork coefficient (OAI.EditApproximation.BinaryFraction.nat N)).1 + let scores := (OAI.EditApproximation.arithmeticMapWithWork (OAI.EditApproximation.BinaryFraction.initialConeReadWithWork sourceLength read a L query) centers).1 + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation (OAI.EditApproximation.BinaryFraction.nat 32) (OAI.EditApproximation.BinaryFraction.nat F) + OAI.EditApproximation.BinaryFraction.canonicalAddAllocation L OAI.EditApproximation.BinaryFraction.one + + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation coefficient (OAI.EditApproximation.BinaryFraction.nat N) + + OAI.EditApproximation.arithmeticMapAllocation (OAI.EditApproximation.BinaryFraction.initialConeReadAllocation read allocation sourceLength a L query) centers + + OAI.EditApproximation.BinaryFraction.minimumAllocation fallback scores + Nat.size F + Nat.size N + +def initialProgramReadAllocation (sourceLength N P F : ℕ) (A a : OAI.EditApproximation.BinaryFraction) (query : OAI.EditApproximation.TargetInterval n) : ℕ := + OAI.EditApproximation.BinaryFraction.initialCentersReadAllocation read allocation N P A query + OAI.EditApproximation.BinaryFraction.initialMinimumReadAllocation read allocation sourceLength N F a + query (OAI.EditApproximation.BinaryFraction.initialCentersReadWithWork N P A read query).1 + +def cachedInitialProgramReadAllocation (sourceLength N P F : ℕ) (A a : OAI.EditApproximation.BinaryFraction) (query : OAI.EditApproximation.TargetInterval n) : ℕ := + OAI.EditApproximation.BinaryFraction.finishCachedAllocation (OAI.EditApproximation.BinaryFraction.initialProgramReadWithWork sourceLength N P F A a read query) + (OAI.EditApproximation.BinaryFraction.initialProgramReadAllocation read allocation sourceLength N P F A a query) [true] (by decide) 0 + + +end OAI.EditApproximation.BinaryFraction +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BinaryFraction +open BinaryFraction + +def onlineParametersAllocation (word : List Bool) : ℕ := + OAI.EditApproximation.bitPowerAllocation word 5 + OAI.EditApproximation.bitPowerAllocation word 4 + 2 + +def refinementDecrementAllocation (word : List Bool) : ℕ := OAI.EditApproximation.bitPowerAllocation word 10 + 1 + + +end OAI.EditApproximation.BinaryFraction +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open BinaryFraction + +def scheduledRefinementAllocation (N pass : ℕ) : ℕ := + if pass < OAI.EditApproximation.computedSeedPassCount N then + OAI.EditApproximation.BinaryFraction.signedPowerTwoAllocation ((OAI.EditApproximation.dyadicSeedExponent (OAI.EditApproximation.smallLogExponent N) + (OAI.EditApproximation.computedSeedInitialExponent N) pass - OAI.EditApproximation.smallLogExponent N : ℕ) : ℤ) + 2 + else 2 + +def refinementBaseAllocation (word : List Bool) : ℕ := + let power := OAI.EditApproximation.bitPowerWithWork word 10 + let increment := OAI.EditApproximation.bitAddWithWork power.1 [true] false + OAI.EditApproximation.bitPowerAllocation word 10 + OAI.EditApproximation.bitAddAllocation power.1 [true] false + + OAI.EditApproximation.trimBitWordAllocation increment.1 + 2 + +def refinementParameterAllocation (N pass : ℕ) (word : List Bool) : ℕ := + OAI.EditApproximation.BinaryFraction.onlineParametersAllocation word + OAI.EditApproximation.scheduledRefinementAllocation N pass + + OAI.EditApproximation.BinaryFraction.refinementDecrementAllocation word + 5 + +def computedQueryPassAllocation (N pass : ℕ) : ℕ := + OAI.EditApproximation.BinaryFraction.signedPowerTwoAllocation ((OAI.EditApproximation.dyadicSeedExponent (OAI.EditApproximation.smallLogExponent N) (OAI.EditApproximation.computedSeedInitialExponent N) pass : ℕ) : ℤ) + + OAI.EditApproximation.refinementParameterAllocation N pass (OAI.EditApproximation.inputSmallLog N).bits + 2 + +def computedQuerySetupAllocation (N : ℕ) : ℕ := + OAI.EditApproximation.vectorMapAllocation (OAI.EditApproximation.computedSeedPassCount N + 1) (fun i => OAI.EditApproximation.computedQueryPassAllocation N i.val) + + OAI.EditApproximation.refinementBaseAllocation (OAI.EditApproximation.inputSmallLog N).bits + 5 + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.UnreducedRational +open Finset + +def nat (n : ℕ) : OAI.EditApproximation.UnreducedRational := ⟨n, 1, by decide⟩ + + +end OAI.EditApproximation.UnreducedRational +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BinaryFraction + +open Finset + +def countedGroupMemberSourceWithWork {M T : ℕ} (Q b : ℕ) (scales : Fin T → OAI.EditApproximation.BinaryFraction) + (connection : OAI.EditApproximation.BinaryFraction) (envelope values : Vector OAI.EditApproximation.BinaryFraction M) + (draw : ∀ t, Fin (OAI.EditApproximation.groupSampleCount M Q b (scales t).value) → Fin M × ℕ) : OAI.EditApproximation.BinaryFraction × ℕ := by + have proof_vectorMapWithWork_value_27 {α : Type 0} (d : ℕ) (f : Fin d → Prod.{0, 0} α ℕ) (i : Fin d) : + (OAI.EditApproximation.vectorMapWithWork d f).1.get i = (f i).1 := by + change (Vector.ofFn f |>.map Prod.fst)[i.val] = _ + simp only [Vector.getElem_map, Vector.getElem_ofFn] + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_wordLEWithWork_value_26 (a : List.{0} Bool) (b : List.{0} Bool) : + (OAI.EditApproximation.wordLEWithWork a b).1 = true ↔ OAI.EditApproximation.bitWordValue a ≤ OAI.EditApproximation.bitWordValue b := by + simp only [OAI.EditApproximation.wordLEWithWork, Bool.not_eq_true', decide_eq_false_iff_not, + proof_bitCompareWithWork_lt_16, not_lt] + have proof_wordMinWithWork_value_29 (a : List.{0} Bool) (b : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.wordMinWithWork a b).1 = min (OAI.EditApproximation.bitWordValue a) (OAI.EditApproximation.bitWordValue b) := by + unfold OAI.EditApproximation.wordMinWithWork + dsimp only + split_ifs with h + · exact (min_eq_left ((proof_wordLEWithWork_value_26 a b).mp h)).symm + · exact (min_eq_right (le_of_not_ge (fun hle => h ((proof_wordLEWithWork_value_26 a b).mpr hle)))).symm + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_bitSubtractor_value_17 (a : Bool) (b : Bool) (borrow : Bool) : + a.toNat + 2 * (OAI.EditApproximation.bitBorrow a b borrow).toNat = + b.toNat + borrow.toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat := by + cases a <;> cases b <;> cases borrow <;> decide + have proof_bitSubtractionRippleEquation_18 (a : ℕ) (b : ℕ) (borrow : ℕ) (nextBorrow : ℕ) (difference : ℕ) (left : ℕ) (right : ℕ) (result : ℕ) (tail : ℕ) (htail : Eq.{1} (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} result right) nextBorrow) (HAdd.hAdd.{0, 0, 0} left tail)) (hbit : Eq.{1} (HAdd.hAdd.{0, 0, 0} a (HMul.hMul.{0, 0, 0} 2 nextBorrow)) + (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} b borrow) difference)) : + (difference + 2 * result) + (b + 2 * right) + borrow = + (a + 2 * left) + 2 * tail := by + omega + have proof_bitSubtractWithWork_value_19 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right borrow).1 + OAI.EditApproximation.bitWordValue right + borrow.toNat = + OAI.EditApproximation.bitWordValue left + 2 ^ max left.length right.length * + (OAI.EditApproximation.bitSubtractWithWork left right borrow).2.1.toNat := by + induction left generalizing right borrow with + | nil => + induction right generalizing borrow with + | nil => (simp [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + have h := ih (OAI.EditApproximation.bitBorrow false b borrow) + have hb := proof_bitSubtractor_value_17 false b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue, + List.length_nil, List.length_cons, Nat.zero_max, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 0 b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow false b borrow).toNat + (OAI.EditApproximation.bitDifference false b borrow).toNat 0 (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).1) + (2 ^ bs.length * (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons a as ih => + cases right with + | nil => + have h := ih [] (OAI.EditApproximation.bitBorrow a false borrow) + have hb := proof_bitSubtractor_value_17 a false borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_nil, List.length_cons, + Nat.max_zero, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat 0 borrow.toNat (OAI.EditApproximation.bitBorrow a false borrow).toNat + (OAI.EditApproximation.bitDifference a false borrow).toNat (OAI.EditApproximation.bitWordValue as) 0 + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).1) + (2 ^ as.length * (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons b bs => + have h := ih bs (OAI.EditApproximation.bitBorrow a b borrow) + have hb := proof_bitSubtractor_value_17 a b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_cons, Nat.succ_max_succ, + pow_succ] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow a b borrow).toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).1) + (2 ^ max as.length bs.length * (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_assoc, Nat.mul_left_comm] using hs + have proof_bitWordValue_lt_pow_length_20 (bits : List.{0} Bool) : OAI.EditApproximation.bitWordValue bits < 2 ^ bits.length := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitWordValue]) + | cons bit bits ih => + cases bit <;> (simp only [OAI.EditApproximation.bitWordValue, List.length_cons, pow_succ, Bool.toNat_false, Bool.toNat_true]) <;> omega + have proof_bitSubtractWithWork_length_21 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + (OAI.EditApproximation.bitSubtractWithWork left right borrow).1.length = max left.length right.length := by + induction left generalizing right borrow with + | nil => + simp only [OAI.EditApproximation.bitSubtractWithWork] + induction right generalizing borrow with + | nil => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork] + | cons b bs ih => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork, ih] + | cons a as ih => + cases right with + | nil => simp [OAI.EditApproximation.bitSubtractWithWork, ih] + | cons b bs => simp [OAI.EditApproximation.bitSubtractWithWork, ih, Nat.succ_max_succ] + have proof_bitSubtractWithWork_sub_22 (left : List.{0} Bool) (right : List.{0} Bool) (h : LE.le.{0} (OAI.EditApproximation.bitWordValue right) (OAI.EditApproximation.bitWordValue left)) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right false).1 = OAI.EditApproximation.bitWordValue left - OAI.EditApproximation.bitWordValue right := by + have hvalue := proof_bitSubtractWithWork_value_19 left right false + have hlt := proof_bitWordValue_lt_pow_length_20 (OAI.EditApproximation.bitSubtractWithWork left right false).1 + rw [proof_bitSubtractWithWork_length_21] at hlt + cases hb : (OAI.EditApproximation.bitSubtractWithWork left right false).2.1 + · simp only [hb, Bool.toNat_false, Nat.mul_zero, Nat.add_zero] at hvalue + omega + · simp only [hb, Bool.toNat_true, Bool.toNat_false, Nat.mul_one, Nat.add_zero] at hvalue + omega + have proof_bitDivModWithWork_value_23 (divisor : List.{0} Bool) (bits : List.{0} Bool) (hd : LT.lt.{0} 0 (OAI.EditApproximation.bitWordValue divisor)) : + OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).1 + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 < OAI.EditApproximation.bitWordValue divisor := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitDivModWithWork, OAI.EditApproximation.bitWordValue, hd]) + | cons bit bits ih => + let previous := OAI.EditApproximation.bitDivModWithWork divisor bits + let candidate := bit :: previous.2.1 + have hp : OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue previous.1 + + OAI.EditApproximation.bitWordValue previous.2.1 := ih.1 + have hr : OAI.EditApproximation.bitWordValue previous.2.1 < OAI.EditApproximation.bitWordValue divisor := ih.2 + have hc : OAI.EditApproximation.bitWordValue candidate < 2 * OAI.EditApproximation.bitWordValue divisor := by + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + cases bit <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega + by_cases hlt : (OAI.EditApproximation.bitCompareWithWork candidate divisor).1 = .lt + · have hv := (proof_bitCompareWithWork_lt_16 candidate divisor).1 hlt + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 = .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * + OAI.EditApproximation.bitWordValue (false :: previous.1) + OAI.EditApproximation.bitWordValue candidate ∧ OAI.EditApproximation.bitWordValue candidate < _ + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_false]) + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + nlinarith only [hp] + · exact hv + · have hv : OAI.EditApproximation.bitWordValue divisor ≤ OAI.EditApproximation.bitWordValue candidate := by + exact Nat.le_of_not_gt (fun h => hlt ((proof_bitCompareWithWork_lt_16 candidate divisor).2 h)) + have hs := proof_bitSubtractWithWork_sub_22 candidate divisor hv + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 ≠ .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (true :: previous.1) + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 < _ + rw [hs] + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_true]) + have he := Nat.sub_add_cancel hv + dsimp only [candidate, OAI.EditApproximation.bitWordValue] at he ⊢ + nlinarith only [hp, he] + · omega + have proof_bitCompareWithWork_eq_3 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .eq ↔ OAI.EditApproximation.bitWordValue left = OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_bitAdder_value_1 (a : Bool) (b : Bool) (carry : Bool) : + (OAI.EditApproximation.bitSum a b carry).toNat + 2 * (OAI.EditApproximation.bitCarry a b carry).toNat = + a.toNat + b.toNat + carry.toNat := by + cases a <;> cases b <;> cases carry <;> decide + have proof_bitAddWithWork_value_2 (left : List.{0} Bool) (right : List.{0} Bool) (carry : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitAddWithWork left right carry).1 = + OAI.EditApproximation.bitWordValue left + OAI.EditApproximation.bitWordValue right + carry.toNat := by + induction left generalizing right carry with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork] + induction right generalizing carry with + | nil => cases carry <;> simp [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue] + | cons b bs ih => + simp only [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 false b carry + simp only [Bool.toNat_false] at h + omega + | cons a as ih => + cases right with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a false carry + simp only [Bool.toNat_false] at h + omega + | cons b bs => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a b carry + omega + have proof_bitCeilDivWithWork_value_30 (divisor : List.{0} Bool) (bits : List.{0} Bool) (hd : LT.lt.{0} 0 (OAI.EditApproximation.bitWordValue divisor)) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitCeilDivWithWork divisor bits).1 = + ⌈((OAI.EditApproximation.bitWordValue bits : ℚ) / OAI.EditApproximation.bitWordValue divisor)⌉₊ := by + let q := OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).1 + let r := OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 + have h := proof_bitDivModWithWork_value_23 divisor bits hd + have heq : OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * q + r := h.1 + have hr : r < OAI.EditApproximation.bitWordValue divisor := h.2 + have hdQ : (0 : ℚ) < OAI.EditApproximation.bitWordValue divisor := by exact_mod_cast hd + unfold OAI.EditApproximation.bitCeilDivWithWork + dsimp only + split_ifs with hz + · have hr0 : r = 0 := by + exact (proof_bitCompareWithWork_eq_3 (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 []).1 hz + have hratio : (OAI.EditApproximation.bitWordValue bits : ℚ) / OAI.EditApproximation.bitWordValue divisor = (q : ℚ) := by + apply (div_eq_iff hdQ.ne').mpr + exact_mod_cast (show OAI.EditApproximation.bitWordValue bits = q * OAI.EditApproximation.bitWordValue divisor by nlinarith only [heq, hr0]) + rw [hratio] + exact (Nat.ceil_natCast q).symm + · have hr0 : r ≠ 0 := by + intro hzero + exact hz ((proof_bitCompareWithWork_eq_3 (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 []).2 hzero) + rw [proof_bitAddWithWork_value_2] + change q + 1 + 0 = _ + simp only [Nat.add_zero] + symm + apply (Nat.ceil_eq_iff (by omega : q + 1 ≠ 0)).mpr + constructor + · simp only [Nat.add_sub_cancel] + rw [lt_div_iff₀ hdQ] + exact_mod_cast (show q * OAI.EditApproximation.bitWordValue divisor < OAI.EditApproximation.bitWordValue bits by + nlinarith only [heq, Nat.pos_of_ne_zero hr0]) + · rw [div_le_iff₀ hdQ] + push_cast + exact_mod_cast (show OAI.EditApproximation.bitWordValue bits ≤ (q + 1) * OAI.EditApproximation.bitWordValue divisor by nlinarith only [heq, hr]) + have proof_naturalCeilingWithWork_value_31 (a : OAI.EditApproximation.BinaryFraction) : + OAI.EditApproximation.bitWordValue (a.naturalCeilingWithWork).1 = ⌈a.value⌉₊ := by + cases hs : a.numerator.negative + · simpa only [OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork, hs, Bool.false_eq_true, ↓reduceIte, + OAI.EditApproximation.BinaryFraction.value, OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, Int.cast_natCast] using + proof_bitCeilDivWithWork_value_30 a.denominator a.numerator.bits a.denominator_pos + · have hn : a.value ≤ 0 := by + (simp only [OAI.EditApproximation.BinaryFraction.value, OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hs, ↓reduceIte, Int.cast_neg, Int.cast_natCast]) + exact div_nonpos_of_nonpos_of_nonneg (neg_nonpos.mpr (Nat.cast_nonneg _)) (Nat.cast_nonneg _) + (simp only [OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork, hs, ↓reduceIte, OAI.EditApproximation.bitWordValue]) + exact (Nat.ceil_eq_zero.mpr hn).symm + have proof_representation_value_32 (a : OAI.EditApproximation.BinaryFraction) : a.representation.value = a.value := rfl + have proof_eq_of_num_den_33 {a : OAI.EditApproximation.UnreducedRational} {b : OAI.EditApproximation.UnreducedRational} (hnum : Eq.{1} a.num b.num) (hden : Eq.{1} a.den b.den) : a = b := by + cases a + cases b + cases hnum + cases hden + rfl + have proof_trimBitWordWithWork_value_6 (bits : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.trimBitWordWithWork bits).1 = OAI.EditApproximation.bitWordValue bits := by + induction bits with + | nil => rfl + | cons bit bits ih => + simp only [OAI.EditApproximation.trimBitWordWithWork] + split_ifs with h + · have ht : OAI.EditApproximation.bitWordValue bits = 0 := by rw [← ih, h.1]; rfl + simp [h.2, OAI.EditApproximation.bitWordValue, ht] + · (simp only [OAI.EditApproximation.bitWordValue, ih]) + have proof_canonicalizeWithWork_representation_34 (a : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.canonicalizeWithWork a).1.representation = a.representation := by + apply proof_eq_of_num_den_33 + · (simp only [OAI.EditApproximation.BinaryFraction.canonicalizeWithWork, OAI.EditApproximation.BinaryFraction.representation, OAI.EditApproximation.SignedBinary.value, proof_trimBitWordWithWork_value_6]) + · exact proof_trimBitWordWithWork_value_6 a.denominator + have proof_bitMulWithWork_value_0 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitMulWithWork left right).1 = OAI.EditApproximation.bitWordValue left * OAI.EditApproximation.bitWordValue right := by + induction left with + | nil => simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue] + | cons bit bits ih => + cases bit <;> simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue, proof_bitAddWithWork_value_2, ih] <;> ring + have proof_mulWithWork_value_35 (a : OAI.EditApproximation.SignedBinary) (b : OAI.EditApproximation.SignedBinary) : + (a.mulWithWork b).1.value = a.value * b.value := by + simp only [OAI.EditApproximation.SignedBinary.mulWithWork, OAI.EditApproximation.SignedBinary.value, proof_bitMulWithWork_value_0] + cases a.negative <;> cases b.negative <;> simp [OAI.EditApproximation.signedMagnitude] + have proof_mulWithWork_representation_36 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (a.mulWithWork b).1.representation = a.representation.mul b.representation := by + apply proof_eq_of_num_den_33 + · exact proof_mulWithWork_value_35 a.numerator b.numerator + · exact proof_bitMulWithWork_value_0 a.denominator b.denominator + have proof_canonicalMulWithWork_representation_37 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork a b).1.representation = a.representation.mul b.representation := by + rw [OAI.EditApproximation.BinaryFraction.canonicalMulWithWork, proof_canonicalizeWithWork_representation_34, proof_mulWithWork_representation_36] + have proof_zero_representation_38 : OAI.EditApproximation.BinaryFraction.zero.representation = OAI.EditApproximation.UnreducedRational.zero := by + apply proof_eq_of_num_den_33 <;> rfl + have proof_invWithWork_representation_39 (a : OAI.EditApproximation.BinaryFraction) : + (a.invWithWork).1.representation = a.representation.inv := by + unfold OAI.EditApproximation.BinaryFraction.invWithWork + dsimp only + split_ifs with h + · have hz : OAI.EditApproximation.bitWordValue a.numerator.bits = 0 := by + simpa only [OAI.EditApproximation.bitWordValue] using (proof_bitCompareWithWork_eq_3 a.numerator.bits []).1 h + have hv : a.numerator.value = 0 := by (simp [OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hz]) + (simp only [OAI.EditApproximation.UnreducedRational.inv, OAI.EditApproximation.BinaryFraction.representation, hv, ↓reduceDIte]) + exact proof_zero_representation_38 + · have hn : OAI.EditApproximation.bitWordValue a.numerator.bits ≠ 0 := by + intro hz + exact h ((proof_bitCompareWithWork_eq_3 a.numerator.bits []).2 (by simpa [OAI.EditApproximation.bitWordValue] using hz)) + have hv : a.numerator.value ≠ 0 := by + cases hs : a.numerator.negative <;> (simp [OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hs, hn]) + (simp only [OAI.EditApproximation.UnreducedRational.inv, OAI.EditApproximation.BinaryFraction.representation, hv, ↓reduceDIte]) + apply proof_eq_of_num_den_33 + · cases hs : a.numerator.negative <;> + simp [OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hs, Int.sign_natCast_of_ne_zero hn] + · cases hs : a.numerator.negative <;> (simp [OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hs]) + have proof_divWithWork_representation_40 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (a.divWithWork b).1.representation = a.representation.div b.representation := by + (simp only [OAI.EditApproximation.BinaryFraction.divWithWork, proof_canonicalMulWithWork_representation_37, proof_invWithWork_representation_39, + OAI.EditApproximation.UnreducedRational.div]) + have proof_value_mul_41 (a : OAI.EditApproximation.UnreducedRational) (b : OAI.EditApproximation.UnreducedRational) : (a.mul b).value = a.value * b.value := by + simp [OAI.EditApproximation.UnreducedRational.mul, OAI.EditApproximation.UnreducedRational.value, mul_div_mul_comm] + have proof_value_inv_42 (a : OAI.EditApproximation.UnreducedRational) : a.inv.value = a.value⁻¹ := by + by_cases h : a.num = 0 + · simp [OAI.EditApproximation.UnreducedRational.inv, h, OAI.EditApproximation.UnreducedRational.value, OAI.EditApproximation.UnreducedRational.zero] + · have hn : (a.num.natAbs : ℚ) ≠ 0 := by exact_mod_cast (Int.natAbs_pos.mpr h).ne' + have hd : (a.den : ℚ) ≠ 0 := by exact_mod_cast a.den_pos.ne' + have hsign : ((a.num.sign : ℤ) : ℚ) * a.num = (a.num.natAbs : ℚ) := by + simpa only [Int.cast_mul, Int.cast_natCast] using + congrArg (fun z : ℤ => (z : ℚ)) (Int.sign_mul_self_eq_natAbs a.num) + simp only [OAI.EditApproximation.UnreducedRational.inv, h, ↓reduceDIte, OAI.EditApproximation.UnreducedRational.value] + push_cast + apply eq_inv_of_mul_eq_one_left + field_simp [hn, hd] + exact hsign + have proof_value_div_43 (a : OAI.EditApproximation.UnreducedRational) (b : OAI.EditApproximation.UnreducedRational) : (a.div b).value = a.value / b.value := by + simp [proof_value_mul_41, proof_value_inv_42, OAI.EditApproximation.UnreducedRational.div, div_eq_mul_inv] + have proof_divWithWork_value_44 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.divWithWork a b).1.value = a.value / b.value := by + rw [← proof_representation_value_32, proof_divWithWork_representation_40, + proof_value_div_43, proof_representation_value_32, proof_representation_value_32] + have proof_canonicalMulWithWork_value_45 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork a b).1.value = a.value * b.value := by + rw [← proof_representation_value_32, proof_canonicalMulWithWork_representation_37, + proof_value_mul_41, proof_representation_value_32, proof_representation_value_32] + have proof_value_ofInt_46 (a : ℤ) : (OAI.EditApproximation.SignedBinary.ofInt a).value = a := by + by_cases h : a < 0 + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_true, + ↓reduceIte] using (Int.eq_neg_natAbs_of_nonpos (le_of_lt h)).symm + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_false, + Bool.false_eq_true, ↓reduceIte] using (Int.eq_natAbs_of_nonneg (le_of_not_gt h)).symm + have proof_nat_representation_47 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).representation = OAI.EditApproximation.UnreducedRational.nat n := by + apply proof_eq_of_num_den_33 + · change (OAI.EditApproximation.SignedBinary.ofInt (n : ℤ)).value = (n : ℤ) + exact proof_value_ofInt_46 _ + · rfl + have proof_value_nat_48 (n : ℕ) : (OAI.EditApproximation.UnreducedRational.nat n).value = n := by (simp [OAI.EditApproximation.UnreducedRational.nat, OAI.EditApproximation.UnreducedRational.value]) + have proof_nat_value_49 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).value = (n : ℚ) := by + rw [← proof_representation_value_32, proof_nat_representation_47, proof_value_nat_48] + have proof_groupSampleCountWithWork_value_28 (M : ℕ) (Q : ℕ) (b : ℕ) (h : OAI.EditApproximation.BinaryFraction) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.BinaryFraction.groupSampleCountWithWork M Q b h).1 = OAI.EditApproximation.groupSampleCount M Q b h.value := by + simp only [OAI.EditApproximation.BinaryFraction.groupSampleCountWithWork, proof_wordMinWithWork_value_29, proof_bitWordValue_bits_15, + proof_naturalCeilingWithWork_value_31, proof_divWithWork_value_44, proof_canonicalMulWithWork_value_45, + proof_nat_value_49, OAI.EditApproximation.groupSampleCount] + exact + let counts := OAI.EditApproximation.vectorMapWithWork T fun t => OAI.EditApproximation.BinaryFraction.groupSampleCountWithWork M Q b (scales t) + let count := fun t => OAI.EditApproximation.bitWordValue (counts.1.get t) + let heq : ∀ t, count t = OAI.EditApproximation.groupSampleCount M Q b (scales t).value := by + intro t + simp only [count, counts, proof_vectorMapWithWork_value_27, proof_groupSampleCountWithWork_value_28] + let result := OAI.EditApproximation.BinaryFraction.groupMemberSourceWithWork scales count connection envelope values + (fun t j => draw t (Fin.cast (heq t) j)) + (result.1, counts.2 + result.2 + 1) + +def roundedBandReadWithWork {n M : ℕ} (exponent b : ℕ) + (band : List (Fin M → OAI.EditApproximation.TargetInterval n)) (hne : band ≠ []) + (read : Fin M → OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) : Vector (OAI.EditApproximation.TargetInterval n) M × ℕ := by + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_bitSubtractor_value_17 (a : Bool) (b : Bool) (borrow : Bool) : + a.toNat + 2 * (OAI.EditApproximation.bitBorrow a b borrow).toNat = + b.toNat + borrow.toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat := by + cases a <;> cases b <;> cases borrow <;> decide + have proof_bitSubtractionRippleEquation_18 (a : ℕ) (b : ℕ) (borrow : ℕ) (nextBorrow : ℕ) (difference : ℕ) (left : ℕ) (right : ℕ) (result : ℕ) (tail : ℕ) (htail : Eq.{1} (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} result right) nextBorrow) (HAdd.hAdd.{0, 0, 0} left tail)) (hbit : Eq.{1} (HAdd.hAdd.{0, 0, 0} a (HMul.hMul.{0, 0, 0} 2 nextBorrow)) + (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} b borrow) difference)) : + (difference + 2 * result) + (b + 2 * right) + borrow = + (a + 2 * left) + 2 * tail := by + omega + have proof_bitSubtractWithWork_value_19 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right borrow).1 + OAI.EditApproximation.bitWordValue right + borrow.toNat = + OAI.EditApproximation.bitWordValue left + 2 ^ max left.length right.length * + (OAI.EditApproximation.bitSubtractWithWork left right borrow).2.1.toNat := by + induction left generalizing right borrow with + | nil => + induction right generalizing borrow with + | nil => (simp [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + have h := ih (OAI.EditApproximation.bitBorrow false b borrow) + have hb := proof_bitSubtractor_value_17 false b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue, + List.length_nil, List.length_cons, Nat.zero_max, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 0 b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow false b borrow).toNat + (OAI.EditApproximation.bitDifference false b borrow).toNat 0 (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).1) + (2 ^ bs.length * (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons a as ih => + cases right with + | nil => + have h := ih [] (OAI.EditApproximation.bitBorrow a false borrow) + have hb := proof_bitSubtractor_value_17 a false borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_nil, List.length_cons, + Nat.max_zero, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat 0 borrow.toNat (OAI.EditApproximation.bitBorrow a false borrow).toNat + (OAI.EditApproximation.bitDifference a false borrow).toNat (OAI.EditApproximation.bitWordValue as) 0 + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).1) + (2 ^ as.length * (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons b bs => + have h := ih bs (OAI.EditApproximation.bitBorrow a b borrow) + have hb := proof_bitSubtractor_value_17 a b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_cons, Nat.succ_max_succ, + pow_succ] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow a b borrow).toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).1) + (2 ^ max as.length bs.length * (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_assoc, Nat.mul_left_comm] using hs + have proof_bitWordValue_lt_pow_length_20 (bits : List.{0} Bool) : OAI.EditApproximation.bitWordValue bits < 2 ^ bits.length := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitWordValue]) + | cons bit bits ih => + cases bit <;> (simp only [OAI.EditApproximation.bitWordValue, List.length_cons, pow_succ, Bool.toNat_false, Bool.toNat_true]) <;> omega + have proof_bitSubtractWithWork_length_21 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + (OAI.EditApproximation.bitSubtractWithWork left right borrow).1.length = max left.length right.length := by + induction left generalizing right borrow with + | nil => + simp only [OAI.EditApproximation.bitSubtractWithWork] + induction right generalizing borrow with + | nil => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork] + | cons b bs ih => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork, ih] + | cons a as ih => + cases right with + | nil => simp [OAI.EditApproximation.bitSubtractWithWork, ih] + | cons b bs => simp [OAI.EditApproximation.bitSubtractWithWork, ih, Nat.succ_max_succ] + have proof_bitSubtractWithWork_sub_22 (left : List.{0} Bool) (right : List.{0} Bool) (h : LE.le.{0} (OAI.EditApproximation.bitWordValue right) (OAI.EditApproximation.bitWordValue left)) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right false).1 = OAI.EditApproximation.bitWordValue left - OAI.EditApproximation.bitWordValue right := by + have hvalue := proof_bitSubtractWithWork_value_19 left right false + have hlt := proof_bitWordValue_lt_pow_length_20 (OAI.EditApproximation.bitSubtractWithWork left right false).1 + rw [proof_bitSubtractWithWork_length_21] at hlt + cases hb : (OAI.EditApproximation.bitSubtractWithWork left right false).2.1 + · simp only [hb, Bool.toNat_false, Nat.mul_zero, Nat.add_zero] at hvalue + omega + · simp only [hb, Bool.toNat_true, Bool.toNat_false, Nat.mul_one, Nat.add_zero] at hvalue + omega + have proof_bitDivModWithWork_value_23 (divisor : List.{0} Bool) (bits : List.{0} Bool) (hd : LT.lt.{0} 0 (OAI.EditApproximation.bitWordValue divisor)) : + OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).1 + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 < OAI.EditApproximation.bitWordValue divisor := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitDivModWithWork, OAI.EditApproximation.bitWordValue, hd]) + | cons bit bits ih => + let previous := OAI.EditApproximation.bitDivModWithWork divisor bits + let candidate := bit :: previous.2.1 + have hp : OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue previous.1 + + OAI.EditApproximation.bitWordValue previous.2.1 := ih.1 + have hr : OAI.EditApproximation.bitWordValue previous.2.1 < OAI.EditApproximation.bitWordValue divisor := ih.2 + have hc : OAI.EditApproximation.bitWordValue candidate < 2 * OAI.EditApproximation.bitWordValue divisor := by + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + cases bit <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega + by_cases hlt : (OAI.EditApproximation.bitCompareWithWork candidate divisor).1 = .lt + · have hv := (proof_bitCompareWithWork_lt_16 candidate divisor).1 hlt + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 = .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * + OAI.EditApproximation.bitWordValue (false :: previous.1) + OAI.EditApproximation.bitWordValue candidate ∧ OAI.EditApproximation.bitWordValue candidate < _ + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_false]) + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + nlinarith only [hp] + · exact hv + · have hv : OAI.EditApproximation.bitWordValue divisor ≤ OAI.EditApproximation.bitWordValue candidate := by + exact Nat.le_of_not_gt (fun h => hlt ((proof_bitCompareWithWork_lt_16 candidate divisor).2 h)) + have hs := proof_bitSubtractWithWork_sub_22 candidate divisor hv + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 ≠ .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (true :: previous.1) + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 < _ + rw [hs] + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_true]) + have he := Nat.sub_add_cancel hv + dsimp only [candidate, OAI.EditApproximation.bitWordValue] at he ⊢ + nlinarith only [hp, he] + · omega + have proof_bitCompareWithWork_eq_3 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .eq ↔ OAI.EditApproximation.bitWordValue left = OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_bitAdder_value_1 (a : Bool) (b : Bool) (carry : Bool) : + (OAI.EditApproximation.bitSum a b carry).toNat + 2 * (OAI.EditApproximation.bitCarry a b carry).toNat = + a.toNat + b.toNat + carry.toNat := by + cases a <;> cases b <;> cases carry <;> decide + have proof_bitAddWithWork_value_2 (left : List.{0} Bool) (right : List.{0} Bool) (carry : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitAddWithWork left right carry).1 = + OAI.EditApproximation.bitWordValue left + OAI.EditApproximation.bitWordValue right + carry.toNat := by + induction left generalizing right carry with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork] + induction right generalizing carry with + | nil => cases carry <;> simp [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue] + | cons b bs ih => + simp only [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 false b carry + simp only [Bool.toNat_false] at h + omega + | cons a as ih => + cases right with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a false carry + simp only [Bool.toNat_false] at h + omega + | cons b bs => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a b carry + omega + have proof_bitCeilDivWithWork_value_30 (divisor : List.{0} Bool) (bits : List.{0} Bool) (hd : LT.lt.{0} 0 (OAI.EditApproximation.bitWordValue divisor)) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitCeilDivWithWork divisor bits).1 = + ⌈((OAI.EditApproximation.bitWordValue bits : ℚ) / OAI.EditApproximation.bitWordValue divisor)⌉₊ := by + let q := OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).1 + let r := OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 + have h := proof_bitDivModWithWork_value_23 divisor bits hd + have heq : OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * q + r := h.1 + have hr : r < OAI.EditApproximation.bitWordValue divisor := h.2 + have hdQ : (0 : ℚ) < OAI.EditApproximation.bitWordValue divisor := by exact_mod_cast hd + unfold OAI.EditApproximation.bitCeilDivWithWork + dsimp only + split_ifs with hz + · have hr0 : r = 0 := by + exact (proof_bitCompareWithWork_eq_3 (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 []).1 hz + have hratio : (OAI.EditApproximation.bitWordValue bits : ℚ) / OAI.EditApproximation.bitWordValue divisor = (q : ℚ) := by + apply (div_eq_iff hdQ.ne').mpr + exact_mod_cast (show OAI.EditApproximation.bitWordValue bits = q * OAI.EditApproximation.bitWordValue divisor by nlinarith only [heq, hr0]) + rw [hratio] + exact (Nat.ceil_natCast q).symm + · have hr0 : r ≠ 0 := by + intro hzero + exact hz ((proof_bitCompareWithWork_eq_3 (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 []).2 hzero) + rw [proof_bitAddWithWork_value_2] + change q + 1 + 0 = _ + simp only [Nat.add_zero] + symm + apply (Nat.ceil_eq_iff (by omega : q + 1 ≠ 0)).mpr + constructor + · simp only [Nat.add_sub_cancel] + rw [lt_div_iff₀ hdQ] + exact_mod_cast (show q * OAI.EditApproximation.bitWordValue divisor < OAI.EditApproximation.bitWordValue bits by + nlinarith only [heq, Nat.pos_of_ne_zero hr0]) + · rw [div_le_iff₀ hdQ] + push_cast + exact_mod_cast (show OAI.EditApproximation.bitWordValue bits ≤ (q + 1) * OAI.EditApproximation.bitWordValue divisor by nlinarith only [heq, hr]) + have proof_naturalCeilingWithWork_value_31 (a : OAI.EditApproximation.BinaryFraction) : + OAI.EditApproximation.bitWordValue (a.naturalCeilingWithWork).1 = ⌈a.value⌉₊ := by + cases hs : a.numerator.negative + · simpa only [OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork, hs, Bool.false_eq_true, ↓reduceIte, + OAI.EditApproximation.BinaryFraction.value, OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, Int.cast_natCast] using + proof_bitCeilDivWithWork_value_30 a.denominator a.numerator.bits a.denominator_pos + · have hn : a.value ≤ 0 := by + (simp only [OAI.EditApproximation.BinaryFraction.value, OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hs, ↓reduceIte, Int.cast_neg, Int.cast_natCast]) + exact div_nonpos_of_nonpos_of_nonneg (neg_nonpos.mpr (Nat.cast_nonneg _)) (Nat.cast_nonneg _) + (simp only [OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork, hs, ↓reduceIte, OAI.EditApproximation.bitWordValue]) + exact (Nat.ceil_eq_zero.mpr hn).symm + have proof_lt_eq_true_57 (a : OAI.EditApproximation.UnreducedRational) (b : OAI.EditApproximation.UnreducedRational) : a.lt b = true ↔ a.value < b.value := by + simp only [OAI.EditApproximation.UnreducedRational.lt, decide_eq_true_eq, OAI.EditApproximation.UnreducedRational.value] + rw [div_lt_div_iff₀ (by exact_mod_cast a.den_pos : (0 : ℚ) < a.den) + (by exact_mod_cast b.den_pos : (0 : ℚ) < b.den)] + exact_mod_cast (Iff.rfl : a.num * (b.den : ℤ) < b.num * (a.den : ℤ) ↔ _) + have proof_nonzeroWithWork_value_58 (bits : List.{0} Bool) : + (OAI.EditApproximation.SignedBinary.nonzeroWithWork bits).1 = true ↔ OAI.EditApproximation.bitWordValue bits ≠ 0 := by + (simp [OAI.EditApproximation.SignedBinary.nonzeroWithWork, proof_bitCompareWithWork_eq_3, OAI.EditApproximation.bitWordValue]) + have proof_ltWithWork_value_59 (a : OAI.EditApproximation.SignedBinary) (b : OAI.EditApproximation.SignedBinary) : + (a.ltWithWork b).1 = true ↔ a.value < b.value := by + cases ha : a.negative <;> cases hb : b.negative + · (simp [OAI.EditApproximation.SignedBinary.ltWithWork, ha, hb, OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, proof_bitCompareWithWork_lt_16]) + · (simp [OAI.EditApproximation.SignedBinary.ltWithWork, ha, hb, OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude]) + · (simp only [OAI.EditApproximation.SignedBinary.ltWithWork, ha, hb, ↓reduceIte, Bool.false_eq_true, + Bool.or_eq_true, proof_nonzeroWithWork_value_58, OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude]) + omega + · (simp [OAI.EditApproximation.SignedBinary.ltWithWork, ha, hb, OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, proof_bitCompareWithWork_lt_16]) + have proof_bitMulWithWork_value_0 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitMulWithWork left right).1 = OAI.EditApproximation.bitWordValue left * OAI.EditApproximation.bitWordValue right := by + induction left with + | nil => simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue] + | cons bit bits ih => + cases bit <;> simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue, proof_bitAddWithWork_value_2, ih] <;> ring + have proof_mulWithWork_value_35 (a : OAI.EditApproximation.SignedBinary) (b : OAI.EditApproximation.SignedBinary) : + (a.mulWithWork b).1.value = a.value * b.value := by + simp only [OAI.EditApproximation.SignedBinary.mulWithWork, OAI.EditApproximation.SignedBinary.value, proof_bitMulWithWork_value_0] + cases a.negative <;> cases b.negative <;> simp [OAI.EditApproximation.signedMagnitude] + have proof_denominatorInteger_value_60 (a : OAI.EditApproximation.BinaryFraction) : + a.denominatorInteger.value = (OAI.EditApproximation.bitWordValue a.denominator : ℤ) := rfl + have proof_representation_value_32 (a : OAI.EditApproximation.BinaryFraction) : a.representation.value = a.value := rfl + have proof_ltWithWork_representation_61 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (a.ltWithWork b).1 = a.representation.lt b.representation := by + apply Bool.eq_iff_iff.mpr + rw [proof_lt_eq_true_57] + simp only [OAI.EditApproximation.BinaryFraction.ltWithWork, proof_ltWithWork_value_59, proof_mulWithWork_value_35, + proof_denominatorInteger_value_60, proof_representation_value_32] + unfold OAI.EditApproximation.BinaryFraction.value + rw [div_lt_div_iff₀ (by exact_mod_cast a.denominator_pos : (0 : ℚ) < bitWordValue a.denominator) + (by exact_mod_cast b.denominator_pos : (0 : ℚ) < bitWordValue b.denominator)] + exact_mod_cast (Iff.rfl : + a.numerator.value * (OAI.EditApproximation.bitWordValue b.denominator : ℤ) < + b.numerator.value * (OAI.EditApproximation.bitWordValue a.denominator : ℤ) ↔ _) + have proof_ltWithWork_value_62 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (a.ltWithWork b).1 = true ↔ a.value < b.value := by + rw [proof_ltWithWork_representation_61, proof_lt_eq_true_57] + rfl + have proof_maxWithWork_value_63 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.maxWithWork a b).1.value = max a.value b.value := by + by_cases h : a.value < b.value + · simp only [OAI.EditApproximation.BinaryFraction.maxWithWork, (proof_ltWithWork_value_62 a b).mpr h, ↓reduceIte, max_eq_right h.le] + · have hb : (a.ltWithWork b).1 = false := Bool.eq_false_iff.mpr (fun hh => h ((proof_ltWithWork_value_62 a b).mp hh)) + simp only [OAI.EditApproximation.BinaryFraction.maxWithWork, hb, Bool.false_eq_true, ↓reduceIte, max_eq_left (le_of_not_gt h)] + have proof_eq_of_num_den_33 {a : OAI.EditApproximation.UnreducedRational} {b : OAI.EditApproximation.UnreducedRational} (hnum : Eq.{1} a.num b.num) (hden : Eq.{1} a.den b.den) : a = b := by + cases a + cases b + cases hnum + cases hden + rfl + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_value_ofInt_46 (a : ℤ) : (OAI.EditApproximation.SignedBinary.ofInt a).value = a := by + by_cases h : a < 0 + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_true, + ↓reduceIte] using (Int.eq_neg_natAbs_of_nonpos (le_of_lt h)).symm + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_false, + Bool.false_eq_true, ↓reduceIte] using (Int.eq_natAbs_of_nonneg (le_of_not_gt h)).symm + have proof_nat_representation_47 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).representation = OAI.EditApproximation.UnreducedRational.nat n := by + apply proof_eq_of_num_den_33 + · change (OAI.EditApproximation.SignedBinary.ofInt (n : ℤ)).value = (n : ℤ) + exact proof_value_ofInt_46 _ + · rfl + have proof_value_nat_48 (n : ℕ) : (OAI.EditApproximation.UnreducedRational.nat n).value = n := by (simp [OAI.EditApproximation.UnreducedRational.nat, OAI.EditApproximation.UnreducedRational.value]) + have proof_nat_value_49 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).value = (n : ℚ) := by + rw [← proof_representation_value_32, proof_nat_representation_47, proof_value_nat_48] + have proof_trimBitWordWithWork_value_6 (bits : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.trimBitWordWithWork bits).1 = OAI.EditApproximation.bitWordValue bits := by + induction bits with + | nil => rfl + | cons bit bits ih => + simp only [OAI.EditApproximation.trimBitWordWithWork] + split_ifs with h + · have ht : OAI.EditApproximation.bitWordValue bits = 0 := by rw [← ih, h.1]; rfl + simp [h.2, OAI.EditApproximation.bitWordValue, ht] + · (simp only [OAI.EditApproximation.bitWordValue, ih]) + have proof_canonicalizeWithWork_representation_34 (a : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.canonicalizeWithWork a).1.representation = a.representation := by + apply proof_eq_of_num_den_33 + · (simp only [OAI.EditApproximation.BinaryFraction.canonicalizeWithWork, OAI.EditApproximation.BinaryFraction.representation, OAI.EditApproximation.SignedBinary.value, proof_trimBitWordWithWork_value_6]) + · exact proof_trimBitWordWithWork_value_6 a.denominator + have proof_mulWithWork_representation_36 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (a.mulWithWork b).1.representation = a.representation.mul b.representation := by + apply proof_eq_of_num_den_33 + · exact proof_mulWithWork_value_35 a.numerator b.numerator + · exact proof_bitMulWithWork_value_0 a.denominator b.denominator + have proof_canonicalMulWithWork_representation_37 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork a b).1.representation = a.representation.mul b.representation := by + rw [OAI.EditApproximation.BinaryFraction.canonicalMulWithWork, proof_canonicalizeWithWork_representation_34, proof_mulWithWork_representation_36] + have proof_value_mul_41 (a : OAI.EditApproximation.UnreducedRational) (b : OAI.EditApproximation.UnreducedRational) : (a.mul b).value = a.value * b.value := by + simp [OAI.EditApproximation.UnreducedRational.mul, OAI.EditApproximation.UnreducedRational.value, mul_div_mul_comm] + have proof_canonicalMulWithWork_value_45 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork a b).1.value = a.value * b.value := by + rw [← proof_representation_value_32, proof_canonicalMulWithWork_representation_37, + proof_value_mul_41, proof_representation_value_32, proof_representation_value_32] + have proof_roundedSpacingWithWork_value_64 (theta : OAI.EditApproximation.BinaryFraction) (envelope : OAI.EditApproximation.BinaryFraction) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.BinaryFraction.roundedSpacingWithWork theta envelope).1 = ⌈max 1 (theta.value * envelope.value)⌉₊ := by + simp only [OAI.EditApproximation.BinaryFraction.roundedSpacingWithWork, proof_naturalCeilingWithWork_value_31, proof_maxWithWork_value_63, + proof_canonicalMulWithWork_value_45, OAI.EditApproximation.BinaryFraction.one, proof_nat_value_49, Nat.cast_one] + have proof_roundedSpacingWithWork_pos_56 (theta : OAI.EditApproximation.BinaryFraction) (envelope : OAI.EditApproximation.BinaryFraction) : + 0 < OAI.EditApproximation.bitWordValue (OAI.EditApproximation.BinaryFraction.roundedSpacingWithWork theta envelope).1 := by + rw [proof_roundedSpacingWithWork_value_64, Nat.ceil_pos] + exact lt_of_lt_of_le (by norm_num : (0 : ℚ) < 1) (le_max_left _ _) + exact + OAI.EditApproximation.vectorMapWithWork M fun i => + let envelope := OAI.EditApproximation.BinaryFraction.bandEnvelopeReadWithWork b band read i + let spacing := OAI.EditApproximation.BinaryFraction.roundedSpacingWithWork (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) envelope.1 + let rounded := OAI.EditApproximation.roundStateWithWork (OAI.EditApproximation.bitWordValue spacing.1) + (proof_roundedSpacingWithWork_pos_56 _ _) (band.head hne i) + (rounded.1, envelope.2 + spacing.2 + rounded.2 + exponent + 3) + +def queryGroupLabelsWithWork (M Q b : ℕ) (h : OAI.EditApproximation.BinaryFraction) + (draw : Fin (OAI.EditApproximation.groupSampleCount M Q b h.value) → Fin M × ℕ) : List (Fin M) × ℕ := by + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_wordLEWithWork_value_26 (a : List.{0} Bool) (b : List.{0} Bool) : + (OAI.EditApproximation.wordLEWithWork a b).1 = true ↔ OAI.EditApproximation.bitWordValue a ≤ OAI.EditApproximation.bitWordValue b := by + simp only [OAI.EditApproximation.wordLEWithWork, Bool.not_eq_true', decide_eq_false_iff_not, + proof_bitCompareWithWork_lt_16, not_lt] + have proof_wordMinWithWork_value_29 (a : List.{0} Bool) (b : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.wordMinWithWork a b).1 = min (OAI.EditApproximation.bitWordValue a) (OAI.EditApproximation.bitWordValue b) := by + unfold OAI.EditApproximation.wordMinWithWork + dsimp only + split_ifs with h + · exact (min_eq_left ((proof_wordLEWithWork_value_26 a b).mp h)).symm + · exact (min_eq_right (le_of_not_ge (fun hle => h ((proof_wordLEWithWork_value_26 a b).mpr hle)))).symm + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_bitSubtractor_value_17 (a : Bool) (b : Bool) (borrow : Bool) : + a.toNat + 2 * (OAI.EditApproximation.bitBorrow a b borrow).toNat = + b.toNat + borrow.toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat := by + cases a <;> cases b <;> cases borrow <;> decide + have proof_bitSubtractionRippleEquation_18 (a : ℕ) (b : ℕ) (borrow : ℕ) (nextBorrow : ℕ) (difference : ℕ) (left : ℕ) (right : ℕ) (result : ℕ) (tail : ℕ) (htail : Eq.{1} (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} result right) nextBorrow) (HAdd.hAdd.{0, 0, 0} left tail)) (hbit : Eq.{1} (HAdd.hAdd.{0, 0, 0} a (HMul.hMul.{0, 0, 0} 2 nextBorrow)) + (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} b borrow) difference)) : + (difference + 2 * result) + (b + 2 * right) + borrow = + (a + 2 * left) + 2 * tail := by + omega + have proof_bitSubtractWithWork_value_19 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right borrow).1 + OAI.EditApproximation.bitWordValue right + borrow.toNat = + OAI.EditApproximation.bitWordValue left + 2 ^ max left.length right.length * + (OAI.EditApproximation.bitSubtractWithWork left right borrow).2.1.toNat := by + induction left generalizing right borrow with + | nil => + induction right generalizing borrow with + | nil => (simp [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + have h := ih (OAI.EditApproximation.bitBorrow false b borrow) + have hb := proof_bitSubtractor_value_17 false b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue, + List.length_nil, List.length_cons, Nat.zero_max, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 0 b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow false b borrow).toNat + (OAI.EditApproximation.bitDifference false b borrow).toNat 0 (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).1) + (2 ^ bs.length * (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons a as ih => + cases right with + | nil => + have h := ih [] (OAI.EditApproximation.bitBorrow a false borrow) + have hb := proof_bitSubtractor_value_17 a false borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_nil, List.length_cons, + Nat.max_zero, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat 0 borrow.toNat (OAI.EditApproximation.bitBorrow a false borrow).toNat + (OAI.EditApproximation.bitDifference a false borrow).toNat (OAI.EditApproximation.bitWordValue as) 0 + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).1) + (2 ^ as.length * (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons b bs => + have h := ih bs (OAI.EditApproximation.bitBorrow a b borrow) + have hb := proof_bitSubtractor_value_17 a b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_cons, Nat.succ_max_succ, + pow_succ] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow a b borrow).toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).1) + (2 ^ max as.length bs.length * (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_assoc, Nat.mul_left_comm] using hs + have proof_bitWordValue_lt_pow_length_20 (bits : List.{0} Bool) : OAI.EditApproximation.bitWordValue bits < 2 ^ bits.length := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitWordValue]) + | cons bit bits ih => + cases bit <;> (simp only [OAI.EditApproximation.bitWordValue, List.length_cons, pow_succ, Bool.toNat_false, Bool.toNat_true]) <;> omega + have proof_bitSubtractWithWork_length_21 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + (OAI.EditApproximation.bitSubtractWithWork left right borrow).1.length = max left.length right.length := by + induction left generalizing right borrow with + | nil => + simp only [OAI.EditApproximation.bitSubtractWithWork] + induction right generalizing borrow with + | nil => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork] + | cons b bs ih => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork, ih] + | cons a as ih => + cases right with + | nil => simp [OAI.EditApproximation.bitSubtractWithWork, ih] + | cons b bs => simp [OAI.EditApproximation.bitSubtractWithWork, ih, Nat.succ_max_succ] + have proof_bitSubtractWithWork_sub_22 (left : List.{0} Bool) (right : List.{0} Bool) (h : LE.le.{0} (OAI.EditApproximation.bitWordValue right) (OAI.EditApproximation.bitWordValue left)) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right false).1 = OAI.EditApproximation.bitWordValue left - OAI.EditApproximation.bitWordValue right := by + have hvalue := proof_bitSubtractWithWork_value_19 left right false + have hlt := proof_bitWordValue_lt_pow_length_20 (OAI.EditApproximation.bitSubtractWithWork left right false).1 + rw [proof_bitSubtractWithWork_length_21] at hlt + cases hb : (OAI.EditApproximation.bitSubtractWithWork left right false).2.1 + · simp only [hb, Bool.toNat_false, Nat.mul_zero, Nat.add_zero] at hvalue + omega + · simp only [hb, Bool.toNat_true, Bool.toNat_false, Nat.mul_one, Nat.add_zero] at hvalue + omega + have proof_bitDivModWithWork_value_23 (divisor : List.{0} Bool) (bits : List.{0} Bool) (hd : LT.lt.{0} 0 (OAI.EditApproximation.bitWordValue divisor)) : + OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).1 + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 < OAI.EditApproximation.bitWordValue divisor := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitDivModWithWork, OAI.EditApproximation.bitWordValue, hd]) + | cons bit bits ih => + let previous := OAI.EditApproximation.bitDivModWithWork divisor bits + let candidate := bit :: previous.2.1 + have hp : OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue previous.1 + + OAI.EditApproximation.bitWordValue previous.2.1 := ih.1 + have hr : OAI.EditApproximation.bitWordValue previous.2.1 < OAI.EditApproximation.bitWordValue divisor := ih.2 + have hc : OAI.EditApproximation.bitWordValue candidate < 2 * OAI.EditApproximation.bitWordValue divisor := by + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + cases bit <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega + by_cases hlt : (OAI.EditApproximation.bitCompareWithWork candidate divisor).1 = .lt + · have hv := (proof_bitCompareWithWork_lt_16 candidate divisor).1 hlt + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 = .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * + OAI.EditApproximation.bitWordValue (false :: previous.1) + OAI.EditApproximation.bitWordValue candidate ∧ OAI.EditApproximation.bitWordValue candidate < _ + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_false]) + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + nlinarith only [hp] + · exact hv + · have hv : OAI.EditApproximation.bitWordValue divisor ≤ OAI.EditApproximation.bitWordValue candidate := by + exact Nat.le_of_not_gt (fun h => hlt ((proof_bitCompareWithWork_lt_16 candidate divisor).2 h)) + have hs := proof_bitSubtractWithWork_sub_22 candidate divisor hv + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 ≠ .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (true :: previous.1) + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 < _ + rw [hs] + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_true]) + have he := Nat.sub_add_cancel hv + dsimp only [candidate, OAI.EditApproximation.bitWordValue] at he ⊢ + nlinarith only [hp, he] + · omega + have proof_bitCompareWithWork_eq_3 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .eq ↔ OAI.EditApproximation.bitWordValue left = OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_bitAdder_value_1 (a : Bool) (b : Bool) (carry : Bool) : + (OAI.EditApproximation.bitSum a b carry).toNat + 2 * (OAI.EditApproximation.bitCarry a b carry).toNat = + a.toNat + b.toNat + carry.toNat := by + cases a <;> cases b <;> cases carry <;> decide + have proof_bitAddWithWork_value_2 (left : List.{0} Bool) (right : List.{0} Bool) (carry : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitAddWithWork left right carry).1 = + OAI.EditApproximation.bitWordValue left + OAI.EditApproximation.bitWordValue right + carry.toNat := by + induction left generalizing right carry with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork] + induction right generalizing carry with + | nil => cases carry <;> simp [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue] + | cons b bs ih => + simp only [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 false b carry + simp only [Bool.toNat_false] at h + omega + | cons a as ih => + cases right with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a false carry + simp only [Bool.toNat_false] at h + omega + | cons b bs => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a b carry + omega + have proof_bitCeilDivWithWork_value_30 (divisor : List.{0} Bool) (bits : List.{0} Bool) (hd : LT.lt.{0} 0 (OAI.EditApproximation.bitWordValue divisor)) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitCeilDivWithWork divisor bits).1 = + ⌈((OAI.EditApproximation.bitWordValue bits : ℚ) / OAI.EditApproximation.bitWordValue divisor)⌉₊ := by + let q := OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).1 + let r := OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 + have h := proof_bitDivModWithWork_value_23 divisor bits hd + have heq : OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * q + r := h.1 + have hr : r < OAI.EditApproximation.bitWordValue divisor := h.2 + have hdQ : (0 : ℚ) < OAI.EditApproximation.bitWordValue divisor := by exact_mod_cast hd + unfold OAI.EditApproximation.bitCeilDivWithWork + dsimp only + split_ifs with hz + · have hr0 : r = 0 := by + exact (proof_bitCompareWithWork_eq_3 (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 []).1 hz + have hratio : (OAI.EditApproximation.bitWordValue bits : ℚ) / OAI.EditApproximation.bitWordValue divisor = (q : ℚ) := by + apply (div_eq_iff hdQ.ne').mpr + exact_mod_cast (show OAI.EditApproximation.bitWordValue bits = q * OAI.EditApproximation.bitWordValue divisor by nlinarith only [heq, hr0]) + rw [hratio] + exact (Nat.ceil_natCast q).symm + · have hr0 : r ≠ 0 := by + intro hzero + exact hz ((proof_bitCompareWithWork_eq_3 (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 []).2 hzero) + rw [proof_bitAddWithWork_value_2] + change q + 1 + 0 = _ + simp only [Nat.add_zero] + symm + apply (Nat.ceil_eq_iff (by omega : q + 1 ≠ 0)).mpr + constructor + · simp only [Nat.add_sub_cancel] + rw [lt_div_iff₀ hdQ] + exact_mod_cast (show q * OAI.EditApproximation.bitWordValue divisor < OAI.EditApproximation.bitWordValue bits by + nlinarith only [heq, Nat.pos_of_ne_zero hr0]) + · rw [div_le_iff₀ hdQ] + push_cast + exact_mod_cast (show OAI.EditApproximation.bitWordValue bits ≤ (q + 1) * OAI.EditApproximation.bitWordValue divisor by nlinarith only [heq, hr]) + have proof_naturalCeilingWithWork_value_31 (a : OAI.EditApproximation.BinaryFraction) : + OAI.EditApproximation.bitWordValue (a.naturalCeilingWithWork).1 = ⌈a.value⌉₊ := by + cases hs : a.numerator.negative + · simpa only [OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork, hs, Bool.false_eq_true, ↓reduceIte, + OAI.EditApproximation.BinaryFraction.value, OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, Int.cast_natCast] using + proof_bitCeilDivWithWork_value_30 a.denominator a.numerator.bits a.denominator_pos + · have hn : a.value ≤ 0 := by + (simp only [OAI.EditApproximation.BinaryFraction.value, OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hs, ↓reduceIte, Int.cast_neg, Int.cast_natCast]) + exact div_nonpos_of_nonpos_of_nonneg (neg_nonpos.mpr (Nat.cast_nonneg _)) (Nat.cast_nonneg _) + (simp only [OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork, hs, ↓reduceIte, OAI.EditApproximation.bitWordValue]) + exact (Nat.ceil_eq_zero.mpr hn).symm + have proof_representation_value_32 (a : OAI.EditApproximation.BinaryFraction) : a.representation.value = a.value := rfl + have proof_eq_of_num_den_33 {a : OAI.EditApproximation.UnreducedRational} {b : OAI.EditApproximation.UnreducedRational} (hnum : Eq.{1} a.num b.num) (hden : Eq.{1} a.den b.den) : a = b := by + cases a + cases b + cases hnum + cases hden + rfl + have proof_trimBitWordWithWork_value_6 (bits : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.trimBitWordWithWork bits).1 = OAI.EditApproximation.bitWordValue bits := by + induction bits with + | nil => rfl + | cons bit bits ih => + simp only [OAI.EditApproximation.trimBitWordWithWork] + split_ifs with h + · have ht : OAI.EditApproximation.bitWordValue bits = 0 := by rw [← ih, h.1]; rfl + simp [h.2, OAI.EditApproximation.bitWordValue, ht] + · (simp only [OAI.EditApproximation.bitWordValue, ih]) + have proof_canonicalizeWithWork_representation_34 (a : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.canonicalizeWithWork a).1.representation = a.representation := by + apply proof_eq_of_num_den_33 + · (simp only [OAI.EditApproximation.BinaryFraction.canonicalizeWithWork, OAI.EditApproximation.BinaryFraction.representation, OAI.EditApproximation.SignedBinary.value, proof_trimBitWordWithWork_value_6]) + · exact proof_trimBitWordWithWork_value_6 a.denominator + have proof_bitMulWithWork_value_0 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitMulWithWork left right).1 = OAI.EditApproximation.bitWordValue left * OAI.EditApproximation.bitWordValue right := by + induction left with + | nil => simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue] + | cons bit bits ih => + cases bit <;> simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue, proof_bitAddWithWork_value_2, ih] <;> ring + have proof_mulWithWork_value_35 (a : OAI.EditApproximation.SignedBinary) (b : OAI.EditApproximation.SignedBinary) : + (a.mulWithWork b).1.value = a.value * b.value := by + simp only [OAI.EditApproximation.SignedBinary.mulWithWork, OAI.EditApproximation.SignedBinary.value, proof_bitMulWithWork_value_0] + cases a.negative <;> cases b.negative <;> simp [OAI.EditApproximation.signedMagnitude] + have proof_mulWithWork_representation_36 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (a.mulWithWork b).1.representation = a.representation.mul b.representation := by + apply proof_eq_of_num_den_33 + · exact proof_mulWithWork_value_35 a.numerator b.numerator + · exact proof_bitMulWithWork_value_0 a.denominator b.denominator + have proof_canonicalMulWithWork_representation_37 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork a b).1.representation = a.representation.mul b.representation := by + rw [OAI.EditApproximation.BinaryFraction.canonicalMulWithWork, proof_canonicalizeWithWork_representation_34, proof_mulWithWork_representation_36] + have proof_zero_representation_38 : OAI.EditApproximation.BinaryFraction.zero.representation = OAI.EditApproximation.UnreducedRational.zero := by + apply proof_eq_of_num_den_33 <;> rfl + have proof_invWithWork_representation_39 (a : OAI.EditApproximation.BinaryFraction) : + (a.invWithWork).1.representation = a.representation.inv := by + unfold OAI.EditApproximation.BinaryFraction.invWithWork + dsimp only + split_ifs with h + · have hz : OAI.EditApproximation.bitWordValue a.numerator.bits = 0 := by + simpa only [OAI.EditApproximation.bitWordValue] using (proof_bitCompareWithWork_eq_3 a.numerator.bits []).1 h + have hv : a.numerator.value = 0 := by (simp [OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hz]) + (simp only [OAI.EditApproximation.UnreducedRational.inv, OAI.EditApproximation.BinaryFraction.representation, hv, ↓reduceDIte]) + exact proof_zero_representation_38 + · have hn : OAI.EditApproximation.bitWordValue a.numerator.bits ≠ 0 := by + intro hz + exact h ((proof_bitCompareWithWork_eq_3 a.numerator.bits []).2 (by simpa [OAI.EditApproximation.bitWordValue] using hz)) + have hv : a.numerator.value ≠ 0 := by + cases hs : a.numerator.negative <;> (simp [OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hs, hn]) + (simp only [OAI.EditApproximation.UnreducedRational.inv, OAI.EditApproximation.BinaryFraction.representation, hv, ↓reduceDIte]) + apply proof_eq_of_num_den_33 + · cases hs : a.numerator.negative <;> + simp [OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hs, Int.sign_natCast_of_ne_zero hn] + · cases hs : a.numerator.negative <;> (simp [OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hs]) + have proof_divWithWork_representation_40 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (a.divWithWork b).1.representation = a.representation.div b.representation := by + (simp only [OAI.EditApproximation.BinaryFraction.divWithWork, proof_canonicalMulWithWork_representation_37, proof_invWithWork_representation_39, + OAI.EditApproximation.UnreducedRational.div]) + have proof_value_mul_41 (a : OAI.EditApproximation.UnreducedRational) (b : OAI.EditApproximation.UnreducedRational) : (a.mul b).value = a.value * b.value := by + simp [OAI.EditApproximation.UnreducedRational.mul, OAI.EditApproximation.UnreducedRational.value, mul_div_mul_comm] + have proof_value_inv_42 (a : OAI.EditApproximation.UnreducedRational) : a.inv.value = a.value⁻¹ := by + by_cases h : a.num = 0 + · simp [OAI.EditApproximation.UnreducedRational.inv, h, OAI.EditApproximation.UnreducedRational.value, OAI.EditApproximation.UnreducedRational.zero] + · have hn : (a.num.natAbs : ℚ) ≠ 0 := by exact_mod_cast (Int.natAbs_pos.mpr h).ne' + have hd : (a.den : ℚ) ≠ 0 := by exact_mod_cast a.den_pos.ne' + have hsign : ((a.num.sign : ℤ) : ℚ) * a.num = (a.num.natAbs : ℚ) := by + simpa only [Int.cast_mul, Int.cast_natCast] using + congrArg (fun z : ℤ => (z : ℚ)) (Int.sign_mul_self_eq_natAbs a.num) + simp only [OAI.EditApproximation.UnreducedRational.inv, h, ↓reduceDIte, OAI.EditApproximation.UnreducedRational.value] + push_cast + apply eq_inv_of_mul_eq_one_left + field_simp [hn, hd] + exact hsign + have proof_value_div_43 (a : OAI.EditApproximation.UnreducedRational) (b : OAI.EditApproximation.UnreducedRational) : (a.div b).value = a.value / b.value := by + simp [proof_value_mul_41, proof_value_inv_42, OAI.EditApproximation.UnreducedRational.div, div_eq_mul_inv] + have proof_divWithWork_value_44 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.divWithWork a b).1.value = a.value / b.value := by + rw [← proof_representation_value_32, proof_divWithWork_representation_40, + proof_value_div_43, proof_representation_value_32, proof_representation_value_32] + have proof_canonicalMulWithWork_value_45 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork a b).1.value = a.value * b.value := by + rw [← proof_representation_value_32, proof_canonicalMulWithWork_representation_37, + proof_value_mul_41, proof_representation_value_32, proof_representation_value_32] + have proof_value_ofInt_46 (a : ℤ) : (OAI.EditApproximation.SignedBinary.ofInt a).value = a := by + by_cases h : a < 0 + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_true, + ↓reduceIte] using (Int.eq_neg_natAbs_of_nonpos (le_of_lt h)).symm + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_false, + Bool.false_eq_true, ↓reduceIte] using (Int.eq_natAbs_of_nonneg (le_of_not_gt h)).symm + have proof_nat_representation_47 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).representation = OAI.EditApproximation.UnreducedRational.nat n := by + apply proof_eq_of_num_den_33 + · change (OAI.EditApproximation.SignedBinary.ofInt (n : ℤ)).value = (n : ℤ) + exact proof_value_ofInt_46 _ + · rfl + have proof_value_nat_48 (n : ℕ) : (OAI.EditApproximation.UnreducedRational.nat n).value = n := by (simp [OAI.EditApproximation.UnreducedRational.nat, OAI.EditApproximation.UnreducedRational.value]) + have proof_nat_value_49 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).value = (n : ℚ) := by + rw [← proof_representation_value_32, proof_nat_representation_47, proof_value_nat_48] + have proof_groupSampleCountWithWork_value_28 (M : ℕ) (Q : ℕ) (b : ℕ) (h : OAI.EditApproximation.BinaryFraction) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.BinaryFraction.groupSampleCountWithWork M Q b h).1 = OAI.EditApproximation.groupSampleCount M Q b h.value := by + simp only [OAI.EditApproximation.BinaryFraction.groupSampleCountWithWork, proof_wordMinWithWork_value_29, proof_bitWordValue_bits_15, + proof_naturalCeilingWithWork_value_31, proof_divWithWork_value_44, proof_canonicalMulWithWork_value_45, + proof_nat_value_49, OAI.EditApproximation.groupSampleCount] + exact + let count := OAI.EditApproximation.BinaryFraction.groupSampleCountWithWork M Q b h + let test := OAI.EditApproximation.naturalEqualWithWork (OAI.EditApproximation.bitWordValue count.1) M + if test.1 then (List.finRange M, count.2 + test.2 + M + 2) + else + let indices := OAI.EditApproximation.queryFinRange (OAI.EditApproximation.bitWordValue count.1) (OAI.EditApproximation.groupSampleCount M Q b h.value) + (proof_groupSampleCountWithWork_value_28 M Q b h) + let labels := OAI.EditApproximation.arithmeticMapWithWork draw indices + (labels.1, count.2 + test.2 + labels.2 + indices.length + 2) + +def queryGroupLabelsAllocation (M Q b : ℕ) (h : OAI.EditApproximation.BinaryFraction) + (_draw : Fin (OAI.EditApproximation.groupSampleCount M Q b h.value) → Fin M × ℕ) + (allocation : Fin (OAI.EditApproximation.groupSampleCount M Q b h.value) → ℕ) : ℕ := by + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_wordLEWithWork_value_26 (a : List.{0} Bool) (b : List.{0} Bool) : + (OAI.EditApproximation.wordLEWithWork a b).1 = true ↔ OAI.EditApproximation.bitWordValue a ≤ OAI.EditApproximation.bitWordValue b := by + simp only [OAI.EditApproximation.wordLEWithWork, Bool.not_eq_true', decide_eq_false_iff_not, + proof_bitCompareWithWork_lt_16, not_lt] + have proof_wordMinWithWork_value_29 (a : List.{0} Bool) (b : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.wordMinWithWork a b).1 = min (OAI.EditApproximation.bitWordValue a) (OAI.EditApproximation.bitWordValue b) := by + unfold OAI.EditApproximation.wordMinWithWork + dsimp only + split_ifs with h + · exact (min_eq_left ((proof_wordLEWithWork_value_26 a b).mp h)).symm + · exact (min_eq_right (le_of_not_ge (fun hle => h ((proof_wordLEWithWork_value_26 a b).mpr hle)))).symm + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_bitSubtractor_value_17 (a : Bool) (b : Bool) (borrow : Bool) : + a.toNat + 2 * (OAI.EditApproximation.bitBorrow a b borrow).toNat = + b.toNat + borrow.toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat := by + cases a <;> cases b <;> cases borrow <;> decide + have proof_bitSubtractionRippleEquation_18 (a : ℕ) (b : ℕ) (borrow : ℕ) (nextBorrow : ℕ) (difference : ℕ) (left : ℕ) (right : ℕ) (result : ℕ) (tail : ℕ) (htail : Eq.{1} (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} result right) nextBorrow) (HAdd.hAdd.{0, 0, 0} left tail)) (hbit : Eq.{1} (HAdd.hAdd.{0, 0, 0} a (HMul.hMul.{0, 0, 0} 2 nextBorrow)) + (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} b borrow) difference)) : + (difference + 2 * result) + (b + 2 * right) + borrow = + (a + 2 * left) + 2 * tail := by + omega + have proof_bitSubtractWithWork_value_19 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right borrow).1 + OAI.EditApproximation.bitWordValue right + borrow.toNat = + OAI.EditApproximation.bitWordValue left + 2 ^ max left.length right.length * + (OAI.EditApproximation.bitSubtractWithWork left right borrow).2.1.toNat := by + induction left generalizing right borrow with + | nil => + induction right generalizing borrow with + | nil => (simp [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + have h := ih (OAI.EditApproximation.bitBorrow false b borrow) + have hb := proof_bitSubtractor_value_17 false b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue, + List.length_nil, List.length_cons, Nat.zero_max, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 0 b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow false b borrow).toNat + (OAI.EditApproximation.bitDifference false b borrow).toNat 0 (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).1) + (2 ^ bs.length * (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons a as ih => + cases right with + | nil => + have h := ih [] (OAI.EditApproximation.bitBorrow a false borrow) + have hb := proof_bitSubtractor_value_17 a false borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_nil, List.length_cons, + Nat.max_zero, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat 0 borrow.toNat (OAI.EditApproximation.bitBorrow a false borrow).toNat + (OAI.EditApproximation.bitDifference a false borrow).toNat (OAI.EditApproximation.bitWordValue as) 0 + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).1) + (2 ^ as.length * (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons b bs => + have h := ih bs (OAI.EditApproximation.bitBorrow a b borrow) + have hb := proof_bitSubtractor_value_17 a b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_cons, Nat.succ_max_succ, + pow_succ] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow a b borrow).toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).1) + (2 ^ max as.length bs.length * (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_assoc, Nat.mul_left_comm] using hs + have proof_bitWordValue_lt_pow_length_20 (bits : List.{0} Bool) : OAI.EditApproximation.bitWordValue bits < 2 ^ bits.length := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitWordValue]) + | cons bit bits ih => + cases bit <;> (simp only [OAI.EditApproximation.bitWordValue, List.length_cons, pow_succ, Bool.toNat_false, Bool.toNat_true]) <;> omega + have proof_bitSubtractWithWork_length_21 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + (OAI.EditApproximation.bitSubtractWithWork left right borrow).1.length = max left.length right.length := by + induction left generalizing right borrow with + | nil => + simp only [OAI.EditApproximation.bitSubtractWithWork] + induction right generalizing borrow with + | nil => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork] + | cons b bs ih => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork, ih] + | cons a as ih => + cases right with + | nil => simp [OAI.EditApproximation.bitSubtractWithWork, ih] + | cons b bs => simp [OAI.EditApproximation.bitSubtractWithWork, ih, Nat.succ_max_succ] + have proof_bitSubtractWithWork_sub_22 (left : List.{0} Bool) (right : List.{0} Bool) (h : LE.le.{0} (OAI.EditApproximation.bitWordValue right) (OAI.EditApproximation.bitWordValue left)) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right false).1 = OAI.EditApproximation.bitWordValue left - OAI.EditApproximation.bitWordValue right := by + have hvalue := proof_bitSubtractWithWork_value_19 left right false + have hlt := proof_bitWordValue_lt_pow_length_20 (OAI.EditApproximation.bitSubtractWithWork left right false).1 + rw [proof_bitSubtractWithWork_length_21] at hlt + cases hb : (OAI.EditApproximation.bitSubtractWithWork left right false).2.1 + · simp only [hb, Bool.toNat_false, Nat.mul_zero, Nat.add_zero] at hvalue + omega + · simp only [hb, Bool.toNat_true, Bool.toNat_false, Nat.mul_one, Nat.add_zero] at hvalue + omega + have proof_bitDivModWithWork_value_23 (divisor : List.{0} Bool) (bits : List.{0} Bool) (hd : LT.lt.{0} 0 (OAI.EditApproximation.bitWordValue divisor)) : + OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).1 + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 < OAI.EditApproximation.bitWordValue divisor := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitDivModWithWork, OAI.EditApproximation.bitWordValue, hd]) + | cons bit bits ih => + let previous := OAI.EditApproximation.bitDivModWithWork divisor bits + let candidate := bit :: previous.2.1 + have hp : OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue previous.1 + + OAI.EditApproximation.bitWordValue previous.2.1 := ih.1 + have hr : OAI.EditApproximation.bitWordValue previous.2.1 < OAI.EditApproximation.bitWordValue divisor := ih.2 + have hc : OAI.EditApproximation.bitWordValue candidate < 2 * OAI.EditApproximation.bitWordValue divisor := by + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + cases bit <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega + by_cases hlt : (OAI.EditApproximation.bitCompareWithWork candidate divisor).1 = .lt + · have hv := (proof_bitCompareWithWork_lt_16 candidate divisor).1 hlt + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 = .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * + OAI.EditApproximation.bitWordValue (false :: previous.1) + OAI.EditApproximation.bitWordValue candidate ∧ OAI.EditApproximation.bitWordValue candidate < _ + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_false]) + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + nlinarith only [hp] + · exact hv + · have hv : OAI.EditApproximation.bitWordValue divisor ≤ OAI.EditApproximation.bitWordValue candidate := by + exact Nat.le_of_not_gt (fun h => hlt ((proof_bitCompareWithWork_lt_16 candidate divisor).2 h)) + have hs := proof_bitSubtractWithWork_sub_22 candidate divisor hv + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 ≠ .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (true :: previous.1) + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 < _ + rw [hs] + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_true]) + have he := Nat.sub_add_cancel hv + dsimp only [candidate, OAI.EditApproximation.bitWordValue] at he ⊢ + nlinarith only [hp, he] + · omega + have proof_bitCompareWithWork_eq_3 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .eq ↔ OAI.EditApproximation.bitWordValue left = OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_bitAdder_value_1 (a : Bool) (b : Bool) (carry : Bool) : + (OAI.EditApproximation.bitSum a b carry).toNat + 2 * (OAI.EditApproximation.bitCarry a b carry).toNat = + a.toNat + b.toNat + carry.toNat := by + cases a <;> cases b <;> cases carry <;> decide + have proof_bitAddWithWork_value_2 (left : List.{0} Bool) (right : List.{0} Bool) (carry : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitAddWithWork left right carry).1 = + OAI.EditApproximation.bitWordValue left + OAI.EditApproximation.bitWordValue right + carry.toNat := by + induction left generalizing right carry with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork] + induction right generalizing carry with + | nil => cases carry <;> simp [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue] + | cons b bs ih => + simp only [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 false b carry + simp only [Bool.toNat_false] at h + omega + | cons a as ih => + cases right with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a false carry + simp only [Bool.toNat_false] at h + omega + | cons b bs => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a b carry + omega + have proof_bitCeilDivWithWork_value_30 (divisor : List.{0} Bool) (bits : List.{0} Bool) (hd : LT.lt.{0} 0 (OAI.EditApproximation.bitWordValue divisor)) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitCeilDivWithWork divisor bits).1 = + ⌈((OAI.EditApproximation.bitWordValue bits : ℚ) / OAI.EditApproximation.bitWordValue divisor)⌉₊ := by + let q := OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).1 + let r := OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 + have h := proof_bitDivModWithWork_value_23 divisor bits hd + have heq : OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * q + r := h.1 + have hr : r < OAI.EditApproximation.bitWordValue divisor := h.2 + have hdQ : (0 : ℚ) < OAI.EditApproximation.bitWordValue divisor := by exact_mod_cast hd + unfold OAI.EditApproximation.bitCeilDivWithWork + dsimp only + split_ifs with hz + · have hr0 : r = 0 := by + exact (proof_bitCompareWithWork_eq_3 (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 []).1 hz + have hratio : (OAI.EditApproximation.bitWordValue bits : ℚ) / OAI.EditApproximation.bitWordValue divisor = (q : ℚ) := by + apply (div_eq_iff hdQ.ne').mpr + exact_mod_cast (show OAI.EditApproximation.bitWordValue bits = q * OAI.EditApproximation.bitWordValue divisor by nlinarith only [heq, hr0]) + rw [hratio] + exact (Nat.ceil_natCast q).symm + · have hr0 : r ≠ 0 := by + intro hzero + exact hz ((proof_bitCompareWithWork_eq_3 (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 []).2 hzero) + rw [proof_bitAddWithWork_value_2] + change q + 1 + 0 = _ + simp only [Nat.add_zero] + symm + apply (Nat.ceil_eq_iff (by omega : q + 1 ≠ 0)).mpr + constructor + · simp only [Nat.add_sub_cancel] + rw [lt_div_iff₀ hdQ] + exact_mod_cast (show q * OAI.EditApproximation.bitWordValue divisor < OAI.EditApproximation.bitWordValue bits by + nlinarith only [heq, Nat.pos_of_ne_zero hr0]) + · rw [div_le_iff₀ hdQ] + push_cast + exact_mod_cast (show OAI.EditApproximation.bitWordValue bits ≤ (q + 1) * OAI.EditApproximation.bitWordValue divisor by nlinarith only [heq, hr]) + have proof_naturalCeilingWithWork_value_31 (a : OAI.EditApproximation.BinaryFraction) : + OAI.EditApproximation.bitWordValue (a.naturalCeilingWithWork).1 = ⌈a.value⌉₊ := by + cases hs : a.numerator.negative + · simpa only [OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork, hs, Bool.false_eq_true, ↓reduceIte, + OAI.EditApproximation.BinaryFraction.value, OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, Int.cast_natCast] using + proof_bitCeilDivWithWork_value_30 a.denominator a.numerator.bits a.denominator_pos + · have hn : a.value ≤ 0 := by + (simp only [OAI.EditApproximation.BinaryFraction.value, OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hs, ↓reduceIte, Int.cast_neg, Int.cast_natCast]) + exact div_nonpos_of_nonpos_of_nonneg (neg_nonpos.mpr (Nat.cast_nonneg _)) (Nat.cast_nonneg _) + (simp only [OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork, hs, ↓reduceIte, OAI.EditApproximation.bitWordValue]) + exact (Nat.ceil_eq_zero.mpr hn).symm + have proof_representation_value_32 (a : OAI.EditApproximation.BinaryFraction) : a.representation.value = a.value := rfl + have proof_eq_of_num_den_33 {a : OAI.EditApproximation.UnreducedRational} {b : OAI.EditApproximation.UnreducedRational} (hnum : Eq.{1} a.num b.num) (hden : Eq.{1} a.den b.den) : a = b := by + cases a + cases b + cases hnum + cases hden + rfl + have proof_trimBitWordWithWork_value_6 (bits : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.trimBitWordWithWork bits).1 = OAI.EditApproximation.bitWordValue bits := by + induction bits with + | nil => rfl + | cons bit bits ih => + simp only [OAI.EditApproximation.trimBitWordWithWork] + split_ifs with h + · have ht : OAI.EditApproximation.bitWordValue bits = 0 := by rw [← ih, h.1]; rfl + simp [h.2, OAI.EditApproximation.bitWordValue, ht] + · (simp only [OAI.EditApproximation.bitWordValue, ih]) + have proof_canonicalizeWithWork_representation_34 (a : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.canonicalizeWithWork a).1.representation = a.representation := by + apply proof_eq_of_num_den_33 + · (simp only [OAI.EditApproximation.BinaryFraction.canonicalizeWithWork, OAI.EditApproximation.BinaryFraction.representation, OAI.EditApproximation.SignedBinary.value, proof_trimBitWordWithWork_value_6]) + · exact proof_trimBitWordWithWork_value_6 a.denominator + have proof_bitMulWithWork_value_0 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitMulWithWork left right).1 = OAI.EditApproximation.bitWordValue left * OAI.EditApproximation.bitWordValue right := by + induction left with + | nil => simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue] + | cons bit bits ih => + cases bit <;> simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue, proof_bitAddWithWork_value_2, ih] <;> ring + have proof_mulWithWork_value_35 (a : OAI.EditApproximation.SignedBinary) (b : OAI.EditApproximation.SignedBinary) : + (a.mulWithWork b).1.value = a.value * b.value := by + simp only [OAI.EditApproximation.SignedBinary.mulWithWork, OAI.EditApproximation.SignedBinary.value, proof_bitMulWithWork_value_0] + cases a.negative <;> cases b.negative <;> simp [OAI.EditApproximation.signedMagnitude] + have proof_mulWithWork_representation_36 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (a.mulWithWork b).1.representation = a.representation.mul b.representation := by + apply proof_eq_of_num_den_33 + · exact proof_mulWithWork_value_35 a.numerator b.numerator + · exact proof_bitMulWithWork_value_0 a.denominator b.denominator + have proof_canonicalMulWithWork_representation_37 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork a b).1.representation = a.representation.mul b.representation := by + rw [OAI.EditApproximation.BinaryFraction.canonicalMulWithWork, proof_canonicalizeWithWork_representation_34, proof_mulWithWork_representation_36] + have proof_zero_representation_38 : OAI.EditApproximation.BinaryFraction.zero.representation = OAI.EditApproximation.UnreducedRational.zero := by + apply proof_eq_of_num_den_33 <;> rfl + have proof_invWithWork_representation_39 (a : OAI.EditApproximation.BinaryFraction) : + (a.invWithWork).1.representation = a.representation.inv := by + unfold OAI.EditApproximation.BinaryFraction.invWithWork + dsimp only + split_ifs with h + · have hz : OAI.EditApproximation.bitWordValue a.numerator.bits = 0 := by + simpa only [OAI.EditApproximation.bitWordValue] using (proof_bitCompareWithWork_eq_3 a.numerator.bits []).1 h + have hv : a.numerator.value = 0 := by (simp [OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hz]) + (simp only [OAI.EditApproximation.UnreducedRational.inv, OAI.EditApproximation.BinaryFraction.representation, hv, ↓reduceDIte]) + exact proof_zero_representation_38 + · have hn : OAI.EditApproximation.bitWordValue a.numerator.bits ≠ 0 := by + intro hz + exact h ((proof_bitCompareWithWork_eq_3 a.numerator.bits []).2 (by simpa [OAI.EditApproximation.bitWordValue] using hz)) + have hv : a.numerator.value ≠ 0 := by + cases hs : a.numerator.negative <;> (simp [OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hs, hn]) + (simp only [OAI.EditApproximation.UnreducedRational.inv, OAI.EditApproximation.BinaryFraction.representation, hv, ↓reduceDIte]) + apply proof_eq_of_num_den_33 + · cases hs : a.numerator.negative <;> + simp [OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hs, Int.sign_natCast_of_ne_zero hn] + · cases hs : a.numerator.negative <;> (simp [OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hs]) + have proof_divWithWork_representation_40 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (a.divWithWork b).1.representation = a.representation.div b.representation := by + (simp only [OAI.EditApproximation.BinaryFraction.divWithWork, proof_canonicalMulWithWork_representation_37, proof_invWithWork_representation_39, + OAI.EditApproximation.UnreducedRational.div]) + have proof_value_mul_41 (a : OAI.EditApproximation.UnreducedRational) (b : OAI.EditApproximation.UnreducedRational) : (a.mul b).value = a.value * b.value := by + simp [OAI.EditApproximation.UnreducedRational.mul, OAI.EditApproximation.UnreducedRational.value, mul_div_mul_comm] + have proof_value_inv_42 (a : OAI.EditApproximation.UnreducedRational) : a.inv.value = a.value⁻¹ := by + by_cases h : a.num = 0 + · simp [OAI.EditApproximation.UnreducedRational.inv, h, OAI.EditApproximation.UnreducedRational.value, OAI.EditApproximation.UnreducedRational.zero] + · have hn : (a.num.natAbs : ℚ) ≠ 0 := by exact_mod_cast (Int.natAbs_pos.mpr h).ne' + have hd : (a.den : ℚ) ≠ 0 := by exact_mod_cast a.den_pos.ne' + have hsign : ((a.num.sign : ℤ) : ℚ) * a.num = (a.num.natAbs : ℚ) := by + simpa only [Int.cast_mul, Int.cast_natCast] using + congrArg (fun z : ℤ => (z : ℚ)) (Int.sign_mul_self_eq_natAbs a.num) + simp only [OAI.EditApproximation.UnreducedRational.inv, h, ↓reduceDIte, OAI.EditApproximation.UnreducedRational.value] + push_cast + apply eq_inv_of_mul_eq_one_left + field_simp [hn, hd] + exact hsign + have proof_value_div_43 (a : OAI.EditApproximation.UnreducedRational) (b : OAI.EditApproximation.UnreducedRational) : (a.div b).value = a.value / b.value := by + simp [proof_value_mul_41, proof_value_inv_42, OAI.EditApproximation.UnreducedRational.div, div_eq_mul_inv] + have proof_divWithWork_value_44 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.divWithWork a b).1.value = a.value / b.value := by + rw [← proof_representation_value_32, proof_divWithWork_representation_40, + proof_value_div_43, proof_representation_value_32, proof_representation_value_32] + have proof_canonicalMulWithWork_value_45 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork a b).1.value = a.value * b.value := by + rw [← proof_representation_value_32, proof_canonicalMulWithWork_representation_37, + proof_value_mul_41, proof_representation_value_32, proof_representation_value_32] + have proof_value_ofInt_46 (a : ℤ) : (OAI.EditApproximation.SignedBinary.ofInt a).value = a := by + by_cases h : a < 0 + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_true, + ↓reduceIte] using (Int.eq_neg_natAbs_of_nonpos (le_of_lt h)).symm + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_false, + Bool.false_eq_true, ↓reduceIte] using (Int.eq_natAbs_of_nonneg (le_of_not_gt h)).symm + have proof_nat_representation_47 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).representation = OAI.EditApproximation.UnreducedRational.nat n := by + apply proof_eq_of_num_den_33 + · change (OAI.EditApproximation.SignedBinary.ofInt (n : ℤ)).value = (n : ℤ) + exact proof_value_ofInt_46 _ + · rfl + have proof_value_nat_48 (n : ℕ) : (OAI.EditApproximation.UnreducedRational.nat n).value = n := by (simp [OAI.EditApproximation.UnreducedRational.nat, OAI.EditApproximation.UnreducedRational.value]) + have proof_nat_value_49 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).value = (n : ℚ) := by + rw [← proof_representation_value_32, proof_nat_representation_47, proof_value_nat_48] + have proof_groupSampleCountWithWork_value_28 (M : ℕ) (Q : ℕ) (b : ℕ) (h : OAI.EditApproximation.BinaryFraction) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.BinaryFraction.groupSampleCountWithWork M Q b h).1 = OAI.EditApproximation.groupSampleCount M Q b h.value := by + simp only [OAI.EditApproximation.BinaryFraction.groupSampleCountWithWork, proof_wordMinWithWork_value_29, proof_bitWordValue_bits_15, + proof_naturalCeilingWithWork_value_31, proof_divWithWork_value_44, proof_canonicalMulWithWork_value_45, + proof_nat_value_49, OAI.EditApproximation.groupSampleCount] + exact + let count := (OAI.EditApproximation.BinaryFraction.groupSampleCountWithWork M Q b h).1 + let test := (OAI.EditApproximation.naturalEqualWithWork (OAI.EditApproximation.bitWordValue count) M).1 + OAI.EditApproximation.BinaryFraction.groupSampleCountAllocation M Q b h + OAI.EditApproximation.naturalEqualAllocation (OAI.EditApproximation.bitWordValue count) M + + if test then M else + let indices := OAI.EditApproximation.queryFinRange (OAI.EditApproximation.bitWordValue count) (OAI.EditApproximation.groupSampleCount M Q b h.value) + (proof_groupSampleCountWithWork_value_28 M Q b h) + OAI.EditApproximation.arithmeticMapAllocation allocation indices + 2 * indices.length + +def countedGroupMemberSourceAllocation {M T : ℕ} (Q b : ℕ) (scales : Fin T → OAI.EditApproximation.BinaryFraction) + (connection : OAI.EditApproximation.BinaryFraction) (envelope values : Vector OAI.EditApproximation.BinaryFraction M) + (draw : ∀ t, Fin (OAI.EditApproximation.groupSampleCount M Q b (scales t).value) → Fin M × ℕ) + (allocation : ∀ t, Fin (OAI.EditApproximation.groupSampleCount M Q b (scales t).value) → ℕ) : ℕ := by + have proof_vectorMapWithWork_value_27 {α : Type 0} (d : ℕ) (f : Fin d → Prod.{0, 0} α ℕ) (i : Fin d) : + (OAI.EditApproximation.vectorMapWithWork d f).1.get i = (f i).1 := by + change (Vector.ofFn f |>.map Prod.fst)[i.val] = _ + simp only [Vector.getElem_map, Vector.getElem_ofFn] + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_wordLEWithWork_value_26 (a : List.{0} Bool) (b : List.{0} Bool) : + (OAI.EditApproximation.wordLEWithWork a b).1 = true ↔ OAI.EditApproximation.bitWordValue a ≤ OAI.EditApproximation.bitWordValue b := by + simp only [OAI.EditApproximation.wordLEWithWork, Bool.not_eq_true', decide_eq_false_iff_not, + proof_bitCompareWithWork_lt_16, not_lt] + have proof_wordMinWithWork_value_29 (a : List.{0} Bool) (b : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.wordMinWithWork a b).1 = min (OAI.EditApproximation.bitWordValue a) (OAI.EditApproximation.bitWordValue b) := by + unfold OAI.EditApproximation.wordMinWithWork + dsimp only + split_ifs with h + · exact (min_eq_left ((proof_wordLEWithWork_value_26 a b).mp h)).symm + · exact (min_eq_right (le_of_not_ge (fun hle => h ((proof_wordLEWithWork_value_26 a b).mpr hle)))).symm + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_bitSubtractor_value_17 (a : Bool) (b : Bool) (borrow : Bool) : + a.toNat + 2 * (OAI.EditApproximation.bitBorrow a b borrow).toNat = + b.toNat + borrow.toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat := by + cases a <;> cases b <;> cases borrow <;> decide + have proof_bitSubtractionRippleEquation_18 (a : ℕ) (b : ℕ) (borrow : ℕ) (nextBorrow : ℕ) (difference : ℕ) (left : ℕ) (right : ℕ) (result : ℕ) (tail : ℕ) (htail : Eq.{1} (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} result right) nextBorrow) (HAdd.hAdd.{0, 0, 0} left tail)) (hbit : Eq.{1} (HAdd.hAdd.{0, 0, 0} a (HMul.hMul.{0, 0, 0} 2 nextBorrow)) + (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} b borrow) difference)) : + (difference + 2 * result) + (b + 2 * right) + borrow = + (a + 2 * left) + 2 * tail := by + omega + have proof_bitSubtractWithWork_value_19 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right borrow).1 + OAI.EditApproximation.bitWordValue right + borrow.toNat = + OAI.EditApproximation.bitWordValue left + 2 ^ max left.length right.length * + (OAI.EditApproximation.bitSubtractWithWork left right borrow).2.1.toNat := by + induction left generalizing right borrow with + | nil => + induction right generalizing borrow with + | nil => (simp [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + have h := ih (OAI.EditApproximation.bitBorrow false b borrow) + have hb := proof_bitSubtractor_value_17 false b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue, + List.length_nil, List.length_cons, Nat.zero_max, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 0 b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow false b borrow).toNat + (OAI.EditApproximation.bitDifference false b borrow).toNat 0 (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).1) + (2 ^ bs.length * (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons a as ih => + cases right with + | nil => + have h := ih [] (OAI.EditApproximation.bitBorrow a false borrow) + have hb := proof_bitSubtractor_value_17 a false borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_nil, List.length_cons, + Nat.max_zero, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat 0 borrow.toNat (OAI.EditApproximation.bitBorrow a false borrow).toNat + (OAI.EditApproximation.bitDifference a false borrow).toNat (OAI.EditApproximation.bitWordValue as) 0 + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).1) + (2 ^ as.length * (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons b bs => + have h := ih bs (OAI.EditApproximation.bitBorrow a b borrow) + have hb := proof_bitSubtractor_value_17 a b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_cons, Nat.succ_max_succ, + pow_succ] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow a b borrow).toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).1) + (2 ^ max as.length bs.length * (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_assoc, Nat.mul_left_comm] using hs + have proof_bitWordValue_lt_pow_length_20 (bits : List.{0} Bool) : OAI.EditApproximation.bitWordValue bits < 2 ^ bits.length := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitWordValue]) + | cons bit bits ih => + cases bit <;> (simp only [OAI.EditApproximation.bitWordValue, List.length_cons, pow_succ, Bool.toNat_false, Bool.toNat_true]) <;> omega + have proof_bitSubtractWithWork_length_21 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + (OAI.EditApproximation.bitSubtractWithWork left right borrow).1.length = max left.length right.length := by + induction left generalizing right borrow with + | nil => + simp only [OAI.EditApproximation.bitSubtractWithWork] + induction right generalizing borrow with + | nil => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork] + | cons b bs ih => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork, ih] + | cons a as ih => + cases right with + | nil => simp [OAI.EditApproximation.bitSubtractWithWork, ih] + | cons b bs => simp [OAI.EditApproximation.bitSubtractWithWork, ih, Nat.succ_max_succ] + have proof_bitSubtractWithWork_sub_22 (left : List.{0} Bool) (right : List.{0} Bool) (h : LE.le.{0} (OAI.EditApproximation.bitWordValue right) (OAI.EditApproximation.bitWordValue left)) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right false).1 = OAI.EditApproximation.bitWordValue left - OAI.EditApproximation.bitWordValue right := by + have hvalue := proof_bitSubtractWithWork_value_19 left right false + have hlt := proof_bitWordValue_lt_pow_length_20 (OAI.EditApproximation.bitSubtractWithWork left right false).1 + rw [proof_bitSubtractWithWork_length_21] at hlt + cases hb : (OAI.EditApproximation.bitSubtractWithWork left right false).2.1 + · simp only [hb, Bool.toNat_false, Nat.mul_zero, Nat.add_zero] at hvalue + omega + · simp only [hb, Bool.toNat_true, Bool.toNat_false, Nat.mul_one, Nat.add_zero] at hvalue + omega + have proof_bitDivModWithWork_value_23 (divisor : List.{0} Bool) (bits : List.{0} Bool) (hd : LT.lt.{0} 0 (OAI.EditApproximation.bitWordValue divisor)) : + OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).1 + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 < OAI.EditApproximation.bitWordValue divisor := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitDivModWithWork, OAI.EditApproximation.bitWordValue, hd]) + | cons bit bits ih => + let previous := OAI.EditApproximation.bitDivModWithWork divisor bits + let candidate := bit :: previous.2.1 + have hp : OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue previous.1 + + OAI.EditApproximation.bitWordValue previous.2.1 := ih.1 + have hr : OAI.EditApproximation.bitWordValue previous.2.1 < OAI.EditApproximation.bitWordValue divisor := ih.2 + have hc : OAI.EditApproximation.bitWordValue candidate < 2 * OAI.EditApproximation.bitWordValue divisor := by + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + cases bit <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega + by_cases hlt : (OAI.EditApproximation.bitCompareWithWork candidate divisor).1 = .lt + · have hv := (proof_bitCompareWithWork_lt_16 candidate divisor).1 hlt + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 = .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * + OAI.EditApproximation.bitWordValue (false :: previous.1) + OAI.EditApproximation.bitWordValue candidate ∧ OAI.EditApproximation.bitWordValue candidate < _ + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_false]) + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + nlinarith only [hp] + · exact hv + · have hv : OAI.EditApproximation.bitWordValue divisor ≤ OAI.EditApproximation.bitWordValue candidate := by + exact Nat.le_of_not_gt (fun h => hlt ((proof_bitCompareWithWork_lt_16 candidate divisor).2 h)) + have hs := proof_bitSubtractWithWork_sub_22 candidate divisor hv + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 ≠ .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (true :: previous.1) + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 < _ + rw [hs] + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_true]) + have he := Nat.sub_add_cancel hv + dsimp only [candidate, OAI.EditApproximation.bitWordValue] at he ⊢ + nlinarith only [hp, he] + · omega + have proof_bitCompareWithWork_eq_3 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .eq ↔ OAI.EditApproximation.bitWordValue left = OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_bitAdder_value_1 (a : Bool) (b : Bool) (carry : Bool) : + (OAI.EditApproximation.bitSum a b carry).toNat + 2 * (OAI.EditApproximation.bitCarry a b carry).toNat = + a.toNat + b.toNat + carry.toNat := by + cases a <;> cases b <;> cases carry <;> decide + have proof_bitAddWithWork_value_2 (left : List.{0} Bool) (right : List.{0} Bool) (carry : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitAddWithWork left right carry).1 = + OAI.EditApproximation.bitWordValue left + OAI.EditApproximation.bitWordValue right + carry.toNat := by + induction left generalizing right carry with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork] + induction right generalizing carry with + | nil => cases carry <;> simp [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue] + | cons b bs ih => + simp only [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 false b carry + simp only [Bool.toNat_false] at h + omega + | cons a as ih => + cases right with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a false carry + simp only [Bool.toNat_false] at h + omega + | cons b bs => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a b carry + omega + have proof_bitCeilDivWithWork_value_30 (divisor : List.{0} Bool) (bits : List.{0} Bool) (hd : LT.lt.{0} 0 (OAI.EditApproximation.bitWordValue divisor)) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitCeilDivWithWork divisor bits).1 = + ⌈((OAI.EditApproximation.bitWordValue bits : ℚ) / OAI.EditApproximation.bitWordValue divisor)⌉₊ := by + let q := OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).1 + let r := OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 + have h := proof_bitDivModWithWork_value_23 divisor bits hd + have heq : OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * q + r := h.1 + have hr : r < OAI.EditApproximation.bitWordValue divisor := h.2 + have hdQ : (0 : ℚ) < OAI.EditApproximation.bitWordValue divisor := by exact_mod_cast hd + unfold OAI.EditApproximation.bitCeilDivWithWork + dsimp only + split_ifs with hz + · have hr0 : r = 0 := by + exact (proof_bitCompareWithWork_eq_3 (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 []).1 hz + have hratio : (OAI.EditApproximation.bitWordValue bits : ℚ) / OAI.EditApproximation.bitWordValue divisor = (q : ℚ) := by + apply (div_eq_iff hdQ.ne').mpr + exact_mod_cast (show OAI.EditApproximation.bitWordValue bits = q * OAI.EditApproximation.bitWordValue divisor by nlinarith only [heq, hr0]) + rw [hratio] + exact (Nat.ceil_natCast q).symm + · have hr0 : r ≠ 0 := by + intro hzero + exact hz ((proof_bitCompareWithWork_eq_3 (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 []).2 hzero) + rw [proof_bitAddWithWork_value_2] + change q + 1 + 0 = _ + simp only [Nat.add_zero] + symm + apply (Nat.ceil_eq_iff (by omega : q + 1 ≠ 0)).mpr + constructor + · simp only [Nat.add_sub_cancel] + rw [lt_div_iff₀ hdQ] + exact_mod_cast (show q * OAI.EditApproximation.bitWordValue divisor < OAI.EditApproximation.bitWordValue bits by + nlinarith only [heq, Nat.pos_of_ne_zero hr0]) + · rw [div_le_iff₀ hdQ] + push_cast + exact_mod_cast (show OAI.EditApproximation.bitWordValue bits ≤ (q + 1) * OAI.EditApproximation.bitWordValue divisor by nlinarith only [heq, hr]) + have proof_naturalCeilingWithWork_value_31 (a : OAI.EditApproximation.BinaryFraction) : + OAI.EditApproximation.bitWordValue (a.naturalCeilingWithWork).1 = ⌈a.value⌉₊ := by + cases hs : a.numerator.negative + · simpa only [OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork, hs, Bool.false_eq_true, ↓reduceIte, + OAI.EditApproximation.BinaryFraction.value, OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, Int.cast_natCast] using + proof_bitCeilDivWithWork_value_30 a.denominator a.numerator.bits a.denominator_pos + · have hn : a.value ≤ 0 := by + (simp only [OAI.EditApproximation.BinaryFraction.value, OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hs, ↓reduceIte, Int.cast_neg, Int.cast_natCast]) + exact div_nonpos_of_nonpos_of_nonneg (neg_nonpos.mpr (Nat.cast_nonneg _)) (Nat.cast_nonneg _) + (simp only [OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork, hs, ↓reduceIte, OAI.EditApproximation.bitWordValue]) + exact (Nat.ceil_eq_zero.mpr hn).symm + have proof_representation_value_32 (a : OAI.EditApproximation.BinaryFraction) : a.representation.value = a.value := rfl + have proof_eq_of_num_den_33 {a : OAI.EditApproximation.UnreducedRational} {b : OAI.EditApproximation.UnreducedRational} (hnum : Eq.{1} a.num b.num) (hden : Eq.{1} a.den b.den) : a = b := by + cases a + cases b + cases hnum + cases hden + rfl + have proof_trimBitWordWithWork_value_6 (bits : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.trimBitWordWithWork bits).1 = OAI.EditApproximation.bitWordValue bits := by + induction bits with + | nil => rfl + | cons bit bits ih => + simp only [OAI.EditApproximation.trimBitWordWithWork] + split_ifs with h + · have ht : OAI.EditApproximation.bitWordValue bits = 0 := by rw [← ih, h.1]; rfl + simp [h.2, OAI.EditApproximation.bitWordValue, ht] + · (simp only [OAI.EditApproximation.bitWordValue, ih]) + have proof_canonicalizeWithWork_representation_34 (a : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.canonicalizeWithWork a).1.representation = a.representation := by + apply proof_eq_of_num_den_33 + · (simp only [OAI.EditApproximation.BinaryFraction.canonicalizeWithWork, OAI.EditApproximation.BinaryFraction.representation, OAI.EditApproximation.SignedBinary.value, proof_trimBitWordWithWork_value_6]) + · exact proof_trimBitWordWithWork_value_6 a.denominator + have proof_bitMulWithWork_value_0 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitMulWithWork left right).1 = OAI.EditApproximation.bitWordValue left * OAI.EditApproximation.bitWordValue right := by + induction left with + | nil => simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue] + | cons bit bits ih => + cases bit <;> simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue, proof_bitAddWithWork_value_2, ih] <;> ring + have proof_mulWithWork_value_35 (a : OAI.EditApproximation.SignedBinary) (b : OAI.EditApproximation.SignedBinary) : + (a.mulWithWork b).1.value = a.value * b.value := by + simp only [OAI.EditApproximation.SignedBinary.mulWithWork, OAI.EditApproximation.SignedBinary.value, proof_bitMulWithWork_value_0] + cases a.negative <;> cases b.negative <;> simp [OAI.EditApproximation.signedMagnitude] + have proof_mulWithWork_representation_36 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (a.mulWithWork b).1.representation = a.representation.mul b.representation := by + apply proof_eq_of_num_den_33 + · exact proof_mulWithWork_value_35 a.numerator b.numerator + · exact proof_bitMulWithWork_value_0 a.denominator b.denominator + have proof_canonicalMulWithWork_representation_37 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork a b).1.representation = a.representation.mul b.representation := by + rw [OAI.EditApproximation.BinaryFraction.canonicalMulWithWork, proof_canonicalizeWithWork_representation_34, proof_mulWithWork_representation_36] + have proof_zero_representation_38 : OAI.EditApproximation.BinaryFraction.zero.representation = OAI.EditApproximation.UnreducedRational.zero := by + apply proof_eq_of_num_den_33 <;> rfl + have proof_invWithWork_representation_39 (a : OAI.EditApproximation.BinaryFraction) : + (a.invWithWork).1.representation = a.representation.inv := by + unfold OAI.EditApproximation.BinaryFraction.invWithWork + dsimp only + split_ifs with h + · have hz : OAI.EditApproximation.bitWordValue a.numerator.bits = 0 := by + simpa only [OAI.EditApproximation.bitWordValue] using (proof_bitCompareWithWork_eq_3 a.numerator.bits []).1 h + have hv : a.numerator.value = 0 := by (simp [OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hz]) + (simp only [OAI.EditApproximation.UnreducedRational.inv, OAI.EditApproximation.BinaryFraction.representation, hv, ↓reduceDIte]) + exact proof_zero_representation_38 + · have hn : OAI.EditApproximation.bitWordValue a.numerator.bits ≠ 0 := by + intro hz + exact h ((proof_bitCompareWithWork_eq_3 a.numerator.bits []).2 (by simpa [OAI.EditApproximation.bitWordValue] using hz)) + have hv : a.numerator.value ≠ 0 := by + cases hs : a.numerator.negative <;> (simp [OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hs, hn]) + (simp only [OAI.EditApproximation.UnreducedRational.inv, OAI.EditApproximation.BinaryFraction.representation, hv, ↓reduceDIte]) + apply proof_eq_of_num_den_33 + · cases hs : a.numerator.negative <;> + simp [OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hs, Int.sign_natCast_of_ne_zero hn] + · cases hs : a.numerator.negative <;> (simp [OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hs]) + have proof_divWithWork_representation_40 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (a.divWithWork b).1.representation = a.representation.div b.representation := by + (simp only [OAI.EditApproximation.BinaryFraction.divWithWork, proof_canonicalMulWithWork_representation_37, proof_invWithWork_representation_39, + OAI.EditApproximation.UnreducedRational.div]) + have proof_value_mul_41 (a : OAI.EditApproximation.UnreducedRational) (b : OAI.EditApproximation.UnreducedRational) : (a.mul b).value = a.value * b.value := by + simp [OAI.EditApproximation.UnreducedRational.mul, OAI.EditApproximation.UnreducedRational.value, mul_div_mul_comm] + have proof_value_inv_42 (a : OAI.EditApproximation.UnreducedRational) : a.inv.value = a.value⁻¹ := by + by_cases h : a.num = 0 + · simp [OAI.EditApproximation.UnreducedRational.inv, h, OAI.EditApproximation.UnreducedRational.value, OAI.EditApproximation.UnreducedRational.zero] + · have hn : (a.num.natAbs : ℚ) ≠ 0 := by exact_mod_cast (Int.natAbs_pos.mpr h).ne' + have hd : (a.den : ℚ) ≠ 0 := by exact_mod_cast a.den_pos.ne' + have hsign : ((a.num.sign : ℤ) : ℚ) * a.num = (a.num.natAbs : ℚ) := by + simpa only [Int.cast_mul, Int.cast_natCast] using + congrArg (fun z : ℤ => (z : ℚ)) (Int.sign_mul_self_eq_natAbs a.num) + simp only [OAI.EditApproximation.UnreducedRational.inv, h, ↓reduceDIte, OAI.EditApproximation.UnreducedRational.value] + push_cast + apply eq_inv_of_mul_eq_one_left + field_simp [hn, hd] + exact hsign + have proof_value_div_43 (a : OAI.EditApproximation.UnreducedRational) (b : OAI.EditApproximation.UnreducedRational) : (a.div b).value = a.value / b.value := by + simp [proof_value_mul_41, proof_value_inv_42, OAI.EditApproximation.UnreducedRational.div, div_eq_mul_inv] + have proof_divWithWork_value_44 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.divWithWork a b).1.value = a.value / b.value := by + rw [← proof_representation_value_32, proof_divWithWork_representation_40, + proof_value_div_43, proof_representation_value_32, proof_representation_value_32] + have proof_canonicalMulWithWork_value_45 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork a b).1.value = a.value * b.value := by + rw [← proof_representation_value_32, proof_canonicalMulWithWork_representation_37, + proof_value_mul_41, proof_representation_value_32, proof_representation_value_32] + have proof_value_ofInt_46 (a : ℤ) : (OAI.EditApproximation.SignedBinary.ofInt a).value = a := by + by_cases h : a < 0 + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_true, + ↓reduceIte] using (Int.eq_neg_natAbs_of_nonpos (le_of_lt h)).symm + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_false, + Bool.false_eq_true, ↓reduceIte] using (Int.eq_natAbs_of_nonneg (le_of_not_gt h)).symm + have proof_nat_representation_47 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).representation = OAI.EditApproximation.UnreducedRational.nat n := by + apply proof_eq_of_num_den_33 + · change (OAI.EditApproximation.SignedBinary.ofInt (n : ℤ)).value = (n : ℤ) + exact proof_value_ofInt_46 _ + · rfl + have proof_value_nat_48 (n : ℕ) : (OAI.EditApproximation.UnreducedRational.nat n).value = n := by (simp [OAI.EditApproximation.UnreducedRational.nat, OAI.EditApproximation.UnreducedRational.value]) + have proof_nat_value_49 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).value = (n : ℚ) := by + rw [← proof_representation_value_32, proof_nat_representation_47, proof_value_nat_48] + have proof_groupSampleCountWithWork_value_28 (M : ℕ) (Q : ℕ) (b : ℕ) (h : OAI.EditApproximation.BinaryFraction) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.BinaryFraction.groupSampleCountWithWork M Q b h).1 = OAI.EditApproximation.groupSampleCount M Q b h.value := by + simp only [OAI.EditApproximation.BinaryFraction.groupSampleCountWithWork, proof_wordMinWithWork_value_29, proof_bitWordValue_bits_15, + proof_naturalCeilingWithWork_value_31, proof_divWithWork_value_44, proof_canonicalMulWithWork_value_45, + proof_nat_value_49, OAI.EditApproximation.groupSampleCount] + exact + let counts := OAI.EditApproximation.vectorMapWithWork T fun t => OAI.EditApproximation.BinaryFraction.groupSampleCountWithWork M Q b (scales t) + let count := fun t => OAI.EditApproximation.bitWordValue (counts.1.get t) + let heq : ∀ t, count t = OAI.EditApproximation.groupSampleCount M Q b (scales t).value := by + intro t + simp only [count, counts, proof_vectorMapWithWork_value_27, proof_groupSampleCountWithWork_value_28] + OAI.EditApproximation.vectorMapAllocation T (fun t => OAI.EditApproximation.BinaryFraction.groupSampleCountAllocation M Q b (scales t)) + + OAI.EditApproximation.BinaryFraction.groupMemberSourceAllocation scales count connection envelope values (fun t j => draw t (Fin.cast (heq t) j)) + (fun t j => allocation t (Fin.cast (heq t) j)) + + +end OAI.EditApproximation.BinaryFraction +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BinaryFraction + + +def unskippedGuardReadWithWork {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) (_center : OAI.EditApproximation.TargetInterval ny) + (b exponent : ℕ) (F : OAI.EditApproximation.BinaryFraction) (band wide : List (Fin M → OAI.EditApproximation.TargetInterval ny)) + (hne : band ≠ []) (read : Fin M → OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) : Bool × ℕ := + let envelope := OAI.EditApproximation.BinaryFraction.envelopeVectorReadWithWork b band read + let total := OAI.EditApproximation.BinaryFraction.bandMassTotalWithWork envelope.1 + let fb := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork F (OAI.EditApproximation.BinaryFraction.nat b) + let limit := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 64) fb.1 + let sumGuard := OAI.EditApproximation.BinaryFraction.leWithWork total.1 limit.1 + let rounded := OAI.EditApproximation.BinaryFraction.roundedBandReadWithWork exponent b band hne read + let wideGuard := OAI.EditApproximation.actionMemberWithWork rounded.1.get wide + let gapGuard := OAI.EditApproximation.allWithWork (fun i => + let sourceLength := OAI.EditApproximation.binaryNaturalSubtractWithWork (OAI.EditApproximation.sourceChild parent i).hi (OAI.EditApproximation.sourceChild parent i).lo + let gap := OAI.EditApproximation.BinaryFraction.stateGapWithWork (OAI.EditApproximation.bitWordValue sourceLength.1) (rounded.1.get i) + let bound := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 2) (envelope.1.get i) + let test := OAI.EditApproximation.BinaryFraction.leWithWork gap.1.absolute bound.1 + (test.1, sourceLength.2 + gap.2 + bound.2 + test.2 + 3)) (List.finRange M) + (sumGuard.1 && wideGuard.1 && gapGuard.1, + envelope.2 + total.2 + fb.2 + limit.2 + sumGuard.2 + rounded.2 + wideGuard.2 + gapGuard.2 + 5) + +def queryGroupInputsWithWork {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (b exponent Q : ℕ) (cell : ℕ × ℕ) (h : OAI.EditApproximation.BinaryFraction) + (draw : Fin (OAI.EditApproximation.groupSampleCount M Q b h.value) → Fin M × ℕ) : + List (Fin M × OAI.EditApproximation.TargetInterval ny) × ℕ := + let labels := OAI.EditApproximation.BinaryFraction.queryGroupLabelsWithWork M Q b h draw + let inputs := OAI.EditApproximation.arithmeticFlatMapWithWork (fun i => + let states := OAI.EditApproximation.BinaryFraction.queryGroupRoundedStatesWithWork (ny := ny) parent b exponent cell i h + let tagged := OAI.EditApproximation.arithmeticMapWithWork (fun r => ((i, r), 1)) states.1 + (tagged.1, states.2 + tagged.2 + 1)) labels.1 + (inputs.1, labels.2 + inputs.2 + 1) + +def coarseIndexedRootWithWork {B d : ℕ} (k q L : ℕ) + (hB : 0 < B) (hq : 0 < q) (hL : 0 < L) (x y : List ℕ) + (draws : OAI.EditApproximation.CoarseThresholdDraws B d) : OAI.EditApproximation.BinaryFraction × ℕ := by + have proof_trimBitWordWithWork_value_6 (bits : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.trimBitWordWithWork bits).1 = OAI.EditApproximation.bitWordValue bits := by + induction bits with + | nil => rfl + | cons bit bits ih => + simp only [OAI.EditApproximation.trimBitWordWithWork] + split_ifs with h + · have ht : OAI.EditApproximation.bitWordValue bits = 0 := by rw [← ih, h.1]; rfl + simp [h.2, OAI.EditApproximation.bitWordValue, ht] + · (simp only [OAI.EditApproximation.bitWordValue, ih]) + have proof_bitAdder_value_1 (a : Bool) (b : Bool) (carry : Bool) : + (OAI.EditApproximation.bitSum a b carry).toNat + 2 * (OAI.EditApproximation.bitCarry a b carry).toNat = + a.toNat + b.toNat + carry.toNat := by + cases a <;> cases b <;> cases carry <;> decide + have proof_bitAddWithWork_value_2 (left : List.{0} Bool) (right : List.{0} Bool) (carry : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitAddWithWork left right carry).1 = + OAI.EditApproximation.bitWordValue left + OAI.EditApproximation.bitWordValue right + carry.toNat := by + induction left generalizing right carry with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork] + induction right generalizing carry with + | nil => cases carry <;> simp [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue] + | cons b bs ih => + simp only [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 false b carry + simp only [Bool.toNat_false] at h + omega + | cons a as ih => + cases right with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a false carry + simp only [Bool.toNat_false] at h + omega + | cons b bs => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a b carry + omega + have proof_bitMulWithWork_value_0 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitMulWithWork left right).1 = OAI.EditApproximation.bitWordValue left * OAI.EditApproximation.bitWordValue right := by + induction left with + | nil => simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue] + | cons bit bits ih => + cases bit <;> simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue, proof_bitAddWithWork_value_2, ih] <;> ring + have proof_bitPowerWithWork_value_76 (base : List.{0} Bool) (n : ℕ) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitPowerWithWork base n).1 = OAI.EditApproximation.bitWordValue base ^ n := by + induction n with + | zero => (simp [OAI.EditApproximation.bitPowerWithWork, OAI.EditApproximation.bitWordValue]) + | succ n ih => + simp only [OAI.EditApproximation.bitPowerWithWork, proof_trimBitWordWithWork_value_6, proof_bitMulWithWork_value_0, ih, pow_succ] + have proof_coarseDenominatorWithWork_value_127 (allowanceDen : List.{0} Bool) (q : List.{0} Bool) (L : List.{0} Bool) (branching : List.{0} Bool) (D : ℕ) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.coarseDenominatorWithWork allowanceDen q L branching D).1 = + OAI.EditApproximation.coarseCommonDenominator (OAI.EditApproximation.bitWordValue allowanceDen) (OAI.EditApproximation.bitWordValue q) + (OAI.EditApproximation.bitWordValue L) (OAI.EditApproximation.bitWordValue branching) D := by + simp only [OAI.EditApproximation.coarseDenominatorWithWork, proof_trimBitWordWithWork_value_6, + proof_bitMulWithWork_value_0, proof_bitPowerWithWork_value_76, OAI.EditApproximation.coarseCommonDenominator] + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_coarseRootDenominator_value_128 (B : ℕ) (q : ℕ) (L : ℕ) (d : ℕ) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.BinaryFraction.coarseRootDenominator B q L d).1 = OAI.EditApproximation.coarseCommonDenominator 1 q L B d := by + simp only [OAI.EditApproximation.BinaryFraction.coarseRootDenominator, proof_coarseDenominatorWithWork_value_127, proof_bitWordValue_bits_15] + have proof_coarseRootDenominator_pos_126 (B : ℕ) (q : ℕ) (L : ℕ) (d : ℕ) (hB : LT.lt.{0} 0 B) (hq : LT.lt.{0} 0 q) (hL : LT.lt.{0} 0 L) : + 0 < OAI.EditApproximation.bitWordValue (OAI.EditApproximation.BinaryFraction.coarseRootDenominator B q L d).1 := by + rw [proof_coarseRootDenominator_value_128] + unfold OAI.EditApproximation.coarseCommonDenominator + positivity + exact + let den := OAI.EditApproximation.BinaryFraction.coarseRootDenominator B q L d + let denPos := proof_coarseRootDenominator_pos_126 B q L d hB hq hL + let two := OAI.EditApproximation.BinaryFraction.coarseGridNatWithWork den.1 denPos 2 + let allowance := OAI.EditApproximation.BinaryFraction.coarseGridNatWithWork den.1 denPos k + let evaluated := OAI.EditApproximation.BinaryFraction.coarseIndexedWithWork k q L (OAI.EditApproximation.coarseEntryWidth x y) x y two.1 d 0 draws allowance.1 0 + (OAI.EditApproximation.BinaryFraction.coarseBinaryRead evaluated.1 (OAI.EditApproximation.coarseRootShift k).val, + den.2 + two.2 + allowance.2 + evaluated.2 + 1) + +def queryGroupInputsAllocation {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (b exponent Q : ℕ) (cell : ℕ × ℕ) (h : OAI.EditApproximation.BinaryFraction) + (draw : Fin (OAI.EditApproximation.groupSampleCount M Q b h.value) → Fin M × ℕ) + (allocation : Fin (OAI.EditApproximation.groupSampleCount M Q b h.value) → ℕ) : ℕ := + let build := fun i : Fin M => + let states := OAI.EditApproximation.BinaryFraction.queryGroupRoundedStatesWithWork (ny := ny) parent b exponent cell i h + let tagged := OAI.EditApproximation.arithmeticMapWithWork (fun r => ((i, r), 1)) states.1 + (tagged.1, states.2 + tagged.2 + 1) + OAI.EditApproximation.BinaryFraction.queryGroupLabelsAllocation M Q b h draw allocation + OAI.EditApproximation.arithmeticFlatMapAllocation build + (fun i => OAI.EditApproximation.BinaryFraction.queryGroupRoundedStatesAllocation (ny := ny) parent b exponent cell i h + + OAI.EditApproximation.arithmeticMapAllocation (fun _ => 1) (OAI.EditApproximation.BinaryFraction.queryGroupRoundedStatesWithWork (ny := ny) parent b exponent cell i h).1) + (OAI.EditApproximation.BinaryFraction.queryGroupLabelsWithWork M Q b h draw).1 + +def unskippedGuardReadAllocation {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (_center : OAI.EditApproximation.TargetInterval ny) (b exponent : ℕ) (F : OAI.EditApproximation.BinaryFraction) + (band wide : List (Fin M → OAI.EditApproximation.TargetInterval ny)) (hne : band ≠ []) + (read : Fin M → OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) + (allocation : Fin M → OAI.EditApproximation.TargetInterval ny → ℕ) : ℕ := + let envelope := (OAI.EditApproximation.BinaryFraction.envelopeVectorReadWithWork b band read).1 + let total := (OAI.EditApproximation.BinaryFraction.bandMassTotalWithWork envelope).1 + let fb := (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork F (OAI.EditApproximation.BinaryFraction.nat b)).1 + let limit := (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 64) fb).1 + let rounded := (OAI.EditApproximation.BinaryFraction.roundedBandReadWithWork exponent b band hne read).1 + OAI.EditApproximation.BinaryFraction.envelopeVectorReadAllocation b band read allocation + OAI.EditApproximation.BinaryFraction.bandMassAllocation envelope + + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation F (OAI.EditApproximation.BinaryFraction.nat b) + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation (OAI.EditApproximation.BinaryFraction.nat 64) fb + OAI.EditApproximation.BinaryFraction.leAllocation total limit + + OAI.EditApproximation.BinaryFraction.roundedBandReadAllocation exponent b band hne read allocation + OAI.EditApproximation.actionMemberAllocation rounded.get wide + + OAI.EditApproximation.allAllocation (OAI.EditApproximation.BinaryFraction.gapGuardAllocation parent envelope rounded) (List.finRange M) + +def queryGroupInputsTransportWithWork {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (b exponent Q : ℕ) (cell : ℕ × ℕ) (word : OAI.EditApproximation.BinaryFraction) (scale : ℚ) + (hv : word.value = scale) (draw : Fin (OAI.EditApproximation.groupSampleCount M Q b scale) → Fin M × ℕ) : + List (Fin M × OAI.EditApproximation.TargetInterval ny) × ℕ := + OAI.EditApproximation.BinaryFraction.queryGroupInputsWithWork parent b exponent Q cell word + (fun sample => draw (Fin.cast (congrArg (OAI.EditApproximation.groupSampleCount M Q b) hv) sample)) + +def coarseIndexedCandidateWithWork {B d : ℕ} (q L : ℕ) + (hB : 0 < B) (hq : 0 < q) (hL : 0 < L) (x y : List ℕ) + (i : OAI.EditApproximation.CoarseGuessIndex (OAI.EditApproximation.coarseEntryWidth x y)) (draws : OAI.EditApproximation.CoarseThresholdDraws B d) : + OAI.EditApproximation.BinaryFraction × ℕ := + let k := OAI.EditApproximation.coarseGuess (OAI.EditApproximation.coarseEntryWidth x y) i + let root := OAI.EditApproximation.BinaryFraction.coarseIndexedRootWithWork k q L hB hq hL x y draws + let shifted := OAI.EditApproximation.BinaryFraction.canonicalAddWithWork root.1 (OAI.EditApproximation.BinaryFraction.nat k) + let doubled := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 2) shifted.1 + (doubled.1, root.2 + shifted.2 + doubled.2 + Nat.size k + 3) + +def preparedUnskippedReadAllocation {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (center : OAI.EditApproximation.TargetInterval ny) (b P exponent : ℕ) (tau F : OAI.EditApproximation.BinaryFraction) + (read initial : Fin M → OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) + (readAllocation initialAllocation : Fin M → OAI.EditApproximation.TargetInterval ny → ℕ) : ℕ := + let band := (OAI.EditApproximation.BinaryFraction.preparedRepresentativeReadWithWork parent center (parent.hi - parent.lo) b P + tau (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) read).1 + OAI.EditApproximation.BinaryFraction.preparedRepresentativeReadAllocation parent center (parent.hi - parent.lo) b P + tau (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) read readAllocation + + if hband : band = [] then 0 else + let wide := (OAI.EditApproximation.wideActionGridWithWork M parent center b P).1 + OAI.EditApproximation.wideActionGridAllocation M parent center b P + wide.length + + OAI.EditApproximation.BinaryFraction.unskippedGuardReadAllocation parent center b exponent F band (wide.map Vector.get) hband initial initialAllocation + + if (OAI.EditApproximation.BinaryFraction.unskippedGuardReadWithWork parent center b exponent F band (wide.map Vector.get) hband initial).1 then 3 else 0 + +def queryGroupInputsTransportAllocation {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (b exponent Q : ℕ) (cell : ℕ × ℕ) (word : OAI.EditApproximation.BinaryFraction) (scale : ℚ) + (hv : word.value = scale) (draw : Fin (OAI.EditApproximation.groupSampleCount M Q b scale) → Fin M × ℕ) + (allocation : Fin (OAI.EditApproximation.groupSampleCount M Q b scale) → ℕ) : ℕ := + OAI.EditApproximation.BinaryFraction.queryGroupInputsAllocation (ny := ny) parent b exponent Q cell word + (fun sample => draw (Fin.cast (congrArg (OAI.EditApproximation.groupSampleCount M Q b) hv) sample)) + (fun sample => allocation (Fin.cast (congrArg (OAI.EditApproximation.groupSampleCount M Q b) hv) sample)) + +def preparedUnskippedReadWithWorkRaw {nx ny M : ℕ} + (parent : OAI.EditApproximation.TargetInterval nx) (b P exponent : ℕ) (tau F : OAI.EditApproximation.BinaryFraction) + (read initial : Fin M → OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) + (center : OAI.EditApproximation.TargetInterval ny) : Option (OAI.EditApproximation.RawUnskippedBand M ny) × ℕ := + let band := OAI.EditApproximation.BinaryFraction.preparedRepresentativeReadWithWork parent center (parent.hi - parent.lo) b P + tau (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) read + if hband : band.1 = [] then (none, band.2 + 1) else + let wide := OAI.EditApproximation.wideActionGridWithWork M parent center b P + let guard := OAI.EditApproximation.BinaryFraction.unskippedGuardReadWithWork parent center b exponent F band.1 + (wide.1.map Vector.get) hband initial + if guard.1 = true then + (some ⟨center, band.1, hband⟩, band.2 + wide.2 + guard.2 + wide.1.length + 3) + else (none, band.2 + wide.2 + guard.2 + wide.1.length + 2) + +def coarseIndexedInitialWithWork {B d : ℕ} (q L N : ℕ) + (hB : 0 < B) (hq : 0 < q) (hL : 0 < L) (x y : List ℕ) + (draws : OAI.EditApproximation.CoarseGuessIndex (OAI.EditApproximation.coarseEntryWidth x y) → OAI.EditApproximation.CoarseThresholdDraws B d) : ℕ × ℕ := + let long := OAI.EditApproximation.binaryNaturalCompareWithWork (2 * x.length) y.length + if long.1 = .lt then (min N y.length, long.2 + Nat.size N + Nat.size y.length + 4) else + let equal := OAI.EditApproximation.BinaryFraction.naturalListEqualWithWork x y + if equal.1 then (0, long.2 + equal.2 + 3) else + let roots := OAI.EditApproximation.arithmeticMapWithWork (fun i => OAI.EditApproximation.BinaryFraction.coarseIndexedCandidateWithWork q L hB hq hL x y i (draws i)) + (List.finRange (Nat.clog 2 (OAI.EditApproximation.coarseEntryWidth x y) + 1)) + let smallest := OAI.EditApproximation.BinaryFraction.coarseMinimumWithWork roots.1 + let rounded := OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork smallest.1 + let result := OAI.EditApproximation.wordMinWithWork N.bits rounded.1 + (OAI.EditApproximation.bitWordValue result.1, long.2 + equal.2 + roots.2 + smallest.2 + rounded.2 + result.2 + Nat.size N + 6) + + +end OAI.EditApproximation.BinaryFraction +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BinaryFraction +variable {ny M T : ℕ} (b exponent Q : ℕ) + (initial current : Fin M → TargetInterval ny → BinaryFraction × ℕ) + (initialAllocation currentAllocation : Fin M → TargetInterval ny → ℕ) + (scales : Fin T → BinaryFraction) + (draw : ∀ t, Fin (groupSampleCount M Q b (scales t).value) → Fin M) + (drawSource : ∀ t, Fin (groupSampleCount M Q b (scales t).value) → Fin M × ℕ) + (drawAllocation : ∀ t, Fin (groupSampleCount M Q b (scales t).value) → ℕ) + +def unskippedEstimateSourceWithWorkRaw (member : (OAI.EditApproximation.RawUnskippedBand M ny)) : OAI.EditApproximation.BinaryFraction × ℕ := + let mass := OAI.EditApproximation.BinaryFraction.envelopeVectorReadWithWork b member.actions initial + let rounded := OAI.EditApproximation.BinaryFraction.roundedBandReadWithWork exponent b member.actions member.nonempty initial + let values := OAI.EditApproximation.vectorMapWithWork M fun i => current i (rounded.1.get i) + let connection := OAI.EditApproximation.BinaryFraction.endpointConnectionWithWork member.center rounded.1.get + let result := OAI.EditApproximation.BinaryFraction.countedGroupMemberSourceWithWork Q b scales connection.1 mass.1 values.1 drawSource + (result.1, mass.2 + rounded.2 + values.2 + connection.2 + result.2 + 5) + +def unskippedEstimateSourceAllocationRaw (member : (OAI.EditApproximation.RawUnskippedBand M ny)) : ℕ := + let mass := (OAI.EditApproximation.BinaryFraction.envelopeVectorReadWithWork b member.actions initial).1 + let rounded := (OAI.EditApproximation.BinaryFraction.roundedBandReadWithWork exponent b member.actions member.nonempty initial).1 + let values := (OAI.EditApproximation.vectorMapWithWork M (fun i => current i (rounded.get i))).1 + let connection := (OAI.EditApproximation.BinaryFraction.endpointConnectionWithWork member.center rounded.get).1 + OAI.EditApproximation.BinaryFraction.envelopeVectorReadAllocation b member.actions initial initialAllocation + + OAI.EditApproximation.BinaryFraction.roundedBandReadAllocation exponent b member.actions member.nonempty initial initialAllocation + + OAI.EditApproximation.vectorMapAllocation M (fun i => currentAllocation i (rounded.get i)) + + OAI.EditApproximation.BinaryFraction.endpointConnectionAllocation member.center rounded.get + OAI.EditApproximation.BinaryFraction.countedGroupMemberSourceAllocation Q b scales connection mass values drawSource drawAllocation + +def chooseUnskippedSourceWithWorkRaw (members : List (OAI.EditApproximation.RawUnskippedBand M ny)) (hne : members ≠ []) : (OAI.EditApproximation.RawUnskippedBand M ny) × ℕ := + OAI.EditApproximation.BinaryFraction.selectGroupWithWork members hne + (OAI.EditApproximation.BinaryFraction.unskippedEstimateSourceWithWorkRaw b exponent Q initial current scales drawSource) + +def chooseUnskippedSourceAllocationRaw (members : List (OAI.EditApproximation.RawUnskippedBand M ny)) : ℕ := + OAI.EditApproximation.BinaryFraction.selectGroupAllocation members + (OAI.EditApproximation.BinaryFraction.unskippedEstimateSourceWithWorkRaw b exponent Q initial current scales drawSource) + (OAI.EditApproximation.BinaryFraction.unskippedEstimateSourceAllocationRaw b exponent Q initial current + initialAllocation currentAllocation scales drawSource drawAllocation) + +def sampledGroupActionSourceWithWorkRaw (members : List (OAI.EditApproximation.RawUnskippedBand M ny)) (hne : members ≠ []) : + OAI.EditApproximation.BinaryBellmanAction (OAI.EditApproximation.TargetInterval ny) (Fin M × OAI.EditApproximation.TargetInterval ny) M × ℕ := + let selected := OAI.EditApproximation.BinaryFraction.chooseUnskippedSourceWithWorkRaw b exponent Q initial current scales drawSource members hne + let rounded := OAI.EditApproximation.BinaryFraction.roundedBandReadWithWork exponent b selected.1.actions selected.1.nonempty initial + let result := OAI.EditApproximation.BinaryFraction.endpointActionWithWork selected.1.center rounded.1.get + (result.1, selected.2 + rounded.2 + result.2 + 3) + +def sampledGroupActionSourceAllocationRaw (members : List (OAI.EditApproximation.RawUnskippedBand M ny)) (hne : members ≠ []) : ℕ := + let selected := (OAI.EditApproximation.BinaryFraction.chooseUnskippedSourceWithWorkRaw b exponent Q initial current + scales drawSource members hne).1 + let rounded := (OAI.EditApproximation.BinaryFraction.roundedBandReadWithWork exponent b selected.actions selected.nonempty initial).1 + OAI.EditApproximation.BinaryFraction.chooseUnskippedSourceAllocationRaw b exponent Q initial current + initialAllocation currentAllocation scales drawSource drawAllocation members + + OAI.EditApproximation.BinaryFraction.roundedBandReadAllocation exponent b selected.actions selected.nonempty initial initialAllocation + + OAI.EditApproximation.BinaryFraction.endpointActionAllocation selected.center rounded.get + + +end OAI.EditApproximation.BinaryFraction +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BinaryFraction + +open Finset + +def preparedOnlineReadWithWorkRaw {α : Type u_1} (source target : List α) {M : ℕ} + (parent : OAI.EditApproximation.TargetInterval source.length) (P F exponent H b : ℕ) (_hb : 0 < b) (_hP : 0 < P) + (tau eta kappa : OAI.EditApproximation.BinaryFraction) + (child initial : Fin M → OAI.EditApproximation.TargetInterval target.length → OAI.EditApproximation.BinaryFraction × ℕ) + (table : ℕ → Fin M × OAI.EditApproximation.TargetInterval target.length → OAI.EditApproximation.BinaryFraction × ℕ) + (R : ℕ) (_hc : ∀ i q, (child i q).2 ≤ R) (_hi : ∀ i q, (initial i q).2 ≤ R) + (t : ℕ) (center : OAI.EditApproximation.TargetInterval target.length) (integer : ℕ) : + Option (OAI.EditApproximation.BinaryBellmanAction (OAI.EditApproximation.TargetInterval target.length) + (Fin M × OAI.EditApproximation.TargetInterval target.length) M) × ℕ := by + have proof_arithmeticFlatMapWithWork_value_69 {α : Type 0} {β : Type 0} (f : α → Prod.{0, 0} (List.{0} β) ℕ) (values : List.{0} α) : + (OAI.EditApproximation.arithmeticFlatMapWithWork f values).1 = values.flatMap (fun a => (f a).1) := by + induction values with + | nil => rfl + | cons a rest ih => simp only [OAI.EditApproximation.arithmeticFlatMapWithWork, ih, List.flatMap_cons] + have proof_arithmeticMapWithWork_value_70 {α : Type 0} {β : Type 0} (f : α → Prod.{0, 0} β ℕ) (values : List.{0} α) : + (OAI.EditApproximation.arithmeticMapWithWork f values).1 = values.map (fun a => (f a).1) := by + induction values with + | nil => rfl + | cons a rest ih => simp only [OAI.EditApproximation.arithmeticMapWithWork, ih, List.map_cons] + have proof_memberByWithWork_value_71 {α : Type 0} (equal : α → α → Prod.{0, 0} Bool ℕ) (heq : ∀ (a b : α), Eq.{1} (equal a b).1 Bool.true ↔ Eq.{0 + 1} a b) (a : α) (xs : List.{0} α) : + (OAI.EditApproximation.memberByWithWork equal a xs).1 = true ↔ a ∈ xs := by + induction xs with + | nil => simp only [OAI.EditApproximation.memberByWithWork, Bool.false_eq_true, List.not_mem_nil] + | cons b xs ih => simp only [OAI.EditApproximation.memberByWithWork, Bool.or_eq_true, heq, ih, List.mem_cons] + have proof_dedupByWithWork_value_72 {α : Type 0} [instLocal1 : DecidableEq.{0 + 1} α] (equal : α → α → Prod.{0, 0} Bool ℕ) (heq : ∀ (a b : α), Eq.{1} (equal a b).1 Bool.true ↔ Eq.{0 + 1} a b) (xs : List.{0} α) : + (OAI.EditApproximation.dedupByWithWork equal xs).1 = xs.dedup := by + induction xs with + | nil => rfl + | cons a rest ih => + have hm := proof_memberByWithWork_value_71 equal heq a rest + have ht : (OAI.EditApproximation.memberByWithWork equal a rest).1 = decide (a ∈ rest) := + Bool.eq_iff_iff.mpr (by simpa only [decide_eq_true_eq] using hm) + simp only [OAI.EditApproximation.dedupByWithWork, ht, ih, List.dedup_cons, decide_eq_true_eq] + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_eq_3 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .eq ↔ OAI.EditApproximation.bitWordValue left = OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_binaryNaturalCompareWithWork_eq_73 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.binaryNaturalCompareWithWork a b).1 = .eq ↔ a = b := by + simpa only [OAI.EditApproximation.binaryNaturalCompareWithWork, proof_bitWordValue_bits_15] using proof_bitCompareWithWork_eq_3 a.bits b.bits + have proof_naturalEqualWithWork_value_74 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.naturalEqualWithWork a b).1 = true ↔ a = b := by + simp only [OAI.EditApproximation.naturalEqualWithWork, decide_eq_true_eq, proof_binaryNaturalCompareWithWork_eq_73] + have proof_coordinateEqualWithWork_value_75 {M : ℕ} {n : ℕ} (a : Prod.{0, 0} (Fin M) (OAI.EditApproximation.TargetInterval n)) (b : Prod.{0, 0} (Fin M) (OAI.EditApproximation.TargetInterval n)) : + (OAI.EditApproximation.coordinateEqualWithWork a b).1 = true ↔ a = b := by + simp only [OAI.EditApproximation.coordinateEqualWithWork, Bool.and_eq_true, proof_naturalEqualWithWork_value_74] + constructor + · rintro ⟨⟨hc, hl⟩, hh⟩ + have hi : a.1 = b.1 := Fin.ext hc + have hq : a.2 = b.2 := by + rcases a with ⟨i, q⟩ + rcases b with ⟨j, r⟩ + cases q + cases r + cases hl + cases hh + rfl + exact Prod.ext hi hq + · intro h + subst b + exact ⟨⟨rfl, rfl⟩, rfl⟩ + have proof_bandCoordinatesWithWork_value_68 {M : ℕ} {n : ℕ} (band : List.{0} (Fin M → OAI.EditApproximation.TargetInterval n)) : + (OAI.EditApproximation.BinaryFraction.bandCoordinatesWithWork band).1 = OAI.EditApproximation.listedBandCoordinates band := by + simp only [OAI.EditApproximation.BinaryFraction.bandCoordinatesWithWork, proof_dedupByWithWork_value_72 _ proof_coordinateEqualWithWork_value_75, + proof_arithmeticFlatMapWithWork_value_69, proof_arithmeticMapWithWork_value_70, OAI.EditApproximation.listedBandCoordinates, + List.ofFn_eq_map] + have proof_bitAdder_value_1 (a : Bool) (b : Bool) (carry : Bool) : + (OAI.EditApproximation.bitSum a b carry).toNat + 2 * (OAI.EditApproximation.bitCarry a b carry).toNat = + a.toNat + b.toNat + carry.toNat := by + cases a <;> cases b <;> cases carry <;> decide + have proof_bitAddWithWork_value_2 (left : List.{0} Bool) (right : List.{0} Bool) (carry : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitAddWithWork left right carry).1 = + OAI.EditApproximation.bitWordValue left + OAI.EditApproximation.bitWordValue right + carry.toNat := by + induction left generalizing right carry with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork] + induction right generalizing carry with + | nil => cases carry <;> simp [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue] + | cons b bs ih => + simp only [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 false b carry + simp only [Bool.toNat_false] at h + omega + | cons a as ih => + cases right with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a false carry + simp only [Bool.toNat_false] at h + omega + | cons b bs => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a b carry + omega + have proof_binaryNaturalAddWithWork_value_52 (a : ℕ) (b : ℕ) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalAddWithWork a b).1 = a + b := by + simp [OAI.EditApproximation.binaryNaturalAddWithWork, proof_bitAddWithWork_value_2, proof_bitWordValue_bits_15] + have proof_onlineIndexSetupWithWork_value_129 {M : ℕ} {n : ℕ} (H : ℕ) (band : List.{0} (Fin M → OAI.EditApproximation.TargetInterval n)) : + (OAI.EditApproximation.BinaryFraction.onlineIndexSetupWithWork H band).1 = H + (OAI.EditApproximation.listedBandCoordinates band).length + 2 := by + simp only [OAI.EditApproximation.BinaryFraction.onlineIndexSetupWithWork, proof_binaryNaturalAddWithWork_value_52, proof_bandCoordinatesWithWork_value_68] + exact + let band := OAI.EditApproximation.BinaryFraction.preparedRepresentativeReadWithWork parent center (parent.hi - parent.lo) b P + tau (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) child + let setup := OAI.EditApproximation.BinaryFraction.onlineIndexSetupWithWork H band.1 + let G := setup.1 + let accepted := OAI.EditApproximation.BinaryFraction.reduceOnlineIntegerWithWork (G ^ 80) (by + dsimp only [G, setup] + rw [proof_onlineIndexSetupWithWork_value_129] + positivity) integer + if hband : band.1 = [] then (none, band.2 + setup.2 + accepted.2 + 1) else + let guard := OAI.EditApproximation.BinaryFraction.preparedUnskippedReadWithWorkRaw parent b P exponent tau (OAI.EditApproximation.BinaryFraction.nat F) child initial center + if guard.1.isSome then + let sampled := OAI.EditApproximation.BinaryFraction.countedSampledOnlineReadWithWork center b initial table eta kappa band.1 hband + G (G ^ 80) t accepted.1 + (some sampled.1, band.2 + setup.2 + accepted.2 + guard.2 + sampled.2 + 2) + else (none, band.2 + setup.2 + accepted.2 + guard.2 + 1) + +def preparedOnlineReadAllocationRaw {α : Type u_1} (source target : List α) {M : ℕ} + (parent : OAI.EditApproximation.TargetInterval source.length) (P F exponent H b : ℕ) (_hb : 0 < b) (_hP : 0 < P) + (tau eta kappa : OAI.EditApproximation.BinaryFraction) + (child initial : Fin M → OAI.EditApproximation.TargetInterval target.length → OAI.EditApproximation.BinaryFraction × ℕ) + (table : ℕ → Fin M × OAI.EditApproximation.TargetInterval target.length → OAI.EditApproximation.BinaryFraction × ℕ) + (R : ℕ) (_hc : ∀ i q, (child i q).2 ≤ R) (_hi : ∀ i q, (initial i q).2 ≤ R) + (childAllocation initialAllocation : Fin M → OAI.EditApproximation.TargetInterval target.length → ℕ) + (tableAllocation : ℕ → Fin M × OAI.EditApproximation.TargetInterval target.length → ℕ) + + + (t : ℕ) (center : OAI.EditApproximation.TargetInterval target.length) (integer : ℕ) : ℕ := by + have proof_arithmeticFlatMapWithWork_value_69 {α : Type 0} {β : Type 0} (f : α → Prod.{0, 0} (List.{0} β) ℕ) (values : List.{0} α) : + (OAI.EditApproximation.arithmeticFlatMapWithWork f values).1 = values.flatMap (fun a => (f a).1) := by + induction values with + | nil => rfl + | cons a rest ih => simp only [OAI.EditApproximation.arithmeticFlatMapWithWork, ih, List.flatMap_cons] + have proof_arithmeticMapWithWork_value_70 {α : Type 0} {β : Type 0} (f : α → Prod.{0, 0} β ℕ) (values : List.{0} α) : + (OAI.EditApproximation.arithmeticMapWithWork f values).1 = values.map (fun a => (f a).1) := by + induction values with + | nil => rfl + | cons a rest ih => simp only [OAI.EditApproximation.arithmeticMapWithWork, ih, List.map_cons] + have proof_memberByWithWork_value_71 {α : Type 0} (equal : α → α → Prod.{0, 0} Bool ℕ) (heq : ∀ (a b : α), Eq.{1} (equal a b).1 Bool.true ↔ Eq.{0 + 1} a b) (a : α) (xs : List.{0} α) : + (OAI.EditApproximation.memberByWithWork equal a xs).1 = true ↔ a ∈ xs := by + induction xs with + | nil => simp only [OAI.EditApproximation.memberByWithWork, Bool.false_eq_true, List.not_mem_nil] + | cons b xs ih => simp only [OAI.EditApproximation.memberByWithWork, Bool.or_eq_true, heq, ih, List.mem_cons] + have proof_dedupByWithWork_value_72 {α : Type 0} [instLocal1 : DecidableEq.{0 + 1} α] (equal : α → α → Prod.{0, 0} Bool ℕ) (heq : ∀ (a b : α), Eq.{1} (equal a b).1 Bool.true ↔ Eq.{0 + 1} a b) (xs : List.{0} α) : + (OAI.EditApproximation.dedupByWithWork equal xs).1 = xs.dedup := by + induction xs with + | nil => rfl + | cons a rest ih => + have hm := proof_memberByWithWork_value_71 equal heq a rest + have ht : (OAI.EditApproximation.memberByWithWork equal a rest).1 = decide (a ∈ rest) := + Bool.eq_iff_iff.mpr (by simpa only [decide_eq_true_eq] using hm) + simp only [OAI.EditApproximation.dedupByWithWork, ht, ih, List.dedup_cons, decide_eq_true_eq] + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_eq_3 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .eq ↔ OAI.EditApproximation.bitWordValue left = OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_binaryNaturalCompareWithWork_eq_73 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.binaryNaturalCompareWithWork a b).1 = .eq ↔ a = b := by + simpa only [OAI.EditApproximation.binaryNaturalCompareWithWork, proof_bitWordValue_bits_15] using proof_bitCompareWithWork_eq_3 a.bits b.bits + have proof_naturalEqualWithWork_value_74 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.naturalEqualWithWork a b).1 = true ↔ a = b := by + simp only [OAI.EditApproximation.naturalEqualWithWork, decide_eq_true_eq, proof_binaryNaturalCompareWithWork_eq_73] + have proof_coordinateEqualWithWork_value_75 {M : ℕ} {n : ℕ} (a : Prod.{0, 0} (Fin M) (OAI.EditApproximation.TargetInterval n)) (b : Prod.{0, 0} (Fin M) (OAI.EditApproximation.TargetInterval n)) : + (OAI.EditApproximation.coordinateEqualWithWork a b).1 = true ↔ a = b := by + simp only [OAI.EditApproximation.coordinateEqualWithWork, Bool.and_eq_true, proof_naturalEqualWithWork_value_74] + constructor + · rintro ⟨⟨hc, hl⟩, hh⟩ + have hi : a.1 = b.1 := Fin.ext hc + have hq : a.2 = b.2 := by + rcases a with ⟨i, q⟩ + rcases b with ⟨j, r⟩ + cases q + cases r + cases hl + cases hh + rfl + exact Prod.ext hi hq + · intro h + subst b + exact ⟨⟨rfl, rfl⟩, rfl⟩ + have proof_bandCoordinatesWithWork_value_68 {M : ℕ} {n : ℕ} (band : List.{0} (Fin M → OAI.EditApproximation.TargetInterval n)) : + (OAI.EditApproximation.BinaryFraction.bandCoordinatesWithWork band).1 = OAI.EditApproximation.listedBandCoordinates band := by + simp only [OAI.EditApproximation.BinaryFraction.bandCoordinatesWithWork, proof_dedupByWithWork_value_72 _ proof_coordinateEqualWithWork_value_75, + proof_arithmeticFlatMapWithWork_value_69, proof_arithmeticMapWithWork_value_70, OAI.EditApproximation.listedBandCoordinates, + List.ofFn_eq_map] + have proof_bitAdder_value_1 (a : Bool) (b : Bool) (carry : Bool) : + (OAI.EditApproximation.bitSum a b carry).toNat + 2 * (OAI.EditApproximation.bitCarry a b carry).toNat = + a.toNat + b.toNat + carry.toNat := by + cases a <;> cases b <;> cases carry <;> decide + have proof_bitAddWithWork_value_2 (left : List.{0} Bool) (right : List.{0} Bool) (carry : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitAddWithWork left right carry).1 = + OAI.EditApproximation.bitWordValue left + OAI.EditApproximation.bitWordValue right + carry.toNat := by + induction left generalizing right carry with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork] + induction right generalizing carry with + | nil => cases carry <;> simp [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue] + | cons b bs ih => + simp only [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 false b carry + simp only [Bool.toNat_false] at h + omega + | cons a as ih => + cases right with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a false carry + simp only [Bool.toNat_false] at h + omega + | cons b bs => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a b carry + omega + have proof_binaryNaturalAddWithWork_value_52 (a : ℕ) (b : ℕ) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalAddWithWork a b).1 = a + b := by + simp [OAI.EditApproximation.binaryNaturalAddWithWork, proof_bitAddWithWork_value_2, proof_bitWordValue_bits_15] + have proof_onlineIndexSetupWithWork_value_129 {M : ℕ} {n : ℕ} (H : ℕ) (band : List.{0} (Fin M → OAI.EditApproximation.TargetInterval n)) : + (OAI.EditApproximation.BinaryFraction.onlineIndexSetupWithWork H band).1 = H + (OAI.EditApproximation.listedBandCoordinates band).length + 2 := by + simp only [OAI.EditApproximation.BinaryFraction.onlineIndexSetupWithWork, proof_binaryNaturalAddWithWork_value_52, proof_bandCoordinatesWithWork_value_68] + exact + let band := (OAI.EditApproximation.BinaryFraction.preparedRepresentativeReadWithWork parent center (parent.hi - parent.lo) b P + tau (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) child).1 + let G := (OAI.EditApproximation.BinaryFraction.onlineIndexSetupWithWork H band).1 + let accepted := (OAI.EditApproximation.BinaryFraction.reduceOnlineIntegerWithWork (G ^ 80) (by + dsimp only [G]; rw [proof_onlineIndexSetupWithWork_value_129]; positivity) integer).1 + OAI.EditApproximation.BinaryFraction.preparedRepresentativeReadAllocation parent center (parent.hi - parent.lo) b P + tau (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) child childAllocation + + OAI.EditApproximation.BinaryFraction.onlineIndexSetupAllocation H band + OAI.EditApproximation.reduceOnlineIntegerAllocation (G ^ 80) integer + + if hband : band = [] then 0 else + OAI.EditApproximation.BinaryFraction.preparedUnskippedReadAllocation parent center b P exponent tau (OAI.EditApproximation.BinaryFraction.nat F) + child initial childAllocation initialAllocation + + if (OAI.EditApproximation.BinaryFraction.preparedUnskippedReadWithWorkRaw parent b P exponent tau (OAI.EditApproximation.BinaryFraction.nat F) child initial center).1.isSome then + OAI.EditApproximation.BinaryFraction.countedSampledOnlineAllocation center b initial initialAllocation table tableAllocation eta kappa + band hband G (G ^ 80) t accepted + 1 + else 0 + + +end OAI.EditApproximation.BinaryFraction +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditDistortion + + +inductive Step (substitutions : Bool) {Alpha : Type u} : List Alpha → List Alpha → Prop + | insert (p q : List Alpha) (a : Alpha) : Step substitutions (p ++ q) (p ++ a :: q) + | delete (p q : List Alpha) (a : Alpha) : Step substitutions (p ++ a :: q) (p ++ q) + | substitute (h : substitutions = true) (p q : List Alpha) (a b : Alpha) : + Step substitutions (p ++ a :: q) (p ++ b :: q) + +inductive Script (substitutions : Bool) {Alpha : Type u} : ℕ → List Alpha → List Alpha → Prop + | nil (x : List Alpha) : Script substitutions 0 x x + | cons {n : ℕ} {x y z : List Alpha} (first : OAI.EditDistortion.Step substitutions x y) + (rest : Script substitutions n y z) : Script substitutions (n + 1) x z + +noncomputable def edit {Alpha : Type u} (x y : List Alpha) : ℕ := + sInf {n | Script true n x y} + + +end OAI.EditDistortion +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditDistortion +variable {Alpha : Type u} {s : Bool} + +noncomputable def cost (s : Bool) (x y : List Alpha) : ℕ := sInf {n | Script s n x y} + + +end OAI.EditDistortion +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.CoarseSourceTree +open Finset EditDistortion + +def word {B : ℕ} {α : Type u} : {D : ℕ} → OAI.EditApproximation.CoarseSourceTree B α D → List α + | _, .leaf letter => letter.toList + | _, .branch children => (List.ofFn fun i => word (children i)).flatten + + +end OAI.EditApproximation.CoarseSourceTree +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation + + +def coarseLabelCount {B : ℕ} {α : Type u_1} (Q lam : ℚ) : + {d : ℕ} → OAI.EditApproximation.CoarseSourceTree B α d → OAI.EditApproximation.CoarseThresholdDraws B d → ℚ → ℕ + | _, tree, draws, allowance => + if (tree.word.length : ℚ) ≤ allowance then 0 else + match tree, draws with + | .leaf _, _ => 0 + | .branch children, (draws, below) => B + + OAI.EditApproximation.coarseLabelChildren Q lam allowance (fun child => coarseLabelCount Q lam child) + (List.ofFn fun i => (children i, draws i, below i)) + +def coarseIndexedEntryBinaryCost (N B d : ℕ) [NeZero B] (x y : List ℕ) + (draws : OAI.EditApproximation.CoarseGuessIndex (OAI.EditApproximation.coarseEntryWidth x y) → OAI.EditApproximation.CoarseThresholdDraws B d) : ℕ := + (OAI.EditApproximation.BinaryFraction.coarseIndexedInitialWithWork (OAI.EditApproximation.inputHeight N ^ 4) (64 * OAI.EditApproximation.inputHeight N) N + (Nat.pos_of_neZero B) (pow_pos (Nat.two_pow_pos _) _) + (Nat.mul_pos (by decide) (Nat.two_pow_pos _)) x y draws).2 + +def coarseInitialLabelCount {α : Type u_1} [DecidableEq α] + (B d : ℕ) (Q lam : ℚ) (x y : List α) + (draws : OAI.EditApproximation.CoarseGuessIndex (OAI.EditApproximation.coarseEntryWidth x y) → OAI.EditApproximation.CoarseThresholdDraws B d) : ℕ := + if 2 * x.length < y.length then 0 + else if x = y then 0 + else ∑ i, OAI.EditApproximation.coarseLabelCount Q lam (OAI.EditApproximation.coarseEntryTree B d x y) (draws i) + (OAI.EditApproximation.coarseGuess (OAI.EditApproximation.coarseEntryWidth x y) i) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open Finset EditDistortion + +def coarseChildrenCost {B D : ℕ} {α : Type u} (k : ℕ) + (value : OAI.EditApproximation.CoarseSourceTree B α D → ℕ → Fin (2 * k + 1) → ℕ) : + List (OAI.EditApproximation.CoarseSourceTree B α D) → ℕ → Fin (2 * k + 1) → ℕ + | [], _, _ => 0 + | child :: rest, start, shift => + univ.inf' univ_nonempty (fun next => value child start next + 2 * Nat.dist shift.val next.val) + + coarseChildrenCost k value rest (start + child.word.length) shift + +def coarseShiftCost {B : ℕ} {α : Type u} [DecidableEq α] (k : ℕ) (frame : List (Option α)) : + {D : ℕ} → OAI.EditApproximation.CoarseSourceTree B α D → ℕ → Fin (2 * k + 1) → ℕ + | _, .leaf none, _, _ => 0 + | _, .leaf (some letter), start, shift => + if (frame[start + shift.val]?.getD none) = some letter then 0 else 1 + | _, .branch children, start, shift => + OAI.EditApproximation.coarseChildrenCost k (fun child => coarseShiftCost k frame child) + (List.ofFn children) start shift + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open Finset +open EditDistortion + +instance targetIntervalFintype (n : ℕ) : Fintype (OAI.EditApproximation.TargetInterval n) := by + have proof_targetStates_complete_12 (n : ℕ) (q : OAI.EditApproximation.TargetInterval n) : q ∈ OAI.EditApproximation.targetStates n := by + apply List.mem_flatMap.mpr + refine ⟨q.lo, List.mem_range.mpr (Nat.lt_succ_of_le (q.ordered.trans q.valid)), ?_⟩ + apply List.mem_filterMap.mpr + refine ⟨q.hi, List.mem_range.mpr (Nat.lt_succ_of_le q.valid), ?_⟩ + rw [OAI.EditApproximation.makeTargetState, dite_eq_left (show q.lo ≤ q.hi ∧ q.hi ≤ n from ⟨q.ordered, q.valid⟩)] + exact + Fintype.ofList (OAI.EditApproximation.targetStates n) (proof_targetStates_complete_12 n) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.UnskippedBand +open Finset + +def actions {α : Type u_1} {source target : List α} {M : ℕ} + {parent : OAI.EditApproximation.TargetInterval source.length} {b P thetaExponent : ℕ} + {tau F : ℚ} {child initial : Fin M → OAI.EditApproximation.TargetInterval target.length → ℚ} + (member : OAI.EditApproximation.UnskippedBand source target parent b P thetaExponent tau F child initial) := + OAI.EditApproximation.representativeBandActions source target parent member.center b P tau + ((2 : ℚ) ^ (-(thetaExponent : ℤ))) child + +def envelope {α : Type u_1} {source target : List α} {M : ℕ} + {parent : OAI.EditApproximation.TargetInterval source.length} {b P thetaExponent : ℕ} + {tau F : ℚ} {child initial : Fin M → OAI.EditApproximation.TargetInterval target.length → ℚ} + (member : OAI.EditApproximation.UnskippedBand source target parent b P thetaExponent tau F child initial) (i : Fin M) : ℚ := + OAI.EditApproximation.bandChildEnvelope b member.actions initial i + +def rounded {α : Type u_1} {source target : List α} {M : ℕ} + {parent : OAI.EditApproximation.TargetInterval source.length} {b P thetaExponent : ℕ} + {tau F : ℚ} {child initial : Fin M → OAI.EditApproximation.TargetInterval target.length → ℚ} + (member : OAI.EditApproximation.UnskippedBand source target parent b P thetaExponent tau F child initial) : + Fin M → OAI.EditApproximation.TargetInterval target.length := + OAI.EditApproximation.canonicalRoundedBandAction thetaExponent b member.actions member.nonempty initial + +def rationalAction {α : Type u_1} {source target : List α} {M b P thetaExponent : ℕ} + {parent : OAI.EditApproximation.TargetInterval source.length} {tau F : ℚ} + {child initial : Fin M → OAI.EditApproximation.TargetInterval target.length → ℚ} + (member : OAI.EditApproximation.UnskippedBand source target parent b P thetaExponent tau F child initial) : + OAI.EditApproximation.RationalBellmanAction (OAI.EditApproximation.TargetInterval target.length) (Fin M × OAI.EditApproximation.TargetInterval target.length) M := + ⟨member.center, OAI.EditApproximation.endpointActionConnection member.center member.rounded, fun i => (i, member.rounded i)⟩ + + +end OAI.EditApproximation.UnskippedBand +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open Finset MeasureTheory ProbabilityTheory +variable {α : Type u_1} {source target : List α} {M b P thetaExponent : ℕ} {parent : TargetInterval source.length} {tau F : ℚ} {child initial : Fin M → TargetInterval target.length → ℚ} + +def unskippedGroupEstimate {T : ℕ} (scales : Fin T → ℚ) (count : Fin T → ℕ) + (value : Fin M → OAI.EditApproximation.TargetInterval target.length → ℚ) + (member : OAI.EditApproximation.UnskippedBand source target parent b P thetaExponent tau F child initial) + (draw : ∀ scale : Fin T, Fin (count scale) → Fin M) : ℚ := + OAI.EditApproximation.groupMemberEstimate scales count (OAI.EditApproximation.endpointActionConnection member.center member.rounded) + member.envelope (fun i => value i (member.rounded i)) draw + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open Finset MeasureTheory ProbabilityTheory +variable {α : Type*} {source target : List α} {M b P thetaExponent : ℕ} {parent : TargetInterval source.length} {tau F : ℚ} {child initial : Fin M → TargetInterval target.length → ℚ} + +def groupDyadicScaleAt (M b : ℕ) (F : ℚ) (i : Fin (OAI.EditApproximation.groupDyadicScales M b F).length) : ℚ := + (OAI.EditApproximation.groupDyadicScales M b F).get i + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation + + +abbrev CellGroupDraws (M F Q : ℕ) := ∀ b : ℕ, (ℕ × ℕ) → + ∀ scale : Fin (OAI.EditApproximation.groupDyadicScales M b F).length, + Fin (OAI.EditApproximation.groupSampleCount M Q b (OAI.EditApproximation.groupDyadicScaleAt M b F scale)) → Fin M + +abbrev cellScaleReadDraw (M b Q : ℕ) (F : ℚ) := + ∀ (t : Fin (OAI.EditApproximation.groupDyadicScales M b F).length), + Fin (OAI.EditApproximation.groupSampleCount M Q b (OAI.EditApproximation.groupDyadicScaleAt M b F t)) → Fin M × ℕ + +abbrev GroupScalarKey (M F Q : ℕ) := + Σ key : ℕ × (ℕ × ℕ), Σ scale : Fin (OAI.EditApproximation.groupDyadicScales M key.1 F).length, + Fin (OAI.EditApproximation.groupSampleCount M Q key.1 (OAI.EditApproximation.groupDyadicScaleAt M key.1 F scale)) + +abbrev CountedCellGroupDraws (M F Q : ℕ) := + ∀ b : ℕ, ∀ _cell : ℕ × ℕ, ∀ scale : Fin (OAI.EditApproximation.groupDyadicScales M b F).length, + Fin (OAI.EditApproximation.groupSampleCount M Q b (OAI.EditApproximation.groupDyadicScaleAt M b F scale)) → Fin M × ℕ + +abbrev CellGroupSourceAllocations (M F Q : ℕ) := ∀ (b : ℕ) (_cell : ℕ × ℕ), + ∀ t : Fin (OAI.EditApproximation.groupDyadicScales M b F).length, + Fin (OAI.EditApproximation.groupSampleCount M Q b (OAI.EditApproximation.groupDyadicScaleAt M b F t)) → ℕ + +abbrev CountedCellGroupAllocations (M F Q : ℕ) := + ∀ b : ℕ, ∀ _cell : ℕ × ℕ, ∀ scale : Fin (OAI.EditApproximation.groupDyadicScales M b F).length, + Fin (OAI.EditApproximation.groupSampleCount M Q b (OAI.EditApproximation.groupDyadicScaleAt M b F scale)) → ℕ + +abbrev CellGroupReadDraws (M F Q : ℕ) := ∀ (b : ℕ) (_cell : ℕ × ℕ), + OAI.EditApproximation.cellScaleReadDraw M b Q F + +def groupScalarKeys (M F Q : ℕ) (groups : List (ℕ × (ℕ × ℕ))) : List (OAI.EditApproximation.GroupScalarKey M F Q) := + groups.flatMap fun (key : ℕ × (ℕ × ℕ)) => + (List.finRange (OAI.EditApproximation.groupDyadicScales M key.1 F).length).flatMap + fun (scale : Fin (OAI.EditApproximation.groupDyadicScales M key.1 F).length) => + (List.finRange (OAI.EditApproximation.groupSampleCount M Q key.1 (OAI.EditApproximation.groupDyadicScaleAt M key.1 F scale))).map + fun sample => Sigma.mk key (Sigma.mk scale sample) + +noncomputable def groupDrawFromValues {M F Q : ℕ} [NeZero M] + (keys : List (OAI.EditApproximation.GroupScalarKey M F Q)) (values : List ℚ) : OAI.EditApproximation.CellGroupDraws M F Q := by + classical + exact fun b cell scale sample => Fin.ofNat M ⌊OAI.EditApproximation.finiteAnswerTable keys values ⟨(b, cell), scale, sample⟩⌋₊ + +def queryGroupKeyEqualWithWork {M F Q : ℕ} (a b : OAI.EditApproximation.GroupScalarKey M F Q) : Bool × ℕ := + let scale := OAI.EditApproximation.naturalEqualWithWork a.1.1 b.1.1 + let lo := OAI.EditApproximation.naturalEqualWithWork a.1.2.1 b.1.2.1 + let hi := OAI.EditApproximation.naturalEqualWithWork a.1.2.2 b.1.2.2 + let label := OAI.EditApproximation.naturalEqualWithWork a.2.1.val b.2.1.val + let sample := OAI.EditApproximation.naturalEqualWithWork a.2.2.val b.2.2.val + (scale.1 && lo.1 && hi.1 && label.1 && sample.1, + scale.2 + lo.2 + hi.2 + label.2 + sample.2 + 4) + +def queryGroupKeyEqualAllocation {M F Q : ℕ} (a b : OAI.EditApproximation.GroupScalarKey M F Q) : ℕ := + OAI.EditApproximation.naturalEqualAllocation a.1.1 b.1.1 + OAI.EditApproximation.naturalEqualAllocation a.1.2.1 b.1.2.1 + + OAI.EditApproximation.naturalEqualAllocation a.1.2.2 b.1.2.2 + OAI.EditApproximation.naturalEqualAllocation a.2.1.val b.2.1.val + + OAI.EditApproximation.naturalEqualAllocation a.2.2.val b.2.2.val + 4 + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BinaryFraction + +open Finset + +def queryGroupKeySamplesWithWork (M F Q eM eb eF : ℕ) + (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (cell : ℕ × ℕ) : + List (OAI.EditApproximation.GroupScalarKey M F Q) × ℕ := by + have proof_representation_value_32 (a : OAI.EditApproximation.BinaryFraction) : a.representation.value = a.value := rfl + have proof_eq_of_num_den_33 {a : OAI.EditApproximation.UnreducedRational} {b : OAI.EditApproximation.UnreducedRational} (hnum : Eq.{1} a.num b.num) (hden : Eq.{1} a.den b.den) : a = b := by + cases a + cases b + cases hnum + cases hden + rfl + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_value_ofInt_46 (a : ℤ) : (OAI.EditApproximation.SignedBinary.ofInt a).value = a := by + by_cases h : a < 0 + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_true, + ↓reduceIte] using (Int.eq_neg_natAbs_of_nonpos (le_of_lt h)).symm + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_false, + Bool.false_eq_true, ↓reduceIte] using (Int.eq_natAbs_of_nonneg (le_of_not_gt h)).symm + have proof_nat_representation_47 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).representation = OAI.EditApproximation.UnreducedRational.nat n := by + apply proof_eq_of_num_den_33 + · change (OAI.EditApproximation.SignedBinary.ofInt (n : ℤ)).value = (n : ℤ) + exact proof_value_ofInt_46 _ + · rfl + have proof_value_nat_48 (n : ℕ) : (OAI.EditApproximation.UnreducedRational.nat n).value = n := by (simp [OAI.EditApproximation.UnreducedRational.nat, OAI.EditApproximation.UnreducedRational.value]) + have proof_nat_value_49 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).value = (n : ℚ) := by + rw [← proof_representation_value_32, proof_nat_representation_47, proof_value_nat_48] + have proof_arithmeticMapWithWork_value_70 {α : Type 0} {β : Type 0} (f : α → Prod.{0, 0} β ℕ) (values : List.{0} α) : + (OAI.EditApproximation.arithmeticMapWithWork f values).1 = values.map (fun a => (f a).1) := by + induction values with + | nil => rfl + | cons a rest ih => simp only [OAI.EditApproximation.arithmeticMapWithWork, ih, List.map_cons] + have proof_powerTwoWord_value_13 (n : ℕ) : OAI.EditApproximation.bitWordValue (OAI.EditApproximation.powerTwoWord n) = 2 ^ n := by + induction n with + | zero => (simp [OAI.EditApproximation.powerTwoWord, OAI.EditApproximation.bitWordValue]) + | succ n ih => + (simp only [OAI.EditApproximation.powerTwoWord, List.replicate_succ, List.cons_append, OAI.EditApproximation.bitWordValue, + Bool.toNat_false, zero_add] at *) + rw [ih, pow_succ] + omega + have proof_inversePowerTwo_value_89 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.inversePowerTwo n).value = (2 : ℚ) ^ (-(n : ℤ)) := by + (simp only [OAI.EditApproximation.BinaryFraction.inversePowerTwo, OAI.EditApproximation.BinaryFraction.value, OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, Bool.false_eq_true, + ↓reduceIte, OAI.EditApproximation.bitWordValue, Bool.toNat_true, + Int.cast_natCast, proof_powerTwoWord_value_13, Nat.cast_pow, Nat.cast_ofNat, zpow_neg, zpow_natCast]) + norm_num [one_div] + have proof_signedPowerTwoWithWork_value_90 (e : ℤ) : + (OAI.EditApproximation.BinaryFraction.signedPowerTwoWithWork e).1.value = (2 : ℚ) ^ e := by + unfold OAI.EditApproximation.BinaryFraction.signedPowerTwoWithWork + split_ifs with h + · change (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.powerTwoWord e.toNat) : ℚ) / 1 = (2 : ℚ) ^ e + rw [div_one, proof_powerTwoWord_value_13, Nat.cast_pow, Nat.cast_ofNat, ← zpow_natCast, + Int.toNat_of_nonneg h] + · rw [proof_inversePowerTwo_value_89, Int.toNat_of_nonneg + (show 0 ≤ -e from neg_nonneg.mpr (le_of_lt (lt_of_not_ge h))), neg_neg] + have proof_groupScalesWithWork_value_91 (eM : ℕ) (eb : ℕ) (eF : ℕ) : + ((OAI.EditApproximation.BinaryFraction.groupScalesWithWork eM eb eF).1.map OAI.EditApproximation.BinaryFraction.value) = + OAI.EditApproximation.groupDyadicScales (2 ^ eM) (2 ^ eb) ((2 : ℚ) ^ eF) := by + have hlower : ((2 ^ eb : ℕ) : ℚ) / (2 ^ eM : ℕ) = (2 : ℚ) ^ ((eb : ℤ) - eM) := by + rw [Nat.cast_pow, Nat.cast_pow, Nat.cast_ofNat, zpow_sub₀ (by norm_num : (2 : ℚ) ≠ 0), + zpow_natCast, zpow_natCast] + have hupper : (64 : ℚ) * (2 : ℚ) ^ eF * (2 ^ eb : ℕ) = + (2 : ℚ) ^ ((6 + eF + eb : ℕ) : ℤ) := by + rw [Nat.cast_pow, Nat.cast_ofNat, zpow_natCast, pow_add, pow_add] + norm_num + have hlog : Int.log 2 ((2 : ℚ) ^ ((6 + eF + eb : ℕ) : ℤ)) = ((6 + eF + eb : ℕ) : ℤ) := by + simpa only [Nat.cast_ofNat] using Int.log_zpow (R := ℚ) (by decide : 1 < 2) ((6 + eF + eb : ℕ) : ℤ) + have hclog : Int.clog 2 ((2 : ℚ) ^ ((eb : ℤ) - eM)) = (eb : ℤ) - eM := by + simpa only [Nat.cast_ofNat] using Int.clog_zpow (R := ℚ) (by decide : 1 < 2) ((eb : ℤ) - eM) + simp only [OAI.EditApproximation.BinaryFraction.groupScalesWithWork, proof_arithmeticMapWithWork_value_70, List.map_map, + Function.comp_def, proof_signedPowerTwoWithWork_value_90, OAI.EditApproximation.groupDyadicScales, hlower, hupper, hlog, hclog] + have proof_computedGroupScales_value_87 (M : ℕ) (b : ℕ) (F : ℕ) (eM : ℕ) (eb : ℕ) (eF : ℕ) (hM : Eq.{1} M (HPow.hPow.{0, 0, 0} 2 eM)) (hb : Eq.{1} b (HPow.hPow.{0, 0, 0} 2 eb)) (hF : Eq.{1} F (HPow.hPow.{0, 0, 0} 2 eF)) : + (OAI.EditApproximation.BinaryFraction.groupScalesWithWork eM eb eF).1.map OAI.EditApproximation.BinaryFraction.value = OAI.EditApproximation.groupDyadicScales M b (OAI.EditApproximation.BinaryFraction.nat F).value := by + rw [proof_nat_value_49, hM, hb, hF, Nat.cast_pow, Nat.cast_ofNat] + exact proof_groupScalesWithWork_value_91 eM eb eF + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_wordLEWithWork_value_26 (a : List.{0} Bool) (b : List.{0} Bool) : + (OAI.EditApproximation.wordLEWithWork a b).1 = true ↔ OAI.EditApproximation.bitWordValue a ≤ OAI.EditApproximation.bitWordValue b := by + simp only [OAI.EditApproximation.wordLEWithWork, Bool.not_eq_true', decide_eq_false_iff_not, + proof_bitCompareWithWork_lt_16, not_lt] + have proof_wordMinWithWork_value_29 (a : List.{0} Bool) (b : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.wordMinWithWork a b).1 = min (OAI.EditApproximation.bitWordValue a) (OAI.EditApproximation.bitWordValue b) := by + unfold OAI.EditApproximation.wordMinWithWork + dsimp only + split_ifs with h + · exact (min_eq_left ((proof_wordLEWithWork_value_26 a b).mp h)).symm + · exact (min_eq_right (le_of_not_ge (fun hle => h ((proof_wordLEWithWork_value_26 a b).mpr hle)))).symm + have proof_bitSubtractor_value_17 (a : Bool) (b : Bool) (borrow : Bool) : + a.toNat + 2 * (OAI.EditApproximation.bitBorrow a b borrow).toNat = + b.toNat + borrow.toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat := by + cases a <;> cases b <;> cases borrow <;> decide + have proof_bitSubtractionRippleEquation_18 (a : ℕ) (b : ℕ) (borrow : ℕ) (nextBorrow : ℕ) (difference : ℕ) (left : ℕ) (right : ℕ) (result : ℕ) (tail : ℕ) (htail : Eq.{1} (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} result right) nextBorrow) (HAdd.hAdd.{0, 0, 0} left tail)) (hbit : Eq.{1} (HAdd.hAdd.{0, 0, 0} a (HMul.hMul.{0, 0, 0} 2 nextBorrow)) + (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} b borrow) difference)) : + (difference + 2 * result) + (b + 2 * right) + borrow = + (a + 2 * left) + 2 * tail := by + omega + have proof_bitSubtractWithWork_value_19 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right borrow).1 + OAI.EditApproximation.bitWordValue right + borrow.toNat = + OAI.EditApproximation.bitWordValue left + 2 ^ max left.length right.length * + (OAI.EditApproximation.bitSubtractWithWork left right borrow).2.1.toNat := by + induction left generalizing right borrow with + | nil => + induction right generalizing borrow with + | nil => (simp [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + have h := ih (OAI.EditApproximation.bitBorrow false b borrow) + have hb := proof_bitSubtractor_value_17 false b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue, + List.length_nil, List.length_cons, Nat.zero_max, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 0 b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow false b borrow).toNat + (OAI.EditApproximation.bitDifference false b borrow).toNat 0 (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).1) + (2 ^ bs.length * (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons a as ih => + cases right with + | nil => + have h := ih [] (OAI.EditApproximation.bitBorrow a false borrow) + have hb := proof_bitSubtractor_value_17 a false borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_nil, List.length_cons, + Nat.max_zero, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat 0 borrow.toNat (OAI.EditApproximation.bitBorrow a false borrow).toNat + (OAI.EditApproximation.bitDifference a false borrow).toNat (OAI.EditApproximation.bitWordValue as) 0 + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).1) + (2 ^ as.length * (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons b bs => + have h := ih bs (OAI.EditApproximation.bitBorrow a b borrow) + have hb := proof_bitSubtractor_value_17 a b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_cons, Nat.succ_max_succ, + pow_succ] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow a b borrow).toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).1) + (2 ^ max as.length bs.length * (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_assoc, Nat.mul_left_comm] using hs + have proof_bitWordValue_lt_pow_length_20 (bits : List.{0} Bool) : OAI.EditApproximation.bitWordValue bits < 2 ^ bits.length := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitWordValue]) + | cons bit bits ih => + cases bit <;> (simp only [OAI.EditApproximation.bitWordValue, List.length_cons, pow_succ, Bool.toNat_false, Bool.toNat_true]) <;> omega + have proof_bitSubtractWithWork_length_21 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + (OAI.EditApproximation.bitSubtractWithWork left right borrow).1.length = max left.length right.length := by + induction left generalizing right borrow with + | nil => + simp only [OAI.EditApproximation.bitSubtractWithWork] + induction right generalizing borrow with + | nil => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork] + | cons b bs ih => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork, ih] + | cons a as ih => + cases right with + | nil => simp [OAI.EditApproximation.bitSubtractWithWork, ih] + | cons b bs => simp [OAI.EditApproximation.bitSubtractWithWork, ih, Nat.succ_max_succ] + have proof_bitSubtractWithWork_sub_22 (left : List.{0} Bool) (right : List.{0} Bool) (h : LE.le.{0} (OAI.EditApproximation.bitWordValue right) (OAI.EditApproximation.bitWordValue left)) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right false).1 = OAI.EditApproximation.bitWordValue left - OAI.EditApproximation.bitWordValue right := by + have hvalue := proof_bitSubtractWithWork_value_19 left right false + have hlt := proof_bitWordValue_lt_pow_length_20 (OAI.EditApproximation.bitSubtractWithWork left right false).1 + rw [proof_bitSubtractWithWork_length_21] at hlt + cases hb : (OAI.EditApproximation.bitSubtractWithWork left right false).2.1 + · simp only [hb, Bool.toNat_false, Nat.mul_zero, Nat.add_zero] at hvalue + omega + · simp only [hb, Bool.toNat_true, Bool.toNat_false, Nat.mul_one, Nat.add_zero] at hvalue + omega + have proof_bitDivModWithWork_value_23 (divisor : List.{0} Bool) (bits : List.{0} Bool) (hd : LT.lt.{0} 0 (OAI.EditApproximation.bitWordValue divisor)) : + OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).1 + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 < OAI.EditApproximation.bitWordValue divisor := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitDivModWithWork, OAI.EditApproximation.bitWordValue, hd]) + | cons bit bits ih => + let previous := OAI.EditApproximation.bitDivModWithWork divisor bits + let candidate := bit :: previous.2.1 + have hp : OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue previous.1 + + OAI.EditApproximation.bitWordValue previous.2.1 := ih.1 + have hr : OAI.EditApproximation.bitWordValue previous.2.1 < OAI.EditApproximation.bitWordValue divisor := ih.2 + have hc : OAI.EditApproximation.bitWordValue candidate < 2 * OAI.EditApproximation.bitWordValue divisor := by + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + cases bit <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega + by_cases hlt : (OAI.EditApproximation.bitCompareWithWork candidate divisor).1 = .lt + · have hv := (proof_bitCompareWithWork_lt_16 candidate divisor).1 hlt + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 = .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * + OAI.EditApproximation.bitWordValue (false :: previous.1) + OAI.EditApproximation.bitWordValue candidate ∧ OAI.EditApproximation.bitWordValue candidate < _ + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_false]) + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + nlinarith only [hp] + · exact hv + · have hv : OAI.EditApproximation.bitWordValue divisor ≤ OAI.EditApproximation.bitWordValue candidate := by + exact Nat.le_of_not_gt (fun h => hlt ((proof_bitCompareWithWork_lt_16 candidate divisor).2 h)) + have hs := proof_bitSubtractWithWork_sub_22 candidate divisor hv + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 ≠ .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (true :: previous.1) + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 < _ + rw [hs] + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_true]) + have he := Nat.sub_add_cancel hv + dsimp only [candidate, OAI.EditApproximation.bitWordValue] at he ⊢ + nlinarith only [hp, he] + · omega + have proof_bitCompareWithWork_eq_3 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .eq ↔ OAI.EditApproximation.bitWordValue left = OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_bitAdder_value_1 (a : Bool) (b : Bool) (carry : Bool) : + (OAI.EditApproximation.bitSum a b carry).toNat + 2 * (OAI.EditApproximation.bitCarry a b carry).toNat = + a.toNat + b.toNat + carry.toNat := by + cases a <;> cases b <;> cases carry <;> decide + have proof_bitAddWithWork_value_2 (left : List.{0} Bool) (right : List.{0} Bool) (carry : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitAddWithWork left right carry).1 = + OAI.EditApproximation.bitWordValue left + OAI.EditApproximation.bitWordValue right + carry.toNat := by + induction left generalizing right carry with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork] + induction right generalizing carry with + | nil => cases carry <;> simp [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue] + | cons b bs ih => + simp only [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 false b carry + simp only [Bool.toNat_false] at h + omega + | cons a as ih => + cases right with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a false carry + simp only [Bool.toNat_false] at h + omega + | cons b bs => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a b carry + omega + have proof_bitCeilDivWithWork_value_30 (divisor : List.{0} Bool) (bits : List.{0} Bool) (hd : LT.lt.{0} 0 (OAI.EditApproximation.bitWordValue divisor)) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitCeilDivWithWork divisor bits).1 = + ⌈((OAI.EditApproximation.bitWordValue bits : ℚ) / OAI.EditApproximation.bitWordValue divisor)⌉₊ := by + let q := OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).1 + let r := OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 + have h := proof_bitDivModWithWork_value_23 divisor bits hd + have heq : OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * q + r := h.1 + have hr : r < OAI.EditApproximation.bitWordValue divisor := h.2 + have hdQ : (0 : ℚ) < OAI.EditApproximation.bitWordValue divisor := by exact_mod_cast hd + unfold OAI.EditApproximation.bitCeilDivWithWork + dsimp only + split_ifs with hz + · have hr0 : r = 0 := by + exact (proof_bitCompareWithWork_eq_3 (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 []).1 hz + have hratio : (OAI.EditApproximation.bitWordValue bits : ℚ) / OAI.EditApproximation.bitWordValue divisor = (q : ℚ) := by + apply (div_eq_iff hdQ.ne').mpr + exact_mod_cast (show OAI.EditApproximation.bitWordValue bits = q * OAI.EditApproximation.bitWordValue divisor by nlinarith only [heq, hr0]) + rw [hratio] + exact (Nat.ceil_natCast q).symm + · have hr0 : r ≠ 0 := by + intro hzero + exact hz ((proof_bitCompareWithWork_eq_3 (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 []).2 hzero) + rw [proof_bitAddWithWork_value_2] + change q + 1 + 0 = _ + simp only [Nat.add_zero] + symm + apply (Nat.ceil_eq_iff (by omega : q + 1 ≠ 0)).mpr + constructor + · simp only [Nat.add_sub_cancel] + rw [lt_div_iff₀ hdQ] + exact_mod_cast (show q * OAI.EditApproximation.bitWordValue divisor < OAI.EditApproximation.bitWordValue bits by + nlinarith only [heq, Nat.pos_of_ne_zero hr0]) + · rw [div_le_iff₀ hdQ] + push_cast + exact_mod_cast (show OAI.EditApproximation.bitWordValue bits ≤ (q + 1) * OAI.EditApproximation.bitWordValue divisor by nlinarith only [heq, hr]) + have proof_naturalCeilingWithWork_value_31 (a : OAI.EditApproximation.BinaryFraction) : + OAI.EditApproximation.bitWordValue (a.naturalCeilingWithWork).1 = ⌈a.value⌉₊ := by + cases hs : a.numerator.negative + · simpa only [OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork, hs, Bool.false_eq_true, ↓reduceIte, + OAI.EditApproximation.BinaryFraction.value, OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, Int.cast_natCast] using + proof_bitCeilDivWithWork_value_30 a.denominator a.numerator.bits a.denominator_pos + · have hn : a.value ≤ 0 := by + (simp only [OAI.EditApproximation.BinaryFraction.value, OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hs, ↓reduceIte, Int.cast_neg, Int.cast_natCast]) + exact div_nonpos_of_nonpos_of_nonneg (neg_nonpos.mpr (Nat.cast_nonneg _)) (Nat.cast_nonneg _) + (simp only [OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork, hs, ↓reduceIte, OAI.EditApproximation.bitWordValue]) + exact (Nat.ceil_eq_zero.mpr hn).symm + have proof_trimBitWordWithWork_value_6 (bits : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.trimBitWordWithWork bits).1 = OAI.EditApproximation.bitWordValue bits := by + induction bits with + | nil => rfl + | cons bit bits ih => + simp only [OAI.EditApproximation.trimBitWordWithWork] + split_ifs with h + · have ht : OAI.EditApproximation.bitWordValue bits = 0 := by rw [← ih, h.1]; rfl + simp [h.2, OAI.EditApproximation.bitWordValue, ht] + · (simp only [OAI.EditApproximation.bitWordValue, ih]) + have proof_canonicalizeWithWork_representation_34 (a : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.canonicalizeWithWork a).1.representation = a.representation := by + apply proof_eq_of_num_den_33 + · (simp only [OAI.EditApproximation.BinaryFraction.canonicalizeWithWork, OAI.EditApproximation.BinaryFraction.representation, OAI.EditApproximation.SignedBinary.value, proof_trimBitWordWithWork_value_6]) + · exact proof_trimBitWordWithWork_value_6 a.denominator + have proof_bitMulWithWork_value_0 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitMulWithWork left right).1 = OAI.EditApproximation.bitWordValue left * OAI.EditApproximation.bitWordValue right := by + induction left with + | nil => simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue] + | cons bit bits ih => + cases bit <;> simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue, proof_bitAddWithWork_value_2, ih] <;> ring + have proof_mulWithWork_value_35 (a : OAI.EditApproximation.SignedBinary) (b : OAI.EditApproximation.SignedBinary) : + (a.mulWithWork b).1.value = a.value * b.value := by + simp only [OAI.EditApproximation.SignedBinary.mulWithWork, OAI.EditApproximation.SignedBinary.value, proof_bitMulWithWork_value_0] + cases a.negative <;> cases b.negative <;> simp [OAI.EditApproximation.signedMagnitude] + have proof_mulWithWork_representation_36 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (a.mulWithWork b).1.representation = a.representation.mul b.representation := by + apply proof_eq_of_num_den_33 + · exact proof_mulWithWork_value_35 a.numerator b.numerator + · exact proof_bitMulWithWork_value_0 a.denominator b.denominator + have proof_canonicalMulWithWork_representation_37 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork a b).1.representation = a.representation.mul b.representation := by + rw [OAI.EditApproximation.BinaryFraction.canonicalMulWithWork, proof_canonicalizeWithWork_representation_34, proof_mulWithWork_representation_36] + have proof_zero_representation_38 : OAI.EditApproximation.BinaryFraction.zero.representation = OAI.EditApproximation.UnreducedRational.zero := by + apply proof_eq_of_num_den_33 <;> rfl + have proof_invWithWork_representation_39 (a : OAI.EditApproximation.BinaryFraction) : + (a.invWithWork).1.representation = a.representation.inv := by + unfold OAI.EditApproximation.BinaryFraction.invWithWork + dsimp only + split_ifs with h + · have hz : OAI.EditApproximation.bitWordValue a.numerator.bits = 0 := by + simpa only [OAI.EditApproximation.bitWordValue] using (proof_bitCompareWithWork_eq_3 a.numerator.bits []).1 h + have hv : a.numerator.value = 0 := by (simp [OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hz]) + (simp only [OAI.EditApproximation.UnreducedRational.inv, OAI.EditApproximation.BinaryFraction.representation, hv, ↓reduceDIte]) + exact proof_zero_representation_38 + · have hn : OAI.EditApproximation.bitWordValue a.numerator.bits ≠ 0 := by + intro hz + exact h ((proof_bitCompareWithWork_eq_3 a.numerator.bits []).2 (by simpa [OAI.EditApproximation.bitWordValue] using hz)) + have hv : a.numerator.value ≠ 0 := by + cases hs : a.numerator.negative <;> (simp [OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hs, hn]) + (simp only [OAI.EditApproximation.UnreducedRational.inv, OAI.EditApproximation.BinaryFraction.representation, hv, ↓reduceDIte]) + apply proof_eq_of_num_den_33 + · cases hs : a.numerator.negative <;> + simp [OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hs, Int.sign_natCast_of_ne_zero hn] + · cases hs : a.numerator.negative <;> (simp [OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hs]) + have proof_divWithWork_representation_40 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (a.divWithWork b).1.representation = a.representation.div b.representation := by + (simp only [OAI.EditApproximation.BinaryFraction.divWithWork, proof_canonicalMulWithWork_representation_37, proof_invWithWork_representation_39, + OAI.EditApproximation.UnreducedRational.div]) + have proof_value_mul_41 (a : OAI.EditApproximation.UnreducedRational) (b : OAI.EditApproximation.UnreducedRational) : (a.mul b).value = a.value * b.value := by + simp [OAI.EditApproximation.UnreducedRational.mul, OAI.EditApproximation.UnreducedRational.value, mul_div_mul_comm] + have proof_value_inv_42 (a : OAI.EditApproximation.UnreducedRational) : a.inv.value = a.value⁻¹ := by + by_cases h : a.num = 0 + · simp [OAI.EditApproximation.UnreducedRational.inv, h, OAI.EditApproximation.UnreducedRational.value, OAI.EditApproximation.UnreducedRational.zero] + · have hn : (a.num.natAbs : ℚ) ≠ 0 := by exact_mod_cast (Int.natAbs_pos.mpr h).ne' + have hd : (a.den : ℚ) ≠ 0 := by exact_mod_cast a.den_pos.ne' + have hsign : ((a.num.sign : ℤ) : ℚ) * a.num = (a.num.natAbs : ℚ) := by + simpa only [Int.cast_mul, Int.cast_natCast] using + congrArg (fun z : ℤ => (z : ℚ)) (Int.sign_mul_self_eq_natAbs a.num) + simp only [OAI.EditApproximation.UnreducedRational.inv, h, ↓reduceDIte, OAI.EditApproximation.UnreducedRational.value] + push_cast + apply eq_inv_of_mul_eq_one_left + field_simp [hn, hd] + exact hsign + have proof_value_div_43 (a : OAI.EditApproximation.UnreducedRational) (b : OAI.EditApproximation.UnreducedRational) : (a.div b).value = a.value / b.value := by + simp [proof_value_mul_41, proof_value_inv_42, OAI.EditApproximation.UnreducedRational.div, div_eq_mul_inv] + have proof_divWithWork_value_44 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.divWithWork a b).1.value = a.value / b.value := by + rw [← proof_representation_value_32, proof_divWithWork_representation_40, + proof_value_div_43, proof_representation_value_32, proof_representation_value_32] + have proof_canonicalMulWithWork_value_45 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork a b).1.value = a.value * b.value := by + rw [← proof_representation_value_32, proof_canonicalMulWithWork_representation_37, + proof_value_mul_41, proof_representation_value_32, proof_representation_value_32] + have proof_groupSampleCountWithWork_value_28 (M : ℕ) (Q : ℕ) (b : ℕ) (h : OAI.EditApproximation.BinaryFraction) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.BinaryFraction.groupSampleCountWithWork M Q b h).1 = OAI.EditApproximation.groupSampleCount M Q b h.value := by + simp only [OAI.EditApproximation.BinaryFraction.groupSampleCountWithWork, proof_wordMinWithWork_value_29, proof_bitWordValue_bits_15, + proof_naturalCeilingWithWork_value_31, proof_divWithWork_value_44, proof_canonicalMulWithWork_value_45, + proof_nat_value_49, OAI.EditApproximation.groupSampleCount] + have proof_queryScaleAt_value_88 (words : List.{0} OAI.EditApproximation.BinaryFraction) (scales : List.{0} ℚ) (h : Eq.{1} (List.map.{0, 0} OAI.EditApproximation.BinaryFraction.value words) scales) (i : Fin (List.length.{0} scales)) : + (OAI.EditApproximation.BinaryFraction.queryScaleAt words scales h i).value = scales[i.val] := by + subst scales + simp only [OAI.EditApproximation.BinaryFraction.queryScaleAt, List.getElem_map] + exact + let b := 2 ^ eb + let scales := OAI.EditApproximation.BinaryFraction.groupScalesWithWork eM eb eF + let hs : scales.1.map OAI.EditApproximation.BinaryFraction.value = OAI.EditApproximation.groupDyadicScales M b F := by + simpa only [proof_nat_value_49] using proof_computedGroupScales_value_87 M b F eM eb eF hM rfl hF + let hlen : scales.1.length = (OAI.EditApproximation.groupDyadicScales M b F).length := by + simpa only [List.length_map] using congrArg List.length hs + let indices := OAI.EditApproximation.queryFinRange scales.1.length (OAI.EditApproximation.groupDyadicScales M b F).length hlen + let samples := OAI.EditApproximation.arithmeticFlatMapWithWork (fun scale => + let word := OAI.EditApproximation.BinaryFraction.queryScaleAt scales.1 (OAI.EditApproximation.groupDyadicScales M b F) hs scale + let count := OAI.EditApproximation.BinaryFraction.groupSampleCountWithWork M Q b word + let hc : OAI.EditApproximation.bitWordValue count.1 = OAI.EditApproximation.groupSampleCount M Q b (OAI.EditApproximation.groupDyadicScaleAt M b F scale) := by + rw [proof_groupSampleCountWithWork_value_28, proof_queryScaleAt_value_88] + rfl + let coordinates := OAI.EditApproximation.queryFinRange (OAI.EditApproximation.bitWordValue count.1) + (OAI.EditApproximation.groupSampleCount M Q b (OAI.EditApproximation.groupDyadicScaleAt M b F scale)) hc + let labeled := OAI.EditApproximation.arithmeticMapWithWork (fun sample => + ((⟨(b, cell), scale, sample⟩ : OAI.EditApproximation.GroupScalarKey M F Q), 2)) coordinates + (labeled.1, scales.1.length + count.2 + labeled.2 + coordinates.length + 3)) indices + (samples.1, scales.2 + 4 * scales.1.length + samples.2 + eb + 4) + +def querySharedCellInputsWithWork {nx ny : ℕ} (M F Q eM eb eF : ℕ) + (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (parent : OAI.EditApproximation.TargetInterval nx) + (exponent : ℕ) (cell : ℕ × ℕ) + (draw : ∀ scale : Fin (OAI.EditApproximation.groupDyadicScales M (2 ^ eb) F).length, + Fin (OAI.EditApproximation.groupSampleCount M Q (2 ^ eb) (OAI.EditApproximation.groupDyadicScaleAt M (2 ^ eb) F scale)) → Fin M × ℕ) : + List (Fin M × OAI.EditApproximation.TargetInterval ny) × ℕ := by + have proof_representation_value_32 (a : OAI.EditApproximation.BinaryFraction) : a.representation.value = a.value := rfl + have proof_eq_of_num_den_33 {a : OAI.EditApproximation.UnreducedRational} {b : OAI.EditApproximation.UnreducedRational} (hnum : Eq.{1} a.num b.num) (hden : Eq.{1} a.den b.den) : a = b := by + cases a + cases b + cases hnum + cases hden + rfl + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_value_ofInt_46 (a : ℤ) : (OAI.EditApproximation.SignedBinary.ofInt a).value = a := by + by_cases h : a < 0 + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_true, + ↓reduceIte] using (Int.eq_neg_natAbs_of_nonpos (le_of_lt h)).symm + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_false, + Bool.false_eq_true, ↓reduceIte] using (Int.eq_natAbs_of_nonneg (le_of_not_gt h)).symm + have proof_nat_representation_47 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).representation = OAI.EditApproximation.UnreducedRational.nat n := by + apply proof_eq_of_num_den_33 + · change (OAI.EditApproximation.SignedBinary.ofInt (n : ℤ)).value = (n : ℤ) + exact proof_value_ofInt_46 _ + · rfl + have proof_value_nat_48 (n : ℕ) : (OAI.EditApproximation.UnreducedRational.nat n).value = n := by (simp [OAI.EditApproximation.UnreducedRational.nat, OAI.EditApproximation.UnreducedRational.value]) + have proof_nat_value_49 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).value = (n : ℚ) := by + rw [← proof_representation_value_32, proof_nat_representation_47, proof_value_nat_48] + have proof_arithmeticMapWithWork_value_70 {α : Type 0} {β : Type 0} (f : α → Prod.{0, 0} β ℕ) (values : List.{0} α) : + (OAI.EditApproximation.arithmeticMapWithWork f values).1 = values.map (fun a => (f a).1) := by + induction values with + | nil => rfl + | cons a rest ih => simp only [OAI.EditApproximation.arithmeticMapWithWork, ih, List.map_cons] + have proof_powerTwoWord_value_13 (n : ℕ) : OAI.EditApproximation.bitWordValue (OAI.EditApproximation.powerTwoWord n) = 2 ^ n := by + induction n with + | zero => (simp [OAI.EditApproximation.powerTwoWord, OAI.EditApproximation.bitWordValue]) + | succ n ih => + (simp only [OAI.EditApproximation.powerTwoWord, List.replicate_succ, List.cons_append, OAI.EditApproximation.bitWordValue, + Bool.toNat_false, zero_add] at *) + rw [ih, pow_succ] + omega + have proof_inversePowerTwo_value_89 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.inversePowerTwo n).value = (2 : ℚ) ^ (-(n : ℤ)) := by + (simp only [OAI.EditApproximation.BinaryFraction.inversePowerTwo, OAI.EditApproximation.BinaryFraction.value, OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, Bool.false_eq_true, + ↓reduceIte, OAI.EditApproximation.bitWordValue, Bool.toNat_true, + Int.cast_natCast, proof_powerTwoWord_value_13, Nat.cast_pow, Nat.cast_ofNat, zpow_neg, zpow_natCast]) + norm_num [one_div] + have proof_signedPowerTwoWithWork_value_90 (e : ℤ) : + (OAI.EditApproximation.BinaryFraction.signedPowerTwoWithWork e).1.value = (2 : ℚ) ^ e := by + unfold OAI.EditApproximation.BinaryFraction.signedPowerTwoWithWork + split_ifs with h + · change (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.powerTwoWord e.toNat) : ℚ) / 1 = (2 : ℚ) ^ e + rw [div_one, proof_powerTwoWord_value_13, Nat.cast_pow, Nat.cast_ofNat, ← zpow_natCast, + Int.toNat_of_nonneg h] + · rw [proof_inversePowerTwo_value_89, Int.toNat_of_nonneg + (show 0 ≤ -e from neg_nonneg.mpr (le_of_lt (lt_of_not_ge h))), neg_neg] + have proof_groupScalesWithWork_value_91 (eM : ℕ) (eb : ℕ) (eF : ℕ) : + ((OAI.EditApproximation.BinaryFraction.groupScalesWithWork eM eb eF).1.map OAI.EditApproximation.BinaryFraction.value) = + OAI.EditApproximation.groupDyadicScales (2 ^ eM) (2 ^ eb) ((2 : ℚ) ^ eF) := by + have hlower : ((2 ^ eb : ℕ) : ℚ) / (2 ^ eM : ℕ) = (2 : ℚ) ^ ((eb : ℤ) - eM) := by + rw [Nat.cast_pow, Nat.cast_pow, Nat.cast_ofNat, zpow_sub₀ (by norm_num : (2 : ℚ) ≠ 0), + zpow_natCast, zpow_natCast] + have hupper : (64 : ℚ) * (2 : ℚ) ^ eF * (2 ^ eb : ℕ) = + (2 : ℚ) ^ ((6 + eF + eb : ℕ) : ℤ) := by + rw [Nat.cast_pow, Nat.cast_ofNat, zpow_natCast, pow_add, pow_add] + norm_num + have hlog : Int.log 2 ((2 : ℚ) ^ ((6 + eF + eb : ℕ) : ℤ)) = ((6 + eF + eb : ℕ) : ℤ) := by + simpa only [Nat.cast_ofNat] using Int.log_zpow (R := ℚ) (by decide : 1 < 2) ((6 + eF + eb : ℕ) : ℤ) + have hclog : Int.clog 2 ((2 : ℚ) ^ ((eb : ℤ) - eM)) = (eb : ℤ) - eM := by + simpa only [Nat.cast_ofNat] using Int.clog_zpow (R := ℚ) (by decide : 1 < 2) ((eb : ℤ) - eM) + simp only [OAI.EditApproximation.BinaryFraction.groupScalesWithWork, proof_arithmeticMapWithWork_value_70, List.map_map, + Function.comp_def, proof_signedPowerTwoWithWork_value_90, OAI.EditApproximation.groupDyadicScales, hlower, hupper, hlog, hclog] + have proof_computedGroupScales_value_87 (M : ℕ) (b : ℕ) (F : ℕ) (eM : ℕ) (eb : ℕ) (eF : ℕ) (hM : Eq.{1} M (HPow.hPow.{0, 0, 0} 2 eM)) (hb : Eq.{1} b (HPow.hPow.{0, 0, 0} 2 eb)) (hF : Eq.{1} F (HPow.hPow.{0, 0, 0} 2 eF)) : + (OAI.EditApproximation.BinaryFraction.groupScalesWithWork eM eb eF).1.map OAI.EditApproximation.BinaryFraction.value = OAI.EditApproximation.groupDyadicScales M b (OAI.EditApproximation.BinaryFraction.nat F).value := by + rw [proof_nat_value_49, hM, hb, hF, Nat.cast_pow, Nat.cast_ofNat] + exact proof_groupScalesWithWork_value_91 eM eb eF + have proof_queryScaleAt_value_88 (words : List.{0} OAI.EditApproximation.BinaryFraction) (scales : List.{0} ℚ) (h : Eq.{1} (List.map.{0, 0} OAI.EditApproximation.BinaryFraction.value words) scales) (i : Fin (List.length.{0} scales)) : + (OAI.EditApproximation.BinaryFraction.queryScaleAt words scales h i).value = scales[i.val] := by + subst scales + simp only [OAI.EditApproximation.BinaryFraction.queryScaleAt, List.getElem_map] + have proof_queryGroupScaleAt_value_92 (M : ℕ) (b : ℕ) (F : ℕ) (words : List.{0} OAI.EditApproximation.BinaryFraction) (h : Eq.{1} (List.map.{0, 0} OAI.EditApproximation.BinaryFraction.value words) + (OAI.EditApproximation.groupDyadicScales M b ↑F)) (i : Fin (List.length.{0} (OAI.EditApproximation.groupDyadicScales M b ↑F))) : + (OAI.EditApproximation.BinaryFraction.queryScaleAt words (OAI.EditApproximation.groupDyadicScales M b F) h i).value = OAI.EditApproximation.groupDyadicScaleAt M b F i := + proof_queryScaleAt_value_88 words (OAI.EditApproximation.groupDyadicScales M b F) h i + exact + let b := 2 ^ eb + let scales := OAI.EditApproximation.BinaryFraction.groupScalesWithWork eM eb eF + let hs : scales.1.map OAI.EditApproximation.BinaryFraction.value = OAI.EditApproximation.groupDyadicScales M b F := by + simpa only [proof_nat_value_49] using proof_computedGroupScales_value_87 M b F eM eb eF hM rfl hF + let hlen : scales.1.length = (OAI.EditApproximation.groupDyadicScales M b F).length := by + simpa only [List.length_map] using congrArg List.length hs + let indices := OAI.EditApproximation.queryFinRange scales.1.length (OAI.EditApproximation.groupDyadicScales M b F).length hlen + let inputs := OAI.EditApproximation.arithmeticFlatMapWithWork (fun scale => + let word := OAI.EditApproximation.BinaryFraction.queryScaleAt scales.1 (OAI.EditApproximation.groupDyadicScales M b F) hs scale + let hv : word.value = OAI.EditApproximation.groupDyadicScaleAt M b F scale := proof_queryGroupScaleAt_value_92 M b F _ hs scale + let states := OAI.EditApproximation.BinaryFraction.queryGroupInputsTransportWithWork (ny := ny) parent b exponent Q cell word + (OAI.EditApproximation.groupDyadicScaleAt M b F scale) hv (draw scale) + (states.1, states.2 + scales.1.length + 1)) indices + (inputs.1, scales.2 + 4 * scales.1.length + inputs.2 + eb + 4) + +def groupKeySampleBlock {M F Q : ℕ} (b : ℕ) (raw : List OAI.EditApproximation.BinaryFraction) + (hs : raw.map OAI.EditApproximation.BinaryFraction.value = OAI.EditApproximation.groupDyadicScales M b F) (cell : ℕ × ℕ) + (scale : Fin (OAI.EditApproximation.groupDyadicScales M b F).length) : List (OAI.EditApproximation.GroupScalarKey M F Q) × ℕ := by + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_wordLEWithWork_value_26 (a : List.{0} Bool) (b : List.{0} Bool) : + (OAI.EditApproximation.wordLEWithWork a b).1 = true ↔ OAI.EditApproximation.bitWordValue a ≤ OAI.EditApproximation.bitWordValue b := by + simp only [OAI.EditApproximation.wordLEWithWork, Bool.not_eq_true', decide_eq_false_iff_not, + proof_bitCompareWithWork_lt_16, not_lt] + have proof_wordMinWithWork_value_29 (a : List.{0} Bool) (b : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.wordMinWithWork a b).1 = min (OAI.EditApproximation.bitWordValue a) (OAI.EditApproximation.bitWordValue b) := by + unfold OAI.EditApproximation.wordMinWithWork + dsimp only + split_ifs with h + · exact (min_eq_left ((proof_wordLEWithWork_value_26 a b).mp h)).symm + · exact (min_eq_right (le_of_not_ge (fun hle => h ((proof_wordLEWithWork_value_26 a b).mpr hle)))).symm + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_bitSubtractor_value_17 (a : Bool) (b : Bool) (borrow : Bool) : + a.toNat + 2 * (OAI.EditApproximation.bitBorrow a b borrow).toNat = + b.toNat + borrow.toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat := by + cases a <;> cases b <;> cases borrow <;> decide + have proof_bitSubtractionRippleEquation_18 (a : ℕ) (b : ℕ) (borrow : ℕ) (nextBorrow : ℕ) (difference : ℕ) (left : ℕ) (right : ℕ) (result : ℕ) (tail : ℕ) (htail : Eq.{1} (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} result right) nextBorrow) (HAdd.hAdd.{0, 0, 0} left tail)) (hbit : Eq.{1} (HAdd.hAdd.{0, 0, 0} a (HMul.hMul.{0, 0, 0} 2 nextBorrow)) + (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} b borrow) difference)) : + (difference + 2 * result) + (b + 2 * right) + borrow = + (a + 2 * left) + 2 * tail := by + omega + have proof_bitSubtractWithWork_value_19 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right borrow).1 + OAI.EditApproximation.bitWordValue right + borrow.toNat = + OAI.EditApproximation.bitWordValue left + 2 ^ max left.length right.length * + (OAI.EditApproximation.bitSubtractWithWork left right borrow).2.1.toNat := by + induction left generalizing right borrow with + | nil => + induction right generalizing borrow with + | nil => (simp [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + have h := ih (OAI.EditApproximation.bitBorrow false b borrow) + have hb := proof_bitSubtractor_value_17 false b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue, + List.length_nil, List.length_cons, Nat.zero_max, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 0 b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow false b borrow).toNat + (OAI.EditApproximation.bitDifference false b borrow).toNat 0 (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).1) + (2 ^ bs.length * (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons a as ih => + cases right with + | nil => + have h := ih [] (OAI.EditApproximation.bitBorrow a false borrow) + have hb := proof_bitSubtractor_value_17 a false borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_nil, List.length_cons, + Nat.max_zero, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat 0 borrow.toNat (OAI.EditApproximation.bitBorrow a false borrow).toNat + (OAI.EditApproximation.bitDifference a false borrow).toNat (OAI.EditApproximation.bitWordValue as) 0 + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).1) + (2 ^ as.length * (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons b bs => + have h := ih bs (OAI.EditApproximation.bitBorrow a b borrow) + have hb := proof_bitSubtractor_value_17 a b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_cons, Nat.succ_max_succ, + pow_succ] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow a b borrow).toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).1) + (2 ^ max as.length bs.length * (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_assoc, Nat.mul_left_comm] using hs + have proof_bitWordValue_lt_pow_length_20 (bits : List.{0} Bool) : OAI.EditApproximation.bitWordValue bits < 2 ^ bits.length := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitWordValue]) + | cons bit bits ih => + cases bit <;> (simp only [OAI.EditApproximation.bitWordValue, List.length_cons, pow_succ, Bool.toNat_false, Bool.toNat_true]) <;> omega + have proof_bitSubtractWithWork_length_21 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + (OAI.EditApproximation.bitSubtractWithWork left right borrow).1.length = max left.length right.length := by + induction left generalizing right borrow with + | nil => + simp only [OAI.EditApproximation.bitSubtractWithWork] + induction right generalizing borrow with + | nil => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork] + | cons b bs ih => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork, ih] + | cons a as ih => + cases right with + | nil => simp [OAI.EditApproximation.bitSubtractWithWork, ih] + | cons b bs => simp [OAI.EditApproximation.bitSubtractWithWork, ih, Nat.succ_max_succ] + have proof_bitSubtractWithWork_sub_22 (left : List.{0} Bool) (right : List.{0} Bool) (h : LE.le.{0} (OAI.EditApproximation.bitWordValue right) (OAI.EditApproximation.bitWordValue left)) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right false).1 = OAI.EditApproximation.bitWordValue left - OAI.EditApproximation.bitWordValue right := by + have hvalue := proof_bitSubtractWithWork_value_19 left right false + have hlt := proof_bitWordValue_lt_pow_length_20 (OAI.EditApproximation.bitSubtractWithWork left right false).1 + rw [proof_bitSubtractWithWork_length_21] at hlt + cases hb : (OAI.EditApproximation.bitSubtractWithWork left right false).2.1 + · simp only [hb, Bool.toNat_false, Nat.mul_zero, Nat.add_zero] at hvalue + omega + · simp only [hb, Bool.toNat_true, Bool.toNat_false, Nat.mul_one, Nat.add_zero] at hvalue + omega + have proof_bitDivModWithWork_value_23 (divisor : List.{0} Bool) (bits : List.{0} Bool) (hd : LT.lt.{0} 0 (OAI.EditApproximation.bitWordValue divisor)) : + OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).1 + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 < OAI.EditApproximation.bitWordValue divisor := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitDivModWithWork, OAI.EditApproximation.bitWordValue, hd]) + | cons bit bits ih => + let previous := OAI.EditApproximation.bitDivModWithWork divisor bits + let candidate := bit :: previous.2.1 + have hp : OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue previous.1 + + OAI.EditApproximation.bitWordValue previous.2.1 := ih.1 + have hr : OAI.EditApproximation.bitWordValue previous.2.1 < OAI.EditApproximation.bitWordValue divisor := ih.2 + have hc : OAI.EditApproximation.bitWordValue candidate < 2 * OAI.EditApproximation.bitWordValue divisor := by + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + cases bit <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega + by_cases hlt : (OAI.EditApproximation.bitCompareWithWork candidate divisor).1 = .lt + · have hv := (proof_bitCompareWithWork_lt_16 candidate divisor).1 hlt + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 = .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * + OAI.EditApproximation.bitWordValue (false :: previous.1) + OAI.EditApproximation.bitWordValue candidate ∧ OAI.EditApproximation.bitWordValue candidate < _ + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_false]) + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + nlinarith only [hp] + · exact hv + · have hv : OAI.EditApproximation.bitWordValue divisor ≤ OAI.EditApproximation.bitWordValue candidate := by + exact Nat.le_of_not_gt (fun h => hlt ((proof_bitCompareWithWork_lt_16 candidate divisor).2 h)) + have hs := proof_bitSubtractWithWork_sub_22 candidate divisor hv + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 ≠ .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (true :: previous.1) + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 < _ + rw [hs] + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_true]) + have he := Nat.sub_add_cancel hv + dsimp only [candidate, OAI.EditApproximation.bitWordValue] at he ⊢ + nlinarith only [hp, he] + · omega + have proof_bitCompareWithWork_eq_3 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .eq ↔ OAI.EditApproximation.bitWordValue left = OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_bitAdder_value_1 (a : Bool) (b : Bool) (carry : Bool) : + (OAI.EditApproximation.bitSum a b carry).toNat + 2 * (OAI.EditApproximation.bitCarry a b carry).toNat = + a.toNat + b.toNat + carry.toNat := by + cases a <;> cases b <;> cases carry <;> decide + have proof_bitAddWithWork_value_2 (left : List.{0} Bool) (right : List.{0} Bool) (carry : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitAddWithWork left right carry).1 = + OAI.EditApproximation.bitWordValue left + OAI.EditApproximation.bitWordValue right + carry.toNat := by + induction left generalizing right carry with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork] + induction right generalizing carry with + | nil => cases carry <;> simp [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue] + | cons b bs ih => + simp only [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 false b carry + simp only [Bool.toNat_false] at h + omega + | cons a as ih => + cases right with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a false carry + simp only [Bool.toNat_false] at h + omega + | cons b bs => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a b carry + omega + have proof_bitCeilDivWithWork_value_30 (divisor : List.{0} Bool) (bits : List.{0} Bool) (hd : LT.lt.{0} 0 (OAI.EditApproximation.bitWordValue divisor)) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitCeilDivWithWork divisor bits).1 = + ⌈((OAI.EditApproximation.bitWordValue bits : ℚ) / OAI.EditApproximation.bitWordValue divisor)⌉₊ := by + let q := OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).1 + let r := OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 + have h := proof_bitDivModWithWork_value_23 divisor bits hd + have heq : OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * q + r := h.1 + have hr : r < OAI.EditApproximation.bitWordValue divisor := h.2 + have hdQ : (0 : ℚ) < OAI.EditApproximation.bitWordValue divisor := by exact_mod_cast hd + unfold OAI.EditApproximation.bitCeilDivWithWork + dsimp only + split_ifs with hz + · have hr0 : r = 0 := by + exact (proof_bitCompareWithWork_eq_3 (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 []).1 hz + have hratio : (OAI.EditApproximation.bitWordValue bits : ℚ) / OAI.EditApproximation.bitWordValue divisor = (q : ℚ) := by + apply (div_eq_iff hdQ.ne').mpr + exact_mod_cast (show OAI.EditApproximation.bitWordValue bits = q * OAI.EditApproximation.bitWordValue divisor by nlinarith only [heq, hr0]) + rw [hratio] + exact (Nat.ceil_natCast q).symm + · have hr0 : r ≠ 0 := by + intro hzero + exact hz ((proof_bitCompareWithWork_eq_3 (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 []).2 hzero) + rw [proof_bitAddWithWork_value_2] + change q + 1 + 0 = _ + simp only [Nat.add_zero] + symm + apply (Nat.ceil_eq_iff (by omega : q + 1 ≠ 0)).mpr + constructor + · simp only [Nat.add_sub_cancel] + rw [lt_div_iff₀ hdQ] + exact_mod_cast (show q * OAI.EditApproximation.bitWordValue divisor < OAI.EditApproximation.bitWordValue bits by + nlinarith only [heq, Nat.pos_of_ne_zero hr0]) + · rw [div_le_iff₀ hdQ] + push_cast + exact_mod_cast (show OAI.EditApproximation.bitWordValue bits ≤ (q + 1) * OAI.EditApproximation.bitWordValue divisor by nlinarith only [heq, hr]) + have proof_naturalCeilingWithWork_value_31 (a : OAI.EditApproximation.BinaryFraction) : + OAI.EditApproximation.bitWordValue (a.naturalCeilingWithWork).1 = ⌈a.value⌉₊ := by + cases hs : a.numerator.negative + · simpa only [OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork, hs, Bool.false_eq_true, ↓reduceIte, + OAI.EditApproximation.BinaryFraction.value, OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, Int.cast_natCast] using + proof_bitCeilDivWithWork_value_30 a.denominator a.numerator.bits a.denominator_pos + · have hn : a.value ≤ 0 := by + (simp only [OAI.EditApproximation.BinaryFraction.value, OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hs, ↓reduceIte, Int.cast_neg, Int.cast_natCast]) + exact div_nonpos_of_nonpos_of_nonneg (neg_nonpos.mpr (Nat.cast_nonneg _)) (Nat.cast_nonneg _) + (simp only [OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork, hs, ↓reduceIte, OAI.EditApproximation.bitWordValue]) + exact (Nat.ceil_eq_zero.mpr hn).symm + have proof_representation_value_32 (a : OAI.EditApproximation.BinaryFraction) : a.representation.value = a.value := rfl + have proof_eq_of_num_den_33 {a : OAI.EditApproximation.UnreducedRational} {b : OAI.EditApproximation.UnreducedRational} (hnum : Eq.{1} a.num b.num) (hden : Eq.{1} a.den b.den) : a = b := by + cases a + cases b + cases hnum + cases hden + rfl + have proof_trimBitWordWithWork_value_6 (bits : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.trimBitWordWithWork bits).1 = OAI.EditApproximation.bitWordValue bits := by + induction bits with + | nil => rfl + | cons bit bits ih => + simp only [OAI.EditApproximation.trimBitWordWithWork] + split_ifs with h + · have ht : OAI.EditApproximation.bitWordValue bits = 0 := by rw [← ih, h.1]; rfl + simp [h.2, OAI.EditApproximation.bitWordValue, ht] + · (simp only [OAI.EditApproximation.bitWordValue, ih]) + have proof_canonicalizeWithWork_representation_34 (a : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.canonicalizeWithWork a).1.representation = a.representation := by + apply proof_eq_of_num_den_33 + · (simp only [OAI.EditApproximation.BinaryFraction.canonicalizeWithWork, OAI.EditApproximation.BinaryFraction.representation, OAI.EditApproximation.SignedBinary.value, proof_trimBitWordWithWork_value_6]) + · exact proof_trimBitWordWithWork_value_6 a.denominator + have proof_bitMulWithWork_value_0 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitMulWithWork left right).1 = OAI.EditApproximation.bitWordValue left * OAI.EditApproximation.bitWordValue right := by + induction left with + | nil => simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue] + | cons bit bits ih => + cases bit <;> simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue, proof_bitAddWithWork_value_2, ih] <;> ring + have proof_mulWithWork_value_35 (a : OAI.EditApproximation.SignedBinary) (b : OAI.EditApproximation.SignedBinary) : + (a.mulWithWork b).1.value = a.value * b.value := by + simp only [OAI.EditApproximation.SignedBinary.mulWithWork, OAI.EditApproximation.SignedBinary.value, proof_bitMulWithWork_value_0] + cases a.negative <;> cases b.negative <;> simp [OAI.EditApproximation.signedMagnitude] + have proof_mulWithWork_representation_36 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (a.mulWithWork b).1.representation = a.representation.mul b.representation := by + apply proof_eq_of_num_den_33 + · exact proof_mulWithWork_value_35 a.numerator b.numerator + · exact proof_bitMulWithWork_value_0 a.denominator b.denominator + have proof_canonicalMulWithWork_representation_37 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork a b).1.representation = a.representation.mul b.representation := by + rw [OAI.EditApproximation.BinaryFraction.canonicalMulWithWork, proof_canonicalizeWithWork_representation_34, proof_mulWithWork_representation_36] + have proof_zero_representation_38 : OAI.EditApproximation.BinaryFraction.zero.representation = OAI.EditApproximation.UnreducedRational.zero := by + apply proof_eq_of_num_den_33 <;> rfl + have proof_invWithWork_representation_39 (a : OAI.EditApproximation.BinaryFraction) : + (a.invWithWork).1.representation = a.representation.inv := by + unfold OAI.EditApproximation.BinaryFraction.invWithWork + dsimp only + split_ifs with h + · have hz : OAI.EditApproximation.bitWordValue a.numerator.bits = 0 := by + simpa only [OAI.EditApproximation.bitWordValue] using (proof_bitCompareWithWork_eq_3 a.numerator.bits []).1 h + have hv : a.numerator.value = 0 := by (simp [OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hz]) + (simp only [OAI.EditApproximation.UnreducedRational.inv, OAI.EditApproximation.BinaryFraction.representation, hv, ↓reduceDIte]) + exact proof_zero_representation_38 + · have hn : OAI.EditApproximation.bitWordValue a.numerator.bits ≠ 0 := by + intro hz + exact h ((proof_bitCompareWithWork_eq_3 a.numerator.bits []).2 (by simpa [OAI.EditApproximation.bitWordValue] using hz)) + have hv : a.numerator.value ≠ 0 := by + cases hs : a.numerator.negative <;> (simp [OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hs, hn]) + (simp only [OAI.EditApproximation.UnreducedRational.inv, OAI.EditApproximation.BinaryFraction.representation, hv, ↓reduceDIte]) + apply proof_eq_of_num_den_33 + · cases hs : a.numerator.negative <;> + simp [OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hs, Int.sign_natCast_of_ne_zero hn] + · cases hs : a.numerator.negative <;> (simp [OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hs]) + have proof_divWithWork_representation_40 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (a.divWithWork b).1.representation = a.representation.div b.representation := by + (simp only [OAI.EditApproximation.BinaryFraction.divWithWork, proof_canonicalMulWithWork_representation_37, proof_invWithWork_representation_39, + OAI.EditApproximation.UnreducedRational.div]) + have proof_value_mul_41 (a : OAI.EditApproximation.UnreducedRational) (b : OAI.EditApproximation.UnreducedRational) : (a.mul b).value = a.value * b.value := by + simp [OAI.EditApproximation.UnreducedRational.mul, OAI.EditApproximation.UnreducedRational.value, mul_div_mul_comm] + have proof_value_inv_42 (a : OAI.EditApproximation.UnreducedRational) : a.inv.value = a.value⁻¹ := by + by_cases h : a.num = 0 + · simp [OAI.EditApproximation.UnreducedRational.inv, h, OAI.EditApproximation.UnreducedRational.value, OAI.EditApproximation.UnreducedRational.zero] + · have hn : (a.num.natAbs : ℚ) ≠ 0 := by exact_mod_cast (Int.natAbs_pos.mpr h).ne' + have hd : (a.den : ℚ) ≠ 0 := by exact_mod_cast a.den_pos.ne' + have hsign : ((a.num.sign : ℤ) : ℚ) * a.num = (a.num.natAbs : ℚ) := by + simpa only [Int.cast_mul, Int.cast_natCast] using + congrArg (fun z : ℤ => (z : ℚ)) (Int.sign_mul_self_eq_natAbs a.num) + simp only [OAI.EditApproximation.UnreducedRational.inv, h, ↓reduceDIte, OAI.EditApproximation.UnreducedRational.value] + push_cast + apply eq_inv_of_mul_eq_one_left + field_simp [hn, hd] + exact hsign + have proof_value_div_43 (a : OAI.EditApproximation.UnreducedRational) (b : OAI.EditApproximation.UnreducedRational) : (a.div b).value = a.value / b.value := by + simp [proof_value_mul_41, proof_value_inv_42, OAI.EditApproximation.UnreducedRational.div, div_eq_mul_inv] + have proof_divWithWork_value_44 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.divWithWork a b).1.value = a.value / b.value := by + rw [← proof_representation_value_32, proof_divWithWork_representation_40, + proof_value_div_43, proof_representation_value_32, proof_representation_value_32] + have proof_canonicalMulWithWork_value_45 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork a b).1.value = a.value * b.value := by + rw [← proof_representation_value_32, proof_canonicalMulWithWork_representation_37, + proof_value_mul_41, proof_representation_value_32, proof_representation_value_32] + have proof_value_ofInt_46 (a : ℤ) : (OAI.EditApproximation.SignedBinary.ofInt a).value = a := by + by_cases h : a < 0 + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_true, + ↓reduceIte] using (Int.eq_neg_natAbs_of_nonpos (le_of_lt h)).symm + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_false, + Bool.false_eq_true, ↓reduceIte] using (Int.eq_natAbs_of_nonneg (le_of_not_gt h)).symm + have proof_nat_representation_47 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).representation = OAI.EditApproximation.UnreducedRational.nat n := by + apply proof_eq_of_num_den_33 + · change (OAI.EditApproximation.SignedBinary.ofInt (n : ℤ)).value = (n : ℤ) + exact proof_value_ofInt_46 _ + · rfl + have proof_value_nat_48 (n : ℕ) : (OAI.EditApproximation.UnreducedRational.nat n).value = n := by (simp [OAI.EditApproximation.UnreducedRational.nat, OAI.EditApproximation.UnreducedRational.value]) + have proof_nat_value_49 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).value = (n : ℚ) := by + rw [← proof_representation_value_32, proof_nat_representation_47, proof_value_nat_48] + have proof_groupSampleCountWithWork_value_28 (M : ℕ) (Q : ℕ) (b : ℕ) (h : OAI.EditApproximation.BinaryFraction) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.BinaryFraction.groupSampleCountWithWork M Q b h).1 = OAI.EditApproximation.groupSampleCount M Q b h.value := by + simp only [OAI.EditApproximation.BinaryFraction.groupSampleCountWithWork, proof_wordMinWithWork_value_29, proof_bitWordValue_bits_15, + proof_naturalCeilingWithWork_value_31, proof_divWithWork_value_44, proof_canonicalMulWithWork_value_45, + proof_nat_value_49, OAI.EditApproximation.groupSampleCount] + have proof_queryScaleAt_value_88 (words : List.{0} OAI.EditApproximation.BinaryFraction) (scales : List.{0} ℚ) (h : Eq.{1} (List.map.{0, 0} OAI.EditApproximation.BinaryFraction.value words) scales) (i : Fin (List.length.{0} scales)) : + (OAI.EditApproximation.BinaryFraction.queryScaleAt words scales h i).value = scales[i.val] := by + subst scales + simp only [OAI.EditApproximation.BinaryFraction.queryScaleAt, List.getElem_map] + exact + let word := OAI.EditApproximation.BinaryFraction.queryScaleAt raw (OAI.EditApproximation.groupDyadicScales M b F) hs scale + let count := OAI.EditApproximation.BinaryFraction.groupSampleCountWithWork M Q b word + let hc : OAI.EditApproximation.bitWordValue count.1 = OAI.EditApproximation.groupSampleCount M Q b (OAI.EditApproximation.groupDyadicScaleAt M b F scale) := by + rw [proof_groupSampleCountWithWork_value_28, proof_queryScaleAt_value_88] + rfl + let coordinates := OAI.EditApproximation.queryFinRange (OAI.EditApproximation.bitWordValue count.1) + (OAI.EditApproximation.groupSampleCount M Q b (OAI.EditApproximation.groupDyadicScaleAt M b F scale)) hc + let labeled := OAI.EditApproximation.arithmeticMapWithWork (fun sample => + ((⟨(b, cell), scale, sample⟩ : OAI.EditApproximation.GroupScalarKey M F Q), 2)) coordinates + (labeled.1, raw.length + count.2 + labeled.2 + coordinates.length + 3) + +def groupKeySampleBlockAllocation {M F Q : ℕ} (b : ℕ) (raw : List OAI.EditApproximation.BinaryFraction) + (hs : raw.map OAI.EditApproximation.BinaryFraction.value = OAI.EditApproximation.groupDyadicScales M b F) (_cell : ℕ × ℕ) + (scale : Fin (OAI.EditApproximation.groupDyadicScales M b F).length) : ℕ := by + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_wordLEWithWork_value_26 (a : List.{0} Bool) (b : List.{0} Bool) : + (OAI.EditApproximation.wordLEWithWork a b).1 = true ↔ OAI.EditApproximation.bitWordValue a ≤ OAI.EditApproximation.bitWordValue b := by + simp only [OAI.EditApproximation.wordLEWithWork, Bool.not_eq_true', decide_eq_false_iff_not, + proof_bitCompareWithWork_lt_16, not_lt] + have proof_wordMinWithWork_value_29 (a : List.{0} Bool) (b : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.wordMinWithWork a b).1 = min (OAI.EditApproximation.bitWordValue a) (OAI.EditApproximation.bitWordValue b) := by + unfold OAI.EditApproximation.wordMinWithWork + dsimp only + split_ifs with h + · exact (min_eq_left ((proof_wordLEWithWork_value_26 a b).mp h)).symm + · exact (min_eq_right (le_of_not_ge (fun hle => h ((proof_wordLEWithWork_value_26 a b).mpr hle)))).symm + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_bitSubtractor_value_17 (a : Bool) (b : Bool) (borrow : Bool) : + a.toNat + 2 * (OAI.EditApproximation.bitBorrow a b borrow).toNat = + b.toNat + borrow.toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat := by + cases a <;> cases b <;> cases borrow <;> decide + have proof_bitSubtractionRippleEquation_18 (a : ℕ) (b : ℕ) (borrow : ℕ) (nextBorrow : ℕ) (difference : ℕ) (left : ℕ) (right : ℕ) (result : ℕ) (tail : ℕ) (htail : Eq.{1} (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} result right) nextBorrow) (HAdd.hAdd.{0, 0, 0} left tail)) (hbit : Eq.{1} (HAdd.hAdd.{0, 0, 0} a (HMul.hMul.{0, 0, 0} 2 nextBorrow)) + (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} b borrow) difference)) : + (difference + 2 * result) + (b + 2 * right) + borrow = + (a + 2 * left) + 2 * tail := by + omega + have proof_bitSubtractWithWork_value_19 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right borrow).1 + OAI.EditApproximation.bitWordValue right + borrow.toNat = + OAI.EditApproximation.bitWordValue left + 2 ^ max left.length right.length * + (OAI.EditApproximation.bitSubtractWithWork left right borrow).2.1.toNat := by + induction left generalizing right borrow with + | nil => + induction right generalizing borrow with + | nil => (simp [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + have h := ih (OAI.EditApproximation.bitBorrow false b borrow) + have hb := proof_bitSubtractor_value_17 false b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue, + List.length_nil, List.length_cons, Nat.zero_max, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 0 b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow false b borrow).toNat + (OAI.EditApproximation.bitDifference false b borrow).toNat 0 (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).1) + (2 ^ bs.length * (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons a as ih => + cases right with + | nil => + have h := ih [] (OAI.EditApproximation.bitBorrow a false borrow) + have hb := proof_bitSubtractor_value_17 a false borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_nil, List.length_cons, + Nat.max_zero, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat 0 borrow.toNat (OAI.EditApproximation.bitBorrow a false borrow).toNat + (OAI.EditApproximation.bitDifference a false borrow).toNat (OAI.EditApproximation.bitWordValue as) 0 + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).1) + (2 ^ as.length * (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons b bs => + have h := ih bs (OAI.EditApproximation.bitBorrow a b borrow) + have hb := proof_bitSubtractor_value_17 a b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_cons, Nat.succ_max_succ, + pow_succ] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow a b borrow).toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).1) + (2 ^ max as.length bs.length * (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_assoc, Nat.mul_left_comm] using hs + have proof_bitWordValue_lt_pow_length_20 (bits : List.{0} Bool) : OAI.EditApproximation.bitWordValue bits < 2 ^ bits.length := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitWordValue]) + | cons bit bits ih => + cases bit <;> (simp only [OAI.EditApproximation.bitWordValue, List.length_cons, pow_succ, Bool.toNat_false, Bool.toNat_true]) <;> omega + have proof_bitSubtractWithWork_length_21 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + (OAI.EditApproximation.bitSubtractWithWork left right borrow).1.length = max left.length right.length := by + induction left generalizing right borrow with + | nil => + simp only [OAI.EditApproximation.bitSubtractWithWork] + induction right generalizing borrow with + | nil => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork] + | cons b bs ih => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork, ih] + | cons a as ih => + cases right with + | nil => simp [OAI.EditApproximation.bitSubtractWithWork, ih] + | cons b bs => simp [OAI.EditApproximation.bitSubtractWithWork, ih, Nat.succ_max_succ] + have proof_bitSubtractWithWork_sub_22 (left : List.{0} Bool) (right : List.{0} Bool) (h : LE.le.{0} (OAI.EditApproximation.bitWordValue right) (OAI.EditApproximation.bitWordValue left)) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right false).1 = OAI.EditApproximation.bitWordValue left - OAI.EditApproximation.bitWordValue right := by + have hvalue := proof_bitSubtractWithWork_value_19 left right false + have hlt := proof_bitWordValue_lt_pow_length_20 (OAI.EditApproximation.bitSubtractWithWork left right false).1 + rw [proof_bitSubtractWithWork_length_21] at hlt + cases hb : (OAI.EditApproximation.bitSubtractWithWork left right false).2.1 + · simp only [hb, Bool.toNat_false, Nat.mul_zero, Nat.add_zero] at hvalue + omega + · simp only [hb, Bool.toNat_true, Bool.toNat_false, Nat.mul_one, Nat.add_zero] at hvalue + omega + have proof_bitDivModWithWork_value_23 (divisor : List.{0} Bool) (bits : List.{0} Bool) (hd : LT.lt.{0} 0 (OAI.EditApproximation.bitWordValue divisor)) : + OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).1 + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 < OAI.EditApproximation.bitWordValue divisor := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitDivModWithWork, OAI.EditApproximation.bitWordValue, hd]) + | cons bit bits ih => + let previous := OAI.EditApproximation.bitDivModWithWork divisor bits + let candidate := bit :: previous.2.1 + have hp : OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue previous.1 + + OAI.EditApproximation.bitWordValue previous.2.1 := ih.1 + have hr : OAI.EditApproximation.bitWordValue previous.2.1 < OAI.EditApproximation.bitWordValue divisor := ih.2 + have hc : OAI.EditApproximation.bitWordValue candidate < 2 * OAI.EditApproximation.bitWordValue divisor := by + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + cases bit <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega + by_cases hlt : (OAI.EditApproximation.bitCompareWithWork candidate divisor).1 = .lt + · have hv := (proof_bitCompareWithWork_lt_16 candidate divisor).1 hlt + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 = .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * + OAI.EditApproximation.bitWordValue (false :: previous.1) + OAI.EditApproximation.bitWordValue candidate ∧ OAI.EditApproximation.bitWordValue candidate < _ + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_false]) + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + nlinarith only [hp] + · exact hv + · have hv : OAI.EditApproximation.bitWordValue divisor ≤ OAI.EditApproximation.bitWordValue candidate := by + exact Nat.le_of_not_gt (fun h => hlt ((proof_bitCompareWithWork_lt_16 candidate divisor).2 h)) + have hs := proof_bitSubtractWithWork_sub_22 candidate divisor hv + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 ≠ .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (true :: previous.1) + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 < _ + rw [hs] + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_true]) + have he := Nat.sub_add_cancel hv + dsimp only [candidate, OAI.EditApproximation.bitWordValue] at he ⊢ + nlinarith only [hp, he] + · omega + have proof_bitCompareWithWork_eq_3 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .eq ↔ OAI.EditApproximation.bitWordValue left = OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_bitAdder_value_1 (a : Bool) (b : Bool) (carry : Bool) : + (OAI.EditApproximation.bitSum a b carry).toNat + 2 * (OAI.EditApproximation.bitCarry a b carry).toNat = + a.toNat + b.toNat + carry.toNat := by + cases a <;> cases b <;> cases carry <;> decide + have proof_bitAddWithWork_value_2 (left : List.{0} Bool) (right : List.{0} Bool) (carry : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitAddWithWork left right carry).1 = + OAI.EditApproximation.bitWordValue left + OAI.EditApproximation.bitWordValue right + carry.toNat := by + induction left generalizing right carry with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork] + induction right generalizing carry with + | nil => cases carry <;> simp [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue] + | cons b bs ih => + simp only [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 false b carry + simp only [Bool.toNat_false] at h + omega + | cons a as ih => + cases right with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a false carry + simp only [Bool.toNat_false] at h + omega + | cons b bs => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a b carry + omega + have proof_bitCeilDivWithWork_value_30 (divisor : List.{0} Bool) (bits : List.{0} Bool) (hd : LT.lt.{0} 0 (OAI.EditApproximation.bitWordValue divisor)) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitCeilDivWithWork divisor bits).1 = + ⌈((OAI.EditApproximation.bitWordValue bits : ℚ) / OAI.EditApproximation.bitWordValue divisor)⌉₊ := by + let q := OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).1 + let r := OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 + have h := proof_bitDivModWithWork_value_23 divisor bits hd + have heq : OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * q + r := h.1 + have hr : r < OAI.EditApproximation.bitWordValue divisor := h.2 + have hdQ : (0 : ℚ) < OAI.EditApproximation.bitWordValue divisor := by exact_mod_cast hd + unfold OAI.EditApproximation.bitCeilDivWithWork + dsimp only + split_ifs with hz + · have hr0 : r = 0 := by + exact (proof_bitCompareWithWork_eq_3 (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 []).1 hz + have hratio : (OAI.EditApproximation.bitWordValue bits : ℚ) / OAI.EditApproximation.bitWordValue divisor = (q : ℚ) := by + apply (div_eq_iff hdQ.ne').mpr + exact_mod_cast (show OAI.EditApproximation.bitWordValue bits = q * OAI.EditApproximation.bitWordValue divisor by nlinarith only [heq, hr0]) + rw [hratio] + exact (Nat.ceil_natCast q).symm + · have hr0 : r ≠ 0 := by + intro hzero + exact hz ((proof_bitCompareWithWork_eq_3 (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 []).2 hzero) + rw [proof_bitAddWithWork_value_2] + change q + 1 + 0 = _ + simp only [Nat.add_zero] + symm + apply (Nat.ceil_eq_iff (by omega : q + 1 ≠ 0)).mpr + constructor + · simp only [Nat.add_sub_cancel] + rw [lt_div_iff₀ hdQ] + exact_mod_cast (show q * OAI.EditApproximation.bitWordValue divisor < OAI.EditApproximation.bitWordValue bits by + nlinarith only [heq, Nat.pos_of_ne_zero hr0]) + · rw [div_le_iff₀ hdQ] + push_cast + exact_mod_cast (show OAI.EditApproximation.bitWordValue bits ≤ (q + 1) * OAI.EditApproximation.bitWordValue divisor by nlinarith only [heq, hr]) + have proof_naturalCeilingWithWork_value_31 (a : OAI.EditApproximation.BinaryFraction) : + OAI.EditApproximation.bitWordValue (a.naturalCeilingWithWork).1 = ⌈a.value⌉₊ := by + cases hs : a.numerator.negative + · simpa only [OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork, hs, Bool.false_eq_true, ↓reduceIte, + OAI.EditApproximation.BinaryFraction.value, OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, Int.cast_natCast] using + proof_bitCeilDivWithWork_value_30 a.denominator a.numerator.bits a.denominator_pos + · have hn : a.value ≤ 0 := by + (simp only [OAI.EditApproximation.BinaryFraction.value, OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hs, ↓reduceIte, Int.cast_neg, Int.cast_natCast]) + exact div_nonpos_of_nonpos_of_nonneg (neg_nonpos.mpr (Nat.cast_nonneg _)) (Nat.cast_nonneg _) + (simp only [OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork, hs, ↓reduceIte, OAI.EditApproximation.bitWordValue]) + exact (Nat.ceil_eq_zero.mpr hn).symm + have proof_representation_value_32 (a : OAI.EditApproximation.BinaryFraction) : a.representation.value = a.value := rfl + have proof_eq_of_num_den_33 {a : OAI.EditApproximation.UnreducedRational} {b : OAI.EditApproximation.UnreducedRational} (hnum : Eq.{1} a.num b.num) (hden : Eq.{1} a.den b.den) : a = b := by + cases a + cases b + cases hnum + cases hden + rfl + have proof_trimBitWordWithWork_value_6 (bits : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.trimBitWordWithWork bits).1 = OAI.EditApproximation.bitWordValue bits := by + induction bits with + | nil => rfl + | cons bit bits ih => + simp only [OAI.EditApproximation.trimBitWordWithWork] + split_ifs with h + · have ht : OAI.EditApproximation.bitWordValue bits = 0 := by rw [← ih, h.1]; rfl + simp [h.2, OAI.EditApproximation.bitWordValue, ht] + · (simp only [OAI.EditApproximation.bitWordValue, ih]) + have proof_canonicalizeWithWork_representation_34 (a : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.canonicalizeWithWork a).1.representation = a.representation := by + apply proof_eq_of_num_den_33 + · (simp only [OAI.EditApproximation.BinaryFraction.canonicalizeWithWork, OAI.EditApproximation.BinaryFraction.representation, OAI.EditApproximation.SignedBinary.value, proof_trimBitWordWithWork_value_6]) + · exact proof_trimBitWordWithWork_value_6 a.denominator + have proof_bitMulWithWork_value_0 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitMulWithWork left right).1 = OAI.EditApproximation.bitWordValue left * OAI.EditApproximation.bitWordValue right := by + induction left with + | nil => simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue] + | cons bit bits ih => + cases bit <;> simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue, proof_bitAddWithWork_value_2, ih] <;> ring + have proof_mulWithWork_value_35 (a : OAI.EditApproximation.SignedBinary) (b : OAI.EditApproximation.SignedBinary) : + (a.mulWithWork b).1.value = a.value * b.value := by + simp only [OAI.EditApproximation.SignedBinary.mulWithWork, OAI.EditApproximation.SignedBinary.value, proof_bitMulWithWork_value_0] + cases a.negative <;> cases b.negative <;> simp [OAI.EditApproximation.signedMagnitude] + have proof_mulWithWork_representation_36 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (a.mulWithWork b).1.representation = a.representation.mul b.representation := by + apply proof_eq_of_num_den_33 + · exact proof_mulWithWork_value_35 a.numerator b.numerator + · exact proof_bitMulWithWork_value_0 a.denominator b.denominator + have proof_canonicalMulWithWork_representation_37 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork a b).1.representation = a.representation.mul b.representation := by + rw [OAI.EditApproximation.BinaryFraction.canonicalMulWithWork, proof_canonicalizeWithWork_representation_34, proof_mulWithWork_representation_36] + have proof_zero_representation_38 : OAI.EditApproximation.BinaryFraction.zero.representation = OAI.EditApproximation.UnreducedRational.zero := by + apply proof_eq_of_num_den_33 <;> rfl + have proof_invWithWork_representation_39 (a : OAI.EditApproximation.BinaryFraction) : + (a.invWithWork).1.representation = a.representation.inv := by + unfold OAI.EditApproximation.BinaryFraction.invWithWork + dsimp only + split_ifs with h + · have hz : OAI.EditApproximation.bitWordValue a.numerator.bits = 0 := by + simpa only [OAI.EditApproximation.bitWordValue] using (proof_bitCompareWithWork_eq_3 a.numerator.bits []).1 h + have hv : a.numerator.value = 0 := by (simp [OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hz]) + (simp only [OAI.EditApproximation.UnreducedRational.inv, OAI.EditApproximation.BinaryFraction.representation, hv, ↓reduceDIte]) + exact proof_zero_representation_38 + · have hn : OAI.EditApproximation.bitWordValue a.numerator.bits ≠ 0 := by + intro hz + exact h ((proof_bitCompareWithWork_eq_3 a.numerator.bits []).2 (by simpa [OAI.EditApproximation.bitWordValue] using hz)) + have hv : a.numerator.value ≠ 0 := by + cases hs : a.numerator.negative <;> (simp [OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hs, hn]) + (simp only [OAI.EditApproximation.UnreducedRational.inv, OAI.EditApproximation.BinaryFraction.representation, hv, ↓reduceDIte]) + apply proof_eq_of_num_den_33 + · cases hs : a.numerator.negative <;> + simp [OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hs, Int.sign_natCast_of_ne_zero hn] + · cases hs : a.numerator.negative <;> (simp [OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hs]) + have proof_divWithWork_representation_40 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (a.divWithWork b).1.representation = a.representation.div b.representation := by + (simp only [OAI.EditApproximation.BinaryFraction.divWithWork, proof_canonicalMulWithWork_representation_37, proof_invWithWork_representation_39, + OAI.EditApproximation.UnreducedRational.div]) + have proof_value_mul_41 (a : OAI.EditApproximation.UnreducedRational) (b : OAI.EditApproximation.UnreducedRational) : (a.mul b).value = a.value * b.value := by + simp [OAI.EditApproximation.UnreducedRational.mul, OAI.EditApproximation.UnreducedRational.value, mul_div_mul_comm] + have proof_value_inv_42 (a : OAI.EditApproximation.UnreducedRational) : a.inv.value = a.value⁻¹ := by + by_cases h : a.num = 0 + · simp [OAI.EditApproximation.UnreducedRational.inv, h, OAI.EditApproximation.UnreducedRational.value, OAI.EditApproximation.UnreducedRational.zero] + · have hn : (a.num.natAbs : ℚ) ≠ 0 := by exact_mod_cast (Int.natAbs_pos.mpr h).ne' + have hd : (a.den : ℚ) ≠ 0 := by exact_mod_cast a.den_pos.ne' + have hsign : ((a.num.sign : ℤ) : ℚ) * a.num = (a.num.natAbs : ℚ) := by + simpa only [Int.cast_mul, Int.cast_natCast] using + congrArg (fun z : ℤ => (z : ℚ)) (Int.sign_mul_self_eq_natAbs a.num) + simp only [OAI.EditApproximation.UnreducedRational.inv, h, ↓reduceDIte, OAI.EditApproximation.UnreducedRational.value] + push_cast + apply eq_inv_of_mul_eq_one_left + field_simp [hn, hd] + exact hsign + have proof_value_div_43 (a : OAI.EditApproximation.UnreducedRational) (b : OAI.EditApproximation.UnreducedRational) : (a.div b).value = a.value / b.value := by + simp [proof_value_mul_41, proof_value_inv_42, OAI.EditApproximation.UnreducedRational.div, div_eq_mul_inv] + have proof_divWithWork_value_44 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.divWithWork a b).1.value = a.value / b.value := by + rw [← proof_representation_value_32, proof_divWithWork_representation_40, + proof_value_div_43, proof_representation_value_32, proof_representation_value_32] + have proof_canonicalMulWithWork_value_45 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork a b).1.value = a.value * b.value := by + rw [← proof_representation_value_32, proof_canonicalMulWithWork_representation_37, + proof_value_mul_41, proof_representation_value_32, proof_representation_value_32] + have proof_value_ofInt_46 (a : ℤ) : (OAI.EditApproximation.SignedBinary.ofInt a).value = a := by + by_cases h : a < 0 + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_true, + ↓reduceIte] using (Int.eq_neg_natAbs_of_nonpos (le_of_lt h)).symm + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_false, + Bool.false_eq_true, ↓reduceIte] using (Int.eq_natAbs_of_nonneg (le_of_not_gt h)).symm + have proof_nat_representation_47 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).representation = OAI.EditApproximation.UnreducedRational.nat n := by + apply proof_eq_of_num_den_33 + · change (OAI.EditApproximation.SignedBinary.ofInt (n : ℤ)).value = (n : ℤ) + exact proof_value_ofInt_46 _ + · rfl + have proof_value_nat_48 (n : ℕ) : (OAI.EditApproximation.UnreducedRational.nat n).value = n := by (simp [OAI.EditApproximation.UnreducedRational.nat, OAI.EditApproximation.UnreducedRational.value]) + have proof_nat_value_49 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).value = (n : ℚ) := by + rw [← proof_representation_value_32, proof_nat_representation_47, proof_value_nat_48] + have proof_groupSampleCountWithWork_value_28 (M : ℕ) (Q : ℕ) (b : ℕ) (h : OAI.EditApproximation.BinaryFraction) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.BinaryFraction.groupSampleCountWithWork M Q b h).1 = OAI.EditApproximation.groupSampleCount M Q b h.value := by + simp only [OAI.EditApproximation.BinaryFraction.groupSampleCountWithWork, proof_wordMinWithWork_value_29, proof_bitWordValue_bits_15, + proof_naturalCeilingWithWork_value_31, proof_divWithWork_value_44, proof_canonicalMulWithWork_value_45, + proof_nat_value_49, OAI.EditApproximation.groupSampleCount] + have proof_queryScaleAt_value_88 (words : List.{0} OAI.EditApproximation.BinaryFraction) (scales : List.{0} ℚ) (h : Eq.{1} (List.map.{0, 0} OAI.EditApproximation.BinaryFraction.value words) scales) (i : Fin (List.length.{0} scales)) : + (OAI.EditApproximation.BinaryFraction.queryScaleAt words scales h i).value = scales[i.val] := by + subst scales + simp only [OAI.EditApproximation.BinaryFraction.queryScaleAt, List.getElem_map] + exact + let word := OAI.EditApproximation.BinaryFraction.queryScaleAt raw (OAI.EditApproximation.groupDyadicScales M b F) hs scale + let count := OAI.EditApproximation.BinaryFraction.groupSampleCountWithWork M Q b word + let hc : OAI.EditApproximation.bitWordValue count.1 = OAI.EditApproximation.groupSampleCount M Q b (OAI.EditApproximation.groupDyadicScaleAt M b F scale) := by + rw [proof_groupSampleCountWithWork_value_28, proof_queryScaleAt_value_88] + rfl + let coordinates := OAI.EditApproximation.queryFinRange (OAI.EditApproximation.bitWordValue count.1) + (OAI.EditApproximation.groupSampleCount M Q b (OAI.EditApproximation.groupDyadicScaleAt M b F scale)) hc + OAI.EditApproximation.BinaryFraction.groupSampleCountAllocation M Q b word + OAI.EditApproximation.arithmeticMapAllocation (fun _ => 2) coordinates + + 2 * coordinates.length + +def querySharedCellInputsAllocation {nx ny : ℕ} (M F Q eM eb eF : ℕ) + (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (parent : OAI.EditApproximation.TargetInterval nx) + (exponent : ℕ) (cell : ℕ × ℕ) + (draw : ∀ scale : Fin (OAI.EditApproximation.groupDyadicScales M (2 ^ eb) F).length, + Fin (OAI.EditApproximation.groupSampleCount M Q (2 ^ eb) (OAI.EditApproximation.groupDyadicScaleAt M (2 ^ eb) F scale)) → Fin M × ℕ) + (allocation : ∀ scale : Fin (OAI.EditApproximation.groupDyadicScales M (2 ^ eb) F).length, + Fin (OAI.EditApproximation.groupSampleCount M Q (2 ^ eb) (OAI.EditApproximation.groupDyadicScaleAt M (2 ^ eb) F scale)) → ℕ) : ℕ := by + have proof_representation_value_32 (a : OAI.EditApproximation.BinaryFraction) : a.representation.value = a.value := rfl + have proof_eq_of_num_den_33 {a : OAI.EditApproximation.UnreducedRational} {b : OAI.EditApproximation.UnreducedRational} (hnum : Eq.{1} a.num b.num) (hden : Eq.{1} a.den b.den) : a = b := by + cases a + cases b + cases hnum + cases hden + rfl + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_value_ofInt_46 (a : ℤ) : (OAI.EditApproximation.SignedBinary.ofInt a).value = a := by + by_cases h : a < 0 + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_true, + ↓reduceIte] using (Int.eq_neg_natAbs_of_nonpos (le_of_lt h)).symm + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_false, + Bool.false_eq_true, ↓reduceIte] using (Int.eq_natAbs_of_nonneg (le_of_not_gt h)).symm + have proof_nat_representation_47 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).representation = OAI.EditApproximation.UnreducedRational.nat n := by + apply proof_eq_of_num_den_33 + · change (OAI.EditApproximation.SignedBinary.ofInt (n : ℤ)).value = (n : ℤ) + exact proof_value_ofInt_46 _ + · rfl + have proof_value_nat_48 (n : ℕ) : (OAI.EditApproximation.UnreducedRational.nat n).value = n := by (simp [OAI.EditApproximation.UnreducedRational.nat, OAI.EditApproximation.UnreducedRational.value]) + have proof_nat_value_49 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).value = (n : ℚ) := by + rw [← proof_representation_value_32, proof_nat_representation_47, proof_value_nat_48] + have proof_arithmeticMapWithWork_value_70 {α : Type 0} {β : Type 0} (f : α → Prod.{0, 0} β ℕ) (values : List.{0} α) : + (OAI.EditApproximation.arithmeticMapWithWork f values).1 = values.map (fun a => (f a).1) := by + induction values with + | nil => rfl + | cons a rest ih => simp only [OAI.EditApproximation.arithmeticMapWithWork, ih, List.map_cons] + have proof_powerTwoWord_value_13 (n : ℕ) : OAI.EditApproximation.bitWordValue (OAI.EditApproximation.powerTwoWord n) = 2 ^ n := by + induction n with + | zero => (simp [OAI.EditApproximation.powerTwoWord, OAI.EditApproximation.bitWordValue]) + | succ n ih => + (simp only [OAI.EditApproximation.powerTwoWord, List.replicate_succ, List.cons_append, OAI.EditApproximation.bitWordValue, + Bool.toNat_false, zero_add] at *) + rw [ih, pow_succ] + omega + have proof_inversePowerTwo_value_89 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.inversePowerTwo n).value = (2 : ℚ) ^ (-(n : ℤ)) := by + (simp only [OAI.EditApproximation.BinaryFraction.inversePowerTwo, OAI.EditApproximation.BinaryFraction.value, OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, Bool.false_eq_true, + ↓reduceIte, OAI.EditApproximation.bitWordValue, Bool.toNat_true, + Int.cast_natCast, proof_powerTwoWord_value_13, Nat.cast_pow, Nat.cast_ofNat, zpow_neg, zpow_natCast]) + norm_num [one_div] + have proof_signedPowerTwoWithWork_value_90 (e : ℤ) : + (OAI.EditApproximation.BinaryFraction.signedPowerTwoWithWork e).1.value = (2 : ℚ) ^ e := by + unfold OAI.EditApproximation.BinaryFraction.signedPowerTwoWithWork + split_ifs with h + · change (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.powerTwoWord e.toNat) : ℚ) / 1 = (2 : ℚ) ^ e + rw [div_one, proof_powerTwoWord_value_13, Nat.cast_pow, Nat.cast_ofNat, ← zpow_natCast, + Int.toNat_of_nonneg h] + · rw [proof_inversePowerTwo_value_89, Int.toNat_of_nonneg + (show 0 ≤ -e from neg_nonneg.mpr (le_of_lt (lt_of_not_ge h))), neg_neg] + have proof_groupScalesWithWork_value_91 (eM : ℕ) (eb : ℕ) (eF : ℕ) : + ((OAI.EditApproximation.BinaryFraction.groupScalesWithWork eM eb eF).1.map OAI.EditApproximation.BinaryFraction.value) = + OAI.EditApproximation.groupDyadicScales (2 ^ eM) (2 ^ eb) ((2 : ℚ) ^ eF) := by + have hlower : ((2 ^ eb : ℕ) : ℚ) / (2 ^ eM : ℕ) = (2 : ℚ) ^ ((eb : ℤ) - eM) := by + rw [Nat.cast_pow, Nat.cast_pow, Nat.cast_ofNat, zpow_sub₀ (by norm_num : (2 : ℚ) ≠ 0), + zpow_natCast, zpow_natCast] + have hupper : (64 : ℚ) * (2 : ℚ) ^ eF * (2 ^ eb : ℕ) = + (2 : ℚ) ^ ((6 + eF + eb : ℕ) : ℤ) := by + rw [Nat.cast_pow, Nat.cast_ofNat, zpow_natCast, pow_add, pow_add] + norm_num + have hlog : Int.log 2 ((2 : ℚ) ^ ((6 + eF + eb : ℕ) : ℤ)) = ((6 + eF + eb : ℕ) : ℤ) := by + simpa only [Nat.cast_ofNat] using Int.log_zpow (R := ℚ) (by decide : 1 < 2) ((6 + eF + eb : ℕ) : ℤ) + have hclog : Int.clog 2 ((2 : ℚ) ^ ((eb : ℤ) - eM)) = (eb : ℤ) - eM := by + simpa only [Nat.cast_ofNat] using Int.clog_zpow (R := ℚ) (by decide : 1 < 2) ((eb : ℤ) - eM) + simp only [OAI.EditApproximation.BinaryFraction.groupScalesWithWork, proof_arithmeticMapWithWork_value_70, List.map_map, + Function.comp_def, proof_signedPowerTwoWithWork_value_90, OAI.EditApproximation.groupDyadicScales, hlower, hupper, hlog, hclog] + have proof_computedGroupScales_value_87 (M : ℕ) (b : ℕ) (F : ℕ) (eM : ℕ) (eb : ℕ) (eF : ℕ) (hM : Eq.{1} M (HPow.hPow.{0, 0, 0} 2 eM)) (hb : Eq.{1} b (HPow.hPow.{0, 0, 0} 2 eb)) (hF : Eq.{1} F (HPow.hPow.{0, 0, 0} 2 eF)) : + (OAI.EditApproximation.BinaryFraction.groupScalesWithWork eM eb eF).1.map OAI.EditApproximation.BinaryFraction.value = OAI.EditApproximation.groupDyadicScales M b (OAI.EditApproximation.BinaryFraction.nat F).value := by + rw [proof_nat_value_49, hM, hb, hF, Nat.cast_pow, Nat.cast_ofNat] + exact proof_groupScalesWithWork_value_91 eM eb eF + have proof_queryScaleAt_value_88 (words : List.{0} OAI.EditApproximation.BinaryFraction) (scales : List.{0} ℚ) (h : Eq.{1} (List.map.{0, 0} OAI.EditApproximation.BinaryFraction.value words) scales) (i : Fin (List.length.{0} scales)) : + (OAI.EditApproximation.BinaryFraction.queryScaleAt words scales h i).value = scales[i.val] := by + subst scales + simp only [OAI.EditApproximation.BinaryFraction.queryScaleAt, List.getElem_map] + have proof_queryGroupScaleAt_value_92 (M : ℕ) (b : ℕ) (F : ℕ) (words : List.{0} OAI.EditApproximation.BinaryFraction) (h : Eq.{1} (List.map.{0, 0} OAI.EditApproximation.BinaryFraction.value words) + (OAI.EditApproximation.groupDyadicScales M b ↑F)) (i : Fin (List.length.{0} (OAI.EditApproximation.groupDyadicScales M b ↑F))) : + (OAI.EditApproximation.BinaryFraction.queryScaleAt words (OAI.EditApproximation.groupDyadicScales M b F) h i).value = OAI.EditApproximation.groupDyadicScaleAt M b F i := + proof_queryScaleAt_value_88 words (OAI.EditApproximation.groupDyadicScales M b F) h i + exact + let b := 2 ^ eb + let scales := OAI.EditApproximation.BinaryFraction.groupScalesWithWork eM eb eF + let hs : scales.1.map OAI.EditApproximation.BinaryFraction.value = OAI.EditApproximation.groupDyadicScales M b F := by + simpa only [proof_nat_value_49] using proof_computedGroupScales_value_87 M b F eM eb eF hM rfl hF + let hlen : scales.1.length = (OAI.EditApproximation.groupDyadicScales M b F).length := by + simpa only [List.length_map] using congrArg List.length hs + let indices := OAI.EditApproximation.queryFinRange scales.1.length (OAI.EditApproximation.groupDyadicScales M b F).length hlen + let build := fun scale => + let word := OAI.EditApproximation.BinaryFraction.queryScaleAt scales.1 (OAI.EditApproximation.groupDyadicScales M b F) hs scale + let hv : word.value = OAI.EditApproximation.groupDyadicScaleAt M b F scale := proof_queryGroupScaleAt_value_92 M b F _ hs scale + let states := OAI.EditApproximation.BinaryFraction.queryGroupInputsTransportWithWork (ny := ny) parent b exponent Q cell word + (OAI.EditApproximation.groupDyadicScaleAt M b F scale) hv (draw scale) + (states.1, states.2 + scales.1.length + 1) + OAI.EditApproximation.BinaryFraction.groupScalesAllocation eM eb eF + 2 * scales.1.length + eb + 1 + + OAI.EditApproximation.arithmeticFlatMapAllocation build (fun scale => + let word := OAI.EditApproximation.BinaryFraction.queryScaleAt scales.1 (OAI.EditApproximation.groupDyadicScales M b F) hs scale + let hv : word.value = OAI.EditApproximation.groupDyadicScaleAt M b F scale := proof_queryGroupScaleAt_value_92 M b F _ hs scale + OAI.EditApproximation.BinaryFraction.queryGroupInputsTransportAllocation (ny := ny) parent b exponent Q cell word + (OAI.EditApproximation.groupDyadicScaleAt M b F scale) hv (draw scale) (allocation scale)) indices + +def queryGroupKeySamplesAllocation (M F Q eM eb eF : ℕ) + (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (cell : ℕ × ℕ) : ℕ := by + have proof_representation_value_32 (a : OAI.EditApproximation.BinaryFraction) : a.representation.value = a.value := rfl + have proof_eq_of_num_den_33 {a : OAI.EditApproximation.UnreducedRational} {b : OAI.EditApproximation.UnreducedRational} (hnum : Eq.{1} a.num b.num) (hden : Eq.{1} a.den b.den) : a = b := by + cases a + cases b + cases hnum + cases hden + rfl + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_value_ofInt_46 (a : ℤ) : (OAI.EditApproximation.SignedBinary.ofInt a).value = a := by + by_cases h : a < 0 + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_true, + ↓reduceIte] using (Int.eq_neg_natAbs_of_nonpos (le_of_lt h)).symm + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_false, + Bool.false_eq_true, ↓reduceIte] using (Int.eq_natAbs_of_nonneg (le_of_not_gt h)).symm + have proof_nat_representation_47 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).representation = OAI.EditApproximation.UnreducedRational.nat n := by + apply proof_eq_of_num_den_33 + · change (OAI.EditApproximation.SignedBinary.ofInt (n : ℤ)).value = (n : ℤ) + exact proof_value_ofInt_46 _ + · rfl + have proof_value_nat_48 (n : ℕ) : (OAI.EditApproximation.UnreducedRational.nat n).value = n := by (simp [OAI.EditApproximation.UnreducedRational.nat, OAI.EditApproximation.UnreducedRational.value]) + have proof_nat_value_49 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).value = (n : ℚ) := by + rw [← proof_representation_value_32, proof_nat_representation_47, proof_value_nat_48] + have proof_arithmeticMapWithWork_value_70 {α : Type 0} {β : Type 0} (f : α → Prod.{0, 0} β ℕ) (values : List.{0} α) : + (OAI.EditApproximation.arithmeticMapWithWork f values).1 = values.map (fun a => (f a).1) := by + induction values with + | nil => rfl + | cons a rest ih => simp only [OAI.EditApproximation.arithmeticMapWithWork, ih, List.map_cons] + have proof_powerTwoWord_value_13 (n : ℕ) : OAI.EditApproximation.bitWordValue (OAI.EditApproximation.powerTwoWord n) = 2 ^ n := by + induction n with + | zero => (simp [OAI.EditApproximation.powerTwoWord, OAI.EditApproximation.bitWordValue]) + | succ n ih => + (simp only [OAI.EditApproximation.powerTwoWord, List.replicate_succ, List.cons_append, OAI.EditApproximation.bitWordValue, + Bool.toNat_false, zero_add] at *) + rw [ih, pow_succ] + omega + have proof_inversePowerTwo_value_89 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.inversePowerTwo n).value = (2 : ℚ) ^ (-(n : ℤ)) := by + (simp only [OAI.EditApproximation.BinaryFraction.inversePowerTwo, OAI.EditApproximation.BinaryFraction.value, OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, Bool.false_eq_true, + ↓reduceIte, OAI.EditApproximation.bitWordValue, Bool.toNat_true, + Int.cast_natCast, proof_powerTwoWord_value_13, Nat.cast_pow, Nat.cast_ofNat, zpow_neg, zpow_natCast]) + norm_num [one_div] + have proof_signedPowerTwoWithWork_value_90 (e : ℤ) : + (OAI.EditApproximation.BinaryFraction.signedPowerTwoWithWork e).1.value = (2 : ℚ) ^ e := by + unfold OAI.EditApproximation.BinaryFraction.signedPowerTwoWithWork + split_ifs with h + · change (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.powerTwoWord e.toNat) : ℚ) / 1 = (2 : ℚ) ^ e + rw [div_one, proof_powerTwoWord_value_13, Nat.cast_pow, Nat.cast_ofNat, ← zpow_natCast, + Int.toNat_of_nonneg h] + · rw [proof_inversePowerTwo_value_89, Int.toNat_of_nonneg + (show 0 ≤ -e from neg_nonneg.mpr (le_of_lt (lt_of_not_ge h))), neg_neg] + have proof_groupScalesWithWork_value_91 (eM : ℕ) (eb : ℕ) (eF : ℕ) : + ((OAI.EditApproximation.BinaryFraction.groupScalesWithWork eM eb eF).1.map OAI.EditApproximation.BinaryFraction.value) = + OAI.EditApproximation.groupDyadicScales (2 ^ eM) (2 ^ eb) ((2 : ℚ) ^ eF) := by + have hlower : ((2 ^ eb : ℕ) : ℚ) / (2 ^ eM : ℕ) = (2 : ℚ) ^ ((eb : ℤ) - eM) := by + rw [Nat.cast_pow, Nat.cast_pow, Nat.cast_ofNat, zpow_sub₀ (by norm_num : (2 : ℚ) ≠ 0), + zpow_natCast, zpow_natCast] + have hupper : (64 : ℚ) * (2 : ℚ) ^ eF * (2 ^ eb : ℕ) = + (2 : ℚ) ^ ((6 + eF + eb : ℕ) : ℤ) := by + rw [Nat.cast_pow, Nat.cast_ofNat, zpow_natCast, pow_add, pow_add] + norm_num + have hlog : Int.log 2 ((2 : ℚ) ^ ((6 + eF + eb : ℕ) : ℤ)) = ((6 + eF + eb : ℕ) : ℤ) := by + simpa only [Nat.cast_ofNat] using Int.log_zpow (R := ℚ) (by decide : 1 < 2) ((6 + eF + eb : ℕ) : ℤ) + have hclog : Int.clog 2 ((2 : ℚ) ^ ((eb : ℤ) - eM)) = (eb : ℤ) - eM := by + simpa only [Nat.cast_ofNat] using Int.clog_zpow (R := ℚ) (by decide : 1 < 2) ((eb : ℤ) - eM) + simp only [OAI.EditApproximation.BinaryFraction.groupScalesWithWork, proof_arithmeticMapWithWork_value_70, List.map_map, + Function.comp_def, proof_signedPowerTwoWithWork_value_90, OAI.EditApproximation.groupDyadicScales, hlower, hupper, hlog, hclog] + have proof_computedGroupScales_value_87 (M : ℕ) (b : ℕ) (F : ℕ) (eM : ℕ) (eb : ℕ) (eF : ℕ) (hM : Eq.{1} M (HPow.hPow.{0, 0, 0} 2 eM)) (hb : Eq.{1} b (HPow.hPow.{0, 0, 0} 2 eb)) (hF : Eq.{1} F (HPow.hPow.{0, 0, 0} 2 eF)) : + (OAI.EditApproximation.BinaryFraction.groupScalesWithWork eM eb eF).1.map OAI.EditApproximation.BinaryFraction.value = OAI.EditApproximation.groupDyadicScales M b (OAI.EditApproximation.BinaryFraction.nat F).value := by + rw [proof_nat_value_49, hM, hb, hF, Nat.cast_pow, Nat.cast_ofNat] + exact proof_groupScalesWithWork_value_91 eM eb eF + exact + let b := 2 ^ eb + let scales := OAI.EditApproximation.BinaryFraction.groupScalesWithWork eM eb eF + let hs : scales.1.map OAI.EditApproximation.BinaryFraction.value = OAI.EditApproximation.groupDyadicScales M b F := by + simpa only [proof_nat_value_49] using proof_computedGroupScales_value_87 M b F eM eb eF hM rfl hF + let hlen : scales.1.length = (OAI.EditApproximation.groupDyadicScales M b F).length := by + simpa only [List.length_map] using congrArg List.length hs + let indices := OAI.EditApproximation.queryFinRange scales.1.length (OAI.EditApproximation.groupDyadicScales M b F).length hlen + OAI.EditApproximation.BinaryFraction.groupScalesAllocation eM eb eF + 2 * scales.1.length + eb + 1 + + OAI.EditApproximation.arithmeticFlatMapAllocation (OAI.EditApproximation.BinaryFraction.groupKeySampleBlock (Q := Q) b scales.1 hs cell) + (OAI.EditApproximation.BinaryFraction.groupKeySampleBlockAllocation (Q := Q) b scales.1 hs cell) indices + + +end OAI.EditApproximation.BinaryFraction +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BinaryFraction + + +def querySharedInputsWithWork {nx ny : ℕ} (M N F Q exponent eM eF : ℕ) + (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (parent : OAI.EditApproximation.TargetInterval nx) + (a value : OAI.EditApproximation.BinaryFraction) (query : OAI.EditApproximation.TargetInterval ny) (draw : OAI.EditApproximation.CountedCellGroupDraws M F Q) : + List (Fin M × OAI.EditApproximation.TargetInterval ny) × ℕ := + let scales := OAI.EditApproximation.BinaryFraction.queryExponentsWithWork N F a value + let radius := OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork value + let inputs := OAI.EditApproximation.arithmeticFlatMapWithWork (fun eb => + let side := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) (OAI.EditApproximation.BinaryFraction.nat (2 ^ eb)) + let cells := OAI.EditApproximation.BinaryFraction.targetCellsWithWork side.1 (OAI.EditApproximation.bitWordValue radius.1) query + let states := OAI.EditApproximation.arithmeticFlatMapWithWork (fun cell => + OAI.EditApproximation.BinaryFraction.querySharedCellInputsWithWork M F Q eM eb eF hM hF parent exponent cell (draw (2 ^ eb) cell)) cells.1 + (states.1, side.2 + cells.2 + states.2 + eb + exponent + 4)) scales.1 + let sorted := OAI.EditApproximation.queryOrderedChildInputsWithWork inputs.1 + (sorted.1, scales.2 + radius.2 + inputs.2 + sorted.2 + 3) + +def queryGroupDrawReadWithWork {M F Q : ℕ} [NeZero M] + (keys : List (OAI.EditApproximation.GroupScalarKey M F Q)) (values : List OAI.EditApproximation.BinaryFraction) + (b : ℕ) (cell : ℕ × ℕ) (scale : Fin (OAI.EditApproximation.groupDyadicScales M b F).length) + (sample : Fin (OAI.EditApproximation.groupSampleCount M Q b (OAI.EditApproximation.groupDyadicScaleAt M b F scale))) : Fin M × ℕ := by + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_bitSubtractor_value_17 (a : Bool) (b : Bool) (borrow : Bool) : + a.toNat + 2 * (OAI.EditApproximation.bitBorrow a b borrow).toNat = + b.toNat + borrow.toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat := by + cases a <;> cases b <;> cases borrow <;> decide + have proof_bitSubtractionRippleEquation_18 (a : ℕ) (b : ℕ) (borrow : ℕ) (nextBorrow : ℕ) (difference : ℕ) (left : ℕ) (right : ℕ) (result : ℕ) (tail : ℕ) (htail : Eq.{1} (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} result right) nextBorrow) (HAdd.hAdd.{0, 0, 0} left tail)) (hbit : Eq.{1} (HAdd.hAdd.{0, 0, 0} a (HMul.hMul.{0, 0, 0} 2 nextBorrow)) + (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} b borrow) difference)) : + (difference + 2 * result) + (b + 2 * right) + borrow = + (a + 2 * left) + 2 * tail := by + omega + have proof_bitSubtractWithWork_value_19 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right borrow).1 + OAI.EditApproximation.bitWordValue right + borrow.toNat = + OAI.EditApproximation.bitWordValue left + 2 ^ max left.length right.length * + (OAI.EditApproximation.bitSubtractWithWork left right borrow).2.1.toNat := by + induction left generalizing right borrow with + | nil => + induction right generalizing borrow with + | nil => (simp [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + have h := ih (OAI.EditApproximation.bitBorrow false b borrow) + have hb := proof_bitSubtractor_value_17 false b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue, + List.length_nil, List.length_cons, Nat.zero_max, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 0 b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow false b borrow).toNat + (OAI.EditApproximation.bitDifference false b borrow).toNat 0 (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).1) + (2 ^ bs.length * (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons a as ih => + cases right with + | nil => + have h := ih [] (OAI.EditApproximation.bitBorrow a false borrow) + have hb := proof_bitSubtractor_value_17 a false borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_nil, List.length_cons, + Nat.max_zero, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat 0 borrow.toNat (OAI.EditApproximation.bitBorrow a false borrow).toNat + (OAI.EditApproximation.bitDifference a false borrow).toNat (OAI.EditApproximation.bitWordValue as) 0 + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).1) + (2 ^ as.length * (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons b bs => + have h := ih bs (OAI.EditApproximation.bitBorrow a b borrow) + have hb := proof_bitSubtractor_value_17 a b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_cons, Nat.succ_max_succ, + pow_succ] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow a b borrow).toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).1) + (2 ^ max as.length bs.length * (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_assoc, Nat.mul_left_comm] using hs + have proof_bitWordValue_lt_pow_length_20 (bits : List.{0} Bool) : OAI.EditApproximation.bitWordValue bits < 2 ^ bits.length := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitWordValue]) + | cons bit bits ih => + cases bit <;> (simp only [OAI.EditApproximation.bitWordValue, List.length_cons, pow_succ, Bool.toNat_false, Bool.toNat_true]) <;> omega + have proof_bitSubtractWithWork_length_21 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + (OAI.EditApproximation.bitSubtractWithWork left right borrow).1.length = max left.length right.length := by + induction left generalizing right borrow with + | nil => + simp only [OAI.EditApproximation.bitSubtractWithWork] + induction right generalizing borrow with + | nil => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork] + | cons b bs ih => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork, ih] + | cons a as ih => + cases right with + | nil => simp [OAI.EditApproximation.bitSubtractWithWork, ih] + | cons b bs => simp [OAI.EditApproximation.bitSubtractWithWork, ih, Nat.succ_max_succ] + have proof_bitSubtractWithWork_sub_22 (left : List.{0} Bool) (right : List.{0} Bool) (h : LE.le.{0} (OAI.EditApproximation.bitWordValue right) (OAI.EditApproximation.bitWordValue left)) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right false).1 = OAI.EditApproximation.bitWordValue left - OAI.EditApproximation.bitWordValue right := by + have hvalue := proof_bitSubtractWithWork_value_19 left right false + have hlt := proof_bitWordValue_lt_pow_length_20 (OAI.EditApproximation.bitSubtractWithWork left right false).1 + rw [proof_bitSubtractWithWork_length_21] at hlt + cases hb : (OAI.EditApproximation.bitSubtractWithWork left right false).2.1 + · simp only [hb, Bool.toNat_false, Nat.mul_zero, Nat.add_zero] at hvalue + omega + · simp only [hb, Bool.toNat_true, Bool.toNat_false, Nat.mul_one, Nat.add_zero] at hvalue + omega + have proof_bitDivModWithWork_value_23 (divisor : List.{0} Bool) (bits : List.{0} Bool) (hd : LT.lt.{0} 0 (OAI.EditApproximation.bitWordValue divisor)) : + OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).1 + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 < OAI.EditApproximation.bitWordValue divisor := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitDivModWithWork, OAI.EditApproximation.bitWordValue, hd]) + | cons bit bits ih => + let previous := OAI.EditApproximation.bitDivModWithWork divisor bits + let candidate := bit :: previous.2.1 + have hp : OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue previous.1 + + OAI.EditApproximation.bitWordValue previous.2.1 := ih.1 + have hr : OAI.EditApproximation.bitWordValue previous.2.1 < OAI.EditApproximation.bitWordValue divisor := ih.2 + have hc : OAI.EditApproximation.bitWordValue candidate < 2 * OAI.EditApproximation.bitWordValue divisor := by + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + cases bit <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega + by_cases hlt : (OAI.EditApproximation.bitCompareWithWork candidate divisor).1 = .lt + · have hv := (proof_bitCompareWithWork_lt_16 candidate divisor).1 hlt + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 = .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * + OAI.EditApproximation.bitWordValue (false :: previous.1) + OAI.EditApproximation.bitWordValue candidate ∧ OAI.EditApproximation.bitWordValue candidate < _ + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_false]) + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + nlinarith only [hp] + · exact hv + · have hv : OAI.EditApproximation.bitWordValue divisor ≤ OAI.EditApproximation.bitWordValue candidate := by + exact Nat.le_of_not_gt (fun h => hlt ((proof_bitCompareWithWork_lt_16 candidate divisor).2 h)) + have hs := proof_bitSubtractWithWork_sub_22 candidate divisor hv + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 ≠ .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (true :: previous.1) + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 < _ + rw [hs] + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_true]) + have he := Nat.sub_add_cancel hv + dsimp only [candidate, OAI.EditApproximation.bitWordValue] at he ⊢ + nlinarith only [hp, he] + · omega + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_binaryNaturalDivModWithWork_spec_24 (n : ℕ) (d : ℕ) (hd : LT.lt.{0} 0 d) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalDivModWithWork n d).1 = n / d ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalDivModWithWork n d).2.1 = n % d := by + have h := proof_bitDivModWithWork_value_23 d.bits n.bits (by simpa only [proof_bitWordValue_bits_15] using hd) + simp only [proof_bitWordValue_bits_15] at h + have hmod : n % d = OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork d.bits n.bits).2.1 := by + conv_lhs => rw [h.1] + simp only [Nat.add_mod, Nat.mul_mod_right, Nat.zero_add, Nat.mod_eq_of_lt h.2] + have hdiv : n / d = OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork d.bits n.bits).1 := by + conv_lhs => rw [h.1] + rw [Nat.mul_add_div hd, Nat.div_eq_of_lt h.2, Nat.add_zero] + exact ⟨hdiv.symm, hmod.symm⟩ + exact + let word := OAI.EditApproximation.BinaryFraction.gatheredWordLookupWithWork OAI.EditApproximation.queryGroupKeyEqualWithWork keys values ⟨(b, cell), scale, sample⟩ + let floor := OAI.EditApproximation.BinaryFraction.naturalFloorWithWork word.1 + let reduced := OAI.EditApproximation.binaryNaturalDivModWithWork (OAI.EditApproximation.bitWordValue floor.1) M + (⟨OAI.EditApproximation.bitWordValue reduced.2.1, by + rw [(proof_binaryNaturalDivModWithWork_spec_24 _ M (NeZero.pos M)).2] + exact Nat.mod_lt _ (NeZero.pos M)⟩, + word.2 + floor.2 + reduced.2.2 + 3) + +def queryGroupSourceKeysWithWork {n : ℕ} (M N F Q exponent eM eF : ℕ) + (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (a value : OAI.EditApproximation.BinaryFraction) + (q : OAI.EditApproximation.TargetInterval n) : List (OAI.EditApproximation.GroupScalarKey M F Q) × ℕ := + let scales := OAI.EditApproximation.BinaryFraction.queryExponentsWithWork N F a value + let radius := OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork value + let keys := OAI.EditApproximation.arithmeticFlatMapWithWork (fun eb => + let side := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) (OAI.EditApproximation.BinaryFraction.nat (2 ^ eb)) + let cells := OAI.EditApproximation.BinaryFraction.targetCellsWithWork side.1 (OAI.EditApproximation.bitWordValue radius.1) q + let sources := OAI.EditApproximation.arithmeticFlatMapWithWork + (OAI.EditApproximation.BinaryFraction.queryGroupKeySamplesWithWork M F Q eM eb eF hM hF) cells.1 + (sources.1, side.2 + cells.2 + sources.2 + eb + exponent + 4)) scales.1 + (keys.1, scales.2 + radius.2 + keys.2 + 2) + +def queryGroupDrawReadAllocation {M F Q : ℕ} [NeZero M] + (keys : List (OAI.EditApproximation.GroupScalarKey M F Q)) (values : List OAI.EditApproximation.BinaryFraction) + (b : ℕ) (cell : ℕ × ℕ) (scale : Fin (OAI.EditApproximation.groupDyadicScales M b F).length) + (sample : Fin (OAI.EditApproximation.groupSampleCount M Q b (OAI.EditApproximation.groupDyadicScaleAt M b F scale))) : ℕ := + let key : OAI.EditApproximation.GroupScalarKey M F Q := ⟨(b, cell), scale, sample⟩ + let word := (OAI.EditApproximation.BinaryFraction.gatheredWordLookupWithWork OAI.EditApproximation.queryGroupKeyEqualWithWork keys values key).1 + let floor := (OAI.EditApproximation.BinaryFraction.naturalFloorWithWork word).1 + OAI.EditApproximation.BinaryFraction.gatheredLookupAllocation OAI.EditApproximation.queryGroupKeyEqualWithWork OAI.EditApproximation.queryGroupKeyEqualAllocation keys values key + + OAI.EditApproximation.BinaryFraction.naturalFloorAllocation word + OAI.EditApproximation.bitDivModAllocation M.bits (OAI.EditApproximation.bitWordValue floor).bits + +def queryGroupSourceKeysAllocation {n : ℕ} (M N F Q exponent eM eF : ℕ) + (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (a value : OAI.EditApproximation.BinaryFraction) (q : OAI.EditApproximation.TargetInterval n) : ℕ := + let radius := (OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork value).1 + let build := fun eb => + let side := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) (OAI.EditApproximation.BinaryFraction.nat (2 ^ eb)) + let cells := OAI.EditApproximation.BinaryFraction.targetCellsWithWork side.1 (OAI.EditApproximation.bitWordValue radius) q + let sources := OAI.EditApproximation.arithmeticFlatMapWithWork (OAI.EditApproximation.BinaryFraction.queryGroupKeySamplesWithWork M F Q eM eb eF hM hF) cells.1 + (sources.1, side.2 + cells.2 + sources.2 + eb + exponent + 4) + let allocation := fun eb => + let side := (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) (OAI.EditApproximation.BinaryFraction.nat (2 ^ eb))).1 + let cells := (OAI.EditApproximation.BinaryFraction.targetCellsWithWork side (OAI.EditApproximation.bitWordValue radius) q).1 + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) (OAI.EditApproximation.BinaryFraction.nat (2 ^ eb)) + OAI.EditApproximation.BinaryFraction.targetCellsAllocation side (OAI.EditApproximation.bitWordValue radius) q + + OAI.EditApproximation.arithmeticFlatMapAllocation (OAI.EditApproximation.BinaryFraction.queryGroupKeySamplesWithWork M F Q eM eb eF hM hF) + (OAI.EditApproximation.BinaryFraction.queryGroupKeySamplesAllocation M F Q eM eb eF hM hF) cells + eb + exponent + 2 + OAI.EditApproximation.BinaryFraction.queryExponentsAllocation N F a value + OAI.EditApproximation.BinaryFraction.naturalCeilingAllocation value + + OAI.EditApproximation.arithmeticFlatMapAllocation build allocation (OAI.EditApproximation.BinaryFraction.queryExponentsWithWork N F a value).1 + +def querySharedInputsAllocation {nx ny : ℕ} (M N F Q exponent eM eF : ℕ) + (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (parent : OAI.EditApproximation.TargetInterval nx) + (a value : OAI.EditApproximation.BinaryFraction) (query : OAI.EditApproximation.TargetInterval ny) (draw : OAI.EditApproximation.CountedCellGroupDraws M F Q) + (allocation : OAI.EditApproximation.CountedCellGroupAllocations M F Q) : ℕ := + let scales := (OAI.EditApproximation.BinaryFraction.queryExponentsWithWork N F a value).1 + let radius := (OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork value).1 + let build := fun eb => + let side := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) (OAI.EditApproximation.BinaryFraction.nat (2 ^ eb)) + let cells := OAI.EditApproximation.BinaryFraction.targetCellsWithWork side.1 (OAI.EditApproximation.bitWordValue radius) query + let states := OAI.EditApproximation.arithmeticFlatMapWithWork (fun cell => + OAI.EditApproximation.BinaryFraction.querySharedCellInputsWithWork (ny := ny) M F Q eM eb eF hM hF parent exponent cell (draw (2 ^ eb) cell)) cells.1 + (states.1, side.2 + cells.2 + states.2 + eb + exponent + 4) + let alloc := fun eb => + let side := (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) (OAI.EditApproximation.BinaryFraction.nat (2 ^ eb))).1 + let cells := (OAI.EditApproximation.BinaryFraction.targetCellsWithWork side (OAI.EditApproximation.bitWordValue radius) query).1 + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) (OAI.EditApproximation.BinaryFraction.nat (2 ^ eb)) + OAI.EditApproximation.BinaryFraction.targetCellsAllocation side (OAI.EditApproximation.bitWordValue radius) query + + OAI.EditApproximation.arithmeticFlatMapAllocation + (fun cell => OAI.EditApproximation.BinaryFraction.querySharedCellInputsWithWork (ny := ny) M F Q eM eb eF hM hF parent exponent cell (draw (2 ^ eb) cell)) + (fun cell => OAI.EditApproximation.BinaryFraction.querySharedCellInputsAllocation (ny := ny) M F Q eM eb eF hM hF parent exponent cell + (draw (2 ^ eb) cell) (allocation (2 ^ eb) cell)) cells + eb + exponent + 2 + let inputs := (OAI.EditApproximation.arithmeticFlatMapWithWork build scales).1 + OAI.EditApproximation.BinaryFraction.queryExponentsAllocation N F a value + OAI.EditApproximation.BinaryFraction.naturalCeilingAllocation value + + OAI.EditApproximation.arithmeticFlatMapAllocation build alloc scales + OAI.EditApproximation.queryOrderedChildInputsAllocation inputs + +def preparedCellGroupSourceAllocationRaw {α : Type u_1} (source target : List α) {M : ℕ} + (parent : OAI.EditApproximation.TargetInterval source.length) (b P F exponent Q : ℕ) (_hb : 0 < b) (_hP : 0 < P) + (tau a : OAI.EditApproximation.BinaryFraction) + (parentInitial : OAI.EditApproximation.TargetInterval target.length → OAI.EditApproximation.BinaryFraction × ℕ) + (child initial current : Fin M → OAI.EditApproximation.TargetInterval target.length → OAI.EditApproximation.BinaryFraction × ℕ) + (R C : ℕ) (_hr : ∀ i q, (child i q).2 ≤ R) (_hi : ∀ i q, (initial i q).2 ≤ C) + (raw : List OAI.EditApproximation.BinaryFraction) (hraw : raw.map OAI.EditApproximation.BinaryFraction.value = OAI.EditApproximation.groupDyadicScales M b (OAI.EditApproximation.BinaryFraction.nat F).value) + (draw : ∀ t : Fin (OAI.EditApproximation.groupDyadicScales M b (OAI.EditApproximation.BinaryFraction.nat F).value).length, + Fin (OAI.EditApproximation.groupSampleCount M Q b (OAI.EditApproximation.groupDyadicScaleAt M b (OAI.EditApproximation.BinaryFraction.nat F).value t)) → Fin M × ℕ) + (parentAllocation : OAI.EditApproximation.TargetInterval target.length → ℕ) + (childAllocation initialAllocation currentAllocation : Fin M → OAI.EditApproximation.TargetInterval target.length → ℕ) + (drawAllocation : ∀ t : Fin (OAI.EditApproximation.groupDyadicScales M b (OAI.EditApproximation.BinaryFraction.nat F).value).length, + Fin (OAI.EditApproximation.groupSampleCount M Q b (OAI.EditApproximation.groupDyadicScaleAt M b (OAI.EditApproximation.BinaryFraction.nat F).value t)) → ℕ) + + + (cell : ℕ × ℕ) : ℕ := by + have proof_indexedGroupScales_value_130 (raw : List.{0} OAI.EditApproximation.BinaryFraction) (M : ℕ) (b : ℕ) (F : ℚ) (h : Eq.{1} (List.map.{0, 0} OAI.EditApproximation.BinaryFraction.value raw) (OAI.EditApproximation.groupDyadicScales M b F)) (i : Fin (List.length.{0} (OAI.EditApproximation.groupDyadicScales M b F))) : + (OAI.EditApproximation.BinaryFraction.indexedGroupScales raw M b F h i).value = OAI.EditApproximation.groupDyadicScaleAt M b F i := by + unfold OAI.EditApproximation.BinaryFraction.indexedGroupScales OAI.EditApproximation.groupDyadicScaleAt + simp only [List.get_eq_getElem] + rw [← List.getElem_map OAI.EditApproximation.BinaryFraction.value (l := raw) (i := i.val) (h := by rw [h]; exact i.isLt)] + simp only [h] + exact + let centers := (OAI.EditApproximation.BinaryFraction.cellCentersReadWithWork P F b a (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) parentInitial cell).1 + let members := (OAI.EditApproximation.filterMapWithWork + (OAI.EditApproximation.BinaryFraction.preparedUnskippedReadWithWorkRaw parent b P exponent tau (OAI.EditApproximation.BinaryFraction.nat F) child initial) centers).1 + OAI.EditApproximation.BinaryFraction.cellCentersReadAllocation P F b a (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) parentInitial parentAllocation cell + + OAI.EditApproximation.filterMapAllocation (OAI.EditApproximation.BinaryFraction.preparedUnskippedReadWithWorkRaw parent b P exponent tau (OAI.EditApproximation.BinaryFraction.nat F) child initial) + (fun center => OAI.EditApproximation.BinaryFraction.preparedUnskippedReadAllocation parent center b P exponent tau (OAI.EditApproximation.BinaryFraction.nat F) + child initial childAllocation initialAllocation) centers + + if hempty : members = [] then 0 else + OAI.EditApproximation.BinaryFraction.sampledGroupActionSourceAllocationRaw b exponent Q initial current initialAllocation currentAllocation + (OAI.EditApproximation.BinaryFraction.indexedGroupScales raw M b (OAI.EditApproximation.BinaryFraction.nat F).value hraw) + (fun t j => draw t (Fin.cast (congrArg (OAI.EditApproximation.groupSampleCount M Q b) + (proof_indexedGroupScales_value_130 raw M b (OAI.EditApproximation.BinaryFraction.nat F).value hraw t)) j)) + (fun t j => drawAllocation t (Fin.cast (congrArg (OAI.EditApproximation.groupSampleCount M Q b) + (proof_indexedGroupScales_value_130 raw M b (OAI.EditApproximation.BinaryFraction.nat F).value hraw t)) j)) members hempty + 1 + +def preparedCellGroupSourceWithWorkRaw {α : Type u_1} (source target : List α) {M : ℕ} + (parent : OAI.EditApproximation.TargetInterval source.length) (b P F exponent Q : ℕ) (_hb : 0 < b) (_hP : 0 < P) + (tau a : OAI.EditApproximation.BinaryFraction) + (parentInitial : OAI.EditApproximation.TargetInterval target.length → OAI.EditApproximation.BinaryFraction × ℕ) + (child initial current : Fin M → OAI.EditApproximation.TargetInterval target.length → OAI.EditApproximation.BinaryFraction × ℕ) + (R C : ℕ) (_hr : ∀ i q, (child i q).2 ≤ R) (_hi : ∀ i q, (initial i q).2 ≤ C) + (raw : List OAI.EditApproximation.BinaryFraction) (hraw : raw.map OAI.EditApproximation.BinaryFraction.value = OAI.EditApproximation.groupDyadicScales M b (OAI.EditApproximation.BinaryFraction.nat F).value) + (draw : ∀ t : Fin (OAI.EditApproximation.groupDyadicScales M b (OAI.EditApproximation.BinaryFraction.nat F).value).length, + Fin (OAI.EditApproximation.groupSampleCount M Q b (OAI.EditApproximation.groupDyadicScaleAt M b (OAI.EditApproximation.BinaryFraction.nat F).value t)) → Fin M × ℕ) + (cell : ℕ × ℕ) : + Option (OAI.EditApproximation.BinaryBellmanAction (OAI.EditApproximation.TargetInterval target.length) + (Fin M × OAI.EditApproximation.TargetInterval target.length) M) × ℕ := by + have proof_indexedGroupScales_value_130 (raw : List.{0} OAI.EditApproximation.BinaryFraction) (M : ℕ) (b : ℕ) (F : ℚ) (h : Eq.{1} (List.map.{0, 0} OAI.EditApproximation.BinaryFraction.value raw) (OAI.EditApproximation.groupDyadicScales M b F)) (i : Fin (List.length.{0} (OAI.EditApproximation.groupDyadicScales M b F))) : + (OAI.EditApproximation.BinaryFraction.indexedGroupScales raw M b F h i).value = OAI.EditApproximation.groupDyadicScaleAt M b F i := by + unfold OAI.EditApproximation.BinaryFraction.indexedGroupScales OAI.EditApproximation.groupDyadicScaleAt + simp only [List.get_eq_getElem] + rw [← List.getElem_map OAI.EditApproximation.BinaryFraction.value (l := raw) (i := i.val) (h := by rw [h]; exact i.isLt)] + simp only [h] + exact + let centers := OAI.EditApproximation.BinaryFraction.cellCentersReadWithWork P F b a (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) parentInitial cell + let members := OAI.EditApproximation.filterMapWithWork + (OAI.EditApproximation.BinaryFraction.preparedUnskippedReadWithWorkRaw parent b P exponent tau (OAI.EditApproximation.BinaryFraction.nat F) child initial) centers.1 + if h : members.1 = [] then (none, centers.2 + members.2 + 1) else + let selected := OAI.EditApproximation.BinaryFraction.sampledGroupActionSourceWithWorkRaw b exponent Q initial current (OAI.EditApproximation.BinaryFraction.indexedGroupScales raw M b (OAI.EditApproximation.BinaryFraction.nat F).value hraw) + (fun t j => draw t (Fin.cast (congrArg (OAI.EditApproximation.groupSampleCount M Q b) + (proof_indexedGroupScales_value_130 raw M b (OAI.EditApproximation.BinaryFraction.nat F).value hraw t)) j)) members.1 h + (some selected.1, centers.2 + members.2 + selected.2 + 2) + + +end OAI.EditApproximation.BinaryFraction +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open Finset + +def querySharedInputCover {α : Type u_1} (source target : List α) {M : ℕ} + (parent : OAI.EditApproximation.TargetInterval source.length) (N F exponent Q : ℕ) (a : ℚ) + (initial : OAI.EditApproximation.TargetInterval target.length → ℚ) (q : OAI.EditApproximation.TargetInterval target.length) + (draw : OAI.EditApproximation.CellGroupDraws M F Q) : Finset (Fin M × OAI.EditApproximation.TargetInterval target.length) := + (OAI.EditApproximation.localGroupQueryKeys N F exponent a initial q).toFinset.biUnion fun key => + Finset.univ.biUnion fun scale : Fin (OAI.EditApproximation.groupDyadicScales M key.1 F).length => + OAI.EditApproximation.groupCurrentInputCover source target parent key.1 exponent Q key.2 + (OAI.EditApproximation.groupDyadicScaleAt M key.1 F scale) (draw key.1 key.2 scale) + +def coarseThresholdChildrenCost {B D : ℕ} {α : Type u} + (k : ℕ) (Q lam : ℚ) + (value : OAI.EditApproximation.CoarseSourceTree B α D → OAI.EditApproximation.CoarseThresholdDraws B D → ℚ → ℕ → Fin (2 * k + 1) → ℚ) + (allowance : ℚ) : + List (OAI.EditApproximation.CoarseSourceTree B α D × Fin B × OAI.EditApproximation.CoarseThresholdDraws B D) → ℕ → Fin (2 * k + 1) → ℚ + | [], _, _ => 0 + | (child, draw, below) :: rest, start, shift => + let threshold := OAI.EditApproximation.coarseChildThreshold B Q allowance draw + let childMinimum := univ.inf' univ_nonempty (fun next => + value child below (lam * threshold) start next + (2 * Nat.dist shift.val next.val : ℕ)) + OAI.EditApproximation.coarseThresholdContribution threshold (allowance / Q) childMinimum + + coarseThresholdChildrenCost k Q lam value allowance rest (start + child.word.length) shift + +def coarseThresholdEstimate {B : ℕ} {α : Type u} [DecidableEq α] + (k : ℕ) (Q lam : ℚ) (frame : List (Option α)) : + {D : ℕ} → OAI.EditApproximation.CoarseSourceTree B α D → OAI.EditApproximation.CoarseThresholdDraws B D → ℚ → ℕ → Fin (2 * k + 1) → ℚ + | _, tree, draws, allowance, start, shift => + if (tree.word.length : ℚ) ≤ allowance then 0 else + match tree, draws with + | .leaf letter, _ => (OAI.EditApproximation.coarseShiftCost k frame (.leaf (B := B) letter) start shift : ℚ) + | .branch children, (draws, below) => + OAI.EditApproximation.coarseThresholdChildrenCost k Q lam + (fun child => coarseThresholdEstimate k Q lam frame child) allowance + (List.ofFn fun i => (children i, draws i, below i)) start shift + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open MeasureTheory ProbabilityTheory + +abbrev PhysicalScalarIndex (M J N n exponent F Q R B : ℕ) + (key : OAI.EditApproximation.PhysicalCommonKey M J N n exponent B) : Type := + match key with + | .inl _ => Fin R + | .inr group => Σ _time : Fin R, + Σ scale : Fin (OAI.EditApproximation.groupDyadicScales M ((OAI.EditApproximation.dyadicScales N).get group.2.1) F).length, + Fin (OAI.EditApproximation.groupSampleCount M Q ((OAI.EditApproximation.dyadicScales N).get group.2.1) + (OAI.EditApproximation.groupDyadicScaleAt M ((OAI.EditApproximation.dyadicScales N).get group.2.1) F scale)) + +def computedPhysicalCoarseDepth (source target : List ℕ) (N : ℕ) + (entry : OAI.EditApproximation.PhysicalEntry (OAI.EditApproximation.integerParameters N).M + (OAI.EditApproximation.intervalTreeDepth (OAI.EditApproximation.integerParameters N).M source.length) target.length) : ℕ := + OAI.EditApproximation.computedCoarseDepth N (OAI.EditApproximation.coarseEntryWidth (OAI.EditApproximation.physicalSource source entry.1) + (OAI.EditApproximation.substring target entry.2.lo entry.2.hi)) + +abbrev PhysicalScalarKey (M J N n exponent F Q R B : ℕ) := + Σ key : OAI.EditApproximation.PhysicalCommonKey M J N n exponent B, OAI.EditApproximation.PhysicalScalarIndex M J N n exponent F Q R B key + +instance physicalScalarIndexFintype (M J N n exponent F Q R B : ℕ) + (key : OAI.EditApproximation.PhysicalCommonKey M J N n exponent B) : + Fintype (OAI.EditApproximation.PhysicalScalarIndex M J N n exponent F Q R B key) := by + cases key <;> dsimp only [OAI.EditApproximation.PhysicalScalarIndex] <;> infer_instance + +def physicalScalarRange (M J N n exponent F Q R B : ℕ) + (key : OAI.EditApproximation.PhysicalScalarKey M J N n exponent F Q R B) : ℕ := + match key.1 with + | .inl online => online.2.val.val + | .inr _ => M + +instance physicalScalarRangeNeZero (M J N n exponent F Q R B : ℕ) [NeZero M] + (key : OAI.EditApproximation.PhysicalScalarKey M J N n exponent F Q R B) : + NeZero (OAI.EditApproximation.physicalScalarRange M J N n exponent F Q R B key) := by + rcases key with ⟨key, index⟩ + cases key <;> dsimp only [OAI.EditApproximation.physicalScalarRange] <;> infer_instance + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation + + +def queryGroupSourceGather {ι : Type u_1} {β : Type u_2} {n : ℕ} (M N F Q exponent eM eF : ℕ) + (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (a : OAI.EditApproximation.BinaryFraction) + (initial : OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) (q : OAI.EditApproximation.TargetInterval n) + (reader : OAI.EditApproximation.GroupScalarKey M F Q → OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (next : List (OAI.EditApproximation.GroupScalarKey M F Q) → List OAI.EditApproximation.BinaryFraction → OAI.EditApproximation.BitQuery ι β) : OAI.EditApproximation.BitQuery ι β := + let query := initial q + .charge query.2 ((OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.queryGroupSourceKeysWithWork M N F Q exponent eM eF hM hF a query.1 q)).bind + fun keys => OAI.EditApproximation.BitQuery.collect reader keys (next keys)) + +def physicalScalarCodeWithWork {M J N n exponent F Q R B : ℕ} + (key : OAI.EditApproximation.PhysicalScalarKey M J N n exponent F Q R B) : ℕ × ℕ := + match key with + | ⟨.inl online, time⟩ => + let entry := OAI.EditApproximation.physicalEntryCodeWithWork (online.1.1.val, online.1.2.2) + let first := OAI.EditApproximation.naturalPairWithWork online.2.val.val time.val + let second := OAI.EditApproximation.naturalPairWithWork online.1.2.1.val first.1 + let last := OAI.EditApproximation.naturalPairWithWork entry.1 second.1 + (2 * last.1, entry.2 + first.2 + second.2 + last.2 + 2) + | ⟨.inr group, index⟩ => + let node := OAI.EditApproximation.physicalNodeCodeWithWork group.1.val + let a := OAI.EditApproximation.naturalPairWithWork index.2.1.val index.2.2.val + let b := OAI.EditApproximation.naturalPairWithWork index.1.val a.1 + let c := OAI.EditApproximation.naturalPairWithWork group.2.2.2.val b.1 + let d := OAI.EditApproximation.naturalPairWithWork group.2.2.1.val c.1 + let e := OAI.EditApproximation.naturalPairWithWork group.2.1.val d.1 + let f := OAI.EditApproximation.naturalPairWithWork node.1 e.1 + (2 * f.1 + 1, node.2 + a.2 + b.2 + c.2 + d.2 + e.2 + f.2 + 3) + +def physicalScalarCodeAllocation {M J N n exponent F Q R B : ℕ} + (key : OAI.EditApproximation.PhysicalScalarKey M J N n exponent F Q R B) : ℕ := + match key with + | ⟨.inl online, _⟩ => 2 * online.1.1.val.1.val + J + 20 + | ⟨.inr group, _⟩ => 2 * group.1.val.1.val + J + 25 + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable (M J N n exponent F Q R B : ℕ) [NeZero M] + +abbrev PhysicalGroupQueries (b : ℕ) := + ∀ scale : Fin (OAI.EditApproximation.groupDyadicScales M b F).length, + Fin (OAI.EditApproximation.groupSampleCount M Q b (OAI.EditApproximation.groupDyadicScaleAt M b F scale)) → + OAI.EditApproximation.FiniteQuery (OAI.EditApproximation.PhysicalScalarKey M J N n exponent F Q R B) + +def physicalScalarOnlineRead (node : OAI.EditApproximation.PhysicalInternalNode M J) (time : Fin R) + (key : ℕ × OAI.EditApproximation.TargetInterval n) (range : ℕ) : OAI.EditApproximation.FiniteQuery (OAI.EditApproximation.PhysicalScalarKey M J N n exponent F Q R B) := + if hb : key.1 ∈ OAI.EditApproximation.dyadicScales N then + if hr : 0 < range ∧ range ≤ B then + .read ⟨.inl ((node, OAI.EditApproximation.physicalScaleIndex N key.1 hb, key.2), + OAI.EditApproximation.positiveDrawRangeOfLE B range hr.1 hr.2), time⟩ .done + else .done 0 + else .done 0 + +def physicalScalarGroupQueriesAt (key : OAI.EditApproximation.PhysicalLocalGroupKey M J N n exponent) (time : Fin R) : + OAI.EditApproximation.PhysicalGroupQueries M J N n exponent F Q R B ((OAI.EditApproximation.dyadicScales N).get key.2.1) := + fun scale sample => .read ⟨.inr key, ⟨time, scale, sample⟩⟩ .done + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable (M J N n exponent F Q R B : ℕ) + +abbrev BitPhysicalGroupQueries (b : ℕ) := + ∀ scale : Fin (OAI.EditApproximation.groupDyadicScales M b F).length, + Fin (OAI.EditApproximation.groupSampleCount M Q b (OAI.EditApproximation.groupDyadicScaleAt M b F scale)) → + OAI.EditApproximation.BitQuery (OAI.EditApproximation.PhysicalScalarKey M J N n exponent F Q R B) OAI.EditApproximation.BinaryFraction + +def queryPhysicalScalarRead (key : OAI.EditApproximation.PhysicalScalarKey M J N n exponent F Q R B) : + OAI.EditApproximation.BitQuery (OAI.EditApproximation.PhysicalScalarKey M J N n exponent F Q R B) OAI.EditApproximation.BinaryFraction := + .charge ((OAI.EditApproximation.physicalScalarCodeWithWork key).2 + 1) (.read key .done) + +def queryPhysicalScalarGroupQueriesAt (key : OAI.EditApproximation.PhysicalLocalGroupKey M J N n exponent) (time : Fin R) : + OAI.EditApproximation.BitPhysicalGroupQueries M J N n exponent F Q R B ((OAI.EditApproximation.dyadicScales N).get key.2.1) := + fun scale sample => OAI.EditApproximation.queryPhysicalScalarRead M J N n exponent F Q R B + ⟨.inr key, ⟨time, scale, sample⟩⟩ + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open Finset MeasureTheory ProbabilityTheory +variable {α : Type u_1} {source target : List α} {M b P thetaExponent : ℕ} {parent : TargetInterval source.length} {tau F : ℚ} {child initial : Fin M → TargetInterval target.length → ℚ} + +def dyadicUnskippedGroupEstimate (Q : ℕ) + (value : Fin M → OAI.EditApproximation.TargetInterval target.length → ℚ) + (member : OAI.EditApproximation.UnskippedBand source target parent b P thetaExponent tau F child initial) + (draw : ∀ scale : Fin (OAI.EditApproximation.groupDyadicScales M b F).length, + Fin (OAI.EditApproximation.groupSampleCount M Q b (OAI.EditApproximation.groupDyadicScaleAt M b F scale)) → Fin M) : ℚ := + OAI.EditApproximation.unskippedGroupEstimate (OAI.EditApproximation.groupDyadicScaleAt M b F) + (fun scale => OAI.EditApproximation.groupSampleCount M Q b (OAI.EditApproximation.groupDyadicScaleAt M b F scale)) value member draw + +def chooseUnskippedGroup (Q : ℕ) + (value : Fin M → OAI.EditApproximation.TargetInterval target.length → ℚ) + (members : List (OAI.EditApproximation.UnskippedBand source target parent b P thetaExponent tau F child initial)) + (hnonempty : members ≠ []) + (draw : ∀ scale : Fin (OAI.EditApproximation.groupDyadicScales M b F).length, + Fin (OAI.EditApproximation.groupSampleCount M Q b (OAI.EditApproximation.groupDyadicScaleAt M b F scale)) → Fin M) : + OAI.EditApproximation.UnskippedBand source target parent b P thetaExponent tau F child initial := + OAI.EditApproximation.selectGroupMember members hnonempty (fun member => OAI.EditApproximation.dyadicUnskippedGroupEstimate Q value member draw) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open Finset + +def chooseCellGroupAction {α : Type u_1} (source target : List α) {M : ℕ} + (parent : OAI.EditApproximation.TargetInterval source.length) (b P F thetaExponent Q : ℕ) (tau a : ℚ) + (parentInitial : OAI.EditApproximation.TargetInterval target.length → ℚ) + (child initial value : Fin M → OAI.EditApproximation.TargetInterval target.length → ℚ) (cell : ℕ × ℕ) + (draw : ∀ scale : Fin (OAI.EditApproximation.groupDyadicScales M b F).length, + Fin (OAI.EditApproximation.groupSampleCount M Q b (OAI.EditApproximation.groupDyadicScaleAt M b F scale)) → Fin M) : + Option (OAI.EditApproximation.RationalBellmanAction (OAI.EditApproximation.TargetInterval target.length) (Fin M × OAI.EditApproximation.TargetInterval target.length) M) := + let members := OAI.EditApproximation.cellUnskippedBands source target parent b P F thetaExponent tau a parentInitial child initial cell + if h : members = [] then none else some (OAI.EditApproximation.chooseUnskippedGroup Q value members h draw).rationalAction + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {α : Type u_1} {M : ℕ} (source target : List α) (parent : TargetInterval source.length) (N P F exponent Q : ℕ) (tau a : ℚ) (parentInitial : TargetInterval target.length → ℚ) (child initial current : Fin M → TargetInterval target.length → ℚ) (draw : CellGroupDraws M F Q) +local notation (name := source_Combinatorics_EditApproximation_Geometry_LocalGroupCones_8) "theta" => (2 : ℚ) ^ (-(exponent : ℤ)) + +def localCellGroupActions (q : OAI.EditApproximation.TargetInterval target.length) : List (OAI.EditApproximation.PhysicalRationalAction M target.length) := + ((OAI.EditApproximation.dyadicScales N).filter fun (b : ℕ) => decide + (parentInitial q / (16 * F) ≤ b ∧ (b : ℚ) ≤ 8 * a * parentInitial q)).flatMap fun (b : ℕ) => + (OAI.EditApproximation.localTargetCells (theta * b) ⌈parentInitial q⌉₊ q).filterMap fun cell => + OAI.EditApproximation.chooseCellGroupAction source target parent b P F exponent Q tau a parentInitial + child initial current cell (draw b cell) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {ι : Type u_1} {α : Type u_2} (source target : List α) {M : ℕ} (parent : TargetInterval source.length) (N P F exponent H Q : ℕ) (tau a eta kappa delta : ℚ) (t : ℕ) (parentInitial : TargetInterval target.length → ℚ) (child initial : Fin M → TargetInterval target.length → ℚ) (draw : CellGroupDraws M F Q) (integer : ℕ → TargetInterval target.length → ℕ) (q : TargetInterval target.length) (readEarlier : (Fin M × ℕ × TargetInterval target.length) → FiniteQuery ι) (readCurrent : (Fin M × TargetInterval target.length) → FiniteQuery ι) + +def localRefinementStepQuery : OAI.EditApproximation.FiniteQuery ι := by + have proof_mixedRadix_injective_84 {radix : ℕ} {lo : ℕ} {lo' : ℕ} {hi : ℕ} {hi' : ℕ} (hlo : LT.lt.{0} lo radix) (hlo' : LT.lt.{0} lo' radix) (heq : Eq.{1} (HAdd.hAdd.{0, 0, 0} lo (HMul.hMul.{0, 0, 0} radix hi)) (HAdd.hAdd.{0, 0, 0} lo' (HMul.hMul.{0, 0, 0} radix hi'))) : lo = lo' ∧ hi = hi' := by + have hmod := congrArg (fun n => n % radix) heq + simp only [Nat.add_mul_mod_self_left, Nat.mod_eq_of_lt hlo, Nat.mod_eq_of_lt hlo'] at hmod + refine ⟨hmod, ?_⟩ + apply Nat.mul_left_cancel (by omega : 0 < radix) + omega + have proof_childInputCode_injective_83 (M : ℕ) (n : ℕ) : + Function.Injective (@OAI.EditApproximation.childInputCode M n) := by + rintro ⟨i, q⟩ ⟨i', q'⟩ heq + obtain ⟨hi, hq⟩ := proof_mixedRadix_injective_84 i.isLt i'.isLt heq + have hqlo : q.lo < n + 1 := by have := q.ordered.trans q.valid; omega + have hqlo' : q'.lo < n + 1 := by have := q'.ordered.trans q'.valid; omega + obtain ⟨hlo, hhi⟩ := proof_mixedRadix_injective_84 hqlo hqlo' hq + have hqeq : q = q' := by cases q; cases q'; cases hlo; cases hhi; rfl + exact Prod.ext (Fin.ext hi) hqeq + have proof_historyInputCode_injective_82 (M : ℕ) (n : ℕ) : + Function.Injective (OAI.EditApproximation.historyInputCode (M := M) (n := n)) := by + rintro ⟨i, s, q⟩ ⟨i', s', q'⟩ heq + have h := Nat.pair_eq_pair.mp heq + have hc := proof_childInputCode_injective_83 M n h.2 + cases hc + cases h.1 + rfl + exact + let earlierKeys := OAI.EditApproximation.orderedInputs OAI.EditApproximation.historyInputCode (proof_historyInputCode_injective_82 M target.length) + (OAI.EditApproximation.queryEarlierInputCover parent N P F exponent t a parentInitial q) + OAI.EditApproximation.FiniteQuery.collect readEarlier earlierKeys fun earlierAnswers => + let earlier := fun i s r => OAI.EditApproximation.finiteAnswerTable earlierKeys earlierAnswers (i, s, r) + let online := OAI.EditApproximation.localOnlineCandidates source target parent N P F exponent H tau a eta kappa + parentInitial child initial earlier (t - 1) integer q + let sharedKeys := OAI.EditApproximation.orderedInputs OAI.EditApproximation.childInputCode (proof_childInputCode_injective_83 M target.length) + (OAI.EditApproximation.querySharedInputCover source target parent N F exponent Q a parentInitial q draw) + OAI.EditApproximation.FiniteQuery.collect readCurrent sharedKeys fun sharedAnswers => + let current := fun i r => OAI.EditApproximation.finiteAnswerTable sharedKeys sharedAnswers (i, r) + let selected := OAI.EditApproximation.localCellGroupActions source target parent N P F exponent Q tau a + parentInitial child initial current draw q + let needed := OAI.EditApproximation.actionCurrentInputCover selected ∪ OAI.EditApproximation.actionCurrentInputCover online + let currentKeys := OAI.EditApproximation.orderedInputs OAI.EditApproximation.childInputCode (proof_childInputCode_injective_83 M target.length) needed + OAI.EditApproximation.FiniteQuery.collect readCurrent currentKeys fun currentAnswers => + let value := OAI.EditApproximation.rationalActionValue (fun q r => OAI.EditApproximation.targetEndpointDistance q r) (128 * F) + (OAI.EditApproximation.finiteAnswerTable currentKeys currentAnswers) q + let fallback := OAI.EditApproximation.rationalBellman parentInitial (fun q r => OAI.EditApproximation.targetEndpointDistance q r) (128 * F) + (OAI.EditApproximation.rationalActualWideActions parent (OAI.EditApproximation.localRefinementRepresentatives N P F a parentInitial q) P) + (fun input => earlier input.1 (t - 1) input.2) q + .done (OAI.EditApproximation.rationalRefinementUpdate delta (OAI.EditApproximation.rationalMinimum fallback (selected.map value)) + (OAI.EditApproximation.rationalOnlineMinimum (online.map value))) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {ι : Type u_1} {α : Type u_2} (source target : List α) {M : ℕ} (parent : TargetInterval source.length) (N P F exponent H Q : ℕ) (tau a eta kappa delta : ℚ) (t : ℕ) (parentInitial : TargetInterval target.length → ℚ) (child initial : Fin M → TargetInterval target.length → ℚ) (draw : CellGroupDraws M F Q) (q : TargetInterval target.length) (readInteger : (ℕ × TargetInterval target.length) → ℕ → FiniteQuery ι) (readEarlier : (Fin M × ℕ × TargetInterval target.length) → FiniteQuery ι) (readCurrent : (Fin M × TargetInterval target.length) → FiniteQuery ι) + +def localOnlineSourceStepQuery : OAI.EditApproximation.FiniteQuery ι := + let keys := OAI.EditApproximation.localOnlineSourceKeys N P F a parentInitial q + OAI.EditApproximation.FiniteQuery.collect + (fun key => readInteger key (OAI.EditApproximation.keyedOnlineSourceRange source target parent P exponent H tau child key)) + keys fun values => + OAI.EditApproximation.localRefinementStepQuery source target parent N P F exponent H Q tau a eta kappa delta t + parentInitial child initial draw (fun b r => ⌊OAI.EditApproximation.finiteAnswerTable keys values (b, r)⌋₊) q + readEarlier readCurrent + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {ι : Type u_1} {β : Type u_2} {α : Type u_3} (source target : List α) {M : ℕ} (parent : TargetInterval source.length) (N P F exponent Q eM eF : ℕ) (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (a : BinaryFraction) (t : ℕ) (initial : TargetInterval target.length → BinaryFraction × ℕ) (draw : CountedCellGroupDraws M F Q) (q : TargetInterval target.length) (readEarlier : (Fin M × ℕ × TargetInterval target.length) → BitQuery ι BinaryFraction) (readCurrent : (Fin M × TargetInterval target.length) → BitQuery ι BinaryFraction) (online : List (Fin M × ℕ × TargetInterval target.length) → List BinaryFraction → + List (BinaryBellmanAction (TargetInterval target.length) + (Fin M × TargetInterval target.length) M) × ℕ) (selected : List (Fin M × TargetInterval target.length) → List BinaryFraction → + List (BinaryBellmanAction (TargetInterval target.length) + (Fin M × TargetInterval target.length) M) × ℕ) (next : List (Fin M × ℕ × TargetInterval target.length) → List BinaryFraction → + List (BinaryBellmanAction (TargetInterval target.length) (Fin M × TargetInterval target.length) M) → + List (BinaryBellmanAction (TargetInterval target.length) (Fin M × TargetInterval target.length) M) → + List (Fin M × TargetInterval target.length) → List BinaryFraction → BitQuery ι β) + +def queryRefinementGather : OAI.EditApproximation.BitQuery ι β := + (OAI.EditApproximation.BitQuery.compute (OAI.EditApproximation.BinaryFraction.queryEarlierInputsWithWork M parent N P F exponent t hP a initial q)).bind + fun earlierKeys => OAI.EditApproximation.BitQuery.collect readEarlier earlierKeys fun earlierWords => + (OAI.EditApproximation.BitQuery.compute (online earlierKeys earlierWords)).bind fun onlineActions => + let word := initial q + .charge word.2 ((OAI.EditApproximation.BitQuery.compute (OAI.EditApproximation.BinaryFraction.querySharedInputsWithWork M N F Q exponent + eM eF hM hF parent a word.1 q draw)).bind fun sharedKeys => + OAI.EditApproximation.BitQuery.collect readCurrent sharedKeys fun sharedWords => + (OAI.EditApproximation.BitQuery.compute (selected sharedKeys sharedWords)).bind fun selectedActions => + (OAI.EditApproximation.BitQuery.compute (OAI.EditApproximation.queryNeededInputsWithWork selectedActions onlineActions)).bind + fun currentKeys => OAI.EditApproximation.BitQuery.collect readCurrent currentKeys + (next earlierKeys earlierWords selectedActions onlineActions currentKeys)) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BinaryFraction +variable {nx ny M : ℕ} (parent : TargetInterval nx) (N P F : ℕ) (a delta : BinaryFraction) (initial : TargetInterval ny → BinaryFraction × ℕ) (t : ℕ) (earlierKeys : List (Fin M × ℕ × TargetInterval ny)) (earlierWords : List BinaryFraction) (groups online : List (BinaryBellmanAction (TargetInterval ny) (Fin M × TargetInterval ny) M)) (currentKeys : List (Fin M × TargetInterval ny)) (currentWords : List BinaryFraction) (query : TargetInterval ny) + +def queryRefinementFinishWithWork : OAI.EditApproximation.BinaryFraction × ℕ := + let fallback := initial query + let representatives := OAI.EditApproximation.BinaryFraction.localRepresentativeReadWithWork N P F a initial query + let result := OAI.EditApproximation.BinaryFraction.physicalContinuationReadWithWork parent representatives.1 P F delta fallback.1 + (OAI.EditApproximation.BinaryFraction.queryHistoryReadWithWork earlierKeys earlierWords (t - 1)) + (fun input => OAI.EditApproximation.BinaryFraction.queryChildReadWithWork currentKeys currentWords input.1 input.2) + groups online query + (result.1, fallback.2 + representatives.2 + result.2 + 2) + + +end OAI.EditApproximation.BinaryFraction +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {ι : Type u_1} {α : Type u_2} (source target : List α) {M : ℕ} [NeZero M] (parent : TargetInterval source.length) (N P F exponent H Q : ℕ) (tau a eta kappa delta : ℚ) (t : ℕ) (parentInitial : TargetInterval target.length → ℚ) (child initial : Fin M → TargetInterval target.length → ℚ) (q : TargetInterval target.length) (readGroup : GroupScalarKey M F Q → FiniteQuery ι) (readInteger : (ℕ × TargetInterval target.length) → ℕ → FiniteQuery ι) (readEarlier : (Fin M × ℕ × TargetInterval target.length) → FiniteQuery ι) (readCurrent : (Fin M × TargetInterval target.length) → FiniteQuery ι) + +noncomputable def localRandomSourceStepQuery : OAI.EditApproximation.FiniteQuery ι := + let keys := OAI.EditApproximation.groupScalarKeys M F Q (OAI.EditApproximation.localGroupQueryKeys N F exponent a parentInitial q) + OAI.EditApproximation.FiniteQuery.collect readGroup keys fun values => + OAI.EditApproximation.localOnlineSourceStepQuery source target parent N P F exponent H Q tau a eta kappa delta t + parentInitial child initial (OAI.EditApproximation.groupDrawFromValues keys values) q readInteger readEarlier readCurrent + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {ι : Type u_1} {α : Type u_2} (source target : List α) {M : ℕ} [NeZero M] (parent : TargetInterval source.length) (N P F exponent H Q : ℕ) (tau a eta kappa delta : ℚ) (t : ℕ) (parentInitial : TargetInterval target.length → ℚ) (readMass readInitial : Fin M × TargetInterval target.length → FiniteQuery ι) (readGroup : GroupScalarKey M F Q → FiniteQuery ι) (readInteger : (ℕ × TargetInterval target.length) → ℕ → FiniteQuery ι) (q : TargetInterval target.length) (readEarlier : (Fin M × ℕ × TargetInterval target.length) → FiniteQuery ι) (readCurrent : (Fin M × TargetInterval target.length) → FiniteQuery ι) + +noncomputable def localRandomBandDataQuery : OAI.EditApproximation.FiniteQuery ι := + let keys := OAI.EditApproximation.refinementBandInputList (M := M) parent N P F exponent a parentInitial q + OAI.EditApproximation.FiniteQuery.collect readMass keys fun massValues => + OAI.EditApproximation.FiniteQuery.collect readInitial keys fun initialValues => + OAI.EditApproximation.localRandomSourceStepQuery source target parent N P F exponent H Q tau a eta kappa delta t + parentInitial (fun i r => OAI.EditApproximation.finiteAnswerTable keys massValues (i, r)) + (fun i r => OAI.EditApproximation.finiteAnswerTable keys initialValues (i, r)) q readGroup readInteger readEarlier readCurrent + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {ι : Type u_1} {α : Type u_2} (source target : List α) {M : ℕ} [NeZero M] (parent : TargetInterval source.length) (N P F exponent H Q : ℕ) (tau a eta kappa delta : ℚ) (t : ℕ) (readParentInitial : TargetInterval target.length → FiniteQuery ι) (readMass readInitial : Fin M × TargetInterval target.length → FiniteQuery ι) (readGroup : GroupScalarKey M F Q → FiniteQuery ι) (readInteger : (ℕ × TargetInterval target.length) → ℕ → FiniteQuery ι) (q : TargetInterval target.length) (readEarlier : (Fin M × ℕ × TargetInterval target.length) → FiniteQuery ι) (readCurrent : (Fin M × TargetInterval target.length) → FiniteQuery ι) + +noncomputable def localRandomDataQuery : OAI.EditApproximation.FiniteQuery ι := + OAI.EditApproximation.FiniteQuery.bind (readParentInitial q) fun value => + let keys := OAI.EditApproximation.refinementInitialSupport N P F exponent a value q + OAI.EditApproximation.FiniteQuery.collect readParentInitial keys fun initialValues => + OAI.EditApproximation.localRandomBandDataQuery source target parent N P F exponent H Q tau a eta kappa delta t + (OAI.EditApproximation.finiteAnswerTable keys initialValues) readMass readInitial readGroup readInteger q readEarlier readCurrent + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {M J N n exponent F Q R B : ℕ} + +def physicalScalarCode (key : OAI.EditApproximation.PhysicalScalarKey M J N n exponent F Q R B) : ℕ := + match key with + | ⟨.inl online, time⟩ => 2 * Nat.pair (OAI.EditApproximation.physicalEntryCode (online.1.1.val, online.1.2.2)) + (Nat.pair online.1.2.1.val (Nat.pair online.2.val.val time.val)) + | ⟨.inr group, index⟩ => 2 * Nat.pair (OAI.EditApproximation.physicalNodeCode group.1.val) + (Nat.pair group.2.1.val (Nat.pair group.2.2.1.val (Nat.pair group.2.2.2.val + (Nat.pair index.1.val (Nat.pair index.2.1.val index.2.2.val))))) + 1 + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable (M J N n exponent F Q R B : ℕ) [NeZero M] +open MeasureTheory ProbabilityTheory + +def physicalScalarGroupQueries (node : OAI.EditApproximation.PhysicalInternalNode M J) (time : Fin R) + (b : ℕ) (cell : ℕ × ℕ) : OAI.EditApproximation.PhysicalGroupQueries M J N n exponent F Q R B b := by + have proof_physicalScaleIndex_get_93 (N : ℕ) (b : ℕ) (hb : Membership.mem.{0, 0} (OAI.EditApproximation.dyadicScales N) b) : + (OAI.EditApproximation.dyadicScales N).get (OAI.EditApproximation.physicalScaleIndex N b hb) = b := + List.getElem_idxOf (List.idxOf_lt_length_of_mem hb) + exact + if hb : b ∈ OAI.EditApproximation.dyadicScales N then + if hc : cell.1 ≤ n * 2 ^ exponent ∧ cell.2 ≤ n * 2 ^ exponent then + let key : OAI.EditApproximation.PhysicalLocalGroupKey M J N n exponent := + (node, OAI.EditApproximation.physicalScaleIndex N b hb, + ⟨cell.1, Nat.lt_succ_of_le hc.1⟩, ⟨cell.2, Nat.lt_succ_of_le hc.2⟩) + Eq.mp (congrArg (OAI.EditApproximation.PhysicalGroupQueries M J N n exponent F Q R B) + (proof_physicalScaleIndex_get_93 N b hb)) (OAI.EditApproximation.physicalScalarGroupQueriesAt M J N n exponent F Q R B key time) + else fun _ _ => .done 0 + else fun _ _ => .done 0 + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable (M J N n exponent F Q R B : ℕ) [NeZero M] + +def physicalScalarGroupRead (node : OAI.EditApproximation.PhysicalInternalNode M J) (time : Fin R) + (key : OAI.EditApproximation.GroupScalarKey M F Q) : OAI.EditApproximation.FiniteQuery (OAI.EditApproximation.PhysicalScalarKey M J N n exponent F Q R B) := + OAI.EditApproximation.physicalScalarGroupQueries M J N n exponent F Q R B node time key.1.1 key.1.2 key.2.1 key.2.2 + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {σ : Type u_1} {α : Type u_2} (source target : List α) {M J : ℕ} [NeZero M] (N P F exponent H Q : ℕ) (tau a eta kappa delta : ℚ) (pass copy T S t : ℕ) (ht : 0 < t) (node : PhysicalNode M J) (hbelow : node.1.val < J) (readGroup : GroupScalarKey M F Q → FiniteQuery σ) (readInteger : (ℕ × TargetInterval target.length) → ℕ → FiniteQuery σ) (q : TargetInterval target.length) + +noncomputable def physicalRandomDataRequestQuery : + OAI.EditApproximation.FiniteQuery (Sum σ {child : OAI.EditApproximation.PhysicalTableRequest M J target.length // + child.combinedRank T S < (OAI.EditApproximation.PhysicalTableRequest.refinement pass copy node T t q).combinedRank T S}) := + OAI.EditApproximation.localRandomDataQuery source target (OAI.EditApproximation.physicalSourceInterval source.length node) + N P F exponent H Q tau a eta kappa delta t + (fun r => OAI.EditApproximation.FiniteQuery.mapKeys Sum.inr + (OAI.EditApproximation.physicalRefinementWarmupRead pass copy T S t ht node q node le_rfl 0 (Nat.zero_le T) r)) + (fun input => OAI.EditApproximation.FiniteQuery.mapKeys Sum.inr + (OAI.EditApproximation.physicalRefinementMassQuery pass copy T S t ht node hbelow q input)) + (fun input => OAI.EditApproximation.FiniteQuery.mapKeys Sum.inr + (OAI.EditApproximation.physicalRefinementWarmupRead pass copy T S t ht node q + (OAI.EditApproximation.physicalChild node hbelow input.1) (by change node.1.val ≤ node.1.val + 1; omega) + 0 (Nat.zero_le T) input.2)) + (fun key => OAI.EditApproximation.FiniteQuery.mapKeys Sum.inl (readGroup key)) + (fun key range => OAI.EditApproximation.FiniteQuery.mapKeys Sum.inl (readInteger key range)) q + (fun input => OAI.EditApproximation.FiniteQuery.mapKeys Sum.inr + (OAI.EditApproximation.physicalRefinementEarlierQuery pass copy T S t node hbelow q input)) + (fun input => OAI.EditApproximation.FiniteQuery.mapKeys Sum.inr + (OAI.EditApproximation.physicalRefinementCurrentQuery pass copy T S t node hbelow q input)) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {σ : Type*} {α : Type u_2} [DecidableEq α] {M J R : ℕ} [NeZero M] [NeZero R] (source target : List α) (N P F exponent H Q T S copies : ℕ) (factor : ℕ → ℚ) (multiplier : ℕ → ℕ) (tau eta kappa delta : ℚ) (readGroup : ℕ → ℕ → PhysicalInternalNode M J → Fin R → GroupScalarKey M F Q → FiniteQuery σ) (readInteger : ℕ → ℕ → PhysicalInternalNode M J → Fin R → + (ℕ × TargetInterval target.length) → ℕ → FiniteQuery σ) (initial : PhysicalEntry M J target.length → ℕ) + +def physicalInactiveGlobalQuery (request : OAI.EditApproximation.PhysicalTableRequest M J target.length) : + OAI.EditApproximation.FiniteQuery {child : OAI.EditApproximation.PhysicalTableRequest M J target.length // + child.combinedRank T S < request.combinedRank T S} := + if request.index ≤ T then + OAI.EditApproximation.physicalWarmupRequestQuery source target N P F (factor request.pass) + request.pass request.copy T S request.index request.node request.state + (OAI.EditApproximation.globalSeedRead N T S copies multiplier initial request) + else OAI.EditApproximation.physicalInitialQuery source target N P F (factor request.pass) + (OAI.EditApproximation.globalSeedRead N T S copies multiplier initial request) (request.node, request.state) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {σ : Type u_1} {α : Type u_2} [DecidableEq α] {M J R : ℕ} [NeZero M] [NeZero R] (source target : List α) (N P F exponent H Q T S copies : ℕ) (factor : ℕ → ℚ) (multiplier : ℕ → ℕ) (tau eta kappa delta : ℚ) (readGroup : ℕ → ℕ → PhysicalInternalNode M J → Fin R → GroupScalarKey M F Q → FiniteQuery σ) (readInteger : ℕ → ℕ → PhysicalInternalNode M J → Fin R → + (ℕ × TargetInterval target.length) → ℕ → FiniteQuery σ) (initial : PhysicalEntry M J target.length → ℕ) + +noncomputable def physicalRandomGlobalQuery (request : OAI.EditApproximation.PhysicalTableRequest M J target.length) : + OAI.EditApproximation.FiniteQuery (Sum σ {child : OAI.EditApproximation.PhysicalTableRequest M J target.length // + child.combinedRank T S < request.combinedRank T S}) := by + by_cases hactive : T < request.index ∧ request.node.1.val < J ∧ + ¬ (OAI.EditApproximation.physicalSourceInterval source.length request.node).hi - + (OAI.EditApproximation.physicalSourceInterval source.length request.node).lo ≤ 1 + · have ht : 0 < request.index - T := Nat.sub_pos_of_lt hactive.1 + have hrequest : OAI.EditApproximation.PhysicalTableRequest.refinement request.pass request.copy request.node + T (request.index - T) request.state = request := by + have hi : T + (request.index - T) = request.index := by omega + unfold OAI.EditApproximation.PhysicalTableRequest.refinement + rw [hi] + let node : OAI.EditApproximation.PhysicalInternalNode M J := ⟨request.node, hactive.2.1⟩ + let time : Fin R := Fin.ofNat R (request.index - T - 1) + exact OAI.EditApproximation.FiniteQuery.mapKeys + (Sum.map id (fun child => ⟨child.val, by simpa only [hrequest] using child.property⟩)) + (OAI.EditApproximation.physicalRandomDataRequestQuery source target N P F exponent H Q tau + (OAI.EditApproximation.refinementFactor (factor request.pass) F) eta kappa delta request.pass request.copy T S + (request.index - T) ht request.node hactive.2.1 + (readGroup request.pass request.copy node time) + (readInteger request.pass request.copy node time) request.state) + · exact OAI.EditApproximation.FiniteQuery.mapKeys Sum.inr + (OAI.EditApproximation.physicalInactiveGlobalQuery source target N P F T S copies factor multiplier initial request) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.PhysicalTableRequest + + +def entryCapacity (M J n : ℕ) : ℕ := (n + 1) ^ 2 * (M ^ J * (J + 1)) + +def code {M J n : ℕ} (copies T S : ℕ) (request : OAI.EditApproximation.PhysicalTableRequest M J n) : ℕ := + request.index + (T + S + 1) * (request.copy + copies * + (OAI.EditApproximation.physicalEntryCode (request.node, request.state) + OAI.EditApproximation.PhysicalTableRequest.entryCapacity M J n * request.pass)) + + +end OAI.EditApproximation.PhysicalTableRequest +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.SourceRanked +variable {σ : Type u_1} {κ : Type u_2} (tableRank : κ → ℕ) (supported : κ → Prop) + +def supportedChild (parent : κ) : Sum σ {key : κ // tableRank key < tableRank parent} → Prop + | .inl _ => True + | .inr table => supported table.val + +def supportedChildMap (parent : {key : κ // supported key}) : + {key : Sum σ {key : κ // tableRank key < tableRank parent.val} // + OAI.EditApproximation.SourceRanked.supportedChild tableRank supported parent.val key} → + Sum σ {key : {key : κ // supported key} // tableRank key.val < tableRank parent.val} + | ⟨.inl source, _⟩ => .inl source + | ⟨.inr table, hs⟩ => .inr ⟨⟨table.val, hs⟩, table.property⟩ + +noncomputable def restrictBody + (tableBody : (parent : κ) → OAI.EditApproximation.FiniteQuery (Sum σ {key : κ // tableRank key < tableRank parent})) + (parent : {key : κ // supported key}) : + OAI.EditApproximation.FiniteQuery (Sum σ {key : {key : κ // supported key} // tableRank key.val < tableRank parent.val}) := by + classical + exact OAI.EditApproximation.FiniteQuery.mapKeys (OAI.EditApproximation.SourceRanked.supportedChildMap tableRank supported parent) + (OAI.EditApproximation.FiniteQuery.restrict (OAI.EditApproximation.SourceRanked.supportedChild tableRank supported parent.val) (tableBody parent.val)) + + +end OAI.EditApproximation.SourceRanked +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {σ : Type u_1} {α : Type u_2} [DecidableEq α] {M J R : ℕ} [NeZero M] [NeZero R] (source target : List α) (N P F exponent H Q T S passes copies : ℕ) (factor : ℕ → ℚ) (multiplier : ℕ → ℕ) (tau eta kappa delta : ℚ) (readGroup : ℕ → ℕ → PhysicalInternalNode M J → Fin R → GroupScalarKey M F Q → FiniteQuery σ) (readInteger : ℕ → ℕ → PhysicalInternalNode M J → Fin R → + (ℕ × TargetInterval target.length) → ℕ → FiniteQuery σ) (initial : PhysicalEntry M J target.length → ℕ) + +noncomputable def physicalRandomBoundedQuery + (request : {request : OAI.EditApproximation.PhysicalTableRequest M J target.length // request.Bounded passes copies T S}) : + OAI.EditApproximation.FiniteQuery (Sum σ {child : {child : OAI.EditApproximation.PhysicalTableRequest M J target.length // + child.Bounded passes copies T S} // child.val.combinedRank T S < request.val.combinedRank T S}) := + OAI.EditApproximation.SourceRanked.restrictBody (OAI.EditApproximation.PhysicalTableRequest.combinedRank T S) + (OAI.EditApproximation.PhysicalTableRequest.Bounded passes copies T S) + (OAI.EditApproximation.physicalRandomGlobalQuery source target N P F exponent H Q T S copies factor multiplier + tau eta kappa delta readGroup readInteger initial) request + +noncomputable def chargedRandomGlobalQuery + (request : OAI.EditApproximation.ChargedPhysicalRequest M J target.length passes copies T S) : + OAI.EditApproximation.FiniteQuery (Sum σ {child : OAI.EditApproximation.ChargedPhysicalRequest M J target.length passes copies T S // + child.rank < request.rank}) := by + have proof_table_rank_lt_99 {M : ℕ} {J : ℕ} {ny : ℕ} {passes : ℕ} {copies : ℕ} {T : ℕ} {S : ℕ} (parent : Subtype.{1} fun request => OAI.EditApproximation.PhysicalTableRequest.Bounded (M := M) (J := J) (ny := ny) passes copies T S request) (child : Subtype.{1} fun request => OAI.EditApproximation.PhysicalTableRequest.Bounded (M := M) (J := J) (ny := ny) passes copies T S request) (h : LT.lt.{0} (OAI.EditApproximation.PhysicalTableRequest.combinedRank T S child.val) + (OAI.EditApproximation.PhysicalTableRequest.combinedRank T S parent.val)) : + OAI.EditApproximation.ChargedPhysicalRequest.rank (Sum.inr child : OAI.EditApproximation.ChargedPhysicalRequest M J ny passes copies T S) < OAI.EditApproximation.ChargedPhysicalRequest.rank (Sum.inr parent) := by + simpa only [OAI.EditApproximation.ChargedPhysicalRequest.rank, OAI.EditApproximation.ChargedPhysicalRequest.depth, OAI.EditApproximation.ChargedPhysicalRequest.index, ← Nat.add_assoc, OAI.EditApproximation.PhysicalTableRequest.combinedRank] using + Nat.add_lt_add_right h 1 + exact + match request with + | .inl entry => .done (initial entry) + | .inr parent => + if parent.val.index ≤ T then + OAI.EditApproximation.FiniteQuery.mapKeys Sum.inr (OAI.EditApproximation.chargedWarmupQuery source target N P F factor multiplier parent) + else if parent.val.node.1.val < J then + if (OAI.EditApproximation.physicalSourceInterval source.length parent.val.node).hi - + (OAI.EditApproximation.physicalSourceInterval source.length parent.val.node).lo ≤ 1 then + OAI.EditApproximation.FiniteQuery.mapKeys Sum.inr + (OAI.EditApproximation.physicalInitialQuery source target N P F (factor parent.val.pass) + (OAI.EditApproximation.chargedSeedQuery N multiplier parent) (parent.val.node, parent.val.state)) + else OAI.EditApproximation.FiniteQuery.mapKeys + (Sum.map id (fun child => + ⟨Sum.inr child.val, proof_table_rank_lt_99 parent child.val child.property⟩)) + (OAI.EditApproximation.physicalRandomBoundedQuery source target N P F exponent H Q T S passes copies factor multiplier + tau eta kappa delta readGroup readInteger initial parent) + else OAI.EditApproximation.FiniteQuery.mapKeys Sum.inr + (OAI.EditApproximation.physicalInitialQuery source target N P F (factor parent.val.pass) + (OAI.EditApproximation.chargedSeedQuery N multiplier parent) (parent.val.node, parent.val.state)) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {α : Type u_1} [DecidableEq α] {M J R : ℕ} [NeZero M] [NeZero R] (source target : List α) (N P F exponent H Q T S passes copies : ℕ) + +abbrev PhysicalFamilyScalarKey := Fin (passes + 1) × Fin (copies + 1) × + OAI.EditApproximation.PhysicalScalarKey M J N target.length exponent F Q R (OAI.EditApproximation.localOnlineMassBound M P H) + +abbrev PhysicalFamilyScalarDraw := ∀ key : OAI.EditApproximation.PhysicalFamilyScalarKey + (M := M) (J := J) (R := R) target N P F exponent H Q passes copies, + Fin (OAI.EditApproximation.physicalScalarRange M J N target.length exponent F Q R (OAI.EditApproximation.localOnlineMassBound M P H) key.2.2) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {α : Type u_1} [DecidableEq α] {M J R : ℕ} [NeZero M] [NeZero R] (source target : List α) (N P F exponent H Q T S passes copies : ℕ) +variable (draw : PhysicalFamilyScalarDraw + (M := M) (J := J) (R := R) target N P F exponent H Q passes copies) + +def physicalFamilyAnswer (key : OAI.EditApproximation.PhysicalFamilyScalarKey + (M := M) (J := J) (R := R) target N P F exponent H Q passes copies) : ℚ := + (draw key).val + +def physicalFamilyGroupRead (pass copy : ℕ) (node : OAI.EditApproximation.PhysicalInternalNode M J) (time : Fin R) + (key : OAI.EditApproximation.GroupScalarKey M F Q) : OAI.EditApproximation.FiniteQuery (OAI.EditApproximation.PhysicalFamilyScalarKey + (M := M) (J := J) (R := R) target N P F exponent H Q passes copies) := + OAI.EditApproximation.FiniteQuery.mapKeys (fun scalar => (Fin.ofNat (passes + 1) pass, Fin.ofNat (copies + 1) copy, scalar)) + (OAI.EditApproximation.physicalScalarGroupRead M J N target.length exponent F Q R (OAI.EditApproximation.localOnlineMassBound M P H) node time key) + +def physicalFamilyOnlineRead (pass copy : ℕ) (node : OAI.EditApproximation.PhysicalInternalNode M J) (time : Fin R) + (key : ℕ × OAI.EditApproximation.TargetInterval target.length) (range : ℕ) : OAI.EditApproximation.FiniteQuery (OAI.EditApproximation.PhysicalFamilyScalarKey + (M := M) (J := J) (R := R) target N P F exponent H Q passes copies) := + OAI.EditApproximation.FiniteQuery.mapKeys (fun scalar => (Fin.ofNat (passes + 1) pass, Fin.ofNat (copies + 1) copy, scalar)) + (OAI.EditApproximation.physicalScalarOnlineRead M J N target.length exponent F Q R (OAI.EditApproximation.localOnlineMassBound M P H) node time key range) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {M J R passes copies T S : ℕ} [NeZero M] [NeZero R] (source target : List ℕ) (N P F exponent H Q eM eF : ℕ) (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (A a : ℕ → BinaryFraction) (tau eta kappa delta : BinaryFraction) (multiplier : ℕ → ℕ) (occurrence : BinaryMemo PositionCounts) (symbolBits positionBits : ℕ) (coarse : PhysicalEntry M J target.length → BinaryFraction × ℕ) (draw : PhysicalFamilyScalarDraw (M := M) (J := J) (R := R) + target N P F exponent H Q passes copies) + +abbrev QueryFamilyMemoKey := + Sum (OAI.EditApproximation.PhysicalFamilyScalarKey (M := M) (J := J) (R := R) target N P F exponent H Q passes copies) + (OAI.EditApproximation.ChargedPhysicalRequest M J target.length (passes + 1) copies T S) + +def queryFamilySourceWordWithWork + (key : OAI.EditApproximation.PhysicalFamilyScalarKey (M := M) (J := J) (R := R) + target N P F exponent H Q passes copies) : OAI.EditApproximation.BinaryFraction × ℕ := + (OAI.EditApproximation.BinaryFraction.nat (draw key).val, Nat.size (draw key).val + 3) + +def queryFamilyMemoRemaining : OAI.EditApproximation.QueryFamilyMemoKey (M := M) (J := J) (R := R) (passes := passes) (copies := copies) (T := T) (S := S) target N P F exponent H Q → ℕ + | .inl _ => 0 + | .inr request => OAI.EditApproximation.chargedPhysicalRemaining request + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open Filter MeasureTheory + +abbrev ComputedFamilySeed (source target : List ℕ) (N : ℕ) := + OAI.EditApproximation.ClampedPhysicalSeed (OAI.EditApproximation.integerParameters N).M + (OAI.EditApproximation.intervalTreeDepth (OAI.EditApproximation.integerParameters N).M source.length) target.length N + +abbrev ComputedFamilyDraw (source target : List ℕ) (N : ℕ) := + OAI.EditApproximation.PhysicalFamilyScalarDraw (M := (OAI.EditApproximation.integerParameters N).M) + (J := OAI.EditApproximation.intervalTreeDepth (OAI.EditApproximation.integerParameters N).M source.length) (R := OAI.EditApproximation.inputHeight N ^ 2) + target N (OAI.EditApproximation.integerParameters N).P (OAI.EditApproximation.inputSmallLog N) (40 * OAI.EditApproximation.smallLogExponent N) + (OAI.EditApproximation.inputHeight N) (OAI.EditApproximation.inputSmallLog N ^ 80) (OAI.EditApproximation.computedSeedPassCount N) (OAI.EditApproximation.inputHeight N ^ 2) + +abbrev ComputedFamilyInput (source target : List ℕ) (N : ℕ) := + OAI.EditApproximation.ComputedFamilySeed source target N × OAI.EditApproximation.ComputedFamilyDraw source target N + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {α : Type u_1} {M J R : ℕ} (target : List α) (N P F exponent H Q passes copies : ℕ) +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyEncoding_3) "Key" => PhysicalFamilyScalarKey (M := M) (J := J) (R := R) + target N P F exponent H Q passes copies + +def physicalFamilyCode (key : Key) : ℕ := + Nat.pair key.1.val (Nat.pair key.2.1.val (OAI.EditApproximation.physicalScalarCode key.2.2)) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.ChargedPhysicalRequest + + +def code {M J ny passes copies T S : ℕ} : OAI.EditApproximation.ChargedPhysicalRequest M J ny passes copies T S → ℕ + | .inl entry => 2 * OAI.EditApproximation.physicalEntryCode entry + | .inr request => 2 * OAI.EditApproximation.PhysicalTableRequest.code copies T S request.val + 1 + + +end OAI.EditApproximation.ChargedPhysicalRequest +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation + + +abbrev ComputedFamilyScalarKey (source target : List ℕ) (N R : ℕ) := + OAI.EditApproximation.PhysicalFamilyScalarKey (M := (OAI.EditApproximation.integerParameters N).M) + (J := OAI.EditApproximation.intervalTreeDepth (OAI.EditApproximation.integerParameters N).M source.length) (R := R) + target N (OAI.EditApproximation.integerParameters N).P (OAI.EditApproximation.inputSmallLog N) (40 * OAI.EditApproximation.smallLogExponent N) + (OAI.EditApproximation.inputHeight N) (OAI.EditApproximation.inputSmallLog N ^ 80) (OAI.EditApproximation.computedSeedPassCount N) (OAI.EditApproximation.inputHeight N ^ 2) + +def computedFamilyMemoCode (source target : List ℕ) (N R : ℕ) : + Sum (OAI.EditApproximation.ComputedFamilyScalarKey source target N R) (OAI.EditApproximation.ComputedFamilyTableKey source target N) → ℕ := + OAI.EditApproximation.SourceRanked.keyCode + (OAI.EditApproximation.physicalFamilyCode target N (OAI.EditApproximation.integerParameters N).P (OAI.EditApproximation.inputSmallLog N) (40 * OAI.EditApproximation.smallLogExponent N) + (OAI.EditApproximation.inputHeight N) (OAI.EditApproximation.inputSmallLog N ^ 80) (OAI.EditApproximation.computedSeedPassCount N) (OAI.EditApproximation.inputHeight N ^ 2)) + OAI.EditApproximation.ChargedPhysicalRequest.code + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open EditDistortion Finset MeasureTheory ProbabilityTheory + +def coarseInitialCandidate {α : Type u} [DecidableEq α] + (B D : ℕ) (Q lam : ℚ) (x y : List α) + (i : OAI.EditApproximation.CoarseGuessIndex (OAI.EditApproximation.coarseEntryWidth x y)) (draws : OAI.EditApproximation.CoarseThresholdDraws B D) : ℚ := + let k := OAI.EditApproximation.coarseGuess (OAI.EditApproximation.coarseEntryWidth x y) i + 2 * (OAI.EditApproximation.coarseThresholdEstimate k Q lam + (OAI.EditApproximation.coarseTargetFrame k (OAI.EditApproximation.coarsePadTo (OAI.EditApproximation.coarseEntryWidth x y) y)) + (OAI.EditApproximation.coarseEntryTree B D x y) draws k 0 (OAI.EditApproximation.coarseRootShift k) + k) + +def coarseInitialMinimum {α : Type u} [DecidableEq α] + (B D : ℕ) (Q lam : ℚ) (x y : List α) + (draws : OAI.EditApproximation.CoarseGuessIndex (OAI.EditApproximation.coarseEntryWidth x y) → OAI.EditApproximation.CoarseThresholdDraws B D) : ℚ := + univ.inf' univ_nonempty (fun i => OAI.EditApproximation.coarseInitialCandidate B D Q lam x y i (draws i)) + +def coarseInitialValue {α : Type u} [DecidableEq α] + (B D : ℕ) (Q lam : ℚ) (N : ℕ) (x y : List α) + (draws : OAI.EditApproximation.CoarseGuessIndex (OAI.EditApproximation.coarseEntryWidth x y) → OAI.EditApproximation.CoarseThresholdDraws B D) : ℕ := + if 2 * x.length < y.length then min N y.length + else if x = y then 0 + else min N ⌈OAI.EditApproximation.coarseInitialMinimum B D Q lam x y draws⌉₊ + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open Finset MeasureTheory ProbabilityTheory + +def coarseActiveArrayWork {B : ℕ} {α : Type u} (k : ℕ) (Q lam : ℚ) : + {D : ℕ} → OAI.EditApproximation.CoarseSourceTree B α D → OAI.EditApproximation.CoarseThresholdDraws B D → ℚ → ℕ + | _, tree, draws, allowance => + if (tree.word.length : ℚ) ≤ allowance then 0 else + match tree, draws with + | .leaf _, _ => B * (2 * k + 1) + | .branch children, (draws, below) => + B * (2 * k + 1) + + OAI.EditApproximation.coarseActiveChildrenWork Q lam allowance (fun child => coarseActiveArrayWork k Q lam child) + (List.ofFn fun i => (children i, draws i, below i)) + +def coarseFullSeedTable (N B : ℕ) {I : Type u_1} {α : Type u_2} [DecidableEq α] + (depth : I → ℕ) (x y : I → List α) + (draws : OAI.EditApproximation.CoarseFullSeedDraws B depth x y) : I → ℕ := + fun i => OAI.EditApproximation.coarseInitialValue B (depth i) (OAI.EditApproximation.initialThresholdQ N) (OAI.EditApproximation.initialLambda N) N (x i) (y i) (draws i) + +def coarseInitialArrayWork {α : Type u} [DecidableEq α] + (B D : ℕ) (Q lam : ℚ) (x y : List α) + (draws : OAI.EditApproximation.CoarseGuessIndex (OAI.EditApproximation.coarseEntryWidth x y) → OAI.EditApproximation.CoarseThresholdDraws B D) : ℕ := + if 2 * x.length < y.length then 0 + else if x = y then 0 + else ∑ i, OAI.EditApproximation.coarseActiveArrayWork (OAI.EditApproximation.coarseGuess (OAI.EditApproximation.coarseEntryWidth x y) i) Q lam + (OAI.EditApproximation.coarseEntryTree B D x y) (draws i) (OAI.EditApproximation.coarseGuess (OAI.EditApproximation.coarseEntryWidth x y) i) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open Filter +open scoped Topology + +def integerEqualWithWork : List ℤ → List ℤ → Bool × ℕ + | [], [] => (true, 1) + | [], _ :: _ => (false, 1) + | _ :: _, [] => (false, 1) + | x :: xs, y :: ys => + if x = y then + let tail := integerEqualWithWork xs ys + (tail.1, tail.2 + 1) + else (false, 1) + +def integerPreprocessingWork (source target : List ℤ) : ℕ := + (OAI.EditApproximation.integerInputInspectionWithWork source target).2 + + (OAI.EditApproximation.encodeIntegerSymbolsWithWork source).2 + (OAI.EditApproximation.encodeIntegerSymbolsWithWork target).2 + + (OAI.EditApproximation.integerOccurrenceBuildWithWork source target).2 + (OAI.EditApproximation.integerEqualWithWork source target).2 + 1 + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open Filter + +abbrev ComputedFamilyMemoKey (source target : List ℕ) (N : ℕ) := + Sum (OAI.EditApproximation.ComputedFamilyScalarKey source target N (OAI.EditApproximation.inputHeight N ^ 2)) + (OAI.EditApproximation.ComputedFamilyTableKey source target N) + +def integerPreevaluationWork (source target : List ℤ) (N : ℕ) (epsilon : OAI.EditApproximation.BinaryFraction) : ℕ := + OAI.EditApproximation.integerPreprocessingWork source target + OAI.EditApproximation.globalParameterWork N + + (OAI.EditApproximation.physicalLargeInputWithWork N epsilon).2 + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {α : Type u_1} {M J R : ℕ} (target : List α) (N P F exponent H Q passes copies : ℕ) + +def physicalFamilyCodeWithWork + (key : OAI.EditApproximation.PhysicalFamilyScalarKey (M := M) (J := J) (R := R) + target N P F exponent H Q passes copies) : ℕ × ℕ := + let scalar := OAI.EditApproximation.physicalScalarCodeWithWork key.2.2 + let copy := OAI.EditApproximation.naturalPairWithWork key.2.1.val scalar.1 + let pass := OAI.EditApproximation.naturalPairWithWork key.1.val copy.1 + (pass.1, scalar.2 + copy.2 + pass.2 + 2) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation + + +def computedFamilyMemoCodeWithWork (source target : List ℕ) (N R : ℕ) : + Sum (OAI.EditApproximation.ComputedFamilyScalarKey source target N R) (OAI.EditApproximation.ComputedFamilyTableKey source target N) → ℕ × ℕ + | .inl key => + let result := OAI.EditApproximation.physicalFamilyCodeWithWork target N (OAI.EditApproximation.integerParameters N).P (OAI.EditApproximation.inputSmallLog N) + (40 * OAI.EditApproximation.smallLogExponent N) (OAI.EditApproximation.inputHeight N) (OAI.EditApproximation.inputSmallLog N ^ 80) + (OAI.EditApproximation.computedSeedPassCount N) (OAI.EditApproximation.inputHeight N ^ 2) key + (2 * result.1, result.2 + 2) + | .inr key => let result := OAI.EditApproximation.chargedPhysicalCodeWithWork key + (2 * result.1 + 1, result.2 + 3) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable (M J N n exponent F Q R B : ℕ) +open Finset +open MeasureTheory ProbabilityTheory + +def queryPhysicalScalarGroupQueries (node : OAI.EditApproximation.PhysicalInternalNode M J) (time : Fin R) + (b : ℕ) (cell : ℕ × ℕ) : OAI.EditApproximation.BitPhysicalGroupQueries M J N n exponent F Q R B b := by + have proof_log_two_add_one_eq_size_103 (N : ℕ) (hN : LT.lt.{0} 0 N) : + Nat.log 2 N + 1 = Nat.size N := by + apply Nat.le_antisymm + · have h := Nat.pow_log_le_self 2 hN.ne' + have hlt : Nat.log 2 N < Nat.size N := Nat.lt_size.mpr h + omega + · exact Nat.size_le.mpr (Nat.lt_pow_succ_log_self (by decide : 1 < 2) N) + have proof_powerTwoWord_value_13 (n : ℕ) : OAI.EditApproximation.bitWordValue (OAI.EditApproximation.powerTwoWord n) = 2 ^ n := by + induction n with + | zero => (simp [OAI.EditApproximation.powerTwoWord, OAI.EditApproximation.bitWordValue]) + | succ n ih => + (simp only [OAI.EditApproximation.powerTwoWord, List.replicate_succ, List.cons_append, OAI.EditApproximation.bitWordValue, + Bool.toNat_false, zero_add] at *) + rw [ih, pow_succ] + omega + have proof_arithmeticMapWithWork_value_70 {α : Type 0} {β : Type 0} (f : α → Prod.{0, 0} β ℕ) (values : List.{0} α) : + (OAI.EditApproximation.arithmeticMapWithWork f values).1 = values.map (fun a => (f a).1) := by + induction values with + | nil => rfl + | cons a rest ih => simp only [OAI.EditApproximation.arithmeticMapWithWork, ih, List.map_cons] + have proof_dyadicScalesWithWork_value_104 (N : ℕ) : + (OAI.EditApproximation.dyadicScalesWithWork N).1 = OAI.EditApproximation.dyadicScales N := by + have hcount : max 1 N.bits.length = Nat.log 2 N + 1 := by + by_cases hz : N = 0 + · subst N + decide + · have h := proof_log_two_add_one_eq_size_103 N (Nat.pos_of_ne_zero hz) + have hp := Nat.size_pos.mpr (Nat.pos_of_ne_zero hz) + rw [Nat.size_eq_bits_len, max_eq_right hp, h] + simp only [OAI.EditApproximation.dyadicScalesWithWork, proof_arithmeticMapWithWork_value_70, proof_powerTwoWord_value_13, hcount, + OAI.EditApproximation.dyadicScales] + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_eq_3 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .eq ↔ OAI.EditApproximation.bitWordValue left = OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_binaryNaturalCompareWithWork_eq_73 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.binaryNaturalCompareWithWork a b).1 = .eq ↔ a = b := by + simpa only [OAI.EditApproximation.binaryNaturalCompareWithWork, proof_bitWordValue_bits_15] using proof_bitCompareWithWork_eq_3 a.bits b.bits + have proof_naturalEqualWithWork_value_74 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.naturalEqualWithWork a b).1 = true ↔ a = b := by + simp only [OAI.EditApproximation.naturalEqualWithWork, decide_eq_true_eq, proof_binaryNaturalCompareWithWork_eq_73] + have proof_queryNaturalIndexWithWork_value_105 (a : ℕ) (xs : List.{0} ℕ) : + (OAI.EditApproximation.queryNaturalIndexWithWork a xs).1 = xs.idxOf a := by + induction xs with + | nil => rfl + | cons b xs ih => + simp only [OAI.EditApproximation.queryNaturalIndexWithWork] + by_cases hab : a = b + · subst b + rw [ite_eq_left ((proof_naturalEqualWithWork_value_74 a a).mpr rfl)] + simp + · rw [ite_eq_right (fun h => hab ((proof_naturalEqualWithWork_value_74 a b).mp h))] + simp only [ih, List.idxOf_cons, beq_iff_eq] + rw [ite_eq_right (Ne.symm hab)] + have proof_queryScaleDispatchWithWork_value_106 (N : ℕ) (b : ℕ) : + (OAI.EditApproximation.queryScaleDispatchWithWork N b).1 = (OAI.EditApproximation.dyadicScales N).idxOf b := by + simp only [OAI.EditApproximation.queryScaleDispatchWithWork, proof_queryNaturalIndexWithWork_value_105, proof_dyadicScalesWithWork_value_104] + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_binaryNaturalCompareWithWork_lt_53 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.binaryNaturalCompareWithWork a b).1 = .lt ↔ a < b := by + simpa only [OAI.EditApproximation.binaryNaturalCompareWithWork, proof_bitWordValue_bits_15] using proof_bitCompareWithWork_lt_16 a.bits b.bits + have proof_queryScalePresentWithWork_value_101 (N : ℕ) (b : ℕ) : + (OAI.EditApproximation.queryScalePresentWithWork N b).1 = true ↔ b ∈ OAI.EditApproximation.dyadicScales N := by + simp only [OAI.EditApproximation.queryScalePresentWithWork, decide_eq_true_eq, proof_binaryNaturalCompareWithWork_lt_53, + proof_queryScaleDispatchWithWork_value_106] + have hl : (OAI.EditApproximation.dyadicScales N).length = max 1 N.bits.length := by + rw [← proof_dyadicScalesWithWork_value_104 N] + (simp only [OAI.EditApproximation.dyadicScalesWithWork, proof_arithmeticMapWithWork_value_70, List.length_map, List.length_range]) + rw [← hl] + exact List.idxOf_lt_length_iff + have proof_wordLEWithWork_value_26 (a : List.{0} Bool) (b : List.{0} Bool) : + (OAI.EditApproximation.wordLEWithWork a b).1 = true ↔ OAI.EditApproximation.bitWordValue a ≤ OAI.EditApproximation.bitWordValue b := by + simp only [OAI.EditApproximation.wordLEWithWork, Bool.not_eq_true', decide_eq_false_iff_not, + proof_bitCompareWithWork_lt_16, not_lt] + have proof_bitAdder_value_1 (a : Bool) (b : Bool) (carry : Bool) : + (OAI.EditApproximation.bitSum a b carry).toNat + 2 * (OAI.EditApproximation.bitCarry a b carry).toNat = + a.toNat + b.toNat + carry.toNat := by + cases a <;> cases b <;> cases carry <;> decide + have proof_bitAddWithWork_value_2 (left : List.{0} Bool) (right : List.{0} Bool) (carry : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitAddWithWork left right carry).1 = + OAI.EditApproximation.bitWordValue left + OAI.EditApproximation.bitWordValue right + carry.toNat := by + induction left generalizing right carry with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork] + induction right generalizing carry with + | nil => cases carry <;> simp [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue] + | cons b bs ih => + simp only [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 false b carry + simp only [Bool.toNat_false] at h + omega + | cons a as ih => + cases right with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a false carry + simp only [Bool.toNat_false] at h + omega + | cons b bs => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a b carry + omega + have proof_bitMulWithWork_value_0 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitMulWithWork left right).1 = OAI.EditApproximation.bitWordValue left * OAI.EditApproximation.bitWordValue right := by + induction left with + | nil => simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue] + | cons bit bits ih => + cases bit <;> simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue, proof_bitAddWithWork_value_2, ih] <;> ring + have proof_binaryNaturalMulWithWork_value_55 (a : ℕ) (b : ℕ) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalMulWithWork a b).1 = a * b := by + simp [OAI.EditApproximation.binaryNaturalMulWithWork, proof_bitMulWithWork_value_0, proof_bitWordValue_bits_15] + have proof_queryCellValidWithWork_value_102 (n : ℕ) (exponent : ℕ) (cell : Prod.{0, 0} ℕ ℕ) : + (OAI.EditApproximation.queryCellValidWithWork n exponent cell).1 = true ↔ + cell.1 ≤ n * 2 ^ exponent ∧ cell.2 ≤ n * 2 ^ exponent := by + simp only [OAI.EditApproximation.queryCellValidWithWork, Bool.and_eq_true, proof_wordLEWithWork_value_26, proof_bitWordValue_bits_15, + proof_binaryNaturalMulWithWork_value_55, proof_powerTwoWord_value_13] + have proof_physicalScaleIndex_get_93 (N : ℕ) (b : ℕ) (hb : Membership.mem.{0, 0} (OAI.EditApproximation.dyadicScales N) b) : + (OAI.EditApproximation.dyadicScales N).get (OAI.EditApproximation.physicalScaleIndex N b hb) = b := + List.getElem_idxOf (List.idxOf_lt_length_of_mem hb) + exact + if hb : (OAI.EditApproximation.queryScalePresentWithWork N b).1 = true then + if hc : (OAI.EditApproximation.queryCellValidWithWork n exponent cell).1 = true then + let key : OAI.EditApproximation.PhysicalLocalGroupKey M J N n exponent := + (node, OAI.EditApproximation.physicalScaleIndex N b ((proof_queryScalePresentWithWork_value_101 N b).mp hb), + ⟨cell.1, Nat.lt_succ_of_le ((proof_queryCellValidWithWork_value_102 n exponent cell).mp hc).1⟩, + ⟨cell.2, Nat.lt_succ_of_le ((proof_queryCellValidWithWork_value_102 n exponent cell).mp hc).2⟩) + Eq.mp (congrArg (OAI.EditApproximation.BitPhysicalGroupQueries M J N n exponent F Q R B) + (proof_physicalScaleIndex_get_93 N b ((proof_queryScalePresentWithWork_value_101 N b).mp hb))) + (OAI.EditApproximation.queryPhysicalScalarGroupQueriesAt M J N n exponent F Q R B key time) + else fun _ _ => .done (OAI.EditApproximation.BinaryFraction.nat 0) + else fun _ _ => .done (OAI.EditApproximation.BinaryFraction.nat 0) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable (M J N n exponent F Q R B : ℕ) + +def queryPhysicalScalarGroupRead (node : OAI.EditApproximation.PhysicalInternalNode M J) (time : Fin R) + (key : OAI.EditApproximation.GroupScalarKey M F Q) : OAI.EditApproximation.BitQuery (OAI.EditApproximation.PhysicalScalarKey M J N n exponent F Q R B) OAI.EditApproximation.BinaryFraction := + .charge ((OAI.EditApproximation.queryScalePresentWithWork N key.1.1).2 + + (OAI.EditApproximation.queryCellValidWithWork n exponent key.1.2).2 + 2) + (OAI.EditApproximation.queryPhysicalScalarGroupQueries M J N n exponent F Q R B node time + key.1.1 key.1.2 key.2.1 key.2.2) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable (M J N n exponent F Q R B : ℕ) +open Finset + +def queryPhysicalScalarOnlineRead (node : OAI.EditApproximation.PhysicalInternalNode M J) (time : Fin R) + (key : ℕ × OAI.EditApproximation.TargetInterval n) (range : ℕ) : + OAI.EditApproximation.BitQuery (OAI.EditApproximation.PhysicalScalarKey M J N n exponent F Q R B) OAI.EditApproximation.BinaryFraction := by + have proof_log_two_add_one_eq_size_103 (N : ℕ) (hN : LT.lt.{0} 0 N) : + Nat.log 2 N + 1 = Nat.size N := by + apply Nat.le_antisymm + · have h := Nat.pow_log_le_self 2 hN.ne' + have hlt : Nat.log 2 N < Nat.size N := Nat.lt_size.mpr h + omega + · exact Nat.size_le.mpr (Nat.lt_pow_succ_log_self (by decide : 1 < 2) N) + have proof_powerTwoWord_value_13 (n : ℕ) : OAI.EditApproximation.bitWordValue (OAI.EditApproximation.powerTwoWord n) = 2 ^ n := by + induction n with + | zero => (simp [OAI.EditApproximation.powerTwoWord, OAI.EditApproximation.bitWordValue]) + | succ n ih => + (simp only [OAI.EditApproximation.powerTwoWord, List.replicate_succ, List.cons_append, OAI.EditApproximation.bitWordValue, + Bool.toNat_false, zero_add] at *) + rw [ih, pow_succ] + omega + have proof_arithmeticMapWithWork_value_70 {α : Type 0} {β : Type 0} (f : α → Prod.{0, 0} β ℕ) (values : List.{0} α) : + (OAI.EditApproximation.arithmeticMapWithWork f values).1 = values.map (fun a => (f a).1) := by + induction values with + | nil => rfl + | cons a rest ih => simp only [OAI.EditApproximation.arithmeticMapWithWork, ih, List.map_cons] + have proof_dyadicScalesWithWork_value_104 (N : ℕ) : + (OAI.EditApproximation.dyadicScalesWithWork N).1 = OAI.EditApproximation.dyadicScales N := by + have hcount : max 1 N.bits.length = Nat.log 2 N + 1 := by + by_cases hz : N = 0 + · subst N + decide + · have h := proof_log_two_add_one_eq_size_103 N (Nat.pos_of_ne_zero hz) + have hp := Nat.size_pos.mpr (Nat.pos_of_ne_zero hz) + rw [Nat.size_eq_bits_len, max_eq_right hp, h] + simp only [OAI.EditApproximation.dyadicScalesWithWork, proof_arithmeticMapWithWork_value_70, proof_powerTwoWord_value_13, hcount, + OAI.EditApproximation.dyadicScales] + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_eq_3 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .eq ↔ OAI.EditApproximation.bitWordValue left = OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_binaryNaturalCompareWithWork_eq_73 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.binaryNaturalCompareWithWork a b).1 = .eq ↔ a = b := by + simpa only [OAI.EditApproximation.binaryNaturalCompareWithWork, proof_bitWordValue_bits_15] using proof_bitCompareWithWork_eq_3 a.bits b.bits + have proof_naturalEqualWithWork_value_74 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.naturalEqualWithWork a b).1 = true ↔ a = b := by + simp only [OAI.EditApproximation.naturalEqualWithWork, decide_eq_true_eq, proof_binaryNaturalCompareWithWork_eq_73] + have proof_queryNaturalIndexWithWork_value_105 (a : ℕ) (xs : List.{0} ℕ) : + (OAI.EditApproximation.queryNaturalIndexWithWork a xs).1 = xs.idxOf a := by + induction xs with + | nil => rfl + | cons b xs ih => + simp only [OAI.EditApproximation.queryNaturalIndexWithWork] + by_cases hab : a = b + · subst b + rw [ite_eq_left ((proof_naturalEqualWithWork_value_74 a a).mpr rfl)] + simp + · rw [ite_eq_right (fun h => hab ((proof_naturalEqualWithWork_value_74 a b).mp h))] + simp only [ih, List.idxOf_cons, beq_iff_eq] + rw [ite_eq_right (Ne.symm hab)] + have proof_queryScaleDispatchWithWork_value_106 (N : ℕ) (b : ℕ) : + (OAI.EditApproximation.queryScaleDispatchWithWork N b).1 = (OAI.EditApproximation.dyadicScales N).idxOf b := by + simp only [OAI.EditApproximation.queryScaleDispatchWithWork, proof_queryNaturalIndexWithWork_value_105, proof_dyadicScalesWithWork_value_104] + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_binaryNaturalCompareWithWork_lt_53 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.binaryNaturalCompareWithWork a b).1 = .lt ↔ a < b := by + simpa only [OAI.EditApproximation.binaryNaturalCompareWithWork, proof_bitWordValue_bits_15] using proof_bitCompareWithWork_lt_16 a.bits b.bits + have proof_queryScalePresentWithWork_value_101 (N : ℕ) (b : ℕ) : + (OAI.EditApproximation.queryScalePresentWithWork N b).1 = true ↔ b ∈ OAI.EditApproximation.dyadicScales N := by + simp only [OAI.EditApproximation.queryScalePresentWithWork, decide_eq_true_eq, proof_binaryNaturalCompareWithWork_lt_53, + proof_queryScaleDispatchWithWork_value_106] + have hl : (OAI.EditApproximation.dyadicScales N).length = max 1 N.bits.length := by + rw [← proof_dyadicScalesWithWork_value_104 N] + (simp only [OAI.EditApproximation.dyadicScalesWithWork, proof_arithmeticMapWithWork_value_70, List.length_map, List.length_range]) + rw [← hl] + exact List.idxOf_lt_length_iff + have proof_wordLEWithWork_value_26 (a : List.{0} Bool) (b : List.{0} Bool) : + (OAI.EditApproximation.wordLEWithWork a b).1 = true ↔ OAI.EditApproximation.bitWordValue a ≤ OAI.EditApproximation.bitWordValue b := by + simp only [OAI.EditApproximation.wordLEWithWork, Bool.not_eq_true', decide_eq_false_iff_not, + proof_bitCompareWithWork_lt_16, not_lt] + have proof_queryRangeValidWithWork_value_107 (B : ℕ) (range : ℕ) : + (OAI.EditApproximation.queryRangeValidWithWork B range).1 = true ↔ 0 < range ∧ range ≤ B := by + simp only [OAI.EditApproximation.queryRangeValidWithWork, Bool.and_eq_true, decide_eq_true_eq, + proof_binaryNaturalCompareWithWork_lt_53, proof_wordLEWithWork_value_26, proof_bitWordValue_bits_15] + exact + .charge ((OAI.EditApproximation.queryScalePresentWithWork N key.1).2 + (OAI.EditApproximation.queryRangeValidWithWork B range).2 + 2) + (if hb : (OAI.EditApproximation.queryScalePresentWithWork N key.1).1 = true then + if hr : (OAI.EditApproximation.queryRangeValidWithWork B range).1 = true then + OAI.EditApproximation.queryPhysicalScalarRead M J N n exponent F Q R B + ⟨.inl ((node, OAI.EditApproximation.physicalScaleIndex N key.1 ((proof_queryScalePresentWithWork_value_101 N key.1).mp hb), key.2), + OAI.EditApproximation.positiveDrawRangeOfLE B range ((proof_queryRangeValidWithWork_value_107 B range).mp hr).1 + ((proof_queryRangeValidWithWork_value_107 B range).mp hr).2), time⟩ + else .done (OAI.EditApproximation.BinaryFraction.nat 0) + else .done (OAI.EditApproximation.BinaryFraction.nat 0)) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {α : Type u_1} {M J R : ℕ} (target : List α) (N P F exponent H Q passes copies pass copy : ℕ) + +def queryFamilyTagWithWork + (scalar : OAI.EditApproximation.PhysicalScalarKey M J N target.length exponent F Q R (OAI.EditApproximation.localOnlineMassBound M P H)) : + OAI.EditApproximation.PhysicalFamilyScalarKey (M := M) (J := J) (R := R) + target N P F exponent H Q passes copies × ℕ := + let p := OAI.EditApproximation.queryFinOfNatWithWork (passes + 1) pass (Nat.succ_pos _) + let c := OAI.EditApproximation.queryFinOfNatWithWork (copies + 1) copy (Nat.succ_pos _) + let key := (p.1, c.1, scalar) + (key, p.2 + c.2 + (OAI.EditApproximation.physicalFamilyCodeWithWork target N P F exponent H Q passes copies key).2 + 1) + +def queryFamilyGroupRead (node : OAI.EditApproximation.PhysicalInternalNode M J) (time : Fin R) + (key : OAI.EditApproximation.GroupScalarKey M F Q) : + OAI.EditApproximation.BitQuery (OAI.EditApproximation.PhysicalFamilyScalarKey (M := M) (J := J) (R := R) + target N P F exponent H Q passes copies) OAI.EditApproximation.BinaryFraction := + OAI.EditApproximation.BitQuery.mapKeysWithWork + (OAI.EditApproximation.queryFamilyTagWithWork target N P F exponent H Q passes copies pass copy) + (OAI.EditApproximation.queryPhysicalScalarGroupRead M J N target.length exponent F Q R (OAI.EditApproximation.localOnlineMassBound M P H) + node time key) + +def queryFamilyOnlineRead (node : OAI.EditApproximation.PhysicalInternalNode M J) (time : Fin R) + (key : ℕ × OAI.EditApproximation.TargetInterval target.length) (range : ℕ) : + OAI.EditApproximation.BitQuery (OAI.EditApproximation.PhysicalFamilyScalarKey (M := M) (J := J) (R := R) + target N P F exponent H Q passes copies) OAI.EditApproximation.BinaryFraction := + OAI.EditApproximation.BitQuery.mapKeysWithWork + (OAI.EditApproximation.queryFamilyTagWithWork target N P F exponent H Q passes copies pass copy) + (OAI.EditApproximation.queryPhysicalScalarOnlineRead M J N target.length exponent F Q R (OAI.EditApproximation.localOnlineMassBound M P H) + node time key range) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {σ : Type u_1} {M J n : ℕ} (passes copies T S : ℕ) (parent : {r : PhysicalTableRequest M J n // r.Bounded passes copies T S}) + +abbrev QueryPhysicalChild := Sum σ {child : OAI.EditApproximation.PhysicalTableRequest M J n // + child.combinedRank T S < parent.val.combinedRank T S} + +def querySupportedChildWithWork (key : OAI.EditApproximation.QueryPhysicalChild (σ := σ) passes copies T S parent) : Bool × ℕ := + match key with + | .inl _ => (true, 1) + | .inr child => OAI.EditApproximation.queryPhysicalBoundedWithWork passes copies T S child.val + +def queryRestrictPhysicalBody (program : OAI.EditApproximation.BitQuery (OAI.EditApproximation.QueryPhysicalChild (σ := σ) passes copies T S parent) OAI.EditApproximation.BinaryFraction) : + OAI.EditApproximation.BitQuery (Sum σ {child : {r : OAI.EditApproximation.PhysicalTableRequest M J n // r.Bounded passes copies T S} // + child.val.combinedRank T S < parent.val.combinedRank T S}) OAI.EditApproximation.BinaryFraction := by + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_binaryNaturalCompareWithWork_lt_53 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.binaryNaturalCompareWithWork a b).1 = .lt ↔ a < b := by + simpa only [OAI.EditApproximation.binaryNaturalCompareWithWork, proof_bitWordValue_bits_15] using proof_bitCompareWithWork_lt_16 a.bits b.bits + have proof_wordLEWithWork_value_26 (a : List.{0} Bool) (b : List.{0} Bool) : + (OAI.EditApproximation.wordLEWithWork a b).1 = true ↔ OAI.EditApproximation.bitWordValue a ≤ OAI.EditApproximation.bitWordValue b := by + simp only [OAI.EditApproximation.wordLEWithWork, Bool.not_eq_true', decide_eq_false_iff_not, + proof_bitCompareWithWork_lt_16, not_lt] + have proof_bitAdder_value_1 (a : Bool) (b : Bool) (carry : Bool) : + (OAI.EditApproximation.bitSum a b carry).toNat + 2 * (OAI.EditApproximation.bitCarry a b carry).toNat = + a.toNat + b.toNat + carry.toNat := by + cases a <;> cases b <;> cases carry <;> decide + have proof_bitAddWithWork_value_2 (left : List.{0} Bool) (right : List.{0} Bool) (carry : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitAddWithWork left right carry).1 = + OAI.EditApproximation.bitWordValue left + OAI.EditApproximation.bitWordValue right + carry.toNat := by + induction left generalizing right carry with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork] + induction right generalizing carry with + | nil => cases carry <;> simp [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue] + | cons b bs ih => + simp only [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 false b carry + simp only [Bool.toNat_false] at h + omega + | cons a as ih => + cases right with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a false carry + simp only [Bool.toNat_false] at h + omega + | cons b bs => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a b carry + omega + have proof_binaryNaturalAddWithWork_value_52 (a : ℕ) (b : ℕ) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalAddWithWork a b).1 = a + b := by + simp [OAI.EditApproximation.binaryNaturalAddWithWork, proof_bitAddWithWork_value_2, proof_bitWordValue_bits_15] + have proof_queryPhysicalBoundedWithWork_value_109 {M : ℕ} {J : ℕ} {n : ℕ} (passes : ℕ) (copies : ℕ) (T : ℕ) (S : ℕ) (request : OAI.EditApproximation.PhysicalTableRequest M J n) : + (OAI.EditApproximation.queryPhysicalBoundedWithWork passes copies T S request).1 = true ↔ + request.Bounded passes copies T S := by + simp only [OAI.EditApproximation.queryPhysicalBoundedWithWork, Bool.and_eq_true, decide_eq_true_eq, + proof_binaryNaturalCompareWithWork_lt_53, proof_wordLEWithWork_value_26, proof_bitWordValue_bits_15, + proof_binaryNaturalAddWithWork_value_52, OAI.EditApproximation.PhysicalTableRequest.Bounded] + tauto + have proof_querySupportedChildWithWork_value_108 {σ : Type u_1} {M : ℕ} {J : ℕ} {n : ℕ} (passes : ℕ) (copies : ℕ) (T : ℕ) (S : ℕ) (parent : Subtype.{1} fun r => OAI.EditApproximation.PhysicalTableRequest.Bounded (M := M) (J := J) (ny := n) passes copies T S r) (key : OAI.EditApproximation.QueryPhysicalChild.{u_1} (σ := σ) passes copies T S parent) : + (OAI.EditApproximation.querySupportedChildWithWork passes copies T S parent key).1 = true ↔ + OAI.EditApproximation.SourceRanked.supportedChild (OAI.EditApproximation.PhysicalTableRequest.combinedRank T S) + (OAI.EditApproximation.PhysicalTableRequest.Bounded passes copies T S) parent.val key := by + cases key with + | inl source => exact iff_of_true rfl trivial + | inr child => exact proof_queryPhysicalBoundedWithWork_value_109 passes copies T S child.val + exact + OAI.EditApproximation.BitQuery.mapKeysWithWork + (fun key => (OAI.EditApproximation.SourceRanked.supportedChildMap (OAI.EditApproximation.PhysicalTableRequest.combinedRank T S) + (OAI.EditApproximation.PhysicalTableRequest.Bounded passes copies T S) parent key, 1)) + (OAI.EditApproximation.BitQuery.restrictWithWork + (OAI.EditApproximation.SourceRanked.supportedChild (OAI.EditApproximation.PhysicalTableRequest.combinedRank T S) + (OAI.EditApproximation.PhysicalTableRequest.Bounded passes copies T S) parent.val) + (OAI.EditApproximation.querySupportedChildWithWork passes copies T S parent) + (proof_querySupportedChildWithWork_value_108 passes copies T S parent) program) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {ι : Type u_1} {α : Type*} (source target : List α) (N P F : ℕ) (A a : BinaryFraction) (reader : TargetInterval target.length → BitQuery ι BinaryFraction) (q : TargetInterval target.length) + +def queryInitialConeProgramAt {n : ℕ} (sourceLength N P F : ℕ) (A a : OAI.EditApproximation.BinaryFraction) + (reader : OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) (q : OAI.EditApproximation.TargetInterval n) : + OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction := + (reader q).bind fun value => + (OAI.EditApproximation.BitQuery.compute (OAI.EditApproximation.BinaryFraction.queryInitialConeCentersWithWork N P A value q)).bind fun keys => + OAI.EditApproximation.BitQuery.collect reader keys fun words => + OAI.EditApproximation.BitQuery.compute (OAI.EditApproximation.BinaryFraction.cachedInitialProgramReadWithWork sourceLength N P F A a + (OAI.EditApproximation.BinaryFraction.queryInitialSeedReadWithWork value q keys words) q) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {M J n passes copies T S : ℕ} (parent : {r : PhysicalTableRequest M J n // r.Bounded passes copies T S}) + +def queryChargedRead + (key : {child : OAI.EditApproximation.ChargedPhysicalRequest M J n passes copies T S // + child.rank < OAI.EditApproximation.ChargedPhysicalRequest.rank (.inr parent)}) : + OAI.EditApproximation.BitQuery {child : OAI.EditApproximation.ChargedPhysicalRequest M J n passes copies T S // + child.rank < OAI.EditApproximation.ChargedPhysicalRequest.rank (.inr parent)} OAI.EditApproximation.BinaryFraction := + .charge ((OAI.EditApproximation.chargedPhysicalCodeWithWork key.val).2 + 1) (.read key .done) + +def queryChargedPreviousRead (hp : 0 < parent.val.pass) (q : OAI.EditApproximation.TargetInterval n) (copy : Fin copies) : + OAI.EditApproximation.BitQuery {child : OAI.EditApproximation.ChargedPhysicalRequest M J n passes copies T S // + child.rank < OAI.EditApproximation.ChargedPhysicalRequest.rank (.inr parent)} OAI.EditApproximation.BinaryFraction := by + have proof_table_rank_lt_99 {M : ℕ} {J : ℕ} {ny : ℕ} {passes : ℕ} {copies : ℕ} {T : ℕ} {S : ℕ} (parent : Subtype.{1} fun request => OAI.EditApproximation.PhysicalTableRequest.Bounded (M := M) (J := J) (ny := ny) passes copies T S request) (child : Subtype.{1} fun request => OAI.EditApproximation.PhysicalTableRequest.Bounded (M := M) (J := J) (ny := ny) passes copies T S request) (h : LT.lt.{0} (OAI.EditApproximation.PhysicalTableRequest.combinedRank T S child.val) + (OAI.EditApproximation.PhysicalTableRequest.combinedRank T S parent.val)) : + OAI.EditApproximation.ChargedPhysicalRequest.rank (Sum.inr child : OAI.EditApproximation.ChargedPhysicalRequest M J ny passes copies T S) < OAI.EditApproximation.ChargedPhysicalRequest.rank (Sum.inr parent) := by + simpa only [OAI.EditApproximation.ChargedPhysicalRequest.rank, OAI.EditApproximation.ChargedPhysicalRequest.depth, OAI.EditApproximation.ChargedPhysicalRequest.index, ← Nat.add_assoc, OAI.EditApproximation.PhysicalTableRequest.combinedRank] using + Nat.add_lt_add_right h 1 + have proof_combinedRank_lt_of_progress_80 {M : ℕ} {J : ℕ} {ny : ℕ} (T : ℕ) (S : ℕ) (first : OAI.EditApproximation.PhysicalTableRequest M J ny) (second : OAI.EditApproximation.PhysicalTableRequest M J ny) (hprogress : LT.lt.{0} second.remainingDepth first.remainingDepth ∧ + LE.le.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first) ∨ + LE.le.{0} second.remainingDepth first.remainingDepth ∧ + LT.lt.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first)) : + OAI.EditApproximation.PhysicalTableRequest.combinedRank T S second < OAI.EditApproximation.PhysicalTableRequest.combinedRank T S first := by + unfold OAI.EditApproximation.PhysicalTableRequest.combinedRank + rcases hprogress with h | h + · exact Nat.add_lt_add_of_lt_of_le h.1 h.2 + · exact Nat.add_lt_add_of_le_of_lt h.1 h.2 + have proof_rank_lt_previous_pass_98 {M : ℕ} {J : ℕ} {ny : ℕ} (T : ℕ) (S : ℕ) (first : OAI.EditApproximation.PhysicalTableRequest M J ny) (second : OAI.EditApproximation.PhysicalTableRequest M J ny) (hpass : LT.lt.{0} second.pass first.pass) (hindex : LE.le.{0} second.index (HAdd.hAdd.{0, 0, 0} T S)) : + OAI.EditApproximation.PhysicalTableRequest.rank T S second < OAI.EditApproximation.PhysicalTableRequest.rank T S first := by + have hblock : second.pass * (T + S + 1) + second.index < + (second.pass + 1) * (T + S + 1) := by + nlinarith only [hindex] + have hnext := Nat.mul_le_mul_right (T + S + 1) (Nat.succ_le_of_lt hpass) + exact hblock.trans_le (hnext.trans (Nat.le_add_right _ _)) + have proof_previousPassRequest_progress_97 {M : ℕ} {J : ℕ} {ny : ℕ} (T : ℕ) (S : ℕ) (copy : ℕ) (parent : OAI.EditApproximation.PhysicalTableRequest M J ny) (hpass : LT.lt.{0} 0 parent.pass) (state : OAI.EditApproximation.TargetInterval ny) : + (OAI.EditApproximation.previousPassRequest T S copy parent state).remainingDepth = parent.remainingDepth ∧ + (OAI.EditApproximation.previousPassRequest T S copy parent state).rank T S < parent.rank T S := by + refine ⟨rfl, ?_⟩ + exact proof_rank_lt_previous_pass_98 T S parent _ (by + change parent.pass - 1 < parent.pass + omega) le_rfl + exact + OAI.EditApproximation.queryChargedRead parent ⟨.inr (OAI.EditApproximation.chargedPreviousPass parent q copy), by + apply proof_table_rank_lt_99 + apply proof_combinedRank_lt_of_progress_80 T S parent.val _ + exact Or.inr ⟨(proof_previousPassRequest_progress_97 T S copy.val parent.val hp q).1.le, + (proof_previousPassRequest_progress_97 T S copy.val parent.val hp q).2⟩⟩ + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {M J n passes copies T S : ℕ} (parent : {r : PhysicalTableRequest M J n // r.Bounded passes copies T S}) +open Finset + +def queryChargedSeedAt (N : ℕ) (multiplier : ℕ → ℕ) (q : OAI.EditApproximation.TargetInterval n) : + OAI.EditApproximation.BitQuery {child : OAI.EditApproximation.ChargedPhysicalRequest M J n passes copies T S // + child.rank < OAI.EditApproximation.ChargedPhysicalRequest.rank (.inr parent)} OAI.EditApproximation.BinaryFraction := by + have proof_coarse_rank_lt_100 {M : ℕ} {J : ℕ} {ny : ℕ} {passes : ℕ} {copies : ℕ} {T : ℕ} {S : ℕ} (entry : OAI.EditApproximation.PhysicalEntry M J ny) (request : Subtype.{1} fun request => OAI.EditApproximation.PhysicalTableRequest.Bounded (M := M) (J := J) (ny := ny) passes copies T S request) (hnode : Eq.{1} entry.1 request.val.node) : + OAI.EditApproximation.ChargedPhysicalRequest.rank (Sum.inl entry : OAI.EditApproximation.ChargedPhysicalRequest M J ny passes copies T S) < OAI.EditApproximation.ChargedPhysicalRequest.rank (Sum.inr request) := by + change J - entry.1.1.val + 0 < request.val.remainingDepth + (request.val.rank T S + 1) + rw [hnode] + unfold OAI.EditApproximation.PhysicalTableRequest.remainingDepth + omega + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_eq_3 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .eq ↔ OAI.EditApproximation.bitWordValue left = OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_binaryNaturalCompareWithWork_eq_73 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.binaryNaturalCompareWithWork a b).1 = .eq ↔ a = b := by + simpa only [OAI.EditApproximation.binaryNaturalCompareWithWork, proof_bitWordValue_bits_15] using proof_bitCompareWithWork_eq_3 a.bits b.bits + have proof_naturalEqualWithWork_value_74 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.naturalEqualWithWork a b).1 = true ↔ a = b := by + simp only [OAI.EditApproximation.naturalEqualWithWork, decide_eq_true_eq, proof_binaryNaturalCompareWithWork_eq_73] + exact + .charge ((OAI.EditApproximation.naturalEqualWithWork parent.val.pass 0).2 + 1) + (if hp : (OAI.EditApproximation.naturalEqualWithWork parent.val.pass 0).1 = true then + OAI.EditApproximation.queryChargedRead parent ⟨.inl (parent.val.node, q), proof_coarse_rank_lt_100 _ parent rfl⟩ + else .charge (copies + 1) + (OAI.EditApproximation.BitQuery.collect (OAI.EditApproximation.queryChargedPreviousRead parent + (Nat.pos_of_ne_zero (fun h => hp ((proof_naturalEqualWithWork_value_74 _ _).mpr h))) q) + (List.finRange copies) fun words => OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.querySeedMedianWithWork N (multiplier (parent.val.pass - 1)) words))) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable (source target : List ℕ) {M J passes copies T S : ℕ} (N P F : ℕ) (A a : BinaryFraction) (multiplier : ℕ → ℕ) (parent : {r : PhysicalTableRequest M J target.length // r.Bounded passes copies T S}) (occurrence : BinaryMemo PositionCounts) (symbolBits positionBits : ℕ) (q : TargetInterval target.length) + +def queryPhysicalInitial : + OAI.EditApproximation.BitQuery {child : OAI.EditApproximation.ChargedPhysicalRequest M J target.length passes copies T S // + child.rank < OAI.EditApproximation.ChargedPhysicalRequest.rank (.inr parent)} OAI.EditApproximation.BinaryFraction := + let interval := OAI.EditApproximation.physicalSourceInterval source.length parent.val.node + let length := OAI.EditApproximation.saturatingSubtractWithWork interval.hi interval.lo + let test := OAI.EditApproximation.wordLEWithWork length.1 [true] + .charge (length.2 + test.2 + 2) + (if test.1 then + OAI.EditApproximation.BitQuery.compute (OAI.EditApproximation.queryIndexedSliceWithWork source interval target.length q + occurrence symbolBits positionBits) + else OAI.EditApproximation.queryInitialConeProgramAt (OAI.EditApproximation.bitWordValue length.1) N P F A a + (OAI.EditApproximation.queryChargedSeedAt parent N multiplier) q) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {ι : Type u_1} {nx ny M : ℕ} (parent : TargetInterval nx) (N P F : ℕ) (a : BinaryFraction) (initialRead : TargetInterval ny → BitQuery ι BinaryFraction) (childRead : (Fin M × TargetInterval ny) → BitQuery ι BinaryFraction) (q : TargetInterval ny) + +def queryWarmupProgram : OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction := + (initialRead q).bind fun value => + (OAI.EditApproximation.BitQuery.compute (OAI.EditApproximation.BinaryFraction.queryRawCentersWithWork N P F a value q)).bind fun centers => + OAI.EditApproximation.BitQuery.collect initialRead centers fun words => + let initial := OAI.EditApproximation.BinaryFraction.queryOverrideParentReadWithWork value q centers words + (OAI.EditApproximation.BitQuery.compute (OAI.EditApproximation.BinaryFraction.queryWarmupInputsWithWork M parent N P F a initial q)).bind + fun inputs => OAI.EditApproximation.BitQuery.collect childRead inputs fun childWords => + OAI.EditApproximation.BitQuery.compute (OAI.EditApproximation.BinaryFraction.localWarmupReadKernelWithWork parent N P F a initial + (fun input => OAI.EditApproximation.BinaryFraction.queryChildReadWithWork inputs childWords input.1 input.2) q) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {M J ny passes copies T S : ℕ} (parent : {r : PhysicalTableRequest M J ny // r.Bounded passes copies T S}) (hbelow : parent.val.node.1.val < J) (hindex : 0 < parent.val.index) (input : Fin M × TargetInterval ny) + +def queryChargedWarmupChild : + OAI.EditApproximation.BitQuery {child : OAI.EditApproximation.ChargedPhysicalRequest M J ny passes copies T S // + child.rank < OAI.EditApproximation.ChargedPhysicalRequest.rank (.inr parent)} OAI.EditApproximation.BinaryFraction := by + have proof_table_rank_lt_99 {M : ℕ} {J : ℕ} {ny : ℕ} {passes : ℕ} {copies : ℕ} {T : ℕ} {S : ℕ} (parent : Subtype.{1} fun request => OAI.EditApproximation.PhysicalTableRequest.Bounded (M := M) (J := J) (ny := ny) passes copies T S request) (child : Subtype.{1} fun request => OAI.EditApproximation.PhysicalTableRequest.Bounded (M := M) (J := J) (ny := ny) passes copies T S request) (h : LT.lt.{0} (OAI.EditApproximation.PhysicalTableRequest.combinedRank T S child.val) + (OAI.EditApproximation.PhysicalTableRequest.combinedRank T S parent.val)) : + OAI.EditApproximation.ChargedPhysicalRequest.rank (Sum.inr child : OAI.EditApproximation.ChargedPhysicalRequest M J ny passes copies T S) < OAI.EditApproximation.ChargedPhysicalRequest.rank (Sum.inr parent) := by + simpa only [OAI.EditApproximation.ChargedPhysicalRequest.rank, OAI.EditApproximation.ChargedPhysicalRequest.depth, OAI.EditApproximation.ChargedPhysicalRequest.index, ← Nat.add_assoc, OAI.EditApproximation.PhysicalTableRequest.combinedRank] using + Nat.add_lt_add_right h 1 + have proof_combinedRank_lt_of_progress_80 {M : ℕ} {J : ℕ} {ny : ℕ} (T : ℕ) (S : ℕ) (first : OAI.EditApproximation.PhysicalTableRequest M J ny) (second : OAI.EditApproximation.PhysicalTableRequest M J ny) (hprogress : LT.lt.{0} second.remainingDepth first.remainingDepth ∧ + LE.le.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first) ∨ + LE.le.{0} second.remainingDepth first.remainingDepth ∧ + LT.lt.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first)) : + OAI.EditApproximation.PhysicalTableRequest.combinedRank T S second < OAI.EditApproximation.PhysicalTableRequest.combinedRank T S first := by + unfold OAI.EditApproximation.PhysicalTableRequest.combinedRank + rcases hprogress with h | h + · exact Nat.add_lt_add_of_lt_of_le h.1 h.2 + · exact Nat.add_lt_add_of_le_of_lt h.1 h.2 + have proof_warmup_previous_child_progress_81 {M : ℕ} {J : ℕ} {ny : ℕ} (pass : ℕ) (copy : ℕ) (T : ℕ) (S : ℕ) (j : ℕ) (node : OAI.EditApproximation.PhysicalNode M J) (hbelow : LT.lt.{0} (↑(Sigma.fst.{0, 0} node)) J) (i : Fin M) (state : OAI.EditApproximation.TargetInterval ny) (previousState : OAI.EditApproximation.TargetInterval ny) (hj : LT.lt.{0} 0 j) : + (OAI.EditApproximation.PhysicalTableRequest.warmup pass copy (OAI.EditApproximation.physicalChild node hbelow i) (j - 1) previousState).remainingDepth < + (OAI.EditApproximation.PhysicalTableRequest.warmup pass copy node j state).remainingDepth ∧ + OAI.EditApproximation.PhysicalTableRequest.rank T S (OAI.EditApproximation.PhysicalTableRequest.warmup pass copy (OAI.EditApproximation.physicalChild node hbelow i) (j - 1) previousState) < + OAI.EditApproximation.PhysicalTableRequest.rank T S (OAI.EditApproximation.PhysicalTableRequest.warmup pass copy node j state) := by + constructor + · unfold OAI.EditApproximation.PhysicalTableRequest.remainingDepth OAI.EditApproximation.PhysicalTableRequest.warmup OAI.EditApproximation.physicalChild + dsimp only + omega + · dsimp only [OAI.EditApproximation.PhysicalTableRequest.rank, OAI.EditApproximation.PhysicalTableRequest.warmup] + omega + have proof_combinedRank_warmup_child_79 {M : ℕ} {J : ℕ} {ny : ℕ} (pass : ℕ) (copy : ℕ) (T : ℕ) (S : ℕ) (j : ℕ) (node : OAI.EditApproximation.PhysicalNode M J) (hbelow : LT.lt.{0} (↑(Sigma.fst.{0, 0} node)) J) (i : Fin M) (state : OAI.EditApproximation.TargetInterval ny) (previousState : OAI.EditApproximation.TargetInterval ny) (hj : LT.lt.{0} 0 j) : + OAI.EditApproximation.PhysicalTableRequest.combinedRank T S (OAI.EditApproximation.PhysicalTableRequest.warmup pass copy (OAI.EditApproximation.physicalChild node hbelow i) (j - 1) previousState) < + OAI.EditApproximation.PhysicalTableRequest.combinedRank T S (OAI.EditApproximation.PhysicalTableRequest.warmup pass copy node j state) := + proof_combinedRank_lt_of_progress_80 T S _ _ (Or.inr + ⟨(proof_warmup_previous_child_progress_81 pass copy T S j node hbelow i state previousState hj).1.le, + (proof_warmup_previous_child_progress_81 pass copy T S j node hbelow i state previousState hj).2⟩) + exact + OAI.EditApproximation.queryChargedRead parent ⟨.inr ⟨OAI.EditApproximation.PhysicalTableRequest.warmup parent.val.pass parent.val.copy + (OAI.EditApproximation.physicalChild parent.val.node hbelow input.1) (parent.val.index - 1) input.2, + parent.property.1, parent.property.2.1, + (Nat.sub_le _ _).trans parent.property.2.2⟩, by + apply proof_table_rank_lt_99 + exact proof_combinedRank_warmup_child_79 parent.val.pass parent.val.copy T S + parent.val.index parent.val.node hbelow input.1 parent.val.state input.2 hindex⟩ + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable (source target : List ℕ) {M J passes copies T S : ℕ} (N P F : ℕ) (A a : BinaryFraction) (multiplier : ℕ → ℕ) (parent : {r : PhysicalTableRequest M J target.length // r.Bounded passes copies T S}) (occurrence : BinaryMemo PositionCounts) (symbolBits positionBits : ℕ) +open Finset + +def queryChargedWarmup : + OAI.EditApproximation.BitQuery {child : OAI.EditApproximation.ChargedPhysicalRequest M J target.length passes copies T S // + child.rank < OAI.EditApproximation.ChargedPhysicalRequest.rank (.inr parent)} OAI.EditApproximation.BinaryFraction := by + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_binaryNaturalCompareWithWork_lt_53 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.binaryNaturalCompareWithWork a b).1 = .lt ↔ a < b := by + simpa only [OAI.EditApproximation.binaryNaturalCompareWithWork, proof_bitWordValue_bits_15] using proof_bitCompareWithWork_lt_16 a.bits b.bits + have proof_bitCompareWithWork_eq_3 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .eq ↔ OAI.EditApproximation.bitWordValue left = OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_binaryNaturalCompareWithWork_eq_73 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.binaryNaturalCompareWithWork a b).1 = .eq ↔ a = b := by + simpa only [OAI.EditApproximation.binaryNaturalCompareWithWork, proof_bitWordValue_bits_15] using proof_bitCompareWithWork_eq_3 a.bits b.bits + have proof_naturalEqualWithWork_value_74 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.naturalEqualWithWork a b).1 = true ↔ a = b := by + simp only [OAI.EditApproximation.naturalEqualWithWork, decide_eq_true_eq, proof_binaryNaturalCompareWithWork_eq_73] + exact + .charge ((OAI.EditApproximation.naturalEqualWithWork parent.val.index 0).2 + 1) + (if hz : (OAI.EditApproximation.naturalEqualWithWork parent.val.index 0).1 = true then + OAI.EditApproximation.queryPhysicalInitial source target N P F A a multiplier parent occurrence symbolBits positionBits + parent.val.state + else .charge ((OAI.EditApproximation.binaryNaturalCompareWithWork parent.val.node.1.val J).2 + 1) + (if hb : (OAI.EditApproximation.binaryNaturalCompareWithWork parent.val.node.1.val J).1 = .lt then + let interval := OAI.EditApproximation.physicalSourceInterval source.length parent.val.node + let length := OAI.EditApproximation.saturatingSubtractWithWork interval.hi interval.lo + let test := OAI.EditApproximation.wordLEWithWork length.1 [true] + .charge (length.2 + test.2 + 1) + (if test.1 then + OAI.EditApproximation.queryPhysicalInitial source target N P F A a multiplier parent occurrence symbolBits + positionBits parent.val.state + else OAI.EditApproximation.queryWarmupProgram interval N P F a + (OAI.EditApproximation.queryPhysicalInitial source target N P F A a multiplier parent occurrence symbolBits positionBits) + (OAI.EditApproximation.queryChargedWarmupChild parent ((proof_binaryNaturalCompareWithWork_lt_53 _ _).mp hb) + (Nat.pos_of_ne_zero (fun h => hz ((proof_naturalEqualWithWork_value_74 _ _).mpr h)))) + parent.val.state) + else OAI.EditApproximation.queryPhysicalInitial source target N P F A a multiplier parent occurrence symbolBits positionBits + parent.val.state)) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {M J R passes copies T S : ℕ} [NeZero M] [NeZero R] (source target : List ℕ) (N P F exponent H Q eM eF : ℕ) (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (A a : ℕ → BinaryFraction) (tau eta kappa delta : BinaryFraction) (multiplier : ℕ → ℕ) (occurrence : BinaryMemo PositionCounts) (symbolBits positionBits : ℕ) + +abbrev ChargedFamilyQueryKey (parent : OAI.EditApproximation.ChargedPhysicalRequest M J target.length (passes + 1) copies T S) := + Sum (OAI.EditApproximation.PhysicalFamilyScalarKey (M := M) (J := J) (R := R) target N P F exponent H Q passes copies) + {child : OAI.EditApproximation.ChargedPhysicalRequest M J target.length (passes + 1) copies T S // child.rank < parent.rank} + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {κ : Type u_1} (rank : κ → ℕ) (raw : (key : κ) → BitQuery {child : κ // rank child < rank key} BinaryFraction) (base : List Bool) (hbase : 0 < bitWordValue base) (remaining : κ → ℕ) + +def rankedNormalizeBody (key : κ) : + OAI.EditApproximation.BitQuery {child : κ // rank child < rank key} OAI.EditApproximation.BinaryFraction := + (raw key).normalize base hbase (remaining key) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {σ : Type u_1} {α : Type u_2} [DecidableEq α] {M J R : ℕ} [NeZero M] [NeZero R] (source target : List α) (N P F exponent H Q T S passes copies : ℕ) (factor : ℕ → ℚ) (multiplier : ℕ → ℕ) (tau eta kappa delta : ℚ) (readGroup : ℕ → ℕ → PhysicalInternalNode M J → Fin R → GroupScalarKey M F Q → FiniteQuery σ) (readInteger : ℕ → ℕ → PhysicalInternalNode M J → Fin R → + (ℕ × TargetInterval target.length) → ℕ → FiniteQuery σ) (initial : PhysicalEntry M J target.length → ℕ) (sourceAnswer : σ → ℚ) + +noncomputable def chargedRandomMemoEvaluate (bits : ℕ) + (encode : Sum σ (OAI.EditApproximation.ChargedPhysicalRequest M J target.length passes copies T S) → ℕ) + (request : OAI.EditApproximation.ChargedPhysicalRequest M J target.length passes copies T S) := + OAI.EditApproximation.rankedMemoEvaluate (OAI.EditApproximation.SourceRanked.rank OAI.EditApproximation.ChargedPhysicalRequest.rank) + (OAI.EditApproximation.SourceRanked.body OAI.EditApproximation.ChargedPhysicalRequest.rank + (OAI.EditApproximation.chargedRandomGlobalQuery source target N P F exponent H Q T S passes copies factor multiplier + tau eta kappa delta readGroup readInteger initial) sourceAnswer) + bits encode (.inr request) .empty + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {α : Type u_1} [DecidableEq α] {M J R : ℕ} [NeZero M] [NeZero R] (source target : List α) (N P F exponent H Q T S passes copies : ℕ) (factor : ℕ → ℚ) (multiplier : ℕ → ℕ) (tau eta kappa delta : ℚ) (initial : PhysicalEntry M J target.length → ℕ) + +noncomputable def physicalFamilyProgram := + OAI.EditApproximation.chargedRandomGlobalQuery source target N P F exponent H Q T S (passes + 1) copies + factor multiplier tau eta kappa delta + (OAI.EditApproximation.physicalFamilyGroupRead (M := M) (J := J) (R := R) target N P F exponent H Q passes copies) + (OAI.EditApproximation.physicalFamilyOnlineRead (M := M) (J := J) (R := R) target N P F exponent H Q passes copies) + initial + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open MeasureTheory ProbabilityTheory +variable {α : Type u_1} [DecidableEq α] {M J : ℕ} (source target : List α) (N B : ℕ) (depth : PhysicalEntry M J target.length → ℕ) + +abbrev PhysicalCoarseDraw := OAI.EditApproximation.CoarseFullSeedDraws B depth + (fun state : OAI.EditApproximation.PhysicalEntry M J target.length => OAI.EditApproximation.physicalSource source state.1) + (fun state : OAI.EditApproximation.PhysicalEntry M J target.length => OAI.EditApproximation.substring target state.2.lo state.2.hi) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open MeasureTheory ProbabilityTheory +variable {α : Type u_1} [DecidableEq α] {M J : ℕ} (source target : List α) (N B : ℕ) (depth : PhysicalEntry M J target.length → ℕ) +open EditDistortion Finset MeasureTheory ProbabilityTheory +open Finset MeasureTheory ProbabilityTheory + +noncomputable def physicalCoarseSeedTable (draw : OAI.EditApproximation.PhysicalCoarseDraw source target B depth) : + OAI.EditApproximation.ClampedPhysicalSeed M J target.length N := by + have proof_coarseInitialValue_le_length_111 {α : Type u_1} [instLocal1 : DecidableEq.{u_1 + 1} α] (B : ℕ) (D : ℕ) (Q : ℚ) (lam : ℚ) (N : ℕ) (x : List.{u_1} α) (y : List.{u_1} α) (draws : OAI.EditApproximation.CoarseGuessIndex (OAI.EditApproximation.coarseEntryWidth.{u_1} x y) → + OAI.EditApproximation.CoarseThresholdDraws B D) : + OAI.EditApproximation.coarseInitialValue B D Q lam N x y draws ≤ N := by + unfold OAI.EditApproximation.coarseInitialValue + split_ifs + · exact min_le_left _ _ + · exact Nat.zero_le _ + · exact min_le_left _ _ + have proof_trans_112 {Alpha : Type u_1} {s : Bool} {m : ℕ} {n : ℕ} {x : List.{u_1} Alpha} {y : List.{u_1} Alpha} {z : List.{u_1} Alpha} (h : OAI.EditDistortion.Script.{u_1} s m x y) (k : OAI.EditDistortion.Script.{u_1} s n y z) : OAI.EditDistortion.Script s (m + n) x z := by + induction h with + | nil => simpa using k + | @cons l x w y e h ih => + simpa only [Nat.add_right_comm] using OAI.EditDistortion.Script.cons e (ih k) + have proof_to_nil_113 {Alpha : Type u_1} {s : Bool} (x : List.{u_1} Alpha) : OAI.EditDistortion.Script s x.length x [] := by + induction x with + | nil => exact .nil [] + | cons a x ih => exact .cons (.delete [] x a) ih + have proof_single_114 {Alpha : Type u_1} {s : Bool} {x : List.{u_1} Alpha} {y : List.{u_1} Alpha} (h : OAI.EditDistortion.Step.{u_1} s x y) : OAI.EditDistortion.Script s 1 x y := + .cons h (.nil y) + have proof_symm_115 {Alpha : Type u_1} {s : Bool} {x : List.{u_1} Alpha} {y : List.{u_1} Alpha} (h : OAI.EditDistortion.Step.{u_1} s x y) : OAI.EditDistortion.Step s y x := by + cases h with + | insert p q a => exact .delete p q a + | delete p q a => exact .insert p q a + | substitute hs p q a b => exact .substitute hs p q b a + have proof_symm_116 {Alpha : Type u_1} {s : Bool} {n : ℕ} {x : List.{u_1} Alpha} {y : List.{u_1} Alpha} (h : OAI.EditDistortion.Script.{u_1} s n x y) : OAI.EditDistortion.Script s n y x := by + induction h with + | nil x => exact .nil x + | cons e h ih => exact (proof_trans_112 ih (proof_single_114 (proof_symm_115 e))) + have proof_exists_script_117 {Alpha : Type u_1} {s : Bool} (x : List.{u_1} Alpha) (y : List.{u_1} Alpha) : ∃ n, OAI.EditDistortion.Script s n x y := + ⟨x.length + y.length, (proof_trans_112 (proof_to_nil_113 x) + (proof_symm_116 (proof_to_nil_113 y)))⟩ + have proof_cost_spec_118 {Alpha : Type u_1} {s : Bool} (x : List.{u_1} Alpha) (y : List.{u_1} Alpha) : OAI.EditDistortion.Script s (OAI.EditDistortion.cost s x y) x y := + Nat.sInf_mem (proof_exists_script_117 x y) + have proof_eq_of_zero_119 {Alpha : Type u_1} {s : Bool} {x : List.{u_1} Alpha} {y : List.{u_1} Alpha} (h : OAI.EditDistortion.Script.{u_1} s 0 x y) : x = y := by + cases h + rfl + have proof_cost_le_120 {Alpha : Type u_1} {s : Bool} {n : ℕ} {x : List.{u_1} Alpha} {y : List.{u_1} Alpha} (h : OAI.EditDistortion.Script.{u_1} s n x y) : OAI.EditDistortion.cost s x y ≤ n := + Nat.sInf_le h + have proof_cost_refl_121 {Alpha : Type u_1} {s : Bool} (x : List.{u_1} Alpha) : OAI.EditDistortion.cost s x x = 0 := + Nat.eq_zero_of_le_zero (proof_cost_le_120 (.nil x)) + have proof_cost_eq_zero_iff_122 {Alpha : Type u_1} {s : Bool} {x : List.{u_1} Alpha} {y : List.{u_1} Alpha} : OAI.EditDistortion.cost s x y = 0 ↔ x = y := by + constructor + · intro h + have hc := proof_cost_spec_118 (s := s) x y + rw [h] at hc + exact (proof_eq_of_zero_119 hc) + · rintro rfl + exact proof_cost_refl_121 _ + have proof_coarseInitialValue_zero_123 {α : Type u_1} [instLocal1 : DecidableEq.{u_1 + 1} α] (B : ℕ) (D : ℕ) (Q : ℚ) (lam : ℚ) (N : ℕ) (x : List.{u_1} α) (y : List.{u_1} α) (draws : OAI.EditApproximation.CoarseGuessIndex (OAI.EditApproximation.coarseEntryWidth.{u_1} x y) → + OAI.EditApproximation.CoarseThresholdDraws B D) (hzero : Eq.{1} (OAI.EditDistortion.edit.{u_1} x y) 0) : OAI.EditApproximation.coarseInitialValue B D Q lam N x y draws = 0 := by + have hxy : x = y := (proof_cost_eq_zero_iff_122 (s := true)).mp hzero + subst y + simp only [OAI.EditApproximation.coarseInitialValue, ite_eq_right (by omega : ¬ 2 * x.length < x.length), ite_true] + have proof_computed_fullSeedTable_range_zero_110 (N : ℕ) (B : ℕ) {I : Type 0} {α : Type u_1} [instLocal4 : DecidableEq.{u_1 + 1} α] (depth : I → ℕ) (x : I → List.{u_1} α) (y : I → List.{u_1} α) (draws : OAI.EditApproximation.CoarseFullSeedDraws.{0, u_1} B depth x y) : + ∀ i, OAI.EditApproximation.coarseFullSeedTable N B depth x y draws i ≤ N ∧ + (OAI.EditDistortion.edit (x i) (y i) = 0 → OAI.EditApproximation.coarseFullSeedTable N B depth x y draws i = 0) := by + intro i + exact ⟨proof_coarseInitialValue_le_length_111 _ _ _ _ _ _ _ _, + proof_coarseInitialValue_zero_123 _ _ _ _ _ _ _ _⟩ + exact + fun state => + ⟨OAI.EditApproximation.coarseFullSeedTable N B depth + (fun state : OAI.EditApproximation.PhysicalEntry M J target.length => OAI.EditApproximation.physicalSource source state.1) + (fun state : OAI.EditApproximation.PhysicalEntry M J target.length => OAI.EditApproximation.substring target state.2.lo state.2.hi) draw state, + Nat.lt_succ_of_le ((proof_computed_fullSeedTable_range_zero_110 N B depth _ _ draw state).1)⟩ + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open MeasureTheory ProbabilityTheory +variable {α : Type u_1} [DecidableEq α] {M J R : ℕ} [NeZero M] [NeZero R] [MeasurableSpace (Fin M)] [MeasurableSingletonClass (Fin M)] (source target : List α) (N P T S H : ℕ) +local notation (name := source_Combinatorics_EditApproximation_Geometry_LocalTraceMemoOutput_5) "passes" => computedSeedPassCount N + +def localFinalRootRequest (hH : 0 < H) (rootQ : OAI.EditApproximation.TargetInterval target.length) : + OAI.EditApproximation.ChargedPhysicalRequest M J target.length (passes + 1) (H ^ 2) T S := + .inr ⟨OAI.EditApproximation.PhysicalTableRequest.refinement passes 0 + (Sigma.mk (Fin.mk 0 (Nat.zero_lt_succ J)) PUnit.unit) T S rootQ, + ⟨Nat.lt_succ_self _, pow_pos hH 2, le_rfl⟩⟩ + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open Filter + +noncomputable def computedFamilyKernelWork (source target : List ℕ) (N : ℕ) + (input : OAI.EditApproximation.ComputedFamilyInput source target N) + (cost : OAI.EditApproximation.ComputedFamilyMemoKey source target N → ℕ) : ℕ := + OAI.EditApproximation.rankedMemoKernelWork (OAI.EditApproximation.SourceRanked.rank OAI.EditApproximation.ChargedPhysicalRequest.rank) + (OAI.EditApproximation.SourceRanked.body OAI.EditApproximation.ChargedPhysicalRequest.rank + (OAI.EditApproximation.physicalFamilyProgram source target N (OAI.EditApproximation.integerParameters N).P (OAI.EditApproximation.inputSmallLog N) + (40 * OAI.EditApproximation.smallLogExponent N) (OAI.EditApproximation.inputHeight N) (OAI.EditApproximation.inputSmallLog N ^ 80) + (OAI.EditApproximation.integerParameters N).T (OAI.EditApproximation.integerParameters N).S (OAI.EditApproximation.computedSeedPassCount N) (OAI.EditApproximation.inputHeight N ^ 2) + (OAI.EditApproximation.scheduledSeedFactor N) (OAI.EditApproximation.scheduledSeedMultiplier N) + (OAI.EditApproximation.rationalParameters (OAI.EditApproximation.inputSmallLog N)).tau (OAI.EditApproximation.rationalParameters (OAI.EditApproximation.inputSmallLog N)).eta + (OAI.EditApproximation.rationalParameters (OAI.EditApproximation.inputSmallLog N)).kappa (OAI.EditApproximation.rationalParameters (OAI.EditApproximation.inputSmallLog N)).delta + (OAI.EditApproximation.clampedSeedNat input.1)) + (OAI.EditApproximation.physicalFamilyAnswer target N (OAI.EditApproximation.integerParameters N).P (OAI.EditApproximation.inputSmallLog N) + (40 * OAI.EditApproximation.smallLogExponent N) (OAI.EditApproximation.inputHeight N) (OAI.EditApproximation.inputSmallLog N ^ 80) + (OAI.EditApproximation.computedSeedPassCount N) (OAI.EditApproximation.inputHeight N ^ 2) input.2)) + (16384 * OAI.EditApproximation.inputHeight N + 5) (OAI.EditApproximation.computedFamilyMemoCode source target N (OAI.EditApproximation.inputHeight N ^ 2)) cost + (.inr (OAI.EditApproximation.localFinalRootRequest target N (OAI.EditApproximation.integerParameters N).T (OAI.EditApproximation.integerParameters N).S + (OAI.EditApproximation.inputHeight N) (Nat.two_pow_pos _) (OAI.EditApproximation.finalTargetState target.length))) .empty + +noncomputable def computedFamilyAddressWork (source target : List ℕ) (N : ℕ) + (input : OAI.EditApproximation.ComputedFamilyInput source target N) : ℕ := + OAI.EditApproximation.rankedMemoAddressWork (OAI.EditApproximation.SourceRanked.rank OAI.EditApproximation.ChargedPhysicalRequest.rank) + (OAI.EditApproximation.SourceRanked.body OAI.EditApproximation.ChargedPhysicalRequest.rank + (OAI.EditApproximation.physicalFamilyProgram source target N (OAI.EditApproximation.integerParameters N).P (OAI.EditApproximation.inputSmallLog N) + (40 * OAI.EditApproximation.smallLogExponent N) (OAI.EditApproximation.inputHeight N) (OAI.EditApproximation.inputSmallLog N ^ 80) + (OAI.EditApproximation.integerParameters N).T (OAI.EditApproximation.integerParameters N).S (OAI.EditApproximation.computedSeedPassCount N) (OAI.EditApproximation.inputHeight N ^ 2) + (OAI.EditApproximation.scheduledSeedFactor N) (OAI.EditApproximation.scheduledSeedMultiplier N) + (OAI.EditApproximation.rationalParameters (OAI.EditApproximation.inputSmallLog N)).tau (OAI.EditApproximation.rationalParameters (OAI.EditApproximation.inputSmallLog N)).eta + (OAI.EditApproximation.rationalParameters (OAI.EditApproximation.inputSmallLog N)).kappa (OAI.EditApproximation.rationalParameters (OAI.EditApproximation.inputSmallLog N)).delta + (OAI.EditApproximation.clampedSeedNat input.1)) + (OAI.EditApproximation.physicalFamilyAnswer target N (OAI.EditApproximation.integerParameters N).P (OAI.EditApproximation.inputSmallLog N) + (40 * OAI.EditApproximation.smallLogExponent N) (OAI.EditApproximation.inputHeight N) (OAI.EditApproximation.inputSmallLog N ^ 80) + (OAI.EditApproximation.computedSeedPassCount N) (OAI.EditApproximation.inputHeight N ^ 2) input.2)) + (16384 * OAI.EditApproximation.inputHeight N + 5) (OAI.EditApproximation.computedFamilyMemoCode source target N (OAI.EditApproximation.inputHeight N ^ 2)) + (fun key => (OAI.EditApproximation.computedFamilyMemoCodeWithWork source target N (OAI.EditApproximation.inputHeight N ^ 2) key).2) + (.inr (OAI.EditApproximation.localFinalRootRequest target N (OAI.EditApproximation.integerParameters N).T (OAI.EditApproximation.integerParameters N).S + (OAI.EditApproximation.inputHeight N) (Nat.two_pow_pos _) (OAI.EditApproximation.finalTargetState target.length))) .empty + +noncomputable def computedFamilyCoarseCopyStorage (source target : List ℕ) (N : ℕ) + (input : OAI.EditApproximation.ComputedFamilyInput source target N) : ℕ := + OAI.EditApproximation.computedFamilyKernelWork source target N input (OAI.EditApproximation.coarseHistoryKeyCost + (OAI.EditApproximation.physicalCoarseInputStorage (M := (OAI.EditApproximation.integerParameters N).M) + (J := OAI.EditApproximation.intervalTreeDepth (OAI.EditApproximation.integerParameters N).M source.length) source target)) + +noncomputable def computedFamilyCoarseArrayCapacity (source target : List ℕ) (N : ℕ) + (input : OAI.EditApproximation.ComputedFamilyInput source target N) : ℕ := + OAI.EditApproximation.computedFamilyKernelWork source target N input (OAI.EditApproximation.coarseHistoryKeyCost (fun _ => (N + 2) ^ 37)) + +noncomputable def computedFamilyCoarseScratchCapacity (source target : List ℕ) (N : ℕ) + (input : OAI.EditApproximation.ComputedFamilyInput source target N) : ℕ := + OAI.EditApproximation.computedFamilyKernelWork source target N input (OAI.EditApproximation.coarseHistoryKeyCost (fun _ => (N + 2) ^ 181)) + +noncomputable def computedFamilyCoarseControlCapacity (source target : List ℕ) (N : ℕ) + (input : OAI.EditApproximation.ComputedFamilyInput source target N) : ℕ := + OAI.EditApproximation.computedFamilyKernelWork source target N input (OAI.EditApproximation.coarseHistoryKeyCost (fun _ => (N + 2) ^ 182)) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open MeasureTheory ProbabilityTheory +variable {α : Type} [DecidableEq α] {M J R : ℕ} [NeZero M] [NeZero R] (source target : List α) (N P T S H : ℕ) +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyMemo_4) "Seed" => ClampedPhysicalSeed M J target.length N +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyMemo_5) "ell" => inputSmallLog N +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyMemo_6) "exponent" => (40 * smallLogExponent N : ℕ) +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyMemo_7) "passes" => computedSeedPassCount N +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyMemo_8) "tau" => RationalParameters.tau (rationalParameters ell) +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyMemo_9) "eta" => RationalParameters.eta (rationalParameters ell) +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyMemo_10) "kappa" => RationalParameters.kappa (rationalParameters ell) +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyMemo_11) "delta" => RationalParameters.delta (rationalParameters ell) +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyMemo_12) "Key" => PhysicalFamilyScalarKey (M := M) (J := J) (R := R) + target N P ell exponent H (ell ^ 80) passes (H ^ 2) +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyMemo_13) "Family" => PhysicalFamilyScalarDraw (M := M) (J := J) (R := R) + target N P ell exponent H (ell ^ 80) passes (H ^ 2) +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyMemo_14) "Table" => ChargedPhysicalRequest M J target.length (passes + 1) (H ^ 2) T S + +noncomputable def physicalFamilyMemoResult (hH : 0 < H) (bits : ℕ) + (encode : Sum Key Table → ℕ) (rootQ : OAI.EditApproximation.TargetInterval target.length) (input : Seed × Family) := + OAI.EditApproximation.chargedRandomMemoEvaluate source target N P ell exponent H (ell ^ 80) T S (passes + 1) (H ^ 2) + (OAI.EditApproximation.scheduledSeedFactor N) (OAI.EditApproximation.scheduledSeedMultiplier N) tau eta kappa delta + (OAI.EditApproximation.physicalFamilyGroupRead target N P ell exponent H (ell ^ 80) passes (H ^ 2)) + (OAI.EditApproximation.physicalFamilyOnlineRead target N P ell exponent H (ell ^ 80) passes (H ^ 2)) + (OAI.EditApproximation.clampedSeedNat input.1) + (OAI.EditApproximation.physicalFamilyAnswer target N P ell exponent H (ell ^ 80) passes (H ^ 2) input.2) + bits encode (OAI.EditApproximation.localFinalRootRequest target N T S H hH rootQ) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open MeasureTheory ProbabilityTheory Finset +attribute [local instance] Classical.propDecidable + +noncomputable def selectionIndicator (p : Prop) : ℝ := if p then 1 else 0 + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation + + +noncomputable def coarseIndexedEntryCostSum {M J B : ℕ} [NeZero B] (source target : List ℕ) + (N : ℕ) (depth : OAI.EditApproximation.PhysicalEntry M J target.length → ℕ) + (draw : OAI.EditApproximation.PhysicalCoarseDraw source target B depth) + (selected : OAI.EditApproximation.PhysicalEntry M J target.length → Prop) : ℝ := by + classical + exact ∑ entry : OAI.EditApproximation.PhysicalEntry M J target.length, OAI.EditApproximation.selectionIndicator (selected entry) * + (OAI.EditApproximation.coarseIndexedEntryBinaryCost N B (depth entry) (OAI.EditApproximation.physicalSource source entry.1) + (OAI.EditApproximation.substring target entry.2.lo entry.2.hi) (draw entry) : ℝ) + +def querySupportedChildAllocation {σ : Type u_1} {M J n : ℕ} (passes copies T S : ℕ) + (parent : {r : OAI.EditApproximation.PhysicalTableRequest M J n // r.Bounded passes copies T S}) + (key : OAI.EditApproximation.QueryPhysicalChild (σ := σ) passes copies T S parent) : ℕ := + match key with + | .inl _ => 0 + | .inr child => OAI.EditApproximation.queryPhysicalBoundedAllocation passes copies T S child.val + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open MeasureTheory ProbabilityTheory +variable {ι : Type u_1} [Fintype ι] (range : ι → ℕ) [∀ i, NeZero (range i)] +open Finset + +noncomputable def rejectionFailureLaw (i : ι) : Measure ℕ := by + have proof_rejectionWord_range_124 (N : ℕ) (hN : LT.lt.{0} 0 N) : + N ≤ 2 ^ OAI.EditApproximation.rejectionBitCount N ∧ 2 ^ OAI.EditApproximation.rejectionBitCount N < 2 * N := by + constructor + · exact Nat.le_pow_clog (by norm_num) N + · by_cases hNone : N = 1 + · subst N + norm_num [OAI.EditApproximation.rejectionBitCount] + · have hN1 : 1 < N := by omega + have hpred := Nat.pow_pred_clog_lt_self (by norm_num : 1 < 2) hN1 + have hB := Nat.clog_pos (by norm_num : 1 < 2) hN1 + have hpow : 2 ^ OAI.EditApproximation.rejectionBitCount N = 2 ^ (Nat.clog 2 N).pred * 2 := by + rw [OAI.EditApproximation.rejectionBitCount, ← pow_succ] + congr 1 + exact (Nat.succ_pred_eq_of_pos hB).symm + rw [hpow] + omega + exact + geometricMeasure (OAI.EditApproximation.rejectionSuccessParameter (range i) (2 ^ OAI.EditApproximation.rejectionBitCount (range i)) + (Nat.pos_of_ne_zero (NeZero.ne (range i))) + (proof_rejectionWord_range_124 (range i) (Nat.pos_of_ne_zero (NeZero.ne (range i)))).1) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open MeasureTheory ProbabilityTheory +variable {ι : Type u_1} [Fintype ι] (range : ι → ℕ) [∀ i, NeZero (range i)] + +noncomputable def rejectionRuntimeArrayLaw : Measure (OAI.EditApproximation.RejectionRuntimeArray range) := + (Measure.pi (OAI.EditApproximation.rejectionFailureLaw range)).prod (OAI.EditApproximation.rejectionAcceptedLaw range) + +noncomputable def rejectionSelectedBits + (selected : ι → (∀ i, Fin (range i)) → Prop) (execution : OAI.EditApproximation.RejectionRuntimeArray range) : ℝ := + ∑ i, (((execution.1 i : ℝ) + 1) * OAI.EditApproximation.rejectionBitCount (range i)) * + OAI.EditApproximation.selectionIndicator (selected i execution.2) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open MeasureTheory ProbabilityTheory +variable {α : Type u_1} {M J R : ℕ} [NeZero M] (target : List α) (N P F exponent H Q passes copies : ℕ) + +abbrev physicalFamilyRange (key : OAI.EditApproximation.PhysicalFamilyScalarKey (M := M) (J := J) (R := R) + target N P F exponent H Q passes copies) : ℕ := + OAI.EditApproximation.physicalScalarRange M J N target.length exponent F Q R (OAI.EditApproximation.localOnlineMassBound M P H) key.2.2 + +instance physicalFamilyRange_neZero (key : OAI.EditApproximation.PhysicalFamilyScalarKey (M := M) (J := J) (R := R) + target N P F exponent H Q passes copies) : + NeZero (OAI.EditApproximation.physicalFamilyRange target N P F exponent H Q passes copies key) := by + exact OAI.EditApproximation.physicalScalarRangeNeZero M J N target.length exponent F Q R + (OAI.EditApproximation.localOnlineMassBound M P H) key.2.2 + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open MeasureTheory + +abbrev ComputedPhysicalCoarseDraw (source target : List ℕ) (N : ℕ) := + OAI.EditApproximation.PhysicalCoarseDraw (M := (OAI.EditApproximation.integerParameters N).M) + (J := OAI.EditApproximation.intervalTreeDepth (OAI.EditApproximation.integerParameters N).M source.length) source target (OAI.EditApproximation.integerParameters N).B (OAI.EditApproximation.computedPhysicalCoarseDepth source target N) + +abbrev ComputedRejectionRuntime (source target : List ℕ) (N : ℕ) := + OAI.EditApproximation.RejectionRuntimeArray (OAI.EditApproximation.physicalFamilyRange (M := (OAI.EditApproximation.integerParameters N).M) + (J := OAI.EditApproximation.intervalTreeDepth (OAI.EditApproximation.integerParameters N).M source.length) (R := OAI.EditApproximation.inputHeight N ^ 2) + target N (OAI.EditApproximation.integerParameters N).P (OAI.EditApproximation.inputSmallLog N) (40 * OAI.EditApproximation.smallLogExponent N) + (OAI.EditApproximation.inputHeight N) (OAI.EditApproximation.inputSmallLog N ^ 80) (OAI.EditApproximation.computedSeedPassCount N) (OAI.EditApproximation.inputHeight N ^ 2)) + +noncomputable def computedPhysicalCoarseLaw (source target : List ℕ) (N : ℕ) : + Measure (OAI.EditApproximation.ComputedPhysicalCoarseDraw source target N) := + OAI.EditApproximation.coarseFullSeedMeasure (OAI.EditApproximation.integerParameters N).B (OAI.EditApproximation.computedPhysicalCoarseDepth source target N) + (fun entry => OAI.EditApproximation.physicalSource source entry.1) + (fun entry => OAI.EditApproximation.substring target entry.2.lo entry.2.hi) + +abbrev ComputedExecutionOutcome (source target : List ℕ) (N : ℕ) := + OAI.EditApproximation.ComputedPhysicalCoarseDraw source target N × OAI.EditApproximation.ComputedRejectionRuntime source target N + +noncomputable def computedExecutionLaw (source target : List ℕ) (N : ℕ) : + Measure (OAI.EditApproximation.ComputedExecutionOutcome source target N) := + (OAI.EditApproximation.computedPhysicalCoarseLaw source target N).prod + (OAI.EditApproximation.rejectionRuntimeArrayLaw (OAI.EditApproximation.physicalFamilyRange (M := (OAI.EditApproximation.integerParameters N).M) + (J := OAI.EditApproximation.intervalTreeDepth (OAI.EditApproximation.integerParameters N).M source.length) (R := OAI.EditApproximation.inputHeight N ^ 2) + target N (OAI.EditApproximation.integerParameters N).P (OAI.EditApproximation.inputSmallLog N) (40 * OAI.EditApproximation.smallLogExponent N) + (OAI.EditApproximation.inputHeight N) (OAI.EditApproximation.inputSmallLog N ^ 80) (OAI.EditApproximation.computedSeedPassCount N) (OAI.EditApproximation.inputHeight N ^ 2))) + +abbrev ComputedFullOutcome (source target : List ℕ) (N : ℕ) := + Unit ⊕ OAI.EditApproximation.ComputedExecutionOutcome source target N + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open MeasureTheory ProbabilityTheory +variable {α : Type} [DecidableEq α] {M J R : ℕ} [NeZero M] [NeZero R] (source target : List α) (N P T S H : ℕ) +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyRuntime_4) "SeedState" => ClampedPhysicalSeed M J target.length N +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyRuntime_5) "ell" => inputSmallLog N +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyRuntime_6) "exponent" => (40 * smallLogExponent N : ℕ) +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyRuntime_7) "passes" => computedSeedPassCount N +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyRuntime_8) "FamilyRange" => physicalFamilyRange (M := M) (J := J) (R := R) + target N P ell exponent H (ell ^ 80) passes (H ^ 2) +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyRuntime_9) "Family" => PhysicalFamilyScalarDraw (M := M) (J := J) (R := R) + target N P ell exponent H (ell ^ 80) passes (H ^ 2) + +abbrev PhysicalFamilyRuntimeOutcome := SeedState × OAI.EditApproximation.RejectionRuntimeArray FamilyRange + +def physicalFamilyRuntimeAccepted + (execution : OAI.EditApproximation.PhysicalFamilyRuntimeOutcome (M := M) (J := J) (R := R) target N P H) : SeedState × Family := + (execution.1, execution.2.2) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open MeasureTheory ProbabilityTheory Filter + +def physicalLargeInput (N : ℕ) (epsilon : OAI.EditApproximation.BinaryFraction) : Prop := + (OAI.EditApproximation.inspectAccuracyWithWork (OAI.EditApproximation.inputHeight N) epsilon).1.isSome = true ∧ + OAI.EditApproximation.largeAccuracyInput N epsilon.value ∧ + Nat.size (OAI.EditApproximation.localOnlineMassBound (OAI.EditApproximation.integerParameters N).M (OAI.EditApproximation.integerParameters N).P + (OAI.EditApproximation.inputHeight N)) ≤ OAI.EditApproximation.inputHeight N + +instance physicalLargeInput_decidable (N : ℕ) (epsilon : OAI.EditApproximation.BinaryFraction) : + Decidable (OAI.EditApproximation.physicalLargeInput N epsilon) := inferInstanceAs (Decidable (_ ∧ _ ∧ _)) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open MeasureTheory ProbabilityTheory +variable {α : Type} [DecidableEq α] {M J R : ℕ} [NeZero M] [NeZero R] (source target : List α) (N P T S H : ℕ) +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyRejectionWork_4) "SeedState" => ClampedPhysicalSeed M J target.length N +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyRejectionWork_5) "ell" => inputSmallLog N +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyRejectionWork_6) "exponent" => (40 * smallLogExponent N : ℕ) +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyRejectionWork_7) "passes" => computedSeedPassCount N +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyRejectionWork_8) "Key" => PhysicalFamilyScalarKey (M := M) (J := J) (R := R) + target N P ell exponent H (ell ^ 80) passes (H ^ 2) +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyRejectionWork_9) "Table" => ChargedPhysicalRequest M J target.length (passes + 1) (H ^ 2) T S +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyRejectionWork_10) "FamilyRange" => physicalFamilyRange (M := M) (J := J) (R := R) + target N P ell exponent H (ell ^ 80) passes (H ^ 2) + +noncomputable def physicalFamilyMemoBits (hH : 0 < H) (bits : ℕ) + (encode : Sum Key Table → ℕ) (rootQ : OAI.EditApproximation.TargetInterval target.length) (seed : SeedState) + (execution : OAI.EditApproximation.RejectionRuntimeArray FamilyRange) : ℝ := + OAI.EditApproximation.rejectionSelectedBits FamilyRange (fun key accepted => Sum.inl key ∈ + (OAI.EditApproximation.physicalFamilyMemoResult source target N P T S H hH bits encode rootQ (seed, accepted)).freshKeys) + execution + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open Filter MeasureTheory + +noncomputable def computedFamilyResult (source target : List ℕ) (N : ℕ) + (input : OAI.EditApproximation.ComputedFamilyInput source target N) := + OAI.EditApproximation.physicalFamilyMemoResult source target N (OAI.EditApproximation.integerParameters N).P (OAI.EditApproximation.integerParameters N).T + (OAI.EditApproximation.integerParameters N).S (OAI.EditApproximation.inputHeight N) (Nat.two_pow_pos _) + (16384 * OAI.EditApproximation.inputHeight N + 5) (OAI.EditApproximation.computedFamilyMemoCode source target N (OAI.EditApproximation.inputHeight N ^ 2)) + (OAI.EditApproximation.finalTargetState target.length) input + +noncomputable def computedFamilyRejectionWork (source target : List ℕ) (N : ℕ) + (execution : OAI.EditApproximation.PhysicalFamilyRuntimeOutcome (M := (OAI.EditApproximation.integerParameters N).M) + (J := OAI.EditApproximation.intervalTreeDepth (OAI.EditApproximation.integerParameters N).M source.length) (R := OAI.EditApproximation.inputHeight N ^ 2) + target N (OAI.EditApproximation.integerParameters N).P (OAI.EditApproximation.inputHeight N)) : ℝ := + OAI.EditApproximation.physicalFamilyMemoBits source target N (OAI.EditApproximation.integerParameters N).P (OAI.EditApproximation.integerParameters N).T + (OAI.EditApproximation.integerParameters N).S (OAI.EditApproximation.inputHeight N) (Nat.two_pow_pos _) (16384 * OAI.EditApproximation.inputHeight N + 5) + (OAI.EditApproximation.computedFamilyMemoCode source target N (OAI.EditApproximation.inputHeight N ^ 2)) (OAI.EditApproximation.finalTargetState target.length) + execution.1 execution.2 + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open MeasureTheory +variable {α : Type u_1} [DecidableEq α] {M J R : ℕ} [NeZero M] [NeZero R] (source target : List α) (N P H T S passes copies : ℕ) (factor : ℕ → ℚ) (multiplier : ℕ → ℕ) (tau eta kappa delta : ℚ) (draw : PhysicalFamilyScalarDraw (M := M) (J := J) (R := R) + target N P (inputSmallLog N) (40 * smallLogExponent N) H (inputSmallLog N ^ 80) passes copies) (B : ℕ) [NeZero B] [MeasurableSpace (Fin B)] [MeasurableSingletonClass (Fin B)] (depth : PhysicalEntry M J target.length → ℕ) +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyMemoCoarse_5) "ell" => inputSmallLog N +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyMemoCoarse_6) "exponent" => (40 * smallLogExponent N : ℕ) +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyMemoCoarse_7) "Key" => PhysicalFamilyScalarKey (M := M) (J := J) (R := R) + target N P ell exponent H (ell ^ 80) passes copies +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyMemoCoarse_8) "Table" => ChargedPhysicalRequest M J target.length (passes + 1) copies T S +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyMemoCoarse_9) "readGroup" => physicalFamilyGroupRead (M := M) (J := J) (R := R) + target N P ell exponent H (ell ^ 80) passes copies +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyMemoCoarse_10) "readInteger" => physicalFamilyOnlineRead (M := M) (J := J) (R := R) + target N P ell exponent H (ell ^ 80) passes copies +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyMemoCoarse_11) "answer" => physicalFamilyAnswer target N P ell exponent H (ell ^ 80) passes copies draw + +noncomputable def physicalFamilyMemoCoarseWork (bits : ℕ) (encode : Sum Key Table → ℕ) + (root : Table) (coarse : OAI.EditApproximation.PhysicalCoarseDraw source target B depth) : ℝ := + let initial := OAI.EditApproximation.clampedSeedNat (OAI.EditApproximation.physicalCoarseSeedTable source target N B depth coarse) + let result := OAI.EditApproximation.chargedRandomMemoEvaluate source target N P ell exponent H (ell ^ 80) + T S (passes + 1) copies factor multiplier tau eta kappa delta readGroup readInteger initial + answer bits encode root + ∑ entry, OAI.EditApproximation.selectionIndicator (Sum.inr (Sum.inl entry) ∈ result.freshKeys) * + (OAI.EditApproximation.coarseInitialArrayWork B (depth entry) (OAI.EditApproximation.initialThresholdQ N) (OAI.EditApproximation.initialLambda N) + (OAI.EditApproximation.physicalSource source entry.1) (OAI.EditApproximation.substring target entry.2.lo entry.2.hi) (coarse entry) : ℝ) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open MeasureTheory +variable {α : Type} [DecidableEq α] {M J R : ℕ} [NeZero M] [NeZero R] (source target : List α) (N P H B : ℕ) (depth : PhysicalEntry M J target.length → ℕ) + +abbrev PhysicalCoarseExecution := OAI.EditApproximation.PhysicalCoarseDraw source target B depth × + OAI.EditApproximation.RejectionRuntimeArray (OAI.EditApproximation.physicalFamilyRange (M := M) (J := J) (R := R) + target N P (OAI.EditApproximation.inputSmallLog N) (40 * OAI.EditApproximation.smallLogExponent N) H + (OAI.EditApproximation.inputSmallLog N ^ 80) (OAI.EditApproximation.computedSeedPassCount N) (H ^ 2)) + +noncomputable def physicalCoarseExecutionProjection + (execution : OAI.EditApproximation.PhysicalCoarseExecution (R := R) source target N P H B depth) : + OAI.EditApproximation.PhysicalFamilyRuntimeOutcome (M := M) (J := J) (R := R) target N P H := + (OAI.EditApproximation.physicalCoarseSeedTable source target N B depth execution.1, execution.2) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open MeasureTheory + +noncomputable def computedExecutionProjection (source target : List ℕ) (N : ℕ) := + OAI.EditApproximation.physicalCoarseExecutionProjection (M := (OAI.EditApproximation.integerParameters N).M) + (J := OAI.EditApproximation.intervalTreeDepth (OAI.EditApproximation.integerParameters N).M source.length) (R := OAI.EditApproximation.inputHeight N ^ 2) + source target N (OAI.EditApproximation.integerParameters N).P (OAI.EditApproximation.inputHeight N) (OAI.EditApproximation.integerParameters N).B + (OAI.EditApproximation.computedPhysicalCoarseDepth source target N) + +noncomputable def computedFullLaw (source target : List ℕ) (N : ℕ) (epsilon : OAI.EditApproximation.BinaryFraction) : + Measure (OAI.EditApproximation.ComputedFullOutcome source target N) := + if OAI.EditApproximation.physicalLargeInput N epsilon then (OAI.EditApproximation.computedExecutionLaw source target N).map Sum.inr + else Measure.dirac (Sum.inl ()) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open MeasureTheory Filter + +noncomputable def computedExecutionAccepted (source target : List ℕ) (N : ℕ) + (execution : OAI.EditApproximation.ComputedExecutionOutcome source target N) : OAI.EditApproximation.ComputedFamilyInput source target N := + OAI.EditApproximation.physicalFamilyRuntimeAccepted target N (OAI.EditApproximation.integerParameters N).P (OAI.EditApproximation.inputHeight N) + (OAI.EditApproximation.computedExecutionProjection source target N execution) + +noncomputable def computedExecutionRejectionWork (source target : List ℕ) (N : ℕ) : + OAI.EditApproximation.ComputedExecutionOutcome source target N → ℝ := + OAI.EditApproximation.computedFamilyRejectionWork source target N ∘ OAI.EditApproximation.computedExecutionProjection source target N + +def computedFinalRoot (source target : List ℕ) (N : ℕ) : OAI.EditApproximation.ComputedFamilyTableKey source target N := + OAI.EditApproximation.localFinalRootRequest (M := (OAI.EditApproximation.integerParameters N).M) + (J := OAI.EditApproximation.intervalTreeDepth (OAI.EditApproximation.integerParameters N).M source.length) target N + (OAI.EditApproximation.integerParameters N).T (OAI.EditApproximation.integerParameters N).S (OAI.EditApproximation.inputHeight N) (Nat.two_pow_pos _) + (OAI.EditApproximation.finalTargetState target.length) + +noncomputable def computedExecutionKernelWork (source target : List ℕ) (N : ℕ) + (cost : OAI.EditApproximation.ComputedFamilyInput source target N → OAI.EditApproximation.ComputedFamilyMemoKey source target N → ℕ) + (execution : OAI.EditApproximation.ComputedExecutionOutcome source target N) : ℝ := + let input := OAI.EditApproximation.computedExecutionAccepted source target N execution + OAI.EditApproximation.computedFamilyKernelWork source target N input (cost input) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open Filter MeasureTheory + +noncomputable def computedExecutionDictionaryWork (source target : List ℕ) (N : ℕ) + (execution : OAI.EditApproximation.ComputedExecutionOutcome source target N) : ℝ := + (OAI.EditApproximation.computedFamilyResult source target N (OAI.EditApproximation.computedExecutionAccepted source target N execution)).dictionaryVisits + +noncomputable def computedExecutionAddressWork (source target : List ℕ) (N : ℕ) + (execution : OAI.EditApproximation.ComputedExecutionOutcome source target N) : ℝ := + OAI.EditApproximation.computedFamilyAddressWork source target N (OAI.EditApproximation.computedExecutionAccepted source target N execution) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open MeasureTheory Filter +variable {M J R B : ℕ} [NeZero M] [NeZero R] [NeZero B] (source target : List ℕ) (N : ℕ) (depth : PhysicalEntry M J target.length → ℕ) (encode : Sum (PhysicalFamilyScalarKey (M := M) (J := J) (R := R) + target N (integerParameters N).P (inputSmallLog N) (40 * smallLogExponent N) + (inputHeight N) (inputSmallLog N ^ 80) (computedSeedPassCount N) (inputHeight N ^ 2)) + (ChargedPhysicalRequest M J target.length (computedSeedPassCount N + 1) + (inputHeight N ^ 2) (integerParameters N).T (integerParameters N).S) → ℕ) + +noncomputable def symbolicComputedCoarseWork := + fun draw => OAI.EditApproximation.physicalFamilyMemoCoarseWork source target N (OAI.EditApproximation.integerParameters N).P + (OAI.EditApproximation.inputHeight N) (OAI.EditApproximation.integerParameters N).T (OAI.EditApproximation.integerParameters N).S (OAI.EditApproximation.computedSeedPassCount N) + (OAI.EditApproximation.inputHeight N ^ 2) (OAI.EditApproximation.scheduledSeedFactor N) (OAI.EditApproximation.scheduledSeedMultiplier N) + (OAI.EditApproximation.rationalParameters (OAI.EditApproximation.inputSmallLog N)).tau (OAI.EditApproximation.rationalParameters (OAI.EditApproximation.inputSmallLog N)).eta + (OAI.EditApproximation.rationalParameters (OAI.EditApproximation.inputSmallLog N)).kappa (OAI.EditApproximation.rationalParameters (OAI.EditApproximation.inputSmallLog N)).delta + draw B depth (16384 * OAI.EditApproximation.inputHeight N + 5) encode + (OAI.EditApproximation.localFinalRootRequest target N (OAI.EditApproximation.integerParameters N).T (OAI.EditApproximation.integerParameters N).S + (OAI.EditApproximation.inputHeight N) (Nat.two_pow_pos _) (OAI.EditApproximation.finalTargetState target.length)) + +noncomputable def symbolicComputedExecutionCoarseWork + (execution : OAI.EditApproximation.PhysicalCoarseExecution (R := R) source target N + (OAI.EditApproximation.integerParameters N).P (OAI.EditApproximation.inputHeight N) B depth) : ℝ := + OAI.EditApproximation.symbolicComputedCoarseWork source target N depth encode execution.2.2 execution.1 + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open MeasureTheory Filter + +noncomputable def computedExecutionCoarseWork (source target : List ℕ) (N : ℕ) := + OAI.EditApproximation.symbolicComputedExecutionCoarseWork (M := (OAI.EditApproximation.integerParameters N).M) + (J := OAI.EditApproximation.intervalTreeDepth (OAI.EditApproximation.integerParameters N).M source.length) (R := OAI.EditApproximation.inputHeight N ^ 2) + (B := (OAI.EditApproximation.integerParameters N).B) source target N (OAI.EditApproximation.computedPhysicalCoarseDepth source target N) + (OAI.EditApproximation.computedFamilyMemoCode source target N (OAI.EditApproximation.inputHeight N ^ 2)) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open Filter MeasureTheory + +noncomputable def computedExecutionNonlocalWork (source target : List ℕ) (N : ℕ) + (execution : OAI.EditApproximation.ComputedExecutionOutcome source target N) : ℝ := + OAI.EditApproximation.computedExecutionCoarseWork source target N execution + + OAI.EditApproximation.computedExecutionRejectionWork source target N execution + + OAI.EditApproximation.computedExecutionDictionaryWork source target N execution + + OAI.EditApproximation.computedExecutionAddressWork source target N execution + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {M J R B : ℕ} [NeZero M] [NeZero R] [NeZero B] (source target : List ℕ) (N P H T S passes copies : ℕ) (factor : ℕ → ℚ) (multiplier : ℕ → ℕ) (tau eta kappa delta : ℚ) (draw : PhysicalFamilyScalarDraw (M := M) (J := J) (R := R) + target N P (inputSmallLog N) (40 * smallLogExponent N) H (inputSmallLog N ^ 80) passes copies) (depth : PhysicalEntry M J target.length → ℕ) +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalIndexedCoarseWork_3) "ell" => inputSmallLog N +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalIndexedCoarseWork_4) "exponent" => (40 * smallLogExponent N : ℕ) +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalIndexedCoarseWork_5) "Key" => PhysicalFamilyScalarKey (M := M) (J := J) (R := R) + target N P ell exponent H (ell ^ 80) passes copies +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalIndexedCoarseWork_6) "Table" => ChargedPhysicalRequest M J target.length (passes + 1) copies T S +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalIndexedCoarseWork_7) "readGroup" => physicalFamilyGroupRead (M := M) (J := J) (R := R) + target N P ell exponent H (ell ^ 80) passes copies +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalIndexedCoarseWork_8) "readInteger" => physicalFamilyOnlineRead (M := M) (J := J) (R := R) + target N P ell exponent H (ell ^ 80) passes copies +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalIndexedCoarseWork_9) "answer" => physicalFamilyAnswer target N P ell exponent H (ell ^ 80) passes copies draw + +noncomputable def physicalFamilyIndexedCoarseWork (bits : ℕ) (encode : Sum Key Table → ℕ) + (root : Table) (coarse : OAI.EditApproximation.PhysicalCoarseDraw source target B depth) : ℝ := + let initial := OAI.EditApproximation.clampedSeedNat (OAI.EditApproximation.physicalCoarseSeedTable source target N B depth coarse) + let result := OAI.EditApproximation.chargedRandomMemoEvaluate source target N P ell exponent H (ell ^ 80) + T S (passes + 1) copies factor multiplier tau eta kappa delta readGroup readInteger initial + answer bits encode root + OAI.EditApproximation.coarseIndexedEntryCostSum source target N depth coarse + (fun entry => Sum.inr (Sum.inl entry) ∈ result.freshKeys) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open Filter MeasureTheory +variable {M J R B : ℕ} [NeZero M] [NeZero R] [NeZero B] (source target : List ℕ) (N : ℕ) (depth : PhysicalEntry M J target.length → ℕ) (encode : Sum (PhysicalFamilyScalarKey (M := M) (J := J) (R := R) + target N (integerParameters N).P (inputSmallLog N) (40 * smallLogExponent N) + (inputHeight N) (inputSmallLog N ^ 80) (computedSeedPassCount N) (inputHeight N ^ 2)) + (ChargedPhysicalRequest M J target.length (computedSeedPassCount N + 1) + (inputHeight N ^ 2) (integerParameters N).T (integerParameters N).S) → ℕ) + +noncomputable def symbolicComputedExecutionIndexedCoarseWork + (execution : OAI.EditApproximation.PhysicalCoarseExecution (R := R) source target N + (OAI.EditApproximation.integerParameters N).P (OAI.EditApproximation.inputHeight N) B depth) : ℝ := + OAI.EditApproximation.physicalFamilyIndexedCoarseWork source target N (OAI.EditApproximation.integerParameters N).P (OAI.EditApproximation.inputHeight N) + (OAI.EditApproximation.integerParameters N).T (OAI.EditApproximation.integerParameters N).S (OAI.EditApproximation.computedSeedPassCount N) + (OAI.EditApproximation.inputHeight N ^ 2) (OAI.EditApproximation.scheduledSeedFactor N) (OAI.EditApproximation.scheduledSeedMultiplier N) + (OAI.EditApproximation.rationalParameters (OAI.EditApproximation.inputSmallLog N)).tau (OAI.EditApproximation.rationalParameters (OAI.EditApproximation.inputSmallLog N)).eta + (OAI.EditApproximation.rationalParameters (OAI.EditApproximation.inputSmallLog N)).kappa (OAI.EditApproximation.rationalParameters (OAI.EditApproximation.inputSmallLog N)).delta + execution.2.2 depth (16384 * OAI.EditApproximation.inputHeight N + 5) encode + (OAI.EditApproximation.localFinalRootRequest target N (OAI.EditApproximation.integerParameters N).T (OAI.EditApproximation.integerParameters N).S + (OAI.EditApproximation.inputHeight N) (Nat.two_pow_pos _) (OAI.EditApproximation.finalTargetState target.length)) execution.1 + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open Filter MeasureTheory + +noncomputable def computedExecutionIndexedCoarseWork (source target : List ℕ) (N : ℕ) := + OAI.EditApproximation.symbolicComputedExecutionIndexedCoarseWork (M := (OAI.EditApproximation.integerParameters N).M) + (J := OAI.EditApproximation.intervalTreeDepth (OAI.EditApproximation.integerParameters N).M source.length) (R := OAI.EditApproximation.inputHeight N ^ 2) + (B := (OAI.EditApproximation.integerParameters N).B) source target N (OAI.EditApproximation.computedPhysicalCoarseDepth source target N) + (OAI.EditApproximation.computedFamilyMemoCode source target N (OAI.EditApproximation.inputHeight N ^ 2)) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {M J R B : ℕ} [NeZero M] [NeZero R] [NeZero B] (source target : List ℕ) (N P H T S passes copies : ℕ) (factor : ℕ → ℚ) (multiplier : ℕ → ℕ) (tau eta kappa delta : ℚ) (draw : PhysicalFamilyScalarDraw (M := M) (J := J) (R := R) + target N P (inputSmallLog N) (40 * smallLogExponent N) H (inputSmallLog N ^ 80) passes copies) (depth : PhysicalEntry M J target.length → ℕ) +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalCoarseSamplingWork_3) "ell" => inputSmallLog N +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalCoarseSamplingWork_4) "exponent" => (40 * smallLogExponent N : ℕ) +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalCoarseSamplingWork_5) "Key" => PhysicalFamilyScalarKey (M := M) (J := J) (R := R) + target N P ell exponent H (ell ^ 80) passes copies +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalCoarseSamplingWork_6) "Table" => ChargedPhysicalRequest M J target.length (passes + 1) copies T S +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalCoarseSamplingWork_7) "readGroup" => physicalFamilyGroupRead (M := M) (J := J) (R := R) + target N P ell exponent H (ell ^ 80) passes copies +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalCoarseSamplingWork_8) "readInteger" => physicalFamilyOnlineRead (M := M) (J := J) (R := R) + target N P ell exponent H (ell ^ 80) passes copies +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalCoarseSamplingWork_9) "answer" => physicalFamilyAnswer target N P ell exponent H (ell ^ 80) passes copies draw + +noncomputable def physicalFamilyCoarseSamplingWork (bits : ℕ) (encode : Sum Key Table → ℕ) + (root : Table) (coarse : OAI.EditApproximation.PhysicalCoarseDraw source target B depth) : ℝ := + let initial := OAI.EditApproximation.clampedSeedNat (OAI.EditApproximation.physicalCoarseSeedTable source target N B depth coarse) + let result := OAI.EditApproximation.chargedRandomMemoEvaluate source target N P ell exponent H (ell ^ 80) + T S (passes + 1) copies factor multiplier tau eta kappa delta readGroup readInteger initial + answer bits encode root + ∑ entry, OAI.EditApproximation.selectionIndicator (Sum.inr (Sum.inl entry) ∈ result.freshKeys) * + ((Nat.size B * OAI.EditApproximation.coarseInitialLabelCount B (depth entry) (OAI.EditApproximation.initialThresholdQ N) (OAI.EditApproximation.initialLambda N) + (OAI.EditApproximation.physicalSource source entry.1) (OAI.EditApproximation.substring target entry.2.lo entry.2.hi) (coarse entry) : ℕ) : ℝ) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open MeasureTheory Filter +variable {M J R B : ℕ} [NeZero M] [NeZero R] [NeZero B] (source target : List ℕ) (N : ℕ) (depth : PhysicalEntry M J target.length → ℕ) (encode : Sum (PhysicalFamilyScalarKey (M := M) (J := J) (R := R) + target N (integerParameters N).P (inputSmallLog N) (40 * smallLogExponent N) + (inputHeight N) (inputSmallLog N ^ 80) (computedSeedPassCount N) (inputHeight N ^ 2)) + (ChargedPhysicalRequest M J target.length (computedSeedPassCount N + 1) + (inputHeight N ^ 2) (integerParameters N).T (integerParameters N).S) → ℕ) + +noncomputable def symbolicComputedExecutionCoarseSamplingWork + (execution : OAI.EditApproximation.PhysicalCoarseExecution (R := R) source target N + (OAI.EditApproximation.integerParameters N).P (OAI.EditApproximation.inputHeight N) B depth) : ℝ := + OAI.EditApproximation.physicalFamilyCoarseSamplingWork source target N (OAI.EditApproximation.integerParameters N).P (OAI.EditApproximation.inputHeight N) + (OAI.EditApproximation.integerParameters N).T (OAI.EditApproximation.integerParameters N).S (OAI.EditApproximation.computedSeedPassCount N) + (OAI.EditApproximation.inputHeight N ^ 2) (OAI.EditApproximation.scheduledSeedFactor N) (OAI.EditApproximation.scheduledSeedMultiplier N) + (OAI.EditApproximation.rationalParameters (OAI.EditApproximation.inputSmallLog N)).tau (OAI.EditApproximation.rationalParameters (OAI.EditApproximation.inputSmallLog N)).eta + (OAI.EditApproximation.rationalParameters (OAI.EditApproximation.inputSmallLog N)).kappa (OAI.EditApproximation.rationalParameters (OAI.EditApproximation.inputSmallLog N)).delta + execution.2.2 depth (16384 * OAI.EditApproximation.inputHeight N + 5) encode + (OAI.EditApproximation.localFinalRootRequest target N (OAI.EditApproximation.integerParameters N).T (OAI.EditApproximation.integerParameters N).S + (OAI.EditApproximation.inputHeight N) (Nat.two_pow_pos _) (OAI.EditApproximation.finalTargetState target.length)) execution.1 + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open MeasureTheory Filter + +noncomputable def computedExecutionCoarseSamplingWork (source target : List ℕ) (N : ℕ) := + OAI.EditApproximation.symbolicComputedExecutionCoarseSamplingWork (M := (OAI.EditApproximation.integerParameters N).M) + (J := OAI.EditApproximation.intervalTreeDepth (OAI.EditApproximation.integerParameters N).M source.length) (R := OAI.EditApproximation.inputHeight N ^ 2) + (B := (OAI.EditApproximation.integerParameters N).B) source target N (OAI.EditApproximation.computedPhysicalCoarseDepth source target N) + (OAI.EditApproximation.computedFamilyMemoCode source target N (OAI.EditApproximation.inputHeight N ^ 2)) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {M J R : ℕ} [NeZero M] [NeZero R] (source target : List ℕ) (N P H T S passes copies : ℕ) (factor : ℕ → ℚ) (multiplier : ℕ → ℕ) (tau eta kappa delta : ℚ) (initial : PhysicalEntry M J target.length → ℕ) (draw : PhysicalFamilyScalarDraw (M := M) (J := J) (R := R) + target N P (inputSmallLog N) (40 * smallLogExponent N) H (inputSmallLog N ^ 80) passes copies) +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalCoarsePreparation_5) "ell" => inputSmallLog N +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalCoarsePreparation_6) "exponent" => (40 * smallLogExponent N : ℕ) +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalCoarsePreparation_7) "Key" => PhysicalFamilyScalarKey (M := M) (J := J) (R := R) + target N P ell exponent H (ell ^ 80) passes copies +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalCoarsePreparation_8) "Table" => ChargedPhysicalRequest M J target.length (passes + 1) copies T S +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalCoarsePreparation_9) "readGroup" => physicalFamilyGroupRead (M := M) (J := J) (R := R) + target N P ell exponent H (ell ^ 80) passes copies +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalCoarsePreparation_10) "readInteger" => physicalFamilyOnlineRead (M := M) (J := J) (R := R) + target N P ell exponent H (ell ^ 80) passes copies +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalCoarsePreparation_11) "answer" => physicalFamilyAnswer target N P ell exponent H (ell ^ 80) passes copies draw + +noncomputable def physicalFamilyCoarsePreparationWork (bits : ℕ) (encode : Sum Key Table → ℕ) + (root : Table) : ℝ := + let result := OAI.EditApproximation.chargedRandomMemoEvaluate source target N P ell exponent H (ell ^ 80) + T S (passes + 1) copies factor multiplier tau eta kappa delta readGroup readInteger initial + answer bits encode root + ∑ entry, OAI.EditApproximation.selectionIndicator (Sum.inr (Sum.inl entry) ∈ result.freshKeys) * + (OAI.EditApproximation.physicalCoarsePreparationCost source target entry : ℝ) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open Filter MeasureTheory + +noncomputable def computedFamilyCoarsePreparationWork (source target : List ℕ) (N : ℕ) + (input : OAI.EditApproximation.ComputedFamilyInput source target N) : ℝ := + OAI.EditApproximation.physicalFamilyCoarsePreparationWork source target N (OAI.EditApproximation.integerParameters N).P (OAI.EditApproximation.inputHeight N) + (OAI.EditApproximation.integerParameters N).T (OAI.EditApproximation.integerParameters N).S (OAI.EditApproximation.computedSeedPassCount N) (OAI.EditApproximation.inputHeight N ^ 2) + (OAI.EditApproximation.scheduledSeedFactor N) (OAI.EditApproximation.scheduledSeedMultiplier N) + (OAI.EditApproximation.rationalParameters (OAI.EditApproximation.inputSmallLog N)).tau (OAI.EditApproximation.rationalParameters (OAI.EditApproximation.inputSmallLog N)).eta + (OAI.EditApproximation.rationalParameters (OAI.EditApproximation.inputSmallLog N)).kappa (OAI.EditApproximation.rationalParameters (OAI.EditApproximation.inputSmallLog N)).delta + (OAI.EditApproximation.clampedSeedNat input.1) input.2 (16384 * OAI.EditApproximation.inputHeight N + 5) + (OAI.EditApproximation.computedFamilyMemoCode source target N (OAI.EditApproximation.inputHeight N ^ 2)) + (OAI.EditApproximation.computedFinalRoot source target N) + +noncomputable def computedExecutionCoarsePreparationWork (source target : List ℕ) (N : ℕ) + (execution : OAI.EditApproximation.ComputedExecutionOutcome source target N) : ℝ := + OAI.EditApproximation.computedFamilyCoarsePreparationWork source target N (OAI.EditApproximation.computedExecutionAccepted source target N execution) + +noncomputable def computedExecutionReadChargedWork (source target : List ℕ) (N : ℕ) + (execution : OAI.EditApproximation.ComputedExecutionOutcome source target N) : ℝ := + OAI.EditApproximation.computedExecutionIndexedCoarseWork source target N execution + + OAI.EditApproximation.computedExecutionCoarseSamplingWork source target N execution + + OAI.EditApproximation.computedExecutionNonlocalWork source target N execution + + OAI.EditApproximation.computedExecutionCoarsePreparationWork source target N execution + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open MeasureTheory Filter + +noncomputable def computedExecutionTotalWork (source target : List ℕ) (N : ℕ) + (cost : OAI.EditApproximation.ComputedFamilyInput source target N → OAI.EditApproximation.ComputedFamilyMemoKey source target N → ℕ) + (execution : OAI.EditApproximation.ComputedExecutionOutcome source target N) : ℝ := + OAI.EditApproximation.computedExecutionReadChargedWork source target N execution + + OAI.EditApproximation.computedExecutionKernelWork source target N cost execution + +noncomputable def computedFullOutputWork (source target : List ℕ) (N : ℕ) + (cost : OAI.EditApproximation.ComputedFamilyInput source target N → OAI.EditApproximation.ComputedFamilyMemoKey source target N → ℕ) + (setup : ℝ) (shared : ℕ) (output : OAI.EditApproximation.ComputedFamilyInput source target N → ℕ) + (fallbackOutput : ℕ) : OAI.EditApproximation.ComputedFullOutcome source target N → ℝ + | .inl _ => setup + (OAI.EditApproximation.chargedSuffixDP source target).2 + fallbackOutput + | .inr execution => setup + shared + OAI.EditApproximation.computedExecutionTotalWork source target N cost execution + + output (OAI.EditApproximation.computedExecutionAccepted source target N execution) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open BitQuery +variable {α : Type u_1} {M J R : ℕ} (target : List α) (N P F exponent H Q passes copies pass copy : ℕ) + +def queryFamilyTagAllocation + (scalar : OAI.EditApproximation.PhysicalScalarKey M J N target.length exponent F Q R (OAI.EditApproximation.localOnlineMassBound M P H)) : ℕ := + OAI.EditApproximation.binaryNaturalDivAllocation pass (passes + 1) + OAI.EditApproximation.binaryNaturalDivAllocation copy (copies + 1) + + OAI.EditApproximation.physicalScalarCodeAllocation scalar + 9 + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BitQuery.Footprint + + +def rankedBitMemoCells {κ : Type u_1} (rank : κ → ℕ) + (program : (key : κ) → OAI.EditApproximation.BitQuery {child : κ // rank child < rank key} OAI.EditApproximation.BinaryFraction) + (heap : ∀ key, OAI.EditApproximation.BitQuery.Footprint (program key)) + (bits : ℕ) (encode addressCells : κ → ℕ) (key : κ) (memory : OAI.EditApproximation.BinaryMemo OAI.EditApproximation.BinaryFraction) : ℕ := + let found := memory.lookupCosted (OAI.EditApproximation.binaryMemoKey bits (encode key)) + match found.1 with + | some _ => OAI.EditApproximation.memoRequestCells bits (addressCells key) + | none => OAI.EditApproximation.memoRequestCells bits (addressCells key) + (heap key).runCells + (fun child previous => OAI.EditApproximation.rankedBitMemoEvaluate rank program bits encode child.val previous) + (fun child previous => rankedBitMemoCells rank program heap bits encode addressCells child.val previous) + memory +termination_by rank key +decreasing_by exact child.property + + +end OAI.EditApproximation.BitQuery.Footprint +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open BitQuery + +local instance queryArityNeZero (N : ℕ) : NeZero (OAI.EditApproximation.integerParameters N).M := + ⟨by change 2 ^ (OAI.EditApproximation.heightExponent N / 20) ≠ 0; exact Nat.ne_of_gt (Nat.two_pow_pos _)⟩ + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open BitQuery +attribute [local instance] queryArityNeZero queryRoundsNeZero + +def queryInitialGatherFootprint + {ι : Type u_1} + {β : Type u_2} + {n : ℕ} + (N P F exponent : ℕ) + (hP : 0 < P) + (a : OAI.EditApproximation.BinaryFraction) + (q : OAI.EditApproximation.TargetInterval n) + (reader : OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (hr : (key : OAI.EditApproximation.TargetInterval n) → (reader key).Footprint) + (next : List (OAI.EditApproximation.TargetInterval n) → + List OAI.EditApproximation.BinaryFraction → OAI.EditApproximation.BitQuery ι β) + (hn : (keys : List (OAI.EditApproximation.TargetInterval n)) → + (words : List OAI.EditApproximation.BinaryFraction) → (next keys words).Footprint) : (OAI.EditApproximation.queryInitialGather N P F exponent hP a q reader next).Footprint := +(hr q).bind + (fun (value : OAI.EditApproximation.BinaryFraction) => + (OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.queryInitialSupportWithWork N P F exponent hP a value q)).bind + fun (keys : List (OAI.EditApproximation.TargetInterval n)) => + OAI.EditApproximation.BitQuery.collect reader keys (next keys)) + fun (value : OAI.EditApproximation.BinaryFraction) => + (OAI.EditApproximation.BitQuery.Footprint.computeOf + (OAI.EditApproximation.BinaryFraction.queryInitialSupportWithWork N P F exponent hP a value q) + (OAI.EditApproximation.BinaryFraction.queryInitialSupportAllocation N P F exponent hP a value q)).bind + (fun (keys : List (OAI.EditApproximation.TargetInterval n)) => + OAI.EditApproximation.BitQuery.collect reader keys (next keys)) + fun (keys : List (OAI.EditApproximation.TargetInterval n)) => + OAI.EditApproximation.BitQuery.Footprint.collect reader hr keys (next keys) (hn keys) + +def queryBandGatherFootprint + {ι : Type u_1} + {β : Type u_2} + {nx ny : ℕ} + (M : ℕ) + (parent : OAI.EditApproximation.TargetInterval nx) + (N P F exponent : ℕ) + (hP : 0 < P) + (a : OAI.EditApproximation.BinaryFraction) + (initial : OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) + (allocation : OAI.EditApproximation.TargetInterval ny → ℕ) + (q : OAI.EditApproximation.TargetInterval ny) + (massReader initialReader : Fin M × OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (hm : (key : Fin M × OAI.EditApproximation.TargetInterval ny) → (massReader key).Footprint) + (hi : (key : Fin M × OAI.EditApproximation.TargetInterval ny) → (initialReader key).Footprint) + (next : List (Fin M × OAI.EditApproximation.TargetInterval ny) → + List OAI.EditApproximation.BinaryFraction → + List OAI.EditApproximation.BinaryFraction → OAI.EditApproximation.BitQuery ι β) + (hn : (keys : List (Fin M × OAI.EditApproximation.TargetInterval ny)) → + (mass words : List OAI.EditApproximation.BinaryFraction) → (next keys mass words).Footprint) : (OAI.EditApproximation.queryBandGather M parent N P F exponent hP a initial q massReader initialReader next).Footprint := +(OAI.EditApproximation.BitQuery.Footprint.computeOf + (OAI.EditApproximation.BinaryFraction.queryBandInputsWithWork M parent N P F exponent hP a initial q) + (OAI.EditApproximation.BinaryFraction.queryBandInputsAllocation M parent N P F exponent hP a initial allocation + q)).bind + (fun (keys : List (Fin M × OAI.EditApproximation.TargetInterval ny)) => + OAI.EditApproximation.BitQuery.collect massReader keys fun (mass : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.BitQuery.collect initialReader keys (next keys mass)) + fun (keys : List (Fin M × OAI.EditApproximation.TargetInterval ny)) => + OAI.EditApproximation.BitQuery.Footprint.collect massReader hm keys + (fun (mass : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.BitQuery.collect initialReader keys (next keys mass)) + fun (mass : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.BitQuery.Footprint.collect initialReader hi keys (next keys mass) (hn keys mass) + +def queryGroupSourceGatherFootprint + {ι : Type u_1} + {β : Type u_2} + {n : ℕ} + (M N F Q exponent eM eF : ℕ) + (hM : M = 2 ^ eM) + (hF : F = 2 ^ eF) + (a : OAI.EditApproximation.BinaryFraction) + (initial : OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) + (allocation : OAI.EditApproximation.TargetInterval n → ℕ) + (q : OAI.EditApproximation.TargetInterval n) + (reader : OAI.EditApproximation.GroupScalarKey M F Q → OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (hr : (key : OAI.EditApproximation.GroupScalarKey M F Q) → (reader key).Footprint) + (next : List (OAI.EditApproximation.GroupScalarKey M F Q) → + List OAI.EditApproximation.BinaryFraction → OAI.EditApproximation.BitQuery ι β) + (hn : (keys : List (OAI.EditApproximation.GroupScalarKey M F Q)) → + (words : List OAI.EditApproximation.BinaryFraction) → (next keys words).Footprint) : (OAI.EditApproximation.queryGroupSourceGather M N F Q exponent eM eF hM hF a initial q reader next).Footprint := +OAI.EditApproximation.BitQuery.Footprint.chargeOf (allocation q) + ((OAI.EditApproximation.BitQuery.Footprint.computeOf + (OAI.EditApproximation.BinaryFraction.queryGroupSourceKeysWithWork M N F Q exponent eM eF hM hF a (initial q).1 + q) + (OAI.EditApproximation.BinaryFraction.queryGroupSourceKeysAllocation M N F Q exponent eM eF hM hF a + (initial q).1 q)).bind + (fun (keys : List (OAI.EditApproximation.GroupScalarKey M F Q)) => + OAI.EditApproximation.BitQuery.collect reader keys (next keys)) + fun (keys : List (OAI.EditApproximation.GroupScalarKey M F Q)) => + OAI.EditApproximation.BitQuery.Footprint.collect reader hr keys (next keys) (hn keys)) + +def queryOnlineSourceGatherFootprint + {ι : Type u_1} + {β : Type u_2} + {nx ny M : ℕ} + (parent : OAI.EditApproximation.TargetInterval nx) + (N P F exponent H : ℕ) + (hP : 0 < P) + (tau a : OAI.EditApproximation.BinaryFraction) + (initial : OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) + (initialAllocation : OAI.EditApproximation.TargetInterval ny → ℕ) + (child : Fin M → OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) + (childAllocation : Fin M → OAI.EditApproximation.TargetInterval ny → ℕ) + (q : OAI.EditApproximation.TargetInterval ny) + (reader : ℕ × OAI.EditApproximation.TargetInterval ny → ℕ → OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (hr : (key : ℕ × OAI.EditApproximation.TargetInterval ny) → (range : ℕ) → (reader key range).Footprint) + (next : List (ℕ × OAI.EditApproximation.TargetInterval ny) → + List OAI.EditApproximation.BinaryFraction → OAI.EditApproximation.BitQuery ι β) + (hn : (keys : List (ℕ × OAI.EditApproximation.TargetInterval ny)) → + (words : List OAI.EditApproximation.BinaryFraction) → (next keys words).Footprint) : (OAI.EditApproximation.queryOnlineSourceGather parent N P F exponent H hP tau a initial child q reader next).Footprint := +OAI.EditApproximation.BitQuery.Footprint.chargeOf (initialAllocation q) + ((OAI.EditApproximation.BitQuery.Footprint.computeOf + (OAI.EditApproximation.BinaryFraction.queryOnlineKeysWithWork N P F hP a (initial q).1 q) + (OAI.EditApproximation.BinaryFraction.queryOnlineKeysAllocation N P F hP a (initial q).1 q)).bind + (fun (keys : List (ℕ × OAI.EditApproximation.TargetInterval ny)) => + OAI.EditApproximation.BitQuery.collect + (fun (key : ℕ × OAI.EditApproximation.TargetInterval ny) => + (OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.queryOnlineRangeWithWork parent P exponent H tau child key)).bind + (reader key)) + keys (next keys)) + fun (keys : List (ℕ × OAI.EditApproximation.TargetInterval ny)) => + OAI.EditApproximation.BitQuery.Footprint.collect + (fun (key : ℕ × OAI.EditApproximation.TargetInterval ny) => + (OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.queryOnlineRangeWithWork parent P exponent H tau child key)).bind + (reader key)) + (fun (key : ℕ × OAI.EditApproximation.TargetInterval ny) => + (OAI.EditApproximation.BitQuery.Footprint.computeOf + (OAI.EditApproximation.BinaryFraction.queryOnlineRangeWithWork parent P exponent H tau child key) + (OAI.EditApproximation.BinaryFraction.queryOnlineRangeAllocation parent P exponent H tau child + childAllocation key)).bind + (reader key) (hr key)) + keys (next keys) (hn keys)) + +def queryPhysicalTableReadFootprint + {M J n : ℕ} + (copies T S : ℕ) + (parent : OAI.EditApproximation.PhysicalTableRequest M J n) + (child : { r : OAI.EditApproximation.PhysicalTableRequest M J n // + OAI.EditApproximation.PhysicalTableRequest.combinedRank T S r < + OAI.EditApproximation.PhysicalTableRequest.combinedRank T S parent }) : (OAI.EditApproximation.queryPhysicalTableRead copies T S parent child).Footprint := +OAI.EditApproximation.BitQuery.Footprint.chargeOf (OAI.EditApproximation.physicalTableCodeAllocation (M := M) (J := J) (n := n) child.val + 1) + (OAI.EditApproximation.BitQuery.Footprint.read child OAI.EditApproximation.BitQuery.done + fun (word : OAI.EditApproximation.BinaryFraction) => OAI.EditApproximation.BitQuery.Footprint.done word) + +def queryMeanReadFootprint + {ι : Type u_1} + (count : ℕ) + (reader : Fin count → OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (hr : (i : Fin count) → (reader i).Footprint) : (OAI.EditApproximation.queryMeanRead count reader).Footprint := +OAI.EditApproximation.BitQuery.Footprint.chargeOf count + (OAI.EditApproximation.BitQuery.Footprint.collect reader hr (List.ofFn fun (i : Fin count) => i) + (fun (words : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.BitQuery.compute (OAI.EditApproximation.BinaryFraction.queryMeanWithWork count words)) + fun (words : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.BitQuery.Footprint.computeOf + (OAI.EditApproximation.BinaryFraction.queryMeanWithWork count words) + (OAI.EditApproximation.BinaryFraction.sumListAllocation words + + (OAI.EditApproximation.BinaryFraction.sumListWithWork words).1.divAllocation + (OAI.EditApproximation.BinaryFraction.nat count) + + count.size)) + +def queryPhysicalScalarReadFootprint + (M J N n exponent F Q R B : ℕ) + (key : OAI.EditApproximation.PhysicalScalarKey M J N n exponent F Q R B) : (OAI.EditApproximation.queryPhysicalScalarRead M J N n exponent F Q R B key).Footprint := +OAI.EditApproximation.BitQuery.Footprint.chargeOf (OAI.EditApproximation.physicalScalarCodeAllocation key + 1) + (OAI.EditApproximation.BitQuery.Footprint.read key OAI.EditApproximation.BitQuery.done + fun (word : OAI.EditApproximation.BinaryFraction) => OAI.EditApproximation.BitQuery.Footprint.done word) + +def queryRestrictPhysicalBodyFootprint + {σ : Type u_1} + {M J n : ℕ} + (passes copies T S : ℕ) + (parent : { r : OAI.EditApproximation.PhysicalTableRequest M J n // + OAI.EditApproximation.PhysicalTableRequest.Bounded passes copies T S r }) + (program : OAI.EditApproximation.BitQuery (OAI.EditApproximation.QueryPhysicalChild (σ := σ) passes copies T S parent) + OAI.EditApproximation.BinaryFraction) + (heap : program.Footprint) : (OAI.EditApproximation.queryRestrictPhysicalBody passes copies T S parent program).Footprint := by + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_binaryNaturalCompareWithWork_lt_53 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.binaryNaturalCompareWithWork a b).1 = .lt ↔ a < b := by + simpa only [OAI.EditApproximation.binaryNaturalCompareWithWork, proof_bitWordValue_bits_15] using proof_bitCompareWithWork_lt_16 a.bits b.bits + have proof_wordLEWithWork_value_26 (a : List.{0} Bool) (b : List.{0} Bool) : + (OAI.EditApproximation.wordLEWithWork a b).1 = true ↔ OAI.EditApproximation.bitWordValue a ≤ OAI.EditApproximation.bitWordValue b := by + simp only [OAI.EditApproximation.wordLEWithWork, Bool.not_eq_true', decide_eq_false_iff_not, + proof_bitCompareWithWork_lt_16, not_lt] + have proof_bitAdder_value_1 (a : Bool) (b : Bool) (carry : Bool) : + (OAI.EditApproximation.bitSum a b carry).toNat + 2 * (OAI.EditApproximation.bitCarry a b carry).toNat = + a.toNat + b.toNat + carry.toNat := by + cases a <;> cases b <;> cases carry <;> decide + have proof_bitAddWithWork_value_2 (left : List.{0} Bool) (right : List.{0} Bool) (carry : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitAddWithWork left right carry).1 = + OAI.EditApproximation.bitWordValue left + OAI.EditApproximation.bitWordValue right + carry.toNat := by + induction left generalizing right carry with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork] + induction right generalizing carry with + | nil => cases carry <;> simp [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue] + | cons b bs ih => + simp only [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 false b carry + simp only [Bool.toNat_false] at h + omega + | cons a as ih => + cases right with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a false carry + simp only [Bool.toNat_false] at h + omega + | cons b bs => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a b carry + omega + have proof_binaryNaturalAddWithWork_value_52 (a : ℕ) (b : ℕ) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalAddWithWork a b).1 = a + b := by + simp [OAI.EditApproximation.binaryNaturalAddWithWork, proof_bitAddWithWork_value_2, proof_bitWordValue_bits_15] + have proof_queryPhysicalBoundedWithWork_value_109 {M : ℕ} {J : ℕ} {n : ℕ} (passes : ℕ) (copies : ℕ) (T : ℕ) (S : ℕ) (request : OAI.EditApproximation.PhysicalTableRequest M J n) : + (OAI.EditApproximation.queryPhysicalBoundedWithWork passes copies T S request).1 = true ↔ + request.Bounded passes copies T S := by + simp only [OAI.EditApproximation.queryPhysicalBoundedWithWork, Bool.and_eq_true, decide_eq_true_eq, + proof_binaryNaturalCompareWithWork_lt_53, proof_wordLEWithWork_value_26, proof_bitWordValue_bits_15, + proof_binaryNaturalAddWithWork_value_52, OAI.EditApproximation.PhysicalTableRequest.Bounded] + tauto + have proof_querySupportedChildWithWork_value_108 {σ : Type u_1} {M : ℕ} {J : ℕ} {n : ℕ} (passes : ℕ) (copies : ℕ) (T : ℕ) (S : ℕ) (parent : Subtype.{1} fun r => OAI.EditApproximation.PhysicalTableRequest.Bounded (M := M) (J := J) (ny := n) passes copies T S r) (key : OAI.EditApproximation.QueryPhysicalChild.{u_1} (σ := σ) passes copies T S parent) : + (OAI.EditApproximation.querySupportedChildWithWork passes copies T S parent key).1 = true ↔ + OAI.EditApproximation.SourceRanked.supportedChild (OAI.EditApproximation.PhysicalTableRequest.combinedRank T S) + (OAI.EditApproximation.PhysicalTableRequest.Bounded passes copies T S) parent.val key := by + cases key with + | inl source => exact iff_of_true rfl trivial + | inr child => exact proof_queryPhysicalBoundedWithWork_value_109 passes copies T S child.val + exact + (heap.restrictWithWork _ _ (proof_querySupportedChildWithWork_value_108 passes copies T S parent) + (OAI.EditApproximation.querySupportedChildAllocation passes copies T S parent) + ).mapKeysWithWork _ (fun _ => 1) + +def queryInitialConeProgramAtFootprint + {ι : Type u_1} + {n : ℕ} + (sourceLength N P F : ℕ) + (A a : OAI.EditApproximation.BinaryFraction) + (reader : OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (q : OAI.EditApproximation.TargetInterval n) + (hr : (r : OAI.EditApproximation.TargetInterval n) → (reader r).Footprint) : (OAI.EditApproximation.queryInitialConeProgramAt sourceLength N P F A a reader q).Footprint := +(hr q).bind + (fun (value : OAI.EditApproximation.BinaryFraction) => + (OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.queryInitialConeCentersWithWork N P A value q)).bind + fun (keys : List (OAI.EditApproximation.TargetInterval n)) => + OAI.EditApproximation.BitQuery.collect reader keys fun (words : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.cachedInitialProgramReadWithWork sourceLength N P F A a + (value.queryInitialSeedReadWithWork q keys words) q)) + fun (value : OAI.EditApproximation.BinaryFraction) => + (OAI.EditApproximation.BitQuery.Footprint.computeOf + (OAI.EditApproximation.BinaryFraction.queryInitialConeCentersWithWork N P A value q) + (OAI.EditApproximation.BinaryFraction.queryInitialConeCentersAllocation N P A value q)).bind + (fun (keys : List (OAI.EditApproximation.TargetInterval n)) => + OAI.EditApproximation.BitQuery.collect reader keys fun (words : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.cachedInitialProgramReadWithWork sourceLength N P F A a + (value.queryInitialSeedReadWithWork q keys words) q)) + fun (keys : List (OAI.EditApproximation.TargetInterval n)) => + OAI.EditApproximation.BitQuery.Footprint.collect reader hr keys + (fun (words : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.cachedInitialProgramReadWithWork sourceLength N P F A a + (value.queryInitialSeedReadWithWork q keys words) q)) + fun (words : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.BitQuery.Footprint.computeOf + (OAI.EditApproximation.BinaryFraction.cachedInitialProgramReadWithWork sourceLength N P F A a + (value.queryInitialSeedReadWithWork q keys words) q) + (OAI.EditApproximation.BinaryFraction.cachedInitialProgramReadAllocation + (value.queryInitialSeedReadWithWork q keys words) (value.queryInitialSeedReadAllocation q keys words) + sourceLength N P F A a q) + +def queryChargedReadFootprint + {M J n passes copies T S : ℕ} + (parent : { r : OAI.EditApproximation.PhysicalTableRequest M J n // + OAI.EditApproximation.PhysicalTableRequest.Bounded passes copies T S r }) + (key : { child : OAI.EditApproximation.ChargedPhysicalRequest M J n passes copies T S // + child.rank < OAI.EditApproximation.ChargedPhysicalRequest.rank (Sum.inr parent) }) : (OAI.EditApproximation.queryChargedRead parent key).Footprint := +OAI.EditApproximation.BitQuery.Footprint.chargeOf (OAI.EditApproximation.chargedPhysicalCodeAllocation (M := M) (J := J) (n := n) (passes := passes) (copies := copies) (T := T) (S := S) key.val + 1) + (OAI.EditApproximation.BitQuery.Footprint.read key OAI.EditApproximation.BitQuery.done + fun (word : OAI.EditApproximation.BinaryFraction) => OAI.EditApproximation.BitQuery.Footprint.done word) + +def queryWarmupProgramFootprint + {ι : Type u_1} + {nx ny M : ℕ} + (parent : OAI.EditApproximation.TargetInterval nx) + (N P F : ℕ) + (a : OAI.EditApproximation.BinaryFraction) + (initialRead : OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (childRead : Fin M × OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (q : OAI.EditApproximation.TargetInterval ny) + (hi : (r : OAI.EditApproximation.TargetInterval ny) → (initialRead r).Footprint) + (hc : (key : Fin M × OAI.EditApproximation.TargetInterval ny) → (childRead key).Footprint) : (OAI.EditApproximation.queryWarmupProgram parent N P F a initialRead childRead q).Footprint := +(hi q).bind + (fun (value : OAI.EditApproximation.BinaryFraction) => + (OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.queryRawCentersWithWork N P F a value q)).bind + fun (centers : List (OAI.EditApproximation.TargetInterval ny)) => + OAI.EditApproximation.BitQuery.collect initialRead centers + fun (words : List OAI.EditApproximation.BinaryFraction) => + have initial : OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ := + value.queryOverrideParentReadWithWork q centers words; + (OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.queryWarmupInputsWithWork M parent N P F a initial q)).bind + fun (inputs : List (Fin M × OAI.EditApproximation.TargetInterval ny)) => + OAI.EditApproximation.BitQuery.collect childRead inputs + fun (childWords : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.localWarmupReadKernelWithWork parent N P F a initial + (fun (input : Fin M × OAI.EditApproximation.TargetInterval ny) => + OAI.EditApproximation.BinaryFraction.queryChildReadWithWork inputs childWords input.1 input.2) + q)) + fun (value : OAI.EditApproximation.BinaryFraction) => + (OAI.EditApproximation.BitQuery.Footprint.computeOf + (OAI.EditApproximation.BinaryFraction.queryRawCentersWithWork N P F a value q) + (OAI.EditApproximation.BinaryFraction.queryRawCentersAllocation N P F a value q)).bind + (fun (centers : List (OAI.EditApproximation.TargetInterval ny)) => + OAI.EditApproximation.BitQuery.collect initialRead centers + fun (words : List OAI.EditApproximation.BinaryFraction) => + have initial : OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ := + value.queryOverrideParentReadWithWork q centers words; + (OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.queryWarmupInputsWithWork M parent N P F a initial q)).bind + fun (inputs : List (Fin M × OAI.EditApproximation.TargetInterval ny)) => + OAI.EditApproximation.BitQuery.collect childRead inputs + fun (childWords : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.localWarmupReadKernelWithWork parent N P F a initial + (fun (input : Fin M × OAI.EditApproximation.TargetInterval ny) => + OAI.EditApproximation.BinaryFraction.queryChildReadWithWork inputs childWords input.1 input.2) + q)) + fun (centers : List (OAI.EditApproximation.TargetInterval ny)) => + OAI.EditApproximation.BitQuery.Footprint.collect initialRead hi centers + (fun (words : List OAI.EditApproximation.BinaryFraction) => + have initial : OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ := + value.queryOverrideParentReadWithWork q centers words; + (OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.queryWarmupInputsWithWork M parent N P F a initial q)).bind + fun (inputs : List (Fin M × OAI.EditApproximation.TargetInterval ny)) => + OAI.EditApproximation.BitQuery.collect childRead inputs + fun (childWords : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.localWarmupReadKernelWithWork parent N P F a initial + (fun (input : Fin M × OAI.EditApproximation.TargetInterval ny) => + OAI.EditApproximation.BinaryFraction.queryChildReadWithWork inputs childWords input.1 input.2) + q)) + fun (words : List OAI.EditApproximation.BinaryFraction) => + let initial : OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ := + value.queryOverrideParentReadWithWork q centers words; + let allocation : OAI.EditApproximation.TargetInterval ny → ℕ := + OAI.EditApproximation.BinaryFraction.queryOverrideParentReadAllocation q centers words; + (OAI.EditApproximation.BitQuery.Footprint.computeOf + (OAI.EditApproximation.BinaryFraction.queryWarmupInputsWithWork M parent N P F a initial q) + (OAI.EditApproximation.BinaryFraction.queryWarmupInputsAllocation M parent N P F a initial allocation + q)).bind + (fun (inputs : List (Fin M × OAI.EditApproximation.TargetInterval ny)) => + OAI.EditApproximation.BitQuery.collect childRead inputs + fun (childWords : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.localWarmupReadKernelWithWork parent N P F a + (value.queryOverrideParentReadWithWork q centers words) + (fun (input : Fin M × OAI.EditApproximation.TargetInterval ny) => + OAI.EditApproximation.BinaryFraction.queryChildReadWithWork inputs childWords input.1 input.2) + q)) + fun (inputs : List (Fin M × OAI.EditApproximation.TargetInterval ny)) => + OAI.EditApproximation.BitQuery.Footprint.collect childRead hc inputs + (fun (childWords : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.localWarmupReadKernelWithWork parent N P F a + (value.queryOverrideParentReadWithWork q centers words) + (fun (input : Fin M × OAI.EditApproximation.TargetInterval ny) => + OAI.EditApproximation.BinaryFraction.queryChildReadWithWork inputs childWords input.1 input.2) + q)) + fun (childWords : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.BitQuery.Footprint.computeOf + (OAI.EditApproximation.BinaryFraction.localWarmupReadKernelWithWork parent N P F a initial + (fun (input : Fin M × OAI.EditApproximation.TargetInterval ny) => + OAI.EditApproximation.BinaryFraction.queryChildReadWithWork inputs childWords input.1 input.2) + q) + (OAI.EditApproximation.BinaryFraction.localWarmupReadAllocation parent N P F a initial allocation + (fun (input : Fin M × OAI.EditApproximation.TargetInterval ny) => + OAI.EditApproximation.BinaryFraction.queryChildReadWithWork inputs childWords input.1 input.2) + (fun (input : Fin M × OAI.EditApproximation.TargetInterval ny) => + OAI.EditApproximation.BinaryFraction.queryChildReadAllocation inputs childWords input.1 input.2) + q) + +def queryPhysicalEarlierReadFootprint + {M J n : ℕ} + (copies pass copy T S t : ℕ) + (node : OAI.EditApproximation.PhysicalNode M J) + (hbelow : ↑node.fst < J) + (q : OAI.EditApproximation.TargetInterval n) + (input : Fin M × ℕ × OAI.EditApproximation.TargetInterval n) : (OAI.EditApproximation.queryPhysicalEarlierRead copies pass copy T S t node hbelow q input).Footprint := by + have proof_combinedRank_lt_of_progress_80 {M : ℕ} {J : ℕ} {ny : ℕ} (T : ℕ) (S : ℕ) (first : OAI.EditApproximation.PhysicalTableRequest M J ny) (second : OAI.EditApproximation.PhysicalTableRequest M J ny) (hprogress : LT.lt.{0} second.remainingDepth first.remainingDepth ∧ + LE.le.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first) ∨ + LE.le.{0} second.remainingDepth first.remainingDepth ∧ + LT.lt.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first)) : + OAI.EditApproximation.PhysicalTableRequest.combinedRank T S second < OAI.EditApproximation.PhysicalTableRequest.combinedRank T S first := by + unfold OAI.EditApproximation.PhysicalTableRequest.combinedRank + rcases hprogress with h | h + · exact Nat.add_lt_add_of_lt_of_le h.1 h.2 + · exact Nat.add_lt_add_of_le_of_lt h.1 h.2 + have proof_refinement_history_child_progress_96 {M : ℕ} {J : ℕ} {ny : ℕ} (pass : ℕ) (copy : ℕ) (T : ℕ) (S : ℕ) (t : ℕ) (s : ℕ) (node : OAI.EditApproximation.PhysicalNode M J) (hbelow : LT.lt.{0} (↑(Sigma.fst.{0, 0} node)) J) (i : Fin M) (state : OAI.EditApproximation.TargetInterval ny) (previousState : OAI.EditApproximation.TargetInterval ny) (hs : LT.lt.{0} s t) : + (OAI.EditApproximation.PhysicalTableRequest.refinement pass copy (OAI.EditApproximation.physicalChild node hbelow i) T s previousState).remainingDepth < + (OAI.EditApproximation.PhysicalTableRequest.refinement pass copy node T t state).remainingDepth ∧ + OAI.EditApproximation.PhysicalTableRequest.rank T S (OAI.EditApproximation.PhysicalTableRequest.refinement pass copy (OAI.EditApproximation.physicalChild node hbelow i) T s previousState) < + OAI.EditApproximation.PhysicalTableRequest.rank T S (OAI.EditApproximation.PhysicalTableRequest.refinement pass copy node T t state) := by + constructor + · unfold OAI.EditApproximation.PhysicalTableRequest.remainingDepth OAI.EditApproximation.PhysicalTableRequest.refinement OAI.EditApproximation.physicalChild + dsimp only + omega + · dsimp only [OAI.EditApproximation.PhysicalTableRequest.rank, OAI.EditApproximation.PhysicalTableRequest.refinement] + omega + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_binaryNaturalCompareWithWork_lt_53 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.binaryNaturalCompareWithWork a b).1 = .lt ↔ a < b := by + simpa only [OAI.EditApproximation.binaryNaturalCompareWithWork, proof_bitWordValue_bits_15] using proof_bitCompareWithWork_lt_16 a.bits b.bits + refine OAI.EditApproximation.BitQuery.Footprint.chargeOf (input.2.1.bits.length + t.bits.length) ?_ + split + · exact OAI.EditApproximation.queryPhysicalTableReadFootprint copies T S _ _ + · exact .done _ + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open BitQuery +attribute [local instance] queryArityNeZero queryRoundsNeZero +open Finset + +def queryPhysicalScalarOnlineReadFootprint + (M J N n exponent F Q R B : ℕ) + (node : OAI.EditApproximation.PhysicalInternalNode M J) + (time : Fin R) + (key : ℕ × OAI.EditApproximation.TargetInterval n) + (range : ℕ) : (OAI.EditApproximation.queryPhysicalScalarOnlineRead M J N n exponent F Q R B node time key range).Footprint := by + have proof_log_two_add_one_eq_size_103 (N : ℕ) (hN : LT.lt.{0} 0 N) : + Nat.log 2 N + 1 = Nat.size N := by + apply Nat.le_antisymm + · have h := Nat.pow_log_le_self 2 hN.ne' + have hlt : Nat.log 2 N < Nat.size N := Nat.lt_size.mpr h + omega + · exact Nat.size_le.mpr (Nat.lt_pow_succ_log_self (by decide : 1 < 2) N) + have proof_powerTwoWord_value_13 (n : ℕ) : OAI.EditApproximation.bitWordValue (OAI.EditApproximation.powerTwoWord n) = 2 ^ n := by + induction n with + | zero => (simp [OAI.EditApproximation.powerTwoWord, OAI.EditApproximation.bitWordValue]) + | succ n ih => + (simp only [OAI.EditApproximation.powerTwoWord, List.replicate_succ, List.cons_append, OAI.EditApproximation.bitWordValue, + Bool.toNat_false, zero_add] at *) + rw [ih, pow_succ] + omega + have proof_arithmeticMapWithWork_value_70 {α : Type 0} {β : Type 0} (f : α → Prod.{0, 0} β ℕ) (values : List.{0} α) : + (OAI.EditApproximation.arithmeticMapWithWork f values).1 = values.map (fun a => (f a).1) := by + induction values with + | nil => rfl + | cons a rest ih => simp only [OAI.EditApproximation.arithmeticMapWithWork, ih, List.map_cons] + have proof_dyadicScalesWithWork_value_104 (N : ℕ) : + (OAI.EditApproximation.dyadicScalesWithWork N).1 = OAI.EditApproximation.dyadicScales N := by + have hcount : max 1 N.bits.length = Nat.log 2 N + 1 := by + by_cases hz : N = 0 + · subst N + decide + · have h := proof_log_two_add_one_eq_size_103 N (Nat.pos_of_ne_zero hz) + have hp := Nat.size_pos.mpr (Nat.pos_of_ne_zero hz) + rw [Nat.size_eq_bits_len, max_eq_right hp, h] + simp only [OAI.EditApproximation.dyadicScalesWithWork, proof_arithmeticMapWithWork_value_70, proof_powerTwoWord_value_13, hcount, + OAI.EditApproximation.dyadicScales] + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_eq_3 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .eq ↔ OAI.EditApproximation.bitWordValue left = OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_binaryNaturalCompareWithWork_eq_73 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.binaryNaturalCompareWithWork a b).1 = .eq ↔ a = b := by + simpa only [OAI.EditApproximation.binaryNaturalCompareWithWork, proof_bitWordValue_bits_15] using proof_bitCompareWithWork_eq_3 a.bits b.bits + have proof_naturalEqualWithWork_value_74 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.naturalEqualWithWork a b).1 = true ↔ a = b := by + simp only [OAI.EditApproximation.naturalEqualWithWork, decide_eq_true_eq, proof_binaryNaturalCompareWithWork_eq_73] + have proof_queryNaturalIndexWithWork_value_105 (a : ℕ) (xs : List.{0} ℕ) : + (OAI.EditApproximation.queryNaturalIndexWithWork a xs).1 = xs.idxOf a := by + induction xs with + | nil => rfl + | cons b xs ih => + simp only [OAI.EditApproximation.queryNaturalIndexWithWork] + by_cases hab : a = b + · subst b + rw [ite_eq_left ((proof_naturalEqualWithWork_value_74 a a).mpr rfl)] + simp + · rw [ite_eq_right (fun h => hab ((proof_naturalEqualWithWork_value_74 a b).mp h))] + simp only [ih, List.idxOf_cons, beq_iff_eq] + rw [ite_eq_right (Ne.symm hab)] + have proof_queryScaleDispatchWithWork_value_106 (N : ℕ) (b : ℕ) : + (OAI.EditApproximation.queryScaleDispatchWithWork N b).1 = (OAI.EditApproximation.dyadicScales N).idxOf b := by + simp only [OAI.EditApproximation.queryScaleDispatchWithWork, proof_queryNaturalIndexWithWork_value_105, proof_dyadicScalesWithWork_value_104] + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_binaryNaturalCompareWithWork_lt_53 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.binaryNaturalCompareWithWork a b).1 = .lt ↔ a < b := by + simpa only [OAI.EditApproximation.binaryNaturalCompareWithWork, proof_bitWordValue_bits_15] using proof_bitCompareWithWork_lt_16 a.bits b.bits + have proof_queryScalePresentWithWork_value_101 (N : ℕ) (b : ℕ) : + (OAI.EditApproximation.queryScalePresentWithWork N b).1 = true ↔ b ∈ OAI.EditApproximation.dyadicScales N := by + simp only [OAI.EditApproximation.queryScalePresentWithWork, decide_eq_true_eq, proof_binaryNaturalCompareWithWork_lt_53, + proof_queryScaleDispatchWithWork_value_106] + have hl : (OAI.EditApproximation.dyadicScales N).length = max 1 N.bits.length := by + rw [← proof_dyadicScalesWithWork_value_104 N] + (simp only [OAI.EditApproximation.dyadicScalesWithWork, proof_arithmeticMapWithWork_value_70, List.length_map, List.length_range]) + rw [← hl] + exact List.idxOf_lt_length_iff + have proof_wordLEWithWork_value_26 (a : List.{0} Bool) (b : List.{0} Bool) : + (OAI.EditApproximation.wordLEWithWork a b).1 = true ↔ OAI.EditApproximation.bitWordValue a ≤ OAI.EditApproximation.bitWordValue b := by + simp only [OAI.EditApproximation.wordLEWithWork, Bool.not_eq_true', decide_eq_false_iff_not, + proof_bitCompareWithWork_lt_16, not_lt] + have proof_queryRangeValidWithWork_value_107 (B : ℕ) (range : ℕ) : + (OAI.EditApproximation.queryRangeValidWithWork B range).1 = true ↔ 0 < range ∧ range ≤ B := by + simp only [OAI.EditApproximation.queryRangeValidWithWork, Bool.and_eq_true, decide_eq_true_eq, + proof_binaryNaturalCompareWithWork_lt_53, proof_wordLEWithWork_value_26, proof_bitWordValue_bits_15] + refine OAI.EditApproximation.BitQuery.Footprint.chargeOf + (OAI.EditApproximation.queryScalePresentAllocation N key.1 + OAI.EditApproximation.queryRangeValidAllocation B range) ?_ + split + · split + · exact OAI.EditApproximation.queryPhysicalScalarReadFootprint M J N n exponent F Q R B _ + · exact .done _ + · exact .done _ + +def queryChargedSeedAtFootprint + {M J n passes copies T S : ℕ} + (parent : { r : OAI.EditApproximation.PhysicalTableRequest M J n // + OAI.EditApproximation.PhysicalTableRequest.Bounded passes copies T S r }) + (N : ℕ) + (multiplier : ℕ → ℕ) + (q : OAI.EditApproximation.TargetInterval n) : (OAI.EditApproximation.queryChargedSeedAt parent N multiplier q).Footprint := by + have proof_coarse_rank_lt_100 {M : ℕ} {J : ℕ} {ny : ℕ} {passes : ℕ} {copies : ℕ} {T : ℕ} {S : ℕ} (entry : OAI.EditApproximation.PhysicalEntry M J ny) (request : Subtype.{1} fun request => OAI.EditApproximation.PhysicalTableRequest.Bounded (M := M) (J := J) (ny := ny) passes copies T S request) (hnode : Eq.{1} entry.1 request.val.node) : + OAI.EditApproximation.ChargedPhysicalRequest.rank (Sum.inl entry : OAI.EditApproximation.ChargedPhysicalRequest M J ny passes copies T S) < OAI.EditApproximation.ChargedPhysicalRequest.rank (Sum.inr request) := by + change J - entry.1.1.val + 0 < request.val.remainingDepth + (request.val.rank T S + 1) + rw [hnode] + unfold OAI.EditApproximation.PhysicalTableRequest.remainingDepth + omega + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_eq_3 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .eq ↔ OAI.EditApproximation.bitWordValue left = OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_binaryNaturalCompareWithWork_eq_73 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.binaryNaturalCompareWithWork a b).1 = .eq ↔ a = b := by + simpa only [OAI.EditApproximation.binaryNaturalCompareWithWork, proof_bitWordValue_bits_15] using proof_bitCompareWithWork_eq_3 a.bits b.bits + have proof_naturalEqualWithWork_value_74 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.naturalEqualWithWork a b).1 = true ↔ a = b := by + simp only [OAI.EditApproximation.naturalEqualWithWork, decide_eq_true_eq, proof_binaryNaturalCompareWithWork_eq_73] + have proof_table_rank_lt_99 {M : ℕ} {J : ℕ} {ny : ℕ} {passes : ℕ} {copies : ℕ} {T : ℕ} {S : ℕ} (parent : Subtype.{1} fun request => OAI.EditApproximation.PhysicalTableRequest.Bounded (M := M) (J := J) (ny := ny) passes copies T S request) (child : Subtype.{1} fun request => OAI.EditApproximation.PhysicalTableRequest.Bounded (M := M) (J := J) (ny := ny) passes copies T S request) (h : LT.lt.{0} (OAI.EditApproximation.PhysicalTableRequest.combinedRank T S child.val) + (OAI.EditApproximation.PhysicalTableRequest.combinedRank T S parent.val)) : + OAI.EditApproximation.ChargedPhysicalRequest.rank (Sum.inr child : OAI.EditApproximation.ChargedPhysicalRequest M J ny passes copies T S) < OAI.EditApproximation.ChargedPhysicalRequest.rank (Sum.inr parent) := by + simpa only [OAI.EditApproximation.ChargedPhysicalRequest.rank, OAI.EditApproximation.ChargedPhysicalRequest.depth, OAI.EditApproximation.ChargedPhysicalRequest.index, ← Nat.add_assoc, OAI.EditApproximation.PhysicalTableRequest.combinedRank] using + Nat.add_lt_add_right h 1 + have proof_combinedRank_lt_of_progress_80 {M : ℕ} {J : ℕ} {ny : ℕ} (T : ℕ) (S : ℕ) (first : OAI.EditApproximation.PhysicalTableRequest M J ny) (second : OAI.EditApproximation.PhysicalTableRequest M J ny) (hprogress : LT.lt.{0} second.remainingDepth first.remainingDepth ∧ + LE.le.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first) ∨ + LE.le.{0} second.remainingDepth first.remainingDepth ∧ + LT.lt.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first)) : + OAI.EditApproximation.PhysicalTableRequest.combinedRank T S second < OAI.EditApproximation.PhysicalTableRequest.combinedRank T S first := by + unfold OAI.EditApproximation.PhysicalTableRequest.combinedRank + rcases hprogress with h | h + · exact Nat.add_lt_add_of_lt_of_le h.1 h.2 + · exact Nat.add_lt_add_of_le_of_lt h.1 h.2 + have proof_rank_lt_previous_pass_98 {M : ℕ} {J : ℕ} {ny : ℕ} (T : ℕ) (S : ℕ) (first : OAI.EditApproximation.PhysicalTableRequest M J ny) (second : OAI.EditApproximation.PhysicalTableRequest M J ny) (hpass : LT.lt.{0} second.pass first.pass) (hindex : LE.le.{0} second.index (HAdd.hAdd.{0, 0, 0} T S)) : + OAI.EditApproximation.PhysicalTableRequest.rank T S second < OAI.EditApproximation.PhysicalTableRequest.rank T S first := by + have hblock : second.pass * (T + S + 1) + second.index < + (second.pass + 1) * (T + S + 1) := by + nlinarith only [hindex] + have hnext := Nat.mul_le_mul_right (T + S + 1) (Nat.succ_le_of_lt hpass) + exact hblock.trans_le (hnext.trans (Nat.le_add_right _ _)) + have proof_previousPassRequest_progress_97 {M : ℕ} {J : ℕ} {ny : ℕ} (T : ℕ) (S : ℕ) (copy : ℕ) (parent : OAI.EditApproximation.PhysicalTableRequest M J ny) (hpass : LT.lt.{0} 0 parent.pass) (state : OAI.EditApproximation.TargetInterval ny) : + (OAI.EditApproximation.previousPassRequest T S copy parent state).remainingDepth = parent.remainingDepth ∧ + (OAI.EditApproximation.previousPassRequest T S copy parent state).rank T S < parent.rank T S := by + refine ⟨rfl, ?_⟩ + exact proof_rank_lt_previous_pass_98 T S parent _ (by + change parent.pass - 1 < parent.pass + omega) le_rfl + refine OAI.EditApproximation.BitQuery.Footprint.chargeOf (OAI.EditApproximation.naturalEqualAllocation parent.val.pass 0) ?_ + split + · exact OAI.EditApproximation.queryChargedReadFootprint parent _ + · refine OAI.EditApproximation.BitQuery.Footprint.chargeOf copies ?_ + refine OAI.EditApproximation.BitQuery.Footprint.collect _ (fun _ => OAI.EditApproximation.queryChargedReadFootprint parent _) _ _ fun words => ?_ + let factor := multiplier (parent.val.pass - 1) + exact OAI.EditApproximation.BitQuery.Footprint.computeOf (OAI.EditApproximation.BinaryFraction.querySeedMedianWithWork N factor words) + (OAI.EditApproximation.BinaryFraction.seedMedianAllocation N factor words + + (OAI.EditApproximation.BinaryFraction.seedMedianWithWork N factor words).1.length + 1) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open BitQuery +attribute [local instance] queryArityNeZero queryRoundsNeZero + +def queryFamilyOnlineReadFootprint + {α : Type u_1} + {M J R : ℕ} + (target : List α) + (N P F exponent H Q passes copies pass copy : ℕ) + (node : OAI.EditApproximation.PhysicalInternalNode M J) + (time : Fin R) + (key : ℕ × OAI.EditApproximation.TargetInterval target.length) + (range : ℕ) : (OAI.EditApproximation.queryFamilyOnlineRead target N P F exponent H Q passes copies pass copy node time key + range).Footprint := +OAI.EditApproximation.BitQuery.Footprint.mapKeysWithWork + (OAI.EditApproximation.queryFamilyTagWithWork target N P F exponent H Q passes copies pass copy) + (OAI.EditApproximation.queryFamilyTagAllocation target N P F exponent H Q passes copies pass copy) + (OAI.EditApproximation.queryPhysicalScalarOnlineReadFootprint M J N target.length exponent F Q R + (OAI.EditApproximation.localOnlineMassBound M P H) node time key range) + +def queryPhysicalInitialFootprint + (source target : List ℕ) + {M J passes copies T S : ℕ} + (N P F : ℕ) + (A a : OAI.EditApproximation.BinaryFraction) + (multiplier : ℕ → ℕ) + (parent : { r : OAI.EditApproximation.PhysicalTableRequest M J target.length // + OAI.EditApproximation.PhysicalTableRequest.Bounded passes copies T S r }) + (occurrence : OAI.EditApproximation.BinaryMemo OAI.EditApproximation.PositionCounts) + (symbolBits positionBits : ℕ) + (q : OAI.EditApproximation.TargetInterval target.length) : (OAI.EditApproximation.queryPhysicalInitial source target N P F A a multiplier parent occurrence symbolBits positionBits + q).Footprint := by + let interval := OAI.EditApproximation.physicalSourceInterval source.length parent.val.node + refine OAI.EditApproximation.BitQuery.Footprint.chargeOf (OAI.EditApproximation.saturatingSubtractAllocation interval.hi interval.lo + + OAI.EditApproximation.naturalWordLEAllocation (OAI.EditApproximation.saturatingSubtractWithWork interval.hi interval.lo).1 [true]) ?_ + split + · exact OAI.EditApproximation.BitQuery.Footprint.computeOf _ + (OAI.EditApproximation.queryIndexedSliceAllocation source interval target.length q occurrence symbolBits positionBits) + · exact OAI.EditApproximation.queryInitialConeProgramAtFootprint _ N P F A a (OAI.EditApproximation.queryChargedSeedAt parent N multiplier) q + (OAI.EditApproximation.queryChargedSeedAtFootprint parent N multiplier) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open BitQuery +attribute [local instance] queryArityNeZero queryRoundsNeZero +open Finset +open MeasureTheory ProbabilityTheory + +def queryPhysicalScalarGroupQueriesFootprint (M J N n exponent F Q R B : ℕ) + (node : OAI.EditApproximation.PhysicalInternalNode M J) (time : Fin R) (b : ℕ) (cell : ℕ × ℕ) : + ∀ s j, OAI.EditApproximation.BitQuery.Footprint + (OAI.EditApproximation.queryPhysicalScalarGroupQueries M J N n exponent F Q R B node time b cell s j) := by + have proof_log_two_add_one_eq_size_103 (N : ℕ) (hN : LT.lt.{0} 0 N) : + Nat.log 2 N + 1 = Nat.size N := by + apply Nat.le_antisymm + · have h := Nat.pow_log_le_self 2 hN.ne' + have hlt : Nat.log 2 N < Nat.size N := Nat.lt_size.mpr h + omega + · exact Nat.size_le.mpr (Nat.lt_pow_succ_log_self (by decide : 1 < 2) N) + have proof_powerTwoWord_value_13 (n : ℕ) : OAI.EditApproximation.bitWordValue (OAI.EditApproximation.powerTwoWord n) = 2 ^ n := by + induction n with + | zero => (simp [OAI.EditApproximation.powerTwoWord, OAI.EditApproximation.bitWordValue]) + | succ n ih => + (simp only [OAI.EditApproximation.powerTwoWord, List.replicate_succ, List.cons_append, OAI.EditApproximation.bitWordValue, + Bool.toNat_false, zero_add] at *) + rw [ih, pow_succ] + omega + have proof_arithmeticMapWithWork_value_70 {α : Type 0} {β : Type 0} (f : α → Prod.{0, 0} β ℕ) (values : List.{0} α) : + (OAI.EditApproximation.arithmeticMapWithWork f values).1 = values.map (fun a => (f a).1) := by + induction values with + | nil => rfl + | cons a rest ih => simp only [OAI.EditApproximation.arithmeticMapWithWork, ih, List.map_cons] + have proof_dyadicScalesWithWork_value_104 (N : ℕ) : + (OAI.EditApproximation.dyadicScalesWithWork N).1 = OAI.EditApproximation.dyadicScales N := by + have hcount : max 1 N.bits.length = Nat.log 2 N + 1 := by + by_cases hz : N = 0 + · subst N + decide + · have h := proof_log_two_add_one_eq_size_103 N (Nat.pos_of_ne_zero hz) + have hp := Nat.size_pos.mpr (Nat.pos_of_ne_zero hz) + rw [Nat.size_eq_bits_len, max_eq_right hp, h] + simp only [OAI.EditApproximation.dyadicScalesWithWork, proof_arithmeticMapWithWork_value_70, proof_powerTwoWord_value_13, hcount, + OAI.EditApproximation.dyadicScales] + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_eq_3 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .eq ↔ OAI.EditApproximation.bitWordValue left = OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_binaryNaturalCompareWithWork_eq_73 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.binaryNaturalCompareWithWork a b).1 = .eq ↔ a = b := by + simpa only [OAI.EditApproximation.binaryNaturalCompareWithWork, proof_bitWordValue_bits_15] using proof_bitCompareWithWork_eq_3 a.bits b.bits + have proof_naturalEqualWithWork_value_74 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.naturalEqualWithWork a b).1 = true ↔ a = b := by + simp only [OAI.EditApproximation.naturalEqualWithWork, decide_eq_true_eq, proof_binaryNaturalCompareWithWork_eq_73] + have proof_queryNaturalIndexWithWork_value_105 (a : ℕ) (xs : List.{0} ℕ) : + (OAI.EditApproximation.queryNaturalIndexWithWork a xs).1 = xs.idxOf a := by + induction xs with + | nil => rfl + | cons b xs ih => + simp only [OAI.EditApproximation.queryNaturalIndexWithWork] + by_cases hab : a = b + · subst b + rw [ite_eq_left ((proof_naturalEqualWithWork_value_74 a a).mpr rfl)] + simp + · rw [ite_eq_right (fun h => hab ((proof_naturalEqualWithWork_value_74 a b).mp h))] + simp only [ih, List.idxOf_cons, beq_iff_eq] + rw [ite_eq_right (Ne.symm hab)] + have proof_queryScaleDispatchWithWork_value_106 (N : ℕ) (b : ℕ) : + (OAI.EditApproximation.queryScaleDispatchWithWork N b).1 = (OAI.EditApproximation.dyadicScales N).idxOf b := by + simp only [OAI.EditApproximation.queryScaleDispatchWithWork, proof_queryNaturalIndexWithWork_value_105, proof_dyadicScalesWithWork_value_104] + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_binaryNaturalCompareWithWork_lt_53 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.binaryNaturalCompareWithWork a b).1 = .lt ↔ a < b := by + simpa only [OAI.EditApproximation.binaryNaturalCompareWithWork, proof_bitWordValue_bits_15] using proof_bitCompareWithWork_lt_16 a.bits b.bits + have proof_queryScalePresentWithWork_value_101 (N : ℕ) (b : ℕ) : + (OAI.EditApproximation.queryScalePresentWithWork N b).1 = true ↔ b ∈ OAI.EditApproximation.dyadicScales N := by + simp only [OAI.EditApproximation.queryScalePresentWithWork, decide_eq_true_eq, proof_binaryNaturalCompareWithWork_lt_53, + proof_queryScaleDispatchWithWork_value_106] + have hl : (OAI.EditApproximation.dyadicScales N).length = max 1 N.bits.length := by + rw [← proof_dyadicScalesWithWork_value_104 N] + (simp only [OAI.EditApproximation.dyadicScalesWithWork, proof_arithmeticMapWithWork_value_70, List.length_map, List.length_range]) + rw [← hl] + exact List.idxOf_lt_length_iff + have proof_wordLEWithWork_value_26 (a : List.{0} Bool) (b : List.{0} Bool) : + (OAI.EditApproximation.wordLEWithWork a b).1 = true ↔ OAI.EditApproximation.bitWordValue a ≤ OAI.EditApproximation.bitWordValue b := by + simp only [OAI.EditApproximation.wordLEWithWork, Bool.not_eq_true', decide_eq_false_iff_not, + proof_bitCompareWithWork_lt_16, not_lt] + have proof_bitAdder_value_1 (a : Bool) (b : Bool) (carry : Bool) : + (OAI.EditApproximation.bitSum a b carry).toNat + 2 * (OAI.EditApproximation.bitCarry a b carry).toNat = + a.toNat + b.toNat + carry.toNat := by + cases a <;> cases b <;> cases carry <;> decide + have proof_bitAddWithWork_value_2 (left : List.{0} Bool) (right : List.{0} Bool) (carry : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitAddWithWork left right carry).1 = + OAI.EditApproximation.bitWordValue left + OAI.EditApproximation.bitWordValue right + carry.toNat := by + induction left generalizing right carry with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork] + induction right generalizing carry with + | nil => cases carry <;> simp [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue] + | cons b bs ih => + simp only [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 false b carry + simp only [Bool.toNat_false] at h + omega + | cons a as ih => + cases right with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a false carry + simp only [Bool.toNat_false] at h + omega + | cons b bs => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a b carry + omega + have proof_bitMulWithWork_value_0 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitMulWithWork left right).1 = OAI.EditApproximation.bitWordValue left * OAI.EditApproximation.bitWordValue right := by + induction left with + | nil => simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue] + | cons bit bits ih => + cases bit <;> simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue, proof_bitAddWithWork_value_2, ih] <;> ring + have proof_binaryNaturalMulWithWork_value_55 (a : ℕ) (b : ℕ) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalMulWithWork a b).1 = a * b := by + simp [OAI.EditApproximation.binaryNaturalMulWithWork, proof_bitMulWithWork_value_0, proof_bitWordValue_bits_15] + have proof_queryCellValidWithWork_value_102 (n : ℕ) (exponent : ℕ) (cell : Prod.{0, 0} ℕ ℕ) : + (OAI.EditApproximation.queryCellValidWithWork n exponent cell).1 = true ↔ + cell.1 ≤ n * 2 ^ exponent ∧ cell.2 ≤ n * 2 ^ exponent := by + simp only [OAI.EditApproximation.queryCellValidWithWork, Bool.and_eq_true, proof_wordLEWithWork_value_26, proof_bitWordValue_bits_15, + proof_binaryNaturalMulWithWork_value_55, proof_powerTwoWord_value_13] + have proof_physicalScaleIndex_get_93 (N : ℕ) (b : ℕ) (hb : Membership.mem.{0, 0} (OAI.EditApproximation.dyadicScales N) b) : + (OAI.EditApproximation.dyadicScales N).get (OAI.EditApproximation.physicalScaleIndex N b hb) = b := + List.getElem_idxOf (List.idxOf_lt_length_of_mem hb) + have groupTransport (b c : ℕ) (h : b = c) + (actual : OAI.EditApproximation.BitPhysicalGroupQueries M J N n exponent F Q R B b) + (heap : ∀ s j, OAI.EditApproximation.BitQuery.Footprint (actual s j)) : + ∀ s j, OAI.EditApproximation.BitQuery.Footprint + ((Eq.mp (congrArg (OAI.EditApproximation.BitPhysicalGroupQueries M J N n exponent F Q R B) h) actual) s j) := by + cases h + exact heap + intro s j + unfold OAI.EditApproximation.queryPhysicalScalarGroupQueries + split + · rename_i hb + split + · exact groupTransport _ _ + (proof_physicalScaleIndex_get_93 N b ((proof_queryScalePresentWithWork_value_101 N b).mp hb)) _ + (fun _ _ => OAI.EditApproximation.queryPhysicalScalarReadFootprint M J N n exponent F Q R B _) s j + · exact .done _ + · exact .done _ + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open BitQuery +attribute [local instance] queryArityNeZero queryRoundsNeZero + +def queryPhysicalScalarGroupReadFootprint + (M J N n exponent F Q R B : ℕ) + (node : OAI.EditApproximation.PhysicalInternalNode M J) + (time : Fin R) + (key : OAI.EditApproximation.GroupScalarKey M F Q) : (OAI.EditApproximation.queryPhysicalScalarGroupRead M J N n exponent F Q R B node time key).Footprint := +OAI.EditApproximation.BitQuery.Footprint.chargeOf + (OAI.EditApproximation.queryScalePresentAllocation N key.fst.1 + + OAI.EditApproximation.queryCellValidAllocation n exponent key.fst.2) + (OAI.EditApproximation.queryPhysicalScalarGroupQueriesFootprint M J N n exponent F Q R B node time key.fst.1 key.fst.2 + key.snd.fst key.snd.snd) + +def queryFamilyGroupReadFootprint + {α : Type u_1} + {M J R : ℕ} + (target : List α) + (N P F exponent H Q passes copies pass copy : ℕ) + (node : OAI.EditApproximation.PhysicalInternalNode M J) + (time : Fin R) + (key : OAI.EditApproximation.GroupScalarKey M F Q) : (OAI.EditApproximation.queryFamilyGroupRead target N P F exponent H Q passes copies pass copy node time key).Footprint := +OAI.EditApproximation.BitQuery.Footprint.mapKeysWithWork + (OAI.EditApproximation.queryFamilyTagWithWork target N P F exponent H Q passes copies pass copy) + (OAI.EditApproximation.queryFamilyTagAllocation target N P F exponent H Q passes copies pass copy) + (OAI.EditApproximation.queryPhysicalScalarGroupReadFootprint M J N target.length exponent F Q R + (OAI.EditApproximation.localOnlineMassBound M P H) node time key) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open BitQuery +attribute [local instance] queryArityNeZero queryRoundsNeZero +open Finset + +def queryChargedWarmupFootprint + (source target : List ℕ) + {M J passes copies T S : ℕ} + (N P F : ℕ) + (A a : OAI.EditApproximation.BinaryFraction) + (multiplier : ℕ → ℕ) + (parent : { r : OAI.EditApproximation.PhysicalTableRequest M J target.length // + OAI.EditApproximation.PhysicalTableRequest.Bounded passes copies T S r }) + (occurrence : OAI.EditApproximation.BinaryMemo OAI.EditApproximation.PositionCounts) + (symbolBits positionBits : ℕ) : (OAI.EditApproximation.queryChargedWarmup source target N P F A a multiplier parent occurrence symbolBits + positionBits).Footprint := by + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_binaryNaturalCompareWithWork_lt_53 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.binaryNaturalCompareWithWork a b).1 = .lt ↔ a < b := by + simpa only [OAI.EditApproximation.binaryNaturalCompareWithWork, proof_bitWordValue_bits_15] using proof_bitCompareWithWork_lt_16 a.bits b.bits + have proof_bitCompareWithWork_eq_3 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .eq ↔ OAI.EditApproximation.bitWordValue left = OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_binaryNaturalCompareWithWork_eq_73 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.binaryNaturalCompareWithWork a b).1 = .eq ↔ a = b := by + simpa only [OAI.EditApproximation.binaryNaturalCompareWithWork, proof_bitWordValue_bits_15] using proof_bitCompareWithWork_eq_3 a.bits b.bits + have proof_naturalEqualWithWork_value_74 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.naturalEqualWithWork a b).1 = true ↔ a = b := by + simp only [OAI.EditApproximation.naturalEqualWithWork, decide_eq_true_eq, proof_binaryNaturalCompareWithWork_eq_73] + have proof_table_rank_lt_99 {M : ℕ} {J : ℕ} {ny : ℕ} {passes : ℕ} {copies : ℕ} {T : ℕ} {S : ℕ} (parent : Subtype.{1} fun request => OAI.EditApproximation.PhysicalTableRequest.Bounded (M := M) (J := J) (ny := ny) passes copies T S request) (child : Subtype.{1} fun request => OAI.EditApproximation.PhysicalTableRequest.Bounded (M := M) (J := J) (ny := ny) passes copies T S request) (h : LT.lt.{0} (OAI.EditApproximation.PhysicalTableRequest.combinedRank T S child.val) + (OAI.EditApproximation.PhysicalTableRequest.combinedRank T S parent.val)) : + OAI.EditApproximation.ChargedPhysicalRequest.rank (Sum.inr child : OAI.EditApproximation.ChargedPhysicalRequest M J ny passes copies T S) < OAI.EditApproximation.ChargedPhysicalRequest.rank (Sum.inr parent) := by + simpa only [OAI.EditApproximation.ChargedPhysicalRequest.rank, OAI.EditApproximation.ChargedPhysicalRequest.depth, OAI.EditApproximation.ChargedPhysicalRequest.index, ← Nat.add_assoc, OAI.EditApproximation.PhysicalTableRequest.combinedRank] using + Nat.add_lt_add_right h 1 + have proof_combinedRank_lt_of_progress_80 {M : ℕ} {J : ℕ} {ny : ℕ} (T : ℕ) (S : ℕ) (first : OAI.EditApproximation.PhysicalTableRequest M J ny) (second : OAI.EditApproximation.PhysicalTableRequest M J ny) (hprogress : LT.lt.{0} second.remainingDepth first.remainingDepth ∧ + LE.le.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first) ∨ + LE.le.{0} second.remainingDepth first.remainingDepth ∧ + LT.lt.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first)) : + OAI.EditApproximation.PhysicalTableRequest.combinedRank T S second < OAI.EditApproximation.PhysicalTableRequest.combinedRank T S first := by + unfold OAI.EditApproximation.PhysicalTableRequest.combinedRank + rcases hprogress with h | h + · exact Nat.add_lt_add_of_lt_of_le h.1 h.2 + · exact Nat.add_lt_add_of_le_of_lt h.1 h.2 + have proof_warmup_previous_child_progress_81 {M : ℕ} {J : ℕ} {ny : ℕ} (pass : ℕ) (copy : ℕ) (T : ℕ) (S : ℕ) (j : ℕ) (node : OAI.EditApproximation.PhysicalNode M J) (hbelow : LT.lt.{0} (↑(Sigma.fst.{0, 0} node)) J) (i : Fin M) (state : OAI.EditApproximation.TargetInterval ny) (previousState : OAI.EditApproximation.TargetInterval ny) (hj : LT.lt.{0} 0 j) : + (OAI.EditApproximation.PhysicalTableRequest.warmup pass copy (OAI.EditApproximation.physicalChild node hbelow i) (j - 1) previousState).remainingDepth < + (OAI.EditApproximation.PhysicalTableRequest.warmup pass copy node j state).remainingDepth ∧ + OAI.EditApproximation.PhysicalTableRequest.rank T S (OAI.EditApproximation.PhysicalTableRequest.warmup pass copy (OAI.EditApproximation.physicalChild node hbelow i) (j - 1) previousState) < + OAI.EditApproximation.PhysicalTableRequest.rank T S (OAI.EditApproximation.PhysicalTableRequest.warmup pass copy node j state) := by + constructor + · unfold OAI.EditApproximation.PhysicalTableRequest.remainingDepth OAI.EditApproximation.PhysicalTableRequest.warmup OAI.EditApproximation.physicalChild + dsimp only + omega + · dsimp only [OAI.EditApproximation.PhysicalTableRequest.rank, OAI.EditApproximation.PhysicalTableRequest.warmup] + omega + have proof_combinedRank_warmup_child_79 {M : ℕ} {J : ℕ} {ny : ℕ} (pass : ℕ) (copy : ℕ) (T : ℕ) (S : ℕ) (j : ℕ) (node : OAI.EditApproximation.PhysicalNode M J) (hbelow : LT.lt.{0} (↑(Sigma.fst.{0, 0} node)) J) (i : Fin M) (state : OAI.EditApproximation.TargetInterval ny) (previousState : OAI.EditApproximation.TargetInterval ny) (hj : LT.lt.{0} 0 j) : + OAI.EditApproximation.PhysicalTableRequest.combinedRank T S (OAI.EditApproximation.PhysicalTableRequest.warmup pass copy (OAI.EditApproximation.physicalChild node hbelow i) (j - 1) previousState) < + OAI.EditApproximation.PhysicalTableRequest.combinedRank T S (OAI.EditApproximation.PhysicalTableRequest.warmup pass copy node j state) := + proof_combinedRank_lt_of_progress_80 T S _ _ (Or.inr + ⟨(proof_warmup_previous_child_progress_81 pass copy T S j node hbelow i state previousState hj).1.le, + (proof_warmup_previous_child_progress_81 pass copy T S j node hbelow i state previousState hj).2⟩) + have hinit := OAI.EditApproximation.queryPhysicalInitialFootprint source target N P F A a multiplier parent occurrence + symbolBits positionBits + unfold OAI.EditApproximation.queryChargedWarmup + refine OAI.EditApproximation.BitQuery.Footprint.chargeOf (OAI.EditApproximation.naturalEqualAllocation parent.val.index 0) ?_ + split + · exact hinit _ + · refine OAI.EditApproximation.BitQuery.Footprint.chargeOf (parent.val.node.1.val.bits.length + J.bits.length) ?_ + split + · let interval := OAI.EditApproximation.physicalSourceInterval source.length parent.val.node + refine OAI.EditApproximation.BitQuery.Footprint.chargeOf (OAI.EditApproximation.saturatingSubtractAllocation interval.hi interval.lo + + OAI.EditApproximation.naturalWordLEAllocation (OAI.EditApproximation.saturatingSubtractWithWork interval.hi interval.lo).1 [true]) ?_ + split + · exact hinit _ + · apply OAI.EditApproximation.queryWarmupProgramFootprint + · exact hinit + · intro input + exact OAI.EditApproximation.queryChargedReadFootprint parent _ + · exact hinit _ + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BinaryFraction +variable {α : Type u_4} (source target : List α) {M : ℕ} (parent : TargetInterval source.length) (P F exponent Q eM eF : ℕ) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (hP : 0 < P) (tau a : BinaryFraction) (parentInitial : TargetInterval target.length → BinaryFraction × ℕ) (child initial current : Fin M → TargetInterval target.length → BinaryFraction × ℕ) (R : ℕ) (hc : ∀ i q, (child i q).2 ≤ R) (hi : ∀ i q, (initial i q).2 ≤ R) +open Finset + +def preparedComputedCellSourceWithWorkRawBand (b eb : ℕ) (hb : b = 2 ^ eb) + (draw : ∀ t : Fin (OAI.EditApproximation.groupDyadicScales M b (OAI.EditApproximation.BinaryFraction.nat F).value).length, + Fin (OAI.EditApproximation.groupSampleCount M Q b (OAI.EditApproximation.groupDyadicScaleAt M b (OAI.EditApproximation.BinaryFraction.nat F).value t)) → Fin M × ℕ) + (cell : ℕ × ℕ) : + Option (OAI.EditApproximation.BinaryBellmanAction (OAI.EditApproximation.TargetInterval target.length) + (Fin M × OAI.EditApproximation.TargetInterval target.length) M) × ℕ := by + have proof_representation_value_32 (a : OAI.EditApproximation.BinaryFraction) : a.representation.value = a.value := rfl + have proof_eq_of_num_den_33 {a : OAI.EditApproximation.UnreducedRational} {b : OAI.EditApproximation.UnreducedRational} (hnum : Eq.{1} a.num b.num) (hden : Eq.{1} a.den b.den) : a = b := by + cases a + cases b + cases hnum + cases hden + rfl + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_value_ofInt_46 (a : ℤ) : (OAI.EditApproximation.SignedBinary.ofInt a).value = a := by + by_cases h : a < 0 + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_true, + ↓reduceIte] using (Int.eq_neg_natAbs_of_nonpos (le_of_lt h)).symm + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_false, + Bool.false_eq_true, ↓reduceIte] using (Int.eq_natAbs_of_nonneg (le_of_not_gt h)).symm + have proof_nat_representation_47 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).representation = OAI.EditApproximation.UnreducedRational.nat n := by + apply proof_eq_of_num_den_33 + · change (OAI.EditApproximation.SignedBinary.ofInt (n : ℤ)).value = (n : ℤ) + exact proof_value_ofInt_46 _ + · rfl + have proof_value_nat_48 (n : ℕ) : (OAI.EditApproximation.UnreducedRational.nat n).value = n := by (simp [OAI.EditApproximation.UnreducedRational.nat, OAI.EditApproximation.UnreducedRational.value]) + have proof_nat_value_49 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).value = (n : ℚ) := by + rw [← proof_representation_value_32, proof_nat_representation_47, proof_value_nat_48] + have proof_arithmeticMapWithWork_value_70 {α : Type 0} {β : Type 0} (f : α → Prod.{0, 0} β ℕ) (values : List.{0} α) : + (OAI.EditApproximation.arithmeticMapWithWork f values).1 = values.map (fun a => (f a).1) := by + induction values with + | nil => rfl + | cons a rest ih => simp only [OAI.EditApproximation.arithmeticMapWithWork, ih, List.map_cons] + have proof_powerTwoWord_value_13 (n : ℕ) : OAI.EditApproximation.bitWordValue (OAI.EditApproximation.powerTwoWord n) = 2 ^ n := by + induction n with + | zero => (simp [OAI.EditApproximation.powerTwoWord, OAI.EditApproximation.bitWordValue]) + | succ n ih => + (simp only [OAI.EditApproximation.powerTwoWord, List.replicate_succ, List.cons_append, OAI.EditApproximation.bitWordValue, + Bool.toNat_false, zero_add] at *) + rw [ih, pow_succ] + omega + have proof_inversePowerTwo_value_89 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.inversePowerTwo n).value = (2 : ℚ) ^ (-(n : ℤ)) := by + (simp only [OAI.EditApproximation.BinaryFraction.inversePowerTwo, OAI.EditApproximation.BinaryFraction.value, OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, Bool.false_eq_true, + ↓reduceIte, OAI.EditApproximation.bitWordValue, Bool.toNat_true, + Int.cast_natCast, proof_powerTwoWord_value_13, Nat.cast_pow, Nat.cast_ofNat, zpow_neg, zpow_natCast]) + norm_num [one_div] + have proof_signedPowerTwoWithWork_value_90 (e : ℤ) : + (OAI.EditApproximation.BinaryFraction.signedPowerTwoWithWork e).1.value = (2 : ℚ) ^ e := by + unfold OAI.EditApproximation.BinaryFraction.signedPowerTwoWithWork + split_ifs with h + · change (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.powerTwoWord e.toNat) : ℚ) / 1 = (2 : ℚ) ^ e + rw [div_one, proof_powerTwoWord_value_13, Nat.cast_pow, Nat.cast_ofNat, ← zpow_natCast, + Int.toNat_of_nonneg h] + · rw [proof_inversePowerTwo_value_89, Int.toNat_of_nonneg + (show 0 ≤ -e from neg_nonneg.mpr (le_of_lt (lt_of_not_ge h))), neg_neg] + have proof_groupScalesWithWork_value_91 (eM : ℕ) (eb : ℕ) (eF : ℕ) : + ((OAI.EditApproximation.BinaryFraction.groupScalesWithWork eM eb eF).1.map OAI.EditApproximation.BinaryFraction.value) = + OAI.EditApproximation.groupDyadicScales (2 ^ eM) (2 ^ eb) ((2 : ℚ) ^ eF) := by + have hlower : ((2 ^ eb : ℕ) : ℚ) / (2 ^ eM : ℕ) = (2 : ℚ) ^ ((eb : ℤ) - eM) := by + rw [Nat.cast_pow, Nat.cast_pow, Nat.cast_ofNat, zpow_sub₀ (by norm_num : (2 : ℚ) ≠ 0), + zpow_natCast, zpow_natCast] + have hupper : (64 : ℚ) * (2 : ℚ) ^ eF * (2 ^ eb : ℕ) = + (2 : ℚ) ^ ((6 + eF + eb : ℕ) : ℤ) := by + rw [Nat.cast_pow, Nat.cast_ofNat, zpow_natCast, pow_add, pow_add] + norm_num + have hlog : Int.log 2 ((2 : ℚ) ^ ((6 + eF + eb : ℕ) : ℤ)) = ((6 + eF + eb : ℕ) : ℤ) := by + simpa only [Nat.cast_ofNat] using Int.log_zpow (R := ℚ) (by decide : 1 < 2) ((6 + eF + eb : ℕ) : ℤ) + have hclog : Int.clog 2 ((2 : ℚ) ^ ((eb : ℤ) - eM)) = (eb : ℤ) - eM := by + simpa only [Nat.cast_ofNat] using Int.clog_zpow (R := ℚ) (by decide : 1 < 2) ((eb : ℤ) - eM) + simp only [OAI.EditApproximation.BinaryFraction.groupScalesWithWork, proof_arithmeticMapWithWork_value_70, List.map_map, + Function.comp_def, proof_signedPowerTwoWithWork_value_90, OAI.EditApproximation.groupDyadicScales, hlower, hupper, hlog, hclog] + have proof_computedGroupScales_value_87 (M : ℕ) (b : ℕ) (F : ℕ) (eM : ℕ) (eb : ℕ) (eF : ℕ) (hM : Eq.{1} M (HPow.hPow.{0, 0, 0} 2 eM)) (hb : Eq.{1} b (HPow.hPow.{0, 0, 0} 2 eb)) (hF : Eq.{1} F (HPow.hPow.{0, 0, 0} 2 eF)) : + (OAI.EditApproximation.BinaryFraction.groupScalesWithWork eM eb eF).1.map OAI.EditApproximation.BinaryFraction.value = OAI.EditApproximation.groupDyadicScales M b (OAI.EditApproximation.BinaryFraction.nat F).value := by + rw [proof_nat_value_49, hM, hb, hF, Nat.cast_pow, Nat.cast_ofNat] + exact proof_groupScalesWithWork_value_91 eM eb eF + exact + let scales := OAI.EditApproximation.BinaryFraction.groupScalesWithWork eM eb eF + let result := OAI.EditApproximation.BinaryFraction.preparedCellGroupSourceWithWorkRaw source target parent b P F exponent Q + (by rw [hb]; exact Nat.two_pow_pos eb) hP tau a parentInitial child initial current + R R hc hi scales.1 (proof_computedGroupScales_value_87 M b F eM eb eF hM hb hF) draw cell + (result.1, scales.2 + result.2 + 1) + +def preparedLocalGroupScaleSourceWithWorkRawBand (eb : ℕ) + (draw : OAI.EditApproximation.CellGroupReadDraws M F Q) (query : OAI.EditApproximation.TargetInterval target.length) : + List (OAI.EditApproximation.BinaryBellmanAction (OAI.EditApproximation.TargetInterval target.length) + (Fin M × OAI.EditApproximation.TargetInterval target.length) M) × ℕ := by + have proof_representation_value_32 (a : OAI.EditApproximation.BinaryFraction) : a.representation.value = a.value := rfl + have proof_eq_of_num_den_33 {a : OAI.EditApproximation.UnreducedRational} {b : OAI.EditApproximation.UnreducedRational} (hnum : Eq.{1} a.num b.num) (hden : Eq.{1} a.den b.den) : a = b := by + cases a + cases b + cases hnum + cases hden + rfl + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_value_ofInt_46 (a : ℤ) : (OAI.EditApproximation.SignedBinary.ofInt a).value = a := by + by_cases h : a < 0 + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_true, + ↓reduceIte] using (Int.eq_neg_natAbs_of_nonpos (le_of_lt h)).symm + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_false, + Bool.false_eq_true, ↓reduceIte] using (Int.eq_natAbs_of_nonneg (le_of_not_gt h)).symm + have proof_nat_representation_47 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).representation = OAI.EditApproximation.UnreducedRational.nat n := by + apply proof_eq_of_num_den_33 + · change (OAI.EditApproximation.SignedBinary.ofInt (n : ℤ)).value = (n : ℤ) + exact proof_value_ofInt_46 _ + · rfl + have proof_value_nat_48 (n : ℕ) : (OAI.EditApproximation.UnreducedRational.nat n).value = n := by (simp [OAI.EditApproximation.UnreducedRational.nat, OAI.EditApproximation.UnreducedRational.value]) + have proof_nat_value_49 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).value = (n : ℚ) := by + rw [← proof_representation_value_32, proof_nat_representation_47, proof_value_nat_48] + exact + let b := 2 ^ eb + let word := parentInitial query + let side := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) (OAI.EditApproximation.BinaryFraction.nat b) + let radius := OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork word.1 + let cells := OAI.EditApproximation.BinaryFraction.targetCellsWithWork side.1 (OAI.EditApproximation.bitWordValue radius.1) query + let selected := OAI.EditApproximation.filterMapWithWork (fun cell => + OAI.EditApproximation.BinaryFraction.preparedComputedCellSourceWithWorkRawBand source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial current R hc hi b eb rfl + (Eq.mpr (congrArg (OAI.EditApproximation.cellScaleReadDraw M b Q) (proof_nat_value_49 F)) (draw b cell)) cell) cells.1 + (selected.1, word.2 + side.2 + radius.2 + cells.2 + selected.2 + eb + 4) + + +end OAI.EditApproximation.BinaryFraction +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BinaryFraction +variable {α : Type u_4} (source target : List α) {M : ℕ} (parent : TargetInterval source.length) (P F exponent Q eM eF : ℕ) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (hP : 0 < P) (tau a : BinaryFraction) (parentInitial : TargetInterval target.length → BinaryFraction × ℕ) (child initial current : Fin M → TargetInterval target.length → BinaryFraction × ℕ) (R : ℕ) (hc : ∀ i q, (child i q).2 ≤ R) (hi : ∀ i q, (initial i q).2 ≤ R) + +def preparedLocalCellGroupsSourceWithWorkRawBand (N : ℕ) + (draw : OAI.EditApproximation.CellGroupReadDraws M F Q) (query : OAI.EditApproximation.TargetInterval target.length) : + List (OAI.EditApproximation.BinaryBellmanAction (OAI.EditApproximation.TargetInterval target.length) + (Fin M × OAI.EditApproximation.TargetInterval target.length) M) × ℕ := + let count := max 1 N.bits.length + let word := parentInitial query + let groups := OAI.EditApproximation.arithmeticFlatMapWithWork (fun eb => + let guard := OAI.EditApproximation.BinaryFraction.refinementScaleGuardWithWork F (2 ^ eb) a word.1 + if guard.1 then + let selected := OAI.EditApproximation.BinaryFraction.preparedLocalGroupScaleSourceWithWorkRawBand source target parent P F exponent Q eM eF + hM hF hP tau a parentInitial child initial current R hc hi eb draw query + (selected.1, guard.2 + selected.2 + eb + 4) + else ([], guard.2 + eb + 4)) (List.range count) + (groups.1, word.2 + groups.2 + count + N.bits.length + 2) + + +end OAI.EditApproximation.BinaryFraction +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BinaryFraction +variable {α : Type u_4} (source target : List α) {M : ℕ} (parent : TargetInterval source.length) (P F exponent H : ℕ) (hP : 0 < P) (tau a eta kappa : BinaryFraction) (parentInitial : TargetInterval target.length → BinaryFraction × ℕ) (child initial : Fin M → TargetInterval target.length → BinaryFraction × ℕ) (table : ℕ → Fin M × TargetInterval target.length → BinaryFraction × ℕ) (R : ℕ) (hc : ∀ i q, (child i q).2 ≤ R) (hi : ∀ i q, (initial i q).2 ≤ R) (t : ℕ) (integer : ℕ → TargetInterval target.length → ℕ × ℕ) + +def preparedLocalOnlineScaleSourceWithWorkRawBand (e : ℕ) (query : OAI.EditApproximation.TargetInterval target.length) : + Option (OAI.EditApproximation.BinaryBellmanAction (OAI.EditApproximation.TargetInterval target.length) + (Fin M × OAI.EditApproximation.TargetInterval target.length) M) × ℕ := by + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_bitSubtractor_value_17 (a : Bool) (b : Bool) (borrow : Bool) : + a.toNat + 2 * (OAI.EditApproximation.bitBorrow a b borrow).toNat = + b.toNat + borrow.toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat := by + cases a <;> cases b <;> cases borrow <;> decide + have proof_bitSubtractionRippleEquation_18 (a : ℕ) (b : ℕ) (borrow : ℕ) (nextBorrow : ℕ) (difference : ℕ) (left : ℕ) (right : ℕ) (result : ℕ) (tail : ℕ) (htail : Eq.{1} (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} result right) nextBorrow) (HAdd.hAdd.{0, 0, 0} left tail)) (hbit : Eq.{1} (HAdd.hAdd.{0, 0, 0} a (HMul.hMul.{0, 0, 0} 2 nextBorrow)) + (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} b borrow) difference)) : + (difference + 2 * result) + (b + 2 * right) + borrow = + (a + 2 * left) + 2 * tail := by + omega + have proof_bitSubtractWithWork_value_19 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right borrow).1 + OAI.EditApproximation.bitWordValue right + borrow.toNat = + OAI.EditApproximation.bitWordValue left + 2 ^ max left.length right.length * + (OAI.EditApproximation.bitSubtractWithWork left right borrow).2.1.toNat := by + induction left generalizing right borrow with + | nil => + induction right generalizing borrow with + | nil => (simp [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + have h := ih (OAI.EditApproximation.bitBorrow false b borrow) + have hb := proof_bitSubtractor_value_17 false b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue, + List.length_nil, List.length_cons, Nat.zero_max, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 0 b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow false b borrow).toNat + (OAI.EditApproximation.bitDifference false b borrow).toNat 0 (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).1) + (2 ^ bs.length * (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons a as ih => + cases right with + | nil => + have h := ih [] (OAI.EditApproximation.bitBorrow a false borrow) + have hb := proof_bitSubtractor_value_17 a false borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_nil, List.length_cons, + Nat.max_zero, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat 0 borrow.toNat (OAI.EditApproximation.bitBorrow a false borrow).toNat + (OAI.EditApproximation.bitDifference a false borrow).toNat (OAI.EditApproximation.bitWordValue as) 0 + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).1) + (2 ^ as.length * (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons b bs => + have h := ih bs (OAI.EditApproximation.bitBorrow a b borrow) + have hb := proof_bitSubtractor_value_17 a b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_cons, Nat.succ_max_succ, + pow_succ] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow a b borrow).toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).1) + (2 ^ max as.length bs.length * (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_assoc, Nat.mul_left_comm] using hs + have proof_bitWordValue_lt_pow_length_20 (bits : List.{0} Bool) : OAI.EditApproximation.bitWordValue bits < 2 ^ bits.length := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitWordValue]) + | cons bit bits ih => + cases bit <;> (simp only [OAI.EditApproximation.bitWordValue, List.length_cons, pow_succ, Bool.toNat_false, Bool.toNat_true]) <;> omega + have proof_bitSubtractWithWork_length_21 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + (OAI.EditApproximation.bitSubtractWithWork left right borrow).1.length = max left.length right.length := by + induction left generalizing right borrow with + | nil => + simp only [OAI.EditApproximation.bitSubtractWithWork] + induction right generalizing borrow with + | nil => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork] + | cons b bs ih => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork, ih] + | cons a as ih => + cases right with + | nil => simp [OAI.EditApproximation.bitSubtractWithWork, ih] + | cons b bs => simp [OAI.EditApproximation.bitSubtractWithWork, ih, Nat.succ_max_succ] + have proof_bitSubtractWithWork_sub_22 (left : List.{0} Bool) (right : List.{0} Bool) (h : LE.le.{0} (OAI.EditApproximation.bitWordValue right) (OAI.EditApproximation.bitWordValue left)) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right false).1 = OAI.EditApproximation.bitWordValue left - OAI.EditApproximation.bitWordValue right := by + have hvalue := proof_bitSubtractWithWork_value_19 left right false + have hlt := proof_bitWordValue_lt_pow_length_20 (OAI.EditApproximation.bitSubtractWithWork left right false).1 + rw [proof_bitSubtractWithWork_length_21] at hlt + cases hb : (OAI.EditApproximation.bitSubtractWithWork left right false).2.1 + · simp only [hb, Bool.toNat_false, Nat.mul_zero, Nat.add_zero] at hvalue + omega + · simp only [hb, Bool.toNat_true, Bool.toNat_false, Nat.mul_one, Nat.add_zero] at hvalue + omega + have proof_bitDivModWithWork_value_23 (divisor : List.{0} Bool) (bits : List.{0} Bool) (hd : LT.lt.{0} 0 (OAI.EditApproximation.bitWordValue divisor)) : + OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).1 + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 < OAI.EditApproximation.bitWordValue divisor := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitDivModWithWork, OAI.EditApproximation.bitWordValue, hd]) + | cons bit bits ih => + let previous := OAI.EditApproximation.bitDivModWithWork divisor bits + let candidate := bit :: previous.2.1 + have hp : OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue previous.1 + + OAI.EditApproximation.bitWordValue previous.2.1 := ih.1 + have hr : OAI.EditApproximation.bitWordValue previous.2.1 < OAI.EditApproximation.bitWordValue divisor := ih.2 + have hc : OAI.EditApproximation.bitWordValue candidate < 2 * OAI.EditApproximation.bitWordValue divisor := by + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + cases bit <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega + by_cases hlt : (OAI.EditApproximation.bitCompareWithWork candidate divisor).1 = .lt + · have hv := (proof_bitCompareWithWork_lt_16 candidate divisor).1 hlt + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 = .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * + OAI.EditApproximation.bitWordValue (false :: previous.1) + OAI.EditApproximation.bitWordValue candidate ∧ OAI.EditApproximation.bitWordValue candidate < _ + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_false]) + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + nlinarith only [hp] + · exact hv + · have hv : OAI.EditApproximation.bitWordValue divisor ≤ OAI.EditApproximation.bitWordValue candidate := by + exact Nat.le_of_not_gt (fun h => hlt ((proof_bitCompareWithWork_lt_16 candidate divisor).2 h)) + have hs := proof_bitSubtractWithWork_sub_22 candidate divisor hv + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 ≠ .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (true :: previous.1) + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 < _ + rw [hs] + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_true]) + have he := Nat.sub_add_cancel hv + dsimp only [candidate, OAI.EditApproximation.bitWordValue] at he ⊢ + nlinarith only [hp, he] + · omega + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_binaryNaturalDivModWithWork_spec_24 (n : ℕ) (d : ℕ) (hd : LT.lt.{0} 0 d) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalDivModWithWork n d).1 = n / d ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalDivModWithWork n d).2.1 = n % d := by + have h := proof_bitDivModWithWork_value_23 d.bits n.bits (by simpa only [proof_bitWordValue_bits_15] using hd) + simp only [proof_bitWordValue_bits_15] at h + have hmod : n % d = OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork d.bits n.bits).2.1 := by + conv_lhs => rw [h.1] + simp only [Nat.add_mod, Nat.mul_mod_right, Nat.zero_add, Nat.mod_eq_of_lt h.2] + have hdiv : n / d = OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork d.bits n.bits).1 := by + conv_lhs => rw [h.1] + rw [Nat.mul_add_div hd, Nat.div_eq_of_lt h.2, Nat.add_zero] + exact ⟨hdiv.symm, hmod.symm⟩ + have proof_wordLEWithWork_value_26 (a : List.{0} Bool) (b : List.{0} Bool) : + (OAI.EditApproximation.wordLEWithWork a b).1 = true ↔ OAI.EditApproximation.bitWordValue a ≤ OAI.EditApproximation.bitWordValue b := by + simp only [OAI.EditApproximation.wordLEWithWork, Bool.not_eq_true', decide_eq_false_iff_not, + proof_bitCompareWithWork_lt_16, not_lt] + have proof_seedGridSpacingWithWork_value_86 (b : ℕ) (P : ℕ) (hP : LT.lt.{0} 0 P) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.seedGridSpacingWithWork b P).1 = OAI.EditApproximation.seedGridSpacing b P := by + have hv := (proof_binaryNaturalDivModWithWork_spec_24 b P hP).1 + unfold OAI.EditApproximation.seedGridSpacingWithWork OAI.EditApproximation.seedGridSpacing + dsimp only + split_ifs with ht + · have hq : b / P ≤ 1 := by + have h := (proof_wordLEWithWork_value_26 _ _).mp ht + change OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalDivModWithWork b P).1 ≤ 1 at h + rwa [hv] at h + rw [max_eq_left hq] + rfl + · have hq : 1 ≤ b / P := by + have h := mt (proof_wordLEWithWork_value_26 _ _).mpr ht + change ¬ OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalDivModWithWork b P).1 ≤ 1 at h + rw [hv] at h + exact Nat.le_of_lt (Nat.lt_of_not_ge h) + rw [max_eq_right hq] + exact hv + have proof_seedGridSpacingWithWork_pos_85 (b : ℕ) (P : ℕ) (hP : LT.lt.{0} 0 P) : + 0 < OAI.EditApproximation.bitWordValue (OAI.EditApproximation.seedGridSpacingWithWork b P).1 := by + rw [proof_seedGridSpacingWithWork_value_86 b P hP] + unfold OAI.EditApproximation.seedGridSpacing + omega + exact + let b := 2 ^ e + let spacing := OAI.EditApproximation.seedGridSpacingWithWork b P + let center := OAI.EditApproximation.roundStateWithWork (OAI.EditApproximation.bitWordValue spacing.1) (proof_seedGridSpacingWithWork_pos_85 b P hP) query + let word := parentInitial center.1 + let eligible := OAI.EditApproximation.BinaryFraction.centerEligibilityWithWork b F a word.1 + if eligible.1 then + let sample := integer b center.1 + let selected := OAI.EditApproximation.BinaryFraction.preparedOnlineReadWithWorkRaw source target parent P F exponent H b (Nat.two_pow_pos e) hP + tau eta kappa child initial table R hc hi t center.1 sample.1 + (selected.1, spacing.2 + center.2 + word.2 + eligible.2 + selected.2 + sample.2 + e + 5) + else (none, spacing.2 + center.2 + word.2 + eligible.2 + e + 3) + +def preparedLocalOnlineActionsSourceWithWorkRawBand (N : ℕ) (query : OAI.EditApproximation.TargetInterval target.length) : + List (OAI.EditApproximation.BinaryBellmanAction (OAI.EditApproximation.TargetInterval target.length) + (Fin M × OAI.EditApproximation.TargetInterval target.length) M) × ℕ := + let word := parentInitial query + let scales := OAI.EditApproximation.BinaryFraction.queryExponentsWithWork N F a word.1 + let selected := OAI.EditApproximation.filterMapWithWork + (fun e => OAI.EditApproximation.BinaryFraction.preparedLocalOnlineScaleSourceWithWorkRawBand source target parent P F exponent H hP tau a eta kappa + parentInitial child initial table R hc hi t integer e query) scales.1 + (selected.1, word.2 + scales.2 + selected.2 + 1) + + +end OAI.EditApproximation.BinaryFraction +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BinaryFraction +variable {α : Type u_4} (source target : List α) {M : ℕ} (parent : TargetInterval source.length) (N P F exponent H Q eM eF : ℕ) (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (tau a eta kappa : BinaryFraction) (parentInitial : TargetInterval target.length → BinaryFraction × ℕ) (child initial : Fin M → TargetInterval target.length → BinaryFraction × ℕ) (R : ℕ) (hc : ∀ i r, (child i r).2 ≤ R) (hi : ∀ i r, (initial i r).2 ≤ R) + +def queryOnlineSelectWithWorkRawBand (t : ℕ) + (integer : ℕ → OAI.EditApproximation.TargetInterval target.length → ℕ × ℕ) + (keys : List (Fin M × ℕ × OAI.EditApproximation.TargetInterval target.length)) (words : List OAI.EditApproximation.BinaryFraction) + (q : OAI.EditApproximation.TargetInterval target.length) := + OAI.EditApproximation.BinaryFraction.preparedLocalOnlineActionsSourceWithWorkRawBand source target parent P F exponent H hP tau a eta kappa + parentInitial child initial (OAI.EditApproximation.BinaryFraction.queryHistoryReadWithWork keys words) R hc hi (t - 1) integer N q + +def queryGroupSelectWithWorkRawBand (draw : OAI.EditApproximation.CountedCellGroupDraws M F Q) + (keys : List (Fin M × OAI.EditApproximation.TargetInterval target.length)) (words : List OAI.EditApproximation.BinaryFraction) + (q : OAI.EditApproximation.TargetInterval target.length) := + OAI.EditApproximation.BinaryFraction.preparedLocalCellGroupsSourceWithWorkRawBand source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial (OAI.EditApproximation.BinaryFraction.queryChildReadWithWork keys words) R hc hi N draw q + + +end OAI.EditApproximation.BinaryFraction +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {ι : Type u_4} {α : Type u_5} (source target : List α) {M : ℕ} (parent : TargetInterval source.length) (N P F exponent H Q eM eF : ℕ) (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (tau a eta kappa delta : BinaryFraction) (t : ℕ) (parentInitial : TargetInterval target.length → BinaryFraction × ℕ) (child initial : Fin M → TargetInterval target.length → BinaryFraction × ℕ) (R : ℕ) (hc : ∀ i r, (child i r).2 ≤ R) (hi : ∀ i r, (initial i r).2 ≤ R) (draw : CountedCellGroupDraws M F Q) (integer : ℕ → TargetInterval target.length → ℕ × ℕ) (q : TargetInterval target.length) (readEarlier : (Fin M × ℕ × TargetInterval target.length) → BitQuery ι BinaryFraction) (readCurrent : (Fin M × TargetInterval target.length) → BitQuery ι BinaryFraction) + +def queryLocalRefinementRawBand : OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction := + OAI.EditApproximation.queryRefinementGather source target parent N P F exponent Q eM eF hP hM hF a t parentInitial draw q + readEarlier readCurrent + (fun keys words => OAI.EditApproximation.BinaryFraction.queryOnlineSelectWithWorkRawBand source target parent N P F exponent H hP + tau a eta kappa parentInitial child initial R hc hi t integer keys words q) + (fun keys words => OAI.EditApproximation.BinaryFraction.queryGroupSelectWithWorkRawBand source target parent N P F exponent Q + eM eF hP hM hF tau a parentInitial child initial R hc hi draw keys words q) + (fun earlierKeys earlierWords groups online currentKeys currentWords => + OAI.EditApproximation.BitQuery.compute (OAI.EditApproximation.BinaryFraction.queryRefinementFinishWithWork parent N P F a delta parentInitial + t earlierKeys earlierWords groups online currentKeys currentWords q)) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {ι : Type u_4} {α : Type u_5} (source target : List α) {M : ℕ} [NeZero M] (parent : TargetInterval source.length) (N P F exponent H Q eM eF : ℕ) (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (tau a eta kappa delta : BinaryFraction) (t : ℕ) (parentInitial : TargetInterval target.length → BinaryFraction × ℕ) (child initial : Fin M → TargetInterval target.length → BinaryFraction × ℕ) (R : ℕ) (hc : ∀ i r, (child i r).2 ≤ R) (hi : ∀ i r, (initial i r).2 ≤ R) (q : TargetInterval target.length) (readGroup : GroupScalarKey M F Q → BitQuery ι BinaryFraction) (readInteger : (ℕ × TargetInterval target.length) → ℕ → BitQuery ι BinaryFraction) (readEarlier : (Fin M × ℕ × TargetInterval target.length) → BitQuery ι BinaryFraction) (readCurrent : (Fin M × TargetInterval target.length) → BitQuery ι BinaryFraction) + +def queryLocalRandomSourcesRawBand : OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction := + OAI.EditApproximation.queryGroupSourceGather M N F Q exponent eM eF hM hF a parentInitial q readGroup + fun groupKeys groupWords => + OAI.EditApproximation.queryOnlineSourceGather parent N P F exponent H hP tau a parentInitial child q readInteger + fun onlineKeys onlineWords => + OAI.EditApproximation.queryLocalRefinementRawBand source target parent N P F exponent H Q eM eF hP hM hF + tau a eta kappa delta t parentInitial child initial R hc hi + (OAI.EditApproximation.BinaryFraction.queryGroupDrawReadWithWork groupKeys groupWords) + (OAI.EditApproximation.BinaryFraction.queryOnlineIntegerReadWithWork onlineKeys onlineWords) + q readEarlier readCurrent + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {ι : Type u_4} {α : Type u_5} (source target : List α) {M : ℕ} [NeZero M] (parent : TargetInterval source.length) (N P F exponent H Q eM eF : ℕ) (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (tau a eta kappa delta : BinaryFraction) (t : ℕ) (parentInitial : TargetInterval target.length → BinaryFraction × ℕ) (readMass readInitial : (Fin M × TargetInterval target.length) → BitQuery ι BinaryFraction) (readGroup : GroupScalarKey M F Q → BitQuery ι BinaryFraction) (readInteger : (ℕ × TargetInterval target.length) → ℕ → BitQuery ι BinaryFraction) (q : TargetInterval target.length) (readEarlier : (Fin M × ℕ × TargetInterval target.length) → BitQuery ι BinaryFraction) (readCurrent : (Fin M × TargetInterval target.length) → BitQuery ι BinaryFraction) +open Finset + +def queryLocalBandRawBand : OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction := by + have proof_gatheredWordLookupWithWork_cost_132 {κ : Type 0} (equal : κ → κ → Prod.{0, 0} Bool ℕ) (C : ℕ) (hC : ∀ (a b : κ), LE.le.{0} (equal a b).2 C) (keys : List.{0} κ) (values : List.{0} OAI.EditApproximation.BinaryFraction) (query : κ) : + (OAI.EditApproximation.BinaryFraction.gatheredWordLookupWithWork equal keys values query).2 ≤ 1 + keys.length * (C + 1) := by + induction keys generalizing values with + | nil => simp only [OAI.EditApproximation.BinaryFraction.gatheredWordLookupWithWork, List.length_nil, Nat.zero_mul, Nat.add_zero, le_rfl] + | cons key keys ih => + cases values with + | nil => simp only [OAI.EditApproximation.BinaryFraction.gatheredWordLookupWithWork]; omega + | cons value values => + have hc := hC query key + have hi := ih values + simp only [OAI.EditApproximation.BinaryFraction.gatheredWordLookupWithWork] + split_ifs <;> simp only [List.length_cons, Nat.add_mul, Nat.one_mul] <;> omega + have proof_bitCompareWithWork_cost_133 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).2 ≤ 4 * (left.length + right.length) + 1 := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => simp [OAI.EditApproximation.bitCompareNilLeftWithWork] + | cons b bs ih => + simp only [OAI.EditApproximation.bitCompareNilLeftWithWork, List.length_cons, List.length_nil] at * + omega + | cons a as ih => + cases right with + | nil => + have h := ih [] + simp only [OAI.EditApproximation.bitCompareWithWork, List.length_cons, List.length_nil] at * + omega + | cons b bs => + have h := ih bs + simp only [OAI.EditApproximation.bitCompareWithWork, List.length_cons] at * + omega + have proof_binaryNaturalCompareWithWork_cost_134 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.binaryNaturalCompareWithWork a b).2 ≤ 4 * (Nat.size a + Nat.size b) + 1 := by + simpa only [OAI.EditApproximation.binaryNaturalCompareWithWork, Nat.size_eq_bits_len] using proof_bitCompareWithWork_cost_133 a.bits b.bits + have proof_naturalEqualWithWork_cost_135 (a : ℕ) (b : ℕ) (B : ℕ) (ha : LE.le.{0} a.size B) (hb : LE.le.{0} b.size B) : + (OAI.EditApproximation.naturalEqualWithWork a b).2 ≤ 8 * B + 2 := by + have h := proof_binaryNaturalCompareWithWork_cost_134 a b + change (OAI.EditApproximation.binaryNaturalCompareWithWork a b).2 + 1 ≤ _ + omega + have proof_coordinateEqualWithWork_cost_136 {M : ℕ} {n : ℕ} (a : Prod.{0, 0} (Fin M) (OAI.EditApproximation.TargetInterval n)) (b : Prod.{0, 0} (Fin M) (OAI.EditApproximation.TargetInterval n)) (B : ℕ) (hM : LE.le.{0} M.size B) (hn : LE.le.{0} n.size B) : + (OAI.EditApproximation.coordinateEqualWithWork a b).2 ≤ 24 * B + 8 := by + have hc := proof_naturalEqualWithWork_cost_135 a.1.val b.1.val B + ((Nat.size_le_size a.1.isLt.le).trans hM) ((Nat.size_le_size b.1.isLt.le).trans hM) + have hl := proof_naturalEqualWithWork_cost_135 a.2.lo b.2.lo B + ((Nat.size_le_size (a.2.ordered.trans a.2.valid)).trans hn) + ((Nat.size_le_size (b.2.ordered.trans b.2.valid)).trans hn) + have hh := proof_naturalEqualWithWork_cost_135 a.2.hi b.2.hi B + ((Nat.size_le_size a.2.valid).trans hn) ((Nat.size_le_size b.2.valid).trans hn) + change _ + _ + _ + 2 ≤ _ + omega + have proof_queryChildReadWithWork_cost_137 {M : ℕ} {n : ℕ} (keys : List.{0} (Prod.{0, 0} (Fin M) (OAI.EditApproximation.TargetInterval n))) (values : List.{0} OAI.EditApproximation.BinaryFraction) (i : Fin M) (q : OAI.EditApproximation.TargetInterval n) (B : ℕ) (hM : LE.le.{0} M.size B) (hn : LE.le.{0} n.size B) : + (OAI.EditApproximation.BinaryFraction.queryChildReadWithWork keys values i q).2 ≤ 1 + keys.length * (24 * B + 9) := by + exact proof_gatheredWordLookupWithWork_cost_132 OAI.EditApproximation.coordinateEqualWithWork (24 * B + 8) + (fun a b => proof_coordinateEqualWithWork_cost_136 a b B hM hn) keys values (i, q) + have proof_queryChildReadWithWork_budget_131 {M : ℕ} {n : ℕ} (keys : List.{0} (Prod.{0, 0} (Fin M) (OAI.EditApproximation.TargetInterval n))) (words : List.{0} OAI.EditApproximation.BinaryFraction) (i : Fin M) (r : OAI.EditApproximation.TargetInterval n) : + (OAI.EditApproximation.BinaryFraction.queryChildReadWithWork keys words i r).2 ≤ OAI.EditApproximation.BinaryFraction.queryDataReadBudget M n keys := by + exact proof_queryChildReadWithWork_cost_137 keys words i r _ (Nat.le_max_left _ _) (Nat.le_max_right _ _) + exact + OAI.EditApproximation.queryBandGather M parent N P F exponent hP a parentInitial q readMass readInitial + fun keys massWords initialWords => + OAI.EditApproximation.queryLocalRandomSourcesRawBand source target parent N P F exponent H Q eM eF hP hM hF + tau a eta kappa delta t parentInitial + (OAI.EditApproximation.BinaryFraction.queryChildReadWithWork keys massWords) + (OAI.EditApproximation.BinaryFraction.queryChildReadWithWork keys initialWords) + (OAI.EditApproximation.BinaryFraction.queryDataReadBudget M target.length keys) + (proof_queryChildReadWithWork_budget_131 keys massWords) + (proof_queryChildReadWithWork_budget_131 keys initialWords) + q readGroup readInteger readEarlier readCurrent + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {ι : Type u_4} {α : Type u_5} (source target : List α) {M : ℕ} [NeZero M] (parent : TargetInterval source.length) (N P F exponent H Q eM eF : ℕ) (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (tau a eta kappa delta : BinaryFraction) (t : ℕ) (readParent : TargetInterval target.length → BitQuery ι BinaryFraction) (readMass readInitial : (Fin M × TargetInterval target.length) → BitQuery ι BinaryFraction) (readGroup : GroupScalarKey M F Q → BitQuery ι BinaryFraction) (readInteger : (ℕ × TargetInterval target.length) → ℕ → BitQuery ι BinaryFraction) (q : TargetInterval target.length) (readEarlier : (Fin M × ℕ × TargetInterval target.length) → BitQuery ι BinaryFraction) (readCurrent : (Fin M × TargetInterval target.length) → BitQuery ι BinaryFraction) + +def queryLocalProgramRawBand : OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction := + OAI.EditApproximation.queryInitialGather N P F exponent hP a q readParent fun keys words => + OAI.EditApproximation.queryLocalBandRawBand source target parent N P F exponent H Q eM eF hP hM hF + tau a eta kappa delta t (OAI.EditApproximation.BinaryFraction.queryParentReadWithWork keys words) + readMass readInitial readGroup readInteger q readEarlier readCurrent + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {σ : Type u_4} {α : Type u_5} (source target : List α) {M J : ℕ} [NeZero M] (N P F exponent H Q eM eF : ℕ) (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (tau a eta kappa delta : BinaryFraction) (copies pass copy T S t : ℕ) (ht : 0 < t) (node : PhysicalNode M J) (hbelow : node.1.val < J) (readGroup : GroupScalarKey M F Q → BitQuery σ BinaryFraction) (readInteger : (ℕ × TargetInterval target.length) → ℕ → BitQuery σ BinaryFraction) (q : TargetInterval target.length) + +def queryPhysicalRandomDataRequestRawBand : + OAI.EditApproximation.BitQuery (Sum σ {child : OAI.EditApproximation.PhysicalTableRequest M J target.length // + child.combinedRank T S < (OAI.EditApproximation.PhysicalTableRequest.refinement pass copy node T t q).combinedRank T S}) + OAI.EditApproximation.BinaryFraction := + OAI.EditApproximation.queryLocalProgramRawBand source target (OAI.EditApproximation.physicalSourceInterval source.length node) + N P F exponent H Q eM eF hP hM hF tau a eta kappa delta t + (fun r => OAI.EditApproximation.BitQuery.mapKeysWithWork (fun key => (Sum.inr key, 1)) + (OAI.EditApproximation.queryPhysicalWarmupRead copies pass copy T S t ht node q node le_rfl 0 (Nat.zero_le T) r)) + (fun input => OAI.EditApproximation.BitQuery.mapKeysWithWork (fun key => (Sum.inr key, 1)) + (OAI.EditApproximation.queryPhysicalMassRead copies pass copy T S t ht node hbelow q input)) + (fun input => OAI.EditApproximation.BitQuery.mapKeysWithWork (fun key => (Sum.inr key, 1)) + (OAI.EditApproximation.queryPhysicalWarmupRead copies pass copy T S t ht node q + (OAI.EditApproximation.physicalChild node hbelow input.1) (by change node.1.val ≤ node.1.val + 1; omega) + 0 (Nat.zero_le T) input.2)) + (fun key => OAI.EditApproximation.BitQuery.mapKeysWithWork (fun key => (Sum.inl key, 1)) (readGroup key)) + (fun key range => OAI.EditApproximation.BitQuery.mapKeysWithWork (fun key => (Sum.inl key, 1)) (readInteger key range)) q + (fun input => OAI.EditApproximation.BitQuery.mapKeysWithWork (fun key => (Sum.inr key, 1)) + (OAI.EditApproximation.queryPhysicalEarlierRead copies pass copy T S t node hbelow q input)) + (fun input => OAI.EditApproximation.BitQuery.mapKeysWithWork (fun key => (Sum.inr key, 1)) + (OAI.EditApproximation.queryPhysicalCurrentRead copies pass copy T S t node hbelow q input)) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {α : Type u_4} {M J R : ℕ} [NeZero M] (source target : List α) (N P F exponent H Q eM eF : ℕ) (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (tau a eta kappa delta : BinaryFraction) (passes copies pass copy T S t : ℕ) (ht : 0 < t) (node : PhysicalNode M J) (hbelow : node.1.val < J) (time : Fin R) (q : TargetInterval target.length) + +def queryFamilyRefinementRawBand : + OAI.EditApproximation.BitQuery (Sum (OAI.EditApproximation.PhysicalFamilyScalarKey (M := M) (J := J) (R := R) + target N P F exponent H Q passes copies) + {child : OAI.EditApproximation.PhysicalTableRequest M J target.length // child.combinedRank T S < + (OAI.EditApproximation.PhysicalTableRequest.refinement pass copy node T t q).combinedRank T S}) OAI.EditApproximation.BinaryFraction := + OAI.EditApproximation.queryPhysicalRandomDataRequestRawBand source target N P F exponent H Q eM eF hP hM hF + tau a eta kappa delta copies pass copy T S t ht node hbelow + (OAI.EditApproximation.queryFamilyGroupRead target N P F exponent H Q passes copies pass copy ⟨node, hbelow⟩ time) + (OAI.EditApproximation.queryFamilyOnlineRead target N P F exponent H Q passes copies pass copy ⟨node, hbelow⟩ time) q + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {α : Type u_4} [DecidableEq α] {M J R : ℕ} [NeZero M] [NeZero R] (source target : List α) (N P F exponent H Q eM eF : ℕ) (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (tau a eta kappa delta : BinaryFraction) (T S passes copies : ℕ) (request : PhysicalTableRequest M J target.length) (hindex : T < request.index) (hbelow : request.node.1.val < J) + +def queryFamilyActiveRawBand : + OAI.EditApproximation.BitQuery (Sum (OAI.EditApproximation.PhysicalFamilyScalarKey (M := M) (J := J) (R := R) + target N P F exponent H Q passes copies) + {child : OAI.EditApproximation.PhysicalTableRequest M J target.length // + child.combinedRank T S < request.combinedRank T S}) OAI.EditApproximation.BinaryFraction := by + have proof_active_request_eq_139 {α : Type u_4} {M : ℕ} {J : ℕ} (target : List.{u_4} α) (T : ℕ) (request : OAI.EditApproximation.PhysicalTableRequest M J (List.length.{u_4} target)) (hindex : LT.lt.{0} T request.index) : + OAI.EditApproximation.PhysicalTableRequest.refinement request.pass request.copy request.node T (request.index - T) + request.state = request := by + have hi : T + (request.index - T) = request.index := by omega + unfold OAI.EditApproximation.PhysicalTableRequest.refinement + rw [hi] + have proof_active_request_eqRawBand_138 {α : Type u_4} {M : ℕ} {J : ℕ} (target : List.{u_4} α) (T : ℕ) (request : OAI.EditApproximation.PhysicalTableRequest M J (List.length.{u_4} target)) (hindex : LT.lt.{0} T request.index) : + OAI.EditApproximation.PhysicalTableRequest.refinement request.pass request.copy request.node T (request.index - T) + request.state = request := by + have hi : T + (request.index - T) = request.index := by omega + unfold OAI.EditApproximation.PhysicalTableRequest.refinement + rw [hi] + exact + OAI.EditApproximation.BitQuery.mapKeysWithWork + (fun key => (Sum.map id (fun child => ⟨child.val, by + simpa only [proof_active_request_eqRawBand_138 (target := target) (T := T) (request := request) (hindex := hindex)] using child.property⟩) key, 1)) + (OAI.EditApproximation.queryFamilyRefinementRawBand (R := R) source target N P F exponent H Q eM eF hP hM hF tau a eta kappa delta + passes copies request.pass request.copy T S (request.index - T) (Nat.sub_pos_of_lt hindex) + request.node hbelow (Fin.ofNat R (request.index - T - 1)) request.state) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {α : Type u_4} [DecidableEq α] {M J R : ℕ} [NeZero M] [NeZero R] (source target : List α) (N P F exponent H Q eM eF : ℕ) (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (tau a eta kappa delta : BinaryFraction) (T S passes copies : ℕ) (parent : {r : PhysicalTableRequest M J target.length // r.Bounded (passes + 1) copies T S}) (hindex : T < parent.val.index) (hbelow : parent.val.node.1.val < J) + +def queryFamilyBoundedActiveRawBand : + OAI.EditApproximation.BitQuery (Sum (OAI.EditApproximation.PhysicalFamilyScalarKey (M := M) (J := J) (R := R) + target N P F exponent H Q passes copies) + {child : {r : OAI.EditApproximation.PhysicalTableRequest M J target.length // r.Bounded (passes + 1) copies T S} // + child.val.combinedRank T S < parent.val.combinedRank T S}) OAI.EditApproximation.BinaryFraction := + OAI.EditApproximation.queryRestrictPhysicalBody (passes + 1) copies T S parent + (OAI.EditApproximation.queryFamilyActiveRawBand (R := R) source target N P F exponent H Q eM eF hP hM hF tau a eta kappa delta + T S passes copies parent.val hindex hbelow) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {M J R passes copies T S : ℕ} [NeZero M] [NeZero R] (source target : List ℕ) (N P F exponent H Q eM eF : ℕ) (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (A a : ℕ → BinaryFraction) (tau eta kappa delta : BinaryFraction) (multiplier : ℕ → ℕ) (occurrence : BinaryMemo PositionCounts) (symbolBits positionBits : ℕ) + +def queryChargedFamilyTableRawBand + (parent : {r : OAI.EditApproximation.PhysicalTableRequest M J target.length // r.Bounded (passes + 1) copies T S}) : + OAI.EditApproximation.BitQuery (OAI.EditApproximation.ChargedFamilyQueryKey (R := R) target N P F exponent H Q (.inr parent)) OAI.EditApproximation.BinaryFraction := by + have proof_table_rank_lt_99 {M : ℕ} {J : ℕ} {ny : ℕ} {passes : ℕ} {copies : ℕ} {T : ℕ} {S : ℕ} (parent : Subtype.{1} fun request => OAI.EditApproximation.PhysicalTableRequest.Bounded (M := M) (J := J) (ny := ny) passes copies T S request) (child : Subtype.{1} fun request => OAI.EditApproximation.PhysicalTableRequest.Bounded (M := M) (J := J) (ny := ny) passes copies T S request) (h : LT.lt.{0} (OAI.EditApproximation.PhysicalTableRequest.combinedRank T S child.val) + (OAI.EditApproximation.PhysicalTableRequest.combinedRank T S parent.val)) : + OAI.EditApproximation.ChargedPhysicalRequest.rank (Sum.inr child : OAI.EditApproximation.ChargedPhysicalRequest M J ny passes copies T S) < OAI.EditApproximation.ChargedPhysicalRequest.rank (Sum.inr parent) := by + simpa only [OAI.EditApproximation.ChargedPhysicalRequest.rank, OAI.EditApproximation.ChargedPhysicalRequest.depth, OAI.EditApproximation.ChargedPhysicalRequest.index, ← Nat.add_assoc, OAI.EditApproximation.PhysicalTableRequest.combinedRank] using + Nat.add_lt_add_right h 1 + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_wordLEWithWork_value_26 (a : List.{0} Bool) (b : List.{0} Bool) : + (OAI.EditApproximation.wordLEWithWork a b).1 = true ↔ OAI.EditApproximation.bitWordValue a ≤ OAI.EditApproximation.bitWordValue b := by + simp only [OAI.EditApproximation.wordLEWithWork, Bool.not_eq_true', decide_eq_false_iff_not, + proof_bitCompareWithWork_lt_16, not_lt] + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_queryNaturalLEWithWork_value_140 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.wordLEWithWork a.bits b.bits).1 = true ↔ a ≤ b := by + simp only [proof_wordLEWithWork_value_26, proof_bitWordValue_bits_15] + have proof_binaryNaturalCompareWithWork_lt_53 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.binaryNaturalCompareWithWork a b).1 = .lt ↔ a < b := by + simpa only [OAI.EditApproximation.binaryNaturalCompareWithWork, proof_bitWordValue_bits_15] using proof_bitCompareWithWork_lt_16 a.bits b.bits + exact + let index := OAI.EditApproximation.wordLEWithWork parent.val.index.bits T.bits + .charge (index.2 + 1) + (if hi : index.1 = true then + OAI.EditApproximation.BitQuery.mapKeysWithWork (fun key => (Sum.inr key, 1)) + (OAI.EditApproximation.queryChargedWarmup source target N P F (A parent.val.pass) (a parent.val.pass) multiplier + parent occurrence symbolBits positionBits) + else let depth := OAI.EditApproximation.binaryNaturalCompareWithWork parent.val.node.1.val J + .charge (depth.2 + 1) + (if hb : depth.1 = .lt then + let interval := OAI.EditApproximation.physicalSourceInterval source.length parent.val.node + let length := OAI.EditApproximation.saturatingSubtractWithWork interval.hi interval.lo + let short := OAI.EditApproximation.wordLEWithWork length.1 [true] + .charge (length.2 + short.2 + 1) + (if short.1 then + OAI.EditApproximation.BitQuery.mapKeysWithWork (fun key => (Sum.inr key, 1)) + (OAI.EditApproximation.queryPhysicalInitial source target N P F (A parent.val.pass) (a parent.val.pass) + multiplier parent occurrence symbolBits positionBits parent.val.state) + else OAI.EditApproximation.BitQuery.mapKeysWithWork + (fun key => (Sum.map id (fun child => + ⟨Sum.inr child.val, proof_table_rank_lt_99 parent child.val child.property⟩) + key, 1)) + (OAI.EditApproximation.queryFamilyBoundedActiveRawBand (R := R) source target N P F exponent H Q eM eF hP hM hF + tau (a parent.val.pass) eta kappa delta T S passes copies parent + (Nat.lt_of_not_ge (fun h => hi ((proof_queryNaturalLEWithWork_value_140 parent.val.index T).mpr h))) + ((proof_binaryNaturalCompareWithWork_lt_53 _ _).mp hb))) + else OAI.EditApproximation.BitQuery.mapKeysWithWork (fun key => (Sum.inr key, 1)) + (OAI.EditApproximation.queryPhysicalInitial source target N P F (A parent.val.pass) (a parent.val.pass) + multiplier parent occurrence symbolBits positionBits parent.val.state))) + +def queryChargedFamilyGlobalRawBand + (coarse : OAI.EditApproximation.PhysicalEntry M J target.length → OAI.EditApproximation.BinaryFraction × ℕ) + (request : OAI.EditApproximation.ChargedPhysicalRequest M J target.length (passes + 1) copies T S) : + OAI.EditApproximation.BitQuery (OAI.EditApproximation.ChargedFamilyQueryKey (R := R) target N P F exponent H Q request) OAI.EditApproximation.BinaryFraction := + match request with + | .inl entry => OAI.EditApproximation.BitQuery.compute (coarse entry) + | .inr parent => OAI.EditApproximation.queryChargedFamilyTableRawBand (R := R) source target N P F exponent H Q eM eF hP hM hF + A a tau eta kappa delta multiplier occurrence symbolBits positionBits parent + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {M J R passes copies T S : ℕ} [NeZero M] [NeZero R] (source target : List ℕ) (N P F exponent H Q eM eF : ℕ) (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (A a : ℕ → BinaryFraction) (tau eta kappa delta : BinaryFraction) (multiplier : ℕ → ℕ) (occurrence : BinaryMemo PositionCounts) (symbolBits positionBits : ℕ) (coarse : PhysicalEntry M J target.length → BinaryFraction × ℕ) (draw : PhysicalFamilyScalarDraw (M := M) (J := J) (R := R) + target N P F exponent H Q passes copies) + +def queryFamilyMemoRawRawBand (key : OAI.EditApproximation.QueryFamilyMemoKey (M := M) (J := J) (R := R) (passes := passes) (copies := copies) (T := T) (S := S) target N P F exponent H Q) := + OAI.EditApproximation.SourceRanked.bitBody OAI.EditApproximation.ChargedPhysicalRequest.rank + (OAI.EditApproximation.queryChargedFamilyGlobalRawBand (R := R) source target N P F exponent H Q eM eF hP hM hF + A a tau eta kappa delta multiplier occurrence symbolBits positionBits coarse) + (OAI.EditApproximation.queryFamilySourceWordWithWork target N P F exponent H Q draw) key + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation + +open MeasureTheory ProbabilityTheory + +def computedQueryMemoRawRawBand (source target : List ℕ) (N : ℕ) + (occurrence : OAI.EditApproximation.BinaryMemo OAI.EditApproximation.PositionCounts) (symbolBits positionBits : ℕ) + (input : OAI.EditApproximation.ComputedFamilyInput source target N) (key : OAI.EditApproximation.ComputedFamilyMemoKey source target N) := by + have proof_computedParameterP_pos_141 (N : ℕ) : 0 < (OAI.EditApproximation.integerParameters N).P := + Nat.pow_pos (Nat.two_pow_pos _) + exact + OAI.EditApproximation.queryFamilyMemoRawRawBand source target N (OAI.EditApproximation.integerParameters N).P (OAI.EditApproximation.inputSmallLog N) + (40 * OAI.EditApproximation.smallLogExponent N) (OAI.EditApproximation.inputHeight N) (OAI.EditApproximation.inputSmallLog N ^ 80) + (OAI.EditApproximation.heightExponent N / 20) (OAI.EditApproximation.smallLogExponent N) (proof_computedParameterP_pos_141 N) rfl rfl + (fun pass => (OAI.EditApproximation.scheduledSeedWordWithWork N pass).1) + (fun pass => (OAI.EditApproximation.computedQueryParameters N pass).factor) + (OAI.EditApproximation.computedQueryParameters N 0).tau (OAI.EditApproximation.computedQueryParameters N 0).eta + (OAI.EditApproximation.computedQueryParameters N 0).kappa (OAI.EditApproximation.computedQueryParameters N 0).delta + (OAI.EditApproximation.scheduledSeedMultiplier N) occurrence symbolBits positionBits + (fun entry => (OAI.EditApproximation.BinaryFraction.nat (OAI.EditApproximation.clampedSeedNat input.1 entry), 0)) input.2 key + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation + + +def computedQueryMemoNormalizedRawBand (source target : List ℕ) (N : ℕ) + (occurrence : OAI.EditApproximation.BinaryMemo OAI.EditApproximation.PositionCounts) (symbolBits positionBits : ℕ) + (input : OAI.EditApproximation.ComputedFamilyInput source target N) : + (key : OAI.EditApproximation.ComputedFamilyMemoKey source target N) → OAI.EditApproximation.BitQuery + {child : OAI.EditApproximation.ComputedFamilyMemoKey source target N // + OAI.EditApproximation.SourceRanked.rank OAI.EditApproximation.ChargedPhysicalRequest.rank child < OAI.EditApproximation.SourceRanked.rank OAI.EditApproximation.ChargedPhysicalRequest.rank key} + OAI.EditApproximation.BinaryFraction := by + have proof_trimBitWordWithWork_value_6 (bits : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.trimBitWordWithWork bits).1 = OAI.EditApproximation.bitWordValue bits := by + induction bits with + | nil => rfl + | cons bit bits ih => + simp only [OAI.EditApproximation.trimBitWordWithWork] + split_ifs with h + · have ht : OAI.EditApproximation.bitWordValue bits = 0 := by rw [← ih, h.1]; rfl + simp [h.2, OAI.EditApproximation.bitWordValue, ht] + · (simp only [OAI.EditApproximation.bitWordValue, ih]) + have proof_bitAdder_value_1 (a : Bool) (b : Bool) (carry : Bool) : + (OAI.EditApproximation.bitSum a b carry).toNat + 2 * (OAI.EditApproximation.bitCarry a b carry).toNat = + a.toNat + b.toNat + carry.toNat := by + cases a <;> cases b <;> cases carry <;> decide + have proof_bitAddWithWork_value_2 (left : List.{0} Bool) (right : List.{0} Bool) (carry : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitAddWithWork left right carry).1 = + OAI.EditApproximation.bitWordValue left + OAI.EditApproximation.bitWordValue right + carry.toNat := by + induction left generalizing right carry with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork] + induction right generalizing carry with + | nil => cases carry <;> simp [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue] + | cons b bs ih => + simp only [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 false b carry + simp only [Bool.toNat_false] at h + omega + | cons a as ih => + cases right with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a false carry + simp only [Bool.toNat_false] at h + omega + | cons b bs => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a b carry + omega + have proof_bitMulWithWork_value_0 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitMulWithWork left right).1 = OAI.EditApproximation.bitWordValue left * OAI.EditApproximation.bitWordValue right := by + induction left with + | nil => simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue] + | cons bit bits ih => + cases bit <;> simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue, proof_bitAddWithWork_value_2, ih] <;> ring + have proof_bitPowerWithWork_value_76 (base : List.{0} Bool) (n : ℕ) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitPowerWithWork base n).1 = OAI.EditApproximation.bitWordValue base ^ n := by + induction n with + | zero => (simp [OAI.EditApproximation.bitPowerWithWork, OAI.EditApproximation.bitWordValue]) + | succ n ih => + simp only [OAI.EditApproximation.bitPowerWithWork, proof_trimBitWordWithWork_value_6, proof_bitMulWithWork_value_0, ih, pow_succ] + have proof_refinementBaseWithWork_value_143 (ell : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.refinementBaseWithWork ell).1 = OAI.EditApproximation.bitWordValue ell ^ 10 + 1 := by + (simp only [OAI.EditApproximation.refinementBaseWithWork, proof_trimBitWordWithWork_value_6, proof_bitAddWithWork_value_2, + proof_bitPowerWithWork_value_76, OAI.EditApproximation.bitWordValue, Bool.toNat_true, Bool.toNat_false]) + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_computedQueryBase_value_144 (N : ℕ) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.computedQueryBase N) = OAI.EditApproximation.inputSmallLog N ^ 10 + 1 := by + simp only [OAI.EditApproximation.computedQueryBase, proof_refinementBaseWithWork_value_143, proof_bitWordValue_bits_15] + have proof_computedQueryBase_pos_142 (N : ℕ) : 0 < OAI.EditApproximation.bitWordValue (OAI.EditApproximation.computedQueryBase N) := by + rw [proof_computedQueryBase_value_144] + omega + exact + OAI.EditApproximation.rankedNormalizeBody (OAI.EditApproximation.SourceRanked.rank OAI.EditApproximation.ChargedPhysicalRequest.rank) + (OAI.EditApproximation.computedQueryMemoRawRawBand source target N occurrence symbolBits positionBits input) + (OAI.EditApproximation.computedQueryBase N) (proof_computedQueryBase_pos_142 N) + (OAI.EditApproximation.queryFamilyMemoRemaining target N (OAI.EditApproximation.integerParameters N).P (OAI.EditApproximation.inputSmallLog N) + (40 * OAI.EditApproximation.smallLogExponent N) (OAI.EditApproximation.inputHeight N) (OAI.EditApproximation.inputSmallLog N ^ 80)) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +attribute [local instance] queryRoundsNeZero + +def computedQueryMemoResultRawBand (source target : List ℕ) (N : ℕ) + (occurrence : OAI.EditApproximation.BinaryMemo OAI.EditApproximation.PositionCounts) (symbolBits positionBits : ℕ) + (input : OAI.EditApproximation.ComputedFamilyInput source target N) := + OAI.EditApproximation.rankedBitMemoEvaluate (OAI.EditApproximation.SourceRanked.rank OAI.EditApproximation.ChargedPhysicalRequest.rank) + (OAI.EditApproximation.computedQueryMemoNormalizedRawBand source target N occurrence symbolBits positionBits input) + (16384 * OAI.EditApproximation.inputHeight N + 5) (OAI.EditApproximation.computedFamilyMemoCode source target N (OAI.EditApproximation.inputHeight N ^ 2)) + (.inr (OAI.EditApproximation.localFinalRootRequest target N (OAI.EditApproximation.integerParameters N).T (OAI.EditApproximation.integerParameters N).S + (OAI.EditApproximation.inputHeight N) (Nat.two_pow_pos _) (OAI.EditApproximation.finalTargetState target.length))) .empty + +def computedQueryLocalWorkRawBand (source target : List ℕ) (N : ℕ) + (occurrence : OAI.EditApproximation.BinaryMemo OAI.EditApproximation.PositionCounts) (symbolBits positionBits : ℕ) + (input : OAI.EditApproximation.ComputedFamilyInput source target N) : OAI.EditApproximation.ComputedFamilyMemoKey source target N → ℕ := + OAI.EditApproximation.rankedBitLocalWork (OAI.EditApproximation.SourceRanked.rank OAI.EditApproximation.ChargedPhysicalRequest.rank) + (OAI.EditApproximation.computedQueryMemoNormalizedRawBand source target N occurrence symbolBits positionBits input) + +def computedQueryAnswerWithWorkRawBand (source target : List ℕ) (N : ℕ) + (occurrence : OAI.EditApproximation.BinaryMemo OAI.EditApproximation.PositionCounts) (symbolBits positionBits : ℕ) + (input : OAI.EditApproximation.ComputedFamilyInput source target N) : List Bool × ℕ := + if source = target then ([], source.length + target.length + 1) + else let result := OAI.EditApproximation.computedQueryMemoResultRawBand source target N occurrence symbolBits positionBits input + let answer := OAI.EditApproximation.BinaryFraction.finalAnswerWithWork N result.value + (answer.1, answer.2 + source.length + target.length + 1) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open Filter MeasureTheory + +def integerQueryLocalWorkRawBand (source target : List ℤ) (N : ℕ) := + OAI.EditApproximation.computedQueryLocalWorkRawBand (source.map OAI.EditApproximation.integerSymbolCode) (target.map OAI.EditApproximation.integerSymbolCode) N + (OAI.EditApproximation.integerOccurrenceIndex source target) (OAI.EditApproximation.integerInputSymbolBits source target) (OAI.EditApproximation.integerInputPositionBits target) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation + + +def integerBinaryOutputRawBand (source target : List ℤ) (N : ℕ) + (input : OAI.EditApproximation.ComputedFamilyInput (source.map OAI.EditApproximation.integerSymbolCode) (target.map OAI.EditApproximation.integerSymbolCode) N) := + OAI.EditApproximation.computedQueryAnswerWithWorkRawBand (source.map OAI.EditApproximation.integerSymbolCode) (target.map OAI.EditApproximation.integerSymbolCode) N + (OAI.EditApproximation.integerOccurrenceIndex source target) (OAI.EditApproximation.integerInputSymbolBits source target) (OAI.EditApproximation.integerInputPositionBits target) input + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open MeasureTheory + +noncomputable def integerBinaryAnswerRawBand (source target : List ℤ) (N : ℕ) (epsilon : OAI.EditApproximation.BinaryFraction) + (outcome : OAI.EditApproximation.ComputedFullOutcome (source.map OAI.EditApproximation.integerSymbolCode) (target.map OAI.EditApproximation.integerSymbolCode) N) : ℕ := + if OAI.EditApproximation.physicalLargeInput N epsilon then + match outcome with + | .inl _ => OAI.EditApproximation.exactSuffixAnswer (source.map OAI.EditApproximation.integerSymbolCode) (target.map OAI.EditApproximation.integerSymbolCode) + | .inr execution => OAI.EditApproximation.bitWordValue (OAI.EditApproximation.integerBinaryOutputRawBand source target N + (OAI.EditApproximation.computedExecutionAccepted _ _ N execution)).1 + else OAI.EditApproximation.exactSuffixAnswer (source.map OAI.EditApproximation.integerSymbolCode) (target.map OAI.EditApproximation.integerSymbolCode) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BinaryFraction +variable {α : Type u_4} (source target : List α) {M : ℕ} (parent : TargetInterval source.length) (P F exponent Q eM eF : ℕ) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (hP : 0 < P) (tau a : BinaryFraction) (parentInitial : TargetInterval target.length → BinaryFraction × ℕ) (child initial current : Fin M → TargetInterval target.length → BinaryFraction × ℕ) (R : ℕ) (hc : ∀ i q, (child i q).2 ≤ R) (hi : ∀ i q, (initial i q).2 ≤ R) (parentAllocation : TargetInterval target.length → ℕ) (childAllocation initialAllocation currentAllocation : Fin M → TargetInterval target.length → ℕ) +open Finset + +def preparedComputedCellSourceAllocationRawBand (b eb : ℕ) (hb : b = 2 ^ eb) + (draw : OAI.EditApproximation.cellScaleReadDraw M b Q (OAI.EditApproximation.BinaryFraction.nat F).value) + (drawAllocation : ∀ t : Fin (OAI.EditApproximation.groupDyadicScales M b (OAI.EditApproximation.BinaryFraction.nat F).value).length, + Fin (OAI.EditApproximation.groupSampleCount M Q b (OAI.EditApproximation.groupDyadicScaleAt M b (OAI.EditApproximation.BinaryFraction.nat F).value t)) → ℕ) + (cell : ℕ × ℕ) : ℕ := by + have proof_representation_value_32 (a : OAI.EditApproximation.BinaryFraction) : a.representation.value = a.value := rfl + have proof_eq_of_num_den_33 {a : OAI.EditApproximation.UnreducedRational} {b : OAI.EditApproximation.UnreducedRational} (hnum : Eq.{1} a.num b.num) (hden : Eq.{1} a.den b.den) : a = b := by + cases a + cases b + cases hnum + cases hden + rfl + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_value_ofInt_46 (a : ℤ) : (OAI.EditApproximation.SignedBinary.ofInt a).value = a := by + by_cases h : a < 0 + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_true, + ↓reduceIte] using (Int.eq_neg_natAbs_of_nonpos (le_of_lt h)).symm + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_false, + Bool.false_eq_true, ↓reduceIte] using (Int.eq_natAbs_of_nonneg (le_of_not_gt h)).symm + have proof_nat_representation_47 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).representation = OAI.EditApproximation.UnreducedRational.nat n := by + apply proof_eq_of_num_den_33 + · change (OAI.EditApproximation.SignedBinary.ofInt (n : ℤ)).value = (n : ℤ) + exact proof_value_ofInt_46 _ + · rfl + have proof_value_nat_48 (n : ℕ) : (OAI.EditApproximation.UnreducedRational.nat n).value = n := by (simp [OAI.EditApproximation.UnreducedRational.nat, OAI.EditApproximation.UnreducedRational.value]) + have proof_nat_value_49 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).value = (n : ℚ) := by + rw [← proof_representation_value_32, proof_nat_representation_47, proof_value_nat_48] + have proof_arithmeticMapWithWork_value_70 {α : Type 0} {β : Type 0} (f : α → Prod.{0, 0} β ℕ) (values : List.{0} α) : + (OAI.EditApproximation.arithmeticMapWithWork f values).1 = values.map (fun a => (f a).1) := by + induction values with + | nil => rfl + | cons a rest ih => simp only [OAI.EditApproximation.arithmeticMapWithWork, ih, List.map_cons] + have proof_powerTwoWord_value_13 (n : ℕ) : OAI.EditApproximation.bitWordValue (OAI.EditApproximation.powerTwoWord n) = 2 ^ n := by + induction n with + | zero => (simp [OAI.EditApproximation.powerTwoWord, OAI.EditApproximation.bitWordValue]) + | succ n ih => + (simp only [OAI.EditApproximation.powerTwoWord, List.replicate_succ, List.cons_append, OAI.EditApproximation.bitWordValue, + Bool.toNat_false, zero_add] at *) + rw [ih, pow_succ] + omega + have proof_inversePowerTwo_value_89 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.inversePowerTwo n).value = (2 : ℚ) ^ (-(n : ℤ)) := by + (simp only [OAI.EditApproximation.BinaryFraction.inversePowerTwo, OAI.EditApproximation.BinaryFraction.value, OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, Bool.false_eq_true, + ↓reduceIte, OAI.EditApproximation.bitWordValue, Bool.toNat_true, + Int.cast_natCast, proof_powerTwoWord_value_13, Nat.cast_pow, Nat.cast_ofNat, zpow_neg, zpow_natCast]) + norm_num [one_div] + have proof_signedPowerTwoWithWork_value_90 (e : ℤ) : + (OAI.EditApproximation.BinaryFraction.signedPowerTwoWithWork e).1.value = (2 : ℚ) ^ e := by + unfold OAI.EditApproximation.BinaryFraction.signedPowerTwoWithWork + split_ifs with h + · change (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.powerTwoWord e.toNat) : ℚ) / 1 = (2 : ℚ) ^ e + rw [div_one, proof_powerTwoWord_value_13, Nat.cast_pow, Nat.cast_ofNat, ← zpow_natCast, + Int.toNat_of_nonneg h] + · rw [proof_inversePowerTwo_value_89, Int.toNat_of_nonneg + (show 0 ≤ -e from neg_nonneg.mpr (le_of_lt (lt_of_not_ge h))), neg_neg] + have proof_groupScalesWithWork_value_91 (eM : ℕ) (eb : ℕ) (eF : ℕ) : + ((OAI.EditApproximation.BinaryFraction.groupScalesWithWork eM eb eF).1.map OAI.EditApproximation.BinaryFraction.value) = + OAI.EditApproximation.groupDyadicScales (2 ^ eM) (2 ^ eb) ((2 : ℚ) ^ eF) := by + have hlower : ((2 ^ eb : ℕ) : ℚ) / (2 ^ eM : ℕ) = (2 : ℚ) ^ ((eb : ℤ) - eM) := by + rw [Nat.cast_pow, Nat.cast_pow, Nat.cast_ofNat, zpow_sub₀ (by norm_num : (2 : ℚ) ≠ 0), + zpow_natCast, zpow_natCast] + have hupper : (64 : ℚ) * (2 : ℚ) ^ eF * (2 ^ eb : ℕ) = + (2 : ℚ) ^ ((6 + eF + eb : ℕ) : ℤ) := by + rw [Nat.cast_pow, Nat.cast_ofNat, zpow_natCast, pow_add, pow_add] + norm_num + have hlog : Int.log 2 ((2 : ℚ) ^ ((6 + eF + eb : ℕ) : ℤ)) = ((6 + eF + eb : ℕ) : ℤ) := by + simpa only [Nat.cast_ofNat] using Int.log_zpow (R := ℚ) (by decide : 1 < 2) ((6 + eF + eb : ℕ) : ℤ) + have hclog : Int.clog 2 ((2 : ℚ) ^ ((eb : ℤ) - eM)) = (eb : ℤ) - eM := by + simpa only [Nat.cast_ofNat] using Int.clog_zpow (R := ℚ) (by decide : 1 < 2) ((eb : ℤ) - eM) + simp only [OAI.EditApproximation.BinaryFraction.groupScalesWithWork, proof_arithmeticMapWithWork_value_70, List.map_map, + Function.comp_def, proof_signedPowerTwoWithWork_value_90, OAI.EditApproximation.groupDyadicScales, hlower, hupper, hlog, hclog] + have proof_computedGroupScales_value_87 (M : ℕ) (b : ℕ) (F : ℕ) (eM : ℕ) (eb : ℕ) (eF : ℕ) (hM : Eq.{1} M (HPow.hPow.{0, 0, 0} 2 eM)) (hb : Eq.{1} b (HPow.hPow.{0, 0, 0} 2 eb)) (hF : Eq.{1} F (HPow.hPow.{0, 0, 0} 2 eF)) : + (OAI.EditApproximation.BinaryFraction.groupScalesWithWork eM eb eF).1.map OAI.EditApproximation.BinaryFraction.value = OAI.EditApproximation.groupDyadicScales M b (OAI.EditApproximation.BinaryFraction.nat F).value := by + rw [proof_nat_value_49, hM, hb, hF, Nat.cast_pow, Nat.cast_ofNat] + exact proof_groupScalesWithWork_value_91 eM eb eF + exact + OAI.EditApproximation.BinaryFraction.groupScalesAllocation eM eb eF + + OAI.EditApproximation.BinaryFraction.preparedCellGroupSourceAllocationRaw source target parent b P F exponent Q + (by rw [hb]; exact Nat.two_pow_pos eb) hP tau a parentInitial child initial current + R R hc hi (OAI.EditApproximation.BinaryFraction.groupScalesWithWork eM eb eF).1 (proof_computedGroupScales_value_87 M b F eM eb eF hM hb hF) + draw parentAllocation childAllocation initialAllocation currentAllocation drawAllocation cell + + +end OAI.EditApproximation.BinaryFraction +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BinaryFraction +variable {α : Type*} (source target : List α) {M : ℕ} (parent : TargetInterval source.length) (P F exponent Q eM eF : ℕ) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (hP : 0 < P) (tau a : BinaryFraction) (parentInitial : TargetInterval target.length → BinaryFraction × ℕ) (child initial current : Fin M → TargetInterval target.length → BinaryFraction × ℕ) (R : ℕ) (hc : ∀ i q, (child i q).2 ≤ R) (hi : ∀ i q, (initial i q).2 ≤ R) (parentAllocation : TargetInterval target.length → ℕ) (childAllocation initialAllocation currentAllocation : Fin M → TargetInterval target.length → ℕ) +variable (draw : CellGroupReadDraws M F Q) (drawAllocation : CellGroupSourceAllocations M F Q) +open Finset + +def castGroupSourceAllocationRawBand (b : ℕ) (cell : ℕ × ℕ) : + ∀ t : Fin (OAI.EditApproximation.groupDyadicScales M b (OAI.EditApproximation.BinaryFraction.nat F).value).length, + Fin (OAI.EditApproximation.groupSampleCount M Q b (OAI.EditApproximation.groupDyadicScaleAt M b (OAI.EditApproximation.BinaryFraction.nat F).value t)) → ℕ := by + have proof_representation_value_32 (a : OAI.EditApproximation.BinaryFraction) : a.representation.value = a.value := rfl + have proof_eq_of_num_den_33 {a : OAI.EditApproximation.UnreducedRational} {b : OAI.EditApproximation.UnreducedRational} (hnum : Eq.{1} a.num b.num) (hden : Eq.{1} a.den b.den) : a = b := by + cases a + cases b + cases hnum + cases hden + rfl + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_value_ofInt_46 (a : ℤ) : (OAI.EditApproximation.SignedBinary.ofInt a).value = a := by + by_cases h : a < 0 + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_true, + ↓reduceIte] using (Int.eq_neg_natAbs_of_nonpos (le_of_lt h)).symm + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_false, + Bool.false_eq_true, ↓reduceIte] using (Int.eq_natAbs_of_nonneg (le_of_not_gt h)).symm + have proof_nat_representation_47 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).representation = OAI.EditApproximation.UnreducedRational.nat n := by + apply proof_eq_of_num_den_33 + · change (OAI.EditApproximation.SignedBinary.ofInt (n : ℤ)).value = (n : ℤ) + exact proof_value_ofInt_46 _ + · rfl + have proof_value_nat_48 (n : ℕ) : (OAI.EditApproximation.UnreducedRational.nat n).value = n := by (simp [OAI.EditApproximation.UnreducedRational.nat, OAI.EditApproximation.UnreducedRational.value]) + have proof_nat_value_49 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).value = (n : ℚ) := by + rw [← proof_representation_value_32, proof_nat_representation_47, proof_value_nat_48] + exact + Eq.mpr (congrArg (fun f => ∀ t : Fin (OAI.EditApproximation.groupDyadicScales M b f).length, + Fin (OAI.EditApproximation.groupSampleCount M Q b (OAI.EditApproximation.groupDyadicScaleAt M b f t)) → ℕ) (proof_nat_value_49 F)) (drawAllocation b cell) + + +end OAI.EditApproximation.BinaryFraction +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BinaryFraction +variable {α : Type u_4} (source target : List α) {M : ℕ} (parent : TargetInterval source.length) (P F exponent Q eM eF : ℕ) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (hP : 0 < P) (tau a : BinaryFraction) (parentInitial : TargetInterval target.length → BinaryFraction × ℕ) (child initial current : Fin M → TargetInterval target.length → BinaryFraction × ℕ) (R : ℕ) (hc : ∀ i q, (child i q).2 ≤ R) (hi : ∀ i q, (initial i q).2 ≤ R) (parentAllocation : TargetInterval target.length → ℕ) (childAllocation initialAllocation currentAllocation : Fin M → TargetInterval target.length → ℕ) +variable (draw : CellGroupReadDraws M F Q) (drawAllocation : CellGroupSourceAllocations M F Q) +open Finset + +def preparedLocalGroupScaleSourceAllocationRawBand (eb : ℕ) (query : OAI.EditApproximation.TargetInterval target.length) : ℕ := by + have proof_representation_value_32 (a : OAI.EditApproximation.BinaryFraction) : a.representation.value = a.value := rfl + have proof_eq_of_num_den_33 {a : OAI.EditApproximation.UnreducedRational} {b : OAI.EditApproximation.UnreducedRational} (hnum : Eq.{1} a.num b.num) (hden : Eq.{1} a.den b.den) : a = b := by + cases a + cases b + cases hnum + cases hden + rfl + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_value_ofInt_46 (a : ℤ) : (OAI.EditApproximation.SignedBinary.ofInt a).value = a := by + by_cases h : a < 0 + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_true, + ↓reduceIte] using (Int.eq_neg_natAbs_of_nonpos (le_of_lt h)).symm + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_false, + Bool.false_eq_true, ↓reduceIte] using (Int.eq_natAbs_of_nonneg (le_of_not_gt h)).symm + have proof_nat_representation_47 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).representation = OAI.EditApproximation.UnreducedRational.nat n := by + apply proof_eq_of_num_den_33 + · change (OAI.EditApproximation.SignedBinary.ofInt (n : ℤ)).value = (n : ℤ) + exact proof_value_ofInt_46 _ + · rfl + have proof_value_nat_48 (n : ℕ) : (OAI.EditApproximation.UnreducedRational.nat n).value = n := by (simp [OAI.EditApproximation.UnreducedRational.nat, OAI.EditApproximation.UnreducedRational.value]) + have proof_nat_value_49 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).value = (n : ℚ) := by + rw [← proof_representation_value_32, proof_nat_representation_47, proof_value_nat_48] + exact + let b := 2 ^ eb + let side := (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) (OAI.EditApproximation.BinaryFraction.nat b)).1 + let radius := (OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork (parentInitial query).1).1 + let cells := (OAI.EditApproximation.BinaryFraction.targetCellsWithWork side (OAI.EditApproximation.bitWordValue radius) query).1 + parentAllocation query + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) (OAI.EditApproximation.BinaryFraction.nat b) + + OAI.EditApproximation.BinaryFraction.naturalCeilingAllocation (parentInitial query).1 + OAI.EditApproximation.BinaryFraction.targetCellsAllocation side (OAI.EditApproximation.bitWordValue radius) query + + OAI.EditApproximation.filterMapAllocation (fun cell => + OAI.EditApproximation.BinaryFraction.preparedComputedCellSourceWithWorkRawBand source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial current R hc hi b eb rfl + (Eq.mpr (congrArg (OAI.EditApproximation.cellScaleReadDraw M b Q) (proof_nat_value_49 F)) (draw b cell)) cell) + (fun cell => OAI.EditApproximation.BinaryFraction.preparedComputedCellSourceAllocationRawBand source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial current R hc hi parentAllocation childAllocation initialAllocation currentAllocation + b eb rfl (Eq.mpr (congrArg (OAI.EditApproximation.cellScaleReadDraw M b Q) (proof_nat_value_49 F)) (draw b cell)) + (OAI.EditApproximation.BinaryFraction.castGroupSourceAllocationRawBand F Q drawAllocation b cell) cell) cells + eb + + +end OAI.EditApproximation.BinaryFraction +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BinaryFraction +variable {α : Type u_4} (source target : List α) {M : ℕ} (parent : TargetInterval source.length) (P F exponent Q eM eF : ℕ) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (hP : 0 < P) (tau a : BinaryFraction) (parentInitial : TargetInterval target.length → BinaryFraction × ℕ) (child initial current : Fin M → TargetInterval target.length → BinaryFraction × ℕ) (R : ℕ) (hc : ∀ i q, (child i q).2 ≤ R) (hi : ∀ i q, (initial i q).2 ≤ R) (parentAllocation : TargetInterval target.length → ℕ) (childAllocation initialAllocation currentAllocation : Fin M → TargetInterval target.length → ℕ) +variable (draw : CellGroupReadDraws M F Q) (drawAllocation : CellGroupSourceAllocations M F Q) + +def localGroupSourceScaleBlockRawBand (eb : ℕ) (query : OAI.EditApproximation.TargetInterval target.length) : + List (OAI.EditApproximation.BinaryBellmanAction (OAI.EditApproximation.TargetInterval target.length) (Fin M × OAI.EditApproximation.TargetInterval target.length) M) × ℕ := + let guard := OAI.EditApproximation.BinaryFraction.refinementScaleGuardWithWork F (2 ^ eb) a (parentInitial query).1 + if guard.1 then + let selected := OAI.EditApproximation.BinaryFraction.preparedLocalGroupScaleSourceWithWorkRawBand source target parent P F exponent Q eM eF + hM hF hP tau a parentInitial child initial current R hc hi eb draw query + (selected.1, guard.2 + selected.2 + eb + 4) + else ([], guard.2 + eb + 4) + +def localGroupSourceScaleBlockAllocationRawBand (eb : ℕ) (query : OAI.EditApproximation.TargetInterval target.length) : ℕ := + OAI.EditApproximation.BinaryFraction.refinementScaleGuardAllocation F (2 ^ eb) a (parentInitial query).1 + eb + + if (OAI.EditApproximation.BinaryFraction.refinementScaleGuardWithWork F (2 ^ eb) a (parentInitial query).1).1 then + OAI.EditApproximation.BinaryFraction.preparedLocalGroupScaleSourceAllocationRawBand source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial current R hc hi parentAllocation childAllocation initialAllocation currentAllocation + draw drawAllocation eb query + else 0 + +def preparedLocalCellGroupsSourceAllocationRawBand (N : ℕ) (query : OAI.EditApproximation.TargetInterval target.length) : ℕ := + let count := max 1 N.bits.length + parentAllocation query + count + N.bits.length + + OAI.EditApproximation.arithmeticFlatMapAllocation + (fun eb => OAI.EditApproximation.BinaryFraction.localGroupSourceScaleBlockRawBand source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial current R hc hi draw eb query) + (fun eb => OAI.EditApproximation.BinaryFraction.localGroupSourceScaleBlockAllocationRawBand source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial current R hc hi parentAllocation childAllocation initialAllocation currentAllocation + draw drawAllocation eb query) (List.range count) + + +end OAI.EditApproximation.BinaryFraction +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BinaryFraction +variable {α : Type u_4} (source target : List α) {M : ℕ} (parent : TargetInterval source.length) (P F exponent H : ℕ) (hP : 0 < P) (tau a eta kappa : BinaryFraction) (parentInitial : TargetInterval target.length → BinaryFraction × ℕ) (child initial : Fin M → TargetInterval target.length → BinaryFraction × ℕ) (table : ℕ → Fin M × TargetInterval target.length → BinaryFraction × ℕ) (R : ℕ) (hc : ∀ i q, (child i q).2 ≤ R) (hi : ∀ i q, (initial i q).2 ≤ R) (t : ℕ) (integer : ℕ → TargetInterval target.length → ℕ × ℕ) (parentAllocation : TargetInterval target.length → ℕ) (childAllocation initialAllocation : Fin M → TargetInterval target.length → ℕ) (tableAllocation : ℕ → Fin M × TargetInterval target.length → ℕ) (integerAllocation : ℕ → TargetInterval target.length → ℕ) + +def preparedLocalOnlineScaleSourceAllocationRawBand (e : ℕ) (query : OAI.EditApproximation.TargetInterval target.length) : ℕ := by + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_bitSubtractor_value_17 (a : Bool) (b : Bool) (borrow : Bool) : + a.toNat + 2 * (OAI.EditApproximation.bitBorrow a b borrow).toNat = + b.toNat + borrow.toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat := by + cases a <;> cases b <;> cases borrow <;> decide + have proof_bitSubtractionRippleEquation_18 (a : ℕ) (b : ℕ) (borrow : ℕ) (nextBorrow : ℕ) (difference : ℕ) (left : ℕ) (right : ℕ) (result : ℕ) (tail : ℕ) (htail : Eq.{1} (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} result right) nextBorrow) (HAdd.hAdd.{0, 0, 0} left tail)) (hbit : Eq.{1} (HAdd.hAdd.{0, 0, 0} a (HMul.hMul.{0, 0, 0} 2 nextBorrow)) + (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} b borrow) difference)) : + (difference + 2 * result) + (b + 2 * right) + borrow = + (a + 2 * left) + 2 * tail := by + omega + have proof_bitSubtractWithWork_value_19 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right borrow).1 + OAI.EditApproximation.bitWordValue right + borrow.toNat = + OAI.EditApproximation.bitWordValue left + 2 ^ max left.length right.length * + (OAI.EditApproximation.bitSubtractWithWork left right borrow).2.1.toNat := by + induction left generalizing right borrow with + | nil => + induction right generalizing borrow with + | nil => (simp [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + have h := ih (OAI.EditApproximation.bitBorrow false b borrow) + have hb := proof_bitSubtractor_value_17 false b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue, + List.length_nil, List.length_cons, Nat.zero_max, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 0 b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow false b borrow).toNat + (OAI.EditApproximation.bitDifference false b borrow).toNat 0 (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).1) + (2 ^ bs.length * (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons a as ih => + cases right with + | nil => + have h := ih [] (OAI.EditApproximation.bitBorrow a false borrow) + have hb := proof_bitSubtractor_value_17 a false borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_nil, List.length_cons, + Nat.max_zero, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat 0 borrow.toNat (OAI.EditApproximation.bitBorrow a false borrow).toNat + (OAI.EditApproximation.bitDifference a false borrow).toNat (OAI.EditApproximation.bitWordValue as) 0 + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).1) + (2 ^ as.length * (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons b bs => + have h := ih bs (OAI.EditApproximation.bitBorrow a b borrow) + have hb := proof_bitSubtractor_value_17 a b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_cons, Nat.succ_max_succ, + pow_succ] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow a b borrow).toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).1) + (2 ^ max as.length bs.length * (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_assoc, Nat.mul_left_comm] using hs + have proof_bitWordValue_lt_pow_length_20 (bits : List.{0} Bool) : OAI.EditApproximation.bitWordValue bits < 2 ^ bits.length := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitWordValue]) + | cons bit bits ih => + cases bit <;> (simp only [OAI.EditApproximation.bitWordValue, List.length_cons, pow_succ, Bool.toNat_false, Bool.toNat_true]) <;> omega + have proof_bitSubtractWithWork_length_21 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + (OAI.EditApproximation.bitSubtractWithWork left right borrow).1.length = max left.length right.length := by + induction left generalizing right borrow with + | nil => + simp only [OAI.EditApproximation.bitSubtractWithWork] + induction right generalizing borrow with + | nil => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork] + | cons b bs ih => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork, ih] + | cons a as ih => + cases right with + | nil => simp [OAI.EditApproximation.bitSubtractWithWork, ih] + | cons b bs => simp [OAI.EditApproximation.bitSubtractWithWork, ih, Nat.succ_max_succ] + have proof_bitSubtractWithWork_sub_22 (left : List.{0} Bool) (right : List.{0} Bool) (h : LE.le.{0} (OAI.EditApproximation.bitWordValue right) (OAI.EditApproximation.bitWordValue left)) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right false).1 = OAI.EditApproximation.bitWordValue left - OAI.EditApproximation.bitWordValue right := by + have hvalue := proof_bitSubtractWithWork_value_19 left right false + have hlt := proof_bitWordValue_lt_pow_length_20 (OAI.EditApproximation.bitSubtractWithWork left right false).1 + rw [proof_bitSubtractWithWork_length_21] at hlt + cases hb : (OAI.EditApproximation.bitSubtractWithWork left right false).2.1 + · simp only [hb, Bool.toNat_false, Nat.mul_zero, Nat.add_zero] at hvalue + omega + · simp only [hb, Bool.toNat_true, Bool.toNat_false, Nat.mul_one, Nat.add_zero] at hvalue + omega + have proof_bitDivModWithWork_value_23 (divisor : List.{0} Bool) (bits : List.{0} Bool) (hd : LT.lt.{0} 0 (OAI.EditApproximation.bitWordValue divisor)) : + OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).1 + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 < OAI.EditApproximation.bitWordValue divisor := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitDivModWithWork, OAI.EditApproximation.bitWordValue, hd]) + | cons bit bits ih => + let previous := OAI.EditApproximation.bitDivModWithWork divisor bits + let candidate := bit :: previous.2.1 + have hp : OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue previous.1 + + OAI.EditApproximation.bitWordValue previous.2.1 := ih.1 + have hr : OAI.EditApproximation.bitWordValue previous.2.1 < OAI.EditApproximation.bitWordValue divisor := ih.2 + have hc : OAI.EditApproximation.bitWordValue candidate < 2 * OAI.EditApproximation.bitWordValue divisor := by + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + cases bit <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega + by_cases hlt : (OAI.EditApproximation.bitCompareWithWork candidate divisor).1 = .lt + · have hv := (proof_bitCompareWithWork_lt_16 candidate divisor).1 hlt + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 = .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * + OAI.EditApproximation.bitWordValue (false :: previous.1) + OAI.EditApproximation.bitWordValue candidate ∧ OAI.EditApproximation.bitWordValue candidate < _ + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_false]) + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + nlinarith only [hp] + · exact hv + · have hv : OAI.EditApproximation.bitWordValue divisor ≤ OAI.EditApproximation.bitWordValue candidate := by + exact Nat.le_of_not_gt (fun h => hlt ((proof_bitCompareWithWork_lt_16 candidate divisor).2 h)) + have hs := proof_bitSubtractWithWork_sub_22 candidate divisor hv + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 ≠ .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (true :: previous.1) + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 < _ + rw [hs] + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_true]) + have he := Nat.sub_add_cancel hv + dsimp only [candidate, OAI.EditApproximation.bitWordValue] at he ⊢ + nlinarith only [hp, he] + · omega + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_binaryNaturalDivModWithWork_spec_24 (n : ℕ) (d : ℕ) (hd : LT.lt.{0} 0 d) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalDivModWithWork n d).1 = n / d ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalDivModWithWork n d).2.1 = n % d := by + have h := proof_bitDivModWithWork_value_23 d.bits n.bits (by simpa only [proof_bitWordValue_bits_15] using hd) + simp only [proof_bitWordValue_bits_15] at h + have hmod : n % d = OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork d.bits n.bits).2.1 := by + conv_lhs => rw [h.1] + simp only [Nat.add_mod, Nat.mul_mod_right, Nat.zero_add, Nat.mod_eq_of_lt h.2] + have hdiv : n / d = OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork d.bits n.bits).1 := by + conv_lhs => rw [h.1] + rw [Nat.mul_add_div hd, Nat.div_eq_of_lt h.2, Nat.add_zero] + exact ⟨hdiv.symm, hmod.symm⟩ + have proof_wordLEWithWork_value_26 (a : List.{0} Bool) (b : List.{0} Bool) : + (OAI.EditApproximation.wordLEWithWork a b).1 = true ↔ OAI.EditApproximation.bitWordValue a ≤ OAI.EditApproximation.bitWordValue b := by + simp only [OAI.EditApproximation.wordLEWithWork, Bool.not_eq_true', decide_eq_false_iff_not, + proof_bitCompareWithWork_lt_16, not_lt] + have proof_seedGridSpacingWithWork_value_86 (b : ℕ) (P : ℕ) (hP : LT.lt.{0} 0 P) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.seedGridSpacingWithWork b P).1 = OAI.EditApproximation.seedGridSpacing b P := by + have hv := (proof_binaryNaturalDivModWithWork_spec_24 b P hP).1 + unfold OAI.EditApproximation.seedGridSpacingWithWork OAI.EditApproximation.seedGridSpacing + dsimp only + split_ifs with ht + · have hq : b / P ≤ 1 := by + have h := (proof_wordLEWithWork_value_26 _ _).mp ht + change OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalDivModWithWork b P).1 ≤ 1 at h + rwa [hv] at h + rw [max_eq_left hq] + rfl + · have hq : 1 ≤ b / P := by + have h := mt (proof_wordLEWithWork_value_26 _ _).mpr ht + change ¬ OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalDivModWithWork b P).1 ≤ 1 at h + rw [hv] at h + exact Nat.le_of_lt (Nat.lt_of_not_ge h) + rw [max_eq_right hq] + exact hv + have proof_seedGridSpacingWithWork_pos_85 (b : ℕ) (P : ℕ) (hP : LT.lt.{0} 0 P) : + 0 < OAI.EditApproximation.bitWordValue (OAI.EditApproximation.seedGridSpacingWithWork b P).1 := by + rw [proof_seedGridSpacingWithWork_value_86 b P hP] + unfold OAI.EditApproximation.seedGridSpacing + omega + exact + let b := 2 ^ e + let center := (OAI.EditApproximation.roundStateWithWork (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.seedGridSpacingWithWork b P).1) + (proof_seedGridSpacingWithWork_pos_85 b P hP) query).1 + OAI.EditApproximation.seedGridSpacingAllocation b P + OAI.EditApproximation.roundStateAllocation (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.seedGridSpacingWithWork b P).1) query + + parentAllocation center + OAI.EditApproximation.BinaryFraction.centerEligibilityAllocation b F a (parentInitial center).1 + e + + if (OAI.EditApproximation.BinaryFraction.centerEligibilityWithWork b F a (parentInitial center).1).1 then + integerAllocation b center + OAI.EditApproximation.BinaryFraction.preparedOnlineReadAllocationRaw source target parent P F exponent H b + (Nat.two_pow_pos e) hP tau eta kappa child initial table R hc hi + childAllocation initialAllocation tableAllocation t center (integer b center).1 + else 0 + +def preparedLocalOnlineActionsSourceAllocationRawBand (N : ℕ) (query : OAI.EditApproximation.TargetInterval target.length) : ℕ := + parentAllocation query + OAI.EditApproximation.BinaryFraction.queryExponentsAllocation N F a (parentInitial query).1 + + OAI.EditApproximation.filterMapAllocation + (fun e => OAI.EditApproximation.BinaryFraction.preparedLocalOnlineScaleSourceWithWorkRawBand source target parent P F exponent H hP tau a eta kappa + parentInitial child initial table R hc hi t integer e query) + (fun e => OAI.EditApproximation.BinaryFraction.preparedLocalOnlineScaleSourceAllocationRawBand source target parent P F exponent H hP tau a eta kappa + parentInitial child initial table R hc hi t integer parentAllocation childAllocation initialAllocation + tableAllocation integerAllocation e query) + (OAI.EditApproximation.BinaryFraction.queryExponentsWithWork N F a (parentInitial query).1).1 + + +end OAI.EditApproximation.BinaryFraction +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BinaryFraction +variable {α : Type u_4} (source target : List α) {M : ℕ} (parent : TargetInterval source.length) (N P F exponent H Q eM eF : ℕ) (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (tau a eta kappa : BinaryFraction) (parentInitial : TargetInterval target.length → BinaryFraction × ℕ) (child initial : Fin M → TargetInterval target.length → BinaryFraction × ℕ) (R : ℕ) (hc : ∀ i r, (child i r).2 ≤ R) (hi : ∀ i r, (initial i r).2 ≤ R) (parentAllocation : TargetInterval target.length → ℕ) (childAllocation initialAllocation : Fin M → TargetInterval target.length → ℕ) + +def queryOnlineSelectAllocationRawBand (t : ℕ) + (integer : ℕ → OAI.EditApproximation.TargetInterval target.length → ℕ × ℕ) + (integerAllocation : ℕ → OAI.EditApproximation.TargetInterval target.length → ℕ) + (keys : List (Fin M × ℕ × OAI.EditApproximation.TargetInterval target.length)) (words : List OAI.EditApproximation.BinaryFraction) + (q : OAI.EditApproximation.TargetInterval target.length) : ℕ := + OAI.EditApproximation.BinaryFraction.preparedLocalOnlineActionsSourceAllocationRawBand source target parent P F exponent H hP tau a eta kappa + parentInitial child initial (OAI.EditApproximation.BinaryFraction.queryHistoryReadWithWork keys words) R hc hi (t - 1) integer + parentAllocation childAllocation initialAllocation (OAI.EditApproximation.BinaryFraction.queryHistoryReadAllocation keys words) + integerAllocation N q + +def queryGroupSelectAllocationRawBand (draw : OAI.EditApproximation.CountedCellGroupDraws M F Q) + (drawAllocation : OAI.EditApproximation.CellGroupSourceAllocations M F Q) + (keys : List (Fin M × OAI.EditApproximation.TargetInterval target.length)) (words : List OAI.EditApproximation.BinaryFraction) + (q : OAI.EditApproximation.TargetInterval target.length) : ℕ := + OAI.EditApproximation.BinaryFraction.preparedLocalCellGroupsSourceAllocationRawBand source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial (OAI.EditApproximation.BinaryFraction.queryChildReadWithWork keys words) R hc hi + parentAllocation childAllocation initialAllocation (OAI.EditApproximation.BinaryFraction.queryChildReadAllocation keys words) + draw drawAllocation N q + + +end OAI.EditApproximation.BinaryFraction +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open Filter MeasureTheory + +noncomputable def integerBinaryWorkRawBand (source target : List ℤ) (N : ℕ) (epsilon : OAI.EditApproximation.BinaryFraction) := + OAI.EditApproximation.computedFullOutputWork (source.map OAI.EditApproximation.integerSymbolCode) (target.map OAI.EditApproximation.integerSymbolCode) N + (OAI.EditApproximation.integerQueryLocalWorkRawBand source target N) (OAI.EditApproximation.integerPreevaluationWork source target N epsilon) + (OAI.EditApproximation.computedQuerySetupWithWork N).2 (fun input => (OAI.EditApproximation.integerBinaryOutputRawBand source target N input).2) + (N + 1) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open Filter + +def integerFinalAllocationRawBand (source target : List ℤ) (N : ℕ) + (input : OAI.EditApproximation.ComputedFamilyInput (source.map OAI.EditApproximation.integerSymbolCode) (target.map OAI.EditApproximation.integerSymbolCode) N) : ℕ := + if source.map OAI.EditApproximation.integerSymbolCode = target.map OAI.EditApproximation.integerSymbolCode then 0 else + OAI.EditApproximation.BinaryFraction.finalAnswerAllocation N + (OAI.EditApproximation.computedQueryMemoResultRawBand (source.map OAI.EditApproximation.integerSymbolCode) (target.map OAI.EditApproximation.integerSymbolCode) N + (OAI.EditApproximation.integerOccurrenceIndex source target) (OAI.EditApproximation.integerInputSymbolBits source target) + (OAI.EditApproximation.integerInputPositionBits target) input).value + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open BitQuery +attribute [local instance] queryArityNeZero queryRoundsNeZero + +def queryLocalRefinementFootprintRawBand + {ι : Type u_1} + {α : Type u_2} + (source target : List α) + {M : ℕ} + (parent : OAI.EditApproximation.TargetInterval source.length) + (N P F exponent H Q eM eF : ℕ) + (hP : 0 < P) + (hM : M = 2 ^ eM) + (hF : F = 2 ^ eF) + (tau a eta kappa delta : OAI.EditApproximation.BinaryFraction) + (t : ℕ) + (parentInitial : OAI.EditApproximation.TargetInterval target.length → OAI.EditApproximation.BinaryFraction × ℕ) + (child initial : Fin M → OAI.EditApproximation.TargetInterval target.length → OAI.EditApproximation.BinaryFraction × ℕ) + (R : ℕ) + (hc : ∀ (i : Fin M) (r : OAI.EditApproximation.TargetInterval target.length), (child i r).2 ≤ R) + (hi : ∀ (i : Fin M) (r : OAI.EditApproximation.TargetInterval target.length), (initial i r).2 ≤ R) + (draw : OAI.EditApproximation.CountedCellGroupDraws M F Q) + (integer : ℕ → OAI.EditApproximation.TargetInterval target.length → ℕ × ℕ) + (parentAllocation : OAI.EditApproximation.TargetInterval target.length → ℕ) + (childAllocation initialAllocation : Fin M → OAI.EditApproximation.TargetInterval target.length → ℕ) + (drawAllocation : OAI.EditApproximation.CountedCellGroupAllocations M F Q) + (integerAllocation : ℕ → OAI.EditApproximation.TargetInterval target.length → ℕ) + (q : OAI.EditApproximation.TargetInterval target.length) + (readEarlier : Fin M × ℕ × OAI.EditApproximation.TargetInterval target.length → + OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (readCurrent : Fin M × OAI.EditApproximation.TargetInterval target.length → + OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (he : (key : Fin M × ℕ × OAI.EditApproximation.TargetInterval target.length) → (readEarlier key).Footprint) + (hr : (key : Fin M × OAI.EditApproximation.TargetInterval target.length) → (readCurrent key).Footprint) : (OAI.EditApproximation.queryLocalRefinementRawBand source target parent N P F exponent H Q eM eF hP hM hF tau a eta kappa delta + t parentInitial child initial R hc hi draw integer q readEarlier readCurrent).Footprint := +(OAI.EditApproximation.BitQuery.Footprint.computeOf + (OAI.EditApproximation.BinaryFraction.queryEarlierInputsWithWork M parent N P F exponent t hP a parentInitial q) + (OAI.EditApproximation.BinaryFraction.queryEarlierInputsAllocation M parent N P F exponent t hP a parentInitial + parentAllocation q)).bind + (fun (earlierKeys : List (Fin M × ℕ × OAI.EditApproximation.TargetInterval target.length)) => + OAI.EditApproximation.BitQuery.collect readEarlier earlierKeys + fun (earlierWords : List OAI.EditApproximation.BinaryFraction) => + (OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.queryOnlineSelectWithWorkRawBand source target parent N P F exponent H hP tau + a eta kappa parentInitial child initial R hc hi t integer earlierKeys earlierWords q)).bind + fun + (onlineActions : + List + (OAI.EditApproximation.BinaryBellmanAction (OAI.EditApproximation.TargetInterval target.length) + (Fin M × OAI.EditApproximation.TargetInterval target.length) M)) => + have word : OAI.EditApproximation.BinaryFraction × ℕ := parentInitial q; + OAI.EditApproximation.BitQuery.charge word.2 + ((OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.querySharedInputsWithWork M N F Q exponent eM eF hM hF parent a + word.1 q draw)).bind + fun (sharedKeys : List (Fin M × OAI.EditApproximation.TargetInterval target.length)) => + OAI.EditApproximation.BitQuery.collect readCurrent sharedKeys + fun (sharedWords : List OAI.EditApproximation.BinaryFraction) => + (OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.queryGroupSelectWithWorkRawBand source target parent N P F exponent Q + eM eF hP hM hF tau a parentInitial child initial R hc hi draw sharedKeys sharedWords q)).bind + fun + (selectedActions : + List + (OAI.EditApproximation.BinaryBellmanAction (OAI.EditApproximation.TargetInterval target.length) + (Fin M × OAI.EditApproximation.TargetInterval target.length) M)) => + (OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.queryNeededInputsWithWork selectedActions onlineActions)).bind + fun (currentKeys : List (Fin M × OAI.EditApproximation.TargetInterval target.length)) => + OAI.EditApproximation.BitQuery.collect readCurrent currentKeys + fun (currentWords : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.queryRefinementFinishWithWork parent N P F a delta + parentInitial t earlierKeys earlierWords selectedActions onlineActions currentKeys currentWords + q))) + fun (earlierKeys : List (Fin M × ℕ × OAI.EditApproximation.TargetInterval target.length)) => + OAI.EditApproximation.BitQuery.Footprint.collect readEarlier he earlierKeys + (fun (earlierWords : List OAI.EditApproximation.BinaryFraction) => + (OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.queryOnlineSelectWithWorkRawBand source target parent N P F exponent H hP tau + a eta kappa parentInitial child initial R hc hi t integer earlierKeys earlierWords q)).bind + fun + (onlineActions : + List + (OAI.EditApproximation.BinaryBellmanAction (OAI.EditApproximation.TargetInterval target.length) + (Fin M × OAI.EditApproximation.TargetInterval target.length) M)) => + have word : OAI.EditApproximation.BinaryFraction × ℕ := parentInitial q; + OAI.EditApproximation.BitQuery.charge word.2 + ((OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.querySharedInputsWithWork M N F Q exponent eM eF hM hF parent a + word.1 q draw)).bind + fun (sharedKeys : List (Fin M × OAI.EditApproximation.TargetInterval target.length)) => + OAI.EditApproximation.BitQuery.collect readCurrent sharedKeys + fun (sharedWords : List OAI.EditApproximation.BinaryFraction) => + (OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.queryGroupSelectWithWorkRawBand source target parent N P F exponent Q + eM eF hP hM hF tau a parentInitial child initial R hc hi draw sharedKeys sharedWords q)).bind + fun + (selectedActions : + List + (OAI.EditApproximation.BinaryBellmanAction (OAI.EditApproximation.TargetInterval target.length) + (Fin M × OAI.EditApproximation.TargetInterval target.length) M)) => + (OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.queryNeededInputsWithWork selectedActions onlineActions)).bind + fun (currentKeys : List (Fin M × OAI.EditApproximation.TargetInterval target.length)) => + OAI.EditApproximation.BitQuery.collect readCurrent currentKeys + fun (currentWords : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.queryRefinementFinishWithWork parent N P F a delta + parentInitial t earlierKeys earlierWords selectedActions onlineActions currentKeys currentWords + q))) + fun (earlierWords : List OAI.EditApproximation.BinaryFraction) => + (OAI.EditApproximation.BitQuery.Footprint.compute + (OAI.EditApproximation.BinaryFraction.queryOnlineSelectWithWorkRawBand source target parent N P F exponent H hP tau a + eta kappa parentInitial child initial R hc hi t integer earlierKeys earlierWords q) + (OAI.EditApproximation.BinaryFraction.queryOnlineSelectAllocationRawBand source target parent N P F exponent H hP tau + a eta kappa parentInitial child initial R hc hi parentAllocation childAllocation initialAllocation t integer + integerAllocation earlierKeys earlierWords q)).bind + (fun + (onlineActions : + List + (OAI.EditApproximation.BinaryBellmanAction (OAI.EditApproximation.TargetInterval target.length) + (Fin M × OAI.EditApproximation.TargetInterval target.length) M)) => + have word : OAI.EditApproximation.BinaryFraction × ℕ := parentInitial q; + OAI.EditApproximation.BitQuery.charge word.2 + ((OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.querySharedInputsWithWork M N F Q exponent eM eF hM hF parent a + word.1 q draw)).bind + fun (sharedKeys : List (Fin M × OAI.EditApproximation.TargetInterval target.length)) => + OAI.EditApproximation.BitQuery.collect readCurrent sharedKeys + fun (sharedWords : List OAI.EditApproximation.BinaryFraction) => + (OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.queryGroupSelectWithWorkRawBand source target parent N P F exponent Q + eM eF hP hM hF tau a parentInitial child initial R hc hi draw sharedKeys sharedWords q)).bind + fun + (selectedActions : + List + (OAI.EditApproximation.BinaryBellmanAction (OAI.EditApproximation.TargetInterval target.length) + (Fin M × OAI.EditApproximation.TargetInterval target.length) M)) => + (OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.queryNeededInputsWithWork selectedActions onlineActions)).bind + fun (currentKeys : List (Fin M × OAI.EditApproximation.TargetInterval target.length)) => + OAI.EditApproximation.BitQuery.collect readCurrent currentKeys + fun (currentWords : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.queryRefinementFinishWithWork parent N P F a delta + parentInitial t earlierKeys earlierWords selectedActions onlineActions currentKeys currentWords + q))) + fun + (online : + List + (OAI.EditApproximation.BinaryBellmanAction (OAI.EditApproximation.TargetInterval target.length) + (Fin M × OAI.EditApproximation.TargetInterval target.length) M)) => + OAI.EditApproximation.BitQuery.Footprint.chargeOf (parentAllocation q) + ((OAI.EditApproximation.BitQuery.Footprint.computeOf + (OAI.EditApproximation.BinaryFraction.querySharedInputsWithWork M N F Q exponent eM eF hM hF parent a + (parentInitial q).1 q draw) + (OAI.EditApproximation.BinaryFraction.querySharedInputsAllocation M N F Q exponent eM eF hM hF parent a + (parentInitial q).1 q draw drawAllocation)).bind + (fun (sharedKeys : List (Fin M × OAI.EditApproximation.TargetInterval target.length)) => + OAI.EditApproximation.BitQuery.collect readCurrent sharedKeys + fun (sharedWords : List OAI.EditApproximation.BinaryFraction) => + (OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.queryGroupSelectWithWorkRawBand source target parent N P F exponent Q + eM eF hP hM hF tau a parentInitial child initial R hc hi draw sharedKeys sharedWords q)).bind + fun + (selectedActions : + List + (OAI.EditApproximation.BinaryBellmanAction (OAI.EditApproximation.TargetInterval target.length) + (Fin M × OAI.EditApproximation.TargetInterval target.length) M)) => + (OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.queryNeededInputsWithWork selectedActions online)).bind + fun (currentKeys : List (Fin M × OAI.EditApproximation.TargetInterval target.length)) => + OAI.EditApproximation.BitQuery.collect readCurrent currentKeys + fun (currentWords : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.queryRefinementFinishWithWork parent N P F a delta + parentInitial t earlierKeys earlierWords selectedActions online currentKeys currentWords q)) + fun (sharedKeys : List (Fin M × OAI.EditApproximation.TargetInterval target.length)) => + OAI.EditApproximation.BitQuery.Footprint.collect readCurrent hr sharedKeys + (fun (sharedWords : List OAI.EditApproximation.BinaryFraction) => + (OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.queryGroupSelectWithWorkRawBand source target parent N P F exponent Q + eM eF hP hM hF tau a parentInitial child initial R hc hi draw sharedKeys sharedWords q)).bind + fun + (selectedActions : + List + (OAI.EditApproximation.BinaryBellmanAction (OAI.EditApproximation.TargetInterval target.length) + (Fin M × OAI.EditApproximation.TargetInterval target.length) M)) => + (OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.queryNeededInputsWithWork selectedActions online)).bind + fun (currentKeys : List (Fin M × OAI.EditApproximation.TargetInterval target.length)) => + OAI.EditApproximation.BitQuery.collect readCurrent currentKeys + fun (currentWords : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.queryRefinementFinishWithWork parent N P F a delta + parentInitial t earlierKeys earlierWords selectedActions online currentKeys currentWords q)) + fun (sharedWords : List OAI.EditApproximation.BinaryFraction) => + (OAI.EditApproximation.BitQuery.Footprint.computeOf + (OAI.EditApproximation.BinaryFraction.queryGroupSelectWithWorkRawBand source target parent N P F exponent Q + eM eF hP hM hF tau a parentInitial child initial R hc hi draw sharedKeys sharedWords q) + (OAI.EditApproximation.BinaryFraction.queryGroupSelectAllocationRawBand source target parent N P F exponent Q + eM eF hP hM hF tau a parentInitial child initial R hc hi parentAllocation childAllocation + initialAllocation draw drawAllocation sharedKeys sharedWords q)).bind + (fun + (selectedActions : + List + (OAI.EditApproximation.BinaryBellmanAction (OAI.EditApproximation.TargetInterval target.length) + (Fin M × OAI.EditApproximation.TargetInterval target.length) M)) => + (OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.queryNeededInputsWithWork selectedActions online)).bind + fun (currentKeys : List (Fin M × OAI.EditApproximation.TargetInterval target.length)) => + OAI.EditApproximation.BitQuery.collect readCurrent currentKeys + fun (currentWords : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.queryRefinementFinishWithWork parent N P F a delta + parentInitial t earlierKeys earlierWords selectedActions online currentKeys currentWords q)) + fun + (groups : + List + (OAI.EditApproximation.BinaryBellmanAction (OAI.EditApproximation.TargetInterval target.length) + (Fin M × OAI.EditApproximation.TargetInterval target.length) M)) => + (OAI.EditApproximation.BitQuery.Footprint.computeOf + (OAI.EditApproximation.queryNeededInputsWithWork groups online) + (OAI.EditApproximation.queryNeededInputsAllocation groups online)).bind + (fun (currentKeys : List (Fin M × OAI.EditApproximation.TargetInterval target.length)) => + OAI.EditApproximation.BitQuery.collect readCurrent currentKeys + fun (currentWords : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.queryRefinementFinishWithWork parent N P F a delta + parentInitial t earlierKeys earlierWords groups online currentKeys currentWords q)) + fun (currentKeys : List (Fin M × OAI.EditApproximation.TargetInterval target.length)) => + OAI.EditApproximation.BitQuery.Footprint.collect readCurrent hr currentKeys + (fun (currentWords : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.queryRefinementFinishWithWork parent N P F a delta + parentInitial t earlierKeys earlierWords groups online currentKeys currentWords q)) + fun (currentWords : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.BitQuery.Footprint.computeOf + (OAI.EditApproximation.BinaryFraction.queryRefinementFinishWithWork parent N P F a delta + parentInitial t earlierKeys earlierWords groups online currentKeys currentWords q) + (OAI.EditApproximation.BinaryFraction.queryRefinementFinishAllocation parent N P F a delta + parentInitial parentAllocation t earlierKeys earlierWords groups online currentKeys currentWords + q)) + +def queryLocalRandomSourcesFootprintRawBand + {ι : Type u_1} + {α : Type u_2} + (source target : List α) + {M : ℕ} + [NeZero M] + (parent : OAI.EditApproximation.TargetInterval source.length) + (N P F exponent H Q eM eF : ℕ) + (hP : 0 < P) + (hM : M = 2 ^ eM) + (hF : F = 2 ^ eF) + (tau a eta kappa delta : OAI.EditApproximation.BinaryFraction) + (t : ℕ) + (parentInitial : OAI.EditApproximation.TargetInterval target.length → OAI.EditApproximation.BinaryFraction × ℕ) + (child initial : Fin M → OAI.EditApproximation.TargetInterval target.length → OAI.EditApproximation.BinaryFraction × ℕ) + (R : ℕ) + (hc : ∀ (i : Fin M) (r : OAI.EditApproximation.TargetInterval target.length), (child i r).2 ≤ R) + (hi : ∀ (i : Fin M) (r : OAI.EditApproximation.TargetInterval target.length), (initial i r).2 ≤ R) + (parentAllocation : OAI.EditApproximation.TargetInterval target.length → ℕ) + (childAllocation initialAllocation : Fin M → OAI.EditApproximation.TargetInterval target.length → ℕ) + (q : OAI.EditApproximation.TargetInterval target.length) + (readGroup : OAI.EditApproximation.GroupScalarKey M F Q → OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (readInteger : ℕ × OAI.EditApproximation.TargetInterval target.length → + ℕ → OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (readEarlier : Fin M × ℕ × OAI.EditApproximation.TargetInterval target.length → + OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (readCurrent : Fin M × OAI.EditApproximation.TargetInterval target.length → + OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (hg : (key : OAI.EditApproximation.GroupScalarKey M F Q) → (readGroup key).Footprint) + (hz : (key : ℕ × OAI.EditApproximation.TargetInterval target.length) → (range : ℕ) → (readInteger key range).Footprint) + (he : (key : Fin M × ℕ × OAI.EditApproximation.TargetInterval target.length) → (readEarlier key).Footprint) + (hr : (key : Fin M × OAI.EditApproximation.TargetInterval target.length) → (readCurrent key).Footprint) : (OAI.EditApproximation.queryLocalRandomSourcesRawBand source target parent N P F exponent H Q eM eF hP hM hF tau a eta kappa + delta t parentInitial child initial R hc hi q readGroup readInteger readEarlier readCurrent).Footprint := +OAI.EditApproximation.queryGroupSourceGatherFootprint M N F Q exponent eM eF hM hF a parentInitial parentAllocation q + readGroup hg + (fun (groupKeys : List (OAI.EditApproximation.GroupScalarKey M F Q)) + (groupWords : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.queryOnlineSourceGather parent N P F exponent H hP tau a parentInitial child q readInteger + fun (onlineKeys : List (ℕ × OAI.EditApproximation.TargetInterval target.length)) + (onlineWords : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.queryLocalRefinementRawBand source target parent N P F exponent H Q eM eF hP hM hF tau a eta kappa + delta t parentInitial child initial R hc hi + (OAI.EditApproximation.BinaryFraction.queryGroupDrawReadWithWork groupKeys groupWords) + (OAI.EditApproximation.BinaryFraction.queryOnlineIntegerReadWithWork onlineKeys onlineWords) q readEarlier + readCurrent) + fun (groupKeys : List (OAI.EditApproximation.GroupScalarKey M F Q)) + (groupWords : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.queryOnlineSourceGatherFootprint parent N P F exponent H hP tau a parentInitial parentAllocation + child childAllocation q readInteger hz + (fun (onlineKeys : List (ℕ × OAI.EditApproximation.TargetInterval target.length)) + (onlineWords : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.queryLocalRefinementRawBand source target parent N P F exponent H Q eM eF hP hM hF tau a eta kappa + delta t parentInitial child initial R hc hi + (OAI.EditApproximation.BinaryFraction.queryGroupDrawReadWithWork groupKeys groupWords) + (OAI.EditApproximation.BinaryFraction.queryOnlineIntegerReadWithWork onlineKeys onlineWords) q readEarlier + readCurrent) + fun (onlineKeys : List (ℕ × OAI.EditApproximation.TargetInterval target.length)) + (onlineWords : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.queryLocalRefinementFootprintRawBand source target parent N P F exponent H Q eM eF hP hM hF tau a eta + kappa delta t parentInitial child initial R hc hi + (OAI.EditApproximation.BinaryFraction.queryGroupDrawReadWithWork groupKeys groupWords) + (OAI.EditApproximation.BinaryFraction.queryOnlineIntegerReadWithWork onlineKeys onlineWords) parentAllocation + childAllocation initialAllocation + (OAI.EditApproximation.BinaryFraction.queryGroupDrawReadAllocation groupKeys groupWords) + (OAI.EditApproximation.BinaryFraction.queryOnlineIntegerReadAllocation onlineKeys onlineWords) q readEarlier + readCurrent he hr + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open BitQuery +attribute [local instance] queryArityNeZero queryRoundsNeZero +open Finset + +def queryLocalBandFootprintRawBand + {ι : Type u_1} + {α : Type u_2} + (source target : List α) + {M : ℕ} + [NeZero M] + (parent : OAI.EditApproximation.TargetInterval source.length) + (N P F exponent H Q eM eF : ℕ) + (hP : 0 < P) + (hM : M = 2 ^ eM) + (hF : F = 2 ^ eF) + (tau a eta kappa delta : OAI.EditApproximation.BinaryFraction) + (t : ℕ) + (parentInitial : OAI.EditApproximation.TargetInterval target.length → OAI.EditApproximation.BinaryFraction × ℕ) + (parentAllocation : OAI.EditApproximation.TargetInterval target.length → ℕ) + (readMass readInitial : Fin M × OAI.EditApproximation.TargetInterval target.length → + OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (readGroup : OAI.EditApproximation.GroupScalarKey M F Q → OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (readInteger : ℕ × OAI.EditApproximation.TargetInterval target.length → + ℕ → OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (q : OAI.EditApproximation.TargetInterval target.length) + (readEarlier : Fin M × ℕ × OAI.EditApproximation.TargetInterval target.length → + OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (readCurrent : Fin M × OAI.EditApproximation.TargetInterval target.length → + OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (hm : (key : Fin M × OAI.EditApproximation.TargetInterval target.length) → (readMass key).Footprint) + (hi : (key : Fin M × OAI.EditApproximation.TargetInterval target.length) → (readInitial key).Footprint) + (hg : (key : OAI.EditApproximation.GroupScalarKey M F Q) → (readGroup key).Footprint) + (hz : (key : ℕ × OAI.EditApproximation.TargetInterval target.length) → (range : ℕ) → (readInteger key range).Footprint) + (he : (key : Fin M × ℕ × OAI.EditApproximation.TargetInterval target.length) → (readEarlier key).Footprint) + (hr : (key : Fin M × OAI.EditApproximation.TargetInterval target.length) → (readCurrent key).Footprint) : (OAI.EditApproximation.queryLocalBandRawBand source target parent N P F exponent H Q eM eF hP hM hF tau a eta kappa delta t + parentInitial readMass readInitial readGroup readInteger q readEarlier readCurrent).Footprint := by + have proof_gatheredWordLookupWithWork_cost_132 {κ : Type 0} (equal : κ → κ → Prod.{0, 0} Bool ℕ) (C : ℕ) (hC : ∀ (a b : κ), LE.le.{0} (equal a b).2 C) (keys : List.{0} κ) (values : List.{0} OAI.EditApproximation.BinaryFraction) (query : κ) : + (OAI.EditApproximation.BinaryFraction.gatheredWordLookupWithWork equal keys values query).2 ≤ 1 + keys.length * (C + 1) := by + induction keys generalizing values with + | nil => simp only [OAI.EditApproximation.BinaryFraction.gatheredWordLookupWithWork, List.length_nil, Nat.zero_mul, Nat.add_zero, le_rfl] + | cons key keys ih => + cases values with + | nil => simp only [OAI.EditApproximation.BinaryFraction.gatheredWordLookupWithWork]; omega + | cons value values => + have hc := hC query key + have hi := ih values + simp only [OAI.EditApproximation.BinaryFraction.gatheredWordLookupWithWork] + split_ifs <;> simp only [List.length_cons, Nat.add_mul, Nat.one_mul] <;> omega + have proof_bitCompareWithWork_cost_133 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).2 ≤ 4 * (left.length + right.length) + 1 := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => simp [OAI.EditApproximation.bitCompareNilLeftWithWork] + | cons b bs ih => + simp only [OAI.EditApproximation.bitCompareNilLeftWithWork, List.length_cons, List.length_nil] at * + omega + | cons a as ih => + cases right with + | nil => + have h := ih [] + simp only [OAI.EditApproximation.bitCompareWithWork, List.length_cons, List.length_nil] at * + omega + | cons b bs => + have h := ih bs + simp only [OAI.EditApproximation.bitCompareWithWork, List.length_cons] at * + omega + have proof_binaryNaturalCompareWithWork_cost_134 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.binaryNaturalCompareWithWork a b).2 ≤ 4 * (Nat.size a + Nat.size b) + 1 := by + simpa only [OAI.EditApproximation.binaryNaturalCompareWithWork, Nat.size_eq_bits_len] using proof_bitCompareWithWork_cost_133 a.bits b.bits + have proof_naturalEqualWithWork_cost_135 (a : ℕ) (b : ℕ) (B : ℕ) (ha : LE.le.{0} a.size B) (hb : LE.le.{0} b.size B) : + (OAI.EditApproximation.naturalEqualWithWork a b).2 ≤ 8 * B + 2 := by + have h := proof_binaryNaturalCompareWithWork_cost_134 a b + change (OAI.EditApproximation.binaryNaturalCompareWithWork a b).2 + 1 ≤ _ + omega + have proof_coordinateEqualWithWork_cost_136 {M : ℕ} {n : ℕ} (a : Prod.{0, 0} (Fin M) (OAI.EditApproximation.TargetInterval n)) (b : Prod.{0, 0} (Fin M) (OAI.EditApproximation.TargetInterval n)) (B : ℕ) (hM : LE.le.{0} M.size B) (hn : LE.le.{0} n.size B) : + (OAI.EditApproximation.coordinateEqualWithWork a b).2 ≤ 24 * B + 8 := by + have hc := proof_naturalEqualWithWork_cost_135 a.1.val b.1.val B + ((Nat.size_le_size a.1.isLt.le).trans hM) ((Nat.size_le_size b.1.isLt.le).trans hM) + have hl := proof_naturalEqualWithWork_cost_135 a.2.lo b.2.lo B + ((Nat.size_le_size (a.2.ordered.trans a.2.valid)).trans hn) + ((Nat.size_le_size (b.2.ordered.trans b.2.valid)).trans hn) + have hh := proof_naturalEqualWithWork_cost_135 a.2.hi b.2.hi B + ((Nat.size_le_size a.2.valid).trans hn) ((Nat.size_le_size b.2.valid).trans hn) + change _ + _ + _ + 2 ≤ _ + omega + have proof_queryChildReadWithWork_cost_137 {M : ℕ} {n : ℕ} (keys : List.{0} (Prod.{0, 0} (Fin M) (OAI.EditApproximation.TargetInterval n))) (values : List.{0} OAI.EditApproximation.BinaryFraction) (i : Fin M) (q : OAI.EditApproximation.TargetInterval n) (B : ℕ) (hM : LE.le.{0} M.size B) (hn : LE.le.{0} n.size B) : + (OAI.EditApproximation.BinaryFraction.queryChildReadWithWork keys values i q).2 ≤ 1 + keys.length * (24 * B + 9) := by + exact proof_gatheredWordLookupWithWork_cost_132 OAI.EditApproximation.coordinateEqualWithWork (24 * B + 8) + (fun a b => proof_coordinateEqualWithWork_cost_136 a b B hM hn) keys values (i, q) + have proof_queryChildReadWithWork_budget_131 {M : ℕ} {n : ℕ} (keys : List.{0} (Prod.{0, 0} (Fin M) (OAI.EditApproximation.TargetInterval n))) (words : List.{0} OAI.EditApproximation.BinaryFraction) (i : Fin M) (r : OAI.EditApproximation.TargetInterval n) : + (OAI.EditApproximation.BinaryFraction.queryChildReadWithWork keys words i r).2 ≤ OAI.EditApproximation.BinaryFraction.queryDataReadBudget M n keys := by + exact proof_queryChildReadWithWork_cost_137 keys words i r _ (Nat.le_max_left _ _) (Nat.le_max_right _ _) + exact + OAI.EditApproximation.queryBandGatherFootprint M parent N P F exponent hP a parentInitial parentAllocation q readMass + readInitial hm hi + (fun (keys : List (Fin M × OAI.EditApproximation.TargetInterval target.length)) + (massWords initialWords : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.queryLocalRandomSourcesRawBand source target parent N P F exponent H Q eM eF hP hM hF tau a eta kappa + delta t parentInitial (OAI.EditApproximation.BinaryFraction.queryChildReadWithWork keys massWords) + (OAI.EditApproximation.BinaryFraction.queryChildReadWithWork keys initialWords) + (OAI.EditApproximation.BinaryFraction.queryDataReadBudget M target.length keys) (proof_queryChildReadWithWork_budget_131 keys massWords) (proof_queryChildReadWithWork_budget_131 keys initialWords) q readGroup + readInteger readEarlier readCurrent) + fun (keys : List (Fin M × OAI.EditApproximation.TargetInterval target.length)) + (massWords initialWords : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.queryLocalRandomSourcesFootprintRawBand source target parent N P F exponent H Q eM eF hP hM hF tau a + eta kappa delta t parentInitial (OAI.EditApproximation.BinaryFraction.queryChildReadWithWork keys massWords) + (OAI.EditApproximation.BinaryFraction.queryChildReadWithWork keys initialWords) + (OAI.EditApproximation.BinaryFraction.queryDataReadBudget M target.length keys) (proof_queryChildReadWithWork_budget_131 keys massWords) (proof_queryChildReadWithWork_budget_131 keys initialWords) + parentAllocation (OAI.EditApproximation.BinaryFraction.queryChildReadAllocation keys massWords) + (OAI.EditApproximation.BinaryFraction.queryChildReadAllocation keys initialWords) q readGroup readInteger + readEarlier readCurrent hg hz he hr + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open BitQuery +attribute [local instance] queryArityNeZero queryRoundsNeZero + +def queryLocalProgramFootprintRawBand + {ι : Type u_1} + {α : Type u_2} + (source target : List α) + {M : ℕ} + [NeZero M] + (parent : OAI.EditApproximation.TargetInterval source.length) + (N P F exponent H Q eM eF : ℕ) + (hP : 0 < P) + (hM : M = 2 ^ eM) + (hF : F = 2 ^ eF) + (tau a eta kappa delta : OAI.EditApproximation.BinaryFraction) + (t : ℕ) + (readParent : OAI.EditApproximation.TargetInterval target.length → + OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (readMass readInitial : Fin M × OAI.EditApproximation.TargetInterval target.length → + OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (readGroup : OAI.EditApproximation.GroupScalarKey M F Q → OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (readInteger : ℕ × OAI.EditApproximation.TargetInterval target.length → + ℕ → OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (q : OAI.EditApproximation.TargetInterval target.length) + (readEarlier : Fin M × ℕ × OAI.EditApproximation.TargetInterval target.length → + OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (readCurrent : Fin M × OAI.EditApproximation.TargetInterval target.length → + OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (hp : (key : OAI.EditApproximation.TargetInterval target.length) → (readParent key).Footprint) + (hm : (key : Fin M × OAI.EditApproximation.TargetInterval target.length) → (readMass key).Footprint) + (hi : (key : Fin M × OAI.EditApproximation.TargetInterval target.length) → (readInitial key).Footprint) + (hg : (key : OAI.EditApproximation.GroupScalarKey M F Q) → (readGroup key).Footprint) + (hz : (key : ℕ × OAI.EditApproximation.TargetInterval target.length) → (range : ℕ) → (readInteger key range).Footprint) + (he : (key : Fin M × ℕ × OAI.EditApproximation.TargetInterval target.length) → (readEarlier key).Footprint) + (hr : (key : Fin M × OAI.EditApproximation.TargetInterval target.length) → (readCurrent key).Footprint) : (OAI.EditApproximation.queryLocalProgramRawBand source target parent N P F exponent H Q eM eF hP hM hF tau a eta kappa delta t + readParent readMass readInitial readGroup readInteger q readEarlier readCurrent).Footprint := +OAI.EditApproximation.queryInitialGatherFootprint N P F exponent hP a q readParent hp + (fun (keys : List (OAI.EditApproximation.TargetInterval target.length)) + (words : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.queryLocalBandRawBand source target parent N P F exponent H Q eM eF hP hM hF tau a eta kappa delta t + (OAI.EditApproximation.BinaryFraction.queryParentReadWithWork keys words) readMass readInitial readGroup + readInteger q readEarlier readCurrent) + fun (keys : List (OAI.EditApproximation.TargetInterval target.length)) + (words : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.queryLocalBandFootprintRawBand source target parent N P F exponent H Q eM eF hP hM hF tau a eta kappa + delta t (OAI.EditApproximation.BinaryFraction.queryParentReadWithWork keys words) + (OAI.EditApproximation.BinaryFraction.queryParentReadAllocation keys words) readMass readInitial readGroup + readInteger q readEarlier readCurrent hm hi hg hz he hr + +def queryPhysicalRandomDataRequestFootprintRawBand + {σ : Type u_1} + {α : Type u_2} + (source target : List α) + {M J : ℕ} + [NeZero M] + (N P F exponent H Q eM eF : ℕ) + (hP : 0 < P) + (hM : M = 2 ^ eM) + (hF : F = 2 ^ eF) + (tau a eta kappa delta : OAI.EditApproximation.BinaryFraction) + (copies pass copy T S t : ℕ) + (ht : 0 < t) + (node : OAI.EditApproximation.PhysicalNode M J) + (hbelow : ↑node.fst < J) + (readGroup : OAI.EditApproximation.GroupScalarKey M F Q → OAI.EditApproximation.BitQuery σ OAI.EditApproximation.BinaryFraction) + (readInteger : ℕ × OAI.EditApproximation.TargetInterval target.length → + ℕ → OAI.EditApproximation.BitQuery σ OAI.EditApproximation.BinaryFraction) + (q : OAI.EditApproximation.TargetInterval target.length) + (hg : (key : OAI.EditApproximation.GroupScalarKey M F Q) → (readGroup key).Footprint) + (hz : (key : ℕ × OAI.EditApproximation.TargetInterval target.length) → (range : ℕ) → (readInteger key range).Footprint) : (OAI.EditApproximation.queryPhysicalRandomDataRequestRawBand source target N P F exponent H Q eM eF hP hM hF tau a eta kappa + delta copies pass copy T S t ht node hbelow readGroup readInteger q).Footprint := by + have proof_combinedRank_lt_of_progress_80 {M : ℕ} {J : ℕ} {ny : ℕ} (T : ℕ) (S : ℕ) (first : OAI.EditApproximation.PhysicalTableRequest M J ny) (second : OAI.EditApproximation.PhysicalTableRequest M J ny) (hprogress : LT.lt.{0} second.remainingDepth first.remainingDepth ∧ + LE.le.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first) ∨ + LE.le.{0} second.remainingDepth first.remainingDepth ∧ + LT.lt.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first)) : + OAI.EditApproximation.PhysicalTableRequest.combinedRank T S second < OAI.EditApproximation.PhysicalTableRequest.combinedRank T S first := by + unfold OAI.EditApproximation.PhysicalTableRequest.combinedRank + rcases hprogress with h | h + · exact Nat.add_lt_add_of_lt_of_le h.1 h.2 + · exact Nat.add_lt_add_of_le_of_lt h.1 h.2 + have proof_sameIndexChild_progress_95 {M : ℕ} {J : ℕ} {ny : ℕ} (T : ℕ) (S : ℕ) (request : OAI.EditApproximation.PhysicalTableRequest M J ny) (hbelow : LT.lt.{0} (↑(Sigma.fst.{0, 0} request.node)) J) (i : Fin M) (state : OAI.EditApproximation.TargetInterval ny) : + (OAI.EditApproximation.PhysicalTableRequest.sameIndexChild request hbelow i state).remainingDepth < request.remainingDepth ∧ + OAI.EditApproximation.PhysicalTableRequest.rank T S (OAI.EditApproximation.PhysicalTableRequest.sameIndexChild request hbelow i state) ≤ OAI.EditApproximation.PhysicalTableRequest.rank T S request := by + constructor + · unfold OAI.EditApproximation.PhysicalTableRequest.remainingDepth OAI.EditApproximation.PhysicalTableRequest.sameIndexChild OAI.EditApproximation.physicalChild + dsimp only + omega + · exact le_rfl + have proof_combinedRank_sameIndexChild_94 {M : ℕ} {J : ℕ} {ny : ℕ} (T : ℕ) (S : ℕ) (request : OAI.EditApproximation.PhysicalTableRequest M J ny) (hbelow : LT.lt.{0} (↑(Sigma.fst.{0, 0} request.node)) J) (i : Fin M) (state : OAI.EditApproximation.TargetInterval ny) : + OAI.EditApproximation.PhysicalTableRequest.combinedRank T S (OAI.EditApproximation.PhysicalTableRequest.sameIndexChild request hbelow i state) < OAI.EditApproximation.PhysicalTableRequest.combinedRank T S request := + proof_combinedRank_lt_of_progress_80 T S request _ (Or.inl (proof_sameIndexChild_progress_95 T S request hbelow i state)) + unfold OAI.EditApproximation.queryPhysicalRandomDataRequestRawBand + apply OAI.EditApproximation.queryLocalProgramFootprintRawBand + · intro r + exact (OAI.EditApproximation.queryPhysicalTableReadFootprint copies T S _ _).mapKeysWithWork _ (fun _ => 1) + · intro input + apply OAI.EditApproximation.BitQuery.Footprint.mapKeysWithWork _ (fun _ => 1) + apply OAI.EditApproximation.queryMeanReadFootprint + intro j + exact OAI.EditApproximation.queryPhysicalTableReadFootprint copies T S _ _ + · intro input + exact (OAI.EditApproximation.queryPhysicalTableReadFootprint copies T S _ _).mapKeysWithWork _ (fun _ => 1) + · intro key + exact (hg key).mapKeysWithWork _ (fun _ => 1) + · intro key range + exact (hz key range).mapKeysWithWork _ (fun _ => 1) + · intro input + exact (OAI.EditApproximation.queryPhysicalEarlierReadFootprint copies pass copy T S t node hbelow q input).mapKeysWithWork _ + (fun _ => 1) + · intro input + exact (OAI.EditApproximation.queryPhysicalTableReadFootprint copies T S _ _).mapKeysWithWork _ (fun _ => 1) + +def queryFamilyRefinementFootprintRawBand + {α : Type u_1} + {M J R : ℕ} + [NeZero M] + (source target : List α) + (N P F exponent H Q eM eF : ℕ) + (hP : 0 < P) + (hM : M = 2 ^ eM) + (hF : F = 2 ^ eF) + (tau a eta kappa delta : OAI.EditApproximation.BinaryFraction) + (passes copies pass copy T S t : ℕ) + (ht : 0 < t) + (node : OAI.EditApproximation.PhysicalNode M J) + (hbelow : ↑node.fst < J) + (time : Fin R) + (q : OAI.EditApproximation.TargetInterval target.length) : (OAI.EditApproximation.queryFamilyRefinementRawBand source target N P F exponent H Q eM eF hP hM hF tau a eta kappa delta + passes copies pass copy T S t ht node hbelow time q).Footprint := +OAI.EditApproximation.queryPhysicalRandomDataRequestFootprintRawBand source target N P F exponent H Q eM eF hP hM hF tau a eta + kappa delta copies pass copy T S t ht node hbelow + (OAI.EditApproximation.queryFamilyGroupRead target N P F exponent H Q passes copies pass copy ⟨node, hbelow⟩ time) + (OAI.EditApproximation.queryFamilyOnlineRead target N P F exponent H Q passes copies pass copy ⟨node, hbelow⟩ time) q + (OAI.EditApproximation.queryFamilyGroupReadFootprint target N P F exponent H Q passes copies pass copy ⟨node, hbelow⟩ + time) + (OAI.EditApproximation.queryFamilyOnlineReadFootprint target N P F exponent H Q passes copies pass copy ⟨node, hbelow⟩ + time) + +def queryFamilyActiveFootprintRawBand + {α : Type u_1} + {M J R : ℕ} + [NeZero M] + [NeZero R] + (source target : List α) + (N P F exponent H Q eM eF : ℕ) + (hP : 0 < P) + (hM : M = 2 ^ eM) + (hF : F = 2 ^ eF) + (tau a eta kappa delta : OAI.EditApproximation.BinaryFraction) + (T S passes copies : ℕ) + (request : OAI.EditApproximation.PhysicalTableRequest M J target.length) + (hindex : T < request.index) + (hbelow : ↑request.node.fst < J) : (OAI.EditApproximation.queryFamilyActiveRawBand (R := R) source target N P F exponent H Q eM eF hP hM hF tau a eta kappa delta T S + passes copies request hindex hbelow).Footprint := by + have proof_active_request_eq_145 {α : Type u_1} {M : ℕ} {J : ℕ} (target : List.{u_1} α) (T : ℕ) (request : OAI.EditApproximation.PhysicalTableRequest M J (List.length.{u_1} target)) (hindex : LT.lt.{0} T request.index) : + OAI.EditApproximation.PhysicalTableRequest.refinement request.pass request.copy request.node T (request.index - T) + request.state = request := by + have hi : T + (request.index - T) = request.index := by omega + unfold OAI.EditApproximation.PhysicalTableRequest.refinement + rw [hi] + exact + (OAI.EditApproximation.queryFamilyRefinementFootprintRawBand source target N P F exponent H Q eM eF hP hM hF tau a eta kappa delta + passes copies request.pass request.copy T S (request.index - T) (Nat.sub_pos_of_lt hindex) + request.node hbelow (Fin.ofNat R (request.index - T - 1)) request.state).mapKeysWithWork _ (fun _ => 1) + +def queryFamilyBoundedActiveFootprintRawBand + {α : Type u_1} + {M J R : ℕ} + [NeZero M] + [NeZero R] + (source target : List α) + (N P F exponent H Q eM eF : ℕ) + (hP : 0 < P) + (hM : M = 2 ^ eM) + (hF : F = 2 ^ eF) + (tau a eta kappa delta : OAI.EditApproximation.BinaryFraction) + (T S passes copies : ℕ) + (parent : { r : OAI.EditApproximation.PhysicalTableRequest M J target.length // + OAI.EditApproximation.PhysicalTableRequest.Bounded (passes + 1) copies T S r }) + (hindex : T < parent.val.index) + (hbelow : ↑parent.val.node.fst < J) : (OAI.EditApproximation.queryFamilyBoundedActiveRawBand (R := R) source target N P F exponent H Q eM eF hP hM hF tau a eta kappa delta T + S passes copies parent hindex hbelow).Footprint := + OAI.EditApproximation.queryRestrictPhysicalBodyFootprint (passes + 1) copies T S parent _ + (OAI.EditApproximation.queryFamilyActiveFootprintRawBand (R := R) source target N P F exponent H Q eM eF hP hM hF + tau a eta kappa delta T S passes copies parent.val hindex hbelow) + +def queryChargedFamilyTableFootprintRawBand + {M J R passes copies T S : ℕ} + [NeZero M] + [NeZero R] + (source target : List ℕ) + (N P F exponent H Q eM eF : ℕ) + (hP : 0 < P) + (hM : M = 2 ^ eM) + (hF : F = 2 ^ eF) + (A a : ℕ → OAI.EditApproximation.BinaryFraction) + (tau eta kappa delta : OAI.EditApproximation.BinaryFraction) + (multiplier : ℕ → ℕ) + (occurrence : OAI.EditApproximation.BinaryMemo OAI.EditApproximation.PositionCounts) + (symbolBits positionBits : ℕ) + (parent : { r : OAI.EditApproximation.PhysicalTableRequest M J target.length // + OAI.EditApproximation.PhysicalTableRequest.Bounded (passes + 1) copies T S r }) : (OAI.EditApproximation.queryChargedFamilyTableRawBand (R := R) source target N P F exponent H Q eM eF hP hM hF A a tau eta kappa delta + multiplier occurrence symbolBits positionBits parent).Footprint := by + have proof_table_rank_lt_99 {M : ℕ} {J : ℕ} {ny : ℕ} {passes : ℕ} {copies : ℕ} {T : ℕ} {S : ℕ} (parent : Subtype.{1} fun request => OAI.EditApproximation.PhysicalTableRequest.Bounded (M := M) (J := J) (ny := ny) passes copies T S request) (child : Subtype.{1} fun request => OAI.EditApproximation.PhysicalTableRequest.Bounded (M := M) (J := J) (ny := ny) passes copies T S request) (h : LT.lt.{0} (OAI.EditApproximation.PhysicalTableRequest.combinedRank T S child.val) + (OAI.EditApproximation.PhysicalTableRequest.combinedRank T S parent.val)) : + OAI.EditApproximation.ChargedPhysicalRequest.rank (Sum.inr child : OAI.EditApproximation.ChargedPhysicalRequest M J ny passes copies T S) < OAI.EditApproximation.ChargedPhysicalRequest.rank (Sum.inr parent) := by + simpa only [OAI.EditApproximation.ChargedPhysicalRequest.rank, OAI.EditApproximation.ChargedPhysicalRequest.depth, OAI.EditApproximation.ChargedPhysicalRequest.index, ← Nat.add_assoc, OAI.EditApproximation.PhysicalTableRequest.combinedRank] using + Nat.add_lt_add_right h 1 + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_wordLEWithWork_value_26 (a : List.{0} Bool) (b : List.{0} Bool) : + (OAI.EditApproximation.wordLEWithWork a b).1 = true ↔ OAI.EditApproximation.bitWordValue a ≤ OAI.EditApproximation.bitWordValue b := by + simp only [OAI.EditApproximation.wordLEWithWork, Bool.not_eq_true', decide_eq_false_iff_not, + proof_bitCompareWithWork_lt_16, not_lt] + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_queryNaturalLEWithWork_value_140 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.wordLEWithWork a.bits b.bits).1 = true ↔ a ≤ b := by + simp only [proof_wordLEWithWork_value_26, proof_bitWordValue_bits_15] + have proof_binaryNaturalCompareWithWork_lt_53 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.binaryNaturalCompareWithWork a b).1 = .lt ↔ a < b := by + simpa only [OAI.EditApproximation.binaryNaturalCompareWithWork, proof_bitWordValue_bits_15] using proof_bitCompareWithWork_lt_16 a.bits b.bits + have hinit := OAI.EditApproximation.queryPhysicalInitialFootprint source target N P F (A parent.val.pass) (a parent.val.pass) + multiplier parent occurrence symbolBits positionBits parent.val.state + unfold OAI.EditApproximation.queryChargedFamilyTableRawBand + refine OAI.EditApproximation.BitQuery.Footprint.chargeOf (OAI.EditApproximation.naturalWordLEAllocation parent.val.index.bits T.bits) ?_ + split + · exact (OAI.EditApproximation.queryChargedWarmupFootprint source target N P F (A parent.val.pass) (a parent.val.pass) + multiplier parent occurrence symbolBits positionBits).mapKeysWithWork _ (fun _ => 1) + · refine OAI.EditApproximation.BitQuery.Footprint.chargeOf (parent.val.node.1.val.bits.length + J.bits.length) ?_ + split + · let interval := OAI.EditApproximation.physicalSourceInterval source.length parent.val.node + refine OAI.EditApproximation.BitQuery.Footprint.chargeOf (OAI.EditApproximation.saturatingSubtractAllocation interval.hi interval.lo + + OAI.EditApproximation.naturalWordLEAllocation (OAI.EditApproximation.saturatingSubtractWithWork interval.hi interval.lo).1 [true]) ?_ + split + · exact hinit.mapKeysWithWork _ (fun _ => 1) + · exact (OAI.EditApproximation.queryFamilyBoundedActiveFootprintRawBand (R := R) source target N P F exponent H Q eM eF hP hM hF + tau (a parent.val.pass) eta kappa delta T S passes copies parent _ _).mapKeysWithWork _ + (fun _ => 1) + · exact hinit.mapKeysWithWork _ (fun _ => 1) + +def queryChargedFamilyGlobalFootprintRawBand + {M J R passes copies T S : ℕ} + [NeZero M] + [NeZero R] + (source target : List ℕ) + (N P F exponent H Q eM eF : ℕ) + (hP : 0 < P) + (hM : M = 2 ^ eM) + (hF : F = 2 ^ eF) + (A a : ℕ → OAI.EditApproximation.BinaryFraction) + (tau eta kappa delta : OAI.EditApproximation.BinaryFraction) + (multiplier : ℕ → ℕ) + (occurrence : OAI.EditApproximation.BinaryMemo OAI.EditApproximation.PositionCounts) + (symbolBits positionBits : ℕ) + (coarse : OAI.EditApproximation.PhysicalEntry M J target.length → OAI.EditApproximation.BinaryFraction × ℕ) + (allocation : OAI.EditApproximation.PhysicalEntry M J target.length → ℕ) + (request : OAI.EditApproximation.ChargedPhysicalRequest M J target.length (passes + 1) copies T S) : (OAI.EditApproximation.queryChargedFamilyGlobalRawBand (R := R) source target N P F exponent H Q eM eF hP hM hF A a tau eta kappa delta + multiplier occurrence symbolBits positionBits coarse request).Footprint := by + cases request with + | inl entry => exact OAI.EditApproximation.BitQuery.Footprint.compute (coarse entry) (allocation entry) + | inr parent => + exact OAI.EditApproximation.queryChargedFamilyTableFootprintRawBand (R := R) source target N P F exponent H Q eM eF hP hM hF + A a tau eta kappa delta multiplier occurrence symbolBits positionBits parent + +def queryFamilyMemoRawFootprintRawBand + {M J R passes copies T S : ℕ} + [NeZero M] + [NeZero R] + (source target : List ℕ) + (N P F exponent H Q eM eF : ℕ) + (hP : 0 < P) + (hM : M = 2 ^ eM) + (hF : F = 2 ^ eF) + (A a : ℕ → OAI.EditApproximation.BinaryFraction) + (tau eta kappa delta : OAI.EditApproximation.BinaryFraction) + (multiplier : ℕ → ℕ) + (occurrence : OAI.EditApproximation.BinaryMemo OAI.EditApproximation.PositionCounts) + (symbolBits positionBits : ℕ) + (coarse : OAI.EditApproximation.PhysicalEntry M J target.length → OAI.EditApproximation.BinaryFraction × ℕ) + (allocation : OAI.EditApproximation.PhysicalEntry M J target.length → ℕ) + (draw : OAI.EditApproximation.PhysicalFamilyScalarDraw (M := M) (J := J) (R := R) target N P F exponent H Q passes copies) + (key : OAI.EditApproximation.QueryFamilyMemoKey (M := M) (J := J) (R := R) (passes := passes) (copies := copies) (T := T) (S := S) target N P F exponent H Q) : (OAI.EditApproximation.queryFamilyMemoRawRawBand (R := R) source target N P F exponent H Q eM eF hP hM hF A a tau eta kappa delta + multiplier occurrence symbolBits positionBits coarse draw key).Footprint := by + cases key with + | inl scalar => + exact OAI.EditApproximation.BitQuery.Footprint.computeOf (OAI.EditApproximation.queryFamilySourceWordWithWork target N P F exponent H Q draw scalar) + (Nat.size (draw scalar).val + 2) + | inr request => + exact (OAI.EditApproximation.queryChargedFamilyGlobalFootprintRawBand source target N P F exponent H Q eM eF hP hM hF + A a tau eta kappa delta multiplier occurrence symbolBits positionBits coarse allocation request).mapKeysWithWork + _ (fun _ => 1) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open BitQuery +attribute [local instance] queryArityNeZero queryRoundsNeZero +open MeasureTheory ProbabilityTheory + +def computedQueryMemoRawFootprintRawBand + (source target : List ℕ) + (N : ℕ) + (occurrence : OAI.EditApproximation.BinaryMemo OAI.EditApproximation.PositionCounts) + (symbolBits positionBits : ℕ) + (input : OAI.EditApproximation.ComputedFamilyInput source target N) + (key : OAI.EditApproximation.ComputedFamilyMemoKey source target N) : (OAI.EditApproximation.computedQueryMemoRawRawBand source target N occurrence symbolBits positionBits input key).Footprint := by + have proof_computedParameterP_pos_141 (N : ℕ) : 0 < (OAI.EditApproximation.integerParameters N).P := + Nat.pow_pos (Nat.two_pow_pos _) + exact + OAI.EditApproximation.queryFamilyMemoRawFootprintRawBand source target N (OAI.EditApproximation.integerParameters N).P (OAI.EditApproximation.inputSmallLog N) + (40 * OAI.EditApproximation.smallLogExponent N) (OAI.EditApproximation.inputHeight N) (OAI.EditApproximation.inputSmallLog N ^ 80) + (OAI.EditApproximation.heightExponent N / 20) (OAI.EditApproximation.smallLogExponent N) (proof_computedParameterP_pos_141 N) rfl rfl + (fun pass => (OAI.EditApproximation.scheduledSeedWordWithWork N pass).1) + (fun pass => (OAI.EditApproximation.computedQueryParameters N pass).factor) + (OAI.EditApproximation.computedQueryParameters N 0).tau (OAI.EditApproximation.computedQueryParameters N 0).eta + (OAI.EditApproximation.computedQueryParameters N 0).kappa (OAI.EditApproximation.computedQueryParameters N 0).delta + (OAI.EditApproximation.scheduledSeedMultiplier N) occurrence symbolBits positionBits + (fun entry => (OAI.EditApproximation.BinaryFraction.nat (OAI.EditApproximation.clampedSeedNat input.1 entry), 0)) + (fun _ => 0) input.2 key + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open BitQuery +attribute [local instance] queryArityNeZero queryRoundsNeZero + +def computedQueryMemoFootprintRawBand + (source target : List ℕ) + (N : ℕ) + (occurrence : OAI.EditApproximation.BinaryMemo OAI.EditApproximation.PositionCounts) + (symbolBits positionBits : ℕ) + (input : OAI.EditApproximation.ComputedFamilyInput source target N) + (key : OAI.EditApproximation.ComputedFamilyMemoKey source target N) : (OAI.EditApproximation.computedQueryMemoNormalizedRawBand source target N occurrence symbolBits positionBits input + key).Footprint := by + have proof_trimBitWordWithWork_value_6 (bits : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.trimBitWordWithWork bits).1 = OAI.EditApproximation.bitWordValue bits := by + induction bits with + | nil => rfl + | cons bit bits ih => + simp only [OAI.EditApproximation.trimBitWordWithWork] + split_ifs with h + · have ht : OAI.EditApproximation.bitWordValue bits = 0 := by rw [← ih, h.1]; rfl + simp [h.2, OAI.EditApproximation.bitWordValue, ht] + · (simp only [OAI.EditApproximation.bitWordValue, ih]) + have proof_bitAdder_value_1 (a : Bool) (b : Bool) (carry : Bool) : + (OAI.EditApproximation.bitSum a b carry).toNat + 2 * (OAI.EditApproximation.bitCarry a b carry).toNat = + a.toNat + b.toNat + carry.toNat := by + cases a <;> cases b <;> cases carry <;> decide + have proof_bitAddWithWork_value_2 (left : List.{0} Bool) (right : List.{0} Bool) (carry : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitAddWithWork left right carry).1 = + OAI.EditApproximation.bitWordValue left + OAI.EditApproximation.bitWordValue right + carry.toNat := by + induction left generalizing right carry with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork] + induction right generalizing carry with + | nil => cases carry <;> simp [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue] + | cons b bs ih => + simp only [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 false b carry + simp only [Bool.toNat_false] at h + omega + | cons a as ih => + cases right with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a false carry + simp only [Bool.toNat_false] at h + omega + | cons b bs => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a b carry + omega + have proof_bitMulWithWork_value_0 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitMulWithWork left right).1 = OAI.EditApproximation.bitWordValue left * OAI.EditApproximation.bitWordValue right := by + induction left with + | nil => simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue] + | cons bit bits ih => + cases bit <;> simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue, proof_bitAddWithWork_value_2, ih] <;> ring + have proof_bitPowerWithWork_value_76 (base : List.{0} Bool) (n : ℕ) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitPowerWithWork base n).1 = OAI.EditApproximation.bitWordValue base ^ n := by + induction n with + | zero => (simp [OAI.EditApproximation.bitPowerWithWork, OAI.EditApproximation.bitWordValue]) + | succ n ih => + simp only [OAI.EditApproximation.bitPowerWithWork, proof_trimBitWordWithWork_value_6, proof_bitMulWithWork_value_0, ih, pow_succ] + have proof_refinementBaseWithWork_value_143 (ell : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.refinementBaseWithWork ell).1 = OAI.EditApproximation.bitWordValue ell ^ 10 + 1 := by + (simp only [OAI.EditApproximation.refinementBaseWithWork, proof_trimBitWordWithWork_value_6, proof_bitAddWithWork_value_2, + proof_bitPowerWithWork_value_76, OAI.EditApproximation.bitWordValue, Bool.toNat_true, Bool.toNat_false]) + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_computedQueryBase_value_144 (N : ℕ) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.computedQueryBase N) = OAI.EditApproximation.inputSmallLog N ^ 10 + 1 := by + simp only [OAI.EditApproximation.computedQueryBase, proof_refinementBaseWithWork_value_143, proof_bitWordValue_bits_15] + have proof_computedQueryBase_pos_142 (N : ℕ) : 0 < OAI.EditApproximation.bitWordValue (OAI.EditApproximation.computedQueryBase N) := by + rw [proof_computedQueryBase_value_144] + omega + exact + (OAI.EditApproximation.computedQueryMemoRawFootprintRawBand source target N occurrence symbolBits positionBits input + key).normalize + (OAI.EditApproximation.computedQueryBase N) (proof_computedQueryBase_pos_142 N) + (OAI.EditApproximation.queryFamilyMemoRemaining target N (OAI.EditApproximation.integerParameters N).P + (OAI.EditApproximation.inputSmallLog N) (40 * OAI.EditApproximation.smallLogExponent N) + (OAI.EditApproximation.inputHeight N) (OAI.EditApproximation.inputSmallLog N ^ 80) key) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open Filter MeasureTheory +attribute [local instance] queryRoundsNeZero + +def computedQueryTemporaryCellsFootprintRawBand (source target : List ℕ) (N : ℕ) + (occurrence : OAI.EditApproximation.BinaryMemo OAI.EditApproximation.PositionCounts) (symbolBits positionBits : ℕ) + (input : OAI.EditApproximation.ComputedFamilyInput source target N) : ℕ := + OAI.EditApproximation.BitQuery.Footprint.rankedBitMemoCells (OAI.EditApproximation.SourceRanked.rank OAI.EditApproximation.ChargedPhysicalRequest.rank) + (OAI.EditApproximation.computedQueryMemoNormalizedRawBand source target N occurrence symbolBits positionBits input) + (OAI.EditApproximation.computedQueryMemoFootprintRawBand source target N occurrence symbolBits positionBits input) + (16384 * OAI.EditApproximation.inputHeight N + 5) (OAI.EditApproximation.computedFamilyMemoCode source target N (OAI.EditApproximation.inputHeight N ^ 2)) + (fun key => (OAI.EditApproximation.computedFamilyMemoCodeWithWork source target N (OAI.EditApproximation.inputHeight N ^ 2) key).2) + (.inr (OAI.EditApproximation.localFinalRootRequest target N (OAI.EditApproximation.integerParameters N).T (OAI.EditApproximation.integerParameters N).S + (OAI.EditApproximation.inputHeight N) (Nat.two_pow_pos _) (OAI.EditApproximation.finalTargetState target.length))) .empty + +noncomputable def integerAcceptedSpaceTermsFootprintRawBand (source target : List ℤ) (N : ℕ) + (epsilon : OAI.EditApproximation.BinaryFraction) + (input : OAI.EditApproximation.ComputedFamilyInput (source.map OAI.EditApproximation.integerSymbolCode) (target.map OAI.EditApproximation.integerSymbolCode) N) : List ℕ := + let x := source.map OAI.EditApproximation.integerSymbolCode + let y := target.map OAI.EditApproximation.integerSymbolCode + [8 * OAI.EditApproximation.integerPreevaluationWork source target N epsilon, + 2 * OAI.EditApproximation.integerStoredDataSpace source target, + OAI.EditApproximation.computedQuerySetupAllocation N, + (OAI.EditApproximation.computedQueryMemoResultRawBand x y N (OAI.EditApproximation.integerOccurrenceIndex source target) + (OAI.EditApproximation.integerInputSymbolBits source target) (OAI.EditApproximation.integerInputPositionBits target) input).memory.fractionStorage, + OAI.EditApproximation.computedQueryTemporaryCellsFootprintRawBand x y N (OAI.EditApproximation.integerOccurrenceIndex source target) + (OAI.EditApproximation.integerInputSymbolBits source target) (OAI.EditApproximation.integerInputPositionBits target) input, + OAI.EditApproximation.computedFamilyCoarseCopyStorage x y N input, + OAI.EditApproximation.computedFamilyCoarseArrayCapacity x y N input, + OAI.EditApproximation.computedFamilyCoarseScratchCapacity x y N input, + OAI.EditApproximation.computedFamilyCoarseControlCapacity x y N input, + 4 * (OAI.EditApproximation.inputHeight N + (OAI.EditApproximation.integerParameters N).B + 4), + OAI.EditApproximation.integerFinalAllocationRawBand source target N input, + 8 * (N + 1)] + +noncomputable def integerBinarySpaceFootprintRawBand (source target : List ℤ) (N : ℕ) (epsilon : OAI.EditApproximation.BinaryFraction) + (outcome : OAI.EditApproximation.ComputedFullOutcome (source.map OAI.EditApproximation.integerSymbolCode) (target.map OAI.EditApproximation.integerSymbolCode) N) : ℕ := + if OAI.EditApproximation.physicalLargeInput N epsilon then + match outcome with + | .inl _ => 8 * OAI.EditApproximation.integerPreevaluationWork source target N epsilon + + 2 * OAI.EditApproximation.integerStoredDataSpace source target + + OAI.EditApproximation.suffixDPAllocation (source.map OAI.EditApproximation.integerSymbolCode) (target.map OAI.EditApproximation.integerSymbolCode) + 8 * (N + 1) + | .inr execution => (OAI.EditApproximation.integerAcceptedSpaceTermsFootprintRawBand source target N epsilon + (OAI.EditApproximation.computedExecutionAccepted _ _ N execution)).sum + else 8 * OAI.EditApproximation.integerPreevaluationWork source target N epsilon + + 2 * OAI.EditApproximation.integerStoredDataSpace source target + + OAI.EditApproximation.suffixDPAllocation (source.map OAI.EditApproximation.integerSymbolCode) (target.map OAI.EditApproximation.integerSymbolCode) + 8 * (N + 1) + + + +end OAI.EditApproximation +end diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/Accuracy.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/Accuracy.lean new file mode 100644 index 0000000000000000000000000000000000000000..3c9f67c3a68287539603b8fd05c5c6f02758dce8 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/Accuracy.lean @@ -0,0 +1,119 @@ +import Mathlib + +namespace OAI + +/-! +# Accuracy assembly for the edit-distance approximation scheme + +The probability and integer-conversion bounds of Section 8 of +*An Almost-Linear Approximation Scheme for Edit Distance* +(OpenAI, September 24, 2026) follow from the refinement estimate and +simultaneous seed guarantee using Markov's inequality. +-/ + +namespace EditApproximation + +open MeasureTheory + +/-- The implementation clamps to the input length and rounds down. -/ +noncomputable def integerAnswer (N : ℕ) (value : ℝ) : ℕ := + ⌊max 0 (min (N : ℝ) value)⌋₊ + +/-- Clamping and rounding down preserve a one-sided approximation of an +integer distance. This does not assert that an estimator has that bound. -/ +theorem integerAnswer_spec {N D : ℕ} {value ε : ℝ} + (hDN : D ≤ N) (hε : 0 ≤ ε) + (hlower : (D : ℝ) ≤ value) (hupper : value ≤ (1 + ε) * D) : + D ≤ integerAnswer N value ∧ + (integerAnswer N value : ℝ) ≤ (1 + ε) * D := by + have hD : (0 : ℝ) ≤ D := Nat.cast_nonneg D + have hmin : (D : ℝ) ≤ min (N : ℝ) value := + le_min (by exact_mod_cast hDN) hlower + have hnonneg : 0 ≤ max 0 (min (N : ℝ) value) := le_max_left _ _ + constructor + · exact (Nat.le_floor_iff hnonneg).2 (hmin.trans (le_max_right _ _)) + · apply (Nat.floor_le hnonneg).trans + exact max_le (by positivity) ((min_le_right _ _).trans hupper) + +@[simp] theorem integerAnswer_zero (N : ℕ) : integerAnswer N 0 = 0 := by + simp [integerAnswer, Nat.cast_nonneg] + +/-- The positive excess on executions having a good seed. -/ +noncomputable def goodExcess {Ω : Type*} (G : Set Ω) (value : Ω → ℝ) (D : ℕ) : + Ω → ℝ := G.indicator (fun ω => max (value ω - D) 0) + +theorem goodExcess_nonneg {Ω : Type*} (G : Set Ω) (value : Ω → ℝ) (D : ℕ) + (ω : Ω) : 0 ≤ goodExcess G value D ω := by + classical + by_cases hω : ω ∈ G <;> simp [goodExcess, hω] + +/-- Markov's inequality converts the positive-excess expectation bound of +Section 8 into an approximation tail bound. -/ +theorem goodExcess_tail {Ω : Type*} [MeasurableSpace Ω] + (μ : Measure Ω) [IsFiniteMeasure μ] + {G : Set Ω} {value : Ω → ℝ} {D : ℕ} {ℓ ε : ℝ} + (hD : 0 < D) (hℓ : 0 < ℓ) (hε : 0 < ε) + (hint : Integrable (goodExcess G value D) μ) + (hmoment : (∫ ω, goodExcess G value D ω ∂μ) ≤ (D : ℝ) / ℓ) : + μ.real {ω | ε * D ≤ goodExcess G value D ω} ≤ 1 / (ℓ * ε) := by + have hDr : (0 : ℝ) < D := by exact_mod_cast hD + have hmarkov := mul_meas_ge_le_integral_of_nonneg + (ae_of_all μ (goodExcess_nonneg G value D)) hint (ε * D) + have htail : μ.real {ω | ε * D ≤ goodExcess G value D ω} ≤ + ((D : ℝ) / ℓ) / (ε * D) := + (le_div_iff₀ (mul_pos hε hDr)).2 (by + simpa only [mul_comm] using hmarkov.trans hmoment) + have hratio : ((D : ℝ) / ℓ) / (ε * D) = 1 / (ℓ * ε) := by + field_simp + rwa [hratio] at htail + +/-- Final probability assembly, with the two genuinely unresolved +algorithmic guarantees exposed: a good-seed event and its excess moment. +The stronger success probability `4/5` implies the paper's `2/3`. -/ +theorem final_answer_accuracy {Ω : Type*} [MeasurableSpace Ω] + (μ : Measure Ω) [IsProbabilityMeasure μ] + {G : Set Ω} {value : Ω → ℝ} {N D : ℕ} {ℓ ε : ℝ} + (hvalue : Measurable value) (hDN : D ≤ N) (hD : 0 < D) + (hℓ : 0 < ℓ) (hε : 0 < ε) (haccuracy : 10 ≤ ℓ * ε) + (hseed : μ.real Gᶜ ≤ 1 / 10) + (hlower : ∀ ω ∈ G, (D : ℝ) ≤ value ω) + (hint : Integrable (goodExcess G value D) μ) + (hmoment : (∫ ω, goodExcess G value D ω ∂μ) ≤ (D : ℝ) / ℓ) : + (4 / 5 : ℝ) ≤ μ.real {ω | D ≤ integerAnswer N (value ω) ∧ + (integerAnswer N (value ω) : ℝ) ≤ (1 + ε) * D} := by + classical + let S : Set Ω := {ω | (D : ℝ) ≤ value ω ∧ value ω ≤ (1 + ε) * D} + let B : Set Ω := {ω | ε * D ≤ goodExcess G value D ω} + have hS : MeasurableSet S := + (measurableSet_le measurable_const hvalue).inter + (measurableSet_le hvalue measurable_const) + have hbad : Sᶜ ⊆ Gᶜ ∪ B := by + intro ω hω + by_cases hG : ω ∈ G + · right + have hupper : (1 + ε) * D < value ω := by + by_contra hn + exact hω ⟨hlower ω hG, le_of_not_gt hn⟩ + change ε * D ≤ goodExcess G value D ω + simp only [goodExcess, Set.indicator_of_mem hG] + apply le_trans _ (le_max_left _ _) + nlinarith + · exact Or.inl hG + have htail : μ.real B ≤ 1 / (ℓ * ε) := + goodExcess_tail μ hD hℓ hε hint hmoment + have hratio : 1 / (ℓ * ε) ≤ (1 / 10 : ℝ) := by + exact one_div_le_one_div_of_le (by norm_num) haccuracy + have hfail : μ.real Sᶜ ≤ (1 / 5 : ℝ) := calc + μ.real Sᶜ ≤ μ.real (Gᶜ ∪ B) := measureReal_mono hbad + _ ≤ μ.real Gᶜ + μ.real B := measureReal_union_le (μ := μ) _ _ + _ ≤ 1 / 5 := by linarith + have hmass : μ.real S + μ.real Sᶜ = 1 := by + simpa using measureReal_add_measureReal_compl (μ := μ) hS + have hsuccess : (4 / 5 : ℝ) ≤ μ.real S := by linarith + apply hsuccess.trans + exact measureReal_mono (μ := μ) (fun ω hω => + integerAnswer_spec hDN hε.le hω.1 hω.2) + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/AccuracyCutoff.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/AccuracyCutoff.lean new file mode 100644 index 0000000000000000000000000000000000000000..1c9430a2b399aecfc027add0d322722688fa31e5 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/AccuracyCutoff.lean @@ -0,0 +1,54 @@ +import OAI.Combinatorics.EditApproximation.Geometry.Parameters +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! A computable fixed-accuracy cutoff. The algorithm tests the small-log +conditions directly; it does not construct the double exponential bound. -/ + +namespace EditApproximation + + + + + +def accuracyCutoffExponent (epsilon : ℚ) : ℕ := max (2 ^ 1000) ⌈10 / epsilon⌉₊ + +def accuracyCutoff (epsilon : ℚ) : ℕ := 2 ^ (2 ^ accuracyCutoffExponent epsilon) + +theorem largeAccuracyInput_pos (N : ℕ) (epsilon : ℚ) (h : largeAccuracyInput N epsilon) : 0 < N := by + have htwo : 2 ≤ (2 : ℕ) ^ 1000 := by + simpa only [pow_one] using pow_le_pow_right₀ (by decide : 1 ≤ (2 : ℕ)) (by decide : 1 ≤ 1000) + have hell : 2 ≤ inputSmallLog N := htwo.trans h.1 + by_contra hn + have hzero : N = 0 := Nat.eq_zero_of_not_pos hn + rw [hzero] at hell + norm_num [inputSmallLog, smallLogExponent, heightExponent] at hell + +theorem heightExponent_above_double_power (N exponent : ℕ) (h : 2 ^ (2 ^ exponent) ≤ N) : + exponent ≤ heightExponent N := by + have hfirst := Nat.clog_mono_right 2 (h.trans (Nat.le_add_right N 2)) + rw [Nat.clog_pow _ _ (by decide : 1 < (2 : ℕ))] at hfirst + have hsecond := Nat.clog_mono_right 2 hfirst + simpa only [Nat.clog_pow _ _ (by decide : 1 < (2 : ℕ)), heightExponent] using hsecond + +theorem accuracyCutoff_sufficient (N : ℕ) (epsilon : ℚ) (hepsilon : 0 < epsilon) + (hN : accuracyCutoff epsilon ≤ N) : largeAccuracyInput N epsilon := by + have hpositive : 0 < N := (Nat.two_pow_pos _).trans_le hN + have he : accuracyCutoffExponent epsilon ≤ inputSmallLog N := + (heightExponent_above_double_power N (accuracyCutoffExponent epsilon) hN).trans + (inputSmallLog_bounds N hpositive).1 + constructor + · exact (le_max_left _ _).trans he + · have hc : (10 / epsilon : ℚ) ≤ (inputSmallLog N : ℚ) := + (Nat.le_ceil _).trans (Nat.cast_le.mpr ((le_max_right _ _).trans he)) + exact (div_le_iff₀ hepsilon).mp hc + +theorem largeAccuracyInput_real (N : ℕ) (epsilon : ℚ) (h : largeAccuracyInput N epsilon) : + 2 ^ 1000 ≤ inputSmallLog N ∧ 10 ≤ (inputSmallLog N : ℝ) * (epsilon : ℝ) := + ⟨h.1, by exact_mod_cast h.2⟩ + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/AccuracyPrefixInspection.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/AccuracyPrefixInspection.lean new file mode 100644 index 0000000000000000000000000000000000000000..ba194d47bfb3e3b7289252c2f2026dc021d2769b --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/AccuracyPrefixInspection.lean @@ -0,0 +1,66 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryFractionWork +import OAI.Combinatorics.EditApproximation.Refinement.ComputedNumericalParameters +import OAI.Combinatorics.EditApproximation.Geometry.ParameterAsymptotics +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! The uniform program inspects only a logarithmically bounded prefix +of each accuracy word. An encoding exceeding this bound takes the exact +fallback, without first scanning or retaining its unbounded suffix. -/ + +namespace EditApproximation + +/-- One step reads a constructor of the input word. -/ + + + theorem inspectBitPrefix_accepts (budget : ℕ) (word : List Bool) : + (inspectBitPrefix budget word).1 = true ↔ word.length ≤ budget := by + induction budget generalizing word with + | zero => cases word <;> simp [inspectBitPrefix] + | succ budget ih => + cases word with + | nil => simp [inspectBitPrefix] + | cons bit rest => simpa only [inspectBitPrefix, List.length_cons, Nat.add_le_add_iff_right] using ih rest + + theorem inspectBitPrefix_cost (budget : ℕ) (word : List Bool) : + (inspectBitPrefix budget word).2 ≤ budget + 1 := by + induction budget generalizing word with + | zero => cases word <;> exact le_rfl + | succ budget ih => + cases word with + | nil => exact Nat.succ_le_succ (Nat.zero_le _) + | cons bit rest => exact Nat.add_le_add_right (ih rest) 1 + +/-- On acceptance the input words are already bounded; returning the +input value only retains those bounded words. -/ + + + theorem inspectAccuracyWithWork_spec (budget : ℕ) (epsilon : BinaryFraction) : + (inspectAccuracyWithWork budget epsilon).1 = + if epsilon.width ≤ budget then some epsilon else none := by + simp only [inspectAccuracyWithWork, BinaryFraction.width, max_le_iff] + by_cases hn : epsilon.numerator.bits.length ≤ budget <;> + by_cases hd : epsilon.denominator.length ≤ budget + all_goals + have hnum := inspectBitPrefix_accepts budget epsilon.numerator.bits + have hden := inspectBitPrefix_accepts budget epsilon.denominator + simp_all + + theorem inspectAccuracyWithWork_cost (budget : ℕ) (epsilon : BinaryFraction) : + (inspectAccuracyWithWork budget epsilon).2 ≤ 2 * budget + 4 := by + have hn := inspectBitPrefix_cost budget epsilon.numerator.bits + have hd := inspectBitPrefix_cost budget epsilon.denominator + change (inspectBitPrefix budget epsilon.numerator.bits).2 + + (inspectBitPrefix budget epsilon.denominator).2 + 2 ≤ _ + omega + + theorem inspectAccuracy_eventually_accepts (epsilon : BinaryFraction) : + ∀ᶠ N in Filter.atTop, (inspectAccuracyWithWork (inputHeight N) epsilon).1 = some epsilon := by + filter_upwards [inputSmallLog_tendsto.eventually (Filter.eventually_ge_atTop epsilon.width)] with N hN + rw [inspectAccuracyWithWork_spec, ite_eq_left (hN.trans (computed_smallLog_le_height N))] + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/ActionLower.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/ActionLower.lean new file mode 100644 index 0000000000000000000000000000000000000000..2addd594b138755a0fff42ccc23eadecceac86bb --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/ActionLower.lean @@ -0,0 +1,76 @@ +import OAI.Combinatorics.EditApproximation.Geometry.Connections + +namespace OAI + +/-! +# Preservation of the two action lower bounds + +The action invariant follows from actual edit and shift connection +inequalities, rather than an assumed lower-bound-preserving oracle. +-/ + +namespace EditApproximation + +open EditDistortion + +theorem list_sum_map_le {ι : Type*} (entries : List ι) (f g : ι → ℝ) + (h : ∀ i ∈ entries, f i ≤ g i) : (entries.map f).sum ≤ (entries.map g).sum := by + induction entries with + | nil => rfl + | cons i rest ih => + simp only [List.map_cons, List.sum_cons] + exact add_le_add (h i (by simp)) (ih fun j hj => h j (by simp [hj])) + +theorem list_sum_map_div {ι : Type*} (entries : List ι) (f : ι → ℝ) (a : ℝ) : + (entries.map fun i => f i / a).sum = (entries.map f).sum / a := by + induction entries with + | nil => simp + | cons i rest ih => simp only [List.map_cons, List.sum_cons, ih, add_div] + +theorem actual_action_lower {α : Type*} (word : List α) + (children : List (List α × TargetInterval word.length)) + (parent : TargetInterval word.length) (a : ℝ) (ha : 1 ≤ a) + (value : (List α × TargetInterval word.length) → ℝ) + (hcost : ∀ child ∈ children, + (edit child.1 (substring word child.2.lo child.2.hi) : ℝ) / a ≤ value child) + (hgap : ∀ child ∈ children, + |signedLengthGap child.1 (substring word child.2.lo child.2.hi)| ≤ value child) : + max ((edit (children.map Prod.fst).flatten (substring word parent.lo parent.hi) : ℝ) / a) + |signedLengthGap (children.map Prod.fst).flatten (substring word parent.lo parent.hi)| ≤ + (connectionBudget parent.lo (children.map Prod.snd) parent.hi : ℝ) + + (children.map value).sum := by + have ha0 : 0 < a := by linarith + let conn : ℝ := connectionBudget parent.lo (children.map Prod.snd) parent.hi + have hconn0 : 0 ≤ conn := Nat.cast_nonneg _ + have hconnDiv : conn / a ≤ conn := by + apply (div_le_iff₀ ha0).2 + nlinarith + apply max_le + · have hconnection : + (edit (children.map Prod.fst).flatten (substring word parent.lo parent.hi) : ℝ) ≤ + (children.map fun child => + (edit child.1 (substring word child.2.lo child.2.hi) : ℝ)).sum + conn := by + dsimp only [conn] + have hcast (entries : List (List α × TargetInterval word.length)) : + (((entries.map fun child => + edit child.1 (substring word child.2.lo child.2.hi)).sum : ℕ) : ℝ) = + (entries.map fun child => + (edit child.1 (substring word child.2.lo child.2.hi) : ℝ)).sum := by + induction entries with + | nil => simp + | cons child rest ih => simp only [List.map_cons, List.sum_cons, Nat.cast_add, ih] + rw [← hcast] + exact_mod_cast child_connection_bound word children parent + have hdivide := div_le_div_of_nonneg_right hconnection ha0.le + rw [add_div] at hdivide + have hsum := list_sum_map_le children _ value hcost + rw [list_sum_map_div] at hsum + linarith + · have hconnection := child_shift_connection_bound word children parent + have hsum := list_sum_map_le children _ value hgap + change _ ≤ conn + _ + linarith + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/ActionVectors.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/ActionVectors.lean new file mode 100644 index 0000000000000000000000000000000000000000..171837dfd6340e26fcc9e20214e3d724ca2a17de --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/ActionVectors.lean @@ -0,0 +1,204 @@ +import OAI.Combinatorics.EditApproximation.Numerics.Numerics +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! +# The actual fixed-block action hull + +Coordinates are precisely the child/state pairs occurring in a finite band. +Each action assigns its fixed rational child mass to one state per child. +This verifies the probability, coverage and block-mass hypotheses used by +the numerical optimizer and optimistic entropy regret. +-/ + +namespace EditApproximation + +open Finset + + + + + +theorem action_coordinate_mem {β σ : Type*} [Fintype β] [DecidableEq β] [DecidableEq σ] + (band : Finset (β → σ)) {action : β → σ} (haction : action ∈ band) (child : β) : + (child, action child) ∈ bandCoordinates band := by + apply mem_biUnion.mpr + exact ⟨action, haction, mem_image.mpr ⟨child, mem_univ _, rfl⟩⟩ + +theorem actionVector_probability {β σ : Type*} [Fintype β] [Nonempty β] + [DecidableEq β] [DecidableEq σ] (band : Finset (β → σ)) + (mass : β → ℚ) (hpos : ∀ child, 0 < mass child) + {action : β → σ} (haction : action ∈ band) : + (∀ coordinate ∈ bandCoordinates band, (0 : ℝ) ≤ actionVector mass action coordinate) ∧ + (∑ coordinate ∈ bandCoordinates band, (actionVector mass action coordinate : ℝ)) = 1 := by + have htotal : (0 : ℚ) < ∑ child, mass child := sum_pos (fun child _ => hpos child) univ_nonempty + constructor + · intro coordinate _ + unfold actionVector + split_ifs + · exact_mod_cast (div_pos (hpos _) htotal).le + · norm_num + · have hsubset : (univ.image fun child => (child, action child)) ⊆ bandCoordinates band := by + intro coordinate hc + obtain ⟨child, _, rfl⟩ := mem_image.mp hc + exact action_coordinate_mem band haction child + have hsum : (∑ coordinate ∈ bandCoordinates band, (actionVector mass action coordinate : ℝ)) = + ∑ coordinate ∈ univ.image (fun child => (child, action child)), + (actionVector mass action coordinate : ℝ) := by + symm + apply sum_subset hsubset + intro coordinate _ hnot + have hne : coordinate.2 ≠ action coordinate.1 := by + intro heq + exact hnot (mem_image.mpr ⟨coordinate.1, mem_univ _, Prod.ext rfl heq.symm⟩) + simp only [actionVector, ite_eq_right hne, Rat.cast_zero] + rw [hsum, sum_image] + · simp only [actionVector, ite_true, Rat.cast_div] + rw [← sum_div] + have hcast : (∑ child, (mass child : ℝ)) = ((∑ child, mass child : ℚ) : ℝ) := by + norm_cast + rw [hcast] + exact div_self (by exact_mod_cast htotal.ne') + · intro i _ j _ hij + exact congrArg Prod.fst hij + +theorem actionVector_coordinate_coverage {β σ : Type*} [Fintype β] [Nonempty β] + [DecidableEq β] [DecidableEq σ] (band : Finset (β → σ)) + (mass : β → ℚ) (hpos : ∀ child, 0 < mass child) : + ∀ coordinate ∈ bandCoordinates band, ∃ action ∈ band, + (0 : ℝ) < actionVector mass action coordinate := by + intro coordinate hcoordinate + obtain ⟨action, ha, hcoordinate⟩ := mem_biUnion.mp hcoordinate + obtain ⟨child, _, heq⟩ := mem_image.mp hcoordinate + subst coordinate + refine ⟨action, ha, ?_⟩ + simp only [actionVector, ite_true] + have htotal : (0 : ℚ) < ∑ child, mass child := sum_pos (fun child _ => hpos child) univ_nonempty + exact_mod_cast div_pos (hpos child) htotal + +theorem actionVector_block_mass {β σ : Type*} [Fintype β] [DecidableEq β] [DecidableEq σ] + (band : Finset (β → σ)) (mass : β → ℚ) + {action : β → σ} (haction : action ∈ band) (child : β) : + (∑ coordinate ∈ bandCoordinates band with coordinate.1 = child, + (actionVector mass action coordinate : ℝ)) = + (mass child / (∑ i, mass i) : ℚ) := by + rw [sum_eq_single (child, action child)] + · simp only [actionVector, ite_true] + · intro coordinate hc hne + have hchild : coordinate.1 = child := (mem_filter.mp hc).2 + have hstate : coordinate.2 ≠ action child := by + intro hstate + exact hne (Prod.ext hchild hstate) + simp only [actionVector, hchild, ite_eq_right hstate, Rat.cast_zero] + · intro hnot + exact False.elim (hnot (mem_filter.mpr ⟨action_coordinate_mem band haction child, rfl⟩)) + +theorem actionVector_inner_product {β σ : Type*} [Fintype β] + [DecidableEq β] [DecidableEq σ] (band : Finset (β → σ)) + (mass : β → ℚ) (gain : β × σ → ℝ) + {action : β → σ} (haction : action ∈ band) : + (∑ coordinate ∈ bandCoordinates band, gain coordinate * (actionVector mass action coordinate : ℝ)) = + ∑ child, gain (child, action child) * (mass child / (∑ i, mass i) : ℚ) := by + have hsubset : (univ.image fun child => (child, action child)) ⊆ bandCoordinates band := by + intro coordinate hc + obtain ⟨child, _, rfl⟩ := mem_image.mp hc + exact action_coordinate_mem band haction child + have hsum : (∑ coordinate ∈ bandCoordinates band, + gain coordinate * (actionVector mass action coordinate : ℝ)) = + ∑ coordinate ∈ univ.image (fun child => (child, action child)), + gain coordinate * (actionVector mass action coordinate : ℝ) := by + symm + apply sum_subset hsubset + intro coordinate _ hnot + have hne : coordinate.2 ≠ action coordinate.1 := by + intro heq + exact hnot (mem_image.mpr ⟨coordinate.1, mem_univ _, Prod.ext rfl heq.symm⟩) + simp only [actionVector, ite_eq_right hne, Rat.cast_zero, mul_zero] + rw [hsum, sum_image] + · simp only [actionVector, ite_true] + · intro i _ j _ hij + exact congrArg Prod.fst hij + +/-- The coordinate normalization translates entropy gains exactly into +the unnormalized costs of a band action. -/ +theorem actionVector_cost_identity {β σ : Type*} [Fintype β] [Nonempty β] + [DecidableEq β] [DecidableEq σ] (band : Finset (β → σ)) + (mass : β → ℚ) (hpos : ∀ child, 0 < mass child) (cost : β × σ → ℝ) + {action : β → σ} (haction : action ∈ band) : + -((∑ child, mass child : ℚ) : ℝ) * + (∑ coordinate ∈ bandCoordinates band, + (-cost coordinate / (mass coordinate.1 : ℝ)) * (actionVector mass action coordinate : ℝ)) = + ∑ child, cost (child, action child) := by + rw [actionVector_inner_product band mass _ haction, mul_sum] + apply sum_congr rfl + intro child _ + have hmass : (mass child : ℝ) ≠ 0 := by exact_mod_cast (hpos child).ne' + have htotal : ((∑ child, mass child : ℚ) : ℝ) ≠ 0 := by + exact_mod_cast (sum_pos (fun child _ => hpos child) univ_nonempty).ne' + rw [Rat.cast_div] + field_simp + +theorem band_block_nonempty {β σ : Type*} [Fintype β] [DecidableEq β] [DecidableEq σ] + (band : Finset (β → σ)) (hband : band.Nonempty) (child : β) : + ((bandCoordinates band).filter fun coordinate => coordinate.1 = child).Nonempty := by + obtain ⟨action, ha⟩ := hband + exact ⟨(child, action child), mem_filter.mpr ⟨action_coordinate_mem band ha child, rfl⟩⟩ + +theorem band_hull_block_mass {β σ : Type*} [Fintype β] [DecidableEq β] [DecidableEq σ] + (band : Finset (β → σ)) (mass : β → ℚ) (child : β) + (p : β × σ → ℝ) + (hp : p ∈ convexHull ℝ (rationalVertexSet (band.toList.map (actionVector mass)))) : + (∑ coordinate ∈ bandCoordinates band with coordinate.1 = child, p coordinate) = + (mass child / (∑ i, mass i) : ℚ) := by + let targetMass : ℝ := (mass child / (∑ i, mass i) : ℚ) + have hconvex : Convex ℝ {q : β × σ → ℝ | + (∑ coordinate ∈ bandCoordinates band with coordinate.1 = child, q coordinate) = + targetMass} := by + intro x hx y hy a b _ _ hab + change (∑ coordinate ∈ bandCoordinates band with coordinate.1 = child, + (a * x coordinate + b * y coordinate)) = targetMass + rw [sum_add_distrib, ← mul_sum, ← mul_sum, hx, hy] + calc + a * targetMass + b * targetMass = (a + b) * targetMass := by ring + _ = targetMass := by rw [hab, one_mul] + have hsubset : rationalVertexSet (band.toList.map (actionVector mass)) ⊆ + {q : β × σ → ℝ | + (∑ coordinate ∈ bandCoordinates band with coordinate.1 = child, q coordinate) = + targetMass} := by + rintro _ ⟨vertex, hv, rfl⟩ + obtain ⟨action, ha, rfl⟩ := List.mem_map.mp hv + exact actionVector_block_mass band mass (mem_toList.mp ha) child + exact convexHull_min hsubset hconvex hp + +theorem band_entropy_optimizer {β σ : Type*} [Fintype β] [Nonempty β] + [DecidableEq β] [DecidableEq σ] (band : Finset (β → σ)) (hband : band.Nonempty) + (mass : β → ℚ) (hpos : ∀ child, 0 < mass child) + (linear : β × σ → ℚ) (H : ℕ) (hH : 4 ≤ H) : + let coordinates := bandCoordinates band + let vertices := band.toList.map (actionVector mass) + ∃ maximizer ∈ convexHull ℝ (rationalVertexSet vertices), + IsMaxOn (entropyValue coordinates 1 (fun i => (linear i : ℝ))) + (convexHull ℝ (rationalVertexSet vertices)) maximizer ∧ + (∑ i ∈ coordinates, |(finiteRationalOptimizer coordinates vertices linear + (H + coordinates.card + 2) ((H + coordinates.card + 2) ^ 80) i : ℝ) - maximizer i|) ≤ + 1 / (H : ℝ) ^ 3 := by + dsimp only + have hvertices : band.toList.map (actionVector mass) ≠ [] := by + obtain ⟨action, ha⟩ := hband + intro hnil + have hmem : actionVector mass action ∈ band.toList.map (actionVector mass) := + List.mem_map.mpr ⟨action, mem_toList.mpr ha, rfl⟩ + simp only [hnil, List.not_mem_nil] at hmem + apply finite_entropy_optimizer _ _ _ _ hvertices hH + · intro p hp + obtain ⟨action, ha, rfl⟩ := List.mem_map.mp hp + exact actionVector_probability band mass hpos (mem_toList.mp ha) + · intro coordinate hc + obtain ⟨action, ha, hpositive⟩ := actionVector_coordinate_coverage band mass hpos coordinate hc + exact ⟨actionVector mass action, List.mem_map.mpr ⟨action, mem_toList.mpr ha, rfl⟩, hpositive⟩ + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/ActualActionValues.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/ActualActionValues.lean new file mode 100644 index 0000000000000000000000000000000000000000..1756092961aa70417cc60fcd85b215cbc33aaee8 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/ActualActionValues.lean @@ -0,0 +1,84 @@ +import OAI.Combinatorics.EditApproximation.Geometry.ActionLower +import OAI.Combinatorics.EditApproximation.Geometry.BalancedIntervals +import OAI.Combinatorics.EditApproximation.Geometry.StateGeometry +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! +# Connection values at labeled physical children + +Child table values retain their child labels even when two source +substrings coincide. The edit and shift lower bounds are proved for +the actual finite sum of these labeled values. +-/ + +namespace EditApproximation + +open Finset EditDistortion + + + +noncomputable def endpointActionValue {n M : ℕ} (q : TargetInterval n) + (states : Fin M → TargetInterval n) (value : Fin M → TargetInterval n → ℝ) : ℝ := + endpointActionConnection q states + ∑ i, value i (states i) + +theorem actual_endpoint_action_lower {α : Type*} (source target : List α) + {M : ℕ} (hM : 0 < M) (parent : TargetInterval source.length) + (q : TargetInterval target.length) (states : Fin M → TargetInterval target.length) + (a : ℝ) (ha : 1 ≤ a) (value : Fin M → TargetInterval target.length → ℝ) + (hcost : ∀ i, (stateEditCost + (substring source (sourceChild parent i).lo (sourceChild parent i).hi) target (states i) : ℝ) / a ≤ + value i (states i)) + (hgap : ∀ i, |stateLengthGap + (substring source (sourceChild parent i).lo (sourceChild parent i).hi) target (states i)| ≤ + value i (states i)) : + max ((stateEditCost (substring source parent.lo parent.hi) target q : ℝ) / a) + |stateLengthGap (substring source parent.lo parent.hi) target q| ≤ + endpointActionValue q states value := by + let piece := fun i : Fin M => + substring source (sourceChild parent i).lo (sourceChild parent i).hi + let children := List.ofFn fun i : Fin M => (piece i, states i) + have hsource : (List.ofFn piece).flatten = substring source parent.lo parent.hi := + sourceChild_partition source hM parent + have htarget : (children.map Prod.snd) = List.ofFn states := by + simp only [children, List.map_ofFn, Function.comp_def] + have hchildSource : (children.map Prod.fst).flatten = substring source parent.lo parent.hi := by + simpa only [children, List.map_ofFn, Function.comp_def] using hsource + have hconnection := child_connection_bound target children q + rw [hchildSource, htarget] at hconnection + simp only [children, List.map_ofFn, List.sum_ofFn, Function.comp_def] at hconnection + have hconnectionR : (stateEditCost (substring source parent.lo parent.hi) target q : ℝ) ≤ + (∑ i, (stateEditCost (piece i) target (states i) : ℝ)) + endpointActionConnection q states := by + exact_mod_cast hconnection + have hshift := child_shift_connection_bound target children q + rw [hchildSource, htarget] at hshift + simp only [children, List.map_ofFn, List.sum_ofFn, Function.comp_def] at hshift + have hgapSum : (∑ i, |signedLengthGap (piece i) + (substring target (states i).lo (states i).hi)|) ≤ ∑ i, value i (states i) := by + apply sum_le_sum + intro i hi + rw [← stateLengthGap_actual] + exact hgap i + have hcostSum : (∑ i, (stateEditCost (piece i) target (states i) : ℝ)) / a ≤ + ∑ i, value i (states i) := by + rw [sum_div] + exact sum_le_sum (fun i _ => hcost i) + have hconn0 : (0 : ℝ) ≤ endpointActionConnection q states := Nat.cast_nonneg _ + have ha0 : 0 < a := by linarith + have hconnDiv : (endpointActionConnection q states : ℝ) / a ≤ endpointActionConnection q states := by + apply (div_le_iff₀ ha0).2 + nlinarith + apply max_le + · have hdivide := div_le_div_of_nonneg_right hconnectionR ha0.le + rw [add_div] at hdivide + unfold endpointActionValue + linarith + · rw [stateLengthGap_actual] + unfold endpointActionValue endpointActionConnection + linarith + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/ActualBandBitEnvelope.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/ActualBandBitEnvelope.lean new file mode 100644 index 0000000000000000000000000000000000000000..438f3aea702364f8305b596319ced7f4f62052eb --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/ActualBandBitEnvelope.lean @@ -0,0 +1,119 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryActualBandOptimizer +import OAI.Combinatorics.EditApproximation.Numerics.OptimizerBitEnvelope + +namespace OAI + +/-! A fixed polynomial bounds the complete envelope construction and band +optimizer. In particular the child masses are computed from the initial +table, rather than supplied as already constructed binary fractions. -/ + +namespace EditApproximation + +private theorem square_work_cap (S coefficient width : ℕ) (hc : coefficient ≤ S ^ 2) + (hw : width ≤ S ^ 2) : coefficient * width ^ 2 ≤ S ^ 6 := by + calc + _ ≤ S ^ 2 * (S ^ 2) ^ 2 := Nat.mul_le_mul hc (Nat.pow_le_pow_left hw 2) + _ = _ := by ring + +private theorem square_work_with_constant_cap (S coefficient width extra : ℕ) + (hS : 64 ≤ S) (hc : coefficient ≤ S ^ 2) (hw : width ≤ S ^ 2) + (he : extra ≤ S ^ 6) : coefficient * width ^ 2 + extra ≤ S ^ 7 := by + have h := square_work_cap S coefficient width hc hw + calc + _ ≤ 2 * S ^ 6 := by omega + _ ≤ S * S ^ 6 := Nat.mul_le_mul_right _ (by omega) + _ = _ := by ring + +theorem bandEnvelopeBitBudget_le_power (b M vertices B S : ℕ) (hS : 64 ≤ S) + (hb : Nat.size b ≤ S) (hM : Nat.size M ≤ S) (hv : vertices ≤ S) (hB : B ≤ S) : + BinaryFraction.bandEnvelopeBitBudget b M vertices B ≤ S ^ 10 := by + let W := BinaryFraction.bandEnvelopeWordBudget b M B + have hW : W ≤ 3 * S + 8 := by + dsimp only [W, BinaryFraction.bandEnvelopeWordBudget] + omega + have hW1 : W + 1 ≤ S ^ 2 := by nlinarith + have hW3 : 3 * W + 2 ≤ S ^ 2 := by nlinarith + have hW2 : 2 * W ≤ S ^ 2 := by nlinarith + have htail : 3 * W + 6 ≤ S ^ 2 := by nlinarith + have hfloor : Nat.size b + Nat.size M + 6 ≤ S ^ 2 := by nlinarith + have h1000 : 1000 ≤ S ^ 2 := by nlinarith + have h2100 : 2100 ≤ S ^ 2 := by nlinarith + have hpos : 0 < S := by omega + have hpow6 : 2 ≤ S ^ 6 := (by omega : 2 ≤ S).trans (Nat.le_pow (by omega)) + have hfc := square_work_cap S 2100 (Nat.size b + Nat.size M + 6) h2100 hfloor + have hcmp := square_work_with_constant_cap S 1000 (W + 1) 2 hS h1000 hW1 hpow6 + have hbig := square_work_with_constant_cap S 1000 (3 * W + 2) 2 hS h1000 hW3 hpow6 + have hmember : vertices * (1000 * (W + 1) ^ 2 + 2) ≤ S ^ 8 := by + calc + _ ≤ S * S ^ 7 := Nat.mul_le_mul hv hcmp + _ = _ := by ring + have hscan : 2 * W * (1000 * (3 * W + 2) ^ 2 + 2) ≤ S ^ 9 := by + calc + _ ≤ S ^ 2 * S ^ 7 := Nat.mul_le_mul hW2 hbig + _ = _ := by ring + have h6 : S ^ 6 ≤ S ^ 9 := Nat.pow_le_pow_right hpos (by omega) + have h7 : S ^ 7 ≤ S ^ 9 := Nat.pow_le_pow_right hpos (by omega) + have h8 : S ^ 8 ≤ S ^ 9 := Nat.pow_le_pow_right hpos (by omega) + have h2 : S ^ 2 ≤ S ^ 9 := Nat.pow_le_pow_right hpos (by omega) + have hsmall : vertices + 6 ≤ S ^ 9 := by + have hsq : S + 6 ≤ S ^ 2 := by nlinarith + omega + change 2100 * (Nat.size b + Nat.size M + 6) ^ 2 + + (1 + vertices * (1000 * (W + 1) ^ 2 + 2)) + (1000 * (W + 1) ^ 2 + 1) + + (1 + 2 * W * (1000 * (3 * W + 2) ^ 2 + 2) + 3 * W + 5) + vertices + 4 ≤ _ + have hten : S ^ 10 = S * S ^ 9 := by ring + calc + _ ≤ 6 * S ^ 9 := by + nlinarith only [hfc, hcmp, hmember, hscan, htail, h6, h7, h8, h2, hsmall] + _ ≤ S * S ^ 9 := Nat.mul_le_mul_right _ (by omega) + _ = _ := hten.symm + +def actualBandOptimizerBitDegree : ℕ := max 12 (2 * preparedOptimizerBitPolynomialDegree) + 2 + +theorem actualBandOptimizerBitBudget_le_fixed_power + (M d b vertices G K t Be Bk Bi Bt E S : ℕ) (hS : 64 ≤ S) + (hM : M ≤ S) (hd : d ≤ S) (hb : Nat.size b ≤ S) (hv : vertices ≤ S) + (hG : G ≤ S) (hK : K ≤ S) (ht : t ≤ S) + (hBe : Be ≤ S) (hBk : Bk ≤ S) (hBi : Bi ≤ S) (hBt : Bt ≤ S) (hE : E ≤ S) : + BinaryFraction.actualBandOptimizerBitBudget M d b vertices G K t Be Bk Bi Bt E ≤ + S ^ actualBandOptimizerBitDegree := by + have hpos : 0 < S := by omega + have hSsq : S ≤ S ^ 2 := Nat.le_pow (by omega) + have hMbits : Nat.size M ≤ S := (Nat.size_le.mpr Nat.lt_two_pow_self).trans hM + have hmass : 3 * BinaryFraction.bandEnvelopeWordBudget b M Bi + 1 ≤ S ^ 2 := by + unfold BinaryFraction.bandEnvelopeWordBudget + nlinarith + have hprepared := preparedBandOptimizerBitBudget_le_fixed_power + M d vertices G K t Be Bk (3 * BinaryFraction.bandEnvelopeWordBudget b M Bi + 1) Bt E + (S ^ 2) ((by omega : 2 ≤ S).trans hSsq) + (hM.trans hSsq) (hd.trans hSsq) (hv.trans hSsq) (hG.trans hSsq) (hK.trans hSsq) + (ht.trans hSsq) (hBe.trans hSsq) (hBk.trans hSsq) hmass (hBt.trans hSsq) (hE.trans hSsq) + rw [← pow_mul] at hprepared + have henv := bandEnvelopeBitBudget_le_power b M vertices Bi S hS hb hMbits hv hBi + have h6 : 6 ≤ S ^ 10 := (by omega : 6 ≤ S).trans (Nat.le_pow (by omega)) + have henvelope : M * (BinaryFraction.bandEnvelopeBitBudget b M vertices Bi + 6) ≤ S ^ 12 := by + calc + _ ≤ S * (S ^ 10 + 6) := Nat.mul_le_mul hM (by omega) + _ ≤ S * (S * S ^ 10) := Nat.mul_le_mul_left S (by + calc + _ ≤ 2 * S ^ 10 := by omega + _ ≤ S * S ^ 10 := Nat.mul_le_mul_right _ (by omega)) + _ = _ := by ring + let D := max 12 (2 * preparedOptimizerBitPolynomialDegree) + have hleft : S ^ 12 ≤ S ^ D := Nat.pow_le_pow_right hpos (Nat.le_max_left _ _) + have hright : S ^ (2 * preparedOptimizerBitPolynomialDegree) ≤ S ^ D := + Nat.pow_le_pow_right hpos (Nat.le_max_right _ _) + have hone : 1 ≤ S ^ D := Nat.one_le_pow _ _ hpos + change M * (BinaryFraction.bandEnvelopeBitBudget b M vertices Bi + 6) + + BinaryFraction.preparedBandOptimizerBitBudget M d vertices G K t Be Bk + (3 * BinaryFraction.bandEnvelopeWordBudget b M Bi + 1) Bt E + 1 ≤ S ^ (D + 2) + calc + _ ≤ 3 * S ^ D := by omega + _ ≤ S ^ D * S ^ 2 := by + simpa only [Nat.mul_comm] using + Nat.mul_le_mul_right (S ^ D) (show 3 ≤ S ^ 2 by nlinarith) + _ = _ := (pow_add S D 2).symm + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/ActualRepresentatives.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/ActualRepresentatives.lean new file mode 100644 index 0000000000000000000000000000000000000000..9a732e8492f2d6de9fc08769e2f94ca975fdd271 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/ActualRepresentatives.lean @@ -0,0 +1,60 @@ +import OAI.Combinatorics.EditApproximation.Geometry.InitialConeGrid + +namespace OAI + +/-! The finite representative list and the actual rounded comparison representative. -/ + +namespace EditApproximation + +def representativeList {n : ℕ} (N P F : ℕ) (a : ℚ) + (initial : TargetInterval n → ℚ) : List (ℕ × TargetInterval n) := + (dyadicScales N).flatMap fun b => + ((targetStates n).filter fun r => decide + (seedGridSpacing b P ∣ r.lo ∧ seedGridSpacing b P ∣ r.hi ∧ + (b : ℚ) / (4 * a) ≤ initial r ∧ initial r ≤ 8 * F * b)).map fun r => (b, r) + +theorem representativeList_mem {n N P F b : ℕ} (a : ℚ) + (initial : TargetInterval n → ℚ) (r : TargetInterval n) + (hb : b ∈ dyadicScales N) + (hgrid : seedGridSpacing b P ∣ r.lo ∧ seedGridSpacing b P ∣ r.hi) + (hlower : (b : ℚ) / (4 * a) ≤ initial r) (hupper : initial r ≤ 8 * F * b) : + (b, r) ∈ representativeList N P F a initial := by + apply List.mem_flatMap.mpr + refine ⟨b, hb, List.mem_map.mpr ⟨r, List.mem_filter.mpr ⟨targetStates_complete n r, ?_⟩, rfl⟩⟩ + simpa using ⟨hgrid.1, hgrid.2, hlower, hupper⟩ + +theorem rounded_comparison_representative {α : Type*} (source target : List α) + (N P F : ℕ) (a : ℚ) (hP : 4 ≤ P) (hF : 0 ≤ (F : ℚ)) (ha : 0 < a) + (initial : TargetInterval target.length → ℚ) + (hlower : ∀ r, (stateEditCost source target r : ℚ) / a ≤ initial r) + (hupper : ∀ r, initial r ≤ 2 * F * stateEditCost source target r) + (q : TargetInterval target.length) (hc : 0 < stateEditCost source target q) + (hN : stateEditCost source target q ≤ N) : + let b := 2 ^ Nat.log 2 (stateEditCost source target q) + (b, roundInterval (seedGridSpacing b P) q) ∈ representativeList N P F a initial := by + dsimp only + let b := 2 ^ Nat.log 2 (stateEditCost source target q) + let r := roundInterval (seedGridSpacing b P) q + have hscale := cost_dyadicScale _ N hc hN + have hscaleLower : (b : ℚ) ≤ stateEditCost source target q := by exact_mod_cast hscale.2.1 + have hscaleUpper : (stateEditCost source target q : ℚ) < 2 * b := by exact_mod_cast hscale.2.2 + have he := rounded_seedGrid_error b P (by omega) q + have he0 : (0 : ℚ) ≤ targetEndpointDistance q r := Nat.cast_nonneg _ + have hPr : (4 : ℚ) ≤ P := by exact_mod_cast hP + have hsmall : (targetEndpointDistance q r : ℚ) ≤ b / 2 := by nlinarith only [he, he0, hPr] + have hdist := abs_le.mp (stateEditCost_distance_abs source target q r) + have hcrlo : (b : ℚ) / 4 ≤ stateEditCost source target r := by linarith only [hdist.1, hdist.2, hsmall, hscaleLower] + have hcrhi : (stateEditCost source target r : ℚ) ≤ 4 * b := by + have hb0 : (0 : ℚ) ≤ b := Nat.cast_nonneg _ + linarith only [hdist.1, hdist.2, hsmall, hscaleUpper, hb0] + apply representativeList_mem a initial r hscale.1 (roundInterval_on_grid _ q) + · have hdiv := div_le_div_of_nonneg_right hcrlo ha.le + have hid : (b : ℚ) / 4 / a = b / (4 * a) := by ring + rw [hid] at hdiv + exact hdiv.trans (hlower r) + · have hmul := mul_le_mul_of_nonneg_left hcrhi (mul_nonneg (by norm_num : (0 : ℚ) ≤ 2) hF) + exact (hupper r).trans (by nlinarith only [hmul]) + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/ActualRoundedGroupInputs.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/ActualRoundedGroupInputs.lean new file mode 100644 index 0000000000000000000000000000000000000000..dd7588c50e746d25052d465b0e0daf72570bdaa5 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/ActualRoundedGroupInputs.lean @@ -0,0 +1,101 @@ +import OAI.Combinatorics.EditApproximation.Geometry.RoundedGroupStates +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Every actual unskipped rounded group input belongs to a common +small endpoint list determined by the cell, child and envelope label. -/ + +namespace EditApproximation + + + +theorem groupRoundSpacing_pos (exponent : ℕ) (h : ℚ) : 0 < groupRoundSpacing exponent h := by + apply Nat.ceil_pos.mpr + exact lt_of_lt_of_le zero_lt_one (le_max_left _ _) + +theorem groupRoundSpacing_envelope_bound (exponent : ℕ) (h : ℚ) : + h ≤ (2 : ℚ) ^ exponent * groupRoundSpacing exponent h := by + have hpow : (0 : ℚ) < (2 : ℚ) ^ exponent := by positivity + have hceil : (2 : ℚ) ^ (-(exponent : ℤ)) * h ≤ (groupRoundSpacing exponent h : ℚ) := + (le_max_right _ _).trans (Nat.le_ceil _) + have hmul := mul_le_mul_of_nonneg_left hceil hpow.le + rw [zpow_neg, zpow_natCast] at hmul + simpa only [← mul_assoc, mul_inv_cancel₀ hpow.ne', one_mul] using hmul + +theorem bandRoundSpacing_group_spacing {ny M : ℕ} (exponent b : ℕ) + (band : List (Fin M → TargetInterval ny)) (initial : Fin M → TargetInterval ny → ℚ) + (i : Fin M) (h : ℚ) (henvelope : bandChildEnvelope b band initial i = h) : + bandRoundSpacing exponent b band initial i = groupRoundSpacing exponent h := by + have heq := bandRoundSpacing_exact exponent b band initial i + rw [henvelope] at heq + have hceil := congrArg (fun r : ℚ => ⌈r⌉₊) heq + simpa only [Nat.ceil_natCast, groupRoundSpacing] using hceil + +theorem gridStateBox_sound {n g radius lo hi : ℕ} (hg : 0 < g) (r : TargetInterval n) + (hr : r ∈ gridStateBox n g radius lo hi) : + Nat.dist lo r.lo ≤ radius ∧ Nat.dist hi r.hi ≤ radius ∧ g ∣ r.lo ∧ g ∣ r.hi := by + obtain ⟨s, hs, hr⟩ := List.mem_flatMap.mp hr + obtain ⟨t, ht, hmake⟩ := List.mem_filterMap.mp hr + have heq : r.lo = s ∧ r.hi = t := by + unfold makeTargetState at hmake + split_ifs at hmake with hvalid + cases hmake + exact ⟨rfl, rfl⟩ + rw [← heq.1] at hs + rw [← heq.2] at ht + have hlo := gridPointsBetween_sound hg hs + have hhi := gridPointsBetween_sound hg ht + refine ⟨?_, ?_, hlo.2.2, hhi.2.2⟩ <;> unfold Nat.dist <;> omega + + + +theorem actual_rounded_group_input_mem {α : Type*} (source target : List α) {M b P exponent : ℕ} + (parent : TargetInterval source.length) (tau a : ℚ) (F : ℕ) + (parentInitial : TargetInterval target.length → ℚ) + (child initial : Fin M → TargetInterval target.length → ℚ) (cell : ℕ × ℕ) + (member : UnskippedBand source target parent b P exponent tau F child initial) + (hb : 1 ≤ b) + (hcenter : member.center ∈ cellRepresentativeStates target.length P F b a parentInitial + ((2 : ℚ) ^ (-(exponent : ℤ))) cell) + (i : Fin M) (h : ℚ) (henvelope : member.envelope i = h) : + member.rounded i ∈ groupRoundedStateList source target parent b exponent cell i h := by + have hspacing := bandRoundSpacing_group_spacing exponent b member.actions initial i h henvelope + have hgrid : groupRoundSpacing exponent h ∣ (member.rounded i).lo ∧ + groupRoundSpacing exponent h ∣ (member.rounded i).hi := by + simpa only [UnskippedBand.rounded, canonicalRoundedBandAction, roundedBandAction, hspacing] using + roundInterval_on_grid (bandRoundSpacing exponent b member.actions initial i) + (member.actions.head member.nonempty i) + have hwide : member.rounded i ∈ wideChildStateList parent member.center b P i := + finiteAssignments_sound M (wideChildStateList parent member.center b P) member.rounded member.wide_guard i + have hwideFirst := (gridStateBox_sound (by unfold seedGridSpacing; omega) (member.rounded i) hwide).1 + have htheta : 0 ≤ (2 : ℚ) ^ (-(exponent : ℤ)) ∧ (2 : ℚ) ^ (-(exponent : ℤ)) ≤ 1 := by + refine ⟨(zpow_pos (by norm_num : (0 : ℚ) < 2) _).le, ?_⟩ + rw [zpow_neg, zpow_natCast] + exact inv_le_one_of_one_le₀ (one_le_pow₀ (by norm_num : (1 : ℚ) ≤ 2)) + have hfirst := wide_firstEndpoint_near_cell cell (by unfold seedGridSpacing; omega) htheta hb + member.center (member.rounded i) ((sourceChild parent i).lo - parent.lo) + (List.mem_filter.mp hcenter).1 hwideFirst + have hgap := member.imbalance_guard i + change |rationalStateGap _ _ (member.rounded i)| ≤ 2 * member.envelope i at hgap + rw [henvelope] at hgap + unfold rationalStateGap at hgap + have hgapDistance := lengthGap_guard_distance (member.rounded i) + (substring source (sourceChild parent i).lo (sourceChild parent i).hi).length h hgap + unfold groupRoundedStateList + apply gridGapStates_complete (groupRoundSpacing_pos exponent h) _ _ hgapDistance hgrid + simpa only [mul_assoc] using hfirst + +theorem groupRoundedStateList_length {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (b exponent : ℕ) (cell : ℕ × ℕ) + (i : Fin M) (h : ℚ) (hh : 0 < h) : + ((groupRoundedStateList source target parent b exponent cell i h).length : ℚ) ≤ + 208 * ((2 : ℚ) ^ exponent) ^ 2 * (1 + b / h) := by + exact gridGapStates_rounded_count _ _ _ _ b h ((2 : ℚ) ^ exponent) + (groupRoundSpacing_pos exponent h) hh (one_le_pow₀ (by norm_num : (1 : ℚ) ≤ 2)) + (groupRoundSpacing_envelope_bound exponent h) + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/AlignedStates.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/AlignedStates.lean new file mode 100644 index 0000000000000000000000000000000000000000..86596cd8def4c9d8aec91784e001d3b575ace655 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/AlignedStates.lean @@ -0,0 +1,112 @@ +import OAI.Combinatorics.EditApproximation.Geometry.PartitionIntervals +import OAI.Combinatorics.EditApproximation.Geometry.BalancedIntervals +import OAI.Combinatorics.EditApproximation.Geometry.SourcePrefixes + +namespace OAI + +/-! +# Actual optimal child states + +The alignment split is converted to bounded target endpoint states at +the actual balanced source children. Its sum is exactly the parent +edit distance; its target endpoints are shared. +-/ + +namespace EditApproximation + +open EditDistortion Finset + +theorem zipWith_sum_ofFn {α β γ : Type*} [AddCommMonoid γ] + {M : ℕ} (f : α → β → γ) (x : Fin M → α) (y : Fin M → β) : + (List.zipWith f (List.ofFn x) (List.ofFn y)).sum = ∑ i, f (x i) (y i) := by + have hlist : List.zipWith f (List.ofFn x) (List.ofFn y) = + List.ofFn (fun i => f (x i) (y i)) := by + apply List.ext_getElem + · simp only [List.length_zipWith, List.length_ofFn, min_self] + · intro i hi hj + simp only [List.getElem_zipWith, List.getElem_ofFn] + rw [hlist, List.sum_ofFn] + +theorem optimal_balanced_child_states {α : Type*} (source target : List α) + {M : ℕ} (hM : 0 < M) (parent : TargetInterval source.length) + (q : TargetInterval target.length) : + ∃ states : Fin M → TargetInterval target.length, + (∑ i, stateEditCost + (substring source (sourceChild parent i).lo (sourceChild parent i).hi) target (states i)) = + stateEditCost (substring source parent.lo parent.hi) target q ∧ + (states ⟨0, hM⟩).lo = q.lo ∧ + (states ⟨M - 1, by omega⟩).hi = q.hi ∧ + (∀ i j : Fin M, j.val = i.val + 1 → (states i).hi = (states j).lo) ∧ + ∀ i : Fin M, + Nat.dist (q.lo + ((sourceChild parent i).lo - parent.lo)) (states i).lo ≤ + stateEditCost (substring source parent.lo parent.hi) target q ∧ + Nat.dist (q.lo + ((sourceChild parent i).hi - parent.lo)) (states i).hi ≤ + stateEditCost (substring source parent.lo parent.hi) target q := by + let parts := List.ofFn fun i : Fin M => + substring source (sourceChild parent i).lo (sourceChild parent i).hi + have hpartsLength : parts.length = M := List.length_ofFn + have hnonempty : parts ≠ [] := by intro h; have hl := congrArg List.length h; simp [hpartsLength] at hl; omega + obtain ⟨targets, hlen, hflat, hcost⟩ := edit_partition_split parts hnonempty + (substring target q.lo q.hi) + have htargetsLength : targets.length = M := hlen.trans hpartsLength + let states : Fin M → TargetInterval target.length := fun i => + partitionInterval target q targets hflat ⟨i.val, by omega⟩ + have hsource : parts.flatten = substring source parent.lo parent.hi := + sourceChild_partition source hM parent + refine ⟨states, ?_, ?_, ?_, ?_, ?_⟩ + · have htargets : List.ofFn (fun i : Fin M => targets[i.val]'(by omega)) = targets := by + apply List.ext_getElem + · simp only [List.length_ofFn, htargetsLength] + · intro i hi hj + simp only [List.getElem_ofFn] + have hsum : (∑ i : Fin M, edit + (substring source (sourceChild parent i).lo (sourceChild parent i).hi) + (targets[i.val]'(by omega))) = edit parts.flatten (substring target q.lo q.hi) := by + rw [← zipWith_sum_ofFn, htargets] + exact hcost + rw [hsource] at hsum + convert hsum using 1 + · apply sum_congr rfl + intro i hi + change edit _ (substring target (partitionInterval target q targets hflat _).lo + (partitionInterval target q targets hflat _).hi) = _ + rw [partitionInterval_substring] + · rfl + · simp only [states, partitionInterval, List.take_zero, List.flatten_nil, + List.length_nil, Nat.add_zero] + · have hlast : M - 1 + 1 = targets.length := by omega + have hlength := congrArg List.length hflat + simp only [substring, List.length_drop, List.length_take, Nat.min_eq_left q.valid] at hlength + change q.lo + (targets.take (M - 1 + 1)).flatten.length = q.hi + rw [hlast, List.take_length] + have horder := q.ordered + omega + · intro i j hnext + exact partitionInterval_shared target q targets hflat _ _ hnext + · have hprefixBound (j : ℕ) : + Nat.dist (q.lo + (parts.take j).flatten.length) + (q.lo + (targets.take j).flatten.length) ≤ + stateEditCost (substring source parent.lo parent.hi) target q := by + have h := optimal_partition_anchor_shift_bound parts targets + (substring target q.lo q.hi) hlen.symm hcost j + rw [natural_distance_cast] at h + have hnat : Nat.dist (targets.take j).flatten.length (parts.take j).flatten.length ≤ + edit parts.flatten (substring target q.lo q.hi) := by exact_mod_cast h + rw [hsource] at hnat + change Nat.dist _ _ ≤ edit (substring source parent.lo parent.hi) (substring target q.lo q.hi) + unfold Nat.dist at hnat ⊢ + omega + intro i + constructor + · have h := hprefixBound i.val + dsimp only [parts] at h + rw [sourceChildren_prefix_length source hM parent i.val (by omega)] at h + exact h + · have h := hprefixBound (i.val + 1) + dsimp only [parts] at h + rw [sourceChildren_prefix_length source hM parent (i.val + 1) (by omega)] at h + exact h + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/AlignmentSplitting.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/AlignmentSplitting.lean new file mode 100644 index 0000000000000000000000000000000000000000..12043a6dd8179cefb7f01f368537b1186bb9fc95 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/AlignmentSplitting.lean @@ -0,0 +1,176 @@ +import OAI.Combinatorics.EditApproximation.Geometry.Geometry + +namespace OAI + +/-! +# Splitting an optimal edit script at a source cut + +An arbitrary unrestricted edit script transports a cut through its +intermediate strings. Each edit belongs to one side of that cut. Applied +to a shortest script, this gives an exact optimal target split, including +empty source or target pieces. +-/ + +namespace EditApproximation + +open EditDistortion + +universe u + +theorem step_split {α : Type u} {x y : List α} (step : Step true x y) + (left right : List α) (hx : x = left ++ right) : + ∃ left' right', y = left' ++ right' ∧ + ((Step true left left' ∧ right = right') ∨ + (left = left' ∧ Step true right right')) := by + cases step with + | insert p q a => + rcases List.append_eq_append_iff.mp hx.symm with ⟨mid, hp, hr⟩ | ⟨mid, hl, hq⟩ + · refine ⟨left, mid ++ a :: q, ?_, Or.inr ⟨rfl, ?_⟩⟩ + · simp only [hp, List.append_assoc] + · rw [hr] + exact Step.insert mid q a + · refine ⟨p ++ a :: mid, right, ?_, Or.inl ⟨?_, rfl⟩⟩ + · simp only [hq, List.append_assoc, List.cons_append] + · rw [hl] + exact Step.insert p mid a + | delete p q a => + rcases List.append_eq_append_iff.mp hx.symm with ⟨mid, hp, hr⟩ | ⟨mid, hl, hq⟩ + · refine ⟨left, mid ++ q, ?_, Or.inr ⟨rfl, ?_⟩⟩ + · simp only [hp, List.append_assoc] + · rw [hr] + exact Step.delete mid q a + · cases mid with + | nil => + simp only [List.append_nil] at hl + simp only [List.nil_append] at hq + refine ⟨left, q, ?_, Or.inr ⟨rfl, ?_⟩⟩ + · rw [hl] + · rw [← hq] + exact Step.delete [] q a + | cons b mid => + simp only [List.cons_append, List.cons.injEq] at hq + rcases hq with ⟨rfl, hq⟩ + refine ⟨p ++ mid, right, ?_, Or.inl ⟨?_, rfl⟩⟩ + · simp only [hq, List.append_assoc] + · rw [hl] + exact Step.delete p mid a + | substitute _ p q a b => + rcases List.append_eq_append_iff.mp hx.symm with ⟨mid, hp, hr⟩ | ⟨mid, hl, hq⟩ + · refine ⟨left, mid ++ b :: q, ?_, Or.inr ⟨rfl, ?_⟩⟩ + · simp only [hp, List.append_assoc] + · rw [hr] + exact Step.substitute rfl mid q a b + · cases mid with + | nil => + simp only [List.append_nil] at hl + simp only [List.nil_append] at hq + refine ⟨left, b :: q, ?_, Or.inr ⟨rfl, ?_⟩⟩ + · rw [hl] + · rw [← hq] + exact Step.substitute rfl [] q a b + | cons c mid => + simp only [List.cons_append, List.cons.injEq] at hq + rcases hq with ⟨rfl, hq⟩ + refine ⟨p ++ b :: mid, right, ?_, Or.inl ⟨?_, rfl⟩⟩ + · simp only [hq, List.append_assoc, List.cons_append] + · rw [hl] + exact Step.substitute rfl p mid a b + +theorem script_split {α : Type u} {x y : List α} {n : ℕ} + (script : Script true n x y) (left right : List α) (hx : x = left ++ right) : + ∃ left' right' nleft nright, + y = left' ++ right' ∧ nleft + nright = n ∧ + Script true nleft left left' ∧ Script true nright right right' := by + induction script generalizing left right with + | nil x => exact ⟨left, right, 0, 0, hx, rfl, .nil _, .nil _⟩ + | @cons n x y z step rest ih => + obtain ⟨midleft, midright, hy, hs⟩ := step_split step left right hx + obtain ⟨lastleft, lastright, nl, nr, hz, hn, hleft, hright⟩ := + ih midleft midright hy + rcases hs with ⟨hstep, rfl⟩ | ⟨rfl, hstep⟩ + · exact ⟨lastleft, lastright, nl + 1, nr, hz, by omega, + .cons hstep hleft, hright⟩ + · exact ⟨lastleft, lastright, nl, nr + 1, hz, by omega, + hleft, .cons hstep hright⟩ + +/-- A shortest unrestricted edit script admits an exactly optimal split +at every source cut. -/ +theorem edit_append_split {α : Type u} (left right target : List α) : + ∃ targetLeft targetRight, target = targetLeft ++ targetRight ∧ + edit (left ++ right) target = edit left targetLeft + edit right targetRight := by + obtain ⟨tl, tr, nl, nr, ht, hn, hl, hr⟩ := + script_split (cost_spec (s := true) (left ++ right) target) left right rfl + refine ⟨tl, tr, ht, Nat.le_antisymm ?_ ?_⟩ + · rw [ht] + exact cost_append_le (s := true) left tl right tr + · have hleft := cost_le hl + have hright := cost_le hr + change edit left tl ≤ nl at hleft + change edit right tr ≤ nr at hright + change nl + nr = edit (left ++ right) target at hn + omega + +/-- Repeated source cuts have a common ordered target partition whose +piecewise edit costs sum exactly to the parent optimum. Source pieces +may be empty. A nonempty list of pieces is needed to assign insertions. -/ +theorem edit_partition_split {α : Type u} (parts : List (List α)) + (hne : parts ≠ []) (target : List α) : + ∃ targetParts : List (List α), targetParts.length = parts.length ∧ + targetParts.flatten = target ∧ + (List.zipWith edit parts targetParts).sum = edit parts.flatten target := by + induction parts generalizing target with + | nil => exact False.elim (hne rfl) + | cons first rest ih => + cases rest with + | nil => + refine ⟨[target], rfl, ?_, ?_⟩ + · simp + · simp + | cons second rest => + obtain ⟨tl, tr, ht, hc⟩ := edit_append_split first (second :: rest).flatten target + obtain ⟨targets, hlen, hflatten, hcost⟩ := ih (by simp) tr + refine ⟨tl :: targets, by simp only [List.length_cons, hlen], ?_, ?_⟩ + · simp only [List.flatten_cons, hflatten] + exact ht.symm + · simp only [List.flatten_cons, List.zipWith_cons_cons, List.sum_cons, hcost] + exact hc.symm + +/-- Prefixes of an ordered source/target partition use at most the +partition's total edit cost. This bounds every alignment anchor shift. -/ +theorem edit_partition_prefix_le {α : Type u} + (parts targets : List (List α)) (hlen : parts.length = targets.length) (k : ℕ) : + edit (parts.take k).flatten (targets.take k).flatten ≤ + (List.zipWith edit parts targets).sum := by + induction parts generalizing targets k with + | nil => + have ht : targets = [] := List.length_eq_zero_iff.mp hlen.symm + subst targets + simp only [List.take_nil, List.flatten_nil, List.zipWith_nil_left, List.sum_nil] + exact (cost_refl ([] : List α)).le + | cons first rest ih => + cases targets with + | nil => simp at hlen + | cons targetFirst targetRest => + have hrest : rest.length = targetRest.length := by simpa using hlen + cases k with + | zero => + simp only [List.take_zero, List.flatten_nil] + exact (cost_refl ([] : List α)).le.trans (Nat.zero_le _) + | succ k => + simp only [List.take_succ_cons, List.flatten_cons, List.zipWith_cons_cons, List.sum_cons] + exact (cost_append_le (s := true) first targetFirst + (rest.take k).flatten (targetRest.take k).flatten).trans + (Nat.add_le_add_left (ih targetRest hrest k) _) + +theorem optimal_partition_anchor_shift_bound {α : Type u} + (parts targets : List (List α)) (target : List α) + (hlen : parts.length = targets.length) + (hcost : (List.zipWith edit parts targets).sum = edit parts.flatten target) (k : ℕ) : + |((targets.take k).flatten.length : ℝ) - (parts.take k).flatten.length| ≤ + (edit parts.flatten target : ℝ) := by + apply (abs_length_gap_le_edit (parts.take k).flatten (targets.take k).flatten).trans + exact_mod_cast (edit_partition_prefix_le parts targets hlen k).trans_eq hcost + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/BalancedIntervals.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/BalancedIntervals.lean new file mode 100644 index 0000000000000000000000000000000000000000..c1832d027f307f8ad78b84f5453ca9f6958a23b9 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/BalancedIntervals.lean @@ -0,0 +1,84 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseSeed +import OAI.Combinatorics.EditApproximation.Geometry.TreeAccounting +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! +# The actual balanced interval cuts + +The fixed interval tree uses cuts `l + floor(i*width/M)`. Their substring +pieces concatenate exactly to the parent, including repeated cuts and +empty pieces. These facts instantiate optimal alignment splitting on the +manuscript's actual source intervals. +-/ + +namespace EditApproximation + + + +theorem balancedCut_zero (lo width M : ℕ) : balancedCut lo width M 0 = lo := by + simp [balancedCut] + +theorem balancedCut_last (lo width M : ℕ) (hM : 0 < M) : + balancedCut lo width M M = lo + width := by + simp only [balancedCut, Nat.mul_div_cancel_left _ hM] + +theorem balancedCut_monotone (lo width M : ℕ) : Monotone (balancedCut lo width M) := by + intro i j hij + exact Nat.add_le_add_left (Nat.div_le_div_right (Nat.mul_le_mul_right width hij)) lo + +theorem balancedCut_bounds (lo width M i : ℕ) (hM : 0 < M) (hi : i ≤ M) : + lo ≤ balancedCut lo width M i ∧ balancedCut lo width M i ≤ lo + width := by + constructor + · exact Nat.le_add_right _ _ + · rw [← balancedCut_last lo width M hM] + exact balancedCut_monotone lo width M hi + +def balancedPieces {α : Type*} (word : List α) (lo width M : ℕ) : List (List α) := + (List.range M).map fun i => substring word (balancedCut lo width M i) (balancedCut lo width M (i + 1)) + +theorem balancedPieces_prefix {α : Type*} (word : List α) (lo width M j : ℕ) : + ((List.range j).map fun i => + substring word (balancedCut lo width M i) (balancedCut lo width M (i + 1))).flatten = + substring word lo (balancedCut lo width M j) := by + induction j with + | zero => simp [balancedCut, substring] + | succ j ih => + rw [List.range_succ, List.map_append, List.flatten_append] + simp only [List.map_cons, List.map_nil, List.flatten_cons, List.flatten_nil, List.append_nil] + rw [ih] + exact (substring_split word lo (balancedCut lo width M j) (balancedCut lo width M (j + 1)) + (Nat.le_add_right _ _) (balancedCut_monotone lo width M (Nat.le_succ j))).symm + +theorem balancedPieces_flatten {α : Type*} (word : List α) (lo width M : ℕ) (hM : 0 < M) : + (balancedPieces word lo width M).flatten = substring word lo (lo + width) := by + rw [balancedPieces, balancedPieces_prefix, balancedCut_last lo width M hM] + +theorem balancedPieces_length {α : Type*} (word : List α) (lo width M : ℕ) : + (balancedPieces word lo width M).length = M := by + simp only [balancedPieces, List.length_map, List.length_range] + + + + + +theorem sourceChild_partition {α : Type*} (word : List α) {M : ℕ} (hM : 0 < M) + (parent : TargetInterval word.length) : + (List.ofFn fun child : Fin M => + substring word (sourceChild parent child).lo (sourceChild parent child).hi).flatten = + substring word parent.lo parent.hi := by + have hlist : (List.ofFn fun child : Fin M => + substring word (sourceChild parent child).lo (sourceChild parent child).hi) = + balancedPieces word parent.lo (parent.hi - parent.lo) M := by + apply List.ext_getElem + · simp only [List.length_ofFn, balancedPieces_length] + · intro i hi hj + simp only [List.getElem_ofFn, balancedPieces, List.getElem_map, List.getElem_range, sourceChild] + rw [hlist, balancedPieces_flatten word parent.lo (parent.hi - parent.lo) M hM, + Nat.add_sub_of_le parent.ordered] + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/BalancedWidths.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/BalancedWidths.lean new file mode 100644 index 0000000000000000000000000000000000000000..88f3c98637c31a6a63eb7414d6076fe3e9d8e379 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/BalancedWidths.lean @@ -0,0 +1,82 @@ +import OAI.Combinatorics.EditApproximation.Geometry.BalancedIntervals + +namespace OAI + +/-! +# Width and node counts for the fixed interval tree + +Repeated ceiling division gives the physical-depth width bound. This +includes empty children and repeated interval labels, which must still +be counted as distinct nodes in the lazy evaluation analysis. +-/ + +namespace EditApproximation + +open Finset + +theorem ceilDiv_comp (n a b : ℕ) (ha : 0 < a) (hb : 0 < b) : + (n ⌈/⌉ a) ⌈/⌉ b = n ⌈/⌉ (a * b) := by + apply eq_of_forall_ge_iff + intro k + rw [ceilDiv_le_iff_le_mul hb, ceilDiv_le_iff_le_mul ha, + ceilDiv_le_iff_le_mul (Nat.mul_pos ha hb), Nat.mul_assoc] + +theorem balanced_child_width_le_ceiling (width M i : ℕ) (hM : 0 < M) : + ((i + 1) * width / M) - i * width / M ≤ width ⌈/⌉ M := by + let c := width ⌈/⌉ M + have hceil : width ≤ M * c := (ceilDiv_le_iff_le_mul hM).mp (le_refl c) + have hfloor := Nat.lt_mul_div_succ (i * width) hM + have hsum : i * width + width < (i * width / M + c + 1) * M := by nlinarith + have hdiv := (Nat.div_lt_iff_lt_mul hM).2 hsum + have hid : (i + 1) * width = i * width + width := by ring + rw [hid] + omega + +theorem sourceChild_width_le_ceiling {n M : ℕ} (parent : TargetInterval n) (child : Fin M) : + (sourceChild parent child).hi - (sourceChild parent child).lo ≤ + (parent.hi - parent.lo) ⌈/⌉ M := by + dsimp only [sourceChild, balancedCut] + rw [Nat.add_sub_add_left] + exact balanced_child_width_le_ceiling _ _ _ (Nat.zero_lt_of_lt child.isLt) + +theorem sourceIntervalAt_width (M n d : ℕ) (hM : 0 < M) (node : TreeLayer M d) : + (sourceIntervalAt M n d node).hi - (sourceIntervalAt M n d node).lo ≤ n ⌈/⌉ M ^ d := by + induction d with + | zero => simp [sourceIntervalAt] + | succ d ih => + have hchild := sourceChild_width_le_ceiling (sourceIntervalAt M n d node.1) node.2 + have hmono := (gc_mul_ceilDiv hM).monotone_l (ih node.1) + have hcomp := ceilDiv_comp n (M ^ d) M (pow_pos hM d) hM + change (sourceChild (sourceIntervalAt M n d node.1) node.2).hi - + (sourceChild (sourceIntervalAt M n d node.1) node.2).lo ≤ n ⌈/⌉ M ^ (d + 1) + exact hchild.trans (hmono.trans_eq (by rw [hcomp, pow_succ])) + +theorem sourceIntervalAt_leaf_width (M n J : ℕ) (hM : 0 < M) (hcapacity : n ≤ M ^ J) + (node : TreeLayer M J) : + (sourceIntervalAt M n J node).hi - (sourceIntervalAt M n J node).lo ≤ 1 := by + apply (sourceIntervalAt_width M n J hM node).trans + apply (ceilDiv_le_iff_le_mul (pow_pos hM J)).2 + simpa only [Nat.mul_one] using hcapacity + +theorem treeLayer_card (M d : ℕ) : Fintype.card (TreeLayer M d) = M ^ d := by + induction d with + | zero => + change Fintype.card PUnit = 1 + exact Fintype.card_punit + | succ d ih => + change Fintype.card (TreeLayer M d × Fin M) = M ^ (d + 1) + rw [Fintype.card_prod, Fintype.card_fin, ih, pow_succ] + +theorem complete_tree_node_count (M J : ℕ) (hM : 2 ≤ M) : + (∑ d ∈ range (J + 1), Fintype.card (TreeLayer M d)) ≤ 2 * M ^ J := by + simp_rw [treeLayer_card] + induction J with + | zero => simp + | succ J ih => + rw [sum_range_succ, pow_succ] + have hmul := Nat.mul_le_mul_right (M ^ J) hM + nlinarith + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/BandActionGuards.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/BandActionGuards.lean new file mode 100644 index 0000000000000000000000000000000000000000..3f2f58a708080db13487728f9c2a62258480fcaa --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/BandActionGuards.lean @@ -0,0 +1,320 @@ +import OAI.Combinatorics.EditApproximation.Geometry.BandRounding +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! +# Actual rounded band actions pass the finite guards + +Each child uses its own envelope-derived integer spacing. The action is +rounded with literal integer division; wide-grid, radius and imbalance +claims are proved for these returned states. +-/ + +namespace EditApproximation + +open Finset + + + + + +theorem bandChildEnvelope_pos {ny M : ℕ} (b : ℕ) + (band : List (Fin M → TargetInterval ny)) + (initial : Fin M → TargetInterval ny → ℚ) (i : Fin M) : + 0 < bandChildEnvelope b band initial i := by + unfold bandChildEnvelope rationalDyadicCeiling + positivity + +theorem roundedBandAction_endpoint_error {ny M : ℕ} (thetaExponent b : ℕ) + (band : List (Fin M → TargetInterval ny)) + (initial : Fin M → TargetInterval ny → ℚ) (action : Fin M → TargetInterval ny) (i : Fin M) : + (Nat.dist (action i).lo (roundedBandAction thetaExponent b band initial action i).lo : ℚ) ≤ + (2 : ℚ) ^ (-(thetaExponent : ℤ)) * bandChildEnvelope b band initial i ∧ + (Nat.dist (action i).hi (roundedBandAction thetaExponent b band initial action i).hi : ℚ) ≤ + (2 : ℚ) ^ (-(thetaExponent : ℤ)) * bandChildEnvelope b band initial i := by + have hscaled : 0 ≤ (2 : ℚ) ^ (-(thetaExponent : ℤ)) * bandChildEnvelope b band initial i := + mul_nonneg (zpow_pos (by norm_num : (0 : ℚ) < 2) _).le (bandChildEnvelope_pos b band initial i).le + exact ⟨gridRound_scaled_error _ _ _ (bandRoundSpacing_exact thetaExponent b band initial i) hscaled, + gridRound_scaled_error _ _ _ (bandRoundSpacing_exact thetaExponent b band initial i) hscaled⟩ + +theorem roundedBandAction_distance {ny M : ℕ} (thetaExponent b : ℕ) + (band : List (Fin M → TargetInterval ny)) + (initial : Fin M → TargetInterval ny → ℚ) (action : Fin M → TargetInterval ny) (i : Fin M) : + (targetEndpointDistance (action i) (roundedBandAction thetaExponent b band initial action i) : ℚ) ≤ + 2 * (2 : ℚ) ^ (-(thetaExponent : ℤ)) * bandChildEnvelope b band initial i := by + have h := roundedBandAction_endpoint_error thetaExponent b band initial action i + unfold targetEndpointDistance + push_cast + convert add_le_add h.1 h.2 using 1 + ring + +/-- Actual rounded wide membership and imbalance guard. The sum premise +is supplied by bandChildEnvelope_sum_guard, and the remaining premises +are explicit computed-parameter inequalities. -/ +theorem roundedBandAction_guards {α : Type*} (source target : List α) + {M b P : ℕ} (parent : TargetInterval source.length) (r : TargetInterval target.length) + (thetaExponent : ℕ) (tau velocity : ℚ) + (child initial : Fin M → TargetInterval target.length → ℚ) + (action : Fin M → TargetInterval target.length) + (haction : action ∈ computedBandActions parent r b P tau ((2 : ℚ) ^ (-(thetaExponent : ℤ))) velocity child) + (hM : 0 < M) (hPpos : 0 < P) + (hbPower : ∃ e : ℕ, b = 2 ^ e) (hPPower : ∃ e : ℕ, P = 2 ^ e) + (hscale : (M : ℚ) ≤ (2 : ℚ) ^ (-(thetaExponent : ℤ)) * P) + (F : ℚ) + (hsmall : 64 * F * (2 : ℚ) ^ (-(thetaExponent : ℤ)) ≤ 4) + (htheta : (2 : ℚ) ^ (-(thetaExponent : ℤ)) ≤ 1 / 2) + (hinitialGap : ∀ i s, |rationalStateGap + (substring source (sourceChild parent i).lo (sourceChild parent i).hi) target s| ≤ initial i s) + (hsum : (∑ i : Fin M, bandChildEnvelope b + (computedBandActions parent r b P tau ((2 : ℚ) ^ (-(thetaExponent : ℤ))) velocity child) initial i) ≤ 64 * F * b) : + let band := computedBandActions parent r b P tau ((2 : ℚ) ^ (-(thetaExponent : ℤ))) velocity child + roundedBandAction thetaExponent b band initial action ∈ wideActionList M parent r b P ∧ + ∀ i, |rationalStateGap + (substring source (sourceChild parent i).lo (sourceChild parent i).hi) target + (roundedBandAction thetaExponent b band initial action i)| ≤ 2 * bandChildEnvelope b band initial i := by + let theta : ℚ := 2 ^ (-(thetaExponent : ℤ)) + let band := computedBandActions parent r b P tau theta velocity child + let envelope := fun i : Fin M => bandChildEnvelope b band initial i + let rounded := roundedBandAction thetaExponent b band initial action + have htheta0 : 0 ≤ theta := (zpow_pos (by norm_num : (0 : ℚ) < 2) _).le + have henv (i : Fin M) : 0 ≤ envelope i := (bandChildEnvelope_pos b band initial i).le + have hsingle (i : Fin M) : envelope i ≤ ∑ j, envelope j := + single_le_sum (fun j _ => henv j) (mem_univ i) + have hbudget (i : Fin M) : theta * envelope i ≤ 4 * b := by + have h := (mul_le_mul_of_nonneg_left (hsingle i) htheta0).trans + (mul_le_mul_of_nonneg_left hsum htheta0) + have hb := mul_le_mul_of_nonneg_right hsmall (show (0 : ℚ) ≤ b by positivity) + nlinarith only [h, hb] + obtain ⟨hnonempty, hwide, hv, hpredicate⟩ := + computedBandActions_mem parent r b P tau theta velocity child action haction + have herr := roundedBandAction_endpoint_error thetaExponent b band initial action + have hanchor (anchor before after : ℕ) (i : Fin M) + (hbefore : Nat.dist anchor before ≤ 6 * b) + (herror : (Nat.dist before after : ℚ) ≤ theta * envelope i) : + Nat.dist anchor after ≤ 10 * b := by + have htriangle : (Nat.dist anchor after : ℚ) ≤ (Nat.dist anchor before : ℚ) + Nat.dist before after := by + exact_mod_cast Nat.dist.triangle_inequality anchor before after + have hbeforeQ : (Nat.dist anchor before : ℚ) ≤ 6 * b := by exact_mod_cast hbefore + have hafter : (Nat.dist anchor after : ℚ) ≤ 10 * b := by + linarith only [htriangle, hbeforeQ, herror, hbudget i] + exact_mod_cast hafter + constructor + · apply wideActionList_complete + · intro i + have hgrid := bandRoundSpacing_wide_grid thetaExponent band initial i hM hPpos hbPower hPPower hscale + exact ⟨hgrid.trans (dvd_mul_right _ _), hgrid.trans (dvd_mul_right _ _)⟩ + · intro i + exact hanchor _ _ _ i (hpredicate.2.1 i).1 (herr i).1 + · intro i + exact hanchor _ _ _ i (hpredicate.2.1 i).2 (herr i).2 + · intro i + have hbefore := (hinitialGap i (action i)).trans + ((bandChildEnvelope_lower b band initial i).2 action haction) + have hspatial := stateLengthGap_spatial + (substring source (sourceChild parent i).lo (sourceChild parent i).hi) target (rounded i) (action i) + rw [← rationalStateGap_cast, ← rationalStateGap_cast] at hspatial + have hspatialQ : |rationalStateGap + (substring source (sourceChild parent i).lo (sourceChild parent i).hi) target (rounded i)| ≤ + |rationalStateGap (substring source (sourceChild parent i).lo (sourceChild parent i).hi) target (action i)| + + (targetEndpointDistance (rounded i) (action i) : ℚ) := by exact_mod_cast hspatial + have hdistance := roundedBandAction_distance thetaExponent b band initial action i + have hsym : targetEndpointDistance (rounded i) (action i) = targetEndpointDistance (action i) (rounded i) := by + unfold targetEndpointDistance + rw [Nat.dist_comm (rounded i).lo, Nat.dist_comm (rounded i).hi] + rw [hsym] at hspatialQ + have hscaled := mul_le_mul_of_nonneg_right htheta (henv i) + nlinarith only [hbefore, hspatialQ, hdistance, hscaled] + +/-- Moving the two endpoints of each interval charges at most their total +movement, including the outside connections. -/ +theorem connectionBudget_pair_perturbation {n : ℕ} + (pairs : List (TargetInterval n × TargetInterval n)) (beforeStart afterStart finish : ℕ) : + connectionBudget afterStart (pairs.map Prod.snd) finish ≤ + connectionBudget beforeStart (pairs.map Prod.fst) finish + Nat.dist afterStart beforeStart + + (pairs.map fun pair => targetEndpointDistance pair.1 pair.2).sum := by + induction pairs generalizing beforeStart afterStart with + | nil => + simp only [List.map_nil, List.sum_nil, connectionBudget, Nat.add_zero] + have h := Nat.dist.triangle_inequality afterStart beforeStart finish + omega + | cons pair rest ih => + rcases pair with ⟨before, after⟩ + have htail := ih before.hi after.hi + have hfirst := Nat.dist.triangle_inequality afterStart beforeStart before.lo + have hsecond := Nat.dist.triangle_inequality afterStart before.lo after.lo + rw [Nat.dist_comm after.hi before.hi] at htail + simp only [List.map_cons, List.sum_cons, connectionBudget, targetEndpointDistance] at htail ⊢ + omega + +theorem endpointActionConnection_perturbation {n M : ℕ} (r : TargetInterval n) + (before after : Fin M → TargetInterval n) : + endpointActionConnection r after ≤ endpointActionConnection r before + + ∑ i, targetEndpointDistance (before i) (after i) := by + have h := connectionBudget_pair_perturbation + (List.ofFn fun i : Fin M => (before i, after i)) r.lo r.lo r.hi + simpa only [List.map_ofFn, List.sum_ofFn, Function.comp_def, Nat.dist_self, Nat.add_zero, + endpointActionConnection] using h + +/-- The returned rounded action pays at most `2 θ ∑ hᵢ` in actual +connection cost when its unrounded band action has zero connection. -/ +theorem roundedBandAction_connection {n M : ℕ} (r : TargetInterval n) + (thetaExponent b : ℕ) (band : List (Fin M → TargetInterval n)) + (initial : Fin M → TargetInterval n → ℚ) (action : Fin M → TargetInterval n) + (hzero : endpointActionConnection r action = 0) : + (endpointActionConnection r (roundedBandAction thetaExponent b band initial action) : ℚ) ≤ + 2 * (2 : ℚ) ^ (-(thetaExponent : ℤ)) * ∑ i, bandChildEnvelope b band initial i := by + have hnatural := endpointActionConnection_perturbation r action + (roundedBandAction thetaExponent b band initial action) + rw [hzero, Nat.zero_add] at hnatural + have hcast : (endpointActionConnection r + (roundedBandAction thetaExponent b band initial action) : ℚ) ≤ + ∑ i, (targetEndpointDistance (action i) + (roundedBandAction thetaExponent b band initial action i) : ℚ) := by + exact_mod_cast hnatural + calc + _ ≤ ∑ i, (targetEndpointDistance (action i) + (roundedBandAction thetaExponent b band initial action i) : ℚ) := hcast + _ ≤ ∑ i, 2 * (2 : ℚ) ^ (-(thetaExponent : ℤ)) * bandChildEnvelope b band initial i := + sum_le_sum fun i _ => roundedBandAction_distance thetaExponent b band initial action i + _ = _ := by rw [mul_sum] + +theorem canonicalRoundedBandAction_connection {nx ny M : ℕ} (parent : TargetInterval nx) + (r : TargetInterval ny) (thetaExponent b P : ℕ) (tau velocity : ℚ) + (child initial : Fin M → TargetInterval ny → ℚ) + (hnonempty : computedBandActions parent r b P tau + ((2 : ℚ) ^ (-(thetaExponent : ℤ))) velocity child ≠ []) : + let band := computedBandActions parent r b P tau + ((2 : ℚ) ^ (-(thetaExponent : ℤ))) velocity child + (endpointActionConnection r + (canonicalRoundedBandAction thetaExponent b band hnonempty initial) : ℚ) ≤ + 2 * (2 : ℚ) ^ (-(thetaExponent : ℤ)) * ∑ i, bandChildEnvelope b band initial i := by + have hmem := List.head_mem hnonempty + obtain ⟨_, _, _, hpredicate⟩ := computedBandActions_mem parent r b P tau + ((2 : ℚ) ^ (-(thetaExponent : ℤ))) velocity child _ hmem + exact roundedBandAction_connection r thetaExponent b _ initial _ hpredicate.1 + +/-- The initial table's literal spatial bound controls the value of every +returned rounded state. -/ +theorem roundedBandAction_initialValue {ny M : ℕ} (thetaExponent b : ℕ) + (band : List (Fin M → TargetInterval ny)) + (initial : Fin M → TargetInterval ny → ℚ) (action : Fin M → TargetInterval ny) + (L0 : ℚ) (hL0 : 0 ≤ L0) + (hspatial : ∀ i s t, initial i s ≤ initial i t + L0 * targetEndpointDistance s t) + (i : Fin M) : + initial i (roundedBandAction thetaExponent b band initial action i) ≤ initial i (action i) + + 2 * L0 * (2 : ℚ) ^ (-(thetaExponent : ℤ)) * bandChildEnvelope b band initial i := by + have h := hspatial i (roundedBandAction thetaExponent b band initial action i) (action i) + have hsym : targetEndpointDistance (roundedBandAction thetaExponent b band initial action i) (action i) = + targetEndpointDistance (action i) (roundedBandAction thetaExponent b band initial action i) := by + unfold targetEndpointDistance + rw [Nat.dist_comm (roundedBandAction thetaExponent b band initial action i).lo, + Nat.dist_comm (roundedBandAction thetaExponent b band initial action i).hi] + rw [hsym] at h + have hmove := mul_le_mul_of_nonneg_left + (roundedBandAction_distance thetaExponent b band initial action i) hL0 + nlinarith only [h, hmove] + +theorem roundedBandAction_initialValue_le_twice {ny M : ℕ} (thetaExponent b : ℕ) + (band : List (Fin M → TargetInterval ny)) + (initial : Fin M → TargetInterval ny → ℚ) (action : Fin M → TargetInterval ny) + (haction : action ∈ band) (L0 : ℚ) (hL0 : 0 ≤ L0) + (hsmall : 2 * L0 * (2 : ℚ) ^ (-(thetaExponent : ℤ)) ≤ 1) + (hspatial : ∀ i s t, initial i s ≤ initial i t + L0 * targetEndpointDistance s t) + (i : Fin M) : + initial i (roundedBandAction thetaExponent b band initial action i) ≤ + 2 * bandChildEnvelope b band initial i := by + have hbefore := (bandChildEnvelope_lower b band initial i).2 action haction + have hafter := roundedBandAction_initialValue thetaExponent b band initial action L0 hL0 hspatial i + have hmove := mul_le_mul_of_nonneg_right hsmall (bandChildEnvelope_pos b band initial i).le + nlinarith only [hbefore, hafter, hmove] + +/-- The canonical rounded action is close to every member of its actual +computed band, with distance measured at both child endpoints. -/ +theorem canonicalRoundedBandAction_distance {nx ny M : ℕ} (parent : TargetInterval nx) + (r : TargetInterval ny) (thetaExponent b P : ℕ) (tau velocity : ℚ) (htau : 0 < tau) + (child initial : Fin M → TargetInterval ny → ℚ) + (hnonempty : computedBandActions parent r b P tau + ((2 : ℚ) ^ (-(thetaExponent : ℤ))) velocity child ≠ []) + (action : Fin M → TargetInterval ny) + (haction : action ∈ computedBandActions parent r b P tau + ((2 : ℚ) ^ (-(thetaExponent : ℤ))) velocity child) (i : Fin M) : + let band := computedBandActions parent r b P tau + ((2 : ℚ) ^ (-(thetaExponent : ℤ))) velocity child + (targetEndpointDistance (action i) + (canonicalRoundedBandAction thetaExponent b band hnonempty initial i) : ℚ) ≤ + 6 * (2 : ℚ) ^ (-(thetaExponent : ℤ)) * bandChildEnvelope b band initial i := by + let theta : ℚ := (2 : ℚ) ^ (-(thetaExponent : ℤ)) + let band := computedBandActions parent r b P tau theta velocity child + let canonical := band.head hnonempty + let rounded := canonicalRoundedBandAction thetaExponent b band hnonempty initial + have htheta : 0 ≤ theta := (zpow_pos (by norm_num : (0 : ℚ) < 2) _).le + have hcanonical : canonical ∈ band := List.head_mem hnonempty + have hdiameter := computedBand_child_endpoint_diameter parent r b P tau theta velocity + htau htheta child action canonical haction hcanonical i + have hdiameterQ : (targetEndpointDistance (action i) (canonical i) : ℚ) ≤ 4 * theta * b / M := by + exact_mod_cast hdiameter + have hfloor := (bandChildEnvelope_lower b band initial i).1 + have hscaled := mul_le_mul_of_nonneg_left hfloor (mul_nonneg (by norm_num : (0 : ℚ) ≤ 4) htheta) + have hdiameterEnvelope : (targetEndpointDistance (action i) (canonical i) : ℚ) ≤ + 4 * theta * bandChildEnvelope b band initial i := by + calc + _ ≤ 4 * theta * ((b : ℚ) / M) := by convert hdiameterQ using 1; ring + _ ≤ _ := hscaled + have hround := roundedBandAction_distance thetaExponent b band initial canonical i + change (targetEndpointDistance (canonical i) (rounded i) : ℚ) ≤ + 2 * theta * bandChildEnvelope b band initial i at hround + have htriangle : (targetEndpointDistance (action i) (rounded i) : ℚ) ≤ + targetEndpointDistance (action i) (canonical i) + targetEndpointDistance (canonical i) (rounded i) := by + have hnatural : targetEndpointDistance (action i) (rounded i) ≤ + targetEndpointDistance (action i) (canonical i) + targetEndpointDistance (canonical i) (rounded i) := by + unfold targetEndpointDistance + have hlo := Nat.dist.triangle_inequality (action i).lo (canonical i).lo (rounded i).lo + have hhi := Nat.dist.triangle_inequality (action i).hi (canonical i).hi (rounded i).hi + omega + exact_mod_cast hnatural + change (targetEndpointDistance (action i) (rounded i) : ℚ) ≤ + 6 * theta * bandChildEnvelope b band initial i + linarith only [htriangle, hdiameterEnvelope, hround] + +/-- The actual canonical rounded action satisfies the rounded-action +cost inequality uniformly for every actual band member. -/ +theorem canonicalRoundedBandAction_cost {nx ny M : ℕ} (parent : TargetInterval nx) + (r : TargetInterval ny) (thetaExponent b P : ℕ) (tau velocity : ℚ) (htau : 0 < tau) + (child initial value : Fin M → TargetInterval ny → ℚ) + (hnonempty : computedBandActions parent r b P tau + ((2 : ℚ) ^ (-(thetaExponent : ℤ))) velocity child ≠ []) + (action : Fin M → TargetInterval ny) + (haction : action ∈ computedBandActions parent r b P tau + ((2 : ℚ) ^ (-(thetaExponent : ℤ))) velocity child) + (delta L : ℚ) (hL : 0 ≤ L) + (hspatial : ∀ i s t, value i s ≤ (1 + delta) * value i t + L * targetEndpointDistance s t) : + let band := computedBandActions parent r b P tau + ((2 : ℚ) ^ (-(thetaExponent : ℤ))) velocity child + rationalEndpointActionValue r (canonicalRoundedBandAction thetaExponent b band hnonempty initial) value ≤ + (1 + delta) * (∑ i, value i (action i)) + + (6 * L + 2) * (2 : ℚ) ^ (-(thetaExponent : ℤ)) * ∑ i, bandChildEnvelope b band initial i := by + let theta : ℚ := (2 : ℚ) ^ (-(thetaExponent : ℤ)) + let band := computedBandActions parent r b P tau theta velocity child + let rounded := canonicalRoundedBandAction thetaExponent b band hnonempty initial + have hchild (i : Fin M) : value i (rounded i) ≤ (1 + delta) * value i (action i) + + 6 * L * theta * bandChildEnvelope b band initial i := by + have h := hspatial i (rounded i) (action i) + have hsym : targetEndpointDistance (rounded i) (action i) = targetEndpointDistance (action i) (rounded i) := by + unfold targetEndpointDistance + rw [Nat.dist_comm (rounded i).lo, Nat.dist_comm (rounded i).hi] + rw [hsym] at h + have hmove := mul_le_mul_of_nonneg_left + (canonicalRoundedBandAction_distance parent r thetaExponent b P tau velocity htau child initial + hnonempty action haction i) hL + nlinarith only [h, hmove] + have hsum := sum_le_sum fun i (_ : i ∈ (univ : Finset (Fin M))) => hchild i + rw [sum_add_distrib, ← mul_sum, ← mul_sum] at hsum + have hconnection := canonicalRoundedBandAction_connection parent r thetaExponent b P tau velocity child initial hnonempty + change (endpointActionConnection r rounded : ℚ) + ∑ i, value i (rounded i) ≤ _ + nlinarith only [hsum, hconnection] + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/BandActionPolynomial.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/BandActionPolynomial.lean new file mode 100644 index 0000000000000000000000000000000000000000..5de6abf08970649f43230053bae11324f033c3c7 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/BandActionPolynomial.lean @@ -0,0 +1,207 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryBandAction +import OAI.Combinatorics.EditApproximation.Probability.FiniteBitPolynomial + +namespace OAI + +/-! A fixed-degree envelope for the full labeled action selector, including +its final logarithm-gradient and argmax, after the iterative optimizer. -/ + +namespace EditApproximation + +private abbrev CE := FiniteBitPolynomial (Fin 12) +private def baSize (a : CE) : CE := .bitLength a +private def baMax (a b : CE) : CE := .maximum a b + +private def expressionLogStorage (B K : CE) : CE := + baSize (2 * K) + 2 * (K * K * (4 * B + 18) + K * (baSize (2 * K + 1) + 1) + 1) + 1 + +private def expressionGradientStorage (G P L : CE) : CE := + 4 * expressionLogStorage (2 * P + 2 * (5 + 50 * (baSize G + 2)) + 2) (G ^ 60) + 2 * L + 18 + +private def expressionPoint (K B Bv : CE) : CE := + Bv + 2 * (B + K * (2 * baSize (K + 1) + B)) + 2 + +private def expressionLogUniversal (B K : CE) : CE := + B + (baSize K + 2 * (K * K * B + K * (baSize (2 * K + 1) + 1) + 1) + 1) + + (2 * ((2 * K + 1) * B + 1) + 2) + baSize (2 * K + 1) + 10 + +private def expressionLogStep (W K : CE) : CE := + (2 * K + 1) * (2000 * (W + 1) ^ 2 + 1) + 2100 * (W + 2) ^ 2 + + 6000 * (W + 1) ^ 2 + baSize (2 * K + 1) + 6 + +private def expressionLogBit (B K : CE) : CE := + let W := expressionLogUniversal (8 * B + 22) K + 12000 * (B + 4) ^ 2 + 2100 * (4 * B + 12) ^ 2 + + K * expressionLogStep W K + 2000 * (W + 5) ^ 2 + 10 + +private def expressionGradientBit (G P L : CE) : CE := + let S := 3 + 50 * (baSize G + 2) + let R := 4 * P + 2 * S + 8 + let logBits := expressionLogStorage R (G ^ 60) + let natWidth := baMax (baSize G) 1 + let powerWidth := natWidth + 3 + 50 * (2 * natWidth + 1) + (1 + 50 * (2000 * (powerWidth + 1) ^ 2 + 1)) + (4 * S + 3) + + 6000 * (P + S + 2) ^ 2 + expressionLogBit R (G ^ 60) + + (6000 * (logBits + 4) ^ 2 + 1) + 6000 * (L + 2 * logBits + 9) ^ 2 + baSize G + 70 + +private def expressionMaximizer (d v B V : CE) : CE := + let W := B + baSize (d * V * V) + 2 * (1 + d * (B + B)) + 1 + v * (1 + d * (100000 * (W + 1) ^ 2) + 1000 * (W + 1) ^ 2 + 2) + d + 1 + +private def expressionUpdate (d K P : CE) : CE := + let C := baSize (K + 2) + 8 + let W := P + 2 * C + 8 + 2100 * (baSize (K + 2) + 6) ^ 2 + (6000 * (C + 4) ^ 2 + 1) + + d * (110000 * (W + 1) ^ 2 + 6) + baSize (K + 2) + 4 + +private def expressionOptimizer (d v G K B Bv L V : CE) : CE := + let P := expressionPoint K B Bv + let W := expressionGradientStorage G (2 * P + 1) (2 * L + 1) + d + 1 + K * (d * (expressionGradientBit G P L + 6) + + expressionMaximizer d v (baMax P W) (2 * G ^ 60 + 1 + V + 1) + expressionUpdate d K P + 3) + +private def expressionBandSumStorage (n B : CE) : CE := + baSize n + B + 2 * (1 + n * (B + 1)) + 2 + +private def expressionBandVertexWord (M B : CE) : CE := + 2 * B + expressionBandSumStorage M B + 3 + +private def expressionStoredSumWord (n B : CE) : CE := + (B + 1) + baSize n + 2 * (B + 2) + 2 * (1 + n * ((B + 1) + (B + 1))) + 1 + +private def expressionStoredSumBit (n B : CE) : CE := + 1 + n * (100000 * (expressionStoredSumWord n B + 1) ^ 2) + +private def expressionBandCoordinateBit (M B : CE) : CE := + 2100 * (B + expressionBandSumStorage M B + 2) ^ 2 + +private def expressionBandPreparation (M d v B : CE) : CE := + expressionStoredSumBit M B + v * (d * (expressionBandCoordinateBit M B + 6)) + 6 * v + +private def expressionOptimisticStorage (Bm Bt Bc : CE) : CE := 20 * Bt + 8 * Bm + 4 * Bc + 30 + +private def expressionOnlineStorage (Be Bk Bm Bt t : CE) : CE := + 2 * Be + 2 * expressionBandSumStorage t (expressionOptimisticStorage Bm Bt (4 * Bk + 18)) + + 2 * (2 * Bt + 2 * Bm + 4) + 3 + +private def expressionGainBit (Bm Bt : CE) : CE := 2100 * (Bm + Bt + 2) ^ 2 + 1 + +private def expressionDecrementBit (Bm Bt : CE) : CE := + 6000 * (Bt + 1) ^ 2 + 2100 * (8 * Bt + Bm + 8) ^ 2 + 2 + +private def expressionCoefficientBit (Bk : CE) : CE := + 2000 * (Bk + 3) ^ 2 + 6000 * (2 * Bk + 7) ^ 2 + 2 + +private def expressionOptimisticBit (Bm Bt Bc : CE) : CE := + let W := 8 * Bt + 2 * Bm + 2 * Bc + 12 + expressionGainBit Bm Bt + expressionDecrementBit Bm Bt + + 2000 * (W + 1) ^ 2 + 6000 * (W + 1) ^ 2 + 2 + +private def expressionOnlineBit (Be Bk Bm Bt t : CE) : CE := + let storage := expressionOptimisticStorage Bm Bt (4 * Bk + 18) + let W := Be + expressionBandSumStorage t storage + (2 * Bt + 2 * Bm + 4) + 2 + expressionCoefficientBit Bk + t * (expressionOptimisticBit Bm Bt (4 * Bk + 18) + 6) + + expressionStoredSumBit t storage + expressionGainBit Bm Bt + + 6000 * (W + 1) ^ 2 + 2000 * (2 * W + 3) ^ 2 + 3 + +private def expressionSelection (d v G K B Bv L V : CE) : CE := + let P := expressionPoint K B Bv + let W := expressionGradientStorage G (2 * P + 1) (2 * L + 1) + expressionOptimizer d v G K B Bv L V + d * (expressionGradientBit G P L + 6) + + expressionMaximizer d v (baMax P W) (2 * G ^ 60 + 1 + V + 1) + +private def expressionEnvelopeWord (M bb B : CE) : CE := B + bb + baSize M + 8 +private def expressionEnvelopeWork (M bb v B : CE) : CE := + let W := expressionEnvelopeWord M bb B + 2100 * (bb + baSize M + 6) ^ 2 + + (1 + v * (1000 * (W + 1) ^ 2 + 2)) + (1000 * (W + 1) ^ 2 + 1) + + (1 + 2 * W * (1000 * (3 * W + 2) ^ 2 + 2) + 3 * W + 5) + v + 4 + +private def bandActionExpression : CE := + let M := .input 0 + let d := .input 1 + let bb := .input 2 + let v := .input 3 + let G := .input 4 + let K := .input 5 + let t := .input 6 + let Be := .input 7 + let Bk := .input 8 + let Bi := .input 9 + let Bt := .input 10 + let E := .input 11 + let Bm := 3 * expressionEnvelopeWord M bb Bi + 1 + M * (expressionEnvelopeWork M bb v Bi + 6) + + (expressionBandPreparation M d v Bm + 2 * v + + d * (expressionOnlineBit Be Bk Bm Bt t + 6) + + expressionSelection d v G K (expressionBandVertexWord M Bm) (expressionBandVertexWord M Bm) + (expressionOnlineStorage Be Bk Bm Bt t) (E * (2 * t + 1)) + 2) + 1 + +def bandActionBitDegree : ℕ := bandActionExpression.degree + +private def bandActionEnvironment (M d b v G K t Be Bk Bi Bt E : ℕ) : Fin 12 → ℕ + | 0 => M + | 1 => d + | 2 => Nat.size b + | 3 => v + | 4 => G + | 5 => K + | 6 => t + | 7 => Be + | 8 => Bk + | 9 => Bi + | 10 => Bt + | _ => E + +private theorem bandActionExpression_eval (M d b v G K t Be Bk Bi Bt E : ℕ) : + bandActionExpression.eval (bandActionEnvironment M d b v G K t Be Bk Bi Bt E) = + BinaryFraction.bandActionBitBudget M d b v G K t Be Bk Bi Bt E := by + have hnat : (BinaryFraction.nat G).width = max (Nat.size G) 1 := by + simp only [BinaryFraction.nat, BinaryFraction.width, SignedBinary.ofInt, + Int.natAbs_natCast, ← Nat.size_eq_bits_len, List.length_cons, List.length_nil] + simp only [bandActionExpression, bandActionEnvironment, expressionSelection, + expressionEnvelopeWord, expressionEnvelopeWork, expressionBandPreparation, + expressionBandCoordinateBit, expressionBandVertexWord, expressionBandSumStorage, + expressionStoredSumBit, expressionStoredSumWord, expressionOnlineBit, + expressionOnlineStorage, expressionOptimisticStorage, expressionOptimisticBit, + expressionGainBit, expressionDecrementBit, expressionCoefficientBit, + expressionOptimizer, expressionPoint, expressionGradientStorage, + expressionGradientBit, expressionLogStorage, expressionLogBit, expressionLogUniversal, + expressionLogStep, expressionMaximizer, expressionUpdate, baSize, baMax, + FiniteBitPolynomial.eval, BinaryFraction.bandActionBitBudget, + BinaryFraction.preparedBandActionBitBudget, BinaryFraction.selectionBitBudget, + BinaryFraction.bandEnvelopeWordBudget, BinaryFraction.bandEnvelopeBitBudget, + BinaryFraction.bandPreparationBitBudget, BinaryFraction.bandCoordinateBitBudget, + BinaryFraction.bandVertexWordBudget, BinaryFraction.bandMassTotalStorageBudget, + BinaryFraction.storedSumBitBudget, BinaryFraction.storedSumWordBudget, + BinaryFraction.onlineLinearBitBudget, BinaryFraction.onlineLinearStorageBudget, + BinaryFraction.onlineFinalWordBudget, BinaryFraction.optimisticTermStorageBudget, + BinaryFraction.optimisticTermBitBudget, BinaryFraction.optimisticTermWordBudget, + BinaryFraction.gainBitBudget, BinaryFraction.decrementBitBudget, + BinaryFraction.coefficientBitBudget, BinaryFraction.optimizerBitBudget, + BinaryFraction.optimizerRoundBitBudget, BinaryFraction.optimizerPointWordBudget, + BinaryFraction.optimizerGradientWordBudget, UnreducedRational.gradientStorageBudget, + UnreducedRational.logarithmStorageBudget, BinaryFraction.gradientCellBitBudget, + BinaryFraction.generalPowerWordBudget, BinaryFraction.smoothingStorageBudget, + BinaryFraction.shiftedStorageBudget, BinaryFraction.gradientLogStorageBudget, + BinaryFraction.logarithmBitBudget, BinaryFraction.logarithmUniversalWordBudget, + BinaryFraction.logarithmPartialBitStep, BinaryFraction.maximizerBitBudget, + BinaryFraction.maximizerWordBudget, BinaryFraction.dotWordBudget, + BinaryFraction.optimizerUpdateBitBudget, BinaryFraction.updateCoordinateWordBudget, + BinaryFraction.updateCoefficientWordBudget, hnat] + rfl + +theorem bandActionBitBudget_fixedPower (M d b v G K t Be Bk Bi Bt E S : ℕ) + (hS : 2 ≤ S) (hM : M ≤ S) (hd : d ≤ S) (hb : Nat.size b ≤ S) + (hv : v ≤ S) (hG : G ≤ S) (hK : K ≤ S) (ht : t ≤ S) + (hBe : Be ≤ S) (hBk : Bk ≤ S) (hBi : Bi ≤ S) (hBt : Bt ≤ S) (hE : E ≤ S) : + BinaryFraction.bandActionBitBudget M d b v G K t Be Bk Bi Bt E ≤ S ^ bandActionBitDegree := by + have henv : ∀ i, bandActionEnvironment M d b v G K t Be Bk Bi Bt E i ≤ S := by + intro i + fin_cases i <;> simp only [bandActionEnvironment] <;> assumption + simpa only [bandActionExpression_eval, bandActionBitDegree] using + bandActionExpression.eval_le_pow _ S hS henv + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/BandDimension.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/BandDimension.lean new file mode 100644 index 0000000000000000000000000000000000000000..769ea9a02e14bd0a5d5966f2db2459d3921b3e4c --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/BandDimension.lean @@ -0,0 +1,100 @@ +import OAI.Combinatorics.EditApproximation.Geometry.RepresentativeBands +import OAI.Combinatorics.EditApproximation.Geometry.ActionVectors +import OAI.Combinatorics.EditApproximation.Refinement.ComputedGroupNumerical + +namespace OAI + +/-! The dimension charged by entropy is the number of actual child coordinates. -/ + +namespace EditApproximation + +open Finset + +theorem wideChildStateList_length_le {nx ny M b P : ℕ} (parent : TargetInterval nx) + (r : TargetInterval ny) (hP : 0 < P) (i : Fin M) : + (wideChildStateList parent r b P i).length ≤ (40 * P + 2) ^ 2 := by + have h := gridStateBox_length_le ny (seedGridSpacing b P) (10 * b) + (r.lo + ((sourceChild parent i).lo - parent.lo)) + (r.lo + ((sourceChild parent i).hi - parent.lo)) (by unfold seedGridSpacing; omega) + exact h.trans (Nat.pow_le_pow_left (by + simpa only [show 2 * (10 * b) = 20 * b by omega] using seedGridSpacing_radius_count b P hP) 2) + +theorem bandCoordinates_card_le {nx ny M b P : ℕ} (parent : TargetInterval nx) + (r : TargetInterval ny) (hP : 0 < P) (band : List (Fin M → TargetInterval ny)) + (hband : ∀ action ∈ band, action ∈ wideActionList M parent r b P) : + (bandCoordinates band.toFinset).card ≤ M * (40 * P + 2) ^ 2 := by + classical + let coordinateSet := univ.biUnion fun i : Fin M => + (wideChildStateList parent r b P i).toFinset.image fun s => (i, s) + have hsub : bandCoordinates band.toFinset ⊆ coordinateSet := by + intro coordinate hcoordinate + obtain ⟨action, ha, hcoord⟩ := mem_biUnion.mp hcoordinate + obtain ⟨i, _, rfl⟩ := mem_image.mp hcoord + apply mem_biUnion.mpr + refine ⟨i, mem_univ _, mem_image.mpr ⟨action i, ?_, rfl⟩⟩ + exact List.mem_toFinset.mpr (finiteAssignments_sound M _ action + (hband action (List.mem_toFinset.mp ha)) i) + have hsum : coordinateSet.card ≤ ∑ i : Fin M, (40 * P + 2) ^ 2 := by + apply (card_biUnion_le).trans + apply sum_le_sum + intro i _ + exact (card_image_le).trans ((List.toFinset_card_le _).trans + (wideChildStateList_length_le parent r hP i)) + exact (card_le_card hsub).trans (by simpa only [sum_const, card_univ, Fintype.card_fin, + Nat.nsmul_eq_mul] using hsum) + +theorem computed_band_dimension_log (N : ℕ) (hN : 0 < N) + (hell : 42 ≤ inputSmallLog N) {nx ny b : ℕ} (parent : TargetInterval nx) + (r : TargetInterval ny) (band : List (Fin (integerParameters N).M → TargetInterval ny)) + (hband : ∀ action ∈ band, action ∈ wideActionList (integerParameters N).M parent r b (integerParameters N).P) : + Real.log (bandCoordinates band.toFinset).card ≤ + 4 * (coarseExponent (inputSmallLog N) + 21 : ℕ) * (inputSmallLog N : ℝ) := by + let ell := inputSmallLog N + let p := coarseExponent ell + let H := inputHeight N + let P := (integerParameters N).P + let M := (integerParameters N).M + let d := (bandCoordinates band.toFinset).card + have hellR : (42 : ℝ) ≤ ell := by exact_mod_cast hell + have hell0 : (0 : ℝ) ≤ ell := Nat.cast_nonneg _ + have hPpos : 0 < P := pow_pos (Nat.two_pow_pos (heightExponent N)) _ + have hPone : (1 : ℝ) ≤ P := by exact_mod_cast hPpos + have hM : M ≤ H := pow_le_pow_right₀ (by decide : 1 ≤ (2 : ℕ)) (Nat.div_le_self _ _) + have hMexp : (M : ℝ) ≤ Real.exp ell := + (show (M : ℝ) ≤ H by exact_mod_cast hM).trans (computed_height_exp_upper N hN) + have hPexp : (P : ℝ) ≤ Real.exp (((p : ℝ) + 20) * ell) := by + change ((H ^ (p + 20) : ℕ) : ℝ) ≤ _ + rw [Nat.cast_pow] + have h := pow_le_pow_left₀ (Nat.cast_nonneg H) (computed_height_exp_upper N hN) (p + 20) + rw [← Real.exp_nat_mul] at h + simpa only [Nat.cast_add, Nat.cast_ofNat] using h + have h42 : (42 : ℝ) ≤ Real.exp ell := by linarith only [Real.add_one_le_exp (ell : ℝ), hellR] + have hbox : (40 * P + 2 : ℝ) ≤ Real.exp (((p : ℝ) + 21) * ell) := by + calc + (40 * P + 2 : ℝ) ≤ 42 * P := by linarith only [hPone] + _ ≤ Real.exp ell * Real.exp (((p : ℝ) + 20) * ell) := + mul_le_mul h42 hPexp (Nat.cast_nonneg P) (Real.exp_pos _).le + _ = Real.exp (((p : ℝ) + 21) * ell) := by rw [← Real.exp_add]; congr 1; ring + have hcount : (d : ℝ) ≤ M * (40 * P + 2 : ℝ) ^ 2 := by + exact_mod_cast bandCoordinates_card_le parent r hPpos band hband + have hexp : (d : ℝ) ≤ Real.exp (4 * ((p : ℝ) + 21) * ell) := by + apply hcount.trans + have h := mul_le_mul hMexp (pow_le_pow_left₀ (by positivity) hbox 2) (by positivity) + (Real.exp_pos _).le + apply h.trans + rw [← Real.exp_nat_mul, ← Real.exp_add] + norm_num only [Nat.cast_ofNat] + apply Real.exp_le_exp.mpr + have hp : (0 : ℝ) ≤ p := Nat.cast_nonneg _ + nlinarith only [mul_nonneg hp hell0, hell0] + by_cases hd : d = 0 + · change Real.log (d : ℝ) ≤ _ + rw [hd, Nat.cast_zero, Real.log_zero] + exact mul_nonneg (mul_nonneg (by norm_num) (Nat.cast_nonneg _)) (Nat.cast_nonneg _) + · have hdR : (0 : ℝ) < d := by exact_mod_cast (Nat.pos_of_ne_zero hd) + have hlog := (Real.log_le_iff_le_exp hdR).2 hexp + simpa only [p, ell, d, Nat.cast_mul, Nat.cast_add, Nat.cast_ofNat] using hlog + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/BandEarlierDependence.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/BandEarlierDependence.lean new file mode 100644 index 0000000000000000000000000000000000000000..b8e1ef57fae26f692213b441575122add6ef8f5e --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/BandEarlierDependence.lean @@ -0,0 +1,244 @@ +import OAI.Combinatorics.EditApproximation.Geometry.UnskippedBands +import OAI.Combinatorics.EditApproximation.Geometry.WideEarlierInputs + +namespace OAI + +/-! The band construction and its literal guards use only the child +coordinates of the finite wide action list. The result types retain the +full tables as indices, so acceptance and returned centers are compared +after projecting away proof fields. -/ + +namespace EditApproximation + +open Finset + +theorem rationalWidePrefixCost_congr_child {nx ny M : ℕ} + (parent : TargetInterval nx) (r : TargetInterval ny) (states : Fin M → TargetInterval ny) + (left right : Fin M → TargetInterval ny → ℚ) (j : ℕ) (p : ℚ) + (heq : ∀ i, left i (states i) = right i (states i)) : + rationalWidePrefixCost parent r states left j p = + rationalWidePrefixCost parent r states right j p := by + unfold rationalWidePrefixCost + congr 1 + apply sum_congr rfl + intro i hi + rw [heq i] + +theorem rationalWidePrefixMinimum_congr_child {nx ny M : ℕ} + (parent : TargetInterval nx) (r : TargetInterval ny) + (actions : List (Fin M → TargetInterval ny)) (hne : actions ≠ []) + (left right : Fin M → TargetInterval ny → ℚ) (j : ℕ) (p : ℚ) + (heq : ∀ action ∈ actions, ∀ i, left i (action i) = right i (action i)) : + rationalWidePrefixMinimum parent r actions hne left j p = + rationalWidePrefixMinimum parent r actions hne right j p := by + have hcost (action) (ha : action ∈ actions) := + rationalWidePrefixCost_congr_child parent r action left right j p (heq action ha) + unfold rationalWidePrefixMinimum + rw [hcost _ (List.head_mem hne)] + congr 1 + exact List.map_congr_left hcost + +theorem rationalWideActionMinimum_congr_child {nx ny M : ℕ} + (parent : TargetInterval nx) (r : TargetInterval ny) (b P : ℕ) + (hne : wideActionList M parent r b P ≠ []) + (left right : Fin M → TargetInterval ny → ℚ) + (heq : ∀ action ∈ wideActionList M parent r b P, + ∀ i, left i (action i) = right i (action i)) : + rationalWideActionMinimum parent r b P hne left = + rationalWideActionMinimum parent r b P hne right := by + have hcost (action) (ha : action ∈ wideActionList M parent r b P) : + rationalEndpointActionValue r action left = rationalEndpointActionValue r action right := by + unfold rationalEndpointActionValue + congr 1 + exact sum_congr rfl (fun i hi => heq action ha i) + unfold rationalWideActionMinimum + rw [hcost _ (List.head_mem hne)] + congr 1 + exact List.map_congr_left hcost + +theorem computedBandActions_congr_child {nx ny M : ℕ} + (parent : TargetInterval nx) (r : TargetInterval ny) (b P : ℕ) (tau theta velocity : ℚ) + (left right : Fin M → TargetInterval ny → ℚ) + (heq : ∀ action ∈ wideActionList M parent r b P, + ∀ i, left i (action i) = right i (action i)) : + computedBandActions parent r b P tau theta velocity left = + computedBandActions parent r b P tau theta velocity right := by + unfold computedBandActions + dsimp only + split_ifs with hnonempty hvelocity + · rfl + · have hprefix (j : ℕ) (p : ℚ) := rationalWidePrefixMinimum_congr_child parent r + (wideActionList M parent r b P) hnonempty left right j p heq + simp only [bandActionPredicate, hprefix] + · rfl + +theorem representativeBandActions_congr_child {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (r : TargetInterval target.length) + (b P : ℕ) (tau theta : ℚ) (left right : Fin M → TargetInterval target.length → ℚ) + (heq : ∀ action ∈ wideActionList M parent r b P, + ∀ i, left i (action i) = right i (action i)) : + representativeBandActions source target parent r b P tau theta left = + representativeBandActions source target parent r b P tau theta right := by + by_cases hnonempty : wideActionList M parent r b P = [] + · simp only [representativeBandActions, dite_eq_left hnonempty] + · simp only [representativeBandActions, dite_eq_right hnonempty] + rw [rationalWideActionMinimum_congr_child parent r b P hnonempty left right heq] + split_ifs + · exact computedBandActions_congr_child parent r b P tau theta _ left right heq + · rfl + +theorem bandChildEnvelope_congr_initial {ny M : ℕ} (b : ℕ) + (band : List (Fin M → TargetInterval ny)) (left right : Fin M → TargetInterval ny → ℚ) + (heq : ∀ action ∈ band, ∀ i, left i (action i) = right i (action i)) : + bandChildEnvelope b band left = bandChildEnvelope b band right := by + funext i + have hmap : band.map (fun action => left i (action i)) = + band.map (fun action => right i (action i)) := + List.map_congr_left (fun action ha => heq action ha i) + simp only [bandChildEnvelope, hmap] + +theorem bandRoundSpacing_congr_initial {ny M : ℕ} (exponent b : ℕ) + (band : List (Fin M → TargetInterval ny)) (left right : Fin M → TargetInterval ny → ℚ) + (heq : ∀ action ∈ band, ∀ i, left i (action i) = right i (action i)) : + bandRoundSpacing exponent b band left = bandRoundSpacing exponent b band right := by + funext i + have hmap : band.map (fun action => left i (action i)) = + band.map (fun action => right i (action i)) := + List.map_congr_left (fun action ha => heq action ha i) + simp only [bandRoundSpacing, bandEnvelopeExponent, hmap] + +theorem canonicalRoundedBandAction_congr_initial {ny M : ℕ} (exponent b : ℕ) + (band : List (Fin M → TargetInterval ny)) (hne : band ≠ []) + (left right : Fin M → TargetInterval ny → ℚ) + (heq : ∀ action ∈ band, ∀ i, left i (action i) = right i (action i)) : + canonicalRoundedBandAction exponent b band hne left = + canonicalRoundedBandAction exponent b band hne right := by + unfold canonicalRoundedBandAction roundedBandAction + rw [bandRoundSpacing_congr_initial exponent b band left right heq] + +theorem representativeBandEnvelope_congr {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (r : TargetInterval target.length) + (b P exponent : ℕ) (tau : ℚ) + (child child' initial initial' : Fin M → TargetInterval target.length → ℚ) + (hchild : ∀ action ∈ wideActionList M parent r b P, + ∀ i, child i (action i) = child' i (action i)) + (hinitial : ∀ action ∈ wideActionList M parent r b P, + ∀ i, initial i (action i) = initial' i (action i)) : + bandChildEnvelope b (representativeBandActions source target parent r b P tau + ((2 : ℚ) ^ (-(exponent : ℤ))) child) initial = + bandChildEnvelope b (representativeBandActions source target parent r b P tau + ((2 : ℚ) ^ (-(exponent : ℤ))) child') initial' := by + rw [← representativeBandActions_congr_child source target parent r b P tau _ child child' hchild] + apply bandChildEnvelope_congr_initial + intro action ha i + exact hinitial action + (representativeBandActions_wide source target parent r b P tau _ child action ha) i + +theorem testUnskippedBand_isSome_iff {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (b P exponent : ℕ) (tau F : ℚ) + (child initial : Fin M → TargetInterval target.length → ℚ) (r : TargetInterval target.length) : + (testUnskippedBand source target parent b P exponent tau F child initial r).isSome = true ↔ + ∃ hne : representativeBandActions source target parent r b P tau + ((2 : ℚ) ^ (-(exponent : ℤ))) child ≠ [], + (∑ i, bandChildEnvelope b (representativeBandActions source target parent r b P tau + ((2 : ℚ) ^ (-(exponent : ℤ))) child) initial i) ≤ 64 * F * b ∧ + canonicalRoundedBandAction exponent b (representativeBandActions source target parent r b P tau + ((2 : ℚ) ^ (-(exponent : ℤ))) child) hne initial ∈ wideActionList M parent r b P ∧ + ∀ i, |rationalStateGap + (substring source (sourceChild parent i).lo (sourceChild parent i).hi) target + (canonicalRoundedBandAction exponent b (representativeBandActions source target parent r b P tau + ((2 : ℚ) ^ (-(exponent : ℤ))) child) hne initial i)| ≤ + 2 * bandChildEnvelope b (representativeBandActions source target parent r b P tau + ((2 : ℚ) ^ (-(exponent : ℤ))) child) initial i := by + unfold testUnskippedBand + dsimp only + split_ifs with hband hsum hwide hgap + · simp only [Option.isSome_none, Bool.false_eq_true, false_iff] + rintro ⟨hne, _⟩ + exact hne hband + · constructor + · intro _ + exact ⟨hband, hsum, hwide, hgap⟩ + · intro _ + rfl + · simp only [Option.isSome_none, Bool.false_eq_true, false_iff] + rintro ⟨hne, _, _, hg⟩ + exact hgap hg + · simp only [Option.isSome_none, Bool.false_eq_true, false_iff] + rintro ⟨hne, _, hw, _⟩ + exact hwide hw + · simp only [Option.isSome_none, Bool.false_eq_true, false_iff] + rintro ⟨hne, hs, _⟩ + exact hsum hs + +theorem testUnskippedBand_isSome_congr {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (r : TargetInterval target.length) + (b P exponent : ℕ) (tau F : ℚ) + (child child' initial initial' : Fin M → TargetInterval target.length → ℚ) + (hchild : ∀ action ∈ wideActionList M parent r b P, + ∀ i, child i (action i) = child' i (action i)) + (hinitial : ∀ action ∈ wideActionList M parent r b P, + ∀ i, initial i (action i) = initial' i (action i)) : + (testUnskippedBand source target parent b P exponent tau F child initial r).isSome = + (testUnskippedBand source target parent b P exponent tau F child' initial' r).isSome := by + apply Bool.eq_iff_iff.mpr + rw [testUnskippedBand_isSome_iff, testUnskippedBand_isSome_iff] + have hband := representativeBandActions_congr_child source target parent r b P tau + ((2 : ℚ) ^ (-(exponent : ℤ))) child child' hchild + rw [← hband] + have hinitialBand : ∀ action ∈ representativeBandActions source target parent r b P tau + ((2 : ℚ) ^ (-(exponent : ℤ))) child, ∀ i, initial i (action i) = initial' i (action i) := by + intro action ha i + exact hinitial action + (representativeBandActions_wide source target parent r b P tau _ child action ha) i + have henv := bandChildEnvelope_congr_initial b _ initial initial' hinitialBand + have hrounded (hne) := canonicalRoundedBandAction_congr_initial exponent b _ hne + initial initial' hinitialBand + simp only [henv, hrounded] + +theorem testUnskippedBand_center_projection {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (r : TargetInterval target.length) + (b P exponent : ℕ) (tau F : ℚ) + (child initial : Fin M → TargetInterval target.length → ℚ) : + (testUnskippedBand source target parent b P exponent tau F child initial r).map + UnskippedBand.center = + if (testUnskippedBand source target parent b P exponent tau F child initial r).isSome + then some r else none := by + unfold testUnskippedBand + dsimp only + split_ifs <;> simp_all + +theorem testUnskippedBand_center_congr {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (r : TargetInterval target.length) + (b P exponent : ℕ) (tau F : ℚ) + (child child' initial initial' : Fin M → TargetInterval target.length → ℚ) + (hchild : ∀ action ∈ wideActionList M parent r b P, + ∀ i, child i (action i) = child' i (action i)) + (hinitial : ∀ action ∈ wideActionList M parent r b P, + ∀ i, initial i (action i) = initial' i (action i)) : + (testUnskippedBand source target parent b P exponent tau F child initial r).map + UnskippedBand.center = + (testUnskippedBand source target parent b P exponent tau F child' initial' r).map + UnskippedBand.center := by + rw [testUnskippedBand_center_projection, testUnskippedBand_center_projection, + testUnskippedBand_isSome_congr source target parent r b P exponent tau F + child child' initial initial' hchild hinitial] + +/-- The actual wide coordinates are in the earlier-input cover at every +stored history time. This specializes the congruence premise without +requiring equality of a full child table. -/ +theorem wideAction_child_agreement_of_cover {nx ny M : ℕ} (parent : TargetInterval nx) + (P history b t : ℕ) (r : TargetInterval ny) + (representatives : List (ℕ × TargetInterval ny)) (hrep : (b, r) ∈ representatives) + (ht : t < history) (left right : PhysicalChildTables M ny) + (heq : ∀ i s q, (i, s, q) ∈ wideEarlierInputCover parent P history representatives → + left i s q = right i s q) : + ∀ action ∈ wideActionList M parent r b P, + ∀ i, left i t (action i) = right i t (action i) := by + intro action ha i + exact heq i t (action i) + (wideEarlierInputCover_mem parent P history representatives b r hrep t ht action ha i) + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/BandEnvelopeBits.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/BandEnvelopeBits.lean new file mode 100644 index 0000000000000000000000000000000000000000..58d406fba596040183fb393630711cca2e967347 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/BandEnvelopeBits.lean @@ -0,0 +1,108 @@ +import OAI.Combinatorics.EditApproximation.Geometry.BandNumericalBits +import OAI.Combinatorics.EditApproximation.Geometry.BandEnvelopes + +namespace OAI + +/-! Encoding lengths of the actual finite maxima and dyadic envelopes. +These estimates include the scales below one and require no good seed. -/ + +namespace EditApproximation + +theorem positive_rational_binary_bounds (r : ℚ) (B : ℕ) + (hr : 0 < r) (hbits : rationalEncodingBits r ≤ B) : + (2 : ℚ) ^ (-(B : ℤ)) ≤ r ∧ r ≤ (2 : ℚ) ^ (B : ℤ) := by + have hnumSize : Nat.size r.num.natAbs ≤ B := by unfold rationalEncodingBits at hbits; omega + have hdenSize : Nat.size r.den ≤ B := by unfold rationalEncodingBits at hbits; omega + have hnum : r.num.natAbs ≤ 2 ^ B := + (Nat.lt_size_self _).le.trans (Nat.pow_le_pow_right (by decide) hnumSize) + have hden : r.den ≤ 2 ^ B := + (Nat.lt_size_self _).le.trans (Nat.pow_le_pow_right (by decide) hdenSize) + have hnumPos : 0 < r.num := Rat.num_pos.mpr hr + have hnumOne : 1 ≤ r.num.natAbs := Int.natAbs_pos.mpr (ne_of_gt hnumPos) + have hrep : r = (r.num.natAbs : ℚ) / r.den := by + rw [← Int.cast_natCast, Int.natCast_natAbs, abs_of_pos hnumPos] + exact r.num_div_den.symm + have hd : (0 : ℚ) < r.den := by exact_mod_cast r.den_pos + have hp : (0 : ℚ) < (2 : ℚ) ^ B := pow_pos (by norm_num) _ + simp only [zpow_neg, zpow_natCast] + rw [hrep] + constructor + · rw [inv_eq_one_div, div_le_div_iff₀ hp hd, one_mul] + exact_mod_cast (hden.trans (Nat.le_mul_of_pos_left _ (by omega : 0 < r.num.natAbs))) + · apply (div_le_iff₀ hd).mpr + exact_mod_cast (hnum.trans (Nat.le_mul_of_pos_right _ r.den_pos)) + +theorem rationalDyadicCeiling_encoding (r : ℚ) (B : ℕ) + (hr : 0 < r) (hbits : rationalEncodingBits r ≤ B) : + rationalEncodingBits (rationalDyadicCeiling r) ≤ 5 * B + 5 := by + have hrange := positive_rational_binary_bounds r B hr hbits + have hlo := Int.clog_mono_right (b := 2) (zpow_pos (by norm_num : (0 : ℚ) < 2) (-(B : ℤ))) hrange.1 + have hhi := Int.clog_mono_right (b := 2) hr hrange.2 + have hclog (z : ℤ) : Int.clog 2 ((2 : ℚ) ^ z) = z := by + simpa only [Nat.cast_ofNat] using (Int.clog_zpow (R := ℚ) (b := 2) (by decide) z) + rw [hclog] at hlo hhi + have htwo : rationalEncodingBits (2 : ℚ) = 4 := by + rw [show (2 : ℚ) = (2 : ℕ) by norm_num, rationalEncodingBits_natCast] + rfl + unfold rationalDyadicCeiling + cases he : Int.clog 2 r with + | ofNat n => + rw [he, Int.ofNat_eq_natCast] at hlo hhi + have hn : n ≤ B := by omega + rw [Int.ofNat_eq_natCast, zpow_natCast] + have h := rationalEncodingBits_pow (2 : ℚ) n + rw [htwo] at h + omega + | negSucc n => + rw [he, Int.negSucc_eq] at hlo hhi + have hn : n + 1 ≤ B := by omega + rw [zpow_negSucc] + have hp := rationalEncodingBits_pow (2 : ℚ) (n + 1) + have hi := rationalEncodingBits_inv ((2 : ℚ) ^ (n + 1)) + rw [htwo] at hp + omega + +theorem rationalMaximum_encoding (fallback : ℚ) (values : List ℚ) (B : ℕ) + (hfallback : rationalEncodingBits fallback ≤ B) + (hvalues : ∀ value ∈ values, rationalEncodingBits value ≤ B) : + rationalEncodingBits (rationalMaximum fallback values) ≤ B := by + induction values with + | nil => exact hfallback + | cons value rest ih => + have hv := hvalues value List.mem_cons_self + have ht := ih (fun q hq => hvalues q (List.mem_cons_of_mem _ hq)) + change rationalEncodingBits (max value (rationalMaximum fallback rest)) ≤ B + rcases le_total value (rationalMaximum fallback rest) with h | h + · simpa only [max_eq_right h] using ht + · simpa only [max_eq_left h] using hv + +def bandEnvelopeEncodingBudget (M b initialBits : ℕ) : ℕ := + 5 * max (Nat.size b + Nat.size M + 7) (initialBits + 2) + 5 + +theorem bandChildEnvelope_encoding {ny M : ℕ} (b : ℕ) + (band : List (Fin M → TargetInterval ny)) + (initial : Fin M → TargetInterval ny → ℚ) (B : ℕ) (hb : 0 < b) (hM : 0 < M) + (hinitial : ∀ action ∈ band, ∀ i, rationalEncodingBits (initial i (action i)) ≤ B) + (i : Fin M) : + rationalEncodingBits (bandChildEnvelope b band initial i) ≤ bandEnvelopeEncodingBudget M b B := by + have hmax := rationalMaximum_encoding 0 (band.map fun action => initial i (action i)) (B + 2) + (by norm_num [rationalEncodingBits]) (by + intro q hq + obtain ⟨action, ha, rfl⟩ := List.mem_map.mp hq + exact (hinitial action ha i).trans (by omega)) + have hfloor := rationalEncodingBits_div (b : ℚ) (M : ℚ) + rw [rationalEncodingBits_natCast, rationalEncodingBits_natCast] at hfloor + have hbits : rationalEncodingBits (max ((b : ℚ) / M) + (rationalMaximum 0 (band.map fun action => initial i (action i)))) ≤ + max (Nat.size b + Nat.size M + 7) (B + 2) := by + rcases le_total ((b : ℚ) / M) (rationalMaximum 0 (band.map fun action => initial i (action i))) with h | h + · rw [max_eq_right h] + exact hmax.trans (Nat.le_max_right _ _) + · rw [max_eq_left h] + exact hfloor.trans (by have h := Nat.le_max_left (Nat.size b + Nat.size M + 7) (B + 2); omega) + exact rationalDyadicCeiling_encoding _ _ + ((div_pos (by exact_mod_cast hb) (by exact_mod_cast hM)).trans_le (le_max_left _ _)) hbits + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/BandEnvelopes.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/BandEnvelopes.lean new file mode 100644 index 0000000000000000000000000000000000000000..3a1eb8cf3938cc56b6242cd35f2b772d7b73a335 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/BandEnvelopes.lean @@ -0,0 +1,151 @@ +import OAI.Combinatorics.EditApproximation.Geometry.BandGuards +import Mathlib.Data.Int.Log +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! +# Actual dyadic child envelopes + +The maximum scans the actual finite band. The dyadic ceiling uses the +computable integer upper logarithm of a positive rational, including values +below one. +-/ + +namespace EditApproximation + +open Finset + + + +theorem rationalMaximum_le (fallback upper : ℚ) (values : List ℚ) + (hfallback : fallback ≤ upper) (hvalues : ∀ value ∈ values, value ≤ upper) : + rationalMaximum fallback values ≤ upper := by + induction values with + | nil => exact hfallback + | cons value rest ih => + exact max_le (hvalues value (by simp)) (ih (fun value hv => hvalues value (by simp [hv]))) + +theorem le_rationalMaximum_member (fallback : ℚ) (values : List ℚ) (value : ℚ) + (hvalue : value ∈ values) : value ≤ rationalMaximum fallback values := by + induction values with + | nil => simp only [List.not_mem_nil] at hvalue + | cons head rest ih => + rcases List.mem_cons.mp hvalue with rfl | hrest + · exact le_max_left _ _ + · exact (ih hrest).trans (le_max_right _ _) + + + +theorem rationalDyadicCeiling_bounds (value : ℚ) (hvalue : 0 < value) : + value ≤ rationalDyadicCeiling value ∧ rationalDyadicCeiling value < 2 * value := by + constructor + · exact Int.self_le_zpow_clog (by decide : 1 < 2) value + · have h := mul_lt_mul_of_pos_right + (Int.zpow_pred_clog_lt_self (by decide : 1 < 2) hvalue) (by norm_num : (0 : ℚ) < 2) + change (2 : ℚ) ^ (Int.clog 2 value - 1) * 2 < value * 2 at h + have hexponent : Int.clog 2 value - 1 + 1 = Int.clog 2 value := by omega + rw [← zpow_add_one₀ (by norm_num : (2 : ℚ) ≠ 0), hexponent] at h + simpa only [rationalDyadicCeiling, mul_comm] using h + +/-- Zero is a harmless duplicated fallback under the initial table lower +invariant. The positive b/M floor ensures that the ceiling input is positive. -/ + + +theorem bandChildEnvelope_lower {ny M : ℕ} (b : ℕ) + (band : List (Fin M → TargetInterval ny)) + (initial : Fin M → TargetInterval ny → ℚ) (i : Fin M) : + (b : ℚ) / M ≤ bandChildEnvelope b band initial i ∧ + ∀ action ∈ band, initial i (action i) ≤ bandChildEnvelope b band initial i := by + have hceil := Int.self_le_zpow_clog (R := ℚ) (by decide : 1 < 2) + (max ((b : ℚ) / M) (rationalMaximum 0 (band.map fun action => initial i (action i)))) + refine ⟨(le_max_left _ _).trans hceil, ?_⟩ + intro action ha + exact (le_rationalMaximum_member 0 _ _ (List.mem_map.mpr ⟨action, ha, rfl⟩)).trans + ((le_max_right _ _).trans hceil) + +/-- Every finite envelope is bounded using the actual computed-band +endpoint diameter and the initial table's spatial inequality. -/ +theorem bandChildEnvelope_upper {nx ny M : ℕ} (parent : TargetInterval nx) + (r : TargetInterval ny) (b P : ℕ) (hb : 0 < b) (hM : 0 < M) + (tau theta velocity : ℚ) (htau : 0 < tau) (htheta : 0 ≤ theta) + (child initial : Fin M → TargetInterval ny → ℚ) + (comparison : Fin M → TargetInterval ny) + (hcomparison : comparison ∈ computedBandActions parent r b P tau theta velocity child) + (L0 : ℚ) (hL0 : 0 ≤ L0) + (hinitial : ∀ i, 0 ≤ initial i (comparison i)) + (hspatial : ∀ i s t, initial i s ≤ initial i t + L0 * targetEndpointDistance s t) + (i : Fin M) : + bandChildEnvelope b (computedBandActions parent r b P tau theta velocity child) initial i ≤ + 2 * ((b : ℚ) / M) + 2 * initial i (comparison i) + 8 * L0 * theta * b / M := by + let band := computedBandActions parent r b P tau theta velocity child + let delta : ℚ := 4 * theta * b / M + let upper := initial i (comparison i) + L0 * delta + have hdelta : 0 ≤ delta := by dsimp only [delta]; positivity + have hupper : 0 ≤ upper := add_nonneg (hinitial i) (mul_nonneg hL0 hdelta) + have hmembers : ∀ value ∈ band.map (fun action => initial i (action i)), value ≤ upper := by + intro value hvalue + obtain ⟨action, ha, rfl⟩ := List.mem_map.mp hvalue + have hdistReal := computedBand_child_endpoint_diameter parent r b P tau theta velocity htau htheta + child action comparison ha hcomparison i + have hdist : (targetEndpointDistance (action i) (comparison i) : ℚ) ≤ delta := by exact_mod_cast hdistReal + exact (hspatial i (action i) (comparison i)).trans + (add_le_add le_rfl (mul_le_mul_of_nonneg_left hdist hL0)) + have hmaximum := rationalMaximum_le 0 upper _ hupper hmembers + have hfloor : (0 : ℚ) < (b : ℚ) / M := div_pos (by exact_mod_cast hb) (by exact_mod_cast hM) + have hpositive := hfloor.trans_le (le_max_left ((b : ℚ) / M) + (rationalMaximum 0 (band.map fun action => initial i (action i)))) + have hceil := (rationalDyadicCeiling_bounds _ hpositive).2.le + have hmaxUpper : max ((b : ℚ) / M) + (rationalMaximum 0 (band.map fun action => initial i (action i))) ≤ (b : ℚ) / M + upper := by + apply max_le + · exact le_add_of_nonneg_right hupper + · exact hmaximum.trans (le_add_of_nonneg_left hfloor.le) + apply hceil.trans + have hmul := mul_le_mul_of_nonneg_left hmaxUpper (by norm_num : (0 : ℚ) ≤ 2) + dsimp only [upper, delta] at hmul + convert hmul using 1 + ring + +/-- The actual sum guard follows from the concrete envelopes, the initial +cone bounds at the comparison child states, and their actual edit costs. -/ +theorem bandChildEnvelope_sum_guard {α : Type*} (source target : List α) + {M : ℕ} (parent : TargetInterval source.length) (r : TargetInterval target.length) + (b P : ℕ) (hb : 0 < b) (hM : 0 < M) + (tau theta velocity : ℚ) (htau : 0 < tau) (htheta : 0 ≤ theta) + (child initial : Fin M → TargetInterval target.length → ℚ) + (comparison : Fin M → TargetInterval target.length) + (hcomparison : comparison ∈ computedBandActions parent r b P tau theta velocity child) + (L0 F : ℚ) (hL0 : 0 ≤ L0) (hF : 1 ≤ F) (hsmall : L0 * theta ≤ 1) + (hinitial : ∀ i, 0 ≤ initial i (comparison i)) + (hspatial : ∀ i s t, initial i s ≤ initial i t + L0 * targetEndpointDistance s t) + (hinitialUpper : ∀ i, initial i (comparison i) ≤ 2 * F * (stateEditCost + (substring source (sourceChild parent i).lo (sourceChild parent i).hi) target (comparison i) : ℚ)) + (hcomparisonCost : (∑ i : Fin M, (stateEditCost + (substring source (sourceChild parent i).lo (sourceChild parent i).hi) target (comparison i) : ℚ)) ≤ 4 * b) : + (∑ i : Fin M, bandChildEnvelope b + (computedBandActions parent r b P tau theta velocity child) initial i) ≤ 64 * F * b := by + have hMr : (0 : ℚ) < M := by exact_mod_cast hM + have hpoint := fun i => bandChildEnvelope_upper parent r b P hb hM tau theta velocity htau htheta + child initial comparison hcomparison L0 hL0 hinitial hspatial i + have hsum := sum_le_sum (fun i (_ : i ∈ (univ : Finset (Fin M))) => hpoint i) + have hequal : (∑ i : Fin M, (2 * ((b : ℚ) / M) + 2 * initial i (comparison i) + + 8 * L0 * theta * b / M)) = 2 * b + 2 * (∑ i : Fin M, initial i (comparison i)) + + 8 * L0 * theta * b := by + rw [sum_add_distrib, sum_add_distrib, sum_const, sum_const, + card_univ, Fintype.card_fin, ← mul_sum] + simp only [nsmul_eq_mul] + field_simp [hMr.ne'] + rw [hequal] at hsum + have hinitSum := sum_le_sum (fun i (_ : i ∈ (univ : Finset (Fin M))) => hinitialUpper i) + rw [← mul_sum] at hinitSum + have hFpos : 0 ≤ 2 * F := by linarith + have hcost := mul_le_mul_of_nonneg_left hcomparisonCost hFpos + have hsmallb := mul_le_mul_of_nonneg_right hsmall (show (0 : ℚ) ≤ b by positivity) + have hFb := mul_le_mul_of_nonneg_right hF (show (0 : ℚ) ≤ b by positivity) + nlinarith only [hsum, hinitSum, hcost, hsmallb, hFb] + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/BandGroupSampling.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/BandGroupSampling.lean new file mode 100644 index 0000000000000000000000000000000000000000..30d3d53a3d57ffdde0ccda4a65acdb934011ea86 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/BandGroupSampling.lean @@ -0,0 +1,554 @@ +import OAI.Combinatorics.EditApproximation.Geometry.UnskippedBands +import OAI.Combinatorics.EditApproximation.Geometry.GroupSampling +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! +# Executable shared group estimates + +All dyadic powers in the prescribed closed range are enumerated, including +negative exponents. A scale is evaluated exactly when its sample count +reaches the child count; otherwise one shared array of uniform labels is +used for every member of the group. The selected member is the first +minimizer in the fixed list order. +-/ + +namespace EditApproximation + +open Finset MeasureTheory ProbabilityTheory + + + +theorem integerClosedRange_mem (lo hi value : ℤ) : + value ∈ integerClosedRange lo hi ↔ lo ≤ value ∧ value ≤ hi := by + constructor + · intro h + obtain ⟨i, hi', hequal⟩ := List.mem_map.mp h + have hrange := List.mem_range.mp hi' + omega + · rintro ⟨hlower, hupper⟩ + apply List.mem_map.mpr + refine ⟨(value - lo).toNat, List.mem_range.mpr ?_, ?_⟩ <;> omega + +theorem integerClosedRange_nodup (lo hi : ℤ) : (integerClosedRange lo hi).Nodup := by + apply List.Nodup.map _ (List.nodup_range) + intro i j hequal + change lo + (i : ℤ) = lo + (j : ℤ) at hequal + omega + + + +theorem groupDyadicScales_mem {M b : ℕ} (hM : 0 < M) (hb : 0 < b) + (F : ℚ) (hF : 0 < F) (exponent : ℤ) : + (2 : ℚ) ^ exponent ∈ groupDyadicScales M b F ↔ + (b : ℚ) / M ≤ (2 : ℚ) ^ exponent ∧ (2 : ℚ) ^ exponent ≤ 64 * F * b := by + have hlower : (0 : ℚ) < (b : ℚ) / M := by positivity + have hupper : (0 : ℚ) < 64 * F * b := by positivity + constructor + · intro h + obtain ⟨other, hother, hequal⟩ := List.mem_map.mp h + have hsame : other = exponent := + zpow_right_injective₀ (by norm_num : (0 : ℚ) < 2) (by norm_num : (2 : ℚ) ≠ 1) hequal + subst other + have hrange := (integerClosedRange_mem _ _ _).mp hother + exact ⟨(Int.le_zpow_iff_clog_le (by decide : 1 < 2) hlower).mpr hrange.1, + (Int.zpow_le_iff_le_log (by decide : 1 < 2) hupper).mpr hrange.2⟩ + · rintro ⟨hlow, hhigh⟩ + apply List.mem_map.mpr + refine ⟨exponent, (integerClosedRange_mem _ _ _).mpr ⟨?_, ?_⟩, rfl⟩ + · exact (Int.le_zpow_iff_clog_le (by decide : 1 < 2) hlower).mp hlow + · exact (Int.zpow_le_iff_le_log (by decide : 1 < 2) hupper).mp hhigh + +theorem groupDyadicScales_nodup (M b : ℕ) (F : ℚ) : (groupDyadicScales M b F).Nodup := by + exact (integerClosedRange_nodup _ _).map + (zpow_right_injective₀ (by norm_num : (0 : ℚ) < 2) (by norm_num : (2 : ℚ) ≠ 1)) + +theorem groupDyadicScales_pos {M b : ℕ} {F h : ℚ} + (hh : h ∈ groupDyadicScales M b F) : 0 < h := by + obtain ⟨exponent, _, rfl⟩ := List.mem_map.mp hh + positivity + + + +theorem groupDyadicScales_length (M b : ℕ) (F : ℚ) : + (groupDyadicScales M b F).length = + (Int.log 2 (64 * F * b) - Int.clog 2 ((b : ℚ) / M) + 1).toNat := by + simp only [groupDyadicScales, List.length_map, integerClosedRange, List.length_range] + +theorem groupDyadicScales_length_dyadic (eM eb eF : ℕ) : + (groupDyadicScales (2 ^ eM) (2 ^ eb) ((2 : ℚ) ^ eF)).length = 7 + eM + eF := by + have hlower : ((2 ^ eb : ℕ) : ℚ) / (2 ^ eM : ℕ) = (2 : ℚ) ^ ((eb : ℤ) - eM) := by + rw [Nat.cast_pow, Nat.cast_pow, Nat.cast_ofNat, zpow_sub₀ (by norm_num : (2 : ℚ) ≠ 0), + zpow_natCast, zpow_natCast] + have hupper : (64 : ℚ) * (2 : ℚ) ^ eF * (2 ^ eb : ℕ) = + (2 : ℚ) ^ ((6 + eF + eb : ℕ) : ℤ) := by + rw [Nat.cast_pow, Nat.cast_ofNat, zpow_natCast, pow_add, pow_add] + norm_num + have hlog : Int.log 2 ((2 : ℚ) ^ ((6 + eF + eb : ℕ) : ℤ)) = ((6 + eF + eb : ℕ) : ℤ) := by + simpa only [Nat.cast_ofNat] using Int.log_zpow (R := ℚ) (by decide : 1 < 2) ((6 + eF + eb : ℕ) : ℤ) + have hclog : Int.clog 2 ((2 : ℚ) ^ ((eb : ℤ) - eM)) = (eb : ℤ) - eM := by + simpa only [Nat.cast_ofNat] using Int.clog_zpow (R := ℚ) (by decide : 1 < 2) ((eb : ℤ) - eM) + rw [groupDyadicScales_length, hlower, hupper, hlog, hclog] + omega + +theorem groupSampleCount_pos {M Q b : ℕ} {h : ℚ} + (hM : 0 < M) (hQ : 0 < Q) (hb : 0 < b) (hh : 0 < h) : + 0 < groupSampleCount M Q b h := by + exact lt_min hM (Nat.ceil_pos.mpr (by positivity)) + +theorem groupSampleCount_sampled {M Q b : ℕ} {h : ℚ} + (hsampled : groupSampleCount M Q b h < M) : + (Q : ℚ) * M * h / b ≤ groupSampleCount M Q b h := by + have hceil : groupSampleCount M Q b h = ⌈(Q : ℚ) * M * h / b⌉₊ := by + unfold groupSampleCount at hsampled ⊢ + omega + rw [hceil] + exact Nat.le_ceil _ + + + + + +theorem groupScaleEstimate_exact {M : ℕ} (h : ℚ) (envelope value : Fin M → ℚ) + (draw : Fin M → Fin M) : groupScaleEstimate M h envelope value draw = groupScaleTrueCost h envelope value := by + simp only [groupScaleEstimate, ↓reduceIte] + +/-- The sample and actual scale cost have exactly the normalized average +used in the published Bernstein specialization. -/ +theorem groupScaleEstimate_normalized {M b k : ℕ} (h : ℚ) + (envelope value : Fin M → ℚ) (draw : Fin k → Fin M) + (hM : 0 < M) (hb : 0 < b) (hk : 0 < k) (hsampled : k ≠ M) : + ((groupScaleEstimate k h envelope value draw - groupScaleTrueCost h envelope value : ℚ) : ℝ) = + (b : ℝ) * ((∑ j, normalizedChildSample (b : ℝ) (h : ℝ) + (fun i => (envelope i : ℝ)) (fun i => (value i : ℝ)) (draw j)) / k - + uniformMean (normalizedChildSample (b : ℝ) (h : ℝ) + (fun i => (envelope i : ℝ)) (fun i => (value i : ℝ)))) := by + have hMr : (M : ℝ) ≠ 0 := by exact_mod_cast (Nat.ne_of_gt hM) + have hbr : (b : ℝ) ≠ 0 := by exact_mod_cast (Nat.ne_of_gt hb) + have hkr : (k : ℝ) ≠ 0 := by exact_mod_cast (Nat.ne_of_gt hk) + have hcast (i : Fin M) : normalizedChildSample (b : ℝ) (h : ℝ) + (fun i => (envelope i : ℝ)) (fun i => (value i : ℝ)) i = + (M : ℝ) / b * ((if envelope i = h then value i else 0 : ℚ) : ℝ) := by + by_cases hequal : envelope i = h + · simp only [normalizedChildSample, hequal, ↓reduceIte] + ring + · have hequalR : (envelope i : ℝ) ≠ (h : ℝ) := by exact_mod_cast hequal + simp only [normalizedChildSample, hequal, hequalR, ↓reduceIte, Rat.cast_zero, mul_zero] + unfold uniformMean + simp_rw [hcast] + simp only [groupScaleEstimate, hsampled, ↓reduceIte, groupScaleTrueCost, + Fintype.card_fin, Rat.cast_sub, Rat.cast_mul, Rat.cast_div, + Rat.cast_natCast, Rat.cast_sum] + rw [← mul_sum, ← mul_sum] + field_simp + +/-- Fixed ordered minimization; negating the rational estimate turns the +finite maximum operation into the first cost minimum. -/ + + +theorem selectGroupMember_spec {ι : Type*} (members : List ι) (hnonempty : members ≠ []) + (estimate : ι → ℚ) : + selectGroupMember members hnonempty estimate ∈ members ∧ + ∀ member ∈ members, estimate (selectGroupMember members hnonempty estimate) ≤ estimate member := by + unfold selectGroupMember + cases harg : members.argmax (fun member => -estimate member) with + | none => exact False.elim (hnonempty (List.argmax_eq_none.mp harg)) + | some selected => + simp only [Option.getD_some] + have hmem : selected ∈ members.argmax (fun member => -estimate member) := by rw [harg]; simp + refine ⟨List.argmax_mem hmem, ?_⟩ + intro member hmember + have h := List.le_of_mem_argmax (f := fun member => -estimate member) hmember hmem + linarith + +theorem groupScaleEstimate_concentration {M Q b k : ℕ} [NeZero M] + [MeasurableSpace (Fin M)] [MeasurableSingletonClass (Fin M)] + (hM : 0 < M) (hQ : 0 < Q) (hb : 0 < b) (h F deviation : ℚ) + (hh : 0 < h) (hF : 0 < F) (hdev : 0 < deviation) + (envelope value : Fin M → ℚ) + (henvelope : ∀ i, 0 ≤ envelope i) + (hvalue : ∀ i, 0 ≤ value i ∧ value i ≤ 2 * envelope i) + (hsum : (∑ i, envelope i) ≤ 64 * F * b) + (hcount : k = groupSampleCount M Q b h) + (bernstein : FiniteBernsteinInput + (Measure.pi fun _ : Fin k => (PMF.uniformOfFintype (Fin M)).toMeasure)) : + (Measure.pi fun _ : Fin k => (PMF.uniformOfFintype (Fin M)).toMeasure).real + {draw | (deviation : ℝ) * b ≤ + |((groupScaleEstimate k h envelope value draw - groupScaleTrueCost h envelope value : ℚ) : ℝ)|} ≤ + 2 * Real.exp (-(Q : ℝ) * (deviation : ℝ) ^ 2 / + (512 * (F : ℝ) + (4 / 3 : ℝ) * deviation)) := by + have hbr : (0 : ℝ) < b := by exact_mod_cast hb + have hhr : (0 : ℝ) < h := by exact_mod_cast hh + have hFr : (0 : ℝ) < F := by exact_mod_cast hF + have hdevr : (0 : ℝ) < deviation := by exact_mod_cast hdev + by_cases hexact : k = M + · have hempty : {draw : Fin k → Fin M | (deviation : ℝ) * b ≤ + |((groupScaleEstimate k h envelope value draw - groupScaleTrueCost h envelope value : ℚ) : ℝ)|} = ∅ := by + ext draw + simp only [groupScaleEstimate, hexact, ↓reduceIte, sub_self, Rat.cast_zero, abs_zero, + Set.mem_ofPred_eq, Set.mem_empty_iff_false, iff_false] + exact not_le.mpr (mul_pos hdevr hbr) + rw [hempty, measureReal_empty] + positivity + · have hsampled : groupSampleCount M Q b h < M := by + have hle : groupSampleCount M Q b h ≤ M := min_le_left _ _ + omega + have hk : 0 < k := hcount ▸ groupSampleCount_pos hM hQ hb hh + let sample := normalizedChildSample (b : ℝ) (h : ℝ) + (fun i => (envelope i : ℝ)) (fun i => (value i : ℝ)) + have hmoments := normalizedChildSample_moments hM (b : ℝ) (h : ℝ) (F : ℝ) hbr hhr + (fun i => (envelope i : ℝ)) (fun i => (value i : ℝ)) + (fun i => by exact_mod_cast henvelope i) + (fun i => by exact_mod_cast hvalue i) (by exact_mod_cast hsum) + have hsamples : (Q : ℝ) * ((M : ℝ) * (h : ℝ) / b) ≤ k := by + have hsampleLower := groupSampleCount_sampled hsampled + rw [← hcount] at hsampleLower + have hcast : (Q : ℝ) * M * (h : ℝ) / b ≤ k := by exact_mod_cast hsampleLower + convert hcast using 1 + ring + have htail := group_scale_concentration k hk sample ((M : ℝ) * (h : ℝ) / b) + (F : ℝ) (Q : ℝ) (deviation : ℝ) (by positivity) hFr hdevr + hmoments.1 hmoments.2 hsamples bernstein + have hevent : {draw : Fin k → Fin M | (deviation : ℝ) * b ≤ + |((groupScaleEstimate k h envelope value draw - groupScaleTrueCost h envelope value : ℚ) : ℝ)|} = + {draw | (deviation : ℝ) ≤ |(∑ j, sample (draw j)) / k - uniformMean sample|} := by + ext draw + rw [Set.mem_ofPred_eq, Set.mem_ofPred_eq, + groupScaleEstimate_normalized h envelope value draw hM hb hk hexact, + abs_mul, abs_of_pos hbr, mul_comm (deviation : ℝ) (b : ℝ)] + exact mul_le_mul_iff_right₀ hbr + rw [hevent] + exact htail + +noncomputable def groupSharedDrawLaw {M T : ℕ} [NeZero M] + [MeasurableSpace (Fin M)] (count : Fin T → ℕ) : + Measure (∀ scale : Fin T, Fin (count scale) → Fin M) := + Measure.pi fun scale : Fin T => + Measure.pi fun _ : Fin (count scale) => (PMF.uniformOfFintype (Fin M)).toMeasure + +instance groupSharedDrawLaw_isProbabilityMeasure {M T : ℕ} [NeZero M] + [MeasurableSpace (Fin M)] [MeasurableSingletonClass (Fin M)] (count : Fin T → ℕ) : + IsProbabilityMeasure (groupSharedDrawLaw (M := M) count) := by + unfold groupSharedDrawLaw + infer_instance + +theorem groupSharedDraw_projection {M T : ℕ} [NeZero M] + [MeasurableSpace (Fin M)] [MeasurableSingletonClass (Fin M)] + (count : Fin T → ℕ) (scale : Fin T) (bad : Set (Fin (count scale) → Fin M)) : + (groupSharedDrawLaw count).real {draw | draw scale ∈ bad} = + (Measure.pi fun _ : Fin (count scale) => (PMF.uniformOfFintype (Fin M)).toMeasure).real bad := by + let ν (scale : Fin T) := + Measure.pi fun _ : Fin (count scale) => (PMF.uniformOfFintype (Fin M)).toMeasure + have hmap := (measurePreserving_eval (μ := ν) scale).map_eq + have hpreimage := Measure.map_apply (μ := Measure.pi ν) (measurable_pi_apply scale) + (Set.toFinite bad).measurableSet + rw [hmap] at hpreimage + exact congrArg ENNReal.toReal hpreimage.symm + +/-- Actual shared draws are reused for all group members at this scale; +no independence between representatives is imposed. -/ + + +theorem selectGroupMember_cost_le {ι : Type*} (members : List ι) (hnonempty : members ≠ []) + (cost estimate : ι → ℚ) (specified : ι) (hspecified : specified ∈ members) (error : ℚ) + (haccurate : ∀ member ∈ members, |estimate member - cost member| ≤ error) : + cost (selectGroupMember members hnonempty estimate) ≤ cost specified + 2 * error := by + classical + have hspec := selectGroupMember_spec members hnonempty estimate + have hreal := selected_group_cost_le members.toFinset (fun member => (cost member : ℝ)) + (fun member => (estimate member : ℝ)) (selectGroupMember members hnonempty estimate) specified (error : ℝ) + (by simpa only [List.mem_toFinset] using hspec.1) + (by simpa only [List.mem_toFinset] using hspecified) + (fun member hmember => by exact_mod_cast haccurate member (List.mem_toFinset.mp hmember)) + (by exact_mod_cast hspec.2 specified hspecified) + exact_mod_cast hreal + +theorem groupScaleTrueCost_sum {M T : ℕ} (scales : Fin T → ℚ) + (hinjective : Function.Injective scales) (envelope value : Fin M → ℚ) + (hcover : ∀ i, ∃ scale, scales scale = envelope i) : + (∑ scale, groupScaleTrueCost (scales scale) envelope value) = ∑ i, value i := by + unfold groupScaleTrueCost + rw [sum_comm] + apply sum_congr rfl + intro i hi + obtain ⟨scale, hscale⟩ := hcover i + have h : (∑ other : Fin T, if scales scale = scales other then value i else 0) = value i := by + simp only [hinjective.eq_iff, sum_ite_eq, mem_univ, ↓reduceIte] + simpa only [hscale] using h + +theorem uniform_sample_average_integral {M k : ℕ} [NeZero M] + [MeasurableSpace (Fin M)] [MeasurableSingletonClass (Fin M)] + (hk : 0 < k) (value : Fin M → ℝ) : + (∫ draw, (∑ j : Fin k, value (draw j)) / k + ∂Measure.pi (fun _ : Fin k => (PMF.uniformOfFintype (Fin M)).toMeasure)) = uniformMean value := by + have hkr : (k : ℝ) ≠ 0 := by exact_mod_cast (Nat.ne_of_gt hk) + rw [integral_div, integral_finsetSum univ (by intro j hj; exact .of_finite)] + have hpoint (j : Fin k) : + (∫ draw, value (draw j) + ∂Measure.pi (fun _ : Fin k => (PMF.uniformOfFintype (Fin M)).toMeasure)) = uniformMean value := by + rw [integral_comp_eval (μ := fun _ : Fin k => (PMF.uniformOfFintype (Fin M)).toMeasure) + (i := j) (f := value) (measurable_of_finite _).aestronglyMeasurable, uniform_integral] + simp_rw [hpoint] + simp only [sum_const, card_univ, Fintype.card_fin, nsmul_eq_mul] + field_simp + +theorem groupScaleEstimate_integral {M b k : ℕ} [NeZero M] + [MeasurableSpace (Fin M)] [MeasurableSingletonClass (Fin M)] + (h : ℚ) (envelope value : Fin M → ℚ) (hM : 0 < M) (hb : 0 < b) (hk : 0 < k) : + (∫ draw, (groupScaleEstimate k h envelope value draw : ℝ) + ∂Measure.pi (fun _ : Fin k => (PMF.uniformOfFintype (Fin M)).toMeasure)) = + (groupScaleTrueCost h envelope value : ℝ) := by + let μ := Measure.pi fun _ : Fin k => (PMF.uniformOfFintype (Fin M)).toMeasure + by_cases hexact : k = M + · simp only [groupScaleEstimate, hexact, ↓reduceIte, integral_const, probReal_univ, one_smul] + · let sample := normalizedChildSample (b : ℝ) (h : ℝ) + (fun i => (envelope i : ℝ)) (fun i => (value i : ℝ)) + have herror : (∫ draw, ((groupScaleEstimate k h envelope value draw - groupScaleTrueCost h envelope value : ℚ) : ℝ) + ∂μ) = 0 := by + simp_rw [groupScaleEstimate_normalized h envelope value _ hM hb hk hexact] + rw [integral_const_mul, integral_sub (.of_finite) (integrable_const _), + uniform_sample_average_integral hk, integral_const, probReal_univ, one_smul, sub_self, mul_zero] + simp only [Rat.cast_sub] at herror + rw [integral_sub (.of_finite) (integrable_const _), integral_const, probReal_univ, one_smul] at herror + linarith + +theorem groupMemberEstimate_error {M T : ℕ} (scales : Fin T → ℚ) (count : Fin T → ℕ) + (hinjective : Function.Injective scales) (connection : ℚ) (envelope value : Fin M → ℚ) + (hcover : ∀ i, ∃ scale, scales scale = envelope i) + (draw : ∀ scale : Fin T, Fin (count scale) → Fin M) (error : ℚ) + (herror : ∀ scale, |groupScaleEstimate (count scale) (scales scale) envelope value (draw scale) - + groupScaleTrueCost (scales scale) envelope value| ≤ error) : + |groupMemberEstimate scales count connection envelope value draw - (connection + ∑ i, value i)| ≤ + T * error := by + rw [← groupScaleTrueCost_sum scales hinjective envelope value hcover] + unfold groupMemberEstimate + rw [add_sub_add_left_eq_sub, ← sum_sub_distrib] + apply (abs_sum_le_sum_abs _ _).trans + have hsum := sum_le_sum (s := univ) fun scale _ => herror scale + simpa only [sum_const, card_univ, Fintype.card_fin, nsmul_eq_mul] using hsum + +section ActualUnskippedGroup + +variable {α : Type*} {source target : List α} {M b P thetaExponent : ℕ} + {parent : TargetInterval source.length} {tau F : ℚ} + {child initial : Fin M → TargetInterval target.length → ℚ} + +theorem testUnskippedBand_accept + (member : UnskippedBand source target parent b P thetaExponent tau F child initial) : + testUnskippedBand source target parent b P thetaExponent tau F child initial member.center = some member := by + cases member with + | mk center nonempty hsum hwide hgap => + simp only [testUnskippedBand, dite_eq_right nonempty, dite_eq_left hsum, + dite_eq_left hwide, dite_eq_left hgap] + +theorem testUnskippedBand_center + (center : TargetInterval target.length) + (member : UnskippedBand source target parent b P thetaExponent tau F child initial) + (haccepted : testUnskippedBand source target parent b P thetaExponent tau F child initial center = some member) : + member.center = center := by + unfold testUnskippedBand at haccepted + dsimp only at haccepted + split_ifs at haccepted + cases haccepted + rfl + +theorem unskippedBandList_mem_iff + (centers : List (TargetInterval target.length)) + (member : UnskippedBand source target parent b P thetaExponent tau F child initial) : + member ∈ unskippedBandList source target parent b P thetaExponent tau F child initial centers ↔ + member.center ∈ centers := by + constructor + · intro hmember + obtain ⟨center, hcenter, haccepted⟩ := List.mem_filterMap.mp hmember + rwa [testUnskippedBand_center center member haccepted] + · intro hcenter + exact List.mem_filterMap.mpr ⟨member.center, hcenter, testUnskippedBand_accept member⟩ + +theorem unskippedBand_envelope_scale + (member : UnskippedBand source target parent b P thetaExponent tau F child initial) + (hM : 0 < M) (hb : 0 < b) (hF : 0 < F) (i : Fin M) : + member.envelope i ∈ groupDyadicScales M b F := by + have hlower := (bandChildEnvelope_lower b member.actions initial i).1 + change (b : ℚ) / M ≤ member.envelope i at hlower + have hsingle : member.envelope i ≤ ∑ j, member.envelope j := + single_le_sum (fun j _ => (member.envelope_pos j).le) (mem_univ i) + have hupper := hsingle.trans member.sum_guard + have hpower : member.envelope i = (2 : ℚ) ^ bandEnvelopeExponent b member.actions initial i := rfl + rw [hpower] + exact (groupDyadicScales_mem hM hb F hF _).mpr ⟨by simpa only [hpower] using hlower, + by simpa only [hpower] using hupper⟩ + +theorem unskippedBand_rounded_value_bounds + (member : UnskippedBand source target parent b P thetaExponent tau F child initial) + (value : Fin M → TargetInterval target.length → ℚ) (L0 : ℚ) (hL0 : 0 ≤ L0) + (hsmall : 2 * L0 * (2 : ℚ) ^ (-(thetaExponent : ℤ)) ≤ 1) + (hspatial : ∀ i s t, initial i s ≤ initial i t + L0 * targetEndpointDistance s t) + (hvalue : ∀ i s, 0 ≤ value i s ∧ value i s ≤ initial i s) (i : Fin M) : + 0 ≤ value i (member.rounded i) ∧ value i (member.rounded i) ≤ 2 * member.envelope i := by + refine ⟨(hvalue i (member.rounded i)).1, (hvalue i (member.rounded i)).2.trans ?_⟩ + exact roundedBandAction_initialValue_le_twice thetaExponent b member.actions initial + (member.actions.head member.nonempty) (List.head_mem member.nonempty) L0 hL0 hsmall hspatial i + + + + + + + + + + +theorem unskippedGroupEstimate_error {T : ℕ} (scales : Fin T → ℚ) (count : Fin T → ℕ) + (hscales : List.ofFn scales = groupDyadicScales M b F) + (value : Fin M → TargetInterval target.length → ℚ) + (member : UnskippedBand source target parent b P thetaExponent tau F child initial) + (hM : 0 < M) (hb : 0 < b) (hF : 0 < F) + (draw : ∀ scale : Fin T, Fin (count scale) → Fin M) (error : ℚ) + (herror : ∀ scale, |groupScaleEstimate (count scale) (scales scale) member.envelope + (fun i => value i (member.rounded i)) (draw scale) - + groupScaleTrueCost (scales scale) member.envelope (fun i => value i (member.rounded i))| ≤ error) : + |unskippedGroupEstimate scales count value member draw - + rationalEndpointActionValue member.center member.rounded value| ≤ T * error := by + have hinjective : Function.Injective scales := List.nodup_ofFn.mp + (hscales.symm ▸ groupDyadicScales_nodup M b F) + have hcover (i : Fin M) : ∃ scale, scales scale = member.envelope i := by + have hmember := unskippedBand_envelope_scale member hM hb hF i + rw [← hscales] at hmember + exact List.mem_ofFn.mp hmember + exact groupMemberEstimate_error scales count hinjective _ member.envelope + (fun i => value i (member.rounded i)) hcover draw error herror + +/-- Uniform simultaneous accuracy for the actual fixed list of unskipped +records. The same per-scale samples are reused by every record. -/ +theorem unskippedGroupEstimate_failure {T : ℕ} [NeZero M] + [MeasurableSpace (Fin M)] [MeasurableSingletonClass (Fin M)] + (scales : Fin T → ℚ) (count : Fin T → ℕ) (Q : ℕ) + (hscales : List.ofFn scales = groupDyadicScales M b F) + (hcount : ∀ scale, count scale = groupSampleCount M Q b (scales scale)) + (value : Fin M → TargetInterval target.length → ℚ) + (members : List (UnskippedBand source target parent b P thetaExponent tau F child initial)) + (hM : 0 < M) (hQ : 0 < Q) (hb : 0 < b) (hF : 0 < F) + (L0 : ℚ) (hL0 : 0 ≤ L0) + (hsmall : 2 * L0 * (2 : ℚ) ^ (-(thetaExponent : ℤ)) ≤ 1) + (hspatial : ∀ i s t, initial i s ≤ initial i t + L0 * targetEndpointDistance s t) + (hvalue : ∀ i s, 0 ≤ value i s ∧ value i s ≤ initial i s) + (deviation : ℚ) (hdev : 0 < deviation) + (bernstein : ∀ scale : Fin T, FiniteBernsteinInput + (Measure.pi fun _ : Fin (count scale) => (PMF.uniformOfFintype (Fin M)).toMeasure)) : + (groupSharedDrawLaw count).real + {draw | ∃ member ∈ members, (T : ℝ) * (deviation : ℝ) * b < + |((unskippedGroupEstimate scales count value member draw - + rationalEndpointActionValue member.center member.rounded value : ℚ) : ℝ)|} ≤ + (members.length : ℝ) * T * + (2 * Real.exp (-(Q : ℝ) * (deviation : ℝ) ^ 2 / + (512 * (F : ℝ) + (4 / 3 : ℝ) * deviation))) := by + classical + let μ := groupSharedDrawLaw (M := M) count + let : IsProbabilityMeasure μ := by dsimp only [μ]; infer_instance + let bad (member : UnskippedBand source target parent b P thetaExponent tau F child initial) + (scale : Fin T) : Set (∀ scale : Fin T, Fin (count scale) → Fin M) := + {draw | (deviation : ℝ) * b ≤ + |((groupScaleEstimate (count scale) (scales scale) member.envelope + (fun i => value i (member.rounded i)) (draw scale) - + groupScaleTrueCost (scales scale) member.envelope + (fun i => value i (member.rounded i)) : ℚ) : ℝ)|} + let failure := 2 * Real.exp (-(Q : ℝ) * (deviation : ℝ) ^ 2 / + (512 * (F : ℝ) + (4 / 3 : ℝ) * deviation)) + have hpoint (member : UnskippedBand source target parent b P thetaExponent tau F child initial) + (_hmember : member ∈ members.toFinset) (scale : Fin T) (_hscale : scale ∈ (univ : Finset (Fin T))) : + μ.real (bad member scale) ≤ failure := by + have hscaleMember : scales scale ∈ groupDyadicScales M b F := by + rw [← hscales] + exact List.mem_ofFn.mpr ⟨scale, rfl⟩ + have hscalePos := groupDyadicScales_pos hscaleMember + change μ.real {draw | draw scale ∈ {sample | + (deviation : ℝ) * b ≤ + |((groupScaleEstimate (count scale) (scales scale) member.envelope + (fun i => value i (member.rounded i)) sample - + groupScaleTrueCost (scales scale) member.envelope + (fun i => value i (member.rounded i)) : ℚ) : ℝ)|}} ≤ failure + rw [groupSharedDraw_projection] + exact groupScaleEstimate_concentration hM hQ hb (scales scale) F deviation hscalePos hF hdev + member.envelope (fun i => value i (member.rounded i)) (fun i => (member.envelope_pos i).le) + (unskippedBand_rounded_value_bounds member value L0 hL0 hsmall hspatial hvalue) + member.sum_guard (hcount scale) (bernstein scale) + have hsubset : {draw | ∃ member ∈ members, (T : ℝ) * (deviation : ℝ) * b < + |((unskippedGroupEstimate scales count value member draw - + rationalEndpointActionValue member.center member.rounded value : ℚ) : ℝ)|} ⊆ + ⋃ member ∈ members.toFinset, ⋃ scale ∈ (univ : Finset (Fin T)), bad member scale := by + intro draw hdraw + obtain ⟨member, hmember, herror⟩ := hdraw + by_contra hnot + have hscaleError (scale : Fin T) : + |groupScaleEstimate (count scale) (scales scale) member.envelope + (fun i => value i (member.rounded i)) (draw scale) - + groupScaleTrueCost (scales scale) member.envelope (fun i => value i (member.rounded i))| ≤ deviation * b := by + have hnotScale : draw ∉ bad member scale := by + intro hbad + apply hnot + exact Set.mem_iUnion.mpr ⟨member, Set.mem_iUnion.mpr ⟨List.mem_toFinset.mpr hmember, + Set.mem_iUnion.mpr ⟨scale, Set.mem_iUnion.mpr ⟨mem_univ scale, hbad⟩⟩⟩⟩ + have hlt : |((groupScaleEstimate (count scale) (scales scale) member.envelope + (fun i => value i (member.rounded i)) (draw scale) - + groupScaleTrueCost (scales scale) member.envelope (fun i => value i (member.rounded i)) : ℚ) : ℝ)| < + (deviation : ℝ) * b := lt_of_not_ge hnotScale + exact_mod_cast hlt.le + have htotal := unskippedGroupEstimate_error scales count hscales value member hM hb hF draw + (deviation * b) hscaleError + have htotalR : |((unskippedGroupEstimate scales count value member draw - + rationalEndpointActionValue member.center member.rounded value : ℚ) : ℝ)| ≤ + (T : ℝ) * (deviation : ℝ) * b := by + have hcast : |((unskippedGroupEstimate scales count value member draw - + rationalEndpointActionValue member.center member.rounded value : ℚ) : ℝ)| ≤ + (T : ℝ) * ((deviation : ℝ) * b) := by exact_mod_cast htotal + simpa only [mul_assoc] using hcast + exact (not_lt_of_ge htotalR) herror + have hunion := group_failure_union_bound μ members.toFinset (univ : Finset (Fin T)) bad failure hpoint + have hcard : (members.toFinset.card : ℝ) ≤ members.length := by exact_mod_cast members.toFinset_card_le + have hfailure : 0 ≤ (T : ℝ) * failure := by dsimp [failure]; positivity + calc + _ ≤ μ.real (⋃ member ∈ members.toFinset, ⋃ scale ∈ (univ : Finset (Fin T)), bad member scale) := + measureReal_mono hsubset (measure_ne_top μ _) + _ ≤ (members.toFinset.card : ℝ) * T * failure := by simpa only [card_univ, Fintype.card_fin] using hunion + _ ≤ (members.length : ℝ) * T * failure := by + convert mul_le_mul_of_nonneg_right hcard hfailure using 1 <;> ring + + + +theorem chooseUnskippedGroup_spec (Q : ℕ) + (value : Fin M → TargetInterval target.length → ℚ) + (members : List (UnskippedBand source target parent b P thetaExponent tau F child initial)) + (hnonempty : members ≠ []) + (draw : ∀ scale : Fin (groupDyadicScales M b F).length, + Fin (groupSampleCount M Q b (groupDyadicScaleAt M b F scale)) → Fin M) : + chooseUnskippedGroup Q value members hnonempty draw ∈ members ∧ + ∀ member ∈ members, + dyadicUnskippedGroupEstimate Q value (chooseUnskippedGroup Q value members hnonempty draw) draw ≤ + dyadicUnskippedGroupEstimate Q value member draw := + selectGroupMember_spec members hnonempty (fun member => dyadicUnskippedGroupEstimate Q value member draw) + +theorem chooseUnskippedGroup_cost_le (Q : ℕ) + (value : Fin M → TargetInterval target.length → ℚ) + (members : List (UnskippedBand source target parent b P thetaExponent tau F child initial)) + (hnonempty : members ≠ []) + (draw : ∀ scale : Fin (groupDyadicScales M b F).length, + Fin (groupSampleCount M Q b (groupDyadicScaleAt M b F scale)) → Fin M) + (specified : UnskippedBand source target parent b P thetaExponent tau F child initial) + (hspecified : specified ∈ members) (error : ℚ) + (haccurate : ∀ member ∈ members, |dyadicUnskippedGroupEstimate Q value member draw - + rationalEndpointActionValue member.center member.rounded value| ≤ error) : + let selected := chooseUnskippedGroup Q value members hnonempty draw + rationalEndpointActionValue selected.center selected.rounded value ≤ + rationalEndpointActionValue specified.center specified.rounded value + 2 * error := + selectGroupMember_cost_le members hnonempty + (fun member => rationalEndpointActionValue member.center member.rounded value) + (fun member => dyadicUnskippedGroupEstimate Q value member draw) specified hspecified error haccurate + + +end ActualUnskippedGroup + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/BandGuards.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/BandGuards.lean new file mode 100644 index 0000000000000000000000000000000000000000..8e4c51b47979fabe3e8c0fa67c45cba3d2f15cec --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/BandGuards.lean @@ -0,0 +1,135 @@ +import OAI.Combinatorics.EditApproximation.Geometry.ComparisonBandCoverage + +namespace OAI + +/-! +# Literal band endpoint geometry and rounding guards + +The full child endpoint diameter follows from the computed internal cuts +and zero connection, including the two outside endpoints. +-/ + +namespace EditApproximation + +open Finset + +theorem connectionBudget_zero_head {n : ℕ} (states : List (TargetInterval n)) + (start finish : ℕ) (hzero : connectionBudget start states finish = 0) : + (states.head?.map TargetInterval.lo).getD start = start := by + cases states with + | nil => rfl + | cons state rest => + have hdistance : Nat.dist start state.lo = 0 := by + change Nat.dist start state.lo + connectionBudget state.hi rest finish = 0 at hzero + omega + exact (Nat.eq_of_dist_eq_zero hdistance).symm + +/-- Each actual right endpoint is the next actual left endpoint, or the +parent's end when this is the last child. -/ +theorem connectionBudget_zero_right {n : ℕ} (states : List (TargetInterval n)) + (start finish : ℕ) (hzero : connectionBudget start states finish = 0) + (i : ℕ) (hi : i < states.length) : + states[i].hi = connectionPrefixBoundary states finish (i + 1) := by + induction states generalizing start i with + | nil => simp only [List.length_nil] at hi; omega + | cons state rest ih => + have htail : connectionBudget state.hi rest finish = 0 := by + change Nat.dist start state.lo + connectionBudget state.hi rest finish = 0 at hzero + omega + cases i with + | zero => + cases rest with + | nil => + exact Nat.eq_of_dist_eq_zero htail + | cons next rest => + have hdistance : Nat.dist state.hi next.lo = 0 := by + change Nat.dist state.hi next.lo + connectionBudget next.hi rest finish = 0 at htail + omega + exact Nat.eq_of_dist_eq_zero hdistance + | succ i => + have hprev := ih state.hi htail i (by simp only [List.length_cons] at hi; omega) + simpa only [List.getElem_cons_succ, connectionPrefixBoundary, List.drop_succ_cons] using hprev + +theorem zero_connection_left_endpoint {n M : ℕ} (r : TargetInterval n) + (states : Fin M → TargetInterval n) (hzero : endpointActionConnection r states = 0) + (i : Fin M) (hi : i.val = 0) : (states i).lo = r.lo := by + have hhead := connectionBudget_zero_head (List.ofFn states) r.lo r.hi hzero + have hM : 0 < M := by have := i.isLt; omega + simp only [List.head?_eq_getElem?, List.getElem?_ofFn, dite_eq_left hM, + Option.map_some, Option.getD_some] at hhead + have hequal : (⟨0, hM⟩ : Fin M) = i := Fin.ext hi.symm + rw [hequal] at hhead + exact hhead + +theorem zero_connection_right_endpoint {n M : ℕ} (r : TargetInterval n) + (states : Fin M → TargetInterval n) (hzero : endpointActionConnection r states = 0) + (i : Fin M) : + (states i).hi = connectionPrefixBoundary (List.ofFn states) r.hi (i.val + 1) := by + have h := connectionBudget_zero_right (List.ofFn states) r.lo r.hi hzero i.val + (by simp only [List.length_ofFn]; exact i.isLt) + rw [List.getElem_ofFn] at h + exact h + +/-- Full endpoint distance, including first/last endpoints, for every two +members of the literal computed band. -/ +theorem computedBand_child_endpoint_diameter {nx ny M : ℕ} (parent : TargetInterval nx) + (r : TargetInterval ny) (b P : ℕ) (tau theta velocity : ℚ) (htau : 0 < tau) (htheta : 0 ≤ theta) + (child : Fin M → TargetInterval ny → ℚ) + (states states' : Fin M → TargetInterval ny) + (hstates : states ∈ computedBandActions parent r b P tau theta velocity child) + (hstates' : states' ∈ computedBandActions parent r b P tau theta velocity child) + (i : Fin M) : + (targetEndpointDistance (states i) (states' i) : ℝ) ≤ 4 * (theta : ℝ) * b / M := by + have hthetaR : (0 : ℝ) ≤ theta := by exact_mod_cast htheta + have hthetaBound : 0 ≤ 2 * (theta : ℝ) * b / M := by positivity + obtain ⟨hnonempty, hwide, hv, hpredicate⟩ := computedBandActions_mem parent r b P tau theta velocity child states hstates + obtain ⟨hnonempty', hwide', hv', hpredicate'⟩ := computedBandActions_mem parent r b P tau theta velocity child states' hstates' + have hlo : (Nat.dist (states i).lo (states' i).lo : ℝ) ≤ 2 * (theta : ℝ) * b / M := by + by_cases hi : 0 < i.val + · exact computedBand_cut_diameter parent r b P tau theta velocity htau child states states' hstates hstates' i hi + · have hi0 : i.val = 0 := by omega + rw [zero_connection_left_endpoint r states hpredicate.1 i hi0, + zero_connection_left_endpoint r states' hpredicate'.1 i hi0, Nat.dist_self, Nat.cast_zero] + exact hthetaBound + have hhi : (Nat.dist (states i).hi (states' i).hi : ℝ) ≤ 2 * (theta : ℝ) * b / M := by + rw [zero_connection_right_endpoint r states hpredicate.1 i, + zero_connection_right_endpoint r states' hpredicate'.1 i] + by_cases hnext : i.val + 1 < M + · rw [connectionPrefixBoundary_ofFn states r.hi ⟨i.val + 1, hnext⟩, + connectionPrefixBoundary_ofFn states' r.hi ⟨i.val + 1, hnext⟩] + exact computedBand_cut_diameter parent r b P tau theta velocity htau child states states' hstates hstates' + ⟨i.val + 1, hnext⟩ (by change 0 < i.val + 1; omega) + · have hdrop : M ≤ i.val + 1 := by omega + simp only [connectionPrefixBoundary, List.drop_eq_nil_iff.mpr + (show (List.ofFn states).length ≤ i.val + 1 by simpa only [List.length_ofFn] using hdrop), + List.drop_eq_nil_iff.mpr + (show (List.ofFn states').length ≤ i.val + 1 by simpa only [List.length_ofFn] using hdrop), + List.head?_nil, Option.map_none, Option.getD_none, Nat.dist_self, Nat.cast_zero] + exact hthetaBound + unfold targetEndpointDistance + push_cast + convert add_le_add hlo hhi using 1 + ring + +/-- Grid soundness of the literal local box enumeration. -/ +theorem gridStateBox_on_grid {n g radius lo hi : ℕ} (hg : 0 < g) + (state : TargetInterval n) (hstate : state ∈ gridStateBox n g radius lo hi) : + g ∣ state.lo ∧ g ∣ state.hi := by + obtain ⟨s, hs, htail⟩ := List.mem_flatMap.mp hstate + obtain ⟨t, htpoint, hmade⟩ := List.mem_filterMap.mp htail + unfold makeTargetState at hmade + split_ifs at hmade with hvalid + · cases Option.some.inj hmade + exact ⟨(gridPointsBetween_sound hg hs).2.2, (gridPointsBetween_sound hg htpoint).2.2⟩ + +theorem wideActionList_on_grid {nx ny M b P : ℕ} (parent : TargetInterval nx) + (r : TargetInterval ny) (action : Fin M → TargetInterval ny) + (haction : action ∈ wideActionList M parent r b P) : + ∀ i, seedGridSpacing b P ∣ (action i).lo ∧ seedGridSpacing b P ∣ (action i).hi := by + intro i + exact gridStateBox_on_grid (by unfold seedGridSpacing; omega) (action i) + (finiteAssignments_sound M _ action haction i) + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/BandNumericalBits.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/BandNumericalBits.lean new file mode 100644 index 0000000000000000000000000000000000000000..6205990031ed43b4417352134c3c39816218cb27 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/BandNumericalBits.lean @@ -0,0 +1,91 @@ +import OAI.Combinatorics.EditApproximation.Numerics.GradientStorageBits +import OAI.Combinatorics.EditApproximation.Geometry.BandOptimizerWork +import OAI.Combinatorics.EditApproximation.Numerics.OptimizerWorkspace + +namespace OAI + +/-! The probability vectors actually stored for band actions have polynomial +encodings in the input child masses. No accuracy event is needed. -/ + +namespace EditApproximation + +open Finset + +def bandVertexEncodingBudget (M V B : ℕ) : ℕ := + B + (Nat.size (M * V) + 2 * (M * B + 1) + 1) + 3 + +theorem actionVector_encoding_le {M : ℕ} {σ : Type*} [DecidableEq σ] + (mass : Fin M → ℚ) (action : Fin M → σ) (coordinate : Fin M × σ) + (V B : ℕ) (habs : ∀ i, |mass i| ≤ V) + (hbits : ∀ i, rationalEncodingBits (mass i) ≤ B) : + rationalEncodingBits (actionVector mass action coordinate) ≤ bandVertexEncodingBudget M V B := by + have hsum := rational_finite_sum_encoding_le (univ : Finset (Fin M)) mass V B + (fun i _ => habs i) (fun i _ => (by + unfold rationalEncodingBits at hbits + have h := hbits i + omega)) + simp only [Finset.card_univ, Fintype.card_fin] at hsum + unfold actionVector + split_ifs + · have hdiv := rationalEncodingBits_div (mass coordinate.1) (∑ i, mass i) + have hmass := hbits coordinate.1 + unfold bandVertexEncodingBudget + omega + · norm_num [rationalEncodingBits, bandVertexEncodingBudget] + +theorem actionVector_zero_one {M : ℕ} {σ : Type*} [DecidableEq σ] + (mass : Fin M → ℚ) (action : Fin M → σ) (coordinate : Fin M × σ) + (hpos : ∀ i, 0 < mass i) : + 0 ≤ actionVector mass action coordinate ∧ actionVector mass action coordinate ≤ 1 := by + have hsum : 0 < ∑ i, mass i := + (hpos coordinate.1).trans_le (Finset.single_le_sum (fun i _ => (hpos i).le) (mem_univ _)) + unfold actionVector + split_ifs + · exact ⟨(div_pos (hpos _) hsum).le, + (div_le_one₀ hsum).2 (single_le_sum (fun i _ => (hpos i).le) (mem_univ _))⟩ + · norm_num + +def storedBandVertices {M : ℕ} {σ : Type*} [DecidableEq σ] + (band : List (Fin M → σ)) (mass : Fin M → ℚ) : + List (Vector ℚ (listedBandCoordinates band).length) := + band.map fun action => restrictOptimizerVector (listedBandCoordinateVector band) (actionVector mass action) + +theorem storedBandVertices_nonempty {M : ℕ} {σ : Type*} [DecidableEq σ] + (band : List (Fin M → σ)) (mass : Fin M → ℚ) (hband : band ≠ []) : + storedBandVertices band mass ≠ [] := by + intro hempty + exact hband (List.map_eq_nil_iff.mp hempty) + +theorem storedBandVertices_input_bounds {M : ℕ} {σ : Type*} [DecidableEq σ] + (band : List (Fin M → σ)) (mass : Fin M → ℚ) (V B : ℕ) + (hpos : ∀ i, 0 < mass i) (habs : ∀ i, |mass i| ≤ V) + (hbits : ∀ i, rationalEncodingBits (mass i) ≤ B) + (vertex : Vector ℚ (listedBandCoordinates band).length) + (hvertex : vertex ∈ storedBandVertices band mass) + (i : Fin (listedBandCoordinates band).length) : + (0 ≤ vertex.get i ∧ vertex.get i ≤ 1) ∧ + Nat.size (vertex.get i).den ≤ bandVertexEncodingBudget M V B := by + obtain ⟨action, _, rfl⟩ := List.mem_map.mp hvertex + rw [restrictOptimizerVector_get] + constructor + · exact actionVector_zero_one mass action _ hpos + · have h := actionVector_encoding_le mass action + ((listedBandCoordinateVector band).get i) V B habs hbits + unfold rationalEncodingBits at h + omega + +theorem storedBandOptimizer_history_bits {M : ℕ} {σ : Type*} [DecidableEq σ] + (band : List (Fin M → σ)) (hband : band ≠ []) (mass : Fin M → ℚ) + (linear : Fin M × σ → ℚ) (G K V B : ℕ) + (hpos : ∀ i, 0 < mass i) (habs : ∀ i, |mass i| ≤ V) + (hbits : ∀ i, rationalEncodingBits (mass i) ≤ B) : + rationalVectorListStorageBits (optimizerStoredHistory (storedBandVertices band mass) + (restrictOptimizerVector (listedBandCoordinateVector band) linear) G K) ≤ + (K + 1) * ((listedBandCoordinates band).length * + (2 * ((K + 1) * (2 * Nat.size (K + 1) + 2 + bandVertexEncodingBudget M V B) + 1) + 1)) := by + exact optimizerStoredHistory_storage_le _ _ G K _ (storedBandVertices_nonempty band mass hband) + (fun vertex hvertex i => storedBandVertices_input_bounds band mass V B hpos habs hbits vertex hvertex i) + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/BandOptimizerWork.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/BandOptimizerWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..2891e3ff85a6b46c6029a978a6c743a630fb719e --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/BandOptimizerWork.lean @@ -0,0 +1,221 @@ +import OAI.Combinatorics.EditApproximation.Numerics.VectorOptimizerWork +import OAI.Combinatorics.EditApproximation.Geometry.BandDimension +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Reindexing the exact finite optimizer onto an explicit, duplicate-free +coordinate array. The array order is retained throughout the evaluation. -/ + +namespace EditApproximation + +open Finset + +def restrictOptimizerVector {ι : Type*} {d : ℕ} (coordinates : Vector ι d) + (values : ι → ℚ) : Vector ℚ d := + Vector.ofFn fun i => values (coordinates.get i) + +theorem restrictOptimizerVector_get {ι : Type*} {d : ℕ} (coordinates : Vector ι d) + (values : ι → ℚ) (i : Fin d) : + (restrictOptimizerVector coordinates values).get i = values (coordinates.get i) := + vector_get_ofFn _ _ + +theorem coordinateVector_sum {ι : Type*} [DecidableEq ι] {d : ℕ} + (coordinates : Vector ι d) (hnodup : coordinates.toList.Nodup) (f : ι → ℚ) : + (∑ i : Fin d, f (coordinates.get i)) = ∑ c ∈ coordinates.toList.toFinset, f c := by + rw [List.sum_toFinset f hnodup] + have hcoordinates : coordinates.toList = List.ofFn coordinates.get := by + rw [← Vector.toList_ofFn] + congr 1 + exact (Vector.ofFn_getElem).symm + rw [hcoordinates, List.map_ofFn, List.sum_ofFn] + rfl + +theorem rationalLinearizationMaximizer_restrict {ι : Type*} [DecidableEq ι] {d : ℕ} + (coordinates : Vector ι d) (hnodup : coordinates.toList.Nodup) + (vertices : List (ι → ℚ)) (gradient : ι → ℚ) : + rationalLinearizationMaximizer univ + (vertices.map fun v => fun i => v (coordinates.get i)) + (fun i => gradient (coordinates.get i)) = + fun i => rationalLinearizationMaximizer coordinates.toList.toFinset vertices gradient + (coordinates.get i) := by + have hsum (v : ι → ℚ) : + (∑ i : Fin d, gradient (coordinates.get i) * v (coordinates.get i)) = + ∑ c ∈ coordinates.toList.toFinset, gradient c * v c := + coordinateVector_sum coordinates hnodup (fun c => gradient c * v c) + unfold rationalLinearizationMaximizer + rw [argmax_map_commutes] + simp only [hsum] + cases h : vertices.argmax (fun v => ∑ c ∈ coordinates.toList.toFinset, gradient c * v c) with + | none => rfl + | some v => rfl + +theorem finiteRationalOptimizer_restrict {ι : Type*} [DecidableEq ι] {d : ℕ} + (coordinates : Vector ι d) (hnodup : coordinates.toList.Nodup) + (vertices : List (ι → ℚ)) (linear : ι → ℚ) (G j : ℕ) : + finiteRationalOptimizer univ (vertices.map fun v => fun i => v (coordinates.get i)) + (fun i => linear (coordinates.get i)) G j = + fun i => finiteRationalOptimizer coordinates.toList.toFinset vertices linear G j + (coordinates.get i) := by + induction j with + | zero => cases vertices <;> rfl + | succ j ih => + have hgradient : + rationalSmoothedGradient G (fun i => linear (coordinates.get i)) + (finiteRationalOptimizer univ (vertices.map fun v => fun i => v (coordinates.get i)) + (fun i => linear (coordinates.get i)) G j) = + fun i => rationalSmoothedGradient G linear + (finiteRationalOptimizer coordinates.toList.toFinset vertices linear G j) + (coordinates.get i) := by + rw [ih] + rfl + funext i + rw [finiteRationalOptimizer, finiteRationalOptimizer, hgradient, + rationalLinearizationMaximizer_restrict coordinates hnodup] + simp only [ih] + +theorem materializedOptimizerWithWork_restrict_value {ι : Type*} [DecidableEq ι] {d : ℕ} + (coordinates : Vector ι d) (hnodup : coordinates.toList.Nodup) + (vertices : List (ι → ℚ)) (linear : ι → ℚ) (G j : ℕ) (i : Fin d) : + (materializedOptimizerWithWork (vertices.map (restrictOptimizerVector coordinates)) + (restrictOptimizerVector coordinates linear) G j).1.get i = + finiteRationalOptimizer coordinates.toList.toFinset vertices linear G j (coordinates.get i) := by + rw [materializedOptimizerWithWork_value] + have hvertices : (vertices.map (restrictOptimizerVector coordinates)).map Vector.get = + vertices.map (fun v => fun k => v (coordinates.get k)) := by + simp only [List.map_map] + congr 1 + funext v k + exact restrictOptimizerVector_get coordinates v k + have hlinear : (restrictOptimizerVector coordinates linear).get = + fun k => linear (coordinates.get k) := by + funext k + exact restrictOptimizerVector_get coordinates linear k + rw [hvertices, hlinear, finiteRationalOptimizer_restrict coordinates hnodup] + +/-- Concrete ordered coordinates; no enumeration of the ambient state +type and no choice of an equivalence is used by the evaluator. -/ + + +theorem listedBandCoordinates_nodup {M : ℕ} {σ : Type*} [DecidableEq σ] + (band : List (Fin M → σ)) : (listedBandCoordinates band).Nodup := + List.nodup_dedup _ + +theorem listedBandCoordinates_toFinset {M : ℕ} {σ : Type*} [DecidableEq σ] + (band : List (Fin M → σ)) : + (listedBandCoordinates band).toFinset = bandCoordinates band.toFinset := by + ext coordinate + constructor + · intro hc + obtain ⟨action, ha, hc⟩ := List.mem_flatMap.mp + (List.mem_dedup.mp (List.mem_toFinset.mp hc)) + obtain ⟨child, hchild⟩ := List.mem_ofFn.mp hc + rw [← hchild] + exact action_coordinate_mem band.toFinset (List.mem_toFinset.mpr ha) child + · intro hc + obtain ⟨action, ha, hc⟩ := mem_biUnion.mp hc + obtain ⟨child, _, heq⟩ := mem_image.mp hc + apply List.mem_toFinset.mpr + apply List.mem_dedup.mpr + apply List.mem_flatMap.mpr + exact ⟨action, List.mem_toFinset.mp ha, List.mem_ofFn.mpr ⟨child, heq⟩⟩ + +def listedBandCoordinateVector {M : ℕ} {σ : Type*} [DecidableEq σ] + (band : List (Fin M → σ)) : Vector (Fin M × σ) (listedBandCoordinates band).length := + Vector.ofFn (listedBandCoordinates band).get + +theorem listedBandCoordinateVector_toList {M : ℕ} {σ : Type*} [DecidableEq σ] + (band : List (Fin M → σ)) : + (listedBandCoordinateVector band).toList = listedBandCoordinates band := by + simp only [listedBandCoordinateVector, Vector.toList_ofFn, List.ofFn_get] + +theorem listedBandCoordinates_length {M : ℕ} {σ : Type*} [DecidableEq σ] + (band : List (Fin M → σ)) : + (listedBandCoordinates band).length = (bandCoordinates band.toFinset).card := by + rw [← listedBandCoordinates_toFinset band, + List.toFinset_card_of_nodup (listedBandCoordinates_nodup band)] + +def materializedBandActionWithWork {M : ℕ} {σ : Type*} [DecidableEq σ] + (band : List (Fin M → σ)) (mass : Fin M → ℚ) + (linear : Fin M × σ → ℚ) (G j : ℕ) : Option (Fin M → σ) × ℕ := + let coordinates := listedBandCoordinateVector band + let vertices := band.map fun action => + (action, restrictOptimizerVector coordinates (actionVector mass action)) + materializedSelectionWithWork vertices (restrictOptimizerVector coordinates linear) G j + +/-- Materializing coordinates and vertices preserves the actual action +label selected by the complete finite optimizer, including all ties. -/ +theorem materializedBandActionWithWork_value {M : ℕ} {σ : Type*} [DecidableEq σ] + (band : List (Fin M → σ)) (hband : band ≠ []) (mass : Fin M → ℚ) + (linear : Fin M × σ → ℚ) (G j : ℕ) : + (materializedBandActionWithWork band mass linear G j).1.getD (band.head hband) = + finiteOptimizerAction band hband mass linear G j := by + let coordinates := listedBandCoordinateVector band + have hnodup : coordinates.toList.Nodup := by + rw [show coordinates.toList = listedBandCoordinates band from + listedBandCoordinateVector_toList band] + exact listedBandCoordinates_nodup band + have hcoordinates : coordinates.toList.toFinset = bandCoordinates band.toFinset := by + rw [show coordinates.toList = listedBandCoordinates band from + listedBandCoordinateVector_toList band, listedBandCoordinates_toFinset] + have hvertexMaps : + (((band.map fun action => (action, restrictOptimizerVector coordinates (actionVector mass action))).map + Prod.snd).map Vector.get) = + (band.map (actionVector mass)).map (fun v => fun i => v (coordinates.get i)) := by + simp only [List.map_map] + congr 1 + funext action i + exact restrictOptimizerVector_get coordinates _ i + have hlinear : (restrictOptimizerVector coordinates linear).get = + fun i => linear (coordinates.get i) := by + funext i + exact restrictOptimizerVector_get coordinates linear i + have hscore (action : Fin M → σ) : + (∑ i : Fin (listedBandCoordinates band).length, + rationalSmoothedGradient G (restrictOptimizerVector coordinates linear).get + (finiteRationalOptimizer univ + (((band.map fun action => (action, restrictOptimizerVector coordinates (actionVector mass action))).map + Prod.snd).map Vector.get) (restrictOptimizerVector coordinates linear).get G j) i * + (restrictOptimizerVector coordinates (actionVector mass action)).get i) = + ∑ c ∈ bandCoordinates band.toFinset, + rationalSmoothedGradient G linear + (finiteRationalOptimizer (bandCoordinates band.toFinset) (band.map (actionVector mass)) + linear G j) c * actionVector mass action c := by + rw [hvertexMaps, hlinear, finiteRationalOptimizer_restrict coordinates hnodup] + simp only [restrictOptimizerVector_get] + change (∑ i, rationalSmoothedGradient G linear + (finiteRationalOptimizer coordinates.toList.toFinset (band.map (actionVector mass)) linear G j) + (coordinates.get i) * actionVector mass action (coordinates.get i)) = _ + have hs := coordinateVector_sum coordinates hnodup (fun c => + rationalSmoothedGradient G linear + (finiteRationalOptimizer coordinates.toList.toFinset (band.map (actionVector mass)) linear G j) c * + actionVector mass action c) + simpa only [hcoordinates] using hs + unfold materializedBandActionWithWork + rw [materializedSelectionWithWork_value, argmax_map_commutes] + simp only [Function.comp_def, Option.map_map] + rw [show (fun x : Fin M → σ => x) = id from rfl, Option.map_id] + simp only [finiteOptimizerAction] + apply congrArg (fun result : Option (Fin M → σ) => result.getD (band.head hband)) + apply congrArg (fun score : (Fin M → σ) → ℚ => band.argmax score) + funext action + exact hscore action + +/-- Work of the optimizer after preparing its coordinate/vertex arrays. +The finite preparation loops are charged separately. -/ +theorem materializedBandActionWithWork_optimizer_cost {M : ℕ} {σ : Type*} [DecidableEq σ] + (band : List (Fin M → σ)) (mass : Fin M → ℚ) + (linear : Fin M × σ → ℚ) (G j : ℕ) (hj : j ≤ G ^ 80) : + (materializedBandActionWithWork band mass linear G j).2 ≤ + (band.length + 1) * ((bandCoordinates band.toFinset).card + 1) * (G + 2) ^ 210 := by + unfold materializedBandActionWithWork + simpa only [List.length_map, listedBandCoordinates_length] using + materializedSelectionWithWork_polynomial + (band.map fun action => (action, restrictOptimizerVector + (listedBandCoordinateVector band) (actionVector mass action))) + (restrictOptimizerVector (listedBandCoordinateVector band) linear) G j hj + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/BandParameters.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/BandParameters.lean new file mode 100644 index 0000000000000000000000000000000000000000..1d815e0fc51f5efb7f15c3109d6ccb10d87533bb --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/BandParameters.lean @@ -0,0 +1,126 @@ +import OAI.Combinatorics.EditApproximation.Geometry.Parameters + +namespace OAI + +/-! Computed numerical slack for comparison-band coverage at non-bad nodes. -/ + +namespace EditApproximation + +theorem computed_branching_fourth_power_le_quarterRoot (N : ℕ) : + ((integerParameters N).M : ℝ) ^ 4 ≤ heightQuarterRoot N := by + have hexponent : 16 * (heightExponent N / 20) ≤ heightExponent N := by + have h := Nat.div_mul_le_self (heightExponent N) 20 + omega + have hpower : ((integerParameters N).M : ℝ) ^ 16 ≤ inputHeight N := by + simp only [integerParameters, Nat.cast_pow, Nat.cast_ofNat, inputHeight] + rw [← pow_mul] + exact pow_le_pow_right₀ (by norm_num : (1 : ℝ) ≤ 2) (by omega) + apply (pow_le_pow_iff_left₀ (by positivity : (0 : ℝ) ≤ ((integerParameters N).M : ℝ) ^ 4) + (Real.sqrt_nonneg _) (by decide : 4 ≠ 0)).mp + change (((integerParameters N).M : ℝ) ^ 4) ^ 4 ≤ heightQuarterRoot N ^ 4 + rw [← pow_mul, heightQuarterRoot_fourth_power] + exact hpower + +theorem band_root_slack {ell root M : ℝ} (hell : 2 ≤ ell) (hroot : 0 ≤ root) + (hlarge : ell ^ 5000 ≤ root) (_hM : 0 ≤ M) (hMfour : M ^ 4 ≤ root) : + 128 * ell ^ 90 * M ^ 2 ≤ root := by + have hellone : 1 ≤ ell := by linarith + have hcoef : (16384 : ℝ) ≤ ell ^ 14 := by + have h := pow_le_pow_left₀ (by norm_num : (0 : ℝ) ≤ 2) hell 14 + norm_num at h + exact h + have hbig : 16384 * ell ^ 180 ≤ root := by + calc + 16384 * ell ^ 180 ≤ ell ^ 14 * ell ^ 180 := + mul_le_mul_of_nonneg_right hcoef (by positivity) + _ = ell ^ 194 := by rw [← pow_add] + _ ≤ ell ^ 5000 := pow_le_pow_right₀ hellone (by decide) + _ ≤ root := hlarge + have hproduct := mul_le_mul hMfour hbig (by positivity : (0 : ℝ) ≤ 16384 * ell ^ 180) hroot + apply (sq_le_sq₀ (by positivity : 0 ≤ 128 * ell ^ 90 * M ^ 2) hroot).mp + calc + (128 * ell ^ 90 * M ^ 2) ^ 2 = M ^ 4 * (16384 * ell ^ 180) := by ring + _ ≤ root * root := hproduct + _ = root ^ 2 := by ring + +theorem nonbad_band_numerical_bound {ell root M b K G W : ℝ} + (hell : 2 ≤ ell) (hM : 1 ≤ M) (hb : 0 ≤ b) + (hroot : 128 * ell ^ 90 * M ^ 2 ≤ root) + (_hK : 0 ≤ K) (_hG : 0 ≤ G) (hW : 0 ≤ W) + (hKsmall : K ≤ b / root) (hGsmall : G ≤ b / root) (hWsmall : W ≤ 8 * ell * b) : + Real.sqrt (K * W) + 2 * G ≤ (1 / ell ^ 4) * (1 / ell ^ 40) * b / M := by + have hellpos : 0 < ell := by linarith + have hellone : 1 ≤ ell := by linarith + have hMpos : 0 < M := by linarith + have hMtwo : M ≤ M ^ 2 := by nlinarith only [hM] + have hrootpos : 0 < root := (by positivity : 0 < 128 * ell ^ 90 * M ^ 2).trans_le hroot + have hscale : 32 * ell ^ 89 * M ^ 2 ≤ root := by + calc + 32 * ell ^ 89 * M ^ 2 ≤ 128 * ell ^ 90 * M ^ 2 := by + have hp : ell ^ 89 ≤ ell ^ 90 := pow_le_pow_right₀ hellone (by decide : 89 ≤ 90) + have hc : 32 * ell ^ 89 ≤ 128 * ell ^ 90 := + mul_le_mul (by norm_num : (32 : ℝ) ≤ 128) hp (by positivity) (by norm_num) + exact mul_le_mul_of_nonneg_right hc (sq_nonneg M) + _ ≤ root := hroot + have hscale' : 4 * ell ^ 44 * M ≤ root := by + calc + 4 * ell ^ 44 * M ≤ 128 * ell ^ 90 * M ^ 2 := by + have hp : ell ^ 44 ≤ ell ^ 90 := pow_le_pow_right₀ hellone (by decide : 44 ≤ 90) + have hc : 4 * ell ^ 44 ≤ 128 * ell ^ 90 := + mul_le_mul (by norm_num : (4 : ℝ) ≤ 128) hp (by positivity) (by norm_num) + exact mul_le_mul hc hMtwo hMpos.le (by positivity) + _ ≤ root := hroot + have hKW : K * W ≤ (8 * ell * b ^ 2) / root := by + calc + K * W ≤ (b / root) * (8 * ell * b) := + mul_le_mul hKsmall hWsmall hW (div_nonneg hb hrootpos.le) + _ = (8 * ell * b ^ 2) / root := by ring + have hsquare : K * W ≤ (b / (2 * ell ^ 44 * M)) ^ 2 := by + calc + K * W ≤ (8 * ell * b ^ 2) / root := hKW + _ ≤ b ^ 2 / (4 * ell ^ 88 * M ^ 2) := by + apply (div_le_div_iff₀ hrootpos (by positivity : 0 < 4 * ell ^ 88 * M ^ 2)).2 + have h := mul_le_mul_of_nonneg_right hscale (sq_nonneg b) + nlinarith only [h, show (8 * ell * b ^ 2) * (4 * ell ^ 88 * M ^ 2) = + (32 * ell ^ 89 * M ^ 2) * b ^ 2 by ring] + _ = (b / (2 * ell ^ 44 * M)) ^ 2 := by field_simp; ring + have hsqrt : Real.sqrt (K * W) ≤ b / (2 * ell ^ 44 * M) := + (Real.sqrt_le_left (by positivity)).2 hsquare + have htwice : 2 * G ≤ b / (2 * ell ^ 44 * M) := by + calc + 2 * G ≤ 2 * (b / root) := mul_le_mul_of_nonneg_left hGsmall (by norm_num) + _ = (2 * b) / root := by ring + _ ≤ b / (2 * ell ^ 44 * M) := by + apply (div_le_div_iff₀ hrootpos (by positivity : 0 < 2 * ell ^ 44 * M)).2 + have h := mul_le_mul_of_nonneg_right hscale' hb + nlinarith only [h] + have hid : b / (2 * ell ^ 44 * M) + b / (2 * ell ^ 44 * M) = + (1 / ell ^ 4) * (1 / ell ^ 40) * b / M := by + field_simp + ring + exact (add_le_add hsqrt htwice).trans_eq hid + +theorem computed_nonbad_band_numerical_bound (N : ℕ) (hN : 0 < N) + (hell : 2 ^ 1000 ≤ inputSmallLog N) {b K G W : ℝ} + (hb : 0 ≤ b) (hK : 0 ≤ K) (hG : 0 ≤ G) (hW : 0 ≤ W) + (hKsmall : K ≤ b / heightQuarterRoot N) (hGsmall : G ≤ b / heightQuarterRoot N) + (hWsmall : W ≤ 8 * inputSmallLog N * b) : + Real.sqrt (K * W) + 2 * G ≤ + ((rationalParameters (inputSmallLog N)).tau : ℝ) * + ((rationalParameters (inputSmallLog N)).theta : ℝ) * b / (integerParameters N).M := by + have helltwo : (2 : ℝ) ≤ inputSmallLog N := by + have htwo : 2 ≤ (2 : ℕ) ^ 1000 := by + simpa only [pow_one] using pow_le_pow_right₀ (by decide : 1 ≤ (2 : ℕ)) (by decide : 1 ≤ 1000) + exact_mod_cast htwo.trans hell + have hroot := band_root_slack helltwo (Real.sqrt_nonneg _) + (fourth_root_polynomial_slack (by linarith) (inputHeight_polynomial_slack N hN hell) + (Real.sqrt_nonneg _) (heightQuarterRoot_fourth_power N)) + (Nat.cast_nonneg (integerParameters N).M) (computed_branching_fourth_power_le_quarterRoot N) + have hM : (1 : ℝ) ≤ (integerParameters N).M := by + exact_mod_cast (Nat.one_le_two_pow (n := heightExponent N / 20)) + have h := nonbad_band_numerical_bound helltwo hM hb hroot hK hG hW hKsmall hGsmall hWsmall + simpa only [rationalParameters, Rat.cast_div, Rat.cast_one, Rat.cast_pow, Rat.cast_natCast] using h + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/BandRegret.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/BandRegret.lean new file mode 100644 index 0000000000000000000000000000000000000000..c6e55b63d76f1806d7e94264a0f8c9d598bcedec --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/BandRegret.lean @@ -0,0 +1,175 @@ +import OAI.Combinatorics.EditApproximation.Geometry.ActionVectors +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! +# Regret of the computed rational band mixtures + +The optimistic objective is computed in rational arithmetic. The finite +optimizer supplies every predicted vector used here; no maximization +oracle or unproved entropy-regret hypothesis appears in the conclusion. +-/ + +namespace EditApproximation + +open Finset + + + +theorem rationalOptimisticHistory_cast {ι : Type*} (κ : ℚ) + (gain decrement : ℕ → ι → ℚ) (t : ℕ) (i : ι) : + (rationalOptimisticHistory κ gain decrement t i : ℝ) = + optimisticHistory (κ : ℝ) (fun j i => (gain j i : ℝ)) + (fun j i => (decrement j i : ℝ)) t i := by + simp [rationalOptimisticHistory, optimisticHistory] + + + +def computedOnlineVector {ι : Type*} (coordinates : Finset ι) + (vertices : List (ι → ℚ)) (η κ : ℚ) + (gain decrement : ℕ → ι → ℚ) (H t : ℕ) : ι → ℚ := + finiteRationalOptimizer coordinates vertices (rationalOnlineLinear η κ gain decrement t) + (H + coordinates.card + 2) ((H + coordinates.card + 2) ^ 80) + +theorem rationalOnlineLinear_objective {ι : Type*} (coordinates : Finset ι) + (η κ : ℚ) (gain decrement : ℕ → ι → ℚ) (t : ℕ) (p : ι → ℝ) : + entropyValue coordinates 1 + (fun i => (rationalOnlineLinear η κ gain decrement t i : ℝ)) p = + entropyValue coordinates (η : ℝ) + (fun i => optimisticHistory (κ : ℝ) (fun j i => (gain j i : ℝ)) + (fun j i => (decrement j i : ℝ)) t i + (gain t i : ℝ)) p := by + unfold entropyValue + apply sum_congr rfl + intro i _ + simp only [rationalOnlineLinear, Rat.cast_mul, Rat.cast_add, + rationalOptimisticHistory_cast, one_mul] + +/-- Fixed-block regret for the actual rational optimizer, with its +prescribed `G^80` iterations and `H^-3` numerical loss. -/ +theorem computed_finite_block_entropy_regret {ι β : Type*} [Fintype β] [DecidableEq β] + (coordinates : Finset ι) (block : ι → β) (vertices : List (ι → ℚ)) + (S H : ℕ) (η κ : ℚ) (rangeBound : ℝ) + (gain decrement : ℕ → ι → ℚ) (comparator : ι → ℝ) + (hvertices : vertices ≠ []) (hH : 4 ≤ H) + (hprobability : ∀ p ∈ vertices, + (∀ i ∈ coordinates, (0 : ℝ) ≤ p i) ∧ (∑ i ∈ coordinates, (p i : ℝ)) = 1) + (hcovered : ∀ i ∈ coordinates, ∃ p ∈ vertices, (0 : ℝ) < p i) + (hcQ : comparator ∈ convexHull ℝ (rationalVertexSet vertices)) + (hblocks : ∀ b, (coordinates.filter (fun i => block i = b)).Nonempty) + (hblockMass : ∀ p ∈ convexHull ℝ (rationalVertexSet vertices), + ∀ q ∈ convexHull ℝ (rationalVertexSet vertices), ∀ b, + (∑ i ∈ coordinates with block i = b, p i) = + ∑ i ∈ coordinates with block i = b, q i) + (hη : 0 < η) (hκ : 0 ≤ κ) (hκhalf : κ ≤ 1 / 2) + (hηrange : (η : ℝ) * rangeBound ≤ (κ : ℝ)) + (hdecrementNonneg : ∀ t < S, ∀ i ∈ coordinates, (0 : ℝ) ≤ decrement t i) + (hrange : ∀ t < S, ∀ i ∈ coordinates, ∀ j ∈ coordinates, + block i = block j → |(decrement t i : ℝ) - decrement t j| ≤ rangeBound) + (hdecrement : ∀ i ∈ coordinates, ∑ t ∈ range S, (decrement t i : ℝ) ≤ 1) + (hgain : ∀ t < S, ∀ i ∈ coordinates, + -1 ≤ (gain t i : ℝ) + (1 - (κ : ℝ)) * decrement t i ∧ + (gain t i : ℝ) + (1 - (κ : ℝ)) * decrement t i ≤ 0) : + (∑ t ∈ range S, ∑ i ∈ coordinates, + ((gain t i : ℝ) + decrement t i) * comparator i) - + Real.log coordinates.card / (η : ℝ) - 2 * (κ : ℝ) - (S : ℝ) / (H : ℝ) ^ 3 ≤ + ∑ t ∈ range S, ∑ i ∈ coordinates, + ((gain t i : ℝ) + (1 - (κ : ℝ)) * decrement t i) * + (computedOnlineVector coordinates vertices η κ gain decrement H t i : ℝ) := by + classical + have hfinite : ({p : ι → ℚ | p ∈ vertices} : Set (ι → ℚ)).Finite := by simp + have hcompact := (hfinite.image (fun p : ι → ℚ => fun i => (p i : ℝ))).isCompact_convexHull ℝ + obtain ⟨witness, hwQ, hw⟩ := rationalVertexHull_positive_witness coordinates vertices + hvertices (fun p hp => (hprobability p hp).1) hcovered + have hoptimizer (t : ℕ) := finite_entropy_optimizer coordinates vertices + (rationalOnlineLinear η κ gain decrement t) H hvertices hH hprobability hcovered + choose predicted hpred using hoptimizer + have hpredMax t : IsMaxOn + (entropyValue coordinates (η : ℝ) + (fun i => optimisticHistory (κ : ℝ) (fun j i => (gain j i : ℝ)) + (fun j i => (decrement j i : ℝ)) t i + (gain t i : ℝ))) + (convexHull ℝ (rationalVertexSet vertices)) (predicted t) := by + intro q hq + have hbound := (hpred t).2.1 hq + change entropyValue coordinates 1 + (fun i => (rationalOnlineLinear η κ gain decrement t i : ℝ)) q ≤ + entropyValue coordinates 1 + (fun i => (rationalOnlineLinear η κ gain decrement t i : ℝ)) (predicted t) at hbound + rw [rationalOnlineLinear_objective, rationalOnlineLinear_objective] at hbound + exact hbound + have hκhalfR : (κ : ℝ) ≤ 1 / 2 := by + calc + (κ : ℝ) ≤ ((1 / 2 : ℚ) : ℝ) := Rat.cast_le.mpr hκhalf + _ = 1 / 2 := by norm_num + have hregret := finite_block_entropy_regret coordinates block + (convexHull ℝ (rationalVertexSet vertices)) S (η : ℝ) (κ : ℝ) rangeBound + (fun j i => (gain j i : ℝ)) (fun j i => (decrement j i : ℝ)) predicted + witness comparator hcompact (convex_convexHull ℝ _) hwQ hcQ hw + (rationalVertexHull_probability coordinates vertices hprobability) hblocks hblockMass + (by exact_mod_cast hη) (by exact_mod_cast hκ) hκhalfR hηrange + (fun t _ => (hpred t).1) (fun t _ => hpredMax t) + hdecrementNonneg hrange hdecrement + have hloss := sum_le_sum fun t (ht : t ∈ range S) => + bounded_gain_l1_approximation coordinates + (fun i => (gain t i : ℝ) + (1 - (κ : ℝ)) * decrement t i) + (predicted t) (fun i => (computedOnlineVector coordinates vertices η κ gain decrement H t i : ℝ)) + (1 / (H : ℝ) ^ 3) (hgain t (mem_range.mp ht)) (hpred t).2.2 + simp only [sum_sub_distrib, sum_const, card_range, nsmul_eq_mul] at hloss + rw [mul_one_div] at hloss + linarith + +/-- Specialization to the actual child/state coordinates and rational +fixed child masses of a nonempty band. -/ +theorem band_computed_entropy_regret {β σ : Type*} [Fintype β] [Nonempty β] + [DecidableEq β] [DecidableEq σ] (band : Finset (β → σ)) (hband : band.Nonempty) + (mass : β → ℚ) (hpos : ∀ child, 0 < mass child) + (S H : ℕ) (η κ : ℚ) (rangeBound : ℝ) + (gain decrement : ℕ → β × σ → ℚ) {comparison : β → σ} (hc : comparison ∈ band) + (hH : 4 ≤ H) (hη : 0 < η) (hκ : 0 ≤ κ) (hκhalf : κ ≤ 1 / 2) + (hηrange : (η : ℝ) * rangeBound ≤ (κ : ℝ)) + (hdecrementNonneg : ∀ t < S, ∀ i ∈ bandCoordinates band, (0 : ℝ) ≤ decrement t i) + (hrange : ∀ t < S, ∀ i ∈ bandCoordinates band, ∀ j ∈ bandCoordinates band, + i.1 = j.1 → |(decrement t i : ℝ) - decrement t j| ≤ rangeBound) + (hdecrement : ∀ i ∈ bandCoordinates band, ∑ t ∈ range S, (decrement t i : ℝ) ≤ 1) + (hgain : ∀ t < S, ∀ i ∈ bandCoordinates band, + -1 ≤ (gain t i : ℝ) + (1 - (κ : ℝ)) * decrement t i ∧ + (gain t i : ℝ) + (1 - (κ : ℝ)) * decrement t i ≤ 0) : + (∑ t ∈ range S, ∑ i ∈ bandCoordinates band, + ((gain t i : ℝ) + decrement t i) * (actionVector mass comparison i : ℝ)) - + Real.log (bandCoordinates band).card / (η : ℝ) - 2 * (κ : ℝ) - (S : ℝ) / (H : ℝ) ^ 3 ≤ + ∑ t ∈ range S, ∑ i ∈ bandCoordinates band, + ((gain t i : ℝ) + (1 - (κ : ℝ)) * decrement t i) * + (computedOnlineVector (bandCoordinates band) (band.toList.map (actionVector mass)) + η κ gain decrement H t i : ℝ) := by + have hvertices : band.toList.map (actionVector mass) ≠ [] := by + intro hnil + have hmem : actionVector mass comparison ∈ band.toList.map (actionVector mass) := + List.mem_map.mpr ⟨comparison, mem_toList.mpr hc, rfl⟩ + simp only [hnil, List.not_mem_nil] at hmem + apply computed_finite_block_entropy_regret (bandCoordinates band) Prod.fst + (band.toList.map (actionVector mass)) S H η κ rangeBound gain decrement + (fun i => (actionVector mass comparison i : ℝ)) hvertices hH + · intro p hp + obtain ⟨action, ha, rfl⟩ := List.mem_map.mp hp + exact actionVector_probability band mass hpos (mem_toList.mp ha) + · intro i hi + obtain ⟨action, ha, hpositive⟩ := actionVector_coordinate_coverage band mass hpos i hi + exact ⟨actionVector mass action, List.mem_map.mpr ⟨action, mem_toList.mpr ha, rfl⟩, hpositive⟩ + · exact subset_convexHull ℝ _ ⟨actionVector mass comparison, + List.mem_map.mpr ⟨comparison, mem_toList.mpr hc, rfl⟩, rfl⟩ + · exact band_block_nonempty band hband + · intro p hp q hq b + rw [band_hull_block_mass band mass b p hp, band_hull_block_mass band mass b q hq] + · exact hη + · exact hκ + · exact hκhalf + · exact hηrange + · exact hdecrementNonneg + · exact hrange + · exact hdecrement + · exact hgain + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/BandRounding.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/BandRounding.lean new file mode 100644 index 0000000000000000000000000000000000000000..7f05342bcf6def0bc05c1ad86f10f98d53608d4b --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/BandRounding.lean @@ -0,0 +1,132 @@ +import OAI.Combinatorics.EditApproximation.Geometry.BandEnvelopes +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! +# Integer rounding spacings from the dyadic band envelopes + +Taking the nonnegative part of the dyadic product exponent computes the +integer spacing max(1, theta*h). The resulting spacing preserves the wide +grid by actual divisibility of powers of two. +-/ + +namespace EditApproximation + +open Finset + + + + + +theorem dyadic_nonnegative_spacing (exponent : ℤ) : + ((2 ^ exponent.toNat : ℕ) : ℚ) = max 1 ((2 : ℚ) ^ exponent) := by + by_cases hnonneg : 0 ≤ exponent + · have hcast : ((exponent.toNat : ℕ) : ℤ) = exponent := Int.toNat_of_nonneg hnonneg + have hone : (1 : ℚ) ≤ 2 ^ exponent := by + exact one_le_zpow₀ (by norm_num) hnonneg + rw [max_eq_right hone, Nat.cast_pow, Nat.cast_ofNat, ← zpow_natCast, hcast] + · have hnegative : exponent ≤ 0 := by omega + have htoNat : exponent.toNat = 0 := Int.toNat_eq_zero.mpr hnegative + have hone : (2 : ℚ) ^ exponent ≤ 1 := by + simpa only [zpow_zero] using zpow_le_zpow_right₀ (by norm_num : (1 : ℚ) ≤ 2) hnegative + simp only [htoNat, pow_zero, Nat.cast_one, max_eq_left hone] + +theorem bandRoundSpacing_exact {ny M : ℕ} (thetaExponent b : ℕ) + (band : List (Fin M → TargetInterval ny)) + (initial : Fin M → TargetInterval ny → ℚ) (i : Fin M) : + (bandRoundSpacing thetaExponent b band initial i : ℚ) = + max 1 ((2 : ℚ) ^ (-(thetaExponent : ℤ)) * bandChildEnvelope b band initial i) := by + rw [bandRoundSpacing, dyadic_nonnegative_spacing] + unfold bandChildEnvelope rationalDyadicCeiling bandEnvelopeExponent + rw [← zpow_add₀ (by norm_num : (2 : ℚ) ≠ 0)] + congr 2 + omega + +theorem bandRoundSpacing_pos {ny M : ℕ} (thetaExponent b : ℕ) + (band : List (Fin M → TargetInterval ny)) + (initial : Fin M → TargetInterval ny → ℚ) (i : Fin M) : + 0 < bandRoundSpacing thetaExponent b band initial i := by + unfold bandRoundSpacing + positivity + +/-- Actual division rounding moves each endpoint by at most the scaled +child envelope, including the special spacing-one case. -/ +theorem gridRound_scaled_error (spacing position : ℕ) (scaled : ℚ) + (hspacing : (spacing : ℚ) = max 1 scaled) (hscaled : 0 ≤ scaled) : + (Nat.dist position (gridRound spacing position) : ℚ) ≤ scaled := by + have hpos : 0 < spacing := by + have hone : (1 : ℚ) ≤ spacing := by rw [hspacing]; exact le_max_left _ _ + exact_mod_cast (lt_of_lt_of_le (by norm_num : (0 : ℚ) < 1) hone) + by_cases hone : spacing = 1 + · simp only [hone, gridRound_one, Nat.dist_self, Nat.cast_zero] + exact hscaled + · have htwo : 1 < spacing := by omega + have htwoR : (1 : ℚ) < spacing := by exact_mod_cast htwo + have hscale : 1 < scaled := by + by_contra hnot + have hle : scaled ≤ 1 := le_of_not_gt hnot + rw [max_eq_left hle] at hspacing + linarith only [hspacing, htwoR] + have hequal : (spacing : ℚ) = scaled := hspacing.trans (max_eq_right hscale.le) + have herr : (Nat.dist position (gridRound spacing position) : ℚ) < spacing := by + exact_mod_cast gridRound_error_lt spacing position hpos + exact herr.le.trans_eq hequal + +theorem dyadic_dvd_of_le {small large : ℕ} + (hsmall : ∃ e : ℕ, small = 2 ^ e) (hlarge : ∃ e : ℕ, large = 2 ^ e) + (hle : small ≤ large) : small ∣ large := by + obtain ⟨s, rfl⟩ := hsmall + obtain ⟨l, rfl⟩ := hlarge + exact Nat.pow_dvd_pow 2 ((Nat.pow_le_pow_iff_right (by decide : 1 < 2)).mp hle) + +theorem seedGridSpacing_dyadic {b P : ℕ} + (hb : ∃ e : ℕ, b = 2 ^ e) (hP : ∃ e : ℕ, P = 2 ^ e) : + ∃ e : ℕ, seedGridSpacing b P = 2 ^ e := by + obtain ⟨s, rfl⟩ := hb + obtain ⟨p, rfl⟩ := hP + by_cases horder : p ≤ s + · refine ⟨s - p, ?_⟩ + rw [seedGridSpacing, Nat.pow_div horder (by decide : 0 < 2), max_eq_right Nat.one_le_two_pow] + · refine ⟨0, ?_⟩ + have hlt : 2 ^ s < 2 ^ p := Nat.pow_lt_pow_right (by decide : 1 < 2) (by omega) + simp only [seedGridSpacing, Nat.div_eq_of_lt hlt, max_eq_left (by decide : 0 ≤ 1), pow_zero] + +/-- The envelope floor and the numerical theta*P ≥ M ensure that the +actual rounded integer spacing is a multiple of the actual wide grid. -/ +theorem bandRoundSpacing_wide_grid {ny M b P : ℕ} (thetaExponent : ℕ) + (band : List (Fin M → TargetInterval ny)) + (initial : Fin M → TargetInterval ny → ℚ) (i : Fin M) + (hM : 0 < M) (hPpos : 0 < P) + (hbPower : ∃ e : ℕ, b = 2 ^ e) (hPPower : ∃ e : ℕ, P = 2 ^ e) + (hscale : (M : ℚ) ≤ (2 : ℚ) ^ (-(thetaExponent : ℤ)) * P) : + seedGridSpacing b P ∣ bandRoundSpacing thetaExponent b band initial i := by + let theta : ℚ := 2 ^ (-(thetaExponent : ℤ)) + have htheta : 0 ≤ theta := (zpow_pos (by norm_num : (0 : ℚ) < 2) _).le + have hMr : (0 : ℚ) < M := by exact_mod_cast hM + have hPr : (0 : ℚ) < P := by exact_mod_cast hPpos + have hratio : (M : ℚ) / P ≤ theta := (div_le_iff₀ hPr).2 hscale + have hfloor : (b : ℚ) / P ≤ theta * ((b : ℚ) / M) := by + calc + _ = ((b : ℚ) / M) * ((M : ℚ) / P) := by field_simp [hMr.ne', hPr.ne'] + _ ≤ ((b : ℚ) / M) * theta := + mul_le_mul_of_nonneg_left hratio (div_nonneg (Nat.cast_nonneg _) hMr.le) + _ = _ := mul_comm _ _ + have henvelope := (bandChildEnvelope_lower b band initial i).1 + have hproduct := hfloor.trans (mul_le_mul_of_nonneg_left henvelope htheta) + have hwide : (seedGridSpacing b P : ℚ) ≤ + max 1 (theta * bandChildEnvelope b band initial i) := by + unfold seedGridSpacing + rw [Nat.cast_max, Nat.cast_one] + exact max_le_max le_rfl ((Nat.cast_div_le (m := b) (n := P)).trans hproduct) + have hspacing := bandRoundSpacing_exact thetaExponent b band initial i + have hle : seedGridSpacing b P ≤ bandRoundSpacing thetaExponent b band initial i := by + have h := hwide.trans_eq hspacing.symm + exact_mod_cast h + exact dyadic_dvd_of_le (seedGridSpacing_dyadic hbPower hPPower) + ⟨_, rfl⟩ hle + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/Bands.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/Bands.lean new file mode 100644 index 0000000000000000000000000000000000000000..e9b954f81662befeeaeaf8069e48d57737cab53a --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/Bands.lean @@ -0,0 +1,72 @@ +import Mathlib + +namespace OAI + +/-! +# Predicted-band geometry + +The prefix-cost predictor is 1-Lipschitz, while its velocity has a strict +margin below one. This gives narrow bands without a convexity assumption +on the set of allowed endpoints (Sections 5 and 6 of the manuscript). +-/ + +namespace EditApproximation + +def inPredictedBand (prefixCost : ℝ → ℝ) (origin velocity margin width point : ℝ) : Prop := + |point - origin - velocity * prefixCost point| ≤ margin * width + +theorem predicted_band_diameter {prefixCost : ℝ → ℝ} + {origin velocity margin width p q : ℝ} + (hmargin : 0 < margin) (hvelocity : |velocity| ≤ 1 - margin) + (hLipschitz : |prefixCost p - prefixCost q| ≤ |p - q|) + (hp : inPredictedBand prefixCost origin velocity margin width p) + (hq : inPredictedBand prefixCost origin velocity margin width q) : + |p - q| ≤ 2 * width := by + have hid : p - q = + (p - origin - velocity * prefixCost p) - (q - origin - velocity * prefixCost q) + + velocity * (prefixCost p - prefixCost q) := by ring + have htri := (abs_add_le + ((p - origin - velocity * prefixCost p) - (q - origin - velocity * prefixCost q)) + (velocity * (prefixCost p - prefixCost q))).trans + (add_le_add (abs_sub _ _) le_rfl) + rw [← hid, abs_mul] at htri + have hprod := mul_le_mul hvelocity hLipschitz (abs_nonneg _) + ((abs_nonneg velocity).trans hvelocity) + change |p - origin - velocity * prefixCost p| ≤ margin * width at hp + change |q - origin - velocity * prefixCost q| ≤ margin * width at hq + have hscaled : margin * |p - q| ≤ margin * (2 * width) := by nlinarith + exact le_of_mul_le_mul_left hscaled hmargin + +/-- The comparison prefix error is the weighted deviation plus two +warmup-mass discrepancy charges. -/ +theorem comparison_prefix_prediction_error + {point origin velocity predictedVelocity prefixMass prefixCost totalMass discrepancy deviation : ℝ} + (hprefix : 0 ≤ prefixMass) (hprefixTotal : prefixMass ≤ totalMass) + (hprediction : |velocity - predictedVelocity| * totalMass ≤ discrepancy) + (hvelocity : |predictedVelocity| ≤ 1) + (hcostLower : prefixMass - discrepancy ≤ prefixCost) + (hcostUpper : prefixCost ≤ prefixMass) + (hdeviation : |point - origin - velocity * prefixMass| ≤ deviation) : + |point - origin - predictedVelocity * prefixCost| ≤ deviation + 2 * discrepancy := by + have hcostDiff : |prefixMass - prefixCost| ≤ discrepancy := by + rw [abs_of_nonneg (by linarith : 0 ≤ prefixMass - prefixCost)] + linarith + have hfirst : |(velocity - predictedVelocity) * prefixMass| ≤ discrepancy := by + rw [abs_mul, abs_of_nonneg hprefix] + exact (mul_le_mul_of_nonneg_left hprefixTotal (abs_nonneg _)).trans hprediction + have hsecond : |predictedVelocity * (prefixMass - prefixCost)| ≤ discrepancy := by + rw [abs_mul] + have hprod := mul_le_mul hvelocity hcostDiff (abs_nonneg _) + (by norm_num : (0 : ℝ) ≤ 1) + simpa only [one_mul] using hprod + have hid : point - origin - predictedVelocity * prefixCost = + (point - origin - velocity * prefixMass) + + (velocity - predictedVelocity) * prefixMass + + predictedVelocity * (prefixMass - prefixCost) := by ring + rw [hid] + exact ((abs_add_le _ _).trans (add_le_add (abs_add_le _ _) le_rfl)).trans + (by linarith) + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/Bellman.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/Bellman.lean new file mode 100644 index 0000000000000000000000000000000000000000..5704e0849008ff5c6fc39fbd2d77de1dc1db2ddb --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/Bellman.lean @@ -0,0 +1,250 @@ +import Mathlib + +namespace OAI + +/-! +# Finite Bellman propagation and warmup + +The action minimum is computed by a finite list with the initial cone as +fallback. Empty action families need no extended-real convention. The +warmup lemmas concern the actual repeated finite Bellman operator. +-/ + +namespace EditApproximation + +open Finset + +def finiteMinimum (fallback : ℝ) : List ℝ → ℝ + | [] => fallback + | value :: rest => min value (finiteMinimum fallback rest) + +theorem le_finiteMinimum_iff (lower fallback : ℝ) (values : List ℝ) : + lower ≤ finiteMinimum fallback values ↔ lower ≤ fallback ∧ ∀ v ∈ values, lower ≤ v := by + induction values with + | nil => simp [finiteMinimum] + | cons v rest ih => simp only [finiteMinimum, le_min_iff, ih, List.mem_cons, + forall_eq_or_imp]; tauto + +theorem finiteMinimum_le_fallback (fallback : ℝ) (values : List ℝ) : + finiteMinimum fallback values ≤ fallback := by + induction values with + | nil => rfl + | cons v rest ih => exact (min_le_right _ _).trans ih + +theorem finiteMinimum_le_member (fallback : ℝ) (values : List ℝ) + {value : ℝ} (hvalue : value ∈ values) : finiteMinimum fallback values ≤ value := by + induction values with + | nil => simp at hvalue + | cons v rest ih => + rcases List.mem_cons.mp hvalue with rfl | hvalue + · exact min_le_left _ _ + · exact (min_le_right _ _).trans (ih hvalue) + +theorem finiteMinimum_map_mono {ι : Type*} (indices : List ι) + (fallback fallback' : ℝ) (value value' : ι → ℝ) + (hfallback : fallback ≤ fallback') (hvalue : ∀ i ∈ indices, value i ≤ value' i) : + finiteMinimum fallback (indices.map value) ≤ + finiteMinimum fallback' (indices.map value') := by + induction indices with + | nil => exact hfallback + | cons i rest ih => + simp only [List.map_cons, finiteMinimum] + exact min_le_min (hvalue i (by simp)) (ih fun j hj => hvalue j (by simp [hj])) + +theorem finiteMinimum_map_add {ι : Type*} (indices : List ι) + (fallback charge : ℝ) (value : ι → ℝ) : + finiteMinimum (fallback + charge) (indices.map fun i => value i + charge) = + finiteMinimum fallback (indices.map value) + charge := by + induction indices with + | nil => rfl + | cons i rest ih => simp only [List.map_cons, finiteMinimum, ih, min_add_add_right] + +theorem finiteMinimum_map_spatial {ι : Type*} (indices : List ι) + (fallback fallback' charge : ℝ) (value value' : ι → ℝ) + (hfallback : fallback ≤ fallback' + charge) + (hvalue : ∀ i ∈ indices, value i ≤ value' i + charge) : + finiteMinimum fallback (indices.map value) ≤ + finiteMinimum fallback' (indices.map value') + charge := by + rw [← finiteMinimum_map_add] + exact finiteMinimum_map_mono indices _ _ _ _ hfallback hvalue + +structure BellmanAction (Parent Child : Type*) (M : ℕ) where + center : Parent + connection : ℝ + childState : Fin M → Child + +def bellmanActionValue {Parent Child : Type*} {M : ℕ} + (distance : Parent → Parent → ℝ) (L : ℝ) (child : Child → ℝ) + (query : Parent) (action : BellmanAction Parent Child M) : ℝ := + L * distance query action.center + action.connection + ∑ i, child (action.childState i) + +def finiteBellman {Parent Child : Type*} {M : ℕ} + (fallback : Parent → ℝ) (distance : Parent → Parent → ℝ) (L : ℝ) + (actions : List (BellmanAction Parent Child M)) (child : Child → ℝ) (query : Parent) : ℝ := + finiteMinimum (fallback query) (actions.map (bellmanActionValue distance L child query)) + +theorem finiteBellman_le_fallback {Parent Child : Type*} {M : ℕ} + (fallback : Parent → ℝ) (distance : Parent → Parent → ℝ) (L : ℝ) + (actions : List (BellmanAction Parent Child M)) (child : Child → ℝ) (query : Parent) : + finiteBellman fallback distance L actions child query ≤ fallback query := + finiteMinimum_le_fallback _ _ + +theorem finiteBellman_mono {Parent Child : Type*} {M : ℕ} + (fallback : Parent → ℝ) (distance : Parent → Parent → ℝ) (L : ℝ) + (actions : List (BellmanAction Parent Child M)) {child child' : Child → ℝ} + (hchild : child ≤ child') : + finiteBellman fallback distance L actions child ≤ + finiteBellman fallback distance L actions child' := by + intro query + apply finiteMinimum_map_mono _ _ _ _ _ le_rfl + intro action _ + exact add_le_add le_rfl (sum_le_sum fun i _ => hchild (action.childState i)) + +theorem finiteBellman_le_action {Parent Child : Type*} {M : ℕ} + (fallback : Parent → ℝ) (distance : Parent → Parent → ℝ) (L : ℝ) + (actions : List (BellmanAction Parent Child M)) (child : Child → ℝ) + (query : Parent) (action : BellmanAction Parent Child M) (haction : action ∈ actions) : + finiteBellman fallback distance L actions child query ≤ + bellmanActionValue distance L child query action := + finiteMinimum_le_member _ _ (List.mem_map.mpr ⟨action, haction, rfl⟩) + +theorem finiteBellman_lower {Parent Child : Type*} {M : ℕ} + (fallback lower : Parent → ℝ) (distance : Parent → Parent → ℝ) (L : ℝ) + (actions : List (BellmanAction Parent Child M)) (child : Child → ℝ) + (hfallback : lower ≤ fallback) + (haction : ∀ query, ∀ action ∈ actions, + lower query ≤ bellmanActionValue distance L child query action) : + lower ≤ finiteBellman fallback distance L actions child := by + intro query + exact (le_finiteMinimum_iff _ _ _).2 + ⟨hfallback query, fun v hv => by + obtain ⟨action, ha, rfl⟩ := List.mem_map.mp hv + exact haction query action ha⟩ + +theorem finiteBellman_spatial {Parent Child : Type*} {M : ℕ} + (fallback : Parent → ℝ) (distance : Parent → Parent → ℝ) (L : ℝ) + (actions : List (BellmanAction Parent Child M)) (child : Child → ℝ) + (hL : 0 ≤ L) (query query' : Parent) + (hfallback : fallback query ≤ fallback query' + L * distance query query') + (htriangle : ∀ center, distance query center ≤ distance query' center + distance query query') : + finiteBellman fallback distance L actions child query ≤ + finiteBellman fallback distance L actions child query' + L * distance query query' := by + apply finiteMinimum_map_spatial _ _ _ _ _ _ hfallback + intro action _ + have hdist := mul_le_mul_of_nonneg_left (htriangle action.center) hL + dsimp [bellmanActionValue] + linarith + +def warmup {State : Type*} (operator : (State → ℝ) → State → ℝ) + (initial : State → ℝ) : ℕ → State → ℝ + | 0 => initial + | t + 1 => operator (warmup operator initial t) + +/-- A finite system of node-specific action lists. Child states may +belong to any lower level of the source tree. -/ +def finiteBellmanSystem {State : Type*} {M : ℕ} + (initial : State → ℝ) (distance : State → State → ℝ) (L : ℝ) + (actions : State → List (BellmanAction State State M)) + (child : State → ℝ) (query : State) : ℝ := + finiteBellman initial distance L (actions query) child query + +theorem finiteBellmanSystem_monotone {State : Type*} {M : ℕ} + (initial : State → ℝ) (distance : State → State → ℝ) (L : ℝ) + (actions : State → List (BellmanAction State State M)) : + Monotone (finiteBellmanSystem initial distance L actions) := by + intro child child' hchild query + exact finiteBellman_mono initial distance L (actions query) hchild query + +theorem finiteBellmanSystem_le_initial {State : Type*} {M : ℕ} + (initial : State → ℝ) (distance : State → State → ℝ) (L : ℝ) + (actions : State → List (BellmanAction State State M)) (child : State → ℝ) : + finiteBellmanSystem initial distance L actions child ≤ initial := by + intro query + exact finiteBellman_le_fallback initial distance L (actions query) child query + +theorem warmup_nonincreasing {State : Type*} + (operator : (State → ℝ) → State → ℝ) (initial : State → ℝ) + (hmono : Monotone operator) (hfirst : operator initial ≤ initial) : + ∀ t, warmup operator initial (t + 1) ≤ warmup operator initial t := by + intro t + induction t with + | zero => exact hfirst + | succ t ih => exact hmono ih + +theorem warmup_lower {State : Type*} + (operator : (State → ℝ) → State → ℝ) (initial lower : State → ℝ) + (hinit : lower ≤ initial) + (hpreserve : ∀ value, lower ≤ value → lower ≤ operator value) : + ∀ t, lower ≤ warmup operator initial t := by + intro t + induction t with + | zero => exact hinit + | succ t ih => exact hpreserve _ ih + +theorem finite_bellman_warmup_nonincreasing {State : Type*} {M : ℕ} + (initial : State → ℝ) (distance : State → State → ℝ) (L : ℝ) + (actions : State → List (BellmanAction State State M)) : + ∀ t, warmup (finiteBellmanSystem initial distance L actions) initial (t + 1) ≤ + warmup (finiteBellmanSystem initial distance L actions) initial t := + warmup_nonincreasing _ _ (finiteBellmanSystem_monotone initial distance L actions) + (finiteBellmanSystem_le_initial initial distance L actions initial) + +noncomputable def warmupAverage {State : Type*} + (operator : (State → ℝ) → State → ℝ) (initial : State → ℝ) + (T : ℕ) (state : State) : ℝ := + (∑ t ∈ range T, warmup operator initial t state) / T + +theorem warmup_average_sandwich {State : Type*} + (operator : (State → ℝ) → State → ℝ) (initial : State → ℝ) + (T : ℕ) (hT : 0 < T) (hmono : Monotone operator) + (hfirst : operator initial ≤ initial) (state : State) : + warmup operator initial T state ≤ warmupAverage operator initial T state ∧ + warmupAverage operator initial T state ≤ initial state := by + have hanti : Antitone (fun t => warmup operator initial t state) := + antitone_nat_of_succ_le fun t => warmup_nonincreasing operator initial hmono hfirst t state + have hTr : (0 : ℝ) < T := by exact_mod_cast hT + constructor + · apply (le_div_iff₀ hTr).2 + have hsum := sum_le_sum (s := range T) fun t ht => hanti (show t ≤ T from (mem_range.mp ht).le) + simpa only [sum_const, card_range, nsmul_eq_mul, mul_comm] using hsum + · apply (div_le_iff₀ hTr).2 + have hsum := sum_le_sum (s := range T) fun t _ => hanti (Nat.zero_le t) + simpa only [sum_const, card_range, nsmul_eq_mul, warmup, mul_comm] using hsum + +/-- Averaging the actual one-step action inequality gives the warmup +mass slack, with the exact endpoint correction before its simplification +to the nonnegative initial-cone charge. -/ +theorem warmup_average_action_bound {State ι : Type*} [Fintype ι] + (operator : (State → ℝ) → State → ℝ) (initial : State → ℝ) + (T : ℕ) (hT : 0 < T) (parent : State) (child : ι → State) (charge : ℝ) + (haction : ∀ t < T, warmup operator initial (t + 1) parent ≤ + charge + ∑ i, warmup operator initial t (child i)) : + warmupAverage operator initial T parent - + (initial parent - warmup operator initial T parent) / T ≤ + charge + ∑ i, warmupAverage operator initial T (child i) := by + have hTr : (0 : ℝ) < T := by exact_mod_cast hT + have htelAll : ∀ K : ℕ, (∑ t ∈ range K, warmup operator initial t parent) - + (∑ t ∈ range K, warmup operator initial (t + 1) parent) = + initial parent - warmup operator initial K parent := by + intro K + induction K with + | zero => simp [warmup] + | succ K ih => + rw [sum_range_succ, sum_range_succ] + linarith + have htel := htelAll T + have hsum := sum_le_sum (s := range T) fun t ht => haction t (mem_range.mp ht) + rw [sum_add_distrib, sum_const, card_range, nsmul_eq_mul, sum_comm] at hsum + unfold warmupAverage + rw [← sub_div, ← sum_div] + apply (div_le_iff₀ hTr).2 + have hright : (charge + (∑ i, ∑ t ∈ range T, + warmup operator initial t (child i)) / T) * T = + (T : ℝ) * charge + ∑ i, ∑ t ∈ range T, warmup operator initial t (child i) := by + field_simp + rw [hright, ← htel] + linarith + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/CanonicalFractionWork.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/CanonicalFractionWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..4ee2ae9480104bfda35c50b6f6fca58db810b429 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/CanonicalFractionWork.lean @@ -0,0 +1,125 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryFractionWork +import OAI.Combinatorics.EditApproximation.Binary.BinaryCanonicalWork +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Fractions retain their unreduced numerator and denominator, but discard +leading zero bits after each operation. This exposes actual storage length +without charging or performing rational normalization. -/ + +namespace EditApproximation +namespace BinaryFraction + + + +theorem canonicalizeWithWork_representation (a : BinaryFraction) : + (canonicalizeWithWork a).1.representation = a.representation := by + apply UnreducedRational.eq_of_num_den + · simp only [canonicalizeWithWork, representation, SignedBinary.value, trimBitWordWithWork_value] + · exact trimBitWordWithWork_value a.denominator + +theorem canonicalizeWithWork_width (a : BinaryFraction) : + (canonicalizeWithWork a).1.width = + max (Nat.size a.representation.num.natAbs) (Nat.size a.representation.den) := by + have hnum : a.numerator.value.natAbs = bitWordValue a.numerator.bits := by + cases h : a.numerator.negative <;> simp [SignedBinary.value, signedMagnitude, h] + simp only [canonicalizeWithWork, width, trimBitWordWithWork_length, representation, hnum] + +theorem canonicalizeWithWork_cost (a : BinaryFraction) : + (canonicalizeWithWork a).2 ≤ 6 * a.width + 4 := by + have hn : a.numerator.bits.length ≤ a.width := le_max_left _ _ + have hd : a.denominator.length ≤ a.width := le_max_right _ _ + simp only [canonicalizeWithWork, trimBitWordWithWork_cost] + omega + + + + + +theorem canonicalAddWithWork_representation (a b : BinaryFraction) : + (canonicalAddWithWork a b).1.representation = a.representation.add b.representation := by + rw [canonicalAddWithWork, canonicalizeWithWork_representation, addWithWork_representation] + +theorem canonicalMulWithWork_representation (a b : BinaryFraction) : + (canonicalMulWithWork a b).1.representation = a.representation.mul b.representation := by + rw [canonicalMulWithWork, canonicalizeWithWork_representation, mulWithWork_representation] + +theorem rawAdd_width (a b : BinaryFraction) (B : ℕ) (ha : a.width ≤ B) (hb : b.width ≤ B) : + (a.addWithWork b).1.width ≤ 3 * B + 2 := by + have han : a.numerator.bits.length ≤ B := (le_max_left _ _).trans ha + have had : a.denominator.length ≤ B := (le_max_right _ _).trans ha + have hbn : b.numerator.bits.length ≤ B := (le_max_left _ _).trans hb + have hbd : b.denominator.length ≤ B := (le_max_right _ _).trans hb + have hfirst := SignedBinary.mulWithWork_length a.numerator b.denominatorInteger + have hsecond := SignedBinary.mulWithWork_length b.numerator a.denominatorInteger + have hsum := SignedBinary.addWithWork_length (a.numerator.mulWithWork b.denominatorInteger).1 + (b.numerator.mulWithWork a.denominatorInteger).1 + have hden := bitMulWithWork_length a.denominator b.denominator + simp only [denominatorInteger] at hfirst hsecond + dsimp only [addWithWork, width, denominatorInteger] + simp only [denominatorInteger] at hsum + apply max_le <;> omega + +theorem rawMul_width (a b : BinaryFraction) (B : ℕ) (ha : a.width ≤ B) (hb : b.width ≤ B) : + (a.mulWithWork b).1.width ≤ 3 * B + 1 := by + have han : a.numerator.bits.length ≤ B := (le_max_left _ _).trans ha + have had : a.denominator.length ≤ B := (le_max_right _ _).trans ha + have hbn : b.numerator.bits.length ≤ B := (le_max_left _ _).trans hb + have hbd : b.denominator.length ≤ B := (le_max_right _ _).trans hb + have hnum := SignedBinary.mulWithWork_length a.numerator b.numerator + have hden := bitMulWithWork_length a.denominator b.denominator + dsimp only [mulWithWork, width] + apply max_le <;> omega + +theorem canonicalAddWithWork_cost (a b : BinaryFraction) (B : ℕ) (ha : a.width ≤ B) (hb : b.width ≤ B) : + (canonicalAddWithWork a b).2 ≤ 6000 * (B + 1) ^ 2 := by + have hr := addWithWork_cost a b B ha hb + have hw := rawAdd_width a b B ha hb + have hc := canonicalizeWithWork_cost (a.addWithWork b).1 + change (a.addWithWork b).2 + (canonicalizeWithWork (a.addWithWork b).1).2 ≤ _ + nlinarith only [hr, hw, hc] + +theorem canonicalMulWithWork_cost (a b : BinaryFraction) (B : ℕ) (ha : a.width ≤ B) (hb : b.width ≤ B) : + (canonicalMulWithWork a b).2 ≤ 2000 * (B + 1) ^ 2 := by + have hr := mulWithWork_cost a b B ha hb + have hw := rawMul_width a b B ha hb + have hc := canonicalizeWithWork_cost (a.mulWithWork b).1 + change (a.mulWithWork b).2 + (canonicalizeWithWork (a.mulWithWork b).1).2 ≤ _ + nlinarith only [hr, hw, hc] + +theorem canonicalizeWithWork_width_le_storageBits (a : BinaryFraction) : + (canonicalizeWithWork a).1.width ≤ a.representation.storageBits := by + rw [canonicalizeWithWork_width] + unfold UnreducedRational.storageBits + exact max_le (by omega) (by omega) + +theorem canonicalAddWithWork_width_le_storageBits (a b : BinaryFraction) : + (canonicalAddWithWork a b).1.width ≤ + (a.representation.add b.representation).storageBits := by + have h := canonicalizeWithWork_width_le_storageBits (a.addWithWork b).1 + rw [addWithWork_representation] at h + exact h + +theorem canonicalMulWithWork_width_le_storageBits (a b : BinaryFraction) : + (canonicalMulWithWork a b).1.width ≤ + (a.representation.mul b.representation).storageBits := by + have h := canonicalizeWithWork_width_le_storageBits (a.mulWithWork b).1 + rw [mulWithWork_representation] at h + exact h + +theorem canonicalAddWithWork_self_width (a b : BinaryFraction) : + (canonicalAddWithWork a b).1.width ≤ (canonicalAddWithWork a b).1.representation.storageBits := by + rw [canonicalAddWithWork_representation] + exact canonicalAddWithWork_width_le_storageBits a b + +theorem canonicalMulWithWork_self_width (a b : BinaryFraction) : + (canonicalMulWithWork a b).1.width ≤ (canonicalMulWithWork a b).1.representation.storageBits := by + rw [canonicalMulWithWork_representation] + exact canonicalMulWithWork_width_le_storageBits a b + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/CellGroupSelection.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/CellGroupSelection.lean new file mode 100644 index 0000000000000000000000000000000000000000..24c424363b6b5f6f650aa2d79553e735f1c47661 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/CellGroupSelection.lean @@ -0,0 +1,193 @@ +import OAI.Combinatorics.EditApproximation.Geometry.GroupCells +import OAI.Combinatorics.EditApproximation.Geometry.BandGroupSampling +import OAI.Combinatorics.EditApproximation.Numerics.RationalWideStep +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Literal unskipped groups of whole cells and their selected wide actions. -/ + +namespace EditApproximation + +open Finset + + + +theorem cellUnskippedBands_length_le {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (b P F thetaExponent : ℕ) (tau a : ℚ) + (parentInitial : TargetInterval target.length → ℚ) + (child initial : Fin M → TargetInterval target.length → ℚ) (cell : ℕ × ℕ) + (hb : ∃ e : ℕ, b = 2 ^ e) (hP : ∃ e : ℕ, P = 2 ^ e) : + (cellUnskippedBands source target parent b P F thetaExponent tau a parentInitial child initial cell).length ≤ + (P + 1) ^ 2 := by + have htheta : 0 ≤ (2 : ℚ) ^ (-(thetaExponent : ℤ)) ∧ + (2 : ℚ) ^ (-(thetaExponent : ℤ)) ≤ 1 := by + refine ⟨(zpow_pos (by norm_num : (0 : ℚ) < 2) _).le, ?_⟩ + rw [zpow_neg, zpow_natCast] + exact inv_le_one_of_one_le₀ (one_le_pow₀ (by norm_num : (1 : ℚ) ≤ 2)) + exact (List.length_filterMap_le _ _).trans + (cellRepresentativeStates_length_le a parentInitial _ cell htheta hb hP) + +namespace UnskippedBand + +theorem canonicalRounded_congr {ny M : ℕ} (thetaExponent b : ℕ) + (band band' : List (Fin M → TargetInterval ny)) (heq : band = band') + (hnonempty : band ≠ []) (hnonempty' : band' ≠ []) + (initial : Fin M → TargetInterval ny → ℚ) : + canonicalRoundedBandAction thetaExponent b band hnonempty initial = + canonicalRoundedBandAction thetaExponent b band' hnonempty' initial := by + cases heq + rfl + + + +theorem rationalAction_wide_mem {α : Type*} {source target : List α} {M b P thetaExponent : ℕ} + {parent : TargetInterval source.length} {tau F : ℚ} + {child initial : Fin M → TargetInterval target.length → ℚ} + (member : UnskippedBand source target parent b P thetaExponent tau F child initial) + (representatives : List (ℕ × TargetInterval target.length)) (hrep : (b, member.center) ∈ representatives) : + member.rationalAction ∈ rationalActualWideActions parent representatives P := by + apply List.mem_flatMap.mpr + exact ⟨(b, member.center), hrep, List.mem_map.mpr ⟨member.rounded, member.wide_guard, rfl⟩⟩ + +theorem rounded_cost {α : Type*} {source target : List α} {M b P thetaExponent : ℕ} + {parent : TargetInterval source.length} {tau F : ℚ} + {child initial : Fin M → TargetInterval target.length → ℚ} + (member : UnskippedBand source target parent b P thetaExponent tau F child initial) + (htau : 0 < tau) (value : Fin M → TargetInterval target.length → ℚ) + (action : Fin M → TargetInterval target.length) (haction : action ∈ member.actions) + (delta L : ℚ) (hL : 0 ≤ L) + (hspatial : ∀ i s t, value i s ≤ (1 + delta) * value i t + L * targetEndpointDistance s t) : + rationalEndpointActionValue member.center member.rounded value ≤ + (1 + delta) * (∑ i, value i (action i)) + + (6 * L + 2) * (2 : ℚ) ^ (-(thetaExponent : ℤ)) * ∑ i, member.envelope i := by + have hnonempty := member.nonempty + by_cases hempty : wideActionList M parent member.center b P = [] + · simp only [representativeBandActions, dite_eq_left hempty] at hnonempty + exact False.elim (hnonempty rfl) + · by_cases hZ : 0 < rationalWideActionMinimum parent member.center b P hempty child + · have hband : member.actions = computedBandActions parent member.center b P tau + ((2 : ℚ) ^ (-(thetaExponent : ℤ))) + (rationalStateGap (substring source parent.lo parent.hi) target member.center / + rationalWideActionMinimum parent member.center b P hempty child) child := by + simp only [actions, representativeBandActions, dite_eq_right hempty, ite_eq_left hZ] + have hne : computedBandActions parent member.center b P tau + ((2 : ℚ) ^ (-(thetaExponent : ℤ))) + (rationalStateGap (substring source parent.lo parent.hi) target member.center / + rationalWideActionMinimum parent member.center b P hempty child) child ≠ [] := by + rw [← hband] + exact member.nonempty + have ha := haction + rw [hband] at ha + have hcost := canonicalRoundedBandAction_cost parent member.center thetaExponent b P tau _ htau + child initial value hne action ha delta L hL hspatial + have hround := canonicalRounded_congr thetaExponent b _ _ hband member.nonempty hne initial + change member.rounded = _ at hround + rw [hround] + simpa only [envelope, hband] using hcost + · simp only [representativeBandActions, dite_eq_right hempty, ite_eq_right hZ] at hnonempty + exact False.elim (hnonempty rfl) + +end UnskippedBand + + + +theorem chooseCellGroupAction_wide_mem {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (N b P F thetaExponent Q : ℕ) (tau a : ℚ) + (parentInitial : TargetInterval target.length → ℚ) + (child initial value : Fin M → TargetInterval target.length → ℚ) (cell : ℕ × ℕ) + (draw : ∀ scale : Fin (groupDyadicScales M b F).length, + Fin (groupSampleCount M Q b (groupDyadicScaleAt M b F scale)) → Fin M) + (hb : b ∈ dyadicScales N) (action : RationalBellmanAction + (TargetInterval target.length) (Fin M × TargetInterval target.length) M) + (hselected : chooseCellGroupAction source target parent b P F thetaExponent Q tau a + parentInitial child initial value cell draw = some action) : + action ∈ rationalActualWideActions parent (representativeList N P F a parentInitial) P := by + unfold chooseCellGroupAction at hselected + dsimp only at hselected + split_ifs at hselected with hempty + have heq := Option.some.inj hselected + rw [← heq] + apply UnskippedBand.rationalAction_wide_mem + apply cellRepresentativeStates_mem_representatives a parentInitial _ cell _ hb + apply (unskippedBandList_mem_iff _ _).mp + exact (chooseUnskippedGroup_spec Q value _ hempty draw).1 + +theorem group_rounding_coefficient {F L : ℚ} (hF : 1 ≤ F) (hL : 2 ≤ L) : + (6 * L + 2) * (64 * F) + 2 * L ≤ 512 * L * F := by + have hF0 : 0 ≤ F := by linarith only [hF] + have hL0 : 0 ≤ L := by linarith only [hL] + have hlarge := mul_le_mul_of_nonneg_right hL (mul_nonneg (by norm_num : (0 : ℚ) ≤ 64) hF0) + have hcell := mul_le_mul_of_nonneg_left hF (mul_nonneg (by norm_num : (0 : ℚ) ≤ 2) hL0) + have hprod := mul_nonneg hL0 hF0 + nlinarith only [hlarge, hcell, hprod] + +/-- Estimated minimization in an actual whole cell gives the group cone +bound simultaneously for every action of the specified member's band. -/ +theorem chooseCellGroup_cone_bound {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (b P F thetaExponent Q : ℕ) (tau a : ℚ) + (parentInitial : TargetInterval target.length → ℚ) + (child initial value : Fin M → TargetInterval target.length → ℚ) (cell : ℕ × ℕ) + (hnonempty : cellUnskippedBands source target parent b P F thetaExponent tau a + parentInitial child initial cell ≠ []) + (draw : ∀ scale : Fin (groupDyadicScales M b F).length, + Fin (groupSampleCount M Q b (groupDyadicScaleAt M b F scale)) → Fin M) + (specified : UnskippedBand source target parent b P thetaExponent tau F child initial) + (hspecified : specified ∈ cellUnskippedBands source target parent b P F thetaExponent tau a + parentInitial child initial cell) + (delta L gamma : ℚ) (hF : 1 ≤ F) (hL : 2 ≤ L) (htau : 0 < tau) + (hspatial : ∀ i s t, value i s ≤ (1 + delta) * value i t + L * targetEndpointDistance s t) + (haccurate : ∀ member ∈ cellUnskippedBands source target parent b P F thetaExponent tau a + parentInitial child initial cell, + |dyadicUnskippedGroupEstimate Q value member draw - + rationalEndpointActionValue member.center member.rounded value| ≤ gamma * b) + (action : Fin M → TargetInterval target.length) (haction : action ∈ specified.actions) + (q : TargetInterval target.length) : + let selected := chooseUnskippedGroup Q value + (cellUnskippedBands source target parent b P F thetaExponent tau a parentInitial child initial cell) + hnonempty draw + rationalActionValue (fun q r => targetEndpointDistance q r) L (fun is => value is.1 is.2) q + selected.rationalAction ≤ + L * targetEndpointDistance q specified.center + (1 + delta) * (∑ i, value i (action i)) + + (2 * gamma + 512 * L * F * (2 : ℚ) ^ (-(thetaExponent : ℤ))) * b := by + let members := cellUnskippedBands source target parent b P F thetaExponent tau a + parentInitial child initial cell + let selected := chooseUnskippedGroup Q value members hnonempty draw + have hselected : selected ∈ members := (chooseUnskippedGroup_spec Q value members hnonempty draw).1 + have hcost := chooseUnskippedGroup_cost_le Q value members hnonempty draw specified hspecified + (gamma * b) haccurate + change rationalEndpointActionValue selected.center selected.rounded value ≤ + rationalEndpointActionValue specified.center specified.rounded value + 2 * (gamma * b) at hcost + have hrounded := specified.rounded_cost htau value action haction delta L (by linarith only [hL]) hspatial + have hcenterCell (member : UnskippedBand source target parent b P thetaExponent tau F child initial) + (hm : member ∈ members) : member.center ∈ + cellTargetStates target.length (seedGridSpacing b P) ((2 : ℚ) ^ (-(thetaExponent : ℤ)) * b) cell := by + have hc := (unskippedBandList_mem_iff _ member).mp hm + exact (List.mem_filter.mp hc).1 + have hdiam := cellTargetStates_diameter cell (by unfold seedGridSpacing; omega) + specified.center selected.center (hcenterCell specified hspecified) (hcenterCell selected hselected) + have htriangle : (targetEndpointDistance q selected.center : ℚ) ≤ + targetEndpointDistance q specified.center + targetEndpointDistance specified.center selected.center := by + have h := targetEndpointDistance_triangle q specified.center selected.center + have h' : (targetEndpointDistance q selected.center : ℚ) ≤ + targetEndpointDistance specified.center selected.center + targetEndpointDistance q specified.center := by + exact_mod_cast h + simpa only [add_comm] using h' + have hL0 : 0 ≤ L := by linarith only [hL] + have hdist := mul_le_mul_of_nonneg_left (htriangle.trans (add_le_add_right hdiam _)) hL0 + have htheta : 0 ≤ (2 : ℚ) ^ (-(thetaExponent : ℤ)) := (zpow_pos (by norm_num : (0 : ℚ) < 2) _).le + have hsum := mul_le_mul_of_nonneg_left specified.sum_guard + (mul_nonneg (by linarith only [hL0] : 0 ≤ 6 * L + 2) htheta) + change (6 * L + 2) * (2 : ℚ) ^ (-(thetaExponent : ℤ)) * (∑ i, specified.envelope i) ≤ + (6 * L + 2) * (2 : ℚ) ^ (-(thetaExponent : ℤ)) * (64 * F * b) at hsum + have hcoef := mul_le_mul_of_nonneg_right (group_rounding_coefficient (F := (F : ℚ)) (L := L) + (by exact_mod_cast hF) hL) + (mul_nonneg htheta (Nat.cast_nonneg (α := ℚ) b)) + dsimp only [rationalActionValue, UnskippedBand.rationalAction] + dsimp only [rationalEndpointActionValue] at hcost hrounded + nlinarith only [hcost, hrounded, hdist, hsum, hcoef] + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/ChargedCoarseOracle.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/ChargedCoarseOracle.lean new file mode 100644 index 0000000000000000000000000000000000000000..6eddbf50ded91695e2cbd1b8db122fadfc7df889 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/ChargedCoarseOracle.lean @@ -0,0 +1,130 @@ +import OAI.Combinatorics.EditApproximation.Geometry.ChargedGlobalQuery +import OAI.Combinatorics.EditApproximation.Probability.FiniteQueryWork + +namespace OAI + +/-! All initial-entry information used by a charged table body arrives +through explicit requests. Flattening those requests gives an adaptive +coarse oracle program whose shape is independent of coarse answers. -/ + +namespace EditApproximation + +namespace FiniteQuery + +def substitute {ι κ : Type*} (ask : ι → FiniteQuery κ) : FiniteQuery ι → FiniteQuery κ + | .done value => .done value + | .read key next => bind (ask key) (fun value => substitute ask (next value)) + +theorem substitute_cost {ι κ : Type*} (ask : ι → FiniteQuery κ) (oracle : κ → ℚ) + (weight : κ → ℕ) (query : FiniteQuery ι) : + (query.substitute ask).cost oracle weight = query.cost + (fun key => (ask key).value oracle) (fun key => (ask key).cost oracle weight) := by + induction query with + | done value => rfl + | read key next ih => + simp only [substitute, cost_bind, cost] + exact congrArg ((ask key).cost oracle weight + ·) (ih ((ask key).value oracle)) + +theorem substitute_value {ι κ : Type*} (ask : ι → FiniteQuery κ) (oracle : κ → ℚ) + (query : FiniteQuery ι) : + (query.substitute ask).value oracle = query.value (fun key => (ask key).value oracle) := by + induction query with + | done value => rfl + | read key next ih => + simp only [substitute, bind_value, value] + exact ih ((ask key).value oracle) + +end FiniteQuery + +section Coarse + +variable {α : Type*} [DecidableEq α] {M J R : ℕ} [NeZero R] + (source target : List α) (N P F exponent H Q T S passes copies : ℕ) + (factor : ℕ → ℚ) (multiplier : ℕ → ℕ) (tau eta kappa delta : ℚ) + (group : ℕ → ℕ → PhysicalInternalNode M J → Fin R → CellGroupDraws M F Q) + (integer : ℕ → ℕ → PhysicalInternalNode M J → Fin R → ℕ → TargetInterval target.length → ℕ) + +/-- An internal refinement body never inspects a coarse seed function +while building its local query. Its seed needs are explicit child reads. -/ +theorem physicalGlobalQuery_refinement_initial_independent + (left right : PhysicalEntry M J target.length → ℕ) + (parent : PhysicalTableRequest M J target.length) + (hi : ¬ parent.index ≤ T) (hd : parent.node.1.val < J) + (hw : ¬ (physicalSourceInterval source.length parent.node).hi - + (physicalSourceInterval source.length parent.node).lo ≤ 1) : + physicalGlobalQuery source target N P F exponent H Q T S copies factor multiplier + tau eta kappa delta group integer left parent = + physicalGlobalQuery source target N P F exponent H Q T S copies factor multiplier + tau eta kappa delta group integer right parent := by + unfold physicalGlobalQuery + dsimp only + erw [dite_eq_right hi, dite_eq_right hi, dite_eq_left hd, dite_eq_left hd, + dite_eq_right hw, dite_eq_right hw] + +/-- Coarse answers enter the charged program only at coarse leaves. -/ +theorem chargedGlobalQuery_table_initial_independent + (left right : PhysicalEntry M J target.length → ℕ) + (parent : {request : PhysicalTableRequest M J target.length // request.Bounded passes copies T S}) : + chargedGlobalQuery source target N P F exponent H Q T S passes copies factor multiplier + tau eta kappa delta group integer left (.inr parent) = + chargedGlobalQuery source target N P F exponent H Q T S passes copies factor multiplier + tau eta kappa delta group integer right (.inr parent) := by + unfold chargedGlobalQuery + dsimp only + split_ifs with hi hd hw + · rfl + · rfl + · unfold physicalBoundedQuery restrictRankedProgram + rw [physicalGlobalQuery_refinement_initial_independent source target N P F exponent H Q T S + copies factor multiplier tau eta kappa delta group integer left right parent.val hi hd hw] + · rfl + +/-- The flattened program receives each coarse answer from an explicit +external read. The constant zero here is never used as a seed answer. -/ +def chargedCoarseQuery (root : ChargedPhysicalRequest M J target.length passes copies T S) : + FiniteQuery (PhysicalEntry M J target.length) := + match root with + | .inl entry => .read entry FiniteQuery.done + | .inr parent => + (chargedGlobalQuery source target N P F exponent H Q T S passes copies factor multiplier + tau eta kappa delta group integer (fun _ => 0) (.inr parent)).substitute + (fun child => chargedCoarseQuery child.val) +termination_by root.rank +decreasing_by exact child.property + +theorem chargedCoarseQuery_value + (initial : PhysicalEntry M J target.length → ℕ) + (root : ChargedPhysicalRequest M J target.length passes copies T S) : + (chargedCoarseQuery source target N P F exponent H Q T S passes copies factor multiplier + tau eta kappa delta group integer root).value (fun entry => (initial entry : ℚ)) = + rankedProgramValue ChargedPhysicalRequest.rank + (chargedGlobalQuery source target N P F exponent H Q T S passes copies factor multiplier + tau eta kappa delta group integer initial) root := by + have hall : ∀ level root, root.rank = level → + (chargedCoarseQuery source target N P F exponent H Q T S passes copies factor multiplier + tau eta kappa delta group integer root).value (fun entry => (initial entry : ℚ)) = + rankedProgramValue ChargedPhysicalRequest.rank + (chargedGlobalQuery source target N P F exponent H Q T S passes copies factor multiplier + tau eta kappa delta group integer initial) root := by + intro level + induction level using Nat.strong_induction_on with + | h level ih => + intro root hlevel + cases root with + | inl entry => + rw [chargedCoarseQuery, rankedProgramValue] + rfl + | inr parent => + rw [chargedCoarseQuery, FiniteQuery.substitute_value, rankedProgramValue, + chargedGlobalQuery_table_initial_independent source target N P F exponent H Q T S passes copies + factor multiplier tau eta kappa delta group integer (fun _ => 0) initial parent] + congr 1 + funext child + exact ih child.val.rank (hlevel ▸ child.property) child.val rfl + exact hall root.rank root rfl + +end Coarse + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/ChargedDependencyExpansion.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/ChargedDependencyExpansion.lean new file mode 100644 index 0000000000000000000000000000000000000000..650e76a06b7f6c98a4b131645b4d74dd8ac3e67b --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/ChargedDependencyExpansion.lean @@ -0,0 +1,136 @@ +import OAI.Combinatorics.EditApproximation.Refinement.ComputedChargedQueryBudget +import OAI.Combinatorics.EditApproximation.Queries.QueryDependencyCosts +import OAI.Combinatorics.EditApproximation.Geometry.DependencyWeightedWork + +namespace OAI + +/-! The dependency expansion is built from the charged evaluator's +executed requests. Its branching bounds therefore apply to actual lazy +evaluation, with coarse leaves at their original physical depths. -/ + +namespace EditApproximation + +theorem chargedRequest_index_le {M J ny passes copies T S : ℕ} + (request : ChargedPhysicalRequest M J ny passes copies T S) : + request.index ≤ passes * (T + S + 1) := by + cases request with + | inl entry => exact Nat.zero_le _ + | inr parent => + have hp : parent.val.pass + 1 ≤ passes := parent.property.1 + have hi : parent.val.index + 1 ≤ T + S + 1 := Nat.add_le_add_right parent.property.2.2 1 + change parent.val.pass * (T + S + 1) + parent.val.index + 1 ≤ _ + calc + _ ≤ (parent.val.pass + 1) * (T + S + 1) := by rw [Nat.add_mul, Nat.one_mul]; omega + _ ≤ _ := Nat.mul_le_mul_right _ hp + +section Expansion + +variable {α : Type*} [DecidableEq α] {M J R : ℕ} [NeZero R] + (source target : List α) (N P H T S passes copies : ℕ) + (factor : ℕ → ℚ) (multiplier : ℕ → ℕ) (tau eta kappa delta : ℚ) + (group : ℕ → ℕ → PhysicalInternalNode M J → Fin R → + CellGroupDraws M (inputSmallLog N) (inputSmallLog N ^ 80)) + (integer : ℕ → ℕ → PhysicalInternalNode M J → Fin R → ℕ → TargetInterval target.length → ℕ) + (initial : PhysicalEntry M J target.length → ℕ) + +local notation "program" => chargedGlobalQuery source target N P (inputSmallLog N) + (40 * smallLogExponent N) H (inputSmallLog N ^ 80) T S passes copies factor multiplier + tau eta kappa delta group integer initial +local notation "values" => chargedRequestValue source target N P (inputSmallLog N) + (40 * smallLogExponent N) H (inputSmallLog N ^ 80) T S passes copies factor multiplier + tau eta kappa delta group integer initial +local notation "depth" => @ChargedPhysicalRequest.depth M J target.length passes copies T S +local notation "index" => @ChargedPhysicalRequest.index M J target.length passes copies T S + + theorem chargedRequestList_progress (root child : ChargedPhysicalRequest M J target.length passes copies T S) + (hchild : child ∈ queryRequestList depth index program root) : + (depth child < depth root ∧ index child ≤ index root) ∨ + (depth child ≤ depth root ∧ index child < index root) := by + have hvalue := rankedProgramValue_eq ChargedPhysicalRequest.rank program values + (chargedGlobalQuery_value source target N P (inputSmallLog N) (40 * smallLogExponent N) + H (inputSmallLog N ^ 80) T S passes copies factor multiplier tau eta kappa delta group integer initial) + change child ∈ ((program root).keys + (fun key => rankedProgramValue ChargedPhysicalRequest.rank program key.val)).map Subtype.val at hchild + simp only [hvalue] at hchild + obtain ⟨key, hk, rfl⟩ := List.mem_map.mp hchild + exact chargedGlobalQuery_keys_progress source target N P (inputSmallLog N) (40 * smallLogExponent N) + H (inputSmallLog N ^ 80) T S passes copies factor multiplier tau eta kappa delta group integer initial root key hk + + def chargedDependencyTree (root : ChargedPhysicalRequest M J target.length passes copies T S) : + DependencyExpansion := + queryDependencyExpansion depth index program + (chargedRequestList_progress source target N P H T S passes copies factor multiplier + tau eta kappa delta group integer initial) root + +variable (hN : 0 < N) (hell : 200 ≤ inputSmallLog N) + (hM : M = (integerParameters N).M) (hP : P = (integerParameters N).P) + (hT : T = (integerParameters N).T) (hS : S = (integerParameters N).S) + (hcopies : copies ≤ inputHeight N ^ 2) + (hAmin : ∀ pass, 1 ≤ factor pass) + (hAmax : ∀ pass, factor pass ≤ ((integerParameters N).initialFactor : ℚ)) + +include hN hell hM hP hT hS hcopies hAmin hAmax in + theorem chargedDependencyTree_valid (root : ChargedPhysicalRequest M J target.length passes copies T S) : + (chargedDependencyTree source target N P H T S passes copies factor multiplier + tau eta kappa delta group integer initial root).Valid + (M * inputSmallLog N ^ 257) + (inputHeight N ^ (512 * (coarseExponent (inputSmallLog N) + 1))) := by + apply queryDependencyExpansion_valid + · intro key + rw [querySameRequests_length_eq_cost depth index program values + (chargedGlobalQuery_value source target N P (inputSmallLog N) (40 * smallLogExponent N) + H (inputSmallLog N ^ 80) T S passes copies factor multiplier tau eta kappa delta group integer initial)] + have h := computed_chargedGlobalQuery_current_reads source target N P H T S passes copies + factor multiplier tau eta kappa delta group integer initial hN hell hM hAmax key + apply h.trans + calc + 2 * M * inputSmallLog N ^ 256 ≤ inputSmallLog N * M * inputSmallLog N ^ 256 := by + gcongr + omega + _ = M * inputSmallLog N ^ 257 := by ring + · intro key + rw [queryEarlierRequests_length_eq_cost depth index program values + (chargedGlobalQuery_value source target N P (inputSmallLog N) (40 * smallLogExponent N) + H (inputSmallLog N ^ 80) T S passes copies factor multiplier tau eta kappa delta group integer initial)] + exact computed_chargedGlobalQuery_earlier_reads source target N P H T S passes copies + factor multiplier tau eta kappa delta group integer initial hN hell hM hAmax hP hT hS hcopies hAmin key + + +include hN hell hM hP hT hS hcopies hAmin hAmax in + theorem chargedDependencyTree_widthWork_le + (hJ : J = intervalTreeDepth M source.length) + (hpasses : passes = computedSeedPassCount N + 1) + (root : ChargedPhysicalRequest M J target.length passes copies T S) + (hroot : depth root = J) (overhead : ℝ) (hoverhead : 0 ≤ overhead) + (hpath : ∀ j ≤ intervalTreeDepth M source.length, + (dependencyPathBudget j (computedDependencyIndexCount N) + (M * inputSmallLog N ^ 257) + (inputHeight N ^ (512 * (coarseExponent (inputSmallLog N) + 1))) : ℝ) ≤ + (M : ℝ) ^ j * overhead) : + ((chargedDependencyTree source target N P H T S passes copies factor multiplier + tau eta kappa delta group integer initial root).widthWork M source.length : ℝ) ≤ + (((intervalTreeDepth M source.length + 1) * source.length + + 4 * M * max 1 source.length : ℕ) : ℝ) * overhead := by + apply DependencyExpansion.widthWork_le M source.length _ _ (computedDependencyIndexCount N) + (by rw [hM]; exact (computed_branching_bounds N hN hell).1) _ + (chargedDependencyTree_valid source target N P H T S passes copies factor multiplier + tau eta kappa delta group integer initial hN hell hM hP hT hS hcopies hAmin hAmax root) + · exact (queryDependencyExpansion_depth depth index program + (chargedRequestList_progress source target N P H T S passes copies factor multiplier + tau eta kappa delta group integer initial) root).trans (hroot.trans hJ) + · have hi := chargedRequest_index_le root + have hb : index root ≤ computedDependencyIndexCount N := by + apply hi.trans_eq + unfold computedDependencyIndexCount + rw [hpasses, hT, hS] + exact (queryDependencyExpansion_index depth index program + (chargedRequestList_progress source target N P H T S passes copies factor multiplier + tau eta kappa delta group integer initial) root).le.trans hb + · exact hoverhead + · exact hpath + +end Expansion + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/ChargedGlobalQuery.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/ChargedGlobalQuery.lean new file mode 100644 index 0000000000000000000000000000000000000000..87e0b0fc7668a7be55ce417e10157dea75f3dba0 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/ChargedGlobalQuery.lean @@ -0,0 +1,184 @@ +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalBoundedQuery +import OAI.Combinatorics.EditApproximation.Geometry.ChargedSeedQuery +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! The global lazy program exposes coarse entries as ordinary memo requests. +Warmup uses these explicit seed reads; positive internal refinement uses the +proved finite table query, whose data reads are all earlier table entries. -/ + +namespace EditApproximation + + + + + +section Global + +variable {α : Type*} [DecidableEq α] {M J R : ℕ} [NeZero R] + (source target : List α) (N P F exponent H Q T S passes copies : ℕ) + (factor : ℕ → ℚ) (multiplier : ℕ → ℕ) (tau eta kappa delta : ℚ) + (group : ℕ → ℕ → PhysicalInternalNode M J → Fin R → CellGroupDraws M F Q) + (integer : ℕ → ℕ → PhysicalInternalNode M J → Fin R → ℕ → TargetInterval target.length → ℕ) + (initial : PhysicalEntry M J target.length → ℕ) + +def chargedRequestValue : ChargedPhysicalRequest M J target.length passes copies T S → ℚ + | .inl entry => initial entry + | .inr request => localRequestValue source target N P F exponent H Q T S copies factor multiplier + tau eta kappa delta group integer initial request.val + +theorem chargedSeedQuery_localValue + (parent : {r : PhysicalTableRequest M J target.length // r.Bounded passes copies T S}) + (q : TargetInterval target.length) : + (chargedSeedQuery N multiplier parent (parent.val.node, q)).value + (fun child => chargedRequestValue source target N P F exponent H Q T S passes copies + factor multiplier tau eta kappa delta group integer initial child.val) = + (localSeedSequence source target N P F exponent H Q T S copies factor multiplier + tau eta kappa delta group integer initial parent.val.pass (parent.val.node, q) : ℚ) := by + rw [chargedSeedQuery_value] + by_cases hp : parent.val.pass = 0 + · rw [ite_eq_left hp, hp] + rfl + · rw [ite_eq_right hp] + simp only [chargedRequestValue, chargedPreviousPass] + have hprev (copy : Fin copies) : previousPassRequest T S copy.val parent.val q = + PhysicalTableRequest.refinement (parent.val.pass - 1) copy.val parent.val.node T S q := rfl + simp only [hprev, localRequestValue_refinement] + obtain ⟨pass, heq⟩ := Nat.exists_eq_succ_of_ne_zero hp + simp only [heq, Nat.succ_eq_add_one, Nat.add_sub_cancel, localSeedSequence] + +theorem chargedWarmupQuery_value + (parent : {r : PhysicalTableRequest M J target.length // r.Bounded passes copies T S}) + (hindex : parent.val.index ≤ T) : + (chargedWarmupQuery source target N P F factor multiplier parent).value + (fun child => chargedRequestValue source target N P F exponent H Q T S passes copies + factor multiplier tau eta kappa delta group integer initial child.val) = + localRequestValue source target N P F exponent H Q T S copies factor multiplier + tau eta kappa delta group integer initial parent.val := by + have hreq : PhysicalTableRequest.warmup parent.val.pass parent.val.copy parent.val.node + parent.val.index parent.val.state = parent.val := rfl + rw [← hreq, localRequestValue_warmup source target N P F exponent H Q T S copies factor multiplier + tau eta kappa delta group integer initial _ _ _ _ hindex] + change (chargedWarmupQuery source target N P F factor multiplier parent).value _ = _ + have hseed := chargedSeedQuery_localValue source target N P F exponent H Q T S passes copies + factor multiplier tau eta kappa delta group integer initial parent + unfold chargedWarmupQuery + split_ifs with hz hbelow hshort + · rw [hz] + exact physicalInitialQuery_value_local source target N P F _ _ _ _ _ _ hseed + · rw [physicalLocalWarmup_terminal _ _ _ _ _ _ _ _ _ _ (Or.inr hshort)] + exact physicalInitialQuery_value_local source target N P F _ _ _ _ _ _ hseed + · have hi : parent.val.index = (parent.val.index - 1) + 1 := by omega + conv_rhs => rw [hi] + apply physicalWarmupStepQuery_value_local source target N P F _ _ _ _ _ + parent.val.node hbelow hshort (parent.val.index - 1) parent.val.state hseed + intro input + change localRequestValue source target N P F exponent H Q T S copies factor multiplier + tau eta kappa delta group integer initial + (PhysicalTableRequest.warmup parent.val.pass parent.val.copy + (physicalChild parent.val.node hbelow input.1) (parent.val.index - 1) input.2) = _ + exact localRequestValue_warmup source target N P F exponent H Q T S copies factor multiplier + tau eta kappa delta group integer initial _ _ _ _ (by omega) _ + · rw [physicalLocalWarmup_terminal _ _ _ _ _ _ _ _ _ _ (Or.inl hbelow)] + exact physicalInitialQuery_value_local source target N P F _ _ _ _ _ _ hseed + +def chargedGlobalQuery (request : ChargedPhysicalRequest M J target.length passes copies T S) : + FiniteQuery {child : ChargedPhysicalRequest M J target.length passes copies T S // + child.rank < request.rank} := + match request with + | .inl entry => .done (initial entry) + | .inr parent => + if parent.val.index ≤ T then chargedWarmupQuery source target N P F factor multiplier parent + else if parent.val.node.1.val < J then + if (physicalSourceInterval source.length parent.val.node).hi - + (physicalSourceInterval source.length parent.val.node).lo ≤ 1 then + physicalInitialQuery source target N P F (factor parent.val.pass) + (chargedSeedQuery N multiplier parent) (parent.val.node, parent.val.state) + else FiniteQuery.mapKeys (fun child => + ⟨Sum.inr child.val, ChargedPhysicalRequest.table_rank_lt parent child.val child.property⟩) + (physicalBoundedQuery source target N P F exponent H Q T S passes copies factor multiplier + tau eta kappa delta group integer initial parent) + else physicalInitialQuery source target N P F (factor parent.val.pass) + (chargedSeedQuery N multiplier parent) (parent.val.node, parent.val.state) + + +theorem localRequestValue_terminal (request : PhysicalTableRequest M J target.length) + (hterminal : ¬ request.node.1.val < J ∨ + (physicalSourceInterval source.length request.node).hi - + (physicalSourceInterval source.length request.node).lo ≤ 1) : + localRequestValue source target N P F exponent H Q T S copies factor multiplier + tau eta kappa delta group integer initial request = + stageInitial source target + (localSeedSequence source target N P F exponent H Q T S copies factor multiplier + tau eta kappa delta group integer initial request.pass) + N P F (factor request.pass) (request.node, request.state) := by + unfold localRequestValue unifiedPhysicalValue + dsimp only + split_ifs + · exact physicalLocalWarmup_terminal _ _ _ _ _ _ _ _ _ _ hterminal + · rw [physicalLocalRefinement] + rcases hterminal with hd | hw + · rw [dite_eq_right hd] + · split_ifs <;> rfl + +theorem chargedGlobalQuery_value (request : ChargedPhysicalRequest M J target.length passes copies T S) : + (chargedGlobalQuery source target N P F exponent H Q T S passes copies factor multiplier + tau eta kappa delta group integer initial request).value + (fun child => chargedRequestValue source target N P F exponent H Q T S passes copies + factor multiplier tau eta kappa delta group integer initial child.val) = + chargedRequestValue source target N P F exponent H Q T S passes copies + factor multiplier tau eta kappa delta group integer initial request := by + cases request with + | inl entry => rfl + | inr parent => + change _ = localRequestValue source target N P F exponent H Q T S copies factor multiplier + tau eta kappa delta group integer initial parent.val + unfold chargedGlobalQuery + dsimp only + split_ifs with hi hd hw + · exact chargedWarmupQuery_value source target N P F exponent H Q T S passes copies + factor multiplier tau eta kappa delta group integer initial parent hi + · rw [localRequestValue_terminal source target N P F exponent H Q T S copies factor multiplier + tau eta kappa delta group integer initial parent.val (Or.inr hw)] + exact physicalInitialQuery_value_local source target N P F _ _ _ _ _ _ + (chargedSeedQuery_localValue source target N P F exponent H Q T S passes copies + factor multiplier tau eta kappa delta group integer initial parent) + · rw [FiniteQuery.mapKeys_value] + exact physicalBoundedQuery_value source target N P F exponent H Q T S passes copies + factor multiplier tau eta kappa delta group integer initial parent + · rw [localRequestValue_terminal source target N P F exponent H Q T S copies factor multiplier + tau eta kappa delta group integer initial parent.val (Or.inl hd)] + exact physicalInitialQuery_value_local source target N P F _ _ _ _ _ _ + (chargedSeedQuery_localValue source target N P F exponent H Q T S passes copies + factor multiplier tau eta kappa delta group integer initial parent) + +def chargedMemoEvaluate (request : ChargedPhysicalRequest M J target.length passes copies T S) := + rankedMemoEvaluate ChargedPhysicalRequest.rank + (chargedGlobalQuery source target N P F exponent H Q T S passes copies factor multiplier + tau eta kappa delta group integer initial) + (ChargedPhysicalRequest.bits M J target.length passes copies T S) + ChargedPhysicalRequest.code request .empty + +theorem chargedMemoEvaluate_value (hM : 1 ≤ M) + (request : ChargedPhysicalRequest M J target.length passes copies T S) : + (chargedMemoEvaluate source target N P F exponent H Q T S passes copies factor multiplier + tau eta kappa delta group integer initial request).value = + chargedRequestValue source target N P F exponent H Q T S passes copies + factor multiplier tau eta kappa delta group integer initial request := by + unfold chargedMemoEvaluate + exact rankedMemoEvaluate_specification ChargedPhysicalRequest.rank + (chargedGlobalQuery source target N P F exponent H Q T S passes copies factor multiplier + tau eta kappa delta group integer initial) + (chargedRequestValue source target N P F exponent H Q T S passes copies factor multiplier + tau eta kappa delta group integer initial) + (chargedGlobalQuery_value source target N P F exponent H Q T S passes copies factor multiplier + tau eta kappa delta group integer initial) + _ _ (ChargedPhysicalRequest.code_injective hM) (ChargedPhysicalRequest.code_fits hM) request + +end Global + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/ChargedIndexCost.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/ChargedIndexCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..ad3466951e195080d0406471eb5523d841c474a4 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/ChargedIndexCost.lean @@ -0,0 +1,112 @@ +import OAI.Combinatorics.EditApproximation.Geometry.RefinementRankCost + +namespace OAI + +/-! The charged request index distinguishes previous passes and coarse +leaves. For internal refinement its two index classes are exactly the +current and earlier table-read counters. -/ + +namespace EditApproximation + +def chargedSameWeight {M J ny passes copies T S : ℕ} + (parent child : ChargedPhysicalRequest M J ny passes copies T S) : ℕ := + if ¬ child.index < parent.index then 1 else 0 + +def chargedEarlierWeight {M J ny passes copies T S : ℕ} + (parent child : ChargedPhysicalRequest M J ny passes copies T S) : ℕ := + if child.index < parent.index then 1 else 0 + +theorem chargedSameWeight_table {M J ny passes copies T S : ℕ} + (parent : {r : PhysicalTableRequest M J ny // r.Bounded passes copies T S}) : + chargedSameWeight (Sum.inr parent) = chargedTableWeight 0 + (fun child => if ¬ child.rank T S < parent.val.rank T S then 1 else 0) := by + funext child + cases child <;> simp only [chargedSameWeight, ChargedPhysicalRequest.index, chargedTableWeight, + Nat.zero_lt_succ, not_true_eq_false, ite_false, Nat.add_lt_add_iff_right] + +theorem chargedEarlierWeight_table {M J ny passes copies T S : ℕ} + (parent : {r : PhysicalTableRequest M J ny // r.Bounded passes copies T S}) : + chargedEarlierWeight (Sum.inr parent) = chargedTableWeight 1 + (fun child => if child.rank T S < parent.val.rank T S then 1 else 0) := by + funext child + cases child <;> simp only [chargedEarlierWeight, ChargedPhysicalRequest.index, chargedTableWeight, + Nat.zero_lt_succ, ite_true, Nat.add_lt_add_iff_right] + +section Costs + +variable {α : Type*} [DecidableEq α] {M J R : ℕ} [NeZero R] + (source target : List α) (N P F exponent H Q T S passes copies : ℕ) + (factor : ℕ → ℚ) (multiplier : ℕ → ℕ) (tau eta kappa delta : ℚ) + (group : ℕ → ℕ → PhysicalInternalNode M J → Fin R → CellGroupDraws M F Q) + (integer : ℕ → ℕ → PhysicalInternalNode M J → Fin R → ℕ → TargetInterval target.length → ℕ) + (initial : PhysicalEntry M J target.length → ℕ) + (parent : {r : PhysicalTableRequest M J target.length // r.Bounded passes copies T S}) + (hindex : T < parent.val.index) (hbelow : parent.val.node.1.val < J) + (hshort : ¬ (physicalSourceInterval source.length parent.val.node).hi - + (physicalSourceInterval source.length parent.val.node).lo ≤ 1) + +include hindex hbelow hshort + +theorem chargedGlobalQuery_current_cost : + (chargedGlobalQuery source target N P F exponent H Q T S passes copies factor multiplier + tau eta kappa delta group integer initial (Sum.inr parent)).cost + (fun child => chargedRequestValue source target N P F exponent H Q T S passes copies + factor multiplier tau eta kappa delta group integer initial child.val) + (fun child => chargedSameWeight (Sum.inr parent) child.val) = + (physicalRefinementDataRequestQuery source target N P F exponent H Q tau + (refinementFactor (factor parent.val.pass) F) eta kappa delta parent.val.pass parent.val.copy T S + (parent.val.index - T) (Nat.sub_pos_of_lt hindex) parent.val.node hbelow + (group parent.val.pass parent.val.copy ⟨parent.val.node, hbelow⟩ (Fin.ofNat R (parent.val.index - T - 1))) + (integer parent.val.pass parent.val.copy ⟨parent.val.node, hbelow⟩ (Fin.ofNat R (parent.val.index - T - 1))) + parent.val.state).cost + (fun child => localRequestValue source target N P F exponent H Q T S copies factor multiplier + tau eta kappa delta group integer initial child.val) + (fun child => physicalCurrentReadWeight (T + (parent.val.index - T)) child.val) := by + simp only [chargedSameWeight_table] + rw [chargedGlobalQuery_refinement_cost source target N P F exponent H Q T S passes copies + factor multiplier tau eta kappa delta group integer initial parent hindex hbelow hshort] + have hrank : (PhysicalTableRequest.refinement parent.val.pass parent.val.copy parent.val.node + T (parent.val.index - T) parent.val.state).rank T S = parent.val.rank T S := by + unfold PhysicalTableRequest.refinement PhysicalTableRequest.rank + dsimp only + congr 1 + omega + rw [← hrank] + exact physicalRefinementDataRequest_same_rank_cost source target N P F exponent H Q tau + (refinementFactor (factor parent.val.pass) F) eta kappa delta parent.val.pass parent.val.copy T S + (parent.val.index - T) (Nat.sub_pos_of_lt hindex) parent.val.node hbelow _ _ parent.val.state _ + +theorem chargedGlobalQuery_earlier_cost : + (chargedGlobalQuery source target N P F exponent H Q T S passes copies factor multiplier + tau eta kappa delta group integer initial (Sum.inr parent)).cost + (fun child => chargedRequestValue source target N P F exponent H Q T S passes copies + factor multiplier tau eta kappa delta group integer initial child.val) + (fun child => chargedEarlierWeight (Sum.inr parent) child.val) = + (physicalRefinementDataRequestQuery source target N P F exponent H Q tau + (refinementFactor (factor parent.val.pass) F) eta kappa delta parent.val.pass parent.val.copy T S + (parent.val.index - T) (Nat.sub_pos_of_lt hindex) parent.val.node hbelow + (group parent.val.pass parent.val.copy ⟨parent.val.node, hbelow⟩ (Fin.ofNat R (parent.val.index - T - 1))) + (integer parent.val.pass parent.val.copy ⟨parent.val.node, hbelow⟩ (Fin.ofNat R (parent.val.index - T - 1))) + parent.val.state).cost + (fun child => localRequestValue source target N P F exponent H Q T S copies factor multiplier + tau eta kappa delta group integer initial child.val) + (fun child => physicalEarlierReadWeight (T + (parent.val.index - T)) child.val) := by + simp only [chargedEarlierWeight_table] + rw [chargedGlobalQuery_refinement_cost source target N P F exponent H Q T S passes copies + factor multiplier tau eta kappa delta group integer initial parent hindex hbelow hshort] + have hrank : (PhysicalTableRequest.refinement parent.val.pass parent.val.copy parent.val.node + T (parent.val.index - T) parent.val.state).rank T S = parent.val.rank T S := by + unfold PhysicalTableRequest.refinement PhysicalTableRequest.rank + dsimp only + congr 1 + omega + rw [← hrank] + exact physicalRefinementDataRequest_earlier_rank_cost source target N P F exponent H Q tau + (refinementFactor (factor parent.val.pass) F) eta kappa delta parent.val.pass parent.val.copy T S + (parent.val.index - T) (Nat.sub_pos_of_lt hindex) parent.val.node hbelow _ _ parent.val.state _ + +end Costs + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/ChargedPhysicalRequest.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/ChargedPhysicalRequest.lean new file mode 100644 index 0000000000000000000000000000000000000000..b3278ab67a834cc8fc660da4892aad0ff54d92ca --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/ChargedPhysicalRequest.lean @@ -0,0 +1,100 @@ +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalRequestEncoding +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalWarmupQuery +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Coarse seed computations are explicit cache requests, alongside the +bounded warmup/refinement requests. Their rank is below every table request, +so first exposure of a same-node coarse entry is a genuine leaf of the lazy program. -/ + +namespace EditApproximation + + + +namespace ChargedPhysicalRequest + + + + + + + + + + def capacity (M J ny passes copies T S : ℕ) : ℕ := + 2 * (PhysicalTableRequest.entryCapacity M J ny + + PhysicalTableRequest.capacity M J ny passes copies T S) + + def bits (M J ny passes copies T S : ℕ) : ℕ := + Nat.clog 2 (capacity M J ny passes copies T S + 1) + + theorem code_injective {M J ny passes copies T S : ℕ} (hM : 1 ≤ M) : + Function.Injective (@code M J ny passes copies T S) := by + intro left right heq + cases left with + | inl left => + cases right with + | inl right => + have hentry : physicalEntryCode left = physicalEntryCode right := by + change 2 * physicalEntryCode left = 2 * physicalEntryCode right at heq + omega + exact congrArg Sum.inl (physicalEntryCode_injective hM hentry) + | inr right => + change 2 * physicalEntryCode left = 2 * PhysicalTableRequest.code copies T S right.val + 1 at heq + omega + | inr left => + cases right with + | inl right => + change 2 * PhysicalTableRequest.code copies T S left.val + 1 = 2 * physicalEntryCode right at heq + omega + | inr right => + have htable : PhysicalTableRequest.code copies T S left.val = + PhysicalTableRequest.code copies T S right.val := by + change 2 * PhysicalTableRequest.code copies T S left.val + 1 = + 2 * PhysicalTableRequest.code copies T S right.val + 1 at heq + omega + exact congrArg Sum.inr (PhysicalTableRequest.code_injective hM passes copies T S htable) + + theorem code_bound {M J ny passes copies T S : ℕ} (hM : 1 ≤ M) + (request : ChargedPhysicalRequest M J ny passes copies T S) : + code request < capacity M J ny passes copies T S := by + cases request with + | inl entry => + have h := physicalEntryCode_bound hM entry + change physicalEntryCode entry < PhysicalTableRequest.entryCapacity M J ny at h + simp only [code, capacity] + omega + | inr request => + have h := PhysicalTableRequest.code_bound hM passes copies T S request.val request.property + simp only [code, capacity] + omega + + theorem code_fits {M J ny passes copies T S : ℕ} (hM : 1 ≤ M) + (request : ChargedPhysicalRequest M J ny passes copies T S) : + code request < 2 ^ bits M J ny passes copies T S := + (code_bound hM request).trans_le + ((Nat.le_succ _).trans (Nat.le_pow_clog (by decide : 1 < 2) _)) + + theorem coarse_rank_lt {M J ny passes copies T S : ℕ} (entry : PhysicalEntry M J ny) + (request : {request : PhysicalTableRequest M J ny // request.Bounded passes copies T S}) + (hnode : entry.1 = request.val.node) : + rank (Sum.inl entry : ChargedPhysicalRequest M J ny passes copies T S) < rank (Sum.inr request) := by + change J - entry.1.1.val + 0 < request.val.remainingDepth + (request.val.rank T S + 1) + rw [hnode] + unfold PhysicalTableRequest.remainingDepth + omega + + theorem table_rank_lt {M J ny passes copies T S : ℕ} + (parent child : {request : PhysicalTableRequest M J ny // request.Bounded passes copies T S}) + (h : child.val.combinedRank T S < parent.val.combinedRank T S) : + rank (Sum.inr child : ChargedPhysicalRequest M J ny passes copies T S) < rank (Sum.inr parent) := by + simpa only [rank, depth, index, ← Nat.add_assoc, PhysicalTableRequest.combinedRank] using + Nat.add_lt_add_right h 1 + +end ChargedPhysicalRequest + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/ChargedQueryAsymptotics.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/ChargedQueryAsymptotics.lean new file mode 100644 index 0000000000000000000000000000000000000000..07dc9c81f96b161c35da1b9587a078891aaef887 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/ChargedQueryAsymptotics.lean @@ -0,0 +1,172 @@ +import OAI.Combinatorics.EditApproximation.Geometry.ChargedDependencyExpansion + +namespace OAI + +/-! Almost-linear bounds for the executed request tree. These count +requests and depth-weighted source widths, independently of accuracy events. +Local arithmetic and random-source costs are separate obligations. -/ + +namespace EditApproximation + +open Filter +open scoped Topology + +namespace DependencyExpansion + +theorem nodeCount_le_depthWeightedCount (weight : ℕ → ℕ) + (hweight : ∀ d, 1 ≤ weight d) (tree : DependencyExpansion) : + tree.nodeCount ≤ tree.depthWeightedCount weight := by + induction tree with + | node d k m n same earlier ihs ihe => + exact Nat.add_le_add (Nat.add_le_add (hweight d) (Finset.sum_le_sum fun i _ => ihs i)) + (Finset.sum_le_sum fun i _ => ihe i) + +theorem nodeCount_le_widthWork (M n : ℕ) (tree : DependencyExpansion) : + tree.nodeCount ≤ tree.widthWork M n := + nodeCount_le_depthWeightedCount _ (fun _ => by omega) tree + +end DependencyExpansion + +/-- The deterministic balanced-tree prefactor is only `N` times a fixed +polynomial in the logarithmic height. -/ +theorem computed_width_prefactor_le (N n : ℕ) (hN : 0 < N) (hn : n ≤ N) + (hell : 200 ≤ inputSmallLog N) (hH : 105 ≤ inputHeight N) : + (intervalTreeDepth (integerParameters N).M n + 1) * n + + 4 * (integerParameters N).M * max 1 n ≤ (N + 2) * inputHeight N ^ 2 := by + have hdepth := computed_tree_depth_bound N n hN hn hell + have hellone : 1 ≤ inputSmallLog N := by omega + have hJ : intervalTreeDepth (integerParameters N).M n ≤ 100 * inputHeight N := by + have hm := Nat.mul_le_mul_left (intervalTreeDepth (integerParameters N).M n) hellone + omega + have hM : (integerParameters N).M ≤ inputHeight N := by + change 2 ^ (heightExponent N / 20) ≤ 2 ^ heightExponent N + exact Nat.pow_le_pow_right (by decide : 0 < (2 : ℕ)) (Nat.div_le_self _ _) + have hx : max 1 n ≤ N + 2 := max_le (by omega) (by omega) + calc + _ ≤ (100 * inputHeight N + 1) * (N + 2) + + 4 * inputHeight N * (N + 2) := by gcongr; omega + _ ≤ 105 * inputHeight N * (N + 2) := by nlinarith + _ ≤ (N + 2) * inputHeight N ^ 2 := by + have hsquare : 105 * inputHeight N ≤ inputHeight N ^ 2 := by nlinarith + simpa only [Nat.mul_comm] using Nat.mul_le_mul_right (N + 2) hsquare + +/-- Fixed height-polynomial overheads can be included in the executed +width-work estimate without changing its almost-linear exponent. -/ +theorem computed_weighted_widthWork_near_linear (C : ℕ) (epsilon : ℝ) + (hepsilon : 0 < epsilon) : + ∀ᶠ N in atTop, ∀ n ≤ N, ∀ tree : DependencyExpansion, + tree.Valid ((integerParameters N).M * inputSmallLog N ^ 257) + (inputHeight N ^ (512 * (coarseExponent (inputSmallLog N) + 1))) → + tree.depth = intervalTreeDepth (integerParameters N).M n → + tree.rank ≤ computedDependencyIndexCount N → + (tree.widthWork (integerParameters N).M n : ℝ) * (inputHeight N : ℝ) ^ C ≤ + (N + 2 : ℝ) ^ (1 + epsilon) := by + have hlog : Tendsto (fun N => Real.log (inputHeight N : ℝ) / inputHeight N) + atTop (𝓝 0) := + Real.isLittleO_log_id_atTop.tendsto_div_nhds_zero.comp inputHeight_real_tendsto + have hlimit := (computedDependencyOverheadExponent_tendsto 257 512).add + (hlog.const_mul (C + 2 : ℝ)) + simp only [mul_zero, zero_add] at hlimit + have hfinal := sublinear_height_near_linear + (fun N => computedDependencyOverheadExponent 257 512 N + + (C + 2 : ℝ) * Real.log (inputHeight N : ℝ)) (by + convert hlimit using 1 + ext N + ring) epsilon hepsilon + filter_upwards [hfinal, eventually_ge_atTop 1, + inputSmallLog_tendsto.eventually (eventually_ge_atTop 200), + inputHeight_real_tendsto.eventually (eventually_ge_atTop 105)] with N hfinal hN hell hH + intro n hn tree hv hd hk + have hHnat : 105 ≤ inputHeight N := by exact_mod_cast hH + have hpref := computed_width_prefactor_le N n (by omega) hn hell hHnat + have hw := DependencyExpansion.widthWork_le (integerParameters N).M n _ _ _ + (computed_branching_bounds N (by omega) hell).1 tree hv hd hk + (Real.exp (computedDependencyOverheadExponent 257 512 N)) (Real.exp_nonneg _) (by + intro j hj + exact computed_dependency_path_envelope N 257 512 j + (hj.trans (intervalTreeDepth_le_computedMax N n hn))) + have hprefR : (((intervalTreeDepth (integerParameters N).M n + 1) * n + + 4 * (integerParameters N).M * max 1 n : ℕ) : ℝ) ≤ + (N + 2 : ℝ) * (inputHeight N : ℝ) ^ 2 := by exact_mod_cast hpref + calc + _ ≤ ((N + 2 : ℝ) * (inputHeight N : ℝ) ^ 2 * + Real.exp (computedDependencyOverheadExponent 257 512 N)) * + (inputHeight N : ℝ) ^ C := by + exact mul_le_mul_of_nonneg_right + (hw.trans (mul_le_mul_of_nonneg_right hprefR (Real.exp_nonneg _))) (by positivity) + _ = (N + 2 : ℝ) * Real.exp (computedDependencyOverheadExponent 257 512 N + + (C + 2 : ℝ) * Real.log (inputHeight N : ℝ)) := by + rw [Real.exp_add] + have hexp : Real.exp ((C + 2 : ℝ) * Real.log (inputHeight N : ℝ)) = + (inputHeight N : ℝ) ^ (C + 2) := by + simpa only [Nat.cast_add, Nat.cast_ofNat] using + (nat_pow_eq_exp_log (inputHeight N) (C + 2) (by omega)).symm + rw [hexp, pow_add] + ring + _ ≤ _ := hfinal + +section Charged + +variable {α : Type*} [DecidableEq α] {M J R : ℕ} [NeZero R] + (source target : List α) (N P H T S passes copies : ℕ) + (factor : ℕ → ℚ) (multiplier : ℕ → ℕ) (tau eta kappa delta : ℚ) + (group : ℕ → ℕ → PhysicalInternalNode M J → Fin R → + CellGroupDraws M (inputSmallLog N) (inputSmallLog N ^ 80)) + (integer : ℕ → ℕ → PhysicalInternalNode M J → Fin R → ℕ → TargetInterval target.length → ℕ) + (initial : PhysicalEntry M J target.length → ℕ) + +local notation "program" => chargedGlobalQuery source target N P (inputSmallLog N) + (40 * smallLogExponent N) H (inputSmallLog N ^ 80) T S passes copies factor multiplier + tau eta kappa delta group integer initial +local notation "depth" => @ChargedPhysicalRequest.depth M J target.length passes copies T S +local notation "index" => @ChargedPhysicalRequest.index M J target.length passes copies T S + +/-- The instrumented memo evaluator makes no more requests than there +are nodes in its exact uncached expansion. -/ +theorem chargedMemoEvaluate_requests_le_widthWork (hM : 1 ≤ M) + (root : ChargedPhysicalRequest M J target.length passes copies T S) : + (chargedMemoEvaluate source target N P (inputSmallLog N) (40 * smallLogExponent N) + H (inputSmallLog N ^ 80) T S passes copies factor multiplier tau eta kappa delta + group integer initial root).requests ≤ + (chargedDependencyTree source target N P H T S passes copies factor multiplier + tau eta kappa delta group integer initial root).widthWork M source.length := by + calc + _ ≤ rankedUncachedCalls ChargedPhysicalRequest.rank program root := + rankedMemoEvaluate_requests_le _ _ _ _ + (ChargedPhysicalRequest.code_injective hM) (ChargedPhysicalRequest.code_fits hM) + root .empty (memoSound_empty _ _ _) + _ = (chargedDependencyTree source target N P H T S passes copies factor multiplier + tau eta kappa delta group integer initial root).nodeCount := by + exact (queryDependencyExpansion_nodes depth index program + (chargedRequestList_progress source target N P H T S passes copies factor multiplier + tau eta kappa delta group integer initial) root).symm + _ ≤ _ := DependencyExpansion.nodeCount_le_widthWork _ _ _ + +theorem chargedDependencyTree_depth + (root : ChargedPhysicalRequest M J target.length passes copies T S) : + (chargedDependencyTree source target N P H T S passes copies factor multiplier + tau eta kappa delta group integer initial root).depth = depth root := + queryDependencyExpansion_depth depth index program + (chargedRequestList_progress source target N P H T S passes copies factor multiplier + tau eta kappa delta group integer initial) root + +theorem chargedDependencyTree_index_le + (hpasses : passes = computedSeedPassCount N + 1) + (hT : T = (integerParameters N).T) (hS : S = (integerParameters N).S) + (root : ChargedPhysicalRequest M J target.length passes copies T S) : + (chargedDependencyTree source target N P H T S passes copies factor multiplier + tau eta kappa delta group integer initial root).rank ≤ computedDependencyIndexCount N := by + rw [show (chargedDependencyTree source target N P H T S passes copies factor multiplier + tau eta kappa delta group integer initial root).rank = index root from + queryDependencyExpansion_index depth index program + (chargedRequestList_progress source target N P H T S passes copies factor multiplier + tau eta kappa delta group integer initial) root] + have hi := chargedRequest_index_le root + apply hi.trans_eq + simp only [computedDependencyIndexCount, hpasses, hT, hS] + +end Charged + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/ChargedQueryProgress.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/ChargedQueryProgress.lean new file mode 100644 index 0000000000000000000000000000000000000000..474087da56abf647073d9b439ebbb902653cf507 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/ChargedQueryProgress.lean @@ -0,0 +1,128 @@ +import OAI.Combinatorics.EditApproximation.Geometry.ChargedGlobalQuery +import OAI.Combinatorics.EditApproximation.Geometry.GlobalQueryProgress +import OAI.Combinatorics.EditApproximation.Queries.QueryDependencyExpansion + +namespace OAI + +/-! Every actual charged edge either descends at the current index or +uses a strictly earlier index without moving to an ancestor. Coarse +leaves retain their physical depth for source-width accounting. -/ + +namespace EditApproximation + +namespace ChargedPhysicalRequest + +def DependencyProgress {M J ny passes copies T S : ℕ} + (parent child : ChargedPhysicalRequest M J ny passes copies T S) : Prop := + (child.depth < parent.depth ∧ child.index ≤ parent.index) ∨ + (child.depth ≤ parent.depth ∧ child.index < parent.index) + +theorem table_progress {M J ny passes copies T S : ℕ} + (parent child : {r : PhysicalTableRequest M J ny // r.Bounded passes copies T S}) + (h : PhysicalTableRequest.DependencyProgress T S parent.val child.val) : + DependencyProgress (Sum.inr parent) (Sum.inr child) := by + rcases h with h | h + · exact Or.inl ⟨h.1, Nat.add_le_add_right h.2 1⟩ + · exact Or.inr ⟨h.1, Nat.add_lt_add_right h.2 1⟩ + +end ChargedPhysicalRequest + +theorem chargedSeedQuery_keys_earlier {M J ny passes copies T S : ℕ} + (N : ℕ) (multiplier : ℕ → ℕ) + (parent : {r : PhysicalTableRequest M J ny // r.Bounded passes copies T S}) + (state : PhysicalEntry M J ny) (oracle) : + ∀ key ∈ (chargedSeedQuery N multiplier parent state).keys oracle, + key.val.depth ≤ ChargedPhysicalRequest.depth (Sum.inr parent) ∧ + key.val.index < ChargedPhysicalRequest.index (Sum.inr parent) := by + unfold chargedSeedQuery + split_ifs with hn hp + · intro key hk + simp only [FiniteQuery.keys, List.mem_singleton] at hk + subst key + constructor + · change J - state.1.1.val ≤ J - parent.val.node.1.val + rw [hn] + · change 0 < parent.val.rank T S + 1 + omega + · apply FiniteQuery.keys_all_collect + · intro copy _ key hk + simp only [chargedPreviousRead, FiniteQuery.keys, List.mem_singleton] at hk + subst key + have h := previousPassRequest_progress T S copy.val parent.val (Nat.pos_of_ne_zero hp) state.2 + exact ⟨h.1.le, Nat.add_lt_add_right h.2 1⟩ + · intro values key hk + exact False.elim (List.not_mem_nil hk) + · intro key hk + exact False.elim (List.not_mem_nil hk) + +theorem chargedWarmupQuery_keys_earlier {α : Type*} [DecidableEq α] {M J passes copies T S : ℕ} + (source target : List α) (N P F : ℕ) (factor : ℕ → ℚ) (multiplier : ℕ → ℕ) + (parent : {r : PhysicalTableRequest M J target.length // r.Bounded passes copies T S}) (oracle) : + ∀ key ∈ (chargedWarmupQuery source target N P F factor multiplier parent).keys oracle, + key.val.depth ≤ ChargedPhysicalRequest.depth (Sum.inr parent) ∧ + key.val.index < ChargedPhysicalRequest.index (Sum.inr parent) := by + have hseed (q : TargetInterval target.length) := + chargedSeedQuery_keys_earlier N multiplier parent (parent.val.node, q) oracle + unfold chargedWarmupQuery + split_ifs with hz hb hs + · exact physicalInitialQuery_keys_all source target N P F _ _ _ _ oracle _ hseed + · exact physicalInitialQuery_keys_all source target N P F _ _ _ _ oracle _ hseed + · unfold physicalWarmupStepQuery + apply localWarmupStepQuery_keys_all + · intro q + exact physicalInitialQuery_keys_all source target N P F _ _ _ _ oracle _ hseed + · intro input key hk + simp only [chargedWarmupChild, FiniteQuery.keys, List.mem_singleton] at hk + subst key + have h := PhysicalTableRequest.warmup_previous_child_progress parent.val.pass parent.val.copy T S + parent.val.index parent.val.node hb input.1 parent.val.state input.2 (Nat.pos_of_ne_zero hz) + exact ⟨h.1.le, Nat.add_lt_add_right h.2 1⟩ + · exact physicalInitialQuery_keys_all source target N P F _ _ _ _ oracle _ hseed + +section Global + +variable {α : Type*} [DecidableEq α] {M J R : ℕ} [NeZero R] + (source target : List α) (N P F exponent H Q T S passes copies : ℕ) + (factor : ℕ → ℚ) (multiplier : ℕ → ℕ) (tau eta kappa delta : ℚ) + (group : ℕ → ℕ → PhysicalInternalNode M J → Fin R → CellGroupDraws M F Q) + (integer : ℕ → ℕ → PhysicalInternalNode M J → Fin R → ℕ → TargetInterval target.length → ℕ) + (initial : PhysicalEntry M J target.length → ℕ) + +theorem chargedGlobalQuery_keys_progress (request : ChargedPhysicalRequest M J target.length passes copies T S) : + ∀ key ∈ (chargedGlobalQuery source target N P F exponent H Q T S passes copies factor multiplier + tau eta kappa delta group integer initial request).keys + (fun child => chargedRequestValue source target N P F exponent H Q T S passes copies + factor multiplier tau eta kappa delta group integer initial child.val), + ChargedPhysicalRequest.DependencyProgress request key.val := by + cases request with + | inl entry => + intro key hk + exact False.elim (List.not_mem_nil hk) + | inr parent => + unfold chargedGlobalQuery + dsimp only + split_ifs with hi hb hs + · intro key hk + exact Or.inr (chargedWarmupQuery_keys_earlier source target N P F factor multiplier parent _ key hk) + · intro key hk + apply Or.inr + apply physicalInitialQuery_keys_all source target N P F _ _ _ _ _ _ _ key hk + intro q + exact chargedSeedQuery_keys_earlier N multiplier parent (parent.val.node, q) _ + · rw [FiniteQuery.mapKeys_keys] + intro key hk + obtain ⟨child, hc, rfl⟩ := List.mem_map.mp hk + exact ChargedPhysicalRequest.table_progress parent child.val + (physicalBoundedQuery_keys_progress source target N P F exponent H Q T S passes copies factor multiplier + tau eta kappa delta group integer initial parent child hc) + · intro key hk + apply Or.inr + apply physicalInitialQuery_keys_all source target N P F _ _ _ _ _ _ _ key hk + intro q + exact chargedSeedQuery_keys_earlier N multiplier parent (parent.val.node, q) _ + +end Global + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/ChargedRandomCoarseKeys.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/ChargedRandomCoarseKeys.lean new file mode 100644 index 0000000000000000000000000000000000000000..a4e850876d1e6a9fa8df2bdd9bd23ac4138db439 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/ChargedRandomCoarseKeys.lean @@ -0,0 +1,85 @@ +import OAI.Combinatorics.EditApproximation.Geometry.SourceRankedKeys +import OAI.Combinatorics.EditApproximation.Geometry.ChargedRandomCoarseOracle +import OAI.Combinatorics.EditApproximation.Geometry.ChargedRandomMemo + +namespace OAI + +namespace EditApproximation + +section Keys + +variable {σ α : Type*} [DecidableEq α] {M J R : ℕ} [NeZero M] [NeZero R] + (source target : List α) (N P F exponent H Q T S passes copies : ℕ) + (factor : ℕ → ℚ) (multiplier : ℕ → ℕ) (tau eta kappa delta : ℚ) + (readGroup : ℕ → ℕ → PhysicalInternalNode M J → Fin R → GroupScalarKey M F Q → FiniteQuery σ) + (readInteger : ℕ → ℕ → PhysicalInternalNode M J → Fin R → + (ℕ × TargetInterval target.length) → ℕ → FiniteQuery σ) + (sourceAnswer : σ → ℚ) (initial : PhysicalEntry M J target.length → ℕ) + +local notation "mixed" => chargedRandomGlobalQuery source target N P F exponent H Q T S + passes copies factor multiplier tau eta kappa delta readGroup readInteger initial +local notation "program" => SourceRanked.projectedBody ChargedPhysicalRequest.rank mixed sourceAnswer +local notation "coarse" => chargedRandomCoarseQuery source target N P F exponent H Q T S + passes copies factor multiplier tau eta kappa delta readGroup readInteger sourceAnswer + + theorem chargedRandomCoarseQuery_uncached_keys + (root : ChargedPhysicalRequest M J target.length passes copies T S) + (entry : PhysicalEntry M J target.length) + (hentry : Sum.inl entry ∈ rankedUncachedKeys ChargedPhysicalRequest.rank program root) : + entry ∈ (coarse root).keys (fun entry => (initial entry : ℚ)) := by + have hall : ∀ level root, root.rank = level → ∀ entry, + Sum.inl entry ∈ rankedUncachedKeys ChargedPhysicalRequest.rank program root → + entry ∈ (coarse root).keys (fun entry => (initial entry : ℚ)) := by + intro level + induction level using Nat.strong_induction_on with + | h level ih => + intro root hlevel entry he + cases root with + | inl base => + rw [rankedUncachedKeys] at he + simp only [SourceRanked.projectedBody, chargedRandomGlobalQuery, + FiniteQuery.eraseSources, FiniteQuery.keys, List.flatMap_nil, List.mem_cons, + List.not_mem_nil, or_false, Sum.inl.injEq] at he + subst entry + rw [chargedRandomCoarseQuery] + exact List.mem_cons_self + | inr parent => + rw [rankedUncachedKeys] at he + rcases List.mem_cons.mp he with he | he + · cases he + obtain ⟨child, hc, he⟩ := List.mem_flatMap.mp he + rw [chargedRandomCoarseQuery, FiniteQuery.substitute_keys] + apply List.mem_flatMap.mpr + refine ⟨child, ?_, ih child.val.rank (hlevel ▸ child.property) child.val rfl entry he⟩ + have hv (child) := chargedRandomCoarseQuery_value source target N P F exponent H Q T S + passes copies factor multiplier tau eta kappa delta readGroup readInteger sourceAnswer initial child + simp_rw [hv] + unfold SourceRanked.projectedBody + rw [chargedRandomGlobalQuery_table_initial_independent source target N P F exponent H Q T S + passes copies factor multiplier tau eta kappa delta readGroup readInteger (fun _ => 0) initial parent] + exact hc + exact hall root.rank root rfl entry hentry + + theorem chargedRandomMemo_coarse_key + (values : ChargedPhysicalRequest M J target.length passes copies T S → ℚ) + (hbody : ∀ key, (mixed key).value (Sum.elim sourceAnswer (fun next => values next.val)) = values key) + (bits : ℕ) (encode : Sum σ (ChargedPhysicalRequest M J target.length passes copies T S) → ℕ) + (hinjective : Function.Injective encode) (hbounded : ∀ key, encode key < 2 ^ bits) + (root : ChargedPhysicalRequest M J target.length passes copies T S) + (entry : PhysicalEntry M J target.length) + (hentry : Sum.inr (Sum.inl entry) ∈ + (chargedRandomMemoEvaluate source target N P F exponent H Q T S passes copies factor multiplier + tau eta kappa delta readGroup readInteger initial sourceAnswer bits encode root).freshKeys) : + entry ∈ (coarse root).keys (fun entry => (initial entry : ℚ)) := by + apply chargedRandomCoarseQuery_uncached_keys source target N P F exponent H Q T S passes copies + factor multiplier tau eta kappa delta readGroup readInteger sourceAnswer initial root entry + apply SourceRanked.uncachedKeys_table_mem ChargedPhysicalRequest.rank mixed sourceAnswer values hbody root + (Sum.inl entry) + exact rankedMemoEvaluate_freshKeys_mem _ _ bits encode hinjective hbounded (.inr root) .empty + (memoSound_empty _ _ _) (.inr (.inl entry)) hentry + +end Keys + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/ChargedRandomCoarseOracle.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/ChargedRandomCoarseOracle.lean new file mode 100644 index 0000000000000000000000000000000000000000..41e21068ef8934c7c82b6e24173d66e2ee14b840 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/ChargedRandomCoarseOracle.lean @@ -0,0 +1,105 @@ +import OAI.Combinatorics.EditApproximation.Geometry.ChargedRandomGlobalQuery +import OAI.Combinatorics.EditApproximation.Geometry.ChargedCoarseOracle +import OAI.Combinatorics.EditApproximation.Geometry.SourceRankedWork + +namespace OAI + +/-! A fixed accepted source family leaves a nonanticipating coarse query: +coarse values enter only when the corresponding leaf is requested. -/ + +namespace EditApproximation + +section Coarse + +variable {σ α : Type*} [DecidableEq α] {M J R : ℕ} [NeZero M] [NeZero R] + (source target : List α) (N P F exponent H Q T S passes copies : ℕ) + (factor : ℕ → ℚ) (multiplier : ℕ → ℕ) (tau eta kappa delta : ℚ) + (readGroup : ℕ → ℕ → PhysicalInternalNode M J → Fin R → GroupScalarKey M F Q → FiniteQuery σ) + (readInteger : ℕ → ℕ → PhysicalInternalNode M J → Fin R → (ℕ × TargetInterval target.length) → ℕ → FiniteQuery σ) + (sourceAnswer : σ → ℚ) + +theorem physicalRandomGlobalQuery_refinement_initial_independent + (left right : PhysicalEntry M J target.length → ℕ) + (parent : PhysicalTableRequest M J target.length) + (hi : ¬ parent.index ≤ T) (hd : parent.node.1.val < J) + (hw : ¬ (physicalSourceInterval source.length parent.node).hi - + (physicalSourceInterval source.length parent.node).lo ≤ 1) : + physicalRandomGlobalQuery source target N P F exponent H Q T S copies factor multiplier + tau eta kappa delta readGroup readInteger left parent = + physicalRandomGlobalQuery source target N P F exponent H Q T S copies factor multiplier + tau eta kappa delta readGroup readInteger right parent := by + unfold physicalRandomGlobalQuery + rw [dite_eq_left ⟨by omega, hd, hw⟩, dite_eq_left ⟨by omega, hd, hw⟩] + +/-- Coarse answers enter the charged program only at coarse leaves. -/ +theorem chargedRandomGlobalQuery_table_initial_independent + (left right : PhysicalEntry M J target.length → ℕ) + (parent : {request : PhysicalTableRequest M J target.length // request.Bounded passes copies T S}) : + chargedRandomGlobalQuery source target N P F exponent H Q T S passes copies factor multiplier + tau eta kappa delta readGroup readInteger left (.inr parent) = + chargedRandomGlobalQuery source target N P F exponent H Q T S passes copies factor multiplier + tau eta kappa delta readGroup readInteger right (.inr parent) := by + unfold chargedRandomGlobalQuery + dsimp only + split_ifs with hi hd hw + · rfl + · rfl + · unfold physicalRandomBoundedQuery SourceRanked.restrictBody + rw [physicalRandomGlobalQuery_refinement_initial_independent source target N P F exponent H Q T S + copies factor multiplier tau eta kappa delta readGroup readInteger left right parent.val hi hd hw] + · rfl + +/-- The flattened program receives each coarse answer from an explicit +external read. The constant zero here is never used as a seed answer. -/ +noncomputable def chargedRandomCoarseQuery (root : ChargedPhysicalRequest M J target.length passes copies T S) : + FiniteQuery (PhysicalEntry M J target.length) := + match root with + | .inl entry => .read entry FiniteQuery.done + | .inr parent => + (SourceRanked.projectedBody ChargedPhysicalRequest.rank + (chargedRandomGlobalQuery source target N P F exponent H Q T S passes copies factor multiplier + tau eta kappa delta readGroup readInteger (fun _ => 0)) sourceAnswer (.inr parent)).substitute + (fun child => chargedRandomCoarseQuery child.val) +termination_by root.rank +decreasing_by exact child.property + +theorem chargedRandomCoarseQuery_value + (initial : PhysicalEntry M J target.length → ℕ) + (root : ChargedPhysicalRequest M J target.length passes copies T S) : + (chargedRandomCoarseQuery source target N P F exponent H Q T S passes copies factor multiplier + tau eta kappa delta readGroup readInteger sourceAnswer root).value (fun entry => (initial entry : ℚ)) = + rankedProgramValue ChargedPhysicalRequest.rank + (SourceRanked.projectedBody ChargedPhysicalRequest.rank + (chargedRandomGlobalQuery source target N P F exponent H Q T S passes copies factor multiplier + tau eta kappa delta readGroup readInteger initial) sourceAnswer) root := by + have hall : ∀ level root, root.rank = level → + (chargedRandomCoarseQuery source target N P F exponent H Q T S passes copies factor multiplier + tau eta kappa delta readGroup readInteger sourceAnswer root).value (fun entry => (initial entry : ℚ)) = + rankedProgramValue ChargedPhysicalRequest.rank + (SourceRanked.projectedBody ChargedPhysicalRequest.rank + (chargedRandomGlobalQuery source target N P F exponent H Q T S passes copies factor multiplier + tau eta kappa delta readGroup readInteger initial) sourceAnswer) root := by + intro level + induction level using Nat.strong_induction_on with + | h level ih => + intro root hlevel + cases root with + | inl entry => + rw [chargedRandomCoarseQuery, rankedProgramValue] + rfl + | inr parent => + rw [chargedRandomCoarseQuery, FiniteQuery.substitute_value, rankedProgramValue] + unfold SourceRanked.projectedBody + rw [ + chargedRandomGlobalQuery_table_initial_independent source target N P F exponent H Q T S passes copies + factor multiplier tau eta kappa delta readGroup readInteger (fun _ => 0) initial parent] + congr 1 + funext child + exact ih child.val.rank (hlevel ▸ child.property) child.val rfl + exact hall root.rank root rfl + +end Coarse + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/ChargedRandomCoarseWork.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/ChargedRandomCoarseWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..39d763197f1a966be11f527fac62cfe5546d31c0 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/ChargedRandomCoarseWork.lean @@ -0,0 +1,144 @@ +import OAI.Combinatorics.EditApproximation.Geometry.ChargedRandomCoarseOracle +import OAI.Combinatorics.EditApproximation.Queries.QueryWeightedWork +import OAI.Combinatorics.EditApproximation.Geometry.ChargedRandomExpansion +import OAI.Combinatorics.EditApproximation.Probability.FreshCoordinateCost + +namespace OAI + +namespace EditApproximation + +section Coarse + +variable {σ α : Type*} [DecidableEq α] {M J R : ℕ} [NeZero M] [NeZero R] + (source target : List α) (N P H T S passes copies : ℕ) + (factor : ℕ → ℚ) (multiplier : ℕ → ℕ) (tau eta kappa delta : ℚ) + (readGroup : ℕ → ℕ → PhysicalInternalNode M J → Fin R → + GroupScalarKey M (inputSmallLog N) (inputSmallLog N ^ 80) → FiniteQuery σ) + (readInteger : ℕ → ℕ → PhysicalInternalNode M J → Fin R → + (ℕ × TargetInterval target.length) → ℕ → FiniteQuery σ) + (sourceAnswer : σ → ℚ) + (initial : PhysicalEntry M J target.length → ℕ) + +local notation "program" => SourceRanked.projectedBody ChargedPhysicalRequest.rank + (chargedRandomGlobalQuery source target N P (inputSmallLog N) + (40 * smallLogExponent N) H (inputSmallLog N ^ 80) T S passes copies factor multiplier + tau eta kappa delta readGroup readInteger initial) sourceAnswer +local notation "coarse" => chargedRandomCoarseQuery source target N P (inputSmallLog N) + (40 * smallLogExponent N) H (inputSmallLog N ^ 80) T S passes copies factor multiplier + tau eta kappa delta readGroup readInteger sourceAnswer +local notation "depth" => @ChargedPhysicalRequest.depth M J target.length passes copies T S +local notation "index" => @ChargedPhysicalRequest.index M J target.length passes copies T S + + theorem chargedRandomCoarseQuery_cost_le (weight : ℕ → ℕ) + (root : ChargedPhysicalRequest M J target.length passes copies T S) : + (coarse root).cost (fun entry => (initial entry : ℚ)) + (fun entry => weight (J - entry.1.1.val)) ≤ + rankedUncachedWork ChargedPhysicalRequest.rank program (fun request => weight (depth request)) root := by + have hall : ∀ level root, root.rank = level → + (coarse root).cost (fun entry => (initial entry : ℚ)) + (fun entry => weight (J - entry.1.1.val)) ≤ + rankedUncachedWork ChargedPhysicalRequest.rank program (fun request => weight (depth request)) root := by + intro level + induction level using Nat.strong_induction_on with + | h level ih => + intro root hlevel + cases root with + | inl entry => + rw [chargedRandomCoarseQuery, rankedUncachedWork] + simp only [FiniteQuery.cost, SourceRanked.projectedBody, chargedRandomGlobalQuery, FiniteQuery.eraseSources, ChargedPhysicalRequest.depth, Nat.zero_add, + Nat.add_zero, le_refl] + | inr parent => + rw [chargedRandomCoarseQuery, FiniteQuery.substitute_cost] + have hv (child) := chargedRandomCoarseQuery_value source target N P (inputSmallLog N) + (40 * smallLogExponent N) H (inputSmallLog N ^ 80) T S passes copies factor multiplier + tau eta kappa delta readGroup readInteger sourceAnswer initial child + simp_rw [hv] + unfold SourceRanked.projectedBody + rw [chargedRandomGlobalQuery_table_initial_independent source target N P (inputSmallLog N) + (40 * smallLogExponent N) H (inputSmallLog N ^ 80) T S passes copies factor multiplier + tau eta kappa delta readGroup readInteger (fun _ => 0) initial parent] + rw [rankedUncachedWork] + apply (FiniteQuery.cost_mono_weights _ _ _ _ ?_).trans (Nat.le_add_right _ _) + intro child + exact ih child.val.rank (hlevel ▸ child.property) child.val rfl + exact hall root.rank root rfl + +variable + (group : ℕ → ℕ → PhysicalInternalNode M J → Fin R → + CellGroupDraws M (inputSmallLog N) (inputSmallLog N ^ 80)) + (integer : ℕ → ℕ → PhysicalInternalNode M J → Fin R → ℕ → TargetInterval target.length → ℕ) + +local notation "values" => chargedRequestValue source target N P (inputSmallLog N) + (40 * smallLogExponent N) H (inputSmallLog N ^ 80) T S passes copies factor multiplier + tau eta kappa delta group integer initial + +variable (hbody : ∀ (request : ChargedPhysicalRequest M J target.length passes copies T S), + (chargedRandomGlobalQuery source target N P (inputSmallLog N) + (40 * smallLogExponent N) H (inputSmallLog N ^ 80) T S passes copies factor multiplier + tau eta kappa delta readGroup readInteger initial request).value + (Sum.elim sourceAnswer (fun child : {child : ChargedPhysicalRequest M J target.length passes copies T S // + child.rank < request.rank} => chargedRequestValue source target N P (inputSmallLog N) + (40 * smallLogExponent N) H (inputSmallLog N ^ 80) T S passes copies factor multiplier + tau eta kappa delta group integer initial child.val)) = + chargedRequestValue source target N P (inputSmallLog N) + (40 * smallLogExponent N) H (inputSmallLog N ^ 80) T S passes copies factor multiplier + tau eta kappa delta group integer initial request) + +include hbody + theorem chargedRandomCoarseQuery_width_cost_le + (root : ChargedPhysicalRequest M J target.length passes copies T S) + (hroot : depth root = J) : + (coarse root).cost (fun entry => (initial entry : ℚ)) + (fun entry => 1 + source.length ⌈/⌉ M ^ entry.1.1.val) ≤ + (chargedRandomDependencyTree source target N P H T S passes copies factor multiplier + tau eta kappa delta group integer initial readGroup readInteger sourceAnswer hbody root).widthWork M source.length := by + have hweight := chargedRandomCoarseQuery_cost_le source target N P H T S passes copies + factor multiplier tau eta kappa delta readGroup readInteger sourceAnswer initial + (fun d => 1 + source.length ⌈/⌉ M ^ (J - d)) root + have hdepth : ∀ entry : PhysicalEntry M J target.length, + J - (J - entry.1.1.val) = entry.1.1.val := by + intro entry + have := entry.1.1.isLt + omega + simp only [hdepth] at hweight + apply hweight.trans_eq + have hw := queryDependencyExpansion_weighted depth index program + (chargedRandomRequestList_progress source target N P H T S passes copies factor multiplier + tau eta kappa delta group integer initial readGroup readInteger sourceAnswer hbody) (fun d => 1 + source.length ⌈/⌉ M ^ (J - d)) root + change _ = (chargedRandomDependencyTree source target N P H T S passes copies factor multiplier + tau eta kappa delta group integer initial readGroup readInteger sourceAnswer hbody root).depthWeightedCount + (fun d => 1 + source.length ⌈/⌉ M ^ (_ - d)) + rw [show (chargedRandomDependencyTree source target N P H T S passes copies factor multiplier + tau eta kappa delta group integer initial readGroup readInteger sourceAnswer hbody root).depth = depth root from + queryDependencyExpansion_depth depth index program + (chargedRandomRequestList_progress source target N P H T S passes copies factor multiplier + tau eta kappa delta group integer initial readGroup readInteger sourceAnswer hbody) root] + rw [hroot] + exact hw.symm + +theorem chargedRandomCoarseQuery_fresh_width_le + (root : ChargedPhysicalRequest M J target.length passes copies T S) + (hroot : depth root = J) : + (∑ entry, selectionIndicator (entry ∈ (coarse root).keys (fun entry => (initial entry : ℚ))) * + (1 + (source.length ⌈/⌉ M ^ entry.1.1.val : ℕ) : ℝ)) ≤ + ((chargedRandomDependencyTree source target N P H T S passes copies factor multiplier + tau eta kappa delta group integer initial readGroup readInteger sourceAnswer hbody root).widthWork M source.length : ℝ) := by + classical + have hf := sum_selected_nat_weights_le ((coarse root).keys (fun entry => (initial entry : ℚ))) + (fun entry => 1 + source.length ⌈/⌉ M ^ entry.1.1.val) + have hw := chargedRandomCoarseQuery_width_cost_le source target N P H T S passes copies factor multiplier + tau eta kappa delta readGroup readInteger sourceAnswer initial group integer hbody root hroot + rw [FiniteQuery.cost_eq_sum] at hw + have hwR : (((coarse root).keys (fun entry => (initial entry : ℚ))).map + (fun entry => 1 + source.length ⌈/⌉ M ^ entry.1.1.val)).sum ≤ + (chargedRandomDependencyTree source target N P H T S passes copies factor multiplier + tau eta kappa delta group integer initial readGroup readInteger sourceAnswer hbody root).widthWork M source.length := hw + have hwcast := (Nat.cast_le (α := ℝ)).mpr hwR + apply le_trans ?_ hwcast + simpa only [Nat.cast_add, Nat.cast_one] using hf + +end Coarse + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/ChargedRandomCost.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/ChargedRandomCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..b1b7ba8d93f95e24e08d189916f57abd4051e6bb --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/ChargedRandomCost.lean @@ -0,0 +1,85 @@ +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalRandomBoundedCost +import OAI.Combinatorics.EditApproximation.Geometry.ChargedRandomGlobalQuery +import OAI.Combinatorics.EditApproximation.Geometry.ChargedIndexCost +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalRandomRankCost + +namespace OAI + +namespace EditApproximation + +section Cost + +variable {σ α : Type*} [DecidableEq α] {M J R : ℕ} [NeZero M] [NeZero R] + (source target : List α) (N P F exponent H Q T S passes copies : ℕ) + (factor : ℕ → ℚ) (multiplier : ℕ → ℕ) (tau eta kappa delta : ℚ) + (readGroup : ℕ → ℕ → PhysicalInternalNode M J → Fin R → GroupScalarKey M F Q → FiniteQuery σ) + (readInteger : ℕ → ℕ → PhysicalInternalNode M J → Fin R → + (ℕ × TargetInterval target.length) → ℕ → FiniteQuery σ) + (initial : PhysicalEntry M J target.length → ℕ) + (sourceAnswer : σ → ℚ) (answer : PhysicalTableRequest M J target.length → ℚ) + (sourceWeight : σ → ℕ) (coarse : ℕ) (weight : PhysicalTableRequest M J target.length → ℕ) + + theorem physicalRandomGlobalQuery_refinement_cost + (request : PhysicalTableRequest M J target.length) + (hindex : T < request.index) (hbelow : request.node.1.val < J) + (hshort : ¬ (physicalSourceInterval source.length request.node).hi - + (physicalSourceInterval source.length request.node).lo ≤ 1) : + (physicalRandomGlobalQuery source target N P F exponent H Q T S copies factor multiplier + tau eta kappa delta readGroup readInteger initial request).cost + (Sum.elim sourceAnswer (fun child => answer child.val)) + (Sum.elim sourceWeight (fun child => weight child.val)) = + (physicalRandomDataRequestQuery source target N P F exponent H Q tau + (refinementFactor (factor request.pass) F) eta kappa delta request.pass request.copy T S + (request.index - T) (Nat.sub_pos_of_lt hindex) request.node hbelow + (readGroup request.pass request.copy ⟨request.node, hbelow⟩ (Fin.ofNat R (request.index - T - 1))) + (readInteger request.pass request.copy ⟨request.node, hbelow⟩ (Fin.ofNat R (request.index - T - 1))) + request.state).cost (Sum.elim sourceAnswer (fun child => answer child.val)) + (Sum.elim sourceWeight (fun child => weight child.val)) := by + unfold physicalRandomGlobalQuery + rw [dite_eq_left ⟨hindex, hbelow, hshort⟩, FiniteQuery.mapKeys_cost] + congr 1 <;> (funext key; cases key <;> rfl) + + theorem chargedRandomGlobalQuery_refinement_cost + (parent : {r : PhysicalTableRequest M J target.length // r.Bounded passes copies T S}) + (hindex : T < parent.val.index) (hbelow : parent.val.node.1.val < J) + (hshort : ¬ (physicalSourceInterval source.length parent.val.node).hi - + (physicalSourceInterval source.length parent.val.node).lo ≤ 1) : + (chargedRandomGlobalQuery source target N P F exponent H Q T S passes copies factor multiplier + tau eta kappa delta readGroup readInteger initial (Sum.inr parent)).cost + (Sum.elim sourceAnswer (fun child => Sum.elim (fun entry => (initial entry : ℚ)) + (fun r => answer r.val) child.val)) + (Sum.elim sourceWeight (fun child => chargedTableWeight coarse weight child.val)) = + (physicalRandomDataRequestQuery source target N P F exponent H Q tau + (refinementFactor (factor parent.val.pass) F) eta kappa delta parent.val.pass parent.val.copy T S + (parent.val.index - T) (Nat.sub_pos_of_lt hindex) parent.val.node hbelow + (readGroup parent.val.pass parent.val.copy ⟨parent.val.node, hbelow⟩ + (Fin.ofNat R (parent.val.index - T - 1))) + (readInteger parent.val.pass parent.val.copy ⟨parent.val.node, hbelow⟩ + (Fin.ofNat R (parent.val.index - T - 1))) parent.val.state).cost + (Sum.elim sourceAnswer (fun child => answer child.val)) + (Sum.elim sourceWeight (fun child => weight child.val)) := by + unfold chargedRandomGlobalQuery + dsimp only + rw [ite_eq_right (Nat.not_le.mpr hindex), ite_eq_left hbelow, ite_eq_right hshort, FiniteQuery.mapKeys_cost] + have hcost := physicalRandomBoundedQuery_cost source target N P F exponent H Q T S passes copies + factor multiplier tau eta kappa delta readGroup readInteger initial sourceAnswer answer + sourceWeight weight parent + have heq : (physicalRandomBoundedQuery source target N P F exponent H Q T S passes copies + factor multiplier tau eta kappa delta readGroup readInteger initial parent).cost + (Sum.elim sourceAnswer (fun child => answer child.val.val)) + (Sum.elim sourceWeight (fun child => weight child.val.val)) = _ := hcost + calc + _ = (physicalRandomBoundedQuery source target N P F exponent H Q T S passes copies + factor multiplier tau eta kappa delta readGroup readInteger initial parent).cost + (Sum.elim sourceAnswer (fun child => answer child.val.val)) + (Sum.elim sourceWeight (fun child => weight child.val.val)) := by + congr 1 <;> (funext key; cases key <;> rfl) + _ = _ := heq.trans (physicalRandomGlobalQuery_refinement_cost source target N P F exponent H Q T S + copies factor multiplier tau eta kappa delta readGroup readInteger initial sourceAnswer answer + sourceWeight weight parent.val hindex hbelow hshort) + +end Cost + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/ChargedRandomExpansion.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/ChargedRandomExpansion.lean new file mode 100644 index 0000000000000000000000000000000000000000..555371bbd654a8ccdb7104c35fd76cd2a743d22e --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/ChargedRandomExpansion.lean @@ -0,0 +1,151 @@ +import OAI.Combinatorics.EditApproximation.Refinement.ComputedChargedRandomBudget +import OAI.Combinatorics.EditApproximation.Geometry.ChargedRandomProgress +import OAI.Combinatorics.EditApproximation.Geometry.ChargedQueryAsymptotics +import OAI.Combinatorics.EditApproximation.Geometry.SourceRankedWork + +namespace OAI + +namespace EditApproximation + +section Expansion + +variable {σ α : Type*} [DecidableEq α] {M J R : ℕ} [NeZero M] [NeZero R] + (source target : List α) (N P H T S passes copies : ℕ) + (factor : ℕ → ℚ) (multiplier : ℕ → ℕ) (tau eta kappa delta : ℚ) + (group : ℕ → ℕ → PhysicalInternalNode M J → Fin R → + CellGroupDraws M (inputSmallLog N) (inputSmallLog N ^ 80)) + (integer : ℕ → ℕ → PhysicalInternalNode M J → Fin R → ℕ → TargetInterval target.length → ℕ) + (initial : PhysicalEntry M J target.length → ℕ) + +variable + (readGroup : ℕ → ℕ → PhysicalInternalNode M J → Fin R → + GroupScalarKey M (inputSmallLog N) (inputSmallLog N ^ 80) → FiniteQuery σ) + (readInteger : ℕ → ℕ → PhysicalInternalNode M J → Fin R → + (ℕ × TargetInterval target.length) → ℕ → FiniteQuery σ) + (sourceAnswer : σ → ℚ) + +local notation "mixedProgram" => chargedRandomGlobalQuery source target N P (inputSmallLog N) + (40 * smallLogExponent N) H (inputSmallLog N ^ 80) T S passes copies factor multiplier + tau eta kappa delta readGroup readInteger initial +local notation "program" => SourceRanked.projectedBody ChargedPhysicalRequest.rank mixedProgram sourceAnswer +local notation "values" => chargedRequestValue source target N P (inputSmallLog N) + (40 * smallLogExponent N) H (inputSmallLog N ^ 80) T S passes copies factor multiplier + tau eta kappa delta group integer initial +local notation "depth" => @ChargedPhysicalRequest.depth M J target.length passes copies T S +local notation "index" => @ChargedPhysicalRequest.index M J target.length passes copies T S + +variable (hbody : ∀ (request : ChargedPhysicalRequest M J target.length passes copies T S), + (chargedRandomGlobalQuery source target N P (inputSmallLog N) + (40 * smallLogExponent N) H (inputSmallLog N ^ 80) T S passes copies factor multiplier + tau eta kappa delta readGroup readInteger initial request).value + (Sum.elim sourceAnswer (fun child : {child : ChargedPhysicalRequest M J target.length passes copies T S // + child.rank < request.rank} => chargedRequestValue source target N P (inputSmallLog N) + (40 * smallLogExponent N) H (inputSmallLog N ^ 80) T S passes copies factor multiplier + tau eta kappa delta group integer initial child.val)) = + chargedRequestValue source target N P (inputSmallLog N) + (40 * smallLogExponent N) H (inputSmallLog N ^ 80) T S passes copies factor multiplier + tau eta kappa delta group integer initial request) + +include hbody + + theorem chargedRandomRequestList_progress (root child : ChargedPhysicalRequest M J target.length passes copies T S) + (hchild : child ∈ queryRequestList depth index program root) : + (depth child < depth root ∧ index child ≤ index root) ∨ + (depth child ≤ depth root ∧ index child < index root) := by + have hvalue := rankedProgramValue_eq ChargedPhysicalRequest.rank program values + (SourceRanked.projectedBody_value ChargedPhysicalRequest.rank mixedProgram sourceAnswer values hbody) + change child ∈ ((program root).keys + (fun key => rankedProgramValue ChargedPhysicalRequest.rank program key.val)).map Subtype.val at hchild + simp only [hvalue] at hchild + obtain ⟨key, hk, rfl⟩ := List.mem_map.mp hchild + apply FiniteQuery.eraseSources_keys_all sourceAnswer + (fun child => values child.val) (mixedProgram root) + (fun child => ChargedPhysicalRequest.DependencyProgress root child.val) ?_ key hk + intro next hn + have hp := chargedRandomGlobalQuery_keys_progress source target N P (inputSmallLog N) + (40 * smallLogExponent N) H (inputSmallLog N ^ 80) T S passes copies factor multiplier + tau eta kappa delta readGroup readInteger initial sourceAnswer values root next hn + cases next <;> exact hp + + noncomputable def chargedRandomDependencyTree (root : ChargedPhysicalRequest M J target.length passes copies T S) : + DependencyExpansion := + queryDependencyExpansion depth index program + (chargedRandomRequestList_progress source target N P H T S passes copies factor multiplier + tau eta kappa delta group integer initial readGroup readInteger sourceAnswer hbody) root + +variable (hN : 0 < N) (hell : 200 ≤ inputSmallLog N) + (hM : M = (integerParameters N).M) (hP : P = (integerParameters N).P) + (hT : T = (integerParameters N).T) (hS : S = (integerParameters N).S) + (hcopies : copies ≤ inputHeight N ^ 2) + (hAmin : ∀ pass, 1 ≤ factor pass) + (hAmax : ∀ pass, factor pass ≤ ((integerParameters N).initialFactor : ℚ)) + +include hN hell hM hP hT hS hcopies hAmin hAmax in + theorem chargedRandomDependencyTree_valid (root : ChargedPhysicalRequest M J target.length passes copies T S) : + (chargedRandomDependencyTree source target N P H T S passes copies factor multiplier + tau eta kappa delta group integer initial readGroup readInteger sourceAnswer hbody root).Valid + (M * inputSmallLog N ^ 257) + (inputHeight N ^ (512 * (coarseExponent (inputSmallLog N) + 1))) := by + apply queryDependencyExpansion_valid + · intro key + rw [querySameRequests_length_eq_cost depth index program values + (SourceRanked.projectedBody_value ChargedPhysicalRequest.rank mixedProgram sourceAnswer values hbody)] + change (FiniteQuery.eraseSources sourceAnswer (mixedProgram key)).cost + (fun child => values child.val) (fun child => chargedSameWeight key child.val) ≤ _ + rw [FiniteQuery.eraseSources_cost] + have h := computed_chargedRandomGlobalQuery_current_reads source target N P H T S passes copies + factor multiplier tau eta kappa delta group integer initial readGroup readInteger sourceAnswer hN hell hM hAmax hP hT hS key + apply h.trans + calc + 2 * M * inputSmallLog N ^ 256 ≤ inputSmallLog N * M * inputSmallLog N ^ 256 := by + gcongr + omega + _ = M * inputSmallLog N ^ 257 := by ring + · intro key + rw [queryEarlierRequests_length_eq_cost depth index program values + (SourceRanked.projectedBody_value ChargedPhysicalRequest.rank mixedProgram sourceAnswer values hbody)] + change (FiniteQuery.eraseSources sourceAnswer (mixedProgram key)).cost + (fun child => values child.val) (fun child => chargedEarlierWeight key child.val) ≤ _ + rw [FiniteQuery.eraseSources_cost] + exact computed_chargedRandomGlobalQuery_earlier_reads source target N P H T S passes copies + factor multiplier tau eta kappa delta group integer initial readGroup readInteger sourceAnswer hN hell hM hAmax hP hT hS hcopies hAmin key + + +include hN hell hM hP hT hS hcopies hAmin hAmax in + theorem chargedRandomDependencyTree_widthWork_le + (hJ : J = intervalTreeDepth M source.length) + (hpasses : passes = computedSeedPassCount N + 1) + (root : ChargedPhysicalRequest M J target.length passes copies T S) + (hroot : depth root = J) (overhead : ℝ) (hoverhead : 0 ≤ overhead) + (hpath : ∀ j ≤ intervalTreeDepth M source.length, + (dependencyPathBudget j (computedDependencyIndexCount N) + (M * inputSmallLog N ^ 257) + (inputHeight N ^ (512 * (coarseExponent (inputSmallLog N) + 1))) : ℝ) ≤ + (M : ℝ) ^ j * overhead) : + ((chargedRandomDependencyTree source target N P H T S passes copies factor multiplier + tau eta kappa delta group integer initial readGroup readInteger sourceAnswer hbody root).widthWork M source.length : ℝ) ≤ + (((intervalTreeDepth M source.length + 1) * source.length + + 4 * M * max 1 source.length : ℕ) : ℝ) * overhead := by + apply DependencyExpansion.widthWork_le M source.length _ _ (computedDependencyIndexCount N) + (by rw [hM]; exact (computed_branching_bounds N hN hell).1) _ + (chargedRandomDependencyTree_valid source target N P H T S passes copies factor multiplier + tau eta kappa delta group integer initial readGroup readInteger sourceAnswer hbody hN hell hM hP hT hS hcopies hAmin hAmax root) + · exact (queryDependencyExpansion_depth depth index program + (chargedRandomRequestList_progress source target N P H T S passes copies factor multiplier + tau eta kappa delta group integer initial readGroup readInteger sourceAnswer hbody) root).trans (hroot.trans hJ) + · have hi := chargedRequest_index_le root + have hb : index root ≤ computedDependencyIndexCount N := by + apply hi.trans_eq + unfold computedDependencyIndexCount + rw [hpasses, hT, hS] + exact (queryDependencyExpansion_index depth index program + (chargedRandomRequestList_progress source target N P H T S passes copies factor multiplier + tau eta kappa delta group integer initial readGroup readInteger sourceAnswer hbody) root).le.trans hb + · exact hoverhead + · exact hpath + +end Expansion + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/ChargedRandomGlobalQuery.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/ChargedRandomGlobalQuery.lean new file mode 100644 index 0000000000000000000000000000000000000000..8b175e7376ad4c01af151cbd25c6e97a20a90bbf --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/ChargedRandomGlobalQuery.lean @@ -0,0 +1,80 @@ +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalRandomBoundedQuery +import OAI.Combinatorics.EditApproximation.Geometry.ChargedGlobalQuery +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! The coarse seed, recursive table values, and random scalar sources are +all requested through the memo program. Inactive refinement branches use +the existing explicit coarse/median seed queries. -/ + +namespace EditApproximation + +section Global + +variable {σ α : Type*} [DecidableEq α] {M J R : ℕ} [NeZero M] [NeZero R] + (source target : List α) (N P F exponent H Q T S passes copies : ℕ) + (factor : ℕ → ℚ) (multiplier : ℕ → ℕ) (tau eta kappa delta : ℚ) + (readGroup : ℕ → ℕ → PhysicalInternalNode M J → Fin R → GroupScalarKey M F Q → FiniteQuery σ) + (readInteger : ℕ → ℕ → PhysicalInternalNode M J → Fin R → + (ℕ × TargetInterval target.length) → ℕ → FiniteQuery σ) + (initial : PhysicalEntry M J target.length → ℕ) + + + +variable + (group : ℕ → ℕ → PhysicalInternalNode M J → Fin R → CellGroupDraws M F Q) + (integer : ℕ → ℕ → PhysicalInternalNode M J → Fin R → ℕ → TargetInterval target.length → ℕ) + (sourceAnswer : σ → ℚ) + +/-- Composition with the local source-provider correctness theorem. -/ + theorem chargedRandomGlobalQuery_value + (hbody : ∀ parent, + (physicalRandomBoundedQuery source target N P F exponent H Q T S passes copies factor multiplier + tau eta kappa delta readGroup readInteger initial parent).value + (Sum.elim sourceAnswer (fun child => localRequestValue source target N P F exponent H Q T S copies + factor multiplier tau eta kappa delta group integer initial child.val.val)) = + localRequestValue source target N P F exponent H Q T S copies factor multiplier + tau eta kappa delta group integer initial parent.val) + (request : ChargedPhysicalRequest M J target.length passes copies T S) : + (chargedRandomGlobalQuery source target N P F exponent H Q T S passes copies factor multiplier + tau eta kappa delta readGroup readInteger initial request).value + (Sum.elim sourceAnswer (fun child => chargedRequestValue source target N P F exponent H Q T S + passes copies factor multiplier tau eta kappa delta group integer initial child.val)) = + chargedRequestValue source target N P F exponent H Q T S passes copies factor multiplier + tau eta kappa delta group integer initial request := by + cases request with + | inl entry => rfl + | inr parent => + change _ = localRequestValue source target N P F exponent H Q T S copies factor multiplier + tau eta kappa delta group integer initial parent.val + unfold chargedRandomGlobalQuery + dsimp only + split_ifs with hi hd hw + · rw [FiniteQuery.mapKeys_value] + exact chargedWarmupQuery_value source target N P F exponent H Q T S passes copies + factor multiplier tau eta kappa delta group integer initial parent hi + · rw [FiniteQuery.mapKeys_value, + localRequestValue_terminal source target N P F exponent H Q T S copies factor multiplier + tau eta kappa delta group integer initial parent.val (Or.inr hw)] + exact physicalInitialQuery_value_local source target N P F _ _ _ _ _ _ + (chargedSeedQuery_localValue source target N P F exponent H Q T S passes copies + factor multiplier tau eta kappa delta group integer initial parent) + · rw [FiniteQuery.mapKeys_value] + refine Eq.trans ?_ (hbody parent) + congr 1 + funext next + cases next <;> rfl + · rw [FiniteQuery.mapKeys_value, + localRequestValue_terminal source target N P F exponent H Q T S copies factor multiplier + tau eta kappa delta group integer initial parent.val (Or.inl hd)] + exact physicalInitialQuery_value_local source target N P F _ _ _ _ _ _ + (chargedSeedQuery_localValue source target N P F exponent H Q T S passes copies + factor multiplier tau eta kappa delta group integer initial parent) + +end Global + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/ChargedRandomIndexCost.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/ChargedRandomIndexCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..f3aeb148decfdb0d3fb8e8b0f020f0ca140cd37a --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/ChargedRandomIndexCost.lean @@ -0,0 +1,83 @@ +import OAI.Combinatorics.EditApproximation.Geometry.ChargedRandomCost + +namespace OAI + +namespace EditApproximation + +section Costs + +variable {σ α : Type*} [DecidableEq α] {M J R : ℕ} [NeZero M] [NeZero R] + (source target : List α) (N P F exponent H Q T S passes copies : ℕ) + (factor : ℕ → ℚ) (multiplier : ℕ → ℕ) (tau eta kappa delta : ℚ) + (readGroup : ℕ → ℕ → PhysicalInternalNode M J → Fin R → GroupScalarKey M F Q → FiniteQuery σ) + (readInteger : ℕ → ℕ → PhysicalInternalNode M J → Fin R → (ℕ × TargetInterval target.length) → ℕ → FiniteQuery σ) + (sourceAnswer : σ → ℚ) (answer : PhysicalTableRequest M J target.length → ℚ) + (initial : PhysicalEntry M J target.length → ℕ) + (parent : {r : PhysicalTableRequest M J target.length // r.Bounded passes copies T S}) + (hindex : T < parent.val.index) (hbelow : parent.val.node.1.val < J) + (hshort : ¬ (physicalSourceInterval source.length parent.val.node).hi - + (physicalSourceInterval source.length parent.val.node).lo ≤ 1) + +include hindex hbelow hshort + +theorem chargedRandomGlobalQuery_current_cost : + (chargedRandomGlobalQuery source target N P F exponent H Q T S passes copies factor multiplier + tau eta kappa delta readGroup readInteger initial (Sum.inr parent)).cost + (Sum.elim sourceAnswer (fun child => Sum.elim (fun entry => (initial entry : ℚ)) + (fun r => answer r.val) child.val)) + (Sum.elim (fun _ => 0) (fun child => chargedSameWeight (Sum.inr parent) child.val)) = + (physicalRandomDataRequestQuery source target N P F exponent H Q tau + (refinementFactor (factor parent.val.pass) F) eta kappa delta parent.val.pass parent.val.copy T S + (parent.val.index - T) (Nat.sub_pos_of_lt hindex) parent.val.node hbelow + (readGroup parent.val.pass parent.val.copy ⟨parent.val.node, hbelow⟩ (Fin.ofNat R (parent.val.index - T - 1))) + (readInteger parent.val.pass parent.val.copy ⟨parent.val.node, hbelow⟩ (Fin.ofNat R (parent.val.index - T - 1))) + parent.val.state).cost + (Sum.elim sourceAnswer (fun child => answer child.val)) + (Sum.elim (fun _ => 0) (fun child => physicalCurrentReadWeight (T + (parent.val.index - T)) child.val)) := by + simp only [chargedSameWeight_table] + rw [chargedRandomGlobalQuery_refinement_cost source target N P F exponent H Q T S passes copies + factor multiplier tau eta kappa delta readGroup readInteger initial sourceAnswer answer (fun _ => 0) _ _ parent hindex hbelow hshort] + have hrank : (PhysicalTableRequest.refinement parent.val.pass parent.val.copy parent.val.node + T (parent.val.index - T) parent.val.state).rank T S = parent.val.rank T S := by + unfold PhysicalTableRequest.refinement PhysicalTableRequest.rank + dsimp only + congr 1 + omega + rw [← hrank] + exact physicalRandomDataRequest_same_rank_cost source target N P F exponent H Q tau + (refinementFactor (factor parent.val.pass) F) eta kappa delta parent.val.pass parent.val.copy T S + (parent.val.index - T) (Nat.sub_pos_of_lt hindex) parent.val.node hbelow _ _ sourceAnswer parent.val.state answer + +theorem chargedRandomGlobalQuery_earlier_cost : + (chargedRandomGlobalQuery source target N P F exponent H Q T S passes copies factor multiplier + tau eta kappa delta readGroup readInteger initial (Sum.inr parent)).cost + (Sum.elim sourceAnswer (fun child => Sum.elim (fun entry => (initial entry : ℚ)) + (fun r => answer r.val) child.val)) + (Sum.elim (fun _ => 0) (fun child => chargedEarlierWeight (Sum.inr parent) child.val)) = + (physicalRandomDataRequestQuery source target N P F exponent H Q tau + (refinementFactor (factor parent.val.pass) F) eta kappa delta parent.val.pass parent.val.copy T S + (parent.val.index - T) (Nat.sub_pos_of_lt hindex) parent.val.node hbelow + (readGroup parent.val.pass parent.val.copy ⟨parent.val.node, hbelow⟩ (Fin.ofNat R (parent.val.index - T - 1))) + (readInteger parent.val.pass parent.val.copy ⟨parent.val.node, hbelow⟩ (Fin.ofNat R (parent.val.index - T - 1))) + parent.val.state).cost + (Sum.elim sourceAnswer (fun child => answer child.val)) + (Sum.elim (fun _ => 0) (fun child => physicalEarlierReadWeight (T + (parent.val.index - T)) child.val)) := by + simp only [chargedEarlierWeight_table] + rw [chargedRandomGlobalQuery_refinement_cost source target N P F exponent H Q T S passes copies + factor multiplier tau eta kappa delta readGroup readInteger initial sourceAnswer answer (fun _ => 0) _ _ parent hindex hbelow hshort] + have hrank : (PhysicalTableRequest.refinement parent.val.pass parent.val.copy parent.val.node + T (parent.val.index - T) parent.val.state).rank T S = parent.val.rank T S := by + unfold PhysicalTableRequest.refinement PhysicalTableRequest.rank + dsimp only + congr 1 + omega + rw [← hrank] + exact physicalRandomDataRequest_earlier_rank_cost source target N P F exponent H Q tau + (refinementFactor (factor parent.val.pass) F) eta kappa delta parent.val.pass parent.val.copy T S + (parent.val.index - T) (Nat.sub_pos_of_lt hindex) parent.val.node hbelow _ _ sourceAnswer parent.val.state answer + +end Costs + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/ChargedRandomMemo.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/ChargedRandomMemo.lean new file mode 100644 index 0000000000000000000000000000000000000000..6b34ca1c3fabba11151b5175ad5dbd8442b0f521 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/ChargedRandomMemo.lean @@ -0,0 +1,60 @@ +import OAI.Combinatorics.EditApproximation.Geometry.ChargedRandomGlobalQuery +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalRandomValue +import OAI.Combinatorics.EditApproximation.Geometry.SourceRankedProgram +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! The charged evaluator actually caches random source coordinates and +physical entries in one rank-decreasing memo computation. -/ + +namespace EditApproximation + +section Memo + +variable {σ α : Type*} [DecidableEq α] {M J R : ℕ} [NeZero M] [NeZero R] + (source target : List α) (N P F exponent H Q T S passes copies : ℕ) + (factor : ℕ → ℚ) (multiplier : ℕ → ℕ) (tau eta kappa delta : ℚ) + (readGroup : ℕ → ℕ → PhysicalInternalNode M J → Fin R → GroupScalarKey M F Q → FiniteQuery σ) + (readInteger : ℕ → ℕ → PhysicalInternalNode M J → Fin R → + (ℕ × TargetInterval target.length) → ℕ → FiniteQuery σ) + (initial : PhysicalEntry M J target.length → ℕ) + (sourceAnswer : σ → ℚ) + + + + theorem chargedRandomMemoEvaluate_value + (group : ℕ → ℕ → PhysicalInternalNode M J → Fin R → CellGroupDraws M F Q) + (integer : ℕ → ℕ → PhysicalInternalNode M J → Fin R → ℕ → TargetInterval target.length → ℕ) + (hgroup : ∀ pass copy node time key, (readGroup pass copy node time key).value sourceAnswer = + groupScalarValue (group pass copy node time) key) + (honline : ∀ pass copy (node : PhysicalInternalNode M J) time key, + (readInteger pass copy node time key + (keyedOnlineSourceRange source target (physicalSourceInterval source.length node.val) + P exponent H tau (fun i r => (∑ j : Fin T, localRequestValue source target N P F exponent H Q T S + copies factor multiplier tau eta kappa delta group integer initial (PhysicalTableRequest.warmup + pass copy (physicalChild node.val node.property i) j.val r)) / T) key)).value sourceAnswer = + (integer pass copy node time key.1 key.2 : ℚ)) + (bits : ℕ) (encode : Sum σ (ChargedPhysicalRequest M J target.length passes copies T S) → ℕ) + (hinjective : Function.Injective encode) (hbounded : ∀ key, encode key < 2 ^ bits) + (request : ChargedPhysicalRequest M J target.length passes copies T S) : + (chargedRandomMemoEvaluate source target N P F exponent H Q T S passes copies factor multiplier + tau eta kappa delta readGroup readInteger initial sourceAnswer bits encode request).value = + chargedRequestValue source target N P F exponent H Q T S passes copies factor multiplier + tau eta kappa delta group integer initial request := by + unfold chargedRandomMemoEvaluate + exact SourceRanked.memo_value ChargedPhysicalRequest.rank _ sourceAnswer + (chargedRequestValue source target N P F exponent H Q T S passes copies factor multiplier + tau eta kappa delta group integer initial) + (chargedRandomGlobalQuery_value source target N P F exponent H Q T S passes copies factor multiplier + tau eta kappa delta readGroup readInteger initial group integer sourceAnswer + (physicalRandomBoundedQuery_localValue source target N P F exponent H Q T S passes copies factor + multiplier tau eta kappa delta group integer initial readGroup readInteger sourceAnswer hgroup honline)) + bits encode hinjective hbounded (.inr request) + +end Memo + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/ChargedRandomMemoWork.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/ChargedRandomMemoWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..b718625fbf7e1fc13119f24d7124e180916005a5 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/ChargedRandomMemoWork.lean @@ -0,0 +1,105 @@ +import OAI.Combinatorics.EditApproximation.Geometry.ChargedRandomExpansion +import OAI.Combinatorics.EditApproximation.Geometry.ChargedRandomMemo + +namespace OAI + +/-! Source reads and dictionary visits in the actual shared-cache evaluator +are bounded by the width of its projected table dependency expansion. -/ + +namespace EditApproximation + +section Work + +variable {σ α : Type*} [DecidableEq α] {M J R : ℕ} [NeZero M] [NeZero R] + (source target : List α) (N P H T S passes copies : ℕ) + (factor : ℕ → ℚ) (multiplier : ℕ → ℕ) (tau eta kappa delta : ℚ) + (group : ℕ → ℕ → PhysicalInternalNode M J → Fin R → + CellGroupDraws M (inputSmallLog N) (inputSmallLog N ^ 80)) + (integer : ℕ → ℕ → PhysicalInternalNode M J → Fin R → ℕ → TargetInterval target.length → ℕ) + (initial : PhysicalEntry M J target.length → ℕ) + +variable + (readGroup : ℕ → ℕ → PhysicalInternalNode M J → Fin R → + GroupScalarKey M (inputSmallLog N) (inputSmallLog N ^ 80) → FiniteQuery σ) + (readInteger : ℕ → ℕ → PhysicalInternalNode M J → Fin R → + (ℕ × TargetInterval target.length) → ℕ → FiniteQuery σ) + (sourceAnswer : σ → ℚ) + +local notation "mixedProgram" => chargedRandomGlobalQuery source target N P (inputSmallLog N) + (40 * smallLogExponent N) H (inputSmallLog N ^ 80) T S passes copies factor multiplier + tau eta kappa delta readGroup readInteger initial +local notation "program" => SourceRanked.projectedBody ChargedPhysicalRequest.rank mixedProgram sourceAnswer +local notation "values" => chargedRequestValue source target N P (inputSmallLog N) + (40 * smallLogExponent N) H (inputSmallLog N ^ 80) T S passes copies factor multiplier + tau eta kappa delta group integer initial +local notation "depth" => @ChargedPhysicalRequest.depth M J target.length passes copies T S +local notation "index" => @ChargedPhysicalRequest.index M J target.length passes copies T S + +variable (hbody : ∀ (request : ChargedPhysicalRequest M J target.length passes copies T S), + (chargedRandomGlobalQuery source target N P (inputSmallLog N) + (40 * smallLogExponent N) H (inputSmallLog N ^ 80) T S passes copies factor multiplier + tau eta kappa delta readGroup readInteger initial request).value + (Sum.elim sourceAnswer (fun child : {child : ChargedPhysicalRequest M J target.length passes copies T S // + child.rank < request.rank} => chargedRequestValue source target N P (inputSmallLog N) + (40 * smallLogExponent N) H (inputSmallLog N ^ 80) T S passes copies factor multiplier + tau eta kappa delta group integer initial child.val)) = + chargedRequestValue source target N P (inputSmallLog N) + (40 * smallLogExponent N) H (inputSmallLog N ^ 80) T S passes copies factor multiplier + tau eta kappa delta group integer initial request) + +include hbody + + + theorem chargedRandomMemoEvaluate_requests_le_widthWork + (sourceBudget bits : ℕ) + (encode : Sum σ (ChargedPhysicalRequest M J target.length passes copies T S) → ℕ) + (hinjective : Function.Injective encode) (hbounded : ∀ key, encode key < 2 ^ bits) + (hsource : ∀ key, (mixedProgram key).cost + (Sum.elim sourceAnswer (fun next => values next.val)) + (Sum.elim (fun _ => 1) (fun _ => 0)) ≤ sourceBudget) + (root : ChargedPhysicalRequest M J target.length passes copies T S) : + (chargedRandomMemoEvaluate source target N P (inputSmallLog N) + (40 * smallLogExponent N) H (inputSmallLog N ^ 80) T S passes copies factor multiplier + tau eta kappa delta readGroup readInteger initial sourceAnswer bits encode root).requests ≤ + (sourceBudget + 1) * + (chargedRandomDependencyTree source target N P H T S passes copies factor multiplier + tau eta kappa delta group integer initial readGroup readInteger sourceAnswer hbody root).widthWork + M source.length := by + apply (SourceRanked.memo_requests_le_source_factor ChargedPhysicalRequest.rank mixedProgram + sourceAnswer values hbody sourceBudget hsource bits encode hinjective hbounded root).trans + apply Nat.mul_le_mul_left + calc + rankedUncachedCalls ChargedPhysicalRequest.rank program root = + (chargedRandomDependencyTree source target N P H T S passes copies factor multiplier + tau eta kappa delta group integer initial readGroup readInteger sourceAnswer hbody root).nodeCount := + (queryDependencyExpansion_nodes depth index program + (chargedRandomRequestList_progress source target N P H T S passes copies factor multiplier + tau eta kappa delta group integer initial readGroup readInteger sourceAnswer hbody) root).symm + _ ≤ _ := DependencyExpansion.nodeCount_le_widthWork _ _ _ + + theorem chargedRandomMemoEvaluate_dictionaryVisits_le_widthWork + (sourceBudget bits : ℕ) + (encode : Sum σ (ChargedPhysicalRequest M J target.length passes copies T S) → ℕ) + (hinjective : Function.Injective encode) (hbounded : ∀ key, encode key < 2 ^ bits) + (hsource : ∀ key, (mixedProgram key).cost + (Sum.elim sourceAnswer (fun next => values next.val)) + (Sum.elim (fun _ => 1) (fun _ => 0)) ≤ sourceBudget) + (root : ChargedPhysicalRequest M J target.length passes copies T S) : + (chargedRandomMemoEvaluate source target N P (inputSmallLog N) + (40 * smallLogExponent N) H (inputSmallLog N ^ 80) T S passes copies factor multiplier + tau eta kappa delta readGroup readInteger initial sourceAnswer bits encode root).dictionaryVisits ≤ + (sourceBudget + 1) * + (chargedRandomDependencyTree source target N P H T S passes copies factor multiplier + tau eta kappa delta group integer initial readGroup readInteger sourceAnswer hbody root).widthWork + M source.length * (2 * (bits + 1)) := by + exact (rankedMemoEvaluate_resource_bounds _ _ bits encode (.inr root) .empty).2.1.trans + (Nat.mul_le_mul_right _ + (chargedRandomMemoEvaluate_requests_le_widthWork source target N P H T S passes copies + factor multiplier tau eta kappa delta group integer initial readGroup readInteger sourceAnswer + hbody sourceBudget bits encode hinjective hbounded hsource root)) + +end Work + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/ChargedRandomProgress.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/ChargedRandomProgress.lean new file mode 100644 index 0000000000000000000000000000000000000000..3a6bd8a13c8f38d587aa131f9351fc142e93394f --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/ChargedRandomProgress.lean @@ -0,0 +1,91 @@ +import OAI.Combinatorics.EditApproximation.Geometry.ChargedRandomGlobalQuery +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalRandomBoundedCost +import OAI.Combinatorics.EditApproximation.Geometry.ChargedQueryProgress + +namespace OAI + +/-! Actual mixed requests retain the charged physical depth/index progress. +This statement holds for every returned source and table value. -/ + +namespace EditApproximation + +section Global + +variable {σ α : Type*} [DecidableEq α] {M J R : ℕ} [NeZero M] [NeZero R] + (source target : List α) (N P F exponent H Q T S passes copies : ℕ) + (factor : ℕ → ℚ) (multiplier : ℕ → ℕ) (tau eta kappa delta : ℚ) + (readGroup : ℕ → ℕ → PhysicalInternalNode M J → Fin R → GroupScalarKey M F Q → FiniteQuery σ) + (readInteger : ℕ → ℕ → PhysicalInternalNode M J → Fin R → + (ℕ × TargetInterval target.length) → ℕ → FiniteQuery σ) + (initial : PhysicalEntry M J target.length → ℕ) + (sourceAnswer : σ → ℚ) + (answer : ChargedPhysicalRequest M J target.length passes copies T S → ℚ) + + theorem chargedRandomGlobalQuery_keys_progress + (request : ChargedPhysicalRequest M J target.length passes copies T S) : + ∀ key ∈ (chargedRandomGlobalQuery source target N P F exponent H Q T S passes copies + factor multiplier tau eta kappa delta readGroup readInteger initial request).keys + (Sum.elim sourceAnswer (fun child => answer child.val)), + match key with + | .inl _ => True + | .inr child => ChargedPhysicalRequest.DependencyProgress request child.val := by + cases request with + | inl entry => + intro key hk + exact False.elim (List.not_mem_nil hk) + | inr parent => + unfold chargedRandomGlobalQuery + dsimp only + split_ifs with hi hb hs + · apply FiniteQuery.keys_all_mapKeys + intro key hk + exact Or.inr (chargedWarmupQuery_keys_earlier source target N P F factor multiplier parent _ key hk) + · apply FiniteQuery.keys_all_mapKeys + intro key hk + apply Or.inr + apply physicalInitialQuery_keys_all source target N P F _ _ _ _ _ _ _ key hk + intro q + exact chargedSeedQuery_keys_earlier N multiplier parent (parent.val.node, q) _ + · rw [FiniteQuery.mapKeys_keys] + intro key hk + obtain ⟨child, hc, rfl⟩ := List.mem_map.mp hk + let tableMap : + {child : {r : PhysicalTableRequest M J target.length // r.Bounded passes copies T S} // + child.val.combinedRank T S < parent.val.combinedRank T S} → + {child : ChargedPhysicalRequest M J target.length passes copies T S // + child.rank < ChargedPhysicalRequest.rank (.inr parent)} := + fun child => ⟨.inr child.val, + ChargedPhysicalRequest.table_rank_lt parent child.val child.property⟩ + have horacle : (Sum.elim sourceAnswer (fun child => answer child.val)) ∘ + Sum.map (id : σ → σ) tableMap = + Sum.elim sourceAnswer (fun child => answer (Sum.inr child.val)) := by + funext key + cases key <;> rfl + rw [horacle] at hc + have hp := physicalRandomBoundedQuery_progress source target N P F exponent H Q T S passes copies + factor multiplier tau eta kappa delta readGroup readInteger initial sourceAnswer + (fun r => if hr : r.Bounded passes copies T S then answer (.inr ⟨r, hr⟩) else 0) + parent + cases child with + | inl key => trivial + | inr child => + apply ChargedPhysicalRequest.table_progress + apply hp (.inr child) + convert hc using 1 + congr 1 + funext key + cases key with + | inl key => rfl + | inr key => simp only [Sum.elim_inr, dite_eq_left key.val.property] + · apply FiniteQuery.keys_all_mapKeys + intro key hk + apply Or.inr + apply physicalInitialQuery_keys_all source target N P F _ _ _ _ _ _ _ key hk + intro q + exact chargedSeedQuery_keys_earlier N multiplier parent (parent.val.node, q) _ + +end Global + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/ChargedRequestSpace.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/ChargedRequestSpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..26e39719d2f0ca061fdb0c1fa82668ba949d074e --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/ChargedRequestSpace.lean @@ -0,0 +1,83 @@ +import OAI.Combinatorics.EditApproximation.Geometry.ChargedGlobalQuery +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalRequestBits +import OAI.Combinatorics.EditApproximation.Binary.BinaryMemoSpace + +namespace OAI + +/-! A polynomial retained-cache bound for every execution. The estimate +uses only fixed-width key insertion and computed parameter sizes, and +therefore does not depend on an approximation success event. -/ + +namespace EditApproximation + +theorem computed_charged_request_bits_le (N nx ny passes copies : ℕ) (hN : 0 < N) + (hell : 200 ≤ inputSmallLog N) (hnx : nx ≤ N) (hny : ny ≤ N) + (hpasses : passes ≤ inputHeight N ^ 2) (hcopies : copies ≤ inputHeight N ^ 2) : + ChargedPhysicalRequest.bits (integerParameters N).M + (intervalTreeDepth (integerParameters N).M nx) ny passes copies + (integerParameters N).T (integerParameters N).S ≤ 11 * inputHeight N + 3 := by + let H := inputHeight N + have hentry := computed_entryCapacity_bound N nx ny hN hell hnx hny + have hbits := computed_request_bits_le N nx ny passes copies hN hell hnx hny hpasses hcopies + have htable : PhysicalTableRequest.capacity (integerParameters N).M + (intervalTreeDepth (integerParameters N).M nx) ny passes copies + (integerParameters N).T (integerParameters N).S + 1 ≤ 2 ^ (11 * H + 1) := by + exact (Nat.clog_le_iff_le_pow (by decide : 1 < (2 : ℕ))).mp hbits + have hentry' : PhysicalTableRequest.entryCapacity (integerParameters N).M + (intervalTreeDepth (integerParameters N).M nx) ny ≤ 2 ^ (11 * H + 1) := + hentry.trans (pow_le_pow_right₀ (by decide : 1 ≤ (2 : ℕ)) (by omega)) + unfold ChargedPhysicalRequest.bits + apply (Nat.clog_le_iff_le_pow (by decide : 1 < (2 : ℕ))).2 + unfold ChargedPhysicalRequest.capacity + have hp : 2 ^ (11 * H + 3) = 4 * 2 ^ (11 * H + 1) := by + rw [show 11 * H + 3 = (11 * H + 1) + 2 by omega, pow_add] + norm_num + omega + change 2 * (_ + _) + 1 ≤ 2 ^ (11 * H + 3) + rw [hp] + omega + +theorem two_pow_inputHeight_le (N : ℕ) : 2 ^ inputHeight N ≤ 4 * (N + 2) ^ 2 := by + have hc : 0 < Nat.clog 2 (N + 2) := + Nat.clog_pos (by decide : 1 < (2 : ℕ)) (by omega) + have hH := (rejectionWord_range (Nat.clog 2 (N + 2)) hc).2 + have hN := (rejectionWord_range (N + 2) (by omega)).2 + change inputHeight N < 2 * Nat.clog 2 (N + 2) at hH + change 2 ^ Nat.clog 2 (N + 2) < 2 * (N + 2) at hN + calc + _ ≤ 2 ^ (2 * Nat.clog 2 (N + 2)) := pow_le_pow_right₀ (by decide : 1 ≤ (2 : ℕ)) hH.le + _ = (2 ^ Nat.clog 2 (N + 2)) ^ 2 := by rw [← pow_mul]; congr 1; omega + _ ≤ (2 * (N + 2)) ^ 2 := Nat.pow_le_pow_left hN.le 2 + _ = _ := by ring + +theorem computed_charged_cache_nodes {κ : Type*} (N nx ny passes copies : ℕ) (hN : 0 < N) + (hell : 200 ≤ inputSmallLog N) (hnx : nx ≤ N) (hny : ny ≤ N) + (hpasses : passes ≤ inputHeight N ^ 2) (hcopies : copies ≤ inputHeight N ^ 2) + (rank : κ → ℕ) (program : (key : κ) → FiniteQuery {child : κ // rank child < rank key}) + (encode : κ → ℕ) (key : κ) : + (rankedMemoEvaluate rank program + (ChargedPhysicalRequest.bits (integerParameters N).M + (intervalTreeDepth (integerParameters N).M nx) ny passes copies + (integerParameters N).T (integerParameters N).S) encode key .empty).memory.nodes + 1 ≤ + (N + 2) ^ 48 := by + have hbits := computed_charged_request_bits_le N nx ny passes copies hN hell hnx hny hpasses hcopies + have hcache := rankedMemoEvaluate_nodes_bound rank program + (ChargedPhysicalRequest.bits (integerParameters N).M + (intervalTreeDepth (integerParameters N).M nx) ny passes copies + (integerParameters N).T (integerParameters N).S) encode key + have hpow := Nat.pow_le_pow_right (by decide : 0 < (2 : ℕ)) (Nat.add_le_add_right hbits 1) + apply (hcache.trans hpow).trans + calc + 2 ^ (11 * inputHeight N + 3 + 1) = 16 * (2 ^ inputHeight N) ^ 11 := by + rw [show 11 * inputHeight N + 3 + 1 = inputHeight N * 11 + 4 by omega, pow_add, pow_mul] + norm_num + omega + _ ≤ 16 * (4 * (N + 2) ^ 2) ^ 11 := Nat.mul_le_mul_left 16 (Nat.pow_le_pow_left (two_pow_inputHeight_le N) 11) + _ = 2 ^ 26 * (N + 2) ^ 22 := by ring + _ ≤ (N + 2) ^ 26 * (N + 2) ^ 22 := + Nat.mul_le_mul_right _ (Nat.pow_le_pow_left (by omega) 26) + _ = (N + 2) ^ 48 := by rw [← pow_add] + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/ChargedSeedQuery.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/ChargedSeedQuery.lean new file mode 100644 index 0000000000000000000000000000000000000000..3f1f20c97a358b9da00471ced33af16fc8aaf661 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/ChargedSeedQuery.lean @@ -0,0 +1,53 @@ +import OAI.Combinatorics.EditApproximation.Geometry.ChargedPhysicalRequest +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalMedianQuery +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! A pass-zero seed read requests a cached coarse entry. Later seed reads +request the previous pass's final table value in each distinct copy. +Thus neither kind of seed value enters the charged program as a free oracle. -/ + +namespace EditApproximation + + + + + + + +theorem chargedSeedQuery_value {M J ny passes copies T S : ℕ} (N : ℕ) (multiplier : ℕ → ℕ) + (parent : {r : PhysicalTableRequest M J ny // r.Bounded passes copies T S}) + (q : TargetInterval ny) (answer : ChargedPhysicalRequest M J ny passes copies T S → ℚ) : + (chargedSeedQuery N multiplier parent (parent.val.node, q)).value (fun child => answer child.val) = + if parent.val.pass = 0 then answer (Sum.inl (parent.val.node, q)) else + (min N (upperMedian (List.ofFn fun copy : Fin copies => + ⌈(multiplier (parent.val.pass - 1) : ℚ) * + answer (Sum.inr (chargedPreviousPass parent q copy))⌉₊)) : ℕ) := by + unfold chargedSeedQuery + rw [dite_eq_left rfl] + split_ifs with hp + · rfl + · rw [FiniteQuery.collect_value] + simp only [chargedPreviousRead, FiniteQuery.value, List.map_map, + List.ofFn_eq_map, Function.comp_def] + +theorem chargedSeedQuery_cost {M J ny passes copies T S : ℕ} (N : ℕ) (multiplier : ℕ → ℕ) + (parent : {r : PhysicalTableRequest M J ny // r.Bounded passes copies T S}) + (state : PhysicalEntry M J ny) + (oracle : {child : ChargedPhysicalRequest M J ny passes copies T S // + child.rank < ChargedPhysicalRequest.rank (Sum.inr parent)} → ℚ) : + (chargedSeedQuery N multiplier parent state).cost oracle (fun _ => 1) = + if state.1 = parent.val.node then if parent.val.pass = 0 then 1 else copies else 0 := by + unfold chargedSeedQuery + split_ifs with hnode hpass + · rfl + · rw [FiniteQuery.cost_collect] + simp only [chargedPreviousRead, FiniteQuery.cost, Nat.add_zero, List.map_const', + List.length_finRange, List.sum_replicate, smul_eq_mul, Nat.mul_one] + · rfl + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/ChargedTerminalCost.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/ChargedTerminalCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..1c083a9ef002390464f50d5d83aa6add1c6241fd --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/ChargedTerminalCost.lean @@ -0,0 +1,39 @@ +import OAI.Combinatorics.EditApproximation.Geometry.ChargedQueryProgress +import OAI.Combinatorics.EditApproximation.Geometry.ChargedIndexCost +import OAI.Combinatorics.EditApproximation.Probability.FiniteQueryCostOrder + +namespace OAI + +/-! Warmup and terminal queries have no same-index requests. Their +charged seed reads strictly decrease the pass index, including coarse +entries at pass zero. -/ + +namespace EditApproximation + +theorem chargedWarmupQuery_same_cost_zero {α : Type*} [DecidableEq α] {M J passes copies T S : ℕ} + (source target : List α) (N P F : ℕ) (factor : ℕ → ℚ) (multiplier : ℕ → ℕ) + (parent : {r : PhysicalTableRequest M J target.length // r.Bounded passes copies T S}) (oracle) : + (chargedWarmupQuery source target N P F factor multiplier parent).cost oracle + (fun child => chargedSameWeight (Sum.inr parent) child.val) = 0 := by + apply FiniteQuery.cost_eq_zero_of_keys + intro key hk + have h := chargedWarmupQuery_keys_earlier source target N P F factor multiplier parent oracle key hk + exact ite_eq_right (not_not_intro h.2) + +theorem chargedInitialQuery_same_cost_zero {α : Type*} [DecidableEq α] {M J passes copies T S : ℕ} + (source target : List α) (N P F : ℕ) (factor : ℕ → ℚ) (multiplier : ℕ → ℕ) + (parent : {r : PhysicalTableRequest M J target.length // r.Bounded passes copies T S}) (oracle) : + (physicalInitialQuery source target N P F (factor parent.val.pass) + (chargedSeedQuery N multiplier parent) (parent.val.node, parent.val.state)).cost oracle + (fun child => chargedSameWeight (Sum.inr parent) child.val) = 0 := by + apply FiniteQuery.cost_eq_zero_of_keys + have hkeys := physicalInitialQuery_keys_all source target N P F (factor parent.val.pass) + (chargedSeedQuery N multiplier parent) parent.val.node parent.val.state oracle + (fun key => key.val.index < ChargedPhysicalRequest.index (Sum.inr parent)) + (fun q key hk => (chargedSeedQuery_keys_earlier N multiplier parent (parent.val.node, q) oracle key hk).2) + intro key hk + exact ite_eq_right (not_not_intro (hkeys key hk)) + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/ChildIncrements.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/ChildIncrements.lean new file mode 100644 index 0000000000000000000000000000000000000000..e1a3e495a280b88a2b935172ca4f96fcd4ea4f18 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/ChildIncrements.lean @@ -0,0 +1,107 @@ +import OAI.Combinatorics.EditApproximation.Geometry.BandRegret +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! +# Normalized increments of the actual child tables + +The entropy hypotheses follow from monotonicity, bounds by the fixed child +mass, and spatial regularity. The table indices here start at zero, so the +gain at index `t` uses the table before update `t+1`. +-/ + +namespace EditApproximation + +open Finset + + + + + +theorem childDecrement_telescope {β σ : Type*} (mass : β → ℚ) + (table : ℕ → β × σ → ℚ) (S : ℕ) (i : β × σ) : + (∑ t ∈ range S, childDecrement mass table t i) = + (table 0 i - table S i) / mass i.1 := by + induction S with + | zero => simp [childDecrement] + | succ S ih => + rw [sum_range_succ, ih] + unfold childDecrement + ring + +theorem childDecrement_nonneg {β σ : Type*} (mass : β → ℚ) + (table : ℕ → β × σ → ℚ) (t : ℕ) (i : β × σ) + (hmass : 0 < mass i.1) (hmono : table (t + 1) i ≤ table t i) : + (0 : ℝ) ≤ childDecrement mass table t i := by + exact_mod_cast div_nonneg (sub_nonneg.mpr hmono) hmass.le + +theorem childDecrement_total_le {β σ : Type*} (mass : β → ℚ) + (table : ℕ → β × σ → ℚ) (S : ℕ) (i : β × σ) + (hmass : 0 < mass i.1) (hzero : 0 ≤ table S i) (hupper : table 0 i ≤ mass i.1) : + (∑ t ∈ range S, (childDecrement mass table t i : ℝ)) ≤ 1 := by + have htotal : (∑ t ∈ range S, childDecrement mass table t i) ≤ 1 := by + rw [childDecrement_telescope] + apply (div_le_one₀ hmass).2 + linarith + exact_mod_cast htotal + +theorem childGain_decrement_identity {β σ : Type*} (mass : β → ℚ) + (table : ℕ → β × σ → ℚ) (κ : ℚ) (t : ℕ) (i : β × σ) : + childGain mass table t i + (1 - κ) * childDecrement mass table t i = + -(κ * table t i + (1 - κ) * table (t + 1) i) / mass i.1 := by + unfold childGain childDecrement + ring + +theorem childGain_decrement_bounds {β σ : Type*} (mass : β → ℚ) + (table : ℕ → β × σ → ℚ) (κ : ℚ) (t : ℕ) (i : β × σ) + (hmass : 0 < mass i.1) (hκ : 0 ≤ κ) (hκone : κ ≤ 1) + (hold : 0 ≤ table t i ∧ table t i ≤ mass i.1) + (hnew : 0 ≤ table (t + 1) i ∧ table (t + 1) i ≤ mass i.1) : + -1 ≤ (childGain mass table t i : ℝ) + (1 - (κ : ℝ)) * childDecrement mass table t i ∧ + (childGain mass table t i : ℝ) + (1 - (κ : ℝ)) * childDecrement mass table t i ≤ 0 := by + have hweighted0 : 0 ≤ κ * table t i + (1 - κ) * table (t + 1) i := + add_nonneg (mul_nonneg hκ hold.1) (mul_nonneg (by linarith) hnew.1) + have hweighted1 : κ * table t i + (1 - κ) * table (t + 1) i ≤ mass i.1 := by + have ha := mul_le_mul_of_nonneg_left hold.2 hκ + have hb := mul_le_mul_of_nonneg_left hnew.2 (by linarith : 0 ≤ 1 - κ) + nlinarith + have hbounds : -1 ≤ childGain mass table t i + (1 - κ) * childDecrement mass table t i ∧ + childGain mass table t i + (1 - κ) * childDecrement mass table t i ≤ 0 := by + rw [childGain_decrement_identity] + constructor + · apply (le_div_iff₀ hmass).2 + linarith + · exact div_nonpos_of_nonpos_of_nonneg (neg_nonpos.mpr hweighted0) hmass.le + constructor + · exact_mod_cast hbounds.1 + · exact_mod_cast hbounds.2 + +theorem multiplicative_spatial_absolute {x y mass δ charge : ℝ} + (hδ : 0 ≤ δ) (hx : x ≤ mass) (hy : y ≤ mass) + (hxy : x ≤ (1 + δ) * y + charge) (hyx : y ≤ (1 + δ) * x + charge) : + |x - y| ≤ δ * mass + charge := by + have hxm := mul_le_mul_of_nonneg_left hx hδ + have hym := mul_le_mul_of_nonneg_left hy hδ + apply abs_le.mpr + constructor <;> nlinarith + +theorem normalized_decrement_range {old new old' new' mass δ spatial : ℝ} + (hmass : 0 < mass) + (hold : |old - old'| ≤ δ * mass + spatial) + (hnew : |new - new'| ≤ δ * mass + spatial) : + |(old - new) / mass - (old' - new') / mass| ≤ 2 * δ + 2 * spatial / mass := by + have hid : (old - new) / mass - (old' - new') / mass = + ((old - old') - (new - new')) / mass := by ring + rw [hid, abs_div, abs_of_pos hmass] + apply (div_le_iff₀ hmass).2 + have htriangle := (abs_sub _ _).trans (add_le_add hold hnew) + have hcancel : (2 * δ + 2 * spatial / mass) * mass = 2 * δ * mass + 2 * spatial := by + field_simp + rw [hcancel] + linarith + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/CommonArrayFinal.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/CommonArrayFinal.lean new file mode 100644 index 0000000000000000000000000000000000000000..8fa4b058c9352b2b46765d193fa74bd070e6a409 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/CommonArrayFinal.lean @@ -0,0 +1,113 @@ +import OAI.Combinatorics.EditApproximation.Geometry.CommonArrayTrace + +namespace OAI + +/-! A final independent draw may be stored as the last array row. These +maps expose the literal product law used by the scheduled seed passes. -/ + +namespace EditApproximation + +open MeasureTheory ProbabilityTheory + +variable {Seed Ω Δ : Type} + +def commonArrayFinal (n : ℕ) (input : Seed × (Fin (n + 1) → Ω)) : + CommonSeedTrace Seed (fun _ => Ω) n × Ω := + (commonArrayToTrace n (input.1, fun i => input.2 i.castSucc), input.2 (Fin.last n)) + +def commonFinalArray (n : ℕ) (input : CommonSeedTrace Seed (fun _ => Ω) n × Ω) : + Seed × (Fin (n + 1) → Ω) := + let previous := commonTraceToArray n input.1 + (previous.1, Fin.snoc previous.2 input.2) + + theorem commonArrayFinal_inverse (n : ℕ) (input : Seed × (Fin (n + 1) → Ω)) : + commonFinalArray n (commonArrayFinal n input) = input := by + unfold commonFinalArray commonArrayFinal + rw [commonTraceToArray_toTrace] + apply Prod.ext + · rfl + funext i + refine Fin.lastCases ?_ (fun j => ?_) i <;> simp + + theorem commonFinalArray_inverse (n : ℕ) (input : CommonSeedTrace Seed (fun _ => Ω) n × Ω) : + commonArrayFinal n (commonFinalArray n input) = input := by + rcases input with ⟨trace, last⟩ + unfold commonFinalArray commonArrayFinal + simp only [Fin.snoc_last, Fin.snoc_castSucc] + exact Prod.ext (commonArrayToTrace_toArray n trace) rfl + +section Law + +variable [Fintype Seed] [Fintype Ω] [DecidableEq Seed] + [MeasurableSpace Seed] [MeasurableSingletonClass Seed] + [MeasurableSpace Ω] [MeasurableSingletonClass Ω] + (incoming : Measure Seed) [IsProbabilityMeasure incoming] + (random : Measure Ω) [IsProbabilityMeasure random] + +omit [DecidableEq Seed] [IsProbabilityMeasure incoming] in +theorem commonArrayFinal_law (n : ℕ) : + (incoming.prod (Measure.pi fun _ : Fin (n + 1) => random)).map (commonArrayFinal (Ω := Ω) n) = + (commonTraceLaw (fun _ => random) incoming n).prod random := by + classical + apply Measure.ext_of_singleton + rintro ⟨trace, last⟩ + rw [Measure.map_apply (measurable_of_finite _) (measurableSet_singleton _)] + have hpre : commonArrayFinal (Ω := Ω) n ⁻¹' {(trace, last)} = + {commonFinalArray n (trace, last)} := by + ext input + simp only [Set.mem_preimage, Set.mem_singleton_iff] + constructor + · intro h + rw [← h, commonArrayFinal_inverse] + · rintro rfl + exact commonFinalArray_inverse n (trace, last) + rw [hpre] + change (incoming.prod (Measure.pi fun _ : Fin (n + 1) => random)) + {((commonTraceToArray n trace).1, Fin.snoc (commonTraceToArray n trace).2 last)} = _ + rw [← Set.singleton_prod_singleton, Measure.prod_prod, Measure.pi_singleton, + Fin.prod_univ_castSucc] + simp only [Fin.snoc_castSucc, Fin.snoc_last] + rw [← mul_assoc, ← commonArrayToTrace_atom incoming random n (commonTraceToArray n trace), + commonArrayToTrace_toArray, ← Set.singleton_prod_singleton, Measure.prod_prod] + +end Law + +def mapCommonTrace (f : Ω → Δ) : (n : ℕ) → + CommonSeedTrace Seed (fun _ => Ω) n → CommonSeedTrace Seed (fun _ => Δ) n + | 0, seed => seed + | n + 1, trace => (mapCommonTrace f n trace.1, f trace.2) + + theorem mapCommonTrace_array (f : Ω → Δ) (n : ℕ) (input : Seed × (Fin n → Ω)) : + mapCommonTrace f n (commonArrayToTrace n input) = + commonArrayToTrace n (input.1, fun i => f (input.2 i)) := by + induction n with + | zero => rfl + | succ n ih => exact Prod.ext (ih _) rfl + +section MapLaw + +variable [Fintype Seed] [Fintype Ω] [Fintype Δ] [DecidableEq Seed] + [MeasurableSpace Seed] [MeasurableSingletonClass Seed] + [MeasurableSpace Ω] [MeasurableSingletonClass Ω] + [MeasurableSpace Δ] [MeasurableSingletonClass Δ] + (incoming : Measure Seed) [IsProbabilityMeasure incoming] + (random : Measure Ω) [IsProbabilityMeasure random] + +omit [Fintype Δ] [DecidableEq Seed] [MeasurableSingletonClass Δ] + [IsProbabilityMeasure incoming] [IsProbabilityMeasure random] in + theorem mapCommonTrace_law (f : Ω → Δ) (n : ℕ) : + (commonTraceLaw (fun _ => random) incoming n).map (mapCommonTrace f n) = + commonTraceLaw (fun _ => random.map f) incoming n := by + induction n with + | zero => exact Measure.map_id + | succ n ih => + change ((commonTraceLaw (fun _ => random) incoming n).prod random).map + (Prod.map (mapCommonTrace f n) f) = _ + rw [← Measure.map_prod_map _ _ (measurable_of_finite _) (measurable_of_finite _), ih] + rfl + +end MapLaw + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/CommonArrayTrace.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/CommonArrayTrace.lean new file mode 100644 index 0000000000000000000000000000000000000000..ce2658e4dee4168bb551f60bc7629e2b9e16e34d --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/CommonArrayTrace.lean @@ -0,0 +1,102 @@ +import OAI.Combinatorics.EditApproximation.Geometry.CommonSeedTrace +import Mathlib.MeasureTheory.Constructions.Pi + +namespace OAI + +/-! A finite array of fresh pass draws is equivalent to the sequential +common-source trace. The conversion has exactly the nested product law. -/ + +namespace EditApproximation + +open MeasureTheory ProbabilityTheory + +variable {Seed Ω : Type} + +def commonArrayToTrace : (n : ℕ) → Seed × (Fin n → Ω) → CommonSeedTrace Seed (fun _ => Ω) n + | 0, input => input.1 + | n + 1, input => (commonArrayToTrace n (input.1, fun i => input.2 i.castSucc), input.2 (Fin.last n)) + +def commonTraceToArray : (n : ℕ) → CommonSeedTrace Seed (fun _ => Ω) n → Seed × (Fin n → Ω) + | 0, seed => (seed, Fin.elim0) + | n + 1, trace => + let previous := commonTraceToArray n trace.1 + (previous.1, Fin.snoc previous.2 trace.2) + + theorem commonTraceToArray_toTrace (n : ℕ) (input : Seed × (Fin n → Ω)) : + commonTraceToArray n (commonArrayToTrace n input) = input := by + induction n with + | zero => + apply Prod.ext + · rfl + funext i + exact Fin.elim0 i + | succ n ih => + simp only [commonArrayToTrace, commonTraceToArray, ih] + apply Prod.ext + · rfl + funext i + refine Fin.lastCases ?_ (fun j => ?_) i + · simp + · simp + + theorem commonArrayToTrace_toArray (n : ℕ) (trace : CommonSeedTrace Seed (fun _ => Ω) n) : + commonArrayToTrace n (commonTraceToArray n trace) = trace := by + induction n with + | zero => rfl + | succ n ih => + rcases trace with ⟨trace, last⟩ + simp only [commonArrayToTrace, commonTraceToArray, Fin.snoc_last, Fin.snoc_castSucc] + exact Prod.ext (ih trace) rfl + +section Law + +variable [Fintype Seed] [Fintype Ω] [DecidableEq Seed] + [MeasurableSpace Seed] [MeasurableSingletonClass Seed] + [MeasurableSpace Ω] [MeasurableSingletonClass Ω] + (incoming : Measure Seed) [IsProbabilityMeasure incoming] + (random : Measure Ω) [IsProbabilityMeasure random] + +omit [Fintype Seed] [DecidableEq Seed] [MeasurableSingletonClass Seed] + [MeasurableSingletonClass Ω] [IsProbabilityMeasure incoming] [IsProbabilityMeasure random] in +theorem commonArrayToTrace_atom (n : ℕ) (input : Seed × (Fin n → Ω)) : + (commonTraceLaw (fun _ => random) incoming n) {commonArrayToTrace n input} = + incoming {input.1} * ∏ i, random {input.2 i} := by + induction n with + | zero => + simp only [commonArrayToTrace, commonTraceLaw, Fin.prod_univ_zero, mul_one] + rfl + | succ n ih => + change ((commonTraceLaw (fun _ => random) incoming n).prod random) + {(commonArrayToTrace n (input.1, fun i => input.2 i.castSucc), input.2 (Fin.last n))} = _ + rw [← Set.singleton_prod_singleton, Measure.prod_prod, ih, Fin.prod_univ_castSucc] + exact mul_assoc _ _ _ + +omit [DecidableEq Seed] [IsProbabilityMeasure incoming] in +theorem commonArrayToTrace_law (n : ℕ) : + (incoming.prod (Measure.pi fun _ : Fin n => random)).map (commonArrayToTrace (Ω := Ω) n) = + commonTraceLaw (fun _ => random) incoming n := by + classical + apply Measure.ext_of_singleton + intro trace + rw [Measure.map_apply (measurable_of_finite _) (measurableSet_singleton _)] + have hpre : commonArrayToTrace (Ω := Ω) n ⁻¹' {trace} = {commonTraceToArray n trace} := by + ext input + simp only [Set.mem_preimage, Set.mem_singleton_iff] + constructor + · intro h + rw [← h, commonTraceToArray_toTrace] + · rintro rfl + exact commonArrayToTrace_toArray n trace + rw [hpre] + change (incoming.prod (Measure.pi fun _ : Fin n => random)) + {((commonTraceToArray n trace).1, (commonTraceToArray n trace).2)} = _ + rw [← Set.singleton_prod_singleton, Measure.prod_prod, Measure.pi_singleton] + have h := commonArrayToTrace_atom incoming random n (commonTraceToArray n trace) + rw [commonArrayToTrace_toArray] at h + exact h.symm + +end Law + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/CommonRangeSource.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/CommonRangeSource.lean new file mode 100644 index 0000000000000000000000000000000000000000..a7851a798277a317499e08646b04fe9944700c1d --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/CommonRangeSource.lean @@ -0,0 +1,74 @@ +import OAI.Combinatorics.EditApproximation.Probability.AdaptiveMarginalLaw +import OAI.Combinatorics.EditApproximation.Probability.FiniteKeyRestriction +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! The online draw range depends on earlier seed values. A common random +source is indexed by the physical key and the requested positive range, +not by an entire hypothetical seed table. The unused coordinates exist +only in the probability space. -/ + +namespace EditApproximation + +open MeasureTheory ProbabilityTheory + + + + + + +theorem positiveDrawRangeOfLE_val (B n : ℕ) (hn : 0 < n) (hB : n ≤ B) : + (positiveDrawRangeOfLE B n hn hB).val.val = n := rfl + + + +abbrev CommonRangeDraw (ι : Type*) (B R : ℕ) := + ∀ key : CommonRangeKey ι B, Fin R → Fin key.2.val.val + +noncomputable def commonRangeLaw {ι : Type*} [Fintype ι] (B R : ℕ) : + Measure (CommonRangeDraw ι B R) := + Measure.pi fun key : CommonRangeKey ι B => + Measure.pi fun _ : Fin R => (PMF.uniformOfFintype (Fin key.2.val.val)).toMeasure + +instance commonRangeLaw_probability {ι : Type*} [Fintype ι] (B R : ℕ) : + IsProbabilityMeasure (commonRangeLaw (ι := ι) B R) := by + unfold commonRangeLaw + infer_instance + +section Range + +variable {Seed ι : Type*} [Fintype ι] (B R : ℕ) (range : Seed → ι → ℕ) + [∀ seed key, NeZero (range seed key)] (hbounded : ∀ seed key, range seed key ≤ B) + +def commonRangeSelectedKey (seed : Seed) (key : ι) : CommonRangeKey ι B := + (key, ⟨⟨range seed key, Nat.lt_succ_of_le (hbounded seed key)⟩, Nat.pos_of_ne_zero (NeZero.ne (range seed key))⟩) + +omit [Fintype ι] in +theorem commonRangeSelectedKey_injective (seed : Seed) : + Function.Injective (commonRangeSelectedKey B range hbounded seed) := by + intro left right heq + exact congrArg Prod.fst heq + +def commonRangeSample (seed : Seed) (draw : CommonRangeDraw ι B R) : + ∀ key, Fin R → Fin (range seed key) := + fun key => draw (commonRangeSelectedKey B range hbounded seed key) + +theorem commonRangeSample_law (seed : Seed) : + (commonRangeLaw (ι := ι) B R).map (commonRangeSample B R range hbounded seed) = + Measure.pi fun key => Measure.pi fun _ : Fin R => + (PMF.uniformOfFintype (Fin (range seed key))).toMeasure := by + have h := finite_pi_restrict_map + (fun key : CommonRangeKey ι B => Measure.pi fun _ : Fin R => + (PMF.uniformOfFintype (Fin key.2.val.val)).toMeasure) + (commonRangeSelectedKey B range hbounded seed) + (commonRangeSelectedKey_injective B range hbounded seed) + exact h + + +end Range + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/CommonSeedTrace.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/CommonSeedTrace.lean new file mode 100644 index 0000000000000000000000000000000000000000..3ac7091ef57b4c844230beeabe0e1e62335e6305 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/CommonSeedTrace.lean @@ -0,0 +1,103 @@ +import OAI.Combinatorics.EditApproximation.Probability.AdaptiveMarginalLaw + +namespace OAI + +/-! Adaptive seed passes driven by common per-pass random sources. The +trace stores one source for the actual pass, with no seed-indexed family. +Its returned seed has the original adaptive law. -/ + +namespace EditApproximation + +open MeasureTheory ProbabilityTheory + +def CommonSeedTrace (Seed : Type) (Ω : ℕ → Type) : ℕ → Type + | 0 => Seed + | pass + 1 => CommonSeedTrace Seed Ω pass × Ω pass + +instance commonSeedTraceFintype (Seed : Type) (Ω : ℕ → Type) + [Fintype Seed] [∀ pass, Fintype (Ω pass)] : (pass : ℕ) → Fintype (CommonSeedTrace Seed Ω pass) + | 0 => inferInstanceAs (Fintype Seed) + | pass + 1 => + letI := commonSeedTraceFintype Seed Ω pass + inferInstanceAs (Fintype (CommonSeedTrace Seed Ω pass × Ω pass)) + +instance commonSeedTraceMeasurable (Seed : Type) (Ω : ℕ → Type) + [MeasurableSpace Seed] [∀ pass, MeasurableSpace (Ω pass)] : + (pass : ℕ) → MeasurableSpace (CommonSeedTrace Seed Ω pass) + | 0 => inferInstanceAs (MeasurableSpace Seed) + | pass + 1 => + letI := commonSeedTraceMeasurable Seed Ω pass + inferInstanceAs (MeasurableSpace (CommonSeedTrace Seed Ω pass × Ω pass)) + +instance commonSeedTraceSingleton (Seed : Type) (Ω : ℕ → Type) + [MeasurableSpace Seed] [MeasurableSingletonClass Seed] + [∀ pass, MeasurableSpace (Ω pass)] [∀ pass, MeasurableSingletonClass (Ω pass)] : + (pass : ℕ) → MeasurableSingletonClass (CommonSeedTrace Seed Ω pass) + | 0 => inferInstanceAs (MeasurableSingletonClass Seed) + | pass + 1 => + letI := commonSeedTraceSingleton Seed Ω pass + inferInstanceAs (MeasurableSingletonClass (CommonSeedTrace Seed Ω pass × Ω pass)) + +section Common + +variable {Seed : Type} [Fintype Seed] [DecidableEq Seed] + [MeasurableSpace Seed] [MeasurableSingletonClass Seed] + {Draw : ℕ → Seed → Type} [∀ pass seed, Fintype (Draw pass seed)] + [∀ pass seed, MeasurableSpace (Draw pass seed)] + [∀ pass seed, MeasurableSingletonClass (Draw pass seed)] + {Ω : ℕ → Type} [∀ pass, Fintype (Ω pass)] + [∀ pass, MeasurableSpace (Ω pass)] [∀ pass, MeasurableSingletonClass (Ω pass)] + (drawLaw : ∀ pass seed, Measure (Draw pass seed)) + [∀ pass seed, IsProbabilityMeasure (drawLaw pass seed)] + (randomLaw : ∀ pass, Measure (Ω pass)) [∀ pass, IsProbabilityMeasure (randomLaw pass)] + (sample : ∀ pass seed, Ω pass → Draw pass seed) + (next : ∀ pass seed, Draw pass seed → Seed) + +noncomputable def commonTraceValue : (pass : ℕ) → CommonSeedTrace Seed Ω pass → Seed + | 0, seed => seed + | pass + 1, trace => + let seed := commonTraceValue pass trace.1 + next pass seed (sample pass seed trace.2) + +noncomputable def commonTraceLaw (incoming : Measure Seed) : + (pass : ℕ) → Measure (CommonSeedTrace Seed Ω pass) + | 0 => incoming + | pass + 1 => (commonTraceLaw incoming pass).prod (randomLaw pass) + +instance commonTraceLaw_probability (incoming : Measure Seed) [IsProbabilityMeasure incoming] + (pass : ℕ) : IsProbabilityMeasure (commonTraceLaw randomLaw incoming pass) := by + induction pass with + | zero => exact inferInstanceAs (IsProbabilityMeasure incoming) + | succ pass ih => + let := ih + exact inferInstanceAs (IsProbabilityMeasure + ((commonTraceLaw randomLaw incoming pass).prod (randomLaw pass))) + +theorem commonTraceLaw_map (incoming : Measure Seed) [IsProbabilityMeasure incoming] + (hmarginal : ∀ pass seed, (randomLaw pass).map (sample pass seed) = drawLaw pass seed) + (passes : ℕ) : + (commonTraceLaw randomLaw incoming passes).map (commonTraceValue sample next passes) = + adaptiveSeedSequence drawLaw incoming next passes := by + induction passes with + | zero => exact Measure.map_id + | succ pass ih => + let reindex : CommonSeedTrace Seed Ω pass × Ω pass → Seed × Ω pass := + Prod.map (commonTraceValue sample next pass) id + let step : Seed × Ω pass → Seed := fun pair => next pass pair.1 (sample pass pair.1 pair.2) + have hvalue : commonTraceValue sample next (pass + 1) = step ∘ reindex := rfl + have hproduct : ((commonTraceLaw randomLaw incoming pass).prod (randomLaw pass)).map reindex = + ((commonTraceLaw randomLaw incoming pass).map (commonTraceValue sample next pass)).prod + (randomLaw pass) := by + simpa only [Measure.map_id] using + (Measure.map_prod_map (commonTraceLaw randomLaw incoming pass) (randomLaw pass) + (measurable_of_finite (commonTraceValue sample next pass)) measurable_id).symm + change ((commonTraceLaw randomLaw incoming pass).prod (randomLaw pass)).map _ = _ + rw [hvalue, ← Measure.map_map (measurable_of_finite _) (measurable_of_finite _), hproduct, ih] + exact adaptiveSeedLaw_eq_of_marginals (drawLaw pass) (randomLaw pass) (sample pass) + (hmarginal pass) (adaptiveSeedSequence drawLaw incoming next pass) (next pass) + +end Common + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/ComparisonAccounting.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/ComparisonAccounting.lean new file mode 100644 index 0000000000000000000000000000000000000000..fe234a6c50d7e9608de450795789a8965da8a9a3 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/ComparisonAccounting.lean @@ -0,0 +1,66 @@ +import OAI.Combinatorics.EditApproximation.Geometry.TreeAccounting + +namespace OAI + +/-! +# Accuracy accounting on the comparison tree + +The clipped regrets cancel across every physical frontier. Terminal nodes +can be carried forward in one child slot, with zero in the others, as in +the complete-tree representation used for the curvature accounting. +-/ + +namespace EditApproximation + +open Finset + +theorem tree_regret_telescope (M J : ℕ) + (value charge : (d : ℕ) → TreeLayer M d → ℝ) : + (∑ d ∈ range J, ∑ node : TreeLayer M d, + (value d node - charge d node - + ∑ child : Fin M, value (d + 1) (node, child))) = + value 0 PUnit.unit - (∑ node : TreeLayer M J, value J node) - + ∑ d ∈ range J, ∑ node : TreeLayer M d, charge d node := by + have hpoint d (node : TreeLayer M d) : + value d node - charge d node - (∑ child : Fin M, value (d + 1) (node, child)) = + (value d node - ∑ child : Fin M, value (d + 1) (node, child)) - charge d node := by ring + simp_rw [hpoint, sum_sub_distrib] + have htelescope := tree_frontier_telescope M J value + simp only [sum_sub_distrib] at htelescope + rw [htelescope] + +theorem tree_regret_time_bound (M J S : ℕ) + (value : ℕ → (d : ℕ) → TreeLayer M d → ℝ) + (charge : (d : ℕ) → TreeLayer M d → ℝ) (terminalBound : ℝ) + (hmonotone : ∀ t < S, value S 0 PUnit.unit ≤ value (t + 1) 0 PUnit.unit) + (hterminal : ∀ t < S, (∑ node : TreeLayer M J, value (t + 1) J node) ≤ terminalBound) : + (S : ℝ) * value S 0 PUnit.unit ≤ + (S : ℝ) * (terminalBound + ∑ d ∈ range J, ∑ node : TreeLayer M d, charge d node) + + ∑ t ∈ range S, ∑ d ∈ range J, ∑ node : TreeLayer M d, + (value (t + 1) d node - charge d node - + ∑ child : Fin M, value (t + 1) (d + 1) (node, child)) := by + have hpoint (t : ℕ) (ht : t ∈ range S) : value S 0 PUnit.unit ≤ + terminalBound + (∑ d ∈ range J, ∑ node : TreeLayer M d, charge d node) + + ∑ d ∈ range J, ∑ node : TreeLayer M d, + (value (t + 1) d node - charge d node - + ∑ child : Fin M, value (t + 1) (d + 1) (node, child)) := by + rw [tree_regret_telescope] + linarith [hmonotone t (mem_range.mp ht), hterminal t (mem_range.mp ht)] + have hsum := sum_le_sum hpoint + simpa only [sum_add_distrib, sum_const, card_range, nsmul_eq_mul, mul_add] using hsum + +/-- Dividing the time telescope yields the positive-excess estimate. +For clipped root values, `root-D` is exactly the positive part of error. -/ +theorem root_excess_from_time_bound {S root D terminal charge regret error : ℝ} + (hS : 0 < S) + (htime : S * root ≤ S * (terminal + charge) + regret) + (hterminal : terminal + charge ≤ D + error * D) + (hregret : regret ≤ S * error * D) : + root - D ≤ 2 * error * D := by + have hmain := mul_le_mul_of_nonneg_left hterminal hS.le + have hbound : S * (root - D) ≤ S * (2 * error * D) := by nlinarith + exact (mul_le_mul_iff_right₀ hS).mp hbound + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/ComparisonBandCoverage.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/ComparisonBandCoverage.lean new file mode 100644 index 0000000000000000000000000000000000000000..b19fc46b06aad9038e3a8d8c94884d5c2fffc2be --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/ComparisonBandCoverage.lean @@ -0,0 +1,219 @@ +import OAI.Combinatorics.EditApproximation.Geometry.RepresentativeBands +import OAI.Combinatorics.EditApproximation.Geometry.Curvature + +namespace OAI + +/-! +# Comparison action coverage by the computed predictor + +Masses, gaps, prefix costs and curvature are those of the actual labeled +comparison action. The finite wide-action minimum supplies Z. No scalar +prefix prediction contract is assumed. +-/ + +namespace EditApproximation + +open Finset + +noncomputable def comparisonActionMass {ny M : ℕ} + (comparison : Fin M → TargetInterval ny) (child : Fin M → TargetInterval ny → ℝ) : ℝ := + ∑ i, child i (comparison i) + +noncomputable def comparisonActionCurvature {α : Type*} (source target : List α) + {M : ℕ} (parent : TargetInterval source.length) (r : TargetInterval target.length) + (comparison : Fin M → TargetInterval target.length) + (child : Fin M → TargetInterval target.length → ℝ) : ℝ := + (∑ i, (stateLengthGap + (substring source (sourceChild parent i).lo (sourceChild parent i).hi) target (comparison i)) ^ 2 / + child i (comparison i)) - + (stateLengthGap (substring source parent.lo parent.hi) target r) ^ 2 / + comparisonActionMass comparison child + +theorem comparisonPrefixShift_origin {nx ny M : ℕ} (parent : TargetInterval nx) + (r : TargetInterval ny) (comparison : Fin M → TargetInterval ny) + (hzero : endpointActionConnection r comparison = 0) : + comparisonPrefixShift parent r comparison 0 = (r.lo : ℝ) - parent.lo := by + have h := (zero_connection_prefix_suffix r comparison 0 hzero).1 + simp only [List.take_zero, realConnectionBudget] at h + have heq : (connectionPrefixBoundary (List.ofFn comparison) r.hi 0 : ℝ) = r.lo := + (sub_eq_zero.mp (abs_eq_zero.mp h)).symm + simp only [comparisonPrefixShift, balancedCut_zero, heq] + +/-- The actual comparison prefix prediction error is at most +`sqrt(W*K) + 2*(W-Z)`. All mass, gap and finite-minimum inequalities are +derived from the genuine child table lower invariant. -/ +theorem comparisonPrefixPrediction_error {α : Type*} (source target : List α) + {M b P : ℕ} (hM : 0 < M) (parent : TargetInterval source.length) + (r : TargetInterval target.length) (comparison : Fin M → TargetInterval target.length) + (hcomparison : comparison ∈ wideActionList M parent r b P) + (hnonempty : wideActionList M parent r b P ≠ []) + (child : Fin M → TargetInterval target.length → ℝ) + (a : ℝ) (ha : 1 ≤ a) + (hchild : ∀ i s, max ((stateEditCost + (substring source (sourceChild parent i).lo (sourceChild parent i).hi) target s : ℝ) / a) + |stateLengthGap (substring source (sourceChild parent i).lo (sourceChild parent i).hi) target s| ≤ + child i s) + (hzero : endpointActionConnection r comparison = 0) + (hZpos : 0 < wideActionMinimum parent r b P hnonempty child) + (j : ℕ) (hj : j ≤ M) : + |comparisonPrefixShift parent r comparison j - ((r.lo : ℝ) - parent.lo) - + (stateLengthGap (substring source parent.lo parent.hi) target r / + wideActionMinimum parent r b P hnonempty child) * + widePrefixMinimum parent r (wideActionList M parent r b P) hnonempty child j + (comparisonPrefixShift parent r comparison j)| ≤ + Real.sqrt (comparisonActionMass comparison child * + comparisonActionCurvature source target parent r comparison child) + + 2 * (comparisonActionMass comparison child - wideActionMinimum parent r b P hnonempty child) := by + let mass := fun i : Fin M => child i (comparison i) + let gap := fun i : Fin M => stateLengthGap + (substring source (sourceChild parent i).lo (sourceChild parent i).hi) target (comparison i) + let W := comparisonActionMass comparison child + let Z := wideActionMinimum parent r b P hnonempty child + let parentGap := stateLengthGap (substring source parent.lo parent.hi) target r + let K := comparisonActionCurvature source target parent r comparison child + let prefixMass := comparisonPrefixValue comparison child j + let point := comparisonPrefixShift parent r comparison j + let origin := (r.lo : ℝ) - parent.lo + let predictor := widePrefixMinimum parent r (wideActionList M parent r b P) hnonempty child j point + have hgap (i : Fin M) : |gap i| ≤ mass i := (le_max_right _ _).trans (hchild i (comparison i)) + have hmass (i : Fin M) : 0 ≤ mass i := (abs_nonneg _).trans (hgap i) + have hzeroMass (i : Fin M) (hi : mass i = 0) : gap i = 0 := by + have h := hgap i + rw [hi] at h + exact abs_eq_zero.mp (le_antisymm h (abs_nonneg _)) + have hsum : (∑ i, gap i) = parentGap := zero_connection_gap_sum source target hM parent r comparison hzero + have hZW : Z ≤ W := by + have h := wideActionMinimum_le_member parent r hnonempty child comparison hcomparison + simpa only [Z, W, comparisonActionMass, endpointActionValue, hzero, Nat.cast_zero, zero_add] using h + have hZ : 0 < Z := hZpos + have hW : 0 < W := hZ.trans_le hZW + have hG : 0 ≤ W - Z := sub_nonneg.mpr hZW + have hparentGap : |parentGap| ≤ Z := + (le_max_right _ _).trans (wideActionMinimum_lower source target hM parent r b P hnonempty a ha child hchild) + have hvelocity : |parentGap / Z| ≤ 1 := by + rw [abs_div, abs_of_pos hZpos] + exact (div_le_one hZpos).2 hparentGap + have hprediction : |parentGap / W - parentGap / Z| * W ≤ W - Z := by + have hid : (parentGap / W - parentGap / Z) * W = -(parentGap / Z) * (W - Z) := by + field_simp [hW.ne', hZ.ne'] + ring + calc + _ = |(parentGap / W - parentGap / Z) * W| := by rw [abs_mul, abs_of_pos hW] + _ = |parentGap / Z| * (W - Z) := by rw [hid, abs_mul, abs_neg, abs_of_nonneg hG] + _ ≤ 1 * (W - Z) := mul_le_mul_of_nonneg_right hvelocity hG + _ = _ := one_mul _ + have hprefix : 0 ≤ prefixMass := sum_nonneg (fun i _ => by + dsimp only [mass] at hmass + by_cases hi : i.val < j + · simpa only [comparisonPrefixValue, hi, ite_eq_left] using hmass i + · simp only [hi, ↓reduceIte, le_refl]) + have hprefixTotal : prefixMass ≤ W := by + apply sum_le_sum + intro i hi + by_cases hij : i.val < j + · simp only [hij, ↓reduceIte, le_refl] + · simpa only [hij, ↓reduceIte] using hmass i + have hcost := comparisonPrefixMinimum_actual_bounds parent r comparison hcomparison hnonempty child j hj hzero + have hcurvature := curvature_l1_le_sqrt univ mass gap + (fun i _ => hmass i) (fun i _ hi => hzeroMass i hi) hW + rw [hsum] at hcurvature + change (∑ i, |gap i - (parentGap / W) * mass i|) ≤ Real.sqrt (W * K) at hcurvature + have hprefixGap := comparisonPrefixShift_gap_sum source target hM parent r comparison j hj hzero + rw [comparisonPrefixShift_origin parent r comparison hzero] at hprefixGap + have hdecomposition : point - origin - (parentGap / W) * prefixMass = + ∑ i, if i.val < j then gap i - (parentGap / W) * mass i else 0 := by + rw [hprefixGap] + simp only [prefixMass, comparisonPrefixValue] + rw [mul_sum, ← sum_sub_distrib] + apply sum_congr rfl + intro i hi + by_cases hij : i.val < j <;> simp only [hij, ↓reduceIte, mul_zero, sub_zero, mass, gap] + have hdeviation : |point - origin - (parentGap / W) * prefixMass| ≤ Real.sqrt (W * K) := by + rw [hdecomposition] + apply (abs_sum_le_sum_abs _ _).trans + apply (sum_le_sum (fun i _ => ?_)).trans hcurvature + by_cases hij : i.val < j + · simp only [hij, ↓reduceIte, le_refl] + · simp only [hij, ↓reduceIte, abs_zero] + exact abs_nonneg _ + exact comparison_prefix_prediction_error hprefix hprefixTotal hprediction hvelocity + hcost.1 hcost.2 hdeviation + +/-- The derived analytic estimate places the actual comparison action in +the literal rational finite filter once its explicit numerical budget holds. -/ +theorem comparison_computedBandActions_mem {α : Type*} (source target : List α) + {M b P : ℕ} (hM : 0 < M) (parent : TargetInterval source.length) + (r : TargetInterval target.length) (comparison : Fin M → TargetInterval target.length) + (hcomparison : comparison ∈ wideActionList M parent r b P) + (hnonempty : wideActionList M parent r b P ≠ []) + (tau theta : ℚ) (child : Fin M → TargetInterval target.length → ℚ) + (a : ℝ) (ha : 1 ≤ a) + (hchild : ∀ i s, max ((stateEditCost + (substring source (sourceChild parent i).lo (sourceChild parent i).hi) target s : ℝ) / a) + |stateLengthGap (substring source (sourceChild parent i).lo (sourceChild parent i).hi) target s| ≤ + (child i s : ℝ)) + (hzero : endpointActionConnection r comparison = 0) + (hanchors : ∀ i, Nat.dist (r.lo + ((sourceChild parent i).lo - parent.lo)) (comparison i).lo ≤ 6 * b ∧ + Nat.dist (r.lo + ((sourceChild parent i).hi - parent.lo)) (comparison i).hi ≤ 6 * b) + (hZpos : 0 < rationalWideActionMinimum parent r b P hnonempty child) + (hvelocity : |rationalStateGap (substring source parent.lo parent.hi) target r / + rationalWideActionMinimum parent r b P hnonempty child| ≤ 1 - tau) + (hnumerical : Real.sqrt (comparisonActionMass comparison (fun i s => (child i s : ℝ)) * + comparisonActionCurvature source target parent r comparison (fun i s => (child i s : ℝ))) + + 2 * (comparisonActionMass comparison (fun i s => (child i s : ℝ)) - + wideActionMinimum parent r b P hnonempty (fun i s => (child i s : ℝ))) ≤ + (tau : ℝ) * theta * b / M) : + comparison ∈ computedBandActions parent r b P tau theta + (rationalStateGap (substring source parent.lo parent.hi) target r / + rationalWideActionMinimum parent r b P hnonempty child) child := by + apply computedBandActions_complete parent r b P tau theta _ child comparison hnonempty hcomparison hvelocity + refine ⟨hzero, hanchors, ?_⟩ + intro j hj + have hZreal : 0 < wideActionMinimum parent r b P hnonempty (fun i s => (child i s : ℝ)) := by + rw [← rationalWideActionMinimum_cast] + exact_mod_cast hZpos + have herror := comparisonPrefixPrediction_error source target hM parent r comparison hcomparison hnonempty + (fun i s => (child i s : ℝ)) a ha hchild hzero hZreal j.val (Nat.le_of_lt j.isLt) + have hbound := herror.trans hnumerical + have hpoint : ((bandCutShift parent comparison j : ℚ) : ℝ) = + comparisonPrefixShift parent r comparison j.val := by + rw [comparisonPrefixShift_at_child] + simp only [bandCutShift, Rat.cast_sub, Rat.cast_natCast] + apply (Rat.cast_le (K := ℝ)).mp + simp only [Rat.cast_abs, Rat.cast_sub, Rat.cast_natCast, Rat.cast_div, Rat.cast_mul, + rationalStateGap_cast, rationalWideActionMinimum_cast, rationalWidePrefixMinimum_cast] + rw [hpoint] + exact hbound + +/-- The representative wrapper computes precisely the velocity used in +the preceding finite-filter membership result. -/ +theorem comparison_representativeBandActions_mem {α : Type*} (source target : List α) + {M b P : ℕ} (hM : 0 < M) (parent : TargetInterval source.length) + (r : TargetInterval target.length) (comparison : Fin M → TargetInterval target.length) + (hcomparison : comparison ∈ wideActionList M parent r b P) + (hnonempty : wideActionList M parent r b P ≠ []) + (tau theta : ℚ) (child : Fin M → TargetInterval target.length → ℚ) + (a : ℝ) (ha : 1 ≤ a) + (hchild : ∀ i s, max ((stateEditCost + (substring source (sourceChild parent i).lo (sourceChild parent i).hi) target s : ℝ) / a) + |stateLengthGap (substring source (sourceChild parent i).lo (sourceChild parent i).hi) target s| ≤ + (child i s : ℝ)) + (hzero : endpointActionConnection r comparison = 0) + (hanchors : ∀ i, Nat.dist (r.lo + ((sourceChild parent i).lo - parent.lo)) (comparison i).lo ≤ 6 * b ∧ + Nat.dist (r.lo + ((sourceChild parent i).hi - parent.lo)) (comparison i).hi ≤ 6 * b) + (hZpos : 0 < rationalWideActionMinimum parent r b P hnonempty child) + (hvelocity : |rationalStateGap (substring source parent.lo parent.hi) target r / + rationalWideActionMinimum parent r b P hnonempty child| ≤ 1 - tau) + (hnumerical : Real.sqrt (comparisonActionMass comparison (fun i s => (child i s : ℝ)) * + comparisonActionCurvature source target parent r comparison (fun i s => (child i s : ℝ))) + + 2 * (comparisonActionMass comparison (fun i s => (child i s : ℝ)) - + wideActionMinimum parent r b P hnonempty (fun i s => (child i s : ℝ))) ≤ + (tau : ℝ) * theta * b / M) : + comparison ∈ representativeBandActions source target parent r b P tau theta child := by + simp only [representativeBandActions, dite_eq_right hnonempty, ite_eq_left hZpos] + exact comparison_computedBandActions_mem source target hM parent r comparison hcomparison hnonempty + tau theta child a ha hchild hzero hanchors hZpos hvelocity hnumerical + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/ComparisonBounds.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/ComparisonBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..5d6288e0597fd06ff1b9f611f69ee87bc68fe069 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/ComparisonBounds.lean @@ -0,0 +1,182 @@ +import OAI.Combinatorics.EditApproximation.Geometry.ComparisonTree + +namespace OAI + +/-! Actual terminal, nonterminal-cost and endpoint-movement bounds. -/ + +namespace EditApproximation + +open Finset + +noncomputable def comparisonActiveCost {α : Type*} (source target : List α) : + ComparisonState source.length target.length → ℝ := by + classical + exact fun node => match node with + | none => 0 + | some (parent, q) => if comparisonStopped source target parent q then 0 + else stateEditCost (substring source parent.lo parent.hi) target q + +noncomputable def comparisonMovement {α : Type*} (source target : List α) (P : ℕ) : + ComparisonState source.length target.length → ℝ := by + classical + exact fun node => match node with + | none => 0 + | some (parent, q) => if comparisonStopped source target parent q then 0 else + targetEndpointDistance q (roundInterval (seedGridSpacing + (2 ^ Nat.log 2 (stateEditCost (substring source parent.lo parent.hi) target q)) P) q) + +theorem comparisonActiveCost_bounds {α : Type*} (source target : List α) + (node : ComparisonState source.length target.length) : + 0 ≤ comparisonActiveCost source target node ∧ + comparisonActiveCost source target node ≤ comparisonStateCost source target node := by + classical + cases node with + | none => exact ⟨le_rfl, le_rfl⟩ + | some state => + rcases state with ⟨parent, q⟩ + by_cases hs : comparisonStopped source target parent q + · simp only [comparisonActiveCost, ite_eq_left hs, comparisonStateCost] + exact ⟨le_rfl, Nat.cast_nonneg _⟩ + · simp only [comparisonActiveCost, ite_eq_right hs, comparisonStateCost] + exact ⟨Nat.cast_nonneg _, le_rfl⟩ + +theorem comparisonMovement_bound {α : Type*} (source target : List α) + (P : ℕ) (hP : 0 < P) (node : ComparisonState source.length target.length) : + comparisonMovement source target P node * P ≤ 2 * comparisonActiveCost source target node := by + classical + cases node with + | none => simp only [comparisonMovement, comparisonActiveCost, zero_mul, mul_zero, le_refl] + | some state => + rcases state with ⟨parent, q⟩ + by_cases hs : comparisonStopped source target parent q + · simp only [comparisonMovement, comparisonActiveCost, ite_eq_left hs, zero_mul, mul_zero, le_refl] + · have hc : 0 < stateEditCost (substring source parent.lo parent.hi) target q := by + unfold comparisonStopped at hs + omega + have hb := (cost_dyadicScale _ _ hc le_rfl).2.1 + have herror := rounded_seedGrid_error + (2 ^ Nat.log 2 (stateEditCost (substring source parent.lo parent.hi) target q)) P hP q + have herrorR : (targetEndpointDistance q (roundInterval (seedGridSpacing + (2 ^ Nat.log 2 (stateEditCost (substring source parent.lo parent.hi) target q)) P) q) : ℝ) * P ≤ + 2 * (2 ^ Nat.log 2 (stateEditCost (substring source parent.lo parent.hi) target q) : ℕ) := by + exact_mod_cast herror + have hbR : ((2 ^ Nat.log 2 (stateEditCost (substring source parent.lo parent.hi) target q) : ℕ) : ℝ) ≤ + stateEditCost (substring source parent.lo parent.hi) target q := by exact_mod_cast hb + simp only [comparisonMovement, comparisonActiveCost, ite_eq_right hs] + linarith + +theorem comparison_total_active_cost_bound {α : Type*} (source target : List α) + {M : ℕ} (hM : 0 < M) (P : ℕ) (hP : 66 ≤ P) + (root : ComparisonState source.length target.length) (J : ℕ) + (hsmall : (J : ℝ) * (4 * (M : ℝ) / P) ≤ 1 / 2) : + (∑ d ∈ range J, ∑ node : TreeLayer M d, comparisonActiveCost source target + (comparisonFrontier source target hM P hP root d node)) ≤ + 2 * J * comparisonStateCost source target root := by + have hlevel (d : ℕ) (hd : d ∈ range J) : + (∑ node : TreeLayer M d, comparisonActiveCost source target + (comparisonFrontier source target hM P hP root d node)) ≤ + 2 * comparisonStateCost source target root := by + exact (sum_le_sum (fun node _ => (comparisonActiveCost_bounds source target _).2)).trans + (comparison_frontier_cost_le_twice source target hM P hP root J d (mem_range.mp hd).le hsmall) + have hsum := sum_le_sum hlevel + simpa only [sum_const, card_range, nsmul_eq_mul, mul_assoc, mul_left_comm] using hsum + +theorem comparison_total_movement_bound {α : Type*} (source target : List α) + {M : ℕ} (hM : 0 < M) (P : ℕ) (hP : 66 ≤ P) + (root : ComparisonState source.length target.length) (J : ℕ) + (hsmall : (J : ℝ) * (4 * (M : ℝ) / P) ≤ 1 / 2) : + (∑ d ∈ range J, ∑ node : TreeLayer M d, comparisonMovement source target P + (comparisonFrontier source target hM P hP root d node)) ≤ + 4 * J * comparisonStateCost source target root / P := by + have hPpos : 0 < P := by omega + have hPr : (0 : ℝ) < P := by exact_mod_cast hPpos + have hsum := sum_le_sum (fun d (_ : d ∈ range J) => sum_le_sum + (fun node (_ : node ∈ (univ : Finset (TreeLayer M d))) => + comparisonMovement_bound source target P hPpos + (comparisonFrontier source target hM P hP root d node))) + simp only [← sum_mul, ← mul_sum] at hsum + have hcost := comparison_total_active_cost_bound source target hM P hP root J hsmall + apply (le_div_iff₀ hPr).2 + linarith + +theorem comparisonStep_stopped_or_width {α : Type*} (source target : List α) + {M : ℕ} (hM : 0 < M) (P : ℕ) (hP : 66 ≤ P) + (node : ComparisonState source.length target.length) (w : ℕ) + (hnode : ∀ parent q, node = some (parent, q) → + comparisonStopped source target parent q ∨ parent.hi - parent.lo ≤ w) + (i : Fin M) (resultParent : TargetInterval source.length) (resultQ : TargetInterval target.length) + (heq : comparisonStep source target hM P hP node i = some (resultParent, resultQ)) : + comparisonStopped source target resultParent resultQ ∨ + resultParent.hi - resultParent.lo ≤ w ⌈/⌉ M := by + classical + cases node with + | none => cases heq + | some state => + rcases state with ⟨parent, q⟩ + by_cases hs : comparisonStopped source target parent q + · simp only [comparisonStep, dite_eq_left hs] at heq + split_ifs at heq with hi + have hpq := Option.some.inj heq + have hp : parent = resultParent := congrArg Prod.fst hpq + have hq : q = resultQ := congrArg Prod.snd hpq + exact Or.inl (by rw [← hp, ← hq]; exact hs) + · simp only [comparisonStep, dite_eq_right hs] at heq + have hpq := Option.some.inj heq + have hp : sourceChild parent i = resultParent := congrArg Prod.fst hpq + have hw := (hnode parent q rfl).resolve_left hs + apply Or.inr + rw [← hp] + exact (sourceChild_width_le_ceiling parent i).trans ((gc_mul_ceilDiv hM).monotone_l hw) + +theorem comparison_frontier_stopped_or_width {α : Type*} (source target : List α) + {M : ℕ} (hM : 0 < M) (P : ℕ) (hP : 66 ≤ P) + (rootParent : TargetInterval source.length) (rootQ : TargetInterval target.length) + (d : ℕ) (node : TreeLayer M d) + (parent : TargetInterval source.length) (q : TargetInterval target.length) + (heq : comparisonFrontier source target hM P hP (some (rootParent, rootQ)) d node = some (parent, q)) : + comparisonStopped source target parent q ∨ + parent.hi - parent.lo ≤ (rootParent.hi - rootParent.lo) ⌈/⌉ M ^ d := by + induction d generalizing parent q with + | zero => + change some (rootParent, rootQ) = some (parent, q) at heq + have hp : rootParent = parent := congrArg Prod.fst (Option.some.inj heq) + apply Or.inr + rw [← hp, pow_zero] + simp + | succ d ih => + have h := comparisonStep_stopped_or_width source target hM P hP + (comparisonFrontier source target hM P hP (some (rootParent, rootQ)) d node.1) + ((rootParent.hi - rootParent.lo) ⌈/⌉ M ^ d) + (fun parent q heq => ih node.1 parent q heq) node.2 parent q heq + rw [ceilDiv_comp _ _ _ (pow_pos hM d) hM, ← pow_succ] at h + exact h + +theorem comparison_frontier_terminal {α : Type*} (source target : List α) + {M : ℕ} (hM : 0 < M) (P : ℕ) (hP : 66 ≤ P) + (rootParent : TargetInterval source.length) (rootQ : TargetInterval target.length) (J : ℕ) + (hcapacity : rootParent.hi - rootParent.lo ≤ M ^ J) (node : TreeLayer M J) + (parent : TargetInterval source.length) (q : TargetInterval target.length) + (heq : comparisonFrontier source target hM P hP (some (rootParent, rootQ)) J node = some (parent, q)) : + comparisonStopped source target parent q := by + rcases comparison_frontier_stopped_or_width source target hM P hP rootParent rootQ J node parent q heq with h | h + · exact h + · apply Or.inl + exact h.trans ((ceilDiv_le_iff_le_mul (pow_pos hM J)).2 (by simpa using hcapacity)) + +theorem comparison_frontier_cost_slack {α : Type*} (source target : List α) + {M : ℕ} (hM : 0 < M) (P : ℕ) (hP : 66 ≤ P) + (root : ComparisonState source.length target.length) (J : ℕ) + (hsmall : (J : ℝ) * (4 * (M : ℝ) / P) ≤ 1 / 2) : + (∑ node : TreeLayer M J, comparisonStateCost source target + (comparisonFrontier source target hM P hP root J node)) ≤ + (1 + 8 * (M : ℝ) * J / P) * comparisonStateCost source target root := by + have hx : 0 ≤ 4 * (M : ℝ) / P := by positivity + have hpow := small_growth_pow J hx hsmall + have heq : 1 + 2 * (J : ℝ) * (4 * (M : ℝ) / P) = 1 + 8 * (M : ℝ) * J / P := by ring + rw [heq] at hpow + exact (comparison_frontier_cost_bound source target hM P hP root J).trans + (mul_le_mul_of_nonneg_right hpow (comparisonStateCost_nonneg source target root)) + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/ComparisonLift.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/ComparisonLift.lean new file mode 100644 index 0000000000000000000000000000000000000000..8b6fcc9da3d9891484e2f6a305bef3dd47acaef6 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/ComparisonLift.lean @@ -0,0 +1,129 @@ +import OAI.Combinatorics.EditApproximation.Geometry.ComparisonPhysical +import OAI.Combinatorics.EditApproximation.Geometry.ComparisonBounds + +namespace OAI + +/-! +Actual physical tables on the stopped comparison tree. Stopped states retain +their exact cost while the complete-tree representation carries them forward. +-/ + +namespace EditApproximation + +open Finset + +noncomputable def stoppedComparisonValue {α : Type*} (source target : List α) + (row : TargetInterval target.length → ℝ) : ComparisonState source.length target.length → ℝ := by + classical + exact fun state => match state with + | none => 0 + | some (parent, q) => if comparisonStopped source target parent q then + stateEditCost (substring source parent.lo parent.hi) target q else row q + +noncomputable def comparisonPhysicalLift {α : Type*} {M J : ℕ} (source target : List α) + (hM : 0 < M) (P : ℕ) (hP : 66 ≤ P) + (table : PhysicalEntry M J target.length → ℝ) (rootQ : TargetInterval target.length) + (d : ℕ) (path : TreeLayer M d) : ℝ := by + classical + exact stoppedComparisonValue source target + (if hd : d ≤ J then fun q => table (⟨⟨d, by omega⟩, path⟩, q) else fun _ => 0) + (comparisonFrontier source target hM P hP + (some (sourceIntervalAt M source.length 0 PUnit.unit, rootQ)) d path) + +theorem stoppedComparisonValue_physical {α : Type*} {M J : ℕ} (source target : List α) + (table : PhysicalEntry M J target.length → ℝ) + (hterminal : ∀ node q, comparisonStopped source target (physicalSourceInterval source.length node) q → + table (node, q) = stateEditCost (physicalSource source node) target q) + (node : PhysicalNode M J) (q : TargetInterval target.length) : + stoppedComparisonValue source target (fun r => table (node, r)) + (some (physicalSourceInterval source.length node, q)) = table (node, q) := by + classical + unfold stoppedComparisonValue + dsimp only + split_ifs with hstop + · exact (hterminal node q hstop).symm + · rfl + +theorem comparisonPhysicalLift_root {α : Type*} {M J : ℕ} (source target : List α) + (hM : 0 < M) (P : ℕ) (hP : 66 ≤ P) + (table : PhysicalEntry M J target.length → ℝ) + (hterminal : ∀ node q, comparisonStopped source target (physicalSourceInterval source.length node) q → + table (node, q) = stateEditCost (physicalSource source node) target q) + (rootQ : TargetInterval target.length) : + comparisonPhysicalLift source target hM P hP table rootQ 0 PUnit.unit = + table (⟨⟨0, by omega⟩, PUnit.unit⟩, rootQ) := by + classical + unfold comparisonPhysicalLift + rw [dite_eq_left (Nat.zero_le J)] + exact stoppedComparisonValue_physical source target table hterminal _ rootQ + +theorem comparisonPhysicalLift_step_active {α : Type*} {M J : ℕ} (source target : List α) + (hM : 0 < M) (P : ℕ) (hP : 66 ≤ P) + (table : PhysicalEntry M J target.length → ℝ) + (hterminal : ∀ node q, comparisonStopped source target (physicalSourceInterval source.length node) q → + table (node, q) = stateEditCost (physicalSource source node) target q) + (rootQ : TargetInterval target.length) (node : PhysicalNode M J) (hbelow : node.1.val < J) + (q : TargetInterval target.length) + (hfrontier : comparisonFrontier source target hM P hP + (some (sourceIntervalAt M source.length 0 PUnit.unit, rootQ)) node.1.val node.2 = + some (physicalSourceInterval source.length node, q)) + (hactive : ¬ comparisonStopped source target (physicalSourceInterval source.length node) q) + (i : Fin M) : + let hc : 0 < stateEditCost (physicalSource source node) target q := by + change 0 < stateEditCost (substring source (physicalSourceInterval source.length node).lo + (physicalSourceInterval source.length node).hi) target q + unfold comparisonStopped at hactive + omega + comparisonPhysicalLift source target hM P hP table rootQ (node.1.val + 1) (node.2, i) = + table (physicalChild node hbelow i, + comparisonChildren source target hM P hP (physicalSourceInterval source.length node) q hc i) := by + classical + dsimp only + unfold comparisonPhysicalLift + rw [dite_eq_left (by omega : node.1.val + 1 ≤ J)] + change stoppedComparisonValue source target _ + (comparisonStep source target hM P hP + (comparisonFrontier source target hM P hP _ node.1.val node.2) i) = _ + rw [hfrontier] + simp only [comparisonStep, dite_eq_right hactive] + exact stoppedComparisonValue_physical source target table hterminal (physicalChild node hbelow i) _ + +theorem stoppedComparisonValue_step_stopped {α : Type*} (source target : List α) + {M : ℕ} (hM : 0 < M) (P : ℕ) (hP : 66 ≤ P) + (row : Fin M → TargetInterval target.length → ℝ) + (parent : TargetInterval source.length) (q : TargetInterval target.length) + (hstop : comparisonStopped source target parent q) : + (∑ i, stoppedComparisonValue source target (row i) + (comparisonStep source target hM P hP (some (parent, q)) i)) = + stateEditCost (substring source parent.lo parent.hi) target q := by + classical + have hpoint (i : Fin M) : stoppedComparisonValue source target (row i) + (comparisonStep source target hM P hP (some (parent, q)) i) = + if i = ⟨0, hM⟩ then (stateEditCost (substring source parent.lo parent.hi) target q : ℝ) else 0 := by + simp only [comparisonStep, dite_eq_left hstop] + split_ifs <;> simp only [stoppedComparisonValue, ite_eq_left hstop] + simp_rw [hpoint] + simp + +theorem comparisonPhysicalLift_terminal {α : Type*} {M J : ℕ} (source target : List α) + (hM : 0 < M) (P : ℕ) (hP : 66 ≤ P) + (table : PhysicalEntry M J target.length → ℝ) (rootQ : TargetInterval target.length) + (hcapacity : source.length ≤ M ^ J) (path : TreeLayer M J) : + comparisonPhysicalLift source target hM P hP table rootQ J path = + comparisonStateCost source target (comparisonFrontier source target hM P hP + (some (sourceIntervalAt M source.length 0 PUnit.unit, rootQ)) J path) := by + classical + unfold comparisonPhysicalLift + generalize heq : comparisonFrontier source target hM P hP + (some (sourceIntervalAt M source.length 0 PUnit.unit, rootQ)) J path = state + cases state with + | none => rfl + | some state => + rcases state with ⟨parent, q⟩ + have hstop := comparison_frontier_terminal source target hM P hP + (sourceIntervalAt M source.length 0 PUnit.unit) rootQ J hcapacity path parent q heq + simp only [stoppedComparisonValue, ite_eq_left hstop, comparisonStateCost] + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/ComparisonLiftBounds.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/ComparisonLiftBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..170263ac090bfb941a9d0028625a398ebb0a0565 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/ComparisonLiftBounds.lean @@ -0,0 +1,178 @@ +import OAI.Combinatorics.EditApproximation.Geometry.ComparisonLift +import OAI.Combinatorics.EditApproximation.Refinement.StageTerminal + +namespace OAI + +/-! Actual stopped-tree warmup masses and their energy telescope bounds. -/ + +namespace EditApproximation + +open Finset + +noncomputable def comparisonStateGap {α : Type*} (source target : List α) : + ComparisonState source.length target.length → ℝ + | none => 0 + | some (parent, q) => stateLengthGap (substring source parent.lo parent.hi) target q + +theorem comparisonPhysicalLift_bounds {α : Type*} {M J : ℕ} (source target : List α) + (hM : 0 < M) (P : ℕ) (hP : 66 ≤ P) (F : ℝ) (hF : 1 ≤ F) + (table : PhysicalEntry M J target.length → ℝ) + (htable : ∀ state, 0 ≤ table state ∧ table state ≤ + 2 * F * stateEditCost (physicalSource source state.1) target state.2) + (rootQ : TargetInterval target.length) (d : ℕ) (path : TreeLayer M d) : + 0 ≤ comparisonPhysicalLift source target hM P hP table rootQ d path ∧ + comparisonPhysicalLift source target hM P hP table rootQ d path ≤ + 2 * F * comparisonStateCost source target (comparisonFrontier source target hM P hP + (some (sourceIntervalAt M source.length 0 PUnit.unit, rootQ)) d path) := by + classical + unfold comparisonPhysicalLift + generalize heq : comparisonFrontier source target hM P hP + (some (sourceIntervalAt M source.length 0 PUnit.unit, rootQ)) d path = state + cases state with + | none => simp only [stoppedComparisonValue, comparisonStateCost, mul_zero, le_refl, and_self] + | some state => + rcases state with ⟨parent, q⟩ + by_cases hstop : comparisonStopped source target parent q + · simp only [stoppedComparisonValue, ite_eq_left hstop, comparisonStateCost] + refine ⟨Nat.cast_nonneg _, ?_⟩ + have h := mul_le_mul_of_nonneg_right (show (1 : ℝ) ≤ 2 * F by linarith) (Nat.cast_nonneg + (stateEditCost (substring source parent.lo parent.hi) target q)) + simpa only [one_mul] using h + · simp only [stoppedComparisonValue, ite_eq_right hstop, comparisonStateCost] + split_ifs with hd + · have hp := comparisonFrontier_active_source source target hM P hP rootQ d path parent q heq hstop + have h := htable (⟨⟨d, by omega⟩, path⟩, q) + simpa only [physicalSource, physicalSourceInterval, ← hp] using h + · exact ⟨le_rfl, mul_nonneg (by linarith) (Nat.cast_nonneg _)⟩ + +theorem comparisonPhysicalLift_gap {α : Type*} {M J : ℕ} (source target : List α) + (hM : 0 < M) (P : ℕ) (hP : 66 ≤ P) + (table : PhysicalEntry M J target.length → ℝ) + (htable : ∀ state, |stateLengthGap (physicalSource source state.1) target state.2| ≤ table state) + (rootQ : TargetInterval target.length) (d : ℕ) (hd : d ≤ J) (path : TreeLayer M d) : + |comparisonStateGap source target (comparisonFrontier source target hM P hP + (some (sourceIntervalAt M source.length 0 PUnit.unit, rootQ)) d path)| ≤ + comparisonPhysicalLift source target hM P hP table rootQ d path := by + classical + unfold comparisonPhysicalLift + rw [dite_eq_left hd] + generalize heq : comparisonFrontier source target hM P hP + (some (sourceIntervalAt M source.length 0 PUnit.unit, rootQ)) d path = state + cases state with + | none => simp only [comparisonStateGap, stoppedComparisonValue, abs_zero, le_refl] + | some state => + rcases state with ⟨parent, q⟩ + by_cases hstop : comparisonStopped source target parent q + · simp only [stoppedComparisonValue, ite_eq_left hstop, comparisonStateGap] + exact stateEditCost_length_lower (substring source parent.lo parent.hi) target q + · simp only [stoppedComparisonValue, ite_eq_right hstop, comparisonStateGap] + have hp := comparisonFrontier_active_source source target hM P hP rootQ d path parent q heq hstop + have h := htable (⟨⟨d, by omega⟩, path⟩, q) + simpa only [physicalSource, physicalSourceInterval, ← hp] using h + +theorem gap_energy_bounds {gap mass : ℝ} (hgap : |gap| ≤ mass) : + 0 ≤ gap ^ 2 / mass ∧ gap ^ 2 / mass ≤ mass := by + have hm : 0 ≤ mass := (abs_nonneg _).trans hgap + refine ⟨div_nonneg (sq_nonneg _) hm, ?_⟩ + by_cases hz : mass = 0 + · simp only [hz, div_zero, le_refl] + · have hp : 0 < mass := lt_of_le_of_ne hm (Ne.symm hz) + apply (div_le_iff₀ hp).2 + have hsq : gap ^ 2 ≤ mass ^ 2 := by + simpa only [sq_abs] using (pow_le_pow_left₀ (abs_nonneg gap) hgap 2) + simpa only [pow_two] using hsq + +section Warmup + +variable {α : Type*} [DecidableEq α] {M J : ℕ} + (source target : List α) (hM : 0 < M) + (U : PhysicalEntry M J target.length → ℕ) (N P F : ℕ) (A : ℚ) + (hsize : source.length + target.length ≤ N) (hP : 66 ≤ P) (hF : 1 ≤ F) (hA : 1 ≤ A) + (hseed : ∀ state, stateEditCost (physicalSource source state.1) target state.2 ≤ U state ∧ + (U state : ℚ) ≤ A * stateEditCost (physicalSource source state.1) target state.2) + (T : ℕ) (hT : 0 < T) (rootQ : TargetInterval target.length) + +/-- The comparison mass is the actual averaged warmup at active states and +true cost at carried stopped states. -/ +noncomputable def stageComparisonMass (d : ℕ) (path : TreeLayer M d) : ℝ := + comparisonPhysicalLift source target hM P hP + (fun state => (stageWarmupMass source target U N P F A T state : ℝ)) rootQ d path + +noncomputable def stageComparisonEnergy (d : ℕ) (path : TreeLayer M d) : ℝ := + (comparisonStateGap source target (comparisonFrontier source target hM P hP + (some (sourceIntervalAt M source.length 0 PUnit.unit, rootQ)) d path)) ^ 2 / + stageComparisonMass source target hM U N P F A hP T rootQ d path + +include hsize hF hA hseed hT in + theorem stageComparisonMass_bounds (d : ℕ) (path : TreeLayer M d) : + 0 ≤ stageComparisonMass source target hM U N P F A hP T rootQ d path ∧ + stageComparisonMass source target hM U N P F A hP T rootQ d path ≤ + 2 * F * comparisonStateCost source target (comparisonFrontier source target hM P hP + (some (sourceIntervalAt M source.length 0 PUnit.unit, rootQ)) d path) := by + exact comparisonPhysicalLift_bounds source target hM P hP F (by exact_mod_cast hF) _ + (fun state => by + have h := stageWarmup_invariants source target hM U N P F A hsize hP hF hA hseed T hT state + have hlower := ((le_max_right _ _).trans h.1).trans (Rat.cast_le.mpr h.2.1) + have hupper : (stageWarmupMass source target U N P F A T state : ℝ) ≤ + ((2 * F * stateEditCost (physicalSource source state.1) target state.2 : ℚ) : ℝ) := + Rat.cast_le.mpr (h.2.2.1.trans h.2.2.2) + exact ⟨(abs_nonneg _).trans hlower, by simpa only [Rat.cast_mul, Rat.cast_ofNat, Rat.cast_natCast] using hupper⟩) + rootQ d path + +include hsize hF hA hseed hT in + theorem stageComparisonEnergy_bounds (d : ℕ) (hd : d ≤ J) (path : TreeLayer M d) : + 0 ≤ stageComparisonEnergy source target hM U N P F A hP T rootQ d path ∧ + stageComparisonEnergy source target hM U N P F A hP T rootQ d path ≤ + stageComparisonMass source target hM U N P F A hP T rootQ d path := by + apply gap_energy_bounds + exact comparisonPhysicalLift_gap source target hM P hP _ + (fun state => by + have h := stageWarmup_invariants source target hM U N P F A hsize hP hF hA hseed T hT state + exact ((le_max_right _ _).trans h.1).trans (Rat.cast_le.mpr h.2.1)) rootQ d hd path + +include hsize hF hA hseed hT in + theorem stageComparisonMass_root : + stageComparisonMass source target hM U N P F A hP T rootQ 0 PUnit.unit = + stageWarmupMass source target U N P F A T (⟨⟨0, by omega⟩, PUnit.unit⟩, rootQ) := by + exact comparisonPhysicalLift_root source target hM P hP _ + (fun node q hstop => by + exact_mod_cast stageWarmupMass_at_stopped source target hM U N P F A hsize hP hF hA hseed + T hT node q hstop) rootQ + + theorem stageComparisonMass_terminal (hcapacity : source.length ≤ M ^ J) (path : TreeLayer M J) : + stageComparisonMass source target hM U N P F A hP T rootQ J path = + comparisonStateCost source target (comparisonFrontier source target hM P hP + (some (sourceIntervalAt M source.length 0 PUnit.unit, rootQ)) J path) := by + exact comparisonPhysicalLift_terminal source target hM P hP _ rootQ hcapacity path + +include hsize hF hA hseed hT in + theorem stageComparisonEnergy_telescope (hcapacity : source.length ≤ M ^ J) + (hsmall : (J : ℝ) * (4 * (M : ℝ) / P) ≤ 1 / 2) : + (∑ d ∈ range J, ∑ path : TreeLayer M d, + ((∑ i : Fin M, stageComparisonEnergy source target hM U N P F A hP T rootQ (d + 1) (path, i)) - + stageComparisonEnergy source target hM U N P F A hP T rootQ d path)) ≤ + 2 * comparisonStateCost source target (some (sourceIntervalAt M source.length 0 PUnit.unit, rootQ)) := by + have htel := tree_frontier_telescope M J (stageComparisonEnergy source target hM U N P F A hP T rootQ) + have heq : (∑ d ∈ range J, ∑ path : TreeLayer M d, + ((∑ i : Fin M, stageComparisonEnergy source target hM U N P F A hP T rootQ (d + 1) (path, i)) - + stageComparisonEnergy source target hM U N P F A hP T rootQ d path)) = + (∑ path : TreeLayer M J, stageComparisonEnergy source target hM U N P F A hP T rootQ J path) - + stageComparisonEnergy source target hM U N P F A hP T rootQ 0 PUnit.unit := by + have h := congrArg Neg.neg htel + simp only [← sum_neg_distrib, neg_sub] at h + exact h + rw [heq] + have hroot := (stageComparisonEnergy_bounds source target hM U N P F A hsize hP hF hA hseed T hT rootQ + 0 (Nat.zero_le J) PUnit.unit).1 + have hterminal := sum_le_sum (fun path (_ : path ∈ (univ : Finset (TreeLayer M J))) => + (stageComparisonEnergy_bounds source target hM U N P F A hsize hP hF hA hseed T hT rootQ J le_rfl path).2) + simp_rw [stageComparisonMass_terminal source target hM U N P F A hP T rootQ hcapacity] at hterminal + have hcost := comparison_frontier_cost_le_twice source target hM P hP + (some (sourceIntervalAt M source.length 0 PUnit.unit, rootQ)) J J le_rfl hsmall + linarith only [hroot, hterminal, hcost] + +end Warmup + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/ComparisonLiftStep.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/ComparisonLiftStep.lean new file mode 100644 index 0000000000000000000000000000000000000000..2c0df92ab1a20315e46d6c5cd8fc22834b660f9b --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/ComparisonLiftStep.lean @@ -0,0 +1,153 @@ +import OAI.Combinatorics.EditApproximation.Geometry.ComparisonLiftBounds + +namespace OAI + +/-! Actual mass and energy identities at every kind of comparison-tree node. -/ + +namespace EditApproximation + +open Finset + +theorem stoppedComparisonEnergy_step_stopped {α : Type*} (source target : List α) + {M : ℕ} (hM : 0 < M) (P : ℕ) (hP : 66 ≤ P) + (row : Fin M → TargetInterval target.length → ℝ) + (parent : TargetInterval source.length) (q : TargetInterval target.length) + (hstop : comparisonStopped source target parent q) : + (∑ i, (comparisonStateGap source target (comparisonStep source target hM P hP (some (parent, q)) i)) ^ 2 / + stoppedComparisonValue source target (row i) + (comparisonStep source target hM P hP (some (parent, q)) i)) = + (stateLengthGap (substring source parent.lo parent.hi) target q) ^ 2 / + stateEditCost (substring source parent.lo parent.hi) target q := by + classical + have hpoint (i : Fin M) : + (comparisonStateGap source target (comparisonStep source target hM P hP (some (parent, q)) i)) ^ 2 / + stoppedComparisonValue source target (row i) + (comparisonStep source target hM P hP (some (parent, q)) i) = + if i = ⟨0, hM⟩ then (stateLengthGap (substring source parent.lo parent.hi) target q) ^ 2 / + stateEditCost (substring source parent.lo parent.hi) target q else 0 := by + simp only [comparisonStep, dite_eq_left hstop] + split_ifs <;> simp only [comparisonStateGap, stoppedComparisonValue, ite_eq_left hstop, zero_pow + (by decide : 2 ≠ 0), zero_div] + simp_rw [hpoint] + simp + +section Warmup + +variable {α : Type*} [DecidableEq α] {M J : ℕ} + (source target : List α) (hM : 0 < M) + (U : PhysicalEntry M J target.length → ℕ) (N P F : ℕ) (A : ℚ) + (hsize : source.length + target.length ≤ N) (hP : 66 ≤ P) (hF : 1 ≤ F) (hA : 1 ≤ A) + (hseed : ∀ state, stateEditCost (physicalSource source state.1) target state.2 ≤ U state ∧ + (U state : ℚ) ≤ A * stateEditCost (physicalSource source state.1) target state.2) + (T : ℕ) (hT : 0 < T) (rootQ : TargetInterval target.length) + +local notation "mass" => stageComparisonMass source target hM U N P F A hP T rootQ +local notation "energy" => stageComparisonEnergy source target hM U N P F A hP T rootQ +local notation "frontier" => comparisonFrontier source target hM P hP + (some (sourceIntervalAt M source.length 0 PUnit.unit, rootQ)) + + theorem stageComparisonMass_step_stopped (d : ℕ) (path : TreeLayer M d) + (parent : TargetInterval source.length) (q : TargetInterval target.length) + (heq : frontier d path = some (parent, q)) (hstop : comparisonStopped source target parent q) : + (∑ i : Fin M, mass (d + 1) (path, i)) = mass d path := by + classical + unfold stageComparisonMass comparisonPhysicalLift + have hpoint (i : Fin M) : + stoppedComparisonValue source target + (if hd : d + 1 ≤ J then fun q => (stageWarmupMass source target U N P F A T + (⟨⟨d + 1, by omega⟩, (path, i)⟩, q) : ℝ) else fun _ => 0) + (frontier (d + 1) (path, i)) = + if i = ⟨0, hM⟩ then (stateEditCost (substring source parent.lo parent.hi) target q : ℝ) else 0 := by + change stoppedComparisonValue source target _ + (comparisonStep source target hM P hP (frontier d path) i) = _ + rw [heq] + simp only [comparisonStep, dite_eq_left hstop] + split_ifs <;> simp only [stoppedComparisonValue, ite_eq_left hstop] + simp_rw [hpoint] + rw [heq] + simp only [sum_ite_eq', mem_univ, ite_true, stoppedComparisonValue, ite_eq_left hstop] + + theorem stageComparisonEnergy_step_stopped (d : ℕ) (path : TreeLayer M d) + (parent : TargetInterval source.length) (q : TargetInterval target.length) + (heq : frontier d path = some (parent, q)) (hstop : comparisonStopped source target parent q) : + (∑ i : Fin M, energy (d + 1) (path, i)) = energy d path := by + classical + unfold stageComparisonEnergy stageComparisonMass comparisonPhysicalLift + have hpoint (i : Fin M) : + (comparisonStateGap source target (frontier (d + 1) (path, i))) ^ 2 / + stoppedComparisonValue source target + (if hd : d + 1 ≤ J then fun q => (stageWarmupMass source target U N P F A T + (⟨⟨d + 1, by omega⟩, (path, i)⟩, q) : ℝ) else fun _ => 0) + (frontier (d + 1) (path, i)) = + if i = ⟨0, hM⟩ then (stateLengthGap (substring source parent.lo parent.hi) target q) ^ 2 / + stateEditCost (substring source parent.lo parent.hi) target q else 0 := by + change (comparisonStateGap source target (comparisonStep source target hM P hP (frontier d path) i)) ^ 2 / + stoppedComparisonValue source target _ (comparisonStep source target hM P hP (frontier d path) i) = _ + rw [heq] + simp only [comparisonStep, dite_eq_left hstop] + split_ifs <;> simp only [comparisonStateGap, stoppedComparisonValue, ite_eq_left hstop, + zero_pow (by decide : 2 ≠ 0), zero_div] + simp_rw [hpoint] + rw [heq] + simp only [sum_ite_eq', mem_univ, ite_true, comparisonStateGap, stoppedComparisonValue, ite_eq_left hstop] + + theorem stageComparison_step_none (d : ℕ) (path : TreeLayer M d) (heq : frontier d path = none) : + mass d path = 0 ∧ (∑ i : Fin M, mass (d + 1) (path, i)) = 0 ∧ + energy d path = 0 ∧ (∑ i : Fin M, energy (d + 1) (path, i)) = 0 := by + have hnext (i : Fin M) : frontier (d + 1) (path, i) = none := by + change comparisonStep source target hM P hP (frontier d path) i = none + rw [heq] + rfl + simp only [stageComparisonEnergy, stageComparisonMass, comparisonPhysicalLift, heq, hnext, + comparisonStateGap, stoppedComparisonValue, zero_pow (by decide : 2 ≠ 0), zero_div, + sum_const_zero, and_self] + +include hsize hF hA hseed hT in + theorem stageComparisonMass_step_active (node : PhysicalNode M J) (hbelow : node.1.val < J) + (q : TargetInterval target.length) + (heq : frontier node.1.val node.2 = some (physicalSourceInterval source.length node, q)) + (hactive : ¬ comparisonStopped source target (physicalSourceInterval source.length node) q) + (i : Fin M) : + let hc : 0 < stateEditCost (physicalSource source node) target q := by + change 0 < stateEditCost (substring source (physicalSourceInterval source.length node).lo + (physicalSourceInterval source.length node).hi) target q + unfold comparisonStopped at hactive + omega + mass (node.1.val + 1) (node.2, i) = stageWarmupMass source target U N P F A T + (physicalChild node hbelow i, comparisonChildren source target hM P hP + (physicalSourceInterval source.length node) q hc i) := by + exact comparisonPhysicalLift_step_active source target hM P hP _ + (fun node q hstop => by + exact_mod_cast stageWarmupMass_at_stopped source target hM U N P F A hsize hP hF hA hseed + T hT node q hstop) rootQ node hbelow q heq hactive i + +include hsize hF hA hseed hT in + theorem stageComparisonEnergy_step_active (node : PhysicalNode M J) (hbelow : node.1.val < J) + (q : TargetInterval target.length) + (heq : frontier node.1.val node.2 = some (physicalSourceInterval source.length node, q)) + (hactive : ¬ comparisonStopped source target (physicalSourceInterval source.length node) q) + (i : Fin M) : + let hc : 0 < stateEditCost (physicalSource source node) target q := by + change 0 < stateEditCost (substring source (physicalSourceInterval source.length node).lo + (physicalSourceInterval source.length node).hi) target q + unfold comparisonStopped at hactive + omega + let childQ := comparisonChildren source target hM P hP (physicalSourceInterval source.length node) q hc i + energy (node.1.val + 1) (node.2, i) = + (stateLengthGap (physicalSource source (physicalChild node hbelow i)) target childQ) ^ 2 / + (stageWarmupMass source target U N P F A T (physicalChild node hbelow i, childQ) : ℝ) := by + dsimp only + unfold stageComparisonEnergy + rw [stageComparisonMass_step_active source target hM U N P F A hsize hP hF hA hseed T hT rootQ + node hbelow q heq hactive i] + change (comparisonStateGap source target (comparisonStep source target hM P hP + (frontier node.1.val node.2) i)) ^ 2 / _ = _ + rw [heq] + simp only [comparisonStep, dite_eq_right hactive, comparisonStateGap] + rfl + +end Warmup + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/ComparisonParameters.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/ComparisonParameters.lean new file mode 100644 index 0000000000000000000000000000000000000000..350a2cf302b917b1e2bb09d200d90b4d0959b0f8 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/ComparisonParameters.lean @@ -0,0 +1,51 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseParameters +import OAI.Combinatorics.EditApproximation.Geometry.TreeParameters + +namespace OAI + +/-! The computed parameters discharge the comparison-tree small-growth premises. -/ + +namespace EditApproximation + +theorem computed_comparison_parameters (N nx : ℕ) (hN : 0 < N) (hnx : nx ≤ N) + (hell : 200 ≤ inputSmallLog N) : + 66 ≤ (integerParameters N).P ∧ + (intervalTreeDepth (integerParameters N).M nx : ℝ) * + (4 * ((integerParameters N).M : ℝ) / (integerParameters N).P) ≤ 1 / 2 := by + let H := inputHeight N + let M := (integerParameters N).M + let J := intervalTreeDepth M nx + let P := (integerParameters N).P + have hH : 4 ≤ H := (computed_coarse_branching N hN hell).1 + have hM : M ≤ H := by + exact pow_le_pow_right₀ (by decide : 1 ≤ (2 : ℕ)) (Nat.div_le_self _ _) + have hMtwo : 2 ≤ M := (computed_branching_bounds N hN hell).1 + have hJ : J ≤ H := by + have hlog := Nat.clog_anti_left (by decide : 1 < 2) hMtwo (n := max 1 nx) + have hlength : max 1 nx ≤ 2 ^ H := by + apply max_le Nat.one_le_two_pow + exact hnx.trans ((Nat.le_add_right N 2).trans (inputHeight_covers_length N)) + exact hlog.trans ((Nat.clog_le_iff_le_pow (by decide : 1 < 2)).2 hlength) + have hPfour : H ^ 4 ≤ P := + pow_le_pow_right₀ (by omega : 1 ≤ H) (by omega : 4 ≤ coarseExponent (inputSmallLog N) + 20) + have hHsq : 16 ≤ H ^ 2 := by nlinarith + have hHfour : 256 ≤ H ^ 4 := by + have h := Nat.pow_le_pow_left hH 4 + norm_num at h + exact h + have h66 : 66 ≤ P := by omega + have hprod : M * J ≤ H ^ 2 := by simpa only [pow_two] using Nat.mul_le_mul hM hJ + have hscale : 8 * M * J ≤ P := by + have hmul := Nat.mul_le_mul_left (H ^ 2) hHsq + nlinarith + have hPr : (0 : ℝ) < P := by exact_mod_cast (by omega : 0 < P) + have hscaleR : 8 * (M : ℝ) * J ≤ P := by exact_mod_cast hscale + refine ⟨h66, ?_⟩ + change (J : ℝ) * (4 * (M : ℝ) / P) ≤ 1 / 2 + rw [← mul_div_assoc] + apply (div_le_iff₀ hPr).2 + nlinarith + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/ComparisonPhysical.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/ComparisonPhysical.lean new file mode 100644 index 0000000000000000000000000000000000000000..16d4240d84bd0902a3df3f2c56045eed7a84ea3e --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/ComparisonPhysical.lean @@ -0,0 +1,55 @@ +import OAI.Combinatorics.EditApproximation.Geometry.ComparisonTree +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalWarmup + +namespace OAI + +/-! Active comparison states have precisely the corresponding physical source interval. -/ + +namespace EditApproximation + +theorem comparisonStep_active_parent {α : Type*} (source target : List α) + {M : ℕ} (hM : 0 < M) (P : ℕ) (hP : 66 ≤ P) + (node : ComparisonState source.length target.length) (i : Fin M) + (resultParent : TargetInterval source.length) (resultQ : TargetInterval target.length) + (heq : comparisonStep source target hM P hP node i = some (resultParent, resultQ)) + (hactive : ¬ comparisonStopped source target resultParent resultQ) : + ∃ parent q, node = some (parent, q) ∧ ¬ comparisonStopped source target parent q ∧ + resultParent = sourceChild parent i := by + classical + cases node with + | none => cases heq + | some state => + rcases state with ⟨parent, q⟩ + by_cases hs : comparisonStopped source target parent q + · simp only [comparisonStep, dite_eq_left hs] at heq + split_ifs at heq with hi + · have hpq := Option.some.inj heq + have hp : parent = resultParent := congrArg Prod.fst hpq + have hq : q = resultQ := congrArg Prod.snd hpq + exact False.elim (hactive (by rw [← hp, ← hq]; exact hs)) + · simp only [comparisonStep, dite_eq_right hs] at heq + have hpq := Option.some.inj heq + have hp : sourceChild parent i = resultParent := congrArg Prod.fst hpq + exact ⟨parent, q, rfl, hs, hp.symm⟩ + +theorem comparisonFrontier_active_source {α : Type*} (source target : List α) + {M : ℕ} (hM : 0 < M) (P : ℕ) (hP : 66 ≤ P) (rootQ : TargetInterval target.length) + (d : ℕ) (path : TreeLayer M d) (parent : TargetInterval source.length) (q : TargetInterval target.length) + (heq : comparisonFrontier source target hM P hP + (some (sourceIntervalAt M source.length 0 PUnit.unit, rootQ)) d path = some (parent, q)) + (hactive : ¬ comparisonStopped source target parent q) : + parent = sourceIntervalAt M source.length d path := by + induction d generalizing parent q with + | zero => + have hpq := Option.some.inj heq + exact (congrArg Prod.fst hpq).symm + | succ d ih => + obtain ⟨previousParent, previousQ, hprevious, hpreviousActive, hchild⟩ := + comparisonStep_active_parent source target hM P hP _ path.2 parent q heq hactive + have hp := ih path.1 previousParent previousQ hprevious hpreviousActive + rw [hp] at hchild + exact hchild + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/ComparisonTree.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/ComparisonTree.lean new file mode 100644 index 0000000000000000000000000000000000000000..a9cf33877bce769f30d44316326d6d596c6ca69e --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/ComparisonTree.lean @@ -0,0 +1,195 @@ +import OAI.Combinatorics.EditApproximation.Geometry.RoundedComparison +import OAI.Combinatorics.EditApproximation.Geometry.BalancedWidths + +namespace OAI + +/-! +# The input-determined rounded comparison tree + +The choices here are only for the proof. They use the exact input edit +costs and a fixed classical choice of optimal alignment, and have no +sampling argument. Stopped states are carried in child zero, with the +remaining physical slots empty. +-/ + +namespace EditApproximation + +open Finset + +abbrev ComparisonState (nx ny : ℕ) := Option (TargetInterval nx × TargetInterval ny) + +noncomputable def comparisonStateCost {α : Type*} (source target : List α) : + ComparisonState source.length target.length → ℝ + | none => 0 + | some (parent, q) => stateEditCost (substring source parent.lo parent.hi) target q + +def comparisonStopped {α : Type*} (source target : List α) + (parent : TargetInterval source.length) (q : TargetInterval target.length) : Prop := + parent.hi - parent.lo ≤ 1 ∨ stateEditCost (substring source parent.lo parent.hi) target q = 0 + +noncomputable def comparisonChildren {α : Type*} (source target : List α) + {M : ℕ} (hM : 0 < M) (P : ℕ) (hP : 66 ≤ P) + (parent : TargetInterval source.length) (q : TargetInterval target.length) + (hc : 0 < stateEditCost (substring source parent.lo parent.hi) target q) : + Fin M → TargetInterval target.length := + Classical.choose (rounded_comparison_action source target hM parent q + (2 ^ Nat.log 2 (stateEditCost (substring source parent.lo parent.hi) target q)) P hP + (cost_dyadicScale _ _ hc le_rfl).2.1 (cost_dyadicScale _ _ hc le_rfl).2.2) + +theorem comparisonChildren_cost_bound {α : Type*} (source target : List α) + {M : ℕ} (hM : 0 < M) (P : ℕ) (hP : 66 ≤ P) + (parent : TargetInterval source.length) (q : TargetInterval target.length) + (hc : 0 < stateEditCost (substring source parent.lo parent.hi) target q) : + (∑ i, (stateEditCost (substring source (sourceChild parent i).lo (sourceChild parent i).hi) + target (comparisonChildren source target hM P hP parent q hc i) : ℝ)) ≤ + (1 + 4 * (M : ℝ) / P) * stateEditCost (substring source parent.lo parent.hi) target q := + (Classical.choose_spec (rounded_comparison_action source target hM parent q + (2 ^ Nat.log 2 (stateEditCost (substring source parent.lo parent.hi) target q)) P hP + (cost_dyadicScale _ _ hc le_rfl).2.1 (cost_dyadicScale _ _ hc le_rfl).2.2)).2.2.2.2 + +theorem comparisonChildren_spec {α : Type*} (source target : List α) + {M : ℕ} (hM : 0 < M) (P : ℕ) (hP : 66 ≤ P) + (parent : TargetInterval source.length) (q : TargetInterval target.length) + (hc : 0 < stateEditCost (substring source parent.lo parent.hi) target q) : + let b := 2 ^ Nat.log 2 (stateEditCost (substring source parent.lo parent.hi) target q) + let r := roundInterval (seedGridSpacing b P) q + let states := comparisonChildren source target hM P hP parent q hc + states ∈ wideActionList M parent r b P ∧ endpointActionConnection r states = 0 ∧ + (∀ i j : Fin M, j.val = i.val + 1 → (states i).hi = (states j).lo) ∧ + (∀ i : Fin M, + Nat.dist (r.lo + ((sourceChild parent i).lo - parent.lo)) (states i).lo ≤ 6 * b ∧ + Nat.dist (r.lo + ((sourceChild parent i).hi - parent.lo)) (states i).hi ≤ 6 * b) ∧ + (∑ i, (stateEditCost + (substring source (sourceChild parent i).lo (sourceChild parent i).hi) target (states i) : ℝ)) ≤ + (1 + 4 * (M : ℝ) / P) * stateEditCost (substring source parent.lo parent.hi) target q := + Classical.choose_spec (rounded_comparison_action source target hM parent q + (2 ^ Nat.log 2 (stateEditCost (substring source parent.lo parent.hi) target q)) P hP + (cost_dyadicScale _ _ hc le_rfl).2.1 (cost_dyadicScale _ _ hc le_rfl).2.2) + +theorem comparisonChildren_lower {α : Type*} (source target : List α) + {M : ℕ} (hM : 0 < M) (P : ℕ) (hP : 66 ≤ P) + (parent : TargetInterval source.length) (q : TargetInterval target.length) + (hc : 0 < stateEditCost (substring source parent.lo parent.hi) target q) : + let b := 2 ^ Nat.log 2 (stateEditCost (substring source parent.lo parent.hi) target q) + let r := roundInterval (seedGridSpacing b P) q + (stateEditCost (substring source parent.lo parent.hi) target q : ℝ) ≤ + (∑ i, (stateEditCost (substring source (sourceChild parent i).lo (sourceChild parent i).hi) + target (comparisonChildren source target hM P hP parent q hc i) : ℝ)) + + targetEndpointDistance q r := by + dsimp only + let r := roundInterval (seedGridSpacing + (2 ^ Nat.log 2 (stateEditCost (substring source parent.lo parent.hi) target q)) P) q + have hlower := zero_connection_cost_sum_lower source target hM parent r + (comparisonChildren source target hM P hP parent q hc) + (comparisonChildren_spec source target hM P hP parent q hc).2.1 + have hspatial : (stateEditCost (substring source parent.lo parent.hi) target q : ℝ) ≤ + stateEditCost (substring source parent.lo parent.hi) target r + targetEndpointDistance q r := by + exact_mod_cast stateEditCost_spatial (substring source parent.lo parent.hi) target q r + linarith + +noncomputable def comparisonStep {α : Type*} (source target : List α) + {M : ℕ} (hM : 0 < M) (P : ℕ) (hP : 66 ≤ P) : + ComparisonState source.length target.length → Fin M → ComparisonState source.length target.length + := by + classical + exact fun node i => match node with + | none => none + | some (parent, q) => + if hstop : comparisonStopped source target parent q then + if i = ⟨0, hM⟩ then some (parent, q) else none + else + some (sourceChild parent i, + comparisonChildren source target hM P hP parent q + (by unfold comparisonStopped at hstop; omega) i) + +theorem comparisonStateCost_nonneg {α : Type*} (source target : List α) + (node : ComparisonState source.length target.length) : + 0 ≤ comparisonStateCost source target node := by + cases node with + | none => exact le_rfl + | some state => exact Nat.cast_nonneg _ + +theorem comparisonStep_cost_bound {α : Type*} (source target : List α) + {M : ℕ} (hM : 0 < M) (P : ℕ) (hP : 66 ≤ P) + (node : ComparisonState source.length target.length) : + (∑ i, comparisonStateCost source target (comparisonStep source target hM P hP node i)) ≤ + (1 + 4 * (M : ℝ) / P) * comparisonStateCost source target node := by + classical + cases node with + | none => simp only [comparisonStep, comparisonStateCost, sum_const_zero, mul_zero, le_refl] + | some state => + rcases state with ⟨parent, q⟩ + by_cases hs : comparisonStopped source target parent q + · simp only [comparisonStep, dite_eq_left hs] + have hsum : (∑ i : Fin M, comparisonStateCost source target + (if i = ⟨0, hM⟩ then some (parent, q) else none)) = + comparisonStateCost source target (some (parent, q)) := by + have hpoint (i : Fin M) : comparisonStateCost source target + (if i = ⟨0, hM⟩ then some (parent, q) else none) = + if i = ⟨0, hM⟩ then comparisonStateCost source target (some (parent, q)) else 0 := by + split_ifs <;> rfl + simp_rw [hpoint] + simp + rw [hsum] + have hnonneg := comparisonStateCost_nonneg source target (some (parent, q)) + have hf : 0 ≤ 4 * (M : ℝ) / P := by positivity + nlinarith + · simpa only [comparisonStep, dite_eq_right hs, comparisonStateCost] using + comparisonChildren_cost_bound source target hM P hP parent q + (by unfold comparisonStopped at hs; omega) + +noncomputable def comparisonFrontier {α : Type*} (source target : List α) + {M : ℕ} (hM : 0 < M) (P : ℕ) (hP : 66 ≤ P) + (root : ComparisonState source.length target.length) : + (d : ℕ) → TreeLayer M d → ComparisonState source.length target.length + | 0, _ => root + | d + 1, node => comparisonStep source target hM P hP + (comparisonFrontier source target hM P hP root d node.1) node.2 + +theorem comparison_frontier_cost_bound {α : Type*} (source target : List α) + {M : ℕ} (hM : 0 < M) (P : ℕ) (hP : 66 ≤ P) + (root : ComparisonState source.length target.length) (d : ℕ) : + (∑ node : TreeLayer M d, comparisonStateCost source target + (comparisonFrontier source target hM P hP root d node)) ≤ + (1 + 4 * (M : ℝ) / P) ^ d * comparisonStateCost source target root := by + induction d with + | zero => + change (∑ _ : PUnit, comparisonStateCost source target root) ≤ _ + simp + | succ d ih => + rw [← tree_layer_sum] + have hsum := sum_le_sum (fun node (_ : node ∈ (univ : Finset (TreeLayer M d))) => + comparisonStep_cost_bound source target hM P hP + (comparisonFrontier source target hM P hP root d node)) + have hf : 0 ≤ 1 + 4 * (M : ℝ) / P := by positivity + calc + _ ≤ ∑ node : TreeLayer M d, (1 + 4 * (M : ℝ) / P) * + comparisonStateCost source target + (comparisonFrontier source target hM P hP root d node) := hsum + _ = (1 + 4 * (M : ℝ) / P) * ∑ node : TreeLayer M d, + comparisonStateCost source target + (comparisonFrontier source target hM P hP root d node) := by rw [mul_sum] + _ ≤ (1 + 4 * (M : ℝ) / P) * + ((1 + 4 * (M : ℝ) / P) ^ d * comparisonStateCost source target root) := + mul_le_mul_of_nonneg_left ih hf + _ = _ := by rw [pow_succ]; ring + +theorem comparison_frontier_cost_le_twice {α : Type*} (source target : List α) + {M : ℕ} (hM : 0 < M) (P : ℕ) (hP : 66 ≤ P) + (root : ComparisonState source.length target.length) (J d : ℕ) (hd : d ≤ J) + (hsmall : (J : ℝ) * (4 * (M : ℝ) / P) ≤ 1 / 2) : + (∑ node : TreeLayer M d, comparisonStateCost source target + (comparisonFrontier source target hM P hP root d node)) ≤ + 2 * comparisonStateCost source target root := by + have hx : 0 ≤ 4 * (M : ℝ) / P := by positivity + have hdR : (d : ℝ) ≤ J := by exact_mod_cast hd + have hdx : (d : ℝ) * (4 * (M : ℝ) / P) ≤ 1 / 2 := + (mul_le_mul_of_nonneg_right hdR hx).trans hsmall + have hpow := small_growth_pow d hx hdx + have htwo : (1 + 4 * (M : ℝ) / P) ^ d ≤ 2 := by linarith + exact (comparison_frontier_cost_bound source target hM P hP root d).trans + (mul_le_mul_of_nonneg_right htwo (comparisonStateCost_nonneg source target root)) + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/ConeLocality.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/ConeLocality.lean new file mode 100644 index 0000000000000000000000000000000000000000..6226f1b7af733efe81c5e098eec28ac5c7683588 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/ConeLocality.lean @@ -0,0 +1,45 @@ +import OAI.Combinatorics.EditApproximation.Geometry.InitialCones + +namespace OAI + +/-! +# The numerical locality test for initial cones + +Any globally minimizing cone at a positive-cost query lies in the +algorithm's finite local scale interval and search radius. The inequalities +below use the actual seed factor and cone slope from Section 4. +-/ + +namespace EditApproximation + +theorem initial_cone_locality_numeric {c centerCost Uq Ur distance b A F cone : ℚ} + (hc : 0 < c) (hA : 1 ≤ A) (hF : 0 < F) (hb : 0 ≤ b) + (hquery : c ≤ Uq ∧ Uq ≤ A * c) + (hcenter : centerCost ≤ Ur ∧ Ur ≤ A * centerCost) + (hcost : |c - centerCost| ≤ distance) + (heligible : b / 2 ≤ Ur ∧ Ur ≤ 4 * A * b) + (hconeLower : 32 * F * distance ≤ cone) (hconeUpper : cone ≤ 2 * F * c) : + distance ≤ c / 16 ∧ Ur ≠ 0 ∧ Uq / (16 * A ^ 2) ≤ b ∧ b ≤ 4 * A * Uq ∧ distance ≤ Uq := by + have hA0 : 0 < A := by linarith + have hdist : distance ≤ c / 16 := by + have hscaled : F * (16 * distance - c) ≤ 0 := by nlinarith + have hdiff : 16 * distance - c ≤ 0 := by nlinarith + linarith + have hcosts := abs_le.mp hcost + have hcrLower : c / 2 ≤ centerCost := by linarith + have hcrUpper : centerCost ≤ 2 * c := by linarith + have hUrpos : 0 < Ur := by linarith [hcenter.1] + have hcScale : c ≤ 8 * A * b := by linarith [hcenter.1, heligible.2] + have hAc := mul_le_mul_of_nonneg_left hcScale hA0.le + have hAb : 0 ≤ A ^ 2 * b := mul_nonneg (sq_nonneg _) hb + have hlower : Uq / (16 * A ^ 2) ≤ b := by + apply (div_le_iff₀ (by positivity : 0 < 16 * A ^ 2)).2 + nlinarith [hquery.2] + have hcenterScale := mul_le_mul_of_nonneg_left hcrUpper hA0.le + have hqueryScale := mul_le_mul_of_nonneg_left hquery.1 (by positivity : 0 ≤ 4 * A) + have hupper : b ≤ 4 * A * Uq := by nlinarith [heligible.1, hcenter.2] + exact ⟨hdist, hUrpos.ne', hlower, hupper, by linarith [hquery.1]⟩ + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/Cones.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/Cones.lean new file mode 100644 index 0000000000000000000000000000000000000000..4ecaddfe91d15425fb17b63a77ddd03489033213 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/Cones.lean @@ -0,0 +1,101 @@ +import Mathlib + +namespace OAI + +/-! +# Scalar steps of the refinement update + +These are the min/max and first-crossing calculations in Sections 5 and 7 +of *An Almost-Linear Approximation Scheme for Edit Distance* (2026). +They are internal lemmas, not the main algorithmic theorem. +-/ + +namespace EditApproximation + +/-- The nonzero branch of the refinement update, for a nonempty online list. +An empty list returns the cone minimum directly. -/ +noncomputable def refinementUpdate (δ cone online : ℝ) : ℝ := + min cone (max (cone / (1 + δ)) online) + +theorem refinementUpdate_sandwich {δ cone online lower : ℝ} + (hcone : lower ≤ cone) (honline : lower ≤ online) : + lower ≤ refinementUpdate δ cone online ∧ + refinementUpdate δ cone online ≤ cone := + ⟨le_min hcone (honline.trans (le_max_right _ _)), min_le_left _ _⟩ + +theorem refinementUpdate_div_le {δ cone online : ℝ} + (hδ : 0 ≤ δ) (hcone : 0 ≤ cone) : + cone / (1 + δ) ≤ refinementUpdate δ cone online := by + apply le_min _ (le_max_left _ _) + apply (div_le_iff₀ (by positivity : 0 < 1 + δ)).2 + nlinarith + +/-- The cone sandwich gives the multiplicative spatial regularity, +regardless of the independently sampled online values. -/ +theorem refinementUpdate_spatial {δ cone cone' online online' charge : ℝ} + (hδ : 0 ≤ δ) (hcone' : 0 ≤ cone') (hspatial : cone ≤ cone' + charge) : + refinementUpdate δ cone online ≤ + (1 + δ) * refinementUpdate δ cone' online' + charge := by + have hdiv := refinementUpdate_div_le (online := online') hδ hcone' + have hmul := (div_le_iff₀ (by positivity : 0 < 1 + δ)).1 hdiv + have hup : refinementUpdate δ cone online ≤ cone := min_le_left _ _ + nlinarith + +/-- Prefix step of Proposition `prop:node-regret`: if the group estimate +succeeds, any excess over the sampled action is paid by its decrement. -/ +theorem refinementUpdate_prefix {δ κ cone online action oldAction b c error : ℝ} + (hδ : 0 < δ) (hκ : 0 ≤ κ) (hc0 : 0 ≤ c) (hb : b ≤ c) + (hc : c ≤ action) (hmonotone : action ≤ oldAction) + (honline : online ≤ action) (hbellman : cone ≤ oldAction) + (hgroup : cone ≤ (1 + δ) * action + error * b) + (herror : error * b ≤ κ * δ * b) : + max c (refinementUpdate δ cone online) ≤ + action + κ * (oldAction - action) := by + apply max_le (by nlinarith) _ + by_cases hu : refinementUpdate δ cone online ≤ action + · nlinarith + · have hact : action < refinementUpdate δ cone online := lt_of_not_ge hu + have hdiv : action < cone / (1 + δ) := by + have hmax : action < max (cone / (1 + δ)) online := + hact.trans_le (min_le_right _ _) + exact (lt_max_iff.mp hmax).resolve_right (not_lt_of_ge honline) + have hcone : (1 + δ) * action < cone := by + have := (lt_div_iff₀ (by positivity : 0 < 1 + δ)).1 hdiv + nlinarith + have hdecrement : δ * b < oldAction - action := by + nlinarith + have hcone0 : 0 ≤ cone := + (mul_nonneg (by positivity : 0 ≤ 1 + δ) (hc0.trans hc)).trans hcone.le + have hdivle : cone / (1 + δ) ≤ cone := by + apply (div_le_iff₀ (by positivity : 0 < 1 + δ)).2 + nlinarith + have heq : refinementUpdate δ cone online = cone / (1 + δ) := by + rw [refinementUpdate, max_eq_left (honline.trans hdiv.le)] + exact min_eq_right hdivle + rw [heq] + apply (div_le_iff₀ (by positivity : 0 < 1 + δ)).2 + have hpay : κ * δ * b ≤ κ * (oldAction - action) := + by simpa only [mul_assoc] using mul_le_mul_of_nonneg_left hdecrement.le hκ + have hslack : 0 ≤ δ * (κ * (oldAction - action)) := + mul_nonneg hδ.le (mul_nonneg hκ (sub_nonneg.mpr hmonotone)) + nlinarith + +/-- The crossing iteration is paid once; later Bellman bounds use the +same action and make the clipped regret nonpositive. -/ +theorem refinementUpdate_crossing {δ cone online action c : ℝ} + (hδ : 0 ≤ δ) (hc : 0 ≤ c) (haction : action < c) + (hgroup : cone ≤ (1 + δ) * action + δ * c) : + max c (refinementUpdate δ cone online) ≤ c + 2 * δ * c := by + have hup : refinementUpdate δ cone online ≤ cone := min_le_left _ _ + have hmul := mul_le_mul_of_nonneg_left haction.le (by positivity : 0 ≤ 1 + δ) + apply max_le <;> nlinarith + +theorem clipped_regret_nonpos {parent cost childClipped charge : ℝ} + (hparent : parent ≤ cost) (hconnection : cost ≤ charge + childClipped) : + max cost parent - charge - childClipped ≤ 0 := by + rw [max_eq_left hparent] + linarith + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/Connections.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/Connections.lean new file mode 100644 index 0000000000000000000000000000000000000000..062c25f2c8154fa831d424296f4238e1812e5c8d --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/Connections.lean @@ -0,0 +1,220 @@ +import OAI.Combinatorics.EditApproximation.Geometry.Geometry +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! +# Connection costs with arbitrary gaps and overlaps + +This proves the edit-cost part of the connection inequality of Section 2 +for actual substrings and edit scripts. Prefixes telescope across the +child intervals; common-prefix cancellation then removes the outside +prefix. The children need not have ordered or shared target endpoints. +-/ + +namespace EditApproximation + +open EditDistortion + +universe u + +theorem edit_drop_insert_le {α : Type u} (p q : List α) (a : α) (k : ℕ) : + edit ((p ++ q).drop k) ((p ++ a :: q).drop k) ≤ 1 := by + by_cases hk : k ≤ p.length + · simp only [List.drop_append_of_le_length hk] + exact cost_le (Script.single (Step.insert (p.drop k) q a)) + · have hp : p.length ≤ k := by omega + have hpos : 0 < k - p.length := by omega + simp only [List.drop_append, List.drop_eq_nil_of_le hp, List.nil_append, + List.drop_cons hpos] + apply (edit_drop_indices_le q (k - p.length) (k - p.length - 1)).trans + unfold Nat.dist + omega + +theorem edit_drop_step_le {α : Type u} {x y : List α} (h : Step true x y) (k : ℕ) : + edit (x.drop k) (y.drop k) ≤ 1 := by + cases h with + | insert p q a => exact edit_drop_insert_le p q a k + | delete p q a => + rw [show edit ((p ++ a :: q).drop k) ((p ++ q).drop k) = + edit ((p ++ q).drop k) ((p ++ a :: q).drop k) from cost_symm _ _] + exact edit_drop_insert_le p q a k + | substitute _ p q a b => + by_cases hk : k ≤ p.length + · simp only [List.drop_append_of_le_length hk] + exact cost_le (Script.single (Step.substitute rfl (p.drop k) q a b)) + · have hp : p.length ≤ k := by omega + have hpos : 0 < k - p.length := by omega + simp only [List.drop_append, List.drop_eq_nil_of_le hp, List.nil_append, + List.drop_cons hpos] + have hrefl : edit (q.drop (k - p.length - 1)) (q.drop (k - p.length - 1)) = 0 := + cost_refl _ + rw [hrefl] + omega + +theorem edit_drop_script_le {α : Type u} {x y : List α} {n : ℕ} + (h : Script true n x y) (k : ℕ) : edit (x.drop k) (y.drop k) ≤ n := by + induction h with + | nil x => exact (cost_refl (x.drop k)).le + | @cons n x y z step rest ih => + have hstep := edit_drop_step_le step k + exact (cost_triangle (s := true) (x.drop k) (y.drop k) (z.drop k)).trans + (by change edit (x.drop k) (y.drop k) + edit (y.drop k) (z.drop k) ≤ n + 1; omega) + +theorem edit_drop_nonexpansive {α : Type u} (x y : List α) (k : ℕ) : + edit (x.drop k) (y.drop k) ≤ edit x y := by + simpa only [cost, edit] using edit_drop_script_le (cost_spec (s := true) x y) k + +theorem edit_append_left_cancel {α : Type u} (pre x y : List α) : + edit (pre ++ x) (pre ++ y) = edit x y := by + apply Nat.le_antisymm + · exact cost_le ((cost_spec (s := true) x y).append_left pre) + · simpa only [List.drop_append_length] using + edit_drop_nonexpansive (pre ++ x) (pre ++ y) pre.length + +theorem edit_append_right_le {α : Type u} (x y suffix : List α) : + edit (x ++ suffix) (y ++ suffix) ≤ edit x y := + cost_le ((cost_spec (s := true) x y).append_right suffix) + + + +/-- The outside and successive endpoint charges, including the final jump. -/ + + +def targetConcatenation {α : Type u} (word : List α) + (states : List (TargetInterval word.length)) : List α := + (states.map fun state => substring word state.lo state.hi).flatten + +theorem prefix_append_substring {α : Type u} (word : List α) {lo hi : ℕ} + (horder : lo ≤ hi) : word.take lo ++ substring word lo hi = word.take hi := by + have htake : (word.take hi).take lo = word.take lo := by + simp only [List.take_take, Nat.min_eq_left horder] + rw [substring, ← htake] + exact List.take_append_drop lo (word.take hi) + +theorem prefix_child_step {α : Type u} (word : List α) (start : ℕ) + (state : TargetInterval word.length) : + edit (word.take start ++ substring word state.lo state.hi) (word.take state.hi) ≤ + Nat.dist start state.lo := by + rw [← prefix_append_substring word state.ordered] + apply (edit_append_right_le _ _ _).trans + simpa only [substring, List.drop_zero] using + edit_substring_right_le word 0 start state.lo + +theorem prefix_connection_bound {α : Type u} (word : List α) + (states : List (TargetInterval word.length)) (start finish : ℕ) : + edit (word.take start ++ targetConcatenation word states) (word.take finish) ≤ + connectionBudget start states finish := by + induction states generalizing start with + | nil => + simpa only [targetConcatenation, List.map_nil, List.flatten_nil, List.append_nil, + connectionBudget, substring, List.drop_zero] using + edit_substring_right_le word 0 start finish + | cons state rest ih => + simp only [targetConcatenation, List.map_cons, List.flatten_cons] + rw [← List.append_assoc] + have hstep := (edit_append_right_le _ _ (targetConcatenation word rest)).trans + (prefix_child_step word start state) + have htri := cost_triangle (s := true) + ((word.take start ++ substring word state.lo state.hi) ++ targetConcatenation word rest) + (word.take state.hi ++ targetConcatenation word rest) (word.take finish) + exact htri.trans (Nat.add_le_add hstep (ih state.hi)) + +/-- The target-only part of the connection inequality. The prefix proof +accounts for overlaps and backwards connecting jumps automatically. -/ +theorem target_connection_bound {α : Type u} (word : List α) + (states : List (TargetInterval word.length)) (parent : TargetInterval word.length) : + edit (targetConcatenation word states) (substring word parent.lo parent.hi) ≤ + connectionBudget parent.lo states parent.hi := by + have h := edit_drop_nonexpansive + (word.take parent.lo ++ targetConcatenation word states) + (word.take parent.hi) parent.lo + have hlen : (word.take parent.lo).length = parent.lo := by + simp only [List.length_take, Nat.min_eq_left (parent.ordered.trans parent.valid)] + have hdrop : (word.take parent.lo ++ targetConcatenation word states).drop parent.lo = + targetConcatenation word states := by + simpa only [hlen] using List.drop_append_length + (l₁ := word.take parent.lo) (l₂ := targetConcatenation word states) + rw [hdrop] at h + exact h.trans (prefix_connection_bound word states parent.lo parent.hi) + +theorem edit_flatten_pairs_le {α : Type u} (pairs : List (List α × List α)) : + edit (pairs.map Prod.fst).flatten (pairs.map Prod.snd).flatten ≤ + (pairs.map fun pair => edit pair.1 pair.2).sum := by + induction pairs with + | nil => exact (cost_refl ([] : List α)).le + | cons pair rest ih => + simp only [List.map_cons, List.flatten_cons, List.sum_cons] + exact (cost_append_le (s := true) pair.1 pair.2 + (rest.map Prod.fst).flatten (rest.map Prod.snd).flatten).trans + (Nat.add_le_add_left ih _) + +/-- Child editing plus endpoint connections bounds the parent cost, for +an actual concatenated partition of the source string. -/ +theorem child_connection_bound {α : Type u} (word : List α) + (children : List (List α × TargetInterval word.length)) + (parent : TargetInterval word.length) : + edit (children.map Prod.fst).flatten (substring word parent.lo parent.hi) ≤ + (children.map fun child => edit child.1 (substring word child.2.lo child.2.hi)).sum + + connectionBudget parent.lo (children.map Prod.snd) parent.hi := by + have hchildren := edit_flatten_pairs_le + (children.map fun child => (child.1, substring word child.2.lo child.2.hi)) + simp only [List.map_map, Function.comp_def] at hchildren + have htarget := target_connection_bound word (children.map Prod.snd) parent + have htri := cost_triangle (s := true) (children.map Prod.fst).flatten + (targetConcatenation word (children.map Prod.snd)) (substring word parent.lo parent.hi) + apply htri.trans + exact Nat.add_le_add (by simpa only [targetConcatenation, List.map_map, + Function.comp_def, cost, edit] using hchildren) htarget + +def signedLengthGap {α : Type u} (source target : List α) : ℝ := + (target.length : ℝ) - source.length + +theorem signedLengthGap_append {α : Type u} (x y u v : List α) : + signedLengthGap (x ++ u) (y ++ v) = signedLengthGap x y + signedLengthGap u v := by + simp only [signedLengthGap, List.length_append, Nat.cast_add] + ring + +theorem flattened_length_gap_le {α : Type u} (pairs : List (List α × List α)) : + |signedLengthGap (pairs.map Prod.fst).flatten (pairs.map Prod.snd).flatten| ≤ + (pairs.map fun pair => |signedLengthGap pair.1 pair.2|).sum := by + induction pairs with + | nil => simp [signedLengthGap] + | cons pair rest ih => + simp only [List.map_cons, List.flatten_cons, List.sum_cons, signedLengthGap_append] + exact (abs_add_le _ _).trans (add_le_add le_rfl ih) + +/-- Length gaps obey the same arbitrary-gap connection inequality as +the edit costs. This is the second lower invariant of the Bellman operator. -/ +theorem child_shift_connection_bound {α : Type u} (word : List α) + (children : List (List α × TargetInterval word.length)) + (parent : TargetInterval word.length) : + |signedLengthGap (children.map Prod.fst).flatten (substring word parent.lo parent.hi)| ≤ + (children.map fun child => + |signedLengthGap child.1 (substring word child.2.lo child.2.hi)|).sum + + (connectionBudget parent.lo (children.map Prod.snd) parent.hi : ℝ) := by + let pairs := children.map fun child => (child.1, substring word child.2.lo child.2.hi) + have hflatten := flattened_length_gap_le pairs + have htarget := target_connection_bound word (children.map Prod.snd) parent + have hgap := abs_length_gap_le_edit (targetConcatenation word (children.map Prod.snd)) + (substring word parent.lo parent.hi) + have hbudget : |signedLengthGap (targetConcatenation word (children.map Prod.snd)) + (substring word parent.lo parent.hi)| ≤ + (connectionBudget parent.lo (children.map Prod.snd) parent.hi : ℝ) := + hgap.trans (by exact_mod_cast htarget) + have hid : signedLengthGap (children.map Prod.fst).flatten + (substring word parent.lo parent.hi) = + signedLengthGap (pairs.map Prod.fst).flatten (pairs.map Prod.snd).flatten + + signedLengthGap (targetConcatenation word (children.map Prod.snd)) + (substring word parent.lo parent.hi) := by + simp only [pairs, List.map_map, Function.comp_def, targetConcatenation, signedLengthGap] + ring + rw [hid] + apply (abs_add_le _ _).trans + have hsum := add_le_add hflatten hbudget + simpa only [pairs, List.map_map, Function.comp_def] using hsum + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/CurrentQueryInputs.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/CurrentQueryInputs.lean new file mode 100644 index 0000000000000000000000000000000000000000..868e73e4c6684693cfc0fa8dfe3d5264145148b8 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/CurrentQueryInputs.lean @@ -0,0 +1,184 @@ +import OAI.Combinatorics.EditApproximation.Geometry.SharedGroupInputBudget +import OAI.Combinatorics.EditApproximation.Geometry.LocalGroupBudget +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Distinct current-index inputs of the bounded query loops. The cover +includes all whole-cell shared estimates, selected cell actions, and +online actions; repeated uses do not add recursive calls. -/ + +namespace EditApproximation + +open Finset + +theorem groupDyadicScales_lower {M b F : ℕ} (hM : 0 < M) (hb : 0 < b) + (hF : 0 < F) (h : ℚ) (hh : h ∈ groupDyadicScales M b F) : + (b : ℚ) / M ≤ h := by + obtain ⟨e, he, rfl⟩ := List.mem_map.mp hh + exact ((groupDyadicScales_mem hM hb (F : ℚ) (by exact_mod_cast hF) e).mp + (List.mem_map.mpr ⟨e, he, rfl⟩)).1 + + + +theorem localGroupQueryKeys_scale {n N F exponent : ℕ} {a : ℚ} + {initial : TargetInterval n → ℚ} {q : TargetInterval n} {key : ℕ × (ℕ × ℕ)} + (hkey : key ∈ localGroupQueryKeys N F exponent a initial q) : + key.1 ∈ dyadicScales N := by + obtain ⟨b, hb, hcell⟩ := List.mem_flatMap.mp hkey + obtain ⟨cell, _, rfl⟩ := List.mem_map.mp hcell + exact (List.mem_filter.mp hb).1 + +theorem localGroupQueryKeys_length {n : ℕ} (N F exponent : ℕ) (a : ℚ) + (initial : TargetInterval n → ℚ) (q : TargetInterval n) + (hF : 1 ≤ F) (hw : 0 ≤ initial q) : + (localGroupQueryKeys N F exponent a initial q).length ≤ + (dyadicQueryWindow N (initial q) a F).length * + ((32 * F + 2) * 2 ^ exponent + 2) ^ 2 := by + unfold localGroupQueryKeys + apply list_flatMap_length_le + intro b hb + have hwindow := of_decide_eq_true (List.mem_filter.mp hb).2 + have hbpos : 1 ≤ b := by + obtain ⟨e, _, rfl⟩ := List.mem_map.mp (List.mem_filter.mp hb).1 + exact Nat.one_le_two_pow + simpa only [List.length_map] using + localTargetCells_query_length F b exponent q (initial q) hF hbpos hw hwindow.1 + + + +theorem querySharedInputCover_card {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (N F exponent Q labels : ℕ) (a : ℚ) + (initial : TargetInterval target.length → ℚ) (q : TargetInterval target.length) + (draw : CellGroupDraws M F Q) (hM : 0 < M) (hF : 1 ≤ F) (hQ : 1 ≤ Q) + (hlabels : ∀ b ∈ dyadicScales N, (groupDyadicScales M b F).length ≤ labels) : + ((querySharedInputCover source target parent N F exponent Q a initial q draw).card : ℚ) ≤ + (localGroupQueryKeys N F exponent a initial q).length * labels * + (624 * M * Q * ((2 : ℚ) ^ exponent) ^ 2) := by + let keys := (localGroupQueryKeys N F exponent a initial q).toFinset + let C : ℚ := 624 * M * Q * ((2 : ℚ) ^ exponent) ^ 2 + have hC : 0 ≤ C := by dsimp only [C]; positivity + have hper (key : ℕ × (ℕ × ℕ)) (hk : key ∈ keys) : + ((Finset.univ.biUnion fun scale : Fin (groupDyadicScales M key.1 F).length => + groupCurrentInputCover source target parent key.1 exponent Q key.2 + (groupDyadicScaleAt M key.1 F scale) (draw key.1 key.2 scale)).card : ℚ) ≤ labels * C := by + have hb := localGroupQueryKeys_scale (List.mem_toFinset.mp hk) + have hbpos : 0 < key.1 := by + obtain ⟨e, _, he⟩ := List.mem_map.mp hb + rw [← he] + positivity + have hcard := Finset.card_biUnion_le (s := (Finset.univ : + Finset (Fin (groupDyadicScales M key.1 F).length))) + (t := fun scale => groupCurrentInputCover source target parent key.1 exponent Q key.2 + (groupDyadicScaleAt M key.1 F scale) (draw key.1 key.2 scale)) + have hcardR : ((Finset.univ.biUnion fun scale : Fin (groupDyadicScales M key.1 F).length => + groupCurrentInputCover source target parent key.1 exponent Q key.2 + (groupDyadicScaleAt M key.1 F scale) (draw key.1 key.2 scale)).card : ℚ) ≤ + ∑ scale : Fin (groupDyadicScales M key.1 F).length, + ((groupCurrentInputCover source target parent key.1 exponent Q key.2 + (groupDyadicScaleAt M key.1 F scale) (draw key.1 key.2 scale)).card : ℚ) := by + exact_mod_cast hcard + apply hcardR.trans + have hscale (scale : Fin (groupDyadicScales M key.1 F).length) := + List.get_mem (groupDyadicScales M key.1 F) scale + calc + _ ≤ ∑ _scale : Fin (groupDyadicScales M key.1 F).length, C := by + apply Finset.sum_le_sum + intro scale _ + exact groupCurrentInputCover_card source target parent exponent Q key.2 _ hM hQ hbpos + (groupDyadicScales_pos (hscale scale)) + (groupDyadicScales_lower hM hbpos (by omega) _ (hscale scale)) _ + _ = (groupDyadicScales M key.1 F).length * C := by + rw [Finset.sum_const, Finset.card_univ, Fintype.card_fin, nsmul_eq_mul] + _ ≤ labels * C := mul_le_mul_of_nonneg_right (by exact_mod_cast hlabels key.1 hb) hC + have hcard := Finset.card_biUnion_le (s := keys) + (t := fun key => Finset.univ.biUnion fun scale : Fin (groupDyadicScales M key.1 F).length => + groupCurrentInputCover source target parent key.1 exponent Q key.2 + (groupDyadicScaleAt M key.1 F scale) (draw key.1 key.2 scale)) + have hcardR : ((querySharedInputCover source target parent N F exponent Q a initial q draw).card : ℚ) ≤ + ∑ key ∈ keys, ((Finset.univ.biUnion fun scale : Fin (groupDyadicScales M key.1 F).length => + groupCurrentInputCover source target parent key.1 exponent Q key.2 + (groupDyadicScaleAt M key.1 F scale) (draw key.1 key.2 scale)).card : ℚ) := by + exact_mod_cast hcard + calc + _ ≤ ∑ key ∈ keys, ((Finset.univ.biUnion fun scale : Fin (groupDyadicScales M key.1 F).length => + groupCurrentInputCover source target parent key.1 exponent Q key.2 + (groupDyadicScaleAt M key.1 F scale) (draw key.1 key.2 scale)).card : ℚ) := hcardR + _ ≤ ∑ _key ∈ keys, labels * C := Finset.sum_le_sum hper + _ = (keys.card : ℚ) * (labels * C) := by rw [Finset.sum_const, nsmul_eq_mul] + _ ≤ (localGroupQueryKeys N F exponent a initial q).length * (labels * C) := + mul_le_mul_of_nonneg_right (by exact_mod_cast List.toFinset_card_le _) (mul_nonneg (Nat.cast_nonneg _) hC) + _ = _ := by ring + + + +theorem actionCurrentInputCover_card {Parent Child : Type*} [DecidableEq Child] {M : ℕ} + (actions : List (RationalBellmanAction Parent Child M)) : + (actionCurrentInputCover actions).card ≤ actions.length * M := by + unfold actionCurrentInputCover + have hindices : (List.finRange actions.length).toFinset = (Finset.univ : Finset (Fin actions.length)) := by + ext i + simp + rw [hindices] + apply Finset.card_biUnion_le.trans + apply (Finset.sum_le_sum (fun _ _ => Finset.card_image_le)).trans_eq + simp only [Finset.card_univ, Fintype.card_fin, Finset.sum_const, nsmul_eq_mul, Nat.cast_id] + +theorem actionCurrentInputCover_mem {Parent Child : Type*} [DecidableEq Child] {M : ℕ} + (actions : List (RationalBellmanAction Parent Child M)) + (action : RationalBellmanAction Parent Child M) (ha : action ∈ actions) (i : Fin M) : + action.childState i ∈ actionCurrentInputCover actions := by + obtain ⟨index, hindex⟩ := List.mem_iff_get.mp ha + apply Finset.mem_biUnion.mpr + refine ⟨index, by simp, ?_⟩ + exact Finset.mem_image.mpr ⟨i, Finset.mem_univ _, by rw [hindex]⟩ + +def currentQueryInputCover {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (N P F exponent Q : ℕ) (tau a : ℚ) + (parentInitial : TargetInterval target.length → ℚ) + (child initial current : Fin M → TargetInterval target.length → ℚ) + (draw : CellGroupDraws M F Q) (q : TargetInterval target.length) + (online : List (PhysicalRationalAction M target.length)) : Finset (Fin M × TargetInterval target.length) := + querySharedInputCover source target parent N F exponent Q a parentInitial q draw ∪ + actionCurrentInputCover (localCellGroupActions source target parent N P F exponent Q tau a parentInitial + child initial current draw q) ∪ actionCurrentInputCover online + +theorem currentQueryInputCover_card {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (N P F exponent Q labels : ℕ) (tau a : ℚ) + (parentInitial : TargetInterval target.length → ℚ) + (child initial current : Fin M → TargetInterval target.length → ℚ) + (draw : CellGroupDraws M F Q) (q : TargetInterval target.length) + (online : List (PhysicalRationalAction M target.length)) + (hM : 0 < M) (hF : 1 ≤ F) (hQ : 1 ≤ Q) + (hlabels : ∀ b ∈ dyadicScales N, (groupDyadicScales M b F).length ≤ labels) : + ((currentQueryInputCover source target parent N P F exponent Q tau a parentInitial + child initial current draw q online).card : ℚ) ≤ + (localGroupQueryKeys N F exponent a parentInitial q).length * labels * + (624 * M * Q * ((2 : ℚ) ^ exponent) ^ 2) + + (localCellGroupActions source target parent N P F exponent Q tau a parentInitial + child initial current draw q).length * M + online.length * M := by + have hcard := Finset.card_union_le + (querySharedInputCover source target parent N F exponent Q a parentInitial q draw ∪ + actionCurrentInputCover (localCellGroupActions source target parent N P F exponent Q tau a parentInitial + child initial current draw q)) (actionCurrentInputCover online) + have hleft := Finset.card_union_le + (querySharedInputCover source target parent N F exponent Q a parentInitial q draw) + (actionCurrentInputCover (localCellGroupActions source target parent N P F exponent Q tau a parentInitial + child initial current draw q)) + have hN := hcard.trans (Nat.add_le_add_right hleft _) + have hR : ((currentQueryInputCover source target parent N P F exponent Q tau a parentInitial + child initial current draw q online).card : ℚ) ≤ + (querySharedInputCover source target parent N F exponent Q a parentInitial q draw).card + + (actionCurrentInputCover (localCellGroupActions source target parent N P F exponent Q tau a parentInitial + child initial current draw q)).card + (actionCurrentInputCover online).card := by exact_mod_cast hN + apply hR.trans + exact add_le_add (add_le_add + (querySharedInputCover_card source target parent N F exponent Q labels a parentInitial q draw hM hF hQ hlabels) + (by exact_mod_cast (actionCurrentInputCover_card + (localCellGroupActions source target parent N P F exponent Q tau a parentInitial child initial current draw q)))) + (by exact_mod_cast (actionCurrentInputCover_card online)) + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/Curvature.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/Curvature.lean new file mode 100644 index 0000000000000000000000000000000000000000..459735a03376845f77bb27f98ec0536dda01703a --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/Curvature.lean @@ -0,0 +1,146 @@ +import Mathlib + +namespace OAI + +/-! +# Cost-weighted curvature + +Finite weighted variance and the local energy telescope from Section 6 +of the edit-distance manuscript. Zero child masses are allowed, with the +length-gap invariant forcing their length gaps to vanish. +-/ + +namespace EditApproximation + +open Finset + +theorem weighted_variance_identity {ι : Type*} (children : Finset ι) + (mass gap : ι → ℝ) + (hzero : ∀ i ∈ children, mass i = 0 → gap i = 0) + (hW : 0 < ∑ i ∈ children, mass i) : + (∑ i ∈ children, gap i ^ 2 / mass i) - + (∑ i ∈ children, gap i) ^ 2 / (∑ i ∈ children, mass i) = + ∑ i ∈ children, + (gap i - ((∑ j ∈ children, gap j) / (∑ j ∈ children, mass j)) * mass i) ^ 2 / + mass i := by + let v := (∑ i ∈ children, gap i) / (∑ i ∈ children, mass i) + have hterm (i : ι) (hi : i ∈ children) : + (gap i - v * mass i) ^ 2 / mass i = + gap i ^ 2 / mass i - 2 * v * gap i + v ^ 2 * mass i := by + by_cases hz : mass i = 0 + · simp only [hz, hzero i hi hz, mul_zero, zero_pow (by omega : 2 ≠ 0), + zero_div, sub_self, zero_add] + · field_simp + ring + have hsum := sum_congr rfl hterm + rw [sum_add_distrib, sum_sub_distrib, ← mul_sum, ← mul_sum] at hsum + rw [hsum] + dsimp [v] + field_simp + ring + +theorem curvature_nonneg {ι : Type*} (children : Finset ι) + (mass gap : ι → ℝ) + (hmass : ∀ i ∈ children, 0 ≤ mass i) + (hzero : ∀ i ∈ children, mass i = 0 → gap i = 0) + (hW : 0 < ∑ i ∈ children, mass i) : + 0 ≤ (∑ i ∈ children, gap i ^ 2 / mass i) - + (∑ i ∈ children, gap i) ^ 2 / (∑ i ∈ children, mass i) := by + rw [weighted_variance_identity children mass gap hzero hW] + exact sum_nonneg fun i hi => div_nonneg (sq_nonneg _) (hmass i hi) + +/-- Weighted Cauchy--Schwarz controls the total absolute deviation by +the curvature times the total warmup mass. -/ +theorem curvature_l1_squared_le {ι : Type*} (children : Finset ι) + (mass gap : ι → ℝ) + (hmass : ∀ i ∈ children, 0 ≤ mass i) + (hzero : ∀ i ∈ children, mass i = 0 → gap i = 0) + (hW : 0 < ∑ i ∈ children, mass i) : + (∑ i ∈ children, + |gap i - ((∑ j ∈ children, gap j) / (∑ j ∈ children, mass j)) * mass i|) ^ 2 ≤ + (∑ i ∈ children, mass i) * + ((∑ i ∈ children, gap i ^ 2 / mass i) - + (∑ i ∈ children, gap i) ^ 2 / (∑ i ∈ children, mass i)) := by + let v := (∑ i ∈ children, gap i) / (∑ i ∈ children, mass i) + have hterm (i : ι) (hi : i ∈ children) : + |gap i - v * mass i| ^ 2 ≤ mass i * ((gap i - v * mass i) ^ 2 / mass i) := by + by_cases hz : mass i = 0 + · simp only [hz, hzero i hi hz, mul_zero, sub_zero, abs_zero, + zero_pow (by omega : 2 ≠ 0), zero_div, le_refl] + · rw [sq_abs] + exact le_of_eq (by field_simp) + have hcs := sum_sq_le_sum_mul_sum_of_sq_le_mul children hmass + (fun i hi => div_nonneg (sq_nonneg (gap i - v * mass i)) (hmass i hi)) hterm + rw [weighted_variance_identity children mass gap hzero hW] + exact hcs + +theorem curvature_l1_le_sqrt {ι : Type*} (children : Finset ι) + (mass gap : ι → ℝ) + (hmass : ∀ i ∈ children, 0 ≤ mass i) + (hzero : ∀ i ∈ children, mass i = 0 → gap i = 0) + (hW : 0 < ∑ i ∈ children, mass i) : + (∑ i ∈ children, + |gap i - ((∑ j ∈ children, gap j) / (∑ j ∈ children, mass j)) * mass i|) ≤ + Real.sqrt ((∑ i ∈ children, mass i) * + ((∑ i ∈ children, gap i ^ 2 / mass i) - + (∑ i ∈ children, gap i) ^ 2 / (∑ i ∈ children, mass i))) := by + apply (sq_le_sq₀ (sum_nonneg fun _ _ => abs_nonneg _) (Real.sqrt_nonneg _)).mp + rw [Real.sq_sqrt (mul_nonneg hW.le (curvature_nonneg children mass gap hmass hzero hW))] + exact curvature_l1_squared_le children mass gap hmass hzero hW + +/-- The parent/rounded-parent energy discrepancy is controlled by endpoint +movement and the negative part of the parent-minus-child mass discrepancy. -/ +theorem local_energy_discrepancy {parentMass childMass parentGap roundedGap movement : ℝ} + (hp : 0 < parentMass) (hc : 0 < childMass) + (hparent : |parentGap| ≤ parentMass) + (hchild : |roundedGap| ≤ childMass) + (hmove : |parentGap - roundedGap| ≤ movement) + (hsmall : movement ≤ parentMass) : + parentGap ^ 2 / parentMass - roundedGap ^ 2 / childMass ≤ + 3 * movement + 2 * max (childMass - parentMass) 0 := by + have he : 0 ≤ movement := (abs_nonneg _).trans hmove + have hrounded : |roundedGap| ≤ 2 * parentMass := by + have ht := abs_add_le parentGap (roundedGap - parentGap) + have hdiff : |roundedGap - parentGap| ≤ movement := by + simpa only [abs_sub_comm] using hmove + have hid : parentGap + (roundedGap - parentGap) = roundedGap := by ring + rw [hid] at ht + linarith + have hsum : |parentGap + roundedGap| ≤ 3 * parentMass := + (abs_add_le _ _).trans (by linarith) + have hnum : parentGap ^ 2 - roundedGap ^ 2 ≤ 3 * movement * parentMass := by + have hfactor : parentGap ^ 2 - roundedGap ^ 2 = + (parentGap - roundedGap) * (parentGap + roundedGap) := by ring + rw [hfactor] + apply (le_abs_self _).trans + rw [abs_mul] + have hmul := mul_le_mul hmove hsum (abs_nonneg _) he + nlinarith + have hfirst : (parentGap ^ 2 - roundedGap ^ 2) / parentMass ≤ 3 * movement := + (div_le_iff₀ hp).2 hnum + have hsecond : roundedGap ^ 2 * (childMass - parentMass) / (parentMass * childMass) ≤ + 2 * max (childMass - parentMass) 0 := by + by_cases hle : childMass ≤ parentMass + · have hnumle : roundedGap ^ 2 * (childMass - parentMass) ≤ 0 := + mul_nonpos_of_nonneg_of_nonpos (sq_nonneg _) (by linarith) + have hdivle := div_nonpos_of_nonpos_of_nonneg hnumle (mul_pos hp hc).le + exact hdivle.trans (by positivity) + · have hdiff : 0 ≤ childMass - parentMass := by linarith + have hsq : roundedGap ^ 2 ≤ 2 * parentMass * childMass := by + have hmul := mul_le_mul hrounded hchild (abs_nonneg _) (by positivity) + simpa only [← pow_two, sq_abs] using hmul + rw [max_eq_left hdiff] + apply (div_le_iff₀ (mul_pos hp hc)).2 + have hmul := mul_le_mul_of_nonneg_right hsq hdiff + nlinarith + have hid : parentGap ^ 2 / parentMass - roundedGap ^ 2 / childMass = + (parentGap ^ 2 - roundedGap ^ 2) / parentMass + + roundedGap ^ 2 * (childMass - parentMass) / (parentMass * childMass) := by + field_simp + ring + rw [hid] + linarith + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/DependencyExpansion.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/DependencyExpansion.lean new file mode 100644 index 0000000000000000000000000000000000000000..cecc762f98044b6932d97b2ded24c877b2203926 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/DependencyExpansion.lean @@ -0,0 +1,502 @@ +import OAI.Combinatorics.EditApproximation.Geometry.Work + +namespace OAI + +/-! Finite dependency expansions with two edge sorts. The certificate +checks progress and local branching at every actual node; the global +count follows from these local conditions. -/ + +namespace EditApproximation + +open Finset + +def dependencyWordCount (same earlier r s : ℕ) : ℕ := + (r + s).choose r * same ^ r * earlier ^ s + +theorem dependencyWordCount_succ (a b r s : ℕ) : + dependencyWordCount a b (r + 1) (s + 1) = + a * dependencyWordCount a b r (s + 1) + b * dependencyWordCount a b (r + 1) s := by + unfold dependencyWordCount + rw [show r + 1 + (s + 1) = (r + s + 1) + 1 by omega, Nat.choose_succ_succ'] + rw [show r + (s + 1) = r + s + 1 by omega, show r + 1 + s = r + s + 1 by omega] + simp only [pow_succ] + ring + +theorem dependencyPathBudget_mono (d k D K a b : ℕ) (hd : d ≤ D) (hk : k ≤ K) : + dependencyPathBudget d k a b ≤ dependencyPathBudget D K a b := by + unfold dependencyPathBudget + apply le_trans (sum_le_sum_of_subset (range_mono (Nat.add_le_add_right hd 1))) + apply sum_le_sum + intro r hr + exact sum_le_sum_of_subset (range_mono (Nat.add_le_add_right hk 1)) + +theorem dependencyPathBudget_zero_zero (a b : ℕ) : dependencyPathBudget 0 0 a b = 1 := by + simp [dependencyPathBudget] + +theorem dependencyPathBudget_succ_zero (d a b : ℕ) : + dependencyPathBudget (d + 1) 0 a b = 1 + a * dependencyPathBudget d 0 a b := by + simp only [dependencyPathBudget, zero_add, sum_range_one, add_zero, Nat.choose_self, + one_mul, pow_zero, mul_one] + rw [sum_range_succ'] + simp only [pow_succ, pow_zero] + rw [← sum_mul] + ring + +theorem dependencyPathBudget_zero_succ (k a b : ℕ) : + dependencyPathBudget 0 (k + 1) a b = 1 + b * dependencyPathBudget 0 k a b := by + simp only [dependencyPathBudget, zero_add, sum_range_one, Nat.choose_zero_right, + pow_zero, one_mul] + rw [sum_range_succ'] + simp only [pow_succ, pow_zero] + rw [← sum_mul] + ring + +theorem dependencyPathBudget_succ_succ (d k a b : ℕ) : + dependencyPathBudget (d + 1) (k + 1) a b = + 1 + a * dependencyPathBudget d (k + 1) a b + + b * dependencyPathBudget (d + 1) k a b := by + have hpascal (r s : ℕ) := dependencyWordCount_succ a b r s + have hleft (r : ℕ) : dependencyWordCount a b (r + 1) 0 = + a * dependencyWordCount a b r 0 := by + simp [dependencyWordCount, pow_succ, Nat.mul_comm] + have hright (s : ℕ) : dependencyWordCount a b 0 (s + 1) = + b * dependencyWordCount a b 0 s := by + simp [dependencyWordCount, pow_succ, Nat.mul_comm] + have hzero : dependencyWordCount a b 0 0 = 1 := by simp [dependencyWordCount] + have hsplit (r : ℕ) : (∑ s ∈ range (k + 2), dependencyWordCount a b r s) = + dependencyWordCount a b r 0 + ∑ s ∈ range (k + 1), dependencyWordCount a b r (s + 1) := by + rw [sum_range_succ'] + ring + change (∑ r ∈ range (d + 2), ∑ s ∈ range (k + 2), dependencyWordCount a b r s) = + 1 + a * (∑ r ∈ range (d + 1), ∑ s ∈ range (k + 2), dependencyWordCount a b r s) + + b * (∑ r ∈ range (d + 2), ∑ s ∈ range (k + 1), dependencyWordCount a b r s) + rw [sum_range_succ' (fun r => ∑ s ∈ range (k + 2), dependencyWordCount a b r s) (d + 1), + sum_range_succ' (fun r => ∑ s ∈ range (k + 1), dependencyWordCount a b r s) (d + 1)] + simp_rw [hsplit] + simp_rw [hpascal, sum_add_distrib, ← mul_sum] + simp_rw [hleft, hright, hzero, ← mul_sum] + ring + +theorem dependencyPathBudget_recurrence (d k a b : ℕ) : + dependencyPathBudget d k a b = 1 + + (if d = 0 then 0 else a * dependencyPathBudget (d - 1) k a b) + + (if k = 0 then 0 else b * dependencyPathBudget d (k - 1) a b) := by + cases d with + | zero => + cases k with + | zero => simp [dependencyPathBudget_zero_zero] + | succ k => simpa using dependencyPathBudget_zero_succ k a b + | succ d => + cases k with + | zero => simpa using dependencyPathBudget_succ_zero d a b + | succ k => simpa using dependencyPathBudget_succ_succ d k a b + +/-- Node labels carry remaining physical depth and remaining rank. +Children in the first and second arrays have distinct edge sorts. -/ +inductive DependencyExpansion where + | node (depth rank sameCount earlierCount : ℕ) + (sameChildren : Fin sameCount → DependencyExpansion) + (earlierChildren : Fin earlierCount → DependencyExpansion) : DependencyExpansion + +namespace DependencyExpansion + +def depth : DependencyExpansion → ℕ + | .node d _ _ _ _ _ => d + +def rank : DependencyExpansion → ℕ + | .node _ k _ _ _ _ => k + +def nodeCount : DependencyExpansion → ℕ + | .node _ _ _ _ same earlier => 1 + (∑ i, nodeCount (same i)) + ∑ i, nodeCount (earlier i) + +/-- Every same edge strictly decreases physical depth and never increases +rank. Every earlier edge strictly decreases rank and never increases depth. +No global count is part of this certificate. -/ +def Valid (a b : ℕ) : DependencyExpansion → Prop + | .node d k m n same earlier => + m ≤ a ∧ n ≤ b ∧ + (∀ i, (same i).depth < d ∧ (same i).rank ≤ k ∧ Valid a b (same i)) ∧ + (∀ i, (earlier i).depth ≤ d ∧ (earlier i).rank < k ∧ Valid a b (earlier i)) + +theorem nodeCount_le_budget (a b : ℕ) (tree : DependencyExpansion) (h : Valid a b tree) : + tree.nodeCount ≤ dependencyPathBudget tree.depth tree.rank a b := by + revert h + induction tree with + | node d k m n same earlier ihs ihe => + intro h + obtain ⟨hm, hn, hs, he⟩ := h + have hsame : (∑ i, (same i).nodeCount) ≤ + if d = 0 then 0 else a * dependencyPathBudget (d - 1) k a b := by + by_cases hd : d = 0 + · have hempty : m = 0 := by + by_contra hm0 + have hbad := (hs ⟨0, Nat.pos_of_ne_zero hm0⟩).1 + omega + subst m + simp [hd] + · rw [ite_eq_right hd] + calc + (∑ i, (same i).nodeCount) ≤ ∑ _ : Fin m, dependencyPathBudget (d - 1) k a b := by + apply sum_le_sum + intro i hi + exact (ihs i (hs i).2.2).trans (dependencyPathBudget_mono _ _ _ _ a b + (by have hp := (hs i).1; omega) (hs i).2.1) + _ = m * dependencyPathBudget (d - 1) k a b := by simp + _ ≤ a * dependencyPathBudget (d - 1) k a b := Nat.mul_le_mul_right _ hm + have hearlier : (∑ i, (earlier i).nodeCount) ≤ + if k = 0 then 0 else b * dependencyPathBudget d (k - 1) a b := by + by_cases hk : k = 0 + · have hempty : n = 0 := by + by_contra hn0 + have hbad := (he ⟨0, Nat.pos_of_ne_zero hn0⟩).2.1 + omega + subst n + simp [hk] + · rw [ite_eq_right hk] + calc + (∑ i, (earlier i).nodeCount) ≤ ∑ _ : Fin n, dependencyPathBudget d (k - 1) a b := by + apply sum_le_sum + intro i hi + exact (ihe i (he i).2.2).trans (dependencyPathBudget_mono _ _ _ _ a b + (he i).1 (by have hp := (he i).2.1; omega)) + _ = n * dependencyPathBudget d (k - 1) a b := by simp + _ ≤ b * dependencyPathBudget d (k - 1) a b := Nat.mul_le_mul_right _ hn + change 1 + (∑ i, (same i).nodeCount) + (∑ i, (earlier i).nodeCount) ≤ + dependencyPathBudget d k a b + rw [dependencyPathBudget_recurrence] + exact Nat.add_le_add (Nat.add_le_add_left hsame 1) hearlier + +theorem nodeCount_le_budget_of_le (a b D K : ℕ) (tree : DependencyExpansion) + (h : Valid a b tree) (hd : tree.depth ≤ D) (hk : tree.rank ≤ K) : + tree.nodeCount ≤ dependencyPathBudget D K a b := + (nodeCount_le_budget a b tree h).trans + (dependencyPathBudget_mono _ _ _ _ a b hd hk) + +/-- Literal count of nodes whose remaining physical depth is at least +`floor`. Descendants are inspected even when the current node fails the +test; pruning below the threshold is a consequence of `Valid`. -/ +def nodeCountAtOrAbove (floor : ℕ) : DependencyExpansion → ℕ + | .node d _ _ _ same earlier => + (if floor ≤ d then 1 else 0) + + (∑ i, nodeCountAtOrAbove floor (same i)) + + ∑ i, nodeCountAtOrAbove floor (earlier i) + +/-- Literal count of nodes at one remaining physical depth. -/ +def nodeCountAtDepth (target : ℕ) : DependencyExpansion → ℕ + | .node d _ _ _ same earlier => + (if d = target then 1 else 0) + + (∑ i, nodeCountAtDepth target (same i)) + + ∑ i, nodeCountAtDepth target (earlier i) + +theorem nodeCountAtOrAbove_eq_zero (a b floor : ℕ) (tree : DependencyExpansion) + (h : Valid a b tree) (hd : tree.depth < floor) : + nodeCountAtOrAbove floor tree = 0 := by + revert h hd + induction tree with + | node d k m n same earlier ihs ihe => + intro h hd + obtain ⟨hm, hn, hs, he⟩ := h + change d < floor at hd + change (if floor ≤ d then 1 else 0) + + (∑ i, nodeCountAtOrAbove floor (same i)) + + (∑ i, nodeCountAtOrAbove floor (earlier i)) = 0 + have hsame : ∀ i, nodeCountAtOrAbove floor (same i) = 0 := by + intro i + exact ihs i (hs i).2.2 (lt_trans (hs i).1 hd) + have hearlier : ∀ i, nodeCountAtOrAbove floor (earlier i) = 0 := by + intro i + exact ihe i (he i).2.2 (lt_of_le_of_lt (he i).1 hd) + simp [Nat.not_le.mpr hd, hsame, hearlier] + +/-- The path budget for a depth threshold uses only the available descent +above that threshold, independently of the total depth of the expansion. -/ +theorem nodeCountAtOrAbove_le_budget (a b floor : ℕ) (tree : DependencyExpansion) + (h : Valid a b tree) : + nodeCountAtOrAbove floor tree ≤ + dependencyPathBudget (tree.depth - floor) tree.rank a b := by + revert h + induction tree generalizing floor with + | node d k m n same earlier ihs ihe => + intro h + by_cases hfloor : d < floor + · have hzero := nodeCountAtOrAbove_eq_zero a b floor + (.node d k m n same earlier) h hfloor + rw [hzero] + exact Nat.zero_le _ + obtain ⟨hm, hn, hs, he⟩ := h + have hfd : floor ≤ d := Nat.le_of_not_gt hfloor + have hsame : (∑ i, nodeCountAtOrAbove floor (same i)) ≤ + if d - floor = 0 then 0 + else a * dependencyPathBudget (d - floor - 1) k a b := by + by_cases hd : d - floor = 0 + · have hzero : ∀ i, nodeCountAtOrAbove floor (same i) = 0 := by + intro i + apply nodeCountAtOrAbove_eq_zero a b floor (same i) (hs i).2.2 + have hp := (hs i).1 + omega + simp [hd, hzero] + · rw [ite_eq_right hd] + calc + (∑ i, nodeCountAtOrAbove floor (same i)) ≤ + ∑ _ : Fin m, dependencyPathBudget (d - floor - 1) k a b := by + apply sum_le_sum + intro i hi + exact (ihs i floor (hs i).2.2).trans + (dependencyPathBudget_mono _ _ _ _ a b + (by have hp := (hs i).1; omega) (hs i).2.1) + _ = m * dependencyPathBudget (d - floor - 1) k a b := by simp + _ ≤ a * dependencyPathBudget (d - floor - 1) k a b := + Nat.mul_le_mul_right _ hm + have hearlier : (∑ i, nodeCountAtOrAbove floor (earlier i)) ≤ + if k = 0 then 0 else b * dependencyPathBudget (d - floor) (k - 1) a b := by + by_cases hk : k = 0 + · have hempty : n = 0 := by + by_contra hn0 + have hbad := (he ⟨0, Nat.pos_of_ne_zero hn0⟩).2.1 + omega + subst n + simp [hk] + · rw [ite_eq_right hk] + calc + (∑ i, nodeCountAtOrAbove floor (earlier i)) ≤ + ∑ _ : Fin n, dependencyPathBudget (d - floor) (k - 1) a b := by + apply sum_le_sum + intro i hi + exact (ihe i floor (he i).2.2).trans + (dependencyPathBudget_mono _ _ _ _ a b + (Nat.sub_le_sub_right (he i).1 floor) + (by have hp := (he i).2.1; omega)) + _ = n * dependencyPathBudget (d - floor) (k - 1) a b := by simp + _ ≤ b * dependencyPathBudget (d - floor) (k - 1) a b := + Nat.mul_le_mul_right _ hn + change (if floor ≤ d then 1 else 0) + + (∑ i, nodeCountAtOrAbove floor (same i)) + + (∑ i, nodeCountAtOrAbove floor (earlier i)) ≤ dependencyPathBudget (d - floor) k a b + rw [ite_eq_left hfd, dependencyPathBudget_recurrence] + exact Nat.add_le_add (Nat.add_le_add_left hsame 1) hearlier + +theorem nodeCountAtDepth_le_atOrAbove (target : ℕ) (tree : DependencyExpansion) : + nodeCountAtDepth target tree ≤ nodeCountAtOrAbove target tree := by + induction tree with + | node d k m n same earlier ihs ihe => + change (if d = target then 1 else 0) + + (∑ i, nodeCountAtDepth target (same i)) + + (∑ i, nodeCountAtDepth target (earlier i)) ≤ + (if target ≤ d then 1 else 0) + + (∑ i, nodeCountAtOrAbove target (same i)) + + (∑ i, nodeCountAtOrAbove target (earlier i)) + apply Nat.add_le_add + · apply Nat.add_le_add + · split_ifs <;> omega + · exact sum_le_sum (fun i hi => ihs i) + · exact sum_le_sum (fun i hi => ihe i) + +/-- All nodes reached with physical descent at most `j`, including those +reached through earlier-index edges that themselves decrease depth. -/ +def nodeCountThroughDescent (j : ℕ) (tree : DependencyExpansion) : ℕ := + nodeCountAtOrAbove (tree.depth - j) tree + +/-- Nodes at physical descent exactly `j`. -/ +def layerNodeCount (j : ℕ) (tree : DependencyExpansion) : ℕ := + if j ≤ tree.depth then nodeCountAtDepth (tree.depth - j) tree else 0 + +theorem nodeCountThroughDescent_le_budget (a b j K : ℕ) (tree : DependencyExpansion) + (h : Valid a b tree) (hk : tree.rank ≤ K) : + nodeCountThroughDescent j tree ≤ dependencyPathBudget j K a b := by + exact (nodeCountAtOrAbove_le_budget a b (tree.depth - j) tree h).trans + (dependencyPathBudget_mono _ _ _ _ a b (by omega) hk) + +theorem layerNodeCount_le_throughDescent (j : ℕ) (tree : DependencyExpansion) : + layerNodeCount j tree ≤ nodeCountThroughDescent j tree := by + unfold layerNodeCount nodeCountThroughDescent + split_ifs + · exact nodeCountAtDepth_le_atOrAbove _ tree + · exact Nat.zero_le _ + +theorem layerNodeCount_le_budget (a b j K : ℕ) (tree : DependencyExpansion) + (h : Valid a b tree) (hk : tree.rank ≤ K) : + layerNodeCount j tree ≤ dependencyPathBudget j K a b := + (layerNodeCount_le_throughDescent j tree).trans + (nodeCountThroughDescent_le_budget a b j K tree h hk) + +theorem nodeCountAtDepth_sum (a b D : ℕ) (tree : DependencyExpansion) + (h : Valid a b tree) (hd : tree.depth ≤ D) : + (∑ t ∈ range (D + 1), nodeCountAtDepth t tree) = tree.nodeCount := by + revert h hd + induction tree with + | node d k m n same earlier ihs ihe => + intro h hd + obtain ⟨hm, hn, hs, he⟩ := h + change d ≤ D at hd + have hroot : (∑ t ∈ range (D + 1), if d = t then 1 else 0) = 1 := by + simp [mem_range.mpr (Nat.lt_succ_of_le hd)] + have hsame : (∑ t ∈ range (D + 1), ∑ i, nodeCountAtDepth t (same i)) = + ∑ i, (same i).nodeCount := by + rw [sum_comm] + apply sum_congr rfl + intro i hi + exact ihs i (hs i).2.2 (le_trans (Nat.le_of_lt (hs i).1) hd) + have hearlier : (∑ t ∈ range (D + 1), ∑ i, nodeCountAtDepth t (earlier i)) = + ∑ i, (earlier i).nodeCount := by + rw [sum_comm] + apply sum_congr rfl + intro i hi + exact ihe i (he i).2.2 (le_trans (he i).1 hd) + change (∑ t ∈ range (D + 1), ((if d = t then 1 else 0) + + (∑ i, nodeCountAtDepth t (same i)) + + (∑ i, nodeCountAtDepth t (earlier i)))) = + 1 + (∑ i, (same i).nodeCount) + ∑ i, (earlier i).nodeCount + rw [sum_add_distrib, sum_add_distrib, hroot, hsame, hearlier] + +/-- The actual layers partition the expansion. This lets weighted +initial-state charges be summed layer by layer without using the total +depth bound for every layer. -/ +theorem layerNodeCount_sum (a b : ℕ) (tree : DependencyExpansion) (h : Valid a b tree) : + (∑ j ∈ range (tree.depth + 1), layerNodeCount j tree) = tree.nodeCount := by + calc + (∑ j ∈ range (tree.depth + 1), layerNodeCount j tree) = + ∑ j ∈ range (tree.depth + 1), nodeCountAtDepth (tree.depth - j) tree := by + apply sum_congr rfl + intro j hj + exact ite_eq_left (Nat.le_of_lt_succ (mem_range.mp hj)) + _ = ∑ j ∈ range (tree.depth + 1), nodeCountAtDepth j tree := by + simpa only [Nat.add_sub_cancel] using + sum_range_reflect (fun j => nodeCountAtDepth j tree) (tree.depth + 1) + _ = tree.nodeCount := nodeCountAtDepth_sum a b tree.depth tree h le_rfl + +/-- Charge every actual node by a function of its remaining physical +depth, as needed for length-dependent initial-state evaluation. -/ +def depthWeightedCount (weight : ℕ → ℕ) : DependencyExpansion → ℕ + | .node d _ _ _ same earlier => weight d + + (∑ i, depthWeightedCount weight (same i)) + + ∑ i, depthWeightedCount weight (earlier i) + +theorem depthWeightedCount_eq_depth_sum (a b D : ℕ) (weight : ℕ → ℕ) + (tree : DependencyExpansion) (h : Valid a b tree) (hd : tree.depth ≤ D) : + (∑ t ∈ range (D + 1), nodeCountAtDepth t tree * weight t) = + depthWeightedCount weight tree := by + revert h hd + induction tree with + | node d k m n same earlier ihs ihe => + intro h hd + obtain ⟨hm, hn, hs, he⟩ := h + change d ≤ D at hd + have hroot : (∑ t ∈ range (D + 1), (if d = t then 1 else 0) * weight t) = weight d := by + simp [ite_mul, mem_range.mpr (Nat.lt_succ_of_le hd)] + have hsame : (∑ t ∈ range (D + 1), (∑ i, nodeCountAtDepth t (same i)) * weight t) = + ∑ i, depthWeightedCount weight (same i) := by + simp_rw [sum_mul] + rw [sum_comm] + apply sum_congr rfl + intro i hi + exact ihs i (hs i).2.2 (le_trans (Nat.le_of_lt (hs i).1) hd) + have hearlier : (∑ t ∈ range (D + 1), (∑ i, nodeCountAtDepth t (earlier i)) * weight t) = + ∑ i, depthWeightedCount weight (earlier i) := by + simp_rw [sum_mul] + rw [sum_comm] + apply sum_congr rfl + intro i hi + exact ihe i (he i).2.2 (le_trans (he i).1 hd) + change (∑ t ∈ range (D + 1), ((if d = t then 1 else 0) + + (∑ i, nodeCountAtDepth t (same i)) + + (∑ i, nodeCountAtDepth t (earlier i))) * weight t) = + weight d + (∑ i, depthWeightedCount weight (same i)) + + ∑ i, depthWeightedCount weight (earlier i) + simp_rw [add_mul, sum_add_distrib] + rw [hroot, hsame, hearlier] + +theorem depthWeightedCount_eq_layer_sum (a b : ℕ) (weight : ℕ → ℕ) + (tree : DependencyExpansion) (h : Valid a b tree) : + depthWeightedCount weight tree = + ∑ j ∈ range (tree.depth + 1), layerNodeCount j tree * weight (tree.depth - j) := by + symm + calc + (∑ j ∈ range (tree.depth + 1), layerNodeCount j tree * weight (tree.depth - j)) = + ∑ j ∈ range (tree.depth + 1), + nodeCountAtDepth (tree.depth - j) tree * weight (tree.depth - j) := by + apply sum_congr rfl + intro j hj + rw [layerNodeCount, ite_eq_left (Nat.le_of_lt_succ (mem_range.mp hj))] + _ = ∑ t ∈ range (tree.depth + 1), nodeCountAtDepth t tree * weight t := by + simpa only [Nat.add_sub_cancel] using + sum_range_reflect (fun t => nodeCountAtDepth t tree * weight t) (tree.depth + 1) + _ = depthWeightedCount weight tree := + depthWeightedCount_eq_depth_sum a b tree.depth weight tree h le_rfl + +/-- Unfold actual finite successor arrays. Local progress makes the +construction terminate even when earlier edges also descend physically. -/ +def build {ι : Type*} (d r m n : ι → ℕ) + (s : (x : ι) → Fin (m x) → ι) (e : (x : ι) → Fin (n x) → ι) + (hs : ∀ x i, d (s x i) < d x ∧ r (s x i) ≤ r x) + (he : ∀ x i, d (e x i) ≤ d x ∧ r (e x i) < r x) (root : ι) : DependencyExpansion := + .node (d root) (r root) (m root) (n root) + (fun i => build d r m n s e hs he (s root i)) + (fun i => build d r m n s e hs he (e root i)) +termination_by d root + r root +decreasing_by + · exact Nat.add_lt_add_of_lt_of_le (hs root i).1 (hs root i).2 + · exact Nat.add_lt_add_of_le_of_lt (he root i).1 (he root i).2 + +section Builder + +variable {ι : Type*} (d r m n : ι → ℕ) + (s : (x : ι) → Fin (m x) → ι) (e : (x : ι) → Fin (n x) → ι) + (hs : ∀ x i, d (s x i) < d x ∧ r (s x i) ≤ r x) + (he : ∀ x i, d (e x i) ≤ d x ∧ r (e x i) < r x) + +theorem build_depth (root : ι) : (build d r m n s e hs he root).depth = d root := by + rw [build] + rfl + +theorem build_rank (root : ι) : (build d r m n s e hs he root).rank = r root := by + rw [build] + rfl + +theorem build_valid (a b : ℕ) (hm : ∀ x, m x ≤ a) (hn : ∀ x, n x ≤ b) (root : ι) : + Valid a b (build d r m n s e hs he root) := by + have hall : ∀ fuel x, d x + r x = fuel → Valid a b (build d r m n s e hs he x) := by + intro fuel + induction fuel using Nat.strong_induction_on with + | h fuel ih => + intro x hx + rw [build] + refine ⟨hm x, hn x, ?_, ?_⟩ + · intro i + refine ⟨?_, ?_, ?_⟩ + · rw [build_depth] + exact (hs x i).1 + · rw [build_rank] + exact (hs x i).2 + · apply ih (d (s x i) + r (s x i)) _ (s x i) rfl + rw [← hx] + exact Nat.add_lt_add_of_lt_of_le (hs x i).1 (hs x i).2 + · intro i + refine ⟨?_, ?_, ?_⟩ + · rw [build_depth] + exact (he x i).1 + · rw [build_rank] + exact (he x i).2 + · apply ih (d (e x i) + r (e x i)) _ (e x i) rfl + rw [← hx] + exact Nat.add_lt_add_of_le_of_lt (he x i).1 (he x i).2 + exact hall (d root + r root) root rfl + +/-- A global node bound derived directly from actual successor arrays, +their two local cardinality bounds, and their local progress proofs. -/ +theorem build_nodeCount_le (a b : ℕ) (hm : ∀ x, m x ≤ a) (hn : ∀ x, n x ≤ b) (root : ι) : + (build d r m n s e hs he root).nodeCount ≤ dependencyPathBudget (d root) (r root) a b := by + simpa only [build_depth, build_rank] using + nodeCount_le_budget a b _ (build_valid d r m n s e hs he a b hm hn root) + +theorem build_layerNodeCount_le (a b j K : ℕ) + (hm : ∀ x, m x ≤ a) (hn : ∀ x, n x ≤ b) (root : ι) (hk : r root ≤ K) : + layerNodeCount j (build d r m n s e hs he root) ≤ dependencyPathBudget j K a b := by + apply layerNodeCount_le_budget a b j K _ (build_valid d r m n s e hs he a b hm hn root) + simpa only [build_rank] using hk + +end Builder + +end DependencyExpansion +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/DependencyPathEnvelope.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/DependencyPathEnvelope.lean new file mode 100644 index 0000000000000000000000000000000000000000..a185a5a2bcc5edb5318f2485ba59ece0c4117d39 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/DependencyPathEnvelope.lean @@ -0,0 +1,101 @@ +import OAI.Combinatorics.EditApproximation.Geometry.SubexponentialTransfer +import OAI.Combinatorics.EditApproximation.Geometry.Work + +namespace OAI + +/-! An explicit subpolynomial envelope for the finite dependency-path sum. +The connection between this sum and an execution is a separate obligation. -/ + +namespace EditApproximation + +open Filter +open scoped Topology + +theorem nat_pow_eq_exp_log (a n : ℕ) (ha : 0 < a) : + (a : ℝ) ^ n = Real.exp ((n : ℝ) * Real.log a) := by + rw [Real.exp_nat_mul, Real.exp_log (by exact_mod_cast ha)] + +theorem dependencyPathBudget_exp_bound (M ell H q C₁ C₂ j K : ℕ) + (hM : 1 ≤ M) (hell : 1 ≤ ell) (hH : 1 ≤ H) : + (dependencyPathBudget j K (M * ell ^ C₁) (H ^ (C₂ * q)) : ℝ) ≤ + (M : ℝ) ^ j * Real.exp ((1 + Real.log 2) * (j + K : ℝ) + + C₁ * j * Real.log (ell : ℝ) + C₂ * q * K * Real.log (H : ℝ)) := by + have hsame : 1 ≤ M * ell ^ C₁ := by + have hp : 1 ≤ ell ^ C₁ := one_le_pow₀ hell + nlinarith + have hearlier : 1 ≤ H ^ (C₂ * q) := one_le_pow₀ hH + have hnat := dependencyPathBudget_le j K (M * ell ^ C₁) (H ^ (C₂ * q)) hsame hearlier + have hcast : (dependencyPathBudget j K (M * ell ^ C₁) (H ^ (C₂ * q)) : ℝ) ≤ + (j + 1 : ℝ) * (K + 1 : ℝ) * (2 : ℝ) ^ (j + K) * + ((M : ℝ) * (ell : ℝ) ^ C₁) ^ j * ((H : ℝ) ^ (C₂ * q)) ^ K := by + exact_mod_cast hnat + have hj : (j + 1 : ℝ) ≤ Real.exp (j : ℝ) := Real.add_one_le_exp _ + have hK : (K + 1 : ℝ) ≤ Real.exp (K : ℝ) := Real.add_one_le_exp _ + have hproduct : (j + 1 : ℝ) * (K + 1 : ℝ) ≤ Real.exp (j : ℝ) * Real.exp (K : ℝ) := + mul_le_mul hj hK (by positivity) (Real.exp_nonneg _) + calc + _ ≤ (j + 1 : ℝ) * (K + 1 : ℝ) * (2 : ℝ) ^ (j + K) * + ((M : ℝ) * (ell : ℝ) ^ C₁) ^ j * ((H : ℝ) ^ (C₂ * q)) ^ K := hcast + _ ≤ (Real.exp (j : ℝ) * Real.exp (K : ℝ)) * (2 : ℝ) ^ (j + K) * + ((M : ℝ) * (ell : ℝ) ^ C₁) ^ j * ((H : ℝ) ^ (C₂ * q)) ^ K := by + apply mul_le_mul_of_nonneg_right _ (by positivity) + apply mul_le_mul_of_nonneg_right _ (by positivity) + exact mul_le_mul_of_nonneg_right hproduct (by positivity) + _ = (M : ℝ) ^ j * Real.exp ((1 + Real.log 2) * (j + K : ℝ) + + C₁ * j * Real.log (ell : ℝ) + C₂ * q * K * Real.log (H : ℝ)) := by + have htwo : (2 : ℝ) ^ (j + K) = Real.exp (((j + K : ℕ) : ℝ) * Real.log 2) := by + simpa only [Nat.cast_ofNat] using nat_pow_eq_exp_log 2 (j + K) (by decide) + rw [mul_pow, ← pow_mul, ← pow_mul, htwo, + nat_pow_eq_exp_log ell (C₁ * j) (by omega), + nat_pow_eq_exp_log H (C₂ * q * K) (by omega)] + calc + _ = (M : ℝ) ^ j * (Real.exp (j : ℝ) * Real.exp (K : ℝ) * + Real.exp (((j + K : ℕ) : ℝ) * Real.log 2) * + Real.exp (((C₁ * j : ℕ) : ℝ) * Real.log ell) * + Real.exp (((C₂ * q * K : ℕ) : ℝ) * Real.log H)) := by ring + _ = (M : ℝ) ^ j * Real.exp ((j : ℝ) + K + + ((j + K : ℕ) : ℝ) * Real.log 2 + ((C₁ * j : ℕ) : ℝ) * Real.log ell + + ((C₂ * q * K : ℕ) : ℝ) * Real.log H) := by simp only [← Real.exp_add] + _ = _ := by congr 2; push_cast; ring + +theorem computed_dependency_path_envelope (N C₁ C₂ j : ℕ) + (hj : j ≤ computedMaxTreeDepth N) : + (dependencyPathBudget j (computedDependencyIndexCount N) + ((integerParameters N).M * inputSmallLog N ^ C₁) + (inputHeight N ^ (C₂ * (coarseExponent (inputSmallLog N) + 1))) : ℝ) ≤ + ((integerParameters N).M : ℝ) ^ j * + Real.exp (computedDependencyOverheadExponent C₁ C₂ N) := by + have hM : 1 ≤ (integerParameters N).M := Nat.one_le_two_pow + have hell : 1 ≤ inputSmallLog N := Nat.one_le_two_pow + have hH : 1 ≤ inputHeight N := Nat.one_le_two_pow + have h := dependencyPathBudget_exp_bound (integerParameters N).M (inputSmallLog N) + (inputHeight N) (coarseExponent (inputSmallLog N) + 1) C₁ C₂ j + (computedDependencyIndexCount N) hM hell hH + apply h.trans + apply mul_le_mul_of_nonneg_left _ (by positivity) + apply Real.exp_le_exp.mpr + unfold computedDependencyOverheadExponent + have hjR : (j : ℝ) ≤ computedMaxTreeDepth N := by exact_mod_cast hj + have hlog : 0 ≤ Real.log (inputSmallLog N : ℝ) := Real.log_nonneg (by exact_mod_cast hell) + have hlogtwo : 0 ≤ Real.log 2 := Real.log_nonneg (by norm_num) + push_cast + nlinarith [mul_le_mul_of_nonneg_right hjR (mul_nonneg (Nat.cast_nonneg C₁) hlog)] + +/-- The entire displayed path bound is `M^j` times a subpolynomial factor, +uniformly at all physical depths. -/ +theorem computed_dependency_path_subpolynomial (C₁ C₂ : ℕ) (epsilon : ℝ) + (hepsilon : 0 < epsilon) : + ∀ᶠ N in atTop, ∀ j ≤ computedMaxTreeDepth N, + (dependencyPathBudget j (computedDependencyIndexCount N) + ((integerParameters N).M * inputSmallLog N ^ C₁) + (inputHeight N ^ (C₂ * (coarseExponent (inputSmallLog N) + 1))) : ℝ) ≤ + ((integerParameters N).M : ℝ) ^ j * (N + 2 : ℝ) ^ epsilon := by + filter_upwards [subexponential_height_to_input _ + (computedDependencyOverheadExponent_tendsto C₁ C₂) epsilon hepsilon] with N hN + intro j hj + exact (computed_dependency_path_envelope N C₁ C₂ j hj).trans + (mul_le_mul_of_nonneg_left hN (by positivity)) + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/DependencyWeightedWork.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/DependencyWeightedWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..ebc1a99944ae61dc5dccbb8083253a7f55994b0b --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/DependencyWeightedWork.lean @@ -0,0 +1,81 @@ +import OAI.Combinatorics.EditApproximation.Geometry.DependencyExpansion +import OAI.Combinatorics.EditApproximation.Geometry.DependencyPathEnvelope +import OAI.Combinatorics.EditApproximation.Geometry.WeightedTreeWork + +namespace OAI + +/-! Width-sensitive work summed over an actual finite dependency expansion. +The bound uses its per-layer counts, including earlier edges that descend. -/ + +namespace EditApproximation + +open Finset Filter + +namespace DependencyExpansion + +def widthWork (M n : ℕ) (tree : DependencyExpansion) : ℕ := + tree.depthWeightedCount (fun d => 1 + n ⌈/⌉ M ^ (tree.depth - d)) + +theorem widthWork_le (M n a b K : ℕ) (hM : 2 ≤ M) + (tree : DependencyExpansion) (hvalid : tree.Valid a b) + (hdepth : tree.depth = intervalTreeDepth M n) (hrank : tree.rank ≤ K) + (overhead : ℝ) (hoverhead : 0 ≤ overhead) + (hpath : ∀ j ≤ intervalTreeDepth M n, + (dependencyPathBudget j K a b : ℝ) ≤ (M : ℝ) ^ j * overhead) : + (tree.widthWork M n : ℝ) ≤ + (((intervalTreeDepth M n + 1) * n + 4 * M * max 1 n : ℕ) : ℝ) * overhead := by + have hpartition : tree.widthWork M n = + ∑ j ∈ range (intervalTreeDepth M n + 1), + tree.layerNodeCount j * (1 + n ⌈/⌉ M ^ j) := by + unfold widthWork + rw [depthWeightedCount_eq_layer_sum a b _ tree hvalid] + rw [hdepth] + apply sum_congr rfl + intro j hj + have hsub : intervalTreeDepth M n - (intervalTreeDepth M n - j) = j := by + have := mem_range.mp hj + omega + rw [hsub] + rw [hpartition] + simp only [Nat.cast_sum, Nat.cast_mul, Nat.cast_add, Nat.cast_one] + calc + _ ≤ ∑ j ∈ range (intervalTreeDepth M n + 1), + ((M : ℝ) ^ j * overhead) * (1 + (n ⌈/⌉ M ^ j : ℕ)) := by + apply sum_le_sum + intro j hj + apply mul_le_mul_of_nonneg_right _ (by positivity) + exact (show (tree.layerNodeCount j : ℝ) ≤ dependencyPathBudget j K a b by + exact_mod_cast layerNodeCount_le_budget a b j K tree hvalid hrank).trans + (hpath j (Nat.le_of_lt_succ (mem_range.mp hj))) + _ = (∑ j ∈ range (intervalTreeDepth M n + 1), + (M : ℝ) ^ j * (1 + (n ⌈/⌉ M ^ j : ℕ))) * overhead := by + rw [sum_mul] + apply sum_congr rfl + intro j _ + ring + _ ≤ _ := by + apply mul_le_mul_of_nonneg_right _ hoverhead + exact_mod_cast interval_tree_width_work M n hM + +theorem computed_widthWork_subpolynomial (C₁ C₂ : ℕ) (epsilon : ℝ) (hepsilon : 0 < epsilon) : + ∀ᶠ N in atTop, ∀ n ≤ N, ∀ tree : DependencyExpansion, + tree.Valid ((integerParameters N).M * inputSmallLog N ^ C₁) + (inputHeight N ^ (C₂ * (coarseExponent (inputSmallLog N) + 1))) → + tree.depth = intervalTreeDepth (integerParameters N).M n → + tree.rank ≤ computedDependencyIndexCount N → + (tree.widthWork (integerParameters N).M n : ℝ) ≤ + (((intervalTreeDepth (integerParameters N).M n + 1) * n + + 4 * (integerParameters N).M * max 1 n : ℕ) : ℝ) * (N + 2 : ℝ) ^ epsilon := by + filter_upwards [computed_dependency_path_subpolynomial C₁ C₂ epsilon hepsilon, + inputSmallLog_tendsto.eventually (eventually_ge_atTop 200), eventually_ge_atTop 1] with N hp hell hN + intro n hn tree hv hd hk + apply widthWork_le (integerParameters N).M n _ _ _ + (computed_branching_bounds N (by omega) hell).1 tree hv hd hk _ (by positivity) + intro j hj + exact hp j (hj.trans (intervalTreeDepth_le_computedMax N n hn)) + +end DependencyExpansion + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/DomainCounts.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/DomainCounts.lean new file mode 100644 index 0000000000000000000000000000000000000000..ec591a9f28010d4d2d5962fc229068b5665e3cf6 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/DomainCounts.lean @@ -0,0 +1,75 @@ +import OAI.Combinatorics.EditApproximation.Geometry.TreeParameters +import OAI.Combinatorics.EditApproximation.Geometry.StateGeometry + +namespace OAI + +/-! +# Counting the actual labeled state domain + +The count includes repeated interval labels at different physical nodes. +It bounds simultaneous seed/amplification events without identifying those +nodes or replacing the finite target-state loops by an oracle. +-/ + +namespace EditApproximation + +open Finset + +theorem list_flatMap_length_le {α β : Type*} (entries : List α) (f : α → List β) + (K : ℕ) (h : ∀ a ∈ entries, (f a).length ≤ K) : + (entries.flatMap f).length ≤ entries.length * K := by + induction entries with + | nil => simp + | cons a rest ih => + simp only [List.flatMap_cons, List.length_append, List.length_cons] + have ha := h a (by simp) + have hrest := ih (fun b hb => h b (by simp [hb])) + nlinarith + +theorem targetStates_length_le (n : ℕ) : (targetStates n).length ≤ (n + 1) ^ 2 := by + unfold targetStates + have h := list_flatMap_length_le (List.range (n + 1)) + (fun lo => (List.range (n + 1)).filterMap fun hi => makeTargetState n lo hi) + (n + 1) (by + intro lo hlo + simpa only [List.length_range] using + List.length_filterMap_le (fun hi => makeTargetState n lo hi) (List.range (n + 1))) + simpa only [List.length_range, pow_two] using h + +def labeledStateCount (M nx ny : ℕ) : ℕ := + (∑ d ∈ range (intervalTreeDepth M nx + 1), Fintype.card (TreeLayer M d)) * + (targetStates ny).length + +theorem labeledStateCount_le (M nx ny : ℕ) (hM : 2 ≤ M) : + labeledStateCount M nx ny ≤ 2 * M * max 1 nx * (ny + 1) ^ 2 := by + exact Nat.mul_le_mul (intervalTreeDepth_node_count M nx hM) (targetStates_length_le ny) + +theorem computed_labeledStateCount_le (N nx ny : ℕ) (hN : 0 < N) + (hnx : nx ≤ N) (hny : ny ≤ N) (hell : 200 ≤ inputSmallLog N) : + labeledStateCount (integerParameters N).M nx ny ≤ 2 ^ (5 * inputHeight N) := by + have hbranch := computed_branching_bounds N hN hell + have hM : (integerParameters N).M ≤ 2 ^ inputHeight N := + pow_le_pow_right₀ (by decide : 1 ≤ (2 : ℕ)) hbranch.2.2 + have hx : max 1 nx ≤ 2 ^ inputHeight N := by + apply max_le Nat.one_le_two_pow + exact hnx.trans ((Nat.le_add_right N 2).trans (inputHeight_covers_length N)) + have hy : ny + 1 ≤ 2 ^ inputHeight N := + (by omega : ny + 1 ≤ N + 2).trans (inputHeight_covers_length N) + have hproduct : 2 * (integerParameters N).M * max 1 nx * (ny + 1) ^ 2 ≤ + 2 * 2 ^ inputHeight N * 2 ^ inputHeight N * (2 ^ inputHeight N) ^ 2 := by + gcongr + have hidentity : 2 * 2 ^ inputHeight N * 2 ^ inputHeight N * (2 ^ inputHeight N) ^ 2 = + 2 ^ (4 * inputHeight N + 1) := by + rw [← pow_mul] + conv_lhs => lhs; lhs; lhs; change 2 ^ 1 + rw [← pow_add, ← pow_add, ← pow_add] + congr 1 + omega + have hH : 1 ≤ inputHeight N := Nat.one_le_two_pow + exact (labeledStateCount_le _ _ _ hbranch.1).trans + (hproduct.trans (hidentity.le.trans + (pow_le_pow_right₀ (by decide : 1 ≤ (2 : ℕ)) (by omega)))) + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/DomainExponential.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/DomainExponential.lean new file mode 100644 index 0000000000000000000000000000000000000000..3f9648488abe3b84ee3192c0e148861024c49707 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/DomainExponential.lean @@ -0,0 +1,26 @@ +import OAI.Combinatorics.EditApproximation.Geometry.DomainCounts + +namespace OAI + +/-! The exponential form of the actual domain bound used in amplification. -/ + +namespace EditApproximation + +theorem computed_labeledStateCount_exp (N nx ny : ℕ) (hN : 0 < N) + (hnx : nx ≤ N) (hny : ny ≤ N) (hell : 200 ≤ inputSmallLog N) : + (labeledStateCount (integerParameters N).M nx ny : ℝ) ≤ + Real.exp (10 * inputHeight N) := by + have hcount : (labeledStateCount (integerParameters N).M nx ny : ℝ) ≤ + (2 : ℝ) ^ (5 * inputHeight N) := by + exact_mod_cast computed_labeledStateCount_le N nx ny hN hnx hny hell + have htwo : (2 : ℝ) ≤ Real.exp 1 := by + simpa only [one_add_one_eq_two] using Real.add_one_le_exp (1 : ℝ) + have hpower := pow_le_pow_left₀ (by norm_num : (0 : ℝ) ≤ 2) htwo (5 * inputHeight N) + rw [← Real.exp_nat_mul, mul_one] at hpower + apply hcount.trans (hpower.trans (Real.exp_le_exp.mpr ?_)) + simp only [Nat.cast_mul, Nat.cast_ofNat] + nlinarith [show (0 : ℝ) ≤ inputHeight N from Nat.cast_nonneg _] + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/DyadicQueryWindow.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/DyadicQueryWindow.lean new file mode 100644 index 0000000000000000000000000000000000000000..679803ffeb0ba0e5842c628b09ab64c83f920a04 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/DyadicQueryWindow.lean @@ -0,0 +1,60 @@ +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalOnlineLocality +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! The query scale window has length controlled by the refinement +factor, independently of the number of dyadic scales below N. -/ + +namespace EditApproximation + +open Finset + + + +theorem dyadicQueryWindow_length_le (N C : ℕ) (w a F : ℚ) + (ha : 1 ≤ a) (hF : 1 ≤ F) + (hbudget : 128 * a * F ≤ (2 : ℚ) ^ C) : + (dyadicQueryWindow N w a F).length ≤ C + 1 := by + let keep : ℕ → Bool := fun e => decide (w / (16 * F) ≤ (2 ^ e : ℕ) ∧ + ((2 ^ e : ℕ) : ℚ) ≤ 8 * a * w) + let indices := ((List.range (Nat.log 2 N + 1)).filter keep).toFinset + have hlength : (dyadicQueryWindow N w a F).length = indices.card := by + simp only [dyadicQueryWindow, dyadicScales, List.filter_map, List.length_map] + exact (List.toFinset_card_of_nodup + ((show (List.range (Nat.log 2 N + 1)).Nodup from List.nodup_range).filter keep)).symm + rw [hlength] + by_cases hnonempty : indices.Nonempty + · let first := indices.min' hnonempty + have hfirst : first ∈ indices := Finset.min'_mem _ _ + have hfirstKeep : w / (16 * F) ≤ (2 ^ first : ℕ) ∧ ((2 ^ first : ℕ) : ℚ) ≤ 8 * a * w := + of_decide_eq_true (List.mem_filter.mp (List.mem_toFinset.mp hfirst)).2 + have hFpos : 0 < F := lt_of_lt_of_le zero_lt_one hF + have hwfirst : w ≤ 16 * F * (2 ^ first : ℕ) := by + nlinarith only [(div_le_iff₀ (by positivity : (0 : ℚ) < 16 * F)).mp hfirstKeep.1] + have hsub : indices ⊆ Finset.Icc first (first + C) := by + intro e he + have hkeep : w / (16 * F) ≤ (2 ^ e : ℕ) ∧ ((2 ^ e : ℕ) : ℚ) ≤ 8 * a * w := + of_decide_eq_true (List.mem_filter.mp (List.mem_toFinset.mp he)).2 + have hmul := mul_le_mul_of_nonneg_left hwfirst (show 0 ≤ 8 * a by positivity) + have hpower := mul_le_mul_of_nonneg_right hbudget (Nat.cast_nonneg (α := ℚ) (2 ^ first)) + have hbound : ((2 ^ e : ℕ) : ℚ) ≤ (2 : ℚ) ^ C * (2 ^ first : ℕ) := by + nlinarith only [hkeep.2, hmul, hpower] + have hboundN : 2 ^ e ≤ 2 ^ (first + C) := by + have heq : (2 : ℚ) ^ C * (2 ^ first : ℕ) = ((2 ^ (first + C) : ℕ) : ℚ) := by + push_cast + rw [pow_add] + ring + rw [heq] at hbound + exact_mod_cast hbound + exact Finset.mem_Icc.mpr ⟨Finset.min'_le _ _ he, + (Nat.pow_le_pow_iff_right (by decide : 1 < (2 : ℕ))).mp hboundN⟩ + have hcard := Finset.card_le_card hsub + have hinterval : (Finset.Icc first (first + C)).card = C + 1 := by rw [Nat.card_Icc]; omega + rwa [hinterval] at hcard + · simpa only [Finset.not_nonempty_iff_eq_empty.mp hnonempty, Finset.card_empty] using Nat.zero_le (C + 1) + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/EarlierInputBudget.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/EarlierInputBudget.lean new file mode 100644 index 0000000000000000000000000000000000000000..6f7674fb2871c87ea07f584e5f4f737cc0805eaf --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/EarlierInputBudget.lean @@ -0,0 +1,91 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryEarlierInputs +import OAI.Combinatorics.EditApproximation.Refinement.ComputedCurrentQueryBudget + +namespace OAI + +/-! The explicit wide-history cover fits the polynomial earlier-input +budget used in the dependency-path count. -/ + +namespace EditApproximation + +def localEarlierBudget (window cells M P F history : ℕ) : ℕ := + window * ((64 * F * P + 2) ^ 2 + cells * (P + 1) ^ 2 + 1) * + M * history * (40 * P + 2) ^ 2 + +theorem queryEarlierInputCover_le_budget {nx ny M : ℕ} (parent : TargetInterval nx) + (N P F exponent history window cells : ℕ) (a : ℚ) + (initial : TargetInterval ny → ℚ) (q : TargetInterval ny) + (hP : ∃ e : ℕ, P = 2 ^ e) (hF : 1 ≤ F) (hw : 0 ≤ initial q) + (hwindow : (dyadicQueryWindow N (initial q) a F).length ≤ window) + (hcells : ((32 * F + 2) * 2 ^ exponent + 2) ^ 2 ≤ cells) : + (queryEarlierInputCover (M := M) parent N P F exponent history a initial q).card ≤ + localEarlierBudget window cells M P F history := by + have hmembers : (64 * F * P + 2) ^ 2 + + ((32 * F + 2) * 2 ^ exponent + 2) ^ 2 * (P + 1) ^ 2 + 1 ≤ + (64 * F * P + 2) ^ 2 + cells * (P + 1) ^ 2 + 1 := + Nat.add_le_add_right (Nat.add_le_add_left (Nat.mul_le_mul_right _ hcells) _) _ + exact (queryEarlierInputCover_card parent N P F exponent history a initial q hP hF hw).trans + (Nat.mul_le_mul_right _ (Nat.mul_le_mul_right history + (Nat.mul_le_mul_right M (Nat.mul_le_mul hwindow hmembers)))) + +theorem localEarlierBudget_poly (H p window cells M P F history : ℕ) + (hH : 64 ≤ H) (hPpos : 1 ≤ P) (hP : P ≤ H ^ (p + 20)) + (hwindow : window ≤ H ^ 3) (hcells : cells ≤ H ^ 84) + (hM : M ≤ H) (hF : F ≤ H) (hhistory : history ≤ H ^ 2) : + localEarlierBudget window cells M P F history ≤ H ^ (256 * (p + 1)) := by + have hHone : 1 ≤ H := by omega + have h64 : 64 * F ≤ H ^ 2 := by + calc + _ ≤ H * H := Nat.mul_le_mul hH hF + _ = H ^ 2 := by ring + have hfirstBase : 64 * F * P + 2 ≤ H ^ 3 * P := by + have hm := Nat.mul_le_mul_right P h64 + have hp : 2 ≤ H ^ 2 * P := by + have hlarge : 2 ≤ H ^ 2 := (by norm_num : 2 ≤ (64 : ℕ) ^ 2).trans + (Nat.pow_le_pow_left hH 2) + exact hlarge.trans (Nat.le_mul_of_pos_right _ hPpos) + have hh : 2 * H ^ 2 ≤ H ^ 3 := by + calc + _ ≤ H * H ^ 2 := Nat.mul_le_mul_right _ (by omega : 2 ≤ H) + _ = H ^ 3 := by ring + nlinarith only [hm, hp, Nat.mul_le_mul_right P hh] + have hfirst : (64 * F * P + 2) ^ 2 ≤ H ^ 86 * P ^ 2 := by + calc + _ ≤ (H ^ 3 * P) ^ 2 := Nat.pow_le_pow_left hfirstBase 2 + _ = H ^ 6 * P ^ 2 := by ring + _ ≤ _ := Nat.mul_le_mul_right _ (pow_le_pow_right₀ hHone (by omega : 6 ≤ 86)) + have hPadd : P + 1 ≤ H * P := by nlinarith + have hsecond : cells * (P + 1) ^ 2 ≤ H ^ 86 * P ^ 2 := by + calc + _ ≤ H ^ 84 * (H * P) ^ 2 := Nat.mul_le_mul hcells (Nat.pow_le_pow_left hPadd 2) + _ = _ := by ring + have hone : 1 ≤ H ^ 86 * P ^ 2 := by + simpa only [Nat.one_mul] using Nat.mul_le_mul (one_le_pow₀ hHone (n := 86)) (one_le_pow₀ hPpos (n := 2)) + have hsum : (64 * F * P + 2) ^ 2 + cells * (P + 1) ^ 2 + 1 ≤ H ^ 88 * P ^ 2 := by + have hh : 3 * H ^ 86 ≤ H ^ 88 := by + calc + _ ≤ H ^ 2 * H ^ 86 := Nat.mul_le_mul_right _ + ((by norm_num : 3 ≤ (64 : ℕ) ^ 2).trans (Nat.pow_le_pow_left hH 2)) + _ = _ := by ring + nlinarith only [hfirst, hsecond, hone, Nat.mul_le_mul_right (P ^ 2) hh] + have hwideBase : 40 * P + 2 ≤ H ^ 2 * P := by + have hh : 42 ≤ H ^ 2 := (by norm_num : 42 ≤ (64 : ℕ) ^ 2).trans + (Nat.pow_le_pow_left hH 2) + nlinarith only [Nat.mul_le_mul_right P hh, hPpos] + have hwide : (40 * P + 2) ^ 2 ≤ H ^ 4 * P ^ 2 := by + calc + _ ≤ (H ^ 2 * P) ^ 2 := Nat.pow_le_pow_left hwideBase 2 + _ = _ := by ring + calc + localEarlierBudget window cells M P F history ≤ + H ^ 3 * (H ^ 88 * P ^ 2) * H * H ^ 2 * (H ^ 4 * P ^ 2) := by + exact Nat.mul_le_mul (Nat.mul_le_mul (Nat.mul_le_mul + (Nat.mul_le_mul hwindow hsum) hM) hhistory) hwide + _ = H ^ 98 * P ^ 4 := by ring + _ ≤ H ^ 98 * (H ^ (p + 20)) ^ 4 := Nat.mul_le_mul_left _ (Nat.pow_le_pow_left hP 4) + _ = H ^ (98 + (p + 20) * 4) := by rw [← pow_mul, ← pow_add] + _ ≤ H ^ (256 * (p + 1)) := pow_le_pow_right₀ hHone (by omega) + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/EarlierValueDependence.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/EarlierValueDependence.lean new file mode 100644 index 0000000000000000000000000000000000000000..0c35dbafa3337424c8db93a169f324338414b973 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/EarlierValueDependence.lean @@ -0,0 +1,56 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryEarlierInputs +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalRationalWarmup + +namespace OAI + +/-! Wide Bellman scoring reads only the earlier child coordinates in the +explicit finite cover. Enumeration can reuse their gathered values. -/ + +namespace EditApproximation + +open Finset + +theorem wideActionValues_congr_earlier {nx ny M : ℕ} + (parent : TargetInterval nx) (P history time : ℕ) + (small large : List (ℕ × TargetInterval ny)) (hsub : ∀ br ∈ small, br ∈ large) + (left right : Fin M → ℕ → TargetInterval ny → ℚ) (htime : time < history) + (hvalues : ∀ input ∈ wideEarlierInputCover parent P history large, + left input.1 input.2.1 input.2.2 = right input.1 input.2.1 input.2.2) + (distance : TargetInterval ny → TargetInterval ny → ℚ) (L : ℚ) (q : TargetInterval ny) : + (rationalActualWideActions parent small P).map + (rationalActionValue distance L (fun input => left input.1 time input.2) q) = + (rationalActualWideActions parent small P).map + (rationalActionValue distance L (fun input => right input.1 time input.2) q) := by + apply List.map_congr_left + intro action ha + obtain ⟨br, hbr, ha⟩ := List.mem_flatMap.mp ha + obtain ⟨states, hs, rfl⟩ := List.mem_map.mp ha + unfold rationalActionValue + dsimp only + congr 1 + apply Finset.sum_congr rfl + intro i _ + exact hvalues (i, time, states i) + (wideEarlierInputCover_mem parent P history large br.1 br.2 + (hsub br hbr) time htime states hs i) + +theorem localBellman_congr_earlier {nx ny M : ℕ} + (parent : TargetInterval nx) (N P F exponent history time : ℕ) (a : ℚ) + (initial : TargetInterval ny → ℚ) (q : TargetInterval ny) + (left right : Fin M → ℕ → TargetInterval ny → ℚ) (htime : time < history) + (hvalues : ∀ input ∈ queryEarlierInputCover parent N P F exponent history a initial q, + left input.1 input.2.1 input.2.2 = right input.1 input.2.1 input.2.2) (L : ℚ) : + rationalBellman initial (fun q r => targetEndpointDistance q r) L + (rationalActualWideActions parent (localRefinementRepresentatives N P F a initial q) P) + (fun input => left input.1 time input.2) q = + rationalBellman initial (fun q r => targetEndpointDistance q r) L + (rationalActualWideActions parent (localRefinementRepresentatives N P F a initial q) P) + (fun input => right input.1 time input.2) q := by + unfold rationalBellman + rw [wideActionValues_congr_earlier parent P history time _ _ + (queryEarlierRepresentatives_local N P F exponent a initial q) + left right htime hvalues] + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/FirstCrossing.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/FirstCrossing.lean new file mode 100644 index 0000000000000000000000000000000000000000..c52d3be2a962937353aca05462ae0e98424e006c --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/FirstCrossing.lean @@ -0,0 +1,113 @@ +import OAI.Combinatorics.EditApproximation.Geometry.Cones +import OAI.Combinatorics.EditApproximation.Geometry.BandRegret + +namespace OAI + +/-! +# The actual first crossing of a finite action band + +The crossing index is computed from the fixed child tables for analysis. +It is independent of parent sampling. The lemmas separate the prefixPayoff, +the single crossing, and the nonpositive later clipped regrets. +-/ + +namespace EditApproximation + +open Finset + +noncomputable def firstCrossing {α : Type*} (band : Finset α) + (S : ℕ) (actionCost : ℕ → α → ℝ) (c : ℝ) : ℕ := + if h : ∃ t, t < S ∧ ∃ action ∈ band, actionCost t action < c then Nat.find h else S + +theorem firstCrossing_le {α : Type*} (band : Finset α) + (S : ℕ) (actionCost : ℕ → α → ℝ) (c : ℝ) : + firstCrossing band S actionCost c ≤ S := by + unfold firstCrossing + split_ifs with h + · exact (Nat.find_spec h).1.le + · rfl + +theorem before_firstCrossing {α : Type*} (band : Finset α) + (S : ℕ) (actionCost : ℕ → α → ℝ) (c : ℝ) + {t : ℕ} (ht : t < firstCrossing band S actionCost c) + {action : α} (ha : action ∈ band) : c ≤ actionCost t action := by + by_contra hnot + have htS : t < S := ht.trans_le (firstCrossing_le band S actionCost c) + have hex : ∃ t, t < S ∧ ∃ action ∈ band, actionCost t action < c := + ⟨t, htS, action, ha, lt_of_not_ge hnot⟩ + have hfind : firstCrossing band S actionCost c ≤ t := by + rw [firstCrossing, dite_eq_left hex] + exact Nat.find_min' hex ⟨htS, action, ha, lt_of_not_ge hnot⟩ + omega + +theorem at_firstCrossing {α : Type*} (band : Finset α) + (S : ℕ) (actionCost : ℕ → α → ℝ) (c : ℝ) + (ht : firstCrossing band S actionCost c < S) : + ∃ action ∈ band, actionCost (firstCrossing band S actionCost c) action < c := by + by_cases h : ∃ t, t < S ∧ ∃ action ∈ band, actionCost t action < c + · simpa only [firstCrossing, dite_eq_left h] using (Nat.find_spec h).2 + · have heq : firstCrossing band S actionCost c = S := by + rw [firstCrossing, dite_eq_right h] + omega + +/-- At every later time, the previous-index Bellman option uses the +same crossing action. Child-table monotonicity keeps its cost below `c`. -/ +theorem after_firstCrossing_parent {α : Type*} (band : Finset α) + (S : ℕ) (actionCost : ℕ → α → ℝ) (c : ℝ) (parent : ℕ → ℝ) + (hmono : ∀ action ∈ band, Antitone (fun t => actionCost t action)) + (hbellman : ∀ t < S, ∀ action ∈ band, parent (t + 1) ≤ actionCost t action) + {t : ℕ} (hafter : firstCrossing band S actionCost c < t) (ht : t < S) : + max c (parent t) = c := by + obtain ⟨action, ha, hcross⟩ := at_firstCrossing band S actionCost c + (hafter.trans ht) + have hpred : firstCrossing band S actionCost c ≤ t - 1 := by omega + have hcost := (hmono action ha hpred).trans_lt hcross + have hparent := hbellman (t - 1) (by omega) action ha + have hindex : t - 1 + 1 = t := by omega + rw [hindex] at hparent + exact max_eq_left (hparent.trans hcost.le) + +/-- A finite first-crossing partition charges the crossing only once. +All failure indicators may be correlated with the sampled actions. -/ +theorem firstCrossing_sum_bound (S crossing : ℕ) (regret prefixPayoff failure : ℕ → ℝ) + (crossingCharge failureCharge : ℝ) (hcrossing : crossing ≤ S) + (hcharge : 0 ≤ crossingCharge) (hfailureCharge : 0 ≤ failureCharge) + (hfailure : ∀ t < S, 0 ≤ failure t) + (hprefixPayoff : ∀ t < crossing, regret t ≤ prefixPayoff t + failureCharge * failure t) + (hcross : crossing < S → regret crossing ≤ crossingCharge + failureCharge * failure crossing) + (hafter : ∀ t < S, crossing < t → regret t ≤ 0) : + (∑ t ∈ range S, regret t) ≤ + (∑ t ∈ range crossing, prefixPayoff t) + crossingCharge + + failureCharge * ∑ t ∈ range S, failure t := by + have hpoint (t : ℕ) (ht : t ∈ range S) : + regret t ≤ (if t < crossing then prefixPayoff t else 0) + + (if t = crossing then crossingCharge else 0) + failureCharge * failure t := by + have htS := mem_range.mp ht + by_cases hbefore : t < crossing + · simp only [hbefore, ite_true, show t ≠ crossing by omega, ite_false, add_zero] + exact hprefixPayoff t hbefore + · by_cases heq : t = crossing + · subst t + simpa only [lt_self_iff_false, ite_false, ite_true, zero_add] using hcross htS + · simp only [hbefore, ite_false, heq, zero_add] + exact (hafter t htS (by omega)).trans (mul_nonneg hfailureCharge (hfailure t htS)) + have hsum := sum_le_sum hpoint + have hpre : (∑ t ∈ range S, if t < crossing then prefixPayoff t else 0) = + ∑ t ∈ range crossing, prefixPayoff t := by + rw [← sum_filter] + congr 1 + ext t + simp only [mem_filter, mem_range] + omega + have hcrossSum : (∑ t ∈ range S, if t = crossing then crossingCharge else 0) ≤ crossingCharge := by + rw [sum_ite_eq'] + split_ifs + · rfl + · exact hcharge + simp only [sum_add_distrib, ← mul_sum] at hsum + rw [hpre] at hsum + linarith + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/GatheredInputs.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/GatheredInputs.lean new file mode 100644 index 0000000000000000000000000000000000000000..62025bf12c8301cd192ba153f8b4b1517c901fa9 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/GatheredInputs.lean @@ -0,0 +1,77 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryMemo + +namespace OAI + +/-! One local calculation gathers its distinct recursive inputs once. +Subsequent scoring and optimizer iterations use the binary dictionary. +The counters record oracle calls and actual persistent node writes. -/ + +namespace EditApproximation + +structure GatheredInputs where + memory : BinaryMemo ℚ + recursiveCalls : ℕ + nodeWrites : ℕ + +def gatherInputs {ι : Type*} (bits : ℕ) (encode : ι → ℕ) (fetch : ι → ℚ) : + List ι → GatheredInputs + | [] => ⟨.empty, 0, 0⟩ + | input :: rest => + let previous := gatherInputs bits encode fetch rest + let added := previous.memory.insertCosted (binaryMemoKey bits (encode input)) (fetch input) + ⟨added.1, previous.recursiveCalls + 1, previous.nodeWrites + added.2⟩ + +theorem gatherInputs_calls {ι : Type*} (bits : ℕ) (encode : ι → ℕ) (fetch : ι → ℚ) + (inputs : List ι) : (gatherInputs bits encode fetch inputs).recursiveCalls = inputs.length := by + induction inputs with + | nil => rfl + | cons input rest ih => simpa only [gatherInputs, List.length_cons] using congrArg (· + 1) ih + +theorem gatherInputs_writes {ι : Type*} (bits : ℕ) (encode : ι → ℕ) (fetch : ι → ℚ) + (inputs : List ι) : + (gatherInputs bits encode fetch inputs).nodeWrites = inputs.length * (bits + 1) := by + induction inputs with + | nil => simp only [gatherInputs, List.length_nil, Nat.zero_mul] + | cons input rest ih => + simp only [gatherInputs, BinaryMemo.insertCosted_spec, binaryMemoKey_length, ih, + List.length_cons, Nat.add_mul, Nat.one_mul] + +theorem gatherInputs_lookup {ι : Type*} (bits : ℕ) (encode : ι → ℕ) + (hinjective : Function.Injective encode) (fetch : ι → ℚ) (inputs : List ι) + (hbounded : ∀ input ∈ inputs, encode input < 2 ^ bits) + (query : ι) (hquery : query ∈ inputs) : + (gatherInputs bits encode fetch inputs).memory.lookup (binaryMemoKey bits (encode query)) = + some (fetch query) := by + induction inputs with + | nil => simp only [List.not_mem_nil] at hquery + | cons input rest ih => + simp only [gatherInputs, BinaryMemo.insertCosted_spec] + rw [binaryMemo_lookup_insert _ bits (encode input) (encode query) + (hbounded input (List.mem_cons_self)) (hbounded query hquery)] + by_cases heq : query = input + · subst query + simp only [ite_true] + · rw [ite_eq_right (fun h => heq (hinjective h))] + exact ih (fun other hother => hbounded other (List.mem_cons_of_mem _ hother)) + (List.mem_of_ne_of_mem heq hquery) + +theorem gatherInputs_nodes {ι : Type*} (bits : ℕ) (encode : ι → ℕ) (fetch : ι → ℚ) + (inputs : List ι) : + (gatherInputs bits encode fetch inputs).memory.nodes ≤ inputs.length * (bits + 1) := by + induction inputs with + | nil => exact Nat.zero_le _ + | cons input rest ih => + simp only [gatherInputs, BinaryMemo.insertCosted_spec] + have h := BinaryMemo.insert_nodes (gatherInputs bits encode fetch rest).memory + (binaryMemoKey bits (encode input)) (fetch input) + simp only [binaryMemoKey_length] at h + calc + _ ≤ (gatherInputs bits encode fetch rest).memory.nodes + bits + 1 := h + _ ≤ rest.length * (bits + 1) + bits + 1 := Nat.add_le_add_right (Nat.add_le_add_right ih _) _ + _ = (input :: rest).length * (bits + 1) := by + simp only [List.length_cons, Nat.add_mul, Nat.one_mul] + omega + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/GatheredLocalStep.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/GatheredLocalStep.lean new file mode 100644 index 0000000000000000000000000000000000000000..f384509a7584345de1738132398ef149aa5f60a3 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/GatheredLocalStep.lean @@ -0,0 +1,200 @@ +import OAI.Combinatorics.EditApproximation.Geometry.LocalWideStep +import OAI.Combinatorics.EditApproximation.Geometry.GatheredInputs +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! The current-index part of a local step can be evaluated in two +stages: gather the shared sampled inputs, select the whole-cell actions, +then gather their actual costs and the online action costs. -/ + +namespace EditApproximation + +open Finset + +theorem localCellGroupActions_congr_cover {α : Type*} + (source target : List α) {M : ℕ} (parent : TargetInterval source.length) + (N P F exponent Q : ℕ) (tau a : ℚ) + (parentInitial : TargetInterval target.length → ℚ) + (child initial current current' : Fin M → TargetInterval target.length → ℚ) + (draw : CellGroupDraws M F Q) (q : TargetInterval target.length) + (hvalue : ∀ input ∈ querySharedInputCover source target parent N F exponent Q a parentInitial q draw, + current input.1 input.2 = current' input.1 input.2) : + localCellGroupActions source target parent N P F exponent Q tau a parentInitial + child initial current draw q = + localCellGroupActions source target parent N P F exponent Q tau a parentInitial + child initial current' draw q := by + unfold localCellGroupActions + apply List.flatMap_congr + intro b hb + apply List.filterMap_congr + intro cell hc + have hscale : b ∈ dyadicScales N := (List.mem_filter.mp hb).1 + have hbpos : 1 ≤ b := by + obtain ⟨e, _, he⟩ := List.mem_map.mp hscale + rw [← he] + exact Nat.one_le_two_pow + apply chooseCellGroupAction_congr_cover source target parent tau a F Q parentInitial + child initial current current' cell hbpos (draw b cell) + intro scale input hi + apply hvalue input + apply Finset.mem_biUnion.mpr + refine ⟨(b, cell), ?_, Finset.mem_biUnion.mpr ⟨scale, Finset.mem_univ _, hi⟩⟩ + apply List.mem_toFinset.mpr + exact List.mem_flatMap.mpr ⟨b, hb, List.mem_map.mpr ⟨cell, hc, rfl⟩⟩ + +theorem rationalActionValues_congr_cover {Parent Child : Type*} [DecidableEq Child] {M : ℕ} + (distance : Parent → Parent → ℚ) (L : ℚ) + (actions : List (RationalBellmanAction Parent Child M)) (q : Parent) + (value value' : Child → ℚ) + (hvalue : ∀ input ∈ actionCurrentInputCover actions, value input = value' input) : + actions.map (rationalActionValue distance L value q) = + actions.map (rationalActionValue distance L value' q) := by + apply List.map_congr_left + intro action ha + unfold rationalActionValue + congr 1 + apply Finset.sum_congr rfl + intro i _ + exact hvalue _ (actionCurrentInputCover_mem actions action ha i) + +def gatheredInputValue {ι : Type*} (bits : ℕ) (encode : ι → ℕ) (fetch : ι → ℚ) + (inputs : List ι) (input : ι) : ℚ := + ((gatherInputs bits encode fetch inputs).memory.lookup (binaryMemoKey bits (encode input))).getD 0 + +theorem gatheredInputValue_eq {ι : Type*} (bits : ℕ) (encode : ι → ℕ) + (hinjective : Function.Injective encode) (fetch : ι → ℚ) (inputs : List ι) + (hbounded : ∀ input ∈ inputs, encode input < 2 ^ bits) + (input : ι) (hinput : input ∈ inputs) : + gatheredInputValue bits encode fetch inputs input = fetch input := by + unfold gatheredInputValue + rw [gatherInputs_lookup bits encode hinjective fetch inputs hbounded input hinput] + rfl + + + +theorem mem_orderedInputs {ι : Type*} [DecidableEq ι] (encode : ι → ℕ) + (hinjective : Function.Injective encode) (inputs : Finset ι) (input : ι) : + input ∈ orderedInputs encode hinjective inputs ↔ input ∈ inputs := by + let _ : LinearOrder ι := LinearOrder.lift' encode hinjective + exact Finset.mem_sort (r := (· ≤ ·)) + +theorem orderedInputs_length {ι : Type*} [DecidableEq ι] (encode : ι → ℕ) + (hinjective : Function.Injective encode) (inputs : Finset ι) : + (orderedInputs encode hinjective inputs).length = inputs.card := by + let _ : LinearOrder ι := LinearOrder.lift' encode hinjective + exact Finset.length_sort (r := (· ≤ ·)) + +def gatheredFiniteValue {ι : Type*} [DecidableEq ι] (bits : ℕ) (encode : ι → ℕ) + (hinjective : Function.Injective encode) (fetch : ι → ℚ) (inputs : Finset ι) : ι → ℚ := + gatheredInputValue bits encode fetch (orderedInputs encode hinjective inputs) + +theorem gatheredFiniteValue_eq {ι : Type*} [DecidableEq ι] (bits : ℕ) (encode : ι → ℕ) + (hinjective : Function.Injective encode) (fetch : ι → ℚ) (inputs : Finset ι) + (hbounded : ∀ input, encode input < 2 ^ bits) (input : ι) (hinput : input ∈ inputs) : + gatheredFiniteValue bits encode hinjective fetch inputs input = fetch input := + gatheredInputValue_eq bits encode hinjective fetch _ (fun i _ => hbounded i) input + ((mem_orderedInputs encode hinjective inputs input).2 hinput) + +section TwoStage + +variable {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (N P F exponent Q : ℕ) (tau a delta : ℚ) + (parentInitial : TargetInterval target.length → ℚ) + (child initial old current : Fin M → TargetInterval target.length → ℚ) + (draw : CellGroupDraws M F Q) (online : List (PhysicalRationalAction M target.length)) + (q : TargetInterval target.length) (bits : ℕ) + (encode : Fin M × TargetInterval target.length → ℕ) (hinjective : Function.Injective encode) + +local notation "shared" => querySharedInputCover source target parent N F exponent Q a parentInitial q draw +local notation "groups" => localCellGroupActions source target parent N P F exponent Q tau a parentInitial + child initial current draw q + +def gatheredCellGroupActions : List (PhysicalRationalAction M target.length) := + let cached := gatheredFiniteValue bits encode hinjective (fun input => current input.1 input.2) shared + localCellGroupActions source target parent N P F exponent Q tau a parentInitial + child initial (fun i r => cached (i, r)) draw q + +theorem gatheredCellGroupActions_eq (hbounded : ∀ input, encode input < 2 ^ bits) : + gatheredCellGroupActions source target parent N P F exponent Q tau a parentInitial + child initial current draw q bits encode hinjective = groups := by + apply localCellGroupActions_congr_cover + intro input hinput + exact gatheredFiniteValue_eq bits encode hinjective _ shared hbounded input hinput + +def gatheredLocalWideStep : ℚ := + let selected := gatheredCellGroupActions source target parent N P F exponent Q tau a parentInitial + child initial current draw q bits encode hinjective + let needed := actionCurrentInputCover selected ∪ actionCurrentInputCover online + let cached := gatheredFiniteValue bits encode hinjective (fun input => current input.1 input.2) needed + let value := rationalActionValue (fun q r => targetEndpointDistance q r) (128 * F) cached q + let fallback := rationalBellman parentInitial (fun q r => targetEndpointDistance q r) (128 * F) + (rationalActualWideActions parent (localRefinementRepresentatives N P F a parentInitial q) P) + (fun input => old input.1 input.2) q + rationalRefinementUpdate delta (rationalMinimum fallback (selected.map value)) + (rationalOnlineMinimum (online.map value)) + +theorem gatheredLocalWideStep_eq (hbounded : ∀ input, encode input < 2 ^ bits) : + gatheredLocalWideStep source target parent N P F exponent Q tau a delta parentInitial + child initial old current draw online q bits encode hinjective = + rationalLocalWideStep source target parent N P F exponent Q tau a delta parentInitial + child initial old current draw online q := by + unfold gatheredLocalWideStep + rw [gatheredCellGroupActions_eq source target parent N P F exponent Q tau a parentInitial + child initial current draw q bits encode hinjective hbounded] + dsimp only + let needed := actionCurrentInputCover groups ∪ actionCurrentInputCover online + have hgroup := rationalActionValues_congr_cover + (fun q r : TargetInterval target.length => (targetEndpointDistance q r : ℚ)) (128 * F) groups q + (gatheredFiniteValue bits encode hinjective (fun input => current input.1 input.2) needed) + (fun input => current input.1 input.2) + (fun input hi => gatheredFiniteValue_eq bits encode hinjective _ needed hbounded input + (Finset.mem_union_left _ hi)) + have honline := rationalActionValues_congr_cover + (fun q r : TargetInterval target.length => (targetEndpointDistance q r : ℚ)) (128 * F) online q + (gatheredFiniteValue bits encode hinjective (fun input => current input.1 input.2) needed) + (fun input => current input.1 input.2) + (fun input hi => gatheredFiniteValue_eq bits encode hinjective _ needed hbounded input + (Finset.mem_union_right _ hi)) + rw [hgroup, honline] + rfl + +/-- Actual oracle requests in the two gathers. Each list is sorted and +contains no duplicates; overlap between the two stages is harmless. -/ +def gatheredLocalCurrentCalls : ℕ := + (gatherInputs bits encode (fun input => current input.1 input.2) + (orderedInputs encode hinjective shared)).recursiveCalls + + (gatherInputs bits encode (fun input => current input.1 input.2) + (orderedInputs encode hinjective + (actionCurrentInputCover + (gatheredCellGroupActions source target parent N P F exponent Q tau a parentInitial + child initial current draw q bits encode hinjective) ∪ actionCurrentInputCover online))).recursiveCalls + +theorem gatheredLocalCurrentCalls_le (hbounded : ∀ input, encode input < 2 ^ bits) : + gatheredLocalCurrentCalls source target parent N P F exponent Q tau a parentInitial + child initial current draw online q bits encode hinjective ≤ + 2 * (currentQueryInputCover source target parent N P F exponent Q tau a parentInitial + child initial current draw q online).card := by + unfold gatheredLocalCurrentCalls + rw [gatherInputs_calls, gatherInputs_calls, orderedInputs_length, orderedInputs_length, + gatheredCellGroupActions_eq source target parent N P F exponent Q tau a parentInitial + child initial current draw q bits encode hinjective hbounded] + have hshared : (shared).card ≤ (currentQueryInputCover source target parent N P F exponent Q tau a + parentInitial child initial current draw q online).card := Finset.card_le_card (by + intro input hi + exact Finset.mem_union_left _ (Finset.mem_union_left _ hi)) + have hselected : (actionCurrentInputCover groups ∪ actionCurrentInputCover online).card ≤ + (currentQueryInputCover source target parent N P F exponent Q tau a + parentInitial child initial current draw q online).card := Finset.card_le_card (by + intro input hi + rcases Finset.mem_union.mp hi with hi | hi + · exact Finset.mem_union_left _ (Finset.mem_union_right _ hi) + · exact Finset.mem_union_right _ hi) + omega + +end TwoStage + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/Geometry.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/Geometry.lean new file mode 100644 index 0000000000000000000000000000000000000000..e46af38b58196dc9d584193023cf61d7c253e988 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/Geometry.lean @@ -0,0 +1,107 @@ +import OAI.Combinatorics.EditDistance.Metric +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! +# Interval-state edit geometry + +The edit distance here is the repository's unrestricted unit-cost +insertion/deletion/substitution distance, not an abstract metric supplied +as a hypothesis. These are the length and endpoint bounds in Section 2. +-/ + +namespace EditApproximation + +open EditDistortion + +universe u + +/-- The target substring with boundary indices `lo` and `hi`. -/ + + +theorem substring_length {α : Type u} (word : List α) (lo hi : ℕ) + (hhi : hi ≤ word.length) : (substring word lo hi).length = hi - lo := by + simp only [substring, List.length_drop, List.length_take, Nat.min_eq_left hhi] + +theorem edit_sublist_le {α : Type u} {small large : List α} (h : small.Sublist large) : + edit large small ≤ large.length - small.length := + cost_le (Script.of_sublist h).allow_substitution + +theorem edit_drop_indices_le {α : Type u} (word : List α) (lo lo' : ℕ) : + edit (word.drop lo) (word.drop lo') ≤ Nat.dist lo lo' := by + rcases le_total lo lo' with h | h + · have hs := edit_sublist_le (List.drop_sublist_drop_left word h) + apply hs.trans + simp only [List.length_drop, Nat.dist_eq_sub_of_le h] + omega + · rw [show edit (word.drop lo) (word.drop lo') = + edit (word.drop lo') (word.drop lo) from cost_symm _ _] + have hs := edit_sublist_le (List.drop_sublist_drop_left word h) + apply hs.trans + simp only [List.length_drop, Nat.dist_eq_sub_of_le_right h] + omega + +theorem edit_substring_right_le {α : Type u} (word : List α) (lo hi hi' : ℕ) : + edit (substring word lo hi) (substring word lo hi') ≤ Nat.dist hi hi' := by + rcases le_total hi hi' with h | h + · have hs := edit_sublist_le ((List.take_sublist_take_left (l := word) h).drop lo) + rw [show edit (substring word lo hi) (substring word lo hi') = + edit (substring word lo hi') (substring word lo hi) from cost_symm _ _] + apply hs.trans + simp only [List.length_drop, List.length_take, Nat.dist_eq_sub_of_le h] + omega + · have hs := edit_sublist_le ((List.take_sublist_take_left (l := word) h).drop lo) + apply hs.trans + simp only [List.length_drop, List.length_take, Nat.dist_eq_sub_of_le_right h] + omega + +/-- Changing both substring endpoints costs at most their total movement, +including when the two intervals are disjoint. -/ +theorem edit_substring_endpoints_le {α : Type u} (word : List α) + (lo hi lo' hi' : ℕ) : + edit (substring word lo hi) (substring word lo' hi') ≤ + Nat.dist lo lo' + Nat.dist hi hi' := by + have htri := cost_triangle (s := true) (substring word lo hi) + (substring word lo' hi) (substring word lo' hi') + exact htri.trans (Nat.add_le_add (edit_drop_indices_le (word.take hi) lo lo') + (edit_substring_right_le word lo' hi hi')) + +theorem abs_length_gap_le_edit {α : Type u} (x y : List α) : + |(y.length : ℝ) - x.length| ≤ (edit x y : ℝ) := by + obtain ⟨hxy, hyx⟩ := cost_length_bounds (s := true) x y + have hx : (x.length : ℝ) ≤ y.length + (edit x y : ℝ) := by exact_mod_cast hxy + have hy : (y.length : ℝ) ≤ x.length + (edit x y : ℝ) := by exact_mod_cast hyx + exact abs_le.mpr ⟨by linarith, by linarith⟩ + +/-- The actual interval-state cost is 1-Lipschitz in the endpoint metric. -/ +theorem interval_cost_lipschitz {α : Type u} (x y : List α) + (lo hi lo' hi' : ℕ) : + |(edit x (substring y lo hi) : ℝ) - edit x (substring y lo' hi')| ≤ + (Nat.dist lo lo' + Nat.dist hi hi' : ℕ) := by + have hmove := edit_substring_endpoints_le y lo hi lo' hi' + have hmove' : edit (substring y lo' hi') (substring y lo hi) ≤ + Nat.dist lo lo' + Nat.dist hi hi' := by + rw [show edit (substring y lo' hi') (substring y lo hi) = + edit (substring y lo hi) (substring y lo' hi') from cost_symm _ _] + exact hmove + have hleft := (cost_triangle (s := true) x (substring y lo' hi') + (substring y lo hi)).trans (Nat.add_le_add_left hmove' _) + have hright := (cost_triangle (s := true) x (substring y lo hi) + (substring y lo' hi')).trans (Nat.add_le_add_left hmove _) + have hl : (edit x (substring y lo hi) : ℝ) ≤ + edit x (substring y lo' hi') + (Nat.dist lo lo' + Nat.dist hi hi' : ℕ) := by + exact_mod_cast hleft + have hr : (edit x (substring y lo' hi') : ℝ) ≤ + edit x (substring y lo hi) + (Nat.dist lo lo' + Nat.dist hi hi' : ℕ) := by + exact_mod_cast hright + exact abs_le.mpr ⟨by linarith, by linarith⟩ + +theorem edit_le_total_length {α : Type u} (x y : List α) : + edit x y ≤ x.length + y.length := + (edit_le_max_length x y).trans (max_le (Nat.le_add_right _ _) (Nat.le_add_left _ _)) + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/GlobalQueryCost.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/GlobalQueryCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..8a445839b3182d61e6ba368d26d7ced244cd3e4b --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/GlobalQueryCost.lean @@ -0,0 +1,109 @@ +import OAI.Combinatorics.EditApproximation.Geometry.ChargedGlobalQuery +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalQueryProgress + +namespace OAI + +/-! Exact weighted-cost transport for the full internal refinement body. +In this branch every request is an ordinary table request: parent initial, +child mass, child initial, old history or a current physical child. -/ + +namespace EditApproximation + +namespace FiniteQuery + +theorem cost_congr_weights {ι : Type*} (oracle : ι → ℚ) (program : FiniteQuery ι) + (left right : ι → ℕ) (heq : ∀ key ∈ program.keys oracle, left key = right key) : + program.cost oracle left = program.cost oracle right := by + rw [cost_eq_sum, cost_eq_sum] + congr 1 + exact List.map_congr_left heq + +end FiniteQuery + +def chargedTableWeight {M J ny passes copies T S : ℕ} + (coarse : ℕ) (weight : PhysicalTableRequest M J ny → ℕ) : + ChargedPhysicalRequest M J ny passes copies T S → ℕ + | .inl _ => coarse + | .inr request => weight request.val + +section Costs + +variable {α : Type*} [DecidableEq α] {M J R : ℕ} [NeZero R] + (source target : List α) (N P F exponent H Q T S passes copies : ℕ) + (factor : ℕ → ℚ) (multiplier : ℕ → ℕ) (tau eta kappa delta : ℚ) + (group : ℕ → ℕ → PhysicalInternalNode M J → Fin R → CellGroupDraws M F Q) + (integer : ℕ → ℕ → PhysicalInternalNode M J → Fin R → ℕ → TargetInterval target.length → ℕ) + (initial : PhysicalEntry M J target.length → ℕ) + +theorem physicalBoundedQuery_cost + (request : {r : PhysicalTableRequest M J target.length // r.Bounded passes copies T S}) + (weight : PhysicalTableRequest M J target.length → ℕ) : + (physicalBoundedQuery source target N P F exponent H Q T S passes copies factor multiplier + tau eta kappa delta group integer initial request).cost + (fun child => localRequestValue source target N P F exponent H Q T S copies factor multiplier + tau eta kappa delta group integer initial child.val.val) (fun child => weight child.val.val) = + (physicalGlobalQuery source target N P F exponent H Q T S copies factor multiplier + tau eta kappa delta group integer initial request.val).cost + (fun child => localRequestValue source target N P F exponent H Q T S copies factor multiplier + tau eta kappa delta group integer initial child.val) (fun child => weight child.val) := by + unfold physicalBoundedQuery + exact restrictRankedProgram_cost _ _ _ _ weight request + (physicalGlobalQuery_keys_bounded source target N P F exponent H Q T S passes copies factor multiplier + tau eta kappa delta group integer initial request.val request.property _) + +theorem physicalGlobalQuery_refinement_cost (request : PhysicalTableRequest M J target.length) + (hindex : T < request.index) (hbelow : request.node.1.val < J) + (hshort : ¬ (physicalSourceInterval source.length request.node).hi - + (physicalSourceInterval source.length request.node).lo ≤ 1) + (values : PhysicalTableRequest M J target.length → ℚ) + (weight : PhysicalTableRequest M J target.length → ℕ) : + (physicalGlobalQuery source target N P F exponent H Q T S copies factor multiplier + tau eta kappa delta group integer initial request).cost + (fun child => values child.val) (fun child => weight child.val) = + (physicalRefinementDataRequestQuery source target N P F exponent H Q tau + (refinementFactor (factor request.pass) F) eta kappa delta request.pass request.copy T S + (request.index - T) (Nat.sub_pos_of_lt hindex) request.node hbelow + (group request.pass request.copy ⟨request.node, hbelow⟩ (Fin.ofNat R (request.index - T - 1))) + (integer request.pass request.copy ⟨request.node, hbelow⟩ (Fin.ofNat R (request.index - T - 1))) + request.state).cost (fun child => values child.val) (fun child => weight child.val) := by + unfold physicalGlobalQuery + dsimp only + erw [dite_eq_right (Nat.not_le.mpr hindex), dite_eq_left hbelow, dite_eq_right hshort] + rw [FiniteQuery.mapKeys_cost] + rfl + + +theorem chargedGlobalQuery_refinement_cost + (parent : {r : PhysicalTableRequest M J target.length // r.Bounded passes copies T S}) + (hindex : T < parent.val.index) (hbelow : parent.val.node.1.val < J) + (hshort : ¬ (physicalSourceInterval source.length parent.val.node).hi - + (physicalSourceInterval source.length parent.val.node).lo ≤ 1) + (coarse : ℕ) (weight : PhysicalTableRequest M J target.length → ℕ) : + (chargedGlobalQuery source target N P F exponent H Q T S passes copies factor multiplier + tau eta kappa delta group integer initial (Sum.inr parent)).cost + (fun child => chargedRequestValue source target N P F exponent H Q T S passes copies + factor multiplier tau eta kappa delta group integer initial child.val) + (fun child => chargedTableWeight coarse weight child.val) = + (physicalRefinementDataRequestQuery source target N P F exponent H Q tau + (refinementFactor (factor parent.val.pass) F) eta kappa delta parent.val.pass parent.val.copy T S + (parent.val.index - T) (Nat.sub_pos_of_lt hindex) parent.val.node hbelow + (group parent.val.pass parent.val.copy ⟨parent.val.node, hbelow⟩ (Fin.ofNat R (parent.val.index - T - 1))) + (integer parent.val.pass parent.val.copy ⟨parent.val.node, hbelow⟩ (Fin.ofNat R (parent.val.index - T - 1))) + parent.val.state).cost + (fun child => localRequestValue source target N P F exponent H Q T S copies factor multiplier + tau eta kappa delta group integer initial child.val) (fun child => weight child.val) := by + unfold chargedGlobalQuery + dsimp only + rw [ite_eq_right (Nat.not_le.mpr hindex), ite_eq_left hbelow, ite_eq_right hshort, + FiniteQuery.mapKeys_cost] + simp only [Function.comp_def, chargedRequestValue, chargedTableWeight] + rw [physicalBoundedQuery_cost source target N P F exponent H Q T S passes copies factor multiplier + tau eta kappa delta group integer initial parent weight] + exact physicalGlobalQuery_refinement_cost source target N P F exponent H Q T S copies factor multiplier + tau eta kappa delta group integer initial parent.val hindex hbelow hshort _ weight + +end Costs + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/GlobalQueryProgress.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/GlobalQueryProgress.lean new file mode 100644 index 0000000000000000000000000000000000000000..eea21e1fc7d62f34469f50c7cf5fac803f431b66 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/GlobalQueryProgress.lean @@ -0,0 +1,116 @@ +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalBoundedQuery +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalQueryProgress + +namespace OAI + +/-! Concrete depth/pass-index progress is preserved by the finite-domain +transport. The statement concerns the reads executed at the actual values. -/ + +namespace EditApproximation + +theorem globalSeedRead_keys_progress {M J ny : ℕ} (N T S copies : ℕ) + (multiplier : ℕ → ℕ) (initial : PhysicalEntry M J ny → ℕ) + (parent : PhysicalTableRequest M J ny) (state : PhysicalEntry M J ny) (oracle) : + ∀ key ∈ (globalSeedRead N T S copies multiplier initial parent state).keys oracle, + PhysicalTableRequest.DependencyProgress T S parent key.val := by + unfold globalSeedRead + split_ifs with hnode hpass + · intro key hk + exact False.elim (List.not_mem_nil hk) + · unfold physicalMedianSeedQuery + apply FiniteQuery.keys_all_collect + · intro copy _ key hk + simp only [previousPassRead, FiniteQuery.keys, List.mem_singleton] at hk + subst key + exact Or.inr ⟨(previousPassRequest_progress T S copy.val parent (Nat.pos_of_ne_zero hpass) state.2).1.le, + (previousPassRequest_progress T S copy.val parent (Nat.pos_of_ne_zero hpass) state.2).2⟩ + · intro values key hk + exact False.elim (List.not_mem_nil hk) + · intro key hk + exact False.elim (List.not_mem_nil hk) + +section Progress + +variable {α : Type*} [DecidableEq α] {M J R : ℕ} [NeZero R] + (source target : List α) (N P F exponent H Q T S passes copies : ℕ) + (factor : ℕ → ℚ) (multiplier : ℕ → ℕ) (tau eta kappa delta : ℚ) + (group : ℕ → ℕ → PhysicalInternalNode M J → Fin R → CellGroupDraws M F Q) + (integer : ℕ → ℕ → PhysicalInternalNode M J → Fin R → ℕ → TargetInterval target.length → ℕ) + (initial : PhysicalEntry M J target.length → ℕ) + +theorem physicalGlobalQuery_keys_progress (request : PhysicalTableRequest M J target.length) + (oracle) : + ∀ key ∈ (physicalGlobalQuery source target N P F exponent H Q T S copies factor multiplier + tau eta kappa delta group integer initial request).keys oracle, + PhysicalTableRequest.DependencyProgress T S request key.val := by + rcases request with ⟨pass, copy, node, index, q⟩ + by_cases hj : index ≤ T + · change ∀ key ∈ (physicalGlobalQuery source target N P F exponent H Q T S copies factor multiplier + tau eta kappa delta group integer initial (PhysicalTableRequest.warmup pass copy node index q)).keys oracle, + PhysicalTableRequest.DependencyProgress T S _ key.val + rw [physicalGlobalQuery_warmup source target N P F exponent H Q T S copies factor multiplier + tau eta kappa delta group integer initial pass copy node index hj q] + apply physicalWarmupRequestQuery_keys_progress + intro r key hk + exact globalSeedRead_keys_progress N T S copies multiplier initial _ _ oracle key hk + · unfold physicalGlobalQuery + dsimp only + erw [dite_eq_right (show ¬ ({pass := pass, copy := copy, node := node, index := index, state := q} : + PhysicalTableRequest M J target.length).index ≤ T from hj)] + by_cases hbelow : node.1.val < J + · erw [dite_eq_left hbelow] + by_cases hshort : (physicalSourceInterval source.length node).hi - + (physicalSourceInterval source.length node).lo ≤ 1 + · erw [dite_eq_left hshort] + apply physicalInitialQuery_keys_all + intro r key hk + exact globalSeedRead_keys_progress N T S copies multiplier initial _ _ oracle key hk + · erw [dite_eq_right hshort, FiniteQuery.mapKeys_keys] + intro key hk + obtain ⟨child, hc, rfl⟩ := List.mem_map.mp hk + have h := physicalRefinementDataRequest_keys_progress source target N P F exponent H Q tau + (refinementFactor (factor pass) F) eta kappa delta pass copy T S (index - T) + (by omega) node hbelow _ _ q _ child hc + have heq : PhysicalTableRequest.refinement pass copy node T (index - T) q = + ({pass := pass, copy := copy, node := node, index := index, state := q} : + PhysicalTableRequest M J target.length) := by + unfold PhysicalTableRequest.refinement + congr 1 + omega + simpa only [heq] using h + · erw [dite_eq_right hbelow] + apply physicalInitialQuery_keys_all + intro r key hk + exact globalSeedRead_keys_progress N T S copies multiplier initial _ _ oracle key hk + +theorem physicalBoundedQuery_keys_progress + (request : {r : PhysicalTableRequest M J target.length // r.Bounded passes copies T S}) : + ∀ key ∈ (physicalBoundedQuery source target N P F exponent H Q T S passes copies factor multiplier + tau eta kappa delta group integer initial request).keys + (fun child => localRequestValue source target N P F exponent H Q T S copies factor multiplier + tau eta kappa delta group integer initial child.val.val), + PhysicalTableRequest.DependencyProgress T S request.val key.val.val := by + intro key hk + have hkeys := restrictRankedProgram_keys (PhysicalTableRequest.combinedRank T S) + (physicalGlobalQuery source target N P F exponent H Q T S copies factor multiplier + tau eta kappa delta group integer initial) (PhysicalTableRequest.Bounded passes copies T S) + (localRequestValue source target N P F exponent H Q T S copies factor multiplier + tau eta kappa delta group integer initial) request + (physicalGlobalQuery_keys_bounded source target N P F exponent H Q T S passes copies factor multiplier + tau eta kappa delta group integer initial request.val request.property _) + have hm : key.val.val ∈ ((physicalGlobalQuery source target N P F exponent H Q T S copies factor multiplier + tau eta kappa delta group integer initial request.val).keys + (fun child => localRequestValue source target N P F exponent H Q T S copies factor multiplier + tau eta kappa delta group integer initial child.val)).map Subtype.val := by + rw [← hkeys] + exact List.mem_map.mpr ⟨key, hk, rfl⟩ + obtain ⟨child, hc, heq⟩ := List.mem_map.mp hm + rw [← heq] + exact physicalGlobalQuery_keys_progress source target N P F exponent H Q T S copies factor multiplier + tau eta kappa delta group integer initial request.val _ child hc + +end Progress + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/Grid.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/Grid.lean new file mode 100644 index 0000000000000000000000000000000000000000..2968761e1fab22c1cdb3be04fa59c2d2f96321c9 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/Grid.lean @@ -0,0 +1,89 @@ +import OAI.Combinatorics.EditApproximation.Geometry.Connections +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! +# Integer endpoint grids + +Rounding is an executable integer division. It preserves valid interval +states and shared endpoints, and the edit-distance perturbation is bounded +by the actual two remainders. No real-valued grid is substituted for it. +-/ + +namespace EditApproximation + + + +theorem gridRound_le (spacing position : ℕ) : gridRound spacing position ≤ position := + Nat.mul_div_le _ _ + +theorem gridRound_mono (spacing : ℕ) : Monotone (gridRound spacing) := by + intro p q hpq + exact Nat.mul_le_mul_left spacing (Nat.div_le_div_right hpq) + +theorem gridRound_distance (spacing position : ℕ) : + Nat.dist position (gridRound spacing position) = position % spacing := by + have h := Nat.mod_add_div position spacing + unfold Nat.dist gridRound + omega + +theorem gridRound_error_lt (spacing position : ℕ) (hspacing : 0 < spacing) : + Nat.dist position (gridRound spacing position) < spacing := by + rw [gridRound_distance] + exact Nat.mod_lt _ hspacing + +theorem gridRound_of_dvd {spacing position : ℕ} (hdiv : spacing ∣ position) : + gridRound spacing position = position := by + have hzero := Nat.mod_eq_zero_of_dvd hdiv + have h := Nat.mod_add_div position spacing + simpa only [hzero, zero_add, gridRound] using h + +@[simp] theorem gridRound_one (position : ℕ) : gridRound 1 position = position := by + simp [gridRound] + + + +theorem roundInterval_shared {n spacing : ℕ} (first second : TargetInterval n) + (hshared : first.hi = second.lo) : + (roundInterval spacing first).hi = (roundInterval spacing second).lo := by + exact congrArg (gridRound spacing) hshared + +theorem roundInterval_error {n : ℕ} (spacing : ℕ) (hspacing : 0 < spacing) + (state : TargetInterval n) : + Nat.dist state.lo (roundInterval spacing state).lo + + Nat.dist state.hi (roundInterval spacing state).hi < 2 * spacing := by + have hlo := gridRound_error_lt spacing state.lo hspacing + have hhi := gridRound_error_lt spacing state.hi hspacing + change Nat.dist state.lo (gridRound spacing state.lo) + + Nat.dist state.hi (gridRound spacing state.hi) < 2 * spacing + omega + +theorem edit_roundInterval_bound {α : Type*} (source target : List α) + (spacing : ℕ) (state : TargetInterval target.length) : + EditDistortion.edit source + (substring target (roundInterval spacing state).lo (roundInterval spacing state).hi) ≤ + EditDistortion.edit source (substring target state.lo state.hi) + + state.lo % spacing + state.hi % spacing := by + have hperturb := edit_substring_endpoints_le target state.lo state.hi + (roundInterval spacing state).lo (roundInterval spacing state).hi + have htri := EditDistortion.cost_triangle (s := true) source + (substring target state.lo state.hi) + (substring target (roundInterval spacing state).lo (roundInterval spacing state).hi) + change EditDistortion.edit source + (substring target (roundInterval spacing state).lo (roundInterval spacing state).hi) ≤ + EditDistortion.edit source (substring target state.lo state.hi) + + EditDistortion.edit (substring target state.lo state.hi) + (substring target (roundInterval spacing state).lo (roundInterval spacing state).hi) at htri + apply htri.trans + have hlo : Nat.dist state.lo (roundInterval spacing state).lo = state.lo % spacing := + gridRound_distance spacing state.lo + have hhi : Nat.dist state.hi (roundInterval spacing state).hi = state.hi % spacing := + gridRound_distance spacing state.hi + rw [hlo, hhi] at hperturb + omega + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/GroupCells.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/GroupCells.lean new file mode 100644 index 0000000000000000000000000000000000000000..629ff4d21c26ab1428833128a03b74187ba77a07 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/GroupCells.lean @@ -0,0 +1,188 @@ +import OAI.Combinatorics.EditApproximation.Geometry.LocalGrid +import OAI.Combinatorics.EditApproximation.Geometry.ActualRepresentatives +import OAI.Combinatorics.EditApproximation.Geometry.BandRounding +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Whole rational cells are enumerated by bounded ranges of grid indices. -/ + +namespace EditApproximation + + + +theorem cellGridPoints_mem {side : ℚ} {g cell p : ℕ} (hg : 0 < g) : + p ∈ cellGridPoints side g cell ↔ + g ∣ p ∧ (cell : ℚ) * side ≤ p ∧ (p : ℚ) < ((cell : ℚ) + 1) * side := by + have hgr : (0 : ℚ) < g := by exact_mod_cast hg + constructor + · intro hp + obtain ⟨i, hi, rfl⟩ := List.mem_map.mp hp + obtain ⟨j, hj, rfl⟩ := List.mem_range'.mp hi + have hlo : ⌈(cell : ℚ) * side / g⌉₊ ≤ ⌈(cell : ℚ) * side / g⌉₊ + 1 * j := by omega + have hhi : ⌈(cell : ℚ) * side / g⌉₊ + 1 * j < ⌈((cell : ℚ) + 1) * side / g⌉₊ := by omega + have hloR := (Nat.ceil_le.mp hlo) + have hhiR := (Nat.lt_ceil.mp hhi) + refine ⟨dvd_mul_right _ _, ?_, ?_⟩ + · have h := (div_le_iff₀ hgr).mp hloR + push_cast at h + push_cast + simpa only [mul_comm] using h + · have h := (lt_div_iff₀ hgr).mp hhiR + push_cast at h + push_cast + simpa only [mul_comm] using h + · rintro ⟨hgrid, hlo, hhi⟩ + have heq : g * (p / g) = p := Nat.mul_div_cancel' hgrid + have hloR : (cell : ℚ) * side / g ≤ (p / g : ℕ) := by + apply (div_le_iff₀ hgr).2 + have hc : (g : ℚ) * (p / g : ℕ) = p := by exact_mod_cast heq + linarith only [hlo, hc] + have hhiR : ((p / g : ℕ) : ℚ) < ((cell : ℚ) + 1) * side / g := by + apply (lt_div_iff₀ hgr).2 + have hc : (g : ℚ) * (p / g : ℕ) = p := by exact_mod_cast heq + linarith only [hhi, hc] + have hstart := Nat.ceil_le.mpr hloR + have hend := Nat.lt_ceil.mpr hhiR + apply List.mem_map.mpr + refine ⟨p / g, List.mem_range'.mpr ?_, heq⟩ + exact ⟨p / g - ⌈(cell : ℚ) * side / g⌉₊, by omega, by omega⟩ + +theorem cellGridPoints_length_le {side : ℚ} {g cell P : ℕ} + (hside : 0 ≤ side) (hsize : side / g ≤ P) : + (cellGridPoints side g cell).length ≤ P := by + have hbase : 0 ≤ (cell : ℚ) * side / g := + div_nonneg (mul_nonneg (Nat.cast_nonneg _) hside) (Nat.cast_nonneg _) + have hupper : ((cell : ℚ) + 1) * side / g ≤ (cell : ℚ) * side / g + P := by + calc + _ = (cell : ℚ) * side / g + side / g := by ring + _ ≤ _ := add_le_add_right hsize _ + have hceil := Nat.ceil_le_ceil hupper + rw [Nat.ceil_add_natCast hbase P] at hceil + simp only [cellGridPoints, List.length_map, List.length_range'] + omega + + + +theorem cellTargetStates_mem {n g : ℕ} {side : ℚ} (cell : ℕ × ℕ) (hg : 0 < g) + (q : TargetInterval n) : + q ∈ cellTargetStates n g side cell ↔ + g ∣ q.lo ∧ g ∣ q.hi ∧ + (cell.1 : ℚ) * side ≤ q.lo ∧ (q.lo : ℚ) < ((cell.1 : ℚ) + 1) * side ∧ + (cell.2 : ℚ) * side ≤ q.hi ∧ (q.hi : ℚ) < ((cell.2 : ℚ) + 1) * side := by + constructor + · intro hq + obtain ⟨lo, hlo, hq⟩ := List.mem_flatMap.mp hq + obtain ⟨hi, hhi, hq⟩ := List.mem_filterMap.mp hq + have hstate : q.lo = lo ∧ q.hi = hi := by + unfold makeTargetState at hq + split_ifs at hq with hvalid + have heq := Option.some.inj hq + exact ⟨congrArg TargetInterval.lo heq.symm, congrArg TargetInterval.hi heq.symm⟩ + rw [← hstate.1] at hlo + rw [← hstate.2] at hhi + have hl := cellGridPoints_mem hg |>.mp hlo + have hh := cellGridPoints_mem hg |>.mp hhi + exact ⟨hl.1, hh.1, hl.2.1, hl.2.2, hh.2.1, hh.2.2⟩ + · rintro ⟨hlo, hhi, hloL, hloU, hhiL, hhiU⟩ + apply List.mem_flatMap.mpr + refine ⟨q.lo, (cellGridPoints_mem hg).mpr ⟨hlo, hloL, hloU⟩, List.mem_filterMap.mpr ?_⟩ + refine ⟨q.hi, (cellGridPoints_mem hg).mpr ⟨hhi, hhiL, hhiU⟩, ?_⟩ + rw [makeTargetState, dite_eq_left (show q.lo ≤ q.hi ∧ q.hi ≤ n from ⟨q.ordered, q.valid⟩)] + +theorem cellTargetStates_length_le {n g P : ℕ} {side : ℚ} (cell : ℕ × ℕ) + (hside : 0 ≤ side) (hsize : side / g ≤ P) : + (cellTargetStates n g side cell).length ≤ P ^ 2 := by + have hfirst := cellGridPoints_length_le (cell := cell.1) hside hsize + have hsecond := cellGridPoints_length_le (cell := cell.2) hside hsize + have h := list_flatMap_length_le (cellGridPoints side g cell.1) + (fun lo => (cellGridPoints side g cell.2).filterMap fun hi => makeTargetState n lo hi) P + (fun lo _ => (List.length_filterMap_le _ _).trans hsecond) + exact h.trans (by simpa only [pow_two] using Nat.mul_le_mul_right P hfirst) + +theorem cellTargetStates_diameter {n g : ℕ} {side : ℚ} (cell : ℕ × ℕ) (hg : 0 < g) + (q r : TargetInterval n) (hq : q ∈ cellTargetStates n g side cell) + (hr : r ∈ cellTargetStates n g side cell) : (targetEndpointDistance q r : ℚ) ≤ 2 * side := by + have hq' := (cellTargetStates_mem cell hg q).mp hq + have hr' := (cellTargetStates_mem cell hg r).mp hr + have hlo : |(q.lo : ℚ) - r.lo| ≤ side := by + apply abs_le.mpr + constructor <;> linarith only [hq'.2.2.1, hq'.2.2.2.1, hr'.2.2.1, hr'.2.2.2.1] + have hhi : |(q.hi : ℚ) - r.hi| ≤ side := by + apply abs_le.mpr + constructor <;> linarith only [hq'.2.2.2.2.1, hq'.2.2.2.2.2, hr'.2.2.2.2.1, hr'.2.2.2.2.2] + have hcast (a b : ℕ) : |(a : ℚ) - b| = (Nat.dist a b : ℚ) := by + exact_mod_cast natural_distance_cast a b + rw [targetEndpointDistance, Nat.cast_add, ← hcast, ← hcast] + linarith only [hlo, hhi] + +theorem seedGridSpacing_covers_dyadic {b P : ℕ} + (hb : ∃ e : ℕ, b = 2 ^ e) (hP : ∃ e : ℕ, P = 2 ^ e) : + b ≤ P * seedGridSpacing b P := by + obtain ⟨eb, rfl⟩ := hb + obtain ⟨eP, rfl⟩ := hP + by_cases horder : eP ≤ eb + · rw [seedGridSpacing, Nat.pow_div horder (by decide : 0 < 2), max_eq_right Nat.one_le_two_pow, + ← pow_add, Nat.add_sub_of_le horder] + · have hle : 2 ^ eb ≤ 2 ^ eP := Nat.pow_le_pow_right (by decide : 0 < 2) (by omega) + exact hle.trans (Nat.le_mul_of_pos_right _ (by unfold seedGridSpacing; omega)) + +def targetCell {n : ℕ} (side : ℚ) (q : TargetInterval n) : ℕ × ℕ := + (⌊(q.lo : ℚ) / side⌋₊, ⌊(q.hi : ℚ) / side⌋₊) + +theorem targetCell_contains {n g : ℕ} {side : ℚ} (hg : 0 < g) (hside : 0 < side) + (q : TargetInterval n) (hgrid : g ∣ q.lo ∧ g ∣ q.hi) : + q ∈ cellTargetStates n g side (targetCell side q) := by + have hcoordinate (p : ℕ) : (⌊(p : ℚ) / side⌋₊ : ℚ) * side ≤ p ∧ + (p : ℚ) < ((⌊(p : ℚ) / side⌋₊ : ℚ) + 1) * side := by + exact ⟨(le_div_iff₀ hside).mp (Nat.floor_le (div_nonneg (Nat.cast_nonneg _) hside.le)), + (div_lt_iff₀ hside).mp (Nat.lt_floor_add_one ((p : ℚ) / side))⟩ + exact (cellTargetStates_mem _ hg q).mpr + ⟨hgrid.1, hgrid.2, (hcoordinate q.lo).1, (hcoordinate q.lo).2, + (hcoordinate q.hi).1, (hcoordinate q.hi).2⟩ + + + +theorem cellRepresentativeStates_mem_representatives {n N P F b : ℕ} + (a : ℚ) (initial : TargetInterval n → ℚ) (theta : ℚ) (cell : ℕ × ℕ) + (r : TargetInterval n) (hb : b ∈ dyadicScales N) + (hr : r ∈ cellRepresentativeStates n P F b a initial theta cell) : + (b, r) ∈ representativeList N P F a initial := by + obtain ⟨hcell, heligible⟩ := List.mem_filter.mp hr + have hg : 0 < seedGridSpacing b P := by unfold seedGridSpacing; omega + have hgrid := (cellTargetStates_mem cell hg r).mp hcell + exact representativeList_mem a initial r hb ⟨hgrid.1, hgrid.2.1⟩ + (of_decide_eq_true heligible).1 (of_decide_eq_true heligible).2 + +theorem cellRepresentativeStates_length_le {n P F b : ℕ} + (a : ℚ) (initial : TargetInterval n → ℚ) (theta : ℚ) (cell : ℕ × ℕ) + (htheta : 0 ≤ theta ∧ theta ≤ 1) + (hb : ∃ e : ℕ, b = 2 ^ e) (hP : ∃ e : ℕ, P = 2 ^ e) : + (cellRepresentativeStates n P F b a initial theta cell).length ≤ (P + 1) ^ 2 := by + have hg : 0 < seedGridSpacing b P := by unfold seedGridSpacing; omega + have hgr : (0 : ℚ) < seedGridSpacing b P := by exact_mod_cast hg + have hcover : (b : ℚ) ≤ P * (seedGridSpacing b P : ℚ) := by + exact_mod_cast seedGridSpacing_covers_dyadic hb hP + have hsize : theta * b / seedGridSpacing b P ≤ (P : ℚ) := by + apply (div_le_iff₀ hgr).2 + have h := mul_le_mul_of_nonneg_right htheta.2 (Nat.cast_nonneg (α := ℚ) b) + simp only [one_mul] at h + exact h.trans hcover + unfold cellRepresentativeStates + apply (List.length_filter_le _ _).trans + exact (cellTargetStates_length_le (n := n) cell + (mul_nonneg htheta.1 (Nat.cast_nonneg _)) hsize).trans + (Nat.pow_le_pow_left (Nat.le_succ P) 2) + +theorem cellRepresentativeStates_contains {n P F b : ℕ} + (a : ℚ) (initial : TargetInterval n → ℚ) (theta : ℚ) (r : TargetInterval n) + (hside : 0 < theta * b) (hgrid : seedGridSpacing b P ∣ r.lo ∧ seedGridSpacing b P ∣ r.hi) + (heligible : (b : ℚ) / (4 * a) ≤ initial r ∧ initial r ≤ 8 * F * b) : + r ∈ cellRepresentativeStates n P F b a initial theta (targetCell (theta * b) r) := by + apply List.mem_filter.mpr + exact ⟨targetCell_contains (by unfold seedGridSpacing; omega) hside r hgrid, decide_eq_true heligible⟩ + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/GroupInputDependence.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/GroupInputDependence.lean new file mode 100644 index 0000000000000000000000000000000000000000..d8e61a089084d9db811cefc91d3ecae75b232616 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/GroupInputDependence.lean @@ -0,0 +1,116 @@ +import OAI.Combinatorics.EditApproximation.Geometry.CurrentQueryInputs + +namespace OAI + +/-! Shared group estimates depend only on the explicitly bounded sampled +input cover. Thus scanning or repeatedly scoring all cell members can +reuse gathered values rather than issue new recursive requests. -/ + +namespace EditApproximation + +open Finset + +theorem groupScaleEstimate_congr_queried {M Q b : ℕ} (h : ℚ) + (envelope value value' : Fin M → ℚ) + (draw : Fin (groupSampleCount M Q b h) → Fin M) + (hvalue : ∀ i ∈ groupQueriedChildLabels M Q b h draw, + envelope i = h → value i = value' i) : + groupScaleEstimate (groupSampleCount M Q b h) h envelope value draw = + groupScaleEstimate (groupSampleCount M Q b h) h envelope value' draw := by + unfold groupScaleEstimate + split_ifs with hexact + · unfold groupScaleTrueCost + apply Finset.sum_congr rfl + intro i _ + split_ifs with hi + · exact hvalue i (by simp only [groupQueriedChildLabels, hexact, ↓reduceIte, Finset.mem_univ]) hi + · rfl + · congr 1 + apply Finset.sum_congr rfl + intro j _ + split_ifs with hj + · apply hvalue _ _ hj + simp only [groupQueriedChildLabels, hexact, ↓reduceIte] + exact Finset.mem_image.mpr ⟨j, Finset.mem_univ _, rfl⟩ + · rfl + +theorem dyadicUnskippedGroupEstimate_congr_cover {α : Type*} + (source target : List α) {M b P exponent : ℕ} + (parent : TargetInterval source.length) (tau a : ℚ) (F Q : ℕ) + (parentInitial : TargetInterval target.length → ℚ) + (child initial value value' : Fin M → TargetInterval target.length → ℚ) + (cell : ℕ × ℕ) + (member : UnskippedBand source target parent b P exponent tau F child initial) + (hb : 1 ≤ b) + (hcenter : member.center ∈ cellRepresentativeStates target.length P F b a parentInitial + ((2 : ℚ) ^ (-(exponent : ℤ))) cell) + (draw : ∀ scale : Fin (groupDyadicScales M b F).length, + Fin (groupSampleCount M Q b (groupDyadicScaleAt M b F scale)) → Fin M) + (hvalue : ∀ scale : Fin (groupDyadicScales M b F).length, + ∀ input ∈ groupCurrentInputCover source target parent b exponent Q cell + (groupDyadicScaleAt M b F scale) (draw scale), value input.1 input.2 = value' input.1 input.2) : + dyadicUnskippedGroupEstimate Q value member draw = + dyadicUnskippedGroupEstimate Q value' member draw := by + unfold dyadicUnskippedGroupEstimate unskippedGroupEstimate groupMemberEstimate + congr 1 + apply Finset.sum_congr rfl + intro scale _ + apply groupScaleEstimate_congr_queried + intro i hi henvelope + exact hvalue scale (i, member.rounded i) + (actual_group_input_in_cover source target parent tau a F Q parentInitial child initial cell + member hb hcenter _ (draw scale) i hi henvelope) + +theorem rational_argmax_congr_on {ι : Type*} (members : List ι) (score score' : ι → ℚ) + (hscore : ∀ member ∈ members, score member = score' member) : + members.argmax score = members.argmax score' := by + induction members with + | nil => rfl + | cons first rest ih => + rw [List.argmax_cons, List.argmax_cons, ih (fun member hm => hscore member (by simp [hm]))] + cases hmax : rest.argmax score' with + | none => rfl + | some selected => + have hmem : selected ∈ rest := List.argmax_mem (by rw [hmax]; simp) + dsimp only + rw [hscore first (by simp), hscore selected (by simp [hmem])] + +theorem selectGroupMember_congr_on {ι : Type*} (members : List ι) (hne : members ≠ []) + (estimate estimate' : ι → ℚ) + (heq : ∀ member ∈ members, estimate member = estimate' member) : + selectGroupMember members hne estimate = selectGroupMember members hne estimate' := by + unfold selectGroupMember + rw [rational_argmax_congr_on members (fun member => -estimate member) + (fun member => -estimate' member) (fun member hm => congrArg Neg.neg (heq member hm))] + +theorem chooseCellGroupAction_congr_cover {α : Type*} + (source target : List α) {M b P exponent : ℕ} + (parent : TargetInterval source.length) (tau a : ℚ) (F Q : ℕ) + (parentInitial : TargetInterval target.length → ℚ) + (child initial value value' : Fin M → TargetInterval target.length → ℚ) + (cell : ℕ × ℕ) (hb : 1 ≤ b) + (draw : ∀ scale : Fin (groupDyadicScales M b F).length, + Fin (groupSampleCount M Q b (groupDyadicScaleAt M b F scale)) → Fin M) + (hvalue : ∀ scale : Fin (groupDyadicScales M b F).length, + ∀ input ∈ groupCurrentInputCover source target parent b exponent Q cell + (groupDyadicScaleAt M b F scale) (draw scale), value input.1 input.2 = value' input.1 input.2) : + chooseCellGroupAction source target parent b P F exponent Q tau a parentInitial child initial value cell draw = + chooseCellGroupAction source target parent b P F exponent Q tau a parentInitial child initial value' cell draw := by + let members := cellUnskippedBands source target parent b P F exponent tau a parentInitial child initial cell + change (if hm : members = [] then none else some (chooseUnskippedGroup Q value members hm draw).rationalAction) = + (if hm : members = [] then none else some (chooseUnskippedGroup Q value' members hm draw).rationalAction) + split_ifs with hempty + · rfl + · have hselected : chooseUnskippedGroup Q value members hempty draw = + chooseUnskippedGroup Q value' members hempty draw := by + unfold chooseUnskippedGroup + apply selectGroupMember_congr_on + intro member hm + apply dyadicUnskippedGroupEstimate_congr_cover source target parent tau a F Q parentInitial + child initial value value' cell member hb _ draw hvalue + exact (unskippedBandList_mem_iff _ _).mp hm + exact congrArg (fun member => some member.rationalAction) hselected + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/GroupNumerical.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/GroupNumerical.lean new file mode 100644 index 0000000000000000000000000000000000000000..1bda9e32300e783fe916a7ecc8e8530f91ea07fe --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/GroupNumerical.lean @@ -0,0 +1,87 @@ +import OAI.Combinatorics.EditApproximation.Geometry.Parameters +import OAI.Combinatorics.EditApproximation.Geometry.GroupSampling + +namespace OAI + +/-! Explicit numerical slack for the shared group estimator and online increments. -/ + +namespace EditApproximation + +theorem group_normalized_exponent {ell : ℝ} (hell : 1 ≤ ell) : + ell ^ 37 / 3000 ≤ + ell ^ 80 * (1 / (2 * ell ^ 21)) ^ 2 / + (512 * ell + (4 / 3 : ℝ) * (1 / (2 * ell ^ 21))) := by + have he : 0 < ell := by linarith only [hell] + have halpha : 0 < 1 / (2 * ell ^ 21) := by positivity + have halpha_le : 1 / (2 * ell ^ 21) ≤ ell := by + apply (div_le_iff₀ (by positivity : 0 < 2 * ell ^ 21)).2 + have hpow := one_le_pow₀ hell (n := 21) + nlinarith only [hell, hpow] + have hden : 512 * ell + (4 / 3 : ℝ) * (1 / (2 * ell ^ 21)) ≤ 750 * ell := by + linarith only [halpha_le, hell] + have hnum : ell ^ 80 * (1 / (2 * ell ^ 21)) ^ 2 = ell ^ 38 / 4 := by + field_simp + ring + rw [hnum] + apply (div_le_div_iff₀ (by norm_num : (0 : ℝ) < 3000) + (by positivity : 0 < 512 * ell + (4 / 3 : ℝ) * (1 / (2 * ell ^ 21)))).2 + have h := mul_le_mul_of_nonneg_left hden (pow_nonneg he.le 37) + have hid : ell ^ 37 * (750 * ell) = ell ^ 38 / 4 * 3000 := by ring + exact h.trans_eq hid + +theorem group_exponent_polynomial_slack {ell : ℝ} (hell : 8 ≤ ell) : + 2 * ell ^ 2 + 20 * ell ≤ ell ^ 37 / 3000 := by + have he : 1 ≤ ell := by linarith only [hell] + have hcoef : (131072 : ℝ) ≤ ell ^ 33 := by + have h := pow_le_pow_left₀ (by norm_num : (0 : ℝ) ≤ 8) hell 6 + norm_num at h + exact (by norm_num : (131072 : ℝ) ≤ 262144) |>.trans + (h.trans (pow_le_pow_right₀ he (by decide : 6 ≤ 33))) + have hbig : 131072 * ell ^ 4 ≤ ell ^ 37 := by + calc + _ ≤ ell ^ 33 * ell ^ 4 := mul_le_mul_of_nonneg_right hcoef (pow_nonneg (by linarith only [hell]) 4) + _ = _ := by ring + have he2 : ell ≤ ell ^ 2 := by nlinarith only [he] + have he4 : ell ^ 2 ≤ ell ^ 4 := pow_le_pow_right₀ he (by decide : 2 ≤ 4) + apply (le_div_iff₀ (by norm_num : (0 : ℝ) < 3000)).2 + nlinarith only [hbig, he2, he4] + +/-- The union bound is below H^-4 once its literal count bounds and the +computed height/representative growth bounds have been substituted. -/ +theorem group_union_failure_numeric {ell H members scales : ℝ} + (hell : 8 ≤ ell) (hH : 0 < H) (hHexp : H ≤ Real.exp ell) + (_hmembers : 0 ≤ members) (hmembersBound : members ≤ 4 * Real.exp (2 * ell ^ 2)) + (hscales : 0 ≤ scales) (hscalesBound : scales ≤ 2 * ell) : + members * scales * (2 * Real.exp (-(ell ^ 37 / 3000))) ≤ 1 / H ^ 4 := by + have he : 0 ≤ ell := by linarith only [hell] + have hcounts : members * scales * (2 * Real.exp (-(ell ^ 37 / 3000))) ≤ + 16 * ell * Real.exp (2 * ell ^ 2 - ell ^ 37 / 3000) := by + have h := mul_le_mul hmembersBound hscalesBound hscales (by positivity : 0 ≤ 4 * Real.exp (2 * ell ^ 2)) + have h' := mul_le_mul_of_nonneg_right h (by positivity : 0 ≤ 2 * Real.exp (-(ell ^ 37 / 3000))) + rw [sub_eq_add_neg, Real.exp_add] + convert h' using 1 + ring + have hpower : H ^ 4 ≤ Real.exp (4 * ell) := by + have h := pow_le_pow_left₀ hH.le hHexp 4 + rw [← Real.exp_nat_mul] at h + norm_num only [Nat.cast_ofNat] at h + exact h + apply (le_div_iff₀ (pow_pos hH 4)).2 + have hnonneg : 0 ≤ 16 * ell * Real.exp (2 * ell ^ 2 - ell ^ 37 / 3000) := by positivity + have hprod := mul_le_mul hcounts hpower (pow_nonneg hH.le 4) hnonneg + have hexponent := group_exponent_polynomial_slack hell + have hsmall : 2 * ell ^ 2 - ell ^ 37 / 3000 + 4 * ell ≤ -(16 * ell) := by + linarith only [hexponent] + have hexp := Real.exp_le_exp.mpr hsmall + have hlinear : 16 * ell ≤ Real.exp (16 * ell) := (Real.add_one_le_exp _).trans' (by linarith) + have hfinal : 16 * ell * Real.exp (2 * ell ^ 2 - ell ^ 37 / 3000) * Real.exp (4 * ell) ≤ 1 := by + rw [mul_assoc, ← Real.exp_add] + calc + _ ≤ Real.exp (16 * ell) * Real.exp (-(16 * ell)) := + mul_le_mul hlinear hexp (Real.exp_nonneg _) (Real.exp_nonneg _) + _ = 1 := by rw [← Real.exp_add]; simp only [add_neg_cancel, Real.exp_zero] + exact hprod.trans hfinal + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/GroupSampling.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/GroupSampling.lean new file mode 100644 index 0000000000000000000000000000000000000000..75d9b2212068501b1c81fe4526c5aef3086db0d6 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/GroupSampling.lean @@ -0,0 +1,165 @@ +import OAI.Combinatorics.EditApproximation.Probability.FiniteSampling + +namespace OAI + +/-! +# Shared group sampling + +The one-scale estimator in Section 5 is a finite uniform average. Its +concentration follows from the explicitly cited Bernstein input. Choosing +among representatives and extending their costs by cones is deterministic +on the simultaneous approximation event, even when their samples are shared. +-/ + +namespace EditApproximation + +open Finset MeasureTheory ProbabilityTheory + +noncomputable def normalizedChildSample {M : ℕ} (b h : ℝ) + (childScale childValue : Fin M → ℝ) (i : Fin M) : ℝ := + if childScale i = h then (M : ℝ) * childValue i / b else 0 + +/-- The normalized sample bounds used by the executable group estimator +follow from the rounded action's child bounds and the band sum guard. -/ +theorem normalizedChildSample_moments {M : ℕ} (hM : 0 < M) + (b h F : ℝ) (hb : 0 < b) (hh : 0 < h) + (childScale childValue : Fin M → ℝ) + (hscale : ∀ i, 0 ≤ childScale i) + (hvalue : ∀ i, 0 ≤ childValue i ∧ childValue i ≤ 2 * childScale i) + (hsum : (∑ i, childScale i) ≤ 64 * F * b) : + (∀ i, 0 ≤ normalizedChildSample b h childScale childValue i ∧ + normalizedChildSample b h childScale childValue i ≤ 2 * ((M : ℝ) * h / b)) ∧ + uniformMean (normalizedChildSample b h childScale childValue) ≤ 128 * F := by + have hMr : (0 : ℝ) < M := by exact_mod_cast hM + have hpoint (i : Fin M) : normalizedChildSample b h childScale childValue i ≤ + (M : ℝ) / b * (2 * childScale i) := by + unfold normalizedChildSample + split_ifs + · have hmul := mul_le_mul_of_nonneg_left (hvalue i).2 (div_nonneg hMr.le hb.le) + convert hmul using 1 + ring + · exact mul_nonneg (div_nonneg hMr.le hb.le) + (mul_nonneg (by norm_num) (hscale i)) + constructor + · intro i + unfold normalizedChildSample + split_ifs with hi + · constructor + · exact div_nonneg (mul_nonneg hMr.le (hvalue i).1) hb.le + · have hmul := mul_le_mul_of_nonneg_left (hvalue i).2 hMr.le + rw [hi] at hmul + calc + _ ≤ (2 * ((M : ℝ) * h)) / b := + div_le_div_of_nonneg_right (by nlinarith : + (M : ℝ) * childValue i ≤ 2 * ((M : ℝ) * h)) hb.le + _ = _ := by ring + · constructor + · rfl + · positivity + · unfold uniformMean + rw [Fintype.card_fin] + apply (div_le_iff₀ hMr).2 + have hsumPoint := sum_le_sum (s := univ) fun i _ => hpoint i + rw [← mul_sum, ← mul_sum] at hsumPoint + have hscaled := mul_le_mul_of_nonneg_left hsum (by positivity : 0 ≤ 2 * M / b) + have hid : (M : ℝ) / b * (2 * ∑ i, childScale i) = + (2 * M / b) * ∑ i, childScale i := by ring + rw [hid] at hsumPoint + have hcancel : (2 * M / b) * (64 * F * b) = 128 * F * M := by field_simp; ring + rw [hcancel] at hscaled + linarith + +theorem group_bernstein_exponent {ratio F Q deviation : ℝ} {n : ℕ} + (hratio : 0 < ratio) (hF : 0 < F) (hdev : 0 < deviation) + (hsamples : Q * ratio ≤ n) : + Q * deviation ^ 2 / (512 * F + (4 / 3 : ℝ) * deviation) ≤ + (n : ℝ) * deviation ^ 2 / + (2 * (2 * ratio) * (128 * F) + (2 / 3 : ℝ) * (2 * ratio) * deviation) := by + let den := 512 * F + (4 / 3 : ℝ) * deviation + have hden : 0 < den := by dsimp [den]; positivity + have hid : 2 * (2 * ratio) * (128 * F) + (2 / 3 : ℝ) * (2 * ratio) * deviation = + ratio * den := by dsimp [den]; ring + rw [hid] + apply (div_le_div_iff₀ hden (mul_pos hratio hden)).2 + have hmul := mul_le_mul_of_nonneg_right hsamples + (mul_nonneg (sq_nonneg deviation) hden.le) + nlinarith + +theorem group_scale_concentration {ι : Type*} [Fintype ι] [Nonempty ι] + [MeasurableSpace ι] [MeasurableSingletonClass ι] + (n : ℕ) (hn : 0 < n) (value : ι → ℝ) (ratio F Q deviation : ℝ) + (hratio : 0 < ratio) (hF : 0 < F) (hdev : 0 < deviation) + (hvalue : ∀ i, 0 ≤ value i ∧ value i ≤ 2 * ratio) + (hmean : uniformMean value ≤ 128 * F) (hsamples : Q * ratio ≤ n) + (bernstein : FiniteBernsteinInput + (Measure.pi fun _ : Fin n => (PMF.uniformOfFintype ι).toMeasure)) : + (Measure.pi fun _ : Fin n => (PMF.uniformOfFintype ι).toMeasure).real + {ω | deviation ≤ |(∑ j : Fin n, value (ω j)) / n - uniformMean value|} ≤ + 2 * Real.exp (-Q * deviation ^ 2 / (512 * F + (4 / 3 : ℝ) * deviation)) := by + have htail := uniform_sample_average_concentration n hn value + (2 * ratio) (128 * F) deviation (by positivity) (by positivity) hdev + hvalue hmean bernstein + apply htail.trans + apply mul_le_mul_of_nonneg_left _ (by norm_num) + apply Real.exp_le_exp.mpr + simpa only [neg_div, neg_mul] using + neg_le_neg (group_bernstein_exponent hratio hF hdev hsamples) + +/-- Shared draws may correlate all representatives. The simultaneous +event uses only finite subadditivity. -/ +theorem group_failure_union_bound {Ω ι κ : Type*} [MeasurableSpace Ω] + (μ : Measure Ω) [IsFiniteMeasure μ] (members : Finset ι) (scales : Finset κ) + (bad : ι → κ → Set Ω) (failure : ℝ) + (hfailure : ∀ i ∈ members, ∀ h ∈ scales, μ.real (bad i h) ≤ failure) : + μ.real (⋃ i ∈ members, ⋃ h ∈ scales, bad i h) ≤ + (members.card : ℝ) * scales.card * failure := by + apply (measureReal_biUnion_finset_le members _).trans + have hmember (i : ι) (hi : i ∈ members) : + μ.real (⋃ h ∈ scales, bad i h) ≤ (scales.card : ℝ) * failure := by + apply (measureReal_biUnion_finset_le scales _).trans + have hsum := sum_le_sum (s := scales) fun h hh => hfailure i hi h hh + simpa only [sum_const, nsmul_eq_mul] using hsum + have hsum := sum_le_sum hmember + simpa only [sum_const, nsmul_eq_mul, mul_assoc] using hsum + +theorem group_scale_errors_sum {κ : Type*} (scales : Finset κ) + (estimate cost : κ → ℝ) (deviation : ℝ) + (herror : ∀ h ∈ scales, |estimate h - cost h| ≤ deviation) : + |(∑ h ∈ scales, estimate h) - (∑ h ∈ scales, cost h)| ≤ + (scales.card : ℝ) * deviation := by + rw [← sum_sub_distrib] + apply (abs_sum_le_sum_abs _ _).trans + have hsum := sum_le_sum herror + simpa only [sum_const, nsmul_eq_mul] using hsum + +/-- Estimated-cost minimization followed by actual evaluation loses at +most twice the uniform estimation error. There is no probabilistic +independence premise in this selection step. -/ +theorem selected_group_cost_le {ι : Type*} (members : Finset ι) + (cost estimate : ι → ℝ) (selected specified : ι) (error : ℝ) + (hselected : selected ∈ members) (hspecified : specified ∈ members) + (haccurate : ∀ i ∈ members, |estimate i - cost i| ≤ error) + (hmin : estimate selected ≤ estimate specified) : + cost selected ≤ cost specified + 2 * error := by + have hs := (abs_le.mp (haccurate selected hselected)).1 + have hr := (abs_le.mp (haccurate specified hspecified)).2 + linarith + +theorem selected_group_cone_bound {ι : Type*} (members : Finset ι) + (cost estimate distance : ι → ℝ) (selected specified : ι) + (cone L radius error roundedAction : ℝ) + (hselected : selected ∈ members) (hspecified : specified ∈ members) + (haccurate : ∀ i ∈ members, |estimate i - cost i| ≤ error) + (hmin : estimate selected ≤ estimate specified) + (hcone : cone ≤ cost selected + L * distance selected) + (hL : 0 ≤ L) (hcell : distance selected ≤ distance specified + radius) + (hrounded : cost specified ≤ roundedAction) : + cone ≤ L * distance specified + roundedAction + 2 * error + L * radius := by + have hcost := selected_group_cost_le members cost estimate selected specified error + hselected hspecified haccurate hmin + have hdist := mul_le_mul_of_nonneg_left hcell hL + linarith + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/GroupSamplingWork.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/GroupSamplingWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..afb6553b8c4068b5e34395bc8d1ef6d04ee172e3 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/GroupSamplingWork.lean @@ -0,0 +1,57 @@ +import OAI.Combinatorics.EditApproximation.Geometry.BandGroupSampling + +namespace OAI + +/-! The shared group samples cancel the reciprocal envelope factor in +the number of possible rounded child inputs, including exact evaluation. -/ + +namespace EditApproximation + +theorem groupSampleCount_shared_work {M Q b : ℕ} {h : ℚ} + (hM : 0 < M) (hQ : 1 ≤ Q) (hb : 0 < b) (hh : 0 < h) + (hfloor : (b : ℚ) / M ≤ h) : + (groupSampleCount M Q b h : ℚ) * (1 + b / h) ≤ 3 * Q * M := by + have hMr : (0 : ℚ) < M := by exact_mod_cast hM + have hQr : (1 : ℚ) ≤ Q := by exact_mod_cast hQ + have hbr : (0 : ℚ) < b := by exact_mod_cast hb + have hMh : (b : ℚ) ≤ M * h := by + nlinarith only [(div_le_iff₀ hMr).mp hfloor] + have hQproduct := mul_le_mul_of_nonneg_right hQr (show (0 : ℚ) ≤ M * h by positivity) + have hx : (1 : ℚ) ≤ Q * M * h / b := by + apply (le_div_iff₀ hbr).2 + nlinarith only [hMh, hQproduct] + have hceil : (⌈(Q : ℚ) * M * h / b⌉₊ : ℚ) < (Q : ℚ) * M * h / b + 1 := + Nat.ceil_lt_add_one (by positivity) + have hkM : (groupSampleCount M Q b h : ℚ) ≤ M := by + unfold groupSampleCount + exact_mod_cast (min_le_left M ⌈(Q : ℚ) * M * h / b⌉₊) + have hkceil : (groupSampleCount M Q b h : ℚ) ≤ ⌈(Q : ℚ) * M * h / b⌉₊ := by + unfold groupSampleCount + exact_mod_cast (min_le_right M ⌈(Q : ℚ) * M * h / b⌉₊) + have hkX : (groupSampleCount M Q b h : ℚ) ≤ 2 * ((Q : ℚ) * M * h / b) := by + linarith only [hkceil, hceil, hx] + have hkb : (groupSampleCount M Q b h : ℚ) * b ≤ 2 * Q * M * h := by + apply (le_div_iff₀ hbr).mp + convert hkX using 1 + ring + have hreciprocal : (groupSampleCount M Q b h : ℚ) * b / h ≤ 2 * Q * M := + (div_le_iff₀ hh).2 hkb + have hQM := mul_le_mul_of_nonneg_right hQr hMr.le + calc + _ = (groupSampleCount M Q b h : ℚ) + (groupSampleCount M Q b h : ℚ) * b / h := by ring + _ ≤ (M : ℚ) + 2 * Q * M := add_le_add hkM hreciprocal + _ ≤ 3 * Q * M := by nlinarith only [hQM] + +theorem groupDyadicScale_shared_work {M Q b : ℕ} {F h : ℚ} + (hM : 0 < M) (hQ : 1 ≤ Q) (hb : 0 < b) (hF : 0 < F) + (hh : h ∈ groupDyadicScales M b F) : + (groupSampleCount M Q b h : ℚ) * (1 + b / h) ≤ 3 * Q * M := by + have hpos := groupDyadicScales_pos hh + obtain ⟨exponent, hexponent, heq⟩ := List.mem_map.mp hh + have hbounds := (groupDyadicScales_mem hM hb F hF exponent).mp + (List.mem_map.mpr ⟨exponent, hexponent, rfl⟩) + exact groupSampleCount_shared_work hM hQ hb hpos (heq ▸ hbounds.1) + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/GroupSmallConstants.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/GroupSmallConstants.lean new file mode 100644 index 0000000000000000000000000000000000000000..a1cb11da43fd724e4ce204e10b0f8393edcaae7a --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/GroupSmallConstants.lean @@ -0,0 +1,64 @@ +import OAI.Combinatorics.EditApproximation.Geometry.Parameters + +namespace OAI + +/-! The prescribed small parameters satisfy the group and online error inequalities. -/ + +namespace EditApproximation + +theorem group_online_range_small {ell : ℚ} (hell : 8 ≤ ell) : + 8 * (128 * ell) * (1 / ell ^ 40) ≤ 1 / ell ^ 10 := by + have he : 1 ≤ ell := by linarith only [hell] + have he0 : 0 < ell := by linarith only [hell] + have hcoef : (1024 : ℚ) ≤ ell ^ 29 := by + have h := pow_le_pow_left₀ (by norm_num : (0 : ℚ) ≤ 8) hell 4 + norm_num at h + exact (by norm_num : (1024 : ℚ) ≤ 4096) |>.trans + (h.trans (pow_le_pow_right₀ he (by decide : 4 ≤ 29))) + rw [mul_one_div] + apply (div_le_div_iff₀ (pow_pos he0 40) (pow_pos he0 10)).2 + have h := mul_le_mul_of_nonneg_right hcoef (pow_nonneg he0.le 11) + convert h using 1 <;> ring + +theorem group_online_eta_range {ell : ℚ} (hell : 3 ≤ ell) : + ell ^ 5 * (3 * (1 / ell ^ 10)) ≤ 1 / ell ^ 4 := by + have he0 : 0 < ell := by linarith only [hell] + have h := mul_le_mul_of_nonneg_right hell (pow_nonneg he0.le 9) + have hmul : ell ^ 5 * (3 * (1 / ell ^ 10)) = 3 * ell ^ 5 / ell ^ 10 := by ring + rw [hmul] + apply (div_le_div_iff₀ (pow_pos he0 10) (pow_pos he0 4)).2 + convert h using 1 <;> ring + +theorem group_rounded_error_small {ell : ℚ} (hell : 8 ≤ ell) : + 2 * (1 / ell ^ 20) + 512 * (128 * ell) * ell * (1 / ell ^ 40) ≤ + (1 / ell ^ 4) * (1 / ell ^ 10) := by + have he : 1 ≤ ell := by linarith only [hell] + have he0 : 0 < ell := by linarith only [hell] + have hcoef1 : (4 : ℚ) ≤ ell ^ 6 := by + exact (by norm_num : (4 : ℚ) ≤ 8).trans + (hell.trans (by simpa only [pow_one] using pow_le_pow_right₀ he (by decide : 1 ≤ 6))) + have hcoef2 : (131072 : ℚ) ≤ ell ^ 24 := by + have h := pow_le_pow_left₀ (by norm_num : (0 : ℚ) ≤ 8) hell 6 + norm_num at h + exact (by norm_num : (131072 : ℚ) ≤ 262144) |>.trans + (h.trans (pow_le_pow_right₀ he (by decide : 6 ≤ 24))) + have hfirst : 2 / ell ^ 20 ≤ 1 / (2 * ell ^ 14) := by + apply (div_le_div_iff₀ (pow_pos he0 20) (by positivity : 0 < 2 * ell ^ 14)).2 + have h := mul_le_mul_of_nonneg_right hcoef1 (pow_nonneg he0.le 14) + convert h using 1 <;> ring + have hsecond : 65536 * ell ^ 2 / ell ^ 40 ≤ 1 / (2 * ell ^ 14) := by + apply (div_le_div_iff₀ (pow_pos he0 40) (by positivity : 0 < 2 * ell ^ 14)).2 + have h := mul_le_mul_of_nonneg_right hcoef2 (pow_nonneg he0.le 16) + convert h using 1 <;> ring + have hid : (1 / ell ^ 4) * (1 / ell ^ 10) = 2 * (1 / (2 * ell ^ 14)) := by + field_simp + rw [hid] + have hid2 : 512 * (128 * ell) * ell * (1 / ell ^ 40) = 65536 * ell ^ 2 / ell ^ 40 := by ring + rw [hid2] + have hid1 : 2 * (1 / ell ^ 20) = 2 / ell ^ 20 := by ring + rw [hid1] + simpa only [two_mul] using add_le_add hfirst hsecond + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/HeightPowerWork.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/HeightPowerWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..09a6ad602b6ff599c7ecaf0047bc34a3d1facc74 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/HeightPowerWork.lean @@ -0,0 +1,23 @@ +import OAI.Combinatorics.EditApproximation.Binary.IntegerPreprocessing + +namespace OAI + +namespace EditApproximation +open Filter +open scoped Topology + + theorem fixed_height_power_subpolynomial (k : ℕ) (epsilon : ℝ) (hepsilon : 0 < epsilon) : + ∀ᶠ N : ℕ in atTop, (inputHeight N : ℝ) ^ k ≤ (N + 2 : ℝ) ^ epsilon := by + have hlog : Tendsto (fun N : ℕ => Real.log (inputHeight N : ℝ) / inputHeight N) + atTop (𝓝 0) := + Real.isLittleO_log_id_atTop.tendsto_div_nhds_zero.comp inputHeight_real_tendsto + have hlimit := hlog.const_mul (k : ℝ) + simp only [mul_zero] at hlimit + have hf : Tendsto (fun N => ((k : ℝ) * Real.log (inputHeight N : ℝ)) / inputHeight N) + atTop (𝓝 0) := by convert hlimit using 1; ext N; ring + filter_upwards [subexponential_height_to_input _ hf epsilon hepsilon] with N hN + rwa [← nat_pow_eq_exp_log (inputHeight N) k (Nat.two_pow_pos _)] at hN + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/IndexedTerminalWork.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/IndexedTerminalWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..44b7163545ded2ea4185abec10816078a810f9b4 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/IndexedTerminalWork.lean @@ -0,0 +1,64 @@ +import OAI.Combinatorics.EditApproximation.Binary.IntegerPreprocessing +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation +open Filter + +/-- Empty and singleton terminal states use the already prepared occurrence +index. Endpoints are read directly; no target substring is copied. -/ + + + theorem indexedLeafWithWork_value (table : BinaryMemo PositionCounts) (symbolBits positionBits : ℕ) + (symbol : Option ℕ) (lo hi : ℕ) : + (indexedLeafWithWork table symbolBits positionBits symbol lo hi).1 = + indexedLeafCost table symbolBits positionBits symbol lo hi := by + cases symbol with + | none => rfl + | some a => exact (indexedSingletonCostWithWork_spec table symbolBits positionBits a lo hi).1 + + theorem indexedLeafWithWork_cost (table : BinaryMemo PositionCounts) (symbolBits positionBits : ℕ) + (symbol : Option ℕ) (lo hi : ℕ) : + (indexedLeafWithWork table symbolBits positionBits symbol lo hi).2 ≤ + 2 * symbolBits + 4 * positionBits + 10 := by + cases symbol with + | none => change 2 ≤ _; omega + | some a => exact (indexedSingletonCostWithWork_spec table symbolBits positionBits a lo hi).2.trans (by omega) + + theorem indexedLeafWithWork_exact (symbolBits positionBits : ℕ) (source target : List ℕ) + (hsource : ∀ a ∈ source, a < 2 ^ symbolBits) + (htarget : ∀ a ∈ target, a < 2 ^ symbolBits) (hposition : target.length ≤ 2 ^ positionBits) + (lo hi : ℕ) (hlo : lo ≤ hi) (hhi : hi ≤ target.length) (hleaf : source.length ≤ 1) : + (indexedLeafWithWork (occurrenceBuild symbolBits positionBits target.zipIdx) + symbolBits positionBits source.head? lo hi).1 = + EditDistortion.edit source (substring target lo hi) := by + rw [indexedLeafWithWork_value] + exact indexedLeafCost_exact symbolBits positionBits source target hsource htarget hposition lo hi hlo hhi hleaf + + theorem integerIndexedLeafWithWork_cost (C : ℕ) : + ∀ᶠ N : ℕ in atTop, ∀ source target : List ℤ, source.length + target.length ≤ N → + (∀ z ∈ source ++ target, z.natAbs ≤ (N + 2) ^ C) → + ∀ symbol lo hi, + (indexedLeafWithWork (integerOccurrenceIndex source target) (integerInputSymbolBits source target) + (integerInputPositionBits target) symbol lo hi).2 ≤ inputHeight N ^ 3 := by + filter_upwards [inputHeight_real_tendsto.eventually (eventually_ge_atTop ((max 100 C : ℕ) : ℝ))] with N hH + have hH' : max 100 C ≤ inputHeight N := by exact_mod_cast hH + intro source target hsize halphabet symbol lo hi + have hs := integerInputSymbolBits_polynomial source target N C halphabet + have hp : integerInputPositionBits target ≤ Nat.size (N + 2) := Nat.size_le_size (by omega) + have hn := input_length_bits_le N + have hc := indexedLeafWithWork_cost (integerOccurrenceIndex source target) + (integerInputSymbolBits source target) (integerInputPositionBits target) symbol lo hi + have hCH : C * Nat.size (N + 2) ≤ inputHeight N * (inputHeight N + 1) := + Nat.mul_le_mul (by omega) hn + have h100 : 100 ≤ inputHeight N := by omega + have hcube : 100 * inputHeight N ^ 2 ≤ inputHeight N ^ 3 := by + have h := Nat.mul_le_mul_right (inputHeight N ^ 2) (show 100 ≤ inputHeight N by omega) + nlinarith only [h] + nlinarith only [hc, hs, hp, hn, hCH, hcube, h100] + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/InitialConeGrid.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/InitialConeGrid.lean new file mode 100644 index 0000000000000000000000000000000000000000..4b3a137e900737452326c31029adf0cea36857a2 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/InitialConeGrid.lean @@ -0,0 +1,127 @@ +import OAI.Combinatorics.EditApproximation.Geometry.InitialCones +import OAI.Combinatorics.EditApproximation.Geometry.Grid +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! +# A rounded eligible center for each positive-cost query + +This uses the actual natural division grid and the dyadic scale selected +from the integer edit cost. It supplies a finite-family witness for the +initial cone minimum. +-/ + +namespace EditApproximation + + + + + +theorem cost_dyadicScale (c N : ℕ) (hc : 0 < c) (hcN : c ≤ N) : + let b := 2 ^ Nat.log 2 c + b ∈ dyadicScales N ∧ b ≤ c ∧ c < 2 * b := by + dsimp only + refine ⟨?_, Nat.pow_log_le_self 2 hc.ne', ?_⟩ + · apply List.mem_map.mpr + refine ⟨Nat.log 2 c, List.mem_range.mpr ?_, rfl⟩ + exact Nat.lt_succ_of_le (Nat.log_mono_right hcN) + · have h := Nat.lt_pow_succ_log_self (by decide : 1 < 2) c + simpa only [pow_succ, mul_comm] using h + +theorem rounded_seedGrid_error {n : ℕ} (b P : ℕ) (hP : 0 < P) + (q : TargetInterval n) : + (targetEndpointDistance q (roundInterval (seedGridSpacing b P) q) : ℚ) * P ≤ 2 * b := by + by_cases hg : b / P ≤ 1 + · have he : targetEndpointDistance q (roundInterval (seedGridSpacing b P) q) = 0 := by + simp [targetEndpointDistance, roundInterval, seedGridSpacing, max_eq_left hg] + rw [he] + simp only [Nat.cast_zero, zero_mul] + positivity + · have hquot : 1 ≤ b / P := by omega + have he := roundInterval_error (b / P) (by omega) q + have hdiv := Nat.div_mul_le_self b P + have hprod : targetEndpointDistance q (roundInterval (seedGridSpacing b P) q) * P ≤ 2 * b := by + unfold seedGridSpacing + rw [max_eq_right hquot] + change (Nat.dist q.lo (roundInterval (b / P) q).lo + + Nat.dist q.hi (roundInterval (b / P) q).hi) * P ≤ 2 * b + nlinarith + exact_mod_cast hprod + +theorem roundInterval_on_grid {n : ℕ} (g : ℕ) (q : TargetInterval n) : + g ∣ (roundInterval g q).lo ∧ g ∣ (roundInterval g q).hi := by + exact ⟨dvd_mul_right _ _, dvd_mul_right _ _⟩ + +theorem rounded_initial_center_numeric {c cr Ur b P A F e : ℚ} + (hb : 0 < b) (hbc : b ≤ c) (hcb : c < 2 * b) + (hP : 66 ≤ P) (hA : 1 ≤ A) (hF : 0 ≤ F) (he : 0 ≤ e) + (hgrid : e * P ≤ 2 * b) (hcost : |c - cr| ≤ e) + (hseed : cr ≤ Ur ∧ Ur ≤ A * cr) : + b / 2 ≤ Ur ∧ Ur ≤ 4 * A * b ∧ F * cr + 32 * F * e ≤ 2 * F * c := by + have hcosts := abs_le.mp hcost + have hsmall : 33 * e ≤ b := by nlinarith + have hcrlo : b / 2 ≤ cr := by linarith + have hcrhi : cr ≤ 4 * b := by linarith + have hscaled := mul_le_mul_of_nonneg_left hcrhi (by linarith : 0 ≤ A) + have hcone := mul_le_mul_of_nonneg_left (show cr + 32 * e ≤ 2 * c by linarith) hF + exact ⟨hcrlo.trans hseed.1, hseed.2.trans (by nlinarith), by nlinarith⟩ + +theorem stateEditCost_distance_abs {α : Type*} (source target : List α) + (q r : TargetInterval target.length) : + |(stateEditCost source target q : ℚ) - stateEditCost source target r| ≤ + targetEndpointDistance q r := by + have hqr : (stateEditCost source target q : ℚ) ≤ + stateEditCost source target r + targetEndpointDistance q r := by + exact_mod_cast stateEditCost_spatial source target q r + have hrq : (stateEditCost source target r : ℚ) ≤ + stateEditCost source target q + targetEndpointDistance q r := by + have h := stateEditCost_spatial source target r q + simpa only [targetEndpointDistance, Nat.dist_comm] using (show + (stateEditCost source target r : ℚ) ≤ stateEditCost source target q + + targetEndpointDistance r q by exact_mod_cast h) + exact abs_le.mpr ⟨by linarith, by linarith⟩ + +theorem rounded_initial_cone_witness {α : Type*} (source target : List α) + (U : TargetInterval target.length → ℕ) (N P F : ℕ) (A a : ℚ) + (q : TargetInterval target.length) (hcost : 0 < stateEditCost source target q) + (hN : stateEditCost source target q ≤ N) (hP : 66 ≤ P) (hF : 1 ≤ F) + (hA : 1 ≤ A) (ha : 1 ≤ a) + (hseed : ∀ r, stateEditCost source target r ≤ U r ∧ + (U r : ℚ) ≤ A * stateEditCost source target r) + (hfactor : A ≤ a * F) : + ∃ b ∈ dyadicScales N, ∃ r : TargetInterval target.length, + seedGridSpacing b P ∣ r.lo ∧ seedGridSpacing b P ∣ r.hi ∧ + (b : ℚ) / 2 ≤ U r ∧ (U r : ℚ) ≤ 4 * A * b ∧ + initialConeValue source target U a (32 * F) q r ≤ + 2 * F * stateEditCost source target q := by + let c := stateEditCost source target q + let b := 2 ^ Nat.log 2 c + let r := roundInterval (seedGridSpacing b P) q + have hscale := cost_dyadicScale c N hcost hN + have he := rounded_seedGrid_error b P (by omega) q + have hnumeric := rounded_initial_center_numeric + (c := (c : ℚ)) (cr := stateEditCost source target r) (Ur := U r) + (b := (b : ℚ)) (P := (P : ℚ)) (A := A) (F := (F : ℚ)) + (e := targetEndpointDistance q r) + (by dsimp only [b]; positivity) (by exact_mod_cast hscale.2.1) + (by exact_mod_cast hscale.2.2) (by exact_mod_cast hP) hA (Nat.cast_nonneg _) + (Nat.cast_nonneg _) he (stateEditCost_distance_abs source target q r) + ⟨by exact_mod_cast (hseed r).1, (hseed r).2⟩ + have hgap : |rationalStateGap source target r| ≤ (stateEditCost source target r : ℚ) := by + have h := stateEditCost_length_lower source target r + rw [← rationalStateGap_cast] at h + exact_mod_cast h + have hupper : (U r : ℚ) ≤ a * F * stateEditCost source target r := + (hseed r).2.trans (mul_le_mul_of_nonneg_right hfactor (Nat.cast_nonneg _)) + have hscaled := (scaledSeedValue_bounds (U r) (stateEditCost source target r) + F a _ ha hF (hseed r).1 hupper hgap).2 + refine ⟨b, hscale.1, r, (roundInterval_on_grid _ q).1, + (roundInterval_on_grid _ q).2, hnumeric.1, hnumeric.2.1, ?_⟩ + unfold initialConeValue + linarith [hnumeric.2.2] + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/InitialConeTable.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/InitialConeTable.lean new file mode 100644 index 0000000000000000000000000000000000000000..a9acbe1ab4add63ef78c2b28f843f89cbbf8aa6d --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/InitialConeTable.lean @@ -0,0 +1,152 @@ +import OAI.Combinatorics.EditApproximation.Geometry.InitialConeGrid + +namespace OAI + +/-! +# The finite global initial-cone table + +Every center is a valid target state. The family includes the zero seed +centers and precisely the eligible grid centers at the finite dyadic scales. +The constant fallback is above a witnessed cone on a good seed. +-/ + +namespace EditApproximation + +def initialConeCenters {n : ℕ} (N P : ℕ) (A : ℚ) (U : TargetInterval n → ℕ) : + List (TargetInterval n) := + (targetStates n).filter (fun r => decide (U r = 0)) ++ + (dyadicScales N).flatMap (fun b => + (targetStates n).filter (fun r => decide + (seedGridSpacing b P ∣ r.lo ∧ seedGridSpacing b P ∣ r.hi ∧ + (b : ℚ) / 2 ≤ U r ∧ (U r : ℚ) ≤ 4 * A * b))) + +def globalInitialConeTable {α : Type*} (source target : List α) + (U : TargetInterval target.length → ℕ) (N P F : ℕ) (A a : ℚ) + (q : TargetInterval target.length) : ℚ := + rationalMinimum ((32 * F + 1) * N) + ((initialConeCenters N P A U).map (initialConeValue source target U a (32 * F) q)) + +theorem rationalMinimum_le_member (fallback : ℚ) (values : List ℚ) + {v : ℚ} (hv : v ∈ values) : rationalMinimum fallback values ≤ v := by + induction values with + | nil => simp at hv + | cons x rest ih => + rcases List.mem_cons.mp hv with rfl | hrest + · exact min_le_left _ _ + · exact (min_le_right _ _).trans (ih hrest) + +theorem le_rationalMinimum_iff (lower fallback : ℚ) (values : List ℚ) : + lower ≤ rationalMinimum fallback values ↔ lower ≤ fallback ∧ ∀ v ∈ values, lower ≤ v := by + induction values with + | nil => simp [rationalMinimum] + | cons v rest ih => + simp only [rationalMinimum, le_min_iff, ih, List.mem_cons, forall_eq_or_imp] + tauto + +theorem initialConeCenters_mem_zero {n N P : ℕ} {A : ℚ} (U : TargetInterval n → ℕ) + (r : TargetInterval n) (hzero : U r = 0) : r ∈ initialConeCenters N P A U := by + apply List.mem_append_left + exact List.mem_filter.mpr ⟨targetStates_complete n r, by simpa using hzero⟩ + +theorem initialConeCenters_mem_grid {n N P b : ℕ} {A : ℚ} + (U : TargetInterval n → ℕ) (r : TargetInterval n) (hb : b ∈ dyadicScales N) + (hr : seedGridSpacing b P ∣ r.lo ∧ seedGridSpacing b P ∣ r.hi ∧ + (b : ℚ) / 2 ≤ U r ∧ (U r : ℚ) ≤ 4 * A * b) : + r ∈ initialConeCenters N P A U := by + apply List.mem_append_right + exact List.mem_flatMap.mpr ⟨b, hb, + List.mem_filter.mpr ⟨targetStates_complete n r, by simpa using hr⟩⟩ + +theorem globalInitialConeTable_bounds {α : Type*} (source target : List α) + (U : TargetInterval target.length → ℕ) (N P F : ℕ) (A a : ℚ) + (hP : 66 ≤ P) (hF : 1 ≤ F) (hA : 1 ≤ A) (ha : 1 ≤ a) + (hfactor : A ≤ a * F) + (hcostN : ∀ r, stateEditCost source target r ≤ N) + (hseed : ∀ r, stateEditCost source target r ≤ U r ∧ + (U r : ℚ) ≤ A * stateEditCost source target r) + (q : TargetInterval target.length) : + max ((stateEditCost source target q : ℚ) / a) |rationalStateGap source target q| ≤ + globalInitialConeTable source target U N P F A a q ∧ + globalInitialConeTable source target U N P F A a q ≤ + 2 * F * stateEditCost source target q := by + have hFQ : (1 : ℚ) ≤ F := by exact_mod_cast hF + have hgap : |rationalStateGap source target q| ≤ (stateEditCost source target q : ℚ) := by + have h := stateEditCost_length_lower source target q + rw [← rationalStateGap_cast] at h + exact_mod_cast h + have hcost : (stateEditCost source target q : ℚ) ≤ N := by exact_mod_cast hcostN q + have hN : (0 : ℚ) ≤ N := Nat.cast_nonneg _ + constructor + · apply (le_rationalMinimum_iff _ _ _).2 + constructor + · have hdiv : (stateEditCost source target q : ℚ) / a ≤ stateEditCost source target q := by + apply (div_le_iff₀ (by linarith : 0 < a)).2 + have hc0 : (0 : ℚ) ≤ stateEditCost source target q := Nat.cast_nonneg _ + nlinarith + apply max_le <;> nlinarith + · intro v hv + obtain ⟨r, hr, rfl⟩ := List.mem_map.mp hv + exact initialConeValue_actual_lower source target U a (32 * F) q r ha + (by linarith) (hseed r).1 + · by_cases hc : stateEditCost source target q = 0 + · have hU : U q = 0 := by + have h := (hseed q).2 + rw [hc, Nat.cast_zero, mul_zero] at h + exact_mod_cast (le_antisymm h (Nat.cast_nonneg _)) + have hgap0 : rationalStateGap source target q = 0 := by + rw [hc, Nat.cast_zero] at hgap + exact abs_eq_zero.mp (le_antisymm hgap (abs_nonneg _)) + have hmem := initialConeCenters_mem_zero (N := N) (P := P) (A := A) U q hU + have hvalue := rationalMinimum_le_member ((32 * F + 1) * N) + ((initialConeCenters N P A U).map (initialConeValue source target U a (32 * F) q)) + (List.mem_map.mpr ⟨q, hmem, rfl⟩) + simpa only [globalInitialConeTable, initialConeValue, hU, hgap0, + scaledSeedValue_zero, targetEndpointDistance, Nat.dist_self, zero_add, + Nat.cast_zero, mul_zero, add_zero, hc] using hvalue + · obtain ⟨b, hb, r, hgridLo, hgridHi, hlow, hupp, hcone⟩ := + rounded_initial_cone_witness source target U N P F A a q (by omega) + (hcostN q) hP hF hA ha hseed hfactor + have hmem := initialConeCenters_mem_grid U r hb ⟨hgridLo, hgridHi, hlow, hupp⟩ + exact (rationalMinimum_le_member _ _ (List.mem_map.mpr ⟨r, hmem, rfl⟩)).trans hcone + +theorem targetEndpointDistance_triangle {n : ℕ} (q q' r : TargetInterval n) : + targetEndpointDistance q r ≤ targetEndpointDistance q' r + targetEndpointDistance q q' := by + unfold targetEndpointDistance Nat.dist + omega + +theorem globalInitialConeTable_spatial {α : Type*} (source target : List α) + (U : TargetInterval target.length → ℕ) (N P F : ℕ) (A a : ℚ) + (q q' : TargetInterval target.length) : + globalInitialConeTable source target U N P F A a q ≤ + globalInitialConeTable source target U N P F A a q' + + (32 * F : ℚ) * targetEndpointDistance q q' := by + have hcast (query : TargetInterval target.length) : + (globalInitialConeTable source target U N P F A a query : ℝ) = + finiteMinimum (((32 * F + 1) * N : ℚ) : ℝ) + ((initialConeCenters N P A U).map + fun r => (initialConeValue source target U a (32 * F) query r : ℝ)) := by + rw [globalInitialConeTable, rationalMinimum_cast] + simp only [List.map_map, Function.comp_def] + have h := finiteMinimum_map_spatial (initialConeCenters N P A U) + (((32 * F + 1) * N : ℚ) : ℝ) (((32 * F + 1) * N : ℚ) : ℝ) + (((32 * F : ℚ) * targetEndpointDistance q q' : ℚ) : ℝ) + (fun r => (initialConeValue source target U a (32 * F) q r : ℝ)) + (fun r => (initialConeValue source target U a (32 * F) q' r : ℝ)) + (le_add_of_nonneg_right (by positivity)) (by + intro r hr + have htri : (targetEndpointDistance q r : ℚ) ≤ + targetEndpointDistance q' r + targetEndpointDistance q q' := by + exact_mod_cast targetEndpointDistance_triangle q q' r + have hmult := mul_le_mul_of_nonneg_left htri (by positivity : (0 : ℚ) ≤ 32 * F) + have hcone : initialConeValue source target U a (32 * F) q r ≤ + initialConeValue source target U a (32 * F) q' r + + (32 * F : ℚ) * targetEndpointDistance q q' := by + unfold initialConeValue + linarith + exact_mod_cast hcone) + rw [← hcast q, ← hcast q'] at h + exact_mod_cast h + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/InitialCones.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/InitialCones.lean new file mode 100644 index 0000000000000000000000000000000000000000..80f82c266afae786d2229bb24a435cdb86ea6f6a --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/InitialCones.lean @@ -0,0 +1,84 @@ +import OAI.Combinatorics.EditApproximation.Geometry.StateGeometry +import OAI.Combinatorics.EditApproximation.Numerics.RationalRefinement +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! +# Rational scaled seeds and the actual cone lower invariant + +Ceilings preserve the upper bound because `F*c` is an integer. Cone lower +bounds use the actual edit-distance and signed-length geometry, rather +than an assumed lower-bound-preserving cone oracle. +-/ + +namespace EditApproximation + + + +theorem rationalStateGap_cast {α : Type*} (source target : List α) + (q : TargetInterval target.length) : + (rationalStateGap source target q : ℝ) = stateLengthGap source target q := by + simp only [rationalStateGap, stateLengthGap, Rat.cast_sub, Rat.cast_natCast] + + + +theorem scaledSeedValue_bounds (U c F : ℕ) (a gap : ℚ) + (ha : 1 ≤ a) (hF : 1 ≤ F) (hU : c ≤ U) + (hupper : (U : ℚ) ≤ a * F * c) (hgap : |gap| ≤ c) : + max ((c : ℚ) / a) |gap| ≤ scaledSeedValue U a gap ∧ scaledSeedValue U a gap ≤ F * c := by + have ha0 : 0 < a := by linarith + have hFQ : (1 : ℚ) ≤ F := by exact_mod_cast hF + have hc0 : (0 : ℚ) ≤ c := Nat.cast_nonneg c + have hratio : (U : ℚ) / a ≤ F * c := by + apply (div_le_iff₀ ha0).2 + nlinarith + have hceil : ⌈(U : ℚ) / a⌉₊ ≤ F * c := Nat.ceil_le.mpr (by exact_mod_cast hratio) + constructor + · apply max_le_max _ le_rfl + exact (div_le_div_of_nonneg_right (by exact_mod_cast hU) ha0.le).trans (Nat.le_ceil _) + · apply max_le (by exact_mod_cast hceil) _ + exact hgap.trans (by nlinarith) + +theorem scaledSeedValue_zero (a : ℚ) : scaledSeedValue 0 a 0 = 0 := by + simp only [scaledSeedValue, Nat.cast_zero, zero_div, Nat.ceil_zero, abs_zero, max_self] + + + +theorem initialConeValue_actual_lower {α : Type*} (source target : List α) + (U : TargetInterval target.length → ℕ) (a L0 : ℚ) + (query center : TargetInterval target.length) (ha : 1 ≤ a) (hL : 1 ≤ L0) + (hseed : stateEditCost source target center ≤ U center) : + max ((stateEditCost source target query : ℚ) / a) |rationalStateGap source target query| ≤ + initialConeValue source target U a L0 query center := by + have ha0 : 0 < a := by linarith + let distance : ℚ := targetEndpointDistance query center + let base := scaledSeedValue (U center) a (rationalStateGap source target center) + have hd0 : 0 ≤ distance := Nat.cast_nonneg _ + have hbaseCost : (stateEditCost source target center : ℚ) / a ≤ base := + (div_le_div_of_nonneg_right (by exact_mod_cast hseed) ha0.le).trans + ((Nat.le_ceil _).trans (le_max_left _ _)) + have hbaseGap : |rationalStateGap source target center| ≤ base := le_max_right _ _ + have hdistDiv : distance / a ≤ distance := by + apply (div_le_iff₀ ha0).2 + nlinarith + have hdistSlope : distance ≤ L0 * distance := by nlinarith + have hcost : (stateEditCost source target query : ℚ) ≤ stateEditCost source target center + distance := by + dsimp only [distance] + exact_mod_cast stateEditCost_spatial source target query center + have hgap : |rationalStateGap source target query| ≤ |rationalStateGap source target center| + distance := by + have h := stateLengthGap_spatial source target query center + rw [← rationalStateGap_cast, ← rationalStateGap_cast] at h + exact_mod_cast h + change max ((stateEditCost source target query : ℚ) / a) |rationalStateGap source target query| ≤ + base + L0 * distance + apply max_le + · have hdivide := div_le_div_of_nonneg_right hcost ha0.le + rw [add_div] at hdivide + linarith + · linarith + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/InitialInputBudget.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/InitialInputBudget.lean new file mode 100644 index 0000000000000000000000000000000000000000..8ef2c1cb118d66ddffd13f91e07cfe88ba788dbc --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/InitialInputBudget.lean @@ -0,0 +1,55 @@ +import OAI.Combinatorics.EditApproximation.Geometry.LocalInitialCones +import OAI.Combinatorics.EditApproximation.Geometry.WideActions + +namespace OAI + +/-! The local initial cone uses a bounded number of preceding-seed +queries on every clamped seed, independently of an accuracy event. -/ + +namespace EditApproximation + +theorem localTargetStates_length_from_scale {n : ℕ} (P b radius C : ℕ) + (q : TargetInterval n) (hP : 0 < P) (hradius : radius ≤ C * b) : + (localTargetStates n (seedGridSpacing b P) radius q).length ≤ (4 * C * P + 2) ^ 2 := by + have hg : 0 < seedGridSpacing b P := by unfold seedGridSpacing; omega + have hcover : b ≤ 2 * P * seedGridSpacing b P := by + have hquot : b / P ≤ seedGridSpacing b P := le_max_right _ _ + have hdiv := Nat.lt_mul_div_succ b hP + nlinarith only [hquot, hdiv, hg] + have hprod : 2 * radius ≤ 4 * C * P * seedGridSpacing b P := by + nlinarith only [hradius, Nat.mul_le_mul_left (2 * C) hcover] + have hcount : 2 * radius / seedGridSpacing b P ≤ 4 * C * P := by + have hdivision := Nat.div_mul_le_self (2 * radius) (seedGridSpacing b P) + nlinarith only [hdivision, hprod, hg] + exact (localTargetStates_length_le hg q).trans + (Nat.pow_le_pow_left (Nat.add_le_add_right hcount 2) 2) + +theorem localInitialConeCenters_length {n : ℕ} (N P Amax : ℕ) (A : ℚ) + (U : TargetInterval n → ℕ) (q : TargetInterval n) + (hP : 0 < P) (hA : 1 ≤ A) (hAmax : A ≤ Amax) : + (localInitialConeCenters N P A U q).length ≤ + (dyadicScales N).length * (64 * Amax ^ 2 * P + 2) ^ 2 := by + unfold localInitialConeCenters + apply (list_flatMap_length_le _ _ _ ?_).trans + (Nat.mul_le_mul_right _ (List.length_filter_le _ _)) + intro b hb + have hwindow := of_decide_eq_true (List.mem_filter.mp hb).2 + have hAr : 0 < A := by linarith + have hscale : (U q : ℚ) ≤ 16 * A ^ 2 * b := by + have h := (div_le_iff₀ (by positivity : (0 : ℚ) < 16 * A ^ 2)).mp hwindow.1 + nlinarith only [h] + have hAsq : A ^ 2 ≤ (Amax : ℚ) ^ 2 := + pow_le_pow_left₀ hAr.le hAmax 2 + have hradius : U q ≤ 16 * Amax ^ 2 * b := by + have hmul := mul_le_mul_of_nonneg_right hAsq (by positivity : (0 : ℚ) ≤ 16 * b) + have hr : (U q : ℚ) ≤ (16 * Amax ^ 2 * b : ℕ) := by + push_cast + nlinarith only [hscale, hmul] + exact_mod_cast hr + exact (List.length_filter_le _ _).trans + (by simpa only [show 4 * (16 * Amax ^ 2) * P = 64 * Amax ^ 2 * P by ring] using + localTargetStates_length_from_scale P b (U q) (16 * Amax ^ 2) q hP hradius) + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/InitialSeedTable.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/InitialSeedTable.lean new file mode 100644 index 0000000000000000000000000000000000000000..47fa2a2a381e21eb58b439a6e22ff36cbe14dc95 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/InitialSeedTable.lean @@ -0,0 +1,53 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseGlobalSeed +import OAI.Combinatorics.EditApproximation.Geometry.StateDomain + +namespace OAI + +/-! +# Simultaneous initial accuracy on the actual labeled state domain + +The source and target arguments are the stored substrings at each physical +node and valid target interval. The entry-size and whole-domain cardinal +premises of the coarse seed theorem are discharged here. +-/ + +namespace EditApproximation + +open MeasureTheory ProbabilityTheory + +theorem initialSeedTable_width_bound {α : Type*} (N M : ℕ) (source target : List α) + (hsize : source.length + target.length ≤ N) + (entry : LabeledEntry M source.length target.length) : + coarseEntryWidth (entrySource M source entry) (entryTarget target entry) ≤ N := by + apply max_le + · exact (entrySource_length_le M source entry).trans (by omega) + · exact (entryTarget_length_le target entry).trans (by omega) + +theorem initialSeedTable_accuracy {α : Type*} [DecidableEq α] + (N B M : ℕ) [NeZero B] [MeasurableSpace (Fin B)] [MeasurableSingletonClass (Fin B)] + (source target : List α) + (depth : LabeledEntry M source.length target.length → ℕ) + (hB : B = (integerParameters N).B) (hM : M = (integerParameters N).M) + (hdepth : ∀ entry, depth entry = computedCoarseDepth N + (coarseEntryWidth (entrySource M source entry) (entryTarget target entry))) + (hN : 0 < N) (hsize : source.length + target.length ≤ N) + (hell : 200 ≤ inputSmallLog N) + (bernstein : FiniteBernsteinInput (Measure.pi fun _ : Fin B => + (PMF.uniformOfFintype (Fin B)).toMeasure)) : + (coarseFullSeedMeasure B depth (entrySource M source) (entryTarget target)).real + {draws | ¬ ∀ entry : LabeledEntry M source.length target.length, + stateEditCost (entrySource M source entry) target entry.2 ≤ + coarseFullSeedTable N B depth (entrySource M source) (entryTarget target) draws entry ∧ + coarseFullSeedTable N B depth (entrySource M source) (entryTarget target) draws entry ≤ + (integerParameters N).initialFactor * + stateEditCost (entrySource M source entry) target entry.2} < 1 / 100 := by + have hcount : Fintype.card (LabeledEntry M source.length target.length) ≤ + 2 ^ (5 * inputHeight N) := by + rw [hM] + exact computed_labeledEntry_card_le N source.length target.length hN (by omega) (by omega) hell + exact computed_fullSeedTable_accuracy N B depth (entrySource M source) (entryTarget target) + hB hdepth hN (initialSeedTable_width_bound N M source target hsize) hcount hell bernstein + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/InputViews.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/InputViews.lean new file mode 100644 index 0000000000000000000000000000000000000000..af2fc00b961bb88e4c3a8491120a97a8f267e462 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/InputViews.lean @@ -0,0 +1,71 @@ +import OAI.Combinatorics.EditApproximation.Geometry.Geometry + +namespace OAI + +/-! Input intervals are views into the stored arrays. Their semantic lists +are used by correctness statements; constructing a view stores only its +two endpoints and does not materialize that list. -/ + +namespace EditApproximation + +structure InputView {α : Type*} (input : Array α) where + lo : ℕ + hi : ℕ + ordered : lo ≤ hi + valid : hi ≤ input.size + +namespace InputView + +variable {α : Type*} {input : Array α} + +def width (view : InputView input) : ℕ := view.hi - view.lo + +def contents (view : InputView input) : List α := substring input.toList view.lo view.hi + +theorem contents_length (view : InputView input) : view.contents.length = view.width := + substring_length input.toList view.lo view.hi (by simpa only [Array.length_toList] using view.valid) + +def get (view : InputView input) (i : Fin view.width) : α := + input[view.lo + i.val]'(by have h := i.isLt; have hv := view.valid; dsimp only [width] at h; omega) + +theorem get_contents (view : InputView input) (i : Fin view.width) : + view.get i = view.contents[i.val]'(by rw [contents_length]; exact i.isLt) := by + simp only [get, contents, substring, List.getElem_drop, List.getElem_take, Array.getElem_toList] + +def whole (input : Array α) : InputView input := ⟨0, input.size, Nat.zero_le _, le_rfl⟩ + +theorem whole_contents (input : Array α) : (whole input).contents = input.toList := by + change (input.toList.take input.size).drop 0 = input.toList + rw [List.drop_zero, List.take_of_length_le (by simp only [Array.length_toList, le_refl])] + +def subview (view : InputView input) (lo hi : ℕ) (horder : lo ≤ hi) (hhi : hi ≤ view.width) : + InputView input := + ⟨view.lo + lo, view.lo + hi, Nat.add_le_add_left horder _, by + have hv := view.valid + have ho := view.ordered + dsimp only [width] at hhi + omega⟩ + +theorem subview_width (view : InputView input) (lo hi : ℕ) + (horder : lo ≤ hi) (hhi : hi ≤ view.width) : + (view.subview lo hi horder hhi).width = hi - lo := by + simp only [subview, width, Nat.add_sub_add_left] + +/-- Reading a singleton view touches one stored array entry. -/ +def head? (view : InputView input) : Option α := + if h : 0 < view.width then some (view.get ⟨0, h⟩) else none + +theorem head?_contents (view : InputView input) : view.head? = view.contents.head? := by + by_cases h : 0 < view.width + · rw [head?, dite_eq_left h] + rw [List.head?_eq_getElem?, List.getElem?_eq_getElem (by rw [contents_length]; exact h)] + exact congrArg some (get_contents view ⟨0, h⟩) + · have hempty : view.contents = [] := List.length_eq_zero_iff.mp (by rw [contents_length]; omega) + rw [head?, dite_eq_right h, hempty] + rfl + +end InputView + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/Leaves.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/Leaves.lean new file mode 100644 index 0000000000000000000000000000000000000000..f114dd619dc542a651b12517a4a36083bbb14f7e --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/Leaves.lean @@ -0,0 +1,103 @@ +import OAI.Combinatorics.EditApproximation.Geometry.Geometry +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! +# Exact interval-tree leaves + +An occurrence query gives the exact unit-cost edit distance at a source +leaf of width one (Section 2 of the manuscript). +-/ + +namespace EditApproximation + +open EditDistortion + +universe u + +/-- The part of the singleton cost determined by length and occurrence. -/ + + +theorem occurrenceDeficit_le_length {α : Type u} [DecidableEq α] + (a : α) (word : List α) : occurrenceDeficit a word ≤ word.length := Nat.sub_le _ _ + +theorem length_le_occurrenceDeficit_add_one {α : Type u} [DecidableEq α] + (a : α) (word : List α) : word.length ≤ occurrenceDeficit a word + 1 := by + unfold occurrenceDeficit + split_ifs <;> omega + +/-- One edit can increase the occurrence deficit by at most one. -/ +theorem occurrenceDeficit_step {α : Type u} [DecidableEq α] + (a : α) {x y : List α} (h : Step true x y) : + occurrenceDeficit a y ≤ occurrenceDeficit a x + 1 := by + cases h with + | insert p q b => + by_cases ha : a ∈ p ++ q + · have ha' : a ∈ p ++ b :: q := by + simp only [List.mem_append, List.mem_cons] at ha ⊢ + tauto + simp only [occurrenceDeficit, ite_eq_left ha, ite_eq_left ha', + List.length_append, List.length_cons] + omega + · have hup := occurrenceDeficit_le_length a (p ++ b :: q) + simp only [occurrenceDeficit, ite_eq_right ha, Nat.sub_zero, + List.length_append, List.length_cons] at hup ⊢ + omega + | delete p q b => + have hup := occurrenceDeficit_le_length a (p ++ q) + have hlo := length_le_occurrenceDeficit_add_one a (p ++ b :: q) + simp only [List.length_append, List.length_cons] at hup hlo + omega + | substitute _ p q b c => + have hup := occurrenceDeficit_le_length a (p ++ c :: q) + have hlo := length_le_occurrenceDeficit_add_one a (p ++ b :: q) + simp only [List.length_append, List.length_cons] at hup hlo + omega + +theorem occurrenceDeficit_script {α : Type u} [DecidableEq α] + (a : α) {x y : List α} {n : ℕ} (h : Script true n x y) : + occurrenceDeficit a y ≤ occurrenceDeficit a x + n := by + induction h with + | nil => omega + | cons step rest ih => + have hs := occurrenceDeficit_step a step + omega + +theorem occurrenceDeficit_le_singleton_edit {α : Type u} [DecidableEq α] + (a : α) (word : List α) : occurrenceDeficit a word ≤ edit [a] word := by + have h := occurrenceDeficit_script a (cost_spec (s := true) [a] word) + simpa [occurrenceDeficit, cost, edit] using h + +/-- Executable exact answer for a source interval containing one symbol. -/ + + +theorem singletonCost_eq_edit {α : Type u} [DecidableEq α] + (a : α) (word : List α) : singletonCost a word = edit [a] word := by + by_cases hempty : word = [] + · subst word + have hlo := (cost_length_bounds (s := true) [a] []).1 + have hup := edit_le_max_length [a] ([] : List α) + have hlo' : 1 ≤ edit [a] ([] : List α) := by + simpa [cost, edit] using hlo + have hup' : edit [a] ([] : List α) ≤ 1 := by simpa using hup + simpa [singletonCost] using Nat.le_antisymm hlo' hup' + · rw [singletonCost, ite_eq_right hempty] + apply Nat.le_antisymm (occurrenceDeficit_le_singleton_edit a word) + by_cases ha : a ∈ word + · have hs : [a].Sublist word := List.singleton_sublist.mpr ha + have hedit : edit [a] word = edit word [a] := cost_symm _ _ + rw [hedit] + simpa only [occurrenceDeficit, ite_eq_left ha, List.length_singleton] using + edit_sublist_le hs + · have hlen : 1 ≤ word.length := by + have hpos := List.length_pos_iff.mpr hempty + omega + have hup := edit_le_max_length [a] word + simpa only [occurrenceDeficit, ite_eq_right ha, Nat.sub_zero, + List.length_singleton, max_eq_right hlen] using hup + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/ListBandRegret.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/ListBandRegret.lean new file mode 100644 index 0000000000000000000000000000000000000000..b78571c10c05aa71a16bcf3d8f92e5940dd8790e --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/ListBandRegret.lean @@ -0,0 +1,122 @@ +import OAI.Combinatorics.EditApproximation.Geometry.OnlineActionDraw +import OAI.Combinatorics.EditApproximation.Geometry.ChildIncrements +import OAI.Combinatorics.EditApproximation.Probability.SampledRegret + +namespace OAI + +/-! +# Regret and sampling for the literal finite band list + +The numerical optimizer and exact sampler keep the same listed vertex +order. Passing to the finite set is used only for coordinate support and +convex-hull facts, never to reorder the executable optimizer. +-/ + +namespace EditApproximation + +open Finset + +theorem rationalVertexSet_band_list {β σ : Type*} [Fintype β] [DecidableEq β] [DecidableEq σ] + (band : List (β → σ)) (mass : β → ℚ) : + rationalVertexSet (band.map (actionVector mass)) = + rationalVertexSet (band.toFinset.toList.map (actionVector mass)) := by + unfold rationalVertexSet + congr 1 + ext vertex + simp only [Set.mem_ofPred_eq, List.mem_map, mem_toList, List.mem_toFinset] + +/-- Actual finite-list specialization of the computed entropy optimizer. -/ +theorem list_band_computed_entropy_regret {β σ : Type*} [Fintype β] [Nonempty β] + [DecidableEq β] [DecidableEq σ] (band : List (β → σ)) (hband : band ≠ []) + (mass : β → ℚ) (hpos : ∀ child, 0 < mass child) + (S H : ℕ) (η κ : ℚ) (rangeBound : ℝ) + (gain decrement : ℕ → β × σ → ℚ) {comparison : β → σ} (hc : comparison ∈ band) + (hH : 4 ≤ H) (hη : 0 < η) (hκ : 0 ≤ κ) (hκhalf : κ ≤ 1 / 2) + (hηrange : (η : ℝ) * rangeBound ≤ (κ : ℝ)) + (hdecrementNonneg : ∀ t < S, ∀ i ∈ bandCoordinates band.toFinset, (0 : ℝ) ≤ decrement t i) + (hrange : ∀ t < S, ∀ i ∈ bandCoordinates band.toFinset, ∀ j ∈ bandCoordinates band.toFinset, + i.1 = j.1 → |(decrement t i : ℝ) - decrement t j| ≤ rangeBound) + (hdecrement : ∀ i ∈ bandCoordinates band.toFinset, ∑ t ∈ range S, (decrement t i : ℝ) ≤ 1) + (hgain : ∀ t < S, ∀ i ∈ bandCoordinates band.toFinset, + -1 ≤ (gain t i : ℝ) + (1 - (κ : ℝ)) * decrement t i ∧ + (gain t i : ℝ) + (1 - (κ : ℝ)) * decrement t i ≤ 0) : + (∑ t ∈ range S, ∑ i ∈ bandCoordinates band.toFinset, + ((gain t i : ℝ) + decrement t i) * (actionVector mass comparison i : ℝ)) - + Real.log (bandCoordinates band.toFinset).card / (η : ℝ) - 2 * (κ : ℝ) - (S : ℝ) / (H : ℝ) ^ 3 ≤ + ∑ t ∈ range S, ∑ i ∈ bandCoordinates band.toFinset, + ((gain t i : ℝ) + (1 - (κ : ℝ)) * decrement t i) * + (computedOnlineVector (bandCoordinates band.toFinset) (band.map (actionVector mass)) + η κ gain decrement H t i : ℝ) := by + have hvertices : band.map (actionVector mass) ≠ [] := by + cases band with + | nil => exact False.elim (hband rfl) + | cons action rest => simp + have hcSet : comparison ∈ band.toFinset := List.mem_toFinset.mpr hc + have hset := rationalVertexSet_band_list band mass + apply computed_finite_block_entropy_regret (bandCoordinates band.toFinset) Prod.fst + (band.map (actionVector mass)) S H η κ rangeBound gain decrement + (fun i => (actionVector mass comparison i : ℝ)) hvertices hH + · intro p hp + obtain ⟨action, ha, rfl⟩ := List.mem_map.mp hp + exact actionVector_probability band.toFinset mass hpos (List.mem_toFinset.mpr ha) + · intro i hi + obtain ⟨action, ha, hpositive⟩ := actionVector_coordinate_coverage band.toFinset mass hpos i hi + exact ⟨actionVector mass action, List.mem_map.mpr ⟨action, List.mem_toFinset.mp ha, rfl⟩, hpositive⟩ + · exact subset_convexHull ℝ _ ⟨actionVector mass comparison, List.mem_map.mpr ⟨comparison, hc, rfl⟩, rfl⟩ + · exact band_block_nonempty band.toFinset ⟨comparison, hcSet⟩ + · intro p hp q hq b + rw [hset] at hp hq + rw [band_hull_block_mass band.toFinset mass b p hp, band_hull_block_mass band.toFinset mass b q hq] + · exact hη + · exact hκ + · exact hκhalf + · exact hηrange + · exact hdecrementNonneg + · exact hrange + · exact hdecrement + · exact hgain + +theorem finiteOptimizerActionDraw_linear_mean {β σ : Type*} [Fintype β] + [DecidableEq β] [DecidableEq σ] (band : List (β → σ)) (hband : band ≠ []) + (mass : β → ℚ) (linear : β × σ → ℚ) (G K : ℕ) (hK : 0 < K) + (payoff : β × σ → ℝ) : + uniformMean (fun integer : Fin (optimizerTriangularMass K) => + ∑ coordinate ∈ bandCoordinates band.toFinset, + payoff coordinate * (actionVector mass + (finiteOptimizerActionDraw band hband mass linear G K integer) coordinate : ℝ)) = + ∑ coordinate ∈ bandCoordinates band.toFinset, + payoff coordinate * (finiteRationalOptimizer (bandCoordinates band.toFinset) + (band.map (actionVector mass)) linear G K coordinate : ℝ) := by + unfold uniformMean + rw [Fintype.card_fin, sum_comm, sum_div] + apply sum_congr rfl + intro coordinate hc + rw [← mul_sum, mul_div_assoc] + congr 1 + exact_mod_cast finiteOptimizerActionDraw_mean band hband mass linear G K hK coordinate + +/-- Exact expected weighted child cost of the returned optimizer action. -/ +theorem finiteOptimizerActionDraw_child_cost_mean {β σ : Type*} [Fintype β] [Nonempty β] + [DecidableEq β] [DecidableEq σ] (band : List (β → σ)) (hband : band ≠ []) + (mass : β → ℚ) (hpos : ∀ child, 0 < mass child) + (table : ℕ → β × σ → ℚ) (κ : ℚ) (t : ℕ) + (linear : β × σ → ℚ) (G K : ℕ) (hK : 0 < K) : + uniformMean (fun integer : Fin (optimizerTriangularMass K) => + let action := finiteOptimizerActionDraw band hband mass linear G K integer + (∑ child, (table (t + 1) (child, action child) : ℝ)) + + (κ : ℝ) * ((∑ child, (table t (child, action child) : ℝ)) - + ∑ child, (table (t + 1) (child, action child) : ℝ))) = + -((∑ child, mass child : ℚ) : ℝ) * + ∑ coordinate ∈ bandCoordinates band.toFinset, + ((childGain mass table t coordinate : ℝ) + (1 - (κ : ℝ)) * childDecrement mass table t coordinate) * + (finiteRationalOptimizer (bandCoordinates band.toFinset) + (band.map (actionVector mass)) linear G K coordinate : ℝ) := by + have hpoint (integer : Fin (optimizerTriangularMass K)) := actionVector_child_cost_identity + band.toFinset mass hpos table κ t (List.mem_toFinset.mpr + (finiteOptimizerActionDraw_mem band hband mass linear G K integer)) + simp_rw [← hpoint] + rw [uniformMean_mul, finiteOptimizerActionDraw_linear_mean band hband mass linear G K hK] + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalArithmeticAsymptotics.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalArithmeticAsymptotics.lean new file mode 100644 index 0000000000000000000000000000000000000000..c05f248364d6014c7ec0522d8cc9be431df9203f --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalArithmeticAsymptotics.lean @@ -0,0 +1,79 @@ +import OAI.Combinatorics.EditApproximation.Geometry.LocalArithmeticBudget +import OAI.Combinatorics.EditApproximation.Geometry.DependencyPathEnvelope +import OAI.Combinatorics.EditApproximation.Geometry.SubexponentialTransfer + +namespace OAI + +/-! The actual finite optimizer arithmetic counter is subpolynomial in the +input length. This statement does not include the separate bit-operation +and local-data preparation counters. -/ + +namespace EditApproximation + +open Filter +open scoped Topology + +noncomputable def computedLocalArithmeticExponent (N : ℕ) : ℝ := + Real.log 2 + (44 * Real.log 2) * ((integerParameters N).M : ℝ) * + ((coarseExponent (inputSmallLog N) : ℝ) + 1) * inputSmallLog N + + 10000 * ((coarseExponent (inputSmallLog N) : ℝ) + 1) * Real.log (inputHeight N : ℝ) + +theorem computedLocalArithmeticExponent_tendsto : + Tendsto (fun N => computedLocalArithmeticExponent N / inputHeight N) atTop (𝓝 0) := by + have hconstant : Tendsto (fun N => Real.log 2 / (inputHeight N : ℝ)) atTop (𝓝 0) := by + simpa only [Pi.inv_apply, mul_zero, div_eq_mul_inv] using + inputHeight_real_tendsto.inv_tendsto_atTop.const_mul (Real.log 2) + have h := (hconstant.add (local_enumeration_exponent_div_height_tendsto.const_mul + (44 * Real.log 2))).add (encoding_exponent_div_height_tendsto.const_mul 10000) + simp only [zero_add, mul_zero] at h + convert h using 1 + ext N + unfold computedLocalArithmeticExponent + ring + +theorem computedLocalOptimizer_arithmetic_exp_bound (N : ℕ) (hN : 0 < N) + (hH : 64 ≤ inputHeight N) : + (localOptimizerArithmeticBudget (integerParameters N).M (integerParameters N).P + (inputHeight N) : ℝ) ≤ Real.exp (computedLocalArithmeticExponent N) := by + let H := inputHeight N + let M := (integerParameters N).M + let p := coarseExponent (inputSmallLog N) + have hM : M ≤ H := Nat.pow_le_pow_right (by decide : 0 < (2 : ℕ)) (Nat.div_le_self _ _) + have hP : 1 ≤ (integerParameters N).P := Nat.one_le_pow _ _ (by omega) + have hbudget := localOptimizerArithmeticBudget_cap H M (integerParameters N).P p hH hM hP le_rfl + have hbudgetR : (localOptimizerArithmeticBudget M (integerParameters N).P H : ℝ) ≤ + 2 * (H : ℝ) ^ (44 * M * (p + 1)) * (H : ℝ) ^ (10000 * (p + 1)) := by + exact_mod_cast hbudget + have hlog : Real.log (H : ℝ) ≤ (inputSmallLog N : ℝ) * Real.log 2 := by + rw [show H = inputHeight N from rfl, inputHeight_real_log] + apply mul_le_mul_of_nonneg_right _ (Real.log_nonneg (by norm_num)) + exact_mod_cast (inputSmallLog_bounds N hN).1 + have hpow1 := nat_pow_eq_exp_log H (44 * M * (p + 1)) (by omega) + have hpow2 := nat_pow_eq_exp_log H (10000 * (p + 1)) (by omega) + change (localOptimizerArithmeticBudget M (integerParameters N).P H : ℝ) ≤ _ + calc + _ ≤ 2 * (H : ℝ) ^ (44 * M * (p + 1)) * (H : ℝ) ^ (10000 * (p + 1)) := hbudgetR + _ = Real.exp (Real.log 2 + (44 * M * (p + 1) : ℕ) * Real.log (H : ℝ) + + (10000 * (p + 1) : ℕ) * Real.log (H : ℝ)) := by + rw [hpow1, hpow2, Real.exp_add, Real.exp_add, Real.exp_log (by norm_num : (0 : ℝ) < 2)] + _ ≤ Real.exp (computedLocalArithmeticExponent N) := by + apply Real.exp_le_exp.mpr + have hmul := mul_le_mul_of_nonneg_left hlog + (Nat.cast_nonneg (44 * M * (p + 1)) : (0 : ℝ) ≤ (44 * M * (p + 1) : ℕ)) + push_cast at hmul ⊢ + unfold computedLocalArithmeticExponent + dsimp only [M, p, H] at hmul ⊢ + nlinarith only [hmul] + +theorem computedLocalOptimizer_arithmetic_subpolynomial (epsilon : ℝ) (hepsilon : 0 < epsilon) : + ∀ᶠ N in atTop, + (localOptimizerArithmeticBudget (integerParameters N).M (integerParameters N).P + (inputHeight N) : ℝ) ≤ (N + 2 : ℝ) ^ epsilon := by + filter_upwards [subexponential_height_to_input computedLocalArithmeticExponent + computedLocalArithmeticExponent_tendsto epsilon hepsilon, eventually_ge_atTop 1, + inputHeight_real_tendsto.eventually (eventually_ge_atTop 64)] with N hbound hN hH + exact (computedLocalOptimizer_arithmetic_exp_bound N (by omega) (by exact_mod_cast hH)).trans hbound + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalArithmeticBudget.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalArithmeticBudget.lean new file mode 100644 index 0000000000000000000000000000000000000000..de80345ad9282eb1efebe16f3ccc76996c0f57e1 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalArithmeticBudget.lean @@ -0,0 +1,99 @@ +import OAI.Combinatorics.EditApproximation.Geometry.BandOptimizerWork +import OAI.Combinatorics.EditApproximation.Refinement.ComputedNumericalParameters + +namespace OAI + +/-! The compiled optimizer counter specialized to the literal representative +bands. Preparation of the input arrays remains a separate finite loop. -/ + +namespace EditApproximation + +theorem computedBandActions_length_le {nx ny M : ℕ} (parent : TargetInterval nx) + (r : TargetInterval ny) (b P : ℕ) (tau theta velocity : ℚ) + (child : Fin M → TargetInterval ny → ℚ) : + (computedBandActions parent r b P tau theta velocity child).length ≤ + (wideActionList M parent r b P).length := by + dsimp only [computedBandActions] + split_ifs <;> first | exact List.length_filter_le _ _ | exact Nat.zero_le _ + +theorem representativeBandActions_length_le {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (r : TargetInterval target.length) + (b P : ℕ) (tau theta : ℚ) (child : Fin M → TargetInterval target.length → ℚ) : + (representativeBandActions source target parent r b P tau theta child).length ≤ + (wideActionList M parent r b P).length := by + dsimp only [representativeBandActions] + split_ifs <;> first | exact computedBandActions_length_le _ _ _ _ _ _ _ _ | exact Nat.zero_le _ + +def localOptimizerArithmeticBudget (M P H : ℕ) : ℕ := + ((40 * P + 2) ^ (2 * M) + 1) * (M * (40 * P + 2) ^ 2 + 1) * + (H + M * (40 * P + 2) ^ 2 + 4) ^ 210 + +theorem materializedRepresentativeBand_work_le {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (r : TargetInterval target.length) + (b P H : ℕ) (hP : 0 < P) (tau theta : ℚ) + (child : Fin M → TargetInterval target.length → ℚ) (mass : Fin M → ℚ) + (linear : Fin M × TargetInterval target.length → ℚ) (j : ℕ) + (hj : j ≤ (H + (bandCoordinates + (representativeBandActions source target parent r b P tau theta child).toFinset).card + 2) ^ 80) : + (materializedBandActionWithWork + (representativeBandActions source target parent r b P tau theta child) mass linear + (H + (bandCoordinates + (representativeBandActions source target parent r b P tau theta child).toFinset).card + 2) j).2 ≤ + localOptimizerArithmeticBudget M P H := by + let band := representativeBandActions source target parent r b P tau theta child + have hlength : band.length ≤ (40 * P + 2) ^ (2 * M) := + (representativeBandActions_length_le source target parent r b P tau theta child).trans + (wideActionList_length_le M parent r b P hP) + have hdimension : (bandCoordinates band.toFinset).card ≤ M * (40 * P + 2) ^ 2 := + bandCoordinates_card_le parent r hP band + (fun action ha => representativeBandActions_wide source target parent r b P tau theta child action ha) + apply (materializedBandActionWithWork_optimizer_cost band mass linear _ j hj).trans + unfold localOptimizerArithmeticBudget + apply Nat.mul_le_mul + · exact Nat.mul_le_mul (Nat.add_le_add_right hlength 1) (Nat.add_le_add_right hdimension 1) + · apply Nat.pow_le_pow_left + dsimp only [band] at hdimension + omega + +theorem localOptimizerArithmeticBudget_cap (H M P p : ℕ) (hH : 64 ≤ H) (hM : M ≤ H) + (hP : 1 ≤ P) (hPcap : P ≤ H ^ (p + 20)) : + localOptimizerArithmeticBudget M P H ≤ + 2 * H ^ (44 * M * (p + 1)) * H ^ (10000 * (p + 1)) := by + have hbox : 40 * P + 2 ≤ H ^ (p + 22) := by + have hconstant : 42 ≤ H ^ 2 := by nlinarith + calc + _ ≤ 42 * P := by omega + _ ≤ H ^ 2 * H ^ (p + 20) := Nat.mul_le_mul hconstant hPcap + _ = H ^ (2 + (p + 20)) := (pow_add H 2 (p + 20)).symm + _ = _ := by congr 1; omega + have hlist : (40 * P + 2) ^ (2 * M) ≤ H ^ (44 * M * (p + 1)) := by + calc + _ ≤ (H ^ (p + 22)) ^ (2 * M) := Nat.pow_le_pow_left hbox _ + _ = H ^ ((p + 22) * (2 * M)) := (pow_mul H _ _).symm + _ ≤ _ := Nat.pow_le_pow_right (by omega) (by nlinarith) + have hlist1 : (40 * P + 2) ^ (2 * M) + 1 ≤ 2 * H ^ (44 * M * (p + 1)) := by + have hunit : 1 ≤ H ^ (44 * M * (p + 1)) := Nat.one_le_pow _ _ (by omega) + omega + have hdimension : M * (40 * P + 2) ^ 2 + 1 ≤ H ^ (2 * p + 46) := by + have h := optimizer_parameter_budget_le H M P p hH hM hP hPcap + omega + have hG := optimizer_parameter_budget_le H M P p hH hM hP hPcap + have hproduct : (M * (40 * P + 2) ^ 2 + 1) * + (H + M * (40 * P + 2) ^ 2 + 4) ^ 210 ≤ H ^ (10000 * (p + 1)) := by + calc + _ ≤ H ^ (2 * p + 46) * (H ^ (2 * p + 46)) ^ 210 := + Nat.mul_le_mul hdimension (Nat.pow_le_pow_left hG _) + _ = (H ^ (2 * p + 46)) ^ 211 := (pow_succ' _ 210).symm + _ = H ^ ((2 * p + 46) * 211) := (pow_mul H _ _).symm + _ ≤ _ := Nat.pow_le_pow_right (by omega) (by omega) + calc + localOptimizerArithmeticBudget M P H = + ((40 * P + 2) ^ (2 * M) + 1) * + ((M * (40 * P + 2) ^ 2 + 1) * (H + M * (40 * P + 2) ^ 2 + 4) ^ 210) := by + unfold localOptimizerArithmeticBudget + exact Nat.mul_assoc _ _ _ + _ ≤ _ := Nat.mul_le_mul hlist1 hproduct + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalCells.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalCells.lean new file mode 100644 index 0000000000000000000000000000000000000000..7d12666459b5d8a0b9fd91792b0703beb5a51cb6 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalCells.lean @@ -0,0 +1,96 @@ +import OAI.Combinatorics.EditApproximation.Geometry.GroupCells +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Direct bounded-range enumeration of the cells meeting a query square. -/ + +namespace EditApproximation + + + +theorem localCellCoordinates_complete (side : ℚ) (hside : 0 < side) + (p radius r : ℕ) (hr : Nat.dist p r ≤ radius) : + ⌊(r : ℚ) / side⌋₊ ∈ localCellCoordinates side p radius := by + have hbounds : p - radius ≤ r ∧ r ≤ p + radius := by unfold Nat.dist at hr; omega + have hlo := Nat.floor_le_floor (div_le_div_of_nonneg_right + (show ((p - radius : ℕ) : ℚ) ≤ r by exact_mod_cast hbounds.1) hside.le) + have hhi := Nat.floor_le_floor (div_le_div_of_nonneg_right + (show (r : ℚ) ≤ (p + radius : ℕ) by exact_mod_cast hbounds.2) hside.le) + unfold localCellCoordinates + apply List.mem_range'.mpr + refine ⟨⌊(r : ℚ) / side⌋₊ - ⌊((p - radius : ℕ) : ℚ) / side⌋₊, ?_, ?_⟩ <;> omega + +theorem localCellCoordinates_length_le (side : ℚ) (hside : 0 < side) + (p radius K : ℕ) (hbudget : 2 * (radius : ℚ) / side ≤ K) : + (localCellCoordinates side p radius).length ≤ K + 2 := by + let first := ⌊((p - radius : ℕ) : ℚ) / side⌋₊ + let last := ⌊((p + radius : ℕ) : ℚ) / side⌋₊ + have horder : first ≤ last := Nat.floor_le_floor (div_le_div_of_nonneg_right + (by exact_mod_cast (show p - radius ≤ p + radius by omega)) hside.le) + have hhi : (last : ℚ) ≤ ((p + radius : ℕ) : ℚ) / side := + Nat.floor_le (div_nonneg (Nat.cast_nonneg _) hside.le) + have hlo : ((p - radius : ℕ) : ℚ) / side < (first : ℚ) + 1 := Nat.lt_floor_add_one _ + have hwidth : ((p + radius : ℕ) : ℚ) - ((p - radius : ℕ) : ℚ) ≤ 2 * radius := by + have h : p + radius - (p - radius) ≤ 2 * radius := by omega + have hR : ((p + radius - (p - radius) : ℕ) : ℚ) ≤ ((2 * radius : ℕ) : ℚ) := by exact_mod_cast h + simpa only [Nat.cast_sub (show p - radius ≤ p + radius by omega), Nat.cast_mul, Nat.cast_ofNat] using hR + have hquotient : ((p + radius : ℕ) : ℚ) / side - ((p - radius : ℕ) : ℚ) / side ≤ K := by + calc + _ = (((p + radius : ℕ) : ℚ) - ((p - radius : ℕ) : ℚ)) / side := by ring + _ ≤ (2 * radius) / side := div_le_div_of_nonneg_right hwidth hside.le + _ ≤ K := hbudget + have hcount : ((last + 1 - first : ℕ) : ℚ) < (K : ℚ) + 2 := by + rw [Nat.cast_sub (by omega : first ≤ last + 1), Nat.cast_add, Nat.cast_one] + linarith only [hhi, hlo, hquotient] + have hcountN : last + 1 - first < K + 2 := by exact_mod_cast hcount + exact (by simpa only [localCellCoordinates, List.length_range', first, last] using hcountN.le) + + + +theorem localTargetCells_complete {n : ℕ} (side : ℚ) (hside : 0 < side) + (radius : ℕ) (q r : TargetInterval n) + (hlo : Nat.dist q.lo r.lo ≤ radius) (hhi : Nat.dist q.hi r.hi ≤ radius) : + targetCell side r ∈ localTargetCells side radius q := by + apply List.mem_flatMap.mpr + refine ⟨⌊(r.lo : ℚ) / side⌋₊, localCellCoordinates_complete side hside _ _ _ hlo, ?_⟩ + exact List.mem_map.mpr ⟨⌊(r.hi : ℚ) / side⌋₊, localCellCoordinates_complete side hside _ _ _ hhi, rfl⟩ + +theorem localTargetCells_length_le {n : ℕ} (side : ℚ) (hside : 0 < side) + (radius K : ℕ) (q : TargetInterval n) (hbudget : 2 * (radius : ℚ) / side ≤ K) : + (localTargetCells side radius q).length ≤ (K + 2) ^ 2 := by + have hfirst := localCellCoordinates_length_le side hside q.lo radius K hbudget + have hsecond := localCellCoordinates_length_le side hside q.hi radius K hbudget + have h := list_flatMap_length_le (localCellCoordinates side q.lo radius) + (fun lo => (localCellCoordinates side q.hi radius).map fun hi => (lo, hi)) (K + 2) + (fun lo _ => by simpa only [List.length_map] using hsecond) + exact h.trans (by simpa only [pow_two] using Nat.mul_le_mul_right (K + 2) hfirst) + +/-- Every retained query scale has only polynomially many nearby cells, +even when the initial seed is inaccurate. -/ +theorem localTargetCells_query_length {n : ℕ} (F b exponent : ℕ) + (q : TargetInterval n) (w : ℚ) (hF : 1 ≤ F) (hb : 1 ≤ b) + (hw : 0 ≤ w) (hwindow : w / (16 * F) ≤ b) : + (localTargetCells ((2 : ℚ) ^ (-(exponent : ℤ)) * b) ⌈w⌉₊ q).length ≤ + ((32 * F + 2) * 2 ^ exponent + 2) ^ 2 := by + have hFpos : (0 : ℚ) < F := by exact_mod_cast (by omega : 0 < F) + have hbpos : (0 : ℚ) < b := by exact_mod_cast (by omega : 0 < b) + have hbR : (1 : ℚ) ≤ b := by exact_mod_cast hb + have hside : 0 < (2 : ℚ) ^ (-(exponent : ℤ)) * b := by positivity + apply localTargetCells_length_le _ hside _ ((32 * F + 2) * 2 ^ exponent) q + apply (div_le_iff₀ hside).2 + have hwidth : w ≤ 16 * (F : ℚ) * b := + by nlinarith only [(div_le_iff₀ (by positivity : (0 : ℚ) < 16 * F)).mp hwindow] + have hceil : (⌈w⌉₊ : ℚ) < w + 1 := Nat.ceil_lt_add_one hw + have hcancel : (((32 * F + 2) * 2 ^ exponent : ℕ) : ℚ) * + ((2 : ℚ) ^ (-(exponent : ℤ)) * b) = (32 * (F : ℚ) + 2) * b := by + push_cast + rw [zpow_neg, zpow_natCast] + field_simp + rw [hcancel] + nlinarith only [hceil, hwidth, hbR] + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalCommonOutput.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalCommonOutput.lean new file mode 100644 index 0000000000000000000000000000000000000000..56043bdc85bfb928c5afea7b2f18948bd6924b42 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalCommonOutput.lean @@ -0,0 +1,154 @@ +import OAI.Combinatorics.EditApproximation.Geometry.LocalCommonTrace +import OAI.Combinatorics.EditApproximation.Geometry.LocalTraceMemoOutput + +namespace OAI + +/-! The charged memo answer under one common random source per pass and +one fresh terminal source. Correct marginal laws suffice; hypothetical +seed-indexed draw families are not part of the execution. -/ + +namespace EditApproximation + +open MeasureTheory ProbabilityTheory + +section Output + +variable {α : Type*} [DecidableEq α] {M J R : ℕ} + [NeZero M] [NeZero R] [MeasurableSpace (Fin M)] [MeasurableSingletonClass (Fin M)] + (source target : List α) (N P T S H : ℕ) + +local notation "Seed" => ClampedPhysicalSeed M J target.length N +local notation "passes" => computedSeedPassCount N +local notation "ell" => inputSmallLog N +local notation "thetaExponent" => (40 * smallLogExponent N : ℕ) +local notation "tau" => RationalParameters.tau (rationalParameters ell) +local notation "cap" => localOnlineMassBound M P H + +abbrev LocalCommonTerminalDraw := + PhysicalCommonDraw M J N target.length thetaExponent ell (ell ^ 80) R cap + +noncomputable def localCommonTerminalLaw : + Measure (LocalCommonTerminalDraw (M := M) (J := J) (R := R) target N P H) := + physicalCommonLaw M J N target.length thetaExponent ell (ell ^ 80) R cap + +instance localCommonTerminalLaw_probability : IsProbabilityMeasure + (localCommonTerminalLaw (M := M) (J := J) (R := R) target N P H) := by + unfold localCommonTerminalLaw + infer_instance + +noncomputable def localCommonTerminalSample (hP : 0 < P) (seed : Seed) + (draw : LocalCommonTerminalDraw (M := M) (J := J) (R := R) target N P H) : + LocalFinalProgramDraw (R := R) source target N P T H seed := + physicalCommonSample source target (clampedSeedNat seed) N P ell + (scheduledSeedFactor N passes) T thetaExponent H (ell ^ 80) R cap tau + (physicalLocalOnlineMass_le source target (clampedSeedNat seed) N P ell + (scheduledSeedFactor N passes) T thetaExponent H tau hP) draw + +omit [NeZero R] in +theorem localCommonTerminalSample_law (hP : 0 < P) (seed : Seed) : + (localCommonTerminalLaw (M := M) (J := J) (R := R) target N P H).map + (localCommonTerminalSample source target N P T H hP seed) = + localFinalProgramDrawLaw (R := R) source target N P T H seed := + physicalCommonSample_law source target (clampedSeedNat seed) N P ell + (scheduledSeedFactor N passes) T thetaExponent H (ell ^ 80) R cap tau + (physicalLocalOnlineMass_le source target (clampedSeedNat seed) N P ell + (scheduledSeedFactor N passes) T thetaExponent H tau hP) + +abbrev LocalCommonFinalOutcome := + LocalCommonTrace (M := M) (J := J) (R := R) target N P H passes × + LocalCommonTerminalDraw (M := M) (J := J) (R := R) target N P H + +noncomputable def localCommonFinalLaw (incoming : Measure Seed) : + Measure (LocalCommonFinalOutcome (M := M) (J := J) (R := R) target N P H) := + (localCommonTraceLaw (M := M) (J := J) (R := R) target N P H incoming passes).prod + (localCommonTerminalLaw (M := M) (J := J) (R := R) target N P H) + +instance localCommonFinalLaw_probability (incoming : Measure Seed) [IsProbabilityMeasure incoming] : + IsProbabilityMeasure (localCommonFinalLaw (M := M) (J := J) (R := R) target N P H incoming) := by + unfold localCommonFinalLaw + infer_instance + +noncomputable def localCommonFinalToTrace (hP : 0 < P) + (outcome : LocalCommonFinalOutcome (M := M) (J := J) (R := R) target N P H) : + LocalTraceFinalOutcome (M := M) (J := J) (R := R) source target N P T H := + (localCommonToScheduled source target N P T H hP passes outcome.1, + fun seed => localCommonTerminalSample source target N P T H hP seed outcome.2) + +noncomputable def localCommonMemoAnswer (hP : 0 < P) (hH : 0 < H) + (rootQ : TargetInterval target.length) + (outcome : LocalCommonFinalOutcome (M := M) (J := J) (R := R) target N P H) : ℕ := + localTraceMemoAnswer source target N P T S H hH rootQ + (localCommonFinalToTrace source target N P T H hP outcome) + +omit [MeasurableSpace (Fin M)] [MeasurableSingletonClass (Fin M)] in +theorem localCommonMemoAnswer_eq (hP : 0 < P) (hH : 0 < H) + (rootQ : TargetInterval target.length) + (outcome : LocalCommonFinalOutcome (M := M) (J := J) (R := R) target N P H) : + localCommonMemoAnswer source target N P T S H hP hH rootQ outcome = + localFinalProgramAnswer (R := R) source target N P T S H rootQ + (localCommonSeed source target N P T S H hP passes outcome.1, + fun seed => localCommonTerminalSample source target N P T H hP seed outcome.2) := by + rw [localCommonMemoAnswer, localTraceMemoAnswer_eq] + unfold localTraceFinalProjection localCommonFinalToTrace + rw [localCommonToScheduled_seed] + +theorem localCommonMemoAnswer_law (hP : 0 < P) (hH : 0 < H) + (incoming : Measure Seed) [IsProbabilityMeasure incoming] + (rootQ : TargetInterval target.length) : + (localCommonFinalLaw (M := M) (J := J) (R := R) target N P H incoming).map + (localCommonMemoAnswer source target N P T S H hP hH rootQ) = + (localFinalProgramLaw (R := R) source target N P T S H incoming).map + (localFinalProgramAnswer (R := R) source target N P T S H rootQ) := by + classical + let reindex := Prod.map (localCommonSeed (M := M) (J := J) (R := R) source target N P T S H hP passes) + (id : LocalCommonTerminalDraw (M := M) (J := J) (R := R) target N P H → _) + let answer : Seed × LocalCommonTerminalDraw (M := M) (J := J) (R := R) target N P H → ℕ := + fun pair => localFinalProgramAnswer (R := R) source target N P T S H rootQ + (pair.1, fun seed => localCommonTerminalSample source target N P T H hP seed pair.2) + have hanswer : localCommonMemoAnswer (R := R) source target N P T S H hP hH rootQ = + answer ∘ reindex := by + funext outcome + exact localCommonMemoAnswer_eq source target N P T S H hP hH rootQ outcome + have hproduct : + (localCommonFinalLaw (M := M) (J := J) (R := R) target N P H incoming).map reindex = + (localScheduledSeedLaw (R := R) source target N P T S H incoming passes).prod + (localCommonTerminalLaw (M := M) (J := J) (R := R) target N P H) := by + unfold localCommonFinalLaw + rw [show reindex = Prod.map (localCommonSeed (M := M) (J := J) (R := R) source target N P T S H hP passes) id from rfl] + rw [← Measure.map_prod_map _ _ (measurable_of_finite _) measurable_id, + Measure.map_id, localCommonSeed_law] + rw [hanswer, ← Measure.map_map (measurable_of_finite _) (measurable_of_finite _), hproduct] + unfold localFinalProgramLaw + change _ = (Measure.map (fun pair : LocalFinalProgramOutcome + (M := M) (J := J) (R := R) source target N P T H => + if source = substring target rootQ.lo rootQ.hi then 0 else + integerAnswer N (localFinalProgramValue (R := R) source target N P T S H rootQ + pair.1 (pair.2 pair.1))) _) + convert (adaptiveAnswerLaw_eq_of_marginals + (localFinalProgramDrawLaw (R := R) source target N P T H) + (localCommonTerminalLaw (M := M) (J := J) (R := R) target N P H) + (localCommonTerminalSample source target N P T H hP) + (localCommonTerminalSample_law source target N P T H hP) + (localScheduledSeedLaw (R := R) source target N P T S H incoming passes) + (fun seed draw => if source = substring target rootQ.lo rootQ.hi then 0 else + integerAnswer N (localFinalProgramValue (R := R) source target N P T S H rootQ seed draw))) using 1 + · rfl + +theorem localCommonMemoAnswer_event (hP : 0 < P) (hH : 0 < H) + (incoming : Measure Seed) [IsProbabilityMeasure incoming] + (rootQ : TargetInterval target.length) (event : Set ℕ) : + (localCommonFinalLaw (M := M) (J := J) (R := R) target N P H incoming).real + {outcome | localCommonMemoAnswer source target N P T S H hP hH rootQ outcome ∈ event} = + (localFinalProgramLaw (R := R) source target N P T S H incoming).real + {outcome | localFinalProgramAnswer (R := R) source target N P T S H rootQ outcome ∈ event} := by + classical + have h := congrArg (fun law : Measure ℕ => law.real event) + (localCommonMemoAnswer_law (R := R) source target N P T S H hP hH incoming rootQ) + simpa only [map_measureReal_apply (measurable_of_finite _) (Set.to_countable _).measurableSet, + Set.preimage] using h + +end Output + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalCommonSeed.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalCommonSeed.lean new file mode 100644 index 0000000000000000000000000000000000000000..c17f70ca2acf9e53356b7beddb27ccce3bf3d0d6 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalCommonSeed.lean @@ -0,0 +1,115 @@ +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalCommonSource +import OAI.Combinatorics.EditApproximation.Geometry.LocalOnlineMassBound +import OAI.Combinatorics.EditApproximation.Geometry.LocalSeedSchedule +import OAI.Combinatorics.EditApproximation.Geometry.CommonSeedTrace + +namespace OAI + +/-! Concrete common-source seed passes. The sampler range cap is proved +for every seed; no good-seed event is used to define or bound the draws. -/ + +namespace EditApproximation + +open MeasureTheory ProbabilityTheory + +section CommonSeed + +variable {α : Type*} [DecidableEq α] {M J R : ℕ} + [NeZero M] [NeZero R] [MeasurableSpace (Fin M)] [MeasurableSingletonClass (Fin M)] + (source target : List α) (N P T S H : ℕ) + +local notation "Seed" => ClampedPhysicalSeed M J target.length N +local notation "ell" => inputSmallLog N +local notation "thetaExponent" => (40 * smallLogExponent N : ℕ) +local notation "tau" => RationalParameters.tau (rationalParameters ell) +local notation "cap" => localOnlineMassBound M P H + +abbrev LocalCommonDraw := Fin (H ^ 2) → + PhysicalCommonDraw M J N target.length thetaExponent ell (ell ^ 80) R cap + +noncomputable def localCommonDrawLaw : + Measure (LocalCommonDraw (M := M) (J := J) (R := R) target N P H) := + Measure.pi fun _ : Fin (H ^ 2) => + physicalCommonLaw M J N target.length thetaExponent ell (ell ^ 80) R cap + +instance localCommonDrawLaw_probability : IsProbabilityMeasure + (localCommonDrawLaw (M := M) (J := J) (R := R) target N P H) := by + unfold localCommonDrawLaw + infer_instance + +noncomputable def localCommonSample (hP : 0 < P) (pass : ℕ) (seed : Seed) + (draw : LocalCommonDraw (M := M) (J := J) (R := R) target N P H) : + LocalScheduledSeedDraw (R := R) source target N P T H pass seed := + fun copy => physicalCommonSample source target (clampedSeedNat seed) N P ell + (scheduledSeedFactor N pass) T thetaExponent H (ell ^ 80) R cap tau + (physicalLocalOnlineMass_le source target (clampedSeedNat seed) N P ell + (scheduledSeedFactor N pass) T thetaExponent H tau hP) (draw copy) + +omit [NeZero R] in +theorem localCommonSample_law (hP : 0 < P) (pass : ℕ) (seed : Seed) : + (localCommonDrawLaw (M := M) (J := J) (R := R) target N P H).map + (localCommonSample source target N P T H hP pass seed) = + localScheduledSeedDrawLaw (R := R) source target N P T H pass seed := by + have h := Measure.pi_map_pi (μ := fun _ : Fin (H ^ 2) => + physicalCommonLaw M J N target.length thetaExponent ell (ell ^ 80) R cap) + (fun _ => (measurable_of_finite + (physicalCommonSample source target (clampedSeedNat seed) N P ell + (scheduledSeedFactor N pass) T thetaExponent H (ell ^ 80) R cap tau + (physicalLocalOnlineMass_le source target (clampedSeedNat seed) N P ell + (scheduledSeedFactor N pass) T thetaExponent H tau hP))).aemeasurable) + refine h.trans ?_ + congr 1 + funext copy + exact physicalCommonSample_law source target (clampedSeedNat seed) N P ell + (scheduledSeedFactor N pass) T thetaExponent H (ell ^ 80) R cap tau + (physicalLocalOnlineMass_le source target (clampedSeedNat seed) N P ell + (scheduledSeedFactor N pass) T thetaExponent H tau hP) + +abbrev LocalCommonTrace (passes : ℕ) := CommonSeedTrace Seed + (fun _ => LocalCommonDraw (M := M) (J := J) (R := R) target N P H) passes + +noncomputable instance localCommonTraceFintype (passes : ℕ) : + Fintype (LocalCommonTrace (M := M) (J := J) (R := R) target N P H passes) := by + classical + exact commonSeedTraceFintype Seed + (fun _ => LocalCommonDraw (M := M) (J := J) (R := R) target N P H) passes + +instance localCommonTraceSingleton (passes : ℕ) : + MeasurableSingletonClass + (LocalCommonTrace (M := M) (J := J) (R := R) target N P H passes) := by + exact commonSeedTraceSingleton Seed + (fun _ => LocalCommonDraw (M := M) (J := J) (R := R) target N P H) passes + +noncomputable def localCommonSeed (hP : 0 < P) (passes : ℕ) + (trace : LocalCommonTrace (M := M) (J := J) (R := R) target N P H passes) : Seed := + commonTraceValue (localCommonSample source target N P T H hP) + (localScheduledSeedNext (R := R) source target N P T S H) passes trace + +noncomputable def localCommonTraceLaw (incoming : Measure Seed) (passes : ℕ) : + Measure (LocalCommonTrace (M := M) (J := J) (R := R) target N P H passes) := + commonTraceLaw (fun _ => localCommonDrawLaw (M := M) (J := J) (R := R) target N P H) incoming passes + +instance localCommonTraceLaw_probability (incoming : Measure Seed) [IsProbabilityMeasure incoming] + (passes : ℕ) : IsProbabilityMeasure + (localCommonTraceLaw (M := M) (J := J) (R := R) target N P H incoming passes) := by + classical + unfold localCommonTraceLaw + infer_instance + +theorem localCommonSeed_law (hP : 0 < P) (incoming : Measure Seed) [IsProbabilityMeasure incoming] + (passes : ℕ) : + (localCommonTraceLaw (M := M) (J := J) (R := R) target N P H incoming passes).map + (localCommonSeed source target N P T S H hP passes) = + localScheduledSeedLaw (R := R) source target N P T S H incoming passes := by + classical + exact commonTraceLaw_map (localScheduledSeedDrawLaw (R := R) source target N P T H) + (fun _ => localCommonDrawLaw (M := M) (J := J) (R := R) target N P H) + (localCommonSample source target N P T H hP) + (localScheduledSeedNext (R := R) source target N P T S H) incoming + (localCommonSample_law source target N P T H hP) passes + +end CommonSeed + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalCommonTrace.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalCommonTrace.lean new file mode 100644 index 0000000000000000000000000000000000000000..d61942c7d0d75c2f45ad89d6f6d05ce65627b2ee --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalCommonTrace.lean @@ -0,0 +1,52 @@ +import OAI.Combinatorics.EditApproximation.Geometry.LocalCommonSeed +import OAI.Combinatorics.EditApproximation.Geometry.LocalTraceProgram + +namespace OAI + +/-! A common keyed source gives a lazy functional view of the seed trace. +Only the actual incoming seed is selected during execution. -/ + +namespace EditApproximation + +section Trace + +variable {α : Type*} [DecidableEq α] {M J R : ℕ} + [NeZero M] [NeZero R] [MeasurableSpace (Fin M)] [MeasurableSingletonClass (Fin M)] + (source target : List α) (N P T S H : ℕ) + +noncomputable def localCommonToScheduled (hP : 0 < P) : (passes : ℕ) → + LocalCommonTrace (M := M) (J := J) (R := R) target N P H passes → + LocalScheduledTrace (M := M) (J := J) (R := R) source target N P T H passes + | 0, trace => trace + | passes + 1, trace => + (localCommonToScheduled hP passes trace.1, + fun seed => localCommonSample source target N P T H hP passes seed trace.2) + +omit [MeasurableSpace (Fin M)] [MeasurableSingletonClass (Fin M)] in +theorem localCommonToScheduled_seed (hP : 0 < P) : ∀ (passes : ℕ) + (trace : LocalCommonTrace (M := M) (J := J) (R := R) target N P H passes), + localTraceSeed source target N P T S H passes + (localCommonToScheduled source target N P T H hP passes trace) = + localCommonSeed source target N P T S H hP passes trace := by + intro passes + induction passes with + | zero => intro trace; rfl + | succ passes ih => + intro trace + change localScheduledSeedNext source target N P T S H passes + (localTraceSeed source target N P T S H passes + (localCommonToScheduled source target N P T H hP passes trace.1)) + (localCommonSample source target N P T H hP passes + (localTraceSeed source target N P T S H passes + (localCommonToScheduled source target N P T H hP passes trace.1)) trace.2) = + localScheduledSeedNext source target N P T S H passes + (localCommonSeed source target N P T S H hP passes trace.1) + (localCommonSample source target N P T H hP passes + (localCommonSeed source target N P T S H hP passes trace.1) trace.2) + rw [ih] + +end Trace + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalFinalAccuracy.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalFinalAccuracy.lean new file mode 100644 index 0000000000000000000000000000000000000000..6814813f8b9ca064196b39628546b6ee76f01894 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalFinalAccuracy.lean @@ -0,0 +1,264 @@ +import OAI.Combinatorics.EditApproximation.Geometry.LocalSeedSchedule +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalLocalValueLaw +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalConditionalAccuracy + +namespace OAI + +/-! The final fresh bounded-key local query, following the actual local +median schedule, has the required approximation probability. The incoming +law is supplied by the concrete coarse sampler in the final theorem. -/ + +namespace EditApproximation + +open MeasureTheory ProbabilityTheory + +section Final + +variable {α : Type*} [DecidableEq α] {M J R : ℕ} + [NeZero M] [NeZero R] [MeasurableSpace (Fin M)] [MeasurableSingletonClass (Fin M)] + (source target : List α) (N P T S H : ℕ) + +local notation "Seed" => ClampedPhysicalSeed M J target.length N +local notation "ell" => inputSmallLog N +local notation "terminalFactor" => scheduledSeedFactor N (computedSeedPassCount N) +local notation "thetaExponent" => (40 * smallLogExponent N : ℕ) +local notation "eta" => RationalParameters.eta (rationalParameters ell) +local notation "kappa" => RationalParameters.kappa (rationalParameters ell) +local notation "delta" => RationalParameters.delta (rationalParameters ell) +local notation "tau" => RationalParameters.tau (rationalParameters ell) + +abbrev LocalFinalProgramDraw (seed : Seed) := + PhysicalLocalProgramDraw (R := R) source target (clampedSeedNat seed) N P ell terminalFactor + T thetaExponent H (ell ^ 80) tau + +noncomputable def localFinalProgramDrawLaw (seed : Seed) : + Measure (LocalFinalProgramDraw (R := R) source target N P T H seed) := + physicalLocalProgramDrawLaw (R := R) source target (clampedSeedNat seed) N P ell terminalFactor + T thetaExponent H (ell ^ 80) tau + +instance localFinalProgramDrawLaw_probability (seed : Seed) : + IsProbabilityMeasure (localFinalProgramDrawLaw (R := R) source target N P T H seed) := by + unfold localFinalProgramDrawLaw + infer_instance + +noncomputable def localFinalProgramValue (rootQ : TargetInterval target.length) (seed : Seed) + (draw : LocalFinalProgramDraw (R := R) source target N P T H seed) : ℝ := + physicalLocalJointValue source target (clampedSeedNat seed) N P ell terminalFactor + T thetaExponent H (ell ^ 80) tau eta kappa delta draw + (Sigma.mk (Fin.mk 0 (Nat.zero_lt_succ J)) PUnit.unit : PhysicalNode M J) S rootQ + +abbrev LocalFinalProgramOutcome := + Seed × (∀ seed : Seed, LocalFinalProgramDraw (R := R) source target N P T H seed) + +noncomputable def localFinalProgramLaw (incoming : Measure Seed) : + Measure (LocalFinalProgramOutcome (M := M) (J := J) (R := R) source target N P T H) := by + classical + exact (localScheduledSeedLaw (R := R) source target N P T S H incoming (computedSeedPassCount N)).prod + (Measure.pi (localFinalProgramDrawLaw (R := R) source target N P T H)) + +instance localFinalProgramLaw_probability (incoming : Measure Seed) [IsProbabilityMeasure incoming] : + IsProbabilityMeasure (localFinalProgramLaw (R := R) source target N P T S H incoming) := by + unfold localFinalProgramLaw + infer_instance + +noncomputable def localFinalProgramAnswer (rootQ : TargetInterval target.length) + (pair : LocalFinalProgramOutcome (M := M) (J := J) (R := R) source target N P T H) : ℕ := + if source = substring target rootQ.lo rootQ.hi then 0 else + integerAnswer N (freshSeedValue + (localFinalProgramValue (M := M) (J := J) (R := R) source target N P T S H rootQ) pair) + +omit [MeasurableSpace (Fin M)] [MeasurableSingletonClass (Fin M)] in +theorem localFinalProgramAnswer_equal (rootQ : TargetInterval target.length) + (heq : source = substring target rootQ.lo rootQ.hi) + (pair : LocalFinalProgramOutcome (M := M) (J := J) (R := R) source target N P T H) : + localFinalProgramAnswer (R := R) source target N P T S H rootQ pair = 0 := by + simp only [localFinalProgramAnswer, heq, ite_true] + +omit [MeasurableSpace (Fin M)] [MeasurableSingletonClass (Fin M)] in +theorem localFinalProgramValue_eq (rootQ : TargetInterval target.length) (seed : Seed) + (draw : LocalFinalProgramDraw (R := R) source target N P T H seed) + (hsize : source.length + target.length ≤ N) (hP : 66 ≤ P) + (hseed : physicalSeedGood source target terminalFactor seed) : + localFinalProgramValue source target N P T S H rootQ seed draw = + finalProgramValue source target N P T S H rootQ seed + (physicalLocalProgramToComplete source target (clampedSeedNat seed) N P ell terminalFactor + T thetaExponent H (ell ^ 80) tau hsize hP Nat.one_le_two_pow + (one_le_pow₀ (by norm_num : (1 : ℚ) ≤ 2)) hseed draw) := by + unfold localFinalProgramValue finalProgramValue + rw [physicalLocalJointValue_eq source target (clampedSeedNat seed) N P ell terminalFactor + T thetaExponent H (ell ^ 80) tau eta kappa delta draw hsize hP Nat.one_le_two_pow + (one_le_pow₀ (by norm_num : (1 : ℚ) ≤ 2)) hseed] + +variable (hN : 0 < N) (hell : 2 ^ 1000 ≤ inputSmallLog N) + (hMeq : M = (integerParameters N).M) (hJeq : J = intervalTreeDepth M source.length) + (hPeq : P = (integerParameters N).P) (hTeq : T = (integerParameters N).T) + (hSeq : S = (integerParameters N).S) (hHeq : H = inputHeight N) + (hsize : source.length + target.length ≤ N) + (bernstein : ∀ b : ℕ, ∀ h : Fin (groupDyadicScales M b (inputSmallLog N)).length, + FiniteBernsteinInput (Measure.pi fun _ : Fin + (groupSampleCount M (inputSmallLog N ^ 80) b (groupDyadicScaleAt M b (inputSmallLog N) h)) => + (PMF.uniformOfFintype (Fin M)).toMeasure)) + +include hN hell hMeq hJeq hPeq hTeq hSeq hHeq hsize bernstein in +theorem localFinalProgram_accuracy (incoming : Measure Seed) [IsProbabilityMeasure incoming] + (hinitial : incoming.real {seed | ¬ physicalSeedGood source target + ((integerParameters N).initialFactor : ℚ) seed} ≤ 1 / 100) + (rootQ : TargetInterval target.length) (epsilon : ℝ) (hepsilon : 0 < epsilon) + (haccuracy : 10 ≤ (inputSmallLog N : ℝ) * epsilon) : + (4 / 5 : ℝ) ≤ (localFinalProgramLaw (R := R) source target N P T S H incoming).real + {pair | stateEditCost source target rootQ ≤ + localFinalProgramAnswer (R := R) source target N P T S H rootQ pair ∧ + (localFinalProgramAnswer (R := R) source target N P T S H rootQ pair : ℝ) ≤ + (1 + epsilon) * stateEditCost source target rootQ} := by + classical + by_cases heq : source = substring target rootQ.lo rootQ.hi + · have hcost : stateEditCost source target rootQ = 0 := + (EditDistortion.cost_eq_zero_iff (s := true)).mpr heq + have hans (pair : LocalFinalProgramOutcome (M := M) (J := J) (R := R) source target N P T H) : + localFinalProgramAnswer (R := R) source target N P T S H rootQ pair = 0 := + localFinalProgramAnswer_equal source target N P T S H rootQ heq pair + simp only [hans, hcost, Nat.cast_zero, mul_zero, le_refl, and_self, Set.ofPred_true, probReal_univ] + norm_num + have hD : 0 < stateEditCost source target rootQ := + Nat.pos_of_ne_zero (fun h => heq ((EditDistortion.cost_eq_zero_iff (s := true)).mp h)) + have hf : 3 ≤ smallLogExponent N := by + have h := (Nat.pow_le_pow_iff_right (by decide : 1 < (2 : ℕ))).mp hell + omega + have hA : (1 : ℚ) ≤ terminalFactor := by + unfold scheduledSeedFactor + exact one_le_pow₀ (by norm_num) + have hAupper : terminalFactor ≤ ((integerParameters N).initialFactor : ℚ) := by + unfold scheduledSeedFactor + rw [← computedSeed_initial_factor] + exact dyadicSeedFactor_bound _ _ _ + have ha := scheduledSeedFactor_terminal_refinement N hf + have hbranch : 0 < M := Nat.pos_of_ne_zero (NeZero.ne M) + have hP := computed_program_grid_lower N P hN hPeq + have hF : 1 ≤ ell := Nat.one_le_two_pow + have hT : 0 < T := by rw [hTeq]; exact (computed_stage_positive_counts N hN hell).1 + have hEll : (0 : ℝ) < ell := Nat.cast_pos.2 (Nat.two_pow_pos _) + let terminalLaw := localScheduledSeedLaw (R := R) source target N P T S H incoming (computedSeedPassCount N) + let good : Seed → Prop := physicalSeedGood source target terminalFactor + let value := localFinalProgramValue (M := M) (J := J) (R := R) source target N P T S H rootQ + have hseed : terminalLaw.real {seed | ¬ good seed} ≤ 1 / 10 := + (localScheduledSeedLaw_failure_lt (R := R) source target N P T S H hN hell hMeq hJeq hPeq + hTeq hSeq hHeq hsize bernstein incoming hinitial).le + have hlower (seed : Seed) (hg : good seed) + (draw : LocalFinalProgramDraw (R := R) source target N P T H seed) : + (stateEditCost source target rootQ : ℝ) ≤ value seed draw := by + rw [show value seed draw = finalProgramValue source target N P T S H rootQ seed + (physicalLocalProgramToComplete source target (clampedSeedNat seed) N P ell terminalFactor + T thetaExponent H (ell ^ 80) tau hsize hP hF hA hg draw) from + localFinalProgramValue_eq source target N P T S H rootQ seed draw hsize hP hg] + have h := (physicalRefinement_stage_bounds source target hbranch (clampedSeedNat seed) N P ell + terminalFactor hsize hP hF hA hg T hT delta + (physicalProgramDrawSelections source target (clampedSeedNat seed) N P ell terminalFactor + T thetaExponent H (ell ^ 80) tau eta kappa + (physicalLocalProgramToComplete source target (clampedSeedNat seed) N P ell terminalFactor + T thetaExponent H (ell ^ 80) tau hsize hP hF hA hg draw)) + (Sigma.mk (Fin.mk 0 (Nat.zero_lt_succ J)) PUnit.unit : PhysicalNode M J) S rootQ).1 + have hleft := (le_max_left _ _).trans h + simpa only [finalProgramValue, ha, Rat.cast_one, div_one, physicalSource, physicalSourceInterval, + sourceIntervalAt, substring, List.take_length, List.drop_zero] using hleft + have hmoment (seed : Seed) (hg : good seed) : + (∫ draw, max (value seed draw - stateEditCost source target rootQ) 0 + ∂localFinalProgramDrawLaw (R := R) source target N P T H seed) ≤ + (stateEditCost source target rootQ : ℝ) / ell := by + let project := physicalLocalProgramToComplete (R := R) source target (clampedSeedNat seed) + N P ell terminalFactor T thetaExponent H (ell ^ 80) tau hsize hP hF hA hg + let fullValue := finalProgramValue (M := M) (J := J) (R := R) source target N P T S H rootQ seed + have hpoint (draw : LocalFinalProgramDraw (R := R) source target N P T H seed) : + value seed draw = fullValue (project draw) := + localFinalProgramValue_eq source target N P T S H rootQ seed draw hsize hP hg + have hmap : (localFinalProgramDrawLaw (R := R) source target N P T H seed).map project = + finalProgramDrawLaw (R := R) source target N P T H seed := + physicalLocalProgramDrawLaw_map source target (clampedSeedNat seed) N P ell terminalFactor + T thetaExponent H (ell ^ 80) tau hsize hP hF hA hg + have hcomp := integral_map (μ := localFinalProgramDrawLaw (R := R) source target N P T H seed) + (φ := project) (measurable_of_finite _).aemeasurable + (f := fun draw => max (fullValue draw - stateEditCost source target rootQ) 0) + (measurable_of_finite _).aestronglyMeasurable + have hfull := physicalProgram_expected_root_excess (R := R) source target N hN hell hMeq hJeq + (clampedSeedNat seed) P hPeq terminalFactor hA hAupper hsize hg T S hTeq hSeq hHeq bernstein rootQ + calc + (∫ draw, max (value seed draw - stateEditCost source target rootQ) 0 + ∂localFinalProgramDrawLaw (R := R) source target N P T H seed) = + ∫ draw, max (fullValue (project draw) - stateEditCost source target rootQ) 0 + ∂localFinalProgramDrawLaw (R := R) source target N P T H seed := by + apply integral_congr_ae + filter_upwards [] with draw + rw [hpoint] + _ = ∫ draw, max (fullValue draw - stateEditCost source target rootQ) 0 + ∂finalProgramDrawLaw (R := R) source target N P T H seed := by rw [← hcomp, hmap] + _ ≤ (stateEditCost source target rootQ : ℝ) / ell := by + simpa only [fullValue, finalProgramValue, finalProgramDrawLaw, one_div_mul_eq_div] using hfull + have hDN : stateEditCost source target rootQ ≤ N := by + have h := physical_state_cost_le (M := M) (J := J) source target N hsize + ((Sigma.mk (Fin.mk 0 (Nat.zero_lt_succ J)) PUnit.unit : PhysicalNode M J), rootQ) + simpa only [physicalSource, physicalSourceInterval, sourceIntervalAt, substring, + List.take_length, List.drop_zero] using h + have h := freshSeed_answer_accuracy (localFinalProgramDrawLaw (R := R) source target N P T H) + terminalLaw good value hDN hD hEll hepsilon haccuracy hseed hlower hmoment + simpa only [localFinalProgramLaw, localFinalProgramAnswer, heq, ite_false, terminalLaw, value] using h + +noncomputable def localWholeFinalAnswer + (pair : LocalFinalProgramOutcome (M := M) (J := J) (R := R) source target N P T H) : ℕ := + localFinalProgramAnswer (R := R) source target N P T S H (finalTargetState target.length) pair + +omit [MeasurableSpace (Fin M)] [MeasurableSingletonClass (Fin M)] in +theorem localWholeFinalAnswer_equal (heq : source = target) + (pair : LocalFinalProgramOutcome (M := M) (J := J) (R := R) source target N P T H) : + localWholeFinalAnswer (R := R) source target N P T S H pair = 0 := by + apply localFinalProgramAnswer_equal + simpa only [finalTargetState, substring, List.take_length, List.drop_zero] using heq + +end Final + +section Coarse + +variable {α : Type*} [DecidableEq α] {M J R : ℕ} + [NeZero M] [NeZero R] [MeasurableSpace (Fin M)] [MeasurableSingletonClass (Fin M)] + (source target : List α) (N P T S H B : ℕ) + [NeZero B] [MeasurableSpace (Fin B)] [MeasurableSingletonClass (Fin B)] + (depth : PhysicalEntry M J target.length → ℕ) + +theorem local_physical_conditional_accuracy (hN : 0 < N) (hell : 2 ^ 1000 ≤ inputSmallLog N) + (hsize : source.length + target.length ≤ N) + (hMeq : M = (integerParameters N).M) (hJeq : J = intervalTreeDepth M source.length) + (hPeq : P = (integerParameters N).P) (hTeq : T = (integerParameters N).T) + (hSeq : S = (integerParameters N).S) (hHeq : H = inputHeight N) + (hB : B = (integerParameters N).B) + (hdepth : ∀ state, depth state = computedCoarseDepth N + (coarseEntryWidth (physicalSource source state.1) (substring target state.2.lo state.2.hi))) + (coarseBernstein : FiniteBernsteinInput (Measure.pi fun _ : Fin B => + (PMF.uniformOfFintype (Fin B)).toMeasure)) + (groupBernstein : ∀ b : ℕ, ∀ h : Fin (groupDyadicScales M b (inputSmallLog N)).length, + FiniteBernsteinInput (Measure.pi fun _ : Fin + (groupSampleCount M (inputSmallLog N ^ 80) b (groupDyadicScaleAt M b (inputSmallLog N) h)) => + (PMF.uniformOfFintype (Fin M)).toMeasure)) + (epsilon : ℝ) (hepsilon : 0 < epsilon) (haccuracy : 10 ≤ (inputSmallLog N : ℝ) * epsilon) : + (2 / 3 : ℝ) ≤ (localFinalProgramLaw (R := R) source target N P T S H + (physicalCoarseSeedLaw source target N B depth)).real + {pair | EditDistortion.edit source target ≤ localWholeFinalAnswer (R := R) source target N P T S H pair ∧ + (localWholeFinalAnswer (R := R) source target N P T S H pair : ℝ) ≤ + (1 + epsilon) * EditDistortion.edit source target} := by + classical + have hsmall : 256 ≤ (2 : ℕ) ^ 1000 := by + have h := pow_le_pow_right₀ (by decide : 1 ≤ (2 : ℕ)) (by decide : 8 ≤ 1000) + norm_num only [show (2 : ℕ) ^ 8 = 256 by norm_num] at h + exact h + have hcut : 200 ≤ inputSmallLog N := by omega + have hinitial := physicalCoarseSeedLaw_failure source target N B depth hN hsize hcut + hB hMeq hJeq hdepth coarseBernstein + have h := localFinalProgram_accuracy (R := R) source target N P T S H hN hell hMeq hJeq hPeq + hTeq hSeq hHeq hsize groupBernstein (physicalCoarseSeedLaw source target N B depth) + hinitial.le (finalTargetState target.length) epsilon hepsilon haccuracy + apply (by norm_num : (2 / 3 : ℝ) ≤ 4 / 5).trans + simpa only [localWholeFinalAnswer, stateEditCost, finalTargetState, substring, + List.take_length, List.drop_zero] using h + +end Coarse + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalGrid.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalGrid.lean new file mode 100644 index 0000000000000000000000000000000000000000..e917f63bc8e695a2005424e8f7a65e30edb7764b --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalGrid.lean @@ -0,0 +1,104 @@ +import OAI.Combinatorics.EditApproximation.Geometry.Grid +import OAI.Combinatorics.EditApproximation.Geometry.DomainCounts +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! +# Direct enumeration of a local grid square + +The algorithm enumerates bounded ranges of grid indices. It does not +scan the unrelated target positions. The completeness theorem includes +boundary states and intervals with equal endpoints. +-/ + +namespace EditApproximation + + + +theorem gridPointsBetween_complete {g lo hi p : ℕ} (hg : 0 < g) + (hlo : lo ≤ p) (hhi : p ≤ hi) (hgrid : g ∣ p) : p ∈ gridPointsBetween g lo hi := by + have hp : g * (p / g) = p := Nat.mul_div_cancel' hgrid + have hstart : lo ⌈/⌉ g ≤ p / g := (ceilDiv_le_iff_le_mul hg).2 (by omega) + have hend : p / g ≤ hi / g := Nat.div_le_div_right hhi + apply List.mem_map.mpr + refine ⟨p / g, List.mem_range'.mpr ?_, hp⟩ + refine ⟨p / g - lo ⌈/⌉ g, by omega, ?_⟩ + omega + +theorem gridPointsBetween_sound {g lo hi p : ℕ} (hg : 0 < g) + (hp : p ∈ gridPointsBetween g lo hi) : lo ≤ p ∧ p ≤ hi ∧ g ∣ p := by + obtain ⟨i, hmem, rfl⟩ := List.mem_map.mp hp + obtain ⟨j, hj, rfl⟩ := List.mem_range'.mp hmem + have hstart : lo ≤ g * (lo ⌈/⌉ g) := (ceilDiv_le_iff_le_mul hg).mp le_rfl + have hindex : lo ⌈/⌉ g + 1 * j ≤ hi / g := by omega + have hfinish := Nat.mul_div_le hi g + exact ⟨by nlinarith, (Nat.mul_le_mul_left g hindex).trans hfinish, dvd_mul_right _ _⟩ + +theorem gridPointsBetween_length (g lo hi : ℕ) : + (gridPointsBetween g lo hi).length = (hi / g + 1) - lo ⌈/⌉ g := by + simp only [gridPointsBetween, List.length_map, List.length_range'] + +theorem gridPointsBetween_length_le (g lo hi : ℕ) (hg : 0 < g) : + (gridPointsBetween g lo hi).length ≤ (hi - lo) / g + 2 := by + rw [gridPointsBetween_length] + have hceil : lo ≤ g * (lo ⌈/⌉ g) := (ceilDiv_le_iff_le_mul hg).mp le_rfl + have hfloor : lo / g ≤ lo ⌈/⌉ g := by + have hdiv := Nat.div_le_div_right (c := g) hceil + simpa only [Nat.mul_div_right _ hg] using hdiv + by_cases horder : lo ≤ hi + · have hlo := Nat.lt_mul_div_succ lo hg + have hdiff := Nat.lt_mul_div_succ (hi - lo) hg + have hsplit : lo + (hi - lo) = hi := Nat.add_sub_of_le horder + have hdiv : hi / g < lo / g + (hi - lo) / g + 2 := by + apply (Nat.div_lt_iff_lt_mul hg).2 + nlinarith + apply Nat.sub_le_of_le_add + calc + hi / g + 1 ≤ lo / g + (hi - lo) / g + 2 := hdiv + _ ≤ (lo ⌈/⌉ g) + (hi - lo) / g + 2 := by gcongr + _ = (hi - lo) / g + 2 + lo ⌈/⌉ g := by omega + · have hmono := Nat.div_le_div_right (c := g) (by omega : hi ≤ lo) + have hshort : hi / g + 1 - lo ⌈/⌉ g ≤ 1 := Nat.sub_le_of_le_add (by omega) + exact hshort.trans ((by decide : 1 ≤ 2).trans (Nat.le_add_left 2 _)) + + + +theorem localTargetStates_complete {n g radius : ℕ} (hg : 0 < g) + (q r : TargetInterval n) (hlo : Nat.dist q.lo r.lo ≤ radius) + (hhi : Nat.dist q.hi r.hi ≤ radius) (hgrid : g ∣ r.lo ∧ g ∣ r.hi) : + r ∈ localTargetStates n g radius q := by + have hlo' : q.lo - radius ≤ r.lo ∧ r.lo ≤ q.lo + radius := by + unfold Nat.dist at hlo + omega + have hhi' : q.hi - radius ≤ r.hi ∧ r.hi ≤ q.hi + radius := by + unfold Nat.dist at hhi + omega + apply List.mem_flatMap.mpr + refine ⟨r.lo, gridPointsBetween_complete hg hlo'.1 hlo'.2 hgrid.1, ?_⟩ + apply List.mem_filterMap.mpr + refine ⟨r.hi, gridPointsBetween_complete hg hhi'.1 hhi'.2 hgrid.2, ?_⟩ + rw [makeTargetState, dite_eq_left (show r.lo ≤ r.hi ∧ r.hi ≤ n from ⟨r.ordered, r.valid⟩)] + +theorem localTargetStates_length_le {n g radius : ℕ} (hg : 0 < g) + (q : TargetInterval n) : + (localTargetStates n g radius q).length ≤ (2 * radius / g + 2) ^ 2 := by + have hpoint (p : ℕ) : + (gridPointsBetween g (p - radius) (p + radius)).length ≤ 2 * radius / g + 2 := by + have hlength := gridPointsBetween_length_le g (p - radius) (p + radius) hg + have hwidth : p + radius - (p - radius) ≤ 2 * radius := by omega + exact hlength.trans (Nat.add_le_add_right (Nat.div_le_div_right hwidth) 2) + have hlist := list_flatMap_length_le + (gridPointsBetween g (q.lo - radius) (q.lo + radius)) + (fun lo => (gridPointsBetween g (q.hi - radius) (q.hi + radius)).filterMap + fun hi => makeTargetState n lo hi) + (2 * radius / g + 2) (by + intro lo hlo + exact (List.length_filterMap_le _ _).trans (hpoint q.hi)) + exact hlist.trans (by simpa only [pow_two] using + (Nat.mul_le_mul_right (2 * radius / g + 2) (hpoint q.lo))) + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalGroupBudget.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalGroupBudget.lean new file mode 100644 index 0000000000000000000000000000000000000000..21cb0dea8fdbdd26c618f2fe9390dd424e26c80b --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalGroupBudget.lean @@ -0,0 +1,48 @@ +import OAI.Combinatorics.EditApproximation.Geometry.LocalGroupCones +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalQueryBudget + +namespace OAI + +/-! Bounded local cell loops on arbitrary initial seeds. -/ + +namespace EditApproximation + +theorem localCellGroupActions_length {α : Type*} {M : ℕ} (source target : List α) + (parent : TargetInterval source.length) (N P F exponent Q : ℕ) (tau a : ℚ) + (parentInitial : TargetInterval target.length → ℚ) + (child initial current : Fin M → TargetInterval target.length → ℚ) + (draw : CellGroupDraws M F Q) (q : TargetInterval target.length) + (hF : 1 ≤ F) (hw : 0 ≤ parentInitial q) : + (localCellGroupActions source target parent N P F exponent Q tau a parentInitial + child initial current draw q).length ≤ + (dyadicQueryWindow N (parentInitial q) a F).length * + ((32 * F + 2) * 2 ^ exponent + 2) ^ 2 := by + unfold localCellGroupActions + apply list_flatMap_length_le + intro b hb + have hwindow := of_decide_eq_true (List.mem_filter.mp hb).2 + have hbpos : 1 ≤ b := by + obtain ⟨e, _, rfl⟩ := List.mem_map.mp (List.mem_filter.mp hb).1 + exact Nat.one_le_two_pow + exact (List.length_filterMap_le _ _).trans + (localTargetCells_query_length F b exponent q (parentInitial q) hF hbpos hw hwindow.1) + +theorem localCellGroupActions_length_refinement {α : Type*} {M : ℕ} (source target : List α) + (parent : TargetInterval source.length) (N P F exponent Q initialExponent : ℕ) (tau A : ℚ) + (parentInitial : TargetInterval target.length → ℚ) + (child initial current : Fin M → TargetInterval target.length → ℚ) + (draw : CellGroupDraws M F Q) (q : TargetInterval target.length) + (hF : 1 ≤ F) (hw : 0 ≤ parentInitial q) + (hFbound : (F : ℚ) ≤ (2 : ℚ) ^ initialExponent) + (hAbound : A ≤ (2 : ℚ) ^ initialExponent) : + (localCellGroupActions source target parent N P F exponent Q tau (refinementFactor A F) parentInitial + child initial current draw q).length ≤ + (initialExponent + 8) * ((32 * F + 2) * 2 ^ exponent + 2) ^ 2 := by + exact (localCellGroupActions_length source target parent N P F exponent Q tau (refinementFactor A F) + parentInitial child initial current draw q hF hw).trans + (Nat.mul_le_mul_right _ (refinement_query_window_length N F initialExponent A (parentInitial q) + hF hFbound hAbound)) + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalGroupCones.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalGroupCones.lean new file mode 100644 index 0000000000000000000000000000000000000000..f872ead094e7453f67c3e3da6de4b7f4b6926091 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalGroupCones.lean @@ -0,0 +1,167 @@ +import OAI.Combinatorics.EditApproximation.Geometry.CellGroupSelection +import OAI.Combinatorics.EditApproximation.Geometry.LocalRefinementCones +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Cell-keyed shared draws permit direct local group enumeration. The +complete and local finite programs use the same draw at every cell label. -/ + +namespace EditApproximation + +theorem targetCell_of_cellTargetStates {n g : ℕ} {side : ℚ} + (cell : ℕ × ℕ) (hg : 0 < g) (hside : 0 < side) (r : TargetInterval n) + (hr : r ∈ cellTargetStates n g side cell) : targetCell side r = cell := by + have hc := (cellTargetStates_mem cell hg r).mp hr + apply Prod.ext + · apply (Nat.floor_eq_iff (div_nonneg (Nat.cast_nonneg _) hside.le)).2 + exact ⟨(le_div_iff₀ hside).2 hc.2.2.1, (div_lt_iff₀ hside).2 hc.2.2.2.1⟩ + · apply (Nat.floor_eq_iff (div_nonneg (Nat.cast_nonneg _) hside.le)).2 + exact ⟨(le_div_iff₀ hside).2 hc.2.2.2.2.1, (div_lt_iff₀ hside).2 hc.2.2.2.2.2⟩ + +theorem chooseCellGroupAction_center {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (b P F exponent Q : ℕ) (tau a : ℚ) + (parentInitial : TargetInterval target.length → ℚ) + (child initial current : Fin M → TargetInterval target.length → ℚ) (cell : ℕ × ℕ) + (draw : ∀ scale : Fin (groupDyadicScales M b F).length, + Fin (groupSampleCount M Q b (groupDyadicScaleAt M b F scale)) → Fin M) + (action : PhysicalRationalAction M target.length) + (hselected : chooseCellGroupAction source target parent b P F exponent Q tau a + parentInitial child initial current cell draw = some action) : + action.center ∈ cellRepresentativeStates target.length P F b a parentInitial + ((2 : ℚ) ^ (-(exponent : ℤ))) cell := by + unfold chooseCellGroupAction at hselected + dsimp only at hselected + split_ifs at hselected with hempty + have heq := Option.some.inj hselected + rw [← heq] + exact (unskippedBandList_mem_iff _ _).mp + (chooseUnskippedGroup_spec Q current _ hempty draw).1 + +def representativeCells {n : ℕ} (N P F b : ℕ) (a theta : ℚ) + (initial : TargetInterval n → ℚ) : List (ℕ × ℕ) := + (((representativeList N P F a initial).filter fun br => decide (br.1 = b)).map + fun br => targetCell (theta * b) br.2).eraseDups + +theorem representativeCells_mem {n N P F b : ℕ} (a theta : ℚ) + (initial : TargetInterval n → ℚ) (r : TargetInterval n) + (hr : (b, r) ∈ representativeList N P F a initial) : + targetCell (theta * b) r ∈ representativeCells N P F b a theta initial := by + apply List.mem_eraseDups.mpr + apply List.mem_map.mpr + exact ⟨(b, r), List.mem_filter.mpr ⟨hr, by simp⟩, rfl⟩ + + + +section CellPrograms + +variable {α : Type*} {M : ℕ} (source target : List α) + (parent : TargetInterval source.length) (N P F exponent Q : ℕ) (tau a : ℚ) + (parentInitial : TargetInterval target.length → ℚ) + (child initial current : Fin M → TargetInterval target.length → ℚ) + (draw : CellGroupDraws M F Q) + +local notation "theta" => (2 : ℚ) ^ (-(exponent : ℤ)) + +def completeCellGroupActions : List (PhysicalRationalAction M target.length) := + (dyadicScales N).flatMap fun b => + (representativeCells N P F b a theta parentInitial).filterMap fun cell => + chooseCellGroupAction source target parent b P F exponent Q tau a parentInitial + child initial current cell (draw b cell) + + + +theorem cellGroupAction_location (b : ℕ) (hb : b ∈ dyadicScales N) (cell : ℕ × ℕ) + (action : PhysicalRationalAction M target.length) + (hselected : chooseCellGroupAction source target parent b P F exponent Q tau a + parentInitial child initial current cell (draw b cell) = some action) : + (b, action.center) ∈ representativeList N P F a parentInitial ∧ + targetCell (theta * b) action.center = cell := by + have hcenter := chooseCellGroupAction_center source target parent b P F exponent Q tau a + parentInitial child initial current cell (draw b cell) action hselected + have hrep := cellRepresentativeStates_mem_representatives a parentInitial theta cell action.center hb hcenter + have hbpos : 0 < b := by + obtain ⟨e, _, rfl⟩ := List.mem_map.mp hb + positivity + have hcell := (List.mem_filter.mp hcenter).1 + exact ⟨hrep, targetCell_of_cellTargetStates cell (by unfold seedGridSpacing; omega) + (by positivity) action.center hcell⟩ + +theorem localCellGroupActions_subset (q : TargetInterval target.length) : + ∀ action ∈ localCellGroupActions source target parent N P F exponent Q tau a parentInitial + child initial current draw q, + action ∈ completeCellGroupActions source target parent N P F exponent Q tau a parentInitial + child initial current draw := by + intro action ha + obtain ⟨b, hb, ha⟩ := List.mem_flatMap.mp ha + obtain ⟨cell, _, hselected⟩ := List.mem_filterMap.mp ha + have hb' := (List.mem_filter.mp hb).1 + have hlocation := cellGroupAction_location source target parent N P F exponent Q tau a + parentInitial child initial current draw b hb' cell action hselected + have hcell := representativeCells_mem a theta parentInitial action.center hlocation.1 + rw [hlocation.2] at hcell + exact List.mem_flatMap.mpr ⟨b, hb', List.mem_filterMap.mpr ⟨cell, hcell, hselected⟩⟩ + +theorem completeCellGroupActions_wide : + ∀ action ∈ completeCellGroupActions source target parent N P F exponent Q tau a parentInitial + child initial current draw, + action ∈ rationalActualWideActions parent (representativeList N P F a parentInitial) P := by + intro action ha + obtain ⟨b, hb, ha⟩ := List.mem_flatMap.mp ha + obtain ⟨cell, _, hselected⟩ := List.mem_filterMap.mp ha + exact chooseCellGroupAction_wide_mem source target parent N b P F exponent Q tau a parentInitial + child initial current cell (draw b cell) hb action hselected + +/-- All improving complete cell cones occur in the bounded local cell +program. Identical cell keys use identical shared samples. -/ +theorem localCellGroupMinimum_eq (q : TargetInterval target.length) (fallback : ℚ) + (ha : 1 ≤ a) (hF : 1 ≤ F) (hfallback : fallback ≤ parentInitial q) + (hcurrent : ∀ i r, 0 ≤ current i r) + (hspatial : ∀ r, |parentInitial q - parentInitial r| ≤ 32 * F * targetEndpointDistance q r) : + rationalMinimum fallback + ((localCellGroupActions source target parent N P F exponent Q tau a parentInitial + child initial current draw q).map + (rationalActionValue (fun q r => targetEndpointDistance q r) (128 * F) + (fun is => current is.1 is.2) q)) = + rationalMinimum fallback + ((completeCellGroupActions source target parent N P F exponent Q tau a parentInitial + child initial current draw).map + (rationalActionValue (fun q r => targetEndpointDistance q r) (128 * F) + (fun is => current is.1 is.2) q)) := by + apply rationalMinimum_local_complete_lt + _ _ _ fallback (localCellGroupActions_subset source target parent N P F exponent Q tau a + parentInitial child initial current draw q) + intro action haction hvalue + have hwide := completeCellGroupActions_wide source target parent N P F exponent Q tau a + parentInitial child initial current draw action haction + have hcharge := rationalActionValue_pruned_lower (fun q r => targetEndpointDistance q r) + (128 * (F : ℚ)) (fun is => current is.1 is.2) q action + (128 * (F : ℚ) * targetEndpointDistance q action.center) le_rfl + (rationalActualWideActions_connection_nonneg parent _ P action hwide) (fun i => hcurrent _ _) + have hw : 0 < parentInitial q := by + have hnonneg : (0 : ℚ) ≤ 128 * (F : ℚ) * targetEndpointDistance q action.center := by positivity + exact hnonneg.trans_lt ((hcharge.trans_lt hvalue).trans_le hfallback) + obtain ⟨b, hb, haction⟩ := List.mem_flatMap.mp haction + obtain ⟨cell, _, hselected⟩ := List.mem_filterMap.mp haction + have hlocation := cellGroupAction_location source target parent N P F exponent Q tau a + parentInitial child initial current draw b hb cell action hselected + have hconditions := representativeList_conditions a parentInitial hlocation.1 + have hnumeric := refinement_cone_locality_numeric hw ha (show (1 : ℚ) ≤ F by exact_mod_cast hF) + (Nat.cast_nonneg (α := ℚ) (targetEndpointDistance q action.center)) (hspatial action.center) + hconditions.2.2.2 le_rfl ((hcharge.trans hvalue.le).trans hfallback) + have hdist : targetEndpointDistance q action.center ≤ ⌈parentInitial q⌉₊ := by + exact_mod_cast hnumeric.2.2.trans (Nat.le_ceil _) + have hbpos : 0 < b := by obtain ⟨e, _, rfl⟩ := List.mem_map.mp hb; positivity + have hcell := localTargetCells_complete (theta * b) (by positivity) ⌈parentInitial q⌉₊ q action.center + (by unfold targetEndpointDistance at hdist; omega) (by unfold targetEndpointDistance at hdist; omega) + rw [hlocation.2] at hcell + apply List.mem_flatMap.mpr + refine ⟨b, List.mem_filter.mpr ⟨hb, decide_eq_true ⟨hnumeric.1, hnumeric.2.1⟩⟩, ?_⟩ + exact List.mem_filterMap.mpr ⟨cell, hcell, hselected⟩ + +end CellPrograms + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalGroupSourceQuery.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalGroupSourceQuery.lean new file mode 100644 index 0000000000000000000000000000000000000000..6ae4a485e736c75f535104181159883e2707679c --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalGroupSourceQuery.lean @@ -0,0 +1,129 @@ +import OAI.Combinatorics.EditApproximation.Geometry.LocalOnlineSourceQuery +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Whole-cell group samples are exposed through scalar source reads. +Every needed scale/sample coordinate is enumerated once per group; unused +groups are absent from this query. -/ + +namespace EditApproximation + + + + + +theorem groupScalarKeys_mem (M F Q : ℕ) (groups : List (ℕ × (ℕ × ℕ))) + (key : ℕ × (ℕ × ℕ)) (hk : key ∈ groups) + (scale : Fin (groupDyadicScales M key.1 F).length) + (sample : Fin (groupSampleCount M Q key.1 (groupDyadicScaleAt M key.1 F scale))) : + (⟨key, scale, sample⟩ : GroupScalarKey M F Q) ∈ groupScalarKeys M F Q groups := by + apply List.mem_flatMap.mpr + refine ⟨key, hk, List.mem_flatMap.mpr ?_⟩ + exact ⟨scale, List.mem_finRange _, List.mem_map.mpr ⟨sample, List.mem_finRange _, rfl⟩⟩ + +theorem groupScalarKeys_length_le (M F Q labels : ℕ) (groups : List (ℕ × (ℕ × ℕ))) + (hlabels : ∀ key ∈ groups, (groupDyadicScales M key.1 F).length ≤ labels) : + (groupScalarKeys M F Q groups).length ≤ groups.length * labels * M := by + have hgroup (key : ℕ × (ℕ × ℕ)) (hk : key ∈ groups) : + ((List.finRange (groupDyadicScales M key.1 F).length).flatMap fun scale => + (List.finRange (groupSampleCount M Q key.1 (groupDyadicScaleAt M key.1 F scale))).map + fun sample => (⟨key, scale, sample⟩ : GroupScalarKey M F Q)).length ≤ labels * M := by + apply le_trans (list_flatMap_length_le _ _ M ?_) ?_ + · intro scale _ + simp only [List.length_map, List.length_finRange] + exact min_le_left _ _ + · simpa only [List.length_finRange] using Nat.mul_le_mul_right M (hlabels key hk) + calc + _ ≤ groups.length * (labels * M) := list_flatMap_length_le _ _ _ hgroup + _ = _ := by ring + +def groupScalarValue {M F Q : ℕ} (draw : CellGroupDraws M F Q) (key : GroupScalarKey M F Q) : ℚ := + (draw key.1.1 key.1.2 key.2.1 key.2.2).val + + + +theorem groupDrawFromValues_eq {M F Q : ℕ} [NeZero M] + (groups : List (ℕ × (ℕ × ℕ))) (draw : CellGroupDraws M F Q) + (key : ℕ × (ℕ × ℕ)) (hk : key ∈ groups) : + groupDrawFromValues (groupScalarKeys M F Q groups) + ((groupScalarKeys M F Q groups).map (groupScalarValue draw)) key.1 key.2 = draw key.1 key.2 := by + classical + funext scale sample + apply Fin.ext + simp only [groupDrawFromValues, Fin.val_ofNat] + rw [finiteAnswerTable_map _ _ _ (groupScalarKeys_mem M F Q groups key hk scale sample)] + simp only [groupScalarValue, Nat.floor_natCast] + exact Nat.mod_eq_of_lt (draw key.1 key.2 scale sample).isLt + +theorem localCellGroupActions_congr_draw {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (N P F exponent Q : ℕ) (tau a : ℚ) + (initial : TargetInterval target.length → ℚ) + (child warmup current : Fin M → TargetInterval target.length → ℚ) + (left right : CellGroupDraws M F Q) (q : TargetInterval target.length) + (h : ∀ key ∈ localGroupQueryKeys N F exponent a initial q, left key.1 key.2 = right key.1 key.2) : + localCellGroupActions source target parent N P F exponent Q tau a initial child warmup current left q = + localCellGroupActions source target parent N P F exponent Q tau a initial child warmup current right q := by + unfold localCellGroupActions + apply List.flatMap_congr + intro b hb + apply List.filterMap_congr + intro cell hc + rw [h (b, cell) (List.mem_flatMap.mpr ⟨b, hb, List.mem_map.mpr ⟨cell, hc, rfl⟩⟩)] + +section Query + +variable {ι α : Type*} (source target : List α) {M : ℕ} [NeZero M] + (parent : TargetInterval source.length) (N P F exponent H Q : ℕ) + (tau a eta kappa delta : ℚ) (t : ℕ) + (parentInitial : TargetInterval target.length → ℚ) + (child initial : Fin M → TargetInterval target.length → ℚ) + (integer : ℕ → TargetInterval target.length → ℕ) (q : TargetInterval target.length) + (readGroup : GroupScalarKey M F Q → FiniteQuery ι) + (readEarlier : (Fin M × ℕ × TargetInterval target.length) → FiniteQuery ι) + (readCurrent : (Fin M × TargetInterval target.length) → FiniteQuery ι) + +noncomputable def localGroupSourceStepQuery : FiniteQuery ι := + let keys := groupScalarKeys M F Q (localGroupQueryKeys N F exponent a parentInitial q) + FiniteQuery.collect readGroup keys fun values => + localRefinementStepQuery source target parent N P F exponent H Q tau a eta kappa delta t + parentInitial child initial (groupDrawFromValues keys values) integer q readEarlier readCurrent + +theorem localGroupSourceStepQuery_value (oracle : ι → ℚ) (draw : CellGroupDraws M F Q) + (earlier : PhysicalChildTables M target.length) + (current : Fin M → TargetInterval target.length → ℚ) (ht : 0 < t) + (hreadGroup : ∀ key ∈ groupScalarKeys M F Q (localGroupQueryKeys N F exponent a parentInitial q), + (readGroup key).value oracle = groupScalarValue draw key) + (hreadEarlier : ∀ input, (readEarlier input).value oracle = earlier input.1 input.2.1 input.2.2) + (hreadCurrent : ∀ input, (readCurrent input).value oracle = current input.1 input.2) : + (localGroupSourceStepQuery source target parent N P F exponent H Q tau a eta kappa delta t + parentInitial child initial integer q readGroup readEarlier readCurrent).value oracle = + rationalLocalWideStep source target parent N P F exponent Q tau a delta parentInitial child initial + (fun i r => earlier i (t - 1) r) current draw + (localOnlineCandidates source target parent N P F exponent H tau a eta kappa + parentInitial child initial earlier (t - 1) integer q) q := by + classical + let groups := localGroupQueryKeys N F exponent a parentInitial q + let keys := groupScalarKeys M F Q groups + have hvalues : keys.map (fun key => (readGroup key).value oracle) = keys.map (groupScalarValue draw) := by + apply List.map_congr_left + intro key hk + exact hreadGroup key hk + let cached := groupDrawFromValues keys (keys.map (groupScalarValue draw)) + have hdraw : ∀ key ∈ groups, cached key.1 key.2 = draw key.1 key.2 := + fun key hk => groupDrawFromValues_eq groups draw key hk + unfold localGroupSourceStepQuery + rw [FiniteQuery.collect_value, hvalues] + rw [localRefinementStepQuery_value source target parent N P F exponent H Q tau a eta kappa delta t + parentInitial child initial cached integer q readEarlier readCurrent oracle earlier current ht + hreadEarlier hreadCurrent] + unfold rationalLocalWideStep + rw [localCellGroupActions_congr_draw source target parent N P F exponent Q tau a parentInitial + child initial current cached draw q hdraw] + +end Query + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalInitialCones.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalInitialCones.lean new file mode 100644 index 0000000000000000000000000000000000000000..6380fc3d24443cd4198100db2b54c2fcb17cccf7 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalInitialCones.lean @@ -0,0 +1,146 @@ +import OAI.Combinatorics.EditApproximation.Geometry.InitialConeTable +import OAI.Combinatorics.EditApproximation.Geometry.LocalGrid +import OAI.Combinatorics.EditApproximation.Geometry.ConeLocality +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! +# Exact local evaluation of the initial cones + +The local implementation enumerates only the stated dyadic scale interval +and the grid square about the query. Zero cones are never searched at a +positive seed query. Equality with the global family is proved on a good +seed; the local program is finite on every input table. +-/ + +namespace EditApproximation + + + + + +theorem rationalMinimum_le_fallback (fallback : ℚ) (values : List ℚ) : + rationalMinimum fallback values ≤ fallback := by + induction values with + | nil => rfl + | cons v rest ih => exact (min_le_right _ _).trans ih + +theorem rationalMinimum_attained (fallback : ℚ) (values : List ℚ) : + rationalMinimum fallback values = fallback ∨ rationalMinimum fallback values ∈ values := by + induction values with + | nil => exact Or.inl rfl + | cons v rest ih => + by_cases h : v ≤ rationalMinimum fallback rest + · exact Or.inr (by simp only [rationalMinimum, min_eq_left h, List.mem_cons, true_or]) + · rw [rationalMinimum, min_eq_right (le_of_not_ge h)] + exact ih.imp_right (fun hmem => List.mem_cons.mpr (Or.inr hmem)) + +theorem localTargetStates_on_grid {n g radius : ℕ} (q r : TargetInterval n) + (hmem : r ∈ localTargetStates n g radius q) : g ∣ r.lo ∧ g ∣ r.hi := by + obtain ⟨lo, hlo, hrest⟩ := List.mem_flatMap.mp hmem + obtain ⟨hi, hhi, hmake⟩ := List.mem_filterMap.mp hrest + unfold makeTargetState at hmake + split at hmake + · cases Option.some.inj hmake + obtain ⟨i, hi, rfl⟩ := List.mem_map.mp hlo + obtain ⟨j, hj, rfl⟩ := List.mem_map.mp hhi + exact ⟨dvd_mul_right _ _, dvd_mul_right _ _⟩ + · contradiction + +theorem localInitialConeCenters_subset {n N P : ℕ} {A : ℚ} + (U : TargetInterval n → ℕ) (q : TargetInterval n) : + ∀ r ∈ localInitialConeCenters N P A U q, r ∈ initialConeCenters N P A U := by + intro r hr + obtain ⟨b, hb, hgrid⟩ := List.mem_flatMap.mp hr + have hscale := (List.mem_filter.mp hb).1 + have hlocal := (List.mem_filter.mp hgrid).1 + have heligible : (b : ℚ) / 2 ≤ U r ∧ (U r : ℚ) ≤ 4 * A * b := by + simpa using (List.mem_filter.mp hgrid).2 + have hdiv := localTargetStates_on_grid q r hlocal + exact initialConeCenters_mem_grid U r hscale ⟨hdiv.1, hdiv.2, heligible⟩ + +theorem localInitialConeTable_eq_global {α : Type*} (source target : List α) + (U : TargetInterval target.length → ℕ) (N P F : ℕ) (A a : ℚ) + (hP : 66 ≤ P) (hF : 1 ≤ F) (hA : 1 ≤ A) (ha : 1 ≤ a) + (hfactor : A ≤ a * F) + (hcostN : ∀ r, stateEditCost source target r ≤ N) + (hseed : ∀ r, stateEditCost source target r ≤ U r ∧ + (U r : ℚ) ≤ A * stateEditCost source target r) + (q : TargetInterval target.length) : + localInitialConeTable source target U N P F A a q = + globalInitialConeTable source target U N P F A a q := by + let global := globalInitialConeTable source target U N P F A a q + have hbounds := globalInitialConeTable_bounds source target U N P F A a + hP hF hA ha hfactor hcostN hseed q + have hFQ : (0 : ℚ) < F := by exact_mod_cast (by omega : 0 < F) + have hnonneg : 0 ≤ global := (abs_nonneg _).trans ((le_max_right _ _).trans hbounds.1) + by_cases hzero : U q = 0 + · have hc : stateEditCost source target q = 0 := by have h := (hseed q).1; omega + have hg : global = 0 := by + have hupper := hbounds.2 + rw [hc, Nat.cast_zero, mul_zero] at hupper + exact le_antisymm hupper hnonneg + simpa only [localInitialConeTable, ite_true, hzero] using hg.symm + have hc : (0 : ℚ) < stateEditCost source target q := by + have h := (hseed q).2 + have hU : (0 : ℚ) < U q := by exact_mod_cast (by omega : 0 < U q) + by_contra hn + have hc0 : (stateEditCost source target q : ℚ) = 0 := + le_antisymm (le_of_not_gt hn) (Nat.cast_nonneg _) + rw [hc0, mul_zero] at h + linarith + rw [localInitialConeTable, ite_eq_right hzero] + apply le_antisymm + · rcases rationalMinimum_attained ((32 * F + 1) * N) + ((initialConeCenters N P A U).map + (initialConeValue source target U a (32 * F) q)) with hfallback | hmember + · exact (rationalMinimum_le_fallback _ _).trans_eq hfallback.symm + · obtain ⟨r, hr, hvalue⟩ := List.mem_map.mp hmember + have hconeUpper : initialConeValue source target U a (32 * F) q r ≤ + 2 * F * stateEditCost source target q := hvalue.le.trans hbounds.2 + have hconeLower : (32 * F : ℚ) * targetEndpointDistance q r ≤ + initialConeValue source target U a (32 * F) q r := by + unfold initialConeValue scaledSeedValue + have hscaled : (0 : ℚ) ≤ max (⌈(U r : ℚ) / a⌉₊ : ℚ) + |rationalStateGap source target r| := (abs_nonneg _).trans (le_max_right _ _) + linarith + rcases List.mem_append.mp hr with hzeroCenter | hgridCenter + · have hUr : U r = 0 := by simpa using (List.mem_filter.mp hzeroCenter).2 + have hcr : stateEditCost source target r = 0 := by have h := (hseed r).1; omega + have hdist := stateEditCost_distance_abs source target q r + rw [hcr, Nat.cast_zero, sub_zero, abs_of_pos hc] at hdist + have hmul := mul_le_mul_of_nonneg_left hdist (by positivity : (0 : ℚ) ≤ 32 * F) + nlinarith + · obtain ⟨b, hb, helig⟩ := List.mem_flatMap.mp hgridCenter + have heligible : seedGridSpacing b P ∣ r.lo ∧ seedGridSpacing b P ∣ r.hi ∧ + (b : ℚ) / 2 ≤ U r ∧ (U r : ℚ) ≤ 4 * A * b := by + simpa using (List.mem_filter.mp helig).2 + have hlocality := initial_cone_locality_numeric hc hA hFQ (Nat.cast_nonneg b) + ⟨by exact_mod_cast (hseed q).1, (hseed q).2⟩ + ⟨by exact_mod_cast (hseed r).1, (hseed r).2⟩ + (stateEditCost_distance_abs source target q r) heligible.2.2 hconeLower hconeUpper + have hdist : targetEndpointDistance q r ≤ U q := by exact_mod_cast hlocality.2.2.2.2 + have hmemLocal : r ∈ localInitialConeCenters N P A U q := by + apply List.mem_flatMap.mpr + refine ⟨b, List.mem_filter.mpr ⟨hb, ?_⟩, List.mem_filter.mpr ⟨?_, ?_⟩⟩ + · simpa using ⟨hlocality.2.2.1, hlocality.2.2.2.1⟩ + · apply localTargetStates_complete (by unfold seedGridSpacing; omega) q r + (by unfold targetEndpointDistance at hdist; omega) + (by unfold targetEndpointDistance at hdist; omega) + ⟨heligible.1, heligible.2.1⟩ + · simpa using heligible.2.2 + exact (rationalMinimum_le_member _ _ + (List.mem_map.mpr ⟨r, hmemLocal, rfl⟩)).trans_eq hvalue + · apply (le_rationalMinimum_iff _ _ _).2 + constructor + · exact rationalMinimum_le_fallback _ _ + · intro v hv + obtain ⟨r, hr, rfl⟩ := List.mem_map.mp hv + exact rationalMinimum_le_member _ _ (List.mem_map.mpr + ⟨r, localInitialConeCenters_subset U q r hr, rfl⟩) + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalMedianDrawLaw.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalMedianDrawLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..dd0fd99610d874b5304e2a0696ea10dc040e9ea3 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalMedianDrawLaw.lean @@ -0,0 +1,131 @@ +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalLocalJointProgram +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalSeedTables + +namespace OAI + +/-! The local bounded-key random source implements the same whole-table +median pass as the complete program. Copies are independent, while all +entries within a copy retain their shared online and group draws. -/ + +namespace EditApproximation + +open MeasureTheory ProbabilityTheory + +section Median + +variable {α : Type*} [DecidableEq α] {M J R : ℕ} [NeZero M] [NeZero R] + [MeasurableSpace (Fin M)] [MeasurableSingletonClass (Fin M)] + (source target : List α) (U : PhysicalEntry M J target.length → ℕ) + (N P F : ℕ) (A : ℚ) (T exponent H Q : ℕ) (tau eta kappa delta : ℚ) + (a S copies : ℕ) + +/-- The executable local pass: scale and round each full-copy value, take +the upper median, and clamp each result to the common finite seed type. -/ +noncomputable def physicalLocalMedianUpdateTable + (draws : Fin copies → PhysicalLocalProgramDraw (R := R) + source target U N P F A T exponent H Q tau) : + ClampedPhysicalSeed M J target.length N := fun state => + ⟨finiteMedianSeed N copies + (fun draw => ⌈(a : ℚ) * physicalLocalJointValue source target U N P F A T exponent H Q + tau eta kappa delta draw state.1 S state.2⌉₊) draws, + Nat.lt_succ_of_le (min_le_left _ _)⟩ + +variable (hsize : source.length + target.length ≤ N) (hP : 66 ≤ P) (hF : 1 ≤ F) (hA : 1 ≤ A) + (hseed : ∀ state, stateEditCost (physicalSource source state.1) target state.2 ≤ U state ∧ + (U state : ℚ) ≤ A * stateEditCost (physicalSource source state.1) target state.2) + +omit [MeasurableSpace (Fin M)] [MeasurableSingletonClass (Fin M)] in +theorem physicalLocalMedianUpdateTable_eq + (draws : Fin copies → PhysicalLocalProgramDraw (R := R) + source target U N P F A T exponent H Q tau) : + physicalLocalMedianUpdateTable source target U N P F A T exponent H Q tau eta kappa delta + a S copies draws = + physicalMedianUpdateTable source target U N P F A T delta a S copies + (physicalProgramDrawSelections source target U N P F A T exponent H Q tau eta kappa) + (fun i => physicalLocalProgramToComplete source target U N P F A T exponent H Q tau + hsize hP hF hA hseed (draws i)) := by + funext state + apply Fin.ext + change min N (upperMedian (List.ofFn fun i : Fin copies => + ⌈(a : ℚ) * physicalLocalJointValue source target U N P F A T exponent H Q + tau eta kappa delta (draws i) state.1 S state.2⌉₊)) = _ + apply congrArg (fun values : Fin copies → ℕ => min N (upperMedian (List.ofFn values))) + funext i + rw [physicalLocalJointValue_eq source target U N P F A T exponent H Q tau eta kappa delta + (draws i) hsize hP hF hA hseed] + rfl + +omit [NeZero R] in +/-- The restriction to used keys preserves independence between complete +program copies, as well as the law of each copy. -/ +theorem physicalLocalProgramCopyDrawLaw_map : + (Measure.pi fun _ : Fin copies => physicalLocalProgramDrawLaw (R := R) + source target U N P F A T exponent H Q tau).map + (fun draws i => physicalLocalProgramToComplete source target U N P F A T exponent H Q tau + hsize hP hF hA hseed (draws i)) = + Measure.pi (fun _ : Fin copies => physicalProgramDrawLaw (R := R) + source target U N P F A T exponent H Q tau) := by + classical + let : IsProbabilityMeasure (physicalLocalProgramDrawLaw (R := R) + source target U N P F A T exponent H Q tau) := by + unfold physicalLocalProgramDrawLaw + infer_instance + have hmap := physicalLocalProgramDrawLaw_map (R := R) + source target U N P F A T exponent H Q tau hsize hP hF hA hseed + have hcopies := Measure.pi_map_pi + (μ := fun _ : Fin copies => physicalLocalProgramDrawLaw (R := R) + source target U N P F A T exponent H Q tau) + (f := fun _ => physicalLocalProgramToComplete source target U N P F A T exponent H Q tau + hsize hP hF hA hseed) + (fun _ => (measurable_of_finite _).aemeasurable) + simpa only [hmap] using hcopies + +include hsize hP hF hA hseed in +/-- Equality of the entire returned seed-table distribution. No independent +per-entry resampling is introduced by replacing complete copies with local +bounded-key copies. -/ +theorem physicalLocalMedianUpdateTable_law : + (Measure.pi fun _ : Fin copies => physicalLocalProgramDrawLaw (R := R) + source target U N P F A T exponent H Q tau).map + (physicalLocalMedianUpdateTable source target U N P F A T exponent H Q tau eta kappa delta + a S copies) = + (Measure.pi fun _ : Fin copies => physicalProgramDrawLaw (R := R) + source target U N P F A T exponent H Q tau).map + (physicalMedianUpdateTable source target U N P F A T delta a S copies + (physicalProgramDrawSelections source target U N P F A T exponent H Q tau eta kappa)) := by + classical + rw [← physicalLocalProgramCopyDrawLaw_map source target U N P F A T exponent H Q tau copies + hsize hP hF hA hseed] + rw [Measure.map_map (measurable_of_finite _) (measurable_of_finite _)] + congr 1 + funext draws + exact physicalLocalMedianUpdateTable_eq source target U N P F A T exponent H Q tau eta kappa + delta a S copies hsize hP hF hA hseed draws + +include hsize hP hF hA hseed in +/-- Any whole-seed event, including the simultaneous good-seed event, has +the same probability for the actual local median pass. -/ +theorem physicalLocalMedianUpdateTable_event + (event : Set (ClampedPhysicalSeed M J target.length N)) : + (Measure.pi fun _ : Fin copies => physicalLocalProgramDrawLaw (R := R) + source target U N P F A T exponent H Q tau).real + {draws | physicalLocalMedianUpdateTable source target U N P F A T exponent H Q + tau eta kappa delta a S copies draws ∈ event} = + (Measure.pi fun _ : Fin copies => physicalProgramDrawLaw (R := R) + source target U N P F A T exponent H Q tau).real + {draws | physicalMedianUpdateTable source target U N P F A T delta a S copies + (physicalProgramDrawSelections source target U N P F A T exponent H Q tau eta kappa) + draws ∈ event} := by + classical + have h := congrArg (fun law : Measure (ClampedPhysicalSeed M J target.length N) => law.real event) + (physicalLocalMedianUpdateTable_law (R := R) source target U N P F A T exponent H Q tau eta kappa delta + a S copies hsize hP hF hA hseed) + rw [map_measureReal_apply (measurable_of_finite _) (Set.toFinite event).measurableSet, + map_measureReal_apply (measurable_of_finite _) (Set.toFinite event).measurableSet] at h + exact h + +end Median + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalOnlineMassBound.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalOnlineMassBound.lean new file mode 100644 index 0000000000000000000000000000000000000000..79877d280b1006ce062ff21305b20b6d4ad97639 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalOnlineMassBound.lean @@ -0,0 +1,38 @@ +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalLocalOnlineKeys +import OAI.Combinatorics.EditApproximation.Geometry.BandDimension +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! A single finite source range bounds every actual local online sampler, +independently of the incoming seed and queried state. -/ + +namespace EditApproximation + +theorem keyedOnlineBandG_le {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (P exponent H b : ℕ) (hP : 0 < P) (tau : ℚ) + (child : Fin M → TargetInterval target.length → ℚ) (r : TargetInterval target.length) : + keyedOnlineBandG source target parent P exponent H b tau child r ≤ + H + M * (40 * P + 2) ^ 2 + 2 := by + have hdimension := bandCoordinates_card_le parent r hP + (representativeBandActions source target parent r b P tau ((2 : ℚ) ^ (-(exponent : ℤ))) child) + (fun action ha => representativeBandActions_wide source target parent r b P tau _ child action ha) + exact Nat.add_le_add_right (Nat.add_le_add_left hdimension H) 2 + + + +theorem physicalLocalOnlineMass_le {α : Type*} [DecidableEq α] {M J : ℕ} + (source target : List α) (U : PhysicalEntry M J target.length → ℕ) + (N P F : ℕ) (A : ℚ) (T exponent H : ℕ) (tau : ℚ) (hP : 0 < P) + (key : PhysicalLocalOnlineKey M J N target.length) : + physicalLocalOnlineMass source target U N P F A T exponent H tau key ≤ localOnlineMassBound M P H := by + apply optimizerTriangularMass_monotone + exact Nat.pow_le_pow_left (keyedOnlineBandG_le source target _ P exponent H _ hP tau _ _) 80 + +theorem localOnlineMassBound_positive (M P H : ℕ) : 0 < localOnlineMassBound M P H := + optimizerTriangularMass_positive _ (pow_pos (by omega) _) + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalOnlineProgram.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalOnlineProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..934775c91b5070f48567490a6da8cfe2a52b0d68 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalOnlineProgram.lean @@ -0,0 +1,147 @@ +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalLocalRefinement +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalOnlineLocality +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Direct online queries use one rounded center per allowed scale. The +integer argument denotes the accepted output of the exact rejection sampler; +reduction modulo the requested range merely makes the finite rule total. -/ + +namespace EditApproximation + +open Finset + +theorem rationalRefinementUpdate_online_mem_ext {ι : Type*} + (left right : List ι) (value : ι → ℚ) (delta cone : ℚ) + (hmem : ∀ action, action ∈ left ↔ action ∈ right) : + rationalRefinementUpdate delta cone (rationalOnlineMinimum (left.map value)) = + rationalRefinementUpdate delta cone (rationalOnlineMinimum (right.map value)) := by + simp only [rationalRefinementUpdate_online_list, List.map_map, Function.comp_def] + apply rationalMinimum_local_complete right left + · exact fun action ha => (hmem action).mp ha + · exact fun action ha _ => (hmem action).mpr ha + + + +theorem keyedOnlineBandG_positive {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (P exponent H b : ℕ) (tau : ℚ) + (child : Fin M → TargetInterval target.length → ℚ) (r : TargetInterval target.length) : + 0 < keyedOnlineBandG source target parent P exponent H b tau child r := by + unfold keyedOnlineBandG + omega + + + +theorem boundedOnlineInteger_val (n : ℕ) (hn : 0 < n) (integer : Fin n) : + boundedOnlineInteger n hn integer.val = integer := + Fin.ext (Nat.mod_eq_of_lt integer.isLt) + + + + + +theorem localOnlineCandidates_length {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (N P F exponent H : ℕ) (tau a eta kappa : ℚ) + (parentInitial : TargetInterval target.length → ℚ) + (child initial : Fin M → TargetInterval target.length → ℚ) + (children : PhysicalChildTables M target.length) (t : ℕ) + (integer : ℕ → TargetInterval target.length → ℕ) (q : TargetInterval target.length) : + (localOnlineCandidates source target parent N P F exponent H tau a eta kappa + parentInitial child initial children t integer q).length ≤ + (dyadicQueryWindow N (parentInitial q) a F).length := + List.length_filterMap_le _ _ + +theorem localOnlineCandidates_mem {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (N P F exponent H : ℕ) (tau a eta kappa : ℚ) + (parentInitial : TargetInterval target.length → ℚ) + (child initial : Fin M → TargetInterval target.length → ℚ) + (children : PhysicalChildTables M target.length) (t : ℕ) + (integer : ℕ → TargetInterval target.length → ℕ) (q : TargetInterval target.length) + (action : PhysicalRationalAction M target.length) : + action ∈ localOnlineCandidates source target parent N P F exponent H tau a eta kappa + parentInitial child initial children t integer q ↔ + ∃ b, b ∈ dyadicQueryWindow N (parentInitial q) a F ∧ + (b, roundInterval (seedGridSpacing b P) q) ∈ representativeList N P F a parentInitial ∧ + keyedOnlineCandidate source target parent P F exponent H b tau eta kappa child initial + children t (roundInterval (seedGridSpacing b P) q) + (integer b (roundInterval (seedGridSpacing b P) q)) = some action := by + unfold localOnlineCandidates + constructor + · intro ha + obtain ⟨b, hb, hselected⟩ := List.mem_filterMap.mp ha + dsimp only at hselected + split_ifs at hselected with heligible + refine ⟨b, hb, ?_, hselected⟩ + exact representativeList_mem a parentInitial _ (List.mem_filter.mp hb).1 + (roundInterval_on_grid _ q) heligible.1 heligible.2 + · rintro ⟨b, hb, hrep, hselected⟩ + have hc := representativeList_conditions a parentInitial hrep + apply List.mem_filterMap.mpr + refine ⟨b, hb, ?_⟩ + dsimp only + rw [ite_eq_left hc.2.2.2] + exact hselected + +section Physical + +variable {α : Type*} [DecidableEq α] {M J : ℕ} + (source target : List α) (U : PhysicalEntry M J target.length → ℕ) + (N P F exponent H T : ℕ) (A tau eta kappa : ℚ) + +theorem keyedOnlineCandidate_eq_physical + (node : PhysicalInternalNode M J) + (representative : Fin (stageRepresentatives source target U N P F A node.1).length) + (children : PhysicalChildTables M target.length) (t : ℕ) + (integer : Fin (optimizerTriangularMass + (physicalProgramBandK source target U N P F A T exponent H tau node representative))) : + keyedOnlineCandidate source target (physicalSourceInterval source.length node.1) + P F exponent H ((stageRepresentatives source target U N P F A node.1).get representative).1 + tau eta kappa (physicalBandChildMassTable source target U N P F A T node.1 node.2) + (physicalBandChildInitial source target U N P F A node.1 node.2) children t + ((stageRepresentatives source target U N P F A node.1).get representative).2 integer.val = + physicalProgramOnlineCandidate source target U N P F A T exponent H tau eta kappa + node representative children t integer := by + let G := keyedOnlineBandG source target (physicalSourceInterval source.length node.1) + P exponent H ((stageRepresentatives source target U N P F A node.1).get representative).1 tau + (physicalBandChildMassTable source target U N P F A T node.1 node.2) + ((stageRepresentatives source target U N P F A node.1).get representative).2 + have hG : 0 < G := keyedOnlineBandG_positive source target + (physicalSourceInterval source.length node.1) P exponent H + ((stageRepresentatives source target U N P F A node.1).get representative).1 tau + (physicalBandChildMassTable source target U N P F A T node.1 node.2) + ((stageRepresentatives source target U N P F A node.1).get representative).2 + have haccept : boundedOnlineInteger (optimizerTriangularMass (G ^ 80)) + (optimizerTriangularMass_positive (G ^ 80) (pow_pos hG 80)) integer.val = integer := by + apply Fin.ext + exact Nat.mod_eq_of_lt integer.isLt + unfold keyedOnlineCandidate physicalProgramOnlineCandidate physicalBandOnlineCandidate + dsimp only + rw [haccept] + dsimp only [physicalBandEnvelope, physicalProgramBandK, physicalProgramBandG, + physicalBandActions, keyedOnlineBandG] at integer ⊢ + unfold physicalBandEnvelope + dsimp only [physicalBandActions] + congr 1 + funext hband + split <;> simp_all only + +def physicalLocalOnline {R : ℕ} [NeZero R] + (integer : PhysicalInternalNode M J → Fin R → ℕ → TargetInterval target.length → ℕ) + (node : PhysicalNode M J) (children : PhysicalChildTables M target.length) + (t : ℕ) (q : TargetInterval target.length) : List (PhysicalRationalAction M target.length) := + if hbelow : node.1.val < J then + localOnlineCandidates source target (physicalSourceInterval source.length node) + N P F exponent H tau (refinementFactor A F) eta kappa + (fun r => stageInitial source target U N P F A (node, r)) + (physicalLocalChildMass source target U N P F A T node hbelow) + (physicalBandChildInitial source target U N P F A node hbelow) + children (t - 1) (integer ⟨node, hbelow⟩ (Fin.ofNat R (t - 1))) q + else [] + +end Physical + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalOnlineSourceQuery.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalOnlineSourceQuery.lean new file mode 100644 index 0000000000000000000000000000000000000000..92a8186d1813eeb7baefd5d73f37bdc2e22c5707 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalOnlineSourceQuery.lean @@ -0,0 +1,126 @@ +import OAI.Combinatorics.EditApproximation.Geometry.RefinementDataQuery +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalRawOnlineProgram +import OAI.Combinatorics.EditApproximation.Probability.FiniteQueryWork +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Online ranges are computed from already gathered band data. The +following query reads only the scale/center pairs for the current entry, +then evaluates the existing local step with the returned integers. -/ + +namespace EditApproximation + + + +theorem localOnlineSourceKeys_mem {n : ℕ} (N P F : ℕ) (a : ℚ) + (initial : TargetInterval n → ℚ) (q : TargetInterval n) (b : ℕ) + (hb : b ∈ dyadicQueryWindow N (initial q) a F) : + (b, roundInterval (seedGridSpacing b P) q) ∈ localOnlineSourceKeys N P F a initial q := + List.mem_map.mpr ⟨b, hb, rfl⟩ + + + +theorem keyedOnlineSourceRange_congr {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (P exponent H : ℕ) (tau : ℚ) + (child child' : Fin M → TargetInterval target.length → ℚ) (key : ℕ × TargetInterval target.length) + (h : ∀ action ∈ wideActionList M parent key.2 key.1 P, + ∀ i, child i (action i) = child' i (action i)) : + keyedOnlineSourceRange source target parent P exponent H tau child key = + keyedOnlineSourceRange source target parent P exponent H tau child' key := by + unfold keyedOnlineSourceRange keyedOnlineBandG + rw [representativeBandActions_congr_child source target parent key.2 key.1 P tau + ((2 : ℚ) ^ (-(exponent : ℤ))) child child' h] + +theorem keyedOnlineSourceRange_gathered {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (N P F exponent H : ℕ) (tau a : ℚ) + (parentInitial : TargetInterval target.length → ℚ) + (child : Fin M → TargetInterval target.length → ℚ) (q : TargetInterval target.length) + (b : ℕ) (hb : b ∈ dyadicQueryWindow N (parentInitial q) a F) : + let keys := refinementBandInputList (M := M) parent N P F exponent a parentInitial q + keyedOnlineSourceRange source target parent P exponent H tau + (fun i r => finiteAnswerTable keys (keys.map fun input => child input.1 input.2) (i, r)) + (b, roundInterval (seedGridSpacing b P) q) = + keyedOnlineSourceRange source target parent P exponent H tau child + (b, roundInterval (seedGridSpacing b P) q) := by + dsimp only + apply keyedOnlineSourceRange_congr + intro action ha i + apply finiteAnswerTable_map + exact wideWarmupInputs_pair parent P b _ _ + (queryEarlierRepresentatives_online N P F exponent a parentInitial q b hb) action ha i + +section Query + +variable {ι α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (N P F exponent H Q : ℕ) + (tau a eta kappa delta : ℚ) (t : ℕ) + (parentInitial : TargetInterval target.length → ℚ) + (child initial : Fin M → TargetInterval target.length → ℚ) + (draw : CellGroupDraws M F Q) (q : TargetInterval target.length) + (readInteger : (ℕ × TargetInterval target.length) → ℕ → FiniteQuery ι) + (readEarlier : (Fin M × ℕ × TargetInterval target.length) → FiniteQuery ι) + (readCurrent : (Fin M × TargetInterval target.length) → FiniteQuery ι) + + + +theorem localOnlineSourceStepQuery_value (oracle : ι → ℚ) + (integer : ℕ → TargetInterval target.length → ℕ) + (earlier : PhysicalChildTables M target.length) + (current : Fin M → TargetInterval target.length → ℚ) (ht : 0 < t) + (hreadInteger : ∀ key ∈ localOnlineSourceKeys N P F a parentInitial q, + (readInteger key (keyedOnlineSourceRange source target parent P exponent H tau child key)).value oracle = + (integer key.1 key.2 : ℚ)) + (hreadEarlier : ∀ input, (readEarlier input).value oracle = earlier input.1 input.2.1 input.2.2) + (hreadCurrent : ∀ input, (readCurrent input).value oracle = current input.1 input.2) : + (localOnlineSourceStepQuery source target parent N P F exponent H Q tau a eta kappa delta t + parentInitial child initial draw q readInteger readEarlier readCurrent).value oracle = + rationalLocalWideStep source target parent N P F exponent Q tau a delta parentInitial child initial + (fun i r => earlier i (t - 1) r) current draw + (localOnlineCandidates source target parent N P F exponent H tau a eta kappa + parentInitial child initial earlier (t - 1) integer q) q := by + let keys := localOnlineSourceKeys N P F a parentInitial q + let values := keys.map fun key => + (readInteger key (keyedOnlineSourceRange source target parent P exponent H tau child key)).value oracle + let cached := fun b r => ⌊finiteAnswerTable keys values (b, r)⌋₊ + have hcached (b : ℕ) (hb : b ∈ dyadicQueryWindow N (parentInitial q) a F) : + cached b (roundInterval (seedGridSpacing b P) q) = + integer b (roundInterval (seedGridSpacing b P) q) := by + have hmem := localOnlineSourceKeys_mem N P F a parentInitial q b hb + dsimp only [cached, values] + rw [finiteAnswerTable_map keys _ _ hmem, hreadInteger _ hmem] + simp + have honline := localOnlineCandidates_integer_congr source target parent N P F exponent H tau a eta kappa + parentInitial child initial earlier (t - 1) cached integer q (fun b hb _ => hcached b hb) + unfold localOnlineSourceStepQuery + rw [FiniteQuery.collect_value] + rw [localRefinementStepQuery_value source target parent N P F exponent H Q tau a eta kappa delta t + parentInitial child initial draw cached q readEarlier readCurrent oracle earlier current ht + hreadEarlier hreadCurrent] + rw [honline] + +theorem localOnlineSourceStepQuery_cost (oracle : ι → ℚ) (weight : ι → ℕ) : + (localOnlineSourceStepQuery source target parent N P F exponent H Q tau a eta kappa delta t + parentInitial child initial draw q readInteger readEarlier readCurrent).cost oracle weight = + let keys := localOnlineSourceKeys N P F a parentInitial q + let reader := fun key => readInteger key + (keyedOnlineSourceRange source target parent P exponent H tau child key) + (keys.map fun key => (reader key).cost oracle weight).sum + + (localRefinementStepQuery source target parent N P F exponent H Q tau a eta kappa delta t + parentInitial child initial draw + (fun b r => ⌊finiteAnswerTable keys (keys.map fun key => (reader key).value oracle) (b, r)⌋₊) + q readEarlier readCurrent).cost oracle weight := by + unfold localOnlineSourceStepQuery + rw [FiniteQuery.cost_collect] + +theorem localOnlineSourceKeys_length : + (localOnlineSourceKeys N P F a parentInitial q).length = + (dyadicQueryWindow N (parentInitial q) a F).length := by + simp only [localOnlineSourceKeys, List.length_map] + +end Query + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalRandomDataQuery.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalRandomDataQuery.lean new file mode 100644 index 0000000000000000000000000000000000000000..8d73842ceea7ba110b722b50c5ece2c469b9a14d --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalRandomDataQuery.lean @@ -0,0 +1,143 @@ +import OAI.Combinatorics.EditApproximation.Geometry.LocalRandomSourceQuery +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Gather data before selecting a random source coordinate. Online ranges +are calculated solely from previously requested band values; group draws and +online draws are ordinary scalar reads in the same adaptive query. -/ + +namespace EditApproximation + +section BandData + +variable {ι α : Type*} (source target : List α) {M : ℕ} [NeZero M] + (parent : TargetInterval source.length) (N P F exponent H Q : ℕ) + (tau a eta kappa delta : ℚ) (t : ℕ) + (parentInitial : TargetInterval target.length → ℚ) + (readMass readInitial : Fin M × TargetInterval target.length → FiniteQuery ι) + (readGroup : GroupScalarKey M F Q → FiniteQuery ι) + (readInteger : (ℕ × TargetInterval target.length) → ℕ → FiniteQuery ι) + (q : TargetInterval target.length) + (readEarlier : (Fin M × ℕ × TargetInterval target.length) → FiniteQuery ι) + (readCurrent : (Fin M × TargetInterval target.length) → FiniteQuery ι) + + + +theorem localRandomBandDataQuery_value (oracle : ι → ℚ) + (draw : CellGroupDraws M F Q) (integer : ℕ → TargetInterval target.length → ℕ) + (child initial : Fin M → TargetInterval target.length → ℚ) + (earlier : PhysicalChildTables M target.length) + (current : Fin M → TargetInterval target.length → ℚ) (ht : 0 < t) + (hreadMass : ∀ input, (readMass input).value oracle = child input.1 input.2) + (hreadInitial : ∀ input, (readInitial input).value oracle = initial input.1 input.2) + (hreadEarlier : ∀ input, (readEarlier input).value oracle = earlier input.1 input.2.1 input.2.2) + (hreadGroup : ∀ key, (readGroup key).value oracle = groupScalarValue draw key) + (hreadInteger : ∀ key, + (readInteger key (keyedOnlineSourceRange source target parent P exponent H tau child key)).value oracle = + (integer key.1 key.2 : ℚ)) + (hreadCurrent : ∀ input, (readCurrent input).value oracle = current input.1 input.2) : + (localRandomBandDataQuery source target parent N P F exponent H Q tau a eta kappa delta t + parentInitial readMass readInitial readGroup readInteger q readEarlier readCurrent).value oracle = + rationalLocalWideStep source target parent N P F exponent Q tau a delta parentInitial child initial + (fun i r => earlier i (t - 1) r) current draw + (localOnlineCandidates source target parent N P F exponent H tau a eta kappa + parentInitial child initial earlier (t - 1) integer q) q := by + classical + let keys := refinementBandInputList (M := M) parent N P F exponent a parentInitial q + let mass := fun i r => finiteAnswerTable keys (keys.map fun input => child input.1 input.2) (i, r) + let initial' := fun i r => finiteAnswerTable keys (keys.map fun input => initial input.1 input.2) (i, r) + have hmass : ∀ input ∈ keys, mass input.1 input.2 = child input.1 input.2 := by + intro input hi + exact finiteAnswerTable_map keys _ input hi + have hinitial : ∀ input ∈ keys, initial' input.1 input.2 = initial input.1 input.2 := by + intro input hi + exact finiteAnswerTable_map keys _ input hi + have honline := localOnlineCandidates_congr_bandTables source target parent N P F exponent H + tau a eta kappa (t - 1) parentInitial mass child initial' initial earlier integer q hmass hinitial + have hgroups := localCellGroupActions_congr_bandTables source target parent N P F exponent Q + tau a parentInitial mass child initial' initial current draw q hmass hinitial + unfold localRandomBandDataQuery + rw [FiniteQuery.collect_value] + simp only [hreadMass] + rw [FiniteQuery.collect_value] + simp only [hreadInitial] + rw [localRandomSourceStepQuery_value source target parent N P F exponent H Q tau a eta kappa delta t + parentInitial mass initial' q readGroup readInteger readEarlier readCurrent oracle draw integer earlier current ht + (fun key _ => hreadGroup key) ?_ hreadEarlier hreadCurrent] + rotate_left + · intro key hk + obtain ⟨b, hb, rfl⟩ := List.mem_map.mp hk + rw [keyedOnlineSourceRange_gathered source target parent N P F exponent H tau a + parentInitial child q b hb] + exact hreadInteger _ + rw [honline] + unfold rationalLocalWideStep + rw [hgroups] + +end BandData + +section AllData + +variable {ι α : Type*} (source target : List α) {M : ℕ} [NeZero M] + (parent : TargetInterval source.length) (N P F exponent H Q : ℕ) + (tau a eta kappa delta : ℚ) (t : ℕ) + (readParentInitial : TargetInterval target.length → FiniteQuery ι) + (readMass readInitial : Fin M × TargetInterval target.length → FiniteQuery ι) + (readGroup : GroupScalarKey M F Q → FiniteQuery ι) + (readInteger : (ℕ × TargetInterval target.length) → ℕ → FiniteQuery ι) + (q : TargetInterval target.length) + (readEarlier : (Fin M × ℕ × TargetInterval target.length) → FiniteQuery ι) + (readCurrent : (Fin M × TargetInterval target.length) → FiniteQuery ι) + + + +theorem localRandomDataQuery_value (oracle : ι → ℚ) + (draw : CellGroupDraws M F Q) (integer : ℕ → TargetInterval target.length → ℕ) + (parentInitial : TargetInterval target.length → ℚ) + (child initial : Fin M → TargetInterval target.length → ℚ) + (earlier : PhysicalChildTables M target.length) + (current : Fin M → TargetInterval target.length → ℚ) (ht : 0 < t) + (hreadParentInitial : ∀ r, (readParentInitial r).value oracle = parentInitial r) + (hreadMass : ∀ input, (readMass input).value oracle = child input.1 input.2) + (hreadInitial : ∀ input, (readInitial input).value oracle = initial input.1 input.2) + (hreadEarlier : ∀ input, (readEarlier input).value oracle = earlier input.1 input.2.1 input.2.2) + (hreadGroup : ∀ key, (readGroup key).value oracle = groupScalarValue draw key) + (hreadInteger : ∀ key, + (readInteger key (keyedOnlineSourceRange source target parent P exponent H tau child key)).value oracle = + (integer key.1 key.2 : ℚ)) + (hreadCurrent : ∀ input, (readCurrent input).value oracle = current input.1 input.2) : + (localRandomDataQuery source target parent N P F exponent H Q tau a eta kappa delta t + readParentInitial readMass readInitial readGroup readInteger q readEarlier readCurrent).value oracle = + rationalLocalWideStep source target parent N P F exponent Q tau a delta parentInitial child initial + (fun i r => earlier i (t - 1) r) current draw + (localOnlineCandidates source target parent N P F exponent H tau a eta kappa + parentInitial child initial earlier (t - 1) integer q) q := by + classical + let keys := refinementInitialSupport N P F exponent a (parentInitial q) q + let cached := finiteAnswerTable keys (keys.map parentInitial) + have heq : ∀ r ∈ refinementInitialSupport N P F exponent a (parentInitial q) q, + parentInitial r = cached r := by + intro r hr + exact (finiteAnswerTable_map keys parentInitial r hr).symm + have honline := localOnlineCandidates_congr_initial source target parent N P F exponent H + tau a eta kappa (t - 1) parentInitial cached child initial earlier integer q heq + have hstep := rationalLocalWideStep_congr_initial source target parent N P F exponent Q tau a + parentInitial cached child initial current draw q heq delta (fun i r => earlier i (t - 1) r) + (localOnlineCandidates source target parent N P F exponent H tau a eta kappa + parentInitial child initial earlier (t - 1) integer q) + unfold localRandomDataQuery + rw [FiniteQuery.bind_value, hreadParentInitial q, FiniteQuery.collect_value] + simp only [hreadParentInitial] + rw [localRandomBandDataQuery_value source target parent N P F exponent H Q tau a eta kappa delta t + cached readMass readInitial readGroup readInteger q readEarlier readCurrent oracle draw integer child initial earlier current ht + hreadMass hreadInitial hreadEarlier hreadGroup hreadInteger hreadCurrent] + rw [← honline] + exact hstep.symm + +end AllData + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalRandomQueryKeys.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalRandomQueryKeys.lean new file mode 100644 index 0000000000000000000000000000000000000000..946d29cbea643dd0772dd19d43681ab01e5bfc02 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalRandomQueryKeys.lean @@ -0,0 +1,117 @@ +import OAI.Combinatorics.EditApproximation.Geometry.LocalRandomDataQuery +import OAI.Combinatorics.EditApproximation.Probability.FiniteQueryRestriction +import OAI.Combinatorics.EditApproximation.Geometry.RefinementDataQueryWork + +namespace OAI + +namespace EditApproximation + +namespace FiniteQuery + +theorem keys_all_mapKeys {ι κ : Type*} (f : ι → κ) (query : FiniteQuery ι) + (oracle : κ → ℚ) (predicate : κ → Prop) + (h : ∀ key ∈ query.keys (oracle ∘ f), predicate (f key)) : + ∀ key ∈ (mapKeys f query).keys oracle, predicate key := by + rw [mapKeys_keys] + intro key hk + obtain ⟨other, ho, rfl⟩ := List.mem_map.mp hk + exact h other ho + +end FiniteQuery + +section Keys + +variable {ι α : Type*} (source target : List α) {M : ℕ} [NeZero M] + (parent : TargetInterval source.length) (N P F exponent H Q : ℕ) + (tau a eta kappa delta : ℚ) (t : ℕ) + (parentInitial : TargetInterval target.length → ℚ) + (child initial : Fin M → TargetInterval target.length → ℚ) + (readParent : TargetInterval target.length → FiniteQuery ι) + (readMass readInitial : Fin M × TargetInterval target.length → FiniteQuery ι) + (readGroup : GroupScalarKey M F Q → FiniteQuery ι) + (readInteger : (ℕ × TargetInterval target.length) → ℕ → FiniteQuery ι) + (q : TargetInterval target.length) + (readEarlier : (Fin M × ℕ × TargetInterval target.length) → FiniteQuery ι) + (readCurrent : (Fin M × TargetInterval target.length) → FiniteQuery ι) + (oracle : ι → ℚ) (predicate : ι → Prop) + +variable + (hgroup : ∀ input key, key ∈ (readGroup input).keys oracle → predicate key) + (hinteger : ∀ input range key, key ∈ (readInteger input range).keys oracle → predicate key) + (hearlier : ∀ input key, key ∈ (readEarlier input).keys oracle → predicate key) + (hcurrent : ∀ input key, key ∈ (readCurrent input).keys oracle → predicate key) + +omit [NeZero M] in +include hinteger hearlier hcurrent in + theorem localOnlineSourceStepQuery_keys_all (draw : CellGroupDraws M F Q) : + ∀ key ∈ (localOnlineSourceStepQuery source target parent N P F exponent H Q tau a eta kappa delta t + parentInitial child initial draw q readInteger readEarlier readCurrent).keys oracle, predicate key := by + unfold localOnlineSourceStepQuery + apply FiniteQuery.keys_all_collect + · intro input _ key hk + exact hinteger input _ key hk + · intro values + exact localRefinementStepQuery_keys_all source target parent N P F exponent H Q + tau a eta kappa delta t parentInitial child initial draw _ q readEarlier readCurrent + oracle predicate hearlier hcurrent + +include hgroup hinteger hearlier hcurrent in + theorem localRandomSourceStepQuery_keys_all : + ∀ key ∈ (localRandomSourceStepQuery source target parent N P F exponent H Q tau a eta kappa delta t + parentInitial child initial q readGroup readInteger readEarlier readCurrent).keys oracle, predicate key := by + unfold localRandomSourceStepQuery + apply FiniteQuery.keys_all_collect + · intro input _ key hk + exact hgroup input key hk + · intro values + exact localOnlineSourceStepQuery_keys_all source target parent N P F exponent H Q + tau a eta kappa delta t parentInitial child initial readInteger q readEarlier readCurrent + oracle predicate hinteger hearlier hcurrent _ + +include hgroup hinteger hearlier hcurrent in + theorem localRandomBandDataQuery_keys_all + (hmass : ∀ input key, key ∈ (readMass input).keys oracle → predicate key) + (hinitial : ∀ input key, key ∈ (readInitial input).keys oracle → predicate key) : + ∀ key ∈ (localRandomBandDataQuery source target parent N P F exponent H Q tau a eta kappa delta t + parentInitial readMass readInitial readGroup readInteger q readEarlier readCurrent).keys oracle, + predicate key := by + unfold localRandomBandDataQuery + apply FiniteQuery.keys_all_collect + · intro input _ key hk + exact hmass input key hk + · intro massValues + apply FiniteQuery.keys_all_collect + · intro input _ key hk + exact hinitial input key hk + · intro initialValues + exact localRandomSourceStepQuery_keys_all source target parent N P F exponent H Q + tau a eta kappa delta t parentInitial _ _ readGroup readInteger q readEarlier readCurrent + oracle predicate hgroup hinteger hearlier hcurrent + +include hgroup hinteger hearlier hcurrent in + theorem localRandomDataQuery_keys_all + (hparent : ∀ r key, key ∈ (readParent r).keys oracle → predicate key) + (hmass : ∀ input key, key ∈ (readMass input).keys oracle → predicate key) + (hinitial : ∀ input key, key ∈ (readInitial input).keys oracle → predicate key) : + ∀ key ∈ (localRandomDataQuery source target parent N P F exponent H Q tau a eta kappa delta t + readParent readMass readInitial readGroup readInteger q readEarlier readCurrent).keys oracle, + predicate key := by + unfold localRandomDataQuery + rw [FiniteQuery.keys_bind] + intro key hk + rcases List.mem_append.mp hk with hfirst | hrest + · exact hparent q key hfirst + · apply FiniteQuery.keys_all_collect oracle predicate readParent + (refinementInitialSupport N P F exponent a ((readParent q).value oracle) q) _ ?_ ?_ key hrest + · intro r _ other ho + exact hparent r other ho + · intro initialValues + exact localRandomBandDataQuery_keys_all source target parent N P F exponent H Q + tau a eta kappa delta t _ readMass readInitial readGroup readInteger q readEarlier readCurrent + oracle predicate hgroup hinteger hearlier hcurrent hmass hinitial + +end Keys + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalRandomSourceCost.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalRandomSourceCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..6782092e28d16c260874dd6814ca7a838da129ad --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalRandomSourceCost.lean @@ -0,0 +1,76 @@ +import OAI.Combinatorics.EditApproximation.Geometry.LocalSourceReadCost + +namespace OAI + +/-! Source charges survive the two adaptive data-gathering stages unchanged. +All table reads have weight zero here; their dependency cost is accounted for +by the projected table program. No accuracy event is used. -/ + +namespace EditApproximation + +section Cost + +variable {ι α : Type*} (source target : List α) {M : ℕ} [NeZero M] + (parent : TargetInterval source.length) (N P F exponent H Q : ℕ) + (tau a eta kappa delta : ℚ) (t : ℕ) + (readMass readInitial : Fin M × TargetInterval target.length → FiniteQuery ι) + (readGroup : GroupScalarKey M F Q → FiniteQuery ι) + (readInteger : (ℕ × TargetInterval target.length) → ℕ → FiniteQuery ι) + (q : TargetInterval target.length) + (readEarlier : (Fin M × ℕ × TargetInterval target.length) → FiniteQuery ι) + (readCurrent : (Fin M × TargetInterval target.length) → FiniteQuery ι) + (oracle : ι → ℚ) (weight : ι → ℕ) + (hmass : ∀ input, (readMass input).cost oracle weight = 0) + (hinitial : ∀ input, (readInitial input).cost oracle weight = 0) + (hearlier : ∀ input key, key ∈ (readEarlier input).keys oracle → weight key = 0) + (hcurrent : ∀ input key, key ∈ (readCurrent input).keys oracle → weight key = 0) + (groupBound onlineBound : ℕ) + (hgroup : ∀ key, (readGroup key).cost oracle weight ≤ groupBound) + (honline : ∀ key range, (readInteger key range).cost oracle weight ≤ onlineBound) + +include hmass hinitial hearlier hcurrent hgroup honline + + theorem localRandomBandDataQuery_source_cost_le + (parentInitial : TargetInterval target.length → ℚ) : + (localRandomBandDataQuery source target parent N P F exponent H Q tau a eta kappa delta t + parentInitial readMass readInitial readGroup readInteger q readEarlier readCurrent).cost oracle weight ≤ + (groupScalarKeys M F Q (localGroupQueryKeys N F exponent a parentInitial q)).length * groupBound + + (localOnlineSourceKeys N P F a parentInitial q).length * onlineBound := by + unfold localRandomBandDataQuery + rw [FiniteQuery.cost_collect, FiniteQuery.cost_collect] + simp only [hmass, hinitial, List.map_const', List.sum_replicate, smul_eq_mul, + Nat.mul_zero, Nat.zero_add] + exact localRandomSourceStepQuery_source_cost_le source target parent N P F exponent H Q + tau a eta kappa delta t parentInitial _ _ q readGroup readInteger readEarlier readCurrent + oracle weight hearlier hcurrent groupBound onlineBound hgroup honline + + theorem localRandomDataQuery_source_cost_le + (readParent : TargetInterval target.length → FiniteQuery ι) + (hparent : ∀ r, (readParent r).cost oracle weight = 0) : + let actualInitial := fun r => (readParent r).value oracle + (localRandomDataQuery source target parent N P F exponent H Q tau a eta kappa delta t + readParent readMass readInitial readGroup readInteger q readEarlier readCurrent).cost oracle weight ≤ + (groupScalarKeys M F Q (localGroupQueryKeys N F exponent a actualInitial q)).length * groupBound + + (localOnlineSourceKeys N P F a actualInitial q).length * onlineBound := by + dsimp only + unfold localRandomDataQuery + rw [FiniteQuery.cost_bind, hparent q, Nat.zero_add, FiniteQuery.cost_collect] + simp only [hparent, List.map_const', List.sum_replicate, smul_eq_mul, Nat.mul_zero, Nat.zero_add] + let keys := refinementInitialSupport N P F exponent a ((readParent q).value oracle) q + let cached := finiteAnswerTable keys (keys.map fun r => (readParent r).value oracle) + have hq : cached q = (readParent q).value oracle := + finiteAnswerTable_map keys _ q (refinementInitialSupport_query N P F exponent a _ q) + have hb := localRandomBandDataQuery_source_cost_le source target parent N P F exponent H Q + tau a eta kappa delta t readMass readInitial readGroup readInteger q readEarlier readCurrent + oracle weight hmass hinitial hearlier hcurrent groupBound onlineBound hgroup honline cached + change (localRandomBandDataQuery source target parent N P F exponent H Q tau a eta kappa delta t + cached readMass readInitial readGroup readInteger q readEarlier readCurrent).cost oracle weight ≤ _ + apply hb.trans + simp only [localGroupQueryKeys, localOnlineSourceKeys, hq] + exact le_rfl + +end Cost + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalRandomSourceQuery.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalRandomSourceQuery.lean new file mode 100644 index 0000000000000000000000000000000000000000..7bae03340d2aee2e10fa1cf0706abb0947ba3d53 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalRandomSourceQuery.lean @@ -0,0 +1,68 @@ +import OAI.Combinatorics.EditApproximation.Geometry.LocalGroupSourceQuery +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! A local refinement step with both kinds of random input made explicit. +All scalar group reads and range-indexed online reads precede the existing +finite earlier/current queries, whose semantic values are preserved. -/ + +namespace EditApproximation + +section Step + +variable {ι α : Type*} (source target : List α) {M : ℕ} [NeZero M] + (parent : TargetInterval source.length) (N P F exponent H Q : ℕ) + (tau a eta kappa delta : ℚ) (t : ℕ) + (parentInitial : TargetInterval target.length → ℚ) + (child initial : Fin M → TargetInterval target.length → ℚ) + (q : TargetInterval target.length) + (readGroup : GroupScalarKey M F Q → FiniteQuery ι) + (readInteger : (ℕ × TargetInterval target.length) → ℕ → FiniteQuery ι) + (readEarlier : (Fin M × ℕ × TargetInterval target.length) → FiniteQuery ι) + (readCurrent : (Fin M × TargetInterval target.length) → FiniteQuery ι) + + + +theorem localRandomSourceStepQuery_value (oracle : ι → ℚ) (draw : CellGroupDraws M F Q) + (integer : ℕ → TargetInterval target.length → ℕ) + (earlier : PhysicalChildTables M target.length) + (current : Fin M → TargetInterval target.length → ℚ) (ht : 0 < t) + (hreadGroup : ∀ key ∈ groupScalarKeys M F Q (localGroupQueryKeys N F exponent a parentInitial q), + (readGroup key).value oracle = groupScalarValue draw key) + (hreadInteger : ∀ key ∈ localOnlineSourceKeys N P F a parentInitial q, + (readInteger key (keyedOnlineSourceRange source target parent P exponent H tau child key)).value oracle = + (integer key.1 key.2 : ℚ)) + (hreadEarlier : ∀ input, (readEarlier input).value oracle = earlier input.1 input.2.1 input.2.2) + (hreadCurrent : ∀ input, (readCurrent input).value oracle = current input.1 input.2) : + (localRandomSourceStepQuery source target parent N P F exponent H Q tau a eta kappa delta t + parentInitial child initial q readGroup readInteger readEarlier readCurrent).value oracle = + rationalLocalWideStep source target parent N P F exponent Q tau a delta parentInitial child initial + (fun i r => earlier i (t - 1) r) current draw + (localOnlineCandidates source target parent N P F exponent H tau a eta kappa + parentInitial child initial earlier (t - 1) integer q) q := by + classical + let groups := localGroupQueryKeys N F exponent a parentInitial q + let keys := groupScalarKeys M F Q groups + have hvalues : keys.map (fun key => (readGroup key).value oracle) = keys.map (groupScalarValue draw) := by + apply List.map_congr_left + intro key hk + exact hreadGroup key hk + let cached := groupDrawFromValues keys (keys.map (groupScalarValue draw)) + have hdraw : ∀ key ∈ groups, cached key.1 key.2 = draw key.1 key.2 := + fun key hk => groupDrawFromValues_eq groups draw key hk + unfold localRandomSourceStepQuery + rw [FiniteQuery.collect_value, hvalues] + rw [localOnlineSourceStepQuery_value source target parent N P F exponent H Q tau a eta kappa delta t + parentInitial child initial cached q readInteger readEarlier readCurrent oracle integer earlier current ht + hreadInteger hreadEarlier hreadCurrent] + unfold rationalLocalWideStep + rw [localCellGroupActions_congr_draw source target parent N P F exponent Q tau a parentInitial + child initial current cached draw q hdraw] + +end Step + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalRandomTableCost.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalRandomTableCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..ed98794d272c411b6e7e29022c03f55822a459ad --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalRandomTableCost.lean @@ -0,0 +1,145 @@ +import OAI.Combinatorics.EditApproximation.Geometry.LocalRandomSourceCost + +namespace OAI + +/-! Random source reads have zero table charge. Uniform bounds for the +remaining local step therefore lift through the actual source collectors, +including the adaptive data queries. -/ + +namespace EditApproximation + +section Step + +variable {ι α : Type*} (source target : List α) {M : ℕ} [NeZero M] + (parent : TargetInterval source.length) (N P F exponent H Q : ℕ) + (tau a eta kappa delta : ℚ) (t : ℕ) + (parentInitial : TargetInterval target.length → ℚ) + (child initial : Fin M → TargetInterval target.length → ℚ) + (readGroup : GroupScalarKey M F Q → FiniteQuery ι) + (readInteger : (ℕ × TargetInterval target.length) → ℕ → FiniteQuery ι) + (q : TargetInterval target.length) + (readEarlier : (Fin M × ℕ × TargetInterval target.length) → FiniteQuery ι) + (readCurrent : (Fin M × TargetInterval target.length) → FiniteQuery ι) + (oracle : ι → ℚ) (weight : ι → ℕ) (stepBudget : ℕ) + (hgroup : ∀ key, (readGroup key).cost oracle weight = 0) + (honline : ∀ key range, (readInteger key range).cost oracle weight = 0) + (hstep : ∀ draw integer, + (localRefinementStepQuery source target parent N P F exponent H Q tau a eta kappa delta t + parentInitial child initial draw integer q readEarlier readCurrent).cost oracle weight ≤ stepBudget) + +include hgroup honline hstep in + theorem localRandomSourceStepQuery_table_cost_le : + (localRandomSourceStepQuery source target parent N P F exponent H Q tau a eta kappa delta t + parentInitial child initial q readGroup readInteger readEarlier readCurrent).cost oracle weight ≤ stepBudget := by + unfold localRandomSourceStepQuery + rw [FiniteQuery.cost_collect] + simp only [hgroup, List.map_const', List.sum_replicate, smul_eq_mul, Nat.mul_zero, Nat.zero_add] + rw [localOnlineSourceStepQuery_cost] + dsimp only + simp only [honline, List.map_const', List.sum_replicate, smul_eq_mul, Nat.mul_zero, Nat.zero_add] + exact hstep _ _ + +end Step + +section Band + +variable {ι α : Type*} (source target : List α) {M : ℕ} [NeZero M] + (parent : TargetInterval source.length) (N P F exponent H Q : ℕ) + (tau a eta kappa delta : ℚ) (t : ℕ) + (parentInitial : TargetInterval target.length → ℚ) + (readMass readInitial : Fin M × TargetInterval target.length → FiniteQuery ι) + (readGroup : GroupScalarKey M F Q → FiniteQuery ι) + (readInteger : (ℕ × TargetInterval target.length) → ℕ → FiniteQuery ι) + (q : TargetInterval target.length) + (readEarlier : (Fin M × ℕ × TargetInterval target.length) → FiniteQuery ι) + (readCurrent : (Fin M × TargetInterval target.length) → FiniteQuery ι) + (oracle : ι → ℚ) (weight : ι → ℕ) + (massBudget initialBudget stepBudget : ℕ) + (hmass : ∀ key, (readMass key).cost oracle weight ≤ massBudget) + (hinitial : ∀ key, (readInitial key).cost oracle weight ≤ initialBudget) + (hgroup : ∀ key, (readGroup key).cost oracle weight = 0) + (honline : ∀ key range, (readInteger key range).cost oracle weight = 0) + (hstep : ∀ child initial draw integer, + (localRefinementStepQuery source target parent N P F exponent H Q tau a eta kappa delta t + parentInitial child initial draw integer q readEarlier readCurrent).cost oracle weight ≤ stepBudget) + +include hmass hinitial hgroup honline hstep in + theorem localRandomBandDataQuery_table_cost_le : + (localRandomBandDataQuery source target parent N P F exponent H Q tau a eta kappa delta t + parentInitial readMass readInitial readGroup readInteger q readEarlier readCurrent).cost oracle weight ≤ + (refinementBandInputList (M := M) parent N P F exponent a parentInitial q).length * + (massBudget + initialBudget) + stepBudget := by + let keys := refinementBandInputList (M := M) parent N P F exponent a parentInitial q + let mass := fun i r => finiteAnswerTable keys (keys.map fun input => (readMass input).value oracle) (i, r) + let initial' := fun i r => finiteAnswerTable keys (keys.map fun input => (readInitial input).value oracle) (i, r) + have hm := list_map_sum_le_constant keys (fun input => (readMass input).cost oracle weight) massBudget hmass + have hi := list_map_sum_le_constant keys (fun input => (readInitial input).cost oracle weight) initialBudget hinitial + have hs := localRandomSourceStepQuery_table_cost_le source target parent N P F exponent H Q + tau a eta kappa delta t parentInitial mass initial' readGroup readInteger q readEarlier readCurrent + oracle weight stepBudget hgroup honline (hstep mass initial') + unfold localRandomBandDataQuery + rw [FiniteQuery.cost_collect, FiniteQuery.cost_collect] + change _ + (_ + (localRandomSourceStepQuery source target parent N P F exponent H Q + tau a eta kappa delta t parentInitial mass initial' q readGroup readInteger readEarlier readCurrent).cost + oracle weight) ≤ keys.length * (massBudget + initialBudget) + stepBudget + nlinarith only [hm, hi, hs] + +end Band + +section Data + +variable {ι α : Type*} (source target : List α) {M : ℕ} [NeZero M] + (parent : TargetInterval source.length) (N P F exponent H Q : ℕ) + (tau a eta kappa delta : ℚ) (t : ℕ) + (readParent : TargetInterval target.length → FiniteQuery ι) + (readMass readInitial : Fin M × TargetInterval target.length → FiniteQuery ι) + (readGroup : GroupScalarKey M F Q → FiniteQuery ι) + (readInteger : (ℕ × TargetInterval target.length) → ℕ → FiniteQuery ι) + (q : TargetInterval target.length) + (readEarlier : (Fin M × ℕ × TargetInterval target.length) → FiniteQuery ι) + (readCurrent : (Fin M × TargetInterval target.length) → FiniteQuery ι) + (oracle : ι → ℚ) (weight : ι → ℕ) + (parentBudget massBudget initialBudget bandBudget stepBudget : ℕ) + (hparent : ∀ r, (readParent r).cost oracle weight ≤ parentBudget) + (hmass : ∀ key, (readMass key).cost oracle weight ≤ massBudget) + (hinitial : ∀ key, (readInitial key).cost oracle weight ≤ initialBudget) + (hgroup : ∀ key, (readGroup key).cost oracle weight = 0) + (honline : ∀ key range, (readInteger key range).cost oracle weight = 0) + (hband : ∀ parentInitial : TargetInterval target.length → ℚ, + parentInitial q = (readParent q).value oracle → + (refinementBandInputList (M := M) parent N P F exponent a parentInitial q).length * + (massBudget + initialBudget) ≤ bandBudget) + (hstep : ∀ parentInitial : TargetInterval target.length → ℚ, + parentInitial q = (readParent q).value oracle → ∀ child initial draw integer, + (localRefinementStepQuery source target parent N P F exponent H Q tau a eta kappa delta t + parentInitial child initial draw integer q readEarlier readCurrent).cost oracle weight ≤ stepBudget) + +include hparent hmass hinitial hgroup honline hband hstep in + theorem localRandomDataQuery_table_cost_le : + (localRandomDataQuery source target parent N P F exponent H Q tau a eta kappa delta t + readParent readMass readInitial readGroup readInteger q readEarlier readCurrent).cost oracle weight ≤ + (1 + (refinementInitialSupport N P F exponent a ((readParent q).value oracle) q).length) * + parentBudget + bandBudget + stepBudget := by + let keys := refinementInitialSupport N P F exponent a ((readParent q).value oracle) q + let cached := finiteAnswerTable keys (keys.map fun r => (readParent r).value oracle) + have hq : cached q = (readParent q).value oracle := + finiteAnswerTable_map keys _ q (refinementInitialSupport_query N P F exponent a _ q) + have hlast := localRandomBandDataQuery_table_cost_le source target parent N P F exponent H Q + tau a eta kappa delta t cached readMass readInitial readGroup readInteger q readEarlier readCurrent + oracle weight massBudget initialBudget stepBudget hmass hinitial hgroup honline (hstep cached hq) + have hlast' := hlast.trans (Nat.add_le_add_right (hband cached hq) stepBudget) + have hfirst := hparent q + have hsum := list_map_sum_le_constant keys (fun r => (readParent r).cost oracle weight) parentBudget hparent + unfold localRandomDataQuery + rw [FiniteQuery.cost_bind, FiniteQuery.cost_collect] + change _ + (_ + (localRandomBandDataQuery source target parent N P F exponent H Q + tau a eta kappa delta t cached readMass readInitial readGroup readInteger q readEarlier readCurrent).cost + oracle weight) ≤ _ + change _ ≤ (1 + keys.length) * parentBudget + bandBudget + stepBudget + nlinarith only [hfirst, hsum, hlast'] + +end Data + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalRefinementCones.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalRefinementCones.lean new file mode 100644 index 0000000000000000000000000000000000000000..6daebc6cfe2182e739d0027b311fc5765c032c0a --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalRefinementCones.lean @@ -0,0 +1,166 @@ +import OAI.Combinatorics.EditApproximation.Geometry.RefinementConeLocality +import OAI.Combinatorics.EditApproximation.Geometry.LocalCells +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalSpatial +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Direct local enumeration computes the complete refinement Bellman cone +on a spatially regular initial table. Its finite definition applies to every seed. -/ + +namespace EditApproximation + +open Finset + + + +theorem representativeList_conditions {n N P F : ℕ} (a : ℚ) + (initial : TargetInterval n → ℚ) {b : ℕ} {r : TargetInterval n} + (hrep : (b, r) ∈ representativeList N P F a initial) : + b ∈ dyadicScales N ∧ seedGridSpacing b P ∣ r.lo ∧ seedGridSpacing b P ∣ r.hi ∧ + (b : ℚ) / (4 * a) ≤ initial r ∧ initial r ≤ 8 * F * b := by + obtain ⟨b', hb', hrep⟩ := List.mem_flatMap.mp hrep + obtain ⟨r', hr', heq⟩ := List.mem_map.mp hrep + obtain ⟨rfl, rfl⟩ := Prod.mk.inj heq + exact ⟨hb', of_decide_eq_true (List.mem_filter.mp hr').2⟩ + +theorem localRefinementRepresentatives_subset {n : ℕ} (N P F : ℕ) (a : ℚ) + (initial : TargetInterval n → ℚ) (q : TargetInterval n) : + ∀ br ∈ localRefinementRepresentatives N P F a initial q, + br ∈ representativeList N P F a initial := by + intro br hbr + obtain ⟨b, hb, hbr⟩ := List.mem_flatMap.mp hbr + obtain ⟨r, hr, rfl⟩ := List.mem_map.mp hbr + obtain ⟨hr, heligible⟩ := List.mem_filter.mp hr + have hgrid := localTargetStates_on_grid q r hr + exact representativeList_mem a initial r (List.mem_filter.mp hb).1 hgrid + (of_decide_eq_true heligible).1 (of_decide_eq_true heligible).2 + +theorem rationalActualWideActions_representative {nx ny M : ℕ} + (parent : TargetInterval nx) (representatives : List (ℕ × TargetInterval ny)) (P : ℕ) + (action : RationalBellmanAction (TargetInterval ny) (Fin M × TargetInterval ny) M) + (ha : action ∈ rationalActualWideActions parent representatives P) : + ∃ b, (b, action.center) ∈ representatives := by + obtain ⟨br, hbr, ha⟩ := List.mem_flatMap.mp ha + obtain ⟨states, _, heq⟩ := List.mem_map.mp ha + exact ⟨br.1, (congrArg (fun a => (br.1, a.center)) heq) ▸ hbr⟩ + +theorem rationalActualWideActions_mono {nx ny M : ℕ} + (parent : TargetInterval nx) (complete nearby : List (ℕ × TargetInterval ny)) (P : ℕ) + (hsubset : ∀ br ∈ nearby, br ∈ complete) : + ∀ action ∈ rationalActualWideActions (M := M) parent nearby P, + action ∈ rationalActualWideActions parent complete P := by + intro action ha + obtain ⟨br, hbr, ha⟩ := List.mem_flatMap.mp ha + exact List.mem_flatMap.mpr ⟨br, hsubset br hbr, ha⟩ + +theorem localRefinementRepresentatives_complete {n N P F b : ℕ} {a : ℚ} + (initial : TargetInterval n → ℚ) (q r : TargetInterval n) + (hw : 0 < initial q) (ha : 1 ≤ a) (hF : 1 ≤ F) + (hspatial : |initial q - initial r| ≤ 32 * F * targetEndpointDistance q r) + (hrep : (b, r) ∈ representativeList N P F a initial) + (hcompetitive : 128 * (F : ℚ) * targetEndpointDistance q r ≤ initial q) : + (b, r) ∈ localRefinementRepresentatives N P F a initial q := by + have hconditions := representativeList_conditions a initial hrep + have hnumeric := refinement_cone_locality_numeric hw ha (show (1 : ℚ) ≤ F by exact_mod_cast hF) + (Nat.cast_nonneg (α := ℚ) (targetEndpointDistance q r)) hspatial hconditions.2.2.2 + le_rfl hcompetitive + have hdist : targetEndpointDistance q r ≤ ⌈initial q⌉₊ := by + have hceil : initial q ≤ (⌈initial q⌉₊ : ℚ) := Nat.le_ceil _ + exact_mod_cast hnumeric.2.2.trans hceil + apply List.mem_flatMap.mpr + refine ⟨b, List.mem_filter.mpr ⟨hconditions.1, decide_eq_true ⟨hnumeric.1, hnumeric.2.1⟩⟩, ?_⟩ + apply List.mem_map.mpr + refine ⟨r, List.mem_filter.mpr ⟨?_, decide_eq_true hconditions.2.2.2⟩, rfl⟩ + apply localTargetStates_complete (by unfold seedGridSpacing; omega) q r + (by unfold targetEndpointDistance at hdist; omega) + (by unfold targetEndpointDistance at hdist; omega) + ⟨hconditions.2.1, hconditions.2.2.1⟩ + +/-- Local representatives retain every cone that can improve the initial +fallback. All other complete cones are discarded by their distance charge. -/ +theorem localRefinementBellman_eq {nx ny M : ℕ} + (parent : TargetInterval nx) (N P F : ℕ) (a : ℚ) + (initial : TargetInterval ny → ℚ) (child : Fin M × TargetInterval ny → ℚ) + (q : TargetInterval ny) (ha : 1 ≤ a) (hF : 1 ≤ F) + (hinitial : 0 ≤ initial q) (hchild : ∀ s, 0 ≤ child s) + (hspatial : ∀ r, |initial q - initial r| ≤ 32 * F * targetEndpointDistance q r) : + rationalBellman initial (fun q r => targetEndpointDistance q r) (128 * F) + (rationalActualWideActions parent (localRefinementRepresentatives N P F a initial q) P) child q = + rationalBellman initial (fun q r => targetEndpointDistance q r) (128 * F) + (rationalActualWideActions parent (representativeList N P F a initial) P) child q := by + let complete := rationalActualWideActions (M := M) parent (representativeList N P F a initial) P + let nearby := rationalActualWideActions (M := M) parent (localRefinementRepresentatives N P F a initial q) P + let value := rationalActionValue (M := M) (fun q r : TargetInterval ny => (targetEndpointDistance q r : ℚ)) + (128 * F) child q + have hsubset : ∀ action ∈ nearby, action ∈ complete := rationalActualWideActions_mono parent _ _ P + (localRefinementRepresentatives_subset N P F a initial q) + have hnonneg : ∀ action ∈ complete, 0 ≤ value action := by + intro action ha' + exact rationalActionValue_pruned_lower _ _ child q action 0 (by positivity) + (rationalActualWideActions_connection_nonneg parent _ P action ha') (fun _ => hchild _) + change rationalMinimum (initial q) (nearby.map value) = rationalMinimum (initial q) (complete.map value) + by_cases hw : 0 < initial q + · apply rationalMinimum_local_complete complete nearby value (initial q) hsubset + intro action hacomplete hvalue + obtain ⟨br, hbr, haction⟩ := List.mem_flatMap.mp hacomplete + obtain ⟨states, hstates, heq⟩ := List.mem_map.mp haction + have hcenter : br.2 = action.center := congrArg RationalBellmanAction.center heq + have hcharge : 128 * (F : ℚ) * targetEndpointDistance q action.center ≤ value action := by + exact rationalActionValue_pruned_lower _ _ child q action _ le_rfl + (rationalActualWideActions_connection_nonneg parent _ P action hacomplete) (fun _ => hchild _) + have hrep := localRefinementRepresentatives_complete initial q action.center hw ha hF + (hspatial action.center) (by simpa only [← hcenter] using hbr) (hcharge.trans hvalue) + exact List.mem_flatMap.mpr ⟨br, by simpa only [← hcenter] using hrep, + List.mem_map.mpr ⟨states, hstates, heq⟩⟩ + · have hzero : initial q = 0 := le_antisymm (le_of_not_gt hw) hinitial + have hmin (indices : List (RationalBellmanAction (TargetInterval ny) (Fin M × TargetInterval ny) M)) + (hindices : ∀ action ∈ indices, action ∈ complete) : rationalMinimum (initial q) (indices.map value) = 0 := by + apply le_antisymm + · exact (rationalMinimum_le_fallback _ _).trans_eq hzero + · apply (le_rationalMinimum_iff _ _ _).2 + refine ⟨hinitial, ?_⟩ + intro v hv + obtain ⟨action, haction, rfl⟩ := List.mem_map.mp hv + exact hnonneg action (hindices action haction) + exact (hmin nearby hsubset).trans (hmin complete (fun _ h => h)).symm + +/-- The actual initial table supplies the spatial hypotheses on a good +seed. Thus the bounded local search computes its literal warmup cone. -/ +theorem physical_localRefinementBellman_eq {α : Type*} [DecidableEq α] {M J : ℕ} + (source target : List α) (U : PhysicalEntry M J target.length → ℕ) + (N P F : ℕ) (A : ℚ) (hsize : source.length + target.length ≤ N) + (hP : 66 ≤ P) (hF : 1 ≤ F) (hA : 1 ≤ A) + (hseed : ∀ state, stateEditCost (physicalSource source state.1) target state.2 ≤ U state ∧ + (U state : ℚ) ≤ A * stateEditCost (physicalSource source state.1) target state.2) + (node : PhysicalNode M J) (child : Fin M × TargetInterval target.length → ℚ) + (hchild : ∀ s, 0 ≤ child s) (q : TargetInterval target.length) : + rationalBellman (fun r => stageInitial source target U N P F A (node, r)) + (fun q r => targetEndpointDistance q r) (128 * F) + (rationalActualWideActions (physicalSourceInterval source.length node) + (localRefinementRepresentatives N P F (refinementFactor A F) + (fun r => stageInitial source target U N P F A (node, r)) q) P) child q = + rationalBellman (fun r => stageInitial source target U N P F A (node, r)) + (fun q r => targetEndpointDistance q r) (128 * F) + (rationalActualWideActions (physicalSourceInterval source.length node) + (stageRepresentatives source target U N P F A node) P) child q := by + have hfactor := refinementFactor_spec A F (by omega : 0 < F) + unfold stageRepresentatives + apply localRefinementBellman_eq (M := M) (physicalSourceInterval source.length node) + N P F (refinementFactor A F) (fun r => stageInitial source target U N P F A (node, r)) child q hfactor.1 hF + (stageInitial_nonneg_all_seeds source target U N P F A (node, q)) hchild + intro r + have hqr := physicalInitialTable_spatial source target U N P F A (refinementFactor A F) + hsize hP hF hA hfactor.1 hfactor.2 hseed node q r + have hrq := physicalInitialTable_spatial source target U N P F A (refinementFactor A F) + hsize hP hF hA hfactor.1 hfactor.2 hseed node r q + have hsym : targetEndpointDistance r q = targetEndpointDistance q r := by + exact congrArg₂ (· + ·) (Nat.dist_comm _ _) (Nat.dist_comm _ _) + rw [hsym] at hrq + apply abs_le.mpr + constructor <;> dsimp only [stageInitial] <;> linarith only [hqr, hrq] + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalRefinementQuery.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalRefinementQuery.lean new file mode 100644 index 0000000000000000000000000000000000000000..08bd600d8e8354b060cf4a25344c3715e7f65653 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalRefinementQuery.lean @@ -0,0 +1,118 @@ +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalWarmupQuery +import OAI.Combinatorics.EditApproximation.Geometry.GatheredLocalStep +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalInputEncoding +import OAI.Combinatorics.EditApproximation.Geometry.OnlineEarlierDependence +import OAI.Combinatorics.EditApproximation.Geometry.EarlierValueDependence +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! A local refinement query first reads its finite earlier-history +cover, then the shared current samples, and finally the selected actions. +The continuation is allowed to choose the last list from earlier answers. -/ + +namespace EditApproximation + + + +theorem historyInputCode_injective (M n : ℕ) : + Function.Injective (historyInputCode (M := M) (n := n)) := by + rintro ⟨i, s, q⟩ ⟨i', s', q'⟩ heq + have h := Nat.pair_eq_pair.mp heq + have hc := childInputCode_injective M n h.2 + cases hc + cases h.1 + rfl + +section Step + +variable {ι α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (N P F exponent H Q : ℕ) + (tau a eta kappa delta : ℚ) (t : ℕ) + (parentInitial : TargetInterval target.length → ℚ) + (child initial : Fin M → TargetInterval target.length → ℚ) + (draw : CellGroupDraws M F Q) (integer : ℕ → TargetInterval target.length → ℕ) + (q : TargetInterval target.length) + (readEarlier : (Fin M × ℕ × TargetInterval target.length) → FiniteQuery ι) + (readCurrent : (Fin M × TargetInterval target.length) → FiniteQuery ι) + + + +theorem localRefinementStepQuery_value (oracle : ι → ℚ) + (earlier : PhysicalChildTables M target.length) + (current : Fin M → TargetInterval target.length → ℚ) (ht : 0 < t) + (hreadEarlier : ∀ input, (readEarlier input).value oracle = earlier input.1 input.2.1 input.2.2) + (hreadCurrent : ∀ input, (readCurrent input).value oracle = current input.1 input.2) : + (localRefinementStepQuery source target parent N P F exponent H Q tau a eta kappa delta t + parentInitial child initial draw integer q readEarlier readCurrent).value oracle = + rationalLocalWideStep source target parent N P F exponent Q tau a delta parentInitial child initial + (fun i r => earlier i (t - 1) r) current draw + (localOnlineCandidates source target parent N P F exponent H tau a eta kappa + parentInitial child initial earlier (t - 1) integer q) q := by + let earlierCover := queryEarlierInputCover (M := M) parent N P F exponent t a parentInitial q + let earlierKeys := orderedInputs historyInputCode (historyInputCode_injective M target.length) earlierCover + let cachedEarlier := fun i s r => finiteAnswerTable earlierKeys + (earlierKeys.map fun input => earlier input.1 input.2.1 input.2.2) (i, s, r) + have hearlier : ∀ i s r, (i, s, r) ∈ earlierCover → cachedEarlier i s r = earlier i s r := by + intro i s r hr + exact finiteAnswerTable_map earlierKeys _ _ + ((mem_orderedInputs historyInputCode (historyInputCode_injective M target.length) earlierCover _).2 hr) + have honline := localOnlineCandidates_congr_earlier_cover source target parent N P F exponent H t + tau a eta kappa parentInitial child initial cachedEarlier earlier (t - 1) integer q (by omega) hearlier + let online := localOnlineCandidates source target parent N P F exponent H tau a eta kappa + parentInitial child initial earlier (t - 1) integer q + let shared := querySharedInputCover source target parent N F exponent Q a parentInitial q draw + let sharedKeys := orderedInputs childInputCode (childInputCode_injective M target.length) shared + let sharedCurrent := fun i r => finiteAnswerTable sharedKeys + (sharedKeys.map fun input => current input.1 input.2) (i, r) + have hshared : ∀ input ∈ shared, sharedCurrent input.1 input.2 = current input.1 input.2 := by + intro input hi + exact finiteAnswerTable_map sharedKeys _ input + ((mem_orderedInputs childInputCode (childInputCode_injective M target.length) shared input).2 hi) + have hselected := localCellGroupActions_congr_cover source target parent N P F exponent Q tau a + parentInitial child initial sharedCurrent current draw q hshared + let selected := localCellGroupActions source target parent N P F exponent Q tau a + parentInitial child initial current draw q + let needed := actionCurrentInputCover selected ∪ actionCurrentInputCover online + let currentKeys := orderedInputs childInputCode (childInputCode_injective M target.length) needed + let cachedCurrent := finiteAnswerTable currentKeys (currentKeys.map fun input => current input.1 input.2) + have hcurrent : ∀ input ∈ needed, cachedCurrent input = current input.1 input.2 := by + intro input hi + exact finiteAnswerTable_map currentKeys _ input + ((mem_orderedInputs childInputCode (childInputCode_injective M target.length) needed input).2 hi) + have hgroupValues := rationalActionValues_congr_cover + (fun q r : TargetInterval target.length => (targetEndpointDistance q r : ℚ)) (128 * F) selected q + cachedCurrent (fun input => current input.1 input.2) + (fun input hi => hcurrent input (Finset.mem_union_left _ hi)) + have honlineValues := rationalActionValues_congr_cover + (fun q r : TargetInterval target.length => (targetEndpointDistance q r : ℚ)) (128 * F) online q + cachedCurrent (fun input => current input.1 input.2) + (fun input hi => hcurrent input (Finset.mem_union_right _ hi)) + have hfallback := localBellman_congr_earlier parent N P F exponent t (t - 1) a parentInitial q + cachedEarlier earlier (by omega) (fun input hi => hearlier input.1 input.2.1 input.2.2 hi) (128 * F) + unfold localRefinementStepQuery + rw [FiniteQuery.collect_value] + simp only [hreadEarlier] + change (FiniteQuery.collect readCurrent sharedKeys _).value oracle = _ + rw [FiniteQuery.collect_value] + simp only [hreadCurrent] + change (FiniteQuery.collect readCurrent + (orderedInputs childInputCode (childInputCode_injective M target.length) + (actionCurrentInputCover (localCellGroupActions source target parent N P F exponent Q tau a + parentInitial child initial sharedCurrent draw q) ∪ + actionCurrentInputCover (localOnlineCandidates source target parent N P F exponent H tau a eta kappa + parentInitial child initial cachedEarlier (t - 1) integer q))) _).value oracle = _ + rw [hselected, honline, FiniteQuery.collect_value] + simp only [hreadCurrent, FiniteQuery.value] + change rationalRefinementUpdate delta + (rationalMinimum _ (selected.map (rationalActionValue _ _ cachedCurrent q))) + (rationalOnlineMinimum (online.map (rationalActionValue _ _ cachedCurrent q))) = _ + rw [hgroupValues, honlineValues, hfallback] + rfl + +end Step + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalRefinementQueryWork.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalRefinementQueryWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..33f762e866f9d5c3b5cfa69535123feceaaf5b96 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalRefinementQueryWork.lean @@ -0,0 +1,139 @@ +import OAI.Combinatorics.EditApproximation.Geometry.LocalRefinementQuery +import OAI.Combinatorics.EditApproximation.Probability.FiniteQueryWork + +namespace OAI + +/-! The literal three-stage query plan has the earlier-cover cost plus +at most twice the current-cover cost. This counts its executed readers, +including overlap between its two current gathers. -/ + +namespace EditApproximation + +section Step + +variable {ι α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (N P F exponent H Q : ℕ) + (tau a eta kappa delta : ℚ) (t : ℕ) + (parentInitial : TargetInterval target.length → ℚ) + (child initial : Fin M → TargetInterval target.length → ℚ) + (draw : CellGroupDraws M F Q) (integer : ℕ → TargetInterval target.length → ℕ) + (q : TargetInterval target.length) + (readEarlier : (Fin M × ℕ × TargetInterval target.length) → FiniteQuery ι) + (readCurrent : (Fin M × TargetInterval target.length) → FiniteQuery ι) + (oracle : ι → ℚ) (weight : ι → ℕ) + (earlier : PhysicalChildTables M target.length) + (current : Fin M → TargetInterval target.length → ℚ) + (ht : 0 < t) + (hreadEarlier : ∀ input, (readEarlier input).value oracle = earlier input.1 input.2.1 input.2.2) + (hreadCurrent : ∀ input, (readCurrent input).value oracle = current input.1 input.2) + +include ht hreadEarlier hreadCurrent + +theorem localRefinementStepQuery_cost : + (localRefinementStepQuery source target parent N P F exponent H Q tau a eta kappa delta t + parentInitial child initial draw integer q readEarlier readCurrent).cost oracle weight = + ((orderedInputs historyInputCode (historyInputCode_injective M target.length) + (queryEarlierInputCover parent N P F exponent t a parentInitial q)).map + (fun input => (readEarlier input).cost oracle weight)).sum + + ((orderedInputs childInputCode (childInputCode_injective M target.length) + (querySharedInputCover source target parent N F exponent Q a parentInitial q draw)).map + (fun input => (readCurrent input).cost oracle weight)).sum + + ((orderedInputs childInputCode (childInputCode_injective M target.length) + (actionCurrentInputCover + (localCellGroupActions source target parent N P F exponent Q tau a + parentInitial child initial current draw q) ∪ + actionCurrentInputCover + (localOnlineCandidates source target parent N P F exponent H tau a eta kappa + parentInitial child initial earlier (t - 1) integer q))).map + (fun input => (readCurrent input).cost oracle weight)).sum := by + let earlierCover := queryEarlierInputCover (M := M) parent N P F exponent t a parentInitial q + let earlierKeys := orderedInputs historyInputCode (historyInputCode_injective M target.length) earlierCover + let cachedEarlier := fun i s r => finiteAnswerTable earlierKeys + (earlierKeys.map fun input => earlier input.1 input.2.1 input.2.2) (i, s, r) + have hearlier : ∀ i s r, (i, s, r) ∈ earlierCover → cachedEarlier i s r = earlier i s r := by + intro i s r hr + exact finiteAnswerTable_map earlierKeys _ _ + ((mem_orderedInputs historyInputCode (historyInputCode_injective M target.length) earlierCover _).2 hr) + have honline := localOnlineCandidates_congr_earlier_cover source target parent N P F exponent H t + tau a eta kappa parentInitial child initial cachedEarlier earlier (t - 1) integer q (by omega) hearlier + let shared := querySharedInputCover source target parent N F exponent Q a parentInitial q draw + let sharedKeys := orderedInputs childInputCode (childInputCode_injective M target.length) shared + let sharedCurrent := fun i r => finiteAnswerTable sharedKeys + (sharedKeys.map fun input => current input.1 input.2) (i, r) + have hshared : ∀ input ∈ shared, sharedCurrent input.1 input.2 = current input.1 input.2 := by + intro input hi + exact finiteAnswerTable_map sharedKeys _ input + ((mem_orderedInputs childInputCode (childInputCode_injective M target.length) shared input).2 hi) + have hselected := localCellGroupActions_congr_cover source target parent N P F exponent Q tau a + parentInitial child initial sharedCurrent current draw q hshared + unfold localRefinementStepQuery + rw [FiniteQuery.cost_collect] + simp only [hreadEarlier] + change _ + (FiniteQuery.collect readCurrent sharedKeys _).cost oracle weight = _ + rw [FiniteQuery.cost_collect] + simp only [hreadCurrent] + change _ + (_ + (FiniteQuery.collect readCurrent + (orderedInputs childInputCode (childInputCode_injective M target.length) + (actionCurrentInputCover (localCellGroupActions source target parent N P F exponent Q tau a + parentInitial child initial sharedCurrent draw q) ∪ + actionCurrentInputCover (localOnlineCandidates source target parent N P F exponent H tau a eta kappa + parentInitial child initial cachedEarlier (t - 1) integer q))) _).cost oracle weight) = _ + rw [hselected, honline, FiniteQuery.cost_collect] + simp only [FiniteQuery.cost, Nat.add_zero, Nat.add_assoc] + rfl + +theorem localRefinementStepQuery_cost_le (earlierCost currentCost : ℕ) + (hcostEarlier : ∀ input, (readEarlier input).cost oracle weight ≤ earlierCost) + (hcostCurrent : ∀ input, (readCurrent input).cost oracle weight ≤ currentCost) : + (localRefinementStepQuery source target parent N P F exponent H Q tau a eta kappa delta t + parentInitial child initial draw integer q readEarlier readCurrent).cost oracle weight ≤ + (queryEarlierInputCover (M := M) parent N P F exponent t a parentInitial q).card * earlierCost + + 2 * (currentQueryInputCover source target parent N P F exponent Q tau a parentInitial + child initial current draw q + (localOnlineCandidates source target parent N P F exponent H tau a eta kappa + parentInitial child initial earlier (t - 1) integer q)).card * currentCost := by + rw [localRefinementStepQuery_cost source target parent N P F exponent H Q tau a eta kappa delta t + parentInitial child initial draw integer q readEarlier readCurrent oracle weight earlier current + ht hreadEarlier hreadCurrent] + let online := localOnlineCandidates source target parent N P F exponent H tau a eta kappa + parentInitial child initial earlier (t - 1) integer q + let groups := localCellGroupActions source target parent N P F exponent Q tau a + parentInitial child initial current draw q + let shared := querySharedInputCover source target parent N F exponent Q a parentInitial q draw + let needed := actionCurrentInputCover groups ∪ actionCurrentInputCover online + let cover := currentQueryInputCover source target parent N P F exponent Q tau a parentInitial + child initial current draw q online + have hshared : shared.card ≤ cover.card := Finset.card_le_card (by + intro input hi + exact Finset.mem_union_left _ (Finset.mem_union_left _ hi)) + have hneeded : needed.card ≤ cover.card := Finset.card_le_card (by + intro input hi + rcases Finset.mem_union.mp hi with hi | hi + · exact Finset.mem_union_left _ (Finset.mem_union_right _ hi) + · exact Finset.mem_union_right _ hi) + have bound {β : Type} [DecidableEq β] (code : β → ℕ) (hinj : Function.Injective code) + (inputs : Finset β) (cost : β → ℕ) (B : ℕ) (hcost : ∀ x, cost x ≤ B) : + ((orderedInputs code hinj inputs).map cost).sum ≤ inputs.card * B := by + calc + _ ≤ ((orderedInputs code hinj inputs).map (fun _ => B)).sum := + List.sum_le_sum (fun x _ => hcost x) + _ = inputs.card * B := by simp only [List.map_const', List.sum_replicate, + smul_eq_mul, orderedInputs_length] + have he := bound (β := Fin M × ℕ × TargetInterval target.length) + historyInputCode (historyInputCode_injective M target.length) + (queryEarlierInputCover (M := M) parent N P F exponent t a parentInitial q) + (fun input => (readEarlier input).cost oracle weight) earlierCost hcostEarlier + have hs := bound childInputCode (childInputCode_injective M target.length) shared + (fun input => (readCurrent input).cost oracle weight) currentCost hcostCurrent + have hn := bound childInputCode (childInputCode_injective M target.length) needed + (fun input => (readCurrent input).cost oracle weight) currentCost hcostCurrent + have hs' := Nat.mul_le_mul_right currentCost hshared + have hn' := Nat.mul_le_mul_right currentCost hneeded + change _ ≤ _ + 2 * cover.card * currentCost + nlinarith only [he, hs, hn, hs', hn'] + +end Step + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalSeedSchedule.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalSeedSchedule.lean new file mode 100644 index 0000000000000000000000000000000000000000..bb2971977b2715a5a11c7684404ac6a34072a7a0 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalSeedSchedule.lean @@ -0,0 +1,145 @@ +import OAI.Combinatorics.EditApproximation.Geometry.LocalMedianDrawLaw +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalSeedSchedule + +namespace OAI + +/-! The seed schedule run with bounded local random keys. A whole incoming +seed chooses one fresh product of full-copy local streams. The failure +bound follows from the actual local median law, rather than a seed oracle. -/ + +namespace EditApproximation + +open MeasureTheory ProbabilityTheory + +section Program + +variable {α : Type*} [DecidableEq α] {M J R : ℕ} + [NeZero M] [NeZero R] [MeasurableSpace (Fin M)] [MeasurableSingletonClass (Fin M)] + (source target : List α) (N P T S H : ℕ) + +local notation "Seed" => ClampedPhysicalSeed M J target.length N +local notation "ell" => inputSmallLog N +local notation "thetaExponent" => (40 * smallLogExponent N : ℕ) +local notation "eta" => RationalParameters.eta (rationalParameters ell) +local notation "kappa" => RationalParameters.kappa (rationalParameters ell) +local notation "delta" => RationalParameters.delta (rationalParameters ell) +local notation "tau" => RationalParameters.tau (rationalParameters ell) + +abbrev LocalScheduledSeedDraw (pass : ℕ) (seed : Seed) := Fin (H ^ 2) → + PhysicalLocalProgramDraw (R := R) source target (clampedSeedNat seed) N P ell + (scheduledSeedFactor N pass) T thetaExponent H (ell ^ 80) tau + +noncomputable instance localScheduledSeedDrawFintype (pass : ℕ) (seed : Seed) : + Fintype (LocalScheduledSeedDraw (R := R) source target N P T H pass seed) := by + classical + exact Fintype.ofFinite _ + +noncomputable def localScheduledSeedDrawLaw (pass : ℕ) (seed : Seed) : + Measure (LocalScheduledSeedDraw (R := R) source target N P T H pass seed) := + Measure.pi fun _ : Fin (H ^ 2) => physicalLocalProgramDrawLaw (R := R) + source target (clampedSeedNat seed) N P ell (scheduledSeedFactor N pass) + T thetaExponent H (ell ^ 80) tau + +instance localScheduledSeedDrawLaw_probability (pass : ℕ) (seed : Seed) : + IsProbabilityMeasure (localScheduledSeedDrawLaw (R := R) source target N P T H pass seed) := by + unfold localScheduledSeedDrawLaw physicalLocalProgramDrawLaw + infer_instance + +noncomputable def localScheduledSeedNext (pass : ℕ) (seed : Seed) + (draw : LocalScheduledSeedDraw (R := R) source target N P T H pass seed) : Seed := + physicalLocalMedianUpdateTable source target (clampedSeedNat seed) N P ell + (scheduledSeedFactor N pass) T thetaExponent H (ell ^ 80) tau eta kappa delta + (scheduledSeedMultiplier N pass) S (H ^ 2) draw + +noncomputable def localScheduledSeedLaw (incoming : Measure Seed) (passes : ℕ) : Measure Seed := by + classical + exact adaptiveSeedSequence (localScheduledSeedDrawLaw (R := R) source target N P T H) incoming + (localScheduledSeedNext (R := R) source target N P T S H) passes + +instance localScheduledSeedLaw_probability (incoming : Measure Seed) [IsProbabilityMeasure incoming] + (passes : ℕ) : + IsProbabilityMeasure (localScheduledSeedLaw (R := R) source target N P T S H incoming passes) := by + unfold localScheduledSeedLaw + infer_instance + +variable (hN : 0 < N) (hell : 2 ^ 1000 ≤ inputSmallLog N) + (hMeq : M = (integerParameters N).M) (hJeq : J = intervalTreeDepth M source.length) + (hPeq : P = (integerParameters N).P) (hTeq : T = (integerParameters N).T) + (hSeq : S = (integerParameters N).S) (hHeq : H = inputHeight N) + (hsize : source.length + target.length ≤ N) + (bernstein : ∀ b : ℕ, ∀ h : Fin (groupDyadicScales M b (inputSmallLog N)).length, + FiniteBernsteinInput (Measure.pi fun _ : Fin + (groupSampleCount M (inputSmallLog N ^ 80) b (groupDyadicScaleAt M b (inputSmallLog N) h)) => + (PMF.uniformOfFintype (Fin M)).toMeasure)) + +include hN hPeq hsize in +theorem localScheduledSeedNext_event (pass : ℕ) (seed : Seed) + (hseed : physicalSeedGood source target (scheduledSeedFactor N pass) seed) + (event : Set Seed) : + (localScheduledSeedDrawLaw (R := R) source target N P T H pass seed).real + {draw | localScheduledSeedNext (R := R) source target N P T S H pass seed draw ∈ event} = + (scheduledSeedDrawLaw (R := R) source target N P T H pass seed).real + {draw | scheduledSeedNext (R := R) source target N P T S H pass seed draw ∈ event} := by + have hP : 66 ≤ P := computed_program_grid_lower N P hN hPeq + have hF : 1 ≤ ell := Nat.one_le_two_pow + have hA : (1 : ℚ) ≤ scheduledSeedFactor N pass := by + unfold scheduledSeedFactor + exact one_le_pow₀ (by norm_num) + exact physicalLocalMedianUpdateTable_event (R := R) source target (clampedSeedNat seed) + N P ell (scheduledSeedFactor N pass) T thetaExponent H (ell ^ 80) tau eta kappa delta + (scheduledSeedMultiplier N pass) S (H ^ 2) hsize hP hF hA hseed event + +include hN hell hMeq hJeq hPeq hTeq hSeq hHeq hsize bernstein in +theorem localScheduledSeedNext_failure (pass : ℕ) (hpass : pass < computedSeedPassCount N) + (seed : Seed) (hseed : physicalSeedGood source target (scheduledSeedFactor N pass) seed) : + (localScheduledSeedDrawLaw (R := R) source target N P T H pass seed).real + {draw | ¬ physicalSeedGood source target (scheduledSeedFactor N (pass + 1)) + (localScheduledSeedNext (R := R) source target N P T S H pass seed draw)} ≤ + Real.exp (10 * H - (H : ℝ) ^ 2) := by + have hevent := localScheduledSeedNext_event (R := R) source target N P T S H hN hPeq hsize + pass seed hseed {next | ¬ physicalSeedGood source target (scheduledSeedFactor N (pass + 1)) next} + simp only [Set.mem_ofPred_eq] at hevent + rw [hevent] + exact scheduledSeedNext_failure source target N P T S H hN hell hMeq hJeq hPeq hTeq hSeq hHeq + hsize bernstein pass hpass seed hseed + +include hN hell hMeq hJeq hPeq hTeq hSeq hHeq hsize bernstein in +theorem localScheduledSeedLaw_failure (incoming : Measure Seed) [IsProbabilityMeasure incoming] : + (localScheduledSeedLaw (R := R) source target N P T S H incoming (computedSeedPassCount N)).real + {seed | ¬ physicalSeedGood source target (scheduledSeedFactor N (computedSeedPassCount N)) seed} ≤ + incoming.real {seed | ¬ physicalSeedGood source target (scheduledSeedFactor N 0) seed} + + computedSeedPassCount N * Real.exp (10 * H - (H : ℝ) ^ 2) := by + classical + have h := adaptiveSeedSequence_failure + (localScheduledSeedDrawLaw (R := R) source target N P T H) incoming + (localScheduledSeedNext (R := R) source target N P T S H) + (fun pass => physicalSeedGood source target (scheduledSeedFactor N pass)) + (fun _ => Real.exp (10 * H - (H : ℝ) ^ 2)) (fun _ => (Real.exp_pos _).le) (computedSeedPassCount N) + (fun pass hp seed hg => localScheduledSeedNext_failure source target N P T S H + hN hell hMeq hJeq hPeq hTeq hSeq hHeq hsize bernstein pass hp seed hg) + simpa only [localScheduledSeedLaw, Finset.sum_const, Finset.card_range, nsmul_eq_mul] using h + +include hN hell hMeq hJeq hPeq hTeq hSeq hHeq hsize bernstein in +theorem localScheduledSeedLaw_failure_lt (incoming : Measure Seed) [IsProbabilityMeasure incoming] + (hinitial : incoming.real {seed | ¬ physicalSeedGood source target + ((integerParameters N).initialFactor : ℚ) seed} ≤ 1 / 100) : + (localScheduledSeedLaw (R := R) source target N P T S H incoming (computedSeedPassCount N)).real + {seed | ¬ physicalSeedGood source target (scheduledSeedFactor N (computedSeedPassCount N)) seed} < 1 / 10 := by + have hbound := localScheduledSeedLaw_failure (R := R) source target N P T S H hN hell hMeq hJeq hPeq + hTeq hSeq hHeq hsize bernstein incoming + rw [scheduledSeedFactor_zero] at hbound + have hsmall : 256 ≤ (2 : ℕ) ^ 1000 := by + have h := pow_le_pow_right₀ (by decide : 1 ≤ (2 : ℕ)) (by decide : 8 ≤ 1000) + norm_num only [show (2 : ℕ) ^ 8 = 256 by norm_num] at h + exact h + have hcut : 200 ≤ ell := by omega + apply (hbound.trans (add_le_add hinitial le_rfl)).trans_lt + rw [hHeq] + exact computed_seed_total_failure N (computedSeedPassCount N) hN hcut + (computedSeedPassCount_le_height N hN hell) + +end Program + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalSeedSequence.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalSeedSequence.lean new file mode 100644 index 0000000000000000000000000000000000000000..5a0d39bdfdf83112e3060f6805bd90e63b8be433 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalSeedSequence.lean @@ -0,0 +1,79 @@ +import OAI.Combinatorics.EditApproximation.Geometry.UnifiedPhysicalTable +import OAI.Combinatorics.EditApproximation.Geometry.LocalOnlineProgram +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalDependencyRank +import OAI.Combinatorics.EditApproximation.Probability.Median + +namespace OAI + +/-! Mathematical values for the actual local seed passes. This complete +function is a specification for the lazy program, not a table allocated +by the implementation. Copy streams are kept distinct at every pass. -/ + +namespace EditApproximation + +section Sequence + +variable {α : Type*} [DecidableEq α] {M J R : ℕ} [NeZero R] + (source target : List α) (N P F exponent H Q T S copies : ℕ) + (factor : ℕ → ℚ) (multiplier : ℕ → ℕ) (tau eta kappa delta : ℚ) + (group : ℕ → ℕ → PhysicalInternalNode M J → Fin R → CellGroupDraws M F Q) + (integer : ℕ → ℕ → PhysicalInternalNode M J → Fin R → ℕ → TargetInterval target.length → ℕ) + +def localPassValue (seed : PhysicalEntry M J target.length → ℕ) (pass copy : ℕ) + (node : PhysicalNode M J) (t : ℕ) (q : TargetInterval target.length) : ℚ := + physicalLocalRefinement source target seed N P F exponent Q (factor pass) tau delta T + (fun node t => group pass copy node (Fin.ofNat R (t - 1))) + (physicalLocalOnline source target seed N P F exponent H T (factor pass) tau eta kappa + (integer pass copy)) node t q + +def localSeedSequence (initial : PhysicalEntry M J target.length → ℕ) : + ℕ → PhysicalEntry M J target.length → ℕ + | 0 => initial + | pass + 1 => fun state => min N (upperMedian (List.ofFn fun copy : Fin copies => + ⌈(multiplier pass : ℚ) * localPassValue source target N P F exponent H Q T factor + tau eta kappa delta group integer (localSeedSequence initial pass) pass copy.val state.1 S state.2⌉₊)) + +theorem localSeedSequence_zero (initial : PhysicalEntry M J target.length → ℕ) : + localSeedSequence source target N P F exponent H Q T S copies factor multiplier + tau eta kappa delta group integer initial 0 = initial := rfl + +theorem localSeedSequence_bounded (initial : PhysicalEntry M J target.length → ℕ) + (hinitial : ∀ state, initial state ≤ N) (pass : ℕ) (state : PhysicalEntry M J target.length) : + localSeedSequence source target N P F exponent H Q T S copies factor multiplier + tau eta kappa delta group integer initial pass state ≤ N := by + cases pass with + | zero => exact hinitial state + | succ pass => exact min_le_left _ _ + +def localRequestValue (initial : PhysicalEntry M J target.length → ℕ) + (request : PhysicalTableRequest M J target.length) : ℚ := + let seed := localSeedSequence source target N P F exponent H Q T S copies factor multiplier + tau eta kappa delta group integer initial request.pass + unifiedPhysicalValue source target seed N P F exponent Q (factor request.pass) tau delta T + (fun node t => group request.pass request.copy node (Fin.ofNat R (t - 1))) + (physicalLocalOnline source target seed N P F exponent H T (factor request.pass) tau eta kappa + (integer request.pass request.copy)) request.node request.index request.state + +theorem localRequestValue_warmup (initial : PhysicalEntry M J target.length → ℕ) + (pass copy : ℕ) (node : PhysicalNode M J) (j : ℕ) (hj : j ≤ T) (q : TargetInterval target.length) : + localRequestValue source target N P F exponent H Q T S copies factor multiplier + tau eta kappa delta group integer initial (PhysicalTableRequest.warmup pass copy node j q) = + physicalLocalWarmup source target + (localSeedSequence source target N P F exponent H Q T S copies factor multiplier + tau eta kappa delta group integer initial pass) N P F (factor pass) j (node, q) := + unifiedPhysicalValue_warmup _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ hj _ + +theorem localRequestValue_refinement (initial : PhysicalEntry M J target.length → ℕ) + (pass copy : ℕ) (node : PhysicalNode M J) (t : ℕ) (q : TargetInterval target.length) : + localRequestValue source target N P F exponent H Q T S copies factor multiplier + tau eta kappa delta group integer initial (PhysicalTableRequest.refinement pass copy node T t q) = + localPassValue source target N P F exponent H Q T factor tau eta kappa delta group integer + (localSeedSequence source target N P F exponent H Q T S copies factor multiplier + tau eta kappa delta group integer initial pass) pass copy node t q := + unifiedPhysicalValue_refinement _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ + +end Sequence + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalSourceReadCost.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalSourceReadCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..67a12a44e7b7081df7b99e27b31e635e09c044af --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalSourceReadCost.lean @@ -0,0 +1,85 @@ +import OAI.Combinatorics.EditApproximation.Geometry.LocalRandomQueryKeys +import OAI.Combinatorics.EditApproximation.Probability.FiniteQueryCostOrder + +namespace OAI + +/-! Exact source-read overhead of a local refinement step. The table +reads are charged separately by the existing current/earlier budgets. -/ + +namespace EditApproximation + +section Cost + +variable {ι α : Type*} (source target : List α) {M : ℕ} [NeZero M] + (parent : TargetInterval source.length) (N P F exponent H Q : ℕ) + (tau a eta kappa delta : ℚ) (t : ℕ) + (parentInitial : TargetInterval target.length → ℚ) + (child initial : Fin M → TargetInterval target.length → ℚ) + (q : TargetInterval target.length) + (readGroup : GroupScalarKey M F Q → FiniteQuery ι) + (readInteger : (ℕ × TargetInterval target.length) → ℕ → FiniteQuery ι) + (readEarlier : (Fin M × ℕ × TargetInterval target.length) → FiniteQuery ι) + (readCurrent : (Fin M × TargetInterval target.length) → FiniteQuery ι) + (oracle : ι → ℚ) (weight : ι → ℕ) + (hearlier : ∀ input key, key ∈ (readEarlier input).keys oracle → weight key = 0) + (hcurrent : ∀ input key, key ∈ (readCurrent input).keys oracle → weight key = 0) + +include hearlier hcurrent + +omit [NeZero M] in + theorem localOnlineSourceStepQuery_source_cost_le (draw : CellGroupDraws M F Q) + (bound : ℕ) (hread : ∀ key range, (readInteger key range).cost oracle weight ≤ bound) : + (localOnlineSourceStepQuery source target parent N P F exponent H Q tau a eta kappa delta t + parentInitial child initial draw q readInteger readEarlier readCurrent).cost oracle weight ≤ + (localOnlineSourceKeys N P F a parentInitial q).length * bound := by + rw [localOnlineSourceStepQuery_cost] + dsimp only + have hzero (integer : ℕ → TargetInterval target.length → ℕ) : + (localRefinementStepQuery source target parent N P F exponent H Q tau a eta kappa delta t + parentInitial child initial draw integer q readEarlier readCurrent).cost oracle weight = 0 := by + apply FiniteQuery.cost_eq_zero_of_keys + exact localRefinementStepQuery_keys_all source target parent N P F exponent H Q + tau a eta kappa delta t parentInitial child initial draw integer q readEarlier readCurrent + oracle (fun key => weight key = 0) hearlier hcurrent + rw [hzero, Nat.add_zero] + apply list_map_sum_le_constant + intro key + exact hread key _ + + theorem localRandomSourceStepQuery_source_cost_le (groupBound onlineBound : ℕ) + (hgroup : ∀ key, (readGroup key).cost oracle weight ≤ groupBound) + (honline : ∀ key range, (readInteger key range).cost oracle weight ≤ onlineBound) : + (localRandomSourceStepQuery source target parent N P F exponent H Q tau a eta kappa delta t + parentInitial child initial q readGroup readInteger readEarlier readCurrent).cost oracle weight ≤ + (groupScalarKeys M F Q (localGroupQueryKeys N F exponent a parentInitial q)).length * groupBound + + (localOnlineSourceKeys N P F a parentInitial q).length * onlineBound := by + unfold localRandomSourceStepQuery + rw [FiniteQuery.cost_collect] + exact Nat.add_le_add + (list_map_sum_le_constant _ _ _ hgroup) + (localOnlineSourceStepQuery_source_cost_le source target parent N P F exponent H Q tau a eta kappa delta t + parentInitial child initial q readInteger readEarlier readCurrent oracle weight hearlier hcurrent _ + onlineBound honline) + + theorem localRandomSourceStepQuery_source_cost_labels (labels groupBound onlineBound : ℕ) + (hlabels : ∀ key ∈ localGroupQueryKeys N F exponent a parentInitial q, + (groupDyadicScales M key.1 F).length ≤ labels) + (hgroup : ∀ key, (readGroup key).cost oracle weight ≤ groupBound) + (honline : ∀ key range, (readInteger key range).cost oracle weight ≤ onlineBound) : + (localRandomSourceStepQuery source target parent N P F exponent H Q tau a eta kappa delta t + parentInitial child initial q readGroup readInteger readEarlier readCurrent).cost oracle weight ≤ + (localGroupQueryKeys N F exponent a parentInitial q).length * labels * M * groupBound + + (dyadicQueryWindow N (parentInitial q) a F).length * onlineBound := by + refine (localRandomSourceStepQuery_source_cost_le source target parent N P F exponent H Q + tau a eta kappa delta t parentInitial child initial q readGroup readInteger readEarlier readCurrent + oracle weight hearlier hcurrent groupBound onlineBound hgroup honline).trans ?_ + apply Nat.add_le_add + · exact Nat.mul_le_mul_right groupBound + (groupScalarKeys_length_le M F Q labels _ hlabels) + · rw [localOnlineSourceKeys_length] + +end Cost + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalTraceMemoOutput.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalTraceMemoOutput.lean new file mode 100644 index 0000000000000000000000000000000000000000..e436bbfc25f4bde63160d6402759913efcc787c8 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalTraceMemoOutput.lean @@ -0,0 +1,152 @@ +import OAI.Combinatorics.EditApproximation.Geometry.LocalTraceProgram +import OAI.Combinatorics.EditApproximation.Geometry.LocalFinalAccuracy +import OAI.Combinatorics.EditApproximation.Geometry.ChargedGlobalQuery +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! The bounded-key adaptive trace drives the actual charged memo program. +Its final root query has the same distribution as the local answer. The program +uses all previous-pass copies from the trace and one fresh terminal copy. -/ + +namespace EditApproximation + +open MeasureTheory ProbabilityTheory + +section Output + +variable {α : Type*} [DecidableEq α] {M J R : ℕ} + [NeZero M] [NeZero R] [MeasurableSpace (Fin M)] [MeasurableSingletonClass (Fin M)] + (source target : List α) (N P T S H : ℕ) + +local notation "Seed" => ClampedPhysicalSeed M J target.length N +local notation "passes" => computedSeedPassCount N +local notation "ell" => inputSmallLog N +local notation "thetaExponent" => (40 * smallLogExponent N : ℕ) +local notation "eta" => RationalParameters.eta (rationalParameters ell) +local notation "kappa" => RationalParameters.kappa (rationalParameters ell) +local notation "delta" => RationalParameters.delta (rationalParameters ell) +local notation "tau" => RationalParameters.tau (rationalParameters ell) + +abbrev LocalTraceFinalOutcome := + LocalScheduledTrace (M := M) (J := J) (R := R) source target N P T H passes × + (∀ seed : Seed, LocalFinalProgramDraw (R := R) source target N P T H seed) + +noncomputable def localTraceAppendFinal + (outcome : LocalTraceFinalOutcome (M := M) (J := J) (R := R) source target N P T H) : + LocalScheduledTrace (M := M) (J := J) (R := R) source target N P T H (passes + 1) := + (outcome.1, fun seed _ => outcome.2 seed) + + + +noncomputable def localTraceMemoResult (hH : 0 < H) (rootQ : TargetInterval target.length) + (outcome : LocalTraceFinalOutcome (M := M) (J := J) (R := R) source target N P T H) := + let trace := localTraceAppendFinal source target N P T H outcome + chargedMemoEvaluate source target N P ell thetaExponent H (ell ^ 80) T S (passes + 1) (H ^ 2) + (scheduledSeedFactor N) (scheduledSeedMultiplier N) tau eta kappa delta + (localTraceGroup source target N P T S H (passes + 1) trace) + (localTraceInteger source target N P T S H (passes + 1) trace) + (clampedSeedNat (localTraceInitial source target N P T H passes outcome.1)) + (localFinalRootRequest (M := M) (J := J) target N T S H hH rootQ) + +noncomputable def localTraceFinalProjection + (outcome : LocalTraceFinalOutcome (M := M) (J := J) (R := R) source target N P T H) : + LocalFinalProgramOutcome (M := M) (J := J) (R := R) source target N P T H := + (localTraceSeed source target N P T S H passes outcome.1, outcome.2) + +omit [MeasurableSpace (Fin M)] [MeasurableSingletonClass (Fin M)] in +theorem localTraceMemoResult_value (hH : 0 < H) (rootQ : TargetInterval target.length) + (outcome : LocalTraceFinalOutcome (M := M) (J := J) (R := R) source target N P T H) : + ((localTraceMemoResult source target N P T S H hH rootQ outcome).value : ℝ) = + freshSeedValue (localFinalProgramValue (R := R) source target N P T S H rootQ) + (localTraceFinalProjection source target N P T S H outcome) := by + let trace := localTraceAppendFinal source target N P T H outcome + unfold localTraceMemoResult + rw [chargedMemoEvaluate_value source target N P ell thetaExponent H (ell ^ 80) T S (passes + 1) (H ^ 2) + (scheduledSeedFactor N) (scheduledSeedMultiplier N) tau eta kappa delta + (localTraceGroup source target N P T S H (passes + 1) trace) + (localTraceInteger source target N P T S H (passes + 1) trace) + (clampedSeedNat (localTraceInitial source target N P T H passes outcome.1)) + (Nat.one_le_iff_ne_zero.mpr (NeZero.ne M))] + change (localRequestValue source target N P ell thetaExponent H (ell ^ 80) T S (H ^ 2) + (scheduledSeedFactor N) (scheduledSeedMultiplier N) tau eta kappa delta + (localTraceGroup source target N P T S H (passes + 1) trace) + (localTraceInteger source target N P T S H (passes + 1) trace) + (clampedSeedNat (localTraceInitial source target N P T H passes outcome.1)) + (PhysicalTableRequest.refinement passes 0 + (Sigma.mk (Fin.mk 0 (Nat.zero_lt_succ J)) PUnit.unit) T S rootQ) : ℝ) = _ + rw [localRequestValue_refinement] + have hseed := localTraceSeed_before source target N P T S H passes trace + change localSeedSequence source target N P ell thetaExponent H (ell ^ 80) T S (H ^ 2) + (scheduledSeedFactor N) (scheduledSeedMultiplier N) tau eta kappa delta + (localTraceGroup source target N P T S H (passes + 1) trace) + (localTraceInteger source target N P T S H (passes + 1) trace) + (clampedSeedNat (localTraceInitial source target N P T H passes outcome.1)) passes = _ at hseed + rw [hseed] + rw [localTracePassValue source target N P T S H passes trace ⟨0, pow_pos hH 2⟩] + rfl + +noncomputable def localTraceMemoAnswer (hH : 0 < H) (rootQ : TargetInterval target.length) + (outcome : LocalTraceFinalOutcome (M := M) (J := J) (R := R) source target N P T H) : ℕ := + if source = substring target rootQ.lo rootQ.hi then 0 else + integerAnswer N ((localTraceMemoResult source target N P T S H hH rootQ outcome).value : ℝ) + +omit [MeasurableSpace (Fin M)] [MeasurableSingletonClass (Fin M)] in +theorem localTraceMemoAnswer_eq (hH : 0 < H) (rootQ : TargetInterval target.length) + (outcome : LocalTraceFinalOutcome (M := M) (J := J) (R := R) source target N P T H) : + localTraceMemoAnswer source target N P T S H hH rootQ outcome = + localFinalProgramAnswer (R := R) source target N P T S H rootQ + (localTraceFinalProjection source target N P T S H outcome) := by + unfold localTraceMemoAnswer localFinalProgramAnswer + rw [localTraceMemoResult_value] + +noncomputable def localTraceFinalLaw (incoming : Measure Seed) : + Measure (LocalTraceFinalOutcome (M := M) (J := J) (R := R) source target N P T H) := by + classical + exact (adaptiveTraceLaw (localScheduledSeedDrawLaw (M := M) (J := J) (R := R) source target N P T H) incoming passes).prod + (Measure.pi (localFinalProgramDrawLaw (M := M) (J := J) (R := R) source target N P T H)) + +instance localTraceFinalLaw_probability (incoming : Measure Seed) [IsProbabilityMeasure incoming] : + IsProbabilityMeasure (localTraceFinalLaw (R := R) source target N P T H incoming) := by + unfold localTraceFinalLaw + infer_instance + +theorem localTraceFinalLaw_map (incoming : Measure Seed) : + (localTraceFinalLaw (R := R) source target N P T H incoming).map + (localTraceFinalProjection source target N P T S H) = + localFinalProgramLaw (R := R) source target N P T S H incoming := by + classical + have h := Measure.map_prod_map + (adaptiveTraceLaw (localScheduledSeedDrawLaw (M := M) (J := J) (R := R) source target N P T H) incoming passes) + (Measure.pi (localFinalProgramDrawLaw (M := M) (J := J) (R := R) source target N P T H)) + (measurable_of_finite (localTraceSeed (M := M) (J := J) (R := R) + source target N P T S H passes)) measurable_id + change (localTraceFinalLaw (R := R) source target N P T H incoming).map + (localTraceFinalProjection source target N P T S H) = _ + rw [localTraceFinalLaw, show localTraceFinalProjection source target N P T S H = + Prod.map (localTraceSeed source target N P T S H passes) id from rfl] + rw [← h, Measure.map_id] + unfold localTraceSeed + rw [adaptiveTraceLaw_map] + simp only [localFinalProgramLaw, localScheduledSeedLaw] + +theorem localTraceMemoAnswer_event (incoming : Measure Seed) (hH : 0 < H) + (rootQ : TargetInterval target.length) (event : Set ℕ) : + (localTraceFinalLaw (R := R) source target N P T H incoming).real + {outcome | localTraceMemoAnswer source target N P T S H hH rootQ outcome ∈ event} = + (localFinalProgramLaw (R := R) source target N P T S H incoming).real + {outcome | localFinalProgramAnswer (R := R) source target N P T S H rootQ outcome ∈ event} := by + classical + have h := congrArg + (fun law : Measure (LocalFinalProgramOutcome (M := M) (J := J) (R := R) source target N P T H) => + law.real {outcome | localFinalProgramAnswer (R := R) source target N P T S H rootQ outcome ∈ event}) + (localTraceFinalLaw_map (R := R) source target N P T S H incoming) + rw [map_measureReal_apply (measurable_of_finite _) (Set.toFinite _).measurableSet] at h + simpa only [Set.preimage, Set.mem_ofPred_eq, localTraceMemoAnswer_eq] using h + +end Output + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalTraceProgram.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalTraceProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..5668171e61c3bc26350c6ac2b0d2bda64717e47f --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalTraceProgram.lean @@ -0,0 +1,196 @@ +import OAI.Combinatorics.EditApproximation.Geometry.LocalSeedSchedule +import OAI.Combinatorics.EditApproximation.Probability.AdaptiveSeedTrace +import OAI.Combinatorics.EditApproximation.Geometry.LocalSeedSequence + +namespace OAI + +/-! Extract the actual per-pass streams from a finite adaptive draw trace. +Earlier-pass streams are preserved when a new draw is appended, and the +lazy program's seed recurrence is exactly the trace's returned table. -/ + +namespace EditApproximation + +theorem localSeedSequence_streams_congr {α : Type*} [DecidableEq α] {M J R : ℕ} [NeZero R] + (source target : List α) (N P F exponent H Q T S copies : ℕ) + (factor : ℕ → ℚ) (multiplier : ℕ → ℕ) (tau eta kappa delta : ℚ) + (group group' : ℕ → ℕ → PhysicalInternalNode M J → Fin R → CellGroupDraws M F Q) + (integer integer' : ℕ → ℕ → PhysicalInternalNode M J → Fin R → ℕ → + TargetInterval target.length → ℕ) + (initial : PhysicalEntry M J target.length → ℕ) (pass : ℕ) + (hgroup : ∀ p < pass, group p = group' p) + (hinteger : ∀ p < pass, integer p = integer' p) : + localSeedSequence source target N P F exponent H Q T S copies factor multiplier + tau eta kappa delta group integer initial pass = + localSeedSequence source target N P F exponent H Q T S copies factor multiplier + tau eta kappa delta group' integer' initial pass := by + induction pass with + | zero => rfl + | succ pass ih => + have hprev := ih (fun p hp => hgroup p (by omega)) (fun p hp => hinteger p (by omega)) + simp only [localSeedSequence, hprev, localPassValue, hgroup pass (by omega), hinteger pass (by omega)] + +section Trace + +variable {α : Type*} [DecidableEq α] {M J R : ℕ} + [NeZero M] [NeZero R] + (source target : List α) (N P T S H : ℕ) + +local notation "Seed" => ClampedPhysicalSeed M J target.length N +local notation "ell" => inputSmallLog N +local notation "thetaExponent" => (40 * smallLogExponent N : ℕ) +local notation "eta" => RationalParameters.eta (rationalParameters ell) +local notation "kappa" => RationalParameters.kappa (rationalParameters ell) +local notation "delta" => RationalParameters.delta (rationalParameters ell) +local notation "tau" => RationalParameters.tau (rationalParameters ell) + +abbrev LocalScheduledTrace (passes : ℕ) := AdaptiveSeedTrace Seed + (LocalScheduledSeedDraw (R := R) source target N P T H) passes + +noncomputable def localTraceSeed (passes : ℕ) + (trace : LocalScheduledTrace (M := M) (J := J) (R := R) source target N P T H passes) : Seed := + adaptiveTraceValue (localScheduledSeedNext (R := R) source target N P T S H) passes trace + +theorem localTraceSeed_succ (passes : ℕ) + (trace : LocalScheduledTrace (M := M) (J := J) (R := R) source target N P T H (passes + 1)) : + localTraceSeed source target N P T S H (passes + 1) trace = + localScheduledSeedNext source target N P T S H passes + (localTraceSeed source target N P T S H passes trace.1) + (trace.2 (localTraceSeed source target N P T S H passes trace.1)) := rfl + +def localTraceInitial : (passes : ℕ) → LocalScheduledTrace (M := M) (J := J) (R := R) source target N P T H passes → Seed + | 0, seed => seed + | passes + 1, trace => localTraceInitial passes trace.1 + +noncomputable def localTraceGroup : (passes : ℕ) → + LocalScheduledTrace (M := M) (J := J) (R := R) source target N P T H passes → + ℕ → ℕ → PhysicalInternalNode M J → Fin R → CellGroupDraws M ell (ell ^ 80) + | 0, _ => fun _ _ _ _ _ _ _ _ => 0 + | passes + 1, trace => fun pass copy node time => + if pass = passes then + if hcopy : copy < H ^ 2 then + physicalRawGroupDraws M J N target.length thetaExponent ell (ell ^ 80) R + (fun key => trace.2 (localTraceSeed source target N P T S H passes trace.1) + ⟨copy, hcopy⟩ (.inr key)) node time + else fun _ _ _ _ => 0 + else localTraceGroup passes trace.1 pass copy node time + +noncomputable def localTraceInteger : (passes : ℕ) → + LocalScheduledTrace (M := M) (J := J) (R := R) source target N P T H passes → + ℕ → ℕ → PhysicalInternalNode M J → Fin R → ℕ → TargetInterval target.length → ℕ + | 0, _ => fun _ _ _ _ _ _ => 0 + | passes + 1, trace => fun pass copy => + if pass = passes then + if hcopy : copy < H ^ 2 then + physicalRawOnlineIntegers source target + (clampedSeedNat (localTraceSeed source target N P T S H passes trace.1)) + N P ell (scheduledSeedFactor N passes) T thetaExponent H tau + (fun key => trace.2 (localTraceSeed source target N P T S H passes trace.1) + ⟨copy, hcopy⟩ (.inl key)) + else fun _ _ _ _ => 0 + else localTraceInteger passes trace.1 pass copy + +theorem localTraceGroup_before (passes : ℕ) + (trace : LocalScheduledTrace (M := M) (J := J) (R := R) source target N P T H (passes + 1)) + (pass : ℕ) (hpass : pass < passes) : + localTraceGroup source target N P T S H (passes + 1) trace pass = + localTraceGroup source target N P T S H passes trace.1 pass := by + funext copy node time + simp only [localTraceGroup, ite_eq_right (show pass ≠ passes by omega)] + +theorem localTraceInteger_before (passes : ℕ) + (trace : LocalScheduledTrace (M := M) (J := J) (R := R) source target N P T H (passes + 1)) + (pass : ℕ) (hpass : pass < passes) : + localTraceInteger source target N P T S H (passes + 1) trace pass = + localTraceInteger source target N P T S H passes trace.1 pass := by + funext copy + simp only [localTraceInteger, ite_eq_right (show pass ≠ passes by omega)] + +theorem localTracePassValue (passes : ℕ) + (trace : LocalScheduledTrace (M := M) (J := J) (R := R) source target N P T H (passes + 1)) + (copy : Fin (H ^ 2)) (node : PhysicalNode M J) (t : ℕ) + (q : TargetInterval target.length) : + localPassValue source target N P ell thetaExponent H (ell ^ 80) T + (scheduledSeedFactor N) tau eta kappa delta + (localTraceGroup source target N P T S H (passes + 1) trace) + (localTraceInteger source target N P T S H (passes + 1) trace) + (clampedSeedNat (localTraceSeed source target N P T S H passes trace.1)) + passes copy.val node t q = + physicalLocalJointValue source target + (clampedSeedNat (localTraceSeed source target N P T S H passes trace.1)) + N P ell (scheduledSeedFactor N passes) T thetaExponent H (ell ^ 80) tau eta kappa delta + (trace.2 (localTraceSeed source target N P T S H passes trace.1) copy) node t q := by + simp only [localPassValue, localTraceGroup, localTraceInteger, ite_true, dite_eq_left copy.isLt, + physicalLocalJointValue] + +theorem localTraceSeed_eq : ∀ (passes : ℕ) + (trace : LocalScheduledTrace (M := M) (J := J) (R := R) source target N P T H passes), + localSeedSequence source target N P ell thetaExponent H (ell ^ 80) T S (H ^ 2) + (scheduledSeedFactor N) (scheduledSeedMultiplier N) tau eta kappa delta + (localTraceGroup source target N P T S H passes trace) + (localTraceInteger source target N P T S H passes trace) + (clampedSeedNat (localTraceInitial source target N P T H passes trace)) passes = + clampedSeedNat (localTraceSeed source target N P T S H passes trace) := by + intro passes + induction passes with + | zero => intro trace; rfl + | succ passes ih => + intro trace + have hprevious := localSeedSequence_streams_congr source target N P ell thetaExponent H (ell ^ 80) + T S (H ^ 2) (scheduledSeedFactor N) (scheduledSeedMultiplier N) tau eta kappa delta + (localTraceGroup source target N P T S H (passes + 1) trace) + (localTraceGroup source target N P T S H passes trace.1) + (localTraceInteger source target N P T S H (passes + 1) trace) + (localTraceInteger source target N P T S H passes trace.1) + (clampedSeedNat (localTraceInitial source target N P T H passes trace.1)) passes + (localTraceGroup_before source target N P T S H passes trace) + (localTraceInteger_before source target N P T S H passes trace) + have hseed := hprevious.trans (ih trace.1) + conv_lhs => rw [localSeedSequence] + rw [show localTraceInitial source target N P T H (passes + 1) trace = + localTraceInitial source target N P T H passes trace.1 from rfl] + rw [hseed] + rw [localTraceSeed_succ] + funext state + change min N (upperMedian (List.ofFn _)) = + min N (upperMedian (List.ofFn fun copy : Fin (H ^ 2) => + ⌈(scheduledSeedMultiplier N passes : ℚ) * physicalLocalJointValue source target + (clampedSeedNat (localTraceSeed source target N P T S H passes trace.1)) + N P ell (scheduledSeedFactor N passes) T thetaExponent H (ell ^ 80) tau eta kappa delta + (trace.2 (localTraceSeed source target N P T S H passes trace.1) copy) state.1 S state.2⌉₊)) + apply congrArg (fun values : Fin (H ^ 2) → ℕ => min N (upperMedian (List.ofFn values))) + funext copy + rw [localTracePassValue source target N P T S H passes trace copy state.1 S state.2] + +theorem localTraceSeed_before (passes : ℕ) + (trace : LocalScheduledTrace (M := M) (J := J) (R := R) source target N P T H (passes + 1)) : + localSeedSequence source target N P ell thetaExponent H (ell ^ 80) T S (H ^ 2) + (scheduledSeedFactor N) (scheduledSeedMultiplier N) tau eta kappa delta + (localTraceGroup source target N P T S H (passes + 1) trace) + (localTraceInteger source target N P T S H (passes + 1) trace) + (clampedSeedNat (localTraceInitial source target N P T H (passes + 1) trace)) passes = + clampedSeedNat (localTraceSeed source target N P T S H passes trace.1) := by + apply (localSeedSequence_streams_congr source target N P ell thetaExponent H (ell ^ 80) + T S (H ^ 2) (scheduledSeedFactor N) (scheduledSeedMultiplier N) tau eta kappa delta + (localTraceGroup source target N P T S H (passes + 1) trace) + (localTraceGroup source target N P T S H passes trace.1) + (localTraceInteger source target N P T S H (passes + 1) trace) + (localTraceInteger source target N P T S H passes trace.1) + (clampedSeedNat (localTraceInitial source target N P T H passes trace.1)) passes + (localTraceGroup_before source target N P T S H passes trace) + (localTraceInteger_before source target N P T S H passes trace)).trans + exact localTraceSeed_eq source target N P T S H passes trace.1 + +end Trace + +instance localScheduledTrace_measurableSingleton {α : Type*} [DecidableEq α] {M J R : ℕ} + [NeZero M] [NeZero R] [MeasurableSpace (Fin M)] [MeasurableSingletonClass (Fin M)] + (source target : List α) (N P T H passes : ℕ) : + MeasurableSingletonClass + (LocalScheduledTrace (M := M) (J := J) (R := R) source target N P T H passes) := by + classical + exact adaptiveSeedTraceSingleton (ClampedPhysicalSeed M J target.length N) + (LocalScheduledSeedDraw (R := R) source target N P T H) passes + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalWideStep.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalWideStep.lean new file mode 100644 index 0000000000000000000000000000000000000000..16dabf54c32c70435e8af0ed483395b0a9c91be5 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalWideStep.lean @@ -0,0 +1,108 @@ +import OAI.Combinatorics.EditApproximation.Geometry.GroupInputDependence + +namespace OAI + +/-! One concrete refinement entry, using direct local representative and +cell loops. Band data and previously gathered child tables are arguments; +no complete current-index child table is enumerated. -/ + +namespace EditApproximation + +def rationalLocalWideStep {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (N P F exponent Q : ℕ) (tau a delta : ℚ) + (parentInitial : TargetInterval target.length → ℚ) + (childMass childInitial old current : Fin M → TargetInterval target.length → ℚ) + (draw : CellGroupDraws M F Q) (online : List (PhysicalRationalAction M target.length)) + (q : TargetInterval target.length) : ℚ := + let fallback := rationalBellman parentInitial (fun q r => targetEndpointDistance q r) (128 * F) + (rationalActualWideActions parent (localRefinementRepresentatives N P F a parentInitial q) P) + (fun is => old is.1 is.2) q + let groups := localCellGroupActions source target parent N P F exponent Q tau a parentInitial + childMass childInitial current draw q + let cone := rationalMinimum fallback + (groups.map (rationalActionValue (fun q r => targetEndpointDistance q r) (128 * F) + (fun is => current is.1 is.2) q)) + rationalRefinementUpdate delta cone + (rationalOnlineMinimum (online.map + (rationalActionValue (fun q r => targetEndpointDistance q r) (128 * F) + (fun is => current is.1 is.2) q))) + +theorem rationalLocalWideStep_eq {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (N P F exponent Q : ℕ) (tau a delta : ℚ) + (parentInitial : TargetInterval target.length → ℚ) + (childMass childInitial old current : Fin M → TargetInterval target.length → ℚ) + (draw : CellGroupDraws M F Q) (online : List (PhysicalRationalAction M target.length)) + (q : TargetInterval target.length) (ha : 1 ≤ a) (hF : 1 ≤ F) + (hinitial : 0 ≤ parentInitial q) (hold : ∀ i r, 0 ≤ old i r) (hcurrent : ∀ i r, 0 ≤ current i r) + (hspatial : ∀ r, |parentInitial q - parentInitial r| ≤ 32 * F * targetEndpointDistance q r) : + rationalLocalWideStep source target parent N P F exponent Q tau a delta parentInitial + childMass childInitial old current draw online q = + rationalWideStep parent (representativeList N P F a parentInitial) P parentInitial (128 * F) delta + (fun is => old is.1 is.2) (fun is => current is.1 is.2) + (completeCellGroupActions source target parent N P F exponent Q tau a parentInitial + childMass childInitial current draw) online q := by + have hbellman := localRefinementBellman_eq parent N P F a parentInitial + (fun is => old is.1 is.2) q ha hF hinitial (fun is => hold is.1 is.2) hspatial + have hgroups := localCellGroupMinimum_eq source target parent N P F exponent Q tau a parentInitial + childMass childInitial current draw q + (rationalBellman parentInitial (fun q r => targetEndpointDistance q r) (128 * F) + (rationalActualWideActions parent (representativeList N P F a parentInitial) P) + (fun is => old is.1 is.2) q) ha hF (rationalMinimum_le_fallback _ _) hcurrent hspatial + unfold rationalLocalWideStep rationalWideStep rationalWideStepCone + dsimp only + rw [hbellman, hgroups] + +theorem rationalLocalWideStep_bounds {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (N P F exponent Q : ℕ) (tau a delta : ℚ) + (parentInitial : TargetInterval target.length → ℚ) + (childMass childInitial old current : Fin M → TargetInterval target.length → ℚ) + (draw : CellGroupDraws M F Q) (online : List (PhysicalRationalAction M target.length)) + (q : TargetInterval target.length) (hdelta : 0 ≤ delta) (hinitial : 0 ≤ parentInitial q) + (hold : ∀ i r, 0 ≤ old i r) (hcurrent : ∀ i r, 0 ≤ current i r) : + 0 ≤ rationalLocalWideStep source target parent N P F exponent Q tau a delta parentInitial + childMass childInitial old current draw online q ∧ + rationalLocalWideStep source target parent N P F exponent Q tau a delta parentInitial + childMass childInitial old current draw online q ≤ parentInitial q := by + let fallback := rationalBellman parentInitial (fun q r => targetEndpointDistance q r) (128 * F) + (rationalActualWideActions parent (localRefinementRepresentatives N P F a parentInitial q) P) + (fun is => old is.1 is.2) q + let groups := localCellGroupActions source target parent N P F exponent Q tau a parentInitial + childMass childInitial current draw q + let cone := rationalMinimum fallback + (groups.map (rationalActionValue (fun q r => targetEndpointDistance q r) (128 * F) + (fun is => current is.1 is.2) q)) + have hfallback : 0 ≤ fallback := by + apply (le_rationalMinimum_iff _ _ _).2 + refine ⟨hinitial, ?_⟩ + intro v hv + obtain ⟨action, ha, rfl⟩ := List.mem_map.mp hv + exact rationalActionValue_pruned_lower _ _ _ _ action 0 (by positivity) + (rationalActualWideActions_connection_nonneg _ _ _ action ha) (fun i => hold _ _) + have hgroups : ∀ action ∈ groups, action ∈ + rationalActualWideActions parent (representativeList N P F a parentInitial) P := by + intro action ha + exact completeCellGroupActions_wide source target parent N P F exponent Q tau a parentInitial + childMass childInitial current draw action + (localCellGroupActions_subset source target parent N P F exponent Q tau a parentInitial + childMass childInitial current draw q action ha) + have hcone : 0 ≤ cone := by + apply (le_rationalMinimum_iff _ _ _).2 + refine ⟨hfallback, ?_⟩ + intro v hv + obtain ⟨action, ha, rfl⟩ := List.mem_map.mp hv + exact rationalActionValue_pruned_lower _ _ _ _ action 0 (by positivity) + (rationalActualWideActions_connection_nonneg _ _ _ action (hgroups action ha)) (fun i => hcurrent _ _) + have hupper : cone ≤ parentInitial q := (rationalMinimum_le_fallback _ _).trans + (rationalMinimum_le_fallback _ _) + change 0 ≤ rationalRefinementUpdate delta cone _ ∧ rationalRefinementUpdate delta cone _ ≤ parentInitial q + cases hmin : rationalOnlineMinimum (online.map + (rationalActionValue (fun q r => targetEndpointDistance q r) (128 * F) + (fun is => current is.1 is.2) q)) with + | none => exact ⟨hcone, hupper⟩ + | some value => + exact ⟨le_min hcone ((div_nonneg hcone (by linarith)).trans (le_max_left _ _)), + (min_le_left _ _).trans hupper⟩ + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalWorkEnvelope.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalWorkEnvelope.lean new file mode 100644 index 0000000000000000000000000000000000000000..e1aab331fefb288d5c84c1010abc9f282b3f4255 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/LocalWorkEnvelope.lean @@ -0,0 +1,56 @@ +import OAI.Combinatorics.EditApproximation.Geometry.LocalArithmeticAsymptotics +import OAI.Combinatorics.EditApproximation.Coarse.CoarseWorkEnvelope + +namespace OAI + +/-! Multiplying the actual charged dependency-tree work by the concrete +local arithmetic counter preserves the almost-linear exponent. -/ + +namespace EditApproximation + +open Filter +open scoped Topology + +theorem computed_widthWork_subexponential (f : ℕ → ℝ) + (hf : Tendsto (fun N => f N / inputHeight N) atTop (𝓝 0)) + (epsilon : ℝ) (hepsilon : 0 < epsilon) : + ∀ᶠ N in atTop, ∀ n ≤ N, ∀ tree : DependencyExpansion, + tree.Valid ((integerParameters N).M * inputSmallLog N ^ 257) + (inputHeight N ^ (512 * (coarseExponent (inputSmallLog N) + 1))) → + tree.depth = intervalTreeDepth (integerParameters N).M n → + tree.rank ≤ computedDependencyIndexCount N → + (tree.widthWork (integerParameters N).M n : ℝ) * Real.exp (f N) ≤ + (N + 2 : ℝ) ^ (1 + epsilon) := by + filter_upwards [computed_weighted_widthWork_near_linear 0 (epsilon / 2) (by linarith), + subexponential_height_to_input f hf (epsilon / 2) (by linarith)] with N hw hfN + intro n hn tree hv hd hk + have hwidth := hw n hn tree hv hd hk + simp only [pow_zero, mul_one] at hwidth + calc + _ ≤ (N + 2 : ℝ) ^ (1 + epsilon / 2) * (N + 2 : ℝ) ^ (epsilon / 2) := + mul_le_mul hwidth hfN (by positivity) (by positivity) + _ = _ := by + rw [← Real.rpow_add (by positivity : (0 : ℝ) < N + 2)] + congr 1 + ring + +theorem computed_local_arithmetic_widthWork_near_linear (epsilon : ℝ) (hepsilon : 0 < epsilon) : + ∀ᶠ N in atTop, ∀ n ≤ N, ∀ tree : DependencyExpansion, + tree.Valid ((integerParameters N).M * inputSmallLog N ^ 257) + (inputHeight N ^ (512 * (coarseExponent (inputSmallLog N) + 1))) → + tree.depth = intervalTreeDepth (integerParameters N).M n → + tree.rank ≤ computedDependencyIndexCount N → + (tree.widthWork (integerParameters N).M n : ℝ) * + localOptimizerArithmeticBudget (integerParameters N).M (integerParameters N).P + (inputHeight N) ≤ (N + 2 : ℝ) ^ (1 + epsilon) := by + filter_upwards [computed_widthWork_subexponential computedLocalArithmeticExponent + computedLocalArithmeticExponent_tendsto epsilon hepsilon, + eventually_ge_atTop 1, inputHeight_real_tendsto.eventually (eventually_ge_atTop 64)] with N h hN hH + intro n hn tree hv hd hk + exact (mul_le_mul_of_nonneg_left + (computedLocalOptimizer_arithmetic_exp_bound N (by omega) (by exact_mod_cast hH)) + (Nat.cast_nonneg _)).trans (h n hn tree hv hd hk) + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/MemoCodeWork.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/MemoCodeWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..ed0bd92bd8156787086edf53623989dcb5ba9c24 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/MemoCodeWork.lean @@ -0,0 +1,191 @@ +import OAI.Combinatorics.EditApproximation.Refinement.ComputedFamilyMemoCode +import OAI.Combinatorics.EditApproximation.Geometry.ParameterConstruction +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Address generation is charged separately from binary trie traversal. +The loops visit only coordinates in a key, never the ambient key space. -/ +namespace EditApproximation + + + + @[simp] theorem naturalPairWithWork_value (a b : ℕ) : + (naturalPairWithWork a b).1 = Nat.pair a b := by + unfold naturalPairWithWork Nat.pair + split_ifs <;> rfl + + theorem naturalPairWithWork_cost (a b : ℕ) : (naturalPairWithWork a b).2 ≤ 5 := by + unfold naturalPairWithWork + split_ifs <;> dsimp only <;> decide + + + + @[simp] theorem treeLayerCodeWithWork_value (M d : ℕ) (path : TreeLayer M d) : + (treeLayerCodeWithWork M d path).1 = treeLayerCode M d path := by + induction d with + | zero => rfl + | succ d ih => simp only [treeLayerCodeWithWork, treeLayerCode, ih] + + theorem treeLayerCodeWithWork_cost (M d : ℕ) (path : TreeLayer M d) : + (treeLayerCodeWithWork M d path).2 = 3 * d + 1 := by + induction d with + | zero => rfl + | succ d ih => simp only [treeLayerCodeWithWork, ih]; omega + + + + @[simp] theorem physicalNodeCodeWithWork_value {M J : ℕ} (node : PhysicalNode M J) : + (physicalNodeCodeWithWork node).1 = physicalNodeCode node := by + simp only [physicalNodeCodeWithWork, treeLayerCodeWithWork_value, + parameterPowerWithWork_spec, physicalNodeCode] + + theorem physicalNodeCodeWithWork_cost {M J : ℕ} (node : PhysicalNode M J) : + (physicalNodeCodeWithWork node).2 ≤ 5 * J + 5 := by + have h := node.1.isLt + simp only [physicalNodeCodeWithWork, treeLayerCodeWithWork_cost, parameterPowerWithWork_spec] + omega + + + + @[simp] theorem physicalEntryCodeWithWork_value {M J n : ℕ} (entry : PhysicalEntry M J n) : + (physicalEntryCodeWithWork entry).1 = physicalEntryCode entry := by + simp only [physicalEntryCodeWithWork, physicalNodeCodeWithWork_value, + physicalEntryCode, childInputCode, Fin.val_zero, zero_add, one_mul, pow_two] + + theorem physicalEntryCodeWithWork_cost {M J n : ℕ} (entry : PhysicalEntry M J n) : + (physicalEntryCodeWithWork entry).2 ≤ 5 * J + 13 := by + have h := physicalNodeCodeWithWork_cost entry.1 + change (physicalNodeCodeWithWork entry.1).2 + 8 ≤ _ + omega + + + + @[simp] theorem physicalTableCodeWithWork_value {M J n : ℕ} (copies T S : ℕ) + (request : PhysicalTableRequest M J n) : + (physicalTableCodeWithWork copies T S request).1 = PhysicalTableRequest.code copies T S request := by + simp only [physicalTableCodeWithWork, physicalEntryCodeWithWork_value, + parameterPowerWithWork_spec, PhysicalTableRequest.code, PhysicalTableRequest.entryCapacity, pow_two] + + theorem physicalTableCodeWithWork_cost {M J n : ℕ} (copies T S : ℕ) + (request : PhysicalTableRequest M J n) : + (physicalTableCodeWithWork copies T S request).2 ≤ 7 * J + 29 := by + have he := physicalEntryCodeWithWork_cost (request.node, request.state) + simp only [physicalTableCodeWithWork, parameterPowerWithWork_spec] + omega + + + + @[simp] theorem chargedPhysicalCodeWithWork_value {M J n passes copies T S : ℕ} + (request : ChargedPhysicalRequest M J n passes copies T S) : + (chargedPhysicalCodeWithWork request).1 = request.code := by + cases request <;> simp only [chargedPhysicalCodeWithWork, ChargedPhysicalRequest.code, + physicalEntryCodeWithWork_value, physicalTableCodeWithWork_value] + + theorem chargedPhysicalCodeWithWork_cost {M J n passes copies T S : ℕ} + (request : ChargedPhysicalRequest M J n passes copies T S) : + (chargedPhysicalCodeWithWork request).2 ≤ 7 * J + 32 := by + cases request with + | inl entry => have h := physicalEntryCodeWithWork_cost entry + change (physicalEntryCodeWithWork entry).2 + 2 ≤ _ + omega + | inr request => have h := physicalTableCodeWithWork_cost copies T S request.val + change (physicalTableCodeWithWork copies T S request.val).2 + 3 ≤ _ + omega + + + + @[simp] theorem physicalScalarCodeWithWork_value {M J N n exponent F Q R B : ℕ} + (key : PhysicalScalarKey M J N n exponent F Q R B) : + (physicalScalarCodeWithWork key).1 = physicalScalarCode key := by + rcases key with ⟨online | group, index⟩ <;> + simp only [physicalScalarCodeWithWork, naturalPairWithWork_value, + physicalEntryCodeWithWork_value, physicalNodeCodeWithWork_value, physicalScalarCode] + + theorem physicalScalarCodeWithWork_cost {M J N n exponent F Q R B : ℕ} + (key : PhysicalScalarKey M J N n exponent F Q R B) : + (physicalScalarCodeWithWork key).2 ≤ 5 * J + 40 := by + rcases key with ⟨online | group, index⟩ + · have hn := physicalEntryCodeWithWork_cost (online.1.1.val, online.1.2.2) + have ha := naturalPairWithWork_cost online.2.val.val index.val + have hb := naturalPairWithWork_cost online.1.2.1.val + (naturalPairWithWork online.2.val.val index.val).1 + have hc := naturalPairWithWork_cost (physicalEntryCodeWithWork (online.1.1.val, online.1.2.2)).1 + (naturalPairWithWork online.1.2.1.val (naturalPairWithWork online.2.val.val index.val).1).1 + dsimp only [physicalScalarCodeWithWork] + omega + · have hn := physicalNodeCodeWithWork_cost group.1.val + have ha := naturalPairWithWork_cost index.2.1.val index.2.2.val + have hb := naturalPairWithWork_cost index.1.val (naturalPairWithWork index.2.1.val index.2.2.val).1 + have hc := naturalPairWithWork_cost group.2.2.2.val + (naturalPairWithWork index.1.val (naturalPairWithWork index.2.1.val index.2.2.val).1).1 + have hd := naturalPairWithWork_cost group.2.2.1.val + (naturalPairWithWork group.2.2.2.val + (naturalPairWithWork index.1.val (naturalPairWithWork index.2.1.val index.2.2.val).1).1).1 + have he := naturalPairWithWork_cost group.2.1.val + (naturalPairWithWork group.2.2.1.val + (naturalPairWithWork group.2.2.2.val + (naturalPairWithWork index.1.val (naturalPairWithWork index.2.1.val index.2.2.val).1).1).1).1 + have hf := naturalPairWithWork_cost (physicalNodeCodeWithWork group.1.val).1 + (naturalPairWithWork group.2.1.val + (naturalPairWithWork group.2.2.1.val + (naturalPairWithWork group.2.2.2.val + (naturalPairWithWork index.1.val (naturalPairWithWork index.2.1.val index.2.2.val).1).1).1).1).1 + dsimp only [physicalScalarCodeWithWork] + omega + +section Family +variable {α : Type*} {M J R : ℕ} (target : List α) (N P F exponent H Q passes copies : ℕ) + + + + @[simp] theorem physicalFamilyCodeWithWork_value + (key : PhysicalFamilyScalarKey (M := M) (J := J) (R := R) + target N P F exponent H Q passes copies) : + (physicalFamilyCodeWithWork target N P F exponent H Q passes copies key).1 = + physicalFamilyCode target N P F exponent H Q passes copies key := by + simp only [physicalFamilyCodeWithWork, physicalScalarCodeWithWork_value, + naturalPairWithWork_value, physicalFamilyCode] + + theorem physicalFamilyCodeWithWork_cost + (key : PhysicalFamilyScalarKey (M := M) (J := J) (R := R) + target N P F exponent H Q passes copies) : + (physicalFamilyCodeWithWork target N P F exponent H Q passes copies key).2 ≤ 5 * J + 52 := by + have hs := physicalScalarCodeWithWork_cost key.2.2 + have hc := naturalPairWithWork_cost key.2.1.val (physicalScalarCodeWithWork key.2.2).1 + have hp := naturalPairWithWork_cost key.1.val + (naturalPairWithWork key.2.1.val (physicalScalarCodeWithWork key.2.2).1).1 + dsimp only [physicalFamilyCodeWithWork] + omega +end Family + + + + @[simp] theorem computedFamilyMemoCodeWithWork_value (source target : List ℕ) (N R : ℕ) + (key : Sum (ComputedFamilyScalarKey source target N R) (ComputedFamilyTableKey source target N)) : + (computedFamilyMemoCodeWithWork source target N R key).1 = computedFamilyMemoCode source target N R key := by + cases key <;> simp only [computedFamilyMemoCodeWithWork, computedFamilyMemoCode, + SourceRanked.keyCode, physicalFamilyCodeWithWork_value, chargedPhysicalCodeWithWork_value] + + theorem computedFamilyMemoCodeWithWork_cost (source target : List ℕ) (N R : ℕ) + (key : Sum (ComputedFamilyScalarKey source target N R) (ComputedFamilyTableKey source target N)) : + (computedFamilyMemoCodeWithWork source target N R key).2 ≤ + 7 * intervalTreeDepth (integerParameters N).M source.length + 60 := by + cases key with + | inl key => + have h := physicalFamilyCodeWithWork_cost target N (integerParameters N).P (inputSmallLog N) + (40 * smallLogExponent N) (inputHeight N) (inputSmallLog N ^ 80) + (computedSeedPassCount N) (inputHeight N ^ 2) key + change (physicalFamilyCodeWithWork target N (integerParameters N).P (inputSmallLog N) + (40 * smallLogExponent N) (inputHeight N) (inputSmallLog N ^ 80) + (computedSeedPassCount N) (inputHeight N ^ 2) key).2 + 2 ≤ _ + omega + | inr key => + have h := chargedPhysicalCodeWithWork_cost key + change (chargedPhysicalCodeWithWork key).2 + 3 ≤ _ + omega + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/MemoizedOracle.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/MemoizedOracle.lean new file mode 100644 index 0000000000000000000000000000000000000000..6d56817dc6ecfbf05c97a244bf99bf77e15143da --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/MemoizedOracle.lean @@ -0,0 +1,198 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryMemo + +namespace OAI + +/-! Persistent dictionary requests. A fresh oracle is called only on a +cache miss; subsequent requests preserve and return the stored answer. -/ + +namespace EditApproximation + +structure MemoRequestResult where + value : ℚ + memory : BinaryMemo ℚ + fresh : Bool + dictionaryVisits : ℕ + +section Requests + +variable {ι : Type*} (bits : ℕ) (encode : ι → ℕ) (oracle : ι → ℚ) + +def memoRequest (memory : BinaryMemo ℚ) (key : ι) : MemoRequestResult := + let found := memory.lookupCosted (binaryMemoKey bits (encode key)) + match found.1 with + | some value => ⟨value, memory, false, found.2⟩ + | none => + let value := oracle key + let stored := memory.insertCosted (binaryMemoKey bits (encode key)) value + ⟨value, stored.1, true, found.2 + stored.2⟩ + +theorem memoRequest_lookup (memory : BinaryMemo ℚ) (key : ι) : + (memoRequest bits encode oracle memory key).memory.lookup (binaryMemoKey bits (encode key)) = + some (memoRequest bits encode oracle memory key).value := by + simp only [memoRequest, BinaryMemo.lookupCosted_spec] + split <;> simp_all only [BinaryMemo.insertCosted_spec, BinaryMemo.lookup_insert_same] + +theorem memoRequest_preserves (memory : BinaryMemo ℚ) (key other : ι) (value : ℚ) + (hold : memory.lookup (binaryMemoKey bits (encode other)) = some value) : + (memoRequest bits encode oracle memory key).memory.lookup (binaryMemoKey bits (encode other)) = some value := by + simp only [memoRequest, BinaryMemo.lookupCosted_spec] + split + · exact hold + · rename_i hnone + simp only [BinaryMemo.insertCosted_spec] + apply (BinaryMemo.lookup_insert_other _ _ _ _ ?_).trans hold + intro heq + rw [heq, hnone] at hold + cases hold + +theorem memoRequest_fresh_iff (memory : BinaryMemo ℚ) (key : ι) : + (memoRequest bits encode oracle memory key).fresh = true ↔ + memory.lookup (binaryMemoKey bits (encode key)) = none := by + simp only [memoRequest, BinaryMemo.lookupCosted_spec] + split <;> simp_all + +theorem memoRequest_visits (memory : BinaryMemo ℚ) (key : ι) : + (memoRequest bits encode oracle memory key).dictionaryVisits ≤ 2 * (bits + 1) := by + simp only [memoRequest, BinaryMemo.lookupCosted_spec] + split + · simp only [binaryMemoKey_length] + omega + · simp only [BinaryMemo.insertCosted_spec, binaryMemoKey_length] + omega + +def memoSound (memory : BinaryMemo ℚ) : Prop := + ∀ key value, memory.lookup (binaryMemoKey bits (encode key)) = some value → value = oracle key + +theorem memoRequest_sound (hinjective : Function.Injective encode) + (hbounded : ∀ key, encode key < 2 ^ bits) (memory : BinaryMemo ℚ) + (hsound : memoSound bits encode oracle memory) (key : ι) : + (memoRequest bits encode oracle memory key).value = oracle key ∧ + memoSound bits encode oracle (memoRequest bits encode oracle memory key).memory := by + simp only [memoRequest, BinaryMemo.lookupCosted_spec] + split + · rename_i value hvalue + exact ⟨hsound key value hvalue, hsound⟩ + · simp only [BinaryMemo.insertCosted_spec] + refine ⟨True.intro, ?_⟩ + intro other value hvalue + rw [binaryMemo_lookup_insert _ bits (encode key) (encode other) + (hbounded key) (hbounded other)] at hvalue + split_ifs at hvalue with heq + · have heqkey := hinjective heq + cases heqkey + exact Option.some.inj hvalue.symm + · exact hsound other value hvalue + +structure MemoBatchResult (ι : Type*) where + values : List ℚ + memory : BinaryMemo ℚ + freshKeys : List ι + dictionaryVisits : ℕ + +def memoRequests (memory : BinaryMemo ℚ) : List ι → MemoBatchResult ι + | [] => ⟨[], memory, [], 0⟩ + | key :: rest => + let first := memoRequest bits encode oracle memory key + let remaining := memoRequests first.memory rest + ⟨first.value :: remaining.values, remaining.memory, + (if first.fresh then [key] else []) ++ remaining.freshKeys, + first.dictionaryVisits + remaining.dictionaryVisits⟩ + +theorem memoRequests_preserves (memory : BinaryMemo ℚ) (keys : List ι) (key : ι) (value : ℚ) + (hold : memory.lookup (binaryMemoKey bits (encode key)) = some value) : + (memoRequests bits encode oracle memory keys).memory.lookup (binaryMemoKey bits (encode key)) = some value := by + induction keys generalizing memory with + | nil => exact hold + | cons first rest ih => + exact ih _ (memoRequest_preserves bits encode oracle memory first key value hold) + +theorem memoRequests_fresh_absent (memory : BinaryMemo ℚ) (keys : List ι) (key : ι) + (hfresh : key ∈ (memoRequests bits encode oracle memory keys).freshKeys) : + memory.lookup (binaryMemoKey bits (encode key)) = none := by + induction keys generalizing memory with + | nil => cases hfresh + | cons first rest ih => + simp only [memoRequests, List.mem_append] at hfresh + rcases hfresh with hfirst | hrest + · split_ifs at hfirst with hf + · have heq : key = first := by simpa only [List.mem_singleton] using hfirst + subst key + exact (memoRequest_fresh_iff bits encode oracle memory first).1 hf + · cases hfirst + · have hafter := ih _ hrest + cases hbefore : memory.lookup (binaryMemoKey bits (encode key)) with + | none => rfl + | some value => + have hkeep := memoRequest_preserves bits encode oracle memory first key value hbefore + rw [hafter] at hkeep + cases hkeep + +theorem memoRequests_fresh_nodup [DecidableEq ι] (memory : BinaryMemo ℚ) (keys : List ι) : + (memoRequests bits encode oracle memory keys).freshKeys.Nodup := by + induction keys generalizing memory with + | nil => exact List.nodup_nil + | cons first rest ih => + simp only [memoRequests] + split_ifs with hf + · rw [List.singleton_append, List.nodup_cons] + refine ⟨?_, ih _⟩ + intro hmem + have hnone := memoRequests_fresh_absent bits encode oracle _ rest first hmem + have hsome := memoRequest_lookup bits encode oracle memory first + rw [hnone] at hsome + cases hsome + · exact ih _ + +theorem memoRequests_fresh_subset (memory : BinaryMemo ℚ) (keys : List ι) : + ∀ key ∈ (memoRequests bits encode oracle memory keys).freshKeys, key ∈ keys := by + induction keys generalizing memory with + | nil => intro key hmem; cases hmem + | cons first rest ih => + intro key hmem + simp only [memoRequests, List.mem_append] at hmem + rcases hmem with hfirst | hrest + · split_ifs at hfirst + · exact List.mem_cons.mpr (Or.inl (List.mem_singleton.mp hfirst)) + · cases hfirst + · exact List.mem_cons_of_mem first (ih _ key hrest) + +theorem memoRequests_fresh_count [DecidableEq ι] (memory : BinaryMemo ℚ) (keys : List ι) : + (memoRequests bits encode oracle memory keys).freshKeys.length ≤ keys.toFinset.card := by + rw [← List.toFinset_card_of_nodup (memoRequests_fresh_nodup bits encode oracle memory keys)] + apply Finset.card_le_card + intro key hkey + exact List.mem_toFinset.mpr (memoRequests_fresh_subset bits encode oracle memory keys key + (List.mem_toFinset.mp hkey)) + +theorem memoRequests_visits (memory : BinaryMemo ℚ) (keys : List ι) : + (memoRequests bits encode oracle memory keys).dictionaryVisits ≤ keys.length * (2 * (bits + 1)) := by + induction keys generalizing memory with + | nil => simp only [memoRequests, List.length_nil, Nat.zero_mul, le_refl] + | cons first rest ih => + have hfirst := memoRequest_visits bits encode oracle memory first + have hrest := ih (memoRequest bits encode oracle memory first).memory + simpa only [memoRequests, List.length_cons, Nat.add_mul, Nat.one_mul, Nat.add_comm] using + Nat.add_le_add hfirst hrest + +theorem memoSound_empty : memoSound bits encode oracle .empty := by + intro key value hvalue + rw [BinaryMemo.lookup_empty] at hvalue + cases hvalue + +theorem memoRequests_sound (hinjective : Function.Injective encode) + (hbounded : ∀ key, encode key < 2 ^ bits) (memory : BinaryMemo ℚ) + (hsound : memoSound bits encode oracle memory) (keys : List ι) : + (memoRequests bits encode oracle memory keys).values = keys.map oracle ∧ + memoSound bits encode oracle (memoRequests bits encode oracle memory keys).memory := by + induction keys generalizing memory with + | nil => exact ⟨rfl, hsound⟩ + | cons first rest ih => + have hf := memoRequest_sound bits encode oracle hinjective hbounded memory hsound first + have hr := ih _ hf.2 + exact ⟨congrArg₂ List.cons hf.1 hr.1, hr.2⟩ + +end Requests + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/NodeRegret.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/NodeRegret.lean new file mode 100644 index 0000000000000000000000000000000000000000..cd62983485c05b5f71ee6bae238dad00ceb2c99e --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/NodeRegret.lean @@ -0,0 +1,114 @@ +import OAI.Combinatorics.EditApproximation.Geometry.FirstCrossing + +namespace OAI + +/-! +# Clipped regret of the actual refinement update + +This is the deterministic first-crossing transfer in Proposition 7.3. +The hypothesis about group estimates is a pointwise estimate on their +success event; their probability is handled separately. No independence +between a sampled action and that success event is required. +-/ + +namespace EditApproximation + +open Finset + +noncomputable def bandActionCost {β σ : Type*} [Fintype β] + (charge : ℝ) (table : ℕ → β × σ → ℝ) (t : ℕ) (action : β → σ) : ℝ := + charge + ∑ child, table t (child, action child) + +noncomputable def sampledPrefixRegret {β σ : Type*} [Fintype β] + (charge κ : ℝ) (table : ℕ → β × σ → ℝ) + (comparisonClipped : ℕ → ℝ) (sample : ℕ → β → σ) (t : ℕ) : ℝ := + bandActionCost charge table (t + 1) (sample t) + + κ * (bandActionCost charge table t (sample t) - + bandActionCost charge table (t + 1) (sample t)) - charge - comparisonClipped (t + 1) + +theorem refinement_firstCrossing_regret {β σ : Type*} [Fintype β] + (band : Finset (β → σ)) (S : ℕ) + (table : ℕ → β × σ → ℝ) (comparisonClipped : ℕ → ℝ) + (sample : ℕ → β → σ) (cone online : ℕ → ℝ) (failure : ℕ → Bool) + (charge c b F δ κ error : ℝ) + (hc : 0 ≤ c) (hF : 1 ≤ F) (hδ : 0 < δ) (hκ : 0 ≤ κ) (hb : b ≤ c) + (herror : error * b ≤ κ * δ * b) (herrorCross : error * b ≤ δ * c) + (hmono : ∀ action ∈ band, Antitone (fun t => bandActionCost charge table t action)) + (hsample : ∀ t < S, sample t ∈ band) + (hcomparison : ∀ t ≤ S, c ≤ charge + comparisonClipped t) + (honline : ∀ t < S, online t ≤ bandActionCost charge table (t + 1) (sample t)) + (hbellman : ∀ t < S, ∀ action ∈ band, cone t ≤ bandActionCost charge table t action) + (hgroup : ∀ t < S, failure t = false → ∀ action ∈ band, + cone t ≤ (1 + δ) * bandActionCost charge table (t + 1) action + error * b) + (hupper : ∀ t < S, max c (refinementUpdate δ (cone t) (online t)) ≤ 2 * F * c) : + let crossing := firstCrossing band S (fun t => bandActionCost charge table (t + 1)) c + (∑ t ∈ range S, + (max c (refinementUpdate δ (cone t) (online t)) - charge - comparisonClipped (t + 1))) ≤ + (∑ t ∈ range crossing, sampledPrefixRegret charge κ table comparisonClipped sample t) + + 2 * δ * c + 2 * F * c * ∑ t ∈ range S, (if failure t then (1 : ℝ) else 0) := by + let actionCost := fun t => bandActionCost charge table (t + 1) + let crossing := firstCrossing band S actionCost c + let regret := fun t => max c (refinementUpdate δ (cone t) (online t)) - + charge - comparisonClipped (t + 1) + have hcrossing : crossing ≤ S := firstCrossing_le band S actionCost c + change (∑ t ∈ range S, regret t) ≤ + (∑ t ∈ range crossing, sampledPrefixRegret charge κ table comparisonClipped sample t) + + 2 * δ * c + 2 * F * c * ∑ t ∈ range S, (if failure t then (1 : ℝ) else 0) + apply firstCrossing_sum_bound S crossing regret + (sampledPrefixRegret charge κ table comparisonClipped sample) + (fun t => if failure t then (1 : ℝ) else 0) (2 * δ * c) (2 * F * c) + hcrossing (by positivity) (by positivity) + · intro t _ + split_ifs <;> norm_num + · intro t ht + have htS : t < S := ht.trans_le hcrossing + have ha := hsample t htS + have hcost : c ≤ bandActionCost charge table (t + 1) (sample t) := + before_firstCrossing band S actionCost c ht ha + have hdecrease := hmono (sample t) ha (Nat.le_succ t) + have hclip : max c (refinementUpdate δ (cone t) (online t)) ≤ + bandActionCost charge table (t + 1) (sample t) + + κ * (bandActionCost charge table t (sample t) - + bandActionCost charge table (t + 1) (sample t)) + + 2 * F * c * (if failure t then (1 : ℝ) else 0) := by + cases hf : failure t with + | false => + simp only [Bool.false_eq_true, ite_false, mul_zero, add_zero] + exact refinementUpdate_prefix hδ hκ hc hb hcost hdecrease + (honline t htS) (hbellman t htS (sample t) ha) + (hgroup t htS hf (sample t) ha) herror + | true => + simp only [ite_true, mul_one] + have hdec0 := mul_nonneg hκ (sub_nonneg.mpr hdecrease) + linarith [hupper t htS] + dsimp only [regret, sampledPrefixRegret] + linarith + · intro ht + obtain ⟨action, ha, hcross⟩ := at_firstCrossing band S actionCost c ht + have hclip : max c (refinementUpdate δ (cone crossing) (online crossing)) ≤ + c + 2 * δ * c + 2 * F * c * (if failure crossing then (1 : ℝ) else 0) := by + cases hf : failure crossing with + | false => + simp only [Bool.false_eq_true, ite_false, mul_zero, add_zero] + apply refinementUpdate_crossing hδ.le hc hcross + have hestimate := hgroup crossing ht hf action ha + linarith + | true => + simp only [ite_true, mul_one] + have hslack := mul_nonneg hδ.le hc + linarith [hupper crossing ht] + dsimp only [regret] + linarith [hcomparison (crossing + 1) (by omega)] + · intro t ht hafter + obtain ⟨action, ha, hcross⟩ := at_firstCrossing band S actionCost c (hafter.trans ht) + have hcost : bandActionCost charge table t action < c := + (hmono action ha (show crossing + 1 ≤ t by omega)).trans_lt hcross + have hparent : refinementUpdate δ (cone t) (online t) ≤ c := + (min_le_left _ _).trans ((hbellman t ht action ha).trans hcost.le) + dsimp only [regret] + rw [max_eq_left hparent] + linarith [hcomparison (t + 1) (by omega)] + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/OccurrenceIndex.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/OccurrenceIndex.lean new file mode 100644 index 0000000000000000000000000000000000000000..fc2636a68785aa02f29ffbdc8513c9fbf9943cbc --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/OccurrenceIndex.lean @@ -0,0 +1,155 @@ +import OAI.Combinatorics.EditApproximation.Geometry.OccurrencePrefix +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalInitial +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! A symbol dictionary of cached position tries. The target is enumerated +once; interval occurrence queries use two logarithmic prefix counts. -/ + +namespace EditApproximation + +def occurrencePrefixCount : List (ℕ × ℕ) → ℕ → ℕ → ℕ + | [], _, _ => 0 + | e :: es, a, t => occurrencePrefixCount es a t + if e.1 = a ∧ e.2 < t then 1 else 0 + +def occurrenceRangeCount : List (ℕ × ℕ) → ℕ → ℕ → ℕ → ℕ + | [], _, _, _ => 0 + | e :: es, a, lo, hi => occurrenceRangeCount es a lo hi + + if e.1 = a ∧ lo ≤ e.2 ∧ e.2 < hi then 1 else 0 + +theorem occurrencePrefixCount_sub (entries : List (ℕ × ℕ)) (a lo hi : ℕ) (h : lo ≤ hi) : + occurrencePrefixCount entries a hi - occurrencePrefixCount entries a lo = + occurrenceRangeCount entries a lo hi := by + have hall : occurrencePrefixCount entries a lo + occurrenceRangeCount entries a lo hi = + occurrencePrefixCount entries a hi := by + induction entries with + | nil => rfl + | cons e es ih => + simp only [occurrencePrefixCount, occurrenceRangeCount] + by_cases ha : e.1 = a <;> by_cases hlo : e.2 < lo <;> + by_cases hhi : e.2 < hi <;> by_cases hge : lo ≤ e.2 <;> + simp only [ha, hlo, hhi, hge, true_and, false_and, and_self, ite_true, ite_false] <;> omega + omega + +theorem occurrenceRangeCount_pos (entries : List (ℕ × ℕ)) (a lo hi : ℕ) : + 0 < occurrenceRangeCount entries a lo hi ↔ + ∃ e ∈ entries, e.1 = a ∧ lo ≤ e.2 ∧ e.2 < hi := by + induction entries with + | nil => simp only [occurrenceRangeCount, lt_self_iff_false, List.not_mem_nil, false_and, exists_false] + | cons e es ih => + rw [occurrenceRangeCount] + by_cases he : e.1 = a ∧ lo ≤ e.2 ∧ e.2 < hi + · rw [ite_eq_left he] + constructor + · intro _ + exact ⟨e, List.mem_cons_self, he⟩ + · intro _ + omega + · rw [ite_eq_right he, add_zero, ih] + constructor + · rintro ⟨f, hf, hp⟩ + exact ⟨f, List.mem_cons_of_mem e hf, hp⟩ + · rintro ⟨f, hf, hp⟩ + rcases List.mem_cons.mp hf with hfe | hf + · subst f + exact False.elim (he hp) + · exact ⟨f, hf, hp⟩ + + + +def occurrencePrefix (table : BinaryMemo PositionCounts) (symbolBits positionBits a t : ℕ) : ℕ := + ((table.lookup (binaryMemoKey symbolBits a)).getD .empty).prefixCount positionBits t + +theorem occurrenceBuild_prefix (symbolBits positionBits : ℕ) (entries : List (ℕ × ℕ)) + (hentries : ∀ e ∈ entries, e.1 < 2 ^ symbolBits ∧ e.2 < 2 ^ positionBits) + (a t : ℕ) (ha : a < 2 ^ symbolBits) : + occurrencePrefix (occurrenceBuild symbolBits positionBits entries) symbolBits positionBits a t = + occurrencePrefixCount entries a t := by + induction entries with + | nil => simp only [occurrenceBuild, occurrencePrefix, BinaryMemo.lookup_empty, + Option.getD_none, PositionCounts.prefix_empty, occurrencePrefixCount] + | cons e es ih => + have he := hentries e (by simp only [List.mem_cons, true_or]) + have hes : ∀ e ∈ es, e.1 < 2 ^ symbolBits ∧ e.2 < 2 ^ positionBits := + fun e hm => hentries e (List.mem_cons_of_mem _ hm) + simp only [occurrenceBuild, occurrencePrefix] + rw [binaryMemo_lookup_insert _ symbolBits e.1 a he.1 ha] + by_cases heq : a = e.1 + · subst a + simp only [ite_true, Option.getD_some, PositionCounts.prefix_add _ _ _ _ he.2] + have hi := ih hes + unfold occurrencePrefix at hi + rw [hi] + simp only [occurrencePrefixCount, true_and] + · simp only [heq, ite_false] + have hi := ih hes + unfold occurrencePrefix at hi + rw [hi] + simp only [occurrencePrefixCount, Ne.symm heq, false_and, ite_false, add_zero] + +def occurrenceQuery (table : BinaryMemo PositionCounts) (symbolBits positionBits a lo hi : ℕ) : Bool := + decide (occurrencePrefix table symbolBits positionBits a lo < + occurrencePrefix table symbolBits positionBits a hi) + +theorem occurrenceQuery_build (symbolBits positionBits : ℕ) (entries : List (ℕ × ℕ)) + (hentries : ∀ e ∈ entries, e.1 < 2 ^ symbolBits ∧ e.2 < 2 ^ positionBits) + (a lo hi : ℕ) (ha : a < 2 ^ symbolBits) (h : lo ≤ hi) : + occurrenceQuery (occurrenceBuild symbolBits positionBits entries) symbolBits positionBits a lo hi = true ↔ + ∃ e ∈ entries, e.1 = a ∧ lo ≤ e.2 ∧ e.2 < hi := by + rw [occurrenceQuery, decide_eq_true_eq, occurrenceBuild_prefix _ _ _ hentries _ _ ha, + occurrenceBuild_prefix _ _ _ hentries _ _ ha] + rw [← occurrenceRangeCount_pos, ← occurrencePrefixCount_sub entries a lo hi h] + omega + + + +theorem occurrenceBuildWithWork_spec (symbolBits positionBits : ℕ) (entries : List (ℕ × ℕ)) : + occurrenceBuildWithWork symbolBits positionBits entries = + (occurrenceBuild symbolBits positionBits entries, + entries.length * (3 * symbolBits + 2 * positionBits + 5)) := by + induction entries with + | nil => simp only [occurrenceBuildWithWork, occurrenceBuild, List.length_nil, zero_mul] + | cons e es ih => + simp only [occurrenceBuildWithWork, ih, BinaryMemo.lookupCosted_spec, + PositionCounts.addWithWork_spec, BinaryMemo.insertCosted_spec, + binaryMemoKey_length, occurrenceBuild, List.length_cons] + congr 1 + ring + + + +theorem occurrenceQueryWithWork_spec (table : BinaryMemo PositionCounts) + (symbolBits positionBits a lo hi : ℕ) : + occurrenceQueryWithWork table symbolBits positionBits a lo hi = + (occurrenceQuery table symbolBits positionBits a lo hi, 2 * symbolBits + 4 * positionBits + 5) := by + simp only [occurrenceQueryWithWork, BinaryMemo.lookupCosted_spec, + PositionCounts.prefixWithWork_spec, binaryMemoKey_length, occurrenceQuery, occurrencePrefix] + congr 1 + ring + +/-- Converting the input list to its indexed entries is done only during +preprocessing. Subsequent queries use endpoints and the dictionary. -/ +theorem occurrenceQuery_target (symbolBits positionBits : ℕ) (target : List ℕ) + (hsymbol : ∀ a ∈ target, a < 2 ^ symbolBits) (hposition : target.length ≤ 2 ^ positionBits) + (a lo hi : ℕ) (ha : a < 2 ^ symbolBits) (hlo : lo ≤ hi) (hhi : hi ≤ target.length) : + occurrenceQuery (occurrenceBuild symbolBits positionBits target.zipIdx) + symbolBits positionBits a lo hi = true ↔ a ∈ substring target lo hi := by + have hentries : ∀ e ∈ target.zipIdx, e.1 < 2 ^ symbolBits ∧ e.2 < 2 ^ positionBits := by + intro e he + exact ⟨hsymbol e.1 (List.fst_mem_of_mem_zipIdx he), + (by have h := List.snd_lt_of_mem_zipIdx he; simp only [Nat.add_zero] at h; omega)⟩ + rw [occurrenceQuery_build _ _ _ hentries _ _ _ ha hlo, List.exists_mem_zipIdx'] + simp only [substring, List.mem_drop_iff_getElem, List.length_take, Nat.min_eq_left hhi] + constructor + · rintro ⟨i, hi', heq, hil, hih⟩ + refine ⟨i - lo, by omega, ?_⟩ + simpa only [Nat.add_sub_of_le hil, List.getElem_take] using heq + · rintro ⟨j, hj, heq⟩ + refine ⟨lo + j, by omega, ?_, by omega, by omega⟩ + simpa only [List.getElem_take] using heq + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/OccurrenceLeaf.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/OccurrenceLeaf.lean new file mode 100644 index 0000000000000000000000000000000000000000..831266deaf0038ae57357c31234edefb7693b883 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/OccurrenceLeaf.lean @@ -0,0 +1,74 @@ +import OAI.Combinatorics.EditApproximation.Geometry.OccurrenceIndex +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Constant-size leaf descriptors use the preprocessed occurrence index. +The target interval is represented by endpoints; it is never copied or +scanned while evaluating a singleton leaf. -/ + +namespace EditApproximation + +def indexedSingletonCost (table : BinaryMemo PositionCounts) + (symbolBits positionBits a lo hi : ℕ) : ℕ := + if lo = hi then 1 else hi - lo - + if occurrenceQuery table symbolBits positionBits a lo hi = true then 1 else 0 + +theorem indexedSingletonCost_eq (symbolBits positionBits : ℕ) (target : List ℕ) + (hsymbol : ∀ a ∈ target, a < 2 ^ symbolBits) (hposition : target.length ≤ 2 ^ positionBits) + (a lo hi : ℕ) (ha : a < 2 ^ symbolBits) (hlo : lo ≤ hi) (hhi : hi ≤ target.length) : + indexedSingletonCost (occurrenceBuild symbolBits positionBits target.zipIdx) + symbolBits positionBits a lo hi = singletonCost a (substring target lo hi) := by + have hlength := substring_length target lo hi hhi + have hzero : substring target lo hi = [] ↔ lo = hi := by + rw [← List.length_eq_zero_iff, hlength] + omega + have hocc := occurrenceQuery_target symbolBits positionBits target hsymbol hposition a lo hi ha hlo hhi + simp only [indexedSingletonCost, singletonCost, hzero, occurrenceDeficit, hlength, hocc] + + + +theorem indexedSingletonCostWithWork_spec (table : BinaryMemo PositionCounts) + (symbolBits positionBits a lo hi : ℕ) : + (indexedSingletonCostWithWork table symbolBits positionBits a lo hi).1 = + indexedSingletonCost table symbolBits positionBits a lo hi ∧ + (indexedSingletonCostWithWork table symbolBits positionBits a lo hi).2 ≤ + 2 * symbolBits + 4 * positionBits + 9 := by + by_cases h : lo = hi + · simp only [indexedSingletonCostWithWork, indexedSingletonCost, h, ite_true] + exact ⟨True.intro, by omega⟩ + · simp only [indexedSingletonCostWithWork, indexedSingletonCost, h, ite_false] + rw [occurrenceQueryWithWork_spec] + exact ⟨rfl, by omega⟩ + +def indexedLeafCost (table : BinaryMemo PositionCounts) + (symbolBits positionBits : ℕ) (symbol : Option ℕ) (lo hi : ℕ) : ℕ := + match symbol with + | none => hi - lo + | some a => indexedSingletonCost table symbolBits positionBits a lo hi + +theorem indexedLeafCost_eq (symbolBits positionBits : ℕ) (source target : List ℕ) + (hsource : ∀ a ∈ source, a < 2 ^ symbolBits) + (htarget : ∀ a ∈ target, a < 2 ^ symbolBits) (hposition : target.length ≤ 2 ^ positionBits) + (lo hi : ℕ) (hlo : lo ≤ hi) (hhi : hi ≤ target.length) : + indexedLeafCost (occurrenceBuild symbolBits positionBits target.zipIdx) + symbolBits positionBits source.head? lo hi = shortSourceCost source (substring target lo hi) := by + cases source with + | nil => exact (substring_length target lo hi hhi).symm + | cons a rest => + exact indexedSingletonCost_eq symbolBits positionBits target htarget hposition a lo hi + (hsource a (by simp only [List.mem_cons, true_or])) hlo hhi + +theorem indexedLeafCost_exact (symbolBits positionBits : ℕ) (source target : List ℕ) + (hsource : ∀ a ∈ source, a < 2 ^ symbolBits) + (htarget : ∀ a ∈ target, a < 2 ^ symbolBits) (hposition : target.length ≤ 2 ^ positionBits) + (lo hi : ℕ) (hlo : lo ≤ hi) (hhi : hi ≤ target.length) (hleaf : source.length ≤ 1) : + indexedLeafCost (occurrenceBuild symbolBits positionBits target.zipIdx) + symbolBits positionBits source.head? lo hi = EditDistortion.edit source (substring target lo hi) := by + rw [indexedLeafCost_eq symbolBits positionBits source target hsource htarget hposition lo hi hlo hhi] + exact shortSourceCost_eq_edit source _ hleaf + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/OccurrencePrefix.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/OccurrencePrefix.lean new file mode 100644 index 0000000000000000000000000000000000000000..3448fe4dac52cbcdb5d0b2642607f12df242fd2c --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/OccurrencePrefix.lean @@ -0,0 +1,123 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryMemo +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Cached binary position counts. Inserting a position and counting positions +strictly below a boundary both follow one root-to-leaf path. Counts are stored +at internal nodes, so a prefixCount query does not traverse a whole interval. -/ + +namespace EditApproximation + + + +namespace PositionCounts + + + + + + + + + +@[simp] theorem count_add (tree : PositionCounts) (d i : ℕ) : + (tree.add d i).count = tree.count + 1 := by + cases d with + | zero => rfl + | succ d => + simp only [add] + split_ifs <;> rfl + +def prefixCount (tree : PositionCounts) : ℕ → ℕ → ℕ + | 0, t => if t = 0 then 0 else tree.count + | d + 1, t => + if t ≤ 2 ^ d then tree.left.prefixCount d t + else tree.left.count + tree.right.prefixCount d (t - 2 ^ d) + +@[simp] theorem prefix_empty (d t : ℕ) : prefixCount .empty d t = 0 := by + induction d generalizing t with + | zero => simp only [prefixCount, count, ite_self] + | succ d ih => simp only [prefixCount, left, right, count, ih, zero_add, ite_self] + +/-- Adding one stored position changes a prefixCount count by exactly its +membership indicator. This holds for any prior tree, without a balance +or density assumption. -/ +theorem prefix_add (tree : PositionCounts) (d i t : ℕ) (hi : i < 2 ^ d) : + (tree.add d i).prefixCount d t = tree.prefixCount d t + if i < t then 1 else 0 := by + induction d generalizing tree i t with + | zero => + have hi0 : i = 0 := by simpa using hi + subst i + by_cases ht : t = 0 + · subst t; simp only [prefixCount, add, count, lt_self_iff_false, ite_true, ite_false, add_zero] + · have hpos : 0 < t := Nat.pos_of_ne_zero ht + simp only [prefixCount, add, count, ht, hpos, ite_false, ite_true] + | succ d ih => + have hi' : i < 2 ^ d * 2 := by simpa only [pow_succ] using hi + by_cases hip : i < 2 ^ d + · by_cases htp : t ≤ 2 ^ d + · simpa only [add, hip, ite_true, prefixCount, htp, left] using ih tree.left i t hip + · have hit : i < t := by omega + simp only [add, hip, ite_true, prefixCount, htp, ite_false, left, right, count_add, hit] + omega + · have hir : i - 2 ^ d < 2 ^ d := by omega + by_cases htp : t ≤ 2 ^ d + · have hit : ¬ i < t := by omega + simp only [add, hip, ite_false, prefixCount, htp, ite_true, left, hit, add_zero] + · have heq : i - 2 ^ d < t - 2 ^ d ↔ i < t := by omega + simp only [add, hip, ite_false, prefixCount, htp, left, right, ih _ _ _ hir, heq] + omega + + + +theorem addWithWork_spec (tree : PositionCounts) (d i : ℕ) : + tree.addWithWork d i = (tree.add d i, 2 * d + 1) := by + induction d generalizing tree i with + | zero => rfl + | succ d ih => + simp only [addWithWork, add] + split_ifs <;> rw [ih] <;> simp only <;> congr 1 + + + +theorem prefixWithWork_spec (tree : PositionCounts) (d t : ℕ) : + tree.prefixWithWork d t = (tree.prefixCount d t, 2 * d + 1) := by + induction d generalizing tree t with + | zero => rfl + | succ d ih => + simp only [prefixWithWork, prefixCount] + split_ifs <;> rw [ih] <;> simp only <;> congr 1 + +def nodes : PositionCounts → ℕ + | .empty => 0 + | .node _ l r => 1 + l.nodes + r.nodes + +theorem children_nodes (tree : PositionCounts) : + tree.left.nodes + tree.right.nodes ≤ tree.nodes := by + cases tree <;> simp only [left, right, nodes] <;> omega + +theorem add_nodes (tree : PositionCounts) (d i : ℕ) : + (tree.add d i).nodes ≤ tree.nodes + d + 1 := by + induction d generalizing tree i with + | zero => + have h := children_nodes tree + simp only [add, nodes] + omega + | succ d ih => + have h := children_nodes tree + simp only [add] + split_ifs + · have hrec := ih tree.left i + simp only [nodes] + omega + · have hrec := ih tree.right (i - 2 ^ d) + simp only [nodes] + omega + +end PositionCounts + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/OccurrenceStorage.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/OccurrenceStorage.lean new file mode 100644 index 0000000000000000000000000000000000000000..6e23359370d3c8698939305bf34eb4db6d42879e --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/OccurrenceStorage.lean @@ -0,0 +1,136 @@ +import OAI.Combinatorics.EditApproximation.Geometry.OccurrenceIndex +import OAI.Combinatorics.EditApproximation.Geometry.RankedMemoStorage +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation +namespace PositionCounts + +/-- All counters allocated in the position trie are bounded. -/ +def CountsLE (C : ℕ) : PositionCounts → Prop + | .empty => True + | .node n l r => n ≤ C ∧ CountsLE C l ∧ CountsLE C r + +theorem CountsLE.mono {C D : ℕ} (hCD : C ≤ D) {tree : PositionCounts} + (h : tree.CountsLE C) : tree.CountsLE D := by + induction tree with + | empty => trivial + | node n l r ihl ihr => exact ⟨h.1.trans hCD, ihl h.2.1, ihr h.2.2⟩ + +theorem CountsLE.count {C : ℕ} {tree : PositionCounts} (h : tree.CountsLE C) : + tree.count ≤ C := by + cases tree with + | empty => exact Nat.zero_le _ + | node n l r => exact h.1 + +theorem CountsLE.left {C : ℕ} {tree : PositionCounts} (h : tree.CountsLE C) : + tree.left.CountsLE C := by + cases tree with + | empty => trivial + | node n l r => exact h.2.1 + +theorem CountsLE.right {C : ℕ} {tree : PositionCounts} (h : tree.CountsLE C) : + tree.right.CountsLE C := by + cases tree with + | empty => trivial + | node n l r => exact h.2.2 + +theorem CountsLE.add {C : ℕ} {tree : PositionCounts} (h : tree.CountsLE C) (d i : ℕ) : + (tree.add d i).CountsLE (C + 1) := by + induction d generalizing tree i with + | zero => exact ⟨Nat.add_le_add_right h.count 1, + h.left.mono (Nat.le_succ _), h.right.mono (Nat.le_succ _)⟩ + | succ d ih => + simp only [PositionCounts.add] + split + · exact ⟨Nat.add_le_add_right h.count 1, ih h.left _, h.right.mono (Nat.le_succ _)⟩ + · exact ⟨Nat.add_le_add_right h.count 1, h.left.mono (Nat.le_succ _), ih h.right _⟩ + +/-- A tag, two child pointers, and the binary counter at each allocated node. -/ + + +theorem storageBits_le {tree : PositionCounts} {C : ℕ} (h : tree.CountsLE C) : + tree.storageBits ≤ (Nat.size C + 3) * tree.nodes := by + induction tree with + | empty => simp only [storageBits, nodes, Nat.mul_zero, le_refl] + | node n l r ihl ihr => + have hn := Nat.size_le_size h.1 + have hl := ihl h.2.1 + have hr := ihr h.2.2 + simp only [storageBits, nodes] + nlinarith only [hn, hl, hr] + +end PositionCounts +namespace BinaryMemo + +/-- Concrete trie storage with the supplied stored-value representation. -/ + + +theorem valueStorage_le {α : Type*} (bits : α → ℕ) (W : ℕ) (memory : BinaryMemo α) + (h : AllValues (fun a => bits a ≤ W) memory) : + valueStorage bits memory ≤ (W + 3) * memory.nodes := by + induction memory with + | empty => simp only [valueStorage, nodes, Nat.mul_zero, le_refl] + | node value l r ihl ihr => + have hl : AllValues (fun a => bits a ≤ W) l := fun key a ha => h (false :: key) a ha + have hr : AllValues (fun a => bits a ≤ W) r := fun key a ha => h (true :: key) a ha + have hv : (value.map bits).getD 0 ≤ W := by + cases value with + | none => exact Nat.zero_le _ + | some a => exact h [] a rfl + have hls := ihl hl + have hrs := ihr hr + simp only [valueStorage, nodes] + nlinarith only [hv, hls, hrs] + +end BinaryMemo + +theorem occurrenceBuild_nodes (s p : ℕ) (entries : List (ℕ × ℕ)) : + (occurrenceBuild s p entries).nodes ≤ entries.length * (s + 1) := by + induction entries with + | nil => simp only [occurrenceBuild, BinaryMemo.nodes, List.length_nil, Nat.zero_mul, le_refl] + | cons e es ih => + have h := BinaryMemo.insert_nodes (occurrenceBuild s p es) (binaryMemoKey s e.1) + (((occurrenceBuild s p es).lookup (binaryMemoKey s e.1)).getD .empty |>.add p e.2) + simp only [binaryMemoKey_length] at h + simp only [occurrenceBuild, List.length_cons] + nlinarith only [h, ih] + +theorem occurrenceBuild_values (s p : ℕ) (entries : List (ℕ × ℕ)) : + BinaryMemo.AllValues (fun tree : PositionCounts => + tree.CountsLE entries.length ∧ tree.nodes ≤ entries.length * (p + 1)) + (occurrenceBuild s p entries) := by + induction entries with + | nil => exact BinaryMemo.allValues_empty _ + | cons e es ih => + have hold : let tree := ((occurrenceBuild s p es).lookup (binaryMemoKey s e.1)).getD .empty + tree.CountsLE es.length ∧ tree.nodes ≤ es.length * (p + 1) := by + cases hfind : (occurrenceBuild s p es).lookup (binaryMemoKey s e.1) with + | none => simp only [Option.getD_none, PositionCounts.CountsLE, PositionCounts.nodes]; exact ⟨trivial, Nat.zero_le _⟩ + | some tree => exact ih _ _ hfind + apply BinaryMemo.AllValues.insert + · intro key tree htree + obtain ⟨hc, hn⟩ := ih key tree htree + exact ⟨hc.mono (by simp), hn.trans (Nat.mul_le_mul_right _ (by simp))⟩ + · refine ⟨hold.1.add p e.2, ?_⟩ + have hn := PositionCounts.add_nodes + (((occurrenceBuild s p es).lookup (binaryMemoKey s e.1)).getD .empty) p e.2 + have ho := hold.2 + simp only [List.length_cons] + nlinarith only [hn, ho] + +theorem occurrenceBuild_storage (s p : ℕ) (entries : List (ℕ × ℕ)) : + BinaryMemo.valueStorage PositionCounts.storageBits (occurrenceBuild s p entries) ≤ + ((Nat.size entries.length + 3) * (entries.length * (p + 1)) + 3) * + (entries.length * (s + 1)) := by + have hv := occurrenceBuild_values s p entries + apply (BinaryMemo.valueStorage_le _ _ _ (fun key tree htree => + (PositionCounts.storageBits_le (hv key tree htree).1).trans + (Nat.mul_le_mul_left _ (hv key tree htree).2))).trans + exact Nat.mul_le_mul_left _ (occurrenceBuild_nodes s p entries) + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/OnlineActionDraw.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/OnlineActionDraw.lean new file mode 100644 index 0000000000000000000000000000000000000000..60d82813db24193dcbe306c6d47fa66060f50fdd --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/OnlineActionDraw.lean @@ -0,0 +1,85 @@ +import OAI.Combinatorics.EditApproximation.Geometry.BandRegret +import OAI.Combinatorics.EditApproximation.Probability.ExactSampling +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! The finite rational optimizer samples actual band actions, retaining their labels through ties. -/ + +namespace EditApproximation + +open Finset + +theorem argmax_map_commutes {α β γ : Type*} [Preorder γ] [DecidableLT γ] + (mapping : α → β) (score : β → γ) (values : List α) : + (values.map mapping).argmax score = (values.argmax (fun a => score (mapping a))).map mapping := by + induction values using List.reverseRecOn with + | nil => rfl + | append_singleton values a ih => + rw [List.map_append, List.map_singleton, List.argmax_concat, List.argmax_concat, ih] + cases h : values.argmax (fun a => score (mapping a)) with + | none => rfl + | some selected => + simp only [Option.map_some] + split_ifs <;> rfl + + + +theorem finiteOptimizerAction_spec {β σ : Type*} [Fintype β] [DecidableEq β] [DecidableEq σ] + (band : List (β → σ)) (hband : band ≠ []) (mass : β → ℚ) + (linear : β × σ → ℚ) (G j : ℕ) : + finiteOptimizerAction band hband mass linear G j ∈ band ∧ + actionVector mass (finiteOptimizerAction band hband mass linear G j) = + finiteOptimizerSelection (bandCoordinates band.toFinset) (band.map (actionVector mass)) linear G j := by + let coordinates := bandCoordinates band.toFinset + let vertices := band.map (actionVector mass) + let gradient := rationalSmoothedGradient G linear (finiteRationalOptimizer coordinates vertices linear G j) + let score := fun action : β → σ => ∑ coordinate ∈ coordinates, + gradient coordinate * actionVector mass action coordinate + have hmap := argmax_map_commutes (actionVector mass) + (fun vertex => ∑ coordinate ∈ coordinates, gradient coordinate * vertex coordinate) band + cases harg : band.argmax score with + | none => exact False.elim (hband (List.argmax_eq_none.mp harg)) + | some action => + have hmem : action ∈ band := List.argmax_mem (by rw [harg]; simp) + have hvalue : finiteOptimizerAction band hband mass linear G j = action := by + simp only [finiteOptimizerAction, score, coordinates, vertices, gradient] at harg ⊢ + rw [harg] + rfl + refine ⟨hvalue.symm ▸ hmem, ?_⟩ + rw [hvalue] + unfold finiteOptimizerSelection rationalLinearizationMaximizer + change actionVector mass action = (vertices.argmax + (fun vertex => ∑ coordinate ∈ coordinates, gradient coordinate * vertex coordinate)).getD (fun _ => 0) + change vertices.argmax (fun vertex => ∑ coordinate ∈ coordinates, gradient coordinate * vertex coordinate) = + (band.argmax score).map (actionVector mass) at hmap + rw [hmap, harg] + rfl + + + +theorem finiteOptimizerActionDraw_mem {β σ : Type*} [Fintype β] [DecidableEq β] [DecidableEq σ] + (band : List (β → σ)) (hband : band ≠ []) (mass : β → ℚ) + (linear : β × σ → ℚ) (G K : ℕ) (integer : Fin (optimizerTriangularMass K)) : + finiteOptimizerActionDraw band hband mass linear G K integer ∈ band := + (finiteOptimizerAction_spec band hband mass linear G (triangularChoice K integer).val).1 + +theorem finiteOptimizerActionDraw_mean {β σ : Type*} [Fintype β] [DecidableEq β] [DecidableEq σ] + (band : List (β → σ)) (hband : band ≠ []) (mass : β → ℚ) + (linear : β × σ → ℚ) (G K : ℕ) (hK : 0 < K) (coordinate : β × σ) : + (∑ integer : Fin (optimizerTriangularMass K), + actionVector mass (finiteOptimizerActionDraw band hband mass linear G K integer) coordinate) / + optimizerTriangularMass K = + finiteRationalOptimizer (bandCoordinates band.toFinset) (band.map (actionVector mass)) linear G K coordinate := by + have hselected (integer : Fin (optimizerTriangularMass K)) : + actionVector mass (finiteOptimizerActionDraw band hband mass linear G K integer) coordinate = + finiteOptimizerSelection (bandCoordinates band.toFinset) (band.map (actionVector mass)) linear G + (triangularChoice K integer).val coordinate := + congrFun (finiteOptimizerAction_spec band hband mass linear G (triangularChoice K integer).val).2 coordinate + simp_rw [hselected] + exact finiteRationalOptimizer_sampler_mean _ _ linear G K hK coordinate + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/OnlineEarlierDependence.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/OnlineEarlierDependence.lean new file mode 100644 index 0000000000000000000000000000000000000000..f76e1eda1f429552c141e8732d9ca17a823e4983 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/OnlineEarlierDependence.lean @@ -0,0 +1,197 @@ +import OAI.Combinatorics.EditApproximation.Geometry.LocalOnlineProgram +import OAI.Combinatorics.EditApproximation.Queries.QueryEarlierInputs + +namespace OAI + +/-! The actual online optimizer reads only the recorded band coordinates +and earlier child histories. Equality on the finite query cover suffices +for equality of its returned action, including deterministic tie breaking. -/ + +namespace EditApproximation + +open Finset + +theorem rationalLinearizationMaximizer_congr_on {ι : Type*} + (coordinates : Finset ι) (vertices : List (ι → ℚ)) (left right : ι → ℚ) + (heq : ∀ i ∈ coordinates, left i = right i) : + rationalLinearizationMaximizer coordinates vertices left = + rationalLinearizationMaximizer coordinates vertices right := by + have hscore : (fun p : ι → ℚ => ∑ i ∈ coordinates, left i * p i) = + (fun p : ι → ℚ => ∑ i ∈ coordinates, right i * p i) := by + funext p + exact sum_congr rfl (fun i hi => by rw [heq i hi]) + unfold rationalLinearizationMaximizer + rw [hscore] + +theorem finiteRationalOptimizer_congr_linear_on {ι : Type*} + (coordinates : Finset ι) (vertices : List (ι → ℚ)) (left right : ι → ℚ) + (G j : ℕ) (heq : ∀ i ∈ coordinates, left i = right i) : + finiteRationalOptimizer coordinates vertices left G j = + finiteRationalOptimizer coordinates vertices right G j := by + induction j with + | zero => rfl + | succ j ih => + simp only [finiteRationalOptimizer, ih] + have hselected := rationalLinearizationMaximizer_congr_on coordinates vertices + (rationalSmoothedGradient G left (finiteRationalOptimizer coordinates vertices right G j)) + (rationalSmoothedGradient G right (finiteRationalOptimizer coordinates vertices right G j)) + (fun i hi => by simp only [rationalSmoothedGradient, heq i hi]) + rw [hselected] + +theorem finiteOptimizerAction_congr_linear_on {β σ : Type*} + [Fintype β] [DecidableEq β] [DecidableEq σ] + (band : List (β → σ)) (hband : band ≠ []) (mass : β → ℚ) + (left right : β × σ → ℚ) (G j : ℕ) + (heq : ∀ i ∈ bandCoordinates band.toFinset, left i = right i) : + finiteOptimizerAction band hband mass left G j = + finiteOptimizerAction band hband mass right G j := by + unfold finiteOptimizerAction + dsimp only + rw [finiteRationalOptimizer_congr_linear_on _ _ left right G j heq] + have hscore : (fun action : β → σ => ∑ i ∈ bandCoordinates band.toFinset, + rationalSmoothedGradient G left + (finiteRationalOptimizer (bandCoordinates band.toFinset) (band.map (actionVector mass)) right G j) i * + actionVector mass action i) = + (fun action : β → σ => ∑ i ∈ bandCoordinates band.toFinset, + rationalSmoothedGradient G right + (finiteRationalOptimizer (bandCoordinates band.toFinset) (band.map (actionVector mass)) right G j) i * + actionVector mass action i) := by + funext action + apply sum_congr rfl + intro i hi + simp only [rationalSmoothedGradient, heq i hi] + rw [hscore] + +theorem finiteOptimizerActionDraw_congr_linear_on {β σ : Type*} + [Fintype β] [DecidableEq β] [DecidableEq σ] + (band : List (β → σ)) (hband : band ≠ []) (mass : β → ℚ) + (left right : β × σ → ℚ) (G K : ℕ) (integer : Fin (optimizerTriangularMass K)) + (heq : ∀ i ∈ bandCoordinates band.toFinset, left i = right i) : + finiteOptimizerActionDraw band hband mass left G K integer = + finiteOptimizerActionDraw band hband mass right G K integer := + finiteOptimizerAction_congr_linear_on band hband mass left right G _ heq + +/-- The gain at `t` and decrements at indices below `t` inspect exactly +the input table indices at most `t`. -/ +theorem rationalOnlineLinear_child_congr {β σ : Type*} (mass : β → ℚ) + (left right : ℕ → β × σ → ℚ) (eta kappa : ℚ) (t : ℕ) (i : β × σ) + (heq : ∀ s ≤ t, left s i = right s i) : + rationalOnlineLinear eta kappa (childGain mass left) (childDecrement mass left) t i = + rationalOnlineLinear eta kappa (childGain mass right) (childDecrement mass right) t i := by + have hgain (s : ℕ) (hs : s ≤ t) : childGain mass left s i = childGain mass right s i := by + simp only [childGain, heq s hs] + have hdecrement (s : ℕ) (hs : s < t) : + childDecrement mass left s i = childDecrement mass right s i := by + simp only [childDecrement, heq s (by omega), heq (s + 1) (by omega)] + unfold rationalOnlineLinear rationalOptimisticHistory + rw [hgain t le_rfl] + congr 2 + apply sum_congr rfl + intro s hs + rw [hgain s (by have ht := mem_range.mp hs; omega), hdecrement s (mem_range.mp hs)] + +theorem keyedOnlineCandidate_congr_history {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (P F exponent H b : ℕ) (tau eta kappa : ℚ) + (child initial : Fin M → TargetInterval target.length → ℚ) + (left right : PhysicalChildTables M target.length) (t : ℕ) + (r : TargetInterval target.length) (integer : ℕ) + (heq : ∀ i ∈ bandCoordinates (representativeBandActions source target parent r b P tau + ((2 : ℚ) ^ (-(exponent : ℤ))) child).toFinset, ∀ s ≤ t, + left i.1 s i.2 = right i.1 s i.2) : + keyedOnlineCandidate source target parent P F exponent H b tau eta kappa child initial left t r integer = + keyedOnlineCandidate source target parent P F exponent H b tau eta kappa child initial right t r integer := by + have hlinear : ∀ i ∈ bandCoordinates (representativeBandActions source target parent r b P tau + ((2 : ℚ) ^ (-(exponent : ℤ))) child).toFinset, + rationalOnlineLinear eta kappa + (childGain (bandChildEnvelope b (representativeBandActions source target parent r b P tau + ((2 : ℚ) ^ (-(exponent : ℤ))) child) initial) (fun s i => left i.1 s i.2)) + (childDecrement (bandChildEnvelope b (representativeBandActions source target parent r b P tau + ((2 : ℚ) ^ (-(exponent : ℤ))) child) initial) (fun s i => left i.1 s i.2)) t i = + rationalOnlineLinear eta kappa + (childGain (bandChildEnvelope b (representativeBandActions source target parent r b P tau + ((2 : ℚ) ^ (-(exponent : ℤ))) child) initial) (fun s i => right i.1 s i.2)) + (childDecrement (bandChildEnvelope b (representativeBandActions source target parent r b P tau + ((2 : ℚ) ^ (-(exponent : ℤ))) child) initial) (fun s i => right i.1 s i.2)) t i := by + intro i hi + exact rationalOnlineLinear_child_congr _ _ _ eta kappa t i (heq i hi) + unfold keyedOnlineCandidate + dsimp only + split_ifs with hband + · rfl + · cases htest : testUnskippedBand source target parent b P exponent tau F child initial r with + | none => rfl + | some data => + apply congrArg (fun action => some (sharedBandRationalAction r action)) + exact finiteOptimizerActionDraw_congr_linear_on _ hband _ _ _ _ _ _ hlinear + +theorem keyedOnlineCandidate_congr_earlier_cover {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (P F exponent H b history : ℕ) (tau eta kappa : ℚ) + (child initial : Fin M → TargetInterval target.length → ℚ) + (left right : PhysicalChildTables M target.length) (t : ℕ) + (r : TargetInterval target.length) (integer : ℕ) + (representatives : List (ℕ × TargetInterval target.length)) (hrep : (b, r) ∈ representatives) + (ht : t < history) + (heq : ∀ i s q, (i, s, q) ∈ wideEarlierInputCover parent P history representatives → + left i s q = right i s q) : + keyedOnlineCandidate source target parent P F exponent H b tau eta kappa child initial left t r integer = + keyedOnlineCandidate source target parent P F exponent H b tau eta kappa child initial right t r integer := by + apply keyedOnlineCandidate_congr_history + intro i hi s hs + apply heq + exact bandCoordinates_earlier_cover source target parent P history b tau _ representatives r hrep + child s (by omega) i hi + +/-- All online candidates for a local query, with their original order +and ties, are fixed by the finite earlier-input cover. -/ +theorem localOnlineCandidates_congr_earlier_cover {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (N P F exponent H history : ℕ) (tau a eta kappa : ℚ) + (parentInitial : TargetInterval target.length → ℚ) + (child initial : Fin M → TargetInterval target.length → ℚ) + (left right : PhysicalChildTables M target.length) (t : ℕ) + (integer : ℕ → TargetInterval target.length → ℕ) (q : TargetInterval target.length) + (ht : t < history) + (heq : ∀ i s r, (i, s, r) ∈ queryEarlierInputCover parent N P F exponent history a parentInitial q → + left i s r = right i s r) : + localOnlineCandidates source target parent N P F exponent H tau a eta kappa + parentInitial child initial left t integer q = + localOnlineCandidates source target parent N P F exponent H tau a eta kappa + parentInitial child initial right t integer q := by + unfold localOnlineCandidates + apply List.filterMap_congr + intro b hb + dsimp only + split_ifs with heligible + · apply keyedOnlineCandidate_congr_earlier_cover source target parent P F exponent H b history + tau eta kappa child initial left right t _ _ + (queryEarlierRepresentatives N P F exponent a parentInitial q) + (queryEarlierRepresentatives_online N P F exponent a parentInitial q b hb) ht + exact heq + · rfl + +section Physical + +variable {α : Type*} [DecidableEq α] {M J R : ℕ} [NeZero R] + (source target : List α) (U : PhysicalEntry M J target.length → ℕ) + (N P F exponent H T : ℕ) (A tau eta kappa : ℚ) + +/-- At a positive physical refinement time `t`, the online provider +depends only on child times strictly less than `t` in the query cover. -/ +theorem physicalLocalOnline_congr_earlier_cover + (integer : PhysicalInternalNode M J → Fin R → ℕ → TargetInterval target.length → ℕ) + (node : PhysicalInternalNode M J) (left right : PhysicalChildTables M target.length) + (t : ℕ) (ht : 0 < t) (q : TargetInterval target.length) + (heq : ∀ i s r, (i, s, r) ∈ queryEarlierInputCover + (physicalSourceInterval source.length node.1) N P F exponent t (refinementFactor A F) + (fun r => stageInitial source target U N P F A (node.1, r)) q → + left i s r = right i s r) : + physicalLocalOnline source target U N P F exponent H T A tau eta kappa integer node.1 left t q = + physicalLocalOnline source target U N P F exponent H T A tau eta kappa integer node.1 right t q := by + unfold physicalLocalOnline + rw [dite_eq_left node.2, dite_eq_left node.2] + exact localOnlineCandidates_congr_earlier_cover source target _ N P F exponent H t + tau (refinementFactor A F) eta kappa _ _ _ left right (t - 1) _ q (by omega) heq + +end Physical +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/OnlineLinearBits.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/OnlineLinearBits.lean new file mode 100644 index 0000000000000000000000000000000000000000..7d2d71f1610ce12e532776d8e1afd6b8dbd40f5b --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/OnlineLinearBits.lean @@ -0,0 +1,133 @@ +import OAI.Combinatorics.EditApproximation.Geometry.BandEnvelopeBits +import OAI.Combinatorics.EditApproximation.Geometry.ChildIncrements + +namespace OAI + +/-! The actual finite optimistic-history sum has polynomial encoding +length. Its normalized table entries are bounded by the fixed envelopes. -/ + +namespace EditApproximation + +open Finset + +def onlineSummandEncodingBudget (tableBits massBits kappaBits : ℕ) : ℕ := + 10 * tableBits + 4 * massBits + 4 * kappaBits + 56 + +def onlineLinearEncodingBudget (etaBits kappaBits massBits tableBits t : ℕ) : ℕ := + etaBits + 2 * (Nat.size (t * 2) + + 2 * (t * onlineSummandEncodingBudget tableBits massBits kappaBits + 1) + 1) + + 2 * (tableBits + massBits + 3) + 3 + +theorem childGain_encoding {β σ : Type*} (mass : β → ℚ) (table : ℕ → β × σ → ℚ) + (s : ℕ) (i : β × σ) (Bm Bt : ℕ) + (hm : rationalEncodingBits (mass i.1) ≤ Bm) (ht : rationalEncodingBits (table s i) ≤ Bt) : + rationalEncodingBits (childGain mass table s i) ≤ Bt + Bm + 3 := by + have h := rationalEncodingBits_div (-table s i) (mass i.1) + rw [rationalEncodingBits_neg] at h + exact h.trans (by omega) + +theorem childDecrement_encoding {β σ : Type*} (mass : β → ℚ) (table : ℕ → β × σ → ℚ) + (s : ℕ) (i : β × σ) (Bm Bt : ℕ) + (hm : rationalEncodingBits (mass i.1) ≤ Bm) + (ht : rationalEncodingBits (table s i) ≤ Bt) + (ht' : rationalEncodingBits (table (s + 1) i) ≤ Bt) : + rationalEncodingBits (childDecrement mass table s i) ≤ 4 * Bt + Bm + 5 := by + have hs := rationalEncodingBits_sub (table s i) (table (s + 1) i) + have hd := rationalEncodingBits_div (table s i - table (s + 1) i) (mass i.1) + change rationalEncodingBits ((table s i - table (s + 1) i) / mass i.1) ≤ _ + omega + +theorem childGain_abs_le_one {β σ : Type*} (mass : β → ℚ) (table : ℕ → β × σ → ℚ) + (s : ℕ) (i : β × σ) (hm : 0 < mass i.1) + (ht : 0 ≤ table s i ∧ table s i ≤ mass i.1) : |childGain mass table s i| ≤ 1 := by + rw [childGain, abs_div, abs_neg, abs_of_nonneg ht.1, abs_of_pos hm] + exact (div_le_one₀ hm).mpr ht.2 + +theorem childDecrement_abs_le_one {β σ : Type*} (mass : β → ℚ) (table : ℕ → β × σ → ℚ) + (s : ℕ) (i : β × σ) (hm : 0 < mass i.1) + (ht : 0 ≤ table s i ∧ table s i ≤ mass i.1) + (ht' : 0 ≤ table (s + 1) i ∧ table (s + 1) i ≤ mass i.1) : + |childDecrement mass table s i| ≤ 1 := by + rw [childDecrement, abs_div, abs_of_pos hm] + apply (div_le_one₀ hm).mpr + exact abs_le.mpr ⟨by linarith, by linarith⟩ + +theorem rationalOnlineLinear_encoding {β σ : Type*} (mass : β → ℚ) + (table : ℕ → β × σ → ℚ) (eta kappa : ℚ) (t : ℕ) (i : β × σ) + (Be Bk Bm Bt : ℕ) (heta : rationalEncodingBits eta ≤ Be) + (hkappa : rationalEncodingBits kappa ≤ Bk) + (hmass : rationalEncodingBits (mass i.1) ≤ Bm) + (htable : ∀ s ≤ t + 1, rationalEncodingBits (table s i) ≤ Bt) + (hmassPos : 0 < mass i.1) (hkappaRange : 0 ≤ kappa ∧ kappa ≤ 1) + (htableRange : ∀ s ≤ t + 1, 0 ≤ table s i ∧ table s i ≤ mass i.1) : + rationalEncodingBits (rationalOnlineLinear eta kappa (childGain mass table) + (childDecrement mass table) t i) ≤ onlineLinearEncodingBudget Be Bk Bm Bt t := by + let term := fun s => childGain mass table s i + (1 - 2 * kappa) * childDecrement mass table s i + have htwo : rationalEncodingBits (2 : ℚ) = 4 := by + rw [show (2 : ℚ) = (2 : ℕ) by norm_num, rationalEncodingBits_natCast] + rfl + have hone : rationalEncodingBits (1 : ℚ) = 3 := by norm_num [rationalEncodingBits] + have hcoeff : rationalEncodingBits (1 - 2 * kappa) ≤ 2 * Bk + 18 := by + have hm := rationalEncodingBits_mul 2 kappa + have hs := rationalEncodingBits_sub 1 (2 * kappa) + rw [htwo] at hm + rw [hone] at hs + omega + have hcoeffAbs : |1 - 2 * kappa| ≤ 1 := abs_le.mpr ⟨by linarith [hkappaRange.1, hkappaRange.2], by linarith [hkappaRange.1]⟩ + have hterm (s : ℕ) (hs : s < t) : rationalEncodingBits (term s) ≤ onlineSummandEncodingBudget Bt Bm Bk := by + have hg := childGain_encoding mass table s i Bm Bt hmass (htable s (by omega)) + have hd := childDecrement_encoding mass table s i Bm Bt hmass (htable s (by omega)) (htable (s + 1) (by omega)) + have hp := rationalEncodingBits_mul (1 - 2 * kappa) (childDecrement mass table s i) + have ha := rationalEncodingBits_add (childGain mass table s i) ((1 - 2 * kappa) * childDecrement mass table s i) + change rationalEncodingBits (childGain mass table s i + (1 - 2 * kappa) * childDecrement mass table s i) ≤ _ + unfold onlineSummandEncodingBudget + omega + have htermAbs (s : ℕ) (hs : s < t) : |term s| ≤ 2 := by + have hg := childGain_abs_le_one mass table s i hmassPos (htableRange s (by omega)) + have hd := childDecrement_abs_le_one mass table s i hmassPos (htableRange s (by omega)) (htableRange (s + 1) (by omega)) + have hp := mul_le_mul hcoeffAbs hd (abs_nonneg _) (by norm_num : (0 : ℚ) ≤ 1) + have ha := abs_add_le (childGain mass table s i) ((1 - 2 * kappa) * childDecrement mass table s i) + rw [abs_mul] at ha + dsimp only [term] + linarith + have hsum := rational_finite_sum_encoding_le (range t) term 2 (onlineSummandEncodingBudget Bt Bm Bk) + (fun s hs => htermAbs s (mem_range.mp hs)) (by + intro s hs + have h := hterm s (mem_range.mp hs) + unfold rationalEncodingBits at h + omega) + simp only [card_range] at hsum + have hg := childGain_encoding mass table t i Bm Bt hmass (htable t (by omega)) + have ha := rationalEncodingBits_add (∑ s ∈ range t, term s) (childGain mass table t i) + have hm := rationalEncodingBits_mul eta ((∑ s ∈ range t, term s) + childGain mass table t i) + change rationalEncodingBits (eta * ((∑ s ∈ range t, term s) + childGain mass table t i)) ≤ _ + unfold onlineLinearEncodingBudget + omega + +theorem rationalOnlineLinear_abs {β σ : Type*} (mass : β → ℚ) + (table : ℕ → β × σ → ℚ) (eta kappa : ℚ) (t E : ℕ) (i : β × σ) + (heta : |eta| ≤ E) (hmass : 0 < mass i.1) (hkappa : 0 ≤ kappa ∧ kappa ≤ 1) + (htable : ∀ s ≤ t + 1, 0 ≤ table s i ∧ table s i ≤ mass i.1) : + |rationalOnlineLinear eta kappa (childGain mass table) (childDecrement mass table) t i| ≤ E * (2 * t + 1) := by + have hc : |1 - 2 * kappa| ≤ 1 := abs_le.mpr ⟨by linarith [hkappa.2], by linarith [hkappa.1]⟩ + have hterm (s : ℕ) (hs : s ∈ range t) : + |childGain mass table s i + (1 - 2 * kappa) * childDecrement mass table s i| ≤ 2 := by + have hs' := mem_range.mp hs + have hg := childGain_abs_le_one mass table s i hmass (htable s (by omega)) + have hd := childDecrement_abs_le_one mass table s i hmass (htable s (by omega)) (htable (s + 1) (by omega)) + have hp := mul_le_mul hc hd (abs_nonneg _) (by norm_num : (0 : ℚ) ≤ 1) + exact (abs_add_le _ _).trans (by rw [abs_mul]; linarith) + have hsum : |rationalOptimisticHistory kappa (childGain mass table) (childDecrement mass table) t i| ≤ 2 * t := by + unfold rationalOptimisticHistory + calc + _ ≤ ∑ s ∈ range t, |childGain mass table s i + (1 - 2 * kappa) * childDecrement mass table s i| := abs_sum_le_sum_abs _ _ + _ ≤ ∑ _s ∈ range t, (2 : ℚ) := sum_le_sum hterm + _ = _ := by simp; ring + have hg := childGain_abs_le_one mass table t i hmass (htable t (by omega)) + unfold rationalOnlineLinear + rw [abs_mul] + exact mul_le_mul heta ((abs_add_le _ _).trans (add_le_add hsum hg)) (abs_nonneg _) (Nat.cast_nonneg _) + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/ParameterAsymptotics.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/ParameterAsymptotics.lean new file mode 100644 index 0000000000000000000000000000000000000000..846a2804c49f5872cf749b4111f9ce33a96a8af6 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/ParameterAsymptotics.lean @@ -0,0 +1,125 @@ +import OAI.Combinatorics.EditApproximation.Geometry.AccuracyCutoff + +namespace OAI + +/-! +# Growth of the computed parameters + +These are scalar estimates for the literal integer parameters of Section 10. +They do not assert an evaluator cost: the recursive-input and charged local +work bounds must be connected to these estimates separately. +-/ + +namespace EditApproximation + +open Filter +open scoped Topology + +theorem heightExponent_tendsto : Tendsto heightExponent atTop atTop := by + refine tendsto_atTop.2 fun b => ?_ + filter_upwards [eventually_ge_atTop (2 ^ (2 ^ b))] with N hN + exact heightExponent_above_double_power N b hN + +theorem inputSmallLog_tendsto : Tendsto inputSmallLog atTop atTop := by + apply tendsto_atTop_mono' atTop _ heightExponent_tendsto + filter_upwards [eventually_ge_atTop 1] with N hN + exact (inputSmallLog_bounds N hN).1 + +theorem smallLogExponent_tendsto : Tendsto smallLogExponent atTop atTop := by + refine tendsto_atTop.2 fun b => ?_ + filter_upwards [inputSmallLog_tendsto.eventually (eventually_ge_atTop (2 ^ b))] + with N hN + exact (Nat.pow_le_pow_iff_right (by decide : 1 < (2 : ℕ))).mp hN + +theorem inputSmallLog_log_two (N : ℕ) : + Nat.log 2 (inputSmallLog N) = smallLogExponent N := by + exact Nat.log_pow (by decide : 1 < (2 : ℕ)) _ + +theorem coarseExponent_tendsto : + Tendsto (fun N => coarseExponent (inputSmallLog N)) atTop atTop := by + refine tendsto_atTop.2 fun b => ?_ + filter_upwards [smallLogExponent_tendsto.eventually (eventually_ge_atTop (b ^ 4))] + with N hN + exact coarseExponent_maximal _ b ((inputSmallLog_log_two N).symm ▸ hN) + +theorem heightExponent_real_tendsto : + Tendsto (fun N => (heightExponent N : ℝ)) atTop atTop := + tendsto_natCast_atTop_atTop.comp heightExponent_tendsto + +theorem inputSmallLog_real_tendsto : + Tendsto (fun N => (inputSmallLog N : ℝ)) atTop atTop := + tendsto_natCast_atTop_atTop.comp inputSmallLog_tendsto + +theorem coarseExponent_real_tendsto : + Tendsto (fun N => (coarseExponent (inputSmallLog N) : ℝ)) atTop atTop := + tendsto_natCast_atTop_atTop.comp coarseExponent_tendsto + +theorem inputSmallLog_real_log (N : ℕ) : + Real.log (inputSmallLog N : ℝ) = (smallLogExponent N : ℝ) * Real.log 2 := by + simp only [inputSmallLog, Nat.cast_pow, Nat.cast_ofNat, Real.log_pow] + +theorem shifted_square_log_bound (p f : ℝ) (hpR : 1 ≤ p) (hfour : p ^ 4 ≤ f) : + (p + 1) ^ 2 / (f * Real.log 2) ≤ 4 / (Real.log 2 * p ^ 2) := by + have hsquare : (p + 1) ^ 2 ≤ 4 * p ^ 2 := by nlinarith + have hproduct : (p + 1) ^ 2 * p ^ 2 ≤ 4 * f := by + have hm := mul_le_mul_of_nonneg_right hsquare (sq_nonneg p) + nlinarith + have hlogtwo : 0 < Real.log 2 := Real.log_pos (by norm_num) + have hf : 0 < f := by nlinarith [sq_nonneg (p ^ 2)] + apply (div_le_div_iff₀ (mul_pos hf hlogtwo) + (mul_pos hlogtwo (sq_pos_of_pos (by linarith : 0 < p)))).2 + nlinarith [mul_le_mul_of_nonneg_right hproduct hlogtwo.le] + +theorem coarse_shifted_square_log_bound (N : ℕ) + (hp : 1 ≤ coarseExponent (inputSmallLog N)) : + ((coarseExponent (inputSmallLog N) : ℝ) + 1) ^ 2 / + Real.log (inputSmallLog N : ℝ) ≤ + 4 / (Real.log 2 * (coarseExponent (inputSmallLog N) : ℝ) ^ 2) := by + rw [inputSmallLog_real_log] + apply shifted_square_log_bound + · exact_mod_cast hp + · have hnat := coarseExponent_fourth_power (inputSmallLog N) + rw [inputSmallLog_log_two] at hnat + exact_mod_cast hnat + +/-- The central earlier-index dependency exponent in Section 10 is sublinear. -/ +theorem coarse_shifted_square_div_log_tendsto : + Tendsto (fun N => ((coarseExponent (inputSmallLog N) : ℝ) + 1) ^ 2 / + Real.log (inputSmallLog N : ℝ)) atTop (𝓝 0) := by + have hupper : Tendsto (fun N => + 4 / (Real.log 2 * (coarseExponent (inputSmallLog N) : ℝ) ^ 2)) atTop (𝓝 0) := by + have h := (coarseExponent_real_tendsto.inv_tendsto_atTop.pow 2).const_mul (4 / Real.log 2) + convert h using 1 + · ext N + simp only [Pi.inv_apply, div_eq_mul_inv, mul_inv_rev, inv_pow] + ring + · simp + apply squeeze_zero' _ _ hupper + · filter_upwards [smallLogExponent_tendsto.eventually (eventually_ge_atTop 1)] with N hN + apply div_nonneg (sq_nonneg _) + rw [inputSmallLog_real_log] + exact mul_nonneg (Nat.cast_nonneg _) (Real.log_nonneg (by norm_num)) + · filter_upwards [coarseExponent_tendsto.eventually (eventually_ge_atTop 1)] with N hN + exact coarse_shifted_square_log_bound N hN + +theorem inputSmallLog_div_height_tendsto : + Tendsto (fun N => (inputSmallLog N : ℝ) / inputHeight N) atTop (𝓝 0) := by + have hupper : Tendsto (fun N => 2 * (heightExponent N : ℝ) / (2 : ℝ) ^ heightExponent N) + atTop (𝓝 0) := by + simpa only [Function.comp_def, pow_one, mul_zero, mul_div_assoc] using + ((tendsto_pow_const_div_const_pow_of_one_lt 1 (by norm_num : (1 : ℝ) < 2)).comp + heightExponent_tendsto).const_mul 2 + apply squeeze_zero' (Eventually.of_forall fun N => div_nonneg (Nat.cast_nonneg _) (Nat.cast_nonneg _)) _ hupper + filter_upwards [eventually_ge_atTop 1] with N hN + have hbound : (inputSmallLog N : ℝ) ≤ 2 * (heightExponent N : ℝ) := by + exact_mod_cast (inputSmallLog_bounds N hN).2.le + simpa only [inputHeight, Nat.cast_pow, Nat.cast_ofNat] using + div_le_div_of_nonneg_right hbound (by positivity : (0 : ℝ) ≤ 2 ^ heightExponent N) + +theorem log_smallLog_div_smallLog_tendsto : + Tendsto (fun N => Real.log (inputSmallLog N : ℝ) / inputSmallLog N) atTop (𝓝 0) := + Real.isLittleO_log_id_atTop.tendsto_div_nhds_zero.comp inputSmallLog_real_tendsto + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/ParameterConstruction.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/ParameterConstruction.lean new file mode 100644 index 0000000000000000000000000000000000000000..763fac602bfa0cb8d002e2dbd526426da0b68361 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/ParameterConstruction.lean @@ -0,0 +1,158 @@ +import OAI.Combinatorics.EditApproximation.Binary.IntegerPreprocessing +import OAI.Combinatorics.EditApproximation.Refinement.ComputedSourceAddressBits +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Counted register loops for the global integer parameters. Multiplication +and division here are word operations; the word-cap theorem below supplies +room for their intermediate integers. -/ +namespace EditApproximation +open Filter + + theorem size_pred_eq_clog_two (n : ℕ) : (n - 1).size = Nat.clog 2 n := by + apply eq_of_forall_ge_iff + intro k + rw [Nat.size_le, Nat.clog_le_iff_le_pow (by decide)] + have hp := Nat.two_pow_pos k + omega + + theorem size_pred_eq_log_two (n : ℕ) : n.size - 1 = Nat.log 2 n := by + by_cases hn : n = 0 + · subst n; simp + apply eq_of_forall_le_iff + intro k + have hs : 0 < n.size := Nat.size_pos.mpr (Nat.pos_of_ne_zero hn) + rw [Nat.le_log_iff_pow_le (by decide) hn] + have hk := Nat.lt_size (m := k) (n := n) + omega + + + + @[simp] theorem parameterClogWithWork_spec (n : ℕ) : + parameterClogWithWork n = (Nat.clog 2 n, 2 * Nat.clog 2 n + 3) := by + simp only [parameterClogWithWork, inputBitLengthWithWork_spec, size_pred_eq_clog_two] + + + + @[simp] theorem parameterLogWithWork_value (n : ℕ) : + (parameterLogWithWork n).1 = Nat.log 2 n := by + simp only [parameterLogWithWork, inputBitLengthWithWork_spec, size_pred_eq_log_two] + + theorem parameterLogWithWork_cost (n : ℕ) : + (parameterLogWithWork n).2 = 2 * n.size + 2 := by + simp only [parameterLogWithWork, inputBitLengthWithWork_spec] + + + + theorem parameterRootSearch_value (n k : ℕ) (hk : n.sqrt ≤ k) : + (parameterRootSearch n k).1 = n.sqrt := by + induction k with + | zero => simp only [parameterRootSearch]; omega + | succ k ih => + rw [parameterRootSearch] + split_ifs with h + · have := Nat.le_sqrt.mpr h + dsimp only + omega + · have hk' : n.sqrt ≤ k := by + have := Nat.le_sqrt.not.mpr h + omega + exact ih hk' + + theorem parameterRootSearch_cost (n k : ℕ) : + (parameterRootSearch n k).2 ≤ 3 * k + 1 := by + induction k with + | zero => exact le_rfl + | succ k ih => + rw [parameterRootSearch] + split_ifs <;> dsimp only <;> omega + + + + @[simp] theorem parameterSqrtWithWork_value (n : ℕ) : + (parameterSqrtWithWork n).1 = n.sqrt := + parameterRootSearch_value n n (Nat.sqrt_le_self n) + + theorem parameterSqrtWithWork_cost (n : ℕ) : + (parameterSqrtWithWork n).2 ≤ 3 * n + 1 := parameterRootSearch_cost n n + + + + @[simp] theorem parameterPowerWithWork_spec (a k : ℕ) : + parameterPowerWithWork a k = (a ^ k, 2 * k + 1) := by + induction k with + | zero => rfl + | succ k ih => simp only [parameterPowerWithWork, ih, pow_succ]; congr 1 + + theorem parameterPowerWithWork_intermediate (a k j : ℕ) (ha : 1 ≤ a) (hj : j ≤ k) : + (parameterPowerWithWork a j).1 ≤ a ^ k := by + rw [parameterPowerWithWork_spec] + exact Nat.pow_le_pow_right (by omega) hj + + + + @[simp] theorem integerParametersWithWork_value (N : ℕ) : + (integerParametersWithWork N).1 = integerParameters N := by + simp only [integerParametersWithWork, parameterClogWithWork_spec, parameterPowerWithWork_spec, + parameterLogWithWork_value, parameterSqrtWithWork_value, integerParameters, + heightExponent, inputHeight, smallLogExponent, inputSmallLog, coarseExponent] + + theorem integerParametersWithWork_cost (N : ℕ) : + (integerParametersWithWork N).2 ≤ 1000 * (inputHeight N + 1) := by + have hfirst : Nat.clog 2 (N + 2) ≤ inputHeight N := + Nat.clog_le_of_le_pow (inputHeight_covers_length N) + have he : heightExponent N ≤ inputHeight N := Nat.lt_two_pow_self.le + have hs : smallLogExponent N ≤ inputHeight N := + (Nat.lt_two_pow_self.le : smallLogExponent N ≤ inputSmallLog N).trans + (computed_smallLog_le_height N) + have hp : coarseExponent (inputSmallLog N) ≤ inputHeight N := + (coarseExponent_le_smallLog N).trans (computed_smallLog_le_height N) + have hl : Nat.log 2 (inputSmallLog N) ≤ inputHeight N := + (Nat.log_le_self _ _).trans (computed_smallLog_le_height N) + have hr : (Nat.log 2 (inputSmallLog N)).sqrt ≤ inputHeight N := + (Nat.sqrt_le_self _).trans hl + have hlogsize : (inputSmallLog N).size ≤ inputHeight N + 1 := by + change (2 ^ smallLogExponent N).size ≤ _ + rw [Nat.size_pow] + omega + have hroot := parameterSqrtWithWork_cost (Nat.log 2 (inputSmallLog N)) + have hroot2 := parameterSqrtWithWork_cost ((Nat.log 2 (inputSmallLog N)).sqrt) + have hlogcost := parameterLogWithWork_cost (inputSmallLog N) + simp only [integerParametersWithWork, parameterClogWithWork_spec, parameterPowerWithWork_spec, + parameterLogWithWork_value, parameterSqrtWithWork_value] + change 2 * Nat.clog 2 (N + 2) + 3 + (2 * heightExponent N + 3) + (2 * heightExponent N + 1) + + (2 * smallLogExponent N + 3) + (2 * smallLogExponent N + 1) + + (parameterLogWithWork (inputSmallLog N)).2 + + (parameterSqrtWithWork (Nat.log 2 (inputSmallLog N))).2 + + (parameterSqrtWithWork ((Nat.log 2 (inputSmallLog N)).sqrt)).2 + + (2 * (heightExponent N / 20) + 1) + (2 * coarseExponent (inputSmallLog N) + 1) + + (2 * (coarseExponent (inputSmallLog N) + 4) + 1) + + (2 * (coarseExponent (inputSmallLog N) + 20) + 1) + + (2 * ((3 * heightExponent N + 3) / 4) + 1) + (2 * 2 + 1) + 15 ≤ _ + have hdiv := Nat.div_le_self (heightExponent N) 20 + have hdiv' := Nat.div_le_self (3 * heightExponent N + 3) 4 + omega + + theorem integerParameter_power_word_cap : + ∀ᶠ N in atTop, + Nat.size (inputHeight N ^ (coarseExponent (inputSmallLog N) + 20)) ≤ inputHeight N := by + filter_upwards [computed_sourceAddressBits_le_height 20] with N hN + apply (natural_power_bit_length _ _).trans + have hpow : coarseExponent (inputSmallLog N) + 20 ≤ + 20 * (coarseExponent (inputSmallLog N) + 1) := by omega + exact (Nat.add_le_add_right (Nat.mul_le_mul_right _ hpow) 1).trans hN + + theorem parameterPowerWithWork_word_cap (a k W : ℕ) (ha : 1 ≤ a) + (hcap : Nat.size (a ^ k) ≤ W) (j : ℕ) (hj : j ≤ k) : + (parameterPowerWithWork a j).1 < 2 ^ W := + (parameterPowerWithWork_intermediate a k j ha hj).trans_lt (Nat.size_le.mp hcap) + + theorem parameterRootSearch_word_cap (n k W : ℕ) (hk : k ≤ n) + (hcap : n * n < 2 ^ W) : k * k < 2 ^ W := + (Nat.mul_le_mul hk hk).trans_lt hcap + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/ParameterDependencyAsymptotics.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/ParameterDependencyAsymptotics.lean new file mode 100644 index 0000000000000000000000000000000000000000..3a71b607fb0f3ccfea833d75b8c50500303c99b7 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/ParameterDependencyAsymptotics.lean @@ -0,0 +1,295 @@ +import OAI.Combinatorics.EditApproximation.Geometry.ParameterLocalAsymptotics +import OAI.Combinatorics.EditApproximation.Refinement.ComputedStageTime +import OAI.Combinatorics.EditApproximation.Geometry.SeedFactorSchedule + +namespace OAI + +/-! The actual pass/index count and the exponents in the dependency-path +bound. These statements concern computed numbers, independently of the +proof that an evaluator satisfies the dependency budgets. -/ + +namespace EditApproximation + +open Filter +open scoped Topology + +theorem le_fourth_root_of_fourth_power_le {x y : ℝ} (h : x ^ 4 ≤ y) : + x ≤ Real.sqrt (Real.sqrt y) := by + apply Real.le_sqrt_of_sq_le + apply Real.le_sqrt_of_sq_le + simpa only [← pow_mul] using h + +theorem warmup_smallLog_square_div_height_tendsto : + Tendsto (fun N => ((integerParameters N).T : ℝ) * (inputSmallLog N : ℝ) ^ 2 / + inputHeight N) atTop (𝓝 0) := by + have hupper : Tendsto (fun N => Real.sqrt (Real.sqrt + (16 * ((inputSmallLog N : ℝ) ^ 8 / inputHeight N)))) atTop (𝓝 0) := by + simpa only [mul_zero, Real.sqrt_zero] using + ((smallLog_polynomial_div_height_tendsto 8).const_mul 16).sqrt.sqrt + apply squeeze_zero' (Eventually.of_forall fun N => by positivity) _ hupper + apply Eventually.of_forall + intro N + apply le_fourth_root_of_fourth_power_le + have hH : (0 : ℝ) < inputHeight N := by exact_mod_cast Nat.two_pow_pos (heightExponent N) + have hT : ((integerParameters N).T : ℝ) ^ 4 ≤ 16 * (inputHeight N : ℝ) ^ 3 := by + exact_mod_cast (computed_warmup_count_power N).2 + have hmul := mul_le_mul_of_nonneg_right hT + (pow_nonneg (Nat.cast_nonneg (inputSmallLog N)) 8) + rw [div_pow, mul_pow, ← pow_mul] + apply (div_le_iff₀ (pow_pos hH 4)).2 + calc + ((integerParameters N).T : ℝ) ^ 4 * (inputSmallLog N : ℝ) ^ 8 ≤ + 16 * (inputHeight N : ℝ) ^ 3 * (inputSmallLog N : ℝ) ^ 8 := hmul + _ = (16 * ((inputSmallLog N : ℝ) ^ 8 / inputHeight N)) * + (inputHeight N : ℝ) ^ 4 := by field_simp [hH.ne'] + +theorem computed_warmup_le_refinement_eventually : + ∀ᶠ N in atTop, (integerParameters N).T ≤ (integerParameters N).S ∧ + 1 ≤ (integerParameters N).S := by + have hratio := warmup_smallLog_square_div_height_tendsto.eventually + (gt_mem_nhds (by norm_num : (0 : ℝ) < 1)) + filter_upwards [hratio, eventually_ge_atTop 1, + inputSmallLog_tendsto.eventually (eventually_ge_atTop (2 ^ 1000))] with N hratio hN hell + have hcount := computed_refinement_count_exact N hN hell + have hH : (0 : ℝ) < inputHeight N := by exact_mod_cast Nat.two_pow_pos (heightExponent N) + have hproduct : ((integerParameters N).T : ℝ) * (inputSmallLog N : ℝ) ^ 2 < inputHeight N := + (div_lt_one hH).1 hratio + have hT : (integerParameters N).T < (integerParameters N).S := by + have hproductN : (integerParameters N).T * inputSmallLog N ^ 2 < inputHeight N := by + exact_mod_cast hproduct + rw [← hcount] at hproductN + exact Nat.lt_of_mul_lt_mul_right hproductN + exact ⟨hT.le, by omega⟩ + +theorem computed_warmup_div_refinement_tendsto : + Tendsto (fun N => ((integerParameters N).T : ℝ) / (integerParameters N).S) + atTop (𝓝 0) := by + apply warmup_smallLog_square_div_height_tendsto.congr' + filter_upwards [eventually_ge_atTop 1, + inputSmallLog_tendsto.eventually (eventually_ge_atTop (2 ^ 1000))] with N hN hell + rw [computed_refinement_count_real N hN hell] + have hH : (0 : ℝ) < inputHeight N := by exact_mod_cast Nat.two_pow_pos (heightExponent N) + have hellpos : (0 : ℝ) < inputSmallLog N := by exact_mod_cast Nat.two_pow_pos (smallLogExponent N) + field_simp [hH.ne', hellpos.ne'] + +theorem scalar_pass_count_bound (p e ell f K : ℝ) + (hp : 0 ≤ p) (hf : 4 ≤ f) (helf : f ≤ ell) (heel : e ≤ ell) + (hK : K ≤ (p + 4) * e / (f - 2) + 2) : + K ≤ 10 * (p + 1) * ell / f := by + have hfpos : 0 < f := by linarith + have hden : 0 < f - 2 := by linarith + have hqell : 0 ≤ (p + 1) * ell := mul_nonneg (by linarith) (by linarith) + have hnum : (p + 4) * e ≤ 4 * (p + 1) * ell := by + have h := mul_le_mul_of_nonneg_left heel (by linarith : 0 ≤ p + 4) + nlinarith [mul_nonneg hp (show 0 ≤ ell by linarith)] + have hmain : (p + 4) * e / (f - 2) ≤ 8 * (p + 1) * ell / f := by + apply (div_le_div_iff₀ hden hfpos).2 + have hnumf := mul_le_mul_of_nonneg_right hnum hfpos.le + have hslack := mul_nonneg hqell (show 0 ≤ f - 4 by linarith) + nlinarith + have hconst : 2 ≤ 2 * (p + 1) * ell / f := by + apply (le_div_iff₀ hfpos).2 + nlinarith [mul_nonneg hp (show 0 ≤ ell by linarith)] + calc + K ≤ (p + 4) * e / (f - 2) + 2 := hK + _ ≤ 8 * (p + 1) * ell / f + 2 * (p + 1) * ell / f := add_le_add hmain hconst + _ = 10 * (p + 1) * ell / f := by ring + +theorem computed_pass_count_bound (N : ℕ) (hN : 0 < N) (hf : 4 ≤ smallLogExponent N) : + (computedSeedPassCount N + 1 : ℝ) ≤ + 10 * ((coarseExponent (inputSmallLog N) : ℝ) + 1) * inputSmallLog N / smallLogExponent N := by + apply scalar_pass_count_bound (e := (heightExponent N : ℝ)) + · exact Nat.cast_nonneg _ + · exact_mod_cast hf + · have h := (Nat.lt_pow_self (by decide : 1 < (2 : ℕ)) (n := smallLogExponent N)).le + exact_mod_cast h + · exact_mod_cast (inputSmallLog_bounds N hN).1 + · have hraw := dyadicSeedPassCount_le (smallLogExponent N) (computedSeedInitialExponent N) (by omega) + have hcast : (computedSeedPassCount N : ℝ) ≤ + ((computedSeedInitialExponent N / (smallLogExponent N - 2) : ℕ) : ℝ) + 1 := by + exact_mod_cast hraw + have hdiv : ((computedSeedInitialExponent N / (smallLogExponent N - 2) : ℕ) : ℝ) ≤ + (computedSeedInitialExponent N : ℝ) / (smallLogExponent N - 2 : ℕ) := Nat.cast_div_le + have hden : ((smallLogExponent N - 2 : ℕ) : ℝ) = (smallLogExponent N : ℝ) - 2 := by + rw [Nat.cast_sub (by omega : 2 ≤ smallLogExponent N)] + norm_num + rw [hden] at hdiv + have hexp : (computedSeedInitialExponent N : ℝ) = + ((coarseExponent (inputSmallLog N) : ℝ) + 4) * heightExponent N := by + simp only [computedSeedInitialExponent, Nat.cast_mul, Nat.cast_add, Nat.cast_ofNat] + rw [hexp] at hdiv + linarith + +def computedDependencyIndexCount (N : ℕ) : ℕ := + (computedSeedPassCount N + 1) * ((integerParameters N).T + (integerParameters N).S + 1) + +theorem scalar_dependency_index_bound (p ell f H S T K : ℝ) + (hell : 0 < ell) (hf : 0 < f) (hS : 1 ≤ S) (hT : T ≤ S) + (hK : 0 ≤ K) (hcount : S * ell ^ 2 = H) + (hpass : K ≤ 10 * (p + 1) * ell / f) : + K * (T + S + 1) ≤ 30 * H * (p + 1) / (ell * f) := by + calc + K * (T + S + 1) ≤ K * (3 * S) := mul_le_mul_of_nonneg_left (by linarith) hK + _ ≤ (10 * (p + 1) * ell / f) * (3 * S) := + mul_le_mul_of_nonneg_right hpass (by linarith) + _ = 30 * H * (p + 1) / (ell * f) := by + rw [← hcount] + field_simp [hell.ne', hf.ne'] + ring + +theorem computed_dependency_index_bound_eventually : + ∀ᶠ N in atTop, (computedDependencyIndexCount N : ℝ) ≤ + 30 * (inputHeight N : ℝ) * ((coarseExponent (inputSmallLog N) : ℝ) + 1) / + ((inputSmallLog N : ℝ) * smallLogExponent N) := by + filter_upwards [computed_warmup_le_refinement_eventually, eventually_ge_atTop 1, + inputSmallLog_tendsto.eventually (eventually_ge_atTop (2 ^ 1000)), + smallLogExponent_tendsto.eventually (eventually_ge_atTop 4)] with N htime hN hell hf + have h := scalar_dependency_index_bound + (coarseExponent (inputSmallLog N)) (inputSmallLog N) (smallLogExponent N) + (inputHeight N) ((integerParameters N).S) ((integerParameters N).T) + (computedSeedPassCount N + 1) + (by exact_mod_cast Nat.two_pow_pos (smallLogExponent N)) + (by exact_mod_cast (show 0 < smallLogExponent N by omega)) + (by exact_mod_cast htime.2) (by exact_mod_cast htime.1) (by positivity) + (by exact_mod_cast computed_refinement_count_exact N hN hell) + (computed_pass_count_bound N hN hf) + simpa only [computedDependencyIndexCount, Nat.cast_mul, Nat.cast_add, Nat.cast_one] using h + +theorem coarse_shifted_square_div_smallExponent_tendsto : + Tendsto (fun N => ((coarseExponent (inputSmallLog N) : ℝ) + 1) ^ 2 / + smallLogExponent N) atTop (𝓝 0) := by + have h := coarse_shifted_square_div_log_tendsto.const_mul (Real.log 2) + simp only [mul_zero] at h + apply h.congr' + filter_upwards [smallLogExponent_tendsto.eventually (eventually_ge_atTop 1)] with N hf + rw [inputSmallLog_real_log] + have hfn : (smallLogExponent N : ℝ) ≠ 0 := by exact_mod_cast (show smallLogExponent N ≠ 0 by omega) + have hc : Real.log 2 ≠ 0 := (Real.log_pos (by norm_num : (1 : ℝ) < 2)).ne' + field_simp [hfn, hc] + +theorem scalar_weighted_dependency_bound (q k e ell f H c : ℝ) + (hq : 0 ≤ q) (hk : 0 ≤ k) (heel : e ≤ ell) + (hell : 0 < ell) (hf : 0 < f) (hH : 0 < H) (hc : 0 ≤ c) + (hbound : k ≤ 30 * H * q / (ell * f)) : + q * k * (e * c) / H ≤ 30 * c * q ^ 2 / f := by + have hproduct : k * (ell * f) ≤ 30 * H * q := + (le_div_iff₀ (mul_pos hell hf)).1 hbound + apply (div_le_div_iff₀ hH hf).2 + calc + q * k * (e * c) * f = k * (e * f) * (q * c) := by ring + _ ≤ k * (ell * f) * (q * c) := by + apply mul_le_mul_of_nonneg_right _ (mul_nonneg hq hc) + exact mul_le_mul_of_nonneg_left (mul_le_mul_of_nonneg_right heel hf.le) hk + _ ≤ (30 * H * q) * (q * c) := mul_le_mul_of_nonneg_right hproduct (mul_nonneg hq hc) + _ = 30 * c * q ^ 2 * H := by ring + +/-- The exponent of the earlier-index branching factor is `o(H)`. -/ +theorem weighted_dependency_div_height_tendsto : + Tendsto (fun N => ((coarseExponent (inputSmallLog N) : ℝ) + 1) * + computedDependencyIndexCount N * Real.log (inputHeight N : ℝ) / inputHeight N) + atTop (𝓝 0) := by + have hupper := coarse_shifted_square_div_smallExponent_tendsto.const_mul (30 * Real.log 2) + simp only [mul_zero] at hupper + apply squeeze_zero' (Eventually.of_forall fun N => by + apply div_nonneg + · apply mul_nonneg (by positivity) + apply Real.log_nonneg + exact_mod_cast Nat.one_le_two_pow (n := heightExponent N) + · exact Nat.cast_nonneg _) _ hupper + filter_upwards [computed_dependency_index_bound_eventually, eventually_ge_atTop 1, + smallLogExponent_tendsto.eventually (eventually_ge_atTop 1)] with N hbound hN hf + have hlog : Real.log (inputHeight N : ℝ) = (heightExponent N : ℝ) * Real.log 2 := by + simp only [inputHeight, Nat.cast_pow, Nat.cast_ofNat, Real.log_pow] + rw [hlog] + simpa only [mul_div_assoc] using scalar_weighted_dependency_bound + ((coarseExponent (inputSmallLog N) : ℝ) + 1) (computedDependencyIndexCount N) + (heightExponent N) (inputSmallLog N) (smallLogExponent N) (inputHeight N) (Real.log 2) + (by positivity) (Nat.cast_nonneg _) + (by exact_mod_cast (inputSmallLog_bounds N hN).1) + (by exact_mod_cast Nat.two_pow_pos (smallLogExponent N)) + (by exact_mod_cast (show 0 < smallLogExponent N by omega)) + (by exact_mod_cast Nat.two_pow_pos (heightExponent N)) + (Real.log_nonneg (by norm_num)) hbound + +def computedMaxTreeDepth (N : ℕ) : ℕ := intervalTreeDepth (integerParameters N).M N + +theorem intervalTreeDepth_le_computedMax (N nx : ℕ) (hnx : nx ≤ N) : + intervalTreeDepth (integerParameters N).M nx ≤ computedMaxTreeDepth N := + Nat.clog_mono_right _ (max_le_max le_rfl hnx) + +/-- A uniform depth upper bound is obtained by using the total length as +the source length. -/ +theorem tree_logSmallLog_div_height_tendsto : + Tendsto (fun N => (computedMaxTreeDepth N : ℝ) * + Real.log (inputSmallLog N : ℝ) / inputHeight N) atTop (𝓝 0) := by + have hupper := log_smallLog_div_smallLog_tendsto.const_mul 100 + simp only [mul_zero] at hupper + apply squeeze_zero' (Eventually.of_forall fun N => by + apply div_nonneg + · apply mul_nonneg (Nat.cast_nonneg _) + apply Real.log_nonneg + exact_mod_cast Nat.one_le_two_pow (n := smallLogExponent N) + · exact Nat.cast_nonneg _) _ hupper + filter_upwards [eventually_ge_atTop 1, + inputSmallLog_tendsto.eventually (eventually_ge_atTop 200)] with N hN hell + have hbound : (computedMaxTreeDepth N : ℝ) * inputSmallLog N ≤ 100 * (inputHeight N : ℝ) := by + exact_mod_cast computed_tree_depth_bound N N hN le_rfl hell + have hlog : 0 ≤ Real.log (inputSmallLog N : ℝ) := by + apply Real.log_nonneg + exact_mod_cast Nat.one_le_two_pow (n := smallLogExponent N) + have hH : (0 : ℝ) < inputHeight N := by exact_mod_cast Nat.two_pow_pos (heightExponent N) + have hellpos : (0 : ℝ) < inputSmallLog N := by exact_mod_cast Nat.two_pow_pos (smallLogExponent N) + have hscaled := mul_le_mul_of_nonneg_right hbound hlog + rw [← mul_div_assoc] + apply (div_le_div_iff₀ hH hellpos).2 + nlinarith only [hscaled] + +theorem tree_depth_div_height_tendsto : + Tendsto (fun N => (computedMaxTreeDepth N : ℝ) / inputHeight N) atTop (𝓝 0) := by + apply squeeze_zero' (Eventually.of_forall fun N => div_nonneg (Nat.cast_nonneg _) (Nat.cast_nonneg _)) + _ tree_logSmallLog_div_height_tendsto + filter_upwards [(Real.tendsto_log_atTop.comp inputSmallLog_real_tendsto).eventually + (eventually_ge_atTop 1)] with N hlog + apply div_le_div_of_nonneg_right _ (Nat.cast_nonneg _) + exact le_mul_of_one_le_right (Nat.cast_nonneg _) hlog + +theorem dependency_index_div_height_tendsto : + Tendsto (fun N => (computedDependencyIndexCount N : ℝ) / inputHeight N) atTop (𝓝 0) := by + apply squeeze_zero' (Eventually.of_forall fun N => div_nonneg (Nat.cast_nonneg _) (Nat.cast_nonneg _)) + _ weighted_dependency_div_height_tendsto + filter_upwards [(Real.tendsto_log_atTop.comp inputHeight_real_tendsto).eventually + (eventually_ge_atTop 1)] with N hlog + apply div_le_div_of_nonneg_right _ (Nat.cast_nonneg _) + calc + (computedDependencyIndexCount N : ℝ) ≤ + ((coarseExponent (inputSmallLog N) : ℝ) + 1) * computedDependencyIndexCount N := by + have hm : (0 : ℝ) ≤ (coarseExponent (inputSmallLog N) : ℝ) * computedDependencyIndexCount N := + mul_nonneg (Nat.cast_nonneg _) (Nat.cast_nonneg _) + nlinarith only [hm] + _ ≤ _ := le_mul_of_one_le_right (by positivity) hlog + +noncomputable def computedDependencyOverheadExponent (C₁ C₂ : ℝ) (N : ℕ) : ℝ := + (1 + Real.log 2) * ((computedMaxTreeDepth N : ℝ) + computedDependencyIndexCount N + 2) + + C₁ * computedMaxTreeDepth N * Real.log (inputSmallLog N : ℝ) + + C₂ * ((coarseExponent (inputSmallLog N) : ℝ) + 1) * computedDependencyIndexCount N * + Real.log (inputHeight N : ℝ) + +/-- Every fixed choice of the two branching-budget constants yields a +sublinear logarithmic overhead in the dependency-path bound. -/ +theorem computedDependencyOverheadExponent_tendsto (C₁ C₂ : ℝ) : + Tendsto (fun N => computedDependencyOverheadExponent C₁ C₂ N / inputHeight N) + atTop (𝓝 0) := by + have htwo : Tendsto (fun N => 2 / (inputHeight N : ℝ)) atTop (𝓝 0) := by + simpa only [Pi.inv_apply, mul_zero, div_eq_mul_inv] using inputHeight_real_tendsto.inv_tendsto_atTop.const_mul 2 + have h := (((tree_depth_div_height_tendsto.add dependency_index_div_height_tendsto).add htwo).const_mul + (1 + Real.log 2)).add ((tree_logSmallLog_div_height_tendsto.const_mul C₁).add + (weighted_dependency_div_height_tendsto.const_mul C₂)) + simp only [zero_add, mul_zero] at h + convert h using 1 + ext N + unfold computedDependencyOverheadExponent + ring + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/ParameterLocalAsymptotics.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/ParameterLocalAsymptotics.lean new file mode 100644 index 0000000000000000000000000000000000000000..39387f71c49a5bf4646a61a48e4c352aea531ac2 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/ParameterLocalAsymptotics.lean @@ -0,0 +1,165 @@ +import OAI.Combinatorics.EditApproximation.Geometry.ParameterAsymptotics + +namespace OAI + +/-! Scalar bounds for the local enumeration exponent. -/ + +namespace EditApproximation + +open Filter +open scoped Topology + +theorem inputHeight_real_tendsto : + Tendsto (fun N => (inputHeight N : ℝ)) atTop atTop := by + simpa only [inputHeight, Nat.cast_pow, Nat.cast_ofNat, Function.comp_def] using + (tendsto_pow_atTop_atTop_of_one_lt (by norm_num : (1 : ℝ) < 2)).comp heightExponent_tendsto + +/-- Every fixed polynomial in the computed small logarithm is negligible +relative to the computed height. -/ +theorem smallLog_polynomial_div_height_tendsto (k : ℕ) : + Tendsto (fun N => (inputSmallLog N : ℝ) ^ k / inputHeight N) atTop (𝓝 0) := by + have hupper : Tendsto (fun N => (2 : ℝ) ^ k * + ((heightExponent N : ℝ) ^ k / (2 : ℝ) ^ heightExponent N)) atTop (𝓝 0) := by + simpa only [Function.comp_def, mul_zero] using + ((tendsto_pow_const_div_const_pow_of_one_lt k (by norm_num : (1 : ℝ) < 2)).comp + heightExponent_tendsto).const_mul ((2 : ℝ) ^ k) + apply squeeze_zero' (Eventually.of_forall fun N => + div_nonneg (pow_nonneg (Nat.cast_nonneg _) _) (Nat.cast_nonneg _)) _ hupper + filter_upwards [eventually_ge_atTop 1] with N hN + have hbound : (inputSmallLog N : ℝ) ≤ 2 * (heightExponent N : ℝ) := by + exact_mod_cast (inputSmallLog_bounds N hN).2.le + have hpower := pow_le_pow_left₀ (Nat.cast_nonneg (inputSmallLog N)) hbound k + simpa only [inputHeight, Nat.cast_pow, Nat.cast_ofNat, mul_pow, mul_div_assoc] using + div_le_div_of_nonneg_right hpower (by positivity : (0 : ℝ) ≤ 2 ^ heightExponent N) + +theorem computed_branching_square_le_height (N : ℕ) : + ((integerParameters N).M : ℝ) ^ 2 ≤ inputHeight N := by + have hexponent : heightExponent N / 20 * 2 ≤ heightExponent N := by omega + have h := pow_le_pow_right₀ (by norm_num : (1 : ℝ) ≤ 2) hexponent + simpa only [integerParameters, inputHeight, Nat.cast_pow, Nat.cast_ofNat, ← pow_mul] using h + +/-- This directly controls the scalar exponent `M q ell` occurring in the +local wide-action enumeration. -/ +theorem branching_smallLog_polynomial_div_height_tendsto (k : ℕ) : + Tendsto (fun N => ((integerParameters N).M : ℝ) * + (inputSmallLog N : ℝ) ^ k / inputHeight N) atTop (𝓝 0) := by + have hupper : Tendsto (fun N => Real.sqrt + ((inputSmallLog N : ℝ) ^ (2 * k) / inputHeight N)) atTop (𝓝 0) := by + simpa only [Real.sqrt_zero] using (smallLog_polynomial_div_height_tendsto (2 * k)).sqrt + apply squeeze_zero' (Eventually.of_forall fun N => + div_nonneg (mul_nonneg (Nat.cast_nonneg _) (pow_nonneg (Nat.cast_nonneg _) _)) + (Nat.cast_nonneg _)) _ hupper + apply Eventually.of_forall + intro N + apply Real.le_sqrt_of_sq_le + have hH : (0 : ℝ) < inputHeight N := by + exact_mod_cast Nat.two_pow_pos (heightExponent N) + have hM := computed_branching_square_le_height N + have hproduct := mul_le_mul_of_nonneg_right hM + (pow_nonneg (Nat.cast_nonneg (inputSmallLog N)) (2 * k)) + rw [div_pow, mul_pow, ← pow_mul, Nat.mul_comm k 2] + apply (div_le_iff₀ (sq_pos_of_pos hH)).2 + calc + ((integerParameters N).M : ℝ) ^ 2 * (inputSmallLog N : ℝ) ^ (2 * k) ≤ + (inputHeight N : ℝ) * (inputSmallLog N : ℝ) ^ (2 * k) := hproduct + _ = ((inputSmallLog N : ℝ) ^ (2 * k) / inputHeight N) * + (inputHeight N : ℝ) ^ 2 := by field_simp [hH.ne'] + +theorem coarseExponent_le_smallLog (N : ℕ) : + coarseExponent (inputSmallLog N) ≤ inputSmallLog N := by + have h := coarseExponent_fourth_power (inputSmallLog N) + have hp : coarseExponent (inputSmallLog N) ≤ coarseExponent (inputSmallLog N) ^ 4 := by + exact Nat.le_pow (by decide : 0 < 4) + exact hp.trans (h.trans (Nat.log_le_self 2 _)) + +theorem local_enumeration_exponent_div_height_tendsto : + Tendsto (fun N => ((integerParameters N).M : ℝ) * + ((coarseExponent (inputSmallLog N) : ℝ) + 1) * inputSmallLog N / inputHeight N) + atTop (𝓝 0) := by + have hupper := (branching_smallLog_polynomial_div_height_tendsto 2).const_mul 2 + simp only [mul_zero] at hupper + apply squeeze_zero' (Eventually.of_forall fun N => by positivity) _ hupper + apply Eventually.of_forall + intro N + have hell : (1 : ℝ) ≤ inputSmallLog N := by + exact_mod_cast Nat.one_le_two_pow (n := smallLogExponent N) + have hp : (coarseExponent (inputSmallLog N) : ℝ) ≤ inputSmallLog N := by + exact_mod_cast coarseExponent_le_smallLog N + have hq : (coarseExponent (inputSmallLog N) : ℝ) + 1 ≤ 2 * inputSmallLog N := by linarith + have hprod := mul_le_mul_of_nonneg_left + (mul_le_mul_of_nonneg_right hq (Nat.cast_nonneg (inputSmallLog N))) + (Nat.cast_nonneg (integerParameters N).M) + have hdiv := div_le_div_of_nonneg_right hprod (Nat.cast_nonneg (inputHeight N)) + convert hdiv using 1 <;> ring + +theorem inputHeight_real_log (N : ℕ) : + Real.log (inputHeight N : ℝ) = (heightExponent N : ℝ) * Real.log 2 := by + simp only [inputHeight, Nat.cast_pow, Nat.cast_ofNat, Real.log_pow] + +theorem encoding_exponent_div_height_tendsto : + Tendsto (fun N => ((coarseExponent (inputSmallLog N) : ℝ) + 1) * + Real.log (inputHeight N : ℝ) / inputHeight N) atTop (𝓝 0) := by + have hupper := (smallLog_polynomial_div_height_tendsto 2).const_mul (2 * Real.log 2) + simp only [mul_zero] at hupper + apply squeeze_zero' (Eventually.of_forall fun N => by + apply div_nonneg + · apply mul_nonneg (by positivity) + apply Real.log_nonneg + exact_mod_cast Nat.one_le_two_pow (n := heightExponent N) + · exact Nat.cast_nonneg _) _ hupper + filter_upwards [eventually_ge_atTop 1] with N hN + have hp : (coarseExponent (inputSmallLog N) : ℝ) ≤ inputSmallLog N := by + exact_mod_cast coarseExponent_le_smallLog N + have hell : (1 : ℝ) ≤ inputSmallLog N := by exact_mod_cast Nat.one_le_two_pow (n := smallLogExponent N) + have hq : (coarseExponent (inputSmallLog N) : ℝ) + 1 ≤ 2 * inputSmallLog N := by linarith + have he : (heightExponent N : ℝ) ≤ inputSmallLog N := by + exact_mod_cast (inputSmallLog_bounds N hN).1 + have hprod := mul_le_mul hq he (Nat.cast_nonneg _) (by positivity : (0 : ℝ) ≤ 2 * inputSmallLog N) + have hlog := mul_le_mul_of_nonneg_right hprod (Real.log_nonneg (by norm_num : (1 : ℝ) ≤ 2)) + rw [inputHeight_real_log] + have hdiv := div_le_div_of_nonneg_right hlog (Nat.cast_nonneg (inputHeight N)) + convert hdiv using 1 <;> ring + +theorem height_log_sandwich (N : ℕ) (hN : 0 < N) : + Real.log (N + 2 : ℝ) / Real.log 2 ≤ inputHeight N ∧ + (inputHeight N : ℝ) ≤ (4 / Real.log 2) * Real.log (N + 2 : ℝ) := by + have hlogtwo : 0 < Real.log 2 := Real.log_pos (by norm_num) + have hcover : (N + 2 : ℝ) ≤ (2 : ℝ) ^ inputHeight N := by + exact_mod_cast inputHeight_covers_length N + have hlower := Real.log_le_log (by positivity : (0 : ℝ) < N + 2) hcover + rw [Real.log_pow] at hlower + have hL : 1 < Nat.clog 2 (N + 2) := by + exact (Nat.lt_clog_iff_pow_lt (by decide : 1 < 2)).2 (by norm_num; omega) + have hpred := Nat.pow_pred_clog_lt_self (by decide : 1 < (2 : ℕ)) + (by omega : 1 < N + 2) + have hpredR : (2 : ℝ) ^ (Nat.clog 2 (N + 2)).pred < N + 2 := by exact_mod_cast hpred + have hpredlog := Real.log_lt_log (by positivity : (0 : ℝ) < 2 ^ (Nat.clog 2 (N + 2)).pred) hpredR + rw [Real.log_pow] at hpredlog + have hpredcast : ((Nat.clog 2 (N + 2)).pred : ℝ) = (Nat.clog 2 (N + 2) : ℝ) - 1 := by + have hnat : (Nat.clog 2 (N + 2)).pred + 1 = Nat.clog 2 (N + 2) := + Nat.succ_pred_eq_of_pos (by omega) + have hcast : ((Nat.clog 2 (N + 2)).pred : ℝ) + 1 = (Nat.clog 2 (N + 2) : ℝ) := by + exact_mod_cast hnat + linarith + rw [hpredcast] at hpredlog + have hH : (inputHeight N : ℝ) < 2 * (Nat.clog 2 (N + 2) : ℝ) := by + have h := (rejectionWord_range (Nat.clog 2 (N + 2)) (by omega)).2 + simpa only [inputHeight, heightExponent, rejectionBitCount, Nat.cast_pow, + Nat.cast_mul, Nat.cast_ofNat] using (Nat.cast_lt.mpr h : + ((2 ^ rejectionBitCount (Nat.clog 2 (N + 2)) : ℕ) : ℝ) < + ((2 * Nat.clog 2 (N + 2) : ℕ) : ℝ)) + have hlogN : Real.log 2 ≤ Real.log (N + 2 : ℝ) := + Real.log_le_log (by norm_num) (by exact_mod_cast (by omega : 2 ≤ N + 2)) + constructor + · exact (div_le_iff₀ hlogtwo).2 hlower + · have hproduct : (inputHeight N : ℝ) * Real.log 2 ≤ 4 * Real.log (N + 2 : ℝ) := by + have hmul := mul_le_mul_of_nonneg_right hH.le hlogtwo.le + nlinarith + calc + (inputHeight N : ℝ) ≤ (4 * Real.log (N + 2 : ℝ)) / Real.log 2 := + (le_div_iff₀ hlogtwo).2 hproduct + _ = (4 / Real.log 2) * Real.log (N + 2 : ℝ) := by ring + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/ParameterNumericalConstruction.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/ParameterNumericalConstruction.lean new file mode 100644 index 0000000000000000000000000000000000000000..ece54f8cd2dd5326ddad477bee99b0b36a91687d --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/ParameterNumericalConstruction.lean @@ -0,0 +1,67 @@ +import OAI.Combinatorics.EditApproximation.Geometry.ParameterConstruction +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation + + + + @[simp] theorem rationalParametersWithWork_value (ell : ℕ) : + (rationalParametersWithWork ell).1 = rationalParameters ell := by + simp only [rationalParametersWithWork, parameterPowerWithWork_spec, rationalParameters, Nat.cast_pow] + + theorem rationalParametersWithWork_cost (ell : ℕ) : + (rationalParametersWithWork ell).2 = 183 := by + simp only [rationalParametersWithWork, parameterPowerWithWork_spec] + + + + @[simp] theorem onlineMassWithWork_value (M P H : ℕ) : + (onlineMassWithWork M P H).1 = localOnlineMassBound M P H := by + simp only [onlineMassWithWork, parameterPowerWithWork_spec, localOnlineMassBound] + rw [← optimizerTriangularMass_twice, Nat.mul_div_cancel_left _ (by decide : 0 < 2)] + + theorem onlineMassWithWork_cost (M P H : ℕ) : + (onlineMassWithWork M P H).2 = 175 := by + simp only [onlineMassWithWork, parameterPowerWithWork_spec] + + + + theorem globalParameterWork_le (N : ℕ) : + globalParameterWork N ≤ 2000 * (inputHeight N + 1) := by + have h := integerParametersWithWork_cost N + simp only [globalParameterWork, rationalParametersWithWork_cost, onlineMassWithWork_cost] + omega + + theorem globalParameterWork_near_linear (epsilon : ℝ) (hepsilon : 0 < epsilon) : + ∀ᶠ N : ℕ in Filter.atTop, + (globalParameterWork N : ℝ) ≤ (N + 2 : ℝ) ^ (1 + epsilon) := by + filter_upwards [fixed_height_power_near_linear 2 epsilon hepsilon, + inputSmallLog_tendsto.eventually (Filter.eventually_ge_atTop 4000)] with N ht hH + have hheight : 4000 ≤ inputHeight N := hH.trans (computed_smallLog_le_height N) + have hscalar0 : 2000 * (inputHeight N + 1) ≤ inputHeight N ^ 2 := by + nlinarith only [hheight] + have hscalar : 2000 * (inputHeight N + 1) ≤ (N + 2) * inputHeight N ^ 2 := + hscalar0.trans (Nat.le_mul_of_pos_left _ (by omega)) + have hb : globalParameterWork N ≤ (N + 2) * inputHeight N ^ 2 := + (globalParameterWork_le N).trans hscalar + exact (show (globalParameterWork N : ℝ) ≤ (N + 2 : ℝ) * (inputHeight N : ℝ) ^ 2 by + exact_mod_cast hb).trans ht + + theorem triangularMass_word_cap (K W : ℕ) + (hcap : Nat.size (optimizerTriangularMass K) ≤ W) : K * (K + 1) < 2 ^ (W + 1) := by + have h := Nat.size_le.mp hcap + rw [← optimizerTriangularMass_twice, pow_succ] + omega + + theorem onlineMass_intermediate_word_cap (M P H W : ℕ) + (hcap : Nat.size (localOnlineMassBound M P H) ≤ W) : + ((H + M * (40 * P + 2) ^ 2 + 2) ^ 80) * + ((H + M * (40 * P + 2) ^ 2 + 2) ^ 80 + 1) < 2 ^ (W + 1) := + triangularMass_word_cap _ W hcap + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/ParameterSlack.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/ParameterSlack.lean new file mode 100644 index 0000000000000000000000000000000000000000..2a97481310bb14aa5b3ad42de482f40a8e7ae5f6 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/ParameterSlack.lean @@ -0,0 +1,168 @@ +import OAI.Combinatorics.EditApproximation.Geometry.TreeAccounting + +namespace OAI + +/-! +# Explicit slack at the large-input cutoff + +The cutoff is handled symbolically: no expression with an astronomically +large exponent is expanded. The small-growth estimate supplies the +induction step. This proves the generous polynomial-versus-binary bound +used throughout the manuscript's numerical estimates. +-/ + +namespace EditApproximation + +theorem polynomial_binary_growth_step (degree m : ℕ) + (hsize : 4 * degree ≤ 2 * m + 1) : + (2 * (m : ℝ) + 3) ^ degree ≤ 2 * (2 * (m : ℝ) + 1) ^ degree := by + let d : ℝ := 2 * m + 1 + have hd : 0 < d := by dsimp [d]; positivity + have hsizeR : 4 * (degree : ℝ) ≤ d := by + dsimp only [d] + exact_mod_cast hsize + have hsmall : (degree : ℝ) * (2 / d) ≤ 1 / 2 := by + rw [← mul_div_assoc] + apply (div_le_iff₀ hd).2 + nlinarith + have hbound : (1 + 2 / d) ^ degree ≤ 2 := + (small_growth_pow degree (by positivity) hsmall).trans (by nlinarith) + have hrew : 2 * (m : ℝ) + 3 = d * (1 + 2 / d) := by + dsimp [d] + field_simp + ring + rw [hrew, mul_pow] + have hmul := mul_le_mul_of_nonneg_left hbound (pow_nonneg hd.le degree) + simpa only [d, mul_comm] using hmul + +theorem astronomical_polynomial_bound (ell : ℕ) (hell : 2 ^ 1000 ≤ ell) : + (ell : ℝ) ^ 20000 ≤ (2 : ℝ) ^ (ell / 2) := by + let m0 : ℕ := 2 ^ 999 + have hbaseSize : (2 * (m0 : ℝ) + 1) ≤ (2 : ℝ) ^ 1001 := by + have hm0 : (m0 : ℝ) = (2 : ℝ) ^ 999 := by + simp only [m0, Nat.cast_pow, Nat.cast_ofNat] + have hone : (1 : ℝ) ≤ m0 := by rw [hm0]; exact one_le_pow₀ (by norm_num) + have hbig : (2 : ℝ) ^ 1001 = 4 * (m0 : ℝ) := by + rw [show 1001 = 999 + 2 by decide, pow_add, ← hm0] + norm_num only [pow_two] + ring + rw [hbig] + calc + 2 * (m0 : ℝ) + 1 ≤ 2 * (m0 : ℝ) + m0 := add_le_add le_rfl hone + _ = 3 * (m0 : ℝ) := by ring + _ ≤ 4 * (m0 : ℝ) := mul_le_mul_of_nonneg_right (by norm_num) + ((by norm_num : (0 : ℝ) ≤ 1).trans hone) + have hbasePower := pow_le_pow_left₀ (by positivity : 0 ≤ 2 * (m0 : ℝ) + 1) + hbaseSize 20000 + rw [← pow_mul] at hbasePower + have hexponent : 1001 * 20000 ≤ m0 := by + have hsmall : 1001 * 20000 ≤ (2 : ℕ) ^ 25 := by norm_num + exact hsmall.trans (pow_le_pow_right₀ (by decide : (1 : ℕ) ≤ 2) (by decide : 25 ≤ 999)) + have hbase : (2 * (m0 : ℝ) + 1) ^ 20000 ≤ (2 : ℝ) ^ m0 := + hbasePower.trans (pow_le_pow_right₀ (by norm_num : (1 : ℝ) ≤ 2) hexponent) + have hgrowth : ∀ m : ℕ, m0 ≤ m → (2 * (m : ℝ) + 1) ^ 20000 ≤ (2 : ℝ) ^ m := by + intro m hm + induction m, hm using Nat.le_induction with + | base => exact hbase + | succ m hm ih => + have hsize0 : 4 * 20000 ≤ 2 * m0 + 1 := by omega + have hstep := polynomial_binary_growth_step 20000 m (by omega) + calc + (2 * ((m + 1 : ℕ) : ℝ) + 1) ^ 20000 = (2 * (m : ℝ) + 3) ^ 20000 := by + congr 1 + push_cast + ring + _ ≤ 2 * (2 * (m : ℝ) + 1) ^ 20000 := hstep + _ ≤ 2 * (2 : ℝ) ^ m := mul_le_mul_of_nonneg_left ih (by norm_num) + _ = (2 : ℝ) ^ (m + 1) := by rw [pow_succ]; ring + have hcutoff : 2 ^ 1000 = 2 * m0 := by + dsimp only [m0] + rw [show 1000 = 999 + 1 by decide, pow_succ] + exact Nat.mul_comm _ _ + have hm : m0 ≤ ell / 2 := by omega + have hellR : (ell : ℝ) ≤ 2 * ((ell / 2 : ℕ) : ℝ) + 1 := by + exact_mod_cast (show ell ≤ 2 * (ell / 2) + 1 by omega) + exact (pow_le_pow_left₀ (Nat.cast_nonneg ell) hellR 20000).trans (hgrowth _ hm) + +theorem astronomical_parameter_slack (ell : ℕ) (H : ℝ) + (hell : 2 ^ 1000 ≤ ell) (hH : (2 : ℝ) ^ (ell / 2) ≤ H) : + (ell : ℝ) ^ 20000 ≤ H := + (astronomical_polynomial_bound ell hell).trans hH + +/-- The fourth-root scale has ample polynomial slack. -/ +theorem fourth_root_polynomial_slack {ell H quarterRoot : ℝ} + (hell : 1 ≤ ell) (hH : ell ^ 20000 ≤ H) + (hroot : 0 ≤ quarterRoot) (hrootPower : quarterRoot ^ 4 = H) : + ell ^ 5000 ≤ quarterRoot := by + apply (pow_le_pow_iff_left₀ (pow_nonneg (zero_le_one.trans hell) 5000) + hroot (by decide : 4 ≠ 0)).mp + rw [← pow_mul, hrootPower] + exact hH + +/-- The five explicit terms in Section 8 are collectively below `1/ell`. +Here `quarterRoot = H^(1/4)` and `q = p_*+21`. The hypotheses are small +consequences of the manuscript's large-input cutoff, not asymptotic +notation or a presumed error bound. -/ +theorem refinement_error_envelope {ell H quarterRoot q : ℝ} + (hell : 64000000000000 ≤ ell) (hH : ell ^ 2 ≤ H) + (hroot : ell ^ 4 ≤ quarterRoot) (hq : 0 ≤ q) (hqSquare : q ^ 2 ≤ ell) : + 52000 / H ^ 18 + 8040000 * ell ^ 4 / quarterRoot ^ 2 + + 200 * ell / quarterRoot + 1000000 * q / ell ^ 2 + 13200 / H ^ 2 < 1 / ell := by + have hellpos : 0 < ell := by linarith + have hellone : 1 ≤ ell := by linarith + have hHone : 1 ≤ H := (one_le_pow₀ hellone).trans hH + have hHpos : 0 < H := by linarith + have hrootpos : 0 < quarterRoot := (pow_pos hellpos 4).trans_le hroot + have hell2 : ell ≤ ell ^ 2 := by nlinarith + have hHell : ell ≤ H := hell2.trans hH + have hH18 : H ≤ H ^ 18 := by + simpa only [pow_one] using pow_le_pow_right₀ hHone (by decide : 1 ≤ 18) + have ht1 : 52000 / H ^ 18 ≤ 1 / (8 * ell) := by + apply (div_le_div_iff₀ (pow_pos hHpos 18) (by positivity : 0 < 8 * ell)).2 + have hsize : 416000 * ell ≤ ell ^ 2 := by nlinarith + nlinarith + have hrootSquare : ell ^ 8 ≤ quarterRoot ^ 2 := by + have hsq := pow_le_pow_left₀ (pow_nonneg hellpos.le 4) hroot 2 + simpa only [← pow_mul] using hsq + have hell5 : ell ^ 5 ≤ ell ^ 7 := pow_le_pow_right₀ hellone (by decide : 5 ≤ 7) + have hsecondPower : 64320000 * ell ^ 5 ≤ ell ^ 8 := by + have hcoef : 64320000 ≤ ell := by linarith + have hmul := mul_le_mul_of_nonneg_right hcoef (pow_nonneg hellpos.le 7) + have hfirst := mul_le_mul_of_nonneg_left hell5 (by norm_num : (0 : ℝ) ≤ 64320000) + nlinarith [show ell * ell ^ 7 = ell ^ 8 by ring] + have ht2 : 8040000 * ell ^ 4 / quarterRoot ^ 2 ≤ 1 / (8 * ell) := by + apply (div_le_div_iff₀ (pow_pos hrootpos 2) (by positivity : 0 < 8 * ell)).2 + have hid : (8040000 * ell ^ 4) * (8 * ell) = 64320000 * ell ^ 5 := by ring + rw [hid, one_mul] + exact hsecondPower.trans hrootSquare + have hsmallPower : 1600 * ell ^ 2 ≤ ell ^ 4 := by + have hcoef : (1600 : ℝ) ≤ ell ^ 2 := by nlinarith + have hmul := mul_le_mul_of_nonneg_right hcoef (sq_nonneg ell) + nlinarith [show ell ^ 2 * ell ^ 2 = ell ^ 4 by ring] + have ht3 : 200 * ell / quarterRoot ≤ 1 / (8 * ell) := by + apply (div_le_div_iff₀ hrootpos (by positivity : 0 < 8 * ell)).2 + nlinarith [hsmallPower.trans hroot] + have hqScale : 8000000 * q ≤ ell := by + have hsq : (8000000 * q) ^ 2 ≤ ell ^ 2 := by + have ha := mul_le_mul_of_nonneg_left hqSquare (by norm_num : (0 : ℝ) ≤ 8000000 ^ 2) + have hb := mul_le_mul_of_nonneg_right hell hellpos.le + nlinarith + exact (sq_le_sq₀ (by positivity : 0 ≤ 8000000 * q) hellpos.le).mp hsq + have ht4 : 1000000 * q / ell ^ 2 ≤ 1 / (8 * ell) := by + apply (div_le_div_iff₀ (pow_pos hellpos 2) (by positivity : 0 < 8 * ell)).2 + have hmul := mul_le_mul_of_nonneg_right hqScale hellpos.le + nlinarith + have ht5 : 13200 / H ^ 2 ≤ 1 / (8 * ell) := by + apply (div_le_div_iff₀ (pow_pos hHpos 2) (by positivity : 0 < 8 * ell)).2 + have hsq := pow_le_pow_left₀ hellpos.le hHell 2 + have hsize : 105600 * ell ≤ ell ^ 2 := by nlinarith + nlinarith + have hstrict : 5 * (1 / (8 * ell)) < 1 / ell := by + rw [mul_one_div] + apply (div_lt_div_iff₀ (by positivity : 0 < 8 * ell) hellpos).2 + nlinarith + linarith + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/Parameters.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/Parameters.lean new file mode 100644 index 0000000000000000000000000000000000000000..4a06aaab469d8cd06a21e027218cf7496ff96eb8 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/Parameters.lean @@ -0,0 +1,126 @@ +import OAI.Combinatorics.EditApproximation.Geometry.ParameterSlack +import OAI.Combinatorics.EditApproximation.Probability.ExactSampling +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! +# Integer-computed parameters + +The logarithms and fourth roots in Section 2 are computed by natural bit +lengths and nested integer square roots. No real arithmetic oracle is +used to form the algorithm's parameters. +-/ + +namespace EditApproximation + + + + + + + + + + + + + + + + +theorem heightExponent_pos (N : ℕ) (hN : 0 < N) : 0 < heightExponent N := by + apply Nat.clog_pos (by decide) + have hlog : 1 < Nat.clog 2 (N + 2) := by + exact (Nat.lt_clog_iff_pow_lt (by decide : 1 < 2)).2 (by norm_num; omega) + exact hlog + +theorem inputHeight_covers_length (N : ℕ) : N + 2 ≤ 2 ^ inputHeight N := by + have hlog := Nat.le_pow_clog (by decide : 1 < 2) (N + 2) + have hheight := Nat.le_pow_clog (by decide : 1 < 2) (Nat.clog 2 (N + 2)) + exact hlog.trans (pow_le_pow_right₀ (by decide : 1 ≤ (2 : ℕ)) hheight) + +theorem inputSmallLog_bounds (N : ℕ) (hN : 0 < N) : + heightExponent N ≤ inputSmallLog N ∧ inputSmallLog N < 2 * heightExponent N := by + have hpos := heightExponent_pos N hN + have hone : 1 ≤ heightExponent N := hpos + have hrange := rejectionWord_range (heightExponent N) hpos + simpa only [inputSmallLog, smallLogExponent, rejectionBitCount, max_eq_right hone] using hrange + +theorem inputHeight_binary_slack (N : ℕ) (hN : 0 < N) : + (2 : ℝ) ^ (inputSmallLog N / 2) ≤ inputHeight N := by + have hlogs := inputSmallLog_bounds N hN + have hexponent : inputSmallLog N / 2 ≤ heightExponent N := by omega + have hpower := pow_le_pow_right₀ (by norm_num : (1 : ℝ) ≤ 2) hexponent + simpa only [inputHeight, Nat.cast_pow, Nat.cast_ofNat] using hpower + +theorem inputHeight_polynomial_slack (N : ℕ) (hN : 0 < N) + (hell : 2 ^ 1000 ≤ inputSmallLog N) : + (inputSmallLog N : ℝ) ^ 20000 ≤ inputHeight N := + astronomical_parameter_slack _ _ hell (inputHeight_binary_slack N hN) + +theorem coarseExponent_fourth_power (ell : ℕ) : + coarseExponent ell ^ 4 ≤ Nat.log 2 ell := by + have ha := Nat.sqrt_le' (Nat.sqrt (Nat.log 2 ell)) + have hb := Nat.sqrt_le' (Nat.log 2 ell) + have hsq := Nat.pow_le_pow_left ha 2 + rw [← pow_mul] at hsq + exact hsq.trans hb + +theorem coarseExponent_maximal (ell p : ℕ) (hp : p ^ 4 ≤ Nat.log 2 ell) : + p ≤ coarseExponent ell := by + apply Nat.le_sqrt'.2 + apply Nat.le_sqrt'.2 + simpa only [← pow_mul] using hp + +theorem coarseExponent_shift_square (ell : ℕ) (hell : 1764 ≤ ell) : + ((coarseExponent ell : ℝ) + 21) ^ 2 ≤ ell := by + have hp : (coarseExponent ell : ℝ) ^ 4 ≤ ell := by + exact_mod_cast (coarseExponent_fourth_power ell).trans (Nat.log_le_self 2 ell) + have hellR : (1764 : ℝ) ≤ ell := by exact_mod_cast hell + have hscaled : (4 * (coarseExponent ell : ℝ) ^ 2) ^ 2 ≤ (ell : ℝ) ^ 2 := by + have ha := mul_le_mul_of_nonneg_left hp (by norm_num : (0 : ℝ) ≤ 16) + have hb : 16 * (ell : ℝ) ≤ (ell : ℝ) ^ 2 := by nlinarith + nlinarith + have hquarter : 4 * (coarseExponent ell : ℝ) ^ 2 ≤ ell := + (sq_le_sq₀ (by positivity) (Nat.cast_nonneg ell)).mp hscaled + nlinarith [sq_nonneg ((coarseExponent ell : ℝ) - 21)] + +noncomputable def heightQuarterRoot (N : ℕ) : ℝ := + Real.sqrt (Real.sqrt (inputHeight N : ℝ)) + +theorem heightQuarterRoot_fourth_power (N : ℕ) : + heightQuarterRoot N ^ 4 = inputHeight N := by + unfold heightQuarterRoot + rw [show (Real.sqrt (Real.sqrt (inputHeight N : ℝ))) ^ 4 = + ((Real.sqrt (Real.sqrt (inputHeight N : ℝ))) ^ 2) ^ 2 by ring] + rw [Real.sq_sqrt (Real.sqrt_nonneg _), Real.sq_sqrt (Nat.cast_nonneg _)] + +theorem inputParameters_error_envelope (N : ℕ) (hN : 0 < N) + (hell : 2 ^ 1000 ≤ inputSmallLog N) : + let H := (inputHeight N : ℝ) + let ell := (inputSmallLog N : ℝ) + let root := heightQuarterRoot N + let q := (coarseExponent (inputSmallLog N) : ℝ) + 21 + 52000 / H ^ 18 + 8040000 * ell ^ 4 / root ^ 2 + + 200 * ell / root + 1000000 * q / ell ^ 2 + 13200 / H ^ 2 < 1 / ell := by + dsimp only + have hcut : 64000000000000 ≤ inputSmallLog N := by + have hsmall : 64000000000000 ≤ (2 : ℕ) ^ 46 := by norm_num + exact hsmall.trans ((pow_le_pow_right₀ (by decide : 1 ≤ (2 : ℕ)) + (by decide : 46 ≤ 1000)).trans hell) + have hlarge : (64000000000000 : ℝ) ≤ inputSmallLog N := by exact_mod_cast hcut + have hellone : (1 : ℝ) ≤ inputSmallLog N := by linarith + have hpoly := inputHeight_polynomial_slack N hN hell + have hroot := fourth_root_polynomial_slack hellone hpoly + (Real.sqrt_nonneg _) (heightQuarterRoot_fourth_power N) + apply refinement_error_envelope hlarge + · exact (pow_le_pow_right₀ hellone (by decide : 2 ≤ 20000)).trans hpoly + · exact (pow_le_pow_right₀ hellone (by decide : 4 ≤ 5000)).trans hroot + · exact add_nonneg (Nat.cast_nonneg _) (by norm_num) + · exact coarseExponent_shift_square _ ((by decide : 1764 ≤ 64000000000000).trans hcut) + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/PartitionIntervals.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/PartitionIntervals.lean new file mode 100644 index 0000000000000000000000000000000000000000..20b0e15a395421f1de1e61be1813548891afecd7 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/PartitionIntervals.lean @@ -0,0 +1,96 @@ +import OAI.Combinatorics.EditApproximation.Geometry.AlignmentSplitting +import OAI.Combinatorics.EditApproximation.Geometry.StateGeometry + +namespace OAI + +/-! +# Valid target states from an actual alignment partition + +Prefix lengths convert an ordered list partition of a target substring +to valid global endpoint states. Every returned substring is exactly +the corresponding partition piece, even when pieces are empty. +-/ + +namespace EditApproximation + +theorem flatten_take_length_le {α : Type*} (parts : List (List α)) (k : ℕ) : + (parts.take k).flatten.length ≤ parts.flatten.length := by + have h := congrArg (fun p : List (List α) => p.flatten.length) + (List.take_append_drop k parts) + simp only [List.flatten_append, List.length_append] at h + omega + +theorem flatten_take_succ_length {α : Type*} (parts : List (List α)) (i : Fin parts.length) : + (parts.take (i.val + 1)).flatten.length = + (parts.take i.val).flatten.length + parts[i.val].length := by + rw [List.take_succ_eq_append_getElem i.isLt] + simp only [List.flatten_append, List.flatten_cons, List.flatten_nil, + List.append_nil, List.length_append] + +theorem substring_middle {α : Type*} (pre piece suffix : List α) : + substring ((pre ++ piece) ++ suffix) pre.length (pre.length + piece.length) = piece := by + unfold substring + rw [← List.length_append, List.take_append_length, List.drop_append_length] + +theorem substring_flatten_piece {α : Type*} (parts : List (List α)) (i : Fin parts.length) : + substring parts.flatten (parts.take i.val).flatten.length + (parts.take (i.val + 1)).flatten.length = parts[i.val] := by + have hparts : parts.flatten = + ((parts.take i.val).flatten ++ parts[i.val]) ++ (parts.drop (i.val + 1)).flatten := by + have h := congrArg List.flatten (List.take_append_drop (i.val + 1) parts) + rw [List.take_succ_eq_append_getElem i.isLt] at h + simpa only [List.flatten_append, List.flatten_cons, List.flatten_nil, + List.append_nil] using h.symm + rw [flatten_take_succ_length] + conv_lhs => arg 1; rw [hparts] + exact substring_middle _ _ _ + +def partitionInterval {α : Type*} (target : List α) (q : TargetInterval target.length) + (parts : List (List α)) (hparts : parts.flatten = substring target q.lo q.hi) + (i : Fin parts.length) : TargetInterval target.length where + lo := q.lo + (parts.take i.val).flatten.length + hi := q.lo + (parts.take (i.val + 1)).flatten.length + ordered := by rw [flatten_take_succ_length]; omega + valid := by + have hprefix := flatten_take_length_le parts (i.val + 1) + have hlength := congrArg List.length hparts + simp only [substring, List.length_drop, List.length_take, Nat.min_eq_left q.valid] at hlength + have horder := q.ordered + have hvalid := q.valid + omega + +theorem substring_inside_shift {α : Type*} (target : List α) + (q : TargetInterval target.length) (lo hi : ℕ) + (hhi : hi ≤ q.hi - q.lo) : + substring target (q.lo + lo) (q.lo + hi) = + substring (substring target q.lo q.hi) lo hi := by + unfold substring + rw [List.take_drop] + have htake : q.lo + hi ≤ q.hi := by have h := q.ordered; omega + simp only [List.take_take, Nat.min_eq_left htake, List.drop_drop] + +theorem partitionInterval_substring {α : Type*} (target : List α) + (q : TargetInterval target.length) (parts : List (List α)) + (hparts : parts.flatten = substring target q.lo q.hi) (i : Fin parts.length) : + substring target (partitionInterval target q parts hparts i).lo + (partitionInterval target q parts hparts i).hi = parts[i.val] := by + have hhi : (parts.take (i.val + 1)).flatten.length ≤ q.hi - q.lo := by + have h := flatten_take_length_le parts (i.val + 1) + rw [hparts] at h + simpa only [substring, List.length_drop, List.length_take, Nat.min_eq_left q.valid] using h + change substring target (q.lo + (parts.take i.val).flatten.length) + (q.lo + (parts.take (i.val + 1)).flatten.length) = parts[i.val] + rw [substring_inside_shift target q _ _ hhi, ← hparts] + exact substring_flatten_piece parts i + +theorem partitionInterval_shared {α : Type*} (target : List α) + (q : TargetInterval target.length) (parts : List (List α)) + (hparts : parts.flatten = substring target q.lo q.hi) + (i j : Fin parts.length) (hnext : j.val = i.val + 1) : + (partitionInterval target q parts hparts i).hi = + (partitionInterval target q parts hparts j).lo := by + simp only [partitionInterval, hnext] + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/PrefixBitEnvelope.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/PrefixBitEnvelope.lean new file mode 100644 index 0000000000000000000000000000000000000000..1b60306404722bc32bd468558161f2675339642c --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/PrefixBitEnvelope.lean @@ -0,0 +1,89 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryBandGuardWork +import OAI.Combinatorics.EditApproximation.Probability.FiniteBitPolynomial + +namespace OAI + +/-! Fixed-degree polynomial envelope for the literal prefix and band-test +arithmetic. The finite expression represents the bit counters; +its degree is independent of every input length and parameter. -/ + +namespace EditApproximation + +private abbrev PE := FiniteBitPolynomial (Fin 4) + +private def ps (a : PE) : PE := .bitLength a +private def pn (a b : PE) : PE := .minimum a b + +private def peSumWord (n B : PE) : PE := + (B + 1) + ps n + 2 * (B + 2) + 2 * (1 + n * ((B + 1) + (B + 1))) + 1 +private def peSumBit (n B : PE) : PE := 1 + n * (100000 * (peSumWord n B + 1) ^ 2) +private def peSumStorage (n B : PE) : PE := ps n + B + 2 * (1 + n * (B + 1)) + 2 +private def peConnectionWord (n B : PE) : PE := peSumStorage (n + 1) (8 * B + 6) +private def peConnectionBit (n B : PE) : PE := + (n + 1) * (6000 * (B + 1) ^ 2 + 4) + n * (2 * B + 6) + + peSumBit (n + 1) (8 * B + 6) + 6 * (n + 1) + 1 +private def pePrefixWord (M j B : PE) : PE := + 8 * (peConnectionWord (pn j M) (8 * B + 6) + peSumStorage M B) + 6 +private def pePrefixBit (M j B : PE) : PE := + 6000 * (B + 1) ^ 2 + peConnectionBit (pn j M) (8 * B + 6) + + peSumBit M B + 6 * M + + 6000 * (peConnectionWord (pn j M) (8 * B + 6) + peSumStorage M B + 1) ^ 2 + + 2 * B + 6 * M + 5 +private def pePrefixMinimumBit (M j v B : PE) : PE := + pePrefixBit M j B + v * (pePrefixBit M j B + 3) + + (1 + v * (1000 * (pePrefixWord M j B + 1) ^ 2 + 2)) + 1 +private def peAffineBit (B : PE) : PE := + 6000 * (B + 1) ^ 2 + 1 + 2000 * (B + 1) ^ 2 + + (6000 * (12 * B + 9) ^ 2 + 1) + (1000 * (96 * B + 71) ^ 2 + 1) + 4 +private def peCutWord (M j B : PE) : PE := pePrefixWord M j (8 * B + 6) + 76 * B + 50 +private def peCutBit (M j v B : PE) : PE := + 2 * (6000 * (B + 1) ^ 2 + 1) + pePrefixMinimumBit M j v (8 * B + 6) + + peAffineBit (peCutWord M j B) + 4 * B + 6 +private def peNaturalDistanceBit (B : PE) : PE := + 6000 * (B + 1) ^ 2 + 2 + (1000 * (8 * B + 7) ^ 2 + 1) + 3 * B + 3 +private def peToleranceBit (B : PE) : PE := + 2000 * (B + 1) ^ 2 + 2000 * (4 * B + 3) ^ 2 + 2100 * (16 * B + 12) ^ 2 + 2 * B + 3 +private def prefixAggregateExpression : PE := + let M := .input 0 + let j := .input 1 + let v := .input 2 + let B := .input 3 + pePrefixWord M j B + pePrefixBit M j B + pePrefixMinimumBit M j v B + + peCutWord M j B + peCutBit M j v B + peNaturalDistanceBit B + peToleranceBit B + +/-- Fixed degree of the prefix/guard arithmetic implementation. -/ +def prefixArithmeticDegree : ℕ := prefixAggregateExpression.degree + +private def prefixEnv (M j v B : ℕ) : Fin 4 → ℕ + | 0 => M + | 1 => j + | 2 => v + | _ => B + +private theorem prefixAggregateExpression_eval (M j v B : ℕ) : + prefixAggregateExpression.eval (prefixEnv M j v B) = + BinaryFraction.prefixWordBudget M j B + BinaryFraction.prefixBitBudget M j B + + BinaryFraction.prefixMinimumBitBudget M j v B + BinaryFraction.cutGuardWordBudget M j B + + BinaryFraction.cutGuardBitBudget M j v B + BinaryFraction.naturalDistanceBitBudget B + + BinaryFraction.bandToleranceBitBudget B := rfl + +theorem prefix_guard_budgets_le_fixed_power (M j v B S : ℕ) + (hS : 2 ≤ S) (hM : M ≤ S) (hj : j ≤ S) (hv : v ≤ S) (hB : B ≤ S) : + BinaryFraction.prefixWordBudget M j B ≤ S ^ prefixArithmeticDegree ∧ + BinaryFraction.prefixBitBudget M j B ≤ S ^ prefixArithmeticDegree ∧ + BinaryFraction.prefixMinimumBitBudget M j v B ≤ S ^ prefixArithmeticDegree ∧ + BinaryFraction.cutGuardWordBudget M j B ≤ S ^ prefixArithmeticDegree ∧ + BinaryFraction.cutGuardBitBudget M j v B ≤ S ^ prefixArithmeticDegree ∧ + BinaryFraction.naturalDistanceBitBudget B ≤ S ^ prefixArithmeticDegree ∧ + BinaryFraction.bandToleranceBitBudget B ≤ S ^ prefixArithmeticDegree := by + have henv : ∀ i, prefixEnv M j v B i ≤ S := by + intro i + fin_cases i <;> simp only [prefixEnv] <;> assumption + have h := prefixAggregateExpression.eval_le_pow (prefixEnv M j v B) S hS henv + rw [prefixAggregateExpression_eval] at h + change _ ≤ S ^ prefixArithmeticDegree at h + omega + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/PrefixComparison.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/PrefixComparison.lean new file mode 100644 index 0000000000000000000000000000000000000000..cffc18c75de6e2df9d9d28b587800a68dd3272e5 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/PrefixComparison.lean @@ -0,0 +1,342 @@ +import OAI.Combinatorics.EditApproximation.Geometry.PrefixCosts +import OAI.Combinatorics.EditApproximation.Geometry.WideActions +import OAI.Combinatorics.EditApproximation.Geometry.SourcePrefixes + +namespace OAI + +/-! +# Actual comparison prefixes in the finite wide action family + +The cut is the start of the remaining comparator suffix, or the parent's +end when that suffix is empty. Splitting at this cut preserves the literal +connection budget. Splicing any enumerated prefix to the comparator suffix +remains an enumerated wide action. +-/ + +namespace EditApproximation + +open Finset + +def connectionPrefixBoundary {n : ℕ} (states : List (TargetInterval n)) (finish j : ℕ) : ℕ := + ((states.drop j).head?.map TargetInterval.lo).getD finish + +theorem realConnectionBudget_nonneg {n : ℕ} (start finish : ℝ) + (states : List (TargetInterval n)) : 0 ≤ realConnectionBudget start states finish := by + induction states generalizing start with + | nil => exact abs_nonneg _ + | cons state rest ih => exact add_nonneg (abs_nonneg _) (ih state.hi) + +/-- Exact splitting at the first endpoint of the remaining suffix. -/ +theorem realConnectionBudget_split {n : ℕ} (states : List (TargetInterval n)) + (start : ℝ) (finish j : ℕ) : + realConnectionBudget start states finish = + realConnectionBudget start (states.take j) (connectionPrefixBoundary states finish j) + + realConnectionBudget (connectionPrefixBoundary states finish j) (states.drop j) finish := by + induction states generalizing start j with + | nil => simp [connectionPrefixBoundary, realConnectionBudget] + | cons state rest ih => + cases j with + | zero => simp [connectionPrefixBoundary, realConnectionBudget] + | succ j => + simp only [List.take_succ_cons, List.drop_succ_cons, connectionPrefixBoundary, + realConnectionBudget] + rw [ih (state.hi : ℝ) j] + dsimp only [connectionPrefixBoundary] + ring + +/-- A detour through an arbitrary real cut only increases the budget. -/ +theorem realConnectionBudget_append_le {n : ℕ} (before after : List (TargetInterval n)) + (start finish cut : ℝ) : + realConnectionBudget start (before ++ after) finish ≤ + realConnectionBudget start before cut + realConnectionBudget cut after finish := by + induction before generalizing start with + | nil => + cases after with + | nil => exact abs_sub_le start cut finish + | cons state rest => + have h := abs_sub_le start cut (state.lo : ℝ) + simp only [List.nil_append, realConnectionBudget] + linarith + | cons state rest ih => + have h := ih (state.hi : ℝ) + simp only [List.cons_append, realConnectionBudget] + linarith + +theorem zero_connection_prefix_suffix {n M : ℕ} (r : TargetInterval n) + (comparison : Fin M → TargetInterval n) (j : ℕ) + (hzero : endpointActionConnection r comparison = 0) : + realConnectionBudget r.lo ((List.ofFn comparison).take j) + (connectionPrefixBoundary (List.ofFn comparison) r.hi j) = 0 ∧ + realConnectionBudget (connectionPrefixBoundary (List.ofFn comparison) r.hi j) + ((List.ofFn comparison).drop j) r.hi = 0 := by + have hsplit := realConnectionBudget_split (List.ofFn comparison) (r.lo : ℝ) r.hi j + have hfull : realConnectionBudget r.lo (List.ofFn comparison) r.hi = 0 := by + rw [realConnectionBudget_cast] + exact_mod_cast hzero + rw [hfull] at hsplit + have hbefore := realConnectionBudget_nonneg (r.lo : ℝ) + (connectionPrefixBoundary (List.ofFn comparison) r.hi j) + ((List.ofFn comparison).take j) + have hafter := realConnectionBudget_nonneg + (connectionPrefixBoundary (List.ofFn comparison) r.hi j) (r.hi : ℝ) + ((List.ofFn comparison).drop j) + constructor <;> linarith + +def comparisonPrefixSplice {n M : ℕ} (before comparison : Fin M → TargetInterval n) + (j : ℕ) : Fin M → TargetInterval n := fun i => if i.val < j then before i else comparison i + +theorem comparisonPrefixSplice_list {n M : ℕ} (before comparison : Fin M → TargetInterval n) + (j : ℕ) (hj : j ≤ M) : + List.ofFn (comparisonPrefixSplice before comparison j) = + (List.ofFn before).take j ++ (List.ofFn comparison).drop j := by + apply List.ext_getElem + · simp only [List.length_ofFn, List.length_append, List.length_take, List.length_drop, + Nat.min_eq_left hj] + omega + · intro i hi hi' + simp only [List.getElem_ofFn, comparisonPrefixSplice] + by_cases hij : i < j + · rw [ite_eq_left hij, List.getElem_append_left] + · rw [List.getElem_take, List.getElem_ofFn] + · simp only [List.length_take, List.length_ofFn, Nat.min_eq_left hj] + exact hij + · rw [ite_eq_right hij, List.getElem_append_right] + · simp only [List.length_take, List.length_ofFn, Nat.min_eq_left hj, + List.getElem_drop, List.getElem_ofFn] + congr 1 + apply Fin.ext + change i = j + (i - j) + omega + · simp only [List.length_take, List.length_ofFn, Nat.min_eq_left hj] + omega + +theorem comparisonPrefixSplice_mem {nx ny M b P : ℕ} (parent : TargetInterval nx) + (r : TargetInterval ny) (before comparison : Fin M → TargetInterval ny) (j : ℕ) + (hbefore : before ∈ wideActionList M parent r b P) + (hcomparison : comparison ∈ wideActionList M parent r b P) : + comparisonPrefixSplice before comparison j ∈ wideActionList M parent r b P := by + apply finiteAssignments_complete + intro i + unfold comparisonPrefixSplice + split_ifs with hi + · exact finiteAssignments_sound M _ before hbefore i + · exact finiteAssignments_sound M _ comparison hcomparison i + +noncomputable def comparisonPrefixShift {nx ny M : ℕ} (parent : TargetInterval nx) + (r : TargetInterval ny) (comparison : Fin M → TargetInterval ny) (j : ℕ) : ℝ := + (connectionPrefixBoundary (List.ofFn comparison) r.hi j : ℝ) - + balancedCut parent.lo (parent.hi - parent.lo) M j + +theorem connectionPrefixBoundary_ofFn {n M : ℕ} (states : Fin M → TargetInterval n) + (finish : ℕ) (j : Fin M) : + connectionPrefixBoundary (List.ofFn states) finish j.val = (states j).lo := by + simp only [connectionPrefixBoundary, List.head?_drop, List.getElem?_ofFn, + dite_eq_left j.isLt, Option.map_some, Option.getD_some] + +/-- Internal comparison cuts are exactly the next child's left shift. -/ +theorem comparisonPrefixShift_at_child {nx ny M : ℕ} (parent : TargetInterval nx) + (r : TargetInterval ny) (comparison : Fin M → TargetInterval ny) (j : Fin M) : + comparisonPrefixShift parent r comparison j.val = + ((comparison j).lo : ℝ) - (sourceChild parent j).lo := by + simp only [comparisonPrefixShift, connectionPrefixBoundary_ofFn, sourceChild] + +noncomputable def comparisonPrefixValue {ny M : ℕ} (comparison : Fin M → TargetInterval ny) + (child : Fin M → TargetInterval ny → ℝ) (j : ℕ) : ℝ := + ∑ i, if i.val < j then child i (comparison i) else 0 + +theorem comparisonPrefixCost_eq {nx ny M : ℕ} (parent : TargetInterval nx) + (r : TargetInterval ny) (comparison : Fin M → TargetInterval ny) + (child : Fin M → TargetInterval ny → ℝ) (j : ℕ) + (hzero : endpointActionConnection r comparison = 0) : + widePrefixCost parent r comparison child j (comparisonPrefixShift parent r comparison j) = + comparisonPrefixValue comparison child j := by + have hprefix := (zero_connection_prefix_suffix r comparison j hzero).1 + have hfinish : (balancedCut parent.lo (parent.hi - parent.lo) M j : ℝ) + + comparisonPrefixShift parent r comparison j = + connectionPrefixBoundary (List.ofFn comparison) r.hi j := by + unfold comparisonPrefixShift + ring + simp only [widePrefixCost, hfinish, hprefix, zero_add, comparisonPrefixValue] + +/-- An arbitrary actual wide prefix can be completed by the comparator +suffix at exactly the comparison cut. -/ +theorem comparisonPrefixSplice_cost {nx ny M : ℕ} (parent : TargetInterval nx) + (r : TargetInterval ny) (before comparison : Fin M → TargetInterval ny) + (child : Fin M → TargetInterval ny → ℝ) (j : ℕ) (hj : j ≤ M) + (hzero : endpointActionConnection r comparison = 0) : + endpointActionValue r (comparisonPrefixSplice before comparison j) child ≤ + widePrefixCost parent r before child j (comparisonPrefixShift parent r comparison j) + + (∑ i, child i (comparison i)) - comparisonPrefixValue comparison child j := by + have hsuffix := (zero_connection_prefix_suffix r comparison j hzero).2 + have hconnection := realConnectionBudget_append_le + ((List.ofFn before).take j) ((List.ofFn comparison).drop j) (r.lo : ℝ) (r.hi : ℝ) + (connectionPrefixBoundary (List.ofFn comparison) r.hi j) + rw [← comparisonPrefixSplice_list before comparison j hj, + realConnectionBudget_cast, hsuffix, add_zero] at hconnection + have hsum : (∑ i, child i (comparisonPrefixSplice before comparison j i)) = + (∑ i, if i.val < j then child i (before i) else 0) + + (∑ i, child i (comparison i)) - comparisonPrefixValue comparison child j := by + unfold comparisonPrefixValue + rw [← sum_add_distrib, ← sum_sub_distrib] + apply sum_congr rfl + intro i hi + by_cases hij : i.val < j <;> simp [comparisonPrefixSplice, hij] + have hfinish : (balancedCut parent.lo (parent.hi - parent.lo) M j : ℝ) + + comparisonPrefixShift parent r comparison j = + connectionPrefixBoundary (List.ofFn comparison) r.hi j := by + unfold comparisonPrefixShift + ring + unfold endpointActionValue widePrefixCost + rw [hfinish, hsum] + change (connectionBudget r.lo (List.ofFn (comparisonPrefixSplice before comparison j)) r.hi : ℝ) + _ ≤ _ + linarith + +/-- The comparison prefix is covered by the literal finite predictor. +The full-action lower bound is later instantiated by the actual warmup +Bellman value; no prefix estimate is assumed. -/ +theorem comparisonPrefixMinimum_bounds {nx ny M b P : ℕ} (parent : TargetInterval nx) + (r : TargetInterval ny) (comparison : Fin M → TargetInterval ny) + (hcomparison : comparison ∈ wideActionList M parent r b P) + (hnonempty : wideActionList M parent r b P ≠ []) + (child : Fin M → TargetInterval ny → ℝ) (j : ℕ) (hj : j ≤ M) + (hzero : endpointActionConnection r comparison = 0) (fullLower : ℝ) + (hfull : ∀ action ∈ wideActionList M parent r b P, + fullLower ≤ endpointActionValue r action child) : + comparisonPrefixValue comparison child j - ((∑ i, child i (comparison i)) - fullLower) ≤ + widePrefixMinimum parent r (wideActionList M parent r b P) hnonempty child j + (comparisonPrefixShift parent r comparison j) ∧ + widePrefixMinimum parent r (wideActionList M parent r b P) hnonempty child j + (comparisonPrefixShift parent r comparison j) ≤ comparisonPrefixValue comparison child j := by + constructor + · apply le_widePrefixMinimum + intro action ha + have hsplice := comparisonPrefixSplice_mem parent r action comparison j ha hcomparison + have hcost := comparisonPrefixSplice_cost parent r action comparison child j hj hzero + have hlower := hfull _ hsplice + linarith + · exact (widePrefixMinimum_le_member parent r _ hnonempty child j _ comparison hcomparison).trans_eq + (comparisonPrefixCost_eq parent r comparison child j hzero) + +/-- Real form of the literal local wide-action minimum; the first member +is duplicated as fallback, exactly as in the rational predictor. -/ +noncomputable def wideActionMinimum {nx ny M : ℕ} (parent : TargetInterval nx) + (r : TargetInterval ny) (b P : ℕ) (hnonempty : wideActionList M parent r b P ≠ []) + (child : Fin M → TargetInterval ny → ℝ) : ℝ := + finiteMinimum (endpointActionValue r ((wideActionList M parent r b P).head hnonempty) child) + ((wideActionList M parent r b P).map fun action => endpointActionValue r action child) + +theorem wideActionMinimum_le_member {nx ny M b P : ℕ} (parent : TargetInterval nx) + (r : TargetInterval ny) (hnonempty : wideActionList M parent r b P ≠ []) + (child : Fin M → TargetInterval ny → ℝ) (action : Fin M → TargetInterval ny) + (haction : action ∈ wideActionList M parent r b P) : + wideActionMinimum parent r b P hnonempty child ≤ endpointActionValue r action child := + finiteMinimum_le_member _ _ (List.mem_map.mpr ⟨action, haction, rfl⟩) + +/-- Exact finite predictor coverage with its actual wide-action minimum Z. -/ +theorem comparisonPrefixMinimum_actual_bounds {nx ny M b P : ℕ} (parent : TargetInterval nx) + (r : TargetInterval ny) (comparison : Fin M → TargetInterval ny) + (hcomparison : comparison ∈ wideActionList M parent r b P) + (hnonempty : wideActionList M parent r b P ≠ []) + (child : Fin M → TargetInterval ny → ℝ) (j : ℕ) (hj : j ≤ M) + (hzero : endpointActionConnection r comparison = 0) : + comparisonPrefixValue comparison child j - + ((∑ i, child i (comparison i)) - wideActionMinimum parent r b P hnonempty child) ≤ + widePrefixMinimum parent r (wideActionList M parent r b P) hnonempty child j + (comparisonPrefixShift parent r comparison j) ∧ + widePrefixMinimum parent r (wideActionList M parent r b P) hnonempty child j + (comparisonPrefixShift parent r comparison j) ≤ comparisonPrefixValue comparison child j := + comparisonPrefixMinimum_bounds parent r comparison hcomparison hnonempty child j hj hzero + (wideActionMinimum parent r b P hnonempty child) + (fun action ha => wideActionMinimum_le_member parent r hnonempty child action ha) + +/-- A zero connection path has exactly the endpoint length span. -/ +theorem connectionBudget_zero_span {n : ℕ} (states : List (TargetInterval n)) + (start finish : ℕ) (hzero : connectionBudget start states finish = 0) : + start ≤ finish ∧ (states.map fun state => state.hi - state.lo).sum = finish - start := by + induction states generalizing start with + | nil => + have heq : start = finish := Nat.eq_of_dist_eq_zero hzero + subst start + simp only [List.map_nil, List.sum_nil, Nat.sub_self, le_refl, and_self] + | cons state rest ih => + have hparts : Nat.dist start state.lo + connectionBudget state.hi rest finish = 0 := hzero + have hstart : start = state.lo := Nat.eq_of_dist_eq_zero (by omega) + have htail : connectionBudget state.hi rest finish = 0 := by omega + obtain ⟨horder, hsum⟩ := ih state.hi htail + subst start + constructor + · exact state.ordered.trans horder + · simp only [List.map_cons, List.sum_cons, hsum] + have := state.ordered + omega + +/-- The comparison cut displacement is the sum of the actual target-minus- +source child length gaps in its prefix. -/ +theorem comparisonPrefixShift_gap_sum {α : Type*} (source target : List α) + {M : ℕ} (hM : 0 < M) (parent : TargetInterval source.length) + (r : TargetInterval target.length) (comparison : Fin M → TargetInterval target.length) + (j : ℕ) (hj : j ≤ M) (hzero : endpointActionConnection r comparison = 0) : + comparisonPrefixShift parent r comparison j - comparisonPrefixShift parent r comparison 0 = + ∑ i, if i.val < j then + stateLengthGap (substring source (sourceChild parent i).lo (sourceChild parent i).hi) + target (comparison i) else 0 := by + let cut := connectionPrefixBoundary (List.ofFn comparison) r.hi j + have hprefix := (zero_connection_prefix_suffix r comparison j hzero).1 + have hprefixNat : connectionBudget r.lo ((List.ofFn comparison).take j) cut = 0 := by + rw [realConnectionBudget_cast] at hprefix + exact_mod_cast hprefix + obtain ⟨htargetOrder, htargetSpan⟩ := connectionBudget_zero_span + ((List.ofFn comparison).take j) r.lo cut hprefixNat + have htargetNat : (∑ i : Fin M with i.val < j, ((comparison i).hi - (comparison i).lo)) = cut - r.lo := by + rw [← List.sum_take_ofFn] + simpa only [List.map_take, List.map_ofFn, Function.comp_def] using htargetSpan + have hsourceSpan := sourceChildren_prefix_length source hM parent j hj + simp only [List.length_flatten, List.map_take, List.map_ofFn, Function.comp_def] at hsourceSpan + have hsourceNat : (∑ i : Fin M with i.val < j, + (substring source (sourceChild parent i).lo (sourceChild parent i).hi).length) = + balancedCut parent.lo (parent.hi - parent.lo) M j - parent.lo := by + rw [← List.sum_take_ofFn] + exact hsourceSpan + have htargetReal : (∑ i : Fin M, if i.val < j then + ((comparison i).hi : ℝ) - (comparison i).lo else 0) = (cut : ℝ) - r.lo := by + rw [← sum_filter] + calc + _ = ((∑ i : Fin M with i.val < j, ((comparison i).hi - (comparison i).lo) : ℕ) : ℝ) := by + rw [Nat.cast_sum] + apply sum_congr rfl + intro i hi + rw [Nat.cast_sub (comparison i).ordered] + _ = ((cut - r.lo : ℕ) : ℝ) := congrArg (fun a : ℕ => (a : ℝ)) htargetNat + _ = _ := Nat.cast_sub htargetOrder + have hsourceOrder := (balancedCut_bounds parent.lo (parent.hi - parent.lo) M j hM hj).1 + have hsourceReal : (∑ i : Fin M, if i.val < j then + ((substring source (sourceChild parent i).lo (sourceChild parent i).hi).length : ℝ) else 0) = + (balancedCut parent.lo (parent.hi - parent.lo) M j : ℝ) - parent.lo := by + rw [← sum_filter] + calc + _ = ((∑ i : Fin M with i.val < j, + (substring source (sourceChild parent i).lo (sourceChild parent i).hi).length : ℕ) : ℝ) := by + rw [Nat.cast_sum] + _ = ((balancedCut parent.lo (parent.hi - parent.lo) M j - parent.lo : ℕ) : ℝ) := congrArg (fun a : ℕ => (a : ℝ)) hsourceNat + _ = _ := Nat.cast_sub hsourceOrder + have hgap : (∑ i : Fin M, if i.val < j then + stateLengthGap (substring source (sourceChild parent i).lo (sourceChild parent i).hi) + target (comparison i) else 0) = + (cut : ℝ) - r.lo - ((balancedCut parent.lo (parent.hi - parent.lo) M j : ℝ) - parent.lo) := by + rw [← htargetReal, ← hsourceReal, ← sum_sub_distrib] + apply sum_congr rfl + intro i hi + by_cases hij : i.val < j <;> simp only [hij, ↓reduceIte, stateLengthGap, sub_zero] + have horigin := (zero_connection_prefix_suffix r comparison 0 hzero).1 + simp only [List.take_zero, realConnectionBudget] at horigin + have horiginEq : (connectionPrefixBoundary (List.ofFn comparison) r.hi 0 : ℝ) = r.lo := by + exact (sub_eq_zero.mp (abs_eq_zero.mp horigin)).symm + rw [hgap] + unfold comparisonPrefixShift + rw [balancedCut_zero, horiginEq] + dsimp only [cut] + ring + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/PrefixCosts.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/PrefixCosts.lean new file mode 100644 index 0000000000000000000000000000000000000000..5018f5649511a131e81682a38886c0a0265f1547 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/PrefixCosts.lean @@ -0,0 +1,111 @@ +import OAI.Combinatorics.EditApproximation.Geometry.SharedActions +import OAI.Combinatorics.EditApproximation.Geometry.Bellman + +namespace OAI + +/-! +# Finite prefix costs used by the predicted bands + +A prefix is a restriction of an enumerated wide action. The last jump is +evaluated at the proposed real shift. Taking the minimum over the actual +finite list, with its first member duplicated as the fallback, gives the +exact prefix minimum and its 1-Lipschitz property. +-/ + +namespace EditApproximation + +open Finset + +noncomputable def realConnectionBudget {n : ℕ} (start : ℝ) : + List (TargetInterval n) → ℝ → ℝ + | [], finish => |start - finish| + | state :: rest, finish => |start - state.lo| + realConnectionBudget state.hi rest finish + +theorem realConnectionBudget_finish_lipschitz {n : ℕ} (start : ℝ) + (states : List (TargetInterval n)) (finish finish' : ℝ) : + |realConnectionBudget start states finish - realConnectionBudget start states finish'| ≤ + |finish - finish'| := by + induction states generalizing start with + | nil => + have h := abs_abs_sub_abs_le_abs_sub (start - finish) (start - finish') + have heq : start - finish - (start - finish') = -(finish - finish') := by ring + simpa only [realConnectionBudget, heq, abs_neg] using h + | cons state rest ih => + have heq : realConnectionBudget start (state :: rest) finish - + realConnectionBudget start (state :: rest) finish' = + realConnectionBudget state.hi rest finish - realConnectionBudget state.hi rest finish' := by + simp only [realConnectionBudget] + ring + rw [heq] + exact ih state.hi + +theorem realConnectionBudget_cast {n : ℕ} (start finish : ℕ) (states : List (TargetInterval n)) : + realConnectionBudget start states finish = (connectionBudget start states finish : ℝ) := by + induction states generalizing start with + | nil => exact natural_distance_cast start finish + | cons state rest ih => + simp only [realConnectionBudget, connectionBudget, Nat.cast_add, ih, + natural_distance_cast] + +noncomputable def widePrefixCost {nx ny M : ℕ} (parent : TargetInterval nx) + (r : TargetInterval ny) (states : Fin M → TargetInterval ny) + (child : Fin M → TargetInterval ny → ℝ) (j : ℕ) (p : ℝ) : ℝ := + realConnectionBudget r.lo ((List.ofFn states).take j) + ((balancedCut parent.lo (parent.hi - parent.lo) M j : ℝ) + p) + + ∑ i, if i.val < j then child i (states i) else 0 + +theorem widePrefixCost_lipschitz {nx ny M : ℕ} (parent : TargetInterval nx) + (r : TargetInterval ny) (states : Fin M → TargetInterval ny) + (child : Fin M → TargetInterval ny → ℝ) (j : ℕ) (p p' : ℝ) : + |widePrefixCost parent r states child j p - widePrefixCost parent r states child j p'| ≤ + |p - p'| := by + have h := realConnectionBudget_finish_lipschitz (r.lo : ℝ) ((List.ofFn states).take j) + ((balancedCut parent.lo (parent.hi - parent.lo) M j : ℝ) + p) + ((balancedCut parent.lo (parent.hi - parent.lo) M j : ℝ) + p') + have heq : ((balancedCut parent.lo (parent.hi - parent.lo) M j : ℝ) + p) - + ((balancedCut parent.lo (parent.hi - parent.lo) M j : ℝ) + p') = p - p' := by ring + simpa only [widePrefixCost, add_sub_add_right_eq_sub, heq] using h + +noncomputable def widePrefixMinimum {nx ny M : ℕ} (parent : TargetInterval nx) + (r : TargetInterval ny) (actions : List (Fin M → TargetInterval ny)) (hnonempty : actions ≠ []) + (child : Fin M → TargetInterval ny → ℝ) (j : ℕ) (p : ℝ) : ℝ := + finiteMinimum (widePrefixCost parent r (actions.head hnonempty) child j p) + (actions.map fun action => widePrefixCost parent r action child j p) + +theorem widePrefixMinimum_le_member {nx ny M : ℕ} (parent : TargetInterval nx) + (r : TargetInterval ny) (actions : List (Fin M → TargetInterval ny)) (hnonempty : actions ≠ []) + (child : Fin M → TargetInterval ny → ℝ) (j : ℕ) (p : ℝ) + (action : Fin M → TargetInterval ny) (haction : action ∈ actions) : + widePrefixMinimum parent r actions hnonempty child j p ≤ widePrefixCost parent r action child j p := + finiteMinimum_le_member _ _ (List.mem_map.mpr ⟨action, haction, rfl⟩) + +theorem le_widePrefixMinimum {nx ny M : ℕ} (parent : TargetInterval nx) + (r : TargetInterval ny) (actions : List (Fin M → TargetInterval ny)) (hnonempty : actions ≠ []) + (child : Fin M → TargetInterval ny → ℝ) (j : ℕ) (p lower : ℝ) + (hlower : ∀ action ∈ actions, lower ≤ widePrefixCost parent r action child j p) : + lower ≤ widePrefixMinimum parent r actions hnonempty child j p := by + apply (le_finiteMinimum_iff _ _ _).2 + refine ⟨hlower _ (List.head_mem hnonempty), ?_⟩ + intro value hvalue + obtain ⟨action, ha, rfl⟩ := List.mem_map.mp hvalue + exact hlower action ha + +theorem widePrefixMinimum_lipschitz {nx ny M : ℕ} (parent : TargetInterval nx) + (r : TargetInterval ny) (actions : List (Fin M → TargetInterval ny)) (hnonempty : actions ≠ []) + (child : Fin M → TargetInterval ny → ℝ) (j : ℕ) (p p' : ℝ) : + |widePrefixMinimum parent r actions hnonempty child j p - + widePrefixMinimum parent r actions hnonempty child j p'| ≤ |p - p'| := by + have hforward (p p' : ℝ) : widePrefixMinimum parent r actions hnonempty child j p ≤ + widePrefixMinimum parent r actions hnonempty child j p' + |p - p'| := by + apply finiteMinimum_map_spatial + · have h := widePrefixCost_lipschitz parent r (actions.head hnonempty) child j p p' + linarith [(abs_le.mp h).2] + · intro action ha + have h := widePrefixCost_lipschitz parent r action child j p p' + linarith [(abs_le.mp h).2] + exact abs_le.mpr ⟨by have h := hforward p' p; rw [abs_sub_comm p' p] at h; linarith, + by linarith [hforward p p']⟩ + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/PreparedBandPolynomial.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/PreparedBandPolynomial.lean new file mode 100644 index 0000000000000000000000000000000000000000..828d5a541877131a9dc0c4d9abe09a6ef5da21cd --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/PreparedBandPolynomial.lean @@ -0,0 +1,129 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryPreparedUnskippedWork +import OAI.Combinatorics.EditApproximation.Probability.FiniteBitPolynomial + +namespace OAI + +/-! A fixed-degree bound for the complete band constructor. The sole +non-polynomial quantity is the actual Cartesian-product list bound, an +explicit input subsequently bounded by the computed grid parameters. -/ + +namespace EditApproximation + +private abbrev BP := FiniteBitPolynomial (Fin 8) +private def bpSumStorage (n B : BP) : BP := .bitLength n + B + 2 * (1 + n * (B + 1)) + 2 +private def bpSumWord (n B : BP) : BP := + (B + 1) + .bitLength n + 2 * (B + 2) + 2 * (1 + n * ((B + 1) + (B + 1))) + 1 +private def bpSumWork (n B : BP) : BP := 1 + n * (100000 * (bpSumWord n B + 1) ^ 2) +private def bpConnectionWord (M B : BP) : BP := bpSumStorage (M + 1) (8 * B + 6) +private def bpConnectionWork (M B : BP) : BP := + (M + 1) * (6000 * (B + 1) ^ 2 + 4) + M * (2 * B + 6) + + bpSumWork (M + 1) (8 * B + 6) + 6 * (M + 1) + 1 +private def bpEndpointWord (M B : BP) : BP := + 8 * (bpConnectionWord M B + bpSumStorage M B) + 6 +private def bpEndpointWork (M B : BP) : BP := + bpConnectionWork M B + 2 * B + M + 2 + bpSumWork M B + 6 * M + + 6000 * (bpConnectionWord M B + bpSumStorage M B + 1) ^ 2 + 2 +private def bpMinimum (M n B : BP) : BP := + bpEndpointWork M B + n * (bpEndpointWork M B + 3) + + (1 + n * (1000 * (bpEndpointWord M B + 1) ^ 2 + 2)) + 2 +private def bpGapWord (B : BP) : BP := 64 * B + 54 +private def bpGapWork (B : BP) : BP := + (6000 * (B + 1) ^ 2 + 1) + (6000 * (8 * B + 7) ^ 2 + 1) + 3 * B + 2 +private def bpNaturalDistance (B : BP) : BP := + 6000 * (B + 1) ^ 2 + 2 + (1000 * (8 * B + 7) ^ 2 + 1) + 3 * B + 3 +private def bpAnchor (B : BP) : BP := + 2 * (36 * B + 4) + 80 * (B + 4) + 2 * bpNaturalDistance B + 3 +private def bpTolerance (B : BP) : BP := + 2000 * (B + 1) ^ 2 + 2000 * (4 * B + 3) ^ 2 + 2100 * (16 * B + 12) ^ 2 + 2 * B + 3 +private def bpPredicate (M B C : BP) : BP := + (M + 1) * (8 * B + 3) + M * (bpAnchor B + 3) + bpTolerance B + M * (C + 3) + 4 +private def bpBand (n B C : BP) : BP := + 6000 * (B + 1) ^ 2 + 1000 * (8 * B + 7) ^ 2 + n * (C + 3) + 4 +private def bpRepresentative (M n B : BP) : BP := + let W := B + bpEndpointWord M B + bpGapWord B + 1 + let S := 4 * W + 4 + B + M + n + 2 + bpMinimum M n B + 1000 * (W + 1) ^ 2 + bpGapWork B + 2100 * (W + 2) ^ 2 + + bpBand n (4 * W + 4) (bpPredicate M S (S ^ prefixArithmeticDegree)) + 3 +private def bpGridPoints (n B : BP) : BP := + 1000 * (B + 2) ^ 2 + n * (100 * (B + 3) ^ 2 + 5) +private def bpGridBox (n B : BP) : BP := + 96 * (B + 1) + 2 * bpGridPoints n (B + 2) + + n * (n * (16 * (B + 2) + 11) + n + 3) + 6 +private def bpWide (M P B C : BP) : BP := + M * (10000 * (B + 12) ^ 2 + bpGridBox (40 * P + 2) (B + 12) + 6) + + (M + 1) * (6 * M + 10) * C + 1 +private def bpEnvelopeWord (M bb B : BP) : BP := B + bb + .bitLength M + 8 +private def bpEnvelopeWork (M bb n B : BP) : BP := + let W := bpEnvelopeWord M bb B + 2100 * (bb + .bitLength M + 6) ^ 2 + + (1 + n * (1000 * (W + 1) ^ 2 + 2)) + (1000 * (W + 1) ^ 2 + 1) + + (1 + 2 * W * (1000 * (3 * W + 2) ^ 2 + 2) + 3 * W + 5) + n + 4 +private def bpRound (M e bb n B : BP) : BP := + let W := e + 2 + 3 * bpEnvelopeWord M bb B + B + M * (bpEnvelopeWork M bb n B + + (2000 * (W + 1) ^ 2 + 1500 * (4 * W + 3) ^ 2 + 3) + + 500 * (4 * W + 4 + B + 1) ^ 2 + e + 11) +private def bpGuard (e bb M v w B : BP) : BP := + let E := 3 * bpEnvelopeWord M bb B + 1 + let W := B + E + bpSumStorage M E + bpGapWord B + 10 + M * (bpEnvelopeWork M bb v B + 6) + bpSumWork M E + + 2000 * (W + 1) ^ 2 + 2000 * (4 * W + 3) ^ 2 + + (1000 * (16 * W + 11) ^ 2 + 1) + bpRound M e bb v B + + (1 + w * (M * (16 * B + 8) + 1)) + + M * (18 * B + 1 + bpGapWork B + 2000 * (W + 1) ^ 2 + + (1000 * (4 * W + 3) ^ 2 + 1) + 6) + 5 +private def preparedBandPolynomial : BP := + let M := .input 0 + let P := .input 1 + let e := .input 2 + let bb := .input 3 + let v := .input 4 + let w := .input 5 + let B := .input 6 + let C := .input 7 + 2 * bpWide M P B C + bpRepresentative M w (4 * B + 20) + bpGuard e bb M v w B + 2 * w + 4 + +def preparedBandBitDegree : ℕ := preparedBandPolynomial.degree + +private def preparedBandEnvironment (e b M P v w B : ℕ) : Fin 8 → ℕ + | 0 => M + | 1 => P + | 2 => e + | 3 => Nat.size b + | 4 => v + | 5 => w + | 6 => B + | _ => ((40 * P + 2) ^ 2 + 1) ^ (M + 1) + +private theorem preparedBandPolynomial_eval (e b M P v w B : ℕ) : + preparedBandPolynomial.eval (preparedBandEnvironment e b M P v w B) = + BinaryFraction.preparedUnskippedBitBudget e b M P v w B := rfl + +theorem preparedUnskippedBitBudget_fixedPower (e b M P v w B S : ℕ) + (hS : 2 ≤ S) (he : e ≤ S) (hb : Nat.size b ≤ S) (hM : M ≤ S) (hP : P ≤ S) + (hv : v ≤ S) (hw : w ≤ S) (hB : B ≤ S) + (hC : ((40 * P + 2) ^ 2 + 1) ^ (M + 1) ≤ S) : + BinaryFraction.preparedUnskippedBitBudget e b M P v w B ≤ S ^ preparedBandBitDegree := by + have henv : ∀ i, preparedBandEnvironment e b M P v w B i ≤ S := by + intro i + fin_cases i <;> simp only [preparedBandEnvironment] <;> assumption + simpa only [preparedBandPolynomial_eval, preparedBandBitDegree] using + preparedBandPolynomial.eval_le_pow _ S hS henv + +/-- The representative tail used to construct the actual online draw range. -/ +def representativeCompleteBitDegree : ℕ := + (bpRepresentative (.input 0) (.input 1) (.input 2)).degree + +theorem representativeCompleteBitBudget_fixedPower (M vertices B X : ℕ) (hX : 2 ≤ X) + (hM : M ≤ X) (hV : vertices ≤ X) (hB : B ≤ X) : + BinaryFraction.representativeCompleteBitBudget M vertices B ≤ X ^ representativeCompleteBitDegree := by + let env : Fin 8 → ℕ := ![M, vertices, B, 0, 0, 0, 0, 0] + have heval : (bpRepresentative (.input 0) (.input 1) (.input 2)).eval env = + BinaryFraction.representativeCompleteBitBudget M vertices B := by rfl + have henv : ∀ i, env i ≤ X := by intro i; fin_cases i <;> simp [env] <;> omega + rw [← heval] + exact FiniteBitPolynomial.eval_le_pow _ env X hX henv + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/PreparedCachedKernelWork.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/PreparedCachedKernelWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..724095b5eb3bea59e6d6ce6b9d0fdc9f0a7fa9f0 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/PreparedCachedKernelWork.lean @@ -0,0 +1,119 @@ +import OAI.Combinatorics.EditApproximation.Geometry.PreparedKernelPolynomial + +namespace OAI + +/-! The complete refinement return includes literal power-denominator +construction, multiplication, division and trimming before cache insertion. -/ + +namespace EditApproximation + +private abbrev CachePoly := FiniteBitPolynomial (Fin 4) +private def cacheSum (M B : CachePoly) : CachePoly := + .bitLength M + B + 2 * (1 + M * (B + 1)) + 2 +private def cacheConnection (M B : CachePoly) : CachePoly := cacheSum (M + 1) (8 * B + 6) +private def cacheAction (M B : CachePoly) : CachePoly := 8 * (40 * B + 22 + cacheSum M B) + 6 +private def cacheRawWidth (M B : CachePoly) : CachePoly := + let W := B + 4 + cacheConnection M (B + 4) + (64 * (B + 4) + 54) + 4 * (B + 4) + 2 + 32 * (W + 2 * cacheAction M W + 1) + 28 +private def cacheReturnPolynomial : CachePoly := + let M := .input 0 + let B := .input 1 + let n := .input 2 + let D := .input 3 + (1 + n * (200 * ((n + 1) * (D + 1) + 1) ^ 2)) + + 5000 * (cacheRawWidth M B + (n * D + 1) + 2) ^ 2 + 1 + +private def cacheEnvironment (M B n D : ℕ) : Fin 4 → ℕ + | 0 => M + | 1 => B + | 2 => n + | _ => D + +def preparedCacheReturnBitDegree : ℕ := cacheReturnPolynomial.degree + +def preparedCachedKernelBitDegree : ℕ := max preparedKernelBitDegree preparedCacheReturnBitDegree + 2 + +attribute [local irreducible] preparedKernelBitDegree preparedCacheReturnBitDegree + +theorem preparedCacheReturnBitBudget_fixedPower (M B n D X : ℕ) (hX : 2 ≤ X) + (hM : M ≤ X) (hB : B ≤ X) (hn : n ≤ X) (hD : D ≤ X) : + BinaryFraction.powerDenominatorBitBudget n (BinaryFraction.preparedKernelWordBudget M B) D ≤ + X ^ preparedCacheReturnBitDegree := by + have heval : cacheReturnPolynomial.eval (cacheEnvironment M B n D) = + BinaryFraction.powerDenominatorBitBudget n (BinaryFraction.preparedKernelWordBudget M B) D := rfl + have henv : ∀ i, cacheEnvironment M B n D i ≤ X := by + intro i + fin_cases i <;> simp only [cacheEnvironment] <;> assumption + rw [← heval] + simpa only [preparedCacheReturnBitDegree] using cacheReturnPolynomial.eval_le_pow _ X hX henv + +theorem preparedCachedKernelBitBudget_fixedPower (N M P F exponent eM eF B n D X : ℕ) + (hX : 2 ≤ X) (hN : Nat.size N ≤ B) (hM : M ≤ X) (hP : P ≤ X) (hF : F ≤ X) + (he : exponent ≤ X) (htheta : 2 ^ exponent ≤ X) (hword : 16 * B + 200 ≤ X) + (hscales : 7 + eM + eF ≤ X) (hV : (40 * P + 2) ^ (2 * M) ≤ X) + (hCartesian : ((40 * P + 2) ^ 2 + 1) ^ (M + 1) ≤ X) + (hrepCount : (B + 1) * (64 * F * P + 2) ^ 2 ≤ X) + (hgroupCount : (B + 1) * ((32 * F + 2) * 2 ^ exponent + 2) ^ 2 ≤ X) + (hn : n ≤ X) (hD : D ≤ X) : + BinaryFraction.preparedKernelBitBudget N M P F exponent eM eF B X + + BinaryFraction.powerDenominatorBitBudget n (BinaryFraction.preparedKernelWordBudget M B) D + 1 ≤ + X ^ preparedCachedKernelBitDegree := by + let degree := max preparedKernelBitDegree preparedCacheReturnBitDegree + have hpositive : 0 < X := by omega + have hk := (preparedKernelBitBudget_fixedPower N M P F exponent eM eF B X + hX hN hM hP hF he htheta hword hscales hV hCartesian hrepCount hgroupCount).trans + (Nat.pow_le_pow_right hpositive (Nat.le_max_left preparedKernelBitDegree preparedCacheReturnBitDegree)) + have hc := (preparedCacheReturnBitBudget_fixedPower M B n D X hX hM (by omega) hn hD).trans + (Nat.pow_le_pow_right hpositive (Nat.le_max_right preparedKernelBitDegree preparedCacheReturnBitDegree)) + change BinaryFraction.preparedKernelBitBudget N M P F exponent eM eF B X ≤ X ^ degree at hk + change BinaryFraction.powerDenominatorBitBudget n (BinaryFraction.preparedKernelWordBudget M B) D ≤ + X ^ degree at hc + have hone : 1 ≤ X ^ degree := Nat.succ_le_of_lt (pow_pos hpositive degree) + have hfour : 4 ≤ X ^ 2 := (show 4 = (2 : ℕ) ^ 2 by decide).trans_le + (Nat.pow_le_pow_left hX 2) + calc + _ ≤ 2 * X ^ degree + 1 := by omega + _ ≤ 4 * X ^ degree := by omega + _ ≤ X ^ 2 * X ^ degree := Nat.mul_le_mul_right _ hfour + _ = X ^ preparedCachedKernelBitDegree := by + rw [← pow_add] + change X ^ (2 + degree) = X ^ (degree + 2) + rw [Nat.add_comm 2 degree] + +namespace BinaryFraction + +theorem cachedPreparedLocalKernelWithWork_bounds {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (N P F exponent H Q eM eF B E S : ℕ) + (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (hPdyadic : ∃ j : ℕ, P = 2 ^ j) + (tau a eta kappa delta : BinaryFraction) + (parentInitial : TargetInterval target.length → BinaryFraction) + (childMass childInitial : Fin M → TargetInterval target.length → BinaryFraction) + (old current : Fin M × TargetInterval target.length → BinaryFraction) + (history : ℕ → Fin M × TargetInterval target.length → BinaryFraction) (t : ℕ) + (draw : CellGroupDraws M F Q) (integer : ℕ → TargetInterval target.length → ℕ) + (query : TargetInterval target.length) + (hb : PreparedKernelInputBounds (nx := source.length) N P F exponent H Q eM eF B E S t + tau a eta kappa delta parentInitial childMass childInitial old current history integer) + (base : List Bool) (hbase : 0 < bitWordValue base) (remaining D V : ℕ) + (hbaseWidth : base.length ≤ D) + (hden : (preparedLocalKernelWithWork source target parent N P F exponent H Q eM eF hP hM hF + tau a eta kappa delta parentInitial childMass childInitial old current history t draw integer query).1.value.den ∣ + bitWordValue base ^ remaining) + (hvalue : |(preparedLocalKernelWithWork source target parent N P F exponent H Q eM eF hP hM hF + tau a eta kappa delta parentInitial childMass childInitial old current history t draw integer query).1.value| ≤ V) : + (cachedPreparedLocalKernelWithWork source target parent N P F exponent H Q eM eF hP hM hF + tau a eta kappa delta parentInitial childMass childInitial old current history t draw integer query + base hbase remaining).1.width ≤ Nat.size V + 2 * (remaining * D + 1) + 1 ∧ + (cachedPreparedLocalKernelWithWork source target parent N P F exponent H Q eM eF hP hM hF + tau a eta kappa delta parentInitial childMass childInitial old current history t draw integer query + base hbase remaining).2 ≤ preparedKernelBitBudget N M P F exponent eM eF B S + + powerDenominatorBitBudget remaining (preparedKernelWordBudget M B) D + 1 := by + have hk := preparedLocalKernelWithWork_bounds source target parent N P F exponent H Q eM eF B E S + hP hM hF hPdyadic tau a eta kappa delta parentInitial childMass childInitial old current history t draw integer query hb + exact finishCachedWithWork_bounds _ base hbase remaining _ D _ V hk.1 hbaseWidth hk.2 hden hvalue + +end BinaryFraction + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/PreparedGroupPolynomial.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/PreparedGroupPolynomial.lean new file mode 100644 index 0000000000000000000000000000000000000000..13eb887e27e1abbdddad3e64b4d8a4b740d6ea6a --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/PreparedGroupPolynomial.lean @@ -0,0 +1,89 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryPreparedCellGroupWork +import OAI.Combinatorics.EditApproximation.Binary.BinarySampledGroupPolynomial +import OAI.Combinatorics.EditApproximation.Geometry.PreparedBandPolynomial + +namespace OAI + +/-! A fixed-degree cap for the complete cell selector, including all band +construction and exact finite-count sampled scores. -/ + +namespace EditApproximation + +private abbrev CP := FiniteBitPolynomial (Fin 4) +private def cpEligibility (B : CP) : CP := + 4000 * (B + 1) ^ 2 + 2100 * (4 * B + 4) ^ 2 + 2000 * (4 * B + 3) ^ 2 + + 2 * (1000 * (16 * B + 13) ^ 2 + 1) + 2 * B + 8 +private def cpGridPoints (n B : CP) : CP := + 2000000 * (B + 100) ^ 2 + n * (1000 * (B + 100) ^ 2 + 5) +private def cpCellStates (l r B : CP) : CP := + cpGridPoints l B + cpGridPoints r B + l * (r * (16 * (17 * B + 78) + 11) + r + 3) + 2 +private def cpCellCenters (P B : CP) : CP := + 100 * (B + 2) ^ 2 + 2000 * (B + 1) ^ 2 + cpCellStates P P (4 * B + 40) + + P * P * (cpEligibility B + 3) + 3 +private def cellGroupPolynomial : CP := + let M := .input 0 + let P := .input 1 + let B := .input 2 + let X := .input 3 + cpCellCenters P B + (P + 1) ^ 2 * (X ^ preparedBandBitDegree + 3) + + (P + 1) ^ 2 * (X ^ sampledGroupBitDegree + 1000 * (X ^ sampledGroupBitDegree + 1) ^ 2 + 3) + + 1 + 2 * X ^ sampledGroupBitDegree + 2 * B + 2 * M + 6 + 2 + +def preparedCellGroupBitDegree : ℕ := cellGroupPolynomial.degree + +private def cellGroupEnvironment (M P B X : ℕ) : Fin 4 → ℕ + | 0 => M + | 1 => P + | 2 => B + | _ => X + +private theorem cellGroupPolynomial_eval (M P B X : ℕ) : + cellGroupPolynomial.eval (cellGroupEnvironment M P B X) = + BinaryFraction.cellCentersBitBudget P P B + (P + 1) ^ 2 * (X ^ preparedBandBitDegree + 3) + + (P + 1) ^ 2 * (X ^ sampledGroupBitDegree + 1000 * (X ^ sampledGroupBitDegree + 1) ^ 2 + 3) + + 1 + 2 * X ^ sampledGroupBitDegree + 2 * B + 2 * M + 6 + 2 := rfl + +theorem preparedCellGroupBitBudget_fixedPower (M T e b P B X : ℕ) + (hX : 2 ≤ X) (hM : M ≤ X) (hT : T ≤ X) (he : e ≤ X) (hb : Nat.size b ≤ X) + (hP : P ≤ X) (hB : B ≤ X) (hV : (40 * P + 2) ^ (2 * M) ≤ X) + (hCartesian : ((40 * P + 2) ^ 2 + 1) ^ (M + 1) ≤ X) : + BinaryFraction.preparedCellGroupBitBudget M T e b P B ≤ X ^ preparedCellGroupBitDegree := by + let V := (40 * P + 2) ^ (2 * M) + have hband := preparedUnskippedBitBudget_fixedPower e b M P V V B X hX he hb hM hP hV hV hB hCartesian + have hmember := sampledMemberBitBudget_fixedPower M T e b V B X hX hM hT he hb hV hB + have hr : BinaryFraction.roundedBandBitBudget e b M V B ≤ X ^ sampledGroupBitDegree := by + apply le_trans _ hmember.2 + unfold BinaryFraction.sampledMemberBitBudget + omega + have hc : BinaryFraction.connectionBitBudget M B ≤ X ^ sampledGroupBitDegree := by + apply le_trans _ hmember.2 + unfold BinaryFraction.sampledMemberBitBudget + omega + have hs : BinaryFraction.selectedGroupBitBudget M T e b ((P + 1) ^ 2) V B ≤ + (P + 1) ^ 2 * (X ^ sampledGroupBitDegree + 1000 * (X ^ sampledGroupBitDegree + 1) ^ 2 + 3) + + 1 + 2 * X ^ sampledGroupBitDegree + 2 * B + 2 * M + 6 := by + unfold BinaryFraction.selectedGroupBitBudget + have hw := Nat.pow_le_pow_left (Nat.add_le_add_right hmember.1 1) 2 + have hm := Nat.mul_le_mul_left ((P + 1) ^ 2) + (show BinaryFraction.sampledMemberBitBudget M T e b V B + + 1000 * (BinaryFraction.sampledMemberWordBudget M T b B + 1) ^ 2 + 3 ≤ + X ^ sampledGroupBitDegree + 1000 * (X ^ sampledGroupBitDegree + 1) ^ 2 + 3 by + exact Nat.add_le_add_right (Nat.add_le_add hmember.2 (Nat.mul_le_mul_left 1000 hw)) 3) + omega + have hmajor : BinaryFraction.preparedCellGroupBitBudget M T e b P B ≤ + cellGroupPolynomial.eval (cellGroupEnvironment M P B X) := by + rw [cellGroupPolynomial_eval] + unfold BinaryFraction.preparedCellGroupBitBudget + have hp := Nat.mul_le_mul_left ((P + 1) ^ 2) (Nat.add_le_add_right hband 3) + change BinaryFraction.cellCentersBitBudget P P B + + (P + 1) ^ 2 * (BinaryFraction.preparedUnskippedBitBudget e b M P V V B + 3) + + BinaryFraction.selectedGroupBitBudget M T e b ((P + 1) ^ 2) V B + 2 ≤ _ + omega + have henv : ∀ i, cellGroupEnvironment M P B X i ≤ X := by + intro i + fin_cases i <;> simp only [cellGroupEnvironment] <;> omega + exact hmajor.trans (cellGroupPolynomial.eval_le_pow _ X hX henv) + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/PreparedInitialPolynomial.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/PreparedInitialPolynomial.lean new file mode 100644 index 0000000000000000000000000000000000000000..4fe49b152b26f0014011a9ede64e1bd862c5876c --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/PreparedInitialPolynomial.lean @@ -0,0 +1,128 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryInitialGridWork +import OAI.Combinatorics.EditApproximation.Binary.BinarySeedMedianWork +import OAI.Combinatorics.EditApproximation.Binary.BinaryWarmupAverage +import OAI.Combinatorics.EditApproximation.Probability.FiniteBitPolynomial +import OAI.Combinatorics.EditApproximation.Binary.BinaryPowerStorage +import OAI.Combinatorics.EditApproximation.Binary.BinaryCachedShellWork + +namespace OAI + +/-! Fixed degrees for the literal initial grid/minimum, trimmed seed +median, and child warmup average. Grid side length is an explicit input. -/ + +namespace EditApproximation + +private abbrev IP := FiniteBitPolynomial (Fin 2) +private def ipCenter (B : IP) : IP := + 2100 * (B + 2) ^ 2 + 2000 * (B + 1) ^ 2 + 2000 * (4 * B + 3) ^ 2 + + 2 * (1000 * (16 * B + 11) ^ 2 + 1) + 2 * B + 5 +private def ipScale (B : IP) : IP := + 4000 * (B + 1) ^ 2 + 4000 * (4 * B + 3) ^ 2 + 2100 * (16 * B + 12) ^ 2 + + 2 * (1000 * (64 * B + 45) ^ 2 + 1) + 2 * B + 7 +private def ipGrid (L B : IP) : IP := 1000 * (B + 2) ^ 2 + L * (100 * (B + 3) ^ 2 + 5) +private def ipBox (L B : IP) : IP := + 96 * (B + 1) + 2 * ipGrid L (B + 2) + L * (L * (16 * (B + 2) + 11) + L + 3) + 6 +private def ipGridScale (L B : IP) : IP := + 100 * (B + 6) ^ 2 + ipBox L (B + 5) + L ^ 2 * (ipCenter (B + 4) + 3) + 2 +private def ipDistance (B : IP) : IP := + 2 * (6000 * (B + 1) ^ 2 + 2) + 6000 * (8 * B + 7) ^ 2 + 4 * B + 3 +private def ipGap (B : IP) : IP := + (6000 * (B + 1) ^ 2 + 1) + (6000 * (8 * B + 7) ^ 2 + 1) + 3 * B + 2 +private def ipConeInput (B : IP) : IP := B + (64 * B + 54) + (64 * B + 54) +private def ipSeed (B : IP) : IP := + 2100 * (B + 2) ^ 2 + 500 * (4 * B + 5) ^ 2 + (1000 * (4 * B + 7) ^ 2 + 1) + B + 3 +private def ipCone (B : IP) : IP := + ipGap B + ipSeed (ipConeInput B) + ipDistance B + 2000 * (ipConeInput B + 1) ^ 2 + + 6000 * (4 * ipConeInput B + 7) ^ 2 + 4 +private def ipMinimumWord (B : IP) : IP := 128 * B + 90 + (32 * ipConeInput (40 * B + 22) + 54) +private def ipMinimum (n B : IP) : IP := + (8 * B + 2) + 2000 * (B + 1) ^ 2 + 6000 * (4 * B + 3) ^ 2 + + 2000 * (32 * B + 23) ^ 2 + n * (ipCone (40 * B + 22) + 3) + + (1 + n * (1000 * (ipMinimumWord B + 1) ^ 2 + 2)) + 2 * B + 6 +private def initialShellPolynomial : IP := + let B := .input 0 + let L := .input 1 + ((B + 1) * (B + 9) + 2 + (B + 1) * (ipScale (B + 4) + 3) + + (B + 1) * (ipGridScale L B + L ^ 2 + 3) + 3) + + ipMinimum ((B + 1) * L ^ 2) (B + 4) + 1 + +def preparedInitialBitDegree : ℕ := initialShellPolynomial.degree + +private def cachedInitialShellPolynomial : IP := + initialShellPolynomial + (1 + 0 * (200 * ((0 + 1) * (1 + 1) + 1) ^ 2) + + 5000 * (ipMinimumWord (.input 0 + 4) + (0 * 1 + 1) + 2) ^ 2 + 1) + 1 + +def preparedCachedInitialBitDegree : ℕ := cachedInitialShellPolynomial.degree + +theorem initialProgramBitBudget_fixedPower (P Amax B X : ℕ) (hX : 2 ≤ X) + (hB : B ≤ X) (hL : 64 * Amax ^ 2 * P + 2 ≤ X) : + BinaryFraction.initialProgramBitBudget P Amax B ≤ X ^ preparedInitialBitDegree := by + let env : Fin 2 → ℕ := ![B, 64 * Amax ^ 2 * P + 2] + have heval : initialShellPolynomial.eval env = BinaryFraction.initialProgramBitBudget P Amax B := by + simp only [initialShellPolynomial, ipScale, ipGridScale, ipBox, ipGrid, ipCenter, ipMinimum, + ipMinimumWord, ipConeInput, ipCone, ipSeed, ipGap, ipDistance, FiniteBitPolynomial.eval] + simp only [env, Matrix.cons_val_zero] + rfl + have henv : ∀ i, env i ≤ X := by intro i; fin_cases i <;> simp [env] <;> assumption + rw [← heval] + exact initialShellPolynomial.eval_le_pow env X hX henv + +theorem cachedInitialProgramBitBudget_fixedPower (P Amax B X : ℕ) (hX : 2 ≤ X) + (hB : B ≤ X) (hL : 64 * Amax ^ 2 * P + 2 ≤ X) : + BinaryFraction.cachedInitialProgramBitBudget P Amax B ≤ X ^ preparedCachedInitialBitDegree := by + let env : Fin 2 → ℕ := ![B, 64 * Amax ^ 2 * P + 2] + have heval : cachedInitialShellPolynomial.eval env = BinaryFraction.cachedInitialProgramBitBudget P Amax B := by + simp only [cachedInitialShellPolynomial, initialShellPolynomial, ipScale, ipGridScale, ipBox, ipGrid, + ipCenter, ipMinimum, ipMinimumWord, ipConeInput, ipCone, ipSeed, ipGap, ipDistance, + FiniteBitPolynomial.eval] + simp only [env, Matrix.cons_val_zero] + rfl + have henv : ∀ i, env i ≤ X := by intro i; fin_cases i <;> simp [env] <;> assumption + rw [← heval] + exact cachedInitialShellPolynomial.eval_le_pow env X hX henv + +private def medianShellPolynomial : IP := + let n := .input 0 + let B := .input 1 + let ceiling := 2000 * (B + 1) ^ 2 + 500 * (4 * B + 3) ^ 2 + B + 3 + (n * (ceiling + 3) + (n + 1) ^ 2 * (8 * (4 * B + 4) + 6) + + n + 4 * (B + (4 * B + 4)) + 3 + B + 3) + 12 * B + 14 + +def preparedMedianBitDegree : ℕ := medianShellPolynomial.degree + +theorem seedMedianBitBudget_fixedPower (n B X : ℕ) (hX : 2 ≤ X) (hn : n ≤ X) (hB : B ≤ X) : + BinaryFraction.seedMedianBitBudget n B ≤ X ^ preparedMedianBitDegree := by + let env : Fin 2 → ℕ := ![n, B] + have heval : medianShellPolynomial.eval env = BinaryFraction.seedMedianBitBudget n B := by + simp only [medianShellPolynomial, FiniteBitPolynomial.eval] + simp only [env, Matrix.cons_val_zero] + rfl + have henv : ∀ i, env i ≤ X := by intro i; fin_cases i <;> simp [env] <;> assumption + rw [← heval] + exact medianShellPolynomial.eval_le_pow env X hX henv + +private def ipStoredSumWord (n B : IP) : IP := + (B + 1) + .bitLength n + 2 * (B + 2) + 2 * (1 + n * ((B + 1) + (B + 1))) + 1 +private def ipMassStorage (n B : IP) : IP := .bitLength n + B + 2 * (1 + n * (B + 1)) + 2 +private def averageShellPolynomial : IP := + let n := .input 0 + let B := .input 1 + (1 + n * (100000 * (ipStoredSumWord n B + 1) ^ 2)) + 6 * n + + 2100 * (ipMassStorage n B + .bitLength n + 4) ^ 2 + .bitLength n + 2 + +def preparedAverageBitDegree : ℕ := averageShellPolynomial.degree + +theorem warmupAverageBitBudget_fixedPower (n B X : ℕ) (hX : 2 ≤ X) (hn : n ≤ X) (hB : B ≤ X) : + BinaryFraction.warmupAverageBitBudget n B ≤ X ^ preparedAverageBitDegree := by + let env : Fin 2 → ℕ := ![n, B] + have heval : averageShellPolynomial.eval env = BinaryFraction.warmupAverageBitBudget n B := by + simp only [averageShellPolynomial, ipStoredSumWord, ipMassStorage, FiniteBitPolynomial.eval] + simp only [env, Matrix.cons_val_zero] + rfl + have henv : ∀ i, env i ≤ X := by intro i; fin_cases i <;> simp [env] <;> assumption + rw [← heval] + exact averageShellPolynomial.eval_le_pow env X hX henv + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/PreparedKernelPolynomial.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/PreparedKernelPolynomial.lean new file mode 100644 index 0000000000000000000000000000000000000000..1ed547c86a2128cf3f500ccbb6b00cfdf6065009 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/PreparedKernelPolynomial.lean @@ -0,0 +1,59 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryPreparedKernelWork +import OAI.Combinatorics.EditApproximation.Geometry.PreparedLocalGroupPolynomial +import OAI.Combinatorics.EditApproximation.Geometry.PreparedShellPolynomial + +namespace OAI + +/-! One fixed degree bounds every Boolean operation of the complete local +refinement kernel, after primitive word and finite-grid bounds are supplied. -/ + +namespace EditApproximation + +attribute [local irreducible] representativeShellDegree preparedLocalGroupBitDegree + onlineShellDegree physicalShellDegree + +def preparedKernelBitDegree : ℕ := + max representativeShellDegree (max preparedLocalGroupBitDegree (max onlineShellDegree physicalShellDegree)) + 3 + +theorem preparedKernelBitBudget_fixedPower (N M P F exponent eM eF B X : ℕ) + (hX : 2 ≤ X) (hN : Nat.size N ≤ B) (hM : M ≤ X) (hP : P ≤ X) (hF : F ≤ X) + (he : exponent ≤ X) (htheta : 2 ^ exponent ≤ X) (hword : 16 * B + 200 ≤ X) + (hscales : 7 + eM + eF ≤ X) (hV : (40 * P + 2) ^ (2 * M) ≤ X) + (hCartesian : ((40 * P + 2) ^ 2 + 1) ^ (M + 1) ≤ X) + (hrepCount : (B + 1) * (64 * F * P + 2) ^ 2 ≤ X) + (hgroupCount : (B + 1) * ((32 * F + 2) * 2 ^ exponent + 2) ^ 2 ≤ X) : + BinaryFraction.preparedKernelBitBudget N M P F exponent eM eF B X ≤ X ^ preparedKernelBitDegree := by + let D := max representativeShellDegree + (max preparedLocalGroupBitDegree (max onlineShellDegree physicalShellDegree)) + have hB : B ≤ X := by omega + have hr := (localRepresentativesBitBudget_fixedPower P F B X hX hP hF hB).trans + (Nat.pow_le_pow_right (by omega : 0 < X) (show representativeShellDegree ≤ D by + exact Nat.le_max_left _ _)) + have hg := (preparedLocalGroupsBitBudget_fixedPower N M P F exponent eM eF B X hX hN hM hP hF + he htheta hword hscales hV hCartesian).trans + (Nat.pow_le_pow_right (by omega : 0 < X) (show preparedLocalGroupBitDegree ≤ D by + exact (Nat.le_max_left _ _).trans (Nat.le_max_right _ _))) + have ho := (preparedLocalOnlineBitBudget_fixedPower M P B X hX hM hB hV).trans + (Nat.pow_le_pow_right (by omega : 0 < X) (show onlineShellDegree ≤ D by + exact (Nat.le_max_left _ _).trans ((Nat.le_max_right _ _).trans (Nat.le_max_right _ _)))) + have hp := (physicalContinuationBitBudget_fixedPower M P _ _ (B + 1) (B + 4) X hX hM hP + hrepCount hgroupCount (by omega) (by omega) hV hCartesian).trans + (Nat.pow_le_pow_right (by omega : 0 < X) (show physicalShellDegree ≤ D by + exact (Nat.le_max_right _ _).trans ((Nat.le_max_right _ _).trans (Nat.le_max_right _ _)))) + have hone : 1 ≤ X ^ D := Nat.succ_le_of_lt (pow_pos (by omega : 0 < X) D) + have height : 8 ≤ X ^ 3 := by + calc + 8 = (2 : ℕ) ^ 3 := by decide + _ ≤ X ^ 3 := Nat.pow_le_pow_left hX 3 + calc + _ ≤ 4 * X ^ D + 4 := by unfold BinaryFraction.preparedKernelBitBudget; omega + _ ≤ 8 * X ^ D := by omega + _ ≤ X ^ 3 * X ^ D := Nat.mul_le_mul_right _ height + _ = X ^ preparedKernelBitDegree := by + rw [← pow_add] + change X ^ (3 + D) = X ^ (D + 3) + rw [Nat.add_comm 3 D] + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/PreparedLocalGroupPolynomial.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/PreparedLocalGroupPolynomial.lean new file mode 100644 index 0000000000000000000000000000000000000000..b56c0253477b9bdab6d92be69aae492398e5fbf5 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/PreparedLocalGroupPolynomial.lean @@ -0,0 +1,120 @@ +import OAI.Combinatorics.EditApproximation.Geometry.PreparedGroupPolynomial +import OAI.Combinatorics.EditApproximation.Binary.BinaryPreparedLocalGroupWork + +namespace OAI + +/-! A fixed-degree cap on all whole-cell loops at a query. Distance scales +enter through their bit length; their numeric size is never charged. -/ + +namespace EditApproximation + +private abbrev LP := FiniteBitPolynomial (Fin 8) +private def lpGuard (B : LP) : LP := + 4000 * (B + 1) ^ 2 + 2100 * (4 * B + 4) ^ 2 + 2000 * (4 * B + 3) ^ 2 + + 2 * (1000 * (16 * B + 13) ^ 2 + 1) + 2 * B + 8 +private def lpCellSetup (B : LP) : LP := + 100 * (B + 1) + 4200 * (B + 6) ^ 2 + 400 * (4 * B + 21) ^ 2 + 100 * (4 * B + 25) +private def lpTargetCells (K B : LP) : LP := 2 * lpCellSetup B + K + K + K * (5 * K + 3) + 2 +private def lpScales (eM eF B : LP) : LP := + (7 + eM + eF) * (eM + B + eF + 13) + .bitLength eM + .bitLength B + .bitLength eF + 8 +private def localGroupPolynomial : LP := + let F := .input 0 + let thetaPow := .input 1 + let B := .input 2 + let eM := .input 3 + let eF := .input 4 + let X := .input 5 + let K := (32 * F + 2) * thetaPow + 2 + let scale := 2000 * (B + 4) ^ 2 + 500 * (B + 1) ^ 2 + lpTargetCells K (4 * B + 40) + + K ^ 2 * (lpScales eM eF B + X ^ preparedCellGroupBitDegree + 4) + B + 4 + (B + 1) * (lpGuard (B + 3) + scale + B + 4 + K ^ 2 + 3) + (B + 1) + B + 2 + +def preparedLocalGroupBitDegree : ℕ := localGroupPolynomial.degree + +private def localGroupEnvironment (F thetaPow B eM eF X : ℕ) : Fin 8 → ℕ + | 0 => F + | 1 => thetaPow + | 2 => B + | 3 => eM + | 4 => eF + | 5 => X + | _ => 0 + +private def localGroupMajorant (F thetaPow B eM eF X : ℕ) : ℕ := + let K := (32 * F + 2) * thetaPow + 2 + let scale := 2000 * (B + 4) ^ 2 + 500 * (B + 1) ^ 2 + + BinaryFraction.targetCellsBitBudget K K (4 * B + 40) + + K ^ 2 * (BinaryFraction.groupScalesBitBudget eM B eF + X ^ preparedCellGroupBitDegree + 4) + B + 4 + (B + 1) * (BinaryFraction.localEligibilityBitBudget (B + 3) + scale + B + 4 + K ^ 2 + 3) + + (B + 1) + B + 2 + +private theorem localGroupPolynomial_eval (F thetaPow B eM eF X : ℕ) : + localGroupPolynomial.eval (localGroupEnvironment F thetaPow B eM eF X) = + localGroupMajorant F thetaPow B eM eF X := rfl + +theorem preparedLocalGroupsBitBudget_fixedPower (N M P F exponent eM eF B X : ℕ) + (hX : 2 ≤ X) (hN : Nat.size N ≤ B) (hM : M ≤ X) (hP : P ≤ X) (hF : F ≤ X) + (he : exponent ≤ X) (htheta : 2 ^ exponent ≤ X) (hword : 16 * B + 200 ≤ X) + (hscales : 7 + eM + eF ≤ X) (hV : (40 * P + 2) ^ (2 * M) ≤ X) + (hCartesian : ((40 * P + 2) ^ 2 + 1) ^ (M + 1) ≤ X) : + BinaryFraction.preparedLocalGroupsBitBudget N M P F exponent eM eF B ≤ + X ^ preparedLocalGroupBitDegree := by + let count := max 1 N.bits.length + let K := (32 * F + 2) * 2 ^ exponent + 2 + let scale := 2000 * (B + 4) ^ 2 + 500 * (B + 1) ^ 2 + + BinaryFraction.targetCellsBitBudget K K (4 * B + 40) + + K ^ 2 * (BinaryFraction.groupScalesBitBudget eM B eF + X ^ preparedCellGroupBitDegree + 4) + B + 4 + let cost := BinaryFraction.localEligibilityBitBudget (B + 3) + scale + B + 4 + K ^ 2 + 3 + have hcount : count ≤ B + 1 := by dsimp only [count]; rw [Nat.size_eq_bits_len]; omega + have hscale (eb : ℕ) (heb : eb ∈ List.range count) : + BinaryFraction.preparedLocalGroupScaleBitBudget M P F exponent eM eF eb B ≤ scale := by + have heB : eb ≤ B := by have := List.mem_range.mp heb; omega + have hbb : Nat.size (2 ^ eb) ≤ X := by rw [Nat.size_pow]; omega + have hc := preparedCellGroupBitBudget_fixedPower M (7 + eM + eF) exponent (2 ^ eb) P (16 * B + 200) X + hX hM hscales he hbb hP hword hV hCartesian + have hs : BinaryFraction.groupScalesBitBudget eM eb eF ≤ + BinaryFraction.groupScalesBitBudget eM B eF := by + unfold BinaryFraction.groupScalesBitBudget + gcongr + exact Nat.size_le_size heB + unfold BinaryFraction.preparedLocalGroupScaleBitBudget + change 2000 * (B + 4) ^ 2 + 500 * (B + 1) ^ 2 + + BinaryFraction.targetCellsBitBudget K K (4 * B + 40) + K ^ 2 * + (BinaryFraction.groupScalesBitBudget eM eb eF + + BinaryFraction.preparedCellGroupBitBudget M (7 + eM + eF) exponent (2 ^ eb) P (16 * B + 200) + 4) + eb + 4 ≤ _ + dsimp only [scale] + gcongr + have hsum : ((List.range count).map fun eb => BinaryFraction.localEligibilityBitBudget (B + 3) + + BinaryFraction.preparedLocalGroupScaleBitBudget M P F exponent eM eF eb B + eb + 4 + K ^ 2 + 3).sum ≤ + count * cost := by + have hh := List.sum_le_sum (l := List.range count) + (f := fun eb : ℕ => BinaryFraction.localEligibilityBitBudget (B + 3) + + BinaryFraction.preparedLocalGroupScaleBitBudget M P F exponent eM eF eb B + eb + 4 + K ^ 2 + 3) + (g := fun _ => cost) (by + intro eb heb + have heB : eb ≤ B := by have := List.mem_range.mp heb; omega + have hs := hscale eb heb + dsimp only [cost] + omega) + simpa [List.map_const', List.length_range, List.sum_replicate, nsmul_eq_mul] using hh + have hmajor : BinaryFraction.preparedLocalGroupsBitBudget N M P F exponent eM eF B ≤ + localGroupMajorant F (2 ^ exponent) B eM eF X := by + have hh := hsum.trans (Nat.mul_le_mul_right cost hcount) + unfold BinaryFraction.preparedLocalGroupsBitBudget + change ((List.range count).map fun eb : ℕ => BinaryFraction.localEligibilityBitBudget (B + 3) + + BinaryFraction.preparedLocalGroupScaleBitBudget M P F exponent eM eF eb B + eb + 4 + K ^ 2 + 3).sum + + count + N.bits.length + 2 ≤ _ + unfold localGroupMajorant + change _ ≤ (B + 1) * cost + (B + 1) + B + 2 + have hNbits : N.bits.length ≤ B := by simpa only [Nat.size_eq_bits_len] using hN + omega + have henv : ∀ i, localGroupEnvironment F (2 ^ exponent) B eM eF X i ≤ X := by + intro i + fin_cases i <;> simp [localGroupEnvironment] <;> omega + exact hmajor.trans (by + rw [← localGroupPolynomial_eval] + exact localGroupPolynomial.eval_le_pow _ X hX henv) + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/PreparedShellPolynomial.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/PreparedShellPolynomial.lean new file mode 100644 index 0000000000000000000000000000000000000000..c115314c9adfd8c7e7c15aa7ce33cefa5ef813b3 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/PreparedShellPolynomial.lean @@ -0,0 +1,129 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryPreparedLocalOnlineWork +import OAI.Combinatorics.EditApproximation.Binary.BinaryPhysicalContinuationWork +import OAI.Combinatorics.EditApproximation.Probability.FiniteBitPolynomial + +namespace OAI + +/-! Fixed-degree envelopes for the literal representative, online outer, +and continuation loops. Large action counts are explicit numeric inputs. -/ + +namespace EditApproximation + +attribute [local irreducible] preparedBandBitDegree sampledOnlineBitDegree + +private abbrev SP := FiniteBitPolynomial (Fin 8) +private def spGuard (B : SP) : SP := + 4000 * (B + 1) ^ 2 + 2100 * (4 * B + 4) ^ 2 + 2000 * (4 * B + 3) ^ 2 + + 2 * (1000 * (16 * B + 13) ^ 2 + 1) + 2 * B + 8 +private def spGrid (n B : SP) : SP := 1000 * (B + 2) ^ 2 + n * (100 * (B + 3) ^ 2 + 5) +private def spBox (n B : SP) : SP := + 96 * (B + 1) + 2 * spGrid n (B + 2) + n * (n * (16 * (B + 2) + 11) + n + 3) + 6 +private def spQuery (B : SP) : SP := (B + 1) * (spGuard (B + 4) + B + 5) + 2 * B + 3 +private def representativeShell : SP := + let P := .input 0 + let F := .input 1 + let B := .input 2 + let C := B + 4 + let L := 64 * F * P + 2 + spQuery B + 500 * (B + 1) ^ 2 + + (B + 1) * (100 * (C + 2) ^ 2 + spBox L C + L ^ 2 * (spGuard C + 3) + + L ^ 2 * 4 + B + 6 + L ^ 2 + 3) + 3 + +private def spCoordinates (M V B : SP) : SP := + V * (5 * M + 3) + (V * M + 1) ^ 2 * (24 * B + 12) + 1 +private def spPower (n B : SP) : SP := 1 + n * (200 * ((n + 1) * (B + 1) + 1) ^ 2) +private def spOnline (M V B X : SP) : SP := + 2 * X ^ preparedBandBitDegree + (spCoordinates M V B + 40 * (B + 4) + spPower 80 (B + 4) + 3) + + (10000 * (B + 3) ^ 2 + 200 * (4 * B + 6) ^ 2 + B + 2) + X ^ sampledOnlineBitDegree + 3 +private def onlineShell : SP := + let M := .input 0 + let V := .input 1 + let B := .input 2 + let X := .input 3 + let W := B + 4 + spQuery B + (B + 1) * (100 * (W + 2) ^ 2 + (500 * (W + 1) ^ 2 + 1) + + spGuard W + spOnline M V W X + B + 4 + 3) + 1 + +private def spSumStorage (n B : SP) : SP := .bitLength n + B + 2 * (1 + n * (B + 1)) + 2 +private def spSumWord (n B : SP) : SP := + (B + 1) + .bitLength n + 2 * (B + 2) + 2 * (1 + n * ((B + 1) + (B + 1))) + 1 +private def spSumWork (n B : SP) : SP := 1 + n * (100000 * (spSumWord n B + 1) ^ 2) +private def spConnectionWord (M B : SP) : SP := spSumStorage (M + 1) (8 * B + 6) +private def spConnectionWork (M B : SP) : SP := + (M + 1) * (6000 * (B + 1) ^ 2 + 4) + M * (2 * B + 6) + + spSumWork (M + 1) (8 * B + 6) + 6 * (M + 1) + 1 +private def spActionWord (M B : SP) : SP := 8 * (40 * B + 22 + spSumStorage M B) + 6 +private def spActionWork (M B C : SP) : SP := + C + 2000 * (B + 1) ^ 2 + 6000 * (5 * B + 3) ^ 2 + spSumWork M B + 6 * M + + 6000 * (40 * B + 22 + spSumStorage M B + 1) ^ 2 + 3 +private def spBellman (M n B F C : SP) : SP := + n * (spActionWork M B C + 3) + (1 + n * (1000 * (F + spActionWord M B + 1) ^ 2 + 2)) + 1 +private def spUpdate (B : SP) : SP := + 6000 * (B + 1) ^ 2 + 2100 * (8 * B + 8) ^ 2 + 2 * (1000 * (32 * B + 29) ^ 2 + 1) + 2 +private def spContinuation (M nw ng no B C : SP) : SP := + spBellman M nw B B C + spBellman M ng B (B + spActionWord M B) C + + no * (spActionWork M B C + 3) + (2 + no * (1000 * (spActionWord M B + 1) ^ 2 + 2)) + + spUpdate (B + 2 * spActionWord M B + 1) + 3 +private def physicalShell : SP := + let M := .input 0 + let P := .input 1 + let nr := .input 2 + let ng := .input 3 + let no := .input 4 + let B := .input 5 + let V := .input 6 + let Cart := .input 7 + let wide := M * (10000 * (B + 12) ^ 2 + spBox (40 * P + 2) (B + 12) + 6) + + (M + 1) * (6 * M + 10) * Cart + 1 + let W := B + spConnectionWord M B + (64 * B + 54) + 4 * B + 2 + let distance := 2 * (6000 * (B + 1) ^ 2 + 2) + 6000 * (8 * B + 7) ^ 2 + 4 * B + 3 + nr * (wide + V * (spConnectionWork M B + 2 * B + 2 * M + 6) + 1 + V + 3) + + 2000 * (B + 1) ^ 2 + spContinuation M (nr * V) ng no W distance + 1 + +def representativeShellDegree : ℕ := representativeShell.degree +def onlineShellDegree : ℕ := onlineShell.degree +def physicalShellDegree : ℕ := physicalShell.degree + +theorem localRepresentativesBitBudget_fixedPower (P F B X : ℕ) (hX : 2 ≤ X) + (hP : P ≤ X) (hF : F ≤ X) (hB : B ≤ X) : + BinaryFraction.localRepresentativesBitBudget P F B ≤ X ^ representativeShellDegree := by + let env : Fin 8 → ℕ := ![P, F, B, 0, 0, 0, 0, 0] + have heval : representativeShell.eval env = BinaryFraction.localRepresentativesBitBudget P F B := by + simp only [representativeShell, spQuery, spGuard, spBox, spGrid, FiniteBitPolynomial.eval] + simp only [env, Matrix.cons_val_zero] + rfl + have henv : ∀ i, env i ≤ X := by intro i; fin_cases i <;> simp [env] <;> omega + rw [← heval] + exact representativeShell.eval_le_pow env X hX henv + +theorem preparedLocalOnlineBitBudget_fixedPower (M P B X : ℕ) (hX : 2 ≤ X) + (hM : M ≤ X) (hB : B ≤ X) (hV : (40 * P + 2) ^ (2 * M) ≤ X) : + BinaryFraction.preparedLocalOnlineBitBudget M P B X ≤ X ^ onlineShellDegree := by + let env : Fin 8 → ℕ := ![M, (40 * P + 2) ^ (2 * M), B, X, 0, 0, 0, 0] + have heval : onlineShell.eval env = BinaryFraction.preparedLocalOnlineBitBudget M P B X := by + simp only [onlineShell, spQuery, spGuard, spOnline, spCoordinates, spPower, FiniteBitPolynomial.eval] + simp only [env, Matrix.cons_val_zero] + rfl + have henv : ∀ i, env i ≤ X := by intro i; fin_cases i <;> simp [env] <;> omega + rw [← heval] + exact onlineShell.eval_le_pow env X hX henv + +theorem physicalContinuationBitBudget_fixedPower (M P nr ng no B X : ℕ) (hX : 2 ≤ X) + (hM : M ≤ X) (hP : P ≤ X) (hr : nr ≤ X) (hg : ng ≤ X) (ho : no ≤ X) (hB : B ≤ X) + (hV : (40 * P + 2) ^ (2 * M) ≤ X) + (hCart : ((40 * P + 2) ^ 2 + 1) ^ (M + 1) ≤ X) : + BinaryFraction.physicalContinuationBitBudget M P nr ng no B ≤ X ^ physicalShellDegree := by + let env : Fin 8 → ℕ := ![M, P, nr, ng, no, B, (40 * P + 2) ^ (2 * M), ((40 * P + 2) ^ 2 + 1) ^ (M + 1)] + have heval : physicalShell.eval env = BinaryFraction.physicalContinuationBitBudget M P nr ng no B := by + simp only [physicalShell, spConnectionWord, spSumStorage, spBox, spGrid, spConnectionWork, + spSumWork, spSumWord, spContinuation, spBellman, spActionWork, spActionWord, spUpdate, + FiniteBitPolynomial.eval] + simp only [env, Matrix.cons_val_zero] + rfl + have henv : ∀ i, env i ≤ X := by intro i; fin_cases i <;> simp [env] <;> omega + rw [← heval] + exact physicalShell.eval_le_pow env X hX henv + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/PreparedWarmupPolynomial.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/PreparedWarmupPolynomial.lean new file mode 100644 index 0000000000000000000000000000000000000000..5c28a9244ff77b0bfd8c00fedfecad18cd04cf82 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/PreparedWarmupPolynomial.lean @@ -0,0 +1,76 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryLocalWarmupWork +import OAI.Combinatorics.EditApproximation.Geometry.PreparedCachedKernelWork + +namespace OAI + +/-! The initial warmup Bellman scan and its cache return are covered by +the same fixed polynomial envelope as the full continuation. -/ + +namespace EditApproximation + +attribute [local irreducible] representativeShellDegree physicalShellDegree + preparedCacheReturnBitDegree + +private theorem warmup_le_continuation (M P F B : ℕ) : + BinaryFraction.localWarmupBitBudget M P F B ≤ + BinaryFraction.localRepresentativesBitBudget P F B + + BinaryFraction.physicalContinuationBitBudget M P ((B + 1) * (64 * F * P + 2) ^ 2) + 0 0 (B + 4) + 3 := by + unfold BinaryFraction.localWarmupBitBudget BinaryFraction.physicalContinuationBitBudget + BinaryFraction.localContinuationBitBudget + dsimp only + simp only [Nat.zero_mul, Nat.add_assoc, Nat.reduceAdd] + omega + +private theorem warmup_width_le_continuation (M B : ℕ) : + BinaryFraction.localWarmupWordBudget M B ≤ BinaryFraction.preparedKernelWordBudget M B := by + unfold BinaryFraction.localWarmupWordBudget BinaryFraction.preparedKernelWordBudget + BinaryFraction.localContinuationWordBudget BinaryFraction.localContinuationInputBudget + BinaryFraction.refinementUpdateWordBudget + dsimp only + omega + +def preparedWarmupBitDegree : ℕ := + max representativeShellDegree (max physicalShellDegree preparedCacheReturnBitDegree) + 3 + +theorem cachedWarmupBitBudget_fixedPower (M P F B X : ℕ) (hX : 2 ≤ X) + (hM : M ≤ X) (hP : P ≤ X) (hF : F ≤ X) (hB : B + 4 ≤ X) + (hrep : (B + 1) * (64 * F * P + 2) ^ 2 ≤ X) + (hV : (40 * P + 2) ^ (2 * M) ≤ X) + (hCartesian : ((40 * P + 2) ^ 2 + 1) ^ (M + 1) ≤ X) : + BinaryFraction.localWarmupBitBudget M P F B + + BinaryFraction.powerDenominatorBitBudget 0 (BinaryFraction.localWarmupWordBudget M B) 1 + 1 ≤ + X ^ preparedWarmupBitDegree := by + let D := max representativeShellDegree (max physicalShellDegree preparedCacheReturnBitDegree) + have hpos : 0 < X := by omega + have hr := (localRepresentativesBitBudget_fixedPower P F B X hX hP hF (by omega)).trans + (Nat.pow_le_pow_right hpos (show representativeShellDegree ≤ D from Nat.le_max_left _ _)) + have hc := (physicalContinuationBitBudget_fixedPower M P _ 0 0 (B + 4) X hX hM hP hrep + (Nat.zero_le _) (Nat.zero_le _) hB hV hCartesian).trans + (Nat.pow_le_pow_right hpos (show physicalShellDegree ≤ D from + (Nat.le_max_left _ _).trans (Nat.le_max_right _ _))) + have hret := (preparedCacheReturnBitBudget_fixedPower M B 0 1 X hX hM (by omega) + (Nat.zero_le _) (by omega)).trans + (Nat.pow_le_pow_right hpos (show preparedCacheReturnBitDegree ≤ D from + (Nat.le_max_right _ _).trans (Nat.le_max_right _ _))) + have hreturn : BinaryFraction.powerDenominatorBitBudget 0 (BinaryFraction.localWarmupWordBudget M B) 1 ≤ + X ^ D := by + apply le_trans _ hret + unfold BinaryFraction.powerDenominatorBitBudget + gcongr + exact warmup_width_le_continuation M B + have hw := warmup_le_continuation M P F B + have hone : 1 ≤ X ^ D := Nat.succ_le_of_lt (pow_pos hpos D) + have he : 8 ≤ X ^ 3 := (show 8 = (2 : ℕ) ^ 3 by decide).trans_le (Nat.pow_le_pow_left hX 3) + calc + _ ≤ 3 * X ^ D + 4 := by omega + _ ≤ 8 * X ^ D := by omega + _ ≤ X ^ 3 * X ^ D := Nat.mul_le_mul_right _ he + _ = X ^ preparedWarmupBitDegree := by + rw [← pow_add] + change X ^ (3 + D) = X ^ (D + 3) + rw [Nat.add_comm 3 D] + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/PublishedInputs.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/PublishedInputs.lean new file mode 100644 index 0000000000000000000000000000000000000000..f8dece98e01c839588df2f89da4af233fe57047e --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/PublishedInputs.lean @@ -0,0 +1,43 @@ +import Mathlib + +namespace OAI + +/-! +# Finite scalar Bernstein concentration + +The only concentration input needed by the coarse estimator and the shared +group sampler is finite scalar Bernstein: Joel A. Tropp, *ACM 217: +Probability in High Dimensions*, Caltech CMS Lecture Notes 2021-01, +corrected March 2023, Theorem 4.16 (printed p. 36). +https://tropp.caltech.edu/notes/Tro21-Probability-High-LN-corr.pdf + +`FiniteBernsteinInput` states the bound for centered bounded finite sums +with an upper bound on their summed variances. Independence identifies the +variance of the sum with the sum of the variances. Positivity of the proxy +avoids the zero-denominator case. +-/ + +namespace EditApproximation + +open MeasureTheory ProbabilityTheory +open scoped BigOperators + +/-- The finite centered-sum specialization of Tropp, Theorem 4.16. +This is the exact Lean proposition to be passed explicitly to downstream +concentration theorems. -/ +def FiniteBernsteinInput {Ω : Type*} [MeasurableSpace Ω] + (μ : Measure Ω) [IsProbabilityMeasure μ] : Prop := + ∀ (n : ℕ) (X : Fin n → Ω → ℝ) (bound varianceProxy deviation : ℝ), + 0 < bound → 0 < varianceProxy → 0 < deviation → + iIndepFun X μ → (∀ i, Measurable (X i)) → + (∀ i, Integrable (X i) μ) → + (∀ i, (∫ ω, X i ω ∂μ) = 0) → + (∀ i, ∀ᵐ ω ∂μ, |X i ω| ≤ bound) → + (∑ i, ∫ ω, (X i ω) ^ 2 ∂μ) ≤ varianceProxy → + μ.real {ω | deviation ≤ |∑ i, X i ω|} ≤ + 2 * Real.exp (-deviation ^ 2 / + (2 * varianceProxy + (2 / 3 : ℝ) * bound * deviation)) + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/RankedMemoAddressWork.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/RankedMemoAddressWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..3d6d74c0af9882019c8e2677ee7fc644d326f826 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/RankedMemoAddressWork.lean @@ -0,0 +1,68 @@ +import OAI.Combinatorics.EditApproximation.Geometry.MemoCodeWork +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation +namespace FiniteQuery + +/-- Annotate exactly the requests made by an existing adaptive run. -/ + + + theorem requestWork_le {ι κ : Type*} (ask : ι → BinaryMemo ℚ → RecursiveMemoResult κ) + (cost : ι → BinaryMemo ℚ → ℕ) (C : ℕ) + (hcost : ∀ key memory, cost key memory ≤ C * (ask key memory).requests) + (program : FiniteQuery ι) (memory : BinaryMemo ℚ) : + requestWork ask cost program memory ≤ C * (run ask program memory).requests := by + induction program generalizing memory with + | done value => simp only [requestWork, run, Nat.mul_zero, le_refl] + | read key next ih => + have hfirst := hcost key memory + have hrest := ih (ask key memory).value (ask key memory).memory + simp only [requestWork, run, Nat.mul_add] + exact Nat.add_le_add hfirst hrest + +end FiniteQuery + +/-- Code construction is incurred for lookup and, on a miss, for insertion. +The recursive calls use the exact same returned values and cache states. -/ + + + theorem rankedMemoAddressWork_le {κ : Type*} (rank : κ → ℕ) + (program : (key : κ) → FiniteQuery {child : κ // rank child < rank key}) + (bits : ℕ) (encode cost : κ → ℕ) (C : ℕ) (hcost : ∀ key, cost key ≤ C) + (key : κ) (memory : BinaryMemo ℚ) : + rankedMemoAddressWork rank program bits encode cost key memory ≤ + 2 * C * (rankedMemoEvaluate rank program bits encode key memory).requests := by + have hall : ∀ level key, rank key = level → ∀ memory, + rankedMemoAddressWork rank program bits encode cost key memory ≤ + 2 * C * (rankedMemoEvaluate rank program bits encode key memory).requests := by + intro level + induction level using Nat.strong_induction_on with + | h level ih => + intro key hlevel memory + rw [rankedMemoAddressWork, rankedMemoEvaluate] + split + · rename_i result hfound + simp only + simpa only [Nat.mul_one] using (hcost key).trans (by omega : C ≤ 2 * C) + · rename_i hfound + simp only + have hchildren : ∀ (child : {child : κ // rank child < rank key}) previous, + rankedMemoAddressWork rank program bits encode cost child.val previous ≤ + 2 * C * (rankedMemoEvaluate rank program bits encode child.val previous).requests := by + intro child previous + exact ih (rank child.val) (by simpa only [← hlevel] using child.property) child.val rfl previous + have hr := FiniteQuery.requestWork_le + (fun child previous => rankedMemoEvaluate rank program bits encode child.val previous) + (fun child previous => rankedMemoAddressWork rank program bits encode cost child.val previous) + (2 * C) hchildren (program key) memory + have hk := hcost key + rw [Nat.mul_add, Nat.mul_one] + omega + exact hall (rank key) key rfl memory + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/RankedMemoKernelFresh.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/RankedMemoKernelFresh.lean new file mode 100644 index 0000000000000000000000000000000000000000..e395fd5ace60f7018527416fb63a40fd9f3d819d --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/RankedMemoKernelFresh.lean @@ -0,0 +1,49 @@ +import OAI.Combinatorics.EditApproximation.Geometry.RankedMemoKernelWork + +namespace OAI + +namespace EditApproximation +namespace FiniteQuery + +theorem requestWork_eq_fresh_sum {ι κ : Type*} + (ask : ι → BinaryMemo ℚ → RecursiveMemoResult κ) + (cost : ι → BinaryMemo ℚ → ℕ) (weight : κ → ℕ) + (hcost : ∀ key memory, cost key memory = ((ask key memory).freshKeys.map weight).sum) + (program : FiniteQuery ι) (memory : BinaryMemo ℚ) : + requestWork ask cost program memory = ((run ask program memory).freshKeys.map weight).sum := by + induction program generalizing memory with + | done value => rfl + | read key next ih => + simp only [requestWork, run, hcost, ih, List.map_append, List.sum_append] + +end FiniteQuery + +/-- The local kernel annotation is exactly the sum over the freshly +evaluated keys, including the actual adaptive recursive execution. -/ +theorem rankedMemoKernelWork_eq_fresh_sum {κ : Type*} (rank : κ → ℕ) + (program : (key : κ) → FiniteQuery {child : κ // rank child < rank key}) + (bits : ℕ) (encode cost : κ → ℕ) (key : κ) (memory : BinaryMemo ℚ) : + rankedMemoKernelWork rank program bits encode cost key memory = + ((rankedMemoEvaluate rank program bits encode key memory).freshKeys.map cost).sum := by + have hall : ∀ level key, rank key = level → ∀ memory, + rankedMemoKernelWork rank program bits encode cost key memory = + ((rankedMemoEvaluate rank program bits encode key memory).freshKeys.map cost).sum := by + intro level + induction level using Nat.strong_induction_on with + | h level ih => + intro key hlevel memory + rw [rankedMemoKernelWork, rankedMemoEvaluate] + split + · rename_i result hfound + simp only [List.map_nil, List.sum_nil] + · rename_i hfound + simp only [List.map_cons, List.sum_cons] + congr 1 + apply FiniteQuery.requestWork_eq_fresh_sum + intro child previous + exact ih (rank child.val) (by simpa only [← hlevel] using child.property) child.val rfl previous + exact hall (rank key) key rfl memory + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/RankedMemoKernelWork.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/RankedMemoKernelWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..22b6c2b7f20a239006e3550e5f73ef27b0c4edf2 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/RankedMemoKernelWork.lean @@ -0,0 +1,49 @@ +import OAI.Combinatorics.EditApproximation.Geometry.RankedMemoAddressWork +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation + +/-- Count local arithmetic only on a cache miss, following exactly the +recursive evaluator's returned values, requests and intermediate memories. -/ + + + theorem rankedMemoKernelWork_le {κ : Type*} (rank : κ → ℕ) + (program : (key : κ) → FiniteQuery {child : κ // rank child < rank key}) + (bits : ℕ) (encode cost : κ → ℕ) (C : ℕ) (hcost : ∀ key, cost key ≤ C) + (key : κ) (memory : BinaryMemo ℚ) : + rankedMemoKernelWork rank program bits encode cost key memory ≤ + C * (rankedMemoEvaluate rank program bits encode key memory).requests := by + have hall : ∀ level key, rank key = level → ∀ memory, + rankedMemoKernelWork rank program bits encode cost key memory ≤ + C * (rankedMemoEvaluate rank program bits encode key memory).requests := by + intro level + induction level using Nat.strong_induction_on with + | h level ih => + intro key hlevel memory + rw [rankedMemoKernelWork, rankedMemoEvaluate] + split + · rename_i result hfound + simp only + exact Nat.zero_le _ + · rename_i hfound + simp only + have hchildren : ∀ (child : {child : κ // rank child < rank key}) previous, + rankedMemoKernelWork rank program bits encode cost child.val previous ≤ + C * (rankedMemoEvaluate rank program bits encode child.val previous).requests := by + intro child previous + exact ih (rank child.val) (by simpa only [← hlevel] using child.property) child.val rfl previous + have hr := FiniteQuery.requestWork_le + (fun child previous => rankedMemoEvaluate rank program bits encode child.val previous) + (fun child previous => rankedMemoKernelWork rank program bits encode cost child.val previous) + C hchildren (program key) memory + have hk := hcost key + rw [Nat.mul_add, Nat.mul_one] + omega + exact hall (rank key) key rfl memory + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/RankedMemoKeys.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/RankedMemoKeys.lean new file mode 100644 index 0000000000000000000000000000000000000000..fae13d0c46e87db3f6b4e0e993992016279ce3ff --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/RankedMemoKeys.lean @@ -0,0 +1,113 @@ +import OAI.Combinatorics.EditApproximation.Geometry.ChargedCoarseOracle +import OAI.Combinatorics.EditApproximation.Geometry.SourceErasure + +namespace OAI + +/-! A cache miss is among the requests of the uncached execution with +identical answers. This includes adaptive continuations and cache hits. -/ + +namespace EditApproximation + +namespace FiniteQuery + +theorem substitute_keys {ι κ : Type*} (ask : ι → FiniteQuery κ) (oracle : κ → ℚ) + (query : FiniteQuery ι) : + (query.substitute ask).keys oracle = + (query.keys (fun key => (ask key).value oracle)).flatMap (fun key => (ask key).keys oracle) := by + induction query with + | done value => rfl + | read key next ih => + simp only [substitute, keys_bind, keys, List.flatMap_cons] + rw [ih] + +theorem run_freshKeys_mem {ι κ : Type*} (bits : ℕ) (encode : κ → ℕ) + (expected : κ → ℚ) (answer : ι → ℚ) (allowed : ι → List κ) + (ask : ι → BinaryMemo ℚ → RecursiveMemoResult κ) + (hask : ∀ key memory, memoSound bits encode expected memory → + (ask key memory).value = answer key ∧ + memoSound bits encode expected (ask key memory).memory ∧ + ∀ item ∈ (ask key memory).freshKeys, item ∈ allowed key) + (query : FiniteQuery ι) (memory : BinaryMemo ℚ) + (hsound : memoSound bits encode expected memory) : + ∀ item ∈ (run ask query memory).freshKeys, item ∈ (query.keys answer).flatMap allowed := by + induction query generalizing memory with + | done value => simp only [run, List.not_mem_nil, false_implies, implies_true] + | read key next ih => + have hf := hask key memory hsound + intro item hitem + simp only [run, List.mem_append] at hitem + rcases hitem with hfirst | hrest + · exact List.mem_flatMap.mpr ⟨key, List.mem_cons_self, hf.2.2 item hfirst⟩ + · have hr := ih (ask key memory).value (ask key memory).memory hf.2.1 item hrest + rw [hf.1] at hr + obtain ⟨child, hc, hi⟩ := List.mem_flatMap.mp hr + exact List.mem_flatMap.mpr ⟨child, List.mem_cons_of_mem key hc, hi⟩ + +theorem eraseSources_inr_mem_iff {σ κ : Type*} (source : σ → ℚ) (table : κ → ℚ) + (query : FiniteQuery (Sum σ κ)) (key : κ) : + Sum.inr key ∈ query.keys (Sum.elim source table) ↔ + key ∈ (eraseSources source query).keys table := by + induction query with + | done value => simp only [keys, eraseSources, List.not_mem_nil] + | read next continuation ih => + cases next with + | inl scalar => simpa only [keys, eraseSources, Sum.elim_inl, List.mem_cons, + Sum.inr_ne_inl, false_or] using ih (source scalar) + | inr child => simpa only [keys, eraseSources, Sum.elim_inr, List.mem_cons, + Sum.inr.injEq] using or_congr Iff.rfl (ih (table child)) + +end FiniteQuery + +def rankedUncachedKeys {κ : Type*} (rank : κ → ℕ) + (program : (key : κ) → FiniteQuery {child : κ // rank child < rank key}) (key : κ) : List κ := + key :: ((program key).keys (fun child => rankedProgramValue rank program child.val)).flatMap + (fun child => rankedUncachedKeys rank program child.val) +termination_by rank key +decreasing_by exact child.property + +theorem rankedMemoEvaluate_freshKeys_mem {κ : Type*} (rank : κ → ℕ) + (program : (key : κ) → FiniteQuery {child : κ // rank child < rank key}) + (bits : ℕ) (encode : κ → ℕ) (hinjective : Function.Injective encode) + (hbounded : ∀ key, encode key < 2 ^ bits) (key : κ) (memory : BinaryMemo ℚ) + (hsound : memoSound bits encode (rankedProgramValue rank program) memory) : + ∀ item ∈ (rankedMemoEvaluate rank program bits encode key memory).freshKeys, + item ∈ rankedUncachedKeys rank program key := by + have hall : ∀ level key, rank key = level → ∀ memory, + memoSound bits encode (rankedProgramValue rank program) memory → + ∀ item ∈ (rankedMemoEvaluate rank program bits encode key memory).freshKeys, + item ∈ rankedUncachedKeys rank program key := by + intro level + induction level using Nat.strong_induction_on with + | h level ih => + intro key hlevel memory hmemory + rw [rankedMemoEvaluate] + simp only [BinaryMemo.lookupCosted_spec] + split + · simp + · have hchildren : ∀ (child : {child : κ // rank child < rank key}) previous, + memoSound bits encode (rankedProgramValue rank program) previous → + (rankedMemoEvaluate rank program bits encode child.val previous).value = + rankedProgramValue rank program child.val ∧ + memoSound bits encode (rankedProgramValue rank program) + (rankedMemoEvaluate rank program bits encode child.val previous).memory ∧ + ∀ item ∈ (rankedMemoEvaluate rank program bits encode child.val previous).freshKeys, + item ∈ rankedUncachedKeys rank program child.val := by + intro child previous hp + have hs := rankedMemoEvaluate_sound rank program bits encode hinjective hbounded child.val previous hp + exact ⟨hs.1, hs.2, ih (rank child.val) (hlevel ▸ child.property) child.val rfl previous hp⟩ + have hr := FiniteQuery.run_freshKeys_mem bits encode (rankedProgramValue rank program) + (fun child : {child : κ // rank child < rank key} => rankedProgramValue rank program child.val) + (fun child => rankedUncachedKeys rank program child.val) + (fun child previous => rankedMemoEvaluate rank program bits encode child.val previous) + hchildren (program key) memory hmemory + intro item hi + simp only [List.mem_cons] at hi + rw [rankedUncachedKeys] + rcases hi with rfl | hi + · exact List.mem_cons_self + · exact List.mem_cons_of_mem key (hr item hi) + exact hall (rank key) key rfl memory hsound + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/RankedMemoProgram.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/RankedMemoProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..4c98f97f5c401773814ed7cae63e829b34248897 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/RankedMemoProgram.lean @@ -0,0 +1,135 @@ +import OAI.Combinatorics.EditApproximation.Geometry.MemoizedOracle +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Well-founded recursive memo evaluation. A local query program may +choose later requests from earlier answers. Each recursive request carries +its strict rank decrease; no complete table is evaluated in advance. -/ + +namespace EditApproximation + + + + + +namespace FiniteQuery + +def value {ι : Type*} (oracle : ι → ℚ) : FiniteQuery ι → ℚ + | .done result => result + | .read key next => value oracle (next (oracle key)) + + + +theorem run_sound {ι κ : Type*} (bits : ℕ) (encode : κ → ℕ) + (expected : κ → ℚ) (answer : ι → ℚ) + (ask : ι → BinaryMemo ℚ → RecursiveMemoResult κ) + (hask : ∀ key memory, memoSound bits encode expected memory → + (ask key memory).value = answer key ∧ + memoSound bits encode expected (ask key memory).memory) + (program : FiniteQuery ι) (memory : BinaryMemo ℚ) + (hsound : memoSound bits encode expected memory) : + (run ask program memory).value = program.value answer ∧ + memoSound bits encode expected (run ask program memory).memory := by + induction program generalizing memory with + | done result => exact ⟨rfl, hsound⟩ + | read key next ih => + have hfirst := hask key memory hsound + have hrest := ih (ask key memory).value (ask key memory).memory hfirst.2 + refine ⟨?_, hrest.2⟩ + simpa only [run, value, hfirst.1] using hrest.1 + +/-- Gather a finite list before running the dependent local continuation. -/ +def gather {ι : Type*} : List ι → (List ℚ → FiniteQuery ι) → FiniteQuery ι + | [], next => next [] + | key :: keys, next => .read key (fun result => gather keys (fun results => next (result :: results))) + +theorem gather_value {ι : Type*} (oracle : ι → ℚ) (keys : List ι) + (next : List ℚ → FiniteQuery ι) : + (gather keys next).value oracle = (next (keys.map oracle)).value oracle := by + induction keys generalizing next with + | nil => rfl + | cons key keys ih => exact ih (fun results => next (oracle key :: results)) + +end FiniteQuery + +def rankedProgramValue {κ : Type*} (rank : κ → ℕ) + (program : (key : κ) → FiniteQuery {child : κ // rank child < rank key}) (key : κ) : ℚ := + (program key).value (fun child => rankedProgramValue rank program child.val) +termination_by rank key +decreasing_by exact child.property + + + +theorem memoSound_insert {κ : Type*} (bits : ℕ) (encode : κ → ℕ) + (hinjective : Function.Injective encode) (hbounded : ∀ key, encode key < 2 ^ bits) + (expected : κ → ℚ) (memory : BinaryMemo ℚ) + (hsound : memoSound bits encode expected memory) (key : κ) : + memoSound bits encode expected + (memory.insert (binaryMemoKey bits (encode key)) (expected key)) := by + intro other result hresult + rw [binaryMemo_lookup_insert _ bits (encode key) (encode other) + (hbounded key) (hbounded other)] at hresult + split_ifs at hresult with heq + · have hkey : other = key := hinjective heq + subst other + exact Option.some.inj hresult.symm + · exact hsound other result hresult + +theorem rankedMemoEvaluate_sound {κ : Type*} (rank : κ → ℕ) + (program : (key : κ) → FiniteQuery {child : κ // rank child < rank key}) + (bits : ℕ) (encode : κ → ℕ) (hinjective : Function.Injective encode) + (hbounded : ∀ key, encode key < 2 ^ bits) (key : κ) (memory : BinaryMemo ℚ) + (hsound : memoSound bits encode (rankedProgramValue rank program) memory) : + (rankedMemoEvaluate rank program bits encode key memory).value = rankedProgramValue rank program key ∧ + memoSound bits encode (rankedProgramValue rank program) + (rankedMemoEvaluate rank program bits encode key memory).memory := by + have hall : ∀ level key, rank key = level → ∀ memory, + memoSound bits encode (rankedProgramValue rank program) memory → + (rankedMemoEvaluate rank program bits encode key memory).value = rankedProgramValue rank program key ∧ + memoSound bits encode (rankedProgramValue rank program) + (rankedMemoEvaluate rank program bits encode key memory).memory := by + intro level + induction level using Nat.strong_induction_on with + | h level ih => + intro key hlevel memory hmemory + rw [rankedMemoEvaluate] + simp only [BinaryMemo.lookupCosted_spec] + split + · rename_i result hresult + exact ⟨hmemory key result hresult, hmemory⟩ + · have hchildren : ∀ (child : {child : κ // rank child < rank key}) previous, + memoSound bits encode (rankedProgramValue rank program) previous → + (rankedMemoEvaluate rank program bits encode child.val previous).value = + rankedProgramValue rank program child.val ∧ + memoSound bits encode (rankedProgramValue rank program) + (rankedMemoEvaluate rank program bits encode child.val previous).memory := by + intro child previous hprevious + exact ih (rank child.val) (hlevel ▸ child.property) child.val rfl previous hprevious + have hrun := FiniteQuery.run_sound bits encode (rankedProgramValue rank program) + (fun child : {child : κ // rank child < rank key} => rankedProgramValue rank program child.val) + (fun child previous => rankedMemoEvaluate rank program bits encode child.val previous) + hchildren (program key) memory hmemory + have hvalue : (FiniteQuery.run + (fun child previous => rankedMemoEvaluate rank program bits encode child.val previous) + (program key) memory).value = rankedProgramValue rank program key := by + rw [rankedProgramValue] + exact hrun.1 + simp only [BinaryMemo.insertCosted_spec] + refine ⟨hvalue, ?_⟩ + rw [hvalue] + exact memoSound_insert bits encode hinjective hbounded _ _ hrun.2 key + exact hall (rank key) key rfl memory hsound + +theorem rankedMemoEvaluate_empty {κ : Type*} (rank : κ → ℕ) + (program : (key : κ) → FiniteQuery {child : κ // rank child < rank key}) + (bits : ℕ) (encode : κ → ℕ) (hinjective : Function.Injective encode) + (hbounded : ∀ key, encode key < 2 ^ bits) (key : κ) : + (rankedMemoEvaluate rank program bits encode key .empty).value = rankedProgramValue rank program key := + (rankedMemoEvaluate_sound rank program bits encode hinjective hbounded key .empty + (memoSound_empty bits encode _)).1 + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/RankedMemoSimulation.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/RankedMemoSimulation.lean new file mode 100644 index 0000000000000000000000000000000000000000..f0f2cfe221c010d77c126e94fd900e9e216f814e --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/RankedMemoSimulation.lean @@ -0,0 +1,42 @@ +import OAI.Combinatorics.EditApproximation.Geometry.RankedMemoProgram + +namespace OAI + +/-! Local recurrence equalities identify the complete table semantics +of a lazy query program. No complete table is evaluated by the memo +interpreter; it is used only as the mathematical specification. -/ + +namespace EditApproximation + +theorem rankedProgramValue_eq {κ : Type*} (rank : κ → ℕ) + (program : (key : κ) → FiniteQuery {child : κ // rank child < rank key}) + (expected : κ → ℚ) + (hstep : ∀ key, (program key).value (fun child => expected child.val) = expected key) + (key : κ) : rankedProgramValue rank program key = expected key := by + have hall : ∀ level key, rank key = level → rankedProgramValue rank program key = expected key := by + intro level + induction level using Nat.strong_induction_on with + | h level ih => + intro key hlevel + rw [rankedProgramValue] + have hchildren : (fun child : {child : κ // rank child < rank key} => + rankedProgramValue rank program child.val) = fun child => expected child.val := by + funext child + exact ih (rank child.val) (hlevel ▸ child.property) child.val rfl + rw [hchildren] + exact hstep key + exact hall (rank key) key rfl + +theorem rankedMemoEvaluate_specification {κ : Type*} (rank : κ → ℕ) + (program : (key : κ) → FiniteQuery {child : κ // rank child < rank key}) + (expected : κ → ℚ) + (hstep : ∀ key, (program key).value (fun child => expected child.val) = expected key) + (bits : ℕ) (encode : κ → ℕ) (hinjective : Function.Injective encode) + (hbounded : ∀ key, encode key < 2 ^ bits) (key : κ) : + (rankedMemoEvaluate rank program bits encode key .empty).value = expected key := + (rankedMemoEvaluate_empty rank program bits encode hinjective hbounded key).trans + (rankedProgramValue_eq rank program expected hstep key) + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/RankedMemoStorage.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/RankedMemoStorage.lean new file mode 100644 index 0000000000000000000000000000000000000000..03d61455b16d35de0f4b733b1b18c3a2d206194b --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/RankedMemoStorage.lean @@ -0,0 +1,146 @@ +import OAI.Combinatorics.EditApproximation.Geometry.RankedMemoWork +import OAI.Combinatorics.EditApproximation.Numerics.NumericalWork +import OAI.Combinatorics.EditApproximation.Geometry.SourceRankedProgram + +namespace OAI + +/-! Every value retained by the actual binary dictionary obeys the +semantic value bound. This includes every allocated path, not only keys +queried after the computation. -/ + +namespace EditApproximation +namespace BinaryMemo + +def AllValues {α : Type*} (P : α → Prop) (memory : BinaryMemo α) : Prop := + ∀ key value, memory.lookup key = some value → P value + +theorem allValues_empty {α : Type*} (P : α → Prop) : AllValues P (.empty : BinaryMemo α) := by + intro key value h + rw [lookup_empty] at h + cases h + +theorem AllValues.insert {α : Type*} {P : α → Prop} {memory : BinaryMemo α} + (hmem : AllValues P memory) (key : List Bool) (a : α) (ha : P a) : + AllValues P (memory.insert key a) := by + intro query value hvalue + by_cases heq : query = key + · subst query + rw [lookup_insert_same] at hvalue + cases hvalue + exact ha + · rw [lookup_insert_other memory key query a heq] at hvalue + exact hmem query value hvalue + +/-- One word each for the tag and two child pointers, plus the value bits. +Counting bits individually is an upper bound on logarithmic-word storage. -/ +def rationalStorage : BinaryMemo ℚ → ℕ + | .empty => 0 + | .node value left right => + 3 + (value.map rationalEncodingBits).getD 0 + left.rationalStorage + right.rationalStorage + +theorem rationalStorage_le (memory : BinaryMemo ℚ) (W : ℕ) + (hmem : AllValues (fun value => rationalEncodingBits value ≤ W) memory) : + memory.rationalStorage ≤ (W + 3) * memory.nodes := by + induction memory with + | empty => simp only [rationalStorage, nodes, Nat.mul_zero, le_refl] + | node value left right ihl ihr => + have hl : AllValues (fun value => rationalEncodingBits value ≤ W) left := by + intro key value h + exact hmem (false :: key) value h + have hr : AllValues (fun value => rationalEncodingBits value ≤ W) right := by + intro key value h + exact hmem (true :: key) value h + have hv : (value.map rationalEncodingBits).getD 0 ≤ W := by + cases value with + | none => exact Nat.zero_le _ + | some value => exact hmem [] value rfl + have hl' := ihl hl + have hr' := ihr hr + simp only [rationalStorage, nodes] + nlinarith only [hv, hl', hr'] + +end BinaryMemo + +namespace FiniteQuery + +theorem run_invariant {ι κ : Type*} (invariant : BinaryMemo ℚ → Prop) + (ask : ι → BinaryMemo ℚ → RecursiveMemoResult κ) + (hask : ∀ key memory, invariant memory → invariant (ask key memory).memory) + (program : FiniteQuery ι) (memory : BinaryMemo ℚ) (hmem : invariant memory) : + invariant (run ask program memory).memory := by + induction program generalizing memory with + | done value => exact hmem + | read key next ih => exact ih (ask key memory).value _ (hask key memory hmem) + +end FiniteQuery + + theorem rankedMemoEvaluate_allValues {κ : Type*} (rank : κ → ℕ) + (program : (key : κ) → FiniteQuery {child : κ // rank child < rank key}) + (bits : ℕ) (encode : κ → ℕ) (hinjective : Function.Injective encode) + (hbounded : ∀ key, encode key < 2 ^ bits) (P : ℚ → Prop) + (hvalue : ∀ key, P (rankedProgramValue rank program key)) + (key : κ) (memory : BinaryMemo ℚ) + (hsound : memoSound bits encode (rankedProgramValue rank program) memory) + (hmem : BinaryMemo.AllValues P memory) : + BinaryMemo.AllValues P (rankedMemoEvaluate rank program bits encode key memory).memory := by + have hall : ∀ level key, rank key = level → ∀ memory, + memoSound bits encode (rankedProgramValue rank program) memory → + BinaryMemo.AllValues P memory → + BinaryMemo.AllValues P (rankedMemoEvaluate rank program bits encode key memory).memory := by + intro level + induction level using Nat.strong_induction_on with + | h level ih => + intro key hlevel memory hsound hmem + rw [rankedMemoEvaluate] + simp only [BinaryMemo.lookupCosted_spec] + split + · exact hmem + · have hchildren : ∀ (child : {child : κ // rank child < rank key}) previous, + memoSound bits encode (rankedProgramValue rank program) previous → + BinaryMemo.AllValues P previous → + memoSound bits encode (rankedProgramValue rank program) + (rankedMemoEvaluate rank program bits encode child.val previous).memory ∧ + BinaryMemo.AllValues P + (rankedMemoEvaluate rank program bits encode child.val previous).memory := by + intro child previous hs hm + exact ⟨(rankedMemoEvaluate_sound rank program bits encode hinjective hbounded _ _ hs).2, + ih (rank child.val) (hlevel ▸ child.property) child.val rfl previous hs hm⟩ + have hrun := FiniteQuery.run_invariant + (fun previous => memoSound bits encode (rankedProgramValue rank program) previous ∧ + BinaryMemo.AllValues P previous) + (fun child previous => rankedMemoEvaluate rank program bits encode child.val previous) + (fun child previous h => hchildren child previous h.1 h.2) (program key) memory ⟨hsound, hmem⟩ + have hresult := (FiniteQuery.run_sound bits encode (rankedProgramValue rank program) + (fun child : {child : κ // rank child < rank key} => rankedProgramValue rank program child.val) + (fun child previous => rankedMemoEvaluate rank program bits encode child.val previous) + (fun child previous hs => rankedMemoEvaluate_sound rank program bits encode hinjective hbounded + child.val previous hs) (program key) memory hsound).1 + have hv : (FiniteQuery.run + (fun child previous => rankedMemoEvaluate rank program bits encode child.val previous) + (program key) memory).value = rankedProgramValue rank program key := by + rw [rankedProgramValue] + exact hresult + simp only [BinaryMemo.insertCosted_spec] + exact hrun.2.insert _ _ (hv.symm ▸ hvalue key) + exact hall (rank key) key rfl memory hsound hmem + +namespace SourceRanked + +theorem memo_allValues {σ κ : Type*} (tableRank : κ → ℕ) + (tableBody : (parent : κ) → FiniteQuery (Sum σ {key : κ // tableRank key < tableRank parent})) + (sourceValue : σ → ℚ) (tableValue : κ → ℚ) + (hbody : ∀ key, (tableBody key).value (Sum.elim sourceValue (fun next => tableValue next.val)) = + tableValue key) (bits : ℕ) (encode : Sum σ κ → ℕ) + (hinjective : Function.Injective encode) (hbounded : ∀ key, encode key < 2 ^ bits) + (P : ℚ → Prop) (hvalue : ∀ key, P (value sourceValue tableValue key)) (key : Sum σ κ) : + BinaryMemo.AllValues P (rankedMemoEvaluate (rank tableRank) (body tableRank tableBody sourceValue) + bits encode key .empty).memory := by + apply rankedMemoEvaluate_allValues _ _ bits encode hinjective hbounded P + (fun key => ?_) key .empty (memoSound_empty _ _ _) (BinaryMemo.allValues_empty P) + rw [program_value tableRank tableBody sourceValue tableValue hbody] + exact hvalue key + +end SourceRanked +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/RankedMemoWork.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/RankedMemoWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..384743bbdf1042056eb2ac319bbcb4c530044187 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/RankedMemoWork.lean @@ -0,0 +1,177 @@ +import OAI.Combinatorics.EditApproximation.Geometry.RankedMemoProgram + +namespace OAI + +/-! Counts of the actual persistent interpreter. Dictionary operations +are charged on every request, including hits; insertion and retained-node +costs are charged only when a value is computed. -/ + +namespace EditApproximation + +namespace FiniteQuery + +def cost {ι : Type*} (oracle : ι → ℚ) (weight : ι → ℕ) : FiniteQuery ι → ℕ + | .done _ => 0 + | .read key next => weight key + cost oracle weight (next (oracle key)) + +def keys {ι : Type*} (oracle : ι → ℚ) : FiniteQuery ι → List ι + | .done _ => [] + | .read key next => key :: keys oracle (next (oracle key)) + +theorem cost_eq_sum {ι : Type*} (oracle : ι → ℚ) (weight : ι → ℕ) + (program : FiniteQuery ι) : + program.cost oracle weight = ((program.keys oracle).map weight).sum := by + induction program with + | done _ => rfl + | read key next ih => exact congrArg (weight key + ·) (ih (oracle key)) + +theorem run_resource_bounds {ι κ : Type*} + (ask : ι → BinaryMemo ℚ → RecursiveMemoResult κ) (B D : ℕ) + (hask : ∀ key memory, + (ask key memory).freshKeys.length ≤ (ask key memory).requests ∧ + (ask key memory).dictionaryVisits ≤ (ask key memory).requests * D ∧ + (ask key memory).memory.nodes ≤ memory.nodes + (ask key memory).freshKeys.length * B) + (program : FiniteQuery ι) (memory : BinaryMemo ℚ) : + (run ask program memory).freshKeys.length ≤ (run ask program memory).requests ∧ + (run ask program memory).dictionaryVisits ≤ (run ask program memory).requests * D ∧ + (run ask program memory).memory.nodes ≤ memory.nodes + (run ask program memory).freshKeys.length * B := by + induction program generalizing memory with + | done _ => simp only [run, List.length_nil, Nat.zero_mul, Nat.add_zero, le_refl, and_self] + | read key next ih => + have hf := hask key memory + have hr := ih (ask key memory).value (ask key memory).memory + dsimp only [run] + simp only [List.length_append, Nat.add_mul] + exact ⟨Nat.add_le_add hf.1 hr.1, Nat.add_le_add hf.2.1 hr.2.1, by omega⟩ + +theorem run_requests_le {ι κ : Type*} (bits : ℕ) (encode : κ → ℕ) + (expected : κ → ℚ) (answer : ι → ℚ) (weight : ι → ℕ) + (ask : ι → BinaryMemo ℚ → RecursiveMemoResult κ) + (hask : ∀ key memory, memoSound bits encode expected memory → + (ask key memory).value = answer key ∧ + memoSound bits encode expected (ask key memory).memory ∧ + (ask key memory).requests ≤ weight key) + (program : FiniteQuery ι) (memory : BinaryMemo ℚ) + (hsound : memoSound bits encode expected memory) : + (run ask program memory).requests ≤ program.cost answer weight := by + induction program generalizing memory with + | done _ => exact le_rfl + | read key next ih => + have hf := hask key memory hsound + have hr := ih (ask key memory).value (ask key memory).memory hf.2.1 + simp only [run, cost] + rw [hf.1] at hr + rw [hf.1] + exact Nat.add_le_add hf.2.2 hr + +end FiniteQuery + +theorem rankedMemoEvaluate_resource_bounds {κ : Type*} (rank : κ → ℕ) + (program : (key : κ) → FiniteQuery {child : κ // rank child < rank key}) + (bits : ℕ) (encode : κ → ℕ) (key : κ) (memory : BinaryMemo ℚ) : + (rankedMemoEvaluate rank program bits encode key memory).freshKeys.length ≤ + (rankedMemoEvaluate rank program bits encode key memory).requests ∧ + (rankedMemoEvaluate rank program bits encode key memory).dictionaryVisits ≤ + (rankedMemoEvaluate rank program bits encode key memory).requests * (2 * (bits + 1)) ∧ + (rankedMemoEvaluate rank program bits encode key memory).memory.nodes ≤ + memory.nodes + (rankedMemoEvaluate rank program bits encode key memory).freshKeys.length * (bits + 1) := by + have hall : ∀ level key, rank key = level → ∀ memory, + (rankedMemoEvaluate rank program bits encode key memory).freshKeys.length ≤ + (rankedMemoEvaluate rank program bits encode key memory).requests ∧ + (rankedMemoEvaluate rank program bits encode key memory).dictionaryVisits ≤ + (rankedMemoEvaluate rank program bits encode key memory).requests * (2 * (bits + 1)) ∧ + (rankedMemoEvaluate rank program bits encode key memory).memory.nodes ≤ + memory.nodes + (rankedMemoEvaluate rank program bits encode key memory).freshKeys.length * (bits + 1) := by + intro level + induction level using Nat.strong_induction_on with + | h level ih => + intro key hlevel memory + rw [rankedMemoEvaluate] + simp only [BinaryMemo.lookupCosted_spec, binaryMemoKey_length] + split + · simp only [List.length_nil, Nat.one_mul, Nat.zero_mul, Nat.add_zero] + exact ⟨Nat.zero_le _, by omega, le_rfl⟩ + · have hchildren : ∀ (child : {child : κ // rank child < rank key}) previous, + (rankedMemoEvaluate rank program bits encode child.val previous).freshKeys.length ≤ + (rankedMemoEvaluate rank program bits encode child.val previous).requests ∧ + (rankedMemoEvaluate rank program bits encode child.val previous).dictionaryVisits ≤ + (rankedMemoEvaluate rank program bits encode child.val previous).requests * (2 * (bits + 1)) ∧ + (rankedMemoEvaluate rank program bits encode child.val previous).memory.nodes ≤ + previous.nodes + (rankedMemoEvaluate rank program bits encode child.val previous).freshKeys.length * (bits + 1) := by + intro child previous + exact ih (rank child.val) (hlevel ▸ child.property) child.val rfl previous + have hr := FiniteQuery.run_resource_bounds + (fun child previous => rankedMemoEvaluate rank program bits encode child.val previous) + (bits + 1) (2 * (bits + 1)) hchildren (program key) memory + simp only [BinaryMemo.insertCosted_spec, binaryMemoKey_length, List.length_cons] + have hn := BinaryMemo.insert_nodes + (FiniteQuery.run (fun child previous => rankedMemoEvaluate rank program bits encode child.val previous) + (program key) memory).memory (binaryMemoKey bits (encode key)) + (FiniteQuery.run (fun child previous => rankedMemoEvaluate rank program bits encode child.val previous) + (program key) memory).value + simp only [binaryMemoKey_length] at hn + constructor + · omega + constructor + · nlinarith only [hr.2.1] + · nlinarith only [hr.2.2, hn] + exact hall (rank key) key rfl memory + +/-- Number of requests in the same adaptive program without cache hits. +It is a dominating execution tree, not the size of the full table. -/ +def rankedUncachedCalls {κ : Type*} (rank : κ → ℕ) + (program : (key : κ) → FiniteQuery {child : κ // rank child < rank key}) (key : κ) : ℕ := + (program key).cost (fun child => rankedProgramValue rank program child.val) + (fun child => rankedUncachedCalls rank program child.val) + 1 +termination_by rank key +decreasing_by exact child.property + +theorem rankedUncachedCalls_pos {κ : Type*} (rank : κ → ℕ) + (program : (key : κ) → FiniteQuery {child : κ // rank child < rank key}) (key : κ) : + 1 ≤ rankedUncachedCalls rank program key := by + rw [rankedUncachedCalls] + omega + +theorem rankedMemoEvaluate_requests_le {κ : Type*} (rank : κ → ℕ) + (program : (key : κ) → FiniteQuery {child : κ // rank child < rank key}) + (bits : ℕ) (encode : κ → ℕ) (hinjective : Function.Injective encode) + (hbounded : ∀ key, encode key < 2 ^ bits) (key : κ) (memory : BinaryMemo ℚ) + (hsound : memoSound bits encode (rankedProgramValue rank program) memory) : + (rankedMemoEvaluate rank program bits encode key memory).requests ≤ + rankedUncachedCalls rank program key := by + have hall : ∀ level key, rank key = level → ∀ memory, + memoSound bits encode (rankedProgramValue rank program) memory → + (rankedMemoEvaluate rank program bits encode key memory).requests ≤ + rankedUncachedCalls rank program key := by + intro level + induction level using Nat.strong_induction_on with + | h level ih => + intro key hlevel memory hmemory + rw [rankedMemoEvaluate] + simp only [BinaryMemo.lookupCosted_spec] + split + · exact rankedUncachedCalls_pos rank program key + · have hchildren : ∀ (child : {child : κ // rank child < rank key}) previous, + memoSound bits encode (rankedProgramValue rank program) previous → + (rankedMemoEvaluate rank program bits encode child.val previous).value = + rankedProgramValue rank program child.val ∧ + memoSound bits encode (rankedProgramValue rank program) + (rankedMemoEvaluate rank program bits encode child.val previous).memory ∧ + (rankedMemoEvaluate rank program bits encode child.val previous).requests ≤ + rankedUncachedCalls rank program child.val := by + intro child previous hprevious + have hs := rankedMemoEvaluate_sound rank program bits encode hinjective hbounded + child.val previous hprevious + exact ⟨hs.1, hs.2, ih (rank child.val) (hlevel ▸ child.property) child.val rfl previous hprevious⟩ + have hr := FiniteQuery.run_requests_le bits encode (rankedProgramValue rank program) + (fun child : {child : κ // rank child < rank key} => rankedProgramValue rank program child.val) + (fun child => rankedUncachedCalls rank program child.val) + (fun child previous => rankedMemoEvaluate rank program bits encode child.val previous) + hchildren (program key) memory hmemory + rw [rankedUncachedCalls] + exact Nat.add_le_add_right hr 1 + exact hall (rank key) key rfl memory hsound + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/RankedProgramRestriction.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/RankedProgramRestriction.lean new file mode 100644 index 0000000000000000000000000000000000000000..8eedfc227b1c9801c7ac1a7c1e060a98ef673202 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/RankedProgramRestriction.lean @@ -0,0 +1,71 @@ +import OAI.Combinatorics.EditApproximation.Probability.FiniteQueryRestriction +import OAI.Combinatorics.EditApproximation.Geometry.RankedMemoSimulation + +namespace OAI + +/-! Restrict a well-founded query program to its proved finite key domain. +Values, executed read lists and weighted read costs are preserved. -/ + +namespace EditApproximation + + def restrictRankedProgram {κ : Type*} (rank : κ → ℕ) + (program : (key : κ) → FiniteQuery {child : κ // rank child < rank key}) + (P : κ → Prop) [DecidablePred P] (key : {key // P key}) : + FiniteQuery {child : {key // P key} // rank child.val < rank key.val} := + FiniteQuery.mapKeys (fun child => ⟨⟨child.val.val, child.property⟩, child.val.property⟩) + (FiniteQuery.restrict (fun child => P child.val) (program key.val)) + + theorem restrictRankedProgram_value {κ : Type*} (rank : κ → ℕ) + (program : (key : κ) → FiniteQuery {child : κ // rank child < rank key}) + (P : κ → Prop) [DecidablePred P] (expected : κ → ℚ) (key : {key // P key}) + (hvalid : ∀ child ∈ (program key.val).keys (fun child => expected child.val), P child.val) : + (restrictRankedProgram rank program P key).value (fun child => expected child.val.val) = + (program key.val).value (fun child => expected child.val) := by + unfold restrictRankedProgram + rw [FiniteQuery.mapKeys_value] + exact FiniteQuery.restrict_value _ _ _ hvalid + + theorem restrictRankedProgram_cost {κ : Type*} (rank : κ → ℕ) + (program : (key : κ) → FiniteQuery {child : κ // rank child < rank key}) + (P : κ → Prop) [DecidablePred P] (expected : κ → ℚ) (weight : κ → ℕ) (key : {key // P key}) + (hvalid : ∀ child ∈ (program key.val).keys (fun child => expected child.val), P child.val) : + (restrictRankedProgram rank program P key).cost + (fun child => expected child.val.val) (fun child => weight child.val.val) = + (program key.val).cost (fun child => expected child.val) (fun child => weight child.val) := by + unfold restrictRankedProgram + rw [FiniteQuery.mapKeys_cost] + simpa only [Function.comp_def] using + (FiniteQuery.restrict_cost (fun child => P child.val) (fun child => expected child.val) + (fun child => weight child.val) (program key.val) hvalid) + + theorem restrictRankedProgram_keys {κ : Type*} (rank : κ → ℕ) + (program : (key : κ) → FiniteQuery {child : κ // rank child < rank key}) + (P : κ → Prop) [DecidablePred P] (expected : κ → ℚ) (key : {key // P key}) + (hvalid : ∀ child ∈ (program key.val).keys (fun child => expected child.val), P child.val) : + ((restrictRankedProgram rank program P key).keys + (fun child => expected child.val.val)).map (fun child => child.val.val) = + ((program key.val).keys (fun child => expected child.val)).map Subtype.val := by + unfold restrictRankedProgram + rw [FiniteQuery.mapKeys_keys, List.map_map] + have hkeys := FiniteQuery.restrict_keys (fun child => P child.val) + (fun child => expected child.val) (program key.val) hvalid + have hmap := congrArg (List.map Subtype.val) hkeys + simpa only [List.map_map, Function.comp_def] using hmap + + theorem restrictRankedProgram_specification {κ : Type*} (rank : κ → ℕ) + (program : (key : κ) → FiniteQuery {child : κ // rank child < rank key}) + (P : κ → Prop) [DecidablePred P] (expected : κ → ℚ) + (hstep : ∀ key, P key → (program key).value (fun child => expected child.val) = expected key) + (hvalid : ∀ key, P key → ∀ child ∈ (program key).keys (fun child => expected child.val), P child.val) + (key : {key // P key}) : + rankedProgramValue (fun key : {key // P key} => rank key.val) + (restrictRankedProgram rank program P) key = expected key.val := by + refine rankedProgramValue_eq (fun key : {key // P key} => rank key.val) + (restrictRankedProgram rank program P) (fun key : {key // P key} => expected key.val) ?_ key + intro other + rw [restrictRankedProgram_value rank program P expected other (hvalid other.val other.property)] + exact hstep other.val other.property + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/RefinementBandSupport.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/RefinementBandSupport.lean new file mode 100644 index 0000000000000000000000000000000000000000..c08a8d06ead9d875e000b7f368bce178215a120d --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/RefinementBandSupport.lean @@ -0,0 +1,323 @@ +import OAI.Combinatorics.EditApproximation.Geometry.RefinementInitialSupport +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Band-table congruence uses proof-free data. Equality of these data +preserves the ordered minimization and its tie decisions, even though the +guard records have different table-indexed types. -/ + +namespace EditApproximation + +abbrev UnskippedBandData (M ny : ℕ) := + TargetInterval ny × (Fin M → ℚ) × (Fin M → TargetInterval ny) + +def UnskippedBand.data {α : Type*} {source target : List α} {M b P exponent : ℕ} + {parent : TargetInterval source.length} {tau F : ℚ} + {child initial : Fin M → TargetInterval target.length → ℚ} + (member : UnskippedBand source target parent b P exponent tau F child initial) : + UnskippedBandData M target.length := + (member.center, member.envelope, member.rounded) + +def UnskippedBandData.action {M ny : ℕ} (data : UnskippedBandData M ny) : + PhysicalRationalAction M ny := + ⟨data.1, endpointActionConnection data.1 data.2.2, fun i => (i, data.2.2 i)⟩ + +def UnskippedBandData.estimate {M ny : ℕ} (b Q : ℕ) (F : ℚ) + (value : Fin M → TargetInterval ny → ℚ) + (draw : ∀ scale : Fin (groupDyadicScales M b F).length, + Fin (groupSampleCount M Q b (groupDyadicScaleAt M b F scale)) → Fin M) + (data : UnskippedBandData M ny) : ℚ := + groupMemberEstimate (groupDyadicScaleAt M b F) + (fun scale => groupSampleCount M Q b (groupDyadicScaleAt M b F scale)) + (endpointActionConnection data.1 data.2.2) data.2.1 (fun i => value i (data.2.2 i)) draw + +theorem rational_argmax_map {ι κ : Type*} (members : List ι) (project : ι → κ) + (score : κ → ℚ) : + (members.argmax (fun member => score (project member))).map project = + (members.map project).argmax score := by + induction members with + | nil => rfl + | cons first rest ih => + rw [List.map_cons, List.argmax_cons, List.argmax_cons, ← ih] + cases hmax : rest.argmax (fun member => score (project member)) with + | none => rfl + | some selected => + dsimp only [Option.map] + split_ifs <;> rfl + +theorem testUnskippedBand_center_of_some {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (b P exponent : ℕ) (tau F : ℚ) + (child initial : Fin M → TargetInterval target.length → ℚ) (r : TargetInterval target.length) + (member : UnskippedBand source target parent b P exponent tau F child initial) + (hmember : testUnskippedBand source target parent b P exponent tau F child initial r = some member) : + member.center = r := by + have h := testUnskippedBand_center_projection source target parent r b P exponent tau F child initial + rw [hmember] at h + simpa only [Option.map_some, Option.isSome_some, Bool.true_eq, ite_true, Option.some.injEq] using h + +theorem unskippedBand_data_congr {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (r : TargetInterval target.length) + (b P exponent : ℕ) (tau F : ℚ) + (child child' initial initial' : Fin M → TargetInterval target.length → ℚ) + (hchild : ∀ action ∈ wideActionList M parent r b P, + ∀ i, child i (action i) = child' i (action i)) + (hinitial : ∀ action ∈ wideActionList M parent r b P, + ∀ i, initial i (action i) = initial' i (action i)) + (left : UnskippedBand source target parent b P exponent tau F child initial) + (right : UnskippedBand source target parent b P exponent tau F child' initial') + (hleft : left.center = r) (hright : right.center = r) : left.data = right.data := by + have hband := representativeBandActions_congr_child source target parent r b P tau + ((2 : ℚ) ^ (-(exponent : ℤ))) child child' hchild + have hinitialBand : ∀ action ∈ representativeBandActions source target parent r b P tau + ((2 : ℚ) ^ (-(exponent : ℤ))) child, ∀ i, initial i (action i) = initial' i (action i) := by + intro action ha i + exact hinitial action (representativeBandActions_wide source target parent r b P tau _ child action ha) i + apply Prod.ext (hleft.trans hright.symm) + apply Prod.ext + · change left.envelope = right.envelope + unfold UnskippedBand.envelope UnskippedBand.actions + rw [hleft, hright] + exact representativeBandEnvelope_congr source target parent r b P exponent tau + child child' initial initial' hchild hinitial + · change left.rounded = right.rounded + have hactions : left.actions = right.actions := by + simp only [UnskippedBand.actions, hleft, hright] + exact hband + have hrightInitial : ∀ action ∈ right.actions, + ∀ i, initial i (action i) = initial' i (action i) := by + intro action ha i + simp only [UnskippedBand.actions, hright, ← hband] at ha + exact hinitialBand action ha i + exact (UnskippedBand.canonicalRounded_congr exponent b left.actions right.actions + hactions left.nonempty right.nonempty initial).trans + (canonicalRoundedBandAction_congr_initial exponent b right.actions right.nonempty + initial initial' hrightInitial) + +theorem testUnskippedBand_data_congr {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (r : TargetInterval target.length) + (b P exponent : ℕ) (tau F : ℚ) + (child child' initial initial' : Fin M → TargetInterval target.length → ℚ) + (hchild : ∀ action ∈ wideActionList M parent r b P, + ∀ i, child i (action i) = child' i (action i)) + (hinitial : ∀ action ∈ wideActionList M parent r b P, + ∀ i, initial i (action i) = initial' i (action i)) : + (testUnskippedBand source target parent b P exponent tau F child initial r).map UnskippedBand.data = + (testUnskippedBand source target parent b P exponent tau F child' initial' r).map UnskippedBand.data := by + have haccept := testUnskippedBand_isSome_congr source target parent r b P exponent tau F + child child' initial initial' hchild hinitial + cases hleft : testUnskippedBand source target parent b P exponent tau F child initial r with + | none => + cases hright : testUnskippedBand source target parent b P exponent tau F child' initial' r with + | none => rfl + | some right => simp only [hleft, hright, Option.isSome_none, Option.isSome_some, Bool.false_eq_true] at haccept + | some left => + cases hright : testUnskippedBand source target parent b P exponent tau F child' initial' r with + | none => simp only [hleft, hright, Option.isSome_none, Option.isSome_some, Bool.true_eq_false] at haccept + | some right => + apply congrArg some + exact unskippedBand_data_congr source target parent r b P exponent tau F child child' initial initial' + hchild hinitial left right + (testUnskippedBand_center_of_some source target parent b P exponent tau F child initial r left hleft) + (testUnskippedBand_center_of_some source target parent b P exponent tau F child' initial' r right hright) + +theorem unskippedBandList_data_congr {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (b P exponent : ℕ) (tau F : ℚ) + (child child' initial initial' : Fin M → TargetInterval target.length → ℚ) + (centers : List (TargetInterval target.length)) + (hchild : ∀ r ∈ centers, ∀ action ∈ wideActionList M parent r b P, + ∀ i, child i (action i) = child' i (action i)) + (hinitial : ∀ r ∈ centers, ∀ action ∈ wideActionList M parent r b P, + ∀ i, initial i (action i) = initial' i (action i)) : + (unskippedBandList source target parent b P exponent tau F child initial centers).map UnskippedBand.data = + (unskippedBandList source target parent b P exponent tau F child' initial' centers).map UnskippedBand.data := by + simp only [unskippedBandList, List.map_filterMap] + apply List.filterMap_congr + intro r hr + exact testUnskippedBand_data_congr source target parent r b P exponent tau F + child child' initial initial' (hchild r hr) (hinitial r hr) + +theorem chooseCellGroupAction_data {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (b P F exponent Q : ℕ) (tau a : ℚ) + (parentInitial : TargetInterval target.length → ℚ) + (child initial current : Fin M → TargetInterval target.length → ℚ) (cell : ℕ × ℕ) + (draw : ∀ scale : Fin (groupDyadicScales M b F).length, + Fin (groupSampleCount M Q b (groupDyadicScaleAt M b F scale)) → Fin M) : + chooseCellGroupAction source target parent b P F exponent Q tau a parentInitial + child initial current cell draw = + (((cellUnskippedBands source target parent b P F exponent tau a parentInitial child initial cell).map + UnskippedBand.data).argmax (fun data => -data.estimate b Q F current draw)).map UnskippedBandData.action := by + let members := cellUnskippedBands source target parent b P F exponent tau a parentInitial child initial cell + change (if h : members = [] then none else some (chooseUnskippedGroup Q current members h draw).rationalAction) = _ + rw [← rational_argmax_map members UnskippedBand.data (fun data => -data.estimate b Q F current draw)] + by_cases hnil : members = [] + · simp only [hnil, dite_true, List.argmax_nil, Option.map_none] + · rw [dite_eq_right hnil] + unfold chooseUnskippedGroup selectGroupMember + change some (UnskippedBand.rationalAction + ((members.argmax (fun member => -member.data.estimate b Q F current draw)).getD (members.head hnil))) = _ + cases hmax : members.argmax (fun member => -member.data.estimate b Q F current draw) with + | none => exact False.elim (hnil (List.argmax_eq_none.mp hmax)) + | some selected => rfl + +theorem chooseCellGroupAction_congr_bandTables {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (b P F exponent Q : ℕ) (tau a : ℚ) + (parentInitial : TargetInterval target.length → ℚ) + (child child' initial initial' current : Fin M → TargetInterval target.length → ℚ) (cell : ℕ × ℕ) + (draw : ∀ scale : Fin (groupDyadicScales M b F).length, + Fin (groupSampleCount M Q b (groupDyadicScaleAt M b F scale)) → Fin M) + (hchild : ∀ r ∈ cellRepresentativeStates target.length P F b a parentInitial + ((2 : ℚ) ^ (-(exponent : ℤ))) cell, ∀ action ∈ wideActionList M parent r b P, + ∀ i, child i (action i) = child' i (action i)) + (hinitial : ∀ r ∈ cellRepresentativeStates target.length P F b a parentInitial + ((2 : ℚ) ^ (-(exponent : ℤ))) cell, ∀ action ∈ wideActionList M parent r b P, + ∀ i, initial i (action i) = initial' i (action i)) : + chooseCellGroupAction source target parent b P F exponent Q tau a parentInitial + child initial current cell draw = + chooseCellGroupAction source target parent b P F exponent Q tau a parentInitial + child' initial' current cell draw := by + rw [chooseCellGroupAction_data, chooseCellGroupAction_data] + rw [show (cellUnskippedBands source target parent b P F exponent tau a parentInitial child initial cell).map + UnskippedBand.data = + (cellUnskippedBands source target parent b P F exponent tau a parentInitial child' initial' cell).map + UnskippedBand.data from + unskippedBandList_data_congr source target parent b P exponent tau F child child' initial initial' _ + hchild hinitial] + +/-- Keep the optimizer opaque while transporting the finite band data. -/ +def bandDataOnlineCandidate {M ny : ℕ} (band : List (Fin M → TargetInterval ny)) + (envelope : Fin M → ℚ) (H : ℕ) (eta kappa : ℚ) + (children : PhysicalChildTables M ny) (t : ℕ) (r : TargetInterval ny) + (integer : ℕ) (accepted : Bool) : Option (PhysicalRationalAction M ny) := + let G := H + (bandCoordinates band.toFinset).card + 2 + let K := G ^ 80 + let sample := boundedOnlineInteger (optimizerTriangularMass K) + (optimizerTriangularMass_positive _ (pow_pos (by omega : 0 < G) 80)) integer + if hband : band = [] then none else + if accepted then some (sharedBandRationalAction r (finiteOptimizerActionDraw band hband envelope + (rationalOnlineLinear eta kappa + (childGain envelope (fun s coordinate => children coordinate.1 s coordinate.2)) + (childDecrement envelope (fun s coordinate => children coordinate.1 s coordinate.2)) t) + G K sample)) + else none + +theorem keyedOnlineCandidate_test_form {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (P F exponent H b : ℕ) (tau eta kappa : ℚ) + (child initial : Fin M → TargetInterval target.length → ℚ) + (children : PhysicalChildTables M target.length) (t : ℕ) + (r : TargetInterval target.length) (integer : ℕ) : + keyedOnlineCandidate source target parent P F exponent H b tau eta kappa + child initial children t r integer = + bandDataOnlineCandidate + (representativeBandActions source target parent r b P tau ((2 : ℚ) ^ (-(exponent : ℤ))) child) + (bandChildEnvelope b + (representativeBandActions source target parent r b P tau ((2 : ℚ) ^ (-(exponent : ℤ))) child) initial) + H eta kappa children t r integer + (testUnskippedBand source target parent b P exponent tau F child initial r).isSome := by + unfold keyedOnlineCandidate bandDataOnlineCandidate + dsimp only + by_cases hband : representativeBandActions source target parent r b P tau + ((2 : ℚ) ^ (-(exponent : ℤ))) child = [] + · simp only [dite_eq_left hband] + · simp only [dite_eq_right hband] + cases testUnskippedBand source target parent b P exponent tau F child initial r <;> rfl + +theorem keyedOnlineCandidate_congr_bandTables {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (P F exponent H b : ℕ) (tau eta kappa : ℚ) + (child child' initial initial' : Fin M → TargetInterval target.length → ℚ) + (children : PhysicalChildTables M target.length) (t : ℕ) + (r : TargetInterval target.length) (integer : ℕ) + (hchild : ∀ action ∈ wideActionList M parent r b P, + ∀ i, child i (action i) = child' i (action i)) + (hinitial : ∀ action ∈ wideActionList M parent r b P, + ∀ i, initial i (action i) = initial' i (action i)) : + keyedOnlineCandidate source target parent P F exponent H b tau eta kappa + child initial children t r integer = + keyedOnlineCandidate source target parent P F exponent H b tau eta kappa + child' initial' children t r integer := by + have hband := representativeBandActions_congr_child source target parent r b P tau + ((2 : ℚ) ^ (-(exponent : ℤ))) child child' hchild + have henv := representativeBandEnvelope_congr source target parent r b P exponent tau + child child' initial initial' hchild hinitial + have htest := testUnskippedBand_isSome_congr source target parent r b P exponent tau F + child child' initial initial' hchild hinitial + rw [keyedOnlineCandidate_test_form, keyedOnlineCandidate_test_form] + rw [htest, henv, hband] + +theorem wideWarmupInputs_pair {nx ny M : ℕ} (parent : TargetInterval nx) (P b : ℕ) + (representatives : List (ℕ × TargetInterval ny)) (r : TargetInterval ny) + (hrep : (b, r) ∈ representatives) (action : Fin M → TargetInterval ny) + (haction : action ∈ wideActionList M parent r b P) (i : Fin M) : + (i, action i) ∈ wideWarmupInputs parent P representatives := by + apply List.mem_eraseDups.mpr + apply List.mem_flatMap.mpr + refine ⟨(b, r), hrep, List.mem_flatMap.mpr ?_⟩ + exact ⟨i, List.mem_finRange i, List.mem_map.mpr + ⟨action i, finiteAssignments_sound M _ action haction i, rfl⟩⟩ + + + +section QueryBands + +variable {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (N P F exponent H Q : ℕ) + (tau a eta kappa : ℚ) (t : ℕ) + (parentInitial : TargetInterval target.length → ℚ) + (child child' initial initial' current : Fin M → TargetInterval target.length → ℚ) + (children : PhysicalChildTables M target.length) + (integer : ℕ → TargetInterval target.length → ℕ) (draw : CellGroupDraws M F Q) + (q : TargetInterval target.length) + (hchild : ∀ input ∈ refinementBandInputList parent N P F exponent a parentInitial q, + child input.1 input.2 = child' input.1 input.2) + (hinitial : ∀ input ∈ refinementBandInputList parent N P F exponent a parentInitial q, + initial input.1 input.2 = initial' input.1 input.2) + +include hchild hinitial + +theorem localOnlineCandidates_congr_bandTables : + localOnlineCandidates source target parent N P F exponent H tau a eta kappa + parentInitial child initial children t integer q = + localOnlineCandidates source target parent N P F exponent H tau a eta kappa + parentInitial child' initial' children t integer q := by + unfold localOnlineCandidates + apply List.filterMap_congr + intro b hb + dsimp only + split_ifs with heligible + · apply keyedOnlineCandidate_congr_bandTables source target parent P F exponent H b tau eta kappa + child child' initial initial' children t _ _ + · intro action ha i + exact hchild _ (wideWarmupInputs_pair parent P b _ _ + (queryEarlierRepresentatives_online N P F exponent a parentInitial q b hb) action ha i) + · intro action ha i + exact hinitial _ (wideWarmupInputs_pair parent P b _ _ + (queryEarlierRepresentatives_online N P F exponent a parentInitial q b hb) action ha i) + · rfl + +theorem localCellGroupActions_congr_bandTables : + localCellGroupActions source target parent N P F exponent Q tau a parentInitial + child initial current draw q = + localCellGroupActions source target parent N P F exponent Q tau a parentInitial + child' initial' current draw q := by + unfold localCellGroupActions + apply List.flatMap_congr + intro b hb + apply List.filterMap_congr + intro cell hc + have hkey : (b, cell) ∈ localGroupQueryKeys N F exponent a parentInitial q := + List.mem_flatMap.mpr ⟨b, hb, List.mem_map.mpr ⟨cell, hc, rfl⟩⟩ + apply chooseCellGroupAction_congr_bandTables source target parent b P F exponent Q tau a + parentInitial child child' initial initial' current cell (draw b cell) + · intro r hr action ha i + exact hchild _ (wideWarmupInputs_pair parent P b _ r + (queryEarlierRepresentatives_cell N P F exponent a parentInitial q (b, cell) hkey r hr) action ha i) + · intro r hr action ha i + exact hinitial _ (wideWarmupInputs_pair parent P b _ r + (queryEarlierRepresentatives_cell N P F exponent a parentInitial q (b, cell) hkey r hr) action ha i) + +end QueryBands + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/RefinementBufferRanges.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/RefinementBufferRanges.lean new file mode 100644 index 0000000000000000000000000000000000000000..87f0a49e6a2a1219ef8b790d97519df073f380ee --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/RefinementBufferRanges.lean @@ -0,0 +1,81 @@ +import OAI.Combinatorics.EditApproximation.Probability.FiniteBufferRanges +import OAI.Combinatorics.EditApproximation.Geometry.RefinementBandSupport + +namespace OAI + +/-! The actual earlier-history gather projects into the child-initial +gather. Consequently its default-zero word table retains the required +history bounds, even at coordinates absent from both finite buffers. -/ + +namespace EditApproximation + +theorem queryEarlierInputCover_initial {nx ny M : ℕ} + (parent : TargetInterval nx) (N P F exponent history : ℕ) (a : ℚ) + (initial : TargetInterval ny → ℚ) (q : TargetInterval ny) + (input : Fin M × ℕ × TargetInterval ny) + (hinput : input ∈ queryEarlierInputCover parent N P F exponent history a initial q) : + (input.1, input.2.2) ∈ refinementBandInputList parent N P F exponent a initial q := by + obtain ⟨br, hbr, hinput⟩ := Finset.mem_biUnion.mp hinput + obtain ⟨i, _, hinput⟩ := Finset.mem_biUnion.mp hinput + obtain ⟨s, _, hinput⟩ := Finset.mem_biUnion.mp hinput + obtain ⟨r, hr, rfl⟩ := Finset.mem_image.mp hinput + apply List.mem_eraseDups.mpr + apply List.mem_flatMap.mpr + refine ⟨br, List.mem_toFinset.mp hbr, List.mem_flatMap.mpr ?_⟩ + exact ⟨i, List.mem_finRange i, List.mem_map.mpr ⟨r, List.mem_toFinset.mp hr, rfl⟩⟩ + +namespace BinaryFraction + +theorem gatheredRefinementHistory_range {nx ny M : ℕ} + (parent : TargetInterval nx) (N P F exponent history : ℕ) (a : ℚ) + (parentInitial : TargetInterval ny → ℚ) (q : TargetInterval ny) + (equalHistory : (Fin M × ℕ × TargetInterval ny) → + (Fin M × ℕ × TargetInterval ny) → Bool × ℕ) + (equalChild : (Fin M × TargetInterval ny) → (Fin M × TargetInterval ny) → Bool × ℕ) + (heh : ∀ x y, (equalHistory x y).1 = true ↔ x = y) + (hec : ∀ x y, (equalChild x y).1 = true ↔ x = y) + (historical : Fin M × ℕ × TargetInterval ny → BinaryFraction) + (initial : Fin M × TargetInterval ny → BinaryFraction) + (hnonneg : ∀ input, 0 ≤ (historical input).value) + (hinitial : ∀ input, 0 ≤ (initial input).value) + (hbound : ∀ input, (historical input).value ≤ (initial (input.1, input.2.2)).value) + (input : Fin M × ℕ × TargetInterval ny) : + let earlierKeys := orderedInputs historyInputCode (historyInputCode_injective M ny) + (queryEarlierInputCover parent N P F exponent history a parentInitial q) + let initialKeys := refinementBandInputList (M := M) parent N P F exponent a parentInitial q + 0 ≤ (gatheredWordLookupWithWork equalHistory earlierKeys (earlierKeys.map historical) input).1.value ∧ + (gatheredWordLookupWithWork equalHistory earlierKeys (earlierKeys.map historical) input).1.value ≤ + (gatheredWordLookupWithWork equalChild initialKeys (initialKeys.map initial) + (input.1, input.2.2)).1.value := by + dsimp only + rw [gatheredWordLookupWithWork_value equalHistory heh, + gatheredWordLookupWithWork_value equalChild hec] + simp only [List.map_map, Function.comp_def] + let earlierKeys := orderedInputs historyInputCode (historyInputCode_injective M ny) + (queryEarlierInputCover parent N P F exponent history a parentInitial q) + let initialKeys := refinementBandInputList (M := M) parent N P F exponent a parentInitial q + change 0 ≤ finiteAnswerTable earlierKeys (earlierKeys.map fun x => (historical x).value) input ∧ + finiteAnswerTable earlierKeys (earlierKeys.map fun x => (historical x).value) input ≤ + finiteAnswerTable initialKeys (initialKeys.map fun x => (initial x).value) (input.1, input.2.2) + constructor + · apply finiteAnswerTable_nonneg + intro value hv + obtain ⟨key, _, rfl⟩ := List.mem_map.mp hv + exact hnonneg key + · by_cases hinput : input ∈ earlierKeys + · have hp : (input.1, input.2.2) ∈ initialKeys := + queryEarlierInputCover_initial parent N P F exponent history a parentInitial q input + ((mem_orderedInputs historyInputCode (historyInputCode_injective M ny) _ input).mp hinput) + rw [finiteAnswerTable_map earlierKeys _ input hinput, + finiteAnswerTable_map initialKeys _ _ hp] + exact hbound input + · rw [finiteAnswerTable_eq_zero_of_not_mem earlierKeys _ input hinput] + apply finiteAnswerTable_nonneg + intro value hv + obtain ⟨key, _, rfl⟩ := List.mem_map.mp hv + exact hinitial key + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/RefinementConeLocality.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/RefinementConeLocality.lean new file mode 100644 index 0000000000000000000000000000000000000000..ad35fdda9ed5ff42a5eb48d3740f96512014494a --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/RefinementConeLocality.lean @@ -0,0 +1,35 @@ +import OAI.Combinatorics.EditApproximation.Refinement.StageWarmup +import OAI.Combinatorics.EditApproximation.Numerics.RationalPruning + +namespace OAI + +/-! Good-seed equality with the finite local scale and center rule. -/ + +namespace EditApproximation + +theorem refinement_cone_locality_numeric {w wr distance b a F cone : ℚ} + (hw : 0 < w) (ha : 1 ≤ a) (hF : 1 ≤ F) (hdistance : 0 ≤ distance) + (hspatial : |w - wr| ≤ 32 * F * distance) + (heligible : b / (4 * a) ≤ wr ∧ wr ≤ 8 * F * b) + (hconeLower : 128 * F * distance ≤ cone) (hconeUpper : cone ≤ w) : + w / (16 * F) ≤ b ∧ b ≤ 8 * a * w ∧ distance ≤ w := by + have ha0 : 0 < a := lt_of_lt_of_le zero_lt_one ha + have hF0 : 0 < F := lt_of_lt_of_le zero_lt_one hF + have hnear : 32 * F * distance ≤ w / 4 := by nlinarith only [hconeLower, hconeUpper] + have hdiff := abs_le.mp hspatial + have hwrLower : 3 * w / 4 ≤ wr := by linarith only [hdiff.2, hnear] + have hwrUpper : wr ≤ 5 * w / 4 := by linarith only [hdiff.1, hnear] + have hlower : w / (16 * F) ≤ b := by + apply (div_le_iff₀ (by positivity : 0 < 16 * F)).2 + nlinarith only [hwrLower, heligible.2, hw.le] + have hb : b ≤ wr * (4 * a) := (div_le_iff₀ (by positivity : 0 < 4 * a)).1 heligible.1 + have hmul := mul_le_mul_of_nonneg_right hwrUpper (show 0 ≤ 4 * a by positivity) + have hupper : b ≤ 8 * a * w := by nlinarith only [hb, hmul, mul_nonneg ha0.le hw.le] + have hdist : distance ≤ 128 * F * distance := by + have hm := mul_le_mul_of_nonneg_right hF hdistance + nlinarith only [hm, hdistance] + exact ⟨hlower, hupper, hdist.trans (hconeLower.trans hconeUpper)⟩ + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/RefinementDataQuery.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/RefinementDataQuery.lean new file mode 100644 index 0000000000000000000000000000000000000000..3216cf602bb3796e9d5936d945784d39ea9411de --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/RefinementDataQuery.lean @@ -0,0 +1,134 @@ +import OAI.Combinatorics.EditApproximation.Geometry.RefinementBandSupport + +namespace OAI + +/-! Adaptive gathering of all fixed data used by one local refinement +entry: parent initial values, child warmup masses and child initial values. +Only the raw local support and the resulting wide coordinate lists are +requested. The later earlier/current gathers remain those of the literal +local refinement query. -/ + +namespace EditApproximation + +section BandData + +variable {ι α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (N P F exponent H Q : ℕ) + (tau a eta kappa delta : ℚ) (t : ℕ) + (parentInitial : TargetInterval target.length → ℚ) + (readMass readInitial : Fin M × TargetInterval target.length → FiniteQuery ι) + (draw : CellGroupDraws M F Q) (integer : ℕ → TargetInterval target.length → ℕ) + (q : TargetInterval target.length) + (readEarlier : (Fin M × ℕ × TargetInterval target.length) → FiniteQuery ι) + (readCurrent : (Fin M × TargetInterval target.length) → FiniteQuery ι) + +def localRefinementBandDataQuery : FiniteQuery ι := + let keys := refinementBandInputList (M := M) parent N P F exponent a parentInitial q + FiniteQuery.collect readMass keys fun massValues => + FiniteQuery.collect readInitial keys fun initialValues => + localRefinementStepQuery source target parent N P F exponent H Q tau a eta kappa delta t + parentInitial (fun i r => finiteAnswerTable keys massValues (i, r)) + (fun i r => finiteAnswerTable keys initialValues (i, r)) draw integer q readEarlier readCurrent + +theorem localRefinementBandDataQuery_value (oracle : ι → ℚ) + (child initial : Fin M → TargetInterval target.length → ℚ) + (earlier : PhysicalChildTables M target.length) + (current : Fin M → TargetInterval target.length → ℚ) (ht : 0 < t) + (hreadMass : ∀ input, (readMass input).value oracle = child input.1 input.2) + (hreadInitial : ∀ input, (readInitial input).value oracle = initial input.1 input.2) + (hreadEarlier : ∀ input, (readEarlier input).value oracle = earlier input.1 input.2.1 input.2.2) + (hreadCurrent : ∀ input, (readCurrent input).value oracle = current input.1 input.2) : + (localRefinementBandDataQuery source target parent N P F exponent H Q tau a eta kappa delta t + parentInitial readMass readInitial draw integer q readEarlier readCurrent).value oracle = + rationalLocalWideStep source target parent N P F exponent Q tau a delta parentInitial child initial + (fun i r => earlier i (t - 1) r) current draw + (localOnlineCandidates source target parent N P F exponent H tau a eta kappa + parentInitial child initial earlier (t - 1) integer q) q := by + let keys := refinementBandInputList (M := M) parent N P F exponent a parentInitial q + let mass := fun i r => finiteAnswerTable keys (keys.map fun input => child input.1 input.2) (i, r) + let initial' := fun i r => finiteAnswerTable keys (keys.map fun input => initial input.1 input.2) (i, r) + have hmass : ∀ input ∈ keys, mass input.1 input.2 = child input.1 input.2 := by + intro input hi + exact finiteAnswerTable_map keys _ input hi + have hinitial : ∀ input ∈ keys, initial' input.1 input.2 = initial input.1 input.2 := by + intro input hi + exact finiteAnswerTable_map keys _ input hi + have honline := localOnlineCandidates_congr_bandTables source target parent N P F exponent H + tau a eta kappa (t - 1) parentInitial mass child initial' initial earlier integer q hmass hinitial + have hgroups := localCellGroupActions_congr_bandTables source target parent N P F exponent Q + tau a parentInitial mass child initial' initial current draw q hmass hinitial + unfold localRefinementBandDataQuery + rw [FiniteQuery.collect_value] + simp only [hreadMass] + rw [FiniteQuery.collect_value] + simp only [hreadInitial] + rw [localRefinementStepQuery_value source target parent N P F exponent H Q tau a eta kappa delta t + parentInitial mass initial' draw integer q readEarlier readCurrent oracle earlier current ht + hreadEarlier hreadCurrent] + rw [honline] + unfold rationalLocalWideStep + rw [hgroups] + +end BandData + +section AllData + +variable {ι α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (N P F exponent H Q : ℕ) + (tau a eta kappa delta : ℚ) (t : ℕ) + (readParentInitial : TargetInterval target.length → FiniteQuery ι) + (readMass readInitial : Fin M × TargetInterval target.length → FiniteQuery ι) + (draw : CellGroupDraws M F Q) (integer : ℕ → TargetInterval target.length → ℕ) + (q : TargetInterval target.length) + (readEarlier : (Fin M × ℕ × TargetInterval target.length) → FiniteQuery ι) + (readCurrent : (Fin M × TargetInterval target.length) → FiniteQuery ι) + +def localRefinementDataQuery : FiniteQuery ι := + FiniteQuery.bind (readParentInitial q) fun value => + let keys := refinementInitialSupport N P F exponent a value q + FiniteQuery.collect readParentInitial keys fun initialValues => + localRefinementBandDataQuery source target parent N P F exponent H Q tau a eta kappa delta t + (finiteAnswerTable keys initialValues) readMass readInitial draw integer q readEarlier readCurrent + +theorem localRefinementDataQuery_value (oracle : ι → ℚ) + (parentInitial : TargetInterval target.length → ℚ) + (child initial : Fin M → TargetInterval target.length → ℚ) + (earlier : PhysicalChildTables M target.length) + (current : Fin M → TargetInterval target.length → ℚ) (ht : 0 < t) + (hreadParentInitial : ∀ r, (readParentInitial r).value oracle = parentInitial r) + (hreadMass : ∀ input, (readMass input).value oracle = child input.1 input.2) + (hreadInitial : ∀ input, (readInitial input).value oracle = initial input.1 input.2) + (hreadEarlier : ∀ input, (readEarlier input).value oracle = earlier input.1 input.2.1 input.2.2) + (hreadCurrent : ∀ input, (readCurrent input).value oracle = current input.1 input.2) : + (localRefinementDataQuery source target parent N P F exponent H Q tau a eta kappa delta t + readParentInitial readMass readInitial draw integer q readEarlier readCurrent).value oracle = + rationalLocalWideStep source target parent N P F exponent Q tau a delta parentInitial child initial + (fun i r => earlier i (t - 1) r) current draw + (localOnlineCandidates source target parent N P F exponent H tau a eta kappa + parentInitial child initial earlier (t - 1) integer q) q := by + let keys := refinementInitialSupport N P F exponent a (parentInitial q) q + let cached := finiteAnswerTable keys (keys.map parentInitial) + have heq : ∀ r ∈ refinementInitialSupport N P F exponent a (parentInitial q) q, + parentInitial r = cached r := by + intro r hr + exact (finiteAnswerTable_map keys parentInitial r hr).symm + have honline := localOnlineCandidates_congr_initial source target parent N P F exponent H + tau a eta kappa (t - 1) parentInitial cached child initial earlier integer q heq + have hstep := rationalLocalWideStep_congr_initial source target parent N P F exponent Q tau a + parentInitial cached child initial current draw q heq delta (fun i r => earlier i (t - 1) r) + (localOnlineCandidates source target parent N P F exponent H tau a eta kappa + parentInitial child initial earlier (t - 1) integer q) + unfold localRefinementDataQuery + rw [FiniteQuery.bind_value, hreadParentInitial q, FiniteQuery.collect_value] + simp only [hreadParentInitial] + rw [localRefinementBandDataQuery_value source target parent N P F exponent H Q tau a eta kappa delta t + cached readMass readInitial draw integer q readEarlier readCurrent oracle child initial earlier current ht + hreadMass hreadInitial hreadEarlier hreadCurrent] + rw [← honline] + exact hstep.symm + +end AllData + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/RefinementDataQueryWork.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/RefinementDataQueryWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..4eaaae64252a4bc26883f760c0f40df8619d5572 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/RefinementDataQueryWork.lean @@ -0,0 +1,263 @@ +import OAI.Combinatorics.EditApproximation.Geometry.RefinementDataQuery +import OAI.Combinatorics.EditApproximation.Geometry.LocalRefinementQueryWork + +namespace OAI + +/-! Read counts for the full adaptive data query. Weighting reads permits +the same theorem to count current-index and earlier-index dependencies +separately. The bounds count executed readers, including repeated reads +across successive gathering stages. -/ + +namespace EditApproximation + +theorem list_map_sum_le_constant {ι : Type*} (inputs : List ι) (cost : ι → ℕ) (bound : ℕ) + (hcost : ∀ input, cost input ≤ bound) : + (inputs.map cost).sum ≤ inputs.length * bound := by + calc + _ ≤ (inputs.map fun _ => bound).sum := List.sum_le_sum (fun input _ => hcost input) + _ = _ := by simp + +section BandData + +variable {ι α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (N P F exponent H Q : ℕ) + (tau a eta kappa delta : ℚ) (t : ℕ) + (parentInitial : TargetInterval target.length → ℚ) + (readMass readInitial : Fin M × TargetInterval target.length → FiniteQuery ι) + (draw : CellGroupDraws M F Q) (integer : ℕ → TargetInterval target.length → ℕ) + (q : TargetInterval target.length) + (readEarlier : (Fin M × ℕ × TargetInterval target.length) → FiniteQuery ι) + (readCurrent : (Fin M × TargetInterval target.length) → FiniteQuery ι) + (oracle : ι → ℚ) (weight : ι → ℕ) + (child initial : Fin M → TargetInterval target.length → ℚ) + (earlier : PhysicalChildTables M target.length) + (current : Fin M → TargetInterval target.length → ℚ) (ht : 0 < t) + (hreadMass : ∀ input, (readMass input).value oracle = child input.1 input.2) + (hreadInitial : ∀ input, (readInitial input).value oracle = initial input.1 input.2) + (hreadEarlier : ∀ input, (readEarlier input).value oracle = earlier input.1 input.2.1 input.2.2) + (hreadCurrent : ∀ input, (readCurrent input).value oracle = current input.1 input.2) + +include ht hreadMass hreadInitial hreadEarlier hreadCurrent + +theorem localRefinementBandDataQuery_cost_le (massCost initialCost earlierCost currentCost : ℕ) + (hmassCost : ∀ input, (readMass input).cost oracle weight ≤ massCost) + (hinitialCost : ∀ input, (readInitial input).cost oracle weight ≤ initialCost) + (hearlierCost : ∀ input, (readEarlier input).cost oracle weight ≤ earlierCost) + (hcurrentCost : ∀ input, (readCurrent input).cost oracle weight ≤ currentCost) : + (localRefinementBandDataQuery source target parent N P F exponent H Q tau a eta kappa delta t + parentInitial readMass readInitial draw integer q readEarlier readCurrent).cost oracle weight ≤ + (refinementBandInputList (M := M) parent N P F exponent a parentInitial q).length * + (massCost + initialCost) + + (queryEarlierInputCover (M := M) parent N P F exponent t a parentInitial q).card * earlierCost + + 2 * (currentQueryInputCover source target parent N P F exponent Q tau a parentInitial + child initial current draw q + (localOnlineCandidates source target parent N P F exponent H tau a eta kappa + parentInitial child initial earlier (t - 1) integer q)).card * currentCost := by + let keys := refinementBandInputList (M := M) parent N P F exponent a parentInitial q + let mass := fun i r => finiteAnswerTable keys (keys.map fun input => child input.1 input.2) (i, r) + let initial' := fun i r => finiteAnswerTable keys (keys.map fun input => initial input.1 input.2) (i, r) + have hmass : ∀ input ∈ keys, mass input.1 input.2 = child input.1 input.2 := by + intro input hi + exact finiteAnswerTable_map keys _ input hi + have hinitial : ∀ input ∈ keys, initial' input.1 input.2 = initial input.1 input.2 := by + intro input hi + exact finiteAnswerTable_map keys _ input hi + have honline := localOnlineCandidates_congr_bandTables source target parent N P F exponent H + tau a eta kappa (t - 1) parentInitial mass child initial' initial earlier integer q hmass hinitial + have hgroups := localCellGroupActions_congr_bandTables source target parent N P F exponent Q + tau a parentInitial mass child initial' initial current draw q hmass hinitial + have hcover : currentQueryInputCover source target parent N P F exponent Q tau a parentInitial + mass initial' current draw q + (localOnlineCandidates source target parent N P F exponent H tau a eta kappa + parentInitial mass initial' earlier (t - 1) integer q) = + currentQueryInputCover source target parent N P F exponent Q tau a parentInitial + child initial current draw q + (localOnlineCandidates source target parent N P F exponent H tau a eta kappa + parentInitial child initial earlier (t - 1) integer q) := by + unfold currentQueryInputCover + rw [hgroups, honline] + have hstep := localRefinementStepQuery_cost_le source target parent N P F exponent H Q + tau a eta kappa delta t parentInitial mass initial' draw integer q readEarlier readCurrent + oracle weight earlier current ht hreadEarlier hreadCurrent earlierCost currentCost hearlierCost hcurrentCost + rw [hcover] at hstep + have hm := list_map_sum_le_constant keys (fun input => (readMass input).cost oracle weight) massCost hmassCost + have hi := list_map_sum_le_constant keys (fun input => (readInitial input).cost oracle weight) initialCost hinitialCost + unfold localRefinementBandDataQuery + rw [FiniteQuery.cost_collect] + simp only [hreadMass] + rw [FiniteQuery.cost_collect] + simp only [hreadInitial] + change _ + (_ + (localRefinementStepQuery source target parent N P F exponent H Q tau a eta kappa delta t + parentInitial mass initial' draw integer q readEarlier readCurrent).cost oracle weight) ≤ _ + change _ ≤ keys.length * (massCost + initialCost) + _ + _ + nlinarith only [hstep, hm, hi] + +end BandData + +section AllData + +variable {ι α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (N P F exponent H Q : ℕ) + (tau a eta kappa delta : ℚ) (t : ℕ) + (readParentInitial : TargetInterval target.length → FiniteQuery ι) + (readMass readInitial : Fin M × TargetInterval target.length → FiniteQuery ι) + (draw : CellGroupDraws M F Q) (integer : ℕ → TargetInterval target.length → ℕ) + (q : TargetInterval target.length) + (readEarlier : (Fin M × ℕ × TargetInterval target.length) → FiniteQuery ι) + (readCurrent : (Fin M × TargetInterval target.length) → FiniteQuery ι) + (oracle : ι → ℚ) (weight : ι → ℕ) + (parentInitial : TargetInterval target.length → ℚ) + (child initial : Fin M → TargetInterval target.length → ℚ) + (earlier : PhysicalChildTables M target.length) + (current : Fin M → TargetInterval target.length → ℚ) (ht : 0 < t) + (hreadParentInitial : ∀ r, (readParentInitial r).value oracle = parentInitial r) + (hreadMass : ∀ input, (readMass input).value oracle = child input.1 input.2) + (hreadInitial : ∀ input, (readInitial input).value oracle = initial input.1 input.2) + (hreadEarlier : ∀ input, (readEarlier input).value oracle = earlier input.1 input.2.1 input.2.2) + (hreadCurrent : ∀ input, (readCurrent input).value oracle = current input.1 input.2) + +include ht hreadParentInitial hreadMass hreadInitial hreadEarlier hreadCurrent + +theorem localRefinementDataQuery_cost_le (parentCost massCost initialCost earlierCost currentCost : ℕ) + (hparentCost : ∀ r, (readParentInitial r).cost oracle weight ≤ parentCost) + (hmassCost : ∀ input, (readMass input).cost oracle weight ≤ massCost) + (hinitialCost : ∀ input, (readInitial input).cost oracle weight ≤ initialCost) + (hearlierCost : ∀ input, (readEarlier input).cost oracle weight ≤ earlierCost) + (hcurrentCost : ∀ input, (readCurrent input).cost oracle weight ≤ currentCost) : + (localRefinementDataQuery source target parent N P F exponent H Q tau a eta kappa delta t + readParentInitial readMass readInitial draw integer q readEarlier readCurrent).cost oracle weight ≤ + (1 + (refinementInitialSupport N P F exponent a (parentInitial q) q).length) * parentCost + + (refinementBandInputList (M := M) parent N P F exponent a parentInitial q).length * + (massCost + initialCost) + + (queryEarlierInputCover (M := M) parent N P F exponent t a parentInitial q).card * earlierCost + + 2 * (currentQueryInputCover source target parent N P F exponent Q tau a parentInitial + child initial current draw q + (localOnlineCandidates source target parent N P F exponent H tau a eta kappa + parentInitial child initial earlier (t - 1) integer q)).card * currentCost := by + let keys := refinementInitialSupport N P F exponent a (parentInitial q) q + let cached := finiteAnswerTable keys (keys.map parentInitial) + have heq : ∀ r ∈ keys, parentInitial r = cached r := by + intro r hr + exact (finiteAnswerTable_map keys parentInitial r hr).symm + have hreps := queryEarlierRepresentatives_congr_initial N P F exponent a parentInitial cached q heq + have hearlier := queryEarlierInputCover_congr_initial (M := M) N P F exponent a parentInitial cached q heq parent t + have hshared := querySharedInputCover_congr_initial source target parent N P F exponent Q a + parentInitial cached draw q heq + have hgroups := localCellGroupActions_congr_initial source target parent N P F exponent Q tau a + parentInitial cached child initial current draw q heq + have honline := localOnlineCandidates_congr_initial source target parent N P F exponent H + tau a eta kappa (t - 1) parentInitial cached child initial earlier integer q heq + have hstep := localRefinementBandDataQuery_cost_le source target parent N P F exponent H Q + tau a eta kappa delta t cached readMass readInitial draw integer q readEarlier readCurrent + oracle weight child initial earlier current ht hreadMass hreadInitial hreadEarlier hreadCurrent + massCost initialCost earlierCost currentCost hmassCost hinitialCost hearlierCost hcurrentCost + have hbandKeys : refinementBandInputList (M := M) parent N P F exponent a parentInitial q = + refinementBandInputList parent N P F exponent a cached q := by + unfold refinementBandInputList + rw [hreps] + have hcover : currentQueryInputCover source target parent N P F exponent Q tau a parentInitial + child initial current draw q + (localOnlineCandidates source target parent N P F exponent H tau a eta kappa + parentInitial child initial earlier (t - 1) integer q) = + currentQueryInputCover source target parent N P F exponent Q tau a cached + child initial current draw q + (localOnlineCandidates source target parent N P F exponent H tau a eta kappa + cached child initial earlier (t - 1) integer q) := by + unfold currentQueryInputCover + rw [hshared, hgroups, honline] + rw [← hbandKeys, ← hearlier, ← hcover] at hstep + have hsum := list_map_sum_le_constant keys + (fun r => (readParentInitial r).cost oracle weight) parentCost hparentCost + have hfirst := hparentCost q + unfold localRefinementDataQuery + rw [FiniteQuery.cost_bind, hreadParentInitial q, FiniteQuery.cost_collect] + simp only [hreadParentInitial] + change _ + (_ + (localRefinementBandDataQuery source target parent N P F exponent H Q + tau a eta kappa delta t cached readMass readInitial draw integer q readEarlier readCurrent).cost oracle weight) ≤ _ + change _ ≤ (1 + keys.length) * parentCost + _ + _ + _ + nlinarith only [hstep, hsum, hfirst] + +end AllData + +section Keys + +variable {ι α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (N P F exponent H Q : ℕ) + (tau a eta kappa delta : ℚ) (t : ℕ) + (parentInitial : TargetInterval target.length → ℚ) + (child initial : Fin M → TargetInterval target.length → ℚ) + (readParent : TargetInterval target.length → FiniteQuery ι) + (readMass readInitial : Fin M × TargetInterval target.length → FiniteQuery ι) + (draw : CellGroupDraws M F Q) (integer : ℕ → TargetInterval target.length → ℕ) + (q : TargetInterval target.length) + (readEarlier : (Fin M × ℕ × TargetInterval target.length) → FiniteQuery ι) + (readCurrent : (Fin M × TargetInterval target.length) → FiniteQuery ι) + (oracle : ι → ℚ) (predicate : ι → Prop) + +theorem localRefinementStepQuery_keys_all + (hearlier : ∀ input key, key ∈ (readEarlier input).keys oracle → predicate key) + (hcurrent : ∀ input key, key ∈ (readCurrent input).keys oracle → predicate key) : + ∀ key ∈ (localRefinementStepQuery source target parent N P F exponent H Q tau a eta kappa delta t + parentInitial child initial draw integer q readEarlier readCurrent).keys oracle, predicate key := by + unfold localRefinementStepQuery + apply FiniteQuery.keys_all_collect + · intro input _ key hk + exact hearlier input key hk + · intro earlierValues + apply FiniteQuery.keys_all_collect + · intro input _ key hk + exact hcurrent input key hk + · intro sharedValues + apply FiniteQuery.keys_all_collect + · intro input _ key hk + exact hcurrent input key hk + · intro currentValues key hk + exact False.elim (List.not_mem_nil hk) + +theorem localRefinementBandDataQuery_keys_all + (hmass : ∀ input key, key ∈ (readMass input).keys oracle → predicate key) + (hinitial : ∀ input key, key ∈ (readInitial input).keys oracle → predicate key) + (hearlier : ∀ input key, key ∈ (readEarlier input).keys oracle → predicate key) + (hcurrent : ∀ input key, key ∈ (readCurrent input).keys oracle → predicate key) : + ∀ key ∈ (localRefinementBandDataQuery source target parent N P F exponent H Q tau a eta kappa delta t + parentInitial readMass readInitial draw integer q readEarlier readCurrent).keys oracle, predicate key := by + unfold localRefinementBandDataQuery + apply FiniteQuery.keys_all_collect + · intro input _ key hk + exact hmass input key hk + · intro massValues + apply FiniteQuery.keys_all_collect + · intro input _ key hk + exact hinitial input key hk + · intro initialValues + exact localRefinementStepQuery_keys_all source target parent N P F exponent H Q + tau a eta kappa delta t parentInitial _ _ draw integer q readEarlier readCurrent + oracle predicate hearlier hcurrent + +theorem localRefinementDataQuery_keys_all + (hparent : ∀ r key, key ∈ (readParent r).keys oracle → predicate key) + (hmass : ∀ input key, key ∈ (readMass input).keys oracle → predicate key) + (hinitial : ∀ input key, key ∈ (readInitial input).keys oracle → predicate key) + (hearlier : ∀ input key, key ∈ (readEarlier input).keys oracle → predicate key) + (hcurrent : ∀ input key, key ∈ (readCurrent input).keys oracle → predicate key) : + ∀ key ∈ (localRefinementDataQuery source target parent N P F exponent H Q tau a eta kappa delta t + readParent readMass readInitial draw integer q readEarlier readCurrent).keys oracle, predicate key := by + unfold localRefinementDataQuery + rw [FiniteQuery.keys_bind] + intro key hk + rcases List.mem_append.mp hk with hfirst | hrest + · exact hparent q key hfirst + · apply FiniteQuery.keys_all_collect oracle predicate readParent + (refinementInitialSupport N P F exponent a ((readParent q).value oracle) q) _ ?_ ?_ key hrest + · intro r _ other ho + exact hparent r other ho + · intro initialValues + exact localRefinementBandDataQuery_keys_all source target parent N P F exponent H Q + tau a eta kappa delta t _ readMass readInitial draw integer q readEarlier readCurrent + oracle predicate hmass hinitial hearlier hcurrent + +end Keys + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/RefinementErrorTerms.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/RefinementErrorTerms.lean new file mode 100644 index 0000000000000000000000000000000000000000..49d0521aea3e5658ea117451e121022c61085754 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/RefinementErrorTerms.lean @@ -0,0 +1,224 @@ +import OAI.Combinatorics.EditApproximation.Refinement.ComputedStageTime + +namespace OAI + +/-! Explicit estimates for the actual four parts of the refinement error. -/ + +namespace EditApproximation + +theorem refinement_grid_error {ell H M J P : ℝ} + (hell : 1 ≤ ell) (hH : ell ≤ H) (hM : M ≤ H) + (hJ : 0 ≤ J) (hdepth : J * ell ≤ 100 * H) (hP : H ^ 20 ≤ P) : + (8 * M + 512 * ell) * J / P ≤ 52000 / H ^ 18 := by + have hHone : 1 ≤ H := hell.trans hH + have hHpos : 0 < H := lt_of_lt_of_le zero_lt_one hHone + have hJbound : J ≤ 100 * H := by + have hm := mul_le_mul_of_nonneg_left hell hJ + nlinarith only [hm, hdepth] + have hcoef : 8 * M + 512 * ell ≤ 520 * H := by linarith only [hM, hH] + have hnum := mul_le_mul hcoef hJbound hJ (by positivity : (0 : ℝ) ≤ 520 * H) + have hPpos : 0 < P := (pow_pos hHpos 20).trans_le hP + calc + _ ≤ 52000 * H ^ 2 / P := div_le_div_of_nonneg_right (by nlinarith only [hnum]) hPpos.le + _ ≤ 52000 * H ^ 2 / H ^ 20 := div_le_div_of_nonneg_left (by positivity) (pow_pos hHpos 20) hP + _ = _ := by field_simp + +theorem refinement_excluded_error {ell root H J P T S : ℝ} + (hell : 1 ≤ ell) (hroot : 1 ≤ root) (hrootPower : root ^ 4 = H) + (hS : 0 < S) (hcount : S * ell ^ 2 = H) + (hJP : J / P ≤ 1) (hJT : J / T ≤ 100 * root / ell) : + 40000 * ell ^ 2 * root * (1 + J / P + J / T) / S ≤ + 8040000 * ell ^ 4 / root ^ 2 := by + have hellpos : 0 < ell := lt_of_lt_of_le zero_lt_one hell + have hrootpos : 0 < root := lt_of_lt_of_le zero_lt_one hroot + have hSrepr : S = root ^ 4 / ell ^ 2 := by + apply (eq_div_iff (pow_ne_zero 2 hellpos.ne')).2 + exact hcount.trans hrootPower.symm + have hbracket : 1 + J / P + J / T ≤ 2 + 100 * root / ell := by linarith only [hJP, hJT] + have hfirst : 80000 * ell ^ 4 / root ^ 3 ≤ 80000 * ell ^ 4 / root ^ 2 := by + apply div_le_div_of_nonneg_left (by positivity) (pow_pos hrootpos 2) + have hm := mul_le_mul_of_nonneg_right hroot (pow_nonneg hrootpos.le 2) + nlinarith only [hm, show root * root ^ 2 = root ^ 3 by ring] + have hellPower : ell ^ 3 ≤ ell ^ 4 := pow_le_pow_right₀ hell (by decide : 3 ≤ 4) + have hsecond : 4000000 * ell ^ 3 / root ^ 2 ≤ 4000000 * ell ^ 4 / root ^ 2 := + div_le_div_of_nonneg_right (mul_le_mul_of_nonneg_left hellPower (by norm_num)) (pow_nonneg hrootpos.le 2) + calc + _ ≤ 40000 * ell ^ 2 * root * (2 + 100 * root / ell) / S := + div_le_div_of_nonneg_right (mul_le_mul_of_nonneg_left hbracket (by positivity)) hS.le + _ = 80000 * ell ^ 4 / root ^ 3 + 4000000 * ell ^ 3 / root ^ 2 := by + rw [hSrepr] + field_simp + ring + _ ≤ 80000 * ell ^ 4 / root ^ 2 + 4000000 * ell ^ 4 / root ^ 2 := add_le_add hfirst hsecond + _ = 4080000 * ell ^ 4 / root ^ 2 := by ring + _ ≤ _ := div_le_div_of_nonneg_right (mul_le_mul_of_nonneg_right + (by norm_num : (4080000 : ℝ) ≤ 8040000) (pow_nonneg hellpos.le 4)) (pow_nonneg hrootpos.le 2) + +theorem refinement_depth_ratios {ell H root J P T S : ℝ} + (hell : 1 ≤ ell) (hH : 100 ≤ H) (hroot : 0 < root) (hrootPower : root ^ 4 = H) + (hJ : 0 ≤ J) (hdepth : J * ell ≤ 100 * H) + (hP : H ^ 20 ≤ P) (hT : root ^ 3 ≤ T) + (hS : 0 < S) (hcount : S * ell ^ 2 = H) : + J / P ≤ 1 ∧ J / T ≤ 100 * root / ell ∧ J / S ≤ 100 * ell := by + have hellpos : 0 < ell := lt_of_lt_of_le zero_lt_one hell + have hHone : 1 ≤ H := by linarith only [hH] + have hHpos : 0 < H := by linarith only [hH] + have hJbound : J ≤ 100 * H := by + have hm := mul_le_mul_of_nonneg_left hell hJ + nlinarith only [hm, hdepth] + have hPbound : 100 * H ≤ P := by + calc + 100 * H ≤ H ^ 2 := by nlinarith only [hH, sq_nonneg H] + _ ≤ H ^ 20 := pow_le_pow_right₀ hHone (by decide : 2 ≤ 20) + _ ≤ P := hP + have hPpos : 0 < P := (pow_pos hHpos 20).trans_le hP + have hTpos : 0 < T := (pow_pos hroot 3).trans_le hT + refine ⟨(div_le_one₀ hPpos).2 (hJbound.trans hPbound), ?_, ?_⟩ + · apply (div_le_div_iff₀ hTpos hellpos).2 + have hm := mul_le_mul_of_nonneg_left hT (show 0 ≤ 100 * root by positivity) + have hid : (100 * root) * root ^ 3 = 100 * H := by rw [← hrootPower]; ring + rw [hid] at hm + exact hdepth.trans hm + · apply (div_le_iff₀ hS).2 + apply le_of_mul_le_mul_right _ hellpos + calc + J * ell ≤ 100 * H := hdepth + _ = (100 * ell * S) * ell := by rw [← hcount]; ring + +theorem refinement_ordinary_error {ell root q J S : ℝ} + (hell : 1 ≤ ell) (hroot : 0 < root) (hq : 1 ≤ q) + (hJS : J / S ≤ 100 * ell) : + 2 * J / S * (1 / root + 4 * (1 / ell ^ 4) * ell + + 64 * ell * (4 * q * ell / ell ^ 5 + 2 * (1 / ell ^ 4)) + 2 * (1 / ell ^ 10)) ≤ + 200 * ell / root + 1000000 * q / ell ^ 2 := by + have hellpos : 0 < ell := lt_of_lt_of_le zero_lt_one hell + have hqpos : 0 < q := lt_of_lt_of_le zero_lt_one hq + let bracket := 1 / root + 4 * (1 / ell ^ 4) * ell + + 64 * ell * (4 * q * ell / ell ^ 5 + 2 * (1 / ell ^ 4)) + 2 * (1 / ell ^ 10) + have hbracket : 0 ≤ bracket := by dsimp only [bracket]; positivity + have htwo : 2 * J / S ≤ 200 * ell := by + calc + 2 * J / S = 2 * (J / S) := by ring + _ ≤ 2 * (100 * ell) := mul_le_mul_of_nonneg_left hJS (by norm_num) + _ = _ := by ring + have hpower : ell ^ 2 ≤ ell ^ 9 := pow_le_pow_right₀ hell (by decide : 2 ≤ 9) + have hsmall : 400 / ell ^ 9 ≤ 400 / ell ^ 2 := + div_le_div_of_nonneg_left (by norm_num) (pow_pos hellpos 2) hpower + have hcoeff : 26400 + 51200 * q + 400 ≤ 1000000 * q := by linarith only [hq] + calc + _ ≤ 200 * ell * bracket := mul_le_mul_of_nonneg_right htwo hbracket + _ = 200 * ell / root + (26400 + 51200 * q) / ell ^ 2 + 400 / ell ^ 9 := by + dsimp only [bracket] + field_simp + ring + _ ≤ 200 * ell / root + (26400 + 51200 * q + 400) / ell ^ 2 := by + have h := add_le_add_right hsmall (200 * ell / root + (26400 + 51200 * q) / ell ^ 2) + simpa only [add_div, add_assoc] using h + _ ≤ _ := add_le_add_right (div_le_div_of_nonneg_right hcoeff (pow_nonneg hellpos.le 2)) _ + +theorem refinement_numerical_error {ell H J S : ℝ} + (hell : 0 ≤ ell) (hH : 1 ≤ H) (hJ : 0 ≤ J) (hS : 0 < S) + (hdepth : J * ell ≤ 100 * H) : + 2 * J / S * (64 * ell * (S / H ^ 3) + 2 * S * (1 / H ^ 4) * ell) ≤ 13200 / H ^ 2 := by + have hHpos : 0 < H := lt_of_lt_of_le zero_lt_one hH + have hsmall : 4 * ell * J / H ^ 4 ≤ 4 * ell * J / H ^ 3 := + div_le_div_of_nonneg_left (by positivity) (pow_pos hHpos 3) + (pow_le_pow_right₀ hH (by decide : 3 ≤ 4)) + calc + _ = 128 * ell * J / H ^ 3 + 4 * ell * J / H ^ 4 := by field_simp; ring + _ ≤ 128 * ell * J / H ^ 3 + 4 * ell * J / H ^ 3 := add_le_add_right hsmall _ + _ = 132 * (J * ell) / H ^ 3 := by ring + _ ≤ 132 * (100 * H) / H ^ 3 := div_le_div_of_nonneg_right + (mul_le_mul_of_nonneg_left hdepth (by norm_num)) (pow_nonneg hHpos.le 3) + _ = _ := by field_simp; ring + +theorem refinement_error_from_stage_bounds {ell H root q M J P T S : ℝ} + (hell : 64000000000000 ≤ ell) (hH : ell ^ 2 ≤ H) + (hroot : ell ^ 4 ≤ root) (hrootPower : root ^ 4 = H) + (hq : 1 ≤ q) (hqSquare : q ^ 2 ≤ ell) + (hM : M ≤ H) (hJ : 0 ≤ J) (hdepth : J * ell ≤ 100 * H) + (hP : H ^ 20 ≤ P) (hT : root ^ 3 ≤ T) + (hS : 0 < S) (hcount : S * ell ^ 2 = H) : + (8 * M + 512 * ell) * J / P + + (40000 * root * ell ^ 2 * (1 + J / P + J / T) + + 2 * J * (1 / root + 4 * (1 / ell ^ 4) * ell + + (64 * ell * (4 * q * ell / ell ^ 5 + 2 * (1 / ell ^ 4) + S / H ^ 3) + + 2 * (1 / ell ^ 10) + 2 * S * (1 / H ^ 4) * ell))) / S < 1 / ell := by + have hellone : 1 ≤ ell := by linarith only [hell] + have hellpos : 0 < ell := lt_of_lt_of_le zero_lt_one hellone + have hHell : ell ≤ H := (by nlinarith only [hellone] : ell ≤ ell ^ 2).trans hH + have hHlarge : 100 ≤ H := by linarith only [hell, hHell] + have hrootone : 1 ≤ root := (one_le_pow₀ hellone).trans hroot + have hrootpos : 0 < root := lt_of_lt_of_le zero_lt_one hrootone + have hratios := refinement_depth_ratios hellone hHlarge hrootpos hrootPower hJ hdepth hP hT hS hcount + have hgrid := refinement_grid_error hellone hHell hM hJ hdepth hP + have hbad := refinement_excluded_error hellone hrootone hrootPower hS hcount hratios.1 hratios.2.1 + have hordinary := refinement_ordinary_error hellone hrootpos hq hratios.2.2 + have hnumeric := refinement_numerical_error (zero_le_one.trans hellone) (by linarith only [hHlarge]) hJ hS hdepth + have hsplit : (8 * M + 512 * ell) * J / P + + (40000 * root * ell ^ 2 * (1 + J / P + J / T) + + 2 * J * (1 / root + 4 * (1 / ell ^ 4) * ell + + (64 * ell * (4 * q * ell / ell ^ 5 + 2 * (1 / ell ^ 4) + S / H ^ 3) + + 2 * (1 / ell ^ 10) + 2 * S * (1 / H ^ 4) * ell))) / S = + (8 * M + 512 * ell) * J / P + + 40000 * ell ^ 2 * root * (1 + J / P + J / T) / S + + 2 * J / S * (1 / root + 4 * (1 / ell ^ 4) * ell + + 64 * ell * (4 * q * ell / ell ^ 5 + 2 * (1 / ell ^ 4)) + 2 * (1 / ell ^ 10)) + + 2 * J / S * (64 * ell * (S / H ^ 3) + 2 * S * (1 / H ^ 4) * ell) := by ring + rw [hsplit] + apply lt_of_le_of_lt _ (refinement_error_envelope hell hH hroot (zero_le_one.trans hq) hqSquare) + linarith only [hgrid, hbad, hordinary, hnumeric] + +noncomputable def computedRefinementError (N nx : ℕ) : ℝ := + let ell : ℝ := inputSmallLog N + let H : ℝ := inputHeight N + let M : ℝ := (integerParameters N).M + let J : ℝ := intervalTreeDepth (integerParameters N).M nx + let P : ℝ := (integerParameters N).P + let T : ℝ := (integerParameters N).T + let S : ℝ := (integerParameters N).S + let root := heightQuarterRoot N + let q : ℝ := coarseExponent (inputSmallLog N) + 21 + (8 * M + 512 * ell) * J / P + + (40000 * root * ell ^ 2 * (1 + J / P + J / T) + + 2 * J * (1 / root + 4 * (1 / ell ^ 4) * ell + + (64 * ell * (4 * q * ell / ell ^ 5 + 2 * (1 / ell ^ 4) + S / H ^ 3) + + 2 * (1 / ell ^ 10) + 2 * S * (1 / H ^ 4) * ell))) / S + +theorem computedRefinementError_lt (N nx : ℕ) (hN : 0 < N) (hnx : nx ≤ N) + (hell : 2 ^ 1000 ≤ inputSmallLog N) : computedRefinementError N nx < 1 / (inputSmallLog N : ℝ) := by + have hcut : 64000000000000 ≤ inputSmallLog N := by + have hsmall : 64000000000000 ≤ (2 : ℕ) ^ 46 := by norm_num + exact hsmall.trans ((pow_le_pow_right₀ (by decide : 1 ≤ (2 : ℕ)) + (by decide : 46 ≤ 1000)).trans hell) + have hlarge : (64000000000000 : ℝ) ≤ inputSmallLog N := by exact_mod_cast hcut + have hellone : (1 : ℝ) ≤ inputSmallLog N := by linarith only [hlarge] + have hpoly := inputHeight_polynomial_slack N hN hell + have hroot := fourth_root_polynomial_slack hellone hpoly + (Real.sqrt_nonneg _) (heightQuarterRoot_fourth_power N) + have hHone : 1 ≤ inputHeight N := Nat.one_le_two_pow + have hM : (integerParameters N).M ≤ inputHeight N := + pow_le_pow_right₀ (by decide : 1 ≤ (2 : ℕ)) (Nat.div_le_self _ _) + have hP : inputHeight N ^ 20 ≤ (integerParameters N).P := + pow_le_pow_right₀ hHone (by omega : 20 ≤ coarseExponent (inputSmallLog N) + 20) + have hdepth := computed_tree_depth_bound N nx hN hnx ((by decide : 200 ≤ 64000000000000).trans hcut) + have hcount := computed_refinement_count_exact N hN hell + unfold computedRefinementError + apply refinement_error_from_stage_bounds hlarge + · exact (pow_le_pow_right₀ hellone (by decide : 2 ≤ 20000)).trans hpoly + · exact (pow_le_pow_right₀ hellone (by decide : 4 ≤ 5000)).trans hroot + · exact heightQuarterRoot_fourth_power N + · have hp : (0 : ℝ) ≤ coarseExponent (inputSmallLog N) := Nat.cast_nonneg _ + linarith only [hp] + · exact coarseExponent_shift_square _ ((by decide : 1764 ≤ 64000000000000).trans hcut) + · exact_mod_cast hM + · exact Nat.cast_nonneg _ + · exact_mod_cast hdepth + · exact_mod_cast hP + · exact (computed_warmup_count_root N).1 + · exact_mod_cast (computed_stage_positive_counts N hN hell).2 + · exact_mod_cast hcount + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/RefinementInitialSupport.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/RefinementInitialSupport.lean new file mode 100644 index 0000000000000000000000000000000000000000..12305d013245afdbeebc8750b7dd888f3e6aa2bf --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/RefinementInitialSupport.lean @@ -0,0 +1,231 @@ +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalWarmupStepQuery +import OAI.Combinatorics.EditApproximation.Geometry.LocalRefinementQuery +import OAI.Combinatorics.EditApproximation.Geometry.BandEarlierDependence +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Finite initial-table support for the literal refinement loops. The +query value determines the raw local lists; tests of other initial values +only remove elements from these lists. -/ + +namespace EditApproximation + + + +theorem refinementInitialSupport_query {n : ℕ} (N P F exponent : ℕ) (a value : ℚ) + (q : TargetInterval n) : q ∈ refinementInitialSupport N P F exponent a value q := + List.mem_cons_self + +theorem refinementInitialSupport_local {n : ℕ} (N P F exponent : ℕ) (a value : ℚ) + (q r : TargetInterval n) (hr : r ∈ rawRefinementCenters N P F a value q) : + r ∈ refinementInitialSupport N P F exponent a value q := by + exact List.mem_cons_of_mem _ (List.mem_append_left _ (List.mem_append_left _ hr)) + +theorem localGroupQueryKeys_congr_initial {n : ℕ} (N F exponent : ℕ) (a : ℚ) + (left right : TargetInterval n → ℚ) (q : TargetInterval n) (hq : left q = right q) : + localGroupQueryKeys N F exponent a left q = localGroupQueryKeys N F exponent a right q := by + simp only [localGroupQueryKeys, hq] + +theorem refinementInitialSupport_cell {n : ℕ} (N P F exponent : ℕ) (a : ℚ) + (initial : TargetInterval n → ℚ) (q : TargetInterval n) (key : ℕ × (ℕ × ℕ)) + (hk : key ∈ localGroupQueryKeys N F exponent a initial q) (r : TargetInterval n) + (hr : r ∈ cellTargetStates n (seedGridSpacing key.1 P) + ((2 : ℚ) ^ (-(exponent : ℤ)) * key.1) key.2) : + r ∈ refinementInitialSupport N P F exponent a (initial q) q := by + apply List.mem_cons_of_mem + apply List.mem_append_left + apply List.mem_append_right + apply List.mem_flatMap.mpr + refine ⟨key, ?_, hr⟩ + simpa only [localGroupQueryKeys] using hk + +theorem refinementInitialSupport_online {n : ℕ} (N P F exponent : ℕ) (a value : ℚ) + (q : TargetInterval n) (b : ℕ) (hb : b ∈ dyadicQueryWindow N value a F) : + roundInterval (seedGridSpacing b P) q ∈ refinementInitialSupport N P F exponent a value q := by + apply List.mem_cons_of_mem + apply List.mem_append_right + exact List.mem_map.mpr ⟨b, hb, rfl⟩ + +theorem cellRepresentativeStates_congr_initial {n : ℕ} (P F b : ℕ) (a theta : ℚ) + (left right : TargetInterval n → ℚ) (cell : ℕ × ℕ) + (heq : ∀ r ∈ cellTargetStates n (seedGridSpacing b P) (theta * b) cell, + left r = right r) : + cellRepresentativeStates n P F b a left theta cell = + cellRepresentativeStates n P F b a right theta cell := by + unfold cellRepresentativeStates + apply List.filter_congr + intro r hr + rw [heq r hr] + +section ParentTable + +variable {n : ℕ} (N P F exponent : ℕ) (a : ℚ) + (left right : TargetInterval n → ℚ) (q : TargetInterval n) + (heq : ∀ r ∈ refinementInitialSupport N P F exponent a (left q) q, left r = right r) + +include heq + +theorem refinement_local_representatives_congr : + localRefinementRepresentatives N P F a left q = localRefinementRepresentatives N P F a right q := by + apply localRefinementRepresentatives_congr_raw + · exact heq q (refinementInitialSupport_query N P F exponent a (left q) q) + · intro r hr + exact heq r (refinementInitialSupport_local N P F exponent a (left q) q r hr) + +theorem refinement_cell_representatives_congr (key : ℕ × (ℕ × ℕ)) + (hk : key ∈ localGroupQueryKeys N F exponent a left q) : + cellRepresentativeStates n P F key.1 a left ((2 : ℚ) ^ (-(exponent : ℤ))) key.2 = + cellRepresentativeStates n P F key.1 a right ((2 : ℚ) ^ (-(exponent : ℤ))) key.2 := by + apply cellRepresentativeStates_congr_initial + intro r hr + exact heq r (refinementInitialSupport_cell N P F exponent a left q key hk r hr) + +theorem queryEarlierRepresentatives_congr_initial : + queryEarlierRepresentatives N P F exponent a left q = + queryEarlierRepresentatives N P F exponent a right q := by + have hq := heq q (refinementInitialSupport_query N P F exponent a (left q) q) + have hkeys := localGroupQueryKeys_congr_initial N F exponent a left right q hq + unfold queryEarlierRepresentatives + rw [refinement_local_representatives_congr N P F exponent a left right q heq, ← hkeys, ← hq] + congr 2 + apply List.flatMap_congr + intro key hk + rw [refinement_cell_representatives_congr N P F exponent a left right q heq key hk] + +theorem queryEarlierInputCover_congr_initial {nx M : ℕ} (parent : TargetInterval nx) (history : ℕ) : + queryEarlierInputCover (M := M) parent N P F exponent history a left q = + queryEarlierInputCover parent N P F exponent history a right q := by + unfold queryEarlierInputCover + rw [queryEarlierRepresentatives_congr_initial N P F exponent a left right q heq] + +end ParentTable + +section Programs + +variable {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (N P F exponent H Q : ℕ) + (tau a eta kappa : ℚ) (t : ℕ) + (left right : TargetInterval target.length → ℚ) + (child initial current : Fin M → TargetInterval target.length → ℚ) + (children : PhysicalChildTables M target.length) + (integer : ℕ → TargetInterval target.length → ℕ) (draw : CellGroupDraws M F Q) + (q : TargetInterval target.length) + (heq : ∀ r ∈ refinementInitialSupport N P F exponent a (left q) q, left r = right r) + +include heq + +theorem localOnlineCandidates_congr_initial : + localOnlineCandidates source target parent N P F exponent H tau a eta kappa + left child initial children t integer q = + localOnlineCandidates source target parent N P F exponent H tau a eta kappa + right child initial children t integer q := by + have hq := heq q (refinementInitialSupport_query N P F exponent a (left q) q) + unfold localOnlineCandidates + rw [← hq] + apply List.filterMap_congr + intro b hb + dsimp only + rw [heq _ (refinementInitialSupport_online N P F exponent a (left q) q b hb)] + +theorem localCellGroupActions_congr_initial : + localCellGroupActions source target parent N P F exponent Q tau a left child initial current draw q = + localCellGroupActions source target parent N P F exponent Q tau a right child initial current draw q := by + have hq := heq q (refinementInitialSupport_query N P F exponent a (left q) q) + unfold localCellGroupActions + rw [← hq] + apply List.flatMap_congr + intro b hb + apply List.filterMap_congr + intro cell hc + unfold chooseCellGroupAction cellUnskippedBands + rw [refinement_cell_representatives_congr N P F exponent a left right q heq (b, cell) + (List.mem_flatMap.mpr ⟨b, hb, List.mem_map.mpr ⟨cell, hc, rfl⟩⟩)] + +theorem querySharedInputCover_congr_initial : + querySharedInputCover source target parent N F exponent Q a left q draw = + querySharedInputCover source target parent N F exponent Q a right q draw := by + unfold querySharedInputCover + rw [localGroupQueryKeys_congr_initial N F exponent a left right q + (heq q (refinementInitialSupport_query N P F exponent a (left q) q))] + +theorem rationalLocalWideStep_congr_initial (delta : ℚ) + (old : Fin M → TargetInterval target.length → ℚ) + (online : List (PhysicalRationalAction M target.length)) : + rationalLocalWideStep source target parent N P F exponent Q tau a delta left + child initial old current draw online q = + rationalLocalWideStep source target parent N P F exponent Q tau a delta right + child initial old current draw online q := by + have hgroups := localCellGroupActions_congr_initial source target parent N P F exponent Q tau a + left right child initial current draw q heq + have hreps := refinement_local_representatives_congr N P F exponent a left right q heq + have hq := heq q (refinementInitialSupport_query N P F exponent a (left q) q) + unfold rationalLocalWideStep + rw [hgroups, hreps] + unfold rationalBellman + rw [hq] + +end Programs + +section Query + +variable {ι α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (N P F exponent H Q : ℕ) + (tau a eta kappa delta : ℚ) (t : ℕ) + (readInitial : TargetInterval target.length → FiniteQuery ι) + (child initial : Fin M → TargetInterval target.length → ℚ) + (draw : CellGroupDraws M F Q) (integer : ℕ → TargetInterval target.length → ℕ) + (q : TargetInterval target.length) + (readEarlier : (Fin M × ℕ × TargetInterval target.length) → FiniteQuery ι) + (readCurrent : (Fin M × TargetInterval target.length) → FiniteQuery ι) + +/-- First gather the finite parent initial data that select all later +representative and cell lists. Child mass/initial data are gathered by a +separate layer, independently of the current-index reads. -/ +def localRefinementInitialQuery : FiniteQuery ι := + FiniteQuery.bind (readInitial q) fun value => + let keys := refinementInitialSupport N P F exponent a value q + FiniteQuery.collect readInitial keys fun answers => + localRefinementStepQuery source target parent N P F exponent H Q tau a eta kappa delta t + (finiteAnswerTable keys answers) child initial draw integer q readEarlier readCurrent + +theorem localRefinementInitialQuery_value (oracle : ι → ℚ) + (parentInitial : TargetInterval target.length → ℚ) + (earlier : PhysicalChildTables M target.length) + (current : Fin M → TargetInterval target.length → ℚ) (ht : 0 < t) + (hreadInitial : ∀ r, (readInitial r).value oracle = parentInitial r) + (hreadEarlier : ∀ input, (readEarlier input).value oracle = earlier input.1 input.2.1 input.2.2) + (hreadCurrent : ∀ input, (readCurrent input).value oracle = current input.1 input.2) : + (localRefinementInitialQuery source target parent N P F exponent H Q tau a eta kappa delta t + readInitial child initial draw integer q readEarlier readCurrent).value oracle = + rationalLocalWideStep source target parent N P F exponent Q tau a delta parentInitial child initial + (fun i r => earlier i (t - 1) r) current draw + (localOnlineCandidates source target parent N P F exponent H tau a eta kappa + parentInitial child initial earlier (t - 1) integer q) q := by + let keys := refinementInitialSupport N P F exponent a (parentInitial q) q + let cached := finiteAnswerTable keys (keys.map parentInitial) + have heq : ∀ r ∈ refinementInitialSupport N P F exponent a (parentInitial q) q, + parentInitial r = cached r := by + intro r hr + exact (finiteAnswerTable_map keys parentInitial r hr).symm + have honline := localOnlineCandidates_congr_initial source target parent N P F exponent H + tau a eta kappa (t - 1) parentInitial cached child initial earlier integer q heq + have hstep := rationalLocalWideStep_congr_initial source target parent N P F exponent Q tau a + parentInitial cached child initial current draw q heq delta (fun i r => earlier i (t - 1) r) + (localOnlineCandidates source target parent N P F exponent H tau a eta kappa + parentInitial child initial earlier (t - 1) integer q) + unfold localRefinementInitialQuery + rw [FiniteQuery.bind_value, hreadInitial q, FiniteQuery.collect_value] + simp only [hreadInitial] + rw [localRefinementStepQuery_value source target parent N P F exponent H Q tau a eta kappa delta t + cached child initial draw integer q readEarlier readCurrent oracle earlier current ht + hreadEarlier hreadCurrent] + rw [← honline] + exact hstep.symm + +end Query + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/RefinementRankCost.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/RefinementRankCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..fcd5a6a51531e66e49fcb1a3f32297eeb3137c56 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/RefinementRankCost.lean @@ -0,0 +1,64 @@ +import OAI.Combinatorics.EditApproximation.Geometry.GlobalQueryCost + +namespace OAI + +/-! For a fixed pass, the physical rank partition equals the concrete +warmup/refinement index partition on every emitted data-query key. -/ + +namespace EditApproximation + +section Costs + +variable {α : Type*} (source target : List α) {M J : ℕ} + (N P F exponent H Q : ℕ) (tau a eta kappa delta : ℚ) + (pass copy T S t : ℕ) (ht : 0 < t) (node : PhysicalNode M J) (hbelow : node.1.val < J) + (draw : CellGroupDraws M F Q) (integer : ℕ → TargetInterval target.length → ℕ) + (q : TargetInterval target.length) (answer : PhysicalTableRequest M J target.length → ℚ) + +theorem physicalRefinementDataRequest_same_rank_cost : + (physicalRefinementDataRequestQuery source target N P F exponent H Q tau a eta kappa delta + pass copy T S t ht node hbelow draw integer q).cost (fun child => answer child.val) + (fun child => if ¬ child.val.rank T S < + (PhysicalTableRequest.refinement pass copy node T t q).rank T S then 1 else 0) = + (physicalRefinementDataRequestQuery source target N P F exponent H Q tau a eta kappa delta + pass copy T S t ht node hbelow draw integer q).cost (fun child => answer child.val) + (fun child => physicalCurrentReadWeight (T + t) child.val) := by + apply FiniteQuery.cost_congr_weights + intro key hk + have hkey := physicalRefinementDataRequest_keys_pass_copy source target N P F exponent H Q + tau a eta kappa delta pass copy T S t ht node hbelow draw integer q _ key hk + have heq := PhysicalTableRequest.rank_not_lt_iff_index_eq_of_pass T S + (PhysicalTableRequest.refinement pass copy node T t q) key.val hkey.1 hkey.2.2 + by_cases hi : key.val.index = T + t + · have hr := heq.mpr hi + simp only [ite_eq_left hr, physicalCurrentReadWeight, ite_eq_left hi] + · have hr : ¬ ¬ key.val.rank T S < + (PhysicalTableRequest.refinement pass copy node T t q).rank T S := fun h => hi (heq.mp h) + simp only [ite_eq_right hr, physicalCurrentReadWeight, ite_eq_right hi] + +theorem physicalRefinementDataRequest_earlier_rank_cost : + (physicalRefinementDataRequestQuery source target N P F exponent H Q tau a eta kappa delta + pass copy T S t ht node hbelow draw integer q).cost (fun child => answer child.val) + (fun child => if child.val.rank T S < + (PhysicalTableRequest.refinement pass copy node T t q).rank T S then 1 else 0) = + (physicalRefinementDataRequestQuery source target N P F exponent H Q tau a eta kappa delta + pass copy T S t ht node hbelow draw integer q).cost (fun child => answer child.val) + (fun child => physicalEarlierReadWeight (T + t) child.val) := by + apply FiniteQuery.cost_congr_weights + intro key hk + have hkey := physicalRefinementDataRequest_keys_pass_copy source target N P F exponent H Q + tau a eta kappa delta pass copy T S t ht node hbelow draw integer q _ key hk + have heq := PhysicalTableRequest.rank_lt_iff_index_lt_of_pass T S + (PhysicalTableRequest.refinement pass copy node T t q) key.val hkey.1 + by_cases hi : key.val.index < T + t + · have hr := heq.mpr hi + simp only [ite_eq_left hr, physicalEarlierReadWeight, ite_eq_left hi] + · have hr : ¬ key.val.rank T S < + (PhysicalTableRequest.refinement pass copy node T t q).rank T S := fun h => hi (heq.mp h) + simp only [ite_eq_right hr, physicalEarlierReadWeight, ite_eq_right hi] + +end Costs + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/RefinementSupportBudget.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/RefinementSupportBudget.lean new file mode 100644 index 0000000000000000000000000000000000000000..8d1201039603af2d97e27c20bfd63009322540d0 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/RefinementSupportBudget.lean @@ -0,0 +1,112 @@ +import OAI.Combinatorics.EditApproximation.Geometry.RefinementBandSupport +import OAI.Combinatorics.EditApproximation.Geometry.InitialInputBudget + +namespace OAI + +/-! Cardinality of the actual raw initial-data and band-data lists. The +counts apply before any good-seed event and include rejected candidates. -/ + +namespace EditApproximation + +theorem list_eraseDups_length_le {α : Type*} [BEq α] (items : List α) : + items.eraseDups.length ≤ items.length := by + cases items with + | nil => exact le_rfl + | cons first rest => + rw [List.eraseDups_cons, List.length_cons, List.length_cons] + exact Nat.succ_le_succ ((list_eraseDups_length_le _).trans (List.length_filter_le _ _)) +termination_by items.length +decreasing_by + have h := List.length_filter_le (fun b => !b == first) rest + simp only [List.length_cons] + omega + +theorem rawRefinementCenters_length {n : ℕ} (N P F : ℕ) (a value : ℚ) + (q : TargetInterval n) (hP : 0 < P) (hF : 1 ≤ F) : + (rawRefinementCenters N P F a value q).length ≤ + (dyadicQueryWindow N value a F).length * (64 * F * P + 2) ^ 2 := by + apply (list_eraseDups_length_le _).trans + apply list_flatMap_length_le + intro b hb + have hwindow := of_decide_eq_true (List.mem_filter.mp hb).2 + have hceil : ⌈value⌉₊ ≤ 16 * F * b := by + apply Nat.ceil_le.mpr + have h := (div_le_iff₀ (by positivity : (0 : ℚ) < 16 * F)).mp hwindow.1 + push_cast + nlinarith only [h] + simpa only [show 4 * (16 * F) * P = 64 * F * P by ring] using + localTargetStates_length_from_scale P b ⌈value⌉₊ (16 * F) q hP hceil + +theorem cellTargetStates_length_dyadic {n P b : ℕ} (theta : ℚ) (cell : ℕ × ℕ) + (htheta : 0 ≤ theta ∧ theta ≤ 1) + (hb : ∃ e : ℕ, b = 2 ^ e) (hP : ∃ e : ℕ, P = 2 ^ e) : + (cellTargetStates n (seedGridSpacing b P) (theta * b) cell).length ≤ (P + 1) ^ 2 := by + have hg : (0 : ℚ) < seedGridSpacing b P := by + exact_mod_cast (show 0 < seedGridSpacing b P by unfold seedGridSpacing; omega) + have hcover : (b : ℚ) ≤ P * (seedGridSpacing b P : ℚ) := by + exact_mod_cast seedGridSpacing_covers_dyadic hb hP + have hsize : theta * b / seedGridSpacing b P ≤ (P : ℚ) := by + apply (div_le_iff₀ hg).2 + have hsmall : theta * b ≤ (b : ℚ) := by + simpa only [one_mul] using mul_le_mul_of_nonneg_right htheta.2 (Nat.cast_nonneg b) + exact hsmall.trans hcover + exact (cellTargetStates_length_le cell + (mul_nonneg htheta.1 (Nat.cast_nonneg b)) hsize).trans + (Nat.pow_le_pow_left (Nat.le_succ P) 2) + +theorem refinementInitialSupport_length {n : ℕ} (N P F exponent : ℕ) (a value : ℚ) + (q : TargetInterval n) (hP : ∃ e : ℕ, P = 2 ^ e) (hF : 1 ≤ F) (hw : 0 ≤ value) : + (refinementInitialSupport N P F exponent a value q).length ≤ + 1 + (dyadicQueryWindow N value a F).length * + ((64 * F * P + 2) ^ 2 + ((32 * F + 2) * 2 ^ exponent + 2) ^ 2 * (P + 1) ^ 2 + 1) := by + have hPpos : 0 < P := by obtain ⟨e, rfl⟩ := hP; positivity + have hlocal := rawRefinementCenters_length N P F a value q hPpos hF + have hcells := localGroupQueryKeys_length N F exponent a (fun _ => value) q hF hw + have hmembers : ((localGroupQueryKeys N F exponent a (fun _ => value) q).flatMap fun key => + cellTargetStates n (seedGridSpacing key.1 P) ((2 : ℚ) ^ (-(exponent : ℤ)) * key.1) key.2).length ≤ + (localGroupQueryKeys N F exponent a (fun _ => value) q).length * (P + 1) ^ 2 := by + apply list_flatMap_length_le + intro key hk + have hscale := localGroupQueryKeys_scale hk + obtain ⟨e, _, heq⟩ := List.mem_map.mp hscale + exact cellTargetStates_length_dyadic _ key.2 + ⟨by positivity, zpow_le_one_of_nonpos₀ (by norm_num : (1 : ℚ) ≤ 2) (by omega)⟩ + ⟨e, heq.symm⟩ hP + unfold refinementInitialSupport + simp only [List.length_cons, List.length_append, List.length_map] + nlinarith only [hlocal, hmembers, Nat.mul_le_mul_right ((P + 1) ^ 2) hcells] + +theorem wideWarmupInputs_length {nx ny M : ℕ} (parent : TargetInterval nx) (P : ℕ) + (representatives : List (ℕ × TargetInterval ny)) (hP : 0 < P) : + (wideWarmupInputs (M := M) parent P representatives).length ≤ + representatives.length * M * (40 * P + 2) ^ 2 := by + apply (list_eraseDups_length_le _).trans + have h : (representatives.flatMap fun br => (List.finRange M).flatMap fun i => + (wideChildStateList parent br.2 br.1 P i).map fun r => (i, r)).length ≤ + representatives.length * (M * (40 * P + 2) ^ 2) := by + apply list_flatMap_length_le + intro br hbr + have hi : ((List.finRange M).flatMap fun i => + (wideChildStateList parent br.2 br.1 P i).map fun r => (i, r)).length ≤ + (List.finRange M).length * (40 * P + 2) ^ 2 := by + apply list_flatMap_length_le + intro i hi + simpa only [List.length_map] using wideEarlierChildStateList_length_le parent br.2 br.1 P hP i + simpa only [List.length_finRange] using hi + exact h.trans_eq (by ring) + +theorem refinementBandInputList_length {nx ny M : ℕ} (parent : TargetInterval nx) + (N P F exponent : ℕ) (a : ℚ) (initial : TargetInterval ny → ℚ) (q : TargetInterval ny) + (hP : ∃ e : ℕ, P = 2 ^ e) (hF : 1 ≤ F) (hw : 0 ≤ initial q) : + (refinementBandInputList (M := M) parent N P F exponent a initial q).length ≤ + (dyadicQueryWindow N (initial q) a F).length * + ((64 * F * P + 2) ^ 2 + ((32 * F + 2) * 2 ^ exponent + 2) ^ 2 * (P + 1) ^ 2 + 1) * + M * (40 * P + 2) ^ 2 := by + have hPpos : 0 < P := by obtain ⟨e, rfl⟩ := hP; positivity + exact (wideWarmupInputs_length parent P _ hPpos).trans + (Nat.mul_le_mul_right _ (Nat.mul_le_mul_right M + (queryEarlierRepresentatives_length N P F exponent a initial q hP hF hw))) + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/Regret.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/Regret.lean new file mode 100644 index 0000000000000000000000000000000000000000..62a9f2cfbf01cb969bec6eadc8fb80f77bef1256 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/Regret.lean @@ -0,0 +1,980 @@ +import Mathlib + +namespace OAI + +/-! +# Clipped Bellman regret for edit-distance refinement + +The deterministic bound of Lemma `lem:generic-regret` in +Section 7 of *An Almost-Linear Approximation Scheme for Edit Distance* +(manuscript of September 24, 2026) applies to an arbitrary finite set of +children satisfying the Bellman inequality and exact-cost connection +inequality. +-/ + +namespace EditApproximation + +open Finset + +/-- Values are clipped at the exact cost only for the regret analysis. -/ +def clipped (cost value : ℝ) : ℝ := max cost value + +theorem clipped_bellman_bound {ι : Type*} (children : Finset ι) + (cost value charge : ℝ) (childCost childValue : ι → ℝ) + (hcost : cost ≤ charge + ∑ i ∈ children, childCost i) + (hvalue : value ≤ charge + ∑ i ∈ children, childValue i) : + clipped cost value ≤ charge + ∑ i ∈ children, clipped (childCost i) (childValue i) := by + apply max_le + · exact hcost.trans (add_le_add (le_refl charge) + (sum_le_sum fun i _ => le_max_left _ _)) + · exact hvalue.trans (add_le_add (le_refl charge) + (sum_le_sum fun i _ => le_max_right _ _)) + +/-- Clipping preserves the useful endpoint decrease bound even when the +initial estimate itself lies below the true cost. -/ +theorem clipped_endpoint_decrease (cost initial final mass gap : ℝ) + (hmono : final ≤ initial) (hinit : initial ≤ mass) + (hgapCost : |gap| ≤ cost) (hgapMass : |gap| ≤ mass) : + clipped cost initial - clipped cost final ≤ mass - |gap| := by + by_cases h : initial ≤ cost + · simp only [clipped, max_eq_left h, max_eq_left (hmono.trans h), sub_self] + exact sub_nonneg.mpr hgapMass + · have hmax : clipped cost initial = initial := max_eq_right (le_of_not_ge h) + have hfinal : |gap| ≤ clipped cost final := hgapCost.trans (le_max_left _ _) + rw [hmax] + exact sub_le_sub hinit hfinal + +/-- Finite-time telescoping of the clipped parent Bellman inequalities. +The summation uses indices `t + 1`, corresponding to manuscript indices +`1, …, S`. -/ +theorem generic_regret_telescope {ι : Type*} (children : Finset ι) + (S : ℕ) (cost charge : ℝ) (childCost : ι → ℝ) + (parent : ℕ → ℝ) (child : ℕ → ι → ℝ) + (hsplit : cost ≤ charge + ∑ i ∈ children, childCost i) + (hbellman : ∀ t < S, parent (t + 1) ≤ charge + ∑ i ∈ children, child t i) : + ∑ t ∈ range S, + (clipped cost (parent (t + 1)) - charge - + ∑ i ∈ children, clipped (childCost i) (child (t + 1) i)) ≤ + ∑ i ∈ children, + (clipped (childCost i) (child 0 i) - clipped (childCost i) (child S i)) := by + let total : ℕ → ℝ := fun t => ∑ i ∈ children, clipped (childCost i) (child t i) + have hstep (t : ℕ) (ht : t < S) : + clipped cost (parent (t + 1)) - charge - total (t + 1) ≤ + total t - total (t + 1) := by + have hb := clipped_bellman_bound children cost (parent (t + 1)) charge + childCost (child t) hsplit (hbellman t ht) + change clipped cost (parent (t + 1)) ≤ charge + total t at hb + linarith + have htel : ∑ t ∈ range S, (total t - total (t + 1)) = total 0 - total S := by + clear hbellman hstep + induction S with + | zero => simp + | succ S ih => + rw [sum_range_succ, ih] + ring + calc + _ ≤ ∑ t ∈ range S, (total t - total (t + 1)) := by + exact sum_le_sum fun t ht => hstep t (mem_range.mp ht) + _ = total 0 - total S := htel + _ = _ := by simp only [total, sum_sub_distrib] + +/-- The endpoint terms in generic regret are bounded by the warmup masses +minus the absolute length gaps. -/ +theorem generic_regret_mass_bound {ι : Type*} (children : Finset ι) + (S : ℕ) (cost charge : ℝ) (childCost mass gap : ι → ℝ) + (parent : ℕ → ℝ) (child : ℕ → ι → ℝ) + (hsplit : cost ≤ charge + ∑ i ∈ children, childCost i) + (hbellman : ∀ t < S, parent (t + 1) ≤ charge + ∑ i ∈ children, child t i) + (hmono : ∀ i ∈ children, child S i ≤ child 0 i) + (hinit : ∀ i ∈ children, child 0 i ≤ mass i) + (hgapCost : ∀ i ∈ children, |gap i| ≤ childCost i) + (hgapMass : ∀ i ∈ children, |gap i| ≤ mass i) : + ∑ t ∈ range S, + (clipped cost (parent (t + 1)) - charge - + ∑ i ∈ children, clipped (childCost i) (child (t + 1) i)) ≤ + ∑ i ∈ children, (mass i - |gap i|) := by + apply (generic_regret_telescope children S cost charge childCost parent child + hsplit hbellman).trans + exact sum_le_sum fun i hi => clipped_endpoint_decrease (childCost i) + (child 0 i) (child S i) (mass i) (gap i) + (hmono i hi) (hinit i hi) (hgapCost i hi) (hgapMass i hi) + +/-- Since child length gaps add to the parent's gap, their absolute values +give the final bound in manuscript Equation `eq:generic-regret`. -/ +theorem sum_mass_sub_abs_le {ι : Type*} (children : Finset ι) + (mass gap : ι → ℝ) : + ∑ i ∈ children, (mass i - |gap i|) ≤ + (∑ i ∈ children, mass i) - |∑ i ∈ children, gap i| := by + rw [sum_sub_distrib] + exact sub_le_sub_left (abs_sum_le_sum_abs _ _) _ + +/-- At a comparison node whose predicted normalized length gap is close +to one, almost all warmup mass is accounted for by the absolute gap. -/ +theorem predicted_length_gap_bound (W Z gap τ : ℝ) + (hZ : 0 < Z) (hZW : Z ≤ W) (hτ : 0 ≤ τ) + (hprediction : 1 - τ < |gap| / Z) : + W - |gap| ≤ (W - Z) + τ * W := by + have hp : (1 - τ) * Z < |gap| := (lt_div_iff₀ hZ).mp hprediction + have hmass : 0 ≤ τ * (W - Z) := mul_nonneg hτ (sub_nonneg.mpr hZW) + nlinarith + +/-- The refined generic bound at a node that is not bad and whose +normalized length-gap predictor lies near one. The parameter `q` is +`H^(-1/4)` in the manuscript. -/ +theorem near_length_gap_regret_bound (W Z gap τ q F cost : ℝ) + (hZ : 0 < Z) (hZW : Z ≤ W) (hτ : 0 ≤ τ) + (hprediction : 1 - τ < |gap| / Z) + (hdiscrepancy : W - Z ≤ q * cost) + (hmass : W ≤ 4 * F * cost) : + W - |gap| ≤ (q + 4 * τ * F) * cost := by + have hpred := predicted_length_gap_bound W Z gap τ hZ hZW hτ hprediction + have hscale := mul_le_mul_of_nonneg_left hmass hτ + nlinarith + +/-- Scalar exponential estimate used in Lemma `lem:entropy`, Equation +`eq:entropy-exponential`. -/ +theorem entropy_exponential_bound (κ x : ℝ) + (hκ : 0 ≤ κ) (hκhalf : κ ≤ 1 / 2) (hx : 0 ≤ x) (hxκ : x ≤ κ) : + Real.exp ((1 - 2 * κ) * x) ≤ 1 + (1 - κ) * x := by + have h1κ : 0 ≤ 1 - κ := by linarith + have h1κle : 1 - κ ≤ 1 := by linarith + have h2κ : 0 ≤ 1 - 2 * κ := by linarith + have h2κle : 1 - 2 * κ ≤ 1 := by linarith + have hy : 0 ≤ (1 - κ) * x := mul_nonneg h1κ hx + have hypos : 0 < 1 + (1 - κ) * x := by linarith + apply (Real.le_log_iff_exp_le hypos).mp + have hlog := Real.le_log_one_add_of_nonneg hy + apply le_trans _ hlog + apply (le_div_iff₀ (show 0 < (1 - κ) * x + 2 by linarith)).mpr + have hproduct : (1 - 2 * κ) * (1 - κ) ≤ 1 := + (mul_le_mul_of_nonneg_right h2κle h1κ).trans (by simpa using h1κle) + have hprodκ : (1 - 2 * κ) * (1 - κ) * x ≤ κ := + (mul_le_mul_of_nonneg_right hproduct hx).trans (by simpa using hxκ) + have hfinal : 0 ≤ x * (κ - (1 - 2 * κ) * (1 - κ) * x) := + mul_nonneg hx (sub_nonneg.mpr hprodκ) + have hkx : 0 ≤ κ * x := mul_nonneg hκ hx + nlinarith + +/-- The final telescoping step of Lemma `lem:entropy`. Here `played t` +is the inner product with the chosen distribution, `comparator t` is +the comparator inner product, and `decrement t` is its normalized +decrement. The potential-increment and variational bounds are explicit +internal proof obligations; this theorem does not assume a published +online-learning guarantee. -/ +theorem entropy_potential_telescoping (S : ℕ) (η κ bound : ℝ) + (potential played comparator decrement : ℕ → ℝ) + (hη : 0 < η) (hκ : 0 ≤ κ) + (hincrement : ∀ t < S, + potential (t + 1) - potential t ≤ η * played t) + (hstart : potential 0 ≤ bound) + (hcomparator : η * ((∑ t ∈ range S, comparator t) - + 2 * κ * ∑ t ∈ range S, decrement t) ≤ potential S) + (hdecrement : ∑ t ∈ range S, decrement t ≤ 1) : + (∑ t ∈ range S, comparator t) - bound / η - 2 * κ ≤ + ∑ t ∈ range S, played t := by + have htel : ∑ t ∈ range S, (potential (t + 1) - potential t) = + potential S - potential 0 := by + clear hincrement hcomparator hdecrement + induction S with + | zero => simp + | succ S ih => + rw [sum_range_succ, ih] + ring + have hsum : potential S - potential 0 ≤ η * ∑ t ∈ range S, played t := by + rw [← htel, mul_sum] + exact sum_le_sum fun t ht => hincrement t (mem_range.mp ht) + have hdecrement' : η * (2 * κ * ∑ t ∈ range S, decrement t) ≤ η * (2 * κ) := by + calc + _ ≤ η * (2 * κ * 1) := mul_le_mul_of_nonneg_left + (mul_le_mul_of_nonneg_left hdecrement (by positivity)) hη.le + _ = _ := by ring + have hcancel : η * (bound / η) = bound := mul_div_cancel₀ bound hη.ne' + apply le_of_mul_le_mul_left (a := η) _ hη + nlinarith + +/-- Accumulating the loss from approximate mixture vectors. In the +application, `error = H^(-3)` and the coordinate gains lie in `[-1, 0]`. -/ +theorem entropy_approximation_loss (S : ℕ) (bound error : ℝ) + (exactValue approximateValue : ℕ → ℝ) + (hexact : bound ≤ ∑ t ∈ range S, exactValue t) + (happrox : ∀ t < S, exactValue t - error ≤ approximateValue t) : + bound - S * error ≤ ∑ t ∈ range S, approximateValue t := by + have hsum : (∑ t ∈ range S, exactValue t) - S * error ≤ + ∑ t ∈ range S, approximateValue t := by + calc + _ = ∑ t ∈ range S, (exactValue t - error) := by simp [sum_sub_distrib] + _ ≤ _ := sum_le_sum fun t ht => happrox t (mem_range.mp ht) + linarith + +/-- Nonnegativity of relative entropy for a finite probability vector and +a strictly positive reference vector. Zero coordinates of the first +vector are allowed and contribute zero. -/ +theorem finite_relative_entropy_nonnegative {ι : Type*} (coordinates : Finset ι) + (p q : ι → ℝ) + (hp : ∀ i ∈ coordinates, 0 ≤ p i) + (hq : ∀ i ∈ coordinates, 0 < q i) + (hpsum : ∑ i ∈ coordinates, p i = 1) + (hqsum : ∑ i ∈ coordinates, q i = 1) : + 0 ≤ ∑ i ∈ coordinates, p i * Real.log (p i / q i) := by + have hcoord (i : ι) (hi : i ∈ coordinates) : + p i * Real.log (q i / p i) ≤ q i - p i := by + by_cases hzero : p i = 0 + · simpa [hzero] using (hq i hi).le + · have hp' : 0 < p i := lt_of_le_of_ne (hp i hi) (Ne.symm hzero) + have hl := mul_le_mul_of_nonneg_left + (Real.log_le_sub_one_of_pos (div_pos (hq i hi) hp')) hp'.le + have hcancel : p i * (q i / p i - 1) = q i - p i := by + field_simp + rwa [hcancel] at hl + have hsum : ∑ i ∈ coordinates, p i * Real.log (q i / p i) ≤ 0 := by + calc + _ ≤ ∑ i ∈ coordinates, (q i - p i) := sum_le_sum hcoord + _ = 0 := by rw [sum_sub_distrib, hqsum, hpsum]; ring + have hneg (i : ι) (hi : i ∈ coordinates) : + p i * Real.log (p i / q i) = -(p i * Real.log (q i / p i)) := by + by_cases hzero : p i = 0 + · simp [hzero] + · rw [Real.log_div hzero (hq i hi).ne', Real.log_div (hq i hi).ne' hzero] + ring + calc + 0 ≤ -(∑ i ∈ coordinates, p i * Real.log (q i / p i)) := neg_nonneg.mpr hsum + _ = ∑ i ∈ coordinates, p i * Real.log (p i / q i) := by + rw [← sum_neg_distrib] + exact sum_congr rfl fun i hi => (hneg i hi).symm + +/-- The finite Gibbs variational bound used when the innovation +supremum over the actual action hull is extended to the simplex. +This is a proved inequality, with no maximization-oracle assumption. -/ +theorem finite_gibbs_variational_bound {ι : Type*} (coordinates : Finset ι) + (p q gain : ι → ℝ) + (hp : ∀ i ∈ coordinates, 0 ≤ p i) + (hq : ∀ i ∈ coordinates, 0 < q i) + (hpsum : ∑ i ∈ coordinates, p i = 1) + (hqsum : ∑ i ∈ coordinates, q i = 1) : + (∑ i ∈ coordinates, p i * gain i) - + (∑ i ∈ coordinates, p i * Real.log (p i / q i)) ≤ + Real.log (∑ i ∈ coordinates, q i * Real.exp (gain i)) := by + let Z := ∑ i ∈ coordinates, q i * Real.exp (gain i) + have hs : coordinates.Nonempty := by + apply Finset.nonempty_of_ne_empty + intro he + simp [he] at hqsum + have hZ : 0 < Z := sum_pos (fun i hi => mul_pos (hq i hi) (Real.exp_pos _)) hs + let r : ι → ℝ := fun i => q i * Real.exp (gain i) / Z + have hr (i : ι) (hi : i ∈ coordinates) : 0 < r i := + div_pos (mul_pos (hq i hi) (Real.exp_pos _)) hZ + have hrsum : ∑ i ∈ coordinates, r i = 1 := by + simp only [r] + rw [← sum_div] + change Z / Z = 1 + exact div_self hZ.ne' + have hKL := finite_relative_entropy_nonnegative coordinates p r hp hr hpsum hrsum + have hcoord (i : ι) (hi : i ∈ coordinates) : + p i * gain i - p i * Real.log (p i / q i) = + p i * Real.log Z - p i * Real.log (p i / r i) := by + by_cases hzero : p i = 0 + · simp [hzero] + · have hlogr : Real.log (r i) = Real.log (q i) + gain i - Real.log Z := by + change Real.log (q i * Real.exp (gain i) / Z) = _ + rw [Real.log_div (mul_pos (hq i hi) (Real.exp_pos _)).ne' hZ.ne', + Real.log_mul (hq i hi).ne' (Real.exp_pos _).ne', Real.log_exp] + rw [Real.log_div hzero (hq i hi).ne', Real.log_div hzero (hr i hi).ne', hlogr] + ring + have hidentity : + (∑ i ∈ coordinates, p i * gain i) - + (∑ i ∈ coordinates, p i * Real.log (p i / q i)) = + Real.log Z - ∑ i ∈ coordinates, p i * Real.log (p i / r i) := by + rw [← sum_sub_distrib] + calc + _ = ∑ i ∈ coordinates, + (p i * Real.log Z - p i * Real.log (p i / r i)) := sum_congr rfl hcoord + _ = _ := by rw [sum_sub_distrib, ← sum_mul, hpsum, one_mul] + change _ ≤ Real.log Z + rw [hidentity] + exact sub_le_self _ hKL + +/-- The small-decrement logarithmic moment bound in the entropy +innovation argument. The bound on `η * innovation i` is the only +smallness requirement needed here. -/ +theorem entropy_small_increment_logsum {ι : Type*} (coordinates : Finset ι) + (p innovation : ι → ℝ) (η κ : ℝ) + (hp : ∀ i ∈ coordinates, 0 < p i) + (hpsum : ∑ i ∈ coordinates, p i = 1) + (hκ : 0 ≤ κ) (hκhalf : κ ≤ 1 / 2) + (hinnovation : ∀ i ∈ coordinates, 0 ≤ η * innovation i) + (hsmall : ∀ i ∈ coordinates, η * innovation i ≤ κ) : + Real.log (∑ i ∈ coordinates, + p i * Real.exp (η * (1 - 2 * κ) * innovation i)) ≤ + η * (1 - κ) * ∑ i ∈ coordinates, p i * innovation i := by + let Z := ∑ i ∈ coordinates, p i * Real.exp (η * (1 - 2 * κ) * innovation i) + have hs : coordinates.Nonempty := by + apply Finset.nonempty_of_ne_empty + intro he + simp [he] at hpsum + have hZ : 0 < Z := sum_pos (fun i hi => mul_pos (hp i hi) (Real.exp_pos _)) hs + have hbound : Z ≤ 1 + η * (1 - κ) * ∑ i ∈ coordinates, p i * innovation i := by + calc + _ ≤ ∑ i ∈ coordinates, p i * (1 + (1 - κ) * (η * innovation i)) := by + apply sum_le_sum + intro i hi + apply mul_le_mul_of_nonneg_left _ (hp i hi).le + rw [show η * (1 - 2 * κ) * innovation i = + (1 - 2 * κ) * (η * innovation i) by ring] + exact entropy_exponential_bound κ (η * innovation i) hκ hκhalf + (hinnovation i hi) (hsmall i hi) + _ = _ := by + simp_rw [mul_add, mul_one] + rw [sum_add_distrib, hpsum] + congr 1 + rw [mul_sum] + apply sum_congr rfl + intro i hi + ring + exact (Real.log_le_sub_one_of_pos hZ).trans (by linarith) + +/-- Equal probability mass in every child block makes every blockwise +constant vector have the same inner product with the two distributions. -/ +theorem fixed_block_mass_inner_product {ι β : Type*} [Fintype β] [DecidableEq β] + (coordinates : Finset ι) (block : ι → β) (p q : ι → ℝ) (baseline : β → ℝ) + (hblock : ∀ b, (∑ i ∈ coordinates with block i = b, p i) = + ∑ i ∈ coordinates with block i = b, q i) : + (∑ i ∈ coordinates, p i * baseline (block i)) = + ∑ i ∈ coordinates, q i * baseline (block i) := by + classical + have hdecompose (r : ι → ℝ) : + (∑ b : β, baseline b * ∑ i ∈ coordinates with block i = b, r i) = + ∑ i ∈ coordinates, r i * baseline (block i) := by + simp only [mul_sum, sum_filter, mul_ite, mul_zero] + rw [sum_comm] + simp [mul_comm] + rw [← hdecompose p, ← hdecompose q] + exact sum_congr rfl fun b _ => congrArg (baseline b * ·) (hblock b) + +/-- The innovation variational inequality for the actual action hull. +Its fixed block masses are used exactly through `hfixedMass`: the +blockwise minimum vector `baseline` has the same inner product with +every feasible vector. The residual `innovation` has small range. + +Combined with the entropy penalty at a positive maximizer, this bounds +the potential increment without replacing the action hull by a simplex +in the algorithm. -/ +theorem entropy_innovation_variational_bound {ι : Type*} (coordinates : Finset ι) + (p q decrement baseline innovation : ι → ℝ) (η κ : ℝ) + (hp : ∀ i ∈ coordinates, 0 < p i) + (hq : ∀ i ∈ coordinates, 0 ≤ q i) + (hpsum : ∑ i ∈ coordinates, p i = 1) + (hqsum : ∑ i ∈ coordinates, q i = 1) + (hη : 0 ≤ η) (hκ : 0 ≤ κ) (hκhalf : κ ≤ 1 / 2) + (hbaseline : ∀ i ∈ coordinates, 0 ≤ baseline i) + (hdecomposition : ∀ i ∈ coordinates, decrement i = baseline i + innovation i) + (hfixedMass : (∑ i ∈ coordinates, q i * baseline i) = + ∑ i ∈ coordinates, p i * baseline i) + (hinnovation : ∀ i ∈ coordinates, 0 ≤ η * innovation i) + (hsmall : ∀ i ∈ coordinates, η * innovation i ≤ κ) : + η * (1 - 2 * κ) * (∑ i ∈ coordinates, q i * decrement i) - + (∑ i ∈ coordinates, q i * Real.log (q i / p i)) ≤ + η * (1 - κ) * ∑ i ∈ coordinates, p i * decrement i := by + have hgibbs := finite_gibbs_variational_bound coordinates q p + (fun i => η * (1 - 2 * κ) * innovation i) hq hp hqsum hpsum + have hlog := entropy_small_increment_logsum coordinates p innovation η κ + hp hpsum hκ hκhalf hinnovation hsmall + have hgain : (∑ i ∈ coordinates, q i * (η * (1 - 2 * κ) * innovation i)) = + η * (1 - 2 * κ) * ∑ i ∈ coordinates, q i * innovation i := by + rw [mul_sum] + apply sum_congr rfl + intro i hi + ring + rw [hgain] at hgibbs + have hresidual := hgibbs.trans hlog + have hpsumDecrement : (∑ i ∈ coordinates, p i * decrement i) = + (∑ i ∈ coordinates, p i * baseline i) + + ∑ i ∈ coordinates, p i * innovation i := by + rw [← sum_add_distrib] + apply sum_congr rfl + intro i hi + rw [hdecomposition i hi, mul_add] + have hqsumDecrement : (∑ i ∈ coordinates, q i * decrement i) = + (∑ i ∈ coordinates, p i * baseline i) + + ∑ i ∈ coordinates, q i * innovation i := by + rw [← hfixedMass, ← sum_add_distrib] + apply sum_congr rfl + intro i hi + rw [hdecomposition i hi, mul_add] + have hmass : 0 ≤ ∑ i ∈ coordinates, p i * baseline i := + sum_nonneg fun i hi => mul_nonneg (hp i hi).le (hbaseline i hi) + have hcorrection : 0 ≤ η * κ * ∑ i ∈ coordinates, p i * baseline i := + mul_nonneg (mul_nonneg hη hκ) hmass + rw [hpsumDecrement, hqsumDecrement] + nlinarith + +/-- First-order optimality of entropy plus a linear objective along a +feasible segment. The segment-maximization hypothesis is exactly what +an entropy maximizer on a convex action hull supplies. -/ +theorem entropy_first_order_on_segment {ι : Type*} (coordinates : Finset ι) + (p q objective : ι → ℝ) (η : ℝ) + (hp : ∀ i ∈ coordinates, 0 < p i) + (hmax : ∀ t : ℝ, 0 ≤ t → t ≤ 1 → + (∑ i ∈ coordinates, + (Real.negMulLog (p i + t * (q i - p i)) + + η * objective i * (p i + t * (q i - p i)))) ≤ + ∑ i ∈ coordinates, (Real.negMulLog (p i) + η * objective i * p i)) : + ∑ i ∈ coordinates, + (-Real.log (p i) - 1 + η * objective i) * (q i - p i) ≤ 0 := by + let f : ℝ → ℝ := fun t => ∑ i ∈ coordinates, + (Real.negMulLog (p i + t * (q i - p i)) + + η * objective i * (p i + t * (q i - p i))) + have hd : HasDerivAt f (∑ i ∈ coordinates, + (-Real.log (p i) - 1 + η * objective i) * (q i - p i)) 0 := by + apply HasDerivAt.fun_sum + intro i hi + have hline : HasDerivAt (fun t : ℝ => p i + t * (q i - p i)) (q i - p i) 0 := by + simpa using (hasDerivAt_const (0 : ℝ) (p i)).fun_add + ((hasDerivAt_id (0 : ℝ)).mul_const (q i - p i)) + have hneg : HasDerivAt Real.negMulLog (-Real.log (p i) - 1) + (p i + 0 * (q i - p i)) := by + simpa using Real.hasDerivAt_negMulLog (hp i hi).ne' + have hent := hneg.comp 0 hline + have hent' : HasDerivAt (fun t : ℝ => Real.negMulLog (p i + t * (q i - p i))) + ((-Real.log (p i) - 1) * (q i - p i)) 0 := by + convert! hent using 1 + convert hent'.add (hline.const_mul (η * objective i)) using 1 + ring + have hmaxOn : IsMaxOn f (Set.Icc (0 : ℝ) 1) 0 := by + intro t ht + simpa [f] using hmax t ht.1 ht.2 + have htangent : (1 : ℝ) ∈ posTangentConeAt (Set.Icc (0 : ℝ) 1) 0 := by + have hsegment : segment ℝ (0 : ℝ) 1 ⊆ Set.Icc (0 : ℝ) 1 := by + rw [segment_eq_Icc (by norm_num)] + simpa using sub_mem_posTangentConeAt_of_segment_subset hsegment + have hnonpos := hmaxOn.isLocalMaxOn.hasFDerivWithinAt_nonpos + hd.hasFDerivAt.hasFDerivWithinAt htangent + simpa using hnonpos + +/-- The exact relative-entropy penalty at a positive first-order +maximizer. This proves manuscript Equation `eq:entropy-penalty` once +the first-order condition is supplied by +`entropy_first_order_on_segment`. -/ +theorem entropy_penalty_of_first_order {ι : Type*} (coordinates : Finset ι) + (p q objective : ι → ℝ) (η : ℝ) + (hp : ∀ i ∈ coordinates, 0 < p i) + (hpsum : ∑ i ∈ coordinates, p i = 1) + (hqsum : ∑ i ∈ coordinates, q i = 1) + (hfirst : ∑ i ∈ coordinates, + (-Real.log (p i) - 1 + η * objective i) * (q i - p i) ≤ 0) : + (∑ i ∈ coordinates, Real.negMulLog (q i)) + + η * (∑ i ∈ coordinates, objective i * q i) ≤ + (∑ i ∈ coordinates, Real.negMulLog (p i)) + + η * (∑ i ∈ coordinates, objective i * p i) - + (∑ i ∈ coordinates, q i * Real.log (q i / p i)) := by + have hcoord (i : ι) (hi : i ∈ coordinates) : + Real.negMulLog (q i) - Real.negMulLog (p i) + + η * objective i * (q i - p i) + q i * Real.log (q i / p i) = + (-Real.log (p i) - 1 + η * objective i) * (q i - p i) + (q i - p i) := by + by_cases hqzero : q i = 0 + · simp only [hqzero, Real.negMulLog, zero_mul, zero_div] + ring + · rw [Real.log_div hqzero (hp i hi).ne'] + simp only [Real.negMulLog] + ring + have hidentity : + (∑ i ∈ coordinates, + (Real.negMulLog (q i) - Real.negMulLog (p i) + + η * objective i * (q i - p i) + q i * Real.log (q i / p i))) = + ∑ i ∈ coordinates, + (-Real.log (p i) - 1 + η * objective i) * (q i - p i) := by + calc + _ = ∑ i ∈ coordinates, + ((-Real.log (p i) - 1 + η * objective i) * (q i - p i) + (q i - p i)) := + sum_congr rfl hcoord + _ = _ := by rw [sum_add_distrib, sum_sub_distrib, hqsum, hpsum]; ring + have hbound := hidentity.trans_le hfirst + simp only [sum_add_distrib, sum_sub_distrib, mul_sub] at hbound + have hlinear : (∑ i ∈ coordinates, η * objective i * q i) = + η * ∑ i ∈ coordinates, objective i * q i := by + rw [mul_sum] + apply sum_congr rfl + intro i hi + ring + have hlinear' : (∑ i ∈ coordinates, η * objective i * p i) = + η * ∑ i ∈ coordinates, objective i * p i := by + rw [mul_sum] + apply sum_congr rfl + intro i hi + ring + rw [hlinear, hlinear'] at hbound + linarith + +/-- An entropy maximizer cannot have a zero coordinate when a strictly +positive feasible vector is available. Only maximization on the +segments to that vector is needed, so this applies to the actual finite +action hull in the manuscript. -/ +theorem entropy_maximizer_positive {ι : Type*} (coordinates : Finset ι) + (p witness objective : ι → ℝ) (η : ℝ) + (hp : ∀ i ∈ coordinates, 0 ≤ p i) + (hw : ∀ i ∈ coordinates, 0 < witness i) + (hmax : ∀ t : ℝ, 0 ≤ t → t ≤ 1 → + (∑ i ∈ coordinates, + (Real.negMulLog ((1 - t) * p i + t * witness i) + + η * objective i * ((1 - t) * p i + t * witness i))) ≤ + ∑ i ∈ coordinates, (Real.negMulLog (p i) + η * objective i * p i)) : + ∀ i ∈ coordinates, 0 < p i := by + classical + intro k hk + by_contra hnot + have hpk : p k = 0 := le_antisymm (le_of_not_gt hnot) (hp k hk) + let value : ι → ℝ → ℝ := fun i x => Real.negMulLog x + η * objective i * x + let A := (∑ i ∈ coordinates, value i (witness i)) - + ∑ i ∈ coordinates, value i (p i) + let t := Real.exp (-(|A| / witness k + 1)) + have ht : 0 < t := Real.exp_pos _ + have ht1 : t ≤ 1 := by + apply Real.exp_le_one_iff.mpr + have hratio : 0 ≤ |A| / witness k := div_nonneg (abs_nonneg _) (hw k hk).le + linarith + have htlog : Real.log t = -(|A| / witness k + 1) := Real.log_exp _ + have hpositive : 0 < t * A + witness k * Real.negMulLog t := by + have hbracket : 0 < A + |A| + witness k := by + have := neg_le_abs A + linarith [hw k hk] + calc + _ = t * (A + |A| + witness k) := by + rw [Real.negMulLog, htlog] + field_simp [(hw k hk).ne'] + ring + _ > 0 := mul_pos ht hbracket + have hcoord (i : ι) (hi : i ∈ coordinates) : + (1 - t) * value i (p i) + t * value i (witness i) ≤ + value i ((1 - t) * p i + t * witness i) := by + have hconcave := Real.concaveOn_negMulLog.2 (hp i hi) (hw i hi).le + (show 0 ≤ 1 - t by linarith) ht.le (show (1 - t) + t = 1 by ring) + simp only [smul_eq_mul] at hconcave + dsimp only [value] + nlinarith + have hkexact : + (1 - t) * value k (p k) + t * value k (witness k) + + witness k * Real.negMulLog t = + value k ((1 - t) * p k + t * witness k) := by + simp only [hpk, value, mul_zero, Real.negMulLog_zero, zero_add, add_zero] + rw [Real.negMulLog_mul] + ring + let lower : ι → ℝ := fun i => (1 - t) * value i (p i) + t * value i (witness i) + let upper : ι → ℝ := fun i => value i ((1 - t) * p i + t * witness i) + have hothers : ∑ i ∈ coordinates.erase k, lower i ≤ + ∑ i ∈ coordinates.erase k, upper i := + sum_le_sum fun i hi => hcoord i (mem_of_mem_erase hi) + have hwhole : (∑ i ∈ coordinates.erase k, lower i) + lower k + + witness k * Real.negMulLog t ≤ (∑ i ∈ coordinates.erase k, upper i) + upper k := by + change lower k + witness k * Real.negMulLog t = upper k at hkexact + linarith + rw [sum_erase_add coordinates lower hk, sum_erase_add coordinates upper hk] at hwhole + have hlower : (∑ i ∈ coordinates, lower i) = + (1 - t) * (∑ i ∈ coordinates, value i (p i)) + + t * ∑ i ∈ coordinates, value i (witness i) := by + simp only [lower, sum_add_distrib, ← mul_sum] + rw [hlower] at hwhole + have hupper : ∑ i ∈ coordinates, upper i ≤ ∑ i ∈ coordinates, value i (p i) := + hmax t ht.le ht1 + have hfinal := hwhole.trans hupper + dsimp only [A] at hpositive + nlinarith + +/-- Entropy is nonnegative on a finite probability vector. -/ +theorem finite_entropy_nonnegative {ι : Type*} (coordinates : Finset ι) + (p : ι → ℝ) (hp : ∀ i ∈ coordinates, 0 ≤ p i) + (hpsum : ∑ i ∈ coordinates, p i = 1) : + 0 ≤ ∑ i ∈ coordinates, Real.negMulLog (p i) := by + apply sum_nonneg + intro i hi + apply Real.negMulLog_nonneg (hp i hi) + exact (single_le_sum hp hi).trans hpsum.le + +/-- The entropy of a finite probability vector is at most the logarithm +of the number of listed coordinates. -/ +theorem finite_entropy_le_log_card {ι : Type*} (coordinates : Finset ι) + (p : ι → ℝ) (hp : ∀ i ∈ coordinates, 0 ≤ p i) + (hpsum : ∑ i ∈ coordinates, p i = 1) : + (∑ i ∈ coordinates, Real.negMulLog (p i)) ≤ Real.log coordinates.card := by + have hs : coordinates.Nonempty := by + apply Finset.nonempty_of_ne_empty + intro he + simp [he] at hpsum + have hn : 0 < (coordinates.card : ℝ) := Nat.cast_pos.mpr hs.card_pos + let uniform : ι → ℝ := fun _ => 1 / coordinates.card + have hu : ∀ i ∈ coordinates, 0 < uniform i := fun _ _ => div_pos zero_lt_one hn + have husum : ∑ i ∈ coordinates, uniform i = 1 := by + simp only [uniform, sum_const, nsmul_eq_mul] + field_simp + have hKL := finite_relative_entropy_nonnegative coordinates p uniform hp hu hpsum husum + have hcoord (i : ι) (hi : i ∈ coordinates) : + p i * Real.log (p i / uniform i) = + -Real.negMulLog (p i) + p i * Real.log coordinates.card := by + by_cases hzero : p i = 0 + · simp [hzero] + · rw [Real.log_div hzero (hu i hi).ne'] + simp only [uniform, one_div, Real.log_inv, Real.negMulLog] + ring + have hid : (∑ i ∈ coordinates, p i * Real.log (p i / uniform i)) = + -(∑ i ∈ coordinates, Real.negMulLog (p i)) + Real.log coordinates.card := by + calc + _ = ∑ i ∈ coordinates, (-Real.negMulLog (p i) + p i * Real.log coordinates.card) := + sum_congr rfl hcoord + _ = _ := by rw [sum_add_distrib, sum_neg_distrib, ← sum_mul, hpsum, one_mul] + rw [hid] at hKL + linarith + +/-- Entropy plus the linear objective, with the manuscript's scaling. -/ +noncomputable def entropyValue {ι : Type*} (coordinates : Finset ι) + (η : ℝ) (objective p : ι → ℝ) : ℝ := + ∑ i ∈ coordinates, (Real.negMulLog (p i) + η * objective i * p i) + +theorem entropyValue_eq {ι : Type*} (coordinates : Finset ι) + (η : ℝ) (objective p : ι → ℝ) : + entropyValue coordinates η objective p = + (∑ i ∈ coordinates, Real.negMulLog (p i)) + + η * ∑ i ∈ coordinates, objective i * p i := by + unfold entropyValue + rw [sum_add_distrib, mul_sum] + congr 1 + apply sum_congr rfl + intro i hi + ring + +/-- The entropy potential is attained on every nonempty compact action +hull, since the zero-coordinate convention gives continuous entropy. -/ +theorem exists_entropy_maximizer {ι : Type*} (coordinates : Finset ι) + (Q : Set (ι → ℝ)) (η : ℝ) (objective : ι → ℝ) + (hcompact : IsCompact Q) (hne : Q.Nonempty) : + ∃ p ∈ Q, IsMaxOn (entropyValue coordinates η objective) Q p := by + apply hcompact.exists_isMaxOn hne + unfold entropyValue + fun_prop + +/-- Positivity of the entropy maximizer on a convex feasible hull with +a positive feasible witness. -/ +theorem entropy_hull_maximizer_positive {ι : Type*} (coordinates : Finset ι) + (Q : Set (ι → ℝ)) (η : ℝ) (objective p witness : ι → ℝ) + (hconvex : Convex ℝ Q) (hpQ : p ∈ Q) (hwQ : witness ∈ Q) + (hp : ∀ i ∈ coordinates, 0 ≤ p i) + (hw : ∀ i ∈ coordinates, 0 < witness i) + (hmax : IsMaxOn (entropyValue coordinates η objective) Q p) : + ∀ i ∈ coordinates, 0 < p i := by + apply entropy_maximizer_positive coordinates p witness objective η hp hw + intro t ht ht1 + have hmem := hconvex hpQ hwQ (show 0 ≤ 1 - t by linarith) ht + (show (1 - t) + t = 1 by ring) + simpa [entropyValue, Pi.smul_apply, Pi.add_apply, smul_eq_mul] using hmax hmem + +/-- The exact KL penalty holds for every competitor in the action hull, +including competitors with zero coordinates. -/ +theorem entropy_hull_penalty {ι : Type*} (coordinates : Finset ι) + (Q : Set (ι → ℝ)) (η : ℝ) (objective p q : ι → ℝ) + (hconvex : Convex ℝ Q) (hpQ : p ∈ Q) (hqQ : q ∈ Q) + (hp : ∀ i ∈ coordinates, 0 < p i) + (hpsum : ∑ i ∈ coordinates, p i = 1) + (hqsum : ∑ i ∈ coordinates, q i = 1) + (hmax : IsMaxOn (entropyValue coordinates η objective) Q p) : + entropyValue coordinates η objective q ≤ entropyValue coordinates η objective p - + ∑ i ∈ coordinates, q i * Real.log (q i / p i) := by + have hfirst := entropy_first_order_on_segment coordinates p q objective η hp + (by + intro t ht ht1 + have hmem := hconvex hpQ hqQ (show 0 ≤ 1 - t by linarith) ht + (show (1 - t) + t = 1 by ring) + have heq : (1 - t) • p + t • q = fun i => p i + t * (q i - p i) := by + ext i + simp only [Pi.add_apply, Pi.smul_apply, smul_eq_mul] + ring + rw [heq] at hmem + exact hmax hmem) + rw [entropyValue_eq, entropyValue_eq] + exact entropy_penalty_of_first_order coordinates p q objective η hp hpsum hqsum hfirst + +theorem entropyValue_add_scaled {ι : Type*} (coordinates : Finset ι) + (η scale : ℝ) (objective increment p : ι → ℝ) : + entropyValue coordinates η (fun i => objective i + scale * increment i) p = + entropyValue coordinates η objective p + + η * scale * ∑ i ∈ coordinates, increment i * p i := by + rw [entropyValue_eq, entropyValue_eq] + simp_rw [add_mul] + rw [sum_add_distrib] + have hsum : (∑ i ∈ coordinates, scale * increment i * p i) = + scale * ∑ i ∈ coordinates, increment i * p i := by + rw [mul_sum] + apply sum_congr rfl + intro i hi + ring + rw [hsum] + ring + +/-- One complete optimistic entropy-potential step on the actual hull. +The old objective and its predicted increment are arbitrary and may +have negative coordinates. Only the residual decrement is small. -/ +theorem entropy_hull_potential_step {ι : Type*} (coordinates : Finset ι) + (Q : Set (ι → ℝ)) (η κ : ℝ) + (old gain decrement baseline innovation oldLeader predicted newLeader : ι → ℝ) + (hconvex : Convex ℝ Q) + (hpredQ : predicted ∈ Q) (hnewQ : newLeader ∈ Q) + (hpred : ∀ i ∈ coordinates, 0 < predicted i) + (hnew : ∀ i ∈ coordinates, 0 ≤ newLeader i) + (hpredsum : ∑ i ∈ coordinates, predicted i = 1) + (hnewsum : ∑ i ∈ coordinates, newLeader i = 1) + (holdMax : IsMaxOn (entropyValue coordinates η old) Q oldLeader) + (hpredMax : IsMaxOn + (entropyValue coordinates η (fun i => old i + gain i)) Q predicted) + (hη : 0 ≤ η) (hκ : 0 ≤ κ) (hκhalf : κ ≤ 1 / 2) + (hbaseline : ∀ i ∈ coordinates, 0 ≤ baseline i) + (hdecomposition : ∀ i ∈ coordinates, decrement i = baseline i + innovation i) + (hfixedMass : (∑ i ∈ coordinates, newLeader i * baseline i) = + ∑ i ∈ coordinates, predicted i * baseline i) + (hinnovation : ∀ i ∈ coordinates, 0 ≤ η * innovation i) + (hsmall : ∀ i ∈ coordinates, η * innovation i ≤ κ) : + entropyValue coordinates η + (fun i => old i + gain i + (1 - 2 * κ) * decrement i) newLeader - + entropyValue coordinates η old oldLeader ≤ + η * ∑ i ∈ coordinates, (gain i + (1 - κ) * decrement i) * predicted i := by + have hpenalty := entropy_hull_penalty coordinates Q η (fun i => old i + gain i) + predicted newLeader hconvex hpredQ hnewQ hpred hpredsum hnewsum hpredMax + have hinnovationBound := entropy_innovation_variational_bound coordinates predicted + newLeader decrement baseline innovation η κ hpred hnew hpredsum hnewsum + hη hκ hκhalf hbaseline hdecomposition hfixedMass hinnovation hsmall + have hpredComm : (∑ i ∈ coordinates, predicted i * decrement i) = + ∑ i ∈ coordinates, decrement i * predicted i := + sum_congr rfl fun i _ => mul_comm _ _ + have hnewComm : (∑ i ∈ coordinates, newLeader i * decrement i) = + ∑ i ∈ coordinates, decrement i * newLeader i := + sum_congr rfl fun i _ => mul_comm _ _ + rw [hpredComm, hnewComm] at hinnovationBound + have hnewValue := entropyValue_add_scaled coordinates η (1 - 2 * κ) + (fun i => old i + gain i) decrement newLeader + have hpredValue := entropyValue_add_scaled coordinates η 1 old gain predicted + simp only [one_mul, mul_one] at hpredValue + have holdBound := holdMax hpredQ + change entropyValue coordinates η old predicted ≤ + entropyValue coordinates η old oldLeader at holdBound + have hsum : (∑ i ∈ coordinates, (gain i + (1 - κ) * decrement i) * predicted i) = + (∑ i ∈ coordinates, gain i * predicted i) + + (1 - κ) * ∑ i ∈ coordinates, decrement i * predicted i := by + simp_rw [add_mul] + rw [sum_add_distrib] + congr 1 + rw [mul_sum] + apply sum_congr rfl + intro i hi + ring + rw [hsum] + nlinarith + +/-- The accumulated optimistic objective before a time index. -/ +noncomputable def optimisticHistory {ι : Type*} (κ : ℝ) + (gain decrement : ℕ → ι → ℝ) (t : ℕ) (i : ι) : ℝ := + ∑ j ∈ range t, (gain j i + (1 - 2 * κ) * decrement j i) + +theorem optimisticHistory_succ {ι : Type*} (κ : ℝ) + (gain decrement : ℕ → ι → ℝ) (t : ℕ) : + optimisticHistory κ gain decrement (t + 1) = + fun i => optimisticHistory κ gain decrement t i + gain t i + + (1 - 2 * κ) * decrement t i := by + ext i + simp only [optimisticHistory, sum_range_succ] + ring + +theorem optimisticHistory_inner_product {ι : Type*} (coordinates : Finset ι) + (κ : ℝ) (gain decrement : ℕ → ι → ℝ) (S : ℕ) (p : ι → ℝ) : + (∑ i ∈ coordinates, optimisticHistory κ gain decrement S i * p i) = + (∑ t ∈ range S, ∑ i ∈ coordinates, (gain t i + decrement t i) * p i) - + 2 * κ * ∑ t ∈ range S, ∑ i ∈ coordinates, decrement t i * p i := by + simp only [optimisticHistory, sum_mul] + rw [sum_comm, mul_sum, ← sum_sub_distrib] + apply sum_congr rfl + intro t ht + rw [mul_sum, ← sum_sub_distrib] + apply sum_congr rfl + intro i hi + ring + +/-- Lemma `lem:entropy` for a finite compact convex action hull. The +fixed child-block masses enter through the equality of the baseline +inner products; `fixed_block_mass_inner_product` supplies that equality +from the individual block masses. The potential argument uses positivity and the relative-entropy penalty. -/ +theorem finite_hull_entropy_regret {ι : Type*} (coordinates : Finset ι) + (Q : Set (ι → ℝ)) (S : ℕ) (η κ : ℝ) + (gain decrement baseline innovation predicted : ℕ → ι → ℝ) + (witness comparator : ι → ℝ) + (hcompact : IsCompact Q) (hconvex : Convex ℝ Q) + (hwQ : witness ∈ Q) (hcQ : comparator ∈ Q) + (hw : ∀ i ∈ coordinates, 0 < witness i) + (hprob : ∀ p ∈ Q, + (∀ i ∈ coordinates, 0 ≤ p i) ∧ (∑ i ∈ coordinates, p i = 1)) + (hη : 0 < η) (hκ : 0 ≤ κ) (hκhalf : κ ≤ 1 / 2) + (hpredQ : ∀ t < S, predicted t ∈ Q) + (hpredMax : ∀ t < S, IsMaxOn + (entropyValue coordinates η + (fun i => optimisticHistory κ gain decrement t i + gain t i)) Q (predicted t)) + (hbaseline : ∀ t < S, ∀ i ∈ coordinates, 0 ≤ baseline t i) + (hdecomposition : ∀ t < S, ∀ i ∈ coordinates, + decrement t i = baseline t i + innovation t i) + (hfixedMass : ∀ t < S, ∀ p ∈ Q, ∀ q ∈ Q, + (∑ i ∈ coordinates, p i * baseline t i) = + ∑ i ∈ coordinates, q i * baseline t i) + (hinnovation : ∀ t < S, ∀ i ∈ coordinates, 0 ≤ η * innovation t i) + (hsmall : ∀ t < S, ∀ i ∈ coordinates, η * innovation t i ≤ κ) + (hdecrement : ∀ i ∈ coordinates, ∑ t ∈ range S, decrement t i ≤ 1) : + (∑ t ∈ range S, ∑ i ∈ coordinates, (gain t i + decrement t i) * comparator i) - + Real.log coordinates.card / η - 2 * κ ≤ + ∑ t ∈ range S, ∑ i ∈ coordinates, + (gain t i + (1 - κ) * decrement t i) * predicted t i := by + classical + have hex : ∀ t : ℕ, ∃ p ∈ Q, + IsMaxOn (entropyValue coordinates η (optimisticHistory κ gain decrement t)) Q p := + fun t => exists_entropy_maximizer coordinates Q η + (optimisticHistory κ gain decrement t) hcompact ⟨witness, hwQ⟩ + choose leader hleaderQ hleaderMax using hex + let potential : ℕ → ℝ := fun t => entropyValue coordinates η + (optimisticHistory κ gain decrement t) (leader t) + have hpredPositive (t : ℕ) (ht : t < S) : ∀ i ∈ coordinates, 0 < predicted t i := + entropy_hull_maximizer_positive coordinates Q η + (fun i => optimisticHistory κ gain decrement t i + gain t i) + (predicted t) witness hconvex (hpredQ t ht) hwQ + (hprob (predicted t) (hpredQ t ht)).1 hw (hpredMax t ht) + have hincrement (t : ℕ) (ht : t < S) : + potential (t + 1) - potential t ≤ + η * ∑ i ∈ coordinates, (gain t i + (1 - κ) * decrement t i) * predicted t i := by + have hstep := entropy_hull_potential_step coordinates Q η κ + (optimisticHistory κ gain decrement t) (gain t) (decrement t) (baseline t) + (innovation t) (leader t) (predicted t) (leader (t + 1)) hconvex + (hpredQ t ht) (hleaderQ (t + 1)) (hpredPositive t ht) + (hprob (leader (t + 1)) (hleaderQ (t + 1))).1 + (hprob (predicted t) (hpredQ t ht)).2 + (hprob (leader (t + 1)) (hleaderQ (t + 1))).2 + (hleaderMax t) (hpredMax t ht) hη.le hκ hκhalf (hbaseline t ht) + (hdecomposition t ht) + (hfixedMass t ht (leader (t + 1)) (hleaderQ (t + 1)) (predicted t) (hpredQ t ht)) + (hinnovation t ht) (hsmall t ht) + simpa only [potential, optimisticHistory_succ] using hstep + have hstart : potential 0 ≤ Real.log coordinates.card := by + have hbound := finite_entropy_le_log_card coordinates (leader 0) + (hprob (leader 0) (hleaderQ 0)).1 (hprob (leader 0) (hleaderQ 0)).2 + simpa [potential, entropyValue, optimisticHistory] using hbound + have hcomparator : η * + ((∑ t ∈ range S, ∑ i ∈ coordinates, (gain t i + decrement t i) * comparator i) - + 2 * κ * ∑ t ∈ range S, ∑ i ∈ coordinates, decrement t i * comparator i) ≤ + potential S := by + have hmax := hleaderMax S hcQ + change entropyValue coordinates η (optimisticHistory κ gain decrement S) comparator ≤ + potential S at hmax + rw [entropyValue_eq, optimisticHistory_inner_product] at hmax + have hentropy := finite_entropy_nonnegative coordinates comparator + (hprob comparator hcQ).1 (hprob comparator hcQ).2 + linarith + have hdecrementSum : (∑ t ∈ range S, ∑ i ∈ coordinates, decrement t i * comparator i) ≤ 1 := by + calc + _ = ∑ i ∈ coordinates, (∑ t ∈ range S, decrement t i) * comparator i := by + rw [sum_comm] + apply sum_congr rfl + intro i hi + rw [sum_mul] + _ ≤ ∑ i ∈ coordinates, comparator i := sum_le_sum fun i hi => by + simpa using mul_le_mul_of_nonneg_right (hdecrement i hi) ((hprob comparator hcQ).1 i hi) + _ = 1 := (hprob comparator hcQ).2 + exact entropy_potential_telescoping S η κ (Real.log coordinates.card) potential + (fun t => ∑ i ∈ coordinates, (gain t i + (1 - κ) * decrement t i) * predicted t i) + (fun t => ∑ i ∈ coordinates, (gain t i + decrement t i) * comparator i) + (fun t => ∑ i ∈ coordinates, decrement t i * comparator i) + hη hκ hincrement hstart hcomparator hdecrementSum + +/-- Replacing a probability vector by an approximation in `ℓ₁` loses +at most that error against any coordinate gain in `[-1, 0]`. -/ +theorem bounded_gain_l1_approximation {ι : Type*} (coordinates : Finset ι) + (gain exactVector approximateVector : ι → ℝ) (error : ℝ) + (hgain : ∀ i ∈ coordinates, -1 ≤ gain i ∧ gain i ≤ 0) + (hl1 : ∑ i ∈ coordinates, |approximateVector i - exactVector i| ≤ error) : + (∑ i ∈ coordinates, gain i * exactVector i) - error ≤ + ∑ i ∈ coordinates, gain i * approximateVector i := by + have hterm (i : ι) (hi : i ∈ coordinates) : + gain i * (exactVector i - approximateVector i) ≤ + |approximateVector i - exactVector i| := by + have habs : |gain i| ≤ 1 := abs_le.mpr ⟨(hgain i hi).1, (hgain i hi).2.trans zero_le_one⟩ + calc + _ ≤ |gain i * (exactVector i - approximateVector i)| := le_abs_self _ + _ = |gain i| * |exactVector i - approximateVector i| := abs_mul _ _ + _ ≤ 1 * |exactVector i - approximateVector i| := + mul_le_mul_of_nonneg_right habs (abs_nonneg _) + _ = _ := by rw [one_mul, abs_sub_comm] + have hsum := (sum_le_sum hterm).trans hl1 + simp only [mul_sub, sum_sub_distrib] at hsum + linarith + +/-- The entropy-regret lemma in its fixed-child-block form. Baseline +decrements are constructed as the actual minimum within each child +block; the range hypothesis supplies the small residual required by +the potential proof. -/ +theorem finite_block_entropy_regret {ι β : Type*} [Fintype β] [DecidableEq β] + (coordinates : Finset ι) (block : ι → β) + (Q : Set (ι → ℝ)) (S : ℕ) (η κ rangeBound : ℝ) + (gain decrement predicted : ℕ → ι → ℝ) (witness comparator : ι → ℝ) + (hcompact : IsCompact Q) (hconvex : Convex ℝ Q) + (hwQ : witness ∈ Q) (hcQ : comparator ∈ Q) + (hw : ∀ i ∈ coordinates, 0 < witness i) + (hprob : ∀ p ∈ Q, + (∀ i ∈ coordinates, 0 ≤ p i) ∧ (∑ i ∈ coordinates, p i = 1)) + (hblocks : ∀ b, (coordinates.filter (fun i => block i = b)).Nonempty) + (hblockMass : ∀ p ∈ Q, ∀ q ∈ Q, ∀ b, + (∑ i ∈ coordinates with block i = b, p i) = + ∑ i ∈ coordinates with block i = b, q i) + (hη : 0 < η) (hκ : 0 ≤ κ) (hκhalf : κ ≤ 1 / 2) + (hηrange : η * rangeBound ≤ κ) + (hpredQ : ∀ t < S, predicted t ∈ Q) + (hpredMax : ∀ t < S, IsMaxOn + (entropyValue coordinates η + (fun i => optimisticHistory κ gain decrement t i + gain t i)) Q (predicted t)) + (hdecrementNonneg : ∀ t < S, ∀ i ∈ coordinates, 0 ≤ decrement t i) + (hrange : ∀ t < S, ∀ i ∈ coordinates, ∀ j ∈ coordinates, + block i = block j → |decrement t i - decrement t j| ≤ rangeBound) + (hdecrement : ∀ i ∈ coordinates, ∑ t ∈ range S, decrement t i ≤ 1) : + (∑ t ∈ range S, ∑ i ∈ coordinates, (gain t i + decrement t i) * comparator i) - + Real.log coordinates.card / η - 2 * κ ≤ + ∑ t ∈ range S, ∑ i ∈ coordinates, + (gain t i + (1 - κ) * decrement t i) * predicted t i := by + classical + let blockMinimum : ℕ → β → ℝ := fun t b => + (coordinates.filter (fun i => block i = b)).inf' (hblocks b) (decrement t) + let baseline : ℕ → ι → ℝ := fun t i => blockMinimum t (block i) + let innovation : ℕ → ι → ℝ := fun t i => decrement t i - baseline t i + have hbaseline (t : ℕ) (ht : t < S) (i : ι) (hi : i ∈ coordinates) : + 0 ≤ baseline t i := by + apply Finset.le_inf' + intro j hj + exact hdecrementNonneg t ht j (mem_filter.mp hj).1 + have hminor (t : ℕ) (i : ι) (hi : i ∈ coordinates) : + baseline t i ≤ decrement t i := by + have hiBlock : i ∈ coordinates.filter (fun j => block j = block i) := + mem_filter.mpr ⟨hi, rfl⟩ + exact Finset.inf'_le (decrement t) hiBlock + have hresidual (t : ℕ) (ht : t < S) (i : ι) (hi : i ∈ coordinates) : + innovation t i ≤ rangeBound := by + have hlower : decrement t i - rangeBound ≤ baseline t i := by + apply Finset.le_inf' + intro j hj + have hdiff := hrange t ht i hi j (mem_filter.mp hj).1 (mem_filter.mp hj).2.symm + have := (abs_le.mp hdiff).2 + linarith + dsimp only [innovation] + linarith + apply finite_hull_entropy_regret coordinates Q S η κ gain decrement baseline innovation + predicted witness comparator hcompact hconvex hwQ hcQ hw hprob hη hκ hκhalf + hpredQ hpredMax hbaseline + · intro t ht i hi + dsimp only [innovation] + ring + · intro t ht p hp q hq + exact fixed_block_mass_inner_product coordinates block p q (blockMinimum t) + (hblockMass p hp q hq) + · intro t ht i hi + exact mul_nonneg hη.le (sub_nonneg.mpr (hminor t i hi)) + · intro t ht i hi + exact (mul_le_mul_of_nonneg_left (hresidual t ht i hi) hη.le).trans hηrange + · exact hdecrement + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/RepresentativeBands.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/RepresentativeBands.lean new file mode 100644 index 0000000000000000000000000000000000000000..33f7adc7a1275d15763a1d3aba54c66af46d0c64 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/RepresentativeBands.lean @@ -0,0 +1,62 @@ +import OAI.Combinatorics.EditApproximation.Refinement.ComputedBands +import OAI.Combinatorics.EditApproximation.Geometry.PrefixComparison +import OAI.Combinatorics.EditApproximation.Geometry.InitialCones +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! The actual rational wide minimum, computed velocity and representative band. -/ + +namespace EditApproximation + +open Finset + + + +theorem rationalEndpointActionValue_cast {ny M : ℕ} (r : TargetInterval ny) + (states : Fin M → TargetInterval ny) (child : Fin M → TargetInterval ny → ℚ) : + (rationalEndpointActionValue r states child : ℝ) = + endpointActionValue r states (fun i s => (child i s : ℝ)) := by + simp only [rationalEndpointActionValue, endpointActionValue, Rat.cast_add, + Rat.cast_natCast, Rat.cast_sum] + + + +theorem rationalWideActionMinimum_cast {nx ny M : ℕ} (parent : TargetInterval nx) + (r : TargetInterval ny) (b P : ℕ) (hnonempty : wideActionList M parent r b P ≠ []) + (child : Fin M → TargetInterval ny → ℚ) : + (rationalWideActionMinimum parent r b P hnonempty child : ℝ) = + wideActionMinimum parent r b P hnonempty (fun i s => (child i s : ℝ)) := by + rw [rationalWideActionMinimum, rationalMinimum_cast] + simp only [wideActionMinimum, rationalEndpointActionValue_cast, List.map_map, Function.comp_def] + +theorem wideActionMinimum_lower {α : Type*} (source target : List α) + {M : ℕ} (hM : 0 < M) (parent : TargetInterval source.length) + (r : TargetInterval target.length) (b P : ℕ) + (hnonempty : wideActionList M parent r b P ≠ []) (a : ℝ) (ha : 1 ≤ a) + (child : Fin M → TargetInterval target.length → ℝ) + (hchild : ∀ i s, max ((stateEditCost + (substring source (sourceChild parent i).lo (sourceChild parent i).hi) target s : ℝ) / a) + |stateLengthGap (substring source (sourceChild parent i).lo (sourceChild parent i).hi) target s| ≤ + child i s) : + max ((stateEditCost (substring source parent.lo parent.hi) target r : ℝ) / a) + |stateLengthGap (substring source parent.lo parent.hi) target r| ≤ + wideActionMinimum parent r b P hnonempty child := by + have hlower (states : Fin M → TargetInterval target.length) : + max ((stateEditCost (substring source parent.lo parent.hi) target r : ℝ) / a) + |stateLengthGap (substring source parent.lo parent.hi) target r| ≤ endpointActionValue r states child := + actual_endpoint_action_lower source target hM parent r states a ha child + (fun i => (le_max_left _ _).trans (hchild i (states i))) + (fun i => (le_max_right _ _).trans (hchild i (states i))) + apply (le_finiteMinimum_iff _ _ _).2 + refine ⟨hlower _, ?_⟩ + intro value hvalue + obtain ⟨states, hs, rfl⟩ := List.mem_map.mp hvalue + exact hlower states + + + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/RoundedComparison.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/RoundedComparison.lean new file mode 100644 index 0000000000000000000000000000000000000000..e2d020072632508d061b5d2d17d4bda77566f038 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/RoundedComparison.lean @@ -0,0 +1,129 @@ +import OAI.Combinatorics.EditApproximation.Geometry.AlignedStates +import OAI.Combinatorics.EditApproximation.Geometry.SharedActions +import OAI.Combinatorics.EditApproximation.Geometry.WideActions + +namespace OAI + +/-! +# Actual rounded comparison actions + +An optimal balanced alignment at the rounded representative is rounded +on the same integer grid. This produces a shared-endpoint wide action +and the manuscript's multiplicative cost growth, with all empty children +retained as labeled coordinates. +-/ + +namespace EditApproximation + +open Finset EditDistortion + +theorem rounded_comparison_action {α : Type*} (source target : List α) + {M : ℕ} (hM : 0 < M) (parent : TargetInterval source.length) + (q : TargetInterval target.length) (b P : ℕ) (hP : 66 ≤ P) + (hb : b ≤ stateEditCost (substring source parent.lo parent.hi) target q) + (hcost : stateEditCost (substring source parent.lo parent.hi) target q < 2 * b) : + let r := roundInterval (seedGridSpacing b P) q + ∃ states : Fin M → TargetInterval target.length, + states ∈ wideActionList M parent r b P ∧ endpointActionConnection r states = 0 ∧ + (∀ i j : Fin M, j.val = i.val + 1 → (states i).hi = (states j).lo) ∧ + (∀ i : Fin M, + Nat.dist (r.lo + ((sourceChild parent i).lo - parent.lo)) (states i).lo ≤ 6 * b ∧ + Nat.dist (r.lo + ((sourceChild parent i).hi - parent.lo)) (states i).hi ≤ 6 * b) ∧ + (∑ i, (stateEditCost + (substring source (sourceChild parent i).lo (sourceChild parent i).hi) target (states i) : ℝ)) ≤ + (1 + 4 * (M : ℝ) / P) * stateEditCost (substring source parent.lo parent.hi) target q := by + dsimp only + let g := seedGridSpacing b P + let r := roundInterval g q + let piece := fun i : Fin M => + substring source (sourceChild parent i).lo (sourceChild parent i).hi + let c : ℝ := stateEditCost (substring source parent.lo parent.hi) target q + let cr : ℝ := stateEditCost (substring source parent.lo parent.hi) target r + have hPr : (0 : ℝ) < P := by exact_mod_cast (by omega : 0 < P) + have hProne : (1 : ℝ) ≤ P := by exact_mod_cast (by omega : 1 ≤ P) + have hMr : (1 : ℝ) ≤ M := by exact_mod_cast hM + have hbc : (b : ℝ) ≤ c := by dsimp only [c]; exact_mod_cast hb + have hcb : c < 2 * b := by dsimp only [c]; exact_mod_cast hcost + have hqgrid : (targetEndpointDistance q r : ℝ) * P ≤ 2 * b := by + exact_mod_cast rounded_seedGrid_error b P (by omega) q + have hcr : cr ≤ c + targetEndpointDistance q r := by + have h := stateEditCost_distance_abs (substring source parent.lo parent.hi) target q r + have hR : |c - cr| ≤ (targetEndpointDistance q r : ℝ) := by + dsimp only [c, cr] + exact_mod_cast h + linarith [(abs_le.mp hR).1] + have hcrP : cr * P ≤ c * P + 2 * b := by + have hmul := mul_le_mul_of_nonneg_right hcr hPr.le + nlinarith + have hqerror : (targetEndpointDistance q r : ℝ) ≤ 2 * b := by + nlinarith [mul_nonneg (Nat.cast_nonneg (targetEndpointDistance q r)) + (sub_nonneg.mpr hProne)] + obtain ⟨aligned, hsplit, hstart, hend, hshared, hanchors⟩ := + optimal_balanced_child_states source target hM parent r + let states := fun i => roundInterval g (aligned i) + have herror (i : Fin M) : (targetEndpointDistance (aligned i) (states i) : ℝ) * P ≤ 2 * b := by + exact_mod_cast rounded_seedGrid_error b P (by omega) (aligned i) + have hanchorBound (i : Fin M) (anchor endpoint rounded : ℕ) + (hanchor : Nat.dist anchor endpoint ≤ stateEditCost (substring source parent.lo parent.hi) target r) + (hround : Nat.dist endpoint rounded ≤ targetEndpointDistance (aligned i) (states i)) : + Nat.dist anchor rounded ≤ 6 * b := by + have htriangle := Nat.dist.triangle_inequality anchor endpoint rounded + have hbound : (Nat.dist anchor rounded : ℝ) ≤ cr + + targetEndpointDistance (aligned i) (states i) := by + dsimp only [cr] + exact_mod_cast (by omega : Nat.dist anchor rounded ≤ + stateEditCost (substring source parent.lo parent.hi) target r + + targetEndpointDistance (aligned i) (states i)) + have he := herror i + have herr : (targetEndpointDistance (aligned i) (states i) : ℝ) ≤ 2 * b := by + nlinarith [mul_nonneg (Nat.cast_nonneg (targetEndpointDistance (aligned i) (states i))) + (sub_nonneg.mpr hProne)] + have hfinal : (Nat.dist anchor rounded : ℝ) ≤ 6 * b := by linarith + exact_mod_cast hfinal + have hanchorsRounded (i : Fin M) : + Nat.dist (r.lo + ((sourceChild parent i).lo - parent.lo)) (states i).lo ≤ 6 * b ∧ + Nat.dist (r.lo + ((sourceChild parent i).hi - parent.lo)) (states i).hi ≤ 6 * b := by + constructor + · exact hanchorBound i _ _ _ (hanchors i).1 (Nat.le_add_right _ _) + · exact hanchorBound i _ _ _ (hanchors i).2 (Nat.le_add_left _ _) + have hcostPoint (i : Fin M) : + (stateEditCost (piece i) target (states i) : ℝ) * P ≤ + (stateEditCost (piece i) target (aligned i) : ℝ) * P + 2 * b := by + have h := stateEditCost_distance_abs (piece i) target (aligned i) (states i) + have hR : |(stateEditCost (piece i) target (aligned i) : ℝ) - + stateEditCost (piece i) target (states i)| ≤ targetEndpointDistance (aligned i) (states i) := by + exact_mod_cast h + have hstep : (stateEditCost (piece i) target (states i) : ℝ) ≤ + stateEditCost (piece i) target (aligned i) + targetEndpointDistance (aligned i) (states i) := by + linarith [(abs_le.mp hR).1] + have hmul := mul_le_mul_of_nonneg_right hstep hPr.le + nlinarith [herror i] + have hsum := sum_le_sum (fun i (_ : i ∈ (univ : Finset (Fin M))) => hcostPoint i) + simp only [sum_add_distrib, sum_const, card_univ, Fintype.card_fin, nsmul_eq_mul, + ← sum_mul] at hsum + have hsplitR : (∑ i, (stateEditCost (piece i) target (aligned i) : ℝ)) = cr := by + dsimp only [piece, cr] + exact_mod_cast hsplit + rw [hsplitR] at hsum + have hsumFinal : (∑ i, (stateEditCost (piece i) target (states i) : ℝ)) ≤ + (1 + 4 * (M : ℝ) / P) * c := by + have hMb := mul_le_mul_of_nonneg_left hbc (Nat.cast_nonneg M) + have hbM : (b : ℝ) ≤ M * (b : ℝ) := by + nlinarith [mul_nonneg (sub_nonneg.mpr hMr) (Nat.cast_nonneg b)] + have hscaled : (∑ i, (stateEditCost (piece i) target (states i) : ℝ)) * P ≤ + (P + 4 * (M : ℝ)) * c := by nlinarith + have hformula : ((P : ℝ) + 4 * M) * c / P = (1 + 4 * (M : ℝ) / P) * c := by + field_simp + rw [← hformula] + exact (le_div_iff₀ hPr).2 hscaled + refine ⟨states, ?_, ?_, ?_, hanchorsRounded, hsumFinal⟩ + · apply wideActionList_complete parent r states (fun i => roundInterval_on_grid g (aligned i)) + · intro i; exact (hanchorsRounded i).1.trans (by omega) + · intro i; exact (hanchorsRounded i).2.trans (by omega) + · exact round_shared_action hM r aligned hstart hend hshared (roundInterval_on_grid g q) + · intro i j hij + exact roundInterval_shared (aligned i) (aligned j) (hshared i j hij) + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/RoundedGroupStates.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/RoundedGroupStates.lean new file mode 100644 index 0000000000000000000000000000000000000000..f1fa2aca88de0569c6d667f5a74baff4f9587d9d --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/RoundedGroupStates.lean @@ -0,0 +1,136 @@ +import OAI.Combinatorics.EditApproximation.Geometry.GroupSamplingWork +import OAI.Combinatorics.EditApproximation.Geometry.WideActions +import OAI.Combinatorics.EditApproximation.Geometry.GroupCells +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Enumerating rounded endpoints with a length-gap guard costs only +one wide coordinate and one envelope coordinate. -/ + +namespace EditApproximation + + + +theorem gridGapStates_complete {n g anchor radius sourceLength gapRadius : ℕ} + (hg : 0 < g) (r : TargetInterval n) + (hfirst : Nat.dist anchor r.lo ≤ radius) + (hgap : Nat.dist (r.lo + sourceLength) r.hi ≤ gapRadius) + (hgrid : g ∣ r.lo ∧ g ∣ r.hi) : + r ∈ gridGapStates n g anchor radius sourceLength gapRadius := by + have hlo : anchor - radius ≤ r.lo ∧ r.lo ≤ anchor + radius := by unfold Nat.dist at hfirst; omega + have hhi : r.lo + sourceLength - gapRadius ≤ r.hi ∧ r.hi ≤ r.lo + sourceLength + gapRadius := by + unfold Nat.dist at hgap + omega + apply List.mem_flatMap.mpr + refine ⟨r.lo, gridPointsBetween_complete hg hlo.1 hlo.2 hgrid.1, ?_⟩ + apply List.mem_filterMap.mpr + refine ⟨r.hi, gridPointsBetween_complete hg hhi.1 hhi.2 hgrid.2, ?_⟩ + rw [makeTargetState, dite_eq_left (show r.lo ≤ r.hi ∧ r.hi ≤ n from ⟨r.ordered, r.valid⟩)] + +theorem gridGapStates_length_le (n g anchor radius sourceLength gapRadius : ℕ) (hg : 0 < g) : + (gridGapStates n g anchor radius sourceLength gapRadius).length ≤ + (2 * radius / g + 2) * (2 * gapRadius / g + 2) := by + have hpoint (p rad : ℕ) : (gridPointsBetween g (p - rad) (p + rad)).length ≤ 2 * rad / g + 2 := by + exact (gridPointsBetween_length_le g _ _ hg).trans + (Nat.add_le_add_right (Nat.div_le_div_right (by omega : p + rad - (p - rad) ≤ 2 * rad)) 2) + have h := list_flatMap_length_le (gridPointsBetween g (anchor - radius) (anchor + radius)) + (fun lo => (gridPointsBetween g (lo + sourceLength - gapRadius) (lo + sourceLength + gapRadius)).filterMap + fun hi => makeTargetState n lo hi) (2 * gapRadius / g + 2) + (fun lo _ => (List.length_filterMap_le _ _).trans (hpoint (lo + sourceLength) gapRadius)) + exact h.trans (Nat.mul_le_mul_right _ (hpoint anchor radius)) + +theorem lengthGap_guard_distance {n : ℕ} (r : TargetInterval n) (sourceLength : ℕ) (h : ℚ) + (hguard : |(r.hi : ℚ) - r.lo - sourceLength| ≤ 2 * h) : + Nat.dist (r.lo + sourceLength) r.hi ≤ ⌈2 * h⌉₊ := by + have hcast : (Nat.dist (r.lo + sourceLength) r.hi : ℚ) = + |(r.hi : ℚ) - r.lo - sourceLength| := by + have hd : |((r.lo + sourceLength : ℕ) : ℚ) - r.hi| = + (Nat.dist (r.lo + sourceLength) r.hi : ℚ) := by + exact_mod_cast natural_distance_cast (r.lo + sourceLength) r.hi + rw [← hd, abs_sub_comm] + congr 1 + push_cast + ring + have hbound : (Nat.dist (r.lo + sourceLength) r.hi : ℚ) ≤ (⌈2 * h⌉₊ : ℚ) := + hcast.le.trans (hguard.trans (Nat.le_ceil _)) + exact_mod_cast hbound + +theorem wide_firstEndpoint_near_cell {n g b : ℕ} {theta : ℚ} + (cell : ℕ × ℕ) (hg : 0 < g) (htheta : 0 ≤ theta ∧ theta ≤ 1) (hb : 1 ≤ b) + (center r : TargetInterval n) (offset : ℕ) + (hcenter : center ∈ cellTargetStates n g (theta * b) cell) + (hwide : Nat.dist (center.lo + offset) r.lo ≤ 10 * b) : + Nat.dist (⌊(cell.1 : ℚ) * (theta * b)⌋₊ + offset) r.lo ≤ 12 * b := by + have hc := (cellTargetStates_mem cell hg center).mp hcenter + have hbase : 0 ≤ (cell.1 : ℚ) * (theta * b) := + mul_nonneg (Nat.cast_nonneg _) (mul_nonneg htheta.1 (Nat.cast_nonneg _)) + have hfloor := Nat.floor_le hbase + have hfloorUpper := Nat.lt_floor_add_one ((cell.1 : ℚ) * (theta * b)) + have hthetaB := mul_le_mul_of_nonneg_right htheta.2 (Nat.cast_nonneg (α := ℚ) b) + have hbR : (1 : ℚ) ≤ b := by exact_mod_cast hb + have hlo : ⌊(cell.1 : ℚ) * (theta * b)⌋₊ ≤ center.lo := by + exact_mod_cast hfloor.trans hc.2.2.1 + have hhi : center.lo ≤ ⌊(cell.1 : ℚ) * (theta * b)⌋₊ + 2 * b := by + have hhiR : (center.lo : ℚ) ≤ (⌊(cell.1 : ℚ) * (theta * b)⌋₊ : ℚ) + 2 * b := by + nlinarith only [hc.2.2.2.1, hfloorUpper, hthetaB, hbR] + exact_mod_cast hhiR + unfold Nat.dist at hwide ⊢ + omega + +/-- The spacing dominates h/K and one. This includes the spacing-one +case for fractional envelopes. No success or accuracy event is needed. -/ +theorem gridGapStates_rounded_count (n g anchor sourceLength b : ℕ) (h K : ℚ) + (hg : 0 < g) (hh : 0 < h) (hK : 1 ≤ K) (hspacing : h ≤ K * g) : + ((gridGapStates n g anchor (12 * b) sourceLength ⌈2 * h⌉₊).length : ℚ) ≤ + 208 * K ^ 2 * (1 + b / h) := by + have hgr : (0 : ℚ) < g := by exact_mod_cast hg + have hg1 : (1 : ℚ) ≤ g := by exact_mod_cast hg + have hKr : 0 ≤ K := le_trans zero_le_one hK + have hb : (0 : ℚ) ≤ b := Nat.cast_nonneg _ + have hfirstDiv : ((24 * b / g : ℕ) : ℚ) ≤ 24 * K * b / h := by + apply (Nat.cast_div_le (m := 24 * b) (n := g)).trans + push_cast + apply (div_le_div_iff₀ hgr hh).2 + have hm := mul_le_mul_of_nonneg_right hspacing (show (0 : ℚ) ≤ 24 * b by positivity) + nlinarith only [hm] + have hceil : (⌈2 * h⌉₊ : ℚ) < 2 * h + 1 := Nat.ceil_lt_add_one (by positivity) + have hsecondDiv : ((2 * ⌈2 * h⌉₊ / g : ℕ) : ℚ) ≤ 4 * K + 2 := by + apply (Nat.cast_div_le (m := 2 * ⌈2 * h⌉₊) (n := g)).trans + push_cast + apply (div_le_iff₀ hgr).2 + nlinarith only [hceil, hspacing, hg1] + have hratio : 0 ≤ (b : ℚ) / h := div_nonneg hb hh.le + have hfirst : (((2 * (12 * b) / g + 2 : ℕ) : ℚ)) ≤ 26 * K * (1 + b / h) := by + have heq : 2 * (12 * b) = 24 * b := by omega + rw [heq, Nat.cast_add, Nat.cast_ofNat] + have hquotient : 24 * K * b / h = 24 * K * (b / h) := by ring + rw [hquotient] at hfirstDiv + have hKr' := mul_nonneg hKr hratio + nlinarith only [hfirstDiv, hK, hKr'] + have hsecond : (((2 * ⌈2 * h⌉₊ / g + 2 : ℕ) : ℚ)) ≤ 8 * K := by + rw [Nat.cast_add, Nat.cast_ofNat] + linarith only [hsecondDiv, hK] + have hlength : ((gridGapStates n g anchor (12 * b) sourceLength ⌈2 * h⌉₊).length : ℚ) ≤ + (((2 * (12 * b) / g + 2 : ℕ) : ℚ)) * (((2 * ⌈2 * h⌉₊ / g + 2 : ℕ) : ℚ)) := by + exact_mod_cast gridGapStates_length_le n g anchor (12 * b) sourceLength ⌈2 * h⌉₊ hg + apply hlength.trans + calc + _ ≤ (26 * K * (1 + b / h)) * (8 * K) := + mul_le_mul hfirst hsecond (Nat.cast_nonneg _) (by positivity) + _ = _ := by ring + +theorem shared_rounded_inputs_bound {M Q b : ℕ} {h K states : ℚ} + (hM : 0 < M) (hQ : 1 ≤ Q) (hb : 0 < b) (hh : 0 < h) + (hfloor : (b : ℚ) / M ≤ h) (hstates : states ≤ 208 * K ^ 2 * (1 + b / h)) : + (groupSampleCount M Q b h : ℚ) * states ≤ 624 * M * Q * K ^ 2 := by + have hwork := groupSampleCount_shared_work hM hQ hb hh hfloor + have hstateBound := mul_le_mul_of_nonneg_left hstates + (Nat.cast_nonneg (α := ℚ) (groupSampleCount M Q b h)) + have hworkBound := mul_le_mul_of_nonneg_left hwork (by positivity : (0 : ℚ) ≤ 208 * K ^ 2) + nlinarith only [hstateBound, hworkBound] + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/Seed.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/Seed.lean new file mode 100644 index 0000000000000000000000000000000000000000..00ecd9070806c77e520402dcb1a2b9b012b6e69b --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/Seed.lean @@ -0,0 +1,119 @@ +import Mathlib + +namespace OAI + +/-! +# Threshold reconstruction in the initial estimator + +Deterministic reconstruction from Section 3 of the September 24, 2026 +edit-distance manuscript. Concentration is kept separate: the thresholds +can influence the approximate child costs, so no independence assumption +about those approximate costs is made here. +-/ + +namespace EditApproximation + +/-- A threshold contribution of the coarse estimator. -/ +noncomputable def thresholdContribution (threshold scale value : ℝ) : ℝ := + if threshold ≤ value then max value scale else 0 + +theorem thresholdContribution_nonneg {threshold scale value : ℝ} (hscale : 0 ≤ scale) : + 0 ≤ thresholdContribution threshold scale value := by + unfold thresholdContribution + split_ifs + · exact hscale.trans (le_max_right _ _) + · rfl + +theorem thresholdContribution_mono {threshold scale value value' : ℝ} + (hscale : 0 ≤ scale) (hle : value ≤ value') : + thresholdContribution threshold scale value ≤ + thresholdContribution threshold scale value' := by + unfold thresholdContribution + split_ifs with h h' + · exact max_le_max hle le_rfl + · exact False.elim (h' (h.trans hle)) + · exact hscale.trans (le_max_right _ _) + · rfl + +/-- Pathwise threshold sandwich. In particular, `estimate` may depend on +`threshold`; the proof only uses its two deterministic error bounds. -/ +theorem threshold_sandwich {threshold scale estimate lower upper lam : ℝ} + (hscale : 0 ≤ scale) (hlam : 0 ≤ lam) (hlamone : lam < 1) + (hlower : (1 + lam) * lower - lam * threshold ≤ estimate) + (hupper : estimate ≤ (1 - lam) * upper + lam * threshold) : + thresholdContribution threshold scale lower ≤ + thresholdContribution threshold scale estimate ∧ + thresholdContribution threshold scale estimate ≤ + thresholdContribution threshold scale upper := by + constructor + · by_cases hlt : threshold ≤ lower + · have hprod := mul_nonneg hlam (sub_nonneg.mpr hlt) + have hle : lower ≤ estimate := by nlinarith + exact thresholdContribution_mono hscale hle + · simp only [thresholdContribution, ite_eq_right hlt] + exact thresholdContribution_nonneg hscale + · by_cases hlt : threshold ≤ estimate + · have hprod := mul_le_mul_of_nonneg_left hlt hlam + have hle : estimate ≤ upper := by nlinarith + exact thresholdContribution_mono hscale hle + · simp only [thresholdContribution, ite_eq_right hlt] + exact thresholdContribution_nonneg hscale + +/-- The precise factors used in the manuscript's threshold sandwich. -/ +theorem coarse_threshold_sandwich {threshold scale estimate trueCost f lam : ℝ} + (hscale : 0 ≤ scale) (hf : 0 < f) (hlam : 0 ≤ lam) (hlamone : lam < 1) + (hlower : trueCost / f - lam * threshold ≤ estimate) + (hupper : estimate ≤ f * trueCost + lam * threshold) : + thresholdContribution threshold scale (trueCost / (f * (1 + lam))) ≤ + thresholdContribution threshold scale estimate ∧ + thresholdContribution threshold scale estimate ≤ + thresholdContribution threshold scale (f * trueCost / (1 - lam)) := by + apply threshold_sandwich hscale hlam hlamone + · have hid : (1 + lam) * (trueCost / (f * (1 + lam))) = trueCost / f := by + field_simp + simpa only [hid] using hlower + · have hid : (1 - lam) * (f * trueCost / (1 - lam)) = f * trueCost := by + field_simp [ne_of_gt (sub_pos.mpr hlamone)] + simpa only [hid] using hupper + +/-- Combining the two true-cost concentration events with the pathwise +sandwich updates the structural factor from `f` to +`f * (1 + lam) / (1 - lam)`. Neither event conditions on child accuracy. -/ +theorem coarse_reconstruction {ι : Type*} (children : Finset ι) + (threshold estimate trueCost : ι → ℝ) (scale allowance f lam : ℝ) + (hscale : 0 ≤ scale) (hf : 0 < f) (hlam : 0 ≤ lam) (hlamone : lam < 1) + (hchildLower : ∀ i ∈ children, trueCost i / f - lam * threshold i ≤ estimate i) + (hchildUpper : ∀ i ∈ children, estimate i ≤ f * trueCost i + lam * threshold i) + (hconcentrationLower : + (1 - lam) * (∑ i ∈ children, trueCost i / (f * (1 + lam))) - allowance ≤ + ∑ i ∈ children, thresholdContribution (threshold i) scale + (trueCost i / (f * (1 + lam)))) + (hconcentrationUpper : + (∑ i ∈ children, thresholdContribution (threshold i) scale + (f * trueCost i / (1 - lam))) ≤ + (1 + lam) * (∑ i ∈ children, f * trueCost i / (1 - lam)) + allowance) : + (∑ i ∈ children, trueCost i) / (f * (1 + lam) / (1 - lam)) - allowance ≤ + ∑ i ∈ children, thresholdContribution (threshold i) scale (estimate i) ∧ + (∑ i ∈ children, thresholdContribution (threshold i) scale (estimate i)) ≤ + (f * (1 + lam) / (1 - lam)) * (∑ i ∈ children, trueCost i) + allowance := by + have hsandwich (i : ι) (hi : i ∈ children) := coarse_threshold_sandwich + hscale hf hlam hlamone (hchildLower i hi) (hchildUpper i hi) + constructor + · have hlo := hconcentrationLower.trans + (Finset.sum_le_sum fun i hi => (hsandwich i hi).1) + have hid : (1 - lam) * (∑ i ∈ children, trueCost i / (f * (1 + lam))) = + (∑ i ∈ children, trueCost i) / (f * (1 + lam) / (1 - lam)) := by + rw [← Finset.sum_div] + field_simp + simpa only [hid] using hlo + · have hhi := (Finset.sum_le_sum fun i hi => (hsandwich i hi).2).trans + hconcentrationUpper + have hid : (1 + lam) * (∑ i ∈ children, f * trueCost i / (1 - lam)) = + (f * (1 + lam) / (1 - lam)) * (∑ i ∈ children, trueCost i) := by + rw [← Finset.sum_div, ← Finset.mul_sum] + ring + simpa only [hid] using hhi + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/SeedFactorSchedule.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/SeedFactorSchedule.lean new file mode 100644 index 0000000000000000000000000000000000000000..5038033082da3009a15436830ceedba689365a0d --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/SeedFactorSchedule.lean @@ -0,0 +1,132 @@ +import OAI.Combinatorics.EditApproximation.Refinement.StageWarmup +import OAI.Combinatorics.EditApproximation.Geometry.Parameters +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! The literal dyadic factor schedule stops at A<=F. Each active pass +replaces A by 4A/F and uses the integer factor a=A/F. -/ + +namespace EditApproximation + + + + +theorem dyadicSeedExponent_active (f initial pass : ℕ) (hf : 3 ≤ f) + (hpass : pass < dyadicSeedPassCount f initial) : + f < dyadicSeedExponent f initial pass := by + have hd : 0 < f - 2 := by omega + have hproduct : (f - 2) * pass < initial - f := by + by_contra hn + have hle : dyadicSeedPassCount f initial ≤ pass := + (ceilDiv_le_iff_le_mul hd).2 (le_of_not_gt hn) + omega + unfold dyadicSeedExponent + rw [Nat.mul_comm] at hproduct + omega + +theorem dyadicSeedExponent_terminal (f initial : ℕ) (hf : 3 ≤ f) : + dyadicSeedExponent f initial (dyadicSeedPassCount f initial) ≤ f := by + have hd : 0 < f - 2 := by omega + have hproduct : initial - f ≤ (f - 2) * dyadicSeedPassCount f initial := + (ceilDiv_le_iff_le_mul hd).1 le_rfl + unfold dyadicSeedExponent + rw [Nat.mul_comm] at hproduct + omega + +theorem dyadicSeedPassCount_le (f initial : ℕ) (hf : 3 ≤ f) : + dyadicSeedPassCount f initial ≤ initial / (f - 2) + 1 := by + have hd : 0 < f - 2 := by omega + apply (ceilDiv_le_iff_le_mul hd).2 + have hfloor := Nat.lt_mul_div_succ initial hd + nlinarith only [hfloor, show initial - f ≤ initial from Nat.sub_le _ _] + +theorem dyadicSeedPassCount_le_initial (f initial : ℕ) (hf : 3 ≤ f) : + dyadicSeedPassCount f initial ≤ initial := by + apply (ceilDiv_le_iff_le_mul (by omega : 0 < f - 2)).2 + exact (Nat.sub_le initial f).trans (Nat.le_mul_of_pos_left _ (by omega : 0 < f - 2)) + +theorem dyadicSeedExponent_succ (f initial pass : ℕ) : + dyadicSeedExponent f initial (pass + 1) = dyadicSeedExponent f initial pass - (f - 2) := by + simp only [dyadicSeedExponent, Nat.add_mul, one_mul, Nat.sub_sub] + +theorem dyadicSeedFactor_update (f initial pass : ℕ) (hf : 3 ≤ f) + (hpass : pass < dyadicSeedPassCount f initial) : + (2 : ℚ) ^ dyadicSeedExponent f initial (pass + 1) = + 4 * (2 : ℚ) ^ dyadicSeedExponent f initial pass / (2 : ℚ) ^ f := by + have hactive := dyadicSeedExponent_active f initial pass hf hpass + have hexponent : dyadicSeedExponent f initial (pass + 1) + f = + dyadicSeedExponent f initial pass + 2 := by rw [dyadicSeedExponent_succ]; omega + apply (eq_div_iff (pow_ne_zero f (by norm_num : (2 : ℚ) ≠ 0))).2 + rw [← pow_add, hexponent, pow_add] + norm_num + ring + +theorem dyadicSeedFactor_integer (f initial pass : ℕ) (hf : 3 ≤ f) + (hpass : pass < dyadicSeedPassCount f initial) : + refinementFactor ((2 : ℚ) ^ dyadicSeedExponent f initial pass) (2 ^ f) = + ((2 ^ (dyadicSeedExponent f initial pass - f) : ℕ) : ℚ) := by + have hactive := dyadicSeedExponent_active f initial pass hf hpass + have hquotient : (2 : ℚ) ^ dyadicSeedExponent f initial pass / ((2 ^ f : ℕ) : ℚ) = + ((2 ^ (dyadicSeedExponent f initial pass - f) : ℕ) : ℚ) := by + push_cast + apply (div_eq_iff (pow_ne_zero f (by norm_num : (2 : ℚ) ≠ 0))).2 + rw [← pow_add, Nat.sub_add_cancel hactive.le] + unfold refinementFactor + rw [hquotient, max_eq_right] + exact_mod_cast Nat.one_le_two_pow (n := dyadicSeedExponent f initial pass - f) + +theorem dyadicSeedFactor_bound (f initial pass : ℕ) : + (2 : ℚ) ^ dyadicSeedExponent f initial pass ≤ (2 : ℚ) ^ initial := + pow_le_pow_right₀ (by norm_num) (Nat.sub_le _ _) + +theorem dyadicSeedFactor_terminal (f initial : ℕ) (hf : 3 ≤ f) : + (2 : ℚ) ^ dyadicSeedExponent f initial (dyadicSeedPassCount f initial) ≤ (2 ^ f : ℕ) := by + simpa only [Nat.cast_pow, Nat.cast_ofNat] using + pow_le_pow_right₀ (by norm_num : (1 : ℚ) ≤ 2) (dyadicSeedExponent_terminal f initial hf) + +theorem dyadicSeedFactor_terminal_refinement (f initial : ℕ) (hf : 3 ≤ f) : + refinementFactor ((2 : ℚ) ^ dyadicSeedExponent f initial (dyadicSeedPassCount f initial)) (2 ^ f) = 1 := by + unfold refinementFactor + apply max_eq_left + apply (div_le_one (by positivity : (0 : ℚ) < (2 ^ f : ℕ))).2 + exact dyadicSeedFactor_terminal f initial hf + + + + + +theorem computedSeed_initial_factor (N : ℕ) : + (2 : ℚ) ^ computedSeedInitialExponent N = + ((integerParameters N).initialFactor : ℚ) := by + simp only [computedSeedInitialExponent, integerParameters, inputHeight, Nat.cast_pow, Nat.cast_ofNat] + rw [← pow_mul, Nat.mul_comm] + +theorem computedSeedPassCount_le_height (N : ℕ) (hN : 0 < N) + (hell : 2 ^ 1000 ≤ inputSmallLog N) : computedSeedPassCount N ≤ inputHeight N := by + have hf : 3 ≤ smallLogExponent N := by + have h := (Nat.pow_le_pow_iff_right (by decide : 1 < (2 : ℕ))).mp hell + omega + have hlogs := (inputSmallLog_bounds N hN).1 + have hp : coarseExponent (inputSmallLog N) ≤ inputSmallLog N := + (Nat.sqrt_le_self _).trans ((Nat.sqrt_le_self _).trans (Nat.log_le_self _ _)) + have hell4 : 4 ≤ inputSmallLog N := + (by decide : 4 ≤ (2 : ℕ) ^ 3).trans + (Nat.pow_le_pow_right (by decide : 0 < (2 : ℕ)) hf) + have hmul := Nat.mul_le_mul (show coarseExponent (inputSmallLog N) + 4 ≤ 2 * inputSmallLog N by omega) hlogs + have hsmall : computedSeedInitialExponent N ≤ inputSmallLog N ^ 3 := by + unfold computedSeedInitialExponent + apply hmul.trans + have h := Nat.mul_le_mul_right (inputSmallLog N ^ 2) (by omega : 2 ≤ inputSmallLog N) + nlinarith only [h] + have hpoly := inputHeight_polynomial_slack N hN hell + have hellOne : (1 : ℝ) ≤ inputSmallLog N := by exact_mod_cast (show 1 ≤ inputSmallLog N from (by decide : 1 ≤ (4 : ℕ)).trans hell4) + have hpower : (inputSmallLog N : ℝ) ^ 3 ≤ (inputSmallLog N : ℝ) ^ 20000 := + pow_le_pow_right₀ hellOne (by decide : 3 ≤ 20000) + have hH : inputSmallLog N ^ 3 ≤ inputHeight N := by exact_mod_cast hpower.trans hpoly + exact (dyadicSeedPassCount_le_initial _ _ hf).trans (hsmall.trans hH) + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/SeedPassNumerics.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/SeedPassNumerics.lean new file mode 100644 index 0000000000000000000000000000000000000000..98db5ce3a85fe39675e042b193a34e595a1f1643 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/SeedPassNumerics.lean @@ -0,0 +1,79 @@ +import OAI.Combinatorics.EditApproximation.Geometry.DomainExponential +import Mathlib.Analysis.Complex.ExponentialBounds + +namespace OAI + +/-! Numerical amplification for the literal H²-copy seed update and +the finite sequence of refinement passes. -/ + +namespace EditApproximation + +theorem seed_copy_binary_tail (copies ell : ℕ) (hell : 64 ≤ ell) : + (2 : ℝ) ^ copies * (1 / (ell : ℝ)) ^ (copies - copies / 2) ≤ + Real.exp (-(copies : ℝ)) := by + let k := copies - copies / 2 + have hcopies : copies ≤ 2 * k := by dsimp only [k]; omega + have hellR : (64 : ℝ) ≤ ell := by exact_mod_cast hell + have hellpos : (0 : ℝ) < ell := by linarith only [hellR] + have hscale : (4 : ℝ) / ell ≤ 1 / 16 := by + apply (div_le_iff₀ hellpos).2 + linarith only [hellR] + have hexp2 : Real.exp (2 : ℝ) ≤ 16 := by + rw [show (2 : ℝ) = 1 + 1 by norm_num, Real.exp_add] + have he := Real.exp_one_lt_three + have hep := Real.exp_pos (1 : ℝ) + nlinarith only [he, hep] + have hexpinv : (1 / 16 : ℝ) ≤ Real.exp (-2) := by + rw [Real.exp_neg, ← one_div] + exact one_div_le_one_div_of_le (Real.exp_pos _) hexp2 + calc + _ ≤ (2 : ℝ) ^ (2 * k) * (1 / (ell : ℝ)) ^ k := + mul_le_mul_of_nonneg_right (pow_le_pow_right₀ (by norm_num : (1 : ℝ) ≤ 2) hcopies) (by positivity) + _ = ((4 : ℝ) / ell) ^ k := by rw [pow_mul, ← mul_pow]; congr 1; norm_num [div_eq_mul_inv] + _ ≤ (1 / 16 : ℝ) ^ k := pow_le_pow_left₀ (by positivity) hscale k + _ ≤ Real.exp (-2) ^ k := pow_le_pow_left₀ (by norm_num) hexpinv k + _ = Real.exp (-2 * (k : ℝ)) := by rw [← Real.exp_nat_mul]; congr 1; ring + _ ≤ Real.exp (-(copies : ℝ)) := by + apply Real.exp_le_exp.mpr + have hc : (copies : ℝ) ≤ 2 * (k : ℝ) := by exact_mod_cast hcopies + linarith only [hc] + +theorem seed_state_union_numeric (H domain : ℝ) + (hdomain : domain ≤ Real.exp (10 * H)) : + domain * Real.exp (-(H ^ 2)) ≤ Real.exp (10 * H - H ^ 2) := by + calc + _ ≤ Real.exp (10 * H) * Real.exp (-(H ^ 2)) := + mul_le_mul_of_nonneg_right hdomain (Real.exp_pos _).le + _ = _ := by rw [← Real.exp_add]; congr 1 + +theorem seed_pass_union_numeric (H : ℝ) (hH : 100 ≤ H) : + H * Real.exp (10 * H - H ^ 2) ≤ 1 / 100 := by + have hH0 : 0 ≤ H := by linarith only [hH] + have hquadratic := mul_nonneg hH0 (show 0 ≤ H - 100 by linarith only [hH]) + have hexponent : 10 * H - H ^ 2 ≤ -2 * H := by nlinarith only [hquadratic, hH] + have hHexp : H ≤ Real.exp H := by linarith only [Real.add_one_le_exp H] + have hexp100 : (100 : ℝ) ≤ Real.exp H := hH.trans hHexp + calc + _ ≤ H * Real.exp (-2 * H) := mul_le_mul_of_nonneg_left (Real.exp_le_exp.mpr hexponent) hH0 + _ ≤ Real.exp H * Real.exp (-2 * H) := mul_le_mul_of_nonneg_right hHexp (Real.exp_pos _).le + _ = Real.exp (-H) := by rw [← Real.exp_add]; congr 1; ring + _ ≤ 1 / 100 := by + rw [Real.exp_neg, ← one_div] + exact one_div_le_one_div_of_le (by norm_num : (0 : ℝ) < 100) hexp100 + +theorem computed_seed_total_failure (N passes : ℕ) (hN : 0 < N) + (hell : 200 ≤ inputSmallLog N) (hpasses : passes ≤ inputHeight N) : + (1 / 100 : ℝ) + passes * Real.exp (10 * inputHeight N - (inputHeight N : ℝ) ^ 2) < 1 / 10 := by + have hlogs := inputSmallLog_bounds N hN + have hheight : 7 ≤ heightExponent N := by omega + have hH100 : 100 ≤ inputHeight N := (by norm_num : 100 ≤ (2 : ℕ) ^ 7).trans + (Nat.pow_le_pow_right (by decide : 0 < (2 : ℕ)) hheight) + have hpassR : (passes : ℝ) ≤ inputHeight N := by exact_mod_cast hpasses + have hbound := (mul_le_mul_of_nonneg_right hpassR + (Real.exp_pos (10 * inputHeight N - (inputHeight N : ℝ) ^ 2)).le).trans + (seed_pass_union_numeric (inputHeight N) (by exact_mod_cast hH100)) + linarith only [hbound] + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/SharedActions.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/SharedActions.lean new file mode 100644 index 0000000000000000000000000000000000000000..8cf55eacb49be4bddb7f8c798f99c88f75c1b57b --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/SharedActions.lean @@ -0,0 +1,111 @@ +import OAI.Combinatorics.EditApproximation.Geometry.ActualActionValues +import OAI.Combinatorics.EditApproximation.Geometry.Grid + +namespace OAI + +/-! Exact connection cancellation for shared-endpoint finite actions. -/ + +namespace EditApproximation + +theorem connectionBudget_ofFn_zero {n : ℕ} (M : ℕ) (states : Fin M → TargetInterval n) + (start finish : ℕ) + (hstart : ∀ i : Fin M, i.val = 0 → start = (states i).lo) + (hnext : ∀ i j : Fin M, j.val = i.val + 1 → (states i).hi = (states j).lo) + (hend : ∀ i : Fin M, i.val + 1 = M → (states i).hi = finish) + (hempty : M = 0 → start = finish) : + connectionBudget start (List.ofFn states) finish = 0 := by + induction M generalizing start with + | zero => simp only [List.ofFn_zero, connectionBudget, hempty rfl, Nat.dist_self] + | succ M ih => + rw [List.ofFn_succ, connectionBudget, hstart 0 rfl, Nat.dist_self, zero_add] + apply ih (fun i => states i.succ) (states 0).hi + · intro i hi + exact hnext 0 i.succ (by simp only [Fin.val_zero, Fin.val_succ]; omega) + · intro i j hij + exact hnext i.succ j.succ (by simp only [Fin.val_succ]; omega) + · intro i hi + exact hend i.succ (by simp only [Fin.val_succ]; omega) + · intro hM + exact hend 0 (by simp only [Fin.val_zero]; omega) + +theorem endpointActionConnection_zero {n M : ℕ} (hM : 0 < M) (q : TargetInterval n) + (states : Fin M → TargetInterval n) + (hstart : (states ⟨0, hM⟩).lo = q.lo) + (hend : (states ⟨M - 1, by omega⟩).hi = q.hi) + (hnext : ∀ i j : Fin M, j.val = i.val + 1 → (states i).hi = (states j).lo) : + endpointActionConnection q states = 0 := by + apply connectionBudget_ofFn_zero + · intro i hi + have heq : i = ⟨0, hM⟩ := Fin.ext hi + rw [heq] + exact hstart.symm + · exact hnext + · intro i hi + have heq : i = ⟨M - 1, by omega⟩ := Fin.ext (by change i.val = M - 1; omega) + rw [heq] + exact hend + · omega + +theorem round_shared_action {n M g : ℕ} (hM : 0 < M) (q : TargetInterval n) + (states : Fin M → TargetInterval n) + (hstart : (states ⟨0, hM⟩).lo = q.lo) + (hend : (states ⟨M - 1, by omega⟩).hi = q.hi) + (hnext : ∀ i j : Fin M, j.val = i.val + 1 → (states i).hi = (states j).lo) + (hqGrid : g ∣ q.lo ∧ g ∣ q.hi) : + endpointActionConnection q (fun i => roundInterval g (states i)) = 0 := by + apply endpointActionConnection_zero hM q + · change gridRound g (states ⟨0, hM⟩).lo = q.lo + rw [hstart, gridRound_of_dvd hqGrid.1] + · change gridRound g (states ⟨M - 1, by omega⟩).hi = q.hi + rw [hend, gridRound_of_dvd hqGrid.2] + · intro i j hij + exact roundInterval_shared (states i) (states j) (hnext i j hij) + +theorem zero_connection_target_eq {α : Type*} (target : List α) {M : ℕ} + (q : TargetInterval target.length) (states : Fin M → TargetInterval target.length) + (hconn : endpointActionConnection q states = 0) : + targetConcatenation target (List.ofFn states) = substring target q.lo q.hi := by + have h := target_connection_bound target (List.ofFn states) q + change EditDistortion.edit _ _ ≤ endpointActionConnection q states at h + rw [hconn] at h + exact (EditDistortion.cost_eq_zero_iff (s := true)).mp (Nat.eq_zero_of_le_zero h) + +theorem zero_connection_gap_sum {α : Type*} (source target : List α) {M : ℕ} + (hM : 0 < M) (parent : TargetInterval source.length) + (q : TargetInterval target.length) (states : Fin M → TargetInterval target.length) + (hconn : endpointActionConnection q states = 0) : + (∑ i, stateLengthGap + (substring source (sourceChild parent i).lo (sourceChild parent i).hi) target (states i)) = + stateLengthGap (substring source parent.lo parent.hi) target q := by + let piece := fun i : Fin M => + substring source (sourceChild parent i).lo (sourceChild parent i).hi + have hsource := congrArg List.length (sourceChild_partition source hM parent) + simp only [List.length_flatten, List.map_ofFn, List.sum_ofFn, Function.comp_def] at hsource + have htarget := congrArg List.length (zero_connection_target_eq target q states hconn) + simp only [targetConcatenation, List.length_flatten, List.map_ofFn, + List.sum_ofFn, Function.comp_def] at htarget + have hsourceR : (∑ i, ((piece i).length : ℝ)) = + (substring source parent.lo parent.hi).length := by exact_mod_cast hsource + have htargetR : (∑ i, ((substring target (states i).lo (states i).hi).length : ℝ)) = + (substring target q.lo q.hi).length := by exact_mod_cast htarget + simp only [stateLengthGap_actual, signedLengthGap, Finset.sum_sub_distrib] + rw [htargetR, hsourceR] + +theorem zero_connection_cost_sum_lower {α : Type*} (source target : List α) {M : ℕ} + (hM : 0 < M) (parent : TargetInterval source.length) + (q : TargetInterval target.length) (states : Fin M → TargetInterval target.length) + (hconn : endpointActionConnection q states = 0) : + (stateEditCost (substring source parent.lo parent.hi) target q : ℝ) ≤ + ∑ i, (stateEditCost + (substring source (sourceChild parent i).lo (sourceChild parent i).hi) target (states i) : ℝ) := by + have h := actual_endpoint_action_lower source target hM parent q states 1 le_rfl + (fun i s => (stateEditCost + (substring source (sourceChild parent i).lo (sourceChild parent i).hi) target s : ℝ)) + (by intro i; simp only [div_one, le_refl]) + (fun i => stateEditCost_length_lower _ _ _) + have hlower := (le_max_left _ _).trans h + simpa only [div_one, endpointActionValue, hconn, Nat.cast_zero, zero_add] using hlower + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/SharedGroupInputBudget.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/SharedGroupInputBudget.lean new file mode 100644 index 0000000000000000000000000000000000000000..962110ff6bce79e1af76222b97032bdd09a98723 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/SharedGroupInputBudget.lean @@ -0,0 +1,77 @@ +import OAI.Combinatorics.EditApproximation.Geometry.ActualRoundedGroupInputs +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! A pathwise finite cover for every shared group estimator's current +child inputs. Repeated samples and member uses are counted once. -/ + +namespace EditApproximation + +open Finset + + + +theorem groupQueriedChildLabels_card (M Q b : ℕ) (h : ℚ) + (draw : Fin (groupSampleCount M Q b h) → Fin M) : + (groupQueriedChildLabels M Q b h draw).card ≤ groupSampleCount M Q b h := by + unfold groupQueriedChildLabels + split_ifs with hexact + · simpa only [Finset.card_univ, Fintype.card_fin, hexact] using le_rfl (a := M) + · exact (Finset.card_image_le).trans_eq (by simp only [Finset.card_univ, Fintype.card_fin]) + + + +theorem actual_group_input_in_cover {α : Type*} (source target : List α) {M b P exponent : ℕ} + (parent : TargetInterval source.length) (tau a : ℚ) (F Q : ℕ) + (parentInitial : TargetInterval target.length → ℚ) + (child initial : Fin M → TargetInterval target.length → ℚ) (cell : ℕ × ℕ) + (member : UnskippedBand source target parent b P exponent tau F child initial) + (hb : 1 ≤ b) + (hcenter : member.center ∈ cellRepresentativeStates target.length P F b a parentInitial + ((2 : ℚ) ^ (-(exponent : ℤ))) cell) + (h : ℚ) (draw : Fin (groupSampleCount M Q b h) → Fin M) + (i : Fin M) (hi : i ∈ groupQueriedChildLabels M Q b h draw) (henvelope : member.envelope i = h) : + (i, member.rounded i) ∈ groupCurrentInputCover source target parent b exponent Q cell h draw := by + apply Finset.mem_biUnion.mpr + refine ⟨i, hi, Finset.mem_image.mpr ?_⟩ + exact ⟨member.rounded i, List.mem_toFinset.mpr + (actual_rounded_group_input_mem source target parent tau a F parentInitial child initial cell + member hb hcenter i h henvelope), rfl⟩ + +/-- One group and one envelope label use at most 624*M*Q*theta^-2 +distinct current child inputs, on every seed and every sample outcome. -/ +theorem groupCurrentInputCover_card {α : Type*} (source target : List α) {M b : ℕ} + (parent : TargetInterval source.length) (exponent Q : ℕ) (cell : ℕ × ℕ) (h : ℚ) + (hM : 0 < M) (hQ : 1 ≤ Q) (hb : 0 < b) (hh : 0 < h) (hfloor : (b : ℚ) / M ≤ h) + (draw : Fin (groupSampleCount M Q b h) → Fin M) : + ((groupCurrentInputCover source target parent b exponent Q cell h draw).card : ℚ) ≤ + 624 * M * Q * ((2 : ℚ) ^ exponent) ^ 2 := by + let labels := groupQueriedChildLabels M Q b h draw + let C : ℚ := 208 * ((2 : ℚ) ^ exponent) ^ 2 * (1 + b / h) + have hC : 0 ≤ C := by dsimp only [C]; positivity + have hlength (i : Fin M) : + ((groupRoundedStateList source target parent b exponent cell i h).length : ℚ) ≤ C := + groupRoundedStateList_length source target parent b exponent cell i h hh + have hcardN : (groupCurrentInputCover source target parent b exponent Q cell h draw).card ≤ + ∑ i ∈ labels, (groupRoundedStateList source target parent b exponent cell i h).length := by + apply Finset.card_biUnion_le.trans + apply Finset.sum_le_sum + intro i _ + exact Finset.card_image_le.trans (List.toFinset_card_le _) + have hcardR : ((groupCurrentInputCover source target parent b exponent Q cell h draw).card : ℚ) ≤ + ∑ i ∈ labels, ((groupRoundedStateList source target parent b exponent cell i h).length : ℚ) := by + exact_mod_cast hcardN + have hlabels : (labels.card : ℚ) ≤ groupSampleCount M Q b h := by + exact_mod_cast groupQueriedChildLabels_card M Q b h draw + calc + _ ≤ ∑ i ∈ labels, ((groupRoundedStateList source target parent b exponent cell i h).length : ℚ) := hcardR + _ ≤ ∑ _i ∈ labels, C := Finset.sum_le_sum (fun i _ => hlength i) + _ = (labels.card : ℚ) * C := by rw [Finset.sum_const, nsmul_eq_mul] + _ ≤ (groupSampleCount M Q b h : ℚ) * C := mul_le_mul_of_nonneg_right hlabels hC + _ ≤ _ := shared_rounded_inputs_bound hM hQ hb hh hfloor le_rfl + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/SourceErasure.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/SourceErasure.lean new file mode 100644 index 0000000000000000000000000000000000000000..7939363b07a956ff78d6edaeb05f380b01f0d7fe --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/SourceErasure.lean @@ -0,0 +1,90 @@ +import OAI.Combinatorics.EditApproximation.Geometry.SourceRankedProgram + +namespace OAI + +/-! Removing already fixed source answers is a proof operation on a +query. It preserves the table trace and separates source/table charges; +the implementation continues to cache and sample explicit source keys. -/ + +namespace EditApproximation.FiniteQuery + +variable {σ κ : Type*} + +def eraseSources (sourceAnswer : σ → ℚ) : FiniteQuery (Sum σ κ) → FiniteQuery κ + | .done value => .done value + | .read (.inl source) next => eraseSources sourceAnswer (next (sourceAnswer source)) + | .read (.inr table) next => .read table (fun answer => eraseSources sourceAnswer (next answer)) + + theorem eraseSources_value (sourceAnswer : σ → ℚ) (tableAnswer : κ → ℚ) + (query : FiniteQuery (Sum σ κ)) : + (eraseSources sourceAnswer query).value tableAnswer = + query.value (Sum.elim sourceAnswer tableAnswer) := by + induction query with + | done value => rfl + | read key next ih => + cases key with + | inl source => exact ih (sourceAnswer source) + | inr table => exact ih (tableAnswer table) + + theorem eraseSources_cost (sourceAnswer : σ → ℚ) (tableAnswer : κ → ℚ) + (tableWeight : κ → ℕ) (query : FiniteQuery (Sum σ κ)) : + (eraseSources sourceAnswer query).cost tableAnswer tableWeight = + query.cost (Sum.elim sourceAnswer tableAnswer) (Sum.elim (fun _ => 0) tableWeight) := by + induction query with + | done value => rfl + | read key next ih => + cases key with + | inl source => simpa only [eraseSources, cost, Sum.elim_inl, Nat.zero_add] using ih (sourceAnswer source) + | inr table => exact congrArg (tableWeight table + ·) (ih (tableAnswer table)) + + theorem eraseSources_keys_all (sourceAnswer : σ → ℚ) (tableAnswer : κ → ℚ) + (query : FiniteQuery (Sum σ κ)) (predicate : κ → Prop) + (hquery : ∀ key ∈ query.keys (Sum.elim sourceAnswer tableAnswer), + match key with | .inl _ => True | .inr table => predicate table) : + ∀ key ∈ (eraseSources sourceAnswer query).keys tableAnswer, predicate key := by + induction query with + | done value => intro key hk; exact False.elim (List.not_mem_nil hk) + | read key next ih => + cases key with + | inl source => + apply ih (sourceAnswer source) + intro key hk + exact hquery key (List.mem_cons_of_mem _ hk) + | inr table => + intro key hk + rcases List.mem_cons.mp hk with heq | hk + · subst key + exact hquery (.inr table) (List.mem_cons_self ..) + · apply ih (tableAnswer table) _ key hk + intro key hk + exact hquery key (List.mem_cons_of_mem _ hk) + + theorem cost_add_weights {ι : Type*} (answer : ι → ℚ) (left right : ι → ℕ) + (query : FiniteQuery ι) : + query.cost answer (fun key => left key + right key) = + query.cost answer left + query.cost answer right := by + induction query with + | done value => rfl + | read key next ih => simp only [cost, ih]; omega + + theorem cost_mul_weight {ι : Type*} (answer : ι → ℚ) (weight : ι → ℕ) + (multiplier : ℕ) (query : FiniteQuery ι) : + query.cost answer (fun key => multiplier * weight key) = + multiplier * query.cost answer weight := by + induction query with + | done value => simp only [cost, Nat.mul_zero] + | read key next ih => simp only [cost, ih, Nat.mul_add] + + theorem cost_source_table (sourceAnswer : σ → ℚ) (tableAnswer : κ → ℚ) + (sourceWeight : σ → ℕ) (tableWeight : κ → ℕ) (query : FiniteQuery (Sum σ κ)) : + query.cost (Sum.elim sourceAnswer tableAnswer) (Sum.elim sourceWeight tableWeight) = + query.cost (Sum.elim sourceAnswer tableAnswer) (Sum.elim sourceWeight (fun _ => 0)) + + (eraseSources sourceAnswer query).cost tableAnswer tableWeight := by + rw [eraseSources_cost, ← cost_add_weights] + congr 1 + funext key + cases key <;> simp + +end EditApproximation.FiniteQuery + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/SourcePrefixes.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/SourcePrefixes.lean new file mode 100644 index 0000000000000000000000000000000000000000..96a451973da552b03333ff6e95008ef183c4e888 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/SourcePrefixes.lean @@ -0,0 +1,35 @@ +import OAI.Combinatorics.EditApproximation.Geometry.BalancedIntervals + +namespace OAI + +/-! Actual prefix lengths of the labeled balanced source partition. -/ + +namespace EditApproximation + +theorem sourceChildrenList_eq_balancedPieces {α : Type*} (source : List α) + {M : ℕ} (parent : TargetInterval source.length) : + (List.ofFn fun i : Fin M => + substring source (sourceChild parent i).lo (sourceChild parent i).hi) = + balancedPieces source parent.lo (parent.hi - parent.lo) M := by + apply List.ext_getElem + · simp only [List.length_ofFn, balancedPieces_length] + · intro i hi hj + simp only [List.getElem_ofFn, balancedPieces, List.getElem_map, List.getElem_range, sourceChild] + +theorem sourceChildren_prefix_length {α : Type*} (source : List α) + {M : ℕ} (hM : 0 < M) (parent : TargetInterval source.length) (j : ℕ) (hj : j ≤ M) : + ((List.ofFn fun i : Fin M => + substring source (sourceChild parent i).lo (sourceChild parent i).hi).take j).flatten.length = + balancedCut parent.lo (parent.hi - parent.lo) M j - parent.lo := by + rw [sourceChildrenList_eq_balancedPieces] + simp only [balancedPieces, ← List.map_take, List.take_range, Nat.min_eq_left hj] + rw [balancedPieces_prefix] + have hcut : balancedCut parent.lo (parent.hi - parent.lo) M j ≤ source.length := by + have h := (balancedCut_bounds parent.lo (parent.hi - parent.lo) M j hM hj).2 + rw [Nat.add_sub_of_le parent.ordered] at h + exact h.trans parent.valid + simp only [substring, List.length_drop, List.length_take, Nat.min_eq_left hcut] + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/SourceRankedEncoding.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/SourceRankedEncoding.lean new file mode 100644 index 0000000000000000000000000000000000000000..75040ce9b9b852efbeb1a26263a6f15ec433dde7 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/SourceRankedEncoding.lean @@ -0,0 +1,68 @@ +import OAI.Combinatorics.EditApproximation.Geometry.SourceRankedProgram +import Mathlib.Data.Nat.Log +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! An explicit parity tag separates source coordinates and table keys. +The code is computed from coordinates without enumerating the key type. -/ + +namespace EditApproximation.SourceRanked + +variable {σ κ : Type*} + + + +def keyCapacity (sourceCapacity tableCapacity : ℕ) : ℕ := + 2 * (sourceCapacity + tableCapacity) + +def keyBits (sourceCapacity tableCapacity : ℕ) : ℕ := + Nat.clog 2 (keyCapacity sourceCapacity tableCapacity + 1) + + theorem keyCode_injective (sourceCode : σ → ℕ) (tableCode : κ → ℕ) + (hs : Function.Injective sourceCode) (ht : Function.Injective tableCode) : + Function.Injective (keyCode sourceCode tableCode) := by + intro left right h + cases left with + | inl left => + cases right with + | inl right => + have heq : sourceCode left = sourceCode right := by + change 2 * sourceCode left = 2 * sourceCode right at h + omega + exact congrArg Sum.inl (hs heq) + | inr right => + change 2 * sourceCode left = 2 * tableCode right + 1 at h + omega + | inr left => + cases right with + | inl right => + change 2 * tableCode left + 1 = 2 * sourceCode right at h + omega + | inr right => + have heq : tableCode left = tableCode right := by + change 2 * tableCode left + 1 = 2 * tableCode right + 1 at h + omega + exact congrArg Sum.inr (ht heq) + + theorem keyCode_bound (sourceCode : σ → ℕ) (tableCode : κ → ℕ) + (sourceCapacity tableCapacity : ℕ) + (hs : ∀ source, sourceCode source < sourceCapacity) + (ht : ∀ table, tableCode table < tableCapacity) (key : Sum σ κ) : + keyCode sourceCode tableCode key < keyCapacity sourceCapacity tableCapacity := by + cases key with + | inl source => have := hs source; dsimp [keyCode, keyCapacity]; omega + | inr table => have := ht table; dsimp [keyCode, keyCapacity]; omega + + theorem keyCode_fits (sourceCode : σ → ℕ) (tableCode : κ → ℕ) + (sourceCapacity tableCapacity : ℕ) + (hs : ∀ source, sourceCode source < sourceCapacity) + (ht : ∀ table, tableCode table < tableCapacity) (key : Sum σ κ) : + keyCode sourceCode tableCode key < 2 ^ keyBits sourceCapacity tableCapacity := + (keyCode_bound sourceCode tableCode sourceCapacity tableCapacity hs ht key).trans_le + ((Nat.le_succ _).trans (Nat.le_pow_clog (by decide : 1 < 2) _)) + +end EditApproximation.SourceRanked + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/SourceRankedKeys.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/SourceRankedKeys.lean new file mode 100644 index 0000000000000000000000000000000000000000..7f745e5ff532343056861178a3591e217f2296eb --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/SourceRankedKeys.lean @@ -0,0 +1,69 @@ +import OAI.Combinatorics.EditApproximation.Geometry.RankedMemoKeys +import OAI.Combinatorics.EditApproximation.Geometry.SourceRankedWork + +namespace OAI + +namespace EditApproximation.SourceRanked + +variable {σ κ : Type*} (tableRank : κ → ℕ) + (tableBody : (parent : κ) → FiniteQuery (Sum σ {key : κ // tableRank key < tableRank parent})) + (sourceValue : σ → ℚ) (tableValue : κ → ℚ) + (hbody : ∀ key, (tableBody key).value (Sum.elim sourceValue (fun next => tableValue next.val)) = + tableValue key) + +include hbody + +/-- Forgetting source leaves preserves every table request, including +those which the mixed memo execution first encounters after a cache hit. -/ +theorem uncachedKeys_table_mem (root item : κ) + (hitem : Sum.inr item ∈ rankedUncachedKeys (rank tableRank) + (body tableRank tableBody sourceValue) (.inr root)) : + item ∈ rankedUncachedKeys tableRank (projectedBody tableRank tableBody sourceValue) root := by + let mixed := body tableRank tableBody sourceValue + let projected := projectedBody tableRank tableBody sourceValue + have hvm (key : Sum σ κ) : rankedProgramValue (rank tableRank) mixed key = + value sourceValue tableValue key := program_value tableRank tableBody sourceValue tableValue hbody key + have hvp (key : κ) : rankedProgramValue tableRank projected key = tableValue key := + projectedProgram_value tableRank tableBody sourceValue tableValue hbody key + have hall : ∀ level root, tableRank root = level → ∀ item, + Sum.inr item ∈ rankedUncachedKeys (rank tableRank) mixed (.inr root) → + item ∈ rankedUncachedKeys tableRank projected root := by + intro level + induction level using Nat.strong_induction_on with + | h level ih => + intro root hlevel item hm + rw [rankedUncachedKeys] at hm ⊢ + rcases List.mem_cons.mp hm with heq | hm + · exact List.mem_cons.mpr (.inl (Sum.inr.inj heq)) + · have hanswer : + (fun next => rankedProgramValue (rank tableRank) mixed next.val) ∘ child tableRank root = + Sum.elim sourceValue (fun next => tableValue next.val) := by + funext next + rw [Function.comp_apply, hvm] + cases next <;> rfl + change Sum.inr item ∈ ((mixed (.inr root)).keys _).flatMap _ at hm + dsimp only [mixed, body] at hm + rw [FiniteQuery.mapKeys_keys, hanswer] at hm + obtain ⟨next, hn, hi⟩ := List.mem_flatMap.mp hm + obtain ⟨raw, hr, rfl⟩ := List.mem_map.mp hn + cases raw with + | inl scalar => + change Sum.inr item ∈ rankedUncachedKeys (rank tableRank) mixed (.inl scalar) at hi + rw [rankedUncachedKeys] at hi + simp only [mixed, body, FiniteQuery.keys, List.flatMap_nil, + List.mem_cons, Sum.inr_ne_inl, List.not_mem_nil, or_false] at hi + | inr next => + have ht := (FiniteQuery.eraseSources_inr_mem_iff sourceValue + (fun child => tableValue child.val) (tableBody root) next).mp hr + have hi' := ih (tableRank next.val) (hlevel ▸ next.property) next.val rfl item hi + apply List.mem_cons_of_mem + apply List.mem_flatMap.mpr + refine ⟨next, ?_, hi'⟩ + change next ∈ (FiniteQuery.eraseSources sourceValue (tableBody root)).keys + (fun child => rankedProgramValue tableRank projected child.val) + simpa only [hvp] using ht + exact hall (tableRank root) root rfl item hitem + +end EditApproximation.SourceRanked + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/SourceRankedProgram.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/SourceRankedProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..e69e19f465d8715cae1a6c184b8277dcfe44c517 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/SourceRankedProgram.lean @@ -0,0 +1,70 @@ +import OAI.Combinatorics.EditApproximation.Probability.FiniteQueryRestriction +import OAI.Combinatorics.EditApproximation.Geometry.RankedMemoSimulation +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Random source coordinates and recursive table entries share the same +memo evaluator. Source coordinates have rank zero; each table rank is +shifted by one. Consequently repeated source reads reuse their stored draw. -/ + +namespace EditApproximation + +namespace SourceRanked + +variable {σ κ : Type*} + + + + + + + +def value (sourceValue : σ → ℚ) (tableValue : κ → ℚ) : Sum σ κ → ℚ := + Sum.elim sourceValue tableValue + + theorem body_value (tableRank : κ → ℕ) + (tableBody : (parent : κ) → FiniteQuery (Sum σ {key : κ // tableRank key < tableRank parent})) + (sourceValue : σ → ℚ) (tableValue : κ → ℚ) + (hbody : ∀ key, (tableBody key).value (Sum.elim sourceValue (fun next => tableValue next.val)) = + tableValue key) (key : Sum σ κ) : + (body tableRank tableBody sourceValue key).value + (fun next => value sourceValue tableValue next.val) = value sourceValue tableValue key := by + cases key with + | inl source => rfl + | inr table => + rw [body, FiniteQuery.mapKeys_value] + have horacle : (fun next => value sourceValue tableValue next.val) ∘ child tableRank table = + Sum.elim sourceValue (fun next => tableValue next.val) := by + funext next + cases next <;> rfl + rw [horacle] + exact hbody table + + theorem program_value (tableRank : κ → ℕ) + (tableBody : (parent : κ) → FiniteQuery (Sum σ {key : κ // tableRank key < tableRank parent})) + (sourceValue : σ → ℚ) (tableValue : κ → ℚ) + (hbody : ∀ key, (tableBody key).value (Sum.elim sourceValue (fun next => tableValue next.val)) = + tableValue key) (key : Sum σ κ) : + rankedProgramValue (rank tableRank) (body tableRank tableBody sourceValue) key = + value sourceValue tableValue key := + rankedProgramValue_eq _ _ _ (body_value tableRank tableBody sourceValue tableValue hbody) key + + theorem memo_value (tableRank : κ → ℕ) + (tableBody : (parent : κ) → FiniteQuery (Sum σ {key : κ // tableRank key < tableRank parent})) + (sourceValue : σ → ℚ) (tableValue : κ → ℚ) + (hbody : ∀ key, (tableBody key).value (Sum.elim sourceValue (fun next => tableValue next.val)) = + tableValue key) (bits : ℕ) (encode : Sum σ κ → ℕ) + (hinjective : Function.Injective encode) (hbounded : ∀ key, encode key < 2 ^ bits) + (key : Sum σ κ) : + (rankedMemoEvaluate (rank tableRank) (body tableRank tableBody sourceValue) + bits encode key .empty).value = value sourceValue tableValue key := by + rw [rankedMemoEvaluate_empty _ _ bits encode hinjective hbounded] + exact program_value tableRank tableBody sourceValue tableValue hbody key + +end SourceRanked + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/SourceRankedRestriction.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/SourceRankedRestriction.lean new file mode 100644 index 0000000000000000000000000000000000000000..42e9ef61cf572d3cbd9517786697f4c624f9be8b --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/SourceRankedRestriction.lean @@ -0,0 +1,109 @@ +import OAI.Combinatorics.EditApproximation.Geometry.SourceRankedProgram +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Restrict only the recursive table keys of a mixed source/table query. +The source reads remain explicit. This preserves the finite cache domain +without materializing any counterfactual table. -/ + +namespace EditApproximation.SourceRanked + +variable {σ κ : Type*} (tableRank : κ → ℕ) (supported : κ → Prop) + + + + + + + + theorem restrictBody_value + (tableBody : (parent : κ) → FiniteQuery (Sum σ {key : κ // tableRank key < tableRank parent})) + (sourceValue : σ → ℚ) (tableValue : κ → ℚ) (parent : {key : κ // supported key}) + (hkeys : ∀ key ∈ (tableBody parent.val).keys (Sum.elim sourceValue (fun key => tableValue key.val)), + supportedChild tableRank supported parent.val key) : + (restrictBody tableRank supported tableBody parent).value + (Sum.elim sourceValue (fun key => tableValue key.val.val)) = + (tableBody parent.val).value (Sum.elim sourceValue (fun key => tableValue key.val)) := by + classical + unfold restrictBody + rw [FiniteQuery.mapKeys_value] + have horacle : + (Sum.elim sourceValue (fun key => tableValue key.val.val)) ∘ + supportedChildMap tableRank supported parent = + (fun key => (Sum.elim sourceValue (fun key => tableValue key.val)) key.val) := by + funext key + rcases key with ⟨key, hs⟩ + cases key <;> rfl + rw [horacle] + exact FiniteQuery.restrict_value _ _ _ hkeys + + theorem restrictBody_cost + (tableBody : (parent : κ) → FiniteQuery (Sum σ {key : κ // tableRank key < tableRank parent})) + (sourceValue : σ → ℚ) (tableValue : κ → ℚ) (sourceWeight : σ → ℕ) (tableWeight : κ → ℕ) + (parent : {key : κ // supported key}) + (hkeys : ∀ key ∈ (tableBody parent.val).keys (Sum.elim sourceValue (fun key => tableValue key.val)), + supportedChild tableRank supported parent.val key) : + (restrictBody tableRank supported tableBody parent).cost + (Sum.elim sourceValue (fun key => tableValue key.val.val)) + (Sum.elim sourceWeight (fun key => tableWeight key.val.val)) = + (tableBody parent.val).cost (Sum.elim sourceValue (fun key => tableValue key.val)) + (Sum.elim sourceWeight (fun key => tableWeight key.val)) := by + classical + unfold restrictBody + rw [FiniteQuery.mapKeys_cost] + have horacle : + (Sum.elim sourceValue (fun key => tableValue key.val.val)) ∘ + supportedChildMap tableRank supported parent = + (fun key => (Sum.elim sourceValue (fun key => tableValue key.val)) key.val) := by + funext key + rcases key with ⟨key, hs⟩ + cases key <;> rfl + have hweight : + (Sum.elim sourceWeight (fun key => tableWeight key.val.val)) ∘ + supportedChildMap tableRank supported parent = + (fun key => (Sum.elim sourceWeight (fun key => tableWeight key.val)) key.val) := by + funext key + rcases key with ⟨key, hs⟩ + cases key <;> rfl + rw [horacle, hweight] + exact FiniteQuery.restrict_cost _ _ _ _ hkeys + + theorem restrictBody_keys_all + (tableBody : (parent : κ) → FiniteQuery (Sum σ {key : κ // tableRank key < tableRank parent})) + (sourceValue : σ → ℚ) (tableValue : κ → ℚ) + (sourcePredicate : σ → Prop) (tablePredicate : κ → Prop) + (parent : {key : κ // supported key}) + (hkeys : ∀ key ∈ (tableBody parent.val).keys (Sum.elim sourceValue (fun key => tableValue key.val)), + supportedChild tableRank supported parent.val key) + (hall : ∀ key ∈ (tableBody parent.val).keys (Sum.elim sourceValue (fun key => tableValue key.val)), + match key with | .inl source => sourcePredicate source | .inr table => tablePredicate table.val) : + ∀ key ∈ (restrictBody tableRank supported tableBody parent).keys + (Sum.elim sourceValue (fun key => tableValue key.val.val)), + match key with | .inl source => sourcePredicate source | .inr table => tablePredicate table.val.val := by + classical + unfold restrictBody + rw [FiniteQuery.mapKeys_keys] + intro key hk + obtain ⟨small, hs, rfl⟩ := List.mem_map.mp hk + have horacle : + (Sum.elim sourceValue (fun key => tableValue key.val.val)) ∘ + supportedChildMap tableRank supported parent = + (fun key => (Sum.elim sourceValue (fun key => tableValue key.val)) key.val) := by + funext key + rcases key with ⟨key, hp⟩ + cases key <;> rfl + rw [horacle] at hs + have hmem : small.val ∈ ((FiniteQuery.restrict + (supportedChild tableRank supported parent.val) (tableBody parent.val)).keys + (fun key => (Sum.elim sourceValue (fun key => tableValue key.val)) key.val)).map Subtype.val := + List.mem_map.mpr ⟨small, hs, rfl⟩ + rw [FiniteQuery.restrict_keys _ _ _ hkeys] at hmem + have h := hall small.val hmem + rcases small with ⟨small, hp⟩ + cases small <;> exact h + +end EditApproximation.SourceRanked + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/SourceRankedWork.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/SourceRankedWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..e496308bb2abeb84da00caafcd50f2a453f27288 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/SourceRankedWork.lean @@ -0,0 +1,126 @@ +import OAI.Combinatorics.EditApproximation.Geometry.SourceErasure +import OAI.Combinatorics.EditApproximation.Probability.FiniteQueryCostOrder + +namespace OAI + +/-! Source leaves add only their executed read count to each table body. +Projecting them away preserves the table dependency program, so a uniform +local source budget multiplies its uncached request bound. -/ + +namespace EditApproximation.SourceRanked + +variable {σ κ : Type*} (tableRank : κ → ℕ) + (tableBody : (parent : κ) → FiniteQuery (Sum σ {key : κ // tableRank key < tableRank parent})) + (sourceValue : σ → ℚ) (tableValue : κ → ℚ) + (hbody : ∀ key, (tableBody key).value (Sum.elim sourceValue (fun next => tableValue next.val)) = + tableValue key) + +def projectedBody (key : κ) : FiniteQuery {next : κ // tableRank next < tableRank key} := + FiniteQuery.eraseSources sourceValue (tableBody key) + +include hbody in + theorem projectedBody_value (key : κ) : + (projectedBody tableRank tableBody sourceValue key).value (fun next => tableValue next.val) = + tableValue key := + (FiniteQuery.eraseSources_value sourceValue _ (tableBody key)).trans (hbody key) + +include hbody in + theorem projectedProgram_value (key : κ) : + rankedProgramValue tableRank (projectedBody tableRank tableBody sourceValue) key = tableValue key := + rankedProgramValue_eq tableRank _ tableValue + (projectedBody_value tableRank tableBody sourceValue tableValue hbody) key + +include hbody in + theorem uncachedCalls_le_source_factor (sourceBudget : ℕ) + (hsource : ∀ key, (tableBody key).cost + (Sum.elim sourceValue (fun next => tableValue next.val)) (Sum.elim (fun _ => 1) (fun _ => 0)) ≤ + sourceBudget) (key : κ) : + rankedUncachedCalls (rank tableRank) (body tableRank tableBody sourceValue) (.inr key) ≤ + (sourceBudget + 1) * + rankedUncachedCalls tableRank (projectedBody tableRank tableBody sourceValue) key := by + let mixed := body tableRank tableBody sourceValue + let projected := projectedBody tableRank tableBody sourceValue + let W := rankedUncachedCalls tableRank projected + have hvalue (next : Sum σ κ) : + rankedProgramValue (rank tableRank) mixed next = value sourceValue tableValue next := + program_value tableRank tableBody sourceValue tableValue hbody next + have hpvalue (next : κ) : rankedProgramValue tableRank projected next = tableValue next := + projectedProgram_value tableRank tableBody sourceValue tableValue hbody next + have hW (parent : κ) : W parent = (projected parent).cost + (fun next => tableValue next.val) (fun next => W next.val) + 1 := by + dsimp only [W] + rw [rankedUncachedCalls] + simp only [hpvalue] + have hall : ∀ level parent, tableRank parent = level → + rankedUncachedCalls (rank tableRank) mixed (.inr parent) ≤ (sourceBudget + 1) * W parent := by + intro level + induction level using Nat.strong_induction_on with + | h level ih => + intro parent hlevel + have horacle : + (fun next => rankedProgramValue (rank tableRank) mixed next.val) ∘ child tableRank parent = + Sum.elim sourceValue (fun next => tableValue next.val) := by + funext next + rw [Function.comp_apply, hvalue] + cases next <;> rfl + have hcost := FiniteQuery.cost_mono_weights + (Sum.elim sourceValue (fun next => tableValue next.val)) (tableBody parent) + (fun next => rankedUncachedCalls (rank tableRank) mixed (child tableRank parent next).val) + (Sum.elim (fun _ => 1) (fun next => (sourceBudget + 1) * W next.val)) (by + intro next + cases next with + | inl source => + change rankedUncachedCalls (rank tableRank) mixed (.inl source) ≤ 1 + rw [rankedUncachedCalls] + exact le_rfl + | inr next => + exact ih (tableRank next.val) (hlevel ▸ next.property) next.val rfl) + have hsplit : (tableBody parent).cost + (Sum.elim sourceValue (fun next => tableValue next.val)) + (Sum.elim (fun _ => 1) (fun next => (sourceBudget + 1) * W next.val)) = + (tableBody parent).cost (Sum.elim sourceValue (fun next => tableValue next.val)) + (Sum.elim (fun _ => 1) (fun _ => 0)) + + (sourceBudget + 1) * (projected parent).cost + (fun next => tableValue next.val) (fun next => W next.val) := by + rw [FiniteQuery.cost_source_table, FiniteQuery.cost_mul_weight] + rfl + change rankedUncachedCalls (rank tableRank) (body tableRank tableBody sourceValue) (.inr parent) ≤ _ + rw [rankedUncachedCalls] + change (FiniteQuery.mapKeys (child tableRank parent) (tableBody parent)).cost + (fun next => rankedProgramValue (rank tableRank) mixed next.val) + (fun next => rankedUncachedCalls (rank tableRank) mixed next.val) + 1 ≤ _ + rw [FiniteQuery.mapKeys_cost, horacle] + calc + _ ≤ (tableBody parent).cost + (Sum.elim sourceValue (fun next => tableValue next.val)) + (Sum.elim (fun _ => 1) (fun next => (sourceBudget + 1) * W next.val)) + 1 := + Nat.add_le_add_right hcost 1 + _ = (tableBody parent).cost (Sum.elim sourceValue (fun next => tableValue next.val)) + (Sum.elim (fun _ => 1) (fun _ => 0)) + + (sourceBudget + 1) * (projected parent).cost + (fun next => tableValue next.val) (fun next => W next.val) + 1 := by rw [hsplit] + _ ≤ sourceBudget + (sourceBudget + 1) * (projected parent).cost + (fun next => tableValue next.val) (fun next => W next.val) + 1 := by + exact Nat.add_le_add_right (Nat.add_le_add_right (hsource parent) _) _ + _ = (sourceBudget + 1) * W parent := by rw [hW]; ring + exact hall (tableRank key) key rfl + +include hbody in + theorem memo_requests_le_source_factor (sourceBudget : ℕ) + (hsource : ∀ key, (tableBody key).cost + (Sum.elim sourceValue (fun next => tableValue next.val)) (Sum.elim (fun _ => 1) (fun _ => 0)) ≤ + sourceBudget) + (bits : ℕ) (encode : Sum σ κ → ℕ) (hinjective : Function.Injective encode) + (hbounded : ∀ key, encode key < 2 ^ bits) (key : κ) : + (rankedMemoEvaluate (rank tableRank) (body tableRank tableBody sourceValue) + bits encode (.inr key) .empty).requests ≤ + (sourceBudget + 1) * + rankedUncachedCalls tableRank (projectedBody tableRank tableBody sourceValue) key := + (rankedMemoEvaluate_requests_le _ _ bits encode hinjective hbounded (.inr key) .empty + (memoSound_empty _ _ _)).trans + (uncachedCalls_le_source_factor tableRank tableBody sourceValue tableValue hbody + sourceBudget hsource key) + +end EditApproximation.SourceRanked + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/StateDomain.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/StateDomain.lean new file mode 100644 index 0000000000000000000000000000000000000000..31f81dc58a871ca7ea2e25c8bb94879b3d4838ba --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/StateDomain.lean @@ -0,0 +1,75 @@ +import OAI.Combinatorics.EditApproximation.Geometry.DomainCounts +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! +# The actual finite labeled state type + +Physical nodes are retained as depth/path pairs. In particular, repeated +empty intervals remain distinct entries of the seed and refinement tables. +-/ + +namespace EditApproximation + +open Finset + + + + + +theorem targetInterval_card_le (n : ℕ) : + Fintype.card (TargetInterval n) ≤ (targetStates n).length := by + exact (targetStates n).toFinset_card_le + + + + + +abbrev LabeledEntry (M nx ny : ℕ) := + PhysicalNode M (intervalTreeDepth M nx) × TargetInterval ny + +def entrySourceInterval {M nx ny : ℕ} (entry : LabeledEntry M nx ny) : TargetInterval nx := + sourceIntervalAt M nx entry.1.1.val entry.1.2 + +def entrySource {α : Type*} (M : ℕ) (source : List α) {ny : ℕ} + (entry : LabeledEntry M source.length ny) : List α := + substring source (entrySourceInterval entry).lo (entrySourceInterval entry).hi + +def entryTarget {α : Type*} (target : List α) {M nx : ℕ} + (entry : LabeledEntry M nx target.length) : List α := + substring target entry.2.lo entry.2.hi + +theorem physicalNode_card (M J : ℕ) : + Fintype.card (PhysicalNode M J) = + ∑ d ∈ range (J + 1), Fintype.card (TreeLayer M d) := by + rw [Fintype.card_sigma] + rw [sum_fin_eq_sum_range] + apply sum_congr rfl + intro d hd + rw [dite_eq_left (mem_range.mp hd)] + +theorem labeledEntry_card_le (M nx ny : ℕ) : + Fintype.card (LabeledEntry M nx ny) ≤ labeledStateCount M nx ny := by + rw [Fintype.card_prod, physicalNode_card] + exact Nat.mul_le_mul_left _ (targetInterval_card_le ny) + +theorem computed_labeledEntry_card_le (N nx ny : ℕ) (hN : 0 < N) + (hnx : nx ≤ N) (hny : ny ≤ N) (hell : 200 ≤ inputSmallLog N) : + Fintype.card (LabeledEntry (integerParameters N).M nx ny) ≤ 2 ^ (5 * inputHeight N) := + (labeledEntry_card_le _ _ _).trans (computed_labeledStateCount_le N nx ny hN hnx hny hell) + +theorem entrySource_length_le {α : Type*} (M : ℕ) (source : List α) {ny : ℕ} + (entry : LabeledEntry M source.length ny) : (entrySource M source entry).length ≤ source.length := by + simp only [entrySource, substring, List.length_drop, List.length_take] + exact (Nat.sub_le _ _).trans (min_le_right _ _) + +theorem entryTarget_length_le {α : Type*} (target : List α) {M nx : ℕ} + (entry : LabeledEntry M nx target.length) : (entryTarget target entry).length ≤ target.length := by + simp only [entryTarget, substring, List.length_drop, List.length_take] + exact (Nat.sub_le _ _).trans (min_le_right _ _) + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/StateGeometry.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/StateGeometry.lean new file mode 100644 index 0000000000000000000000000000000000000000..aabb2a415c7ab54ab2e5205e60e0b71c175220bb --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/StateGeometry.lean @@ -0,0 +1,93 @@ +import OAI.Combinatorics.EditApproximation.Geometry.Connections +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! +# The finite domain of valid target states + +The endpoint domain is enumerated by actual bounded natural loops. A +state's true cost and signed length gap use the stored target substring. +-/ + +namespace EditApproximation + +open EditDistortion + + + + + +theorem targetStates_complete (n : ℕ) (q : TargetInterval n) : q ∈ targetStates n := by + apply List.mem_flatMap.mpr + refine ⟨q.lo, List.mem_range.mpr (Nat.lt_succ_of_le (q.ordered.trans q.valid)), ?_⟩ + apply List.mem_filterMap.mpr + refine ⟨q.hi, List.mem_range.mpr (Nat.lt_succ_of_le q.valid), ?_⟩ + rw [makeTargetState, dite_eq_left (show q.lo ≤ q.hi ∧ q.hi ≤ n from ⟨q.ordered, q.valid⟩)] + + + +theorem natural_distance_cast (a b : ℕ) : |(a : ℝ) - b| = (Nat.dist a b : ℝ) := by + rcases le_total a b with h | h + · have hR : (a : ℝ) ≤ b := by exact_mod_cast h + rw [Nat.dist_eq_sub_of_le h, Nat.cast_sub h, abs_of_nonpos (sub_nonpos.mpr hR)] + ring + · have hR : (b : ℝ) ≤ a := by exact_mod_cast h + rw [Nat.dist_eq_sub_of_le_right h, Nat.cast_sub h, abs_of_nonneg (sub_nonneg.mpr hR)] + +noncomputable def stateEditCost {α : Type*} (source target : List α) (q : TargetInterval target.length) : ℕ := + edit source (substring target q.lo q.hi) + +def stateLengthGap {α : Type*} (source target : List α) (q : TargetInterval target.length) : ℝ := + (q.hi : ℝ) - q.lo - source.length + +theorem stateLengthGap_actual {α : Type*} (source target : List α) + (q : TargetInterval target.length) : + stateLengthGap source target q = signedLengthGap source (substring target q.lo q.hi) := by + have hlength : (substring target q.lo q.hi).length = q.hi - q.lo := by + simp only [substring, List.length_drop, List.length_take, Nat.min_eq_left q.valid] + unfold stateLengthGap signedLengthGap + rw [hlength, Nat.cast_sub q.ordered] + +theorem stateEditCost_length_lower {α : Type*} (source target : List α) + (q : TargetInterval target.length) : + |stateLengthGap source target q| ≤ stateEditCost source target q := by + rw [stateLengthGap_actual] + exact abs_length_gap_le_edit source (substring target q.lo q.hi) + +theorem stateEditCost_spatial {α : Type*} (source target : List α) + (q r : TargetInterval target.length) : + stateEditCost source target q ≤ stateEditCost source target r + targetEndpointDistance q r := by + have hmove := edit_substring_endpoints_le target r.lo r.hi q.lo q.hi + have htriangle := cost_triangle (s := true) source + (substring target r.lo r.hi) (substring target q.lo q.hi) + change edit source (substring target q.lo q.hi) ≤ + edit source (substring target r.lo r.hi) + edit (substring target r.lo r.hi) (substring target q.lo q.hi) + at htriangle + change edit source (substring target q.lo q.hi) ≤ + edit source (substring target r.lo r.hi) + (Nat.dist q.lo r.lo + Nat.dist q.hi r.hi) + rw [Nat.dist_comm r.lo q.lo, Nat.dist_comm r.hi q.hi] at hmove + omega + +theorem stateLengthGap_spatial {α : Type*} (source target : List α) + (q r : TargetInterval target.length) : + |stateLengthGap source target q| ≤ |stateLengthGap source target r| + targetEndpointDistance q r := by + have hlo : |(q.lo : ℝ) - r.lo| = Nat.dist q.lo r.lo := by + exact natural_distance_cast q.lo r.lo + have hhi : |(q.hi : ℝ) - r.hi| = Nat.dist q.hi r.hi := by + exact natural_distance_cast q.hi r.hi + have hdiff : stateLengthGap source target q - stateLengthGap source target r = + ((q.hi : ℝ) - r.hi) - ((q.lo : ℝ) - r.lo) := by unfold stateLengthGap; ring + have hmetric : |stateLengthGap source target q - stateLengthGap source target r| ≤ + (targetEndpointDistance q r : ℝ) := by + rw [hdiff] + have habs := abs_sub ((q.hi : ℝ) - r.hi) ((q.lo : ℝ) - r.lo) + rw [hhi, hlo] at habs + simpa only [targetEndpointDistance, Nat.cast_add, add_comm] using habs + have h := (abs_sub_abs_le_abs_sub _ _).trans hmetric + linarith + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/SubexponentialTransfer.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/SubexponentialTransfer.lean new file mode 100644 index 0000000000000000000000000000000000000000..fbc58fda30543318418675279cf7fca614c3b24d --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/SubexponentialTransfer.lean @@ -0,0 +1,100 @@ +import OAI.Combinatorics.EditApproximation.Geometry.ParameterDependencyAsymptotics +import OAI.Combinatorics.EditApproximation.Coarse.CoarseWorkAsymptotics + +namespace OAI + +/-! Conversion from the computed-height bounds to asymptotics in the actual +input length. The bounds concern scalar envelopes, not an uncharged program. -/ + +namespace EditApproximation + +open Filter +open scoped Topology + +theorem fixed_accuracy_large_branch_eventually (epsilon : ℚ) (hepsilon : 0 < epsilon) : + ∀ᶠ N in atTop, largeAccuracyInput N epsilon := by + filter_upwards [eventually_ge_atTop (accuracyCutoff epsilon)] with N hN + exact accuracyCutoff_sufficient N epsilon hepsilon hN + +theorem subexponential_height_to_input (f : ℕ → ℝ) + (hf : Tendsto (fun N => f N / inputHeight N) atTop (𝓝 0)) + (epsilon : ℝ) (hepsilon : 0 < epsilon) : + ∀ᶠ N in atTop, Real.exp (f N) ≤ (N + 2 : ℝ) ^ epsilon := by + have hlogtwo : 0 < Real.log 2 := Real.log_pos (by norm_num) + have hsmall := hf.eventually (gt_mem_nhds + (show (0 : ℝ) < epsilon * Real.log 2 / 4 by positivity)) + filter_upwards [hsmall, eventually_ge_atTop 1] with N hsmall hN + have hH : (0 : ℝ) < inputHeight N := by exact_mod_cast Nat.two_pow_pos (heightExponent N) + have hfN : f N ≤ (epsilon * Real.log 2 / 4) * inputHeight N := + ((div_lt_iff₀ hH).1 hsmall).le + have hheight := (height_log_sandwich N hN).2 + have hscaled := mul_le_mul_of_nonneg_left hheight + (show (0 : ℝ) ≤ epsilon * Real.log 2 / 4 by positivity) + have hcancel : (epsilon * Real.log 2 / 4) * + ((4 / Real.log 2) * Real.log (N + 2 : ℝ)) = epsilon * Real.log (N + 2 : ℝ) := by + field_simp [hlogtwo.ne'] + have hexponent : f N ≤ epsilon * Real.log (N + 2 : ℝ) := + hfN.trans (hscaled.trans_eq hcancel) + rw [Real.rpow_def_of_pos (by positivity : (0 : ℝ) < N + 2)] + apply Real.exp_le_exp.mpr + simpa only [mul_comm] using hexponent + +theorem sublinear_height_near_linear (f : ℕ → ℝ) + (hf : Tendsto (fun N => f N / inputHeight N) atTop (𝓝 0)) + (epsilon : ℝ) (hepsilon : 0 < epsilon) : + ∀ᶠ (N : ℕ) in atTop, (N + 2 : ℝ) * Real.exp (f N) ≤ (N + 2 : ℝ) ^ (1 + epsilon) := by + filter_upwards [subexponential_height_to_input f hf epsilon hepsilon] with N hN + rw [Real.rpow_add (by positivity : (0 : ℝ) < N + 2), Real.rpow_one] + exact mul_le_mul_of_nonneg_left hN (by positivity) + +noncomputable def computedTotalOverheadExponent (C₁ C₂ C₃ C₄ : ℝ) (N : ℕ) : ℝ := + computedDependencyOverheadExponent C₁ C₂ N + + C₃ * ((integerParameters N).M : ℝ) * + ((coarseExponent (inputSmallLog N) : ℝ) + 1) * inputSmallLog N + + C₄ * ((coarseExponent (inputSmallLog N) : ℝ) + 1) * Real.log (inputHeight N : ℝ) + +theorem computedTotalOverheadExponent_tendsto (C₁ C₂ C₃ C₄ : ℝ) : + Tendsto (fun N => computedTotalOverheadExponent C₁ C₂ C₃ C₄ N / inputHeight N) + atTop (𝓝 0) := by + have h := ((computedDependencyOverheadExponent_tendsto C₁ C₂).add + (local_enumeration_exponent_div_height_tendsto.const_mul C₃)).add + (encoding_exponent_div_height_tendsto.const_mul C₄) + simp only [mul_zero, add_zero] at h + convert h using 1 + ext N + unfold computedTotalOverheadExponent + ring + +theorem computed_total_overhead_subpolynomial (C₁ C₂ C₃ C₄ epsilon : ℝ) + (hepsilon : 0 < epsilon) : + ∀ᶠ N in atTop, Real.exp (computedTotalOverheadExponent C₁ C₂ C₃ C₄ N) ≤ + (N + 2 : ℝ) ^ epsilon := + subexponential_height_to_input _ + (computedTotalOverheadExponent_tendsto C₁ C₂ C₃ C₄) epsilon hepsilon + +noncomputable def computedCompleteOverheadExponent (C₁ C₂ C₃ C₄ C₅ : ℝ) (N : ℕ) : ℝ := + computedTotalOverheadExponent C₁ C₂ C₃ C₄ N + computedCoarseOverheadExponent C₅ N + +theorem computedCompleteOverheadExponent_tendsto (C₁ C₂ C₃ C₄ C₅ : ℝ) : + Tendsto (fun N => computedCompleteOverheadExponent C₁ C₂ C₃ C₄ C₅ N / inputHeight N) + atTop (𝓝 0) := by + have h := (computedTotalOverheadExponent_tendsto C₁ C₂ C₃ C₄).add + (computedCoarseOverheadExponent_tendsto C₅) + simp only [add_zero] at h + convert h using 1 + ext N + unfold computedCompleteOverheadExponent + ring + +/-- The combined coarse, local-enumeration and dependency scalar envelope +is subpolynomial in the actual total input length. -/ +theorem computed_complete_overhead_subpolynomial (C₁ C₂ C₃ C₄ C₅ epsilon : ℝ) + (hepsilon : 0 < epsilon) : + ∀ᶠ N in atTop, Real.exp (computedCompleteOverheadExponent C₁ C₂ C₃ C₄ C₅ N) ≤ + (N + 2 : ℝ) ^ epsilon := + subexponential_height_to_input _ + (computedCompleteOverheadExponent_tendsto C₁ C₂ C₃ C₄ C₅) epsilon hepsilon + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/TreeAccounting.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/TreeAccounting.lean new file mode 100644 index 0000000000000000000000000000000000000000..f1c3285fc535f1d06675541c62c1ed55d1e3dc54 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/TreeAccounting.lean @@ -0,0 +1,172 @@ +import Mathlib +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! +# Finite comparison-tree accounting + +A complete tree is indexed by its physical depth and child labels. Terminal +comparison costs may be carried forward, with zero costs in the other child +slots. The identities apply to that representation without any probability +or sampling hypothesis. +-/ + +namespace EditApproximation + +open Finset + +/-- Labeled nodes of a complete `M`-ary tree at one physical depth. -/ + + + + +theorem tree_layer_sum {M d : ℕ} (weight : TreeLayer M (d + 1) → ℝ) : + (∑ node : TreeLayer M d, ∑ child : Fin M, weight (node, child)) = + ∑ node : TreeLayer M (d + 1), weight node := by + exact (Fintype.sum_prod_type weight).symm + +/-- Mass/energy differences cancel exactly between successive frontiers. -/ +theorem tree_frontier_telescope (M J : ℕ) + (weight : (d : ℕ) → TreeLayer M d → ℝ) : + (∑ d ∈ range J, ∑ node : TreeLayer M d, + (weight d node - ∑ child : Fin M, weight (d + 1) (node, child))) = + weight 0 PUnit.unit - ∑ node : TreeLayer M J, weight J node := by + have hstep (d : ℕ) : (∑ node : TreeLayer M d, + (weight d node - ∑ child : Fin M, weight (d + 1) (node, child))) = + (∑ node : TreeLayer M d, weight d node) - + (∑ node : TreeLayer M (d + 1), weight (d + 1) node) := by + rw [sum_sub_distrib, tree_layer_sum] + simp_rw [hstep] + induction J with + | zero => + let : Unique (TreeLayer M 0) := ⟨⟨PUnit.unit⟩, fun a => by cases a; rfl⟩ + rw [sum_range_zero, Fintype.sum_unique] + exact (sub_self _).symm + | succ J ih => + rw [sum_range_succ, ih] + ring + +/-- The explicit small-growth bound used for the comparison frontiers. -/ +theorem small_growth_pow {x : ℝ} (n : ℕ) (hx : 0 ≤ x) + (hsmall : (n : ℝ) * x ≤ 1 / 2) : + (1 + x) ^ n ≤ 1 + 2 * n * x := by + induction n with + | zero => simp + | succ n ih => + have hn : (n : ℝ) * x ≤ 1 / 2 := by + push_cast at hsmall + nlinarith + have hprev := mul_le_mul_of_nonneg_right (ih hn) (by positivity : 0 ≤ 1 + x) + rw [pow_succ] + apply hprev.trans + push_cast + have hprod : 0 ≤ x * (1 - 2 * n * x) := by + apply mul_nonneg hx + nlinarith + nlinarith + +/-- The final scalar summation of the local curvature/energy estimates. +The conservation identities are supplied by `tree_frontier_telescope` for +the comparison masses and energies. -/ +theorem curvature_total_from_telescope {ι : Type*} (nodes : Finset ι) + (curvature discrepancy massDifference movement slack energyDifference : ι → ℝ) + (D rootMass terminalMass : ℝ) + (hroot : 0 ≤ rootMass) (hterminal : terminalMass ≤ 2 * D) + (hconservation : (∑ v ∈ nodes, massDifference v) = rootMass - terminalMass) + (henergy : (∑ v ∈ nodes, energyDifference v) ≤ 2 * D) + (hdiscrepancy : ∀ v ∈ nodes, 0 ≤ discrepancy v) + (hslackNonneg : ∀ v ∈ nodes, 0 ≤ slack v) + (hslack : ∀ v ∈ nodes, massDifference v + discrepancy v ≤ slack v) + (hcurvature : ∀ v ∈ nodes, curvature v ≤ energyDifference v + 3 * movement v + + 2 * max (-massDifference v) 0) : + (∑ v ∈ nodes, (curvature v + discrepancy v)) ≤ + 8 * D + 3 * (∑ v ∈ nodes, movement v) + 4 * (∑ v ∈ nodes, slack v) := by + have hpositive (v : ι) (hv : v ∈ nodes) : max (massDifference v) 0 ≤ slack v := by + apply max_le + · linarith [hslack v hv, hdiscrepancy v hv] + · exact hslackNonneg v hv + have hidentity : (∑ v ∈ nodes, max (-massDifference v) 0) = + (∑ v ∈ nodes, max (massDifference v) 0) - rootMass + terminalMass := by + have hpoint (v : ι) : max (-massDifference v) 0 = + max (massDifference v) 0 - massDifference v := by + by_cases h : 0 ≤ massDifference v + · rw [max_eq_left h, max_eq_right (by linarith : -massDifference v ≤ 0)] + ring + · rw [max_eq_right (by linarith : massDifference v ≤ 0), + max_eq_left (by linarith : 0 ≤ -massDifference v)] + ring + simp_rw [hpoint] + rw [sum_sub_distrib, hconservation] + ring + have hnegative : (∑ v ∈ nodes, max (-massDifference v) 0) ≤ + (∑ v ∈ nodes, slack v) + 2 * D := by + rw [hidentity] + have hsum := sum_le_sum hpositive + linarith + have hG : (∑ v ∈ nodes, discrepancy v) ≤ + (∑ v ∈ nodes, max (-massDifference v) 0) + (∑ v ∈ nodes, slack v) := by + rw [← sum_add_distrib] + apply sum_le_sum + intro v hv + have hminus := le_max_left (-massDifference v) 0 + linarith [hslack v hv] + have hK : (∑ v ∈ nodes, curvature v) ≤ + (∑ v ∈ nodes, energyDifference v) + 3 * (∑ v ∈ nodes, movement v) + + 2 * (∑ v ∈ nodes, max (-massDifference v) 0) := by + have hsum := sum_le_sum hcurvature + simpa only [sum_add_distrib, ← mul_sum] using hsum + rw [sum_add_distrib] + linarith + +/-- Substituting the endpoint and warmup slack totals gives the +manuscript's stated curvature constant. Here `u=J/P` and `v=J/T`. -/ +theorem curvature_total_parameter_bound {total movement slack D F u v : ℝ} + (hD : 0 ≤ D) (hF : 1 ≤ F) (hu : 0 ≤ u) (hv : 0 ≤ v) + (htotal : total ≤ 8 * D + 3 * movement + 4 * slack) + (hmove : movement ≤ 4 * u * D) + (hslack : slack ≤ 512 * F * u * D + 4 * F * v * D) : + total ≤ 5000 * F * (1 + u + v) * D := by + have hF0 : 0 ≤ F := by linarith + have hroot : 8 * D ≤ 5000 * F * D := + mul_le_mul_of_nonneg_right (by linarith) hD + have huc : (2048 * F + 12) * u * D ≤ 5000 * F * u * D := + mul_le_mul_of_nonneg_right + (mul_le_mul_of_nonneg_right (by linarith : 2048 * F + 12 ≤ 5000 * F) hu) hD + have hvc : 16 * F * v * D ≤ 5000 * F * v * D := + mul_le_mul_of_nonneg_right + (mul_le_mul_of_nonneg_right (by nlinarith : 16 * F ≤ 5000 * F) hv) hD + nlinarith + +/-- Exceptional-node cost uses the total curvature/discrepancy charge; +no count of nodes or independence assumption is needed. -/ +theorem bad_node_cost_from_curvature {ι : Type*} (nodes : Finset ι) + (cost scale curvature discrepancy : ι → ℝ) (ratio totalBound : ℝ) + (hratio : 0 ≤ ratio) + (hcost : ∀ i ∈ nodes, cost i ≤ 2 * scale i) + (hcurvature : ∀ i ∈ nodes, 0 ≤ curvature i) + (hdiscrepancy : ∀ i ∈ nodes, 0 ≤ discrepancy i) + (htotal : (∑ i ∈ nodes, (curvature i + discrepancy i)) ≤ totalBound) : + (∑ i ∈ nodes with scale i < ratio * curvature i ∨ scale i < ratio * discrepancy i, + cost i) ≤ 2 * ratio * totalBound := by + classical + let bad := nodes.filter fun i => scale i < ratio * curvature i ∨ + scale i < ratio * discrepancy i + have hpoint (i : ι) (hi : i ∈ bad) : cost i ≤ 2 * ratio * (curvature i + discrepancy i) := by + obtain ⟨hinode, hbad⟩ := mem_filter.mp hi + have hK := mul_nonneg hratio (hcurvature i hinode) + have hG := mul_nonneg hratio (hdiscrepancy i hinode) + rcases hbad with hbad | hbad <;> nlinarith [hcost i hinode] + have hpartial : (∑ i ∈ bad, (curvature i + discrepancy i)) ≤ + ∑ i ∈ nodes, (curvature i + discrepancy i) := by + apply sum_le_sum_of_subset_of_nonneg (filter_subset _ _) + intro i hi _ + exact add_nonneg (hcurvature i hi) (hdiscrepancy i hi) + have hsum := sum_le_sum hpoint + rw [← mul_sum] at hsum + exact hsum.trans (mul_le_mul_of_nonneg_left (hpartial.trans htotal) (by positivity)) + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/TreeParameters.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/TreeParameters.lean new file mode 100644 index 0000000000000000000000000000000000000000..aadab268d55c575af6b67e602783bceaa75834bd --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/TreeParameters.lean @@ -0,0 +1,98 @@ +import OAI.Combinatorics.EditApproximation.Geometry.BalancedWidths +import OAI.Combinatorics.EditApproximation.Geometry.Parameters +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! +# Depth of the computed interval tree + +The branching factor is the power of two prescribed by the algorithm. +Ceiling logarithms count physical levels, including empty intervals. +-/ + +namespace EditApproximation + +open Finset + + + +theorem intervalTreeDepth_capacity (M nx : ℕ) (hM : 2 ≤ M) : + nx ≤ M ^ intervalTreeDepth M nx := + (le_max_right 1 nx).trans (Nat.le_pow_clog hM (max 1 nx)) + +theorem intervalTreeDepth_power_le (M nx : ℕ) (hM : 2 ≤ M) : + M ^ intervalTreeDepth M nx ≤ M * max 1 nx := by + by_cases hx : max 1 nx = 1 + · have hz : Nat.clog M 1 = 0 := by + apply Nat.eq_zero_of_le_zero + exact (Nat.clog_le_iff_le_pow hM).2 (by simp) + simpa only [intervalTreeDepth, hx, hz, pow_zero, mul_one] using + (by omega : 1 ≤ M) + · have hx1 : 1 < max 1 nx := by omega + have hdepth := Nat.clog_pos hM hx1 + have hpred := Nat.pow_pred_clog_lt_self hM hx1 + unfold intervalTreeDepth + rw [← Nat.succ_pred_eq_of_pos hdepth, + pow_succ] + nlinarith + +theorem computed_branching_bounds (N : ℕ) (hN : 0 < N) + (hell : 200 ≤ inputSmallLog N) : + 2 ≤ (integerParameters N).M ∧ + inputSmallLog N ≤ 50 * (heightExponent N / 20) ∧ + heightExponent N / 20 ≤ inputHeight N := by + have hlogs := inputSmallLog_bounds N hN + have hquot := Nat.mod_lt (heightExponent N) (by decide : 0 < 20) + have hsplit := Nat.mod_add_div (heightExponent N) 20 + have hk : 1 ≤ heightExponent N / 20 := by omega + have hpow : 2 ≤ 2 ^ (heightExponent N / 20) := by + simpa using pow_le_pow_right₀ (by decide : 1 ≤ (2 : ℕ)) hk + have hexp : heightExponent N ≤ inputHeight N := by + exact (Nat.lt_pow_self (by decide : 1 < 2)).le + exact ⟨hpow, by omega, (Nat.div_le_self _ _).trans hexp⟩ + +theorem computed_tree_depth_bound (N nx : ℕ) (hN : 0 < N) (hnx : nx ≤ N) + (hell : 200 ≤ inputSmallLog N) : + intervalTreeDepth (integerParameters N).M nx * inputSmallLog N ≤ 100 * inputHeight N := by + let k := heightExponent N / 20 + have hbranch := computed_branching_bounds N hN hell + have hbound : max 1 nx ≤ 2 ^ inputHeight N := by + apply max_le Nat.one_le_two_pow + exact hnx.trans ((Nat.le_add_right N 2).trans (inputHeight_covers_length N)) + have hlog : Nat.clog 2 (max 1 nx) ≤ inputHeight N := + (Nat.clog_le_iff_le_pow (by decide : 1 < 2)).2 hbound + have hdepth : intervalTreeDepth (integerParameters N).M nx = + (Nat.clog 2 (max 1 nx) + (k - 1)) / k := by + exact Nat.clog_pow_left 2 k (max 1 nx) + have hproduct := Nat.div_mul_le_self (Nat.clog 2 (max 1 nx) + (k - 1)) k + rw [← hdepth] at hproduct + have hscale := Nat.mul_le_mul_left + (intervalTreeDepth (integerParameters N).M nx) hbranch.2.1 + change intervalTreeDepth (integerParameters N).M nx * inputSmallLog N ≤ + intervalTreeDepth (integerParameters N).M nx * (50 * k) at hscale + have hkH : k ≤ inputHeight N := hbranch.2.2 + have hsub : k - 1 ≤ k := Nat.sub_le _ _ + nlinarith + +theorem computed_source_leaf_width (N nx : ℕ) (hN : 0 < N) + (hell : 200 ≤ inputSmallLog N) + (node : TreeLayer (integerParameters N).M + (intervalTreeDepth (integerParameters N).M nx)) : + (sourceIntervalAt (integerParameters N).M nx _ node).hi - + (sourceIntervalAt (integerParameters N).M nx _ node).lo ≤ 1 := by + have hM := (computed_branching_bounds N hN hell).1 + exact sourceIntervalAt_leaf_width _ _ _ (by omega) + (intervalTreeDepth_capacity _ _ hM) node + +theorem intervalTreeDepth_node_count (M nx : ℕ) (hM : 2 ≤ M) : + (∑ d ∈ range (intervalTreeDepth M nx + 1), Fintype.card (TreeLayer M d)) ≤ + 2 * M * max 1 nx := by + have hnodes := complete_tree_node_count M (intervalTreeDepth M nx) hM + have hcapacity := intervalTreeDepth_power_le M nx hM + nlinarith + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/UnifiedPhysicalTable.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/UnifiedPhysicalTable.lean new file mode 100644 index 0000000000000000000000000000000000000000..3628cf22a7a347e0350a76332233a13e50859051 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/UnifiedPhysicalTable.lean @@ -0,0 +1,76 @@ +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalLocalRefinement + +namespace OAI + +/-! The cache's unified index uses warmup indices through T and then +refinement indices T+t. Refinement zero is exactly warmup T, including +terminal physical nodes and short source intervals. -/ + +namespace EditApproximation + +theorem physicalLocalWarmup_terminal {α : Type*} [DecidableEq α] {M J : ℕ} + (source target : List α) (U : PhysicalEntry M J target.length → ℕ) + (N P F : ℕ) (A : ℚ) (node : PhysicalNode M J) (t : ℕ) + (q : TargetInterval target.length) + (hterminal : ¬ node.1.val < J ∨ + (physicalSourceInterval source.length node).hi - (physicalSourceInterval source.length node).lo ≤ 1) : + physicalLocalWarmup source target U N P F A t (node, q) = + stageInitial source target U N P F A (node, q) := by + cases t with + | zero => rfl + | succ t => + rw [physicalLocalWarmup] + rcases hterminal with hdepth | hwidth + · rw [dite_eq_right hdepth] + · split_ifs <;> rfl + +theorem physicalLocalRefinement_zero {α : Type*} [DecidableEq α] {M J : ℕ} + (source target : List α) (U : PhysicalEntry M J target.length → ℕ) + (N P F exponent Q : ℕ) (A tau delta : ℚ) (T : ℕ) + (draw : PhysicalInternalNode M J → ℕ → CellGroupDraws M F Q) + (online : PhysicalNode M J → PhysicalChildTables M target.length → ℕ → + TargetInterval target.length → List (PhysicalRationalAction M target.length)) + (node : PhysicalNode M J) (q : TargetInterval target.length) : + physicalLocalRefinement source target U N P F exponent Q A tau delta T draw online node 0 q = + physicalLocalWarmup source target U N P F A T (node, q) := by + rw [physicalLocalRefinement] + split_ifs with hbelow hleaf + · exact (physicalLocalWarmup_terminal source target U N P F A node T q (Or.inr hleaf)).symm + · rfl + · exact (physicalLocalWarmup_terminal source target U N P F A node T q (Or.inl hbelow)).symm + +section Unified + +variable {α : Type*} [DecidableEq α] {M J : ℕ} + (source target : List α) (U : PhysicalEntry M J target.length → ℕ) + (N P F exponent Q : ℕ) (A tau delta : ℚ) (T : ℕ) + (draw : PhysicalInternalNode M J → ℕ → CellGroupDraws M F Q) + (online : PhysicalNode M J → PhysicalChildTables M target.length → ℕ → + TargetInterval target.length → List (PhysicalRationalAction M target.length)) + +def unifiedPhysicalValue (node : PhysicalNode M J) (index : ℕ) (q : TargetInterval target.length) : ℚ := + if index ≤ T then physicalLocalWarmup source target U N P F A index (node, q) + else physicalLocalRefinement source target U N P F exponent Q A tau delta T draw online node (index - T) q + +theorem unifiedPhysicalValue_warmup (node : PhysicalNode M J) (index : ℕ) + (hi : index ≤ T) (q : TargetInterval target.length) : + unifiedPhysicalValue source target U N P F exponent Q A tau delta T draw online node index q = + physicalLocalWarmup source target U N P F A index (node, q) := ite_eq_left hi + +theorem unifiedPhysicalValue_refinement (node : PhysicalNode M J) (t : ℕ) + (q : TargetInterval target.length) : + unifiedPhysicalValue source target U N P F exponent Q A tau delta T draw online node (T + t) q = + physicalLocalRefinement source target U N P F exponent Q A tau delta T draw online node t q := by + cases t with + | zero => + rw [Nat.add_zero, unifiedPhysicalValue_warmup source target U N P F exponent Q A tau delta T draw online node T le_rfl] + exact (physicalLocalRefinement_zero source target U N P F exponent Q A tau delta T draw online node q).symm + | succ t => + unfold unifiedPhysicalValue + rw [ite_eq_right (by omega : ¬ T + (t + 1) ≤ T), Nat.add_sub_cancel_left] + +end Unified + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/UnskippedBands.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/UnskippedBands.lean new file mode 100644 index 0000000000000000000000000000000000000000..54be0dfd4416ad60b932433d9e31965099990db3 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/UnskippedBands.lean @@ -0,0 +1,46 @@ +import OAI.Combinatorics.EditApproximation.Geometry.BandActionGuards +import OAI.Combinatorics.EditApproximation.Geometry.StateDomain +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! +# Literal unskipped-band tests + +The finite representative band, rational child envelopes and canonical +rounded action are tested directly. A successful result carries exactly +the facts checked by the algorithm; inaccurate seeds still produce a +finite list of such tested records. +-/ + +namespace EditApproximation + +open Finset + + + + + + + +namespace UnskippedBand + + + + + + + +theorem envelope_pos {α : Type*} {source target : List α} {M : ℕ} + {parent : TargetInterval source.length} {b P thetaExponent : ℕ} + {tau F : ℚ} {child initial : Fin M → TargetInterval target.length → ℚ} + (member : UnskippedBand source target parent b P thetaExponent tau F child initial) (i : Fin M) : + 0 < member.envelope i := + bandChildEnvelope_pos b member.actions initial i + +end UnskippedBand + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/UnskippedRegretBudget.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/UnskippedRegretBudget.lean new file mode 100644 index 0000000000000000000000000000000000000000..a1189a6452e5914af3b9314ece37f2416b5ad8cc --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/UnskippedRegretBudget.lean @@ -0,0 +1,66 @@ +import OAI.Combinatorics.EditApproximation.Geometry.BandDimension +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalOnlineBand + +namespace OAI + +/-! The actual guarded band supplies the mass and entropy factors in the node budget. -/ + +namespace EditApproximation + +open Finset + +theorem band_dimension_log_of_computed (N : ℕ) (hN : 0 < N) (hell : 42 ≤ inputSmallLog N) + {nx ny M b P : ℕ} (hMeq : M = (integerParameters N).M) (hPeq : P = (integerParameters N).P) + (parent : TargetInterval nx) (r : TargetInterval ny) (band : List (Fin M → TargetInterval ny)) + (hband : ∀ action ∈ band, action ∈ wideActionList M parent r b P) : + Real.log (bandCoordinates band.toFinset).card ≤ + 4 * (coarseExponent (inputSmallLog N) + 21 : ℕ) * (inputSmallLog N : ℝ) := by + subst M P + exact computed_band_dimension_log N hN hell parent r band hband + +theorem unskipped_expected_regret_budget {α : Type*} (source target : List α) + (N : ℕ) (hN : 0 < N) (hell : 42 ≤ inputSmallLog N) {M b P thetaExponent : ℕ} + (hMeq : M = (integerParameters N).M) (hPeq : P = (integerParameters N).P) + (parent : TargetInterval source.length) (tau F : ℚ) + (child initial : Fin M → TargetInterval target.length → ℚ) + (member : UnskippedBand source target parent b P thetaExponent tau F child initial) + (hF : 0 ≤ F) (c : ℝ) (hb : (b : ℝ) ≤ c) + (eta kappa delta : ℚ) (heta : 0 < eta) (hkappa : 0 ≤ kappa) (S H : ℕ) : + ((∑ i, member.envelope i : ℚ) : ℝ) * + (Real.log (bandCoordinates member.actions.toFinset).card / (eta : ℝ) + 2 * (kappa : ℝ) + + (S : ℝ) / (H : ℝ) ^ 3) + 2 * (delta : ℝ) * c + 2 * S * (1 / (H : ℝ) ^ 4) * F * c ≤ + (64 * (F : ℝ) * + ((4 * (coarseExponent (inputSmallLog N) + 21 : ℕ) * (inputSmallLog N : ℝ)) / (eta : ℝ) + + 2 * (kappa : ℝ) + (S : ℝ) / (H : ℝ) ^ 3) + + 2 * (delta : ℝ) + 2 * S * (1 / (H : ℝ) ^ 4) * F) * c := by + have hlog := band_dimension_log_of_computed N hN hell hMeq hPeq parent member.center member.actions + (fun action ha => representativeBandActions_wide source target parent member.center b P tau + ((2 : ℚ) ^ (-(thetaExponent : ℤ))) child action ha) + have hmass : (0 : ℝ) ≤ ((∑ i, member.envelope i : ℚ) : ℝ) := by + exact (Rat.cast_nonneg (K := ℝ)).mpr (sum_nonneg fun i _ => (bandChildEnvelope_pos _ _ _ _).le) + have hmassBound : ((∑ i, member.envelope i : ℚ) : ℝ) ≤ 64 * (F : ℝ) * c := by + have hQ := (Rat.cast_le (K := ℝ)).mpr member.sum_guard + simp only [Rat.cast_sum, Rat.cast_mul, Rat.cast_ofNat, Rat.cast_natCast] at hQ + have hFR := (Rat.cast_nonneg (K := ℝ)).mpr hF + simpa only [UnskippedBand.envelope, UnskippedBand.actions, Rat.cast_sum] using + hQ.trans (mul_le_mul_of_nonneg_left hb (mul_nonneg (by norm_num) hFR)) + let upper : ℝ := (4 * (coarseExponent (inputSmallLog N) + 21 : ℕ) * (inputSmallLog N : ℝ)) / (eta : ℝ) + + 2 * (kappa : ℝ) + (S : ℝ) / (H : ℝ) ^ 3 + have hupper : 0 ≤ upper := by + exact add_nonneg (add_nonneg (div_nonneg (mul_nonneg + (mul_nonneg (by norm_num) (Nat.cast_nonneg _)) (Nat.cast_nonneg _)) + ((Rat.cast_pos (K := ℝ)).mpr heta).le) (mul_nonneg (by norm_num) ((Rat.cast_nonneg (K := ℝ)).mpr hkappa))) + (div_nonneg (Nat.cast_nonneg _) (pow_nonneg (Nat.cast_nonneg _) 3)) + have hbracket : Real.log (bandCoordinates member.actions.toFinset).card / (eta : ℝ) + + 2 * (kappa : ℝ) + (S : ℝ) / (H : ℝ) ^ 3 ≤ upper := by + dsimp only [upper] + exact add_le_add_left (add_le_add_left + (div_le_div_of_nonneg_right hlog ((Rat.cast_pos (K := ℝ)).mpr heta).le) _) _ + have hprod := (mul_le_mul_of_nonneg_left hbracket hmass).trans + (mul_le_mul_of_nonneg_right hmassBound hupper) + dsimp only [upper] at hprod + nlinarith only [hprod] + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/WarmupQueryKeys.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/WarmupQueryKeys.lean new file mode 100644 index 0000000000000000000000000000000000000000..dabae0ebc1c673f3a9cf55409abbdbd3eb7c8d44 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/WarmupQueryKeys.lean @@ -0,0 +1,102 @@ +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalWarmupStepQuery +import OAI.Combinatorics.EditApproximation.Probability.FiniteQueryWork + +namespace OAI + +/-! Initial and warmup queries preserve reader predicates. In particular, +only same-node seed reads are needed to prove boundedness of every emitted +request; unrelated seed-table entries play no role. -/ + +namespace EditApproximation + +theorem physicalInitialQuery_keys_all {ι α : Type*} [DecidableEq α] {M J : ℕ} + (source target : List α) (N P F : ℕ) (A : ℚ) + (seedRead : PhysicalEntry M J target.length → FiniteQuery ι) + (node : PhysicalNode M J) (q : TargetInterval target.length) + (oracle : ι → ℚ) (predicate : ι → Prop) + (hseed : ∀ r key, key ∈ (seedRead (node, r)).keys oracle → predicate key) : + ∀ key ∈ (physicalInitialQuery source target N P F A seedRead (node, q)).keys oracle, predicate key := by + unfold physicalInitialQuery + dsimp only + split_ifs with hleaf + · intro key hk + exact False.elim (List.not_mem_nil hk) + · rw [FiniteQuery.keys_bind] + intro key hk + rcases List.mem_append.mp hk with hfirst | hrest + · exact hseed q key hfirst + · apply FiniteQuery.keys_all_collect oracle predicate _ _ _ ?_ ?_ key hrest + · intro r _ other ho + exact hseed r other ho + · intro answers other ho + exact False.elim (List.not_mem_nil ho) + +theorem localWarmupStepQuery_keys_all {ι : Type*} {nx ny M : ℕ} (parent : TargetInterval nx) + (N P F : ℕ) (a : ℚ) (initialRead : TargetInterval ny → FiniteQuery ι) + (childRead : Fin M × TargetInterval ny → FiniteQuery ι) (q : TargetInterval ny) + (oracle : ι → ℚ) (predicate : ι → Prop) + (hinitial : ∀ r key, key ∈ (initialRead r).keys oracle → predicate key) + (hchild : ∀ input key, key ∈ (childRead input).keys oracle → predicate key) : + ∀ key ∈ (localWarmupStepQuery parent N P F a initialRead childRead q).keys oracle, predicate key := by + unfold localWarmupStepQuery + rw [FiniteQuery.keys_bind] + intro key hk + rcases List.mem_append.mp hk with hfirst | hrest + · exact hinitial q key hfirst + · apply FiniteQuery.keys_all_collect oracle predicate _ _ _ ?_ ?_ key hrest + · intro r _ other ho + exact hinitial r other ho + · intro initialValues + apply FiniteQuery.keys_all_collect + · intro input _ other ho + exact hchild input other ho + · intro childValues other ho + exact False.elim (List.not_mem_nil ho) + +theorem physicalWarmupRequestQuery_keys_all {α : Type*} [DecidableEq α] {M J : ℕ} + (source target : List α) (N P F : ℕ) (A : ℚ) + (pass copy T S j : ℕ) (node : PhysicalNode M J) (q : TargetInterval target.length) + (seedRead : PhysicalEntry M J target.length → + FiniteQuery {child : PhysicalTableRequest M J target.length // + child.combinedRank T S < (PhysicalTableRequest.warmup pass copy node j q).combinedRank T S}) + (oracle) (predicate : PhysicalTableRequest M J target.length → Prop) + (hseed : ∀ r key, key ∈ (seedRead (node, r)).keys oracle → predicate key.val) + (hchild : ∀ (hbelow : node.1.val < J) (input : Fin M × TargetInterval target.length), + predicate (PhysicalTableRequest.warmup pass copy (physicalChild node hbelow input.1) (j - 1) input.2)) : + ∀ key ∈ (physicalWarmupRequestQuery source target N P F A pass copy T S j node q seedRead).keys oracle, + predicate key.val := by + cases j with + | zero => exact physicalInitialQuery_keys_all source target N P F A seedRead node q oracle _ hseed + | succ j => + dsimp only [physicalWarmupRequestQuery] + split_ifs with hbelow hleaf + · exact physicalInitialQuery_keys_all source target N P F A seedRead node q oracle _ hseed + · unfold physicalWarmupStepQuery + apply localWarmupStepQuery_keys_all + · intro r + exact physicalInitialQuery_keys_all source target N P F A seedRead node r oracle _ hseed + · intro input key hk + simp only [physicalWarmupChildQuery, FiniteQuery.keys, List.mem_singleton] at hk + subst key + exact hchild hbelow input + · exact physicalInitialQuery_keys_all source target N P F A seedRead node q oracle _ hseed + +theorem physicalWarmupRequestQuery_keys_bounded {α : Type*} [DecidableEq α] {M J : ℕ} + (source target : List α) (N P F : ℕ) (A : ℚ) + (passes copies pass copy T S j : ℕ) (hpass : pass < passes) (hcopy : copy < copies) (hj : j ≤ T) + (node : PhysicalNode M J) (q : TargetInterval target.length) + (seedRead : PhysicalEntry M J target.length → + FiniteQuery {child : PhysicalTableRequest M J target.length // + child.combinedRank T S < (PhysicalTableRequest.warmup pass copy node j q).combinedRank T S}) + (oracle) + (hseed : ∀ r key, key ∈ (seedRead (node, r)).keys oracle → key.val.Bounded passes copies T S) : + ∀ key ∈ (physicalWarmupRequestQuery source target N P F A pass copy T S j node q seedRead).keys oracle, + key.val.Bounded passes copies T S := by + apply physicalWarmupRequestQuery_keys_all source target N P F A pass copy T S j node q seedRead oracle _ hseed + intro hbelow input + exact PhysicalTableRequest.warmup_bounded passes copies pass copy (physicalChild node hbelow input.1) + T S (j - 1) input.2 hpass hcopy (by omega) + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/WarmupReadWork.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/WarmupReadWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..83b47c2d1a4982e33264fab2cddf569f76ad8934 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/WarmupReadWork.lean @@ -0,0 +1,162 @@ +import OAI.Combinatorics.EditApproximation.Geometry.ChargedGlobalQuery +import OAI.Combinatorics.EditApproximation.Geometry.RefinementSupportBudget + +namespace OAI + +/-! Literal seed, initial-cone and warmup query counts. No accuracy event +is needed: even rejected local centers are included in these bounds. -/ + +namespace EditApproximation + +theorem rawInitialConeCenters_length {n : ℕ} (N P Amax : ℕ) (A : ℚ) + (value : ℕ) (q : TargetInterval n) (hP : 0 < P) (hA : 1 ≤ A) (hmax : A ≤ Amax) : + (rawInitialConeCenters N P A value q).length ≤ + (dyadicScales N).length * (64 * Amax ^ 2 * P + 2) ^ 2 := by + unfold rawInitialConeCenters + apply (list_flatMap_length_le _ _ _ ?_).trans + (Nat.mul_le_mul_right _ (List.length_filter_le _ _)) + intro b hb + have hwindow := of_decide_eq_true (List.mem_filter.mp hb).2 + have hApos : 0 < A := by linarith + have hscale : (value : ℚ) ≤ 16 * A ^ 2 * b := by + have h := (div_le_iff₀ (by positivity : (0 : ℚ) < 16 * A ^ 2)).mp hwindow.1 + nlinarith only [h] + have hAsq : A ^ 2 ≤ (Amax : ℚ) ^ 2 := pow_le_pow_left₀ hApos.le hmax 2 + have hradius : value ≤ 16 * Amax ^ 2 * b := by + have hmul := mul_le_mul_of_nonneg_right hAsq (by positivity : (0 : ℚ) ≤ 16 * b) + have h : (value : ℚ) ≤ (16 * Amax ^ 2 * b : ℕ) := by + push_cast + nlinarith only [hscale, hmul] + exact_mod_cast h + simpa only [show 4 * (16 * Amax ^ 2) * P = 64 * Amax ^ 2 * P by ring] using + localTargetStates_length_from_scale P b value (16 * Amax ^ 2) q hP hradius + +theorem physicalInitialQuery_cost_le {ι α : Type*} [DecidableEq α] {M J : ℕ} + (source target : List α) (N P F Amax seedCost : ℕ) (A : ℚ) + (seedRead : PhysicalEntry M J target.length → FiniteQuery ι) + (node : PhysicalNode M J) (q : TargetInterval target.length) (oracle : ι → ℚ) + (hP : 0 < P) (hA : 1 ≤ A) (hmax : A ≤ Amax) + (hseed : ∀ r, (seedRead (node, r)).cost oracle (fun _ => 1) ≤ seedCost) : + (physicalInitialQuery source target N P F A seedRead (node, q)).cost oracle (fun _ => 1) ≤ + (1 + (dyadicScales N).length * (64 * Amax ^ 2 * P + 2) ^ 2) * seedCost := by + unfold physicalInitialQuery + dsimp only + split_ifs + · exact Nat.zero_le _ + · rw [FiniteQuery.cost_bind] + have hkeys := rawInitialConeCenters_length N P Amax A + ⌈(seedRead (node, q)).value oracle⌉₊ q hP hA hmax + rw [FiniteQuery.cost_collect] + simp only [FiniteQuery.cost, Nat.add_zero] + have hc := list_map_sum_le_constant + (rawInitialConeCenters N P A ⌈(seedRead (node, q)).value oracle⌉₊ q) + (fun r => (seedRead (node, r)).cost oracle (fun _ => 1)) seedCost + (fun r => hseed r) + calc + _ ≤ seedCost + (rawInitialConeCenters N P A + ⌈(seedRead (node, q)).value oracle⌉₊ q).length * seedCost := + Nat.add_le_add (hseed q) hc + _ ≤ seedCost + ((dyadicScales N).length * (64 * Amax ^ 2 * P + 2) ^ 2) * seedCost := by + simpa only [Nat.add_zero] using Nat.add_le_add_left (Nat.mul_le_mul_right seedCost hkeys) seedCost + _ = _ := by ring + +theorem localWarmupStepQuery_cost_le {ι : Type*} {nx ny M : ℕ} (parent : TargetInterval nx) + (N P F window initialCost childCost : ℕ) (a : ℚ) + (initialRead : TargetInterval ny → FiniteQuery ι) + (childRead : Fin M × TargetInterval ny → FiniteQuery ι) + (oracle : ι → ℚ) (q : TargetInterval ny) (hP : 0 < P) (hF : 1 ≤ F) + (hwindow : ∀ w, (dyadicQueryWindow N w a F).length ≤ window) + (hinitial : ∀ r, (initialRead r).cost oracle (fun _ => 1) ≤ initialCost) + (hchild : ∀ input, (childRead input).cost oracle (fun _ => 1) ≤ childCost) : + (localWarmupStepQuery parent N P F a initialRead childRead q).cost oracle (fun _ => 1) ≤ + (1 + window * (64 * F * P + 2) ^ 2) * initialCost + + window * (64 * F * P + 2) ^ 2 * M * (40 * P + 2) ^ 2 * childCost := by + let value := (initialRead q).value oracle + let centers := rawRefinementCenters N P F a value q + have hcenters : centers.length ≤ window * (64 * F * P + 2) ^ 2 := + (rawRefinementCenters_length N P F a value q hP hF).trans + (Nat.mul_le_mul_right _ (hwindow value)) + have hnext (answers : List ℚ) : + (FiniteQuery.collect childRead + (wideWarmupInputs (M := M) parent P + (localRefinementRepresentatives N P F a + (fun r => if r = q then value else finiteAnswerTable centers answers r) q)) + (fun values => .done (rationalBellman (M := M) + (fun r => if r = q then value else finiteAnswerTable centers answers r) + (fun q r => targetEndpointDistance q r) (128 * F) + (rationalActualWideActions parent + (localRefinementRepresentatives N P F a + (fun r => if r = q then value else finiteAnswerTable centers answers r) q) P) + (finiteAnswerTable (wideWarmupInputs (M := M) parent P + (localRefinementRepresentatives N P F a + (fun r => if r = q then value else finiteAnswerTable centers answers r) q)) values) q))).cost oracle (fun _ => 1) ≤ + window * (64 * F * P + 2) ^ 2 * M * (40 * P + 2) ^ 2 * childCost := by + have hreps := localRefinementRepresentatives_length N P F a + (fun r => if r = q then value else finiteAnswerTable centers answers r) q hP hF + have hlen := (wideWarmupInputs_length (M := M) parent P _ hP).trans + (Nat.mul_le_mul_right ((40 * P + 2) ^ 2) (Nat.mul_le_mul_right M + (hreps.trans (Nat.mul_le_mul_right _ (hwindow _))))) + rw [FiniteQuery.cost_collect] + simp only [FiniteQuery.cost, Nat.add_zero] + exact (list_map_sum_le_constant _ (fun input => (childRead input).cost oracle (fun _ => 1)) + childCost (fun input => hchild input)).trans (Nat.mul_le_mul_right childCost hlen) + unfold localWarmupStepQuery + rw [FiniteQuery.cost_bind] + rw [FiniteQuery.cost_collect] + have hc := Nat.add_le_add + (list_map_sum_le_constant centers (fun r => (initialRead r).cost oracle (fun _ => 1)) initialCost hinitial) + (hnext (centers.map fun r => (initialRead r).value oracle)) + calc + _ ≤ initialCost + (centers.length * initialCost + + window * (64 * F * P + 2) ^ 2 * M * (40 * P + 2) ^ 2 * childCost) := + Nat.add_le_add (hinitial q) hc + _ ≤ initialCost + (window * (64 * F * P + 2) ^ 2 * initialCost + + window * (64 * F * P + 2) ^ 2 * M * (40 * P + 2) ^ 2 * childCost) := + Nat.add_le_add_left (Nat.add_le_add_right (Nat.mul_le_mul_right initialCost hcenters) _) _ + _ = _ := by ring + +theorem chargedSeedQuery_cost_le {M J ny passes copies T S : ℕ} (N : ℕ) (multiplier : ℕ → ℕ) + (parent : {r : PhysicalTableRequest M J ny // r.Bounded passes copies T S}) + (state : PhysicalEntry M J ny) (oracle) : + (chargedSeedQuery N multiplier parent state).cost oracle (fun _ => 1) ≤ max 1 copies := by + rw [chargedSeedQuery_cost] + split_ifs + · exact le_max_left _ _ + · exact le_max_right _ _ + · exact Nat.zero_le _ + +theorem chargedWarmupQuery_cost_le {α : Type*} [DecidableEq α] {M J passes copies T S : ℕ} + (source target : List α) (N P F Amax window : ℕ) + (factor : ℕ → ℚ) (multiplier : ℕ → ℕ) + (parent : {r : PhysicalTableRequest M J target.length // r.Bounded passes copies T S}) + (oracle) (hP : 0 < P) (hF : 1 ≤ F) (hA : 1 ≤ factor parent.val.pass) + (hmax : factor parent.val.pass ≤ Amax) + (hwindow : ∀ w, (dyadicQueryWindow N w (refinementFactor (factor parent.val.pass) F) F).length ≤ window) : + (chargedWarmupQuery source target N P F factor multiplier parent).cost oracle (fun _ => 1) ≤ + (1 + window * (64 * F * P + 2) ^ 2) * + ((1 + (dyadicScales N).length * (64 * Amax ^ 2 * P + 2) ^ 2) * max 1 copies) + + window * (64 * F * P + 2) ^ 2 * M * (40 * P + 2) ^ 2 := by + let initialCost := (1 + (dyadicScales N).length * (64 * Amax ^ 2 * P + 2) ^ 2) * max 1 copies + have hinitial (r : TargetInterval target.length) : + (physicalInitialQuery source target N P F (factor parent.val.pass) + (chargedSeedQuery N multiplier parent) (parent.val.node, r)).cost oracle (fun _ => 1) ≤ initialCost := + physicalInitialQuery_cost_le source target N P F Amax (max 1 copies) _ _ _ r oracle hP hA hmax + (fun s => chargedSeedQuery_cost_le N multiplier parent _ oracle) + have hinitialBound : initialCost ≤ + (1 + window * (64 * F * P + 2) ^ 2) * initialCost + + window * (64 * F * P + 2) ^ 2 * M * (40 * P + 2) ^ 2 := by + exact (Nat.le_mul_of_pos_left initialCost (by omega)).trans (Nat.le_add_right _ _) + unfold chargedWarmupQuery + split_ifs with hz hbelow hshort + · exact (hinitial _).trans hinitialBound + · exact (hinitial _).trans hinitialBound + · unfold physicalWarmupStepQuery + simpa only [Nat.mul_one] using localWarmupStepQuery_cost_le + (physicalSourceInterval source.length parent.val.node) N P F window initialCost 1 + (refinementFactor (factor parent.val.pass) F) _ _ oracle parent.val.state hP hF hwindow hinitial + (fun input => by simp only [chargedWarmupChild, FiniteQuery.cost, Nat.add_zero, le_refl]) + · exact (hinitial _).trans hinitialBound + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/WeightedTreeWork.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/WeightedTreeWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..50a4b3a452c0d0594e73ed3d0284593961202ec0 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/WeightedTreeWork.lean @@ -0,0 +1,44 @@ +import OAI.Combinatorics.EditApproximation.Geometry.TreeParameters + +namespace OAI + +/-! +# Summing width-sensitive work over physical levels + +At depth `d`, the product of the number of nodes and their maximum +balanced width is at most the source length plus one layer's node count. +This is the precise summation used for fresh coarse-entry requests. +-/ + +namespace EditApproximation + +open Finset + +theorem mul_ceilDiv_le_add (n m : ℕ) (hm : 0 < m) : + m * (n ⌈/⌉ m) ≤ n + m := by + have hceil : n ⌈/⌉ m ≤ n / m + 1 := + (ceilDiv_le_iff_le_mul hm).2 (Nat.lt_mul_div_succ n hm).le + have hmul := Nat.mul_le_mul_left m hceil + have hfloor := Nat.mul_div_le n m + nlinarith + +theorem layer_width_work (M n d : ℕ) (hM : 0 < M) : + M ^ d * (1 + n ⌈/⌉ M ^ d) ≤ n + 2 * M ^ d := by + have hwidth := mul_ceilDiv_le_add n (M ^ d) (pow_pos hM d) + nlinarith + +theorem interval_tree_width_work (M n : ℕ) (hM : 2 ≤ M) : + (∑ d ∈ range (intervalTreeDepth M n + 1), M ^ d * (1 + n ⌈/⌉ M ^ d)) ≤ + (intervalTreeDepth M n + 1) * n + 4 * M * max 1 n := by + have hpoint (d : ℕ) (_ : d ∈ range (intervalTreeDepth M n + 1)) := + layer_width_work M n d (by omega) + have hsum := sum_le_sum hpoint + rw [sum_add_distrib, sum_const, card_range, nsmul_eq_mul, ← mul_sum] at hsum + have hnodes := complete_tree_node_count M (intervalTreeDepth M n) hM + simp_rw [treeLayer_card] at hnodes + have hcapacity := intervalTreeDepth_power_le M n hM + nlinarith + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/WideActions.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/WideActions.lean new file mode 100644 index 0000000000000000000000000000000000000000..c1b1f1368fc0784194c11ac07b9b6e6edc3077d6 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/WideActions.lean @@ -0,0 +1,95 @@ +import OAI.Combinatorics.EditApproximation.Geometry.LocalGrid +import OAI.Combinatorics.EditApproximation.Geometry.InitialConeGrid +import OAI.Combinatorics.EditApproximation.Probability.FiniteAssignments +import OAI.Combinatorics.EditApproximation.Geometry.BalancedIntervals +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! +# Executable wide action lists + +Endpoint indices are generated in the radius-`10b` grid boxes anchored +at the physical source cuts. Lists contain exactly the valid grid states +in those boxes and their Cartesian product over labeled children. +-/ + +namespace EditApproximation + + + +theorem gridStateBox_complete {n g radius lo hi : ℕ} (hg : 0 < g) + (r : TargetInterval n) (hlo : Nat.dist lo r.lo ≤ radius) + (hhi : Nat.dist hi r.hi ≤ radius) (hgrid : g ∣ r.lo ∧ g ∣ r.hi) : + r ∈ gridStateBox n g radius lo hi := by + have hlo' : lo - radius ≤ r.lo ∧ r.lo ≤ lo + radius := by unfold Nat.dist at hlo; omega + have hhi' : hi - radius ≤ r.hi ∧ r.hi ≤ hi + radius := by unfold Nat.dist at hhi; omega + apply List.mem_flatMap.mpr + refine ⟨r.lo, gridPointsBetween_complete hg hlo'.1 hlo'.2 hgrid.1, ?_⟩ + apply List.mem_filterMap.mpr + refine ⟨r.hi, gridPointsBetween_complete hg hhi'.1 hhi'.2 hgrid.2, ?_⟩ + rw [makeTargetState, dite_eq_left (show r.lo ≤ r.hi ∧ r.hi ≤ n from ⟨r.ordered, r.valid⟩)] + +theorem gridStateBox_length_le (n g radius lo hi : ℕ) (hg : 0 < g) : + (gridStateBox n g radius lo hi).length ≤ (2 * radius / g + 2) ^ 2 := by + have hpoint (p : ℕ) : + (gridPointsBetween g (p - radius) (p + radius)).length ≤ 2 * radius / g + 2 := by + have hlength := gridPointsBetween_length_le g (p - radius) (p + radius) hg + have hwidth : p + radius - (p - radius) ≤ 2 * radius := by omega + exact hlength.trans (Nat.add_le_add_right (Nat.div_le_div_right hwidth) 2) + have hlist := list_flatMap_length_le + (gridPointsBetween g (lo - radius) (lo + radius)) + (fun s => (gridPointsBetween g (hi - radius) (hi + radius)).filterMap + fun t => makeTargetState n s t) + (2 * radius / g + 2) (by intro s hs; exact (List.length_filterMap_le _ _).trans (hpoint hi)) + exact hlist.trans (by simpa only [pow_two] using + (Nat.mul_le_mul_right (2 * radius / g + 2) (hpoint lo))) + + + + + +theorem wideActionList_complete {nx ny M b P : ℕ} (parent : TargetInterval nx) + (r : TargetInterval ny) (action : Fin M → TargetInterval ny) + (hgrid : ∀ i, seedGridSpacing b P ∣ (action i).lo ∧ seedGridSpacing b P ∣ (action i).hi) + (hlo : ∀ i, Nat.dist (r.lo + ((sourceChild parent i).lo - parent.lo)) (action i).lo ≤ 10 * b) + (hhi : ∀ i, Nat.dist (r.lo + ((sourceChild parent i).hi - parent.lo)) (action i).hi ≤ 10 * b) : + action ∈ wideActionList M parent r b P := by + apply finiteAssignments_complete + intro i + exact gridStateBox_complete (by unfold seedGridSpacing; omega) (action i) + (hlo i) (hhi i) (hgrid i) + +theorem seedGridSpacing_radius_count (b P : ℕ) (hP : 0 < P) : + 20 * b / seedGridSpacing b P + 2 ≤ 40 * P + 2 := by + let g := seedGridSpacing b P + have hg : 0 < g := by unfold g seedGridSpacing; omega + have hg1 : 1 ≤ g := hg + have hquot : b / P ≤ g := le_max_right _ _ + have hdiv := Nat.lt_mul_div_succ b hP + have hprod : b < 2 * P * g := by nlinarith + have hscale : 20 * b < (40 * P + 1) * g := by nlinarith + have hresult := (Nat.div_lt_iff_lt_mul hg).2 hscale + change 20 * b / g + 2 ≤ 40 * P + 2 + omega + +theorem wideActionList_length_le {nx ny : ℕ} (M : ℕ) (parent : TargetInterval nx) + (r : TargetInterval ny) (b P : ℕ) (hP : 0 < P) : + (wideActionList M parent r b P).length ≤ (40 * P + 2) ^ (2 * M) := by + have hchoices (i : Fin M) : (wideChildStateList parent r b P i).length ≤ (40 * P + 2) ^ 2 := by + have hlocal := gridStateBox_length_le ny (seedGridSpacing b P) (10 * b) + (r.lo + ((sourceChild parent i).lo - parent.lo)) + (r.lo + ((sourceChild parent i).hi - parent.lo)) + (by unfold seedGridSpacing; omega) + have hcount := seedGridSpacing_radius_count b P hP + apply hlocal.trans + apply Nat.pow_le_pow_left + simpa only [show 2 * (10 * b) = 20 * b by omega] using hcount + have h := finiteAssignments_length_le M ((40 * P + 2) ^ 2) + (wideChildStateList parent r b P) hchoices + simpa only [wideActionList, ← pow_mul] using h + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/WideBellman.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/WideBellman.lean new file mode 100644 index 0000000000000000000000000000000000000000..ebc08fea4e63c4115f16b7f227170836b282e7b8 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/WideBellman.lean @@ -0,0 +1,83 @@ +import OAI.Combinatorics.EditApproximation.Geometry.ActualActionValues +import OAI.Combinatorics.EditApproximation.Geometry.WideActions +import OAI.Combinatorics.EditApproximation.Geometry.Bellman + +namespace OAI + +/-! Bellman cones of the actual labeled finite wide actions preserve both lower invariants. -/ + +namespace EditApproximation + +open Finset + +noncomputable def actualWideActions {nx ny M : ℕ} (parent : TargetInterval nx) + (representatives : List (ℕ × TargetInterval ny)) (P : ℕ) : + List (BellmanAction (TargetInterval ny) (Fin M × TargetInterval ny) M) := + representatives.flatMap fun br => (wideActionList M parent br.2 br.1 P).map fun states => + ⟨br.2, endpointActionConnection br.2 states, fun i => (i, states i)⟩ + +noncomputable def actualWideBellman {nx ny M : ℕ} (parent : TargetInterval nx) + (representatives : List (ℕ × TargetInterval ny)) (P : ℕ) + (initial : TargetInterval ny → ℝ) (L : ℝ) + (child : Fin M → TargetInterval ny → ℝ) (q : TargetInterval ny) : ℝ := + finiteBellman initial (fun q r => targetEndpointDistance q r) L + (actualWideActions parent representatives P) (fun is => child is.1 is.2) q + +theorem actual_coned_action_lower {α : Type*} (source target : List α) + {M : ℕ} (hM : 0 < M) (parent : TargetInterval source.length) + (q r : TargetInterval target.length) (states : Fin M → TargetInterval target.length) + (a L : ℝ) (ha : 1 ≤ a) (hL : 1 ≤ L) + (child : Fin M → TargetInterval target.length → ℝ) + (hchild : ∀ i s, max ((stateEditCost + (substring source (sourceChild parent i).lo (sourceChild parent i).hi) target s : ℝ) / a) + |stateLengthGap (substring source (sourceChild parent i).lo (sourceChild parent i).hi) target s| ≤ + child i s) : + max ((stateEditCost (substring source parent.lo parent.hi) target q : ℝ) / a) + |stateLengthGap (substring source parent.lo parent.hi) target q| ≤ + L * targetEndpointDistance q r + endpointActionValue r states child := by + have hcenter := actual_endpoint_action_lower source target hM parent r states a ha child + (fun i => (le_max_left _ _).trans (hchild i (states i))) + (fun i => (le_max_right _ _).trans (hchild i (states i))) + have hcost := (le_max_left _ _).trans hcenter + have hgap := (le_max_right _ _).trans hcenter + have ha0 : 0 < a := by linarith + have hdist0 : (0 : ℝ) ≤ targetEndpointDistance q r := Nat.cast_nonneg _ + have hcharge : (targetEndpointDistance q r : ℝ) ≤ L * targetEndpointDistance q r := by + simpa only [one_mul] using mul_le_mul_of_nonneg_right hL hdist0 + apply max_le + · have hspatial : (stateEditCost (substring source parent.lo parent.hi) target q : ℝ) ≤ + stateEditCost (substring source parent.lo parent.hi) target r + targetEndpointDistance q r := by + exact_mod_cast stateEditCost_spatial (substring source parent.lo parent.hi) target q r + have hscaled := div_le_div_of_nonneg_right hspatial ha0.le + have hdiv : (targetEndpointDistance q r : ℝ) / a ≤ targetEndpointDistance q r := by + apply (div_le_iff₀ ha0).2 + simpa only [one_mul, mul_one, mul_comm] using mul_le_mul_of_nonneg_right ha hdist0 + rw [add_div] at hscaled + linarith + · have hspatial := stateLengthGap_spatial (substring source parent.lo parent.hi) target q r + linarith + +theorem actualWideBellman_lower {α : Type*} (source target : List α) + {M : ℕ} (hM : 0 < M) (parent : TargetInterval source.length) + (representatives : List (ℕ × TargetInterval target.length)) (P : ℕ) + (initial : TargetInterval target.length → ℝ) (a L : ℝ) (ha : 1 ≤ a) (hL : 1 ≤ L) + (child : Fin M → TargetInterval target.length → ℝ) + (hinit : ∀ q, max ((stateEditCost (substring source parent.lo parent.hi) target q : ℝ) / a) + |stateLengthGap (substring source parent.lo parent.hi) target q| ≤ initial q) + (hchild : ∀ i s, max ((stateEditCost + (substring source (sourceChild parent i).lo (sourceChild parent i).hi) target s : ℝ) / a) + |stateLengthGap (substring source (sourceChild parent i).lo (sourceChild parent i).hi) target s| ≤ + child i s) (q : TargetInterval target.length) : + max ((stateEditCost (substring source parent.lo parent.hi) target q : ℝ) / a) + |stateLengthGap (substring source parent.lo parent.hi) target q| ≤ + actualWideBellman parent representatives P initial L child q := by + apply finiteBellman_lower initial _ _ _ _ _ hinit + intro query action haction + obtain ⟨br, hbr, haction⟩ := List.mem_flatMap.mp haction + obtain ⟨states, hstates, rfl⟩ := List.mem_map.mp haction + simpa only [bellmanActionValue, endpointActionValue, add_assoc] using + actual_coned_action_lower source target hM parent query br.2 states a L ha hL child hchild + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/WideEarlierInputs.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/WideEarlierInputs.lean new file mode 100644 index 0000000000000000000000000000000000000000..017e3c0dc6e8c95ec1df51f0a8973e8da97c0115 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/WideEarlierInputs.lean @@ -0,0 +1,117 @@ +import OAI.Combinatorics.EditApproximation.Geometry.CurrentQueryInputs +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Wide enumeration gathers child states before scoring its Cartesian +action list. Its recursive input count depends on the coordinate lists, +rather than the exponentially larger number of complete actions. -/ + +namespace EditApproximation + +open Finset + +theorem wideEarlierChildStateList_length_le {nx ny M : ℕ} (parent : TargetInterval nx) + (r : TargetInterval ny) (b P : ℕ) (hP : 0 < P) (i : Fin M) : + (wideChildStateList parent r b P i).length ≤ (40 * P + 2) ^ 2 := by + have hlocal := gridStateBox_length_le ny (seedGridSpacing b P) (10 * b) + (r.lo + ((sourceChild parent i).lo - parent.lo)) + (r.lo + ((sourceChild parent i).hi - parent.lo)) + (by unfold seedGridSpacing; omega) + apply hlocal.trans + apply Nat.pow_le_pow_left + simpa only [show 2 * (10 * b) = 20 * b by omega] using seedGridSpacing_radius_count b P hP + + + +theorem wideEarlierInputCover_card {nx ny M : ℕ} (parent : TargetInterval nx) (P history : ℕ) + (representatives : List (ℕ × TargetInterval ny)) (hP : 0 < P) : + (wideEarlierInputCover (M := M) parent P history representatives).card ≤ + representatives.length * M * history * (40 * P + 2) ^ 2 := by + have hstates (br : ℕ × TargetInterval ny) (i : Fin M) (t : ℕ) : + (((wideChildStateList parent br.2 br.1 P i).toFinset).image fun r => (i, t, r)).card ≤ + (40 * P + 2) ^ 2 := + (Finset.card_image_le).trans ((List.toFinset_card_le _).trans + (wideEarlierChildStateList_length_le parent br.2 br.1 P hP i)) + have hhistory (br : ℕ × TargetInterval ny) (i : Fin M) : + ((Finset.range history).biUnion fun t => + ((wideChildStateList parent br.2 br.1 P i).toFinset).image fun r => (i, t, r)).card ≤ + history * (40 * P + 2) ^ 2 := by + exact Finset.card_biUnion_le.trans + ((Finset.sum_le_sum fun t _ => hstates br i t).trans_eq (by simp)) + have hchildren (br : ℕ × TargetInterval ny) : + (Finset.univ.biUnion fun i : Fin M => + (Finset.range history).biUnion fun t => + ((wideChildStateList parent br.2 br.1 P i).toFinset).image fun r => (i, t, r)).card ≤ + M * (history * (40 * P + 2) ^ 2) := by + exact Finset.card_biUnion_le.trans + ((Finset.sum_le_sum fun i _ => hhistory br i).trans_eq (by simp)) + unfold wideEarlierInputCover + calc + _ ≤ ∑ br ∈ representatives.toFinset, M * (history * (40 * P + 2) ^ 2) := + Finset.card_biUnion_le.trans (Finset.sum_le_sum fun br _ => hchildren br) + _ = representatives.toFinset.card * (M * (history * (40 * P + 2) ^ 2)) := by simp + _ ≤ representatives.length * (M * (history * (40 * P + 2) ^ 2)) := + Nat.mul_le_mul_right _ (List.toFinset_card_le representatives) + _ = _ := by ring + +theorem wideEarlierInputCover_mem {nx ny M : ℕ} (parent : TargetInterval nx) (P history : ℕ) + (representatives : List (ℕ × TargetInterval ny)) (b : ℕ) (r : TargetInterval ny) + (hrep : (b, r) ∈ representatives) (t : ℕ) (ht : t < history) + (action : Fin M → TargetInterval ny) (ha : action ∈ wideActionList M parent r b P) + (i : Fin M) : (i, t, action i) ∈ wideEarlierInputCover parent P history representatives := by + apply Finset.mem_biUnion.mpr + refine ⟨(b, r), List.mem_toFinset.mpr hrep, Finset.mem_biUnion.mpr ?_⟩ + refine ⟨i, Finset.mem_univ _, Finset.mem_biUnion.mpr ?_⟩ + refine ⟨t, Finset.mem_range.mpr ht, Finset.mem_image.mpr ?_⟩ + exact ⟨action i, List.mem_toFinset.mpr (finiteAssignments_sound M _ action ha i), rfl⟩ + +theorem bandCoordinates_earlier_cover {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (P history b : ℕ) (tau theta : ℚ) + (representatives : List (ℕ × TargetInterval target.length)) (r : TargetInterval target.length) + (hrep : (b, r) ∈ representatives) (child : Fin M → TargetInterval target.length → ℚ) + (t : ℕ) (ht : t < history) (coordinate : Fin M × TargetInterval target.length) + (hcoordinate : coordinate ∈ bandCoordinates + (representativeBandActions source target parent r b P tau theta child).toFinset) : + (coordinate.1, t, coordinate.2) ∈ wideEarlierInputCover parent P history representatives := by + obtain ⟨action, ha, hcoordinate⟩ := Finset.mem_biUnion.mp hcoordinate + obtain ⟨i, _, heq⟩ := Finset.mem_image.mp hcoordinate + obtain rfl : coordinate = (i, action i) := heq.symm + exact wideEarlierInputCover_mem parent P history representatives b r hrep t ht action + (representativeBandActions_wide source target parent r b P tau theta child action + (List.mem_toFinset.mp ha)) i + +theorem localRefinementRepresentatives_length {n : ℕ} (N P F : ℕ) (a : ℚ) + (initial : TargetInterval n → ℚ) (q : TargetInterval n) (hP : 0 < P) (hF : 1 ≤ F) : + (localRefinementRepresentatives N P F a initial q).length ≤ + (dyadicQueryWindow N (initial q) a F).length * (64 * F * P + 2) ^ 2 := by + unfold localRefinementRepresentatives + apply list_flatMap_length_le + intro b hb + have hwindow := of_decide_eq_true (List.mem_filter.mp hb).2 + have hceil : ⌈initial q⌉₊ ≤ 16 * F * b := by + apply Nat.ceil_le.mpr + have hFpos : (0 : ℚ) < F := Nat.cast_pos.mpr (by omega) + have h := (div_le_iff₀ (by positivity : (0 : ℚ) < 16 * F)).mp hwindow.1 + push_cast + nlinarith only [h] + have hg : 0 < seedGridSpacing b P := by unfold seedGridSpacing; omega + have hcover : b ≤ 2 * P * seedGridSpacing b P := by + have hquot : b / P ≤ seedGridSpacing b P := le_max_right _ _ + have hdiv := Nat.lt_mul_div_succ b hP + nlinarith only [hquot, hdiv, hg] + have hcount : 2 * ⌈initial q⌉₊ / seedGridSpacing b P + 2 ≤ 64 * F * P + 2 := by + have hprod : 2 * ⌈initial q⌉₊ ≤ 64 * F * P * seedGridSpacing b P := by + nlinarith only [hceil, Nat.mul_le_mul_left (32 * F) hcover] + have hdiv := Nat.div_mul_le_self (2 * ⌈initial q⌉₊) (seedGridSpacing b P) + have hquot : 2 * ⌈initial q⌉₊ / seedGridSpacing b P ≤ 64 * F * P := by + nlinarith only [hprod, hdiv, hg] + exact Nat.add_le_add_right hquot 2 + have hlocal := localTargetStates_length_le (radius := ⌈initial q⌉₊) hg q + simpa only [List.length_map] using + (List.length_filter_le _ _).trans (hlocal.trans (Nat.pow_le_pow_left hcount 2)) + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Geometry/Work.lean b/lean/OAI/Combinatorics/EditApproximation/Geometry/Work.lean new file mode 100644 index 0000000000000000000000000000000000000000..833e6dcd16a3ee0e8a0509daab087a39baeb2427 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Geometry/Work.lean @@ -0,0 +1,50 @@ +import Mathlib + +namespace OAI + +/-! +# Finite dependency-path accounting + +The double sum is the dependency-path budget in Section 10 of the +edit-distance manuscript, with separate branching bounds for same-index +and earlier-index requests. +-/ + +namespace EditApproximation + +open Finset + +/-- Overcount of dependency paths with at most `depth` descending edges +and `indices` strictly earlier-index/pass edges. -/ +def dependencyPathBudget (depth indices same earlier : ℕ) : ℕ := + ∑ r ∈ range (depth + 1), ∑ s ∈ range (indices + 1), + (r + s).choose r * same ^ r * earlier ^ s + +/-- Explicit bound on the double sum, before substituting asymptotic +parameters. All quantities are natural numbers. -/ +theorem dependencyPathBudget_le (depth indices same earlier : ℕ) + (hsame : 1 ≤ same) (hearlier : 1 ≤ earlier) : + dependencyPathBudget depth indices same earlier ≤ + (depth + 1) * (indices + 1) * 2 ^ (depth + indices) * + same ^ depth * earlier ^ indices := by + let bound := 2 ^ (depth + indices) * same ^ depth * earlier ^ indices + have hterm (r s : ℕ) (hr : r ≤ depth) (hs : s ≤ indices) : + (r + s).choose r * same ^ r * earlier ^ s ≤ bound := by + have hchoose := (Nat.choose_le_two_pow (r + s) r).trans + (pow_le_pow_right' (by omega : 1 ≤ (2 : ℕ)) (Nat.add_le_add hr hs)) + exact Nat.mul_le_mul (Nat.mul_le_mul hchoose (pow_le_pow_right' hsame hr)) + (pow_le_pow_right' hearlier hs) + have hsum : dependencyPathBudget depth indices same earlier ≤ + ∑ _r ∈ range (depth + 1), ∑ _s ∈ range (indices + 1), bound := by + apply sum_le_sum + intro r hr + apply sum_le_sum + intro s hs + exact hterm r s (by simpa using mem_range.mp hr) (by simpa using mem_range.mp hs) + apply hsum.trans_eq + simp only [sum_const, card_range, smul_eq_mul, bound] + ring + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Numerics/GradientStorageBits.lean b/lean/OAI/Combinatorics/EditApproximation/Numerics/GradientStorageBits.lean new file mode 100644 index 0000000000000000000000000000000000000000..dd7efa96b0e98d7e5f7b510662b4d68e98c9468a --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Numerics/GradientStorageBits.lean @@ -0,0 +1,105 @@ +import OAI.Combinatorics.EditApproximation.Numerics.RationalIntermediateBits +import OAI.Combinatorics.EditApproximation.Numerics.VectorOptimizerWork + +namespace OAI + +/-! Polynomial bounds for the rational data stored by the gradient and +linear-score routines, including the finite logarithm sums. -/ + +namespace EditApproximation + +open Finset + +def logarithmEncodingBudget (inputBits K : ℕ) : ℕ := + 2 * (K * K * inputBits + K * Nat.size (2 * K + 1) + 2) + Nat.size (2 * K) + 1 + +theorem rationalLogApproximation_encoding_le (r : ℚ) (K B : ℕ) + (hr : 0 ≤ r) (hbits : rationalEncodingBits r ≤ B) : + rationalEncodingBits (rationalLogApproximation r K) ≤ logarithmEncodingBudget B K := by + apply (rationalLogApproximation_encoding_bit_length r K hr).trans + unfold logarithmEncodingBudget + have h := Nat.mul_le_mul_left (K * K) hbits + omega + +def smoothedPointEncodingBudget (G B : ℕ) : ℕ := 2 * B + 100 * Nat.size G + 400 + +theorem smoothedPoint_encoding_le (r : ℚ) (G B : ℕ) (hbits : rationalEncodingBits r ≤ B) : + rationalEncodingBits (r + 1 / (G : ℚ) ^ 50) ≤ smoothedPointEncodingBudget G B := by + have hpow := rationalEncodingBits_pow (G : ℚ) 50 + rw [rationalEncodingBits_natCast] at hpow + have hinv := rationalEncodingBits_inv ((G : ℚ) ^ 50) + have hadd := rationalEncodingBits_add r (1 / (G : ℚ) ^ 50) + rw [one_div] at hadd + rw [one_div] + unfold smoothedPointEncodingBudget + omega + +def gradientEncodingBudget (G pointBits linearBits : ℕ) : ℕ := + 4 * logarithmEncodingBudget (smoothedPointEncodingBudget G pointBits) (G ^ 60) + + 2 * linearBits + 20 + +theorem rationalSmoothedGradient_encoding_le {ι : Type*} (G : ℕ) + (linear point : ι → ℚ) (i : ι) (pointBits linearBits : ℕ) + (hpoint : 0 ≤ point i) (hpbits : rationalEncodingBits (point i) ≤ pointBits) + (hlbits : rationalEncodingBits (linear i) ≤ linearBits) : + rationalEncodingBits (rationalSmoothedGradient G linear point i) ≤ + gradientEncodingBudget G pointBits linearBits := by + have hsmooth := smoothedPoint_encoding_le (point i) G pointBits hpbits + have hnonneg : 0 ≤ point i + 1 / (G : ℚ) ^ 50 := + add_nonneg hpoint (div_nonneg (by norm_num) (pow_nonneg (Nat.cast_nonneg _) _)) + have hlog := rationalLogApproximation_encoding_le _ (G ^ 60) _ hnonneg hsmooth + have hsub := rationalEncodingBits_sub + (-rationalLogApproximation (point i + 1 / (G : ℚ) ^ 50) (G ^ 60)) 1 + rw [rationalEncodingBits_neg] at hsub + have hadd := rationalEncodingBits_add + (-rationalLogApproximation (point i + 1 / (G : ℚ) ^ 50) (G ^ 60) - 1) (linear i) + have hone : rationalEncodingBits (1 : ℚ) = 3 := by norm_num [rationalEncodingBits] + rw [hone] at hsub + unfold rationalSmoothedGradient gradientEncodingBudget + omega + +theorem rational_finite_sum_encoding_le {ι : Type*} (s : Finset ι) (values : ι → ℚ) + (V B : ℕ) (habs : ∀ i ∈ s, |values i| ≤ V) + (hbits : ∀ i ∈ s, Nat.size (values i).den ≤ B) : + rationalEncodingBits (∑ i ∈ s, values i) ≤ Nat.size (s.card * V) + 2 * (s.card * B + 1) + 1 := by + have hdenpos : 0 < ∏ i ∈ s, (values i).den := Finset.prod_pos (fun i _ => Rat.den_pos _) + have hden := (Nat.size_le_size (Nat.le_of_dvd hdenpos + (rational_finite_sum_denominator s values))).trans (natural_finite_product_bit_length s _) + have hsum : (∑ i ∈ s, Nat.size (values i).den) ≤ s.card * B := by + calc + _ ≤ ∑ _i ∈ s, B := Finset.sum_le_sum hbits + _ = _ := by simp + have htotal : |∑ i ∈ s, values i| ≤ ((s.card * V : ℕ) : ℚ) := by + calc + _ ≤ ∑ i ∈ s, |values i| := abs_sum_le_sum_abs _ _ + _ ≤ ∑ _i ∈ s, (V : ℚ) := Finset.sum_le_sum habs + _ = _ := by simp + have hnum := (Nat.size_le_size (rational_numerator_bound _ (s.card * V) htotal)).trans + (natural_product_bit_length _ _) + unfold rationalEncodingBits + omega + +theorem vectorDotWithWork_encoding_le {d : ℕ} (left right : Vector ℚ d) + (L R Bleft Bright : ℕ) + (hleft : ∀ i, |left.get i| ≤ L) + (hright : ∀ i, |right.get i| ≤ R) + (hleftbits : ∀ i, Nat.size (left.get i).den ≤ Bleft) + (hrightbits : ∀ i, Nat.size (right.get i).den ≤ Bright) : + rationalEncodingBits (vectorDotWithWork left right).1 ≤ + Nat.size (d * (L * R)) + 2 * (d * (Bleft + Bright) + 1) + 1 := by + rw [vectorDotWithWork_spec] + simpa only [Prod.fst, Finset.card_univ, Fintype.card_fin] using + (rational_finite_sum_encoding_le (Finset.univ : Finset (Fin d)) + (fun i => left.get i * right.get i) (L * R) (Bleft + Bright) (by + intro i _ + rw [abs_mul] + exact_mod_cast mul_le_mul (hleft i) (hright i) (abs_nonneg _) (Nat.cast_nonneg _)) (by + intro i _ + exact (Nat.size_le_size (Nat.le_of_dvd + (Nat.mul_pos (Rat.den_pos _) (Rat.den_pos _)) (Rat.mul_den_dvd _ _))).trans + ((natural_product_bit_length _ _).trans + (Nat.add_le_add (hleftbits i) (hrightbits i))))) + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Numerics/NumericalWork.lean b/lean/OAI/Combinatorics/EditApproximation/Numerics/NumericalWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..ac11e6f1d743dffa62a9201d29bb478042a475cb --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Numerics/NumericalWork.lean @@ -0,0 +1,317 @@ +import OAI.Combinatorics.EditApproximation.Numerics.Numerics + +namespace OAI + +/-! +# Concrete numerical representation and arithmetic work + +These are integer bit-length and exact rational-operation bounds for the +finite optimizer. They are not a RAM theorem: the costed evaluator below +counts rational arithmetic operations, while bit-operation costs also +require the charged evaluation model used by the surrounding algorithm. +-/ + +namespace EditApproximation + +open Finset + +/-- Signed numerator plus positive denominator encoding length. -/ +def rationalEncodingBits (r : ℚ) : ℕ := Nat.size r.num.natAbs + Nat.size r.den + 1 + +theorem natural_product_bit_length (a b : ℕ) : + Nat.size (a * b) ≤ Nat.size a + Nat.size b := by + apply Nat.size_le.mpr + calc + a * b ≤ a * 2 ^ Nat.size b := Nat.mul_le_mul_left a (Nat.lt_size_self b).le + _ < 2 ^ Nat.size a * 2 ^ Nat.size b := + Nat.mul_lt_mul_of_pos_right (Nat.lt_size_self a) (by positivity) + _ = 2 ^ (Nat.size a + Nat.size b) := (pow_add _ _ _).symm + +theorem natural_sum_bit_length (a b : ℕ) : + Nat.size (a + b) ≤ Nat.size a + Nat.size b + 1 := by + apply Nat.size_le.mpr + have ha : a < 2 ^ (Nat.size a + Nat.size b) := + (Nat.lt_size_self a).trans_le (Nat.pow_le_pow_right (by norm_num) (by omega)) + have hb : b < 2 ^ (Nat.size a + Nat.size b) := + (Nat.lt_size_self b).trans_le (Nat.pow_le_pow_right (by norm_num) (by omega)) + rw [pow_succ] + omega + +theorem natural_power_bit_length (a n : ℕ) : + Nat.size (a ^ n) ≤ n * Nat.size a + 1 := by + induction n with + | zero => simp + | succ n ih => + rw [pow_succ] + have hmul := natural_product_bit_length (a ^ n) a + nlinarith + +theorem natural_finite_product_bit_length {ι : Type*} (s : Finset ι) (f : ι → ℕ) : + Nat.size (∏ i ∈ s, f i) ≤ (∑ i ∈ s, Nat.size (f i)) + 1 := by + classical + induction s using Finset.induction_on with + | empty => simp + | @insert i s hi ih => + rw [prod_insert hi, sum_insert hi] + have hmul := natural_product_bit_length (f i) (∏ j ∈ s, f j) + omega + +/-- Denominator of a finite rational sum divides the product of the +individual denominators. -/ +theorem rational_finite_sum_denominator {ι : Type*} (s : Finset ι) (values : ι → ℚ) : + (∑ i ∈ s, values i).den ∣ ∏ i ∈ s, (values i).den := by + classical + induction s using Finset.induction_on with + | empty => simp + | @insert i s hi ih => + rw [sum_insert hi, prod_insert hi] + exact (Rat.add_den_dvd _ _).trans (Nat.mul_dvd_mul (dvd_refl _) ih) + +/-- The symmetric logarithm parameter has a denominator bounded by +the input's numerator/denominator height. -/ +theorem logarithm_parameter_denominator (r : ℚ) : + ((r - 1) / (r + 1)).den ≤ r.num.natAbs + r.den := by + have hden : (r.den : ℚ) ≠ 0 := by exact_mod_cast r.den_ne_zero + have hparameter : (r - 1) / (r + 1) = + Rat.divInt (r.num - (r.den : ℤ)) (r.num + (r.den : ℤ)) := by + rw [Rat.divInt_eq_div] + push_cast + conv_lhs => rw [← r.num_div_den] + rw [div_sub_one hden, div_add_one hden, div_div_div_cancel_right₀ hden] + rw [hparameter] + by_cases hzero : r.num + (r.den : ℤ) = 0 + · simp only [hzero, Rat.divInt_zero, Rat.den_zero] + have hpositive := r.den_pos + omega + · have hdivides := Rat.den_dvd (r.num - (r.den : ℤ)) (r.num + (r.den : ℤ)) + have hdividesNat : (Rat.divInt (r.num - (r.den : ℤ)) (r.num + (r.den : ℤ))).den ∣ + (r.num + (r.den : ℤ)).natAbs := by + simpa only [Int.natAbs_natCast] using Int.natAbs_dvd_natAbs.mpr hdivides + exact (Nat.le_of_dvd (Int.natAbs_pos.mpr hzero) hdividesNat).trans (by + simpa only [Int.natAbs_natCast] using Int.natAbs_add_le r.num (r.den : ℤ)) + +theorem logarithm_parameter_bit_length (r : ℚ) : + Nat.size ((r - 1) / (r + 1)).den ≤ rationalEncodingBits r := by + exact (Nat.size_le_size (logarithm_parameter_denominator r)).trans + (natural_sum_bit_length r.num.natAbs r.den) + +def logarithmDenominatorBudget (r : ℚ) (K : ℕ) : ℕ := + ((r - 1) / (r + 1)).den ^ (K * K) * ∏ k ∈ range K, (2 * k + 1) + +theorem sum_odd_logarithm_exponents (K : ℕ) : + (∑ k ∈ range K, (2 * k + 1)) = K * K := by + induction K with + | zero => simp + | succ K ih => rw [sum_range_succ, ih]; ring + +/-- A concrete unreduced denominator for every finite logarithm sum. +The exponent `K²` is deliberately loose and keeps the proof elementary. -/ +theorem rationalLogApproximation_denominator (r : ℚ) (K : ℕ) : + (rationalLogApproximation r K).den ∣ logarithmDenominatorBudget r K := by + let b := (r - 1) / (r + 1) + have hterm k : (b ^ (2 * k + 1) / (2 * k + 1 : ℕ)).den ∣ + b.den ^ (2 * k + 1) * (2 * k + 1) := by + have hmul := Rat.mul_den_dvd (b ^ (2 * k + 1)) (((2 * k + 1 : ℕ) : ℚ)⁻¹) + rw [Rat.den_pow, Rat.inv_natCast_den_of_pos (by omega : 0 < 2 * k + 1)] at hmul + simpa only [div_eq_mul_inv] using hmul + have hsum := rational_finite_sum_denominator (range K) + (fun k => b ^ (2 * k + 1) / (2 * k + 1 : ℕ)) + have hproducts := Finset.prod_dvd_prod_of_dvd (s := range K) + (fun k => (b ^ (2 * k + 1) / (2 * k + 1 : ℕ)).den) + (fun k => b.den ^ (2 * k + 1) * (2 * k + 1)) (fun k _ => hterm k) + have hproduct : (∏ k ∈ range K, b.den ^ (2 * k + 1) * (2 * k + 1)) = + logarithmDenominatorBudget r K := by + rw [prod_mul_distrib, prod_pow_eq_pow_sum, sum_odd_logarithm_exponents] + rfl + have htwice := Rat.mul_den_dvd (2 : ℚ) + (∑ k ∈ range K, b ^ (2 * k + 1) / (2 * k + 1 : ℕ)) + norm_num only [Rat.den_ofNat, one_mul] at htwice + simpa only [rationalLogApproximation, b, Nat.cast_add, Nat.cast_mul, Nat.cast_one, Nat.cast_ofNat] using + htwice.trans (hsum.trans (hproduct ▸ hproducts)) + +theorem logarithmDenominatorBudget_positive (r : ℚ) (K : ℕ) : + 0 < logarithmDenominatorBudget r K := by + unfold logarithmDenominatorBudget + exact Nat.mul_pos (pow_pos (Rat.den_pos _) _) (prod_pos (fun k _ => by omega)) + +/-- Polynomial bit length of the actual logarithm denominator in the +input encoding length and truncation count. -/ +theorem rationalLogApproximation_denominator_bit_length (r : ℚ) (K : ℕ) : + Nat.size (rationalLogApproximation r K).den ≤ + K * K * rationalEncodingBits r + K * Nat.size (2 * K + 1) + 2 := by + have hden := Nat.le_of_dvd (logarithmDenominatorBudget_positive r K) + (rationalLogApproximation_denominator r K) + have hmono := Nat.size_le_size hden + have hmul := natural_product_bit_length (((r - 1) / (r + 1)).den ^ (K * K)) + (∏ k ∈ range K, (2 * k + 1)) + have hpower := natural_power_bit_length ((r - 1) / (r + 1)).den (K * K) + have hproduct := natural_finite_product_bit_length (range K) (fun k => 2 * k + 1) + have hsum : (∑ k ∈ range K, Nat.size (2 * k + 1)) ≤ K * Nat.size (2 * K + 1) := by + calc + _ ≤ ∑ _ ∈ range K, Nat.size (2 * K + 1) := sum_le_sum (fun k hk => + Nat.size_le_size (by have hkK := mem_range.mp hk; omega)) + _ = _ := by simp + have hinput := Nat.mul_le_mul_left (K * K) (logarithm_parameter_bit_length r) + dsimp only [logarithmDenominatorBudget] at hmono + omega + +/-- Costed repeated multiplication, counting one rational +multiplication at each successor. -/ +def rationalPowerWithWork (r : ℚ) : ℕ → ℚ × ℕ + | 0 => (1, 0) + | n + 1 => let previous := rationalPowerWithWork r n + (previous.1 * r, previous.2 + 1) + +theorem rationalPowerWithWork_spec (r : ℚ) (n : ℕ) : + rationalPowerWithWork r n = (r ^ n, n) := by + induction n with + | zero => simp [rationalPowerWithWork] + | succ n ih => simp [rationalPowerWithWork, ih, pow_succ] + +/-- The direct finite logarithm summation, with every power, +division and addition counted. -/ +def rationalLogPartialWithWork (b : ℚ) : ℕ → ℚ × ℕ + | 0 => (0, 0) + | K + 1 => + let previous := rationalLogPartialWithWork b K + let power := rationalPowerWithWork b (2 * K + 1) + (previous.1 + power.1 / (2 * K + 1 : ℕ), previous.2 + power.2 + 2) + +theorem rationalLogPartialWithWork_spec (b : ℚ) (K : ℕ) : + rationalLogPartialWithWork b K = + (∑ k ∈ range K, b ^ (2 * k + 1) / (2 * k + 1 : ℕ), K * K + 2 * K) := by + induction K with + | zero => simp [rationalLogPartialWithWork] + | succ K ih => + simp only [rationalLogPartialWithWork, ih, rationalPowerWithWork_spec, sum_range_succ] + congr 1 + ring + +/-- Three operations form the logarithm parameter, and one final +multiplication doubles the partial sum. -/ +def rationalLogApproximationWithWork (r : ℚ) (K : ℕ) : ℚ × ℕ := + let seriesResult := rationalLogPartialWithWork ((r - 1) / (r + 1)) K + (2 * seriesResult.1, seriesResult.2 + 4) + +/-- The actual logarithm evaluator uses exactly a quadratic number of +rational arithmetic operations and returns the already verified value. -/ +theorem rationalLogApproximationWithWork_spec (r : ℚ) (K : ℕ) : + rationalLogApproximationWithWork r K = + (rationalLogApproximation r K, K * K + 2 * K + 4) := by + simp [rationalLogApproximationWithWork, rationalLogPartialWithWork_spec, rationalLogApproximation] + +/-- Every logarithm series term is bounded on nonnegative inputs; +this controls the returned numerator without transcendental arithmetic. -/ +theorem rationalLogApproximation_abs_bound (r : ℚ) (K : ℕ) (hr : 0 ≤ r) : + |rationalLogApproximation r K| ≤ 2 * K := by + let b := (r - 1) / (r + 1) + have hrden : 0 < r + 1 := by linarith + have hb : |b| ≤ 1 := by + dsimp only [b] + rw [abs_div, abs_of_pos hrden] + apply (div_le_one₀ hrden).mpr + exact abs_le.mpr ⟨by linarith, by linarith⟩ + have hterm (k : ℕ) : |b ^ (2 * k + 1) / (2 * k + 1 : ℕ)| ≤ 1 := by + have hden : (1 : ℚ) ≤ (2 * k + 1 : ℕ) := by norm_cast; omega + have hdenpos : (0 : ℚ) < (2 * k + 1 : ℕ) := by positivity + rw [abs_div, abs_pow, abs_of_pos hdenpos] + calc + _ ≤ (1 : ℚ) / (2 * k + 1 : ℕ) := div_le_div_of_nonneg_right + (pow_le_one₀ (abs_nonneg b) hb) hdenpos.le + _ ≤ 1 := (div_le_one₀ hdenpos).mpr hden + have hsum : |∑ k ∈ range K, b ^ (2 * k + 1) / (2 * k + 1 : ℕ)| ≤ K := by + calc + _ ≤ ∑ k ∈ range K, |b ^ (2 * k + 1) / (2 * k + 1 : ℕ)| := abs_sum_le_sum_abs _ _ + _ ≤ ∑ _ ∈ range K, (1 : ℚ) := sum_le_sum (fun k _ => hterm k) + _ = K := by simp + unfold rationalLogApproximation + push_cast at hsum + dsimp only [b] at hsum + rw [abs_mul, abs_of_nonneg (by norm_num : (0 : ℚ) ≤ 2)] + linarith + +theorem rational_numerator_bound (r : ℚ) (M : ℕ) (hM : |r| ≤ M) : + r.num.natAbs ≤ M * r.den := by + have hscaled := mul_le_mul_of_nonneg_right hM (show (0 : ℚ) ≤ r.den by positivity) + have hnum : |r| * (r.den : ℚ) = (r.num.natAbs : ℚ) := by + calc + _ = |r * (r.den : ℚ)| := by rw [abs_mul, abs_of_nonneg (by positivity : (0 : ℚ) ≤ r.den)] + _ = |(r.num : ℚ)| := by rw [Rat.mul_den_eq_num] + _ = (r.num.natAbs : ℚ) := by rw [Nat.cast_natAbs, Int.cast_abs] + rw [hnum] at hscaled + exact_mod_cast hscaled + +/-- Polynomial bit-length bound for both numerator and denominator of +all actually returned logarithm approximations. -/ +theorem rationalLogApproximation_encoding_bit_length (r : ℚ) (K : ℕ) (hr : 0 ≤ r) : + rationalEncodingBits (rationalLogApproximation r K) ≤ + 2 * (K * K * rationalEncodingBits r + K * Nat.size (2 * K + 1) + 2) + + Nat.size (2 * K) + 1 := by + have habsolute := rationalLogApproximation_abs_bound r K hr + have habsolute' : |rationalLogApproximation r K| ≤ ((2 * K : ℕ) : ℚ) := by + simpa only [Nat.cast_mul, Nat.cast_ofNat] using habsolute + have hnum := Nat.size_le_size (rational_numerator_bound _ (2 * K) habsolute') + have hmul := natural_product_bit_length (2 * K) (rationalLogApproximation r K).den + have hden := rationalLogApproximation_denominator_bit_length r K + dsimp only [rationalEncodingBits] at hden ⊢ + omega + +/-- Stored mixture coefficients use a denominator dividing `K(K+1)`; +there is no growth with the number of earlier optimizer updates. -/ +theorem optimizerMixtureWeight_denominator (K j : ℕ) (hK : 0 < K) : + (optimizerMixtureWeight K j).den ∣ K * (K + 1) := by + have hrepresentation : optimizerMixtureWeight K j = + ((2 * (j + 1) : ℕ) : ℚ) * (((K * (K + 1) : ℕ) : ℚ))⁻¹ := by + unfold optimizerMixtureWeight + push_cast + ring + rw [hrepresentation] + have hpositive : 0 < K * (K + 1) := Nat.mul_pos hK (by omega) + simpa only [Rat.den_natCast, Rat.inv_natCast_den_of_pos hpositive, one_mul] using + Rat.mul_den_dvd (((2 * (j + 1) : ℕ) : ℚ)) (((K * (K + 1) : ℕ) : ℚ))⁻¹ + +theorem optimizerMixtureWeight_bit_length (K j : ℕ) (hK : 0 < K) : + Nat.size (optimizerMixtureWeight K j).den ≤ 2 * Nat.size K + 2 := by + have hpositive : 0 < K * (K + 1) := Nat.mul_pos hK (by omega) + have hden := Nat.size_le_size (Nat.le_of_dvd hpositive (optimizerMixtureWeight_denominator K j hK)) + have hmul := natural_product_bit_length K (K + 1) + have hadd := natural_sum_bit_length K 1 + norm_num only [Nat.size_one] at hadd + omega + +/-- Every actual rational iterate has a polynomial denominator bit +length in its trace length and the listed vertices' input bit bound. -/ +theorem rationalOptimizerIterate_denominator_bit_length {ι : Type*} + (initial : ι → ℚ) (selected : ℕ → ι → ℚ) (K B : ℕ) (hK : 0 < K) (i : ι) + (hinput : ∀ j ∈ range K, Nat.size (selected j i).den ≤ B) : + Nat.size (rationalOptimizerIterate initial selected K i).den ≤ + K * (2 * Nat.size K + 2 + B) + 1 := by + have hmixture := rationalOptimizerIterate_eq_mixture initial selected (K - 1) i + rw [Nat.sub_add_cancel (show 1 ≤ K by omega)] at hmixture + rw [hmixture] + have hdivides := rational_finite_sum_denominator (range K) + (fun j => optimizerMixtureWeight K j * selected j i) + have hpositive : 0 < ∏ j ∈ range K, (optimizerMixtureWeight K j * selected j i).den := + prod_pos (fun _ _ => Rat.den_pos _) + have hden := Nat.size_le_size (Nat.le_of_dvd hpositive hdivides) + have hproduct := natural_finite_product_bit_length (range K) + (fun j => (optimizerMixtureWeight K j * selected j i).den) + have hterm j (hj : j ∈ range K) : Nat.size (optimizerMixtureWeight K j * selected j i).den ≤ + 2 * Nat.size K + 2 + B := by + have hmulden := Nat.size_le_size (Nat.le_of_dvd + (Nat.mul_pos (Rat.den_pos (optimizerMixtureWeight K j)) (Rat.den_pos (selected j i))) + (Rat.mul_den_dvd (optimizerMixtureWeight K j) (selected j i))) + have hmul := natural_product_bit_length (optimizerMixtureWeight K j).den (selected j i).den + have hweight := optimizerMixtureWeight_bit_length K j hK + have hselected := hinput j hj + omega + have hsum : (∑ j ∈ range K, Nat.size (optimizerMixtureWeight K j * selected j i).den) ≤ + K * (2 * Nat.size K + 2 + B) := by + calc + _ ≤ ∑ _ ∈ range K, (2 * Nat.size K + 2 + B) := sum_le_sum hterm + _ = _ := by simp + omega + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Numerics/Numerics.lean b/lean/OAI/Combinatorics/EditApproximation/Numerics/Numerics.lean new file mode 100644 index 0000000000000000000000000000000000000000..d2b5f1209593b5cab41d29b0cc57ad23013f3bbe --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Numerics/Numerics.lean @@ -0,0 +1,1307 @@ +import OAI.Combinatorics.EditApproximation.Geometry.Regret +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! +# Finite numerical optimizer for edit-distance refinement + +These are the explicit fixed-step recurrence and rational mixture +calculations from Section 9 of *An Almost-Linear Approximation Scheme +for Edit Distance* (September 24, 2026). The recurrence is an internal +analytic obligation of the manuscript, not an assumed published theorem. +-/ + +namespace EditApproximation + +open Finset + +/-- The conditional-gradient step size in the finite entropy optimizer. -/ +noncomputable def frankWolfeStep (j : ℕ) : ℝ := 2 / ((j : ℝ) + 2) + +theorem frankWolfeStep_nonnegative (j : ℕ) : 0 ≤ frankWolfeStep j := by + unfold frankWolfeStep + positivity + +theorem frankWolfeStep_le_one (j : ℕ) : frankWolfeStep j ≤ 1 := by + unfold frankWolfeStep + apply (div_le_one₀ (by positivity)).mpr + have := Nat.cast_nonneg (α := ℝ) j + linarith + +/-- The scalar induction step giving the optimizer's `8/(σ(j+1))` +error term. -/ +theorem frank_wolfe_scalar_step (σ error x : ℝ) (hσ : 0 < σ) (hx : 0 ≤ x) : + (1 - 2 / (x + 3)) * (2 * error + 8 / (σ * (x + 2))) + + 2 * error * (2 / (x + 3)) + 2 * (2 / (x + 3)) ^ 2 / σ ≤ + 2 * error + 8 / (σ * (x + 3)) := by + have h2 : 0 < x + 2 := by linarith + have h3 : 0 < x + 3 := by linarith + have hid : + (2 * error + 8 / (σ * (x + 3))) - + ((1 - 2 / (x + 3)) * (2 * error + 8 / (σ * (x + 2))) + + 2 * error * (2 / (x + 3)) + 2 * (2 / (x + 3)) ^ 2 / σ) = + 8 / (σ * (x + 2) * (x + 3) ^ 2) := by + field_simp [hσ.ne', h2.ne', h3.ne'] + ring + have hnonneg : 0 ≤ 8 / (σ * (x + 2) * (x + 3) ^ 2) := by positivity + linarith + +/-- The first update removes dependence on the initial objective gap. +The conclusion corresponds to manuscript indices `j ≥ 1`. -/ +theorem frank_wolfe_gap_bound (σ error : ℝ) (gap : ℕ → ℝ) + (hσ : 0 < σ) + (hrecurrence : ∀ j, + gap (j + 1) ≤ (1 - frankWolfeStep j) * gap j + + 2 * error * frankWolfeStep j + 2 * (frankWolfeStep j) ^ 2 / σ) : + ∀ j : ℕ, gap (j + 1) ≤ 2 * error + 8 / (σ * ((j : ℝ) + 2)) := by + intro j + induction j with + | zero => + have hfirst : gap 1 ≤ 2 * error + 2 / σ := by + simpa [frankWolfeStep] using hrecurrence 0 + have hratio : 8 / (σ * (0 + 2)) = 4 / σ := by ring + rw [Nat.cast_zero, hratio] + have hnonneg : 0 ≤ 2 / σ := by positivity + have hratio' : 4 / σ = 2 * (2 / σ) := by ring + rw [hratio'] + norm_num only [Nat.zero_add] + linarith + | succ j ih => + have hstep : frankWolfeStep (j + 1) = 2 / ((j : ℝ) + 3) := by + norm_num [frankWolfeStep, Nat.cast_add, add_assoc] + have hcoef : 0 ≤ 1 - frankWolfeStep (j + 1) := + sub_nonneg.mpr (frankWolfeStep_le_one _) + have hmono := mul_le_mul_of_nonneg_left ih hcoef + have hrec := hrecurrence (j + 1) + rw [hstep] at hmono hrec + have hscalar := frank_wolfe_scalar_step σ error (j : ℝ) hσ (Nat.cast_nonneg _) + have hbound : gap (j + 1 + 1) ≤ 2 * error + 8 / (σ * ((j : ℝ) + 3)) := by + linarith + convert hbound using 1 + norm_num [Nat.cast_add, add_assoc] + +/-- Exact rational weight of the vertex selected at step `j`, after +`K` steps. -/ +def optimizerMixtureWeight (K j : ℕ) : ℚ := + 2 * ((j : ℚ) + 1) / ((K : ℚ) * ((K : ℚ) + 1)) + +theorem sum_optimizer_numerators (K : ℕ) : + (∑ j ∈ range K, 2 * ((j : ℚ) + 1)) = (K : ℚ) * ((K : ℚ) + 1) := by + induction K with + | zero => simp + | succ K ih => + rw [sum_range_succ, ih] + push_cast + ring + +theorem optimizerMixtureWeight_positive (K j : ℕ) (hK : 0 < K) : + 0 < optimizerMixtureWeight K j := by + unfold optimizerMixtureWeight + have hK' : 0 < (K : ℚ) := Nat.cast_pos.mpr hK + positivity + +theorem sum_optimizerMixtureWeight (K : ℕ) (hK : 0 < K) : + (∑ j ∈ range K, optimizerMixtureWeight K j) = 1 := by + unfold optimizerMixtureWeight + rw [← sum_div, sum_optimizer_numerators] + apply div_self + have hK' : 0 < (K : ℚ) := Nat.cast_pos.mpr hK + positivity + +theorem optimizerMixtureWeight_update_old (K j : ℕ) (hK : 0 < K) : + (1 - 2 / ((K : ℚ) + 2)) * optimizerMixtureWeight K j = + optimizerMixtureWeight (K + 1) j := by + have hK' : 0 < (K : ℚ) := Nat.cast_pos.mpr hK + unfold optimizerMixtureWeight + push_cast + field_simp + ring + +theorem optimizerMixtureWeight_update_new (K : ℕ) : + 2 / ((K : ℚ) + 2) = optimizerMixtureWeight (K + 1) K := by + unfold optimizerMixtureWeight + push_cast + field_simp + ring + +/-- Exact rational conditional-gradient iterates. -/ +def rationalOptimizerIterate {ι : Type*} (initial : ι → ℚ) (selected : ℕ → ι → ℚ) : + ℕ → ι → ℚ + | 0 => initial + | j + 1 => fun i => + (1 - 2 / ((j : ℚ) + 2)) * rationalOptimizerIterate initial selected j i + + (2 / ((j : ℚ) + 2)) * selected j i + +/-- After the first update, the initial vertex has weight zero. The +remaining iterates are exactly the explicit rational triangular mixture +used by the fair-bit sampler in Section 9. -/ +theorem rationalOptimizerIterate_eq_mixture {ι : Type*} + (initial : ι → ℚ) (selected : ℕ → ι → ℚ) (K : ℕ) (i : ι) : + rationalOptimizerIterate initial selected (K + 1) i = + ∑ j ∈ range (K + 1), optimizerMixtureWeight (K + 1) j * selected j i := by + induction K with + | zero => norm_num [rationalOptimizerIterate, optimizerMixtureWeight] + | succ K ih => + rw [rationalOptimizerIterate] + dsimp only + rw [ih, mul_sum] + conv_rhs => rw [sum_range_succ] + congr 1 + · apply sum_congr rfl + intro j hj + rw [← mul_assoc, optimizerMixtureWeight_update_old (K + 1) j (by omega)] + · rw [optimizerMixtureWeight_update_new] + +/-- Cumulative integer mass for the triangular exact sampler. -/ + + +theorem optimizerTriangularMass_succ (K : ℕ) : + optimizerTriangularMass (K + 1) = optimizerTriangularMass K + (K + 1) := by + unfold optimizerTriangularMass + rw [sum_range_succ] + +theorem optimizerTriangularMass_twice (K : ℕ) : + 2 * optimizerTriangularMass K = K * (K + 1) := by + induction K with + | zero => simp [optimizerTriangularMass] + | succ K ih => + rw [optimizerTriangularMass_succ] + nlinarith + +/-- The integers assigned to selection index `j` form a block of +exactly `j+1` points. -/ +theorem optimizerSampler_block_card (j : ℕ) : + (Icc (optimizerTriangularMass j + 1) (optimizerTriangularMass (j + 1))).card = j + 1 := by + rw [Nat.card_Icc, optimizerTriangularMass_succ] + omega + +/-- Counting the fair uniform integer sampler gives exactly the stored +mixture weights, including repeated selected vertices. -/ +theorem optimizerSampler_block_weight (K j : ℕ) (hK : 0 < K) : + ((j + 1 : ℕ) : ℚ) / optimizerTriangularMass K = optimizerMixtureWeight K j := by + have hK' : 0 < (K : ℚ) := Nat.cast_pos.mpr hK + have hmass : 2 * (optimizerTriangularMass K : ℚ) = (K : ℚ) * ((K : ℚ) + 1) := by + exact_mod_cast optimizerTriangularMass_twice K + have hmasspos : 0 < (optimizerTriangularMass K : ℚ) := by nlinarith + unfold optimizerMixtureWeight + push_cast + field_simp + nlinarith + +/-- The increase of `-x log x` after adding a positive smoothing +parameter is bounded by that parameter's own entropy. -/ +theorem entropy_smoothing_upper (x σ : ℝ) (hx : 0 ≤ x) (hσ : 0 < σ) : + Real.negMulLog (x + σ) - Real.negMulLog x ≤ Real.negMulLog σ := by + by_cases hxzero : x = 0 + · simp [hxzero] + · have hxpos : 0 < x := lt_of_le_of_ne hx (Ne.symm hxzero) + have hlogσ : 0 ≤ Real.log (x + σ) - Real.log σ := + sub_nonneg.mpr (Real.log_le_log hσ (by linarith)) + have hlogx : 0 ≤ Real.log (x + σ) - Real.log x := + sub_nonneg.mpr (Real.log_le_log hxpos (by linarith)) + have hprodσ := mul_nonneg hσ.le hlogσ + have hprodx := mul_nonneg hx hlogx + simp only [Real.negMulLog] + nlinarith + +/-- The negative change in the smoothed entropy coordinate is linear +in the smoothing parameter on the relevant interval `[0,2]`. -/ +theorem entropy_smoothing_lower (x σ : ℝ) (hx : 0 ≤ x) (hσ : 0 < σ) + (hupper : x + σ ≤ 2) : + Real.negMulLog x - Real.negMulLog (x + σ) ≤ 2 * σ := by + have hxs : 0 < x + σ := by linarith + have hlog : Real.log (x + σ) ≤ 1 := by + exact (Real.log_le_log hxs hupper).trans (by + have := Real.log_le_sub_one_of_pos (show (0 : ℝ) < 2 by norm_num) + linarith) + have hσlog := mul_le_mul_of_nonneg_left hlog hσ.le + by_cases hxzero : x = 0 + · rw [hxzero, zero_add] at hσlog + simp only [hxzero, Real.negMulLog, zero_add, neg_zero, zero_mul, zero_sub] + nlinarith + · have hxpos : 0 < x := lt_of_le_of_ne hx (Ne.symm hxzero) + have hratio := Real.log_le_sub_one_of_pos (div_pos hxs hxpos) + rw [Real.log_div hxs.ne' hxpos.ne'] at hratio + have hratio' := mul_le_mul_of_nonneg_left hratio hx + have hcancel : x * ((x + σ) / x - 1) = σ := by + field_simp + ring + rw [hcancel] at hratio' + simp only [Real.negMulLog] + nlinarith + +theorem negMulLog_le_two_sqrt (σ : ℝ) (hσ : 0 < σ) : + Real.negMulLog σ ≤ 2 * Real.sqrt σ := by + have hroot : 0 < Real.sqrt σ := Real.sqrt_pos.mpr hσ + have hsq : (Real.sqrt σ) ^ 2 = σ := Real.sq_sqrt hσ.le + have hdiv : σ / Real.sqrt σ = Real.sqrt σ := by + apply (div_eq_iff hroot.ne').mpr + nlinarith + have hmul : σ * (Real.sqrt σ)⁻¹ = Real.sqrt σ := by + simpa only [div_eq_mul_inv] using hdiv + have hlog := Real.log_le_sub_one_of_pos (inv_pos.mpr hroot) + rw [Real.log_inv, Real.log_sqrt hσ.le] at hlog + have hscaled := mul_le_mul_of_nonneg_left hlog (show 0 ≤ 2 * σ by positivity) + simp only [Real.negMulLog] + nlinarith + +/-- A uniform coordinate modulus for entropy smoothing, valid including +zero coordinates. -/ +theorem entropy_smoothing_coordinate (x σ : ℝ) + (hx : 0 ≤ x) (hx1 : x ≤ 1) (hσ : 0 < σ) (hσ1 : σ ≤ 1) : + |Real.negMulLog (x + σ) - Real.negMulLog x| ≤ 2 * Real.sqrt σ := by + have hupper := (entropy_smoothing_upper x σ hx hσ).trans (negMulLog_le_two_sqrt σ hσ) + have hlower := entropy_smoothing_lower x σ hx hσ (by linarith) + have hσroot : σ ≤ Real.sqrt σ := by + have hsq : (Real.sqrt σ) ^ 2 = σ := Real.sq_sqrt hσ.le + have hroot := Real.sqrt_nonneg σ + have hσsq : σ ^ 2 ≤ σ := by nlinarith + nlinarith + exact abs_le.mpr ⟨by linarith, hupper⟩ + +/-- Manuscript Equation `eq:entropy-smoothing`, with a slightly stronger +constant from the coordinate estimate. The linear coefficient vector +cancels, so the bound is independent of its magnitude. -/ +theorem finite_entropy_smoothing_bound {ι : Type*} (coordinates : Finset ι) + (p objective : ι → ℝ) (σ η : ℝ) + (hp : ∀ i ∈ coordinates, 0 ≤ p i) + (hpsum : ∑ i ∈ coordinates, p i = 1) + (hσ : 0 < σ) (hσ1 : σ ≤ 1) : + |((∑ i ∈ coordinates, Real.negMulLog (p i + σ)) + + η * ∑ i ∈ coordinates, objective i * p i) - + entropyValue coordinates η objective p| ≤ 4 * coordinates.card * Real.sqrt σ := by + rw [entropyValue_eq] + have hcancel : + ((∑ i ∈ coordinates, Real.negMulLog (p i + σ)) + + η * ∑ i ∈ coordinates, objective i * p i) - + ((∑ i ∈ coordinates, Real.negMulLog (p i)) + + η * ∑ i ∈ coordinates, objective i * p i) = + ∑ i ∈ coordinates, (Real.negMulLog (p i + σ) - Real.negMulLog (p i)) := by + rw [sum_sub_distrib] + ring + rw [hcancel] + calc + _ ≤ ∑ i ∈ coordinates, |Real.negMulLog (p i + σ) - Real.negMulLog (p i)| := + abs_sum_le_sum_abs _ _ + _ ≤ ∑ i ∈ coordinates, 2 * Real.sqrt σ := sum_le_sum fun i hi => + entropy_smoothing_coordinate (p i) σ (hp i hi) + ((single_le_sum hp hi).trans hpsum.le) hσ hσ1 + _ ≤ 4 * coordinates.card * Real.sqrt σ := by + simp only [sum_const, nsmul_eq_mul] + have hc : 0 ≤ (coordinates.card : ℝ) := Nat.cast_nonneg _ + have hroot := Real.sqrt_nonneg σ + nlinarith + +private theorem entropy_quadratic_hasDerivAt (x : ℝ) (hx : 0 < x) : + HasDerivAt (fun z : ℝ => z * Real.log z - z ^ 2 / 2) + (Real.log x + 1 - x) x := by + convert! (Real.hasDerivAt_mul_log hx.ne').sub + (((hasDerivAt_id x).pow 2).div_const 2) using 1 + simp only [id_eq] + ring + +/-- Negative entropy minus half the square is convex on the probability +coordinate interval. This is the exact curvature bound used for the +objective-gap estimate in the finite optimizer. -/ +theorem entropy_quadratic_convex : + ConvexOn ℝ (Set.Icc (0 : ℝ) 1) (fun z : ℝ => z * Real.log z - z ^ 2 / 2) := by + apply MonotoneOn.convexOn_of_deriv (convex_Icc (0 : ℝ) 1) + · exact (Real.continuous_mul_log.sub (by fun_prop)).continuousOn + · intro x hx + simp only [interior_Icc, Set.mem_Ioo] at hx + exact (entropy_quadratic_hasDerivAt x hx.1).differentiableAt.differentiableWithinAt + · intro x hx y hy hxy + simp only [interior_Icc, Set.mem_Ioo] at hx hy + rw [(entropy_quadratic_hasDerivAt x hx.1).deriv, + (entropy_quadratic_hasDerivAt y hy.1).deriv] + have hratio := Real.one_sub_inv_le_log_of_pos (div_pos hy.1 hx.1) + have hinv : (y / x)⁻¹ = x / y := by field_simp + rw [hinv, Real.log_div hy.1.ne' hx.1.ne'] at hratio + have hscaled := mul_le_mul_of_nonneg_left hratio hy.1.le + have hcancel : y * (1 - x / y) = y - x := by field_simp [hy.1.ne'] + rw [hcancel] at hscaled + have hlog : 0 ≤ Real.log y - Real.log x := + sub_nonneg.mpr (Real.log_le_log hx.1 hxy) + have hcorrection := mul_nonneg (show 0 ≤ 1 - y by linarith) hlog + nlinarith + +/-- The entropy coordinate gap is at least half the squared coordinate +distance, including the competitor value zero by continuity. -/ +theorem entropy_coordinate_strong_gap (x y : ℝ) + (hx : 0 ≤ x) (hx1 : x ≤ 1) (hy : 0 < y) (hy1 : y ≤ 1) : + (x - y) ^ 2 / 2 ≤ + x * Real.log x - y * Real.log y - (Real.log y + 1) * (x - y) := by + have hderiv := entropy_quadratic_hasDerivAt y hy + rcases lt_trichotomy x y with hxy | rfl | hyx + · have hslope := entropy_quadratic_convex.slope_le_of_hasDerivAt + ⟨hx, hx1⟩ ⟨hy.le, hy1⟩ hxy hderiv + rw [slope_def_field] at hslope + have hmul := (div_le_iff₀ (sub_pos.mpr hxy)).mp hslope + nlinarith + · simp + · have hslope := entropy_quadratic_convex.le_slope_of_hasDerivAt + ⟨hy.le, hy1⟩ ⟨hx, hx1⟩ hyx hderiv + rw [slope_def_field] at hslope + have hmul := (le_div_iff₀ (sub_pos.mpr hyx)).mp hslope + nlinarith + +/-- Relative entropy dominates half the squared Euclidean distance on +the finite probability simplex. -/ +theorem finite_relative_entropy_sq_gap {ι : Type*} (coordinates : Finset ι) + (p q : ι → ℝ) + (hp : ∀ i ∈ coordinates, 0 < p i) + (hq : ∀ i ∈ coordinates, 0 ≤ q i) + (hpsum : ∑ i ∈ coordinates, p i = 1) + (hqsum : ∑ i ∈ coordinates, q i = 1) : + (∑ i ∈ coordinates, (q i - p i) ^ 2) / 2 ≤ + ∑ i ∈ coordinates, q i * Real.log (q i / p i) := by + have hcoord (i : ι) (hi : i ∈ coordinates) : + (q i - p i) ^ 2 / 2 ≤ q i * Real.log (q i / p i) - q i + p i := by + have hstrong := entropy_coordinate_strong_gap (q i) (p i) (hq i hi) + ((single_le_sum hq hi).trans hqsum.le) (hp i hi) + ((single_le_sum (fun j hj => (hp j hj).le) hi).trans hpsum.le) + by_cases hqzero : q i = 0 + · simp only [hqzero, zero_mul, sub_zero, zero_sub] at hstrong ⊢ + nlinarith + · rw [Real.log_div hqzero (hp i hi).ne'] + nlinarith + have hsum := sum_le_sum hcoord + rw [← sum_div, sum_add_distrib, sum_sub_distrib, hqsum, hpsum] at hsum + linarith + +/-- A true entropy-objective gap controls the `ℓ₁` error of a feasible +mixture, with the manuscript's exact factor `sqrt (2d gap)`. -/ +theorem entropy_gap_to_l1 {ι : Type*} (coordinates : Finset ι) + (Q : Set (ι → ℝ)) (η : ℝ) (objective maximizer mixture : ι → ℝ) + (hconvex : Convex ℝ Q) (hmaxQ : maximizer ∈ Q) (hmixQ : mixture ∈ Q) + (hmax : ∀ i ∈ coordinates, 0 < maximizer i) + (hmix : ∀ i ∈ coordinates, 0 ≤ mixture i) + (hmaxsum : ∑ i ∈ coordinates, maximizer i = 1) + (hmixsum : ∑ i ∈ coordinates, mixture i = 1) + (hmaximize : IsMaxOn (entropyValue coordinates η objective) Q maximizer) : + (∑ i ∈ coordinates, |mixture i - maximizer i|) ≤ + Real.sqrt (2 * coordinates.card * + (entropyValue coordinates η objective maximizer - + entropyValue coordinates η objective mixture)) := by + have hpenalty := entropy_hull_penalty coordinates Q η objective maximizer mixture + hconvex hmaxQ hmixQ hmax hmaxsum hmixsum hmaximize + have hsq := finite_relative_entropy_sq_gap coordinates maximizer mixture hmax hmix hmaxsum hmixsum + have hcs := sum_sq_le_sum_mul_sum_of_sq_le_mul coordinates + (fun _ _ => (show (0 : ℝ) ≤ 1 by norm_num)) + (fun i _ => sq_nonneg (mixture i - maximizer i)) + (fun i _ => (show |mixture i - maximizer i| ^ 2 ≤ 1 * (mixture i - maximizer i) ^ 2 by + rw [one_mul, sq_abs])) + simp only [sum_const, nsmul_eq_mul, mul_one] at hcs + apply Real.le_sqrt_of_sq_le + have hc : 0 ≤ (coordinates.card : ℝ) := Nat.cast_nonneg _ + have hscaled := mul_le_mul_of_nonneg_left (show + (∑ i ∈ coordinates, (mixture i - maximizer i) ^ 2) ≤ + 2 * (entropyValue coordinates η objective maximizer - + entropyValue coordinates η objective mixture) by linarith) hc + nlinarith + +/-- Converting a uniform smoothing error and a smoothed objective gap +to a gap for the true entropy objective. -/ +theorem smoothing_gap_transfer (trueBest trueValue smoothBest smoothValue error gap : ℝ) + (hbest : trueBest ≤ smoothBest + error) + (hvalue : smoothValue ≤ trueValue + error) + (hgap : smoothBest - smoothValue ≤ gap) : + trueBest - trueValue ≤ gap + 2 * error := by linarith + +theorem optimizer_work_budget_gap (G : ℝ) (hG : 0 < G) : + 8 / ((1 / G ^ 50) * (G ^ 80 + 1)) ≤ 8 / G ^ 30 := by + have hpow : G ^ 80 = G ^ 50 * G ^ 30 := by rw [← pow_add] + have hcancel : (1 / G ^ 50) * G ^ 80 = G ^ 30 := by + rw [hpow] + field_simp + have hdenom : G ^ 30 ≤ (1 / G ^ 50) * (G ^ 80 + 1) := by + rw [← hcancel] + exact mul_le_mul_of_nonneg_left (by linarith) (by positivity) + exact div_le_div_of_nonneg_left (by norm_num) (pow_pos hG _) hdenom + +theorem optimizer_smoothing_root (G : ℝ) (hG : 0 < G) : + Real.sqrt (1 / G ^ 50) = 1 / G ^ 25 := by + have hpow : G ^ 50 = (G ^ 25) ^ 2 := by rw [← pow_mul] + rw [hpow, Real.sqrt_div (by positivity), Real.sqrt_one, Real.sqrt_sq_eq_abs, + abs_of_pos (pow_pos hG _)] + +/-- The explicit total objective-gap bound after the prescribed +number of fixed-step updates. -/ +theorem optimizer_explicit_gap_budget (G d : ℝ) (hG : 4 ≤ G) (hd : d ≤ G) : + 2 / G ^ 20 + 8 / G ^ 30 + 8 * d / G ^ 25 ≤ 12 / G ^ 20 := by + have hGpos : 0 < G := by linarith + have hG1 : 1 ≤ G := by linarith + have hG10 : 4 ≤ G ^ 10 := hG.trans (by + simpa using pow_le_pow_right₀ hG1 (by norm_num : 1 ≤ 10)) + have hG5 : d ≤ G ^ 5 := hd.trans (by + simpa using pow_le_pow_right₀ hG1 (by norm_num : 1 ≤ 5)) + have hsmall : 8 / G ^ 30 ≤ 2 / G ^ 20 := by + apply (div_le_div_iff₀ (pow_pos hGpos _) (pow_pos hGpos _)).mpr + have hscale := mul_le_mul_of_nonneg_left hG10 (show 0 ≤ 2 * G ^ 20 by positivity) + have hpow : G ^ 30 = G ^ 20 * G ^ 10 := by rw [← pow_add] + rw [hpow] + nlinarith + have hsmooth : 8 * d / G ^ 25 ≤ 8 / G ^ 20 := by + apply (div_le_div_iff₀ (pow_pos hGpos _) (pow_pos hGpos _)).mpr + have hscale := mul_le_mul_of_nonneg_left hG5 (show 0 ≤ 8 * G ^ 20 by positivity) + have hpow : G ^ 25 = G ^ 20 * G ^ 5 := by rw [← pow_add] + rw [hpow] + nlinarith + have hsum : 2 / G ^ 20 + 2 / G ^ 20 + 8 / G ^ 20 = 12 / G ^ 20 := by ring + linarith + +/-- The quantitative final `H^(-3)` precision calculation. The squared +distance premise is supplied by the proved entropy/KL curvature bound. -/ +theorem optimizer_final_l1_precision (H G d distance gap : ℝ) + (hH : 4 ≤ H) (hHG : H ≤ G) (hd : 0 ≤ d) (hdG : d ≤ G) + (hsquared : distance ^ 2 ≤ 2 * d * gap) (hgap : gap ≤ 12 / G ^ 20) : + distance ≤ 1 / H ^ 3 := by + have hHpos : 0 < H := by linarith + have hGpos : 0 < G := lt_of_lt_of_le hHpos hHG + have hG4 : 4 ≤ G := hH.trans hHG + have hG1 : 1 ≤ G := by linarith + have hG3 : 64 ≤ G ^ 3 := by + have h := pow_le_pow_left₀ (by norm_num : (0 : ℝ) ≤ 4) hG4 3 + norm_num at h + exact h + have hG13 : 24 ≤ G ^ 13 := by + have hmono := pow_le_pow_right₀ hG1 (by norm_num : 3 ≤ 13) + linarith + have hratio : 24 / G ^ 19 ≤ 1 / G ^ 6 := by + apply (div_le_div_iff₀ (pow_pos hGpos _) (pow_pos hGpos _)).mpr + have hscale := mul_le_mul_of_nonneg_right hG13 (pow_nonneg hGpos.le 6) + have hpow : G ^ 19 = G ^ 13 * G ^ 6 := by rw [← pow_add] + rw [hpow] + nlinarith + have hHratio : 1 / G ^ 6 ≤ 1 / H ^ 6 := + div_le_div_of_nonneg_left zero_le_one (pow_pos hHpos _) + (pow_le_pow_left₀ hHpos.le hHG 6) + have hscale := mul_le_mul_of_nonneg_left hgap (show 0 ≤ 2 * d by positivity) + have hdimension := div_le_div_of_nonneg_right + (mul_le_mul_of_nonneg_left hdG (by norm_num : (0 : ℝ) ≤ 24)) + (pow_nonneg hGpos.le 20) + have hcancel : 24 * G / G ^ 20 = 24 / G ^ 19 := by + have hpow : G ^ 20 = G ^ 19 * G := by rw [← pow_succ] + rw [hpow] + field_simp + have hsquare : distance ^ 2 ≤ 1 / H ^ 6 := by + rw [hcancel] at hdimension + have hcombined := hdimension.trans (hratio.trans hHratio) + have hscaledGap : 2 * d * (12 / G ^ 20) = 24 * d / G ^ 20 := by ring + rw [hscaledGap] at hscale + exact hsquared.trans (hscale.trans hcombined) + have htarget : (1 / H ^ 3) ^ 2 = 1 / H ^ 6 := by + rw [div_pow, one_pow, ← pow_mul] + have hpositive : 0 < 1 / H ^ 3 := by positivity + rw [← htarget] at hsquare + nlinarith + +/-- Rational truncated logarithm used for the entropy-gradient +calculation. Its evaluation uses only rational arithmetic. -/ + + +theorem rationalLogApproximation_cast (r : ℚ) (K : ℕ) : + (rationalLogApproximation r K : ℝ) = + 2 * ∑ k ∈ range K, + ((((r : ℝ) - 1) / ((r : ℝ) + 1)) ^ (2 * k + 1) / (2 * k + 1)) := by + unfold rationalLogApproximation + push_cast + rfl + +theorem logarithm_symmetric_parameter_bound (r σ : ℝ) + (hσ : 0 < σ) (hσhalf : σ ≤ 1 / 2) + (hr : σ ≤ r) (hrupper : r ≤ 1 + σ) : + |(r - 1) / (r + 1)| ≤ 1 - σ := by + have hrpos : 0 < r := hσ.trans_le hr + have hrden : 0 < r + 1 := by linarith + apply abs_le.mpr + constructor + · apply (le_div_iff₀ hrden).mpr + have hprod := mul_nonneg hrpos.le (show 0 ≤ 1 - σ by linarith) + nlinarith + · apply (div_le_iff₀ hrden).mpr + have hmul := mul_le_mul_of_nonneg_left hrupper hσ.le + have hσsquare : σ ^ 2 ≤ σ / 2 := by + have h := mul_le_mul_of_nonneg_left hσhalf hσ.le + nlinarith + nlinarith + +/-- Explicit logarithm-series remainder for the rational gradient +routine. Mathlib's logarithm remainder is specialized to the bounded +smoothed-coordinate interval. Its bound suffices for the prescribed +polynomial truncation length. -/ +theorem logarithm_series_error (r σ : ℝ) (K : ℕ) + (hσ : 0 < σ) (hσhalf : σ ≤ 1 / 2) + (hr : σ ≤ r) (hrupper : r ≤ 1 + σ) : + |Real.log r - 2 * ∑ k ∈ range K, + (((r - 1) / (r + 1)) ^ (2 * k + 1) / (2 * k + 1))| ≤ + 2 * Real.exp (-2 * K * σ) / σ := by + let b := (r - 1) / (r + 1) + have hrpos : 0 < r := hσ.trans_le hr + have hrden : 0 < r + 1 := by linarith + have hb : |b| ≤ 1 - σ := logarithm_symmetric_parameter_bound r σ hσ hσhalf hr hrupper + have hb1 : |b| < 1 := by linarith + have htransform : (1 + b) / (1 - b) = r := by + dsimp only [b] + field_simp + ring + have hseries := Real.sum_range_sub_log_div_le hb1 K + rw [htransform] at hseries + have htwice := mul_le_mul_of_nonneg_left hseries (show (0 : ℝ) ≤ 2 by norm_num) + have hleft : + |Real.log r - 2 * ∑ k ∈ range K, b ^ (2 * k + 1) / (2 * k + 1)| = + 2 * |1 / 2 * Real.log r - ∑ k ∈ range K, b ^ (2 * k + 1) / (2 * k + 1)| := by + rw [← abs_of_nonneg (show (0 : ℝ) ≤ 2 by norm_num), ← abs_mul] + congr 1 + ring + rw [← hleft, ← mul_div_assoc] at htwice + have hdenom : σ ≤ 1 - b ^ 2 := by + have hsq := pow_le_pow_left₀ (abs_nonneg b) hb 2 + rw [sq_abs] at hsq + have hσsq : σ ^ 2 ≤ σ := by nlinarith + nlinarith + have hnum : |b| ^ (2 * K + 1) ≤ Real.exp (-2 * K * σ) := by + calc + _ ≤ (1 - σ) ^ (2 * K + 1) := pow_le_pow_left₀ (abs_nonneg b) hb _ + _ ≤ Real.exp (-σ) ^ (2 * K + 1) := pow_le_pow_left₀ + (show 0 ≤ 1 - σ by linarith) (Real.one_sub_le_exp_neg σ) _ + _ = Real.exp ((2 * K + 1 : ℕ) * (-σ)) := (Real.exp_nat_mul (-σ) _).symm + _ ≤ Real.exp (-2 * K * σ) := Real.exp_le_exp.mpr (by push_cast; nlinarith) + calc + _ ≤ 2 * |b| ^ (2 * K + 1) / (1 - b ^ 2) := htwice + _ ≤ 2 * Real.exp (-2 * K * σ) / (1 - b ^ 2) := + div_le_div_of_nonneg_right (mul_le_mul_of_nonneg_left hnum (by norm_num)) + (hσ.le.trans hdenom) + _ ≤ _ := div_le_div_of_nonneg_left (by positivity) hσ hdenom + +theorem rationalLogApproximation_error (r : ℚ) (σ : ℝ) (K : ℕ) + (hσ : 0 < σ) (hσhalf : σ ≤ 1 / 2) + (hr : σ ≤ (r : ℝ)) (hrupper : (r : ℝ) ≤ 1 + σ) : + |Real.log (r : ℝ) - (rationalLogApproximation r K : ℝ)| ≤ + 2 * Real.exp (-2 * K * σ) / σ := by + rw [rationalLogApproximation_cast] + exact logarithm_series_error (r : ℝ) σ K hσ hσhalf hr hrupper + +theorem logarithm_truncation_exponential_budget (G : ℝ) (hG : 4 ≤ G) : + 2 * Real.exp (-2 * G ^ 10) / (1 / G ^ 50) ≤ 1 / G ^ 20 := by + have hGpos : 0 < G := by linarith + have hG1 : 1 ≤ G := by linarith + have hG5 : 1024 ≤ G ^ 5 := by + have h := pow_le_pow_left₀ (by norm_num : (0 : ℝ) ≤ 4) hG 5 + norm_num at h + exact h + have hG10 : 315 ≤ G ^ 10 := by + have hmono := pow_le_pow_right₀ hG1 (by norm_num : 5 ≤ 10) + linarith + have hpoly : 2 * G ^ 70 ≤ (2 * G ^ 10) ^ 8 / (8 : ℕ).factorial := by + norm_num + apply (le_div_iff₀ (by norm_num : (0 : ℝ) < 40320)).mpr + rw [mul_pow, ← pow_mul] + have hpow : G ^ 80 = G ^ 70 * G ^ 10 := by rw [← pow_add] + norm_num + rw [hpow] + have hscale := mul_le_mul_of_nonneg_left hG10 (show 0 ≤ 256 * G ^ 70 by positivity) + nlinarith + have hexp : 2 * G ^ 70 ≤ Real.exp (2 * G ^ 10) := + hpoly.trans (Real.pow_div_factorial_le_exp (x := 2 * G ^ 10) (n := 8) (by positivity)) + have heq : 2 * Real.exp (-2 * G ^ 10) / (1 / G ^ 50) = + 2 * G ^ 50 / Real.exp (2 * G ^ 10) := by + rw [show -2 * G ^ 10 = -(2 * G ^ 10) by ring, Real.exp_neg] + field_simp [hGpos.ne'] + rw [heq] + apply (div_le_div_iff₀ (Real.exp_pos _) (pow_pos hGpos _)).mpr + have hpow : G ^ 50 * G ^ 20 = G ^ 70 := by rw [← pow_add] + nlinarith + +/-- The prescribed rational logarithm computation has the required +absolute gradient precision `G^(-20)` after `G^60` rational terms. -/ +theorem rationalLogApproximation_prescribed_precision (r : ℚ) (G : ℕ) + (hG : 4 ≤ G) + (hr : 1 / (G : ℝ) ^ 50 ≤ (r : ℝ)) + (hrupper : (r : ℝ) ≤ 1 + 1 / (G : ℝ) ^ 50) : + |Real.log (r : ℝ) - (rationalLogApproximation r (G ^ 60) : ℝ)| ≤ + 1 / (G : ℝ) ^ 20 := by + have hG4 : (4 : ℝ) ≤ G := by exact_mod_cast hG + have hGpos : (0 : ℝ) < G := by linarith + have hG1 : (1 : ℝ) ≤ G := by linarith + have hG50 : (2 : ℝ) ≤ (G : ℝ) ^ 50 := by + have hmono := pow_le_pow_right₀ hG1 (by norm_num : 1 ≤ 50) + norm_num only [pow_one] at hmono + linarith + have hσpos : 0 < 1 / (G : ℝ) ^ 50 := by positivity + have hσhalf : 1 / (G : ℝ) ^ 50 ≤ 1 / 2 := by + exact div_le_div_of_nonneg_left zero_le_one (by norm_num) hG50 + have herror := rationalLogApproximation_error r (1 / (G : ℝ) ^ 50) (G ^ 60) + hσpos hσhalf hr hrupper + have hprod : ((G ^ 60 : ℕ) : ℝ) * (1 / (G : ℝ) ^ 50) = (G : ℝ) ^ 10 := by + push_cast + have hpow : (G : ℝ) ^ 60 = (G : ℝ) ^ 10 * (G : ℝ) ^ 50 := by rw [← pow_add] + rw [hpow] + field_simp + have hexponent : -2 * ((G ^ 60 : ℕ) : ℝ) * (1 / (G : ℝ) ^ 50) = + -2 * (G : ℝ) ^ 10 := by nlinarith [hprod] + rw [hexponent] at herror + exact herror.trans (logarithm_truncation_exponential_budget (G : ℝ) hG4) + +theorem finite_gradient_error {ι : Type*} (coordinates : Finset ι) + (gradient approximateGradient p : ι → ℝ) (error : ℝ) + (hp : ∀ i ∈ coordinates, 0 ≤ p i) + (hpsum : ∑ i ∈ coordinates, p i = 1) + (herror : ∀ i ∈ coordinates, |approximateGradient i - gradient i| ≤ error) : + |∑ i ∈ coordinates, (approximateGradient i - gradient i) * p i| ≤ error := by + calc + _ ≤ ∑ i ∈ coordinates, |(approximateGradient i - gradient i) * p i| := + abs_sum_le_sum_abs _ _ + _ ≤ ∑ i ∈ coordinates, error * p i := by + apply sum_le_sum + intro i hi + rw [abs_mul, abs_of_nonneg (hp i hi)] + exact mul_le_mul_of_nonneg_right (herror i hi) (hp i hi) + _ = error := by rw [← mul_sum, hpsum, mul_one] + +/-- Enumerating the vertices with an approximate gradient loses at +most `2e₀` in the true linearization, even against an arbitrary feasible +mixture. -/ +theorem approximate_gradient_linearization_loss {ι : Type*} (coordinates : Finset ι) + (gradient approximateGradient selected competitor : ι → ℝ) (error : ℝ) + (hselected : ∀ i ∈ coordinates, 0 ≤ selected i) + (hcompetitor : ∀ i ∈ coordinates, 0 ≤ competitor i) + (hselectedSum : ∑ i ∈ coordinates, selected i = 1) + (hcompetitorSum : ∑ i ∈ coordinates, competitor i = 1) + (herror : ∀ i ∈ coordinates, |approximateGradient i - gradient i| ≤ error) + (hchoose : (∑ i ∈ coordinates, approximateGradient i * competitor i) ≤ + ∑ i ∈ coordinates, approximateGradient i * selected i) : + (∑ i ∈ coordinates, gradient i * competitor i) - + (∑ i ∈ coordinates, gradient i * selected i) ≤ 2 * error := by + have hsel := finite_gradient_error coordinates gradient approximateGradient selected + error hselected hselectedSum herror + have hcomp := finite_gradient_error coordinates gradient approximateGradient competitor + error hcompetitor hcompetitorSum herror + simp only [sub_mul, sum_sub_distrib] at hsel hcomp + have hselBounds := abs_le.mp hsel + have hcompBounds := abs_le.mp hcomp + linarith + +noncomputable def smoothedEntropyValue {ι : Type*} (coordinates : Finset ι) + (σ : ℝ) (linear p : ι → ℝ) : ℝ := + ∑ i ∈ coordinates, (Real.negMulLog (p i + σ) + linear i * p i) + +noncomputable def smoothedEntropyGradient {ι : Type*} + (σ : ℝ) (linear p : ι → ℝ) (i : ι) : ℝ := + -Real.log (p i + σ) - 1 + linear i + +/-- Tangent upper bound for a single smoothed entropy coordinate. -/ +theorem smoothed_entropy_coordinate_upper (x y σ linear : ℝ) + (hx : 0 ≤ x) (hy : 0 ≤ y) (hσ : 0 < σ) : + (Real.negMulLog (y + σ) + linear * y) - + (Real.negMulLog (x + σ) + linear * x) ≤ + (-Real.log (x + σ) - 1 + linear) * (y - x) := by + have hxs : 0 < x + σ := by linarith + have hys : 0 < y + σ := by linarith + have hlog := Real.log_le_sub_one_of_pos (div_pos hxs hys) + rw [Real.log_div hxs.ne' hys.ne'] at hlog + have hscaled := mul_le_mul_of_nonneg_left hlog hys.le + have hcancel : (y + σ) * ((x + σ) / (y + σ) - 1) = x - y := by + field_simp + ring + rw [hcancel] at hscaled + simp only [Real.negMulLog] + nlinarith + +/-- A scalar smoothness bound obtained directly from `log u ≤ u-1`. +The coefficient `1/σ` combines with the sharper simplex diameter below +to give the manuscript's exact `2 ξ²/σ` remainder. -/ +theorem smoothed_entropy_coordinate_lower (x y σ linear : ℝ) + (hx : 0 ≤ x) (hy : 0 ≤ y) (hσ : 0 < σ) : + (-Real.log (x + σ) - 1 + linear) * (y - x) - (y - x) ^ 2 / σ ≤ + (Real.negMulLog (y + σ) + linear * y) - + (Real.negMulLog (x + σ) + linear * x) := by + have hxs : 0 < x + σ := by linarith + have hys : 0 < y + σ := by linarith + have hlog := Real.log_le_sub_one_of_pos (div_pos hys hxs) + rw [Real.log_div hys.ne' hxs.ne'] at hlog + have hscaled := mul_le_mul_of_nonneg_left hlog hys.le + have hcancel : (y + σ) * ((y + σ) / (x + σ) - 1) - y + x = + (y - x) ^ 2 / (x + σ) := by + field_simp + ring + have hratio : (y - x) ^ 2 / (x + σ) ≤ (y - x) ^ 2 / σ := + div_le_div_of_nonneg_left (sq_nonneg _) hσ (by linarith) + have hbound : (y + σ) * (Real.log (y + σ) - Real.log (x + σ)) - y + x ≤ + (y - x) ^ 2 / (x + σ) := by linarith + have hbound' := hbound.trans hratio + simp only [Real.negMulLog] + nlinarith + +theorem probability_vectors_sq_distance_le_two {ι : Type*} (coordinates : Finset ι) + (p q : ι → ℝ) + (hp : ∀ i ∈ coordinates, 0 ≤ p i) + (hq : ∀ i ∈ coordinates, 0 ≤ q i) + (hpsum : ∑ i ∈ coordinates, p i = 1) + (hqsum : ∑ i ∈ coordinates, q i = 1) : + ∑ i ∈ coordinates, (q i - p i) ^ 2 ≤ 2 := by + have hcoord (i : ι) (hi : i ∈ coordinates) : (q i - p i) ^ 2 ≤ q i + p i := by + have hp1 := (single_le_sum hp hi).trans hpsum.le + have hq1 := (single_le_sum hq hi).trans hqsum.le + have hpprod := mul_nonneg (hp i hi) (sub_nonneg.mpr hp1) + have hqprod := mul_nonneg (hq i hi) (sub_nonneg.mpr hq1) + have hpq := mul_nonneg (hp i hi) (hq i hi) + nlinarith + calc + _ ≤ ∑ i ∈ coordinates, (q i + p i) := sum_le_sum hcoord + _ = 2 := by rw [sum_add_distrib, hqsum, hpsum]; norm_num + +theorem smoothed_entropy_tangent_upper {ι : Type*} (coordinates : Finset ι) + (σ : ℝ) (linear p q : ι → ℝ) + (hp : ∀ i ∈ coordinates, 0 ≤ p i) + (hq : ∀ i ∈ coordinates, 0 ≤ q i) (hσ : 0 < σ) : + smoothedEntropyValue coordinates σ linear q - smoothedEntropyValue coordinates σ linear p ≤ + ∑ i ∈ coordinates, smoothedEntropyGradient σ linear p i * (q i - p i) := by + rw [smoothedEntropyValue, smoothedEntropyValue, ← sum_sub_distrib] + exact sum_le_sum fun i hi => smoothed_entropy_coordinate_upper (p i) (q i) σ + (linear i) (hp i hi) (hq i hi) hσ + +theorem smoothed_entropy_mixture_lower {ι : Type*} (coordinates : Finset ι) + (σ ξ : ℝ) (linear p selected : ι → ℝ) + (hp : ∀ i ∈ coordinates, 0 ≤ p i) + (hselected : ∀ i ∈ coordinates, 0 ≤ selected i) + (hpsum : ∑ i ∈ coordinates, p i = 1) + (hselectedSum : ∑ i ∈ coordinates, selected i = 1) + (hσ : 0 < σ) (hξ : 0 ≤ ξ) (hξ1 : ξ ≤ 1) : + ξ * (∑ i ∈ coordinates, smoothedEntropyGradient σ linear p i * (selected i - p i)) - + 2 * ξ ^ 2 / σ ≤ + smoothedEntropyValue coordinates σ linear + (fun i => (1 - ξ) * p i + ξ * selected i) - smoothedEntropyValue coordinates σ linear p := by + let updated : ι → ℝ := fun i => (1 - ξ) * p i + ξ * selected i + have hupdated (i : ι) (hi : i ∈ coordinates) : 0 ≤ updated i := + add_nonneg (mul_nonneg (sub_nonneg.mpr hξ1) (hp i hi)) + (mul_nonneg hξ (hselected i hi)) + have hcoordinate (i : ι) (hi : i ∈ coordinates) := + smoothed_entropy_coordinate_lower (p i) (updated i) σ (linear i) (hp i hi) (hupdated i hi) hσ + have hsum := sum_le_sum hcoordinate + have hterm (i : ι) : updated i - p i = ξ * (selected i - p i) := by + dsimp only [updated] + ring + simp only [smoothedEntropyGradient] at hsum ⊢ + simp_rw [hterm, mul_pow, div_eq_mul_inv] at hsum + rw [sum_sub_distrib] at hsum + have hlinear : + (∑ i ∈ coordinates, (-Real.log (p i + σ) - 1 + linear i) * (ξ * (selected i - p i))) = + ξ * ∑ i ∈ coordinates, (-Real.log (p i + σ) - 1 + linear i) * (selected i - p i) := by + rw [mul_sum] + apply sum_congr rfl + intro i hi + ring + have hquadratic : (∑ i ∈ coordinates, ξ ^ 2 * (selected i - p i) ^ 2 * σ⁻¹) = + (ξ ^ 2 / σ) * ∑ i ∈ coordinates, (selected i - p i) ^ 2 := by + rw [mul_sum] + apply sum_congr rfl + intro i hi + ring + rw [hlinear, hquadratic, sum_sub_distrib] at hsum + have hdiameter := probability_vectors_sq_distance_le_two coordinates p selected hp hselected hpsum hselectedSum + have hscale := mul_le_mul_of_nonneg_left hdiameter (show 0 ≤ ξ ^ 2 / σ by positivity) + change _ ≤ smoothedEntropyValue coordinates σ linear updated - + smoothedEntropyValue coordinates σ linear p at hsum + change _ ≤ smoothedEntropyValue coordinates σ linear updated - + smoothedEntropyValue coordinates σ linear p + have htwo : ξ ^ 2 / σ * 2 = 2 * ξ ^ 2 / σ := by ring + rw [htwo] at hscale + linarith + +/-- The manuscript's fixed-step optimizer recurrence follows from the +actual smoothed entropy objective and approximate gradient selection. -/ +theorem smoothed_frank_wolfe_recurrence {ι : Type*} (coordinates : Finset ι) + (σ ξ error : ℝ) (linear p selected best approximateGradient : ι → ℝ) + (hp : ∀ i ∈ coordinates, 0 ≤ p i) + (hselected : ∀ i ∈ coordinates, 0 ≤ selected i) + (hbest : ∀ i ∈ coordinates, 0 ≤ best i) + (hpsum : ∑ i ∈ coordinates, p i = 1) + (hselectedSum : ∑ i ∈ coordinates, selected i = 1) + (hbestSum : ∑ i ∈ coordinates, best i = 1) + (hσ : 0 < σ) (hξ : 0 ≤ ξ) (hξ1 : ξ ≤ 1) + (hgradient : ∀ i ∈ coordinates, + |approximateGradient i - smoothedEntropyGradient σ linear p i| ≤ error) + (hchoose : (∑ i ∈ coordinates, approximateGradient i * best i) ≤ + ∑ i ∈ coordinates, approximateGradient i * selected i) : + smoothedEntropyValue coordinates σ linear best - + smoothedEntropyValue coordinates σ linear (fun i => (1 - ξ) * p i + ξ * selected i) ≤ + (1 - ξ) * (smoothedEntropyValue coordinates σ linear best - smoothedEntropyValue coordinates σ linear p) + + 2 * error * ξ + 2 * ξ ^ 2 / σ := by + have htangent := smoothed_entropy_tangent_upper coordinates σ linear p best hp hbest hσ + have hlinear := approximate_gradient_linearization_loss coordinates + (smoothedEntropyGradient σ linear p) approximateGradient selected best error + hselected hbest hselectedSum hbestSum hgradient hchoose + have hlower := smoothed_entropy_mixture_lower coordinates σ ξ linear p selected + hp hselected hpsum hselectedSum hσ hξ hξ1 + have hsumBest : (∑ i ∈ coordinates, smoothedEntropyGradient σ linear p i * (best i - p i)) = + (∑ i ∈ coordinates, smoothedEntropyGradient σ linear p i * best i) - + ∑ i ∈ coordinates, smoothedEntropyGradient σ linear p i * p i := by + simp only [mul_sub, sum_sub_distrib] + have hsumSelected : (∑ i ∈ coordinates, smoothedEntropyGradient σ linear p i * (selected i - p i)) = + (∑ i ∈ coordinates, smoothedEntropyGradient σ linear p i * selected i) - + ∑ i ∈ coordinates, smoothedEntropyGradient σ linear p i * p i := by + simp only [mul_sub, sum_sub_distrib] + rw [hsumBest] at htangent + rw [hsumSelected] at hlower + have hgain : smoothedEntropyValue coordinates σ linear best - smoothedEntropyValue coordinates σ linear p - + 2 * error ≤ (∑ i ∈ coordinates, smoothedEntropyGradient σ linear p i * selected i) - + ∑ i ∈ coordinates, smoothedEntropyGradient σ linear p i * p i := by linarith + have hscale := mul_le_mul_of_nonneg_left hgain hξ + nlinarith + +/-- Casting the exact rational update gives precisely the analytic step. -/ +theorem rationalOptimizerIterate_cast_step {ι : Type*} + (initial : ι → ℚ) (selected : ℕ → ι → ℚ) (j : ℕ) : + (fun i => (rationalOptimizerIterate initial selected (j + 1) i : ℝ)) = + (fun i => (1 - frankWolfeStep j) * (rationalOptimizerIterate initial selected j i : ℝ) + + frankWolfeStep j * (selected j i : ℝ)) := by + funext i + simp [rationalOptimizerIterate, frankWolfeStep] + +/-- All exact rational iterates are probability vectors. -/ +theorem rationalOptimizerIterate_probability {ι : Type*} (coordinates : Finset ι) + (initial : ι → ℚ) (selected : ℕ → ι → ℚ) + (hinitial : ∀ i ∈ coordinates, (0 : ℝ) ≤ initial i) + (hinitialSum : ∑ i ∈ coordinates, (initial i : ℝ) = 1) + (hselected : ∀ j i, i ∈ coordinates → (0 : ℝ) ≤ selected j i) + (hselectedSum : ∀ j, ∑ i ∈ coordinates, (selected j i : ℝ) = 1) : + ∀ j, (∀ i ∈ coordinates, (0 : ℝ) ≤ rationalOptimizerIterate initial selected j i) ∧ + (∑ i ∈ coordinates, (rationalOptimizerIterate initial selected j i : ℝ)) = 1 := by + intro j + induction j with + | zero => exact ⟨hinitial, hinitialSum⟩ + | succ j ih => + have hstep := congr_fun (rationalOptimizerIterate_cast_step initial selected j) + constructor + · intro i hi + rw [hstep i] + exact add_nonneg + (mul_nonneg (sub_nonneg.mpr (frankWolfeStep_le_one j)) (ih.1 i hi)) + (mul_nonneg (frankWolfeStep_nonnegative j) (hselected j i hi)) + · simp_rw [hstep] + rw [sum_add_distrib, ← mul_sum, ← mul_sum, ih.2, hselectedSum] + ring + +/-- Convex feasibility is preserved by the actual rational iterates. -/ +theorem rationalOptimizerIterate_mem {ι : Type*} + (Q : Set (ι → ℝ)) (initial : ι → ℚ) (selected : ℕ → ι → ℚ) + (hconvex : Convex ℝ Q) (hinitial : (fun i => (initial i : ℝ)) ∈ Q) + (hselected : ∀ j, (fun i => (selected j i : ℝ)) ∈ Q) : + ∀ j, (fun i => (rationalOptimizerIterate initial selected j i : ℝ)) ∈ Q := by + intro j + induction j with + | zero => exact hinitial + | succ j ih => + rw [rationalOptimizerIterate_cast_step] + exact hconvex ih (hselected j) (sub_nonneg.mpr (frankWolfeStep_le_one j)) + (frankWolfeStep_nonnegative j) (by ring) + +/-- Objective convergence of the exact rational implementation follows +from the proved smoothness and rational approximate-gradient choices. -/ +theorem rational_optimizer_smoothed_gap_bound {ι : Type*} (coordinates : Finset ι) + (σ error : ℝ) (linear best : ι → ℝ) (initial : ι → ℚ) + (selected : ℕ → ι → ℚ) (approximateGradient : ℕ → ι → ℝ) + (hinitial : ∀ i ∈ coordinates, (0 : ℝ) ≤ initial i) + (hinitialSum : ∑ i ∈ coordinates, (initial i : ℝ) = 1) + (hselected : ∀ j i, i ∈ coordinates → (0 : ℝ) ≤ selected j i) + (hselectedSum : ∀ j, ∑ i ∈ coordinates, (selected j i : ℝ) = 1) + (hbest : ∀ i ∈ coordinates, 0 ≤ best i) + (hbestSum : ∑ i ∈ coordinates, best i = 1) (hσ : 0 < σ) + (hgradient : ∀ j i, i ∈ coordinates → + |approximateGradient j i - smoothedEntropyGradient σ linear + (fun i => (rationalOptimizerIterate initial selected j i : ℝ)) i| ≤ error) + (hchoose : ∀ j, (∑ i ∈ coordinates, approximateGradient j i * best i) ≤ + ∑ i ∈ coordinates, approximateGradient j i * (selected j i : ℝ)) : + ∀ j, smoothedEntropyValue coordinates σ linear best - smoothedEntropyValue coordinates σ linear + (fun i => (rationalOptimizerIterate initial selected (j + 1) i : ℝ)) ≤ + 2 * error + 8 / (σ * ((j : ℝ) + 2)) := by + have hprobability := rationalOptimizerIterate_probability coordinates initial selected + hinitial hinitialSum hselected hselectedSum + apply frank_wolfe_gap_bound σ error + (fun j => smoothedEntropyValue coordinates σ linear best - smoothedEntropyValue coordinates σ linear + (fun i => (rationalOptimizerIterate initial selected j i : ℝ))) hσ + intro j + rw [rationalOptimizerIterate_cast_step] + exact smoothed_frank_wolfe_recurrence coordinates σ (frankWolfeStep j) error linear + (fun i => (rationalOptimizerIterate initial selected j i : ℝ)) + (fun i => (selected j i : ℝ)) best (approximateGradient j) + (hprobability j).1 (hselected j) hbest (hprobability j).2 (hselectedSum j) hbestSum hσ + (frankWolfeStep_nonnegative j) (frankWolfeStep_le_one j) (hgradient j) (hchoose j) + +/-- The actual rational gradient routine, including exact linear terms. -/ + + +theorem rationalSmoothedGradient_precision {ι : Type*} (coordinates : Finset ι) + (G : ℕ) (linear p : ι → ℚ) (hG : 4 ≤ G) + (hp : ∀ i ∈ coordinates, (0 : ℝ) ≤ p i) + (hpsum : ∑ i ∈ coordinates, (p i : ℝ) = 1) : + ∀ i ∈ coordinates, + |(rationalSmoothedGradient G linear p i : ℝ) - + smoothedEntropyGradient (1 / (G : ℝ) ^ 50) + (fun i => (linear i : ℝ)) (fun i => (p i : ℝ)) i| ≤ 1 / (G : ℝ) ^ 20 := by + intro i hi + have hinput : (1 / (G : ℝ) ^ 50) ≤ (p i + 1 / (G : ℚ) ^ 50 : ℚ) := by + push_cast + linarith [hp i hi] + have hupper : ((p i + 1 / (G : ℚ) ^ 50 : ℚ) : ℝ) ≤ 1 + 1 / (G : ℝ) ^ 50 := by + push_cast + linarith [(single_le_sum hp hi).trans hpsum.le] + have hlog := rationalLogApproximation_prescribed_precision + (p i + 1 / (G : ℚ) ^ 50) G hG hinput hupper + convert hlog using 1 + congr 1 + simp only [rationalSmoothedGradient, smoothedEntropyGradient] + push_cast + ring + +/-- The prescribed number of exact rational updates reaches the true +entropy-objective precision, with no assumed analytic recurrence. -/ +theorem rational_optimizer_true_gap_precision {ι : Type*} (coordinates : Finset ι) + (G : ℕ) (linear initial : ι → ℚ) (selected : ℕ → ι → ℚ) (best : ι → ℝ) + (hG : 4 ≤ G) (hdG : coordinates.card ≤ G) + (hinitial : ∀ i ∈ coordinates, (0 : ℝ) ≤ initial i) + (hinitialSum : ∑ i ∈ coordinates, (initial i : ℝ) = 1) + (hselected : ∀ j i, i ∈ coordinates → (0 : ℝ) ≤ selected j i) + (hselectedSum : ∀ j, ∑ i ∈ coordinates, (selected j i : ℝ) = 1) + (hbest : ∀ i ∈ coordinates, 0 ≤ best i) + (hbestSum : ∑ i ∈ coordinates, best i = 1) + (hchoose : ∀ j, + (∑ i ∈ coordinates, (rationalSmoothedGradient G linear + (rationalOptimizerIterate initial selected j) i : ℝ) * best i) ≤ + ∑ i ∈ coordinates, (rationalSmoothedGradient G linear + (rationalOptimizerIterate initial selected j) i : ℝ) * (selected j i : ℝ)) : + entropyValue coordinates 1 (fun i => (linear i : ℝ)) best - + entropyValue coordinates 1 (fun i => (linear i : ℝ)) + (fun i => (rationalOptimizerIterate initial selected (G ^ 80) i : ℝ)) ≤ + 12 / (G : ℝ) ^ 20 := by + let σ : ℝ := 1 / (G : ℝ) ^ 50 + have hG4 : (4 : ℝ) ≤ G := by exact_mod_cast hG + have hGpos : (0 : ℝ) < G := by linarith + have hσ : 0 < σ := by dsimp [σ]; positivity + have hσ1 : σ ≤ 1 := by + dsimp [σ] + apply (div_le_one₀ (pow_pos hGpos _)).mpr + exact one_le_pow₀ (by linarith : (1 : ℝ) ≤ G) + have hprobability := rationalOptimizerIterate_probability coordinates initial selected + hinitial hinitialSum hselected hselectedSum + have hgradient j := rationalSmoothedGradient_precision coordinates G linear + (rationalOptimizerIterate initial selected j) hG (hprobability j).1 (hprobability j).2 + have hgap := rational_optimizer_smoothed_gap_bound coordinates σ (1 / (G : ℝ) ^ 20) + (fun i => (linear i : ℝ)) best initial selected + (fun j i => (rationalSmoothedGradient G linear (rationalOptimizerIterate initial selected j) i : ℝ)) + hinitial hinitialSum hselected hselectedSum hbest hbestSum hσ hgradient hchoose (G ^ 80 - 1) + have hK : 1 ≤ G ^ 80 := by + have hGnat : 0 < G := by omega + exact Nat.one_le_iff_ne_zero.mpr (pow_ne_zero 80 (Nat.ne_of_gt hGnat)) + rw [Nat.sub_add_cancel hK] at hgap + have hindex : ((G ^ 80 - 1 : ℕ) : ℝ) + 2 = (G : ℝ) ^ 80 + 1 := by + rw [Nat.cast_sub hK, Nat.cast_one, Nat.cast_pow] + ring + rw [hindex] at hgap + have hbudget := optimizer_work_budget_gap (G : ℝ) hGpos + have hsmoothed : smoothedEntropyValue coordinates σ (fun i => (linear i : ℝ)) best - + smoothedEntropyValue coordinates σ (fun i => (linear i : ℝ)) + (fun i => (rationalOptimizerIterate initial selected (G ^ 80) i : ℝ)) ≤ + 2 / (G : ℝ) ^ 20 + 8 / (G : ℝ) ^ 30 := by + dsimp only [σ] at hgap ⊢ + have htwo : (2 : ℝ) * (1 / (G : ℝ) ^ 20) = 2 / (G : ℝ) ^ 20 := by ring + rw [htwo] at hgap + linarith + have hbestSmoothing := finite_entropy_smoothing_bound coordinates best + (fun i => (linear i : ℝ)) σ 1 hbest hbestSum hσ hσ1 + have hvalueSmoothing := finite_entropy_smoothing_bound coordinates + (fun i => (rationalOptimizerIterate initial selected (G ^ 80) i : ℝ)) + (fun i => (linear i : ℝ)) σ 1 (hprobability _).1 (hprobability _).2 hσ hσ1 + have hbestSmooth : |smoothedEntropyValue coordinates σ (fun i => (linear i : ℝ)) best - + entropyValue coordinates 1 (fun i => (linear i : ℝ)) best| ≤ + 4 * coordinates.card * Real.sqrt σ := by + simpa [smoothedEntropyValue, sum_add_distrib] using hbestSmoothing + have hvalueSmooth : |smoothedEntropyValue coordinates σ (fun i => (linear i : ℝ)) + (fun i => (rationalOptimizerIterate initial selected (G ^ 80) i : ℝ)) - + entropyValue coordinates 1 (fun i => (linear i : ℝ)) + (fun i => (rationalOptimizerIterate initial selected (G ^ 80) i : ℝ))| ≤ + 4 * coordinates.card * Real.sqrt σ := by + simpa [smoothedEntropyValue, sum_add_distrib] using hvalueSmoothing + have htrue : entropyValue coordinates 1 (fun i => (linear i : ℝ)) best - + entropyValue coordinates 1 (fun i => (linear i : ℝ)) + (fun i => (rationalOptimizerIterate initial selected (G ^ 80) i : ℝ)) ≤ + 2 / (G : ℝ) ^ 20 + 8 / (G : ℝ) ^ 30 + 8 * coordinates.card * Real.sqrt σ := by + have hb := abs_le.mp hbestSmooth + have hv := abs_le.mp hvalueSmooth + linarith + have hroot : Real.sqrt σ = 1 / (G : ℝ) ^ 25 := optimizer_smoothing_root _ hGpos + rw [hroot] at htrue + have hdimension : (coordinates.card : ℝ) ≤ G := by exact_mod_cast hdG + have hfinal := optimizer_explicit_gap_budget (G : ℝ) coordinates.card hG4 hdimension + have hnorm : (8 : ℝ) * coordinates.card * (1 / (G : ℝ) ^ 25) = + 8 * coordinates.card / (G : ℝ) ^ 25 := by ring + rw [hnorm] at htrue + exact htrue.trans hfinal + +/-- The final distance guarantee for the prescribed rational updates. +Only their concrete finite linearization choices remain as input. -/ +theorem rational_optimizer_l1_precision {ι : Type*} (coordinates : Finset ι) + (Q : Set (ι → ℝ)) (H G : ℕ) (linear initial : ι → ℚ) + (selected : ℕ → ι → ℚ) (maximizer : ι → ℝ) + (hH : 4 ≤ H) (hHG : H ≤ G) (hdG : coordinates.card ≤ G) + (hconvex : Convex ℝ Q) (hinitialQ : (fun i => (initial i : ℝ)) ∈ Q) + (hselectedQ : ∀ j, (fun i => (selected j i : ℝ)) ∈ Q) + (hmaxQ : maximizer ∈ Q) + (hinitial : ∀ i ∈ coordinates, (0 : ℝ) ≤ initial i) + (hinitialSum : ∑ i ∈ coordinates, (initial i : ℝ) = 1) + (hselected : ∀ j i, i ∈ coordinates → (0 : ℝ) ≤ selected j i) + (hselectedSum : ∀ j, ∑ i ∈ coordinates, (selected j i : ℝ) = 1) + (hmax : ∀ i ∈ coordinates, 0 < maximizer i) + (hmaxSum : ∑ i ∈ coordinates, maximizer i = 1) + (hmaximize : IsMaxOn (entropyValue coordinates 1 (fun i => (linear i : ℝ))) Q maximizer) + (hchoose : ∀ j, + (∑ i ∈ coordinates, (rationalSmoothedGradient G linear + (rationalOptimizerIterate initial selected j) i : ℝ) * maximizer i) ≤ + ∑ i ∈ coordinates, (rationalSmoothedGradient G linear + (rationalOptimizerIterate initial selected j) i : ℝ) * (selected j i : ℝ)) : + (∑ i ∈ coordinates, + |(rationalOptimizerIterate initial selected (G ^ 80) i : ℝ) - maximizer i|) ≤ + 1 / (H : ℝ) ^ 3 := by + have hG : 4 ≤ G := hH.trans hHG + have hprobability := rationalOptimizerIterate_probability coordinates initial selected + hinitial hinitialSum hselected hselectedSum (G ^ 80) + have hmixture := rationalOptimizerIterate_mem Q initial selected + hconvex hinitialQ hselectedQ (G ^ 80) + have hgap := rational_optimizer_true_gap_precision coordinates G linear initial selected maximizer + hG hdG hinitial hinitialSum hselected hselectedSum (fun i hi => (hmax i hi).le) hmaxSum hchoose + have hdistance := entropy_gap_to_l1 coordinates Q 1 (fun i => (linear i : ℝ)) maximizer + (fun i => (rationalOptimizerIterate initial selected (G ^ 80) i : ℝ)) hconvex + hmaxQ hmixture hmax hprobability.1 hmaxSum hprobability.2 hmaximize + have hmaxbound := hmaximize hmixture + change entropyValue coordinates 1 (fun i => (linear i : ℝ)) + (fun i => (rationalOptimizerIterate initial selected (G ^ 80) i : ℝ)) ≤ + entropyValue coordinates 1 (fun i => (linear i : ℝ)) maximizer at hmaxbound + have hnonnegative : 0 ≤ 2 * (coordinates.card : ℝ) * + (entropyValue coordinates 1 (fun i => (linear i : ℝ)) maximizer - + entropyValue coordinates 1 (fun i => (linear i : ℝ)) + (fun i => (rationalOptimizerIterate initial selected (G ^ 80) i : ℝ))) := by positivity + have hsquared := pow_le_pow_left₀ (sum_nonneg (fun _ _ => abs_nonneg _)) hdistance 2 + rw [Real.sq_sqrt hnonnegative] at hsquared + apply optimizer_final_l1_precision (H : ℝ) G coordinates.card _ _ + (by exact_mod_cast hH) (by exact_mod_cast hHG) (Nat.cast_nonneg _) + (by exact_mod_cast hdG) hsquared hgap + +/-- Maximizing a finite list's linearization also maximizes it on the +real convex hull. -/ +theorem finite_linearization_maximizes_convexHull {ι : Type*} (coordinates : Finset ι) + (vertices : Set (ι → ℝ)) (gradient selected : ι → ℝ) + (hchoose : ∀ p ∈ vertices, + (∑ i ∈ coordinates, gradient i * p i) ≤ ∑ i ∈ coordinates, gradient i * selected i) : + ∀ p ∈ convexHull ℝ vertices, + (∑ i ∈ coordinates, gradient i * p i) ≤ ∑ i ∈ coordinates, gradient i * selected i := by + let bound := ∑ i ∈ coordinates, gradient i * selected i + have hconvex : Convex ℝ {p : ι → ℝ | (∑ i ∈ coordinates, gradient i * p i) ≤ bound} := by + intro p hp q hq a b ha hb hab + change (∑ i ∈ coordinates, gradient i * (a * p i + b * q i)) ≤ bound + have hlinear : (∑ i ∈ coordinates, gradient i * (a * p i + b * q i)) = + a * (∑ i ∈ coordinates, gradient i * p i) + + b * (∑ i ∈ coordinates, gradient i * q i) := by + rw [mul_sum, mul_sum, ← sum_add_distrib] + apply sum_congr rfl + intro i hi + ring + rw [hlinear] + have hp' := mul_le_mul_of_nonneg_left hp ha + have hq' := mul_le_mul_of_nonneg_left hq hb + have hbound : a * bound + b * bound = bound := by rw [← add_mul, hab, one_mul] + linarith + exact convexHull_min hchoose hconvex + +/-- Executable finite rational comparisons, with the first listed +maximizer selected in a tie. The fallback only applies to an empty list. -/ + + +theorem rationalLinearizationMaximizer_spec {ι : Type*} (coordinates : Finset ι) + (vertices : List (ι → ℚ)) (gradient : ι → ℚ) (hvertices : vertices ≠ []) : + rationalLinearizationMaximizer coordinates vertices gradient ∈ vertices ∧ + ∀ p ∈ vertices, (∑ i ∈ coordinates, gradient i * p i) ≤ + ∑ i ∈ coordinates, gradient i * rationalLinearizationMaximizer coordinates vertices gradient i := by + unfold rationalLinearizationMaximizer + cases harg : vertices.argmax (fun p => ∑ i ∈ coordinates, gradient i * p i) with + | none => exact False.elim (hvertices (List.argmax_eq_none.mp harg)) + | some selected => + simp only [Option.getD_some] + have hmem : selected ∈ vertices.argmax (fun p => ∑ i ∈ coordinates, gradient i * p i) := by + rw [harg] + simp + exact ⟨List.argmax_mem hmem, fun p hp => List.le_of_mem_argmax + (f := fun p : ι → ℚ => ∑ i ∈ coordinates, gradient i * p i) hp hmem⟩ + +/-- The finite rational optimizer: every operation here is rational +arithmetic, finite enumeration, or the prescribed finite logarithm sum. -/ + + +def finiteOptimizerSelection {ι : Type*} (coordinates : Finset ι) + (vertices : List (ι → ℚ)) (linear : ι → ℚ) (G j : ℕ) : ι → ℚ := + rationalLinearizationMaximizer coordinates vertices + (rationalSmoothedGradient G linear (finiteRationalOptimizer coordinates vertices linear G j)) + +theorem finiteRationalOptimizer_eq_iterate {ι : Type*} (coordinates : Finset ι) + (vertices : List (ι → ℚ)) (linear : ι → ℚ) (G j : ℕ) : + finiteRationalOptimizer coordinates vertices linear G j = + rationalOptimizerIterate (vertices.headD (fun _ => 0)) + (finiteOptimizerSelection coordinates vertices linear G) j := by + induction j with + | zero => rfl + | succ j ih => + funext i + simp only [finiteRationalOptimizer, rationalOptimizerIterate] + change (1 - 2 / ((j : ℚ) + 2)) * finiteRationalOptimizer coordinates vertices linear G j i + + 2 / ((j : ℚ) + 2) * finiteOptimizerSelection coordinates vertices linear G j i = _ + rw [ih] + +def rationalVertexSet {ι : Type*} (vertices : List (ι → ℚ)) : Set (ι → ℝ) := + (fun p : ι → ℚ => fun i => (p i : ℝ)) '' {p | p ∈ vertices} + +/-- Every vector in the listed real convex hull is a probability vector. -/ +theorem rationalVertexHull_probability {ι : Type*} (coordinates : Finset ι) + (vertices : List (ι → ℚ)) + (hvertices : ∀ p ∈ vertices, + (∀ i ∈ coordinates, (0 : ℝ) ≤ p i) ∧ (∑ i ∈ coordinates, (p i : ℝ)) = 1) : + ∀ p ∈ convexHull ℝ (rationalVertexSet vertices), + (∀ i ∈ coordinates, 0 ≤ p i) ∧ (∑ i ∈ coordinates, p i) = 1 := by + have hconvex : Convex ℝ {p : ι → ℝ | + (∀ i ∈ coordinates, 0 ≤ p i) ∧ (∑ i ∈ coordinates, p i) = 1} := by + intro p hp q hq a b ha hb hab + constructor + · intro i hi + exact add_nonneg (mul_nonneg ha (hp.1 i hi)) (mul_nonneg hb (hq.1 i hi)) + · change (∑ i ∈ coordinates, (a * p i + b * q i)) = 1 + rw [sum_add_distrib, ← mul_sum, ← mul_sum, hp.2, hq.2, mul_one, mul_one] + exact hab + apply convexHull_min _ hconvex + rintro _ ⟨p, hp, rfl⟩ + exact hvertices p hp + +/-- Concrete finite vertex selection satisfies the required +linearization inequality against every real feasible mixture. -/ +theorem finiteOptimizerSelection_maximizes {ι : Type*} (coordinates : Finset ι) + (vertices : List (ι → ℚ)) (linear : ι → ℚ) (G j : ℕ) + (hvertices : vertices ≠ []) : + ∀ best ∈ convexHull ℝ (rationalVertexSet vertices), + (∑ i ∈ coordinates, (rationalSmoothedGradient G linear + (finiteRationalOptimizer coordinates vertices linear G j) i : ℝ) * best i) ≤ + ∑ i ∈ coordinates, (rationalSmoothedGradient G linear + (finiteRationalOptimizer coordinates vertices linear G j) i : ℝ) * + (finiteOptimizerSelection coordinates vertices linear G j i : ℝ) := by + apply finite_linearization_maximizes_convexHull + rintro _ ⟨p, hp, rfl⟩ + have hspec := (rationalLinearizationMaximizer_spec coordinates vertices + (rationalSmoothedGradient G linear (finiteRationalOptimizer coordinates vertices linear G j)) + hvertices).2 p hp + dsimp only [finiteOptimizerSelection] + exact_mod_cast hspec + +/-- Accuracy of the executable rational optimizer at every positive +entropy maximizer of its listed action hull. -/ +theorem finiteRationalOptimizer_l1_precision {ι : Type*} (coordinates : Finset ι) + (vertices : List (ι → ℚ)) (linear : ι → ℚ) (H : ℕ) (maximizer : ι → ℝ) + (hvertices : vertices ≠ []) (hH : 4 ≤ H) + (hprobability : ∀ p ∈ vertices, + (∀ i ∈ coordinates, (0 : ℝ) ≤ p i) ∧ (∑ i ∈ coordinates, (p i : ℝ)) = 1) + (hmaxQ : maximizer ∈ convexHull ℝ (rationalVertexSet vertices)) + (hmax : ∀ i ∈ coordinates, 0 < maximizer i) + (hmaximize : IsMaxOn (entropyValue coordinates 1 (fun i => (linear i : ℝ))) + (convexHull ℝ (rationalVertexSet vertices)) maximizer) : + (∑ i ∈ coordinates, |(finiteRationalOptimizer coordinates vertices linear + (H + coordinates.card + 2) ((H + coordinates.card + 2) ^ 80) i : ℝ) - maximizer i|) ≤ + 1 / (H : ℝ) ^ 3 := by + let G := H + coordinates.card + 2 + let initial : ι → ℚ := vertices.headD (fun _ => 0) + let selected := finiteOptimizerSelection coordinates vertices linear G + have hinitialMem : initial ∈ vertices := by + cases vertices with + | nil => exact False.elim (hvertices rfl) + | cons p tail => exact List.mem_cons_self + have hselectedMem j : selected j ∈ vertices := + (rationalLinearizationMaximizer_spec coordinates vertices + (rationalSmoothedGradient G linear (finiteRationalOptimizer coordinates vertices linear G j)) + hvertices).1 + have hinitialQ : (fun i => (initial i : ℝ)) ∈ convexHull ℝ (rationalVertexSet vertices) := + subset_convexHull ℝ _ ⟨initial, hinitialMem, rfl⟩ + have hselectedQ j : (fun i => (selected j i : ℝ)) ∈ convexHull ℝ (rationalVertexSet vertices) := + subset_convexHull ℝ _ ⟨selected j, hselectedMem j, rfl⟩ + have hmaxProbability := rationalVertexHull_probability coordinates vertices hprobability maximizer hmaxQ + have hchoose j := finiteOptimizerSelection_maximizes coordinates vertices linear G j + hvertices maximizer hmaxQ + simp_rw [finiteRationalOptimizer_eq_iterate] at hchoose ⊢ + exact rational_optimizer_l1_precision coordinates (convexHull ℝ (rationalVertexSet vertices)) H G + linear initial selected maximizer hH (by dsimp [G]; omega) (by dsimp [G]; omega) + (convex_convexHull ℝ _) hinitialQ hselectedQ hmaxQ + (hprobability initial hinitialMem).1 (hprobability initial hinitialMem).2 + (fun j => (hprobability (selected j) (hselectedMem j)).1) + (fun j => (hprobability (selected j) (hselectedMem j)).2) + hmax hmaxProbability.2 hmaximize hchoose + +/-- Averaging the finite action list gives a feasible vector positive +at every covered coordinate, including lists with repeated actions. -/ +theorem rationalVertexHull_positive_witness {ι : Type*} (coordinates : Finset ι) + (vertices : List (ι → ℚ)) (hvertices : vertices ≠ []) + (hnonnegative : ∀ p ∈ vertices, ∀ i ∈ coordinates, (0 : ℝ) ≤ p i) + (hcovered : ∀ i ∈ coordinates, ∃ p ∈ vertices, (0 : ℝ) < p i) : + ∃ witness ∈ convexHull ℝ (rationalVertexSet vertices), + ∀ i ∈ coordinates, 0 < witness i := by + classical + let listed := vertices.toFinset + have hlisted : listed.Nonempty := (List.toFinset_nonempty_iff vertices).mpr hvertices + have hcard : 0 < (listed.card : ℝ) := Nat.cast_pos.mpr (card_pos.mpr hlisted) + let weight : ℝ := 1 / listed.card + have hweight : 0 < weight := by dsimp [weight]; positivity + have hweightSum : (∑ _ ∈ listed, weight) = 1 := by + simp only [sum_const, nsmul_eq_mul] + dsimp only [weight] + field_simp + let witness : ι → ℝ := ∑ p ∈ listed, weight • (fun i => (p i : ℝ)) + refine ⟨witness, ?_, ?_⟩ + · exact (convex_convexHull ℝ (rationalVertexSet vertices)).sum_mem + (fun _ _ => hweight.le) hweightSum (fun p hp => + subset_convexHull ℝ _ ⟨p, List.mem_toFinset.mp hp, rfl⟩) + · intro i hi + dsimp only [witness] + simp only [Finset.sum_apply, Pi.smul_apply, smul_eq_mul] + obtain ⟨p, hp, hpi⟩ := hcovered i hi + exact sum_pos' (fun q hq => mul_nonneg hweight.le + (hnonnegative q (List.mem_toFinset.mp hq) i hi)) + ⟨p, List.mem_toFinset.mpr hp, mul_pos hweight hpi⟩ + +/-- The finite optimizer accuracy theorem with exactly the manuscript's +probability and coordinate-coverage assumptions. The returned point is +the executable rational construction defined above. -/ +theorem finite_entropy_optimizer {ι : Type*} (coordinates : Finset ι) + (vertices : List (ι → ℚ)) (linear : ι → ℚ) (H : ℕ) + (hvertices : vertices ≠ []) (hH : 4 ≤ H) + (hprobability : ∀ p ∈ vertices, + (∀ i ∈ coordinates, (0 : ℝ) ≤ p i) ∧ (∑ i ∈ coordinates, (p i : ℝ)) = 1) + (hcovered : ∀ i ∈ coordinates, ∃ p ∈ vertices, (0 : ℝ) < p i) : + ∃ maximizer ∈ convexHull ℝ (rationalVertexSet vertices), + IsMaxOn (entropyValue coordinates 1 (fun i => (linear i : ℝ))) + (convexHull ℝ (rationalVertexSet vertices)) maximizer ∧ + (∑ i ∈ coordinates, |(finiteRationalOptimizer coordinates vertices linear + (H + coordinates.card + 2) ((H + coordinates.card + 2) ^ 80) i : ℝ) - maximizer i|) ≤ + 1 / (H : ℝ) ^ 3 := by + classical + have hfinite : ({p : ι → ℚ | p ∈ vertices} : Set (ι → ℚ)).Finite := by + simp + have hcompact := (hfinite.image (fun p : ι → ℚ => fun i => (p i : ℝ))).isCompact_convexHull ℝ + obtain ⟨witness, hwitnessQ, hwitness⟩ := rationalVertexHull_positive_witness coordinates vertices + hvertices (fun p hp => (hprobability p hp).1) hcovered + obtain ⟨maximizer, hmaxQ, hmaximize⟩ := exists_entropy_maximizer coordinates + (convexHull ℝ (rationalVertexSet vertices)) 1 (fun i => (linear i : ℝ)) hcompact ⟨witness, hwitnessQ⟩ + have hmaxProbability := rationalVertexHull_probability coordinates vertices hprobability maximizer hmaxQ + have hmax := entropy_hull_maximizer_positive coordinates (convexHull ℝ (rationalVertexSet vertices)) + 1 (fun i => (linear i : ℝ)) maximizer witness (convex_convexHull ℝ _) hmaxQ hwitnessQ + hmaxProbability.1 hwitness hmaximize + exact ⟨maximizer, hmaxQ, hmaximize, finiteRationalOptimizer_l1_precision coordinates vertices linear H + maximizer hvertices hH hprobability hmaxQ hmax hmaximize⟩ + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Numerics/OptimizerBitEnvelope.lean b/lean/OAI/Combinatorics/EditApproximation/Numerics/OptimizerBitEnvelope.lean new file mode 100644 index 0000000000000000000000000000000000000000..b1947f4534110279a5eb9d5034aa4e04ff2a4060 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Numerics/OptimizerBitEnvelope.lean @@ -0,0 +1,312 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryPreparedOptimizer + +namespace OAI + +/-! A fixed polynomial envelope for the executed Boolean optimizer. +The expression below records precisely the arithmetic cost formula; its +degree proof avoids expanding powers or changing any computational limit. -/ + +namespace EditApproximation + +private inductive NumericalCostInput + | dimension | vertices | parameter | iterations | denominator | vertexBits | linearBits | linearValue + | branches | history | etaBits | kappaBits | massBits | tableBits | etaValue + +private inductive NumericalCostExpression + | input (i : NumericalCostInput) + | constant (n : ℕ) + | add (a b : NumericalCostExpression) + | mul (a b : NumericalCostExpression) + | pow (a : NumericalCostExpression) (n : ℕ) + | maximum (a b : NumericalCostExpression) + | bitLength (a : NumericalCostExpression) + +private instance (n : ℕ) : OfNat NumericalCostExpression n := ⟨.constant n⟩ +private instance : Add NumericalCostExpression := ⟨.add⟩ +private instance : Mul NumericalCostExpression := ⟨.mul⟩ +private instance : Pow NumericalCostExpression ℕ := ⟨.pow⟩ + +private def NumericalCostExpression.eval (env : NumericalCostInput → ℕ) : NumericalCostExpression → ℕ + | .input i => env i + | .constant n => n + | .add a b => a.eval env + b.eval env + | .mul a b => a.eval env * b.eval env + | .pow a n => a.eval env ^ n + | .maximum a b => max (a.eval env) (b.eval env) + | .bitLength a => Nat.size (a.eval env) + +private def NumericalCostExpression.degree : NumericalCostExpression → ℕ + | .input _ => 1 + | .constant n => Nat.size n + | .add a b => max a.degree b.degree + 1 + | .mul a b => a.degree + b.degree + | .pow a n => a.degree * n + | .maximum a b => max a.degree b.degree + | .bitLength a => a.degree + +private theorem NumericalCostExpression.eval_le_pow (a : NumericalCostExpression) + (env : NumericalCostInput → ℕ) (S : ℕ) (hS : 2 ≤ S) (henv : ∀ i, env i ≤ S) : + a.eval env ≤ S ^ a.degree := by + induction a with + | input i => simpa only [eval, degree, pow_one] using henv i + | constant n => + exact (Nat.lt_size_self n).le.trans (Nat.pow_le_pow_left hS _) + | add a b ha hb => + have ha' := ha.trans (Nat.pow_le_pow_right (by omega : 0 < S) (Nat.le_max_left a.degree b.degree)) + have hb' := hb.trans (Nat.pow_le_pow_right (by omega : 0 < S) (Nat.le_max_right a.degree b.degree)) + change a.eval env + b.eval env ≤ S ^ (max a.degree b.degree + 1) + calc + _ ≤ 2 * S ^ max a.degree b.degree := by omega + _ ≤ S * S ^ max a.degree b.degree := Nat.mul_le_mul_right _ hS + _ = _ := (pow_succ' S _).symm + | mul a b ha hb => + exact (Nat.mul_le_mul ha hb).trans_eq (pow_add S a.degree b.degree).symm + | pow a n ha => + exact (Nat.pow_le_pow_left ha n).trans_eq (pow_mul S a.degree n).symm + | maximum a b ha hb => + exact max_le + (ha.trans (Nat.pow_le_pow_right (by omega) (Nat.le_max_left a.degree b.degree))) + (hb.trans (Nat.pow_le_pow_right (by omega) (Nat.le_max_right a.degree b.degree))) + | bitLength a ha => exact (Nat.size_le.mpr (Nat.lt_two_pow_self)).trans ha + +private def numericalCostEnvironment (d v G K B Bv L V : ℕ) : NumericalCostInput → ℕ + | .dimension => d + | .vertices => v + | .parameter => G + | .iterations => K + | .denominator => B + | .vertexBits => Bv + | .linearBits => L + | .linearValue => V + | _ => 0 + +private abbrev CE := NumericalCostExpression + +private def costSize (a : CE) : CE := .bitLength a +private def costMax (a b : CE) : CE := .maximum a b + +private def expressionLogStorage (B K : CE) : CE := + costSize (2 * K) + 2 * (K * K * (4 * B + 18) + K * (costSize (2 * K + 1) + 1) + 1) + 1 + +private def expressionGradientStorage (G P L : CE) : CE := + 4 * expressionLogStorage (2 * P + 2 * (5 + 50 * (costSize G + 2)) + 2) (G ^ 60) + 2 * L + 18 + +private def expressionPoint (K B Bv : CE) : CE := + Bv + 2 * (B + K * (2 * costSize (K + 1) + B)) + 2 + +private def expressionLogUniversal (B K : CE) : CE := + B + (costSize K + 2 * (K * K * B + K * (costSize (2 * K + 1) + 1) + 1) + 1) + + (2 * ((2 * K + 1) * B + 1) + 2) + costSize (2 * K + 1) + 10 + +private def expressionLogStep (W K : CE) : CE := + (2 * K + 1) * (2000 * (W + 1) ^ 2 + 1) + 2100 * (W + 2) ^ 2 + + 6000 * (W + 1) ^ 2 + costSize (2 * K + 1) + 6 + +private def expressionLogBit (B K : CE) : CE := + let W := expressionLogUniversal (8 * B + 22) K + 12000 * (B + 4) ^ 2 + 2100 * (4 * B + 12) ^ 2 + + K * expressionLogStep W K + 2000 * (W + 5) ^ 2 + 10 + +private def expressionGradientBit (G P L : CE) : CE := + let S := 3 + 50 * (costSize G + 2) + let R := 4 * P + 2 * S + 8 + let logBits := expressionLogStorage R (G ^ 60) + let natWidth := costMax (costSize G) 1 + let powerWidth := natWidth + 3 + 50 * (2 * natWidth + 1) + (1 + 50 * (2000 * (powerWidth + 1) ^ 2 + 1)) + (4 * S + 3) + + 6000 * (P + S + 2) ^ 2 + expressionLogBit R (G ^ 60) + + (6000 * (logBits + 4) ^ 2 + 1) + 6000 * (L + 2 * logBits + 9) ^ 2 + costSize G + 70 + +private def expressionMaximizer (d v B V : CE) : CE := + let W := B + costSize (d * V * V) + 2 * (1 + d * (B + B)) + 1 + v * (1 + d * (100000 * (W + 1) ^ 2) + 1000 * (W + 1) ^ 2 + 2) + d + 1 + +private def expressionUpdate (d K P : CE) : CE := + let C := costSize (K + 2) + 8 + let W := P + 2 * C + 8 + 2100 * (costSize (K + 2) + 6) ^ 2 + (6000 * (C + 4) ^ 2 + 1) + + d * (110000 * (W + 1) ^ 2 + 6) + costSize (K + 2) + 4 + +private def expressionOptimizer (d v G K B Bv L V : CE) : CE := + let P := expressionPoint K B Bv + let W := expressionGradientStorage G (2 * P + 1) (2 * L + 1) + d + 1 + K * (d * (expressionGradientBit G P L + 6) + + expressionMaximizer d v (costMax P W) (2 * G ^ 60 + 1 + V + 1) + expressionUpdate d K P + 3) + + +private def optimizerCostExpression : CE := + expressionOptimizer (.input .dimension) (.input .vertices) (.input .parameter) (.input .iterations) + (.input .denominator) (.input .vertexBits) (.input .linearBits) (.input .linearValue) + +def optimizerBitPolynomialDegree : ℕ := optimizerCostExpression.degree + +private theorem optimizerCostExpression_eval (d v G K B Bv L V : ℕ) : + optimizerCostExpression.eval (numericalCostEnvironment d v G K B Bv L V) = + BinaryFraction.optimizerBitBudget d v G K B Bv L V := by + have hnat : (BinaryFraction.nat G).width = max (Nat.size G) 1 := by + simp only [BinaryFraction.nat, BinaryFraction.width, SignedBinary.ofInt, + Int.natAbs_natCast, ← Nat.size_eq_bits_len, List.length_cons, List.length_nil] + simp only [optimizerCostExpression, expressionOptimizer, expressionPoint, expressionGradientStorage, + expressionGradientBit, expressionLogStorage, expressionLogBit, expressionLogUniversal, + expressionLogStep, expressionMaximizer, expressionUpdate, costSize, costMax, + NumericalCostExpression.eval, numericalCostEnvironment, BinaryFraction.optimizerBitBudget, + BinaryFraction.optimizerRoundBitBudget, BinaryFraction.optimizerPointWordBudget, + BinaryFraction.optimizerGradientWordBudget, UnreducedRational.gradientStorageBudget, + UnreducedRational.logarithmStorageBudget, BinaryFraction.gradientCellBitBudget, + BinaryFraction.generalPowerWordBudget, BinaryFraction.smoothingStorageBudget, + BinaryFraction.shiftedStorageBudget, BinaryFraction.gradientLogStorageBudget, + BinaryFraction.logarithmBitBudget, BinaryFraction.logarithmUniversalWordBudget, + BinaryFraction.logarithmPartialBitStep, BinaryFraction.maximizerBitBudget, + BinaryFraction.maximizerWordBudget, BinaryFraction.dotWordBudget, + BinaryFraction.optimizerUpdateBitBudget, BinaryFraction.updateCoordinateWordBudget, + BinaryFraction.updateCoefficientWordBudget, hnat] + rfl + +theorem optimizerBitBudget_le_fixed_power (d v G K B Bv L V S : ℕ) (hS : 2 ≤ S) + (hd : d ≤ S) (hv : v ≤ S) (hG : G ≤ S) (hK : K ≤ S) + (hB : B ≤ S) (hBv : Bv ≤ S) (hL : L ≤ S) (hV : V ≤ S) : + BinaryFraction.optimizerBitBudget d v G K B Bv L V ≤ S ^ optimizerBitPolynomialDegree := by + rw [← optimizerCostExpression_eval] + apply NumericalCostExpression.eval_le_pow _ _ S hS + intro i + cases i <;> first | assumption | exact Nat.zero_le _ + +theorem booleanOptimizer_cost_le_fixed_power {d : ℕ} + (vertices : List (Vector BinaryFraction d)) (linear : Vector BinaryFraction d) + (G K B Bv L V S : ℕ) (hS : 2 ≤ S) (hd : d ≤ S) (hv : vertices.length ≤ S) + (hG : G ≤ S) (hK : K ≤ S) (hB : B ≤ S) (hBv : Bv ≤ S) (hL : L ≤ S) (hV : V ≤ S) + (hvertices : vertices ≠ []) + (hinput : ∀ v ∈ vertices, ∀ i : Fin d, + (v.get i).width ≤ (v.get i).representation.storageBits ∧ + (0 ≤ (v.get i).value ∧ (v.get i).value ≤ 1) ∧ Nat.size (v.get i).representation.den ≤ B) + (hvw : ∀ v ∈ vertices, ∀ i, (v.get i).width ≤ Bv) + (hlw : ∀ i, (linear.get i).width ≤ L) (hlv : ∀ i, |(linear.get i).value| ≤ V) : + (BinaryFraction.finiteOptimizerWithWork vertices linear G K).2 ≤ S ^ optimizerBitPolynomialDegree := + (BinaryFraction.finiteOptimizerWithWork_cost vertices linear G K B Bv L V hvertices hinput hvw hlw hlv).trans + (optimizerBitBudget_le_fixed_power d vertices.length G K B Bv L V S hS hd hv hG hK hB hBv hL hV) + + +private def expressionBandSumStorage (n B : CE) : CE := + costSize n + B + 2 * (1 + n * (B + 1)) + 2 + +private def expressionBandVertexWord (M B : CE) : CE := + 2 * B + expressionBandSumStorage M B + 3 + +private def expressionStoredSumWord (n B : CE) : CE := + (B + 1) + costSize n + 2 * (B + 2) + 2 * (1 + n * ((B + 1) + (B + 1))) + 1 + +private def expressionStoredSumBit (n B : CE) : CE := + 1 + n * (100000 * (expressionStoredSumWord n B + 1) ^ 2) + +private def expressionBandCoordinateBit (M B : CE) : CE := + 2100 * (B + expressionBandSumStorage M B + 2) ^ 2 + +private def expressionBandPreparation (M d v B : CE) : CE := + expressionStoredSumBit M B + v * (d * (expressionBandCoordinateBit M B + 6)) + 6 * v + +private def expressionOptimisticStorage (Bm Bt Bc : CE) : CE := 20 * Bt + 8 * Bm + 4 * Bc + 30 + +private def expressionOnlineStorage (Be Bk Bm Bt t : CE) : CE := + 2 * Be + 2 * expressionBandSumStorage t (expressionOptimisticStorage Bm Bt (4 * Bk + 18)) + + 2 * (2 * Bt + 2 * Bm + 4) + 3 + +private def expressionGainBit (Bm Bt : CE) : CE := 2100 * (Bm + Bt + 2) ^ 2 + 1 + +private def expressionDecrementBit (Bm Bt : CE) : CE := + 6000 * (Bt + 1) ^ 2 + 2100 * (8 * Bt + Bm + 8) ^ 2 + 2 + +private def expressionCoefficientBit (Bk : CE) : CE := + 2000 * (Bk + 3) ^ 2 + 6000 * (2 * Bk + 7) ^ 2 + 2 + +private def expressionOptimisticBit (Bm Bt Bc : CE) : CE := + let W := 8 * Bt + 2 * Bm + 2 * Bc + 12 + expressionGainBit Bm Bt + expressionDecrementBit Bm Bt + + 2000 * (W + 1) ^ 2 + 6000 * (W + 1) ^ 2 + 2 + +private def expressionOnlineBit (Be Bk Bm Bt t : CE) : CE := + let storage := expressionOptimisticStorage Bm Bt (4 * Bk + 18) + let W := Be + expressionBandSumStorage t storage + (2 * Bt + 2 * Bm + 4) + 2 + expressionCoefficientBit Bk + t * (expressionOptimisticBit Bm Bt (4 * Bk + 18) + 6) + + expressionStoredSumBit t storage + expressionGainBit Bm Bt + + 6000 * (W + 1) ^ 2 + 2000 * (2 * W + 3) ^ 2 + 3 + +private def preparedOptimizerCostExpression : CE := + let M := NumericalCostExpression.input .branches + let d := NumericalCostExpression.input .dimension + let v := NumericalCostExpression.input .vertices + let G := NumericalCostExpression.input .parameter + let K := NumericalCostExpression.input .iterations + let t := NumericalCostExpression.input .history + let Be := NumericalCostExpression.input .etaBits + let Bk := NumericalCostExpression.input .kappaBits + let Bm := NumericalCostExpression.input .massBits + let Bt := NumericalCostExpression.input .tableBits + let E := NumericalCostExpression.input .etaValue + expressionBandPreparation M d v Bm + d * (expressionOnlineBit Be Bk Bm Bt t + 6) + + expressionOptimizer d v G K (expressionBandVertexWord M Bm) (expressionBandVertexWord M Bm) + (expressionOnlineStorage Be Bk Bm Bt t) (E * (2 * t + 1)) + 2 + +private def preparedCostEnvironment (M d v G K t Be Bk Bm Bt E : ℕ) : NumericalCostInput → ℕ + | .branches => M + | .dimension => d + | .vertices => v + | .parameter => G + | .iterations => K + | .history => t + | .etaBits => Be + | .kappaBits => Bk + | .massBits => Bm + | .tableBits => Bt + | .etaValue => E + | _ => 0 + +def preparedOptimizerBitPolynomialDegree : ℕ := preparedOptimizerCostExpression.degree + +private theorem preparedOptimizerCostExpression_eval (M d v G K t Be Bk Bm Bt E : ℕ) : + preparedOptimizerCostExpression.eval (preparedCostEnvironment M d v G K t Be Bk Bm Bt E) = + BinaryFraction.preparedBandOptimizerBitBudget M d v G K t Be Bk Bm Bt E := by + have hnat : (BinaryFraction.nat G).width = max (Nat.size G) 1 := by + simp only [BinaryFraction.nat, BinaryFraction.width, SignedBinary.ofInt, + Int.natAbs_natCast, ← Nat.size_eq_bits_len, List.length_cons, List.length_nil] + simp only [preparedOptimizerCostExpression, preparedCostEnvironment, + expressionBandSumStorage, expressionBandVertexWord, expressionStoredSumWord, + expressionStoredSumBit, expressionBandCoordinateBit, expressionBandPreparation, + expressionOptimisticStorage, expressionOnlineStorage, expressionGainBit, + expressionDecrementBit, expressionCoefficientBit, expressionOptimisticBit, expressionOnlineBit, + expressionOptimizer, expressionPoint, expressionGradientStorage, + expressionGradientBit, expressionLogStorage, expressionLogBit, expressionLogUniversal, + expressionLogStep, expressionMaximizer, expressionUpdate, costSize, costMax, + NumericalCostExpression.eval, BinaryFraction.preparedBandOptimizerBitBudget, + BinaryFraction.bandPreparationBitBudget, BinaryFraction.storedSumBitBudget, + BinaryFraction.storedSumWordBudget, BinaryFraction.bandCoordinateBitBudget, + BinaryFraction.bandMassTotalStorageBudget, BinaryFraction.bandVertexWordBudget, + BinaryFraction.onlineLinearBitBudget, BinaryFraction.coefficientBitBudget, + BinaryFraction.optimisticTermBitBudget, BinaryFraction.optimisticTermWordBudget, + BinaryFraction.decrementBitBudget, BinaryFraction.gainBitBudget, + BinaryFraction.optimisticTermStorageBudget, BinaryFraction.onlineFinalWordBudget, + BinaryFraction.onlineLinearStorageBudget, + BinaryFraction.optimizerBitBudget, BinaryFraction.optimizerRoundBitBudget, + BinaryFraction.optimizerPointWordBudget, BinaryFraction.optimizerGradientWordBudget, + UnreducedRational.gradientStorageBudget, UnreducedRational.logarithmStorageBudget, + BinaryFraction.gradientCellBitBudget, BinaryFraction.generalPowerWordBudget, + BinaryFraction.smoothingStorageBudget, BinaryFraction.shiftedStorageBudget, + BinaryFraction.gradientLogStorageBudget, BinaryFraction.logarithmBitBudget, + BinaryFraction.logarithmUniversalWordBudget, BinaryFraction.logarithmPartialBitStep, + BinaryFraction.maximizerBitBudget, BinaryFraction.maximizerWordBudget, BinaryFraction.dotWordBudget, + BinaryFraction.optimizerUpdateBitBudget, BinaryFraction.updateCoordinateWordBudget, + BinaryFraction.updateCoefficientWordBudget, hnat] + rfl + +theorem preparedBandOptimizerBitBudget_le_fixed_power (M d v G K t Be Bk Bm Bt E S : ℕ) + (hS : 2 ≤ S) (hM : M ≤ S) (hd : d ≤ S) (hv : v ≤ S) (hG : G ≤ S) (hK : K ≤ S) + (ht : t ≤ S) (hBe : Be ≤ S) (hBk : Bk ≤ S) (hBm : Bm ≤ S) (hBt : Bt ≤ S) (hE : E ≤ S) : + BinaryFraction.preparedBandOptimizerBitBudget M d v G K t Be Bk Bm Bt E ≤ + S ^ preparedOptimizerBitPolynomialDegree := by + rw [← preparedOptimizerCostExpression_eval] + apply NumericalCostExpression.eval_le_pow _ _ S hS + intro i + cases i <;> first | assumption | exact Nat.zero_le _ + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Numerics/OptimizerBits.lean b/lean/OAI/Combinatorics/EditApproximation/Numerics/OptimizerBits.lean new file mode 100644 index 0000000000000000000000000000000000000000..2890b4da2ee60f22a4ee7564ed7b97e3cf1e615c --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Numerics/OptimizerBits.lean @@ -0,0 +1,91 @@ +import OAI.Combinatorics.EditApproximation.Numerics.VectorOptimizerWork + +namespace OAI + +/-! Representation bounds for the actual stored optimizer iterates. -/ + +namespace EditApproximation + +open Finset + +theorem finiteRationalOptimizer_coordinate_bounds {ι : Type*} + (coordinates : Finset ι) (vertices : List (ι → ℚ)) (linear : ι → ℚ) + (G j : ℕ) (hvertices : vertices ≠ []) (i : ι) + (hinput : ∀ vertex ∈ vertices, 0 ≤ vertex i ∧ vertex i ≤ 1) : + 0 ≤ finiteRationalOptimizer coordinates vertices linear G j i ∧ + finiteRationalOptimizer coordinates vertices linear G j i ≤ 1 := by + induction j with + | zero => + cases vertices with + | nil => exact False.elim (hvertices rfl) + | cons vertex rest => exact hinput vertex List.mem_cons_self + | succ j ih => + have hselected := (rationalLinearizationMaximizer_spec coordinates vertices + (rationalSmoothedGradient G linear (finiteRationalOptimizer coordinates vertices linear G j)) + hvertices).1 + have hbounds := hinput _ hselected + have hden : (0 : ℚ) < (j : ℚ) + 2 := by positivity + have hweight : (0 : ℚ) ≤ 2 / ((j : ℚ) + 2) := by positivity + have hweightOne : (2 : ℚ) / ((j : ℚ) + 2) ≤ 1 := + (div_le_one₀ hden).2 (by have hj : (0 : ℚ) ≤ j := Nat.cast_nonneg _; linarith) + change 0 ≤ (1 - 2 / ((j : ℚ) + 2)) * _ + 2 / ((j : ℚ) + 2) * _ ∧ + (1 - 2 / ((j : ℚ) + 2)) * _ + 2 / ((j : ℚ) + 2) * _ ≤ 1 + have hcomplement : 0 ≤ 1 - (2 : ℚ) / ((j : ℚ) + 2) := sub_nonneg.mpr hweightOne + constructor + · exact add_nonneg (mul_nonneg hcomplement ih.1) (mul_nonneg hweight hbounds.1) + · calc + _ ≤ (1 - 2 / ((j : ℚ) + 2)) * 1 + (2 : ℚ) / ((j : ℚ) + 2) * 1 := + add_le_add (mul_le_mul_of_nonneg_left ih.2 hcomplement) + (mul_le_mul_of_nonneg_left hbounds.2 hweight) + _ = 1 := by ring + +theorem materializedOptimizerWithWork_denominator {d : ℕ} + (vertices : List (Vector ℚ d)) (linear : Vector ℚ d) (G K B : ℕ) + (hvertices : vertices ≠ []) (hK : 0 < K) (i : Fin d) + (hinput : ∀ vertex ∈ vertices, Nat.size (vertex.get i).den ≤ B) : + Nat.size ((materializedOptimizerWithWork vertices linear G K).1.get i).den ≤ + K * (2 * Nat.size K + 2 + B) + 1 := by + rw [materializedOptimizerWithWork_value, finiteRationalOptimizer_eq_iterate] + apply rationalOptimizerIterate_denominator_bit_length _ _ K B hK i + intro j _ + have hlist : vertices.map Vector.get ≠ [] := by + intro hempty + exact hvertices (List.map_eq_nil_iff.mp hempty) + have hmember := (rationalLinearizationMaximizer_spec univ (vertices.map Vector.get) + (rationalSmoothedGradient G linear.get + (finiteRationalOptimizer univ (vertices.map Vector.get) linear.get G j)) hlist).1 + obtain ⟨vertex, hv, heq⟩ := List.mem_map.mp hmember + change Nat.size (finiteOptimizerSelection univ (vertices.map Vector.get) linear.get G j i).den ≤ B + unfold finiteOptimizerSelection + rw [← heq] + exact hinput vertex hv + +theorem materializedOptimizerWithWork_encoding {d : ℕ} + (vertices : List (Vector ℚ d)) (linear : Vector ℚ d) (G K B : ℕ) + (hvertices : vertices ≠ []) (hK : 0 < K) (i : Fin d) + (hinput : ∀ vertex ∈ vertices, + (0 ≤ vertex.get i ∧ vertex.get i ≤ 1) ∧ Nat.size (vertex.get i).den ≤ B) : + rationalEncodingBits ((materializedOptimizerWithWork vertices linear G K).1.get i) ≤ + 2 * (K * (2 * Nat.size K + 2 + B) + 1) + 1 := by + have hlist : vertices.map Vector.get ≠ [] := by + intro hempty + exact hvertices (List.map_eq_nil_iff.mp hempty) + have hpoint := finiteRationalOptimizer_coordinate_bounds univ (vertices.map Vector.get) + linear.get G K hlist i (by + intro vertex hv + obtain ⟨stored, hs, rfl⟩ := List.mem_map.mp hv + exact (hinput stored hs).1) + rw [← materializedOptimizerWithWork_value vertices linear G K] at hpoint + have habs : |(materializedOptimizerWithWork vertices linear G K).1.get i| ≤ 1 := by + rw [abs_of_nonneg hpoint.1] + exact hpoint.2 + have hnum := Nat.size_le_size (rational_numerator_bound _ 1 habs) + simp only [Nat.one_mul] at hnum + have hden := materializedOptimizerWithWork_denominator vertices linear G K B hvertices hK i + (fun vertex hv => (hinput vertex hv).2) + unfold rationalEncodingBits + omega + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Numerics/OptimizerWorkspace.lean b/lean/OAI/Combinatorics/EditApproximation/Numerics/OptimizerWorkspace.lean new file mode 100644 index 0000000000000000000000000000000000000000..48e76e40dee00d17d53f70de2de71473b5a0ddbd --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Numerics/OptimizerWorkspace.lean @@ -0,0 +1,91 @@ +import OAI.Combinatorics.EditApproximation.Numerics.OptimizerBits + +namespace OAI + +/-! Bit storage of the concrete materialized iterates. The history bound +allows every previous iterate to remain live; it does not rely on a garbage +collector reclaiming old vector allocations. -/ + +namespace EditApproximation + +open Finset + +def rationalVectorStorageBits {d : ℕ} (values : Vector ℚ d) : ℕ := + ∑ i : Fin d, rationalEncodingBits (values.get i) + +def optimizerStoredHistory {d : ℕ} (vertices : List (Vector ℚ d)) + (linear : Vector ℚ d) (G K : ℕ) : List (Vector ℚ d) := + (List.range (K + 1)).map fun j => (materializedOptimizerWithWork vertices linear G j).1 + +def rationalVectorListStorageBits {d : ℕ} (values : List (Vector ℚ d)) : ℕ := + (values.map rationalVectorStorageBits).sum + +theorem rationalVectorStorageBits_le {d : ℕ} (values : Vector ℚ d) (B : ℕ) + (hB : ∀ i, rationalEncodingBits (values.get i) ≤ B) : + rationalVectorStorageBits values ≤ d * B := by + calc + _ ≤ ∑ _i : Fin d, B := Finset.sum_le_sum (fun i _ => hB i) + _ = _ := by simp + +theorem rationalVectorListStorageBits_le {d : ℕ} (values : List (Vector ℚ d)) (B : ℕ) + (hB : ∀ value ∈ values, rationalVectorStorageBits value ≤ B) : + rationalVectorListStorageBits values ≤ values.length * B := by + unfold rationalVectorListStorageBits + induction values with + | nil => simp + | cons value rest ih => + have hv := hB value List.mem_cons_self + have hr := ih (fun v hv => hB v (List.mem_cons_of_mem _ hv)) + simp only [List.map_cons, List.sum_cons, List.length_cons, Nat.add_mul, Nat.one_mul] + omega + +theorem materializedOptimizerWithWork_uniform_encoding {d : ℕ} + (vertices : List (Vector ℚ d)) (linear : Vector ℚ d) (G K B j : ℕ) + (hvertices : vertices ≠ []) (hj : j ≤ K) (i : Fin d) + (hinput : ∀ vertex ∈ vertices, + (0 ≤ vertex.get i ∧ vertex.get i ≤ 1) ∧ Nat.size (vertex.get i).den ≤ B) : + rationalEncodingBits ((materializedOptimizerWithWork vertices linear G j).1.get i) ≤ + 2 * ((K + 1) * (2 * Nat.size (K + 1) + 2 + B) + 1) + 1 := by + by_cases hjzero : j = 0 + · subst j + cases vertices with + | nil => exact False.elim (hvertices rfl) + | cons vertex rest => + have hcoord := hinput vertex List.mem_cons_self + have hnum := Nat.size_le_size (rational_numerator_bound (vertex.get i) 1 (by + rw [abs_of_nonneg hcoord.1.1] + exact hcoord.1.2)) + simp only [Nat.one_mul] at hnum + change rationalEncodingBits (vertex.get i) ≤ _ + unfold rationalEncodingBits + have hK : 1 ≤ K + 1 := by omega + have hpositive : B ≤ 2 * Nat.size (K + 1) + 2 + B := by omega + have hproduct := Nat.mul_le_mul hK hpositive + omega + · have hbound := materializedOptimizerWithWork_encoding vertices linear G j B + hvertices (by omega) i hinput + have hsize := Nat.size_le_size (by omega : j ≤ K + 1) + have hproduct := Nat.mul_le_mul (by omega : j ≤ K + 1) + (by omega : 2 * Nat.size j + 2 + B ≤ 2 * Nat.size (K + 1) + 2 + B) + omega + +theorem optimizerStoredHistory_storage_le {d : ℕ} + (vertices : List (Vector ℚ d)) (linear : Vector ℚ d) (G K B : ℕ) + (hvertices : vertices ≠ []) + (hinput : ∀ vertex ∈ vertices, ∀ i, + (0 ≤ vertex.get i ∧ vertex.get i ≤ 1) ∧ Nat.size (vertex.get i).den ≤ B) : + rationalVectorListStorageBits (optimizerStoredHistory vertices linear G K) ≤ + (K + 1) * (d * (2 * ((K + 1) * (2 * Nat.size (K + 1) + 2 + B) + 1) + 1)) := by + have hstorage := rationalVectorListStorageBits_le (optimizerStoredHistory vertices linear G K) + (d * (2 * ((K + 1) * (2 * Nat.size (K + 1) + 2 + B) + 1) + 1)) (by + intro value hv + obtain ⟨j, hj, rfl⟩ := List.mem_map.mp hv + apply rationalVectorStorageBits_le + intro i + exact materializedOptimizerWithWork_uniform_encoding vertices linear G K B j hvertices + (by have := List.mem_range.mp hj; omega) i (fun vertex hv => hinput vertex hv i)) + simpa only [optimizerStoredHistory, List.length_map, List.length_range] using hstorage + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Numerics/RationalIntermediateBits.lean b/lean/OAI/Combinatorics/EditApproximation/Numerics/RationalIntermediateBits.lean new file mode 100644 index 0000000000000000000000000000000000000000..2e17a015fe9ca3818909ef09874c50077b084df7 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Numerics/RationalIntermediateBits.lean @@ -0,0 +1,89 @@ +import OAI.Combinatorics.EditApproximation.Numerics.NumericalWork + +namespace OAI + +/-! Bounds on the reduced integer representations produced by the rational +operations in the materialized numerical routines. -/ + +namespace EditApproximation + +theorem rational_add_numerator_le (a b : ℚ) : + (a + b).num.natAbs ≤ a.num.natAbs * b.den + b.num.natAbs * a.den := by + have heq := congrArg Int.natAbs (Rat.add_num_den' a b) + simp only [Int.natAbs_mul, Int.natAbs_natCast] at heq + have hadd := Int.natAbs_add_le (a.num * (b.den : ℤ)) (b.num * (a.den : ℤ)) + simp only [Int.natAbs_mul, Int.natAbs_natCast] at hadd + have hden := Nat.le_of_dvd (Nat.mul_pos a.den_pos b.den_pos) (Rat.add_den_dvd a b) + have hmul := Nat.mul_le_mul hadd hden + have hpos := Nat.mul_pos a.den_pos b.den_pos + nlinarith only [heq, hmul, hpos] + +theorem rational_mul_numerator_le (a b : ℚ) : + (a * b).num.natAbs ≤ a.num.natAbs * b.num.natAbs := by + have heq := congrArg Int.natAbs (Rat.mul_num_den' a b) + simp only [Int.natAbs_mul, Int.natAbs_natCast] at heq + have hden := Nat.le_of_dvd (Nat.mul_pos a.den_pos b.den_pos) (Rat.mul_den_dvd a b) + have hmul := Nat.mul_le_mul_left (a.num.natAbs * b.num.natAbs) hden + have hpos := Nat.mul_pos a.den_pos b.den_pos + nlinarith only [heq, hmul, hpos] + +theorem rationalEncodingBits_add (a b : ℚ) : + rationalEncodingBits (a + b) ≤ 2 * rationalEncodingBits a + 2 * rationalEncodingBits b + 2 := by + have hnum := (Nat.size_le_size (rational_add_numerator_le a b)).trans + (natural_sum_bit_length (a.num.natAbs * b.den) (b.num.natAbs * a.den)) + have hnum1 := natural_product_bit_length a.num.natAbs b.den + have hnum2 := natural_product_bit_length b.num.natAbs a.den + have hden := (Nat.size_le_size (Nat.le_of_dvd (Nat.mul_pos a.den_pos b.den_pos) + (Rat.add_den_dvd a b))).trans (natural_product_bit_length a.den b.den) + unfold rationalEncodingBits + omega + +theorem rationalEncodingBits_mul (a b : ℚ) : + rationalEncodingBits (a * b) ≤ rationalEncodingBits a + rationalEncodingBits b + 1 := by + have hnum := (Nat.size_le_size (rational_mul_numerator_le a b)).trans + (natural_product_bit_length a.num.natAbs b.num.natAbs) + have hden := (Nat.size_le_size (Nat.le_of_dvd (Nat.mul_pos a.den_pos b.den_pos) + (Rat.mul_den_dvd a b))).trans (natural_product_bit_length a.den b.den) + unfold rationalEncodingBits + omega + +theorem rationalEncodingBits_neg (a : ℚ) : rationalEncodingBits (-a) = rationalEncodingBits a := by + simp [rationalEncodingBits] + +theorem rationalEncodingBits_sub (a b : ℚ) : + rationalEncodingBits (a - b) ≤ 2 * rationalEncodingBits a + 2 * rationalEncodingBits b + 2 := by + simpa only [sub_eq_add_neg, rationalEncodingBits_neg] using rationalEncodingBits_add a (-b) + +theorem rationalEncodingBits_inv (a : ℚ) : + rationalEncodingBits a⁻¹ ≤ rationalEncodingBits a + 2 := by + by_cases ha : a.num = 0 + · have hzero : a = 0 := Rat.zero_of_num_zero ha + subst a + norm_num [rationalEncodingBits] + · simp only [rationalEncodingBits, Rat.num_inv, Rat.den_inv, ha, ↓reduceIte, + Int.natAbs_mul, Int.natAbs_natCast, Int.natAbs_sign_of_ne_zero ha, Nat.one_mul] + omega + +theorem rationalEncodingBits_div (a b : ℚ) : + rationalEncodingBits (a / b) ≤ rationalEncodingBits a + rationalEncodingBits b + 3 := by + have hmul := rationalEncodingBits_mul a b⁻¹ + have hinv := rationalEncodingBits_inv b + rw [div_eq_mul_inv] + omega + +theorem rationalEncodingBits_natCast (n : ℕ) : + rationalEncodingBits (n : ℚ) = Nat.size n + 2 := by + simp [rationalEncodingBits] + +theorem rationalEncodingBits_pow (a : ℚ) (n : ℕ) : + rationalEncodingBits (a ^ n) ≤ n * (rationalEncodingBits a + 1) + 3 := by + induction n with + | zero => norm_num [rationalEncodingBits] + | succ n ih => + rw [pow_succ] + have hmul := rationalEncodingBits_mul (a ^ n) a + nlinarith only [ih, hmul] + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Numerics/RationalPrefix.lean b/lean/OAI/Combinatorics/EditApproximation/Numerics/RationalPrefix.lean new file mode 100644 index 0000000000000000000000000000000000000000..d958e54457c281bf92208ccf72268264da34f979 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Numerics/RationalPrefix.lean @@ -0,0 +1,50 @@ +import OAI.Combinatorics.EditApproximation.Geometry.PrefixCosts +import OAI.Combinatorics.EditApproximation.Numerics.RationalRefinement +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Rational execution and exact real casts of the finite band predictor. -/ + +namespace EditApproximation + +open Finset + + + +theorem rationalConnectionBudget_cast {n : ℕ} (start finish : ℚ) (states : List (TargetInterval n)) : + (rationalConnectionBudget start states finish : ℝ) = realConnectionBudget start states finish := by + induction states generalizing start with + | nil => simp only [rationalConnectionBudget, realConnectionBudget, Rat.cast_abs, Rat.cast_sub] + | cons state rest ih => + simp only [rationalConnectionBudget, realConnectionBudget, Rat.cast_add, Rat.cast_abs, + Rat.cast_sub, Rat.cast_natCast, ih] + + + +theorem rationalWidePrefixCost_cast {nx ny M : ℕ} (parent : TargetInterval nx) + (r : TargetInterval ny) (states : Fin M → TargetInterval ny) + (child : Fin M → TargetInterval ny → ℚ) (j : ℕ) (p : ℚ) : + (rationalWidePrefixCost parent r states child j p : ℝ) = + widePrefixCost parent r states (fun i s => (child i s : ℝ)) j p := by + simp only [rationalWidePrefixCost, widePrefixCost, Rat.cast_add, Rat.cast_sum, + rationalConnectionBudget_cast, Rat.cast_natCast] + congr 1 + apply sum_congr rfl + intro i hi + split_ifs <;> simp + + + +theorem rationalWidePrefixMinimum_cast {nx ny M : ℕ} (parent : TargetInterval nx) + (r : TargetInterval ny) (actions : List (Fin M → TargetInterval ny)) (hnonempty : actions ≠ []) + (child : Fin M → TargetInterval ny → ℚ) (j : ℕ) (p : ℚ) : + (rationalWidePrefixMinimum parent r actions hnonempty child j p : ℝ) = + widePrefixMinimum parent r actions hnonempty (fun i s => (child i s : ℝ)) j p := by + rw [rationalWidePrefixMinimum, rationalMinimum_cast] + simp only [widePrefixMinimum, rationalWidePrefixCost_cast, List.map_map, Function.comp_def] + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Numerics/RationalPruning.lean b/lean/OAI/Combinatorics/EditApproximation/Numerics/RationalPruning.lean new file mode 100644 index 0000000000000000000000000000000000000000..0de37f82159474c5415e3322ebc973849d20f3f7 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Numerics/RationalPruning.lean @@ -0,0 +1,136 @@ +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalBoundsAllSeeds + +namespace OAI + +/-! Exact candidate pruning uses value lower bounds, without an accuracy event. -/ + +namespace EditApproximation + +open Finset + +theorem rationalMinimum_filter_map {ι : Type*} (indices : List ι) (keep : ι → Bool) + (value : ι → ℚ) (fallback : ℚ) + (hdiscard : ∀ i ∈ indices, keep i = false → fallback ≤ value i) : + rationalMinimum fallback ((indices.filter keep).map value) = + rationalMinimum fallback (indices.map value) := by + induction indices with + | nil => rfl + | cons i rest ih => + have hrest : ∀ j ∈ rest, keep j = false → fallback ≤ value j := + fun j hj => hdiscard j (List.mem_cons.mpr (Or.inr hj)) + cases hp : keep i with + | false => + simp only [List.filter_cons, hp, Bool.false_eq_true, ↓reduceIte, List.map_cons, rationalMinimum] + rw [ih hrest] + exact (min_eq_right ((rationalMinimum_le_fallback _ _).trans + (hdiscard i (List.mem_cons_self) hp))).symm + | true => + simp only [List.filter_cons, hp, ↓reduceIte, List.map_cons, rationalMinimum, ih hrest] + +theorem rationalMinimum_local_complete {ι : Type*} (complete nearby : List ι) + (value : ι → ℚ) (fallback : ℚ) + (hsubset : ∀ i ∈ nearby, i ∈ complete) + (hcover : ∀ i ∈ complete, value i ≤ fallback → i ∈ nearby) : + rationalMinimum fallback (nearby.map value) = rationalMinimum fallback (complete.map value) := by + apply le_antisymm + · apply (le_rationalMinimum_iff _ _ _).2 + refine ⟨rationalMinimum_le_fallback _ _, ?_⟩ + intro v hv + obtain ⟨i, hi, rfl⟩ := List.mem_map.mp hv + by_cases hvalue : value i ≤ fallback + · exact rationalMinimum_le_member _ _ (List.mem_map.mpr ⟨i, hcover i hi hvalue, rfl⟩) + · exact (rationalMinimum_le_fallback _ _).trans (le_of_not_ge hvalue) + · apply (le_rationalMinimum_iff _ _ _).2 + refine ⟨rationalMinimum_le_fallback _ _, ?_⟩ + intro v hv + obtain ⟨i, hi, rfl⟩ := List.mem_map.mp hv + exact rationalMinimum_le_member _ _ (List.mem_map.mpr ⟨i, hsubset i hi, rfl⟩) + +theorem rationalMinimum_min_fallback (a b : ℚ) (values : List ℚ) : + min a (rationalMinimum b values) = rationalMinimum (min a b) values := by + induction values with + | nil => rfl + | cons v rest ih => + simp only [rationalMinimum, ← ih] + exact min_left_comm _ _ _ + +theorem rationalMinimum_local_complete_lt {ι : Type*} (complete nearby : List ι) + (value : ι → ℚ) (fallback : ℚ) + (hsubset : ∀ i ∈ nearby, i ∈ complete) + (hcover : ∀ i ∈ complete, value i < fallback → i ∈ nearby) : + rationalMinimum fallback (nearby.map value) = rationalMinimum fallback (complete.map value) := by + apply le_antisymm + · apply (le_rationalMinimum_iff _ _ _).2 + refine ⟨rationalMinimum_le_fallback _ _, ?_⟩ + intro v hv + obtain ⟨i, hi, rfl⟩ := List.mem_map.mp hv + by_cases hvalue : value i < fallback + · exact rationalMinimum_le_member _ _ (List.mem_map.mpr ⟨i, hcover i hi hvalue, rfl⟩) + · exact (rationalMinimum_le_fallback _ _).trans (le_of_not_gt hvalue) + · apply (le_rationalMinimum_iff _ _ _).2 + refine ⟨rationalMinimum_le_fallback _ _, ?_⟩ + intro v hv + obtain ⟨i, hi, rfl⟩ := List.mem_map.mp hv + exact rationalMinimum_le_member _ _ (List.mem_map.mpr ⟨i, hsubset i hi, rfl⟩) + +theorem rationalMinimum_cons_fallback (fallback v : ℚ) (values : List ℚ) : + rationalMinimum fallback (v :: values) = min fallback (rationalMinimum v values) := by + change min v (rationalMinimum fallback values) = _ + rw [rationalMinimum_min_fallback, rationalMinimum_min_fallback, min_comm v fallback] + +theorem rationalMinimum_map_max (lower fallback : ℚ) (values : List ℚ) : + rationalMinimum (max lower fallback) (values.map (max lower)) = + max lower (rationalMinimum fallback values) := by + induction values with + | nil => rfl + | cons v rest ih => + simp only [List.map_cons, rationalMinimum, ih, max_min_distrib_left] + +theorem rationalRefinementUpdate_online_list (delta cone : ℚ) (values : List ℚ) : + rationalRefinementUpdate delta cone (rationalOnlineMinimum values) = + rationalMinimum cone (values.map (max (cone / (1 + delta)))) := by + cases values with + | nil => rfl + | cons v rest => + simp only [rationalOnlineMinimum, rationalRefinementUpdate, List.map_cons, + rationalMinimum_cons_fallback, rationalMinimum_map_max] + +theorem rationalRefinementUpdate_filter_online {ι : Type*} + (indices : List ι) (keep : ι → Bool) (value : ι → ℚ) (delta cone : ℚ) + (hdiscard : ∀ i ∈ indices, keep i = false → cone ≤ value i) : + rationalRefinementUpdate delta cone (rationalOnlineMinimum ((indices.filter keep).map value)) = + rationalRefinementUpdate delta cone (rationalOnlineMinimum (indices.map value)) := by + simp only [rationalRefinementUpdate_online_list, List.map_map, Function.comp_def] + apply rationalMinimum_filter_map + intro i hi hkeep + exact (hdiscard i hi hkeep).trans (le_max_right _ _) + +theorem rationalActionValue_pruned_lower {Parent Child : Type*} {M : ℕ} + (distance : Parent → Parent → ℚ) (L : ℚ) (child : Child → ℚ) (q : Parent) + (action : RationalBellmanAction Parent Child M) (threshold : ℚ) + (hcharge : threshold ≤ L * distance q action.center) + (hconnection : 0 ≤ action.connection) (hchild : ∀ i, 0 ≤ child (action.childState i)) : + threshold ≤ rationalActionValue distance L child q action := by + unfold rationalActionValue + apply hcharge.trans + simpa only [add_assoc] using + (le_add_of_nonneg_right (a := L * distance q action.center) + (add_nonneg hconnection (sum_nonneg fun i _ => hchild i))) + +theorem rationalBellman_prune_centers {Parent Child : Type*} {M : ℕ} + (fallback : Parent → ℚ) (distance : Parent → Parent → ℚ) (L : ℚ) + (actions : List (RationalBellmanAction Parent Child M)) (child : Child → ℚ) (q : Parent) + (hconnection : ∀ action ∈ actions, 0 ≤ action.connection) (hchild : ∀ s, 0 ≤ child s) : + rationalBellman fallback distance L + (actions.filter (fun action => decide (L * distance q action.center ≤ fallback q))) child q = + rationalBellman fallback distance L actions child q := by + unfold rationalBellman + apply rationalMinimum_filter_map + intro action ha hkeep + have hfar : ¬ L * distance q action.center ≤ fallback q := of_decide_eq_false hkeep + exact rationalActionValue_pruned_lower distance L child q action (fallback q) + (le_of_lt (lt_of_not_ge hfar)) (hconnection action ha) (fun i => hchild _) + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Numerics/RationalRefinement.lean b/lean/OAI/Combinatorics/EditApproximation/Numerics/RationalRefinement.lean new file mode 100644 index 0000000000000000000000000000000000000000..db2476e67c8611febef2ab9f6c6bdd8c998e5611 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Numerics/RationalRefinement.lean @@ -0,0 +1,89 @@ +import OAI.Combinatorics.EditApproximation.Geometry.Bellman +import OAI.Combinatorics.EditApproximation.Geometry.Cones +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! +# Rational execution of the Bellman and refinement operations + +Every finite minimum, cone cost, warmup iteration, and refinement update +is computed in rational arithmetic. The real analysis used elsewhere is +the exact cast of these operations. An absent online candidate returns +the cone minimum, avoiding an extended-real value in the implementation. +-/ + +namespace EditApproximation + + + +theorem rationalMinimum_cast (fallback : ℚ) (values : List ℚ) : + (rationalMinimum fallback values : ℝ) = finiteMinimum (fallback : ℝ) (values.map Rat.cast) := by + induction values with + | nil => rfl + | cons value rest ih => + simp only [rationalMinimum, finiteMinimum, List.map_cons, Rat.cast_min, ih] + + + +def RationalBellmanAction.toReal {Parent Child : Type*} {M : ℕ} + (action : RationalBellmanAction Parent Child M) : BellmanAction Parent Child M := + ⟨action.center, action.connection, action.childState⟩ + + + + + +theorem rationalActionValue_cast {Parent Child : Type*} {M : ℕ} + (distance : Parent → Parent → ℚ) (L : ℚ) (child : Child → ℚ) + (query : Parent) (action : RationalBellmanAction Parent Child M) : + (rationalActionValue distance L child query action : ℝ) = + bellmanActionValue (fun q r => (distance q r : ℝ)) (L : ℝ) + (fun s => (child s : ℝ)) query action.toReal := by + simp only [rationalActionValue, bellmanActionValue, RationalBellmanAction.toReal, + Rat.cast_add, Rat.cast_mul, Rat.cast_sum] + +theorem rationalBellman_cast {Parent Child : Type*} {M : ℕ} + (fallback : Parent → ℚ) (distance : Parent → Parent → ℚ) (L : ℚ) + (actions : List (RationalBellmanAction Parent Child M)) (child : Child → ℚ) (query : Parent) : + (rationalBellman fallback distance L actions child query : ℝ) = + finiteBellman (fun q => (fallback q : ℝ)) (fun q r => (distance q r : ℝ)) (L : ℝ) + (actions.map RationalBellmanAction.toReal) (fun s => (child s : ℝ)) query := by + rw [rationalBellman, rationalMinimum_cast] + unfold finiteBellman + simp only [List.map_map, Function.comp_def, rationalActionValue_cast] + +def rationalWarmup {State : Type*} (operator : (State → ℚ) → State → ℚ) + (initial : State → ℚ) : ℕ → State → ℚ + | 0 => initial + | t + 1 => operator (rationalWarmup operator initial t) + +theorem rationalWarmup_cast {State : Type*} + (operator : (State → ℚ) → State → ℚ) (realOperator : (State → ℝ) → State → ℝ) + (initial : State → ℚ) + (hoperator : ∀ value q, (operator value q : ℝ) = realOperator (fun s => (value s : ℝ)) q) + (t : ℕ) (q : State) : + (rationalWarmup operator initial t q : ℝ) = warmup realOperator (fun s => (initial s : ℝ)) t q := by + induction t generalizing q with + | zero => rfl + | succ t ih => + rw [rationalWarmup, warmup, hoperator] + congr 1 + funext s + exact ih s + + + +theorem rationalRefinementUpdate_cast (δ cone online : ℚ) : + (rationalRefinementUpdate δ cone (some online) : ℝ) = + refinementUpdate (δ : ℝ) (cone : ℝ) (online : ℝ) := by + simp only [rationalRefinementUpdate, refinementUpdate, Rat.cast_min, Rat.cast_max, + Rat.cast_div, Rat.cast_add, Rat.cast_one] + +theorem rationalRefinementUpdate_none (δ cone : ℚ) : + rationalRefinementUpdate δ cone none = cone := rfl + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Numerics/RationalWideSpatial.lean b/lean/OAI/Combinatorics/EditApproximation/Numerics/RationalWideSpatial.lean new file mode 100644 index 0000000000000000000000000000000000000000..27f3e35d6c16bcc8e7bca07c406f4ddc5bf759a5 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Numerics/RationalWideSpatial.lean @@ -0,0 +1,107 @@ +import OAI.Combinatorics.EditApproximation.Numerics.RationalWideStep + +namespace OAI + +/-! Spatial bounds for a literal rational refinement update. -/ + +namespace EditApproximation + +open Finset + +theorem rationalMinimum_map_spatial {ι : Type*} (indices : List ι) + (fallback fallback' charge : ℚ) (value value' : ι → ℚ) + (hfallback : fallback ≤ fallback' + charge) + (hvalue : ∀ i ∈ indices, value i ≤ value' i + charge) : + rationalMinimum fallback (indices.map value) ≤ + rationalMinimum fallback' (indices.map value') + charge := by + induction indices with + | nil => exact hfallback + | cons i rest ih => + change min (value i) (rationalMinimum fallback (rest.map value)) ≤ + min (value' i) (rationalMinimum fallback' (rest.map value')) + charge + rw [← min_add_add_right] + exact min_le_min (hvalue i (by simp)) (ih fun j hj => hvalue j (by simp [hj])) + +theorem rationalActionValue_spatial {ny : ℕ} {Child : Type*} {M : ℕ} + (L : ℚ) (hL : 0 ≤ L) (child : Child → ℚ) + (q q' : TargetInterval ny) (action : RationalBellmanAction (TargetInterval ny) Child M) : + rationalActionValue (fun q r => targetEndpointDistance q r) L child q action ≤ + rationalActionValue (fun q r => targetEndpointDistance q r) L child q' action + + L * targetEndpointDistance q q' := by + have htriangle : (targetEndpointDistance q action.center : ℚ) ≤ + targetEndpointDistance q' action.center + targetEndpointDistance q q' := by + exact_mod_cast targetEndpointDistance_triangle q q' action.center + have h := mul_le_mul_of_nonneg_left htriangle hL + dsimp only [rationalActionValue] + linarith only [h] + +theorem rationalBellman_spatial {ny : ℕ} {Child : Type*} {M : ℕ} + (initial : TargetInterval ny → ℚ) (L : ℚ) (hL : 0 ≤ L) + (actions : List (RationalBellmanAction (TargetInterval ny) Child M)) (child : Child → ℚ) + (q q' : TargetInterval ny) + (hinit : initial q ≤ initial q' + L * targetEndpointDistance q q') : + rationalBellman initial (fun q r => targetEndpointDistance q r) L actions child q ≤ + rationalBellman initial (fun q r => targetEndpointDistance q r) L actions child q' + + L * targetEndpointDistance q q' := by + apply rationalMinimum_map_spatial _ _ _ _ _ _ hinit + intro action _ + exact rationalActionValue_spatial L hL child q q' action + +theorem rationalWideStepCone_spatial {nx ny M : ℕ} (parent : TargetInterval nx) + (representatives : List (ℕ × TargetInterval ny)) (P : ℕ) + (initial : TargetInterval ny → ℚ) (L : ℚ) (hL : 0 ≤ L) + (old current : Fin M × TargetInterval ny → ℚ) + (groups : List (RationalBellmanAction (TargetInterval ny) (Fin M × TargetInterval ny) M)) + (q q' : TargetInterval ny) + (hinit : initial q ≤ initial q' + L * targetEndpointDistance q q') : + rationalWideStepCone parent representatives P initial L old current groups q ≤ + rationalWideStepCone parent representatives P initial L old current groups q' + + L * targetEndpointDistance q q' := by + apply rationalMinimum_map_spatial _ _ _ _ _ _ + (rationalBellman_spatial initial L hL _ old q q' hinit) + intro action _ + exact rationalActionValue_spatial L hL current q q' action + +theorem rationalRefinementUpdate_le_cone (delta cone : ℚ) (online : Option ℚ) : + rationalRefinementUpdate delta cone online ≤ cone := by + cases online with + | none => exact le_rfl + | some value => exact min_le_left _ _ + +theorem rationalRefinementUpdate_div_lower (delta cone : ℚ) (online : Option ℚ) + (hdelta : 0 ≤ delta) (hcone : 0 ≤ cone) : + cone / (1 + delta) ≤ rationalRefinementUpdate delta cone online := by + have hdiv : cone / (1 + delta) ≤ cone := div_le_self hcone (by linarith) + cases online with + | none => exact hdiv + | some value => exact le_min hdiv (le_max_left _ _) + +theorem rationalWideStep_spatial {nx ny M : ℕ} (parent : TargetInterval nx) + (representatives : List (ℕ × TargetInterval ny)) (P : ℕ) + (initial : TargetInterval ny → ℚ) (L delta : ℚ) (hL : 0 ≤ L) (hdelta : 0 ≤ delta) + (old current : Fin M × TargetInterval ny → ℚ) + (groups : List (RationalBellmanAction (TargetInterval ny) (Fin M × TargetInterval ny) M)) + (online : TargetInterval ny → List (RationalBellmanAction (TargetInterval ny) (Fin M × TargetInterval ny) M)) + (q q' : TargetInterval ny) + (hinit : initial q ≤ initial q' + L * targetEndpointDistance q q') + (hcone : 0 ≤ rationalWideStepCone parent representatives P initial L old current groups q') : + rationalWideStep parent representatives P initial L delta old current groups (online q) q ≤ + (1 + delta) * rationalWideStep parent representatives P initial L delta old current groups (online q') q' + + L * targetEndpointDistance q q' := by + have hu := rationalRefinementUpdate_le_cone delta + (rationalWideStepCone parent representatives P initial L old current groups q) + (rationalOnlineMinimum ((online q).map (rationalActionValue (fun q r => targetEndpointDistance q r) L current q))) + have hs := rationalWideStepCone_spatial parent representatives P initial L hL old current groups q q' hinit + have hl := rationalRefinementUpdate_div_lower delta + (rationalWideStepCone parent representatives P initial L old current groups q') + (rationalOnlineMinimum ((online q').map (rationalActionValue (fun q r => targetEndpointDistance q r) L current q'))) + hdelta hcone + have hd : (0 : ℚ) < 1 + delta := by linarith + have hl' := (div_le_iff₀ hd).mp hl + change _ ≤ (1 + delta) * _ + _ + dsimp only [rationalWideStep] at * + nlinarith only [hu, hs, hl'] + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Numerics/RationalWideStep.lean b/lean/OAI/Combinatorics/EditApproximation/Numerics/RationalWideStep.lean new file mode 100644 index 0000000000000000000000000000000000000000..b35a94e4c49a94afd97d6c0572f69ff41e3ef645 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Numerics/RationalWideStep.lean @@ -0,0 +1,115 @@ +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalRationalWarmup +import OAI.Combinatorics.EditApproximation.Geometry.LocalInitialCones +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! One literal refinement update with finite selected-group cones and online action values. -/ + +namespace EditApproximation + +open Finset + +theorem rationalMinimum_map_mono {ι : Type*} (indices : List ι) + (fallback fallback' : ℚ) (value value' : ι → ℚ) + (hfallback : fallback ≤ fallback') (hvalue : ∀ i ∈ indices, value i ≤ value' i) : + rationalMinimum fallback (indices.map value) ≤ rationalMinimum fallback' (indices.map value') := by + induction indices with + | nil => exact hfallback + | cons i rest ih => + exact min_le_min (hvalue i (by simp)) (ih fun j hj => hvalue j (by simp [hj])) + +theorem rationalBellman_mono {Parent Child : Type*} {M : ℕ} + (fallback : Parent → ℚ) (distance : Parent → Parent → ℚ) (L : ℚ) + (actions : List (RationalBellmanAction Parent Child M)) {child child' : Child → ℚ} + (hchild : child ≤ child') (q : Parent) : + rationalBellman fallback distance L actions child q ≤ rationalBellman fallback distance L actions child' q := by + apply rationalMinimum_map_mono _ _ _ _ _ le_rfl + intro action _ + exact add_le_add le_rfl (sum_le_sum fun i _ => hchild (action.childState i)) + +theorem rationalBellman_le_action {Parent Child : Type*} {M : ℕ} + (fallback : Parent → ℚ) (distance : Parent → Parent → ℚ) (L : ℚ) + (actions : List (RationalBellmanAction Parent Child M)) (child : Child → ℚ) + (q : Parent) (action : RationalBellmanAction Parent Child M) (haction : action ∈ actions) : + rationalBellman fallback distance L actions child q ≤ rationalActionValue distance L child q action := + rationalMinimum_le_member _ _ (List.mem_map.mpr ⟨action, haction, rfl⟩) + + + +theorem rationalOnlineMinimum_lower (lower : ℚ) (values : List ℚ) + (hvalues : ∀ v ∈ values, lower ≤ v) {online : ℚ} + (honline : rationalOnlineMinimum values = some online) : lower ≤ online := by + cases values with + | nil => cases honline + | cons first rest => + have heq : rationalMinimum first rest = online := Option.some.inj honline + rw [← heq] + exact (le_rationalMinimum_iff _ _ _).2 + ⟨hvalues first (by simp), fun v hv => hvalues v (by simp [hv])⟩ + +def rationalWideStepCone {nx ny M : ℕ} (parent : TargetInterval nx) + (representatives : List (ℕ × TargetInterval ny)) (P : ℕ) + (initial : TargetInterval ny → ℚ) (L : ℚ) + (old current : Fin M × TargetInterval ny → ℚ) + (groups : List (RationalBellmanAction (TargetInterval ny) (Fin M × TargetInterval ny) M)) + (q : TargetInterval ny) : ℚ := + rationalMinimum (rationalBellman initial (fun q r => targetEndpointDistance q r) L + (rationalActualWideActions parent representatives P) old q) + (groups.map (rationalActionValue (fun q r => targetEndpointDistance q r) L current q)) + +def rationalWideStep {nx ny M : ℕ} (parent : TargetInterval nx) + (representatives : List (ℕ × TargetInterval ny)) (P : ℕ) + (initial : TargetInterval ny → ℚ) (L delta : ℚ) + (old current : Fin M × TargetInterval ny → ℚ) + (groups online : List (RationalBellmanAction (TargetInterval ny) (Fin M × TargetInterval ny) M)) + (q : TargetInterval ny) : ℚ := + rationalRefinementUpdate delta (rationalWideStepCone parent representatives P initial L old current groups q) + (rationalOnlineMinimum (online.map (rationalActionValue (fun q r => targetEndpointDistance q r) L current q))) + +/-- Both lower candidates are genuine current-child wide Bellman cones. +The sampled choices enter only through literal membership in the wide list. -/ +theorem rationalWideStep_bellman_sandwich {nx ny M : ℕ} (parent : TargetInterval nx) + (representatives : List (ℕ × TargetInterval ny)) (P : ℕ) + (initial : TargetInterval ny → ℚ) (L delta : ℚ) + (old current : Fin M × TargetInterval ny → ℚ) (hmono : current ≤ old) + (groups online : List (RationalBellmanAction (TargetInterval ny) (Fin M × TargetInterval ny) M)) + (hgroups : ∀ action ∈ groups, action ∈ rationalActualWideActions parent representatives P) + (honline : ∀ action ∈ online, action ∈ rationalActualWideActions parent representatives P) + (q : TargetInterval ny) : + rationalBellman initial (fun q r => targetEndpointDistance q r) L + (rationalActualWideActions parent representatives P) current q ≤ + rationalWideStep parent representatives P initial L delta old current groups online q ∧ + rationalWideStep parent representatives P initial L delta old current groups online q ≤ + rationalBellman initial (fun q r => targetEndpointDistance q r) L + (rationalActualWideActions parent representatives P) old q := by + let actions := rationalActualWideActions (M := M) parent representatives P + let distance := fun q r : TargetInterval ny => (targetEndpointDistance q r : ℚ) + let lower := rationalBellman initial distance L actions current q + let upper := rationalBellman initial distance L actions old q + let cone := rationalWideStepCone parent representatives P initial L old current groups q + have hcone : lower ≤ cone := by + apply (le_rationalMinimum_iff _ _ _).2 + refine ⟨rationalBellman_mono initial distance L actions hmono q, ?_⟩ + intro value hvalue + obtain ⟨action, ha, rfl⟩ := List.mem_map.mp hvalue + exact rationalBellman_le_action initial distance L actions current q action (hgroups action ha) + have hupper : cone ≤ upper := rationalMinimum_le_fallback _ _ + have honlineLower : ∀ value ∈ online.map (rationalActionValue distance L current q), lower ≤ value := by + intro value hvalue + obtain ⟨action, ha, rfl⟩ := List.mem_map.mp hvalue + exact rationalBellman_le_action initial distance L actions current q action (honline action ha) + change lower ≤ rationalRefinementUpdate delta cone + (rationalOnlineMinimum (online.map (rationalActionValue distance L current q))) ∧ + rationalRefinementUpdate delta cone + (rationalOnlineMinimum (online.map (rationalActionValue distance L current q))) ≤ upper + cases hmin : rationalOnlineMinimum (online.map (rationalActionValue distance L current q)) with + | none => exact ⟨hcone, hupper⟩ + | some value => + have hlower := rationalOnlineMinimum_lower lower _ honlineLower hmin + exact ⟨le_min hcone (hlower.trans (le_max_right _ _)), (min_le_left _ _).trans hupper⟩ + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Numerics/ScalarAllocation.lean b/lean/OAI/Combinatorics/EditApproximation/Numerics/ScalarAllocation.lean new file mode 100644 index 0000000000000000000000000000000000000000..400702a062a81daa3d1f203cecba902e242ae6ef --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Numerics/ScalarAllocation.lean @@ -0,0 +1,129 @@ +import OAI.Combinatorics.EditApproximation.Binary.FractionAllocation +import OAI.Combinatorics.EditApproximation.Binary.BinaryFixedDenominator +import OAI.Combinatorics.EditApproximation.Binary.BinaryCeilingWork +import OAI.Combinatorics.EditApproximation.Coarse.CoarseDenominatorArithmetic +import OAI.Combinatorics.EditApproximation.Probability.FiniteEnumerationWork +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation + + + +theorem bitPowerAllocation_le_work (base : List Bool) (n : ℕ) : + bitPowerAllocation base n ≤ (bitPowerWithWork base n).2 := by + induction n with + | zero => rfl + | succ n ih => + have hm := bitMulAllocation_le_work (bitPowerWithWork base n).1 base + have ht := trimBitWordAllocation_le_work + (bitMulWithWork (bitPowerWithWork base n).1 base).1 + simp only [bitPowerAllocation, bitPowerWithWork] + omega + +def coarseDenominatorAllocation (allowanceDen q L branching : List Bool) (D : ℕ) : ℕ := + let first := bitMulWithWork L branching + let base := bitMulWithWork first.1 q + let trimmed := trimBitWordWithWork base.1 + let power := bitPowerWithWork trimmed.1 D + let initial := bitMulWithWork allowanceDen q + let product := bitMulWithWork initial.1 power.1 + bitMulAllocation L branching + bitMulAllocation first.1 q + trimBitWordAllocation base.1 + + bitPowerAllocation trimmed.1 D + bitMulAllocation allowanceDen q + + bitMulAllocation initial.1 power.1 + trimBitWordAllocation product.1 + +theorem coarseDenominatorAllocation_le_work (allowanceDen q L branching : List Bool) (D : ℕ) : + coarseDenominatorAllocation allowanceDen q L branching D ≤ + (coarseDenominatorWithWork allowanceDen q L branching D).2 := by + have h1 := bitMulAllocation_le_work L branching + have h2 := bitMulAllocation_le_work (bitMulWithWork L branching).1 q + have h3 := trimBitWordAllocation_le_work (bitMulWithWork (bitMulWithWork L branching).1 q).1 + have h4 := bitPowerAllocation_le_work + (trimBitWordWithWork (bitMulWithWork (bitMulWithWork L branching).1 q).1).1 D + have h5 := bitMulAllocation_le_work allowanceDen q + have h6 := bitMulAllocation_le_work (bitMulWithWork allowanceDen q).1 + (bitPowerWithWork (trimBitWordWithWork (bitMulWithWork (bitMulWithWork L branching).1 q).1).1 D).1 + have h7 := trimBitWordAllocation_le_work + (bitMulWithWork (bitMulWithWork allowanceDen q).1 + (bitPowerWithWork (trimBitWordWithWork (bitMulWithWork (bitMulWithWork L branching).1 q).1).1 D).1).1 + unfold coarseDenominatorAllocation coarseDenominatorWithWork + dsimp only + omega + + + +theorem bitCeilDivAllocation_le_work (divisor bits : List Bool) : + bitCeilDivAllocation divisor bits ≤ (bitCeilDivWithWork divisor bits).2 := by + have hd := bitDivModAllocation_le_work divisor bits + have ha := bitAddAllocation_le_work (bitDivModWithWork divisor bits).1 [true] false + unfold bitCeilDivAllocation bitCeilDivWithWork + dsimp only + split_ifs <;> dsimp only <;> omega + +/-- Map allocation includes one result spine cell for every callback. -/ + + +theorem arithmeticMapAllocation_le_work {α β : Type*} (f : α → β × ℕ) + (allocation : α → ℕ) (values : List α) + (h : ∀ a ∈ values, allocation a ≤ (f a).2) : + arithmeticMapAllocation allocation values ≤ (arithmeticMapWithWork f values).2 := by + induction values with + | nil => rfl + | cons a rest ih => + have hh := h a List.mem_cons_self + have ht := ih (fun b hb => h b (List.mem_cons_of_mem _ hb)) + simp only [arithmeticMapAllocation, arithmeticMapWithWork] + omega + +namespace BinaryFraction + + + +theorem invAllocation_le_work (a : BinaryFraction) : + invAllocation a ≤ a.invWithWork.2 := by + unfold invAllocation invWithWork + dsimp only + split_ifs <;> dsimp only + · exact Nat.succ_le_succ (Nat.zero_le _) + · exact Nat.zero_le _ + + + +theorem divAllocation_le_work (a b : BinaryFraction) : + divAllocation a b ≤ (divWithWork a b).2 := by + have hi := invAllocation_le_work b + have hm := canonicalMulAllocation_le_work a b.invWithWork.1 + unfold divAllocation divWithWork + dsimp only + omega + + + +theorem fixedDenominatorAllocation_le_work (a : BinaryFraction) (denominator : List Bool) + (hden : 0 < bitWordValue denominator) : + fixedDenominatorAllocation a denominator hden ≤ (fixedDenominatorWithWork a denominator hden).2 := by + have hm := bitMulAllocation_le_work a.numerator.bits denominator + have hd := bitDivModAllocation_le_work a.denominator + (bitMulWithWork a.numerator.bits denominator).1 + have hc := canonicalizeAllocation_le_work + (⟨⟨a.numerator.negative, + (bitDivModWithWork a.denominator (bitMulWithWork a.numerator.bits denominator).1).1⟩, + denominator, hden⟩ : BinaryFraction) + unfold fixedDenominatorAllocation fixedDenominatorWithWork + dsimp only + omega + + + +theorem naturalCeilingAllocation_le_work (a : BinaryFraction) : + naturalCeilingAllocation a ≤ a.naturalCeilingWithWork.2 := by + have h := bitCeilDivAllocation_le_work a.denominator a.numerator.bits + unfold naturalCeilingAllocation naturalCeilingWithWork + split_ifs <;> dsimp only <;> omega + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Numerics/ScalarControlSpace.lean b/lean/OAI/Combinatorics/EditApproximation/Numerics/ScalarControlSpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..ab323cb4af9067466bd45ff3caf6fdbc55f14e06 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Numerics/ScalarControlSpace.lean @@ -0,0 +1,124 @@ +import OAI.Combinatorics.EditApproximation.Binary.FractionControlSpace + +namespace OAI + +namespace EditApproximation + +def bitCeilDivInvocations (divisor bits : List Bool) : ℕ := + let divided := bitDivModWithWork divisor bits + bitDivModInvocations divisor bits + bitCompareInvocations divided.2.1 [] + 1 + + if (bitCompareWithWork divided.2.1 []).1 = .eq then 0 + else bitAddInvocations divided.1 [true] false + +theorem bitCeilDivInvocations_le_work (divisor bits : List Bool) : + bitCeilDivInvocations divisor bits ≤ (bitCeilDivWithWork divisor bits).2 := by + have hd := bitDivModInvocations_le_work divisor bits + have hc := bitCompareInvocations_le_work (bitDivModWithWork divisor bits).2.1 [] + have ha := bitAddInvocations_le_work (bitDivModWithWork divisor bits).1 [true] false + unfold bitCeilDivInvocations bitCeilDivWithWork + dsimp only + split_ifs <;> dsimp only <;> omega + +def coarseDenominatorInvocations (allowanceDen q L branching : List Bool) (D : ℕ) : ℕ := + let first := bitMulWithWork L branching + let base := bitMulWithWork first.1 q + let trimmed := trimBitWordWithWork base.1 + let power := bitPowerWithWork trimmed.1 D + let initial := bitMulWithWork allowanceDen q + let product := bitMulWithWork initial.1 power.1 + bitMulInvocations L branching + bitMulInvocations first.1 q + trimBitWordInvocations base.1 + + bitPowerInvocations trimmed.1 D + bitMulInvocations allowanceDen q + + bitMulInvocations initial.1 power.1 + trimBitWordInvocations product.1 + 1 + +theorem coarseDenominatorInvocations_le_work (allowanceDen q L branching : List Bool) (D : ℕ) : + coarseDenominatorInvocations allowanceDen q L branching D ≤ + (coarseDenominatorWithWork allowanceDen q L branching D).2 := by + have h1 := bitMulInvocations_le_work L branching + have h2 := bitMulInvocations_le_work (bitMulWithWork L branching).1 q + have h3 := trimBitWordInvocations_le_work (bitMulWithWork (bitMulWithWork L branching).1 q).1 + have h4 := bitPowerInvocations_le_work + (trimBitWordWithWork (bitMulWithWork (bitMulWithWork L branching).1 q).1).1 D + have h5 := bitMulInvocations_le_work allowanceDen q + have h6 := bitMulInvocations_le_work (bitMulWithWork allowanceDen q).1 + (bitPowerWithWork (trimBitWordWithWork (bitMulWithWork (bitMulWithWork L branching).1 q).1).1 D).1 + have h7 := trimBitWordInvocations_le_work + (bitMulWithWork (bitMulWithWork allowanceDen q).1 + (bitPowerWithWork (trimBitWordWithWork (bitMulWithWork (bitMulWithWork L branching).1 q).1).1 D).1).1 + unfold coarseDenominatorInvocations coarseDenominatorWithWork + dsimp only + omega + +/-- Includes the map's base frame and every recursive traversal frame. -/ +def arithmeticMapInvocations {α : Type*} (invocations : α → ℕ) : List α → ℕ + | [] => 1 + | a :: rest => invocations a + arithmeticMapInvocations invocations rest + 1 + +theorem arithmeticMapInvocations_le_work {α β : Type*} (f : α → β × ℕ) + (invocations : α → ℕ) (values : List α) + (h : ∀ a ∈ values, invocations a ≤ (f a).2) : + arithmeticMapInvocations invocations values ≤ (arithmeticMapWithWork f values).2 + 1 := by + induction values with + | nil => rfl + | cons a rest ih => + have hh := h a List.mem_cons_self + have ht := ih (fun b hb => h b (List.mem_cons_of_mem _ hb)) + simp only [arithmeticMapInvocations, arithmeticMapWithWork] + omega + +namespace BinaryFraction + +def invInvocations (a : BinaryFraction) : ℕ := bitCompareInvocations a.numerator.bits [] + 1 + +theorem invInvocations_le_work (a : BinaryFraction) : + invInvocations a ≤ a.invWithWork.2 := by + have h := bitCompareInvocations_le_work a.numerator.bits [] + unfold invInvocations invWithWork + dsimp only + split_ifs <;> dsimp only <;> omega + +def divInvocations (a b : BinaryFraction) : ℕ := + invInvocations b + canonicalMulInvocations a b.invWithWork.1 + 1 + +theorem divInvocations_le_work (a b : BinaryFraction) : + divInvocations a b ≤ (divWithWork a b).2 := by + have hi := invInvocations_le_work b + have hm := canonicalMulInvocations_le_work a b.invWithWork.1 + unfold divInvocations divWithWork + dsimp only + omega + +def fixedDenominatorInvocations (a : BinaryFraction) (denominator : List Bool) + (hden : 0 < bitWordValue denominator) : ℕ := + let product := bitMulWithWork a.numerator.bits denominator + let quotient := bitDivModWithWork a.denominator product.1 + let raw : BinaryFraction := ⟨⟨a.numerator.negative, quotient.1⟩, denominator, hden⟩ + bitMulInvocations a.numerator.bits denominator + bitDivModInvocations a.denominator product.1 + + canonicalizeInvocations raw + 1 + +theorem fixedDenominatorInvocations_le_work (a : BinaryFraction) (denominator : List Bool) + (hden : 0 < bitWordValue denominator) : + fixedDenominatorInvocations a denominator hden ≤ (fixedDenominatorWithWork a denominator hden).2 := by + have hm := bitMulInvocations_le_work a.numerator.bits denominator + have hd := bitDivModInvocations_le_work a.denominator + (bitMulWithWork a.numerator.bits denominator).1 + have hc := canonicalizeInvocations_le_work + (⟨⟨a.numerator.negative, + (bitDivModWithWork a.denominator (bitMulWithWork a.numerator.bits denominator).1).1⟩, + denominator, hden⟩ : BinaryFraction) + unfold fixedDenominatorInvocations fixedDenominatorWithWork + dsimp only + omega + +def naturalCeilingInvocations (a : BinaryFraction) : ℕ := + if a.numerator.negative then 1 else bitCeilDivInvocations a.denominator a.numerator.bits + 1 + +theorem naturalCeilingInvocations_le_work (a : BinaryFraction) : + naturalCeilingInvocations a ≤ a.naturalCeilingWithWork.2 := by + have h := bitCeilDivInvocations_le_work a.denominator a.numerator.bits + unfold naturalCeilingInvocations naturalCeilingWithWork + split_ifs <;> dsimp only <;> omega + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Numerics/VectorOptimizerWork.lean b/lean/OAI/Combinatorics/EditApproximation/Numerics/VectorOptimizerWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..9642aed2cee0385013ce19febca25cfbedb64faa --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Numerics/VectorOptimizerWork.lean @@ -0,0 +1,353 @@ +import OAI.Combinatorics.EditApproximation.Numerics.NumericalWork +import OAI.Combinatorics.EditApproximation.Geometry.OnlineActionDraw +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Materialized rational optimizer iterates. Finite vectors store the +previous iterate and its gradient, and a scored scan stores the current +best score. Counters charge rational arithmetic, comparisons, array +accesses and array writes. Integer/rational bit costs are separate. -/ + +namespace EditApproximation + +open Finset + +def naturalPowerWithWork (a : ℕ) : ℕ → ℕ × ℕ + | 0 => (1, 0) + | k + 1 => let previous := naturalPowerWithWork a k + (previous.1 * a, previous.2 + 1) + +theorem naturalPowerWithWork_spec (a k : ℕ) : naturalPowerWithWork a k = (a ^ k, k) := by + induction k with + | zero => rfl + | succ k ih => simp only [naturalPowerWithWork, ih, pow_succ] + +theorem vector_get_ofFn {α : Type*} {d : ℕ} (f : Fin d → α) (i : Fin d) : + (Vector.ofFn f).get i = f i := Vector.getElem_ofFn i.isLt + +/-- A single materializing array pass. The operation count includes +array construction, the value/counter traversals, and summing counters. -/ + + +theorem vectorMapWithWork_value {α : Type*} (d : ℕ) (f : Fin d → α × ℕ) (i : Fin d) : + (vectorMapWithWork d f).1.get i = (f i).1 := by + change (Vector.ofFn f |>.map Prod.fst)[i.val] = _ + simp only [Vector.getElem_map, Vector.getElem_ofFn] + +theorem vectorMapWithWork_cost {α : Type*} (d : ℕ) (f : Fin d → α × ℕ) + (C : ℕ) (hC : ∀ i, (f i).2 = C) : + (vectorMapWithWork d f).2 = d * (C + 6) := by + simp only [vectorMapWithWork, Vector.toList_map, Vector.toList_ofFn, List.map_ofFn, + Function.comp_def, hC, List.ofFn_const, List.sum_replicate, smul_eq_mul] + ring + +/-- Dot product over an explicit list of array indices. -/ +def vectorDotListWithWork {d : ℕ} (left right : Vector ℚ d) : List (Fin d) → ℚ × ℕ + | [] => (0, 0) + | i :: indices => + let rest := vectorDotListWithWork left right indices + (left.get i * right.get i + rest.1, rest.2 + 8) + +theorem vectorDotListWithWork_spec {d : ℕ} (left right : Vector ℚ d) (indices : List (Fin d)) : + vectorDotListWithWork left right indices = + ((indices.map fun i => left.get i * right.get i).sum, 8 * indices.length) := by + induction indices with + | nil => rfl + | cons i indices ih => + simp only [vectorDotListWithWork, ih, List.map_cons, List.sum_cons, List.length_cons] + congr 1 + +def vectorDotWithWork {d : ℕ} (left right : Vector ℚ d) : ℚ × ℕ := + vectorDotListWithWork left right (List.finRange d) + +theorem vectorDotWithWork_spec {d : ℕ} (left right : Vector ℚ d) : + vectorDotWithWork left right = (∑ i : Fin d, left.get i * right.get i, 8 * d) := by + simp only [vectorDotWithWork, vectorDotListWithWork_spec, List.length_finRange] + congr 1 + +def rationalGradientCellWithWork {d : ℕ} (G : ℕ) (linear point : Vector ℚ d) (i : Fin d) : ℚ × ℕ := + let smoothing := rationalPowerWithWork (G : ℚ) 50 + let truncation := naturalPowerWithWork G 60 + let logarithm := rationalLogApproximationWithWork (point.get i + 1 / smoothing.1) truncation.1 + (-logarithm.1 - 1 + linear.get i, smoothing.2 + truncation.2 + logarithm.2 + 7) + +theorem rationalGradientCellWithWork_spec {d : ℕ} (G : ℕ) (linear point : Vector ℚ d) (i : Fin d) : + rationalGradientCellWithWork G linear point i = + (rationalSmoothedGradient G linear.get point.get i, G ^ 120 + 2 * G ^ 60 + 121) := by + simp only [rationalGradientCellWithWork, rationalPowerWithWork_spec, naturalPowerWithWork_spec, + rationalLogApproximationWithWork_spec, rationalSmoothedGradient] + congr 1 + rw [show (120 : ℕ) = 60 * 2 by rfl, pow_mul] + ring + +def vectorGradientWithWork {d : ℕ} (G : ℕ) (linear point : Vector ℚ d) : Vector ℚ d × ℕ := + vectorMapWithWork d (rationalGradientCellWithWork G linear point) + +theorem vectorGradientWithWork_value {d : ℕ} (G : ℕ) (linear point : Vector ℚ d) (i : Fin d) : + (vectorGradientWithWork G linear point).1.get i = + rationalSmoothedGradient G linear.get point.get i := by + rw [vectorGradientWithWork, vectorMapWithWork_value, rationalGradientCellWithWork_spec] + +theorem vectorGradientWithWork_cost {d : ℕ} (G : ℕ) (linear point : Vector ℚ d) : + (vectorGradientWithWork G linear point).2 = d * (G ^ 120 + 2 * G ^ 60 + 127) := by + unfold vectorGradientWithWork + rw [vectorMapWithWork_cost _ _ (G ^ 120 + 2 * G ^ 60 + 121) (fun i => congrArg Prod.snd + (rationalGradientCellWithWork_spec G linear point i))] + +/-- A scored scan keeps the winning score instead of recomputing it. +It retains the first maximizer, including ties. -/ +def scoredArgmaxWithWork {α : Type*} (score : α → ℚ × ℕ) : List α → Option (α × ℚ) × ℕ + | [] => (none, 0) + | a :: rest => + let tail := scoredArgmaxWithWork score rest + let current := score a + match tail.1 with + | none => (some (a, current.1), tail.2 + current.2 + 1) + | some best => + (if current.1 < best.2 then some best else some (a, current.1), tail.2 + current.2 + 2) + +theorem scoredArgmaxWithWork_value {α : Type*} (score : α → ℚ × ℕ) (values : List α) : + (scoredArgmaxWithWork score values).1 = + (values.argmax (fun a => (score a).1)).map (fun a => (a, (score a).1)) := by + induction values with + | nil => rfl + | cons a rest ih => + simp only [scoredArgmaxWithWork, ih, List.argmax_cons] + cases h : rest.argmax (fun a => (score a).1) with + | none => rfl + | some best => simp only [Option.map_some]; split_ifs <;> rfl + +theorem scoredArgmaxWithWork_cost {α : Type*} (score : α → ℚ × ℕ) (values : List α) + (C : ℕ) (hC : ∀ a ∈ values, (score a).2 ≤ C) : + (scoredArgmaxWithWork score values).2 ≤ values.length * (C + 2) := by + induction values with + | nil => simp only [scoredArgmaxWithWork, List.length_nil, Nat.zero_mul, le_refl] + | cons a rest ih => + have htail := ih (fun b hb => hC b (List.mem_cons_of_mem a hb)) + have ha := hC a (List.mem_cons_self) + simp only [scoredArgmaxWithWork, List.length_cons] + split <;> dsimp only <;> nlinarith only [htail, ha] + +def vectorMaximizerWithWork {d : ℕ} (gradient : Vector ℚ d) + (vertices : List (Vector ℚ d)) : Vector ℚ d × ℕ := + let selected := scoredArgmaxWithWork (vectorDotWithWork gradient) vertices + ((selected.1.map Prod.fst).getD (Vector.replicate d 0), selected.2 + d + 1) + +theorem vectorMaximizerWithWork_value {d : ℕ} (gradient : Vector ℚ d) + (vertices : List (Vector ℚ d)) : + (vectorMaximizerWithWork gradient vertices).1.get = + rationalLinearizationMaximizer univ (vertices.map Vector.get) gradient.get := by + have hmap := argmax_map_commutes (fun vertex : Vector ℚ d => vertex.get) + (fun vertex => ∑ i : Fin d, gradient.get i * vertex i) vertices + simp only [vectorMaximizerWithWork, scoredArgmaxWithWork_value, vectorDotWithWork_spec, + Option.map_map, Function.comp_def] at hmap ⊢ + unfold rationalLinearizationMaximizer + rw [hmap] + cases h : vertices.argmax (fun vertex => ∑ i : Fin d, gradient.get i * vertex.get i) with + | none => funext i; exact Vector.getElem_replicate i.isLt + | some selected => rfl + +theorem vectorMaximizerWithWork_cost {d : ℕ} (gradient : Vector ℚ d) + (vertices : List (Vector ℚ d)) : + (vectorMaximizerWithWork gradient vertices).2 ≤ vertices.length * (8 * d + 2) + d + 1 := by + exact Nat.add_le_add_right (Nat.add_le_add_right + (scoredArgmaxWithWork_cost _ _ (8 * d) (fun vertex _ => + (congrArg Prod.snd (vectorDotWithWork_spec gradient vertex)).le)) d) 1 + +def materializedOptimizerWithWork {d : ℕ} (vertices : List (Vector ℚ d)) + (linear : Vector ℚ d) (G : ℕ) : ℕ → Vector ℚ d × ℕ + | 0 => (vertices.headD (Vector.replicate d 0), d + 1) + | j + 1 => + let previous := materializedOptimizerWithWork vertices linear G j + let gradient := vectorGradientWithWork G linear previous.1 + let selected := vectorMaximizerWithWork gradient.1 vertices + let step : ℚ := 2 / ((j : ℚ) + 2) + let updated := vectorMapWithWork d fun i => + ((1 - step) * previous.1.get i + step * selected.1.get i, 5) + (updated.1, previous.2 + gradient.2 + selected.2 + updated.2 + 3) + +theorem materializedOptimizerWithWork_value {d : ℕ} (vertices : List (Vector ℚ d)) + (linear : Vector ℚ d) (G j : ℕ) : + (materializedOptimizerWithWork vertices linear G j).1.get = + finiteRationalOptimizer univ (vertices.map Vector.get) linear.get G j := by + induction j with + | zero => + cases vertices with + | nil => funext i; exact Vector.getElem_replicate i.isLt + | cons vertex rest => rfl + | succ j ih => + funext i + simp only [materializedOptimizerWithWork, vectorMapWithWork_value, finiteRationalOptimizer] + rw [congrFun ih i, vectorMaximizerWithWork_value] + congr 2 + congr 1 + funext k + rw [vectorGradientWithWork_value, ih] + +def materializedOptimizerStepBudget (d v G : ℕ) : ℕ := + d * (G ^ 120 + 2 * G ^ 60 + 127) + v * (8 * d + 2) + d + 1 + 11 * d + 3 + +theorem materializedOptimizerWithWork_cost {d : ℕ} (vertices : List (Vector ℚ d)) + (linear : Vector ℚ d) (G j : ℕ) : + (materializedOptimizerWithWork vertices linear G j).2 ≤ + d + 1 + j * materializedOptimizerStepBudget d vertices.length G := by + induction j with + | zero => simp only [materializedOptimizerWithWork, Nat.zero_mul, Nat.add_zero, le_refl] + | succ j ih => + have hselected := vectorMaximizerWithWork_cost + (vectorGradientWithWork G linear (materializedOptimizerWithWork vertices linear G j).1).1 vertices + simp only [materializedOptimizerWithWork, vectorGradientWithWork_cost] + rw [vectorMapWithWork_cost _ _ 5 (fun _ => rfl)] + dsimp only [materializedOptimizerStepBudget] at ih ⊢ + nlinarith only [ih, hselected] + +private theorem optimizerStepArithmetic_bound (d v x y U : ℕ) + (hx : x ≤ U) (hy : y ≤ U) (hU : 1 ≤ U) : + d * (x + 2 * y + 127) + v * (8 * d + 2) + d + 1 + 11 * d + 3 ≤ + 156 * ((v + 1) * (d + 1) * U) := by + let C := (v + 1) * (d + 1) * U + have hd : d * U ≤ C := Nat.mul_le_mul_right U (by nlinarith) + have hv : v * (d + 1) * U ≤ C := + Nat.mul_le_mul_right U (Nat.mul_le_mul_right (d + 1) (by omega)) + have hdu : (d + 1) * U ≤ C := Nat.mul_le_mul_right U (by nlinarith) + have hfirst : d * (x + 2 * y + 127) ≤ 130 * C := by + calc + _ ≤ d * (130 * U) := Nat.mul_le_mul_left d (by omega) + _ = 130 * (d * U) := by ring + _ ≤ 130 * C := Nat.mul_le_mul_left 130 hd + have hsecond : v * (8 * d + 2) ≤ 10 * C := by + calc + _ ≤ 10 * (v * (d + 1)) := by nlinarith + _ ≤ 10 * (v * (d + 1) * U) := Nat.mul_le_mul_left 10 (Nat.le_mul_of_pos_right _ hU) + _ ≤ 10 * C := Nat.mul_le_mul_left 10 hv + have hrest : d + 1 + 11 * d + 3 ≤ 16 * C := by + calc + _ ≤ 16 * (d + 1) := by omega + _ ≤ 16 * ((d + 1) * U) := Nat.mul_le_mul_left 16 (Nat.le_mul_of_pos_right _ hU) + _ ≤ 16 * C := Nat.mul_le_mul_left 16 hdu + change _ ≤ 156 * C + omega + +private theorem move_outer_factor (a b c d : ℕ) : d * (a * b * c) = a * b * (d * c) := by + ac_rfl + +private theorem move_outer_factor_right (a b c d : ℕ) : d * (a * b * c) = a * b * (c * d) := by + ac_rfl + +theorem materializedOptimizerStepBudget_polynomial (d v G : ℕ) : + materializedOptimizerStepBudget d v G ≤ (v + 1) * (d + 1) * (G + 2) ^ 128 := by + have hU : 1 ≤ (G + 2) ^ 120 := Nat.one_le_pow _ _ (by omega) + have hG120 : G ^ 120 ≤ (G + 2) ^ 120 := Nat.pow_le_pow_left (by omega) _ + have hG60 : G ^ 60 ≤ (G + 2) ^ 120 := + (Nat.pow_le_pow_left (show G ≤ G + 2 by omega) 60).trans + (Nat.pow_le_pow_right (by omega) (by omega)) + have hconstant : 156 ≤ (G + 2) ^ 8 := + (show 156 ≤ 2 ^ 8 by norm_num).trans (Nat.pow_le_pow_left (by omega) 8) + have hpower : (G + 2) ^ 128 = (G + 2) ^ 8 * (G + 2) ^ 120 := + pow_add (G + 2) 8 120 + calc + _ ≤ 156 * ((v + 1) * (d + 1) * (G + 2) ^ 120) := + optimizerStepArithmetic_bound d v (G ^ 120) (G ^ 60) _ hG120 hG60 hU + _ ≤ (G + 2) ^ 8 * ((v + 1) * (d + 1) * (G + 2) ^ 120) := + Nat.mul_le_mul_right _ hconstant + _ = _ := by rw [hpower]; exact move_outer_factor _ _ _ _ + +theorem materializedOptimizerWithWork_polynomial {d : ℕ} + (vertices : List (Vector ℚ d)) (linear : Vector ℚ d) (G j : ℕ) (hj : j ≤ G ^ 80) : + (materializedOptimizerWithWork vertices linear G j).2 ≤ + (vertices.length + 1) * (d + 1) * (G + 2) ^ 209 := by + let C := (vertices.length + 1) * (d + 1) * (G + 2) ^ 128 + have hbase : d + 1 ≤ C := by + have hpow : 1 ≤ (G + 2) ^ 128 := Nat.one_le_pow _ _ (by omega) + dsimp only [C] + exact (show d + 1 ≤ (vertices.length + 1) * (d + 1) by nlinarith).trans + (Nat.le_mul_of_pos_right _ hpow) + have hj1 : j + 1 ≤ (G + 2) ^ 81 := by + have hj' : j ≤ (G + 2) ^ 80 := hj.trans (Nat.pow_le_pow_left (by omega) 80) + have hpow : 1 ≤ (G + 2) ^ 80 := Nat.one_le_pow _ _ (by omega) + calc + j + 1 ≤ (G + 2) ^ 80 + (G + 2) ^ 80 := Nat.add_le_add hj' hpow + _ = (G + 2) ^ 80 * 2 := by omega + _ ≤ (G + 2) ^ 80 * (G + 2) := Nat.mul_le_mul_left _ (by omega) + _ = (G + 2) ^ 81 := (pow_succ _ _).symm + calc + _ ≤ d + 1 + j * materializedOptimizerStepBudget d vertices.length G := + materializedOptimizerWithWork_cost vertices linear G j + _ ≤ C + j * C := Nat.add_le_add hbase + (Nat.mul_le_mul_left j (materializedOptimizerStepBudget_polynomial d vertices.length G)) + _ = (j + 1) * C := by rw [Nat.add_mul, Nat.one_mul, Nat.add_comm] + _ ≤ (G + 2) ^ 81 * C := Nat.mul_le_mul_right C hj1 + _ = _ := by + dsimp only [C] + have hpower : (G + 2) ^ 209 = (G + 2) ^ 81 * (G + 2) ^ 128 := + pow_add (G + 2) 81 128 + rw [hpower] + exact move_outer_factor _ _ _ _ + +/-- The final scan retains the original action label, so equal vectors +and tied scores do not change which listed action is returned. -/ +def materializedSelectionWithWork {α : Type*} {d : ℕ} + (vertices : List (α × Vector ℚ d)) (linear : Vector ℚ d) (G j : ℕ) : Option α × ℕ := + let iterate := materializedOptimizerWithWork (vertices.map Prod.snd) linear G j + let gradient := vectorGradientWithWork G linear iterate.1 + let selected := scoredArgmaxWithWork (fun vertex => vectorDotWithWork gradient.1 vertex.2) vertices + (selected.1.map fun chosen => chosen.1.1, iterate.2 + gradient.2 + selected.2 + 1) + +theorem materializedSelectionWithWork_value {α : Type*} {d : ℕ} + (vertices : List (α × Vector ℚ d)) (linear : Vector ℚ d) (G j : ℕ) : + (materializedSelectionWithWork vertices linear G j).1 = + (vertices.argmax fun vertex => + ∑ i : Fin d, rationalSmoothedGradient G linear.get + (finiteRationalOptimizer univ ((vertices.map Prod.snd).map Vector.get) linear.get G j) i * + vertex.2.get i).map Prod.fst := by + simp only [materializedSelectionWithWork, scoredArgmaxWithWork_value, + vectorDotWithWork_spec, Option.map_map, Function.comp_def] + congr 2 + funext vertex + apply sum_congr rfl + intro i _ + rw [vectorGradientWithWork_value, materializedOptimizerWithWork_value] + +theorem materializedSelectionWithWork_cost {α : Type*} {d : ℕ} + (vertices : List (α × Vector ℚ d)) (linear : Vector ℚ d) (G j : ℕ) : + (materializedSelectionWithWork vertices linear G j).2 ≤ + (materializedOptimizerWithWork (vertices.map Prod.snd) linear G j).2 + + materializedOptimizerStepBudget d vertices.length G := by + have hscan := scoredArgmaxWithWork_cost + (fun vertex : α × Vector ℚ d => vectorDotWithWork + (vectorGradientWithWork G linear + (materializedOptimizerWithWork (vertices.map Prod.snd) linear G j).1).1 vertex.2) + vertices (8 * d) (fun vertex _ => + (congrArg Prod.snd (vectorDotWithWork_spec _ _)).le) + simp only [materializedSelectionWithWork, vectorGradientWithWork_cost] + unfold materializedOptimizerStepBudget + omega + +theorem materializedSelectionWithWork_polynomial {α : Type*} {d : ℕ} + (vertices : List (α × Vector ℚ d)) (linear : Vector ℚ d) (G j : ℕ) + (hj : j ≤ G ^ 80) : + (materializedSelectionWithWork vertices linear G j).2 ≤ + (vertices.length + 1) * (d + 1) * (G + 2) ^ 210 := by + have hiter := materializedOptimizerWithWork_polynomial (vertices.map Prod.snd) linear G j hj + simp only [List.length_map] at hiter + have hstep := materializedOptimizerStepBudget_polynomial d vertices.length G + have hexp : (G + 2) ^ 128 ≤ (G + 2) ^ 209 := + Nat.pow_le_pow_right (by omega) (by omega) + have htwice : 2 * ((vertices.length + 1) * (d + 1) * (G + 2) ^ 209) ≤ + (vertices.length + 1) * (d + 1) * (G + 2) ^ 210 := by + have hpower : (G + 2) ^ 210 = (G + 2) ^ 209 * (G + 2) := pow_succ _ _ + rw [hpower] + calc + _ ≤ (G + 2) * ((vertices.length + 1) * (d + 1) * (G + 2) ^ 209) := + Nat.mul_le_mul_right _ (by omega) + _ = _ := move_outer_factor_right _ _ _ _ + exact (materializedSelectionWithWork_cost vertices linear G j).trans + ((Nat.add_le_add hiter (hstep.trans + (Nat.mul_le_mul_left ((vertices.length + 1) * (d + 1)) hexp))).trans + (by simpa only [two_mul] using htwice)) + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Probability/AdaptiveMarginalLaw.lean b/lean/OAI/Combinatorics/EditApproximation/Probability/AdaptiveMarginalLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..df68fb0639031fae1f24a524181486399a2f3cd2 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Probability/AdaptiveMarginalLaw.lean @@ -0,0 +1,102 @@ +import OAI.Combinatorics.EditApproximation.Probability.AdaptiveSeedLaw + +namespace OAI + +/-! Adaptive passes need the correct marginal for the actual incoming +seed. Independence between unused, counterfactual seed-indexed draws is +unnecessary. This permits one common keyed random source. -/ + +namespace EditApproximation + +open MeasureTheory ProbabilityTheory + +section Marginal + +variable {Seed : Type*} [Fintype Seed] [DecidableEq Seed] + [MeasurableSpace Seed] [MeasurableSingletonClass Seed] + {Draw : Seed → Type*} [∀ seed, Fintype (Draw seed)] + [∀ seed, MeasurableSpace (Draw seed)] [∀ seed, MeasurableSingletonClass (Draw seed)] + (drawLaw : ∀ seed, Measure (Draw seed)) [∀ seed, IsProbabilityMeasure (drawLaw seed)] + {Ω : Type*} [Fintype Ω] [MeasurableSpace Ω] [MeasurableSingletonClass Ω] + (randomLaw : Measure Ω) [IsProbabilityMeasure randomLaw] + (sample : ∀ seed, Ω → Draw seed) + (hmarginal : ∀ seed, randomLaw.map (sample seed) = drawLaw seed) + +include hmarginal in +/-- The common random source can correlate draws for distinct hypothetical +incoming seeds; only its independence from the actual incoming seed matters. -/ +theorem adaptiveSeedLaw_eq_of_marginals (incoming : Measure Seed) [IsProbabilityMeasure incoming] + (next : ∀ seed, Draw seed → Seed) : + (incoming.prod randomLaw).map + (fun pair : Seed × Ω => next pair.1 (sample pair.1 pair.2)) = + adaptiveSeedLaw drawLaw incoming next := by + classical + apply Measure.ext + intro event hevent + apply (measureReal_eq_measureReal_iff).mp + rw [adaptiveSeedLaw, map_measureReal_apply (measurable_of_finite _) hevent, + map_measureReal_apply (measurable_of_finite _) hevent] + change (incoming.prod randomLaw).real + {pair : Seed × Ω | next pair.1 (sample pair.1 pair.2) ∈ event} = + (incoming.prod (Measure.pi drawLaw)).real + {pair : Seed × (∀ seed, Draw seed) | next pair.1 (pair.2 pair.1) ∈ event} + rw [← finite_integral_test (incoming.prod randomLaw) + (fun pair : Seed × Ω => next pair.1 (sample pair.1 pair.2) ∈ event), + ← finite_integral_test (incoming.prod (Measure.pi drawLaw)) + (fun pair : Seed × (∀ seed, Draw seed) => next pair.1 (pair.2 pair.1) ∈ event)] + rw [integral_prod _ (.of_finite), integral_prod _ (.of_finite)] + apply integral_congr_ae + filter_upwards [] with seed + have hmap := integral_map (μ := randomLaw) (φ := sample seed) + (measurable_of_finite _).aemeasurable + (f := fun draw => if next seed draw ∈ event then (1 : ℝ) else 0) + (measurable_of_finite _).aestronglyMeasurable + rw [hmarginal seed] at hmap + rw [← hmap] + symm + exact integral_comp_eval (μ := drawLaw) (i := seed) + (f := fun draw => if next seed draw ∈ event then (1 : ℝ) else 0) + (measurable_of_finite _).aestronglyMeasurable + +include hmarginal in +/-- The same replacement preserves the final integer answer law, rather +than only a seed transition. -/ +theorem adaptiveAnswerLaw_eq_of_marginals (incoming : Measure Seed) [IsProbabilityMeasure incoming] + (answer : ∀ seed, Draw seed → ℕ) : + (incoming.prod randomLaw).map + (fun pair : Seed × Ω => answer pair.1 (sample pair.1 pair.2)) = + (incoming.prod (Measure.pi drawLaw)).map + (fun pair : Seed × (∀ seed, Draw seed) => answer pair.1 (pair.2 pair.1)) := by + classical + apply Measure.ext + intro event hevent + apply (measureReal_eq_measureReal_iff).mp + rw [map_measureReal_apply (measurable_of_finite _) hevent, + map_measureReal_apply (measurable_of_finite _) hevent] + change (incoming.prod randomLaw).real + {pair : Seed × Ω | answer pair.1 (sample pair.1 pair.2) ∈ event} = + (incoming.prod (Measure.pi drawLaw)).real + {pair : Seed × (∀ seed, Draw seed) | answer pair.1 (pair.2 pair.1) ∈ event} + rw [← finite_integral_test (incoming.prod randomLaw) + (fun pair : Seed × Ω => answer pair.1 (sample pair.1 pair.2) ∈ event), + ← finite_integral_test (incoming.prod (Measure.pi drawLaw)) + (fun pair : Seed × (∀ seed, Draw seed) => answer pair.1 (pair.2 pair.1) ∈ event)] + rw [integral_prod _ (.of_finite), integral_prod _ (.of_finite)] + apply integral_congr_ae + filter_upwards [] with seed + have hmap := integral_map (μ := randomLaw) (φ := sample seed) + (measurable_of_finite _).aemeasurable + (f := fun draw => if answer seed draw ∈ event then (1 : ℝ) else 0) + (measurable_of_finite _).aestronglyMeasurable + rw [hmarginal seed] at hmap + rw [← hmap] + symm + exact integral_comp_eval (μ := drawLaw) (i := seed) + (f := fun draw => if answer seed draw ∈ event then (1 : ℝ) else 0) + (measurable_of_finite _).aestronglyMeasurable + +end Marginal + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Probability/AdaptiveSeedLaw.lean b/lean/OAI/Combinatorics/EditApproximation/Probability/AdaptiveSeedLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..2d0760d02a3e2571f5be6c12c1025a3fa89f4349 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Probability/AdaptiveSeedLaw.lean @@ -0,0 +1,124 @@ +import OAI.Combinatorics.EditApproximation.Probability.FiniteResampling + +namespace OAI + +/-! Fresh streams indexed by every possible incoming seed make adaptive +seed-dependent draw types compatible with a single finite product law. -/ + +namespace EditApproximation + +open MeasureTheory ProbabilityTheory + +theorem finite_integral_test {Ω : Type*} [Fintype Ω] + [MeasurableSpace Ω] [MeasurableSingletonClass Ω] + (μ : Measure Ω) (test : Ω → Prop) [DecidablePred test] : + (∫ ω, if test ω then (1 : ℝ) else 0 ∂μ) = μ.real {ω | test ω} := by + have h := integral_indicator_one (μ := μ) (Set.toFinite {ω | test ω}).measurableSet + simpa only [Set.indicator, Set.mem_ofPred_eq, Pi.one_apply] using h + +section Step + +variable {Seed : Type*} [Fintype Seed] [DecidableEq Seed] + [MeasurableSpace Seed] [MeasurableSingletonClass Seed] + {Draw : Seed → Type*} [∀ seed, Fintype (Draw seed)] + [∀ seed, MeasurableSpace (Draw seed)] [∀ seed, MeasurableSingletonClass (Draw seed)] + (drawLaw : ∀ seed, Measure (Draw seed)) [∀ seed, IsProbabilityMeasure (drawLaw seed)] + +/-- Only the coordinate belonging to the actual incoming table is consumed. +All states within that coordinate retain their shared copy streams. -/ +def adaptiveSeedStep (next : ∀ seed, Draw seed → Seed) (pair : Seed × (∀ seed, Draw seed)) : Seed := + next pair.1 (pair.2 pair.1) + +noncomputable def adaptiveSeedLaw (incoming : Measure Seed) (next : ∀ seed, Draw seed → Seed) : Measure Seed := + (incoming.prod (Measure.pi drawLaw)).map (adaptiveSeedStep next) + +instance adaptiveSeedLaw_probability (incoming : Measure Seed) [IsProbabilityMeasure incoming] + (next : ∀ seed, Draw seed → Seed) : IsProbabilityMeasure (adaptiveSeedLaw drawLaw incoming next) := by + unfold adaptiveSeedLaw + infer_instance + +theorem adaptiveSeedLaw_failure (incoming : Measure Seed) [IsProbabilityMeasure incoming] + (next : ∀ seed, Draw seed → Seed) (good nextGood : Seed → Prop) + [DecidablePred good] [DecidablePred nextGood] (q : ℝ) (hq : 0 ≤ q) + (hstep : ∀ seed, good seed → (drawLaw seed).real {draw | ¬ nextGood (next seed draw)} ≤ q) : + (adaptiveSeedLaw drawLaw incoming next).real {seed | ¬ nextGood seed} ≤ + incoming.real {seed | ¬ good seed} + q := by + classical + rw [adaptiveSeedLaw, map_measureReal_apply (measurable_of_finite _) (Set.toFinite _).measurableSet] + change (incoming.prod (Measure.pi drawLaw)).real + {pair : Seed × (∀ seed, Draw seed) | ¬ nextGood (next pair.1 (pair.2 pair.1))} ≤ _ + rw [← finite_integral_test (incoming.prod (Measure.pi drawLaw)) + (fun pair : Seed × (∀ seed, Draw seed) => ¬ nextGood (next pair.1 (pair.2 pair.1)))] + change (∫ pair : Seed × (∀ seed, Draw seed), + if ¬ nextGood (next pair.1 (pair.2 pair.1)) then (1 : ℝ) else 0 + ∂incoming.prod (Measure.pi drawLaw)) ≤ _ + rw [integral_prod _ (.of_finite)] + have hinner (seed : Seed) : + (∫ draws : ∀ seed, Draw seed, if ¬ nextGood (next seed (draws seed)) then (1 : ℝ) else 0 + ∂Measure.pi drawLaw) = (drawLaw seed).real {draw | ¬ nextGood (next seed draw)} := by + rw [integral_comp_eval (μ := drawLaw) (i := seed) + (f := fun draw => if ¬ nextGood (next seed draw) then (1 : ℝ) else 0) + (measurable_of_finite _).aestronglyMeasurable] + exact finite_integral_test _ _ + simp_rw [hinner] + have hpoint (seed : Seed) : (drawLaw seed).real {draw | ¬ nextGood (next seed draw)} ≤ + (if ¬ good seed then (1 : ℝ) else 0) + q := by + by_cases hg : good seed + · simpa only [hg, not_true_eq_false, ite_false, zero_add] using hstep seed hg + · have hprob : (drawLaw seed).real {draw | ¬ nextGood (next seed draw)} ≤ 1 := measureReal_le_one + simpa only [hg, not_false_eq_true, ite_true] using hprob.trans (le_add_of_nonneg_right hq) + have h := integral_mono (μ := incoming) (.of_finite) (.of_finite) hpoint + rw [integral_add (.of_finite) (integrable_const _), finite_integral_test, + integral_const, probReal_univ, one_smul] at h + exact h + +end Step + +section Sequence + +variable {Seed : Type*} [Fintype Seed] [DecidableEq Seed] + [MeasurableSpace Seed] [MeasurableSingletonClass Seed] + {Draw : ℕ → Seed → Type*} [∀ pass seed, Fintype (Draw pass seed)] + [∀ pass seed, MeasurableSpace (Draw pass seed)] + [∀ pass seed, MeasurableSingletonClass (Draw pass seed)] + (drawLaw : ∀ pass seed, Measure (Draw pass seed)) + [∀ pass seed, IsProbabilityMeasure (drawLaw pass seed)] + (incoming : Measure Seed) (next : ∀ pass seed, Draw pass seed → Seed) + +noncomputable def adaptiveSeedSequence : ℕ → Measure Seed + | 0 => incoming + | pass + 1 => adaptiveSeedLaw (drawLaw pass) (adaptiveSeedSequence pass) (next pass) + +instance adaptiveSeedSequence_probability [IsProbabilityMeasure incoming] (pass : ℕ) : + IsProbabilityMeasure (adaptiveSeedSequence drawLaw incoming next pass) := by + induction pass with + | zero => exact inferInstanceAs (IsProbabilityMeasure incoming) + | succ pass ih => + let := ih + exact inferInstanceAs (IsProbabilityMeasure + (adaptiveSeedLaw (drawLaw pass) (adaptiveSeedSequence drawLaw incoming next pass) (next pass))) + +theorem adaptiveSeedSequence_failure [IsProbabilityMeasure incoming] + (good : ℕ → Seed → Prop) [∀ pass, DecidablePred (good pass)] + (q : ℕ → ℝ) (hq : ∀ pass, 0 ≤ q pass) (passes : ℕ) + (hstep : ∀ pass < passes, ∀ seed, good pass seed → + (drawLaw pass seed).real {draw | ¬ good (pass + 1) (next pass seed draw)} ≤ q pass) : + (adaptiveSeedSequence drawLaw incoming next passes).real {seed | ¬ good passes seed} ≤ + incoming.real {seed | ¬ good 0 seed} + ∑ pass ∈ Finset.range passes, q pass := by + induction passes with + | zero => simp only [adaptiveSeedSequence, Finset.sum_range_zero, add_zero, le_refl] + | succ passes ih => + have hprevious := ih (fun pass hp seed hg => hstep pass (by omega) seed hg) + have hnext := adaptiveSeedLaw_failure (drawLaw passes) + (adaptiveSeedSequence drawLaw incoming next passes) (next passes) + (good passes) (good (passes + 1)) (q passes) (hq passes) + (hstep passes (by omega)) + apply hnext.trans + rw [Finset.sum_range_succ] + linarith only [hprevious] + +end Sequence + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Probability/AdaptiveSeedTrace.lean b/lean/OAI/Combinatorics/EditApproximation/Probability/AdaptiveSeedTrace.lean new file mode 100644 index 0000000000000000000000000000000000000000..2331072da8a360be1d80f5c324886071d8dc1b95 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Probability/AdaptiveSeedTrace.lean @@ -0,0 +1,97 @@ +import OAI.Combinatorics.EditApproximation.Probability.AdaptiveSeedLaw + +namespace OAI + +/-! Preserve the finite draw history of adaptive seed passes. The final +seed has exactly the existing sequential law, while the history remains +available to the lazy evaluator when it asks for an earlier pass. -/ + +namespace EditApproximation + +open MeasureTheory ProbabilityTheory + +def AdaptiveSeedTrace (Seed : Type) (Draw : ℕ → Seed → Type) : ℕ → Type + | 0 => Seed + | pass + 1 => AdaptiveSeedTrace Seed Draw pass × (∀ seed, Draw pass seed) + +instance adaptiveSeedTraceFintype (Seed : Type) (Draw : ℕ → Seed → Type) + [Fintype Seed] [DecidableEq Seed] [∀ pass seed, Fintype (Draw pass seed)] : + (pass : ℕ) → Fintype (AdaptiveSeedTrace Seed Draw pass) + | 0 => inferInstanceAs (Fintype Seed) + | pass + 1 => + letI := adaptiveSeedTraceFintype Seed Draw pass + inferInstanceAs (Fintype (AdaptiveSeedTrace Seed Draw pass × (∀ seed, Draw pass seed))) + +instance adaptiveSeedTraceMeasurable (Seed : Type) (Draw : ℕ → Seed → Type) + [MeasurableSpace Seed] [∀ pass seed, MeasurableSpace (Draw pass seed)] : + (pass : ℕ) → MeasurableSpace (AdaptiveSeedTrace Seed Draw pass) + | 0 => inferInstanceAs (MeasurableSpace Seed) + | pass + 1 => + letI := adaptiveSeedTraceMeasurable Seed Draw pass + inferInstanceAs (MeasurableSpace (AdaptiveSeedTrace Seed Draw pass × (∀ seed, Draw pass seed))) + +instance adaptiveSeedTraceSingleton (Seed : Type) (Draw : ℕ → Seed → Type) + [MeasurableSpace Seed] [MeasurableSingletonClass Seed] + [∀ pass seed, MeasurableSpace (Draw pass seed)] [∀ pass seed, MeasurableSingletonClass (Draw pass seed)] + [Fintype Seed] : (pass : ℕ) → MeasurableSingletonClass (AdaptiveSeedTrace Seed Draw pass) + | 0 => inferInstanceAs (MeasurableSingletonClass Seed) + | pass + 1 => + letI := adaptiveSeedTraceSingleton Seed Draw pass + inferInstanceAs (MeasurableSingletonClass (AdaptiveSeedTrace Seed Draw pass × (∀ seed, Draw pass seed))) + +section Trace + +variable {Seed : Type} [Fintype Seed] [DecidableEq Seed] + [MeasurableSpace Seed] [MeasurableSingletonClass Seed] + {Draw : ℕ → Seed → Type} [∀ pass seed, Fintype (Draw pass seed)] + [∀ pass seed, MeasurableSpace (Draw pass seed)] + [∀ pass seed, MeasurableSingletonClass (Draw pass seed)] + (drawLaw : ∀ pass seed, Measure (Draw pass seed)) + [∀ pass seed, IsProbabilityMeasure (drawLaw pass seed)] + (incoming : Measure Seed) [IsProbabilityMeasure incoming] + (next : ∀ pass seed, Draw pass seed → Seed) + +def adaptiveTraceValue : (pass : ℕ) → AdaptiveSeedTrace Seed Draw pass → Seed + | 0, seed => seed + | pass + 1, trace => + let seed := adaptiveTraceValue pass trace.1 + next pass seed (trace.2 seed) + +noncomputable def adaptiveTraceLaw : (pass : ℕ) → Measure (AdaptiveSeedTrace Seed Draw pass) + | 0 => incoming + | pass + 1 => (adaptiveTraceLaw pass).prod (Measure.pi (drawLaw pass)) + +instance adaptiveTraceLaw_probability (pass : ℕ) : + IsProbabilityMeasure (adaptiveTraceLaw drawLaw incoming pass) := by + induction pass with + | zero => exact inferInstanceAs (IsProbabilityMeasure incoming) + | succ pass ih => + have := ih + exact inferInstanceAs (IsProbabilityMeasure + ((adaptiveTraceLaw drawLaw incoming pass).prod (Measure.pi (drawLaw pass)))) + +omit [∀ pass seed, IsProbabilityMeasure (drawLaw pass seed)] [IsProbabilityMeasure incoming] in +theorem adaptiveTraceLaw_map (pass : ℕ) : + (adaptiveTraceLaw drawLaw incoming pass).map (adaptiveTraceValue next pass) = + adaptiveSeedSequence drawLaw incoming next pass := by + induction pass with + | zero => exact Measure.map_id + | succ pass ih => + let reindex : AdaptiveSeedTrace Seed Draw pass × (∀ seed, Draw pass seed) → + Seed × (∀ seed, Draw pass seed) := Prod.map (adaptiveTraceValue next pass) id + have hvalue : adaptiveTraceValue next (pass + 1) = adaptiveSeedStep (next pass) ∘ reindex := rfl + have hproduct : ((adaptiveTraceLaw drawLaw incoming pass).prod (Measure.pi (drawLaw pass))).map reindex = + ((adaptiveTraceLaw drawLaw incoming pass).map (adaptiveTraceValue next pass)).prod + (Measure.pi (drawLaw pass)) := by + simpa only [Measure.map_id] using + (Measure.map_prod_map (adaptiveTraceLaw drawLaw incoming pass) (Measure.pi (drawLaw pass)) + (measurable_of_finite (adaptiveTraceValue next pass)) measurable_id).symm + change ((adaptiveTraceLaw drawLaw incoming pass).prod (Measure.pi (drawLaw pass))).map _ = _ + rw [hvalue, ← Measure.map_map (measurable_of_finite _) (measurable_of_finite _), hproduct, ih] + rfl + +end Trace + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Probability/Amplification.lean b/lean/OAI/Combinatorics/EditApproximation/Probability/Amplification.lean new file mode 100644 index 0000000000000000000000000000000000000000..71f99fe94919de0f63dd73b0e2fa4356093a864c --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Probability/Amplification.lean @@ -0,0 +1,67 @@ +import Mathlib + +namespace OAI + +/-! +# Independent-copy amplification for the seed passes + +The tail estimate is the direct finite-subset argument from Section 8. +Independence is used only between copies at a fixed state. The subsequent +union bound over states makes no independence assumption between states. +-/ + +namespace EditApproximation + +open Finset MeasureTheory ProbabilityTheory +open scoped Classical + +theorem independent_failure_subset_bound {Ω ι : Type*} [MeasurableSpace Ω] + (μ : Measure Ω) [IsProbabilityMeasure μ] (bad : ι → Set Ω) + (hindep : iIndepSet bad μ) (copies : Finset ι) (q : ℝ) + (hbad : ∀ i ∈ copies, μ.real (bad i) ≤ q) : + μ.real (⋂ i ∈ copies, bad i) ≤ q ^ copies.card := by + rw [measureReal_def, hindep.meas_biInter, ENNReal.toReal_prod] + have hprod := Finset.prod_le_prod₀ (fun i _ => measureReal_nonneg) hbad + simpa only [prod_const, measureReal_def] using hprod + +theorem independent_failure_count_bound {Ω ι : Type*} [MeasurableSpace Ω] + [Fintype ι] [DecidableEq ι] + (μ : Measure Ω) [IsProbabilityMeasure μ] (bad : ι → Set Ω) + (hindep : iIndepSet bad μ) (k : ℕ) (q : ℝ) + (hbad : ∀ i, μ.real (bad i) ≤ q) : + μ.real {ω | k ≤ (univ.filter fun i => ω ∈ bad i).card} ≤ + (Fintype.card ι).choose k * q ^ k := by + classical + let subsets := (univ : Finset ι).powersetCard k + have hcover : {ω | k ≤ (univ.filter fun i => ω ∈ bad i).card} ⊆ + ⋃ s ∈ subsets, ⋂ i ∈ s, bad i := by + intro ω hω + obtain ⟨s, hsub, hcard⟩ := exists_subset_card_eq hω + have hs : s ∈ subsets := mem_powersetCard.mpr + ⟨fun i hi => mem_univ i, hcard⟩ + apply Set.mem_iUnion.mpr + refine ⟨s, Set.mem_iUnion.mpr ⟨hs, ?_⟩⟩ + exact Set.mem_iInter.mpr fun i => Set.mem_iInter.mpr fun hi => (mem_filter.mp (hsub hi)).2 + apply (measureReal_mono (μ := μ) hcover (measure_ne_top μ _)).trans + apply (measureReal_biUnion_finset_le subsets _).trans + have hbound (s : Finset ι) (hs : s ∈ subsets) : + μ.real (⋂ i ∈ s, bad i) ≤ q ^ k := by + have hcard := (mem_powersetCard.mp hs).2 + simpa only [hcard] using independent_failure_subset_bound μ bad hindep s q (fun i _ => hbad i) + have hsum := sum_le_sum hbound + simpa only [sum_const, nsmul_eq_mul, subsets, card_powersetCard, card_univ] using hsum + +theorem independent_failure_count_binary_bound {Ω ι : Type*} [MeasurableSpace Ω] + [Fintype ι] [DecidableEq ι] + (μ : Measure Ω) [IsProbabilityMeasure μ] (bad : ι → Set Ω) + (hindep : iIndepSet bad μ) (k : ℕ) (q : ℝ) (hq : 0 ≤ q) + (hbad : ∀ i, μ.real (bad i) ≤ q) : + μ.real {ω | k ≤ (univ.filter fun i => ω ∈ bad i).card} ≤ + (2 : ℝ) ^ Fintype.card ι * q ^ k := by + apply (independent_failure_count_bound μ bad hindep k q hbad).trans + apply mul_le_mul_of_nonneg_right _ (pow_nonneg hq k) + exact_mod_cast Nat.choose_le_two_pow (Fintype.card ι) k + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Probability/BernsteinEnvelope.lean b/lean/OAI/Combinatorics/EditApproximation/Probability/BernsteinEnvelope.lean new file mode 100644 index 0000000000000000000000000000000000000000..f54c5cdb6e37d4a32c9bf3cfebfd6358ba7ac771 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Probability/BernsteinEnvelope.lean @@ -0,0 +1,68 @@ +import OAI.Combinatorics.EditApproximation.Geometry.PublishedInputs + +namespace OAI + +/-! The scalar exponential estimate used to discharge the finite Bernstein +input. Its rational majorant is proved by a derivative comparison, avoiding +any assumption of a concentration theorem. -/ + +namespace EditApproximation + +noncomputable def bernsteinEnvelope (x : ℝ) : ℝ := + Real.exp (-x) * ((x ^ 2 + 4 * x + 6) / (6 - 2 * x)) + +private theorem bernsteinEnvelope_deriv (x : ℝ) (hx : x < 3) : + HasDerivAt bernsteinEnvelope (Real.exp (-x) * (2 * x ^ 3 / (6 - 2 * x) ^ 2)) x := by + have hd : (6 : ℝ) - 2 * x ≠ 0 := by linarith + have hn := (((hasDerivAt_pow 2 x).add ((hasDerivAt_id x).const_mul 4)).add_const 6) + have hb := (hasDerivAt_const x (6 : ℝ)).sub ((hasDerivAt_id x).const_mul 2) + have h := ((hasDerivAt_id x).neg.exp).mul (hn.div hb hd) + dsimp only [Pi.mul_apply, Pi.div_apply, Pi.add_apply, Pi.sub_apply, Pi.neg_apply, id_eq] at h + unfold bernsteinEnvelope + convert h using 1 + field_simp [hd] + ring + +private theorem bernsteinEnvelope_zero : bernsteinEnvelope 0 = 1 := by + norm_num [bernsteinEnvelope] + +theorem bernsteinEnvelope_one_le (x : ℝ) (hx : x < 3) : 1 ≤ bernsteinEnvelope x := by + by_cases hpos : 0 ≤ x + · have hc : ContinuousOn bernsteinEnvelope (Set.Icc 0 x) := by + intro y hy + exact (bernsteinEnvelope_deriv y (hy.2.trans_lt hx)).continuousAt.continuousWithinAt + have hm := monotoneOn_of_hasDerivWithinAt_nonneg (convex_Icc 0 x) hc + (fun y hy => (bernsteinEnvelope_deriv y ((interior_subset hy).2.trans_lt hx)).hasDerivWithinAt) + (fun y hy => mul_nonneg (Real.exp_nonneg _) (div_nonneg + (mul_nonneg (by norm_num) (pow_nonneg (interior_subset hy).1 3)) (sq_nonneg _))) + simpa only [bernsteinEnvelope_zero] using hm ⟨le_rfl, hpos⟩ ⟨hpos, le_rfl⟩ hpos + · have hneg : x ≤ 0 := le_of_not_ge hpos + have hc : ContinuousOn bernsteinEnvelope (Set.Icc x 0) := by + intro y hy + exact (bernsteinEnvelope_deriv y (by linarith [hy.2])).continuousAt.continuousWithinAt + have hm := antitoneOn_of_hasDerivWithinAt_nonpos (convex_Icc x 0) hc + (fun y hy => (bernsteinEnvelope_deriv y (by linarith [(interior_subset hy).2])).hasDerivWithinAt) + (fun y hy => mul_nonpos_of_nonneg_of_nonpos (Real.exp_nonneg _) (div_nonpos_of_nonpos_of_nonneg + (mul_nonpos_of_nonneg_of_nonpos (by norm_num) (show y ^ 3 ≤ 0 by + have h := mul_nonpos_of_nonneg_of_nonpos (sq_nonneg y) (interior_subset hy).2 + nlinarith only [h])) + (sq_nonneg _))) + simpa only [bernsteinEnvelope_zero] using hm ⟨le_rfl, hneg⟩ ⟨hneg, le_rfl⟩ hneg + +/-- Exact Bernstein exponential majorant, valid for all `x < 3`. -/ +theorem exp_le_bernstein_envelope (x : ℝ) (hx : x < 3) : + Real.exp x ≤ 1 + x + x ^ 2 / (2 * (1 - x / 3)) := by + have h := mul_le_mul_of_nonneg_left (bernsteinEnvelope_one_le x hx) (Real.exp_nonneg x) + have hd : (6 : ℝ) - 2 * x ≠ 0 := by linarith + have he : (2 : ℝ) * (1 - x / 3) ≠ 0 := by linarith + have hc : (x ^ 2 + 4 * x + 6) / (6 - 2 * x) = 1 + x + x ^ 2 / (2 * (1 - x / 3)) := by + have h3 : (3 : ℝ) - x ≠ 0 := by linarith + field_simp [hd, he, h3] + field_simp [show (6 : ℝ) - x * 2 ≠ 0 by linarith] + ring + simpa only [bernsteinEnvelope, mul_one, ← mul_assoc, ← Real.exp_add, add_neg_cancel, + Real.exp_zero, one_mul, hc] using h + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Probability/BernsteinFinite.lean b/lean/OAI/Combinatorics/EditApproximation/Probability/BernsteinFinite.lean new file mode 100644 index 0000000000000000000000000000000000000000..cbadee57d5d156c02164c11a978d887d035cd8de --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Probability/BernsteinFinite.lean @@ -0,0 +1,88 @@ +import OAI.Combinatorics.EditApproximation.Probability.BernsteinMGF + +namespace OAI + +/-! Finite scalar Bernstein concentration for independent +centered bounded real sums with a summed second-moment upper bound. -/ + +namespace EditApproximation +open MeasureTheory ProbabilityTheory +open scoped BigOperators + +private theorem bernstein_chernoff_exponent (b v d : ℝ) (hb : 0 < b) + (hv : 0 < v) (hd : 0 < d) : + let t := d / (v + b * d / 3); + -t * d + t ^ 2 * v / (2 * (1 - t * b / 3)) = + -d ^ 2 / (2 * v + (2 / 3 : ℝ) * b * d) := by + let D := v + b * d / 3 + have hD : D ≠ 0 := ne_of_gt (by dsimp only [D]; positivity) + have hunit : 1 - (d / D) * b / 3 = v / D := by + field_simp [hD] + dsimp only [D] + ring + change -(d / D) * d + (d / D) ^ 2 * v / (2 * (1 - (d / D) * b / 3)) = _ + rw [hunit] + have hfinal : 2 * v + (2 / 3 : ℝ) * b * d = 2 * D := by dsimp only [D]; ring + rw [hfinal] + field_simp [hD, hv.ne'] + ring + +theorem finite_bernstein_upper {Ω : Type*} [MeasurableSpace Ω] + (μ : Measure Ω) [IsProbabilityMeasure μ] + {n : ℕ} (X : Fin n → Ω → ℝ) (b v d : ℝ) + (hb : 0 < b) (hv : 0 < v) (hd : 0 < d) + (hind : iIndepFun X μ) (hm : ∀ i, Measurable (X i)) + (hi : ∀ i, Integrable (X i) μ) (hmean : ∀ i, (∫ ω, X i ω ∂μ) = 0) + (hbound : ∀ i, ∀ᵐ ω ∂μ, |X i ω| ≤ b) + (hvar : (∑ i, ∫ ω, (X i ω) ^ 2 ∂μ) ≤ v) : + μ.real {ω | d ≤ ∑ i, X i ω} ≤ + Real.exp (-d ^ 2 / (2 * v + (2 / 3 : ℝ) * b * d)) := by + let t := d / (v + b * d / 3) + have hden : 0 < v + b * d / 3 := by positivity + have ht : 0 ≤ t := (div_pos hd hden).le + have htb : t * b < 3 := by + dsimp only [t] + rw [div_mul_eq_mul_div, div_lt_iff₀ hden] + nlinarith only [hv] + have heach (i : Fin n) : Integrable (fun ω => Real.exp (t * X i ω)) μ := + integrable_exp_mul_of_le t b ht (hm i).aemeasurable + ((hbound i).mono fun ω hω => (le_abs_self _).trans hω) + have hsum : (∑ i, X i) = fun ω => ∑ i, X i ω := by + ext ω + simp only [Finset.sum_apply] + have hsumint := hind.integrable_exp_mul_sum hm (s := Finset.univ) (fun i _ => heach i) + rw [hsum] at hsumint + have htail := measure_ge_le_exp_mul_mgf (μ := μ) (X := fun ω => ∑ i, X i ω) d ht hsumint + have hmgf := bounded_centered_sum_mgf μ X b v t hb ht htb hind hm hi hmean hbound hvar + calc + _ ≤ Real.exp (-t * d) * mgf (fun ω => ∑ i, X i ω) μ t := htail + _ ≤ Real.exp (-t * d) * Real.exp (t ^ 2 * v / (2 * (1 - t * b / 3))) := + mul_le_mul_of_nonneg_left hmgf (Real.exp_nonneg _) + _ = _ := by + rw [← Real.exp_add] + congr 1 + exact bernstein_chernoff_exponent b v d hb hv hd + +/-- Two-sided Bernstein concentration for independent centered bounded sums. -/ +theorem finiteBernsteinInput {Ω : Type*} [MeasurableSpace Ω] + (μ : Measure Ω) [IsProbabilityMeasure μ] : FiniteBernsteinInput μ := by + intro n X b v d hb hv hd hind hm hi hmean hbound hvar + have hplus := finite_bernstein_upper μ X b v d hb hv hd hind hm hi hmean hbound hvar + have hnegind : iIndepFun (fun i ω => -X i ω) μ := + hind.comp (fun _ x => -x) (fun _ => measurable_neg) + have hnegmean (i) : (∫ ω, -X i ω ∂μ) = 0 := by rw [integral_neg, hmean, neg_zero] + have hnegvar : (∑ i, ∫ ω, (-X i ω) ^ 2 ∂μ) ≤ v := by simpa only [neg_sq] using hvar + have hminus := finite_bernstein_upper μ (fun i ω => -X i ω) b v d hb hv hd hnegind + (fun i => (hm i).neg) (fun i => (hi i).neg) hnegmean + (fun i => (hbound i).mono fun ω hω => by simpa only [abs_neg] using hω) hnegvar + have hevent : {ω | d ≤ |∑ i, X i ω|} = + {ω | d ≤ ∑ i, X i ω} ∪ {ω | d ≤ ∑ i, -X i ω} := by + ext ω + simp only [Set.mem_ofPred_eq, Set.mem_union, Finset.sum_neg_distrib] + rw [le_abs] + rw [hevent] + exact (measureReal_union_le _ _).trans (by linarith only [hplus, hminus]) + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Probability/BernsteinMGF.lean b/lean/OAI/Combinatorics/EditApproximation/Probability/BernsteinMGF.lean new file mode 100644 index 0000000000000000000000000000000000000000..c397b80f32aa6b19cd481cc3ce078578262424da --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Probability/BernsteinMGF.lean @@ -0,0 +1,81 @@ +import OAI.Combinatorics.EditApproximation.Probability.BernsteinEnvelope + +namespace OAI + +namespace EditApproximation +open MeasureTheory ProbabilityTheory +open scoped BigOperators + +section MGF +variable {Ω : Type*} [MeasurableSpace Ω] (μ : Measure Ω) [IsProbabilityMeasure μ] + +theorem bounded_square_integrable (X : Ω → ℝ) (b : ℝ) (hb : 0 ≤ b) + (hm : Measurable X) (hbound : ∀ᵐ ω ∂μ, |X ω| ≤ b) : + Integrable (fun ω => (X ω) ^ 2) μ := by + apply Integrable.of_mem_Icc 0 (b ^ 2) (hm.pow_const 2).aemeasurable + filter_upwards [hbound] with ω hω + refine ⟨sq_nonneg _, ?_⟩ + have h := mul_le_mul hω hω (abs_nonneg _) hb + simpa only [← pow_two, sq_abs] using h + +theorem bounded_centered_mgf (X : Ω → ℝ) (b t : ℝ) (hb : 0 < b) (ht : 0 ≤ t) + (htb : t * b < 3) (hm : Measurable X) (hi : Integrable X μ) + (hmean : (∫ ω, X ω ∂μ) = 0) (hbound : ∀ᵐ ω ∂μ, |X ω| ≤ b) : + mgf X μ t ≤ Real.exp ((t ^ 2 / (2 * (1 - t * b / 3))) * ∫ ω, (X ω) ^ 2 ∂μ) := by + let c := t ^ 2 / (2 * (1 - t * b / 3)) + have hd : 0 < 2 * (1 - t * b / 3) := by linarith + have hi2 := bounded_square_integrable μ X b hb.le hm hbound + have hexp := integrable_exp_mul_of_le t b ht hm.aemeasurable + (hbound.mono fun ω hω => (le_abs_self _).trans hω) + have hpoint : ∀ᵐ ω ∂μ, Real.exp (t * X ω) ≤ 1 + t * X ω + c * (X ω) ^ 2 := by + filter_upwards [hbound] with ω hω + have hu : t * X ω ≤ t * b := mul_le_mul_of_nonneg_left ((le_abs_self _).trans hω) ht + have hx := exp_le_bernstein_envelope (t * X ω) (hu.trans_lt htb) + have hdiv : (t * X ω) ^ 2 / (2 * (1 - t * X ω / 3)) ≤ + (t * X ω) ^ 2 / (2 * (1 - t * b / 3)) := by + apply div_le_div_of_nonneg_left (sq_nonneg _) hd + linarith + calc + _ ≤ 1 + t * X ω + (t * X ω) ^ 2 / (2 * (1 - t * X ω / 3)) := hx + _ ≤ 1 + t * X ω + (t * X ω) ^ 2 / (2 * (1 - t * b / 3)) := add_le_add le_rfl hdiv + _ = _ := by dsimp only [c]; ring + have h1 : Integrable (fun _ : Ω => (1 : ℝ)) μ := integrable_const 1 + have hit := hi.const_mul t + have hic := hi2.const_mul c + have hineq := integral_mono_ae hexp ((h1.add hit).add hic) hpoint + simp only [Pi.add_apply] at hineq + have hadd := integral_add (h1.add hit) hic + have hadd' := integral_add h1 hit + simp only [Pi.add_apply] at hadd hadd' + rw [hadd, hadd', integral_const_mul, integral_const_mul, hmean] at hineq + simp only [integral_const, probReal_univ, smul_eq_mul, one_mul, mul_zero, add_zero] at hineq + exact hineq.trans (by simpa only [add_comm] using Real.add_one_le_exp (c * ∫ ω, (X ω) ^ 2 ∂μ)) + +theorem bounded_centered_sum_mgf {n : ℕ} (X : Fin n → Ω → ℝ) + (b v t : ℝ) (hb : 0 < b) (ht : 0 ≤ t) (htb : t * b < 3) + (hind : iIndepFun X μ) (hm : ∀ i, Measurable (X i)) + (hi : ∀ i, Integrable (X i) μ) (hmean : ∀ i, (∫ ω, X i ω ∂μ) = 0) + (hbound : ∀ i, ∀ᵐ ω ∂μ, |X i ω| ≤ b) + (hvar : (∑ i, ∫ ω, (X i ω) ^ 2 ∂μ) ≤ v) : + mgf (fun ω => ∑ i, X i ω) μ t ≤ Real.exp (t ^ 2 * v / (2 * (1 - t * b / 3))) := by + have hmgf := hind.mgf_sum hm Finset.univ (t := t) + have hsum : (∑ i, X i) = fun ω => ∑ i, X i ω := by + ext ω + simp only [Finset.sum_apply] + rw [hsum] at hmgf + rw [hmgf] + let c := t ^ 2 / (2 * (1 - t * b / 3)) + have hc : 0 ≤ c := div_nonneg (sq_nonneg _) (by linarith) + calc + _ ≤ ∏ i, Real.exp (c * ∫ ω, (X i ω) ^ 2 ∂μ) := + Finset.prod_le_prod₀ (fun i _ => mgf_nonneg) (fun i _ => + bounded_centered_mgf μ (X i) b t hb ht htb (hm i) (hi i) (hmean i) (hbound i)) + _ = Real.exp (c * ∑ i, ∫ ω, (X i ω) ^ 2 ∂μ) := by + rw [Finset.mul_sum, Real.exp_sum] + _ ≤ Real.exp (c * v) := Real.exp_le_exp.mpr (mul_le_mul_of_nonneg_left hvar hc) + _ = _ := by congr 1; dsimp only [c]; ring + +end MGF +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Probability/Concentration.lean b/lean/OAI/Combinatorics/EditApproximation/Probability/Concentration.lean new file mode 100644 index 0000000000000000000000000000000000000000..fb05edba5161649b3db0a331c099604ea97e84d9 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Probability/Concentration.lean @@ -0,0 +1,96 @@ +import OAI.Combinatorics.EditApproximation.Geometry.PublishedInputs + +namespace OAI + +/-! +# Coarse threshold concentration from the published scalar input + +The quantitative Bernstein bound used in Section 3 does not require +independence of estimated child values. +The random variables to which Bernstein is applied are fixed true-cost +threshold contributions, conditional on ancestor thresholds. +-/ + +namespace EditApproximation + +open MeasureTheory ProbabilityTheory +open scoped BigOperators + +/-- Numerical exponent estimate for the coarse estimator's choice of +deviation. The proof also covers the two regimes in the manuscript at once. -/ +theorem coarse_bernstein_exponent {lam V allowance scale Q : ℝ} + (hlam : 0 ≤ lam) (hlamone : lam ≤ 1) (hV : 0 ≤ V) + (ha : 0 < allowance) (hu : 0 < scale) (hQ : Q * scale = allowance) : + lam * Q / 12 ≤ (lam * V + allowance / 2) ^ 2 / + (2 * scale * V + (2 / 3 : ℝ) * scale * (lam * V + allowance / 2)) := by + let z := lam * V + allowance / 2 + have hz : 0 < z := by dsimp [z]; positivity + have ha2 : allowance ≤ 2 * z := by dsimp [z]; nlinarith + have hlamV : lam * V ≤ z := by dsimp [z]; linarith + have hfirst : allowance * (lam * V) ≤ allowance * z := + mul_le_mul_of_nonneg_left hlamV ha.le + have hsecond : lam * (allowance * z) ≤ allowance * z := by + exact (mul_le_mul_of_nonneg_right hlamone (mul_nonneg ha.le hz.le)).trans_eq + (one_mul _) + have hthird : allowance * z ≤ 2 * z ^ 2 := by nlinarith + have hbase : lam * allowance * (2 * V + (2 / 3 : ℝ) * z) ≤ 12 * z ^ 2 := by + nlinarith [sq_nonneg z] + have hdenom : 0 < 2 * scale * V + (2 / 3 : ℝ) * scale * z := by positivity + apply (le_div_iff₀ hdenom).2 + change lam * Q / 12 * (2 * scale * V + (2 / 3 : ℝ) * scale * z) ≤ z ^ 2 + have heq : lam * Q / 12 * (2 * scale * V + (2 / 3 : ℝ) * scale * z) = + lam * allowance * (2 * V + (2 / 3 : ℝ) * z) / 12 := by + rw [← hQ] + ring + rw [heq] + linarith + +/-- Coarse threshold concentration, conditional only on the ancestor +data. Its hypotheses specify the centered *true-cost* random variables, +their moment proxy, and the threshold estimator's small bias. -/ +theorem coarse_threshold_concentration {Ω : Type*} [MeasurableSpace Ω] + (μ : Measure Ω) [IsProbabilityMeasure μ] + (bernstein : FiniteBernsteinInput μ) + {n : ℕ} (X : Fin n → Ω → ℝ) (estimator : Ω → ℝ) + (mean V lam allowance scale Q : ℝ) + (hlam : 0 ≤ lam) (hlamone : lam ≤ 1) (hV : 0 < V) + (ha : 0 < allowance) (hu : 0 < scale) (hQ : Q * scale = allowance) + (hscale : scale ≤ allowance / 2) + (hindep : iIndepFun X μ) (hmeas : ∀ i, Measurable (X i)) + (hint : ∀ i, Integrable (X i) μ) + (hmean : ∀ i, (∫ ω, X i ω ∂μ) = 0) + (hbound : ∀ i, ∀ᵐ ω ∂μ, |X i ω| ≤ scale) + (hvariance : (∑ i, ∫ ω, (X i ω) ^ 2 ∂μ) ≤ scale * V) + (hcenter : ∀ ω, estimator ω - mean = ∑ i, X i ω) + (hbias : |mean - V| ≤ scale) : + μ.real {ω | lam * V + allowance < |estimator ω - V|} ≤ + 2 * Real.exp (-lam * Q / 12) := by + let z := lam * V + allowance / 2 + have hz : 0 < z := by dsimp [z]; positivity + have htail := bernstein n X scale (scale * V) z hu (mul_pos hu hV) hz + hindep hmeas hint hmean hbound hvariance + have hsubset : {ω | lam * V + allowance < |estimator ω - V|} ⊆ + {ω | z ≤ |∑ i, X i ω|} := by + intro ω hω + have htriangle : |estimator ω - V| ≤ |estimator ω - mean| + |mean - V| := by + calc + |estimator ω - V| = |(estimator ω - mean) + (mean - V)| := by + congr 1 + ring + _ ≤ |estimator ω - mean| + |mean - V| := abs_add_le _ _ + rw [hcenter ω] at htriangle + change z ≤ |∑ i, X i ω| + dsimp [z] + have hω' : lam * V + allowance < |estimator ω - V| := hω + linarith + apply (measureReal_mono (μ := μ) hsubset).trans + apply htail.trans + apply mul_le_mul_of_nonneg_left _ (by norm_num) + apply Real.exp_le_exp.mpr + have hexponent := coarse_bernstein_exponent hlam hlamone hV.le ha hu hQ + change -z ^ 2 / (2 * (scale * V) + (2 / 3 : ℝ) * scale * z) ≤ -lam * Q / 12 + simpa only [neg_div, neg_mul, mul_assoc] using neg_le_neg hexponent + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Probability/Exact.lean b/lean/OAI/Combinatorics/EditApproximation/Probability/Exact.lean new file mode 100644 index 0000000000000000000000000000000000000000..584fce3a428e703710102909b87bbda6a50c5055 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Probability/Exact.lean @@ -0,0 +1,88 @@ +import OAI.Combinatorics.EditApproximation.Geometry.AlignmentSplitting +import OAI.Combinatorics.EditApproximation.Geometry.Leaves + +namespace OAI + +/-! +# An executable exact cut recurrence + +This is the exact source-cut dynamic programming recurrence on ordinary +lists and natural numbers. The proof identifies its value with unrestricted +unit-cost edit distance. Storage and evaluation costs are separate from +this value-level recurrence. +-/ + +namespace EditApproximation + +open EditDistortion + +def finiteNatMinimum (fallback : ℕ) : List ℕ → ℕ + | [] => fallback + | value :: rest => min value (finiteNatMinimum fallback rest) + +theorem le_finiteNatMinimum_iff (lower fallback : ℕ) (values : List ℕ) : + lower ≤ finiteNatMinimum fallback values ↔ + lower ≤ fallback ∧ ∀ value ∈ values, lower ≤ value := by + induction values with + | nil => simp [finiteNatMinimum] + | cons value rest ih => + simp only [finiteNatMinimum, le_min_iff, ih, List.mem_cons, forall_eq_or_imp] + tauto + +theorem finiteNatMinimum_le_member (fallback : ℕ) (values : List ℕ) + {value : ℕ} (hvalue : value ∈ values) : finiteNatMinimum fallback values ≤ value := by + induction values with + | nil => simp at hvalue + | cons first rest ih => + rcases List.mem_cons.mp hvalue with rfl | hvalue + · exact min_le_left _ _ + · exact (min_le_right _ _).trans (ih hvalue) + +def exactCutCost {α : Type*} [DecidableEq α] : List α → List α → ℕ + | [], target => target.length + | a :: rest, target => finiteNatMinimum (rest.length + 1 + target.length) + ((List.range (target.length + 1)).map fun cut => + singletonCost a (target.take cut) + exactCutCost rest (target.drop cut)) + +theorem edit_nil_left {α : Type*} (target : List α) : edit [] target = target.length := by + have hlo := (cost_length_bounds (s := true) ([] : List α) target).2 + have hup := cost_le (Script.to_nil (s := true) target).symm + change edit [] target ≤ target.length at hup + change target.length ≤ 0 + edit [] target at hlo + omega + +theorem exactCutCost_eq_edit {α : Type*} [DecidableEq α] (source target : List α) : + exactCutCost source target = edit source target := by + induction source generalizing target with + | nil => exact (edit_nil_left target).symm + | cons a rest ih => + have hcandidate (cut : ℕ) : edit (a :: rest) target ≤ + singletonCost a (target.take cut) + exactCutCost rest (target.drop cut) := by + rw [singletonCost_eq_edit, ih] + have happend := cost_append_le (s := true) [a] (target.take cut) rest (target.drop cut) + simpa only [List.singleton_append, List.take_append_drop, cost, edit] using happend + apply Nat.le_antisymm + · obtain ⟨tl, tr, ht, hc⟩ := edit_append_split [a] rest target + let cut := tl.length + have hcut : cut < target.length + 1 := by simp only [ht, List.length_append]; omega + have htake : target.take cut = tl := by simp [ht, cut] + have hdrop : target.drop cut = tr := by simp [ht, cut] + have hmin := finiteNatMinimum_le_member (rest.length + 1 + target.length) + ((List.range (target.length + 1)).map fun j => + singletonCost a (target.take j) + exactCutCost rest (target.drop j)) + (List.mem_map.mpr ⟨cut, List.mem_range.mpr hcut, rfl⟩) + change exactCutCost (a :: rest) target ≤ + singletonCost a (target.take cut) + exactCutCost rest (target.drop cut) at hmin + rw [htake, hdrop, singletonCost_eq_edit, ih] at hmin + simpa only [List.singleton_append] using hmin.trans_eq hc.symm + · apply (le_finiteNatMinimum_iff _ _ _).2 + constructor + · have hup := edit_le_total_length (a :: rest) target + simpa only [List.length_cons, Nat.add_assoc] using hup + · intro value hvalue + obtain ⟨cut, _, rfl⟩ := List.mem_map.mp hvalue + exact hcandidate cut + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Probability/ExactSampling.lean b/lean/OAI/Combinatorics/EditApproximation/Probability/ExactSampling.lean new file mode 100644 index 0000000000000000000000000000000000000000..7ad43a263ddab7bb0d74bea5b7934268caebeacc --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Probability/ExactSampling.lean @@ -0,0 +1,485 @@ +import OAI.Combinatorics.EditApproximation.Numerics.Numerics +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! +# Exact fair-bit sampling of the optimizer mixture + +The finite-word rejection calculation follows Section 9. +The random trial is encoded from actual Boolean bits. First-success trace +probabilities determine the output law and expected number of trials. +-/ + +namespace EditApproximation + +open Finset + +/-- Little-endian encoding of a finite Boolean word. -/ +def binaryWord : (B : ℕ) → (Fin B → Bool) → Fin (2 ^ B) + | 0, _ => ⟨0, by norm_num⟩ + | B + 1, bits => + ⟨(if bits 0 then 1 else 0) + 2 * (binaryWord B (fun i => bits i.succ)).val, by + have hword := (binaryWord B (fun i => bits i.succ)).isLt + rw [pow_succ] + split_ifs <;> omega⟩ + +theorem binaryWord_injective (B : ℕ) : Function.Injective (binaryWord B) := by + induction B with + | zero => intro bits other _; funext i; exact Fin.elim0 i + | succ B ih => + intro bits other heq + have hvalue := congrArg Fin.val heq + dsimp only [binaryWord] at hvalue + have hhead : bits 0 = other 0 := by + cases hb : bits 0 <;> cases ho : other 0 <;> simp only [hb, ho, Bool.false_eq_true, + ↓reduceIte] at hvalue ⊢ <;> omega + have htail : binaryWord B (fun i => bits i.succ) = binaryWord B (fun i => other i.succ) := by + apply Fin.ext + rw [hhead] at hvalue + omega + have htailEq := ih htail + funext i + exact Fin.cases hhead (fun j => congr_fun htailEq j) i + +theorem binaryWord_bijective (B : ℕ) : Function.Bijective (binaryWord B) := by + apply (Fintype.bijective_iff_injective_and_card _).mpr + exact ⟨binaryWord_injective B, by simp⟩ + +/-- A bijection carries the uniform finite law to the uniform finite law. -/ +theorem uniform_map_of_bijective {α β : Type*} [Fintype α] [Fintype β] + [Nonempty α] [Nonempty β] (f : α → β) (hf : Function.Bijective f) : + (PMF.uniformOfFintype α).map f = PMF.uniformOfFintype β := by + classical + ext b + obtain ⟨a, rfl⟩ := hf.2 b + rw [PMF.map_apply, tsum_eq_single a] + · simp [PMF.uniformOfFintype_apply, Fintype.card_of_bijective hf] + · intro other hother + rw [ite_eq_right] + exact fun heq => hother (hf.1 heq.symm) + +/-- Independent fair Boolean words encode a uniform power-of-two range. -/ +theorem binaryWord_uniform (B : ℕ) : + (PMF.uniformOfFintype (Fin B → Bool)).map (binaryWord B) = + PMF.uniformOfFintype (Fin (2 ^ B)) := by + exact uniform_map_of_bijective _ (binaryWord_bijective B) + +/-- Number of fair bits per rejection trial. -/ + + +theorem rejectionWord_range (N : ℕ) (hN : 0 < N) : + N ≤ 2 ^ rejectionBitCount N ∧ 2 ^ rejectionBitCount N < 2 * N := by + constructor + · exact Nat.le_pow_clog (by norm_num) N + · by_cases hNone : N = 1 + · subst N + norm_num [rejectionBitCount] + · have hN1 : 1 < N := by omega + have hpred := Nat.pow_pred_clog_lt_self (by norm_num : 1 < 2) hN1 + have hB := Nat.clog_pos (by norm_num : 1 < 2) hN1 + have hpow : 2 ^ rejectionBitCount N = 2 ^ (Nat.clog 2 N).pred * 2 := by + rw [rejectionBitCount, ← pow_succ] + congr 1 + exact (Nat.succ_pred_eq_of_pos hB).symm + rw [hpow] + omega + +/-- A trial accepts exactly the words lying in the requested range. -/ +def rejectionTrial (N R : ℕ) (word : Fin R) : Option (Fin N) := + if h : word.val < N then some ⟨word.val, h⟩ else none + +/-- Executable finite prefix of the rejection loop. Each failed trial +is discarded before the next trial is examined. -/ +def rejectionPrefix (N R : ℕ) : List (Fin R) → Option (Fin N) + | [] => none + | word :: words => match rejectionTrial N R word with + | some accepted => some accepted + | none => rejectionPrefix N R words + +theorem rejectionTrial_none_iff (N R : ℕ) (word : Fin R) : + rejectionTrial N R word = none ↔ N ≤ word.val := by + simp [rejectionTrial] + +theorem rejectionTrial_some_iff (N R : ℕ) (word : Fin R) (accepted : Fin N) : + rejectionTrial N R word = some accepted ↔ word.val = accepted.val := by + unfold rejectionTrial + split_ifs with h + · simp only [Option.some.injEq, Fin.ext_iff] + · simp only [false_iff] + exact fun heq => h (heq ▸ accepted.isLt) + +theorem rejectionPrefix_none_iff (N R : ℕ) (words : List (Fin R)) : + rejectionPrefix N R words = none ↔ ∀ word ∈ words, N ≤ word.val := by + induction words with + | nil => simp [rejectionPrefix] + | cons word words ih => + simp only [rejectionPrefix] + cases htrial : rejectionTrial N R word with + | none => simp [ih, (rejectionTrial_none_iff N R word).mp htrial] + | some accepted => + have hlt : word.val < N := by + rw [(rejectionTrial_some_iff N R word accepted).mp htrial] + exact accepted.isLt + simp [show ¬N ≤ word.val by omega] + +theorem rejectionPrefix_first_success (N R : ℕ) (words : List (Fin R)) + (last : Fin R) (accepted : Fin N) + (hfailed : ∀ word ∈ words, N ≤ word.val) (hlast : last.val = accepted.val) : + rejectionPrefix N R (words ++ [last]) = some accepted := by + induction words with + | nil => + simp only [List.nil_append, rejectionPrefix] + rw [(rejectionTrial_some_iff N R last accepted).mpr hlast] + | cons word words ih => + have hword := hfailed word (by simp) + have hwords : ∀ next ∈ words, N ≤ next.val := fun next hnext => hfailed next (by simp [hnext]) + simp only [List.cons_append, rejectionPrefix] + rw [(rejectionTrial_none_iff N R word).mpr hword] + exact ih hwords + +/-- Finite traces with `n` failed words followed by the specified +accepted integer. -/ +def firstSuccessEvent (N R n : ℕ) (accepted : Fin N) : + Set ((Fin n → Fin R) × Fin R) := + {samples | (∀ j, N ≤ (samples.1 j).val) ∧ samples.2.val = accepted.val} + +/-- Each failed word is represented uniquely by its offset above `N`; +the final accepted word is fixed. -/ +def firstSuccessEquiv (N R n : ℕ) (hNR : N ≤ R) (accepted : Fin N) : + firstSuccessEvent N R n accepted ≃ (Fin n → Fin (R - N)) where + toFun samples j := ⟨(samples.val.1 j).val - N, by + have hlt := (samples.val.1 j).isLt + have hge := samples.property.1 j + omega⟩ + invFun failed := ⟨(fun j => ⟨N + (failed j).val, by + have hlt := (failed j).isLt + omega⟩, ⟨accepted.val, accepted.isLt.trans_le hNR⟩), by + constructor + · intro j + simp only + omega + · rfl⟩ + left_inv samples := by + apply Subtype.ext + apply Prod.ext + · funext j + apply Fin.ext + simp only + have hge := samples.property.1 j + omega + · apply Fin.ext + exact samples.property.2.symm + right_inv failed := by + funext j + apply Fin.ext + simp + +/-- First-success events are actual terminating executions of the +finite-prefix rejection program. -/ +theorem firstSuccessEvent_runs (N R n : ℕ) (accepted : Fin N) + (samples : (Fin n → Fin R) × Fin R) (hsamples : samples ∈ firstSuccessEvent N R n accepted) : + rejectionPrefix N R (List.ofFn samples.1 ++ [samples.2]) = some accepted := by + apply rejectionPrefix_first_success N R _ _ accepted _ hsamples.2 + intro word hword + obtain ⟨j, rfl⟩ := List.mem_ofFn.mp hword + exact hsamples.1 j + +/-- Exact finite counting probability for `n` failures and then a +specified accepted value, under independent uniform trial words. -/ +theorem firstSuccessEvent_probability (N R n : ℕ) (hN : 0 < N) (hNR : N ≤ R) + (accepted : Fin N) : + let : NeZero R := ⟨by omega⟩ + ((PMF.uniformOfFintype ((Fin n → Fin R) × Fin R)).toMeasure).real + (firstSuccessEvent N R n accepted) = ((R - N : ℕ) : ℝ) ^ n / ((R : ℝ) ^ n * R) := by + let : NeZero R := ⟨by omega⟩ + classical + have hcard : Fintype.card (firstSuccessEvent N R n accepted) = (R - N) ^ n := by + rw [Fintype.card_congr (firstSuccessEquiv N R n hNR accepted)] + simp + dsimp only + rw [MeasureTheory.measureReal_def, PMF.toMeasure_uniformOfFintype_apply (firstSuccessEvent N R n accepted) (by measurability)] + rw [hcard] + simp only [ENNReal.toReal_div, ENNReal.toReal_pow, ENNReal.toReal_mul, ENNReal.toReal_natCast, Fintype.card_prod, + Fintype.card_fun, Fintype.card_fin, Nat.cast_pow, Nat.cast_mul] + +/-- Rejection probability per trial. -/ +noncomputable def rejectionFailureProbability (N R : ℕ) : ℝ := ((R - N : ℕ) : ℝ) / R + +theorem rejectionFailureProbability_range (N R : ℕ) (hN : 0 < N) (hNR : N ≤ R) : + 0 ≤ rejectionFailureProbability N R ∧ rejectionFailureProbability N R < 1 := by + have hR : (0 : ℝ) < R := by exact_mod_cast hN.trans_le hNR + constructor + · unfold rejectionFailureProbability + positivity + · unfold rejectionFailureProbability + rw [div_lt_one hR, Nat.cast_sub hNR] + have hNreal : (0 : ℝ) < N := by exact_mod_cast hN + linarith + +/-- The sum over all first-success times is exactly uniform on the +requested range. This also establishes total terminating mass one. -/ +theorem rejection_exact_output_mass (N R : ℕ) (hN : 0 < N) (hNR : N ≤ R) : + HasSum (fun n : ℕ => ((R - N : ℕ) : ℝ) ^ n / ((R : ℝ) ^ n * R)) (1 / (N : ℝ)) := by + have hR : (0 : ℝ) < R := by exact_mod_cast hN.trans_le hNR + have hNreal : (0 : ℝ) < N := by exact_mod_cast hN + have hq := rejectionFailureProbability_range N R hN hNR + have hseries := (hasSum_geometric_of_lt_one hq.1 hq.2).div_const (R : ℝ) + have hterm (n : ℕ) : rejectionFailureProbability N R ^ n / R = + ((R - N : ℕ) : ℝ) ^ n / ((R : ℝ) ^ n * R) := by + simp only [rejectionFailureProbability, div_pow] + ring + have hsum : (1 - rejectionFailureProbability N R)⁻¹ / R = 1 / (N : ℝ) := by + unfold rejectionFailureProbability + rw [Nat.cast_sub hNR] + field_simp [hR.ne', hNreal.ne'] + ring + simpa only [hterm, hsum] using hseries + +/-- The expected rejection-loop trial count is the sum of its failure +tails, namely `R/N`. -/ +theorem rejection_expected_trials (N R : ℕ) (hN : 0 < N) (hNR : N ≤ R) : + HasSum (fun n : ℕ => rejectionFailureProbability N R ^ n) ((R : ℝ) / N) := by + have hR : (0 : ℝ) < R := by exact_mod_cast hN.trans_le hNR + have hNreal : (0 : ℝ) < N := by exact_mod_cast hN + have hq := rejectionFailureProbability_range N R hN hNR + have hsum : (1 - rejectionFailureProbability N R)⁻¹ = (R : ℝ) / N := by + unfold rejectionFailureProbability + rw [Nat.cast_sub hNR] + field_simp [hR.ne', hNreal.ne'] + ring + simpa only [hsum] using hasSum_geometric_of_lt_one hq.1 hq.2 + +theorem rejection_fair_bits_expected_trials_lt_two (N : ℕ) (hN : 0 < N) : + (∑' n : ℕ, rejectionFailureProbability N (2 ^ rejectionBitCount N) ^ n) < 2 := by + have hrange := rejectionWord_range N hN + rw [(rejection_expected_trials N _ hN hrange.1).tsum_eq] + apply (div_lt_iff₀ (by exact_mod_cast hN : (0 : ℝ) < N)).mpr + exact_mod_cast hrange.2 + +/-- The actual first-success trace law has expected trial count `R/N`; +this identifies the tail-sum calculation with the terminating executions. -/ +theorem rejection_first_success_expected_trials (N R : ℕ) (hN : 0 < N) (hNR : N ≤ R) : + HasSum (fun n : ℕ => ((n : ℝ) + 1) * N * + (((R - N : ℕ) : ℝ) ^ n / ((R : ℝ) ^ n * R))) ((R : ℝ) / N) := by + have hR : (0 : ℝ) < R := by exact_mod_cast hN.trans_le hNR + have hNreal : (0 : ℝ) < N := by exact_mod_cast hN + have hq := rejectionFailureProbability_range N R hN hNR + have hnorm : ‖rejectionFailureProbability N R‖ < 1 := by + rw [Real.norm_eq_abs, abs_of_nonneg hq.1] + exact hq.2 + have hseries := ((hasSum_coe_mul_geometric_of_norm_lt_one hnorm).add + (hasSum_geometric_of_lt_one hq.1 hq.2)).mul_right ((N : ℝ) / R) + have hterm (n : ℕ) : + ((n : ℝ) * rejectionFailureProbability N R ^ n + rejectionFailureProbability N R ^ n) * + ((N : ℝ) / R) = + ((n : ℝ) + 1) * N * (((R - N : ℕ) : ℝ) ^ n / ((R : ℝ) ^ n * R)) := by + simp only [rejectionFailureProbability, div_pow] + ring + have hratio : 1 - rejectionFailureProbability N R = (N : ℝ) / R := by + unfold rejectionFailureProbability + rw [Nat.cast_sub hNR] + field_simp + ring + have hsum : (rejectionFailureProbability N R / (1 - rejectionFailureProbability N R) ^ 2 + + (1 - rejectionFailureProbability N R)⁻¹) * ((N : ℝ) / R) = (R : ℝ) / N := by + rw [hratio] + have hqeq : rejectionFailureProbability N R = 1 - (N : ℝ) / R := by linarith [hratio] + rw [hqeq] + field_simp [hR.ne', hNreal.ne'] + ring + simpa only [hterm, hsum] using hseries + +/-- A streaming rejection sampler only retains its current accepted +value and the current bounded-width random word. -/ +def rejectionTransition (N R : ℕ) (state : Option (Fin N)) (word : Fin R) : Option (Fin N) := + match state with + | none => rejectionTrial N R word + | some accepted => some accepted + +theorem rejectionTransition_absorbs (N R : ℕ) (accepted : Fin N) (word : Fin R) : + rejectionTransition N R (some accepted) word = some accepted := rfl + +/-- The sampler state space is independent of the number of failures. -/ +theorem rejection_fixed_state_space (N R : ℕ) : + Fintype.card (Option (Fin N)) = N + 1 ∧ Fintype.card (Fin R) = R := by + simp + +/-- Summing the first-success trace probabilities gives exactly the +probability of each value in the uniform target distribution. -/ +theorem rejection_output_is_uniform (N R : ℕ) (hN : 0 < N) (hNR : N ≤ R) + (accepted : Fin N) : + let : NeZero N := ⟨Nat.ne_of_gt hN⟩ + (∑' n : ℕ, ((R - N : ℕ) : ℝ) ^ n / ((R : ℝ) ^ n * R)) = + (PMF.uniformOfFintype (Fin N) accepted).toReal := by + let : NeZero N := ⟨Nat.ne_of_gt hN⟩ + rw [(rejection_exact_output_mass N R hN hNR).tsum_eq] + simp [PMF.uniformOfFintype_apply, ENNReal.toReal_inv, one_div] + +/-- Total mass of terminating rejection executions is one. -/ +theorem rejection_terminating_mass (N R : ℕ) (hN : 0 < N) (hNR : N ≤ R) : + (∑ _ : Fin N, ∑' n : ℕ, ((R - N : ℕ) : ℝ) ^ n / ((R : ℝ) ^ n * R)) = 1 := by + simp only [(rejection_exact_output_mass N R hN hNR).tsum_eq, sum_const, + card_univ, Fintype.card_fin, nsmul_eq_mul] + have hNreal : (N : ℝ) ≠ 0 := by exact_mod_cast Nat.ne_of_gt hN + field_simp + +/-- The finite fair-word law factors into the independent fair-bit laws. -/ +theorem fair_bit_word_probability (B : ℕ) (bits : Fin B → Bool) : + PMF.uniformOfFintype (Fin B → Bool) bits = + ∏ i : Fin B, PMF.uniformOfFintype Bool (bits i) := by + simp [PMF.uniformOfFintype_apply, ENNReal.inv_pow] + +theorem rejection_fair_bits_failure_lt_half (N : ℕ) (hN : 0 < N) : + rejectionFailureProbability N (2 ^ rejectionBitCount N) < 1 / 2 := by + have hrange := rejectionWord_range N hN + have hR : (0 : ℝ) < (2 ^ rejectionBitCount N : ℕ) := by positivity + unfold rejectionFailureProbability + apply (div_lt_iff₀ hR).mpr + rw [Nat.cast_sub hrange.1] + have hRbound : ((2 ^ rejectionBitCount N : ℕ) : ℝ) < 2 * N := by exact_mod_cast hrange.2 + linarith + +theorem optimizerTriangularMass_monotone : Monotone optimizerTriangularMass := by + intro a b hab + have hproduct := Nat.mul_le_mul hab (Nat.add_le_add_right hab 1) + rw [← optimizerTriangularMass_twice a, ← optimizerTriangularMass_twice b] at hproduct + omega + +theorem optimizerTriangularMass_positive (K : ℕ) (hK : 0 < K) : + 0 < optimizerTriangularMass K := by + have hproduct : 0 < K * (K + 1) := Nat.mul_pos hK (by omega) + rw [← optimizerTriangularMass_twice K] at hproduct + omega + +/- Executable triangular-block lookup. Its finite linear search also +has polynomial cost in the prescribed number of optimizer steps. -/ + + +/-- The lookup assigns precisely the `j+1` integers in block `j`. -/ +theorem triangularChoice_fiber (K : ℕ) (integer : Fin (optimizerTriangularMass K)) + (j : ℕ) (hj : j < K) : + (triangularChoice K integer).val = j ↔ + optimizerTriangularMass j ≤ integer.val ∧ integer.val < optimizerTriangularMass (j + 1) := by + induction K with + | zero => omega + | succ K ih => + simp only [triangularChoice] + split_ifs with hprevious + · by_cases hjK : j < K + · exact ih ⟨integer.val, hprevious⟩ hjK + · have hjEq : j = K := by omega + subst j + have hchosen := (triangularChoice K ⟨integer.val, hprevious⟩).isLt + simp only [Fin.val_castSucc] + constructor + · intro heq + omega + · intro hblock + omega + · change K = j ↔ _ + by_cases hjEq : j = K + · subst j + exact ⟨fun _ => ⟨by omega, integer.isLt⟩, fun _ => rfl⟩ + · have hjK : j + 1 ≤ K := by omega + have hupper := optimizerTriangularMass_monotone hjK + constructor + · intro heq + omega + · intro hblock + omega + +/-- Each triangular lookup fiber is exactly a finite interval of the +claimed integer length. -/ +def triangularChoiceFiberEquiv (K j : ℕ) (hj : j < K) : + {integer : Fin (optimizerTriangularMass K) // (triangularChoice K integer).val = j} ≃ Fin (j + 1) where + toFun integer := ⟨integer.val.val - optimizerTriangularMass j, by + have hblock := (triangularChoice_fiber K integer.val j hj).mp integer.property + rw [optimizerTriangularMass_succ] at hblock + omega⟩ + invFun offset := ⟨⟨optimizerTriangularMass j + offset.val, by + have hupper := optimizerTriangularMass_monotone (show j + 1 ≤ K by omega) + rw [optimizerTriangularMass_succ] at hupper + have hoffset := offset.isLt + omega⟩, by + apply (triangularChoice_fiber K _ j hj).mpr + constructor + · simp only + omega + · simp only + rw [optimizerTriangularMass_succ] + have hoffset := offset.isLt + omega⟩ + left_inv integer := by + apply Subtype.ext + apply Fin.ext + simp only + have hblock := (triangularChoice_fiber K integer.val j hj).mp integer.property + omega + right_inv offset := by + apply Fin.ext + simp + +theorem triangularChoice_fiber_card (K : ℕ) (j : Fin K) : + Fintype.card {integer : Fin (optimizerTriangularMass K) // triangularChoice K integer = j} = j.val + 1 := by + have hcard := Fintype.card_congr (triangularChoiceFiberEquiv K j.val j.isLt) + simpa only [Fin.ext_iff, Fintype.card_fin] using hcard + +/-- Uniform integer rejection followed by triangular lookup gives the +stored exact optimizer weights. -/ +theorem triangularChoice_uniform_weights (K : ℕ) (hK : 0 < K) (j : Fin K) : + let : NeZero (optimizerTriangularMass K) := ⟨Nat.ne_of_gt (optimizerTriangularMass_positive K hK)⟩ + (((PMF.uniformOfFintype (Fin (optimizerTriangularMass K))).map (triangularChoice K)) j).toReal = + (optimizerMixtureWeight K j.val : ℝ) := by + let : NeZero (optimizerTriangularMass K) := ⟨Nat.ne_of_gt (optimizerTriangularMass_positive K hK)⟩ + classical + dsimp only + rw [PMF.map_apply, tsum_fintype] + simp_rw [PMF.uniformOfFintype_apply, Fintype.card_fin] + rw [← sum_filter] + simp only [sum_const, nsmul_eq_mul] + have hcard : (univ.filter fun integer : Fin (optimizerTriangularMass K) => + j = triangularChoice K integer).card = j.val + 1 := by + rw [← Fintype.card_subtype] + simpa only [eq_comm] using triangularChoice_fiber_card K j + rw [hcard] + simp only [ENNReal.toReal_mul, ENNReal.toReal_inv, ENNReal.toReal_natCast] + rw [← optimizerSampler_block_weight K j.val hK] + push_cast + ring + +/-- Exact coordinate mean of the sampler, including repeated selected +actions, equals the actual rational optimizer iterate. -/ +theorem triangularChoice_coordinate_mean {ι : Type*} (initial : ι → ℚ) + (selected : ℕ → ι → ℚ) (K : ℕ) (hK : 0 < K) (i : ι) : + (∑ integer : Fin (optimizerTriangularMass K), selected (triangularChoice K integer).val i) / + optimizerTriangularMass K = rationalOptimizerIterate initial selected K i := by + classical + have hsum : (∑ integer : Fin (optimizerTriangularMass K), selected (triangularChoice K integer).val i) = + ∑ j : Fin K, ((j.val + 1 : ℕ) : ℚ) * selected j.val i := by + rw [← Fintype.sum_fiberwise' (triangularChoice K) (fun j => selected j.val i)] + apply sum_congr rfl + intro j hj + rw [sum_const, card_univ, triangularChoice_fiber_card, nsmul_eq_mul] + have hmixture := rationalOptimizerIterate_eq_mixture initial selected (K - 1) i + rw [Nat.sub_add_cancel (show 1 ≤ K by omega)] at hmixture + rw [hsum, sum_div, hmixture, ← Fin.sum_univ_eq_sum_range] + apply sum_congr rfl + intro j hj + rw [← optimizerSampler_block_weight K j.val hK] + ring + +/-- The exactly sampled action has the mean computed by the finite +rational optimizer, with no distinction assumption on its selections. -/ +theorem finiteRationalOptimizer_sampler_mean {ι : Type*} (coordinates : Finset ι) + (vertices : List (ι → ℚ)) (linear : ι → ℚ) (G K : ℕ) (hK : 0 < K) (i : ι) : + (∑ integer : Fin (optimizerTriangularMass K), + finiteOptimizerSelection coordinates vertices linear G (triangularChoice K integer).val i) / + optimizerTriangularMass K = finiteRationalOptimizer coordinates vertices linear G K i := by + rw [finiteRationalOptimizer_eq_iterate] + exact triangularChoice_coordinate_mean _ _ K hK i + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Probability/ExactSuffixDP.lean b/lean/OAI/Combinatorics/EditApproximation/Probability/ExactSuffixDP.lean new file mode 100644 index 0000000000000000000000000000000000000000..d227579e94b58fb2a611b104ff66fe047ca2413c --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Probability/ExactSuffixDP.lean @@ -0,0 +1,127 @@ +import OAI.Combinatorics.EditApproximation.Geometry.AlignmentSplitting +import OAI.Combinatorics.EditApproximation.Geometry.Leaves +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! An exact suffix dynamic program for the bounded initial input range. +Each source row is computed once; its cells minimize over target cuts. +The singleton prefix cost is the executable occurrence formula. -/ + +namespace EditApproximation + +open EditDistortion + + + +theorem natListMinimum_le_fallback (fallback : ℕ) (values : List ℕ) : + natListMinimum fallback values ≤ fallback := by + induction values with + | nil => exact le_rfl + | cons first rest ih => exact (min_le_right _ _).trans ih + +theorem natListMinimum_le_member (fallback value : ℕ) (values : List ℕ) (h : value ∈ values) : + natListMinimum fallback values ≤ value := by + induction values with + | nil => simp only [List.not_mem_nil] at h + | cons first rest ih => + rcases List.mem_cons.mp h with rfl | h + · exact min_le_left _ _ + · exact (min_le_right _ _).trans (ih h) + +theorem natListMinimum_lower (fallback lower : ℕ) (values : List ℕ) + (hfallback : lower ≤ fallback) (hvalues : ∀ value ∈ values, lower ≤ value) : + lower ≤ natListMinimum fallback values := by + induction values with + | nil => exact hfallback + | cons first rest ih => + exact le_min (hvalues first (List.mem_cons_self)) + (ih (fun value h => hvalues value (List.mem_cons_of_mem _ h))) + + + +theorem exactSuffixDP_length {α : Type*} [DecidableEq α] (source target : List α) : + (exactSuffixDP source target).length = target.length + 1 := by + cases source <;> simp only [exactSuffixDP, List.length_ofFn] + +theorem ofFn_nat_getD {n j : ℕ} (f : Fin (n + 1) → ℕ) (hj : j ≤ n) : + (List.ofFn f).getD j 0 = f ⟨j, Nat.lt_succ_of_le hj⟩ := by + have hlt : j < (List.ofFn f).length := by simpa only [List.length_ofFn] using Nat.lt_succ_of_le hj + rw [List.getD_eq_getElem _ _ hlt, List.getElem_ofFn] + +theorem edit_nil_left_exact {α : Type*} (target : List α) : edit ([] : List α) target = target.length := by + have hlo := (cost_length_bounds (s := true) ([] : List α) target).2 + have hup := edit_le_max_length ([] : List α) target + simp only [List.length_nil, zero_add, max_eq_right (Nat.zero_le _)] at hlo hup + exact Nat.le_antisymm hup hlo + +theorem exactSuffixDP_spec {α : Type*} [DecidableEq α] (source target : List α) : + ∀ j ≤ target.length, (exactSuffixDP source target).getD j 0 = edit source (target.drop j) := by + induction source with + | nil => + intro j hj + rw [exactSuffixDP, ofFn_nat_getD _ hj, edit_nil_left_exact, List.length_drop] + | cons a rest ih => + intro j hj + rw [exactSuffixDP, ofFn_nat_getD _ hj] + dsimp only + have hcandidate (k : ℕ) (hk : k ≤ target.length - j) : + edit (a :: rest) (target.drop j) ≤ + singletonCost a ((target.drop j).take k) + (exactSuffixDP rest target).getD (j + k) 0 := by + rw [singletonCost_eq_edit, ih (j + k) (by omega)] + have h := cost_append_le (s := true) [a] ((target.drop j).take k) rest ((target.drop j).drop k) + rw [List.take_append_drop] at h + simpa only [cost, edit, List.singleton_append, List.drop_drop] using h + apply Nat.le_antisymm + · obtain ⟨left, right, hsplit, hcost⟩ := edit_append_split [a] rest (target.drop j) + have hk : left.length ≤ target.length - j := by + have hlen := congrArg List.length hsplit + simp only [List.length_drop, List.length_append] at hlen + omega + have hleft : (target.drop j).take left.length = left := by + rw [hsplit] + simp only [List.take_left] + have hright : target.drop (j + left.length) = right := by + rw [← List.drop_drop, hsplit] + simp only [List.drop_left] + have hm := natListMinimum_le_member + (singletonCost a [] + (exactSuffixDP rest target).getD j 0) + (singletonCost a ((target.drop j).take left.length) + + (exactSuffixDP rest target).getD (j + left.length) 0) + ((List.range (target.length - j + 1)).map fun k => + singletonCost a ((target.drop j).take k) + (exactSuffixDP rest target).getD (j + k) 0) + (List.mem_map.mpr ⟨left.length, List.mem_range.mpr (by omega), rfl⟩) + have hvalue : singletonCost a ((target.drop j).take left.length) + + (exactSuffixDP rest target).getD (j + left.length) 0 = edit [a] left + edit rest right := by + rw [hleft, singletonCost_eq_edit, ih (j + left.length) (by omega), hright] + simpa only [List.singleton_append] using hm.trans_eq (hvalue.trans hcost.symm) + · apply natListMinimum_lower + · simpa only [List.take_zero, Nat.add_zero] using hcandidate 0 (Nat.zero_le _) + · intro value hvalue + rcases List.mem_map.mp hvalue with ⟨k, hk, rfl⟩ + exact hcandidate k (by have := List.mem_range.mp hk; omega) + + + +theorem exactSuffixAnswer_eq_edit {α : Type*} [DecidableEq α] (source target : List α) : + exactSuffixAnswer source target = edit source target := by + simpa only [exactSuffixAnswer, List.drop_zero] using exactSuffixDP_spec source target 0 (Nat.zero_le _) + +theorem exactSuffixAnswer_equal {α : Type*} [DecidableEq α] (source target : List α) + (heq : source = target) : exactSuffixAnswer source target = 0 := by + rw [exactSuffixAnswer_eq_edit] + exact (cost_eq_zero_iff (s := true)).mpr heq + +theorem exactSuffixAnswer_approximation {α : Type*} [DecidableEq α] (source target : List α) + (epsilon : ℝ) (hepsilon : 0 ≤ epsilon) : + edit source target ≤ exactSuffixAnswer source target ∧ + (exactSuffixAnswer source target : ℝ) ≤ (1 + epsilon) * edit source target := by + rw [exactSuffixAnswer_eq_edit] + constructor + · exact le_rfl + · nlinarith [show (0 : ℝ) ≤ (edit source target : ℝ) from Nat.cast_nonneg _] + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Probability/ExactSuffixDPWork.lean b/lean/OAI/Combinatorics/EditApproximation/Probability/ExactSuffixDPWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..206cdd48f98294d3a5b324d5e2d4c6f93683f5a9 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Probability/ExactSuffixDPWork.lean @@ -0,0 +1,298 @@ +import OAI.Combinatorics.EditApproximation.Probability.ExactSuffixDP +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! A costed implementation of the exact cut dynamic program. The counter +counts symbol comparisons and list-cell visits, with explicit outer-loop +overhead. Each counted transition uses a fixed number of word operations; +the surrounding RAM realization supplies that constant. Suffix lookups and +occurrence scans are charged rather than treated as constant-time arrays. -/ + +namespace EditApproximation + + + + + + + + + + + +theorem dpLength_spec {α : Type*} (word : List α) : + (dpLength word).1 = word.length ∧ (dpLength word).2 = word.length + 1 := by + induction word with + | nil => exact ⟨rfl, rfl⟩ + | cons first rest ih => + constructor <;> simp only [dpLength, List.length_cons, ih.1, ih.2] + +theorem dpDrop_spec {α : Type*} (n : ℕ) (word : List α) : + (dpDrop n word).1 = word.drop n ∧ (dpDrop n word).2 ≤ word.length + 1 := by + induction n generalizing word with + | zero => simp only [dpDrop, List.drop_zero, le_add_iff_nonneg_left, Nat.zero_le, and_self] + | succ n ih => + cases word with + | nil => simp only [dpDrop, List.drop_nil, List.length_nil, le_refl, and_self] + | cons first rest => + have h := ih rest + exact ⟨h.1, by simpa only [dpDrop, List.length_cons] using Nat.add_le_add_right h.2 1⟩ + +theorem dpTake_spec {α : Type*} (n : ℕ) (word : List α) : + (dpTake n word).1 = word.take n ∧ (dpTake n word).2 ≤ word.length + 1 := by + induction n generalizing word with + | zero => simp only [dpTake, List.take_zero, le_add_iff_nonneg_left, Nat.zero_le, and_self] + | succ n ih => + cases word with + | nil => simp only [dpTake, List.take_nil, List.length_nil, le_refl, and_self] + | cons first rest => + have h := ih rest + exact ⟨congrArg (List.cons first) h.1, + by simpa only [dpTake, List.length_cons] using Nat.add_le_add_right h.2 1⟩ + +theorem dpGetD_spec (word : List ℕ) (n : ℕ) : + (dpGetD word n).1 = word.getD n 0 ∧ (dpGetD word n).2 ≤ word.length + 1 := by + induction word generalizing n with + | nil => simp [dpGetD] + | cons first rest ih => + cases n with + | zero => simp [dpGetD] + | succ n => + have h := ih n + exact ⟨h.1, by simpa only [dpGetD, List.length_cons] using Nat.add_le_add_right h.2 1⟩ + +theorem dpMember_spec {α : Type*} [DecidableEq α] (a : α) (word : List α) : + (dpMember a word).1 = decide (a ∈ word) ∧ (dpMember a word).2 ≤ word.length + 1 := by + induction word with + | nil => simp [dpMember] + | cons first rest ih => + by_cases h : a = first + · simp [dpMember, h] + · constructor + · simp only [dpMember, h, ite_false, ih.1, List.mem_cons, false_or] + · simpa only [dpMember, h, ite_false, List.length_cons] using Nat.add_le_add_right ih.2 1 + + + +theorem dpSingleton_spec {α : Type*} [DecidableEq α] (a : α) (word : List α) : + (dpSingleton a word).1 = singletonCost a word ∧ (dpSingleton a word).2 ≤ 2 * word.length + 4 := by + by_cases h : word = [] + · subst word; simp [dpSingleton, singletonCost] + · constructor + · simp only [dpSingleton, singletonCost, h, ite_false, occurrenceDeficit, (dpLength_spec word).1, + (dpMember_spec a word).1, decide_eq_true_eq] + · have hc := (dpLength_spec word).2 + have hm := (dpMember_spec a word).2 + simp only [dpSingleton, h, ite_false] + omega + + + +theorem dpMinimum_spec (fallback : ℕ) (values : List ℕ) : + (dpMinimum fallback values).1 = natListMinimum fallback values ∧ + (dpMinimum fallback values).2 = values.length + 1 := by + induction values with + | nil => exact ⟨rfl, rfl⟩ + | cons first rest ih => + constructor <;> simp only [dpMinimum, natListMinimum, ih.1, ih.2, List.length_cons] + + + +theorem dpCandidate_value {α : Type*} [DecidableEq α] (a : α) (target : List α) + (previous : List ℕ) (j k : ℕ) : + (dpCandidate a target previous j k).1 = + singletonCost a ((target.drop j).take k) + previous.getD (j + k) 0 := by + simp only [dpCandidate, (dpSingleton_spec _ _).1, (dpDrop_spec _ _).1, + (dpTake_spec _ _).1, (dpGetD_spec _ _).1] + +theorem dpCandidate_work {α : Type*} [DecidableEq α] (a : α) (target : List α) + (previous : List ℕ) (hprevious : previous.length = target.length + 1) (j k : ℕ) : + (dpCandidate a target previous j k).2 ≤ 12 * (target.length + 1) := by + have hs := (dpDrop_spec j target).2 + have hp := (dpTake_spec k (dpDrop j target).1).2 + have ho := (dpSingleton_spec a (dpTake k (dpDrop j target).1).1).2 + have hg := (dpGetD_spec previous (j + k)).2 + have hsl : (dpDrop j target).1.length ≤ target.length := by + rw [(dpDrop_spec _ _).1, List.length_drop]; omega + have hpl : (dpTake k (dpDrop j target).1).1.length ≤ target.length := by + rw [(dpTake_spec _ _).1, List.length_take] + exact (min_le_right _ _).trans hsl + simp only [dpCandidate] + rw [hprevious] at hg + omega + +theorem nat_pair_sum_bound {ι : Type*} (values : List ι) (cost : ι → ℕ) (budget : ℕ) + (h : ∀ value ∈ values, cost value ≤ budget) : + (values.map cost).sum ≤ values.length * budget := by + induction values with + | nil => simp + | cons first rest ih => + have hf := h first List.mem_cons_self + have hr := ih (fun value hv => h value (List.mem_cons_of_mem _ hv)) + simp only [List.map_cons, List.sum_cons, List.length_cons] + nlinarith + + + +theorem dpCell_value {α : Type*} [DecidableEq α] (a : α) (target : List α) + (previous : List ℕ) (j : ℕ) : + (dpCell a target previous j).1 = + natListMinimum (singletonCost a [] + previous.getD j 0) + ((List.range (target.length - j + 1)).map fun k => + singletonCost a ((target.drop j).take k) + previous.getD (j + k) 0) := by + simp only [dpCell, (dpMinimum_spec _ _).1, dpCandidate_value, List.take_zero, Nat.add_zero, + List.map_map, Function.comp_def] + +theorem dpCell_work {α : Type*} [DecidableEq α] (a : α) (target : List α) + (previous : List ℕ) (hprevious : previous.length = target.length + 1) (j : ℕ) : + (dpCell a target previous j).2 ≤ 40 * (target.length + 1) ^ 2 := by + let candidates := (List.range (target.length - j + 1)).map (dpCandidate a target previous j) + have hsum := nat_pair_sum_bound candidates Prod.snd (12 * (target.length + 1)) (by + intro candidate hc + rcases List.mem_map.mp hc with ⟨k, _, rfl⟩ + exact dpCandidate_work a target previous hprevious j k) + have hcount : candidates.length ≤ target.length + 1 := by + simp only [candidates, List.length_map, List.length_range]; omega + have hf := dpCandidate_work a target previous hprevious j 0 + have hm := (dpMinimum_spec (dpCandidate a target previous j 0).1 (candidates.map Prod.fst)).2 + simp only [List.length_map] at hm + have hl := (dpLength_spec target).2 + change (dpCandidate a target previous j 0).2 + (candidates.map Prod.snd).sum + + (dpMinimum (dpCandidate a target previous j 0).1 (candidates.map Prod.fst)).2 + + (dpLength target).2 + 3 * candidates.length + 4 ≤ _ + have hprod := Nat.mul_le_mul_right (12 * (target.length + 1)) hcount + nlinarith + + + +theorem chargedSuffixDP_value {α : Type*} [DecidableEq α] (source target : List α) : + (chargedSuffixDP source target).1 = exactSuffixDP source target := by + induction source with + | nil => rfl + | cons a rest ih => + simp only [chargedSuffixDP, exactSuffixDP, List.map_ofFn, Function.comp_def, dpCell_value, ih] + +theorem chargedSuffixDP_work {α : Type*} [DecidableEq α] (source target : List α) : + (chargedSuffixDP source target).2 ≤ 50 * (source.length + 1) * (target.length + 1) ^ 3 := by + induction source with + | nil => + have hcube : target.length + 1 ≤ (target.length + 1) ^ 3 := by + simpa only [pow_one] using pow_le_pow_right₀ (by omega : 1 ≤ target.length + 1) (by decide : 1 ≤ 3) + simp only [chargedSuffixDP, List.length_nil] + omega + | cons a rest ih => + let previous := chargedSuffixDP rest target + let cells := List.ofFn fun j : Fin (target.length + 1) => dpCell a target previous.1 j.val + have hprevious : previous.1.length = target.length + 1 := by + rw [chargedSuffixDP_value, exactSuffixDP_length] + have hsum := nat_pair_sum_bound cells Prod.snd (40 * (target.length + 1) ^ 2) (by + intro cell hc + rcases List.mem_ofFn.mp hc with ⟨j, rfl⟩ + exact dpCell_work a target previous.1 hprevious j.val) + have hcount : cells.length = target.length + 1 := List.length_ofFn + have hl := (dpLength_spec target).2 + change previous.2 + (cells.map Prod.snd).sum + 2 * (dpLength target).2 + + 2 * cells.length + 3 ≤ _ + change previous.2 ≤ _ at ih + rw [hcount] at hsum ⊢ + simp only [List.length_cons] + nlinarith [show 0 ≤ target.length by omega] + +/-- Every retained row has linear length, and every stored distance fits +the input length bound; the traversal counter is polynomial even with lists. -/ +theorem chargedSuffixDP_storage {α : Type*} [DecidableEq α] (source target : List α) + (N : ℕ) (hsize : source.length + target.length ≤ N) : + (chargedSuffixDP source target).1.length ≤ N + 1 ∧ + (∀ j ≤ target.length, (chargedSuffixDP source target).1.getD j 0 ≤ N) ∧ + (chargedSuffixDP source target).2 ≤ 50 * (N + 1) ^ 4 := by + rw [chargedSuffixDP_value] + constructor + · rw [exactSuffixDP_length]; omega + constructor + · intro j hj + rw [exactSuffixDP_spec source target j hj] + apply (EditDistortion.edit_le_max_length _ _).trans + simp only [List.length_drop] + exact max_le (by omega) (by omega) + · have h := chargedSuffixDP_work source target + have hn : source.length + 1 ≤ N + 1 := by omega + have hm : target.length + 1 ≤ N + 1 := by omega + have hmul := Nat.mul_le_mul (Nat.mul_le_mul_left 50 hn) (Nat.pow_le_pow_left hm 3) + exact h.trans (by simpa only [show (N + 1) ^ 4 = (N + 1) * (N + 1) ^ 3 by ring, + Nat.mul_assoc] using hmul) + +theorem dpTake_allocation {α : Type*} (n : ℕ) (word : List α) : + (dpTake n word).1.length ≤ (dpTake n word).2 := by + induction n generalizing word with + | zero => simp [dpTake] + | succ n ih => + cases word with + | nil => simp [dpTake] + | cons first rest => simpa only [dpTake, List.length_cons] using Nat.add_le_add_right (ih rest) 1 + + + +theorem dpCandidate_allocation {α : Type*} [DecidableEq α] (a : α) (target : List α) + (previous : List ℕ) (j k : ℕ) : + dpCandidateAllocation target j k ≤ (dpCandidate a target previous j k).2 := by + have h := dpTake_allocation k (dpDrop j target).1 + simp only [dpCandidateAllocation, dpCandidate] + omega + +theorem nat_list_sum_mono {ι : Type*} (values : List ι) (f g : ι → ℕ) + (h : ∀ value ∈ values, f value ≤ g value) : (values.map f).sum ≤ (values.map g).sum := by + induction values with + | nil => exact le_rfl + | cons first rest ih => + have hf := h first List.mem_cons_self + have hr := ih (fun value hv => h value (List.mem_cons_of_mem _ hv)) + simp only [List.map_cons, List.sum_cons] + omega + +/-- Candidate pairs, natural candidate values, the index range and prefix +lists are counted as materialized cells. The fallback prefix is retained. -/ + + +theorem dpCell_allocation {α : Type*} [DecidableEq α] (a : α) (target : List α) + (previous : List ℕ) (j : ℕ) : dpCellAllocation target j ≤ (dpCell a target previous j).2 := by + have hf := dpCandidate_allocation a target previous j 0 + have hs := nat_list_sum_mono (List.range (target.length - j + 1)) + (dpCandidateAllocation target j) (fun k => (dpCandidate a target previous j k).2) + (fun k _ => dpCandidate_allocation a target previous j k) + simp only [dpCell, (dpMinimum_spec _ _).2, List.length_map, List.length_range, + List.map_map, Function.comp_def] + unfold dpCellAllocation + omega + +/-- Total materialized list cells over the whole run. This also bounds +the simultaneously live materialized cells under any deallocation policy. -/ + + +theorem suffixDPAllocation_le_work {α : Type*} [DecidableEq α] (source target : List α) : + suffixDPAllocation source target ≤ (chargedSuffixDP source target).2 := by + induction source with + | nil => simp only [suffixDPAllocation, chargedSuffixDP]; omega + | cons a rest ih => + let previous := chargedSuffixDP rest target + let cells := List.ofFn fun j : Fin (target.length + 1) => dpCell a target previous.1 j.val + have hs : (List.ofFn fun j : Fin (target.length + 1) => dpCellAllocation target j.val).sum ≤ + (cells.map Prod.snd).sum := by + simp only [cells, List.map_ofFn, List.sum_ofFn] + exact Finset.sum_le_sum (fun j _ => dpCell_allocation a target previous.1 j.val) + have hl := (dpLength_spec target).2 + have hc : cells.length = target.length + 1 := List.length_ofFn + change suffixDPAllocation rest target + _ + _ ≤ + previous.2 + (cells.map Prod.snd).sum + 2 * (dpLength target).2 + 2 * cells.length + 3 + change suffixDPAllocation rest target ≤ previous.2 at ih + omega + +theorem suffixDPAllocation_polynomial {α : Type*} [DecidableEq α] (source target : List α) + (N : ℕ) (hsize : source.length + target.length ≤ N) : + suffixDPAllocation source target ≤ 50 * (N + 1) ^ 4 := + (suffixDPAllocation_le_work source target).trans (chargedSuffixDP_storage source target N hsize).2.2 + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Probability/ExpectedRegret.lean b/lean/OAI/Combinatorics/EditApproximation/Probability/ExpectedRegret.lean new file mode 100644 index 0000000000000000000000000000000000000000..66c481ec7b19e304637f536b415b67e4d9a4fc9e --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Probability/ExpectedRegret.lean @@ -0,0 +1,52 @@ +import OAI.Combinatorics.EditApproximation.Geometry.NodeRegret +import OAI.Combinatorics.EditApproximation.Probability.SampledRegret + +namespace OAI + +/-! +# Averaging the first-crossing regret + +All parent random choices may be represented by one finite uniform sample. +Only the separate marginal laws of online draws and group failures are +used. In particular, these two families may be correlated with one another. +-/ + +namespace EditApproximation + +open Finset + +theorem firstCrossing_expected_sum_bound {Ω : Type*} [Fintype Ω] [Nonempty Ω] + (S crossing : ℕ) (regret prefixPayoff failure : Ω → ℕ → ℝ) + (prefixBudget crossingCharge failureCharge q : ℝ) + (hcrossing : crossing ≤ S) (hcharge : 0 ≤ crossingCharge) (hfailureCharge : 0 ≤ failureCharge) + (hfailure : ∀ ω t, t < S → 0 ≤ failure ω t) + (hprefix : ∀ ω t, t < crossing → regret ω t ≤ prefixPayoff ω t + failureCharge * failure ω t) + (hcross : ∀ ω, crossing < S → regret ω crossing ≤ crossingCharge + failureCharge * failure ω crossing) + (hafter : ∀ ω t, t < S → crossing < t → regret ω t ≤ 0) + (hprefixMean : (∑ t ∈ range crossing, uniformMean (fun ω => prefixPayoff ω t)) ≤ prefixBudget) + (hfailureMean : ∀ t < S, uniformMean (fun ω => failure ω t) ≤ q) : + uniformMean (fun ω => ∑ t ∈ range S, regret ω t) ≤ + prefixBudget + crossingCharge + failureCharge * (S : ℝ) * q := by + have hpoint ω := firstCrossing_sum_bound S crossing (regret ω) (prefixPayoff ω) + (failure ω) crossingCharge failureCharge hcrossing hcharge hfailureCharge + (hfailure ω) (hprefix ω) (hcross ω) (hafter ω) + have hmean := uniformMean_mono _ _ hpoint + simp only [uniformMean_add, uniformMean_const, uniformMean_mul, uniformMean_sum] at hmean ⊢ + have hfailSum : (∑ t ∈ range S, uniformMean (fun ω => failure ω t)) ≤ (S : ℝ) * q := by + have hsum := sum_le_sum (s := range S) fun t ht => hfailureMean t (mem_range.mp ht) + simpa only [sum_const, card_range, nsmul_eq_mul] using hsum + have hfailCost := mul_le_mul_of_nonneg_left hfailSum hfailureCharge + nlinarith + +/-- Integrating a fixed child-table environment uses only finite linearity. +The failure cost is the manuscript's `2 S H^-4 F c`. -/ +theorem node_expected_failure_charge {S H : ℕ} {F c failureBudget : ℝ} + (hF : 0 ≤ F) (hc : 0 ≤ c) + (hbudget : failureBudget ≤ (S : ℝ) / (H : ℝ) ^ 4) : + 2 * F * c * failureBudget ≤ 2 * S * (1 / (H : ℝ) ^ 4) * F * c := by + have hmul := mul_le_mul_of_nonneg_left hbudget (by positivity : 0 ≤ 2 * F * c) + convert hmul using 1; ring + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Probability/FiniteArrayMarginal.lean b/lean/OAI/Combinatorics/EditApproximation/Probability/FiniteArrayMarginal.lean new file mode 100644 index 0000000000000000000000000000000000000000..0aa9bbb60668bb648a1260a1b4bca4505fbf85f8 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Probability/FiniteArrayMarginal.lean @@ -0,0 +1,53 @@ +import OAI.Combinatorics.EditApproximation.Geometry.CommonArrayFinal + +namespace OAI + +namespace EditApproximation + +open MeasureTheory ProbabilityTheory + +section Law + +variable {Ω : Type} [Fintype Ω] [MeasurableSpace Ω] [MeasurableSingletonClass Ω] + (μ : Measure Ω) [IsProbabilityMeasure μ] + + theorem finite_init_last_law (n : ℕ) : + (Measure.pi fun _ : Fin (n + 1) => μ).map + (fun draw => ((fun i : Fin n => draw i.castSucc), draw (Fin.last n))) = + (Measure.pi fun _ : Fin n => μ).prod μ := by + classical + apply Measure.ext_of_singleton + rintro ⟨front, last⟩ + rw [Measure.map_apply (measurable_of_finite _) (measurableSet_singleton _)] + have hpre : (fun draw : Fin (n + 1) → Ω => + ((fun i : Fin n => draw i.castSucc), draw (Fin.last n))) ⁻¹' {(front, last)} = + {Fin.snoc front last} := by + ext draw + simp only [Set.mem_preimage, Set.mem_singleton_iff, Prod.mk.injEq] + constructor + · rintro ⟨hp, hl⟩ + funext i + refine Fin.lastCases ?_ (fun j => ?_) i + · simpa only [Fin.snoc_last] using hl + · simpa only [Fin.snoc_castSucc] using congrFun hp j + · rintro rfl + constructor + · funext i; simp only [Fin.snoc_castSucc] + · simp only [Fin.snoc_last] + rw [hpre, Measure.pi_singleton, Fin.prod_univ_castSucc] + simp only [Fin.snoc_castSucc, Fin.snoc_last] + rw [← Set.singleton_prod_singleton, Measure.prod_prod, Measure.pi_singleton] + + theorem finite_init_law (n : ℕ) : + (Measure.pi fun _ : Fin (n + 1) => μ).map + (fun draw (i : Fin n) => draw i.castSucc) = Measure.pi fun _ : Fin n => μ := by + have h := congrArg (fun law : Measure ((Fin n → Ω) × Ω) => law.map Prod.fst) + (finite_init_last_law μ n) + rw [Measure.map_map (measurable_of_finite _) (measurable_of_finite _), Measure.map_fst_prod] at h + simpa only [Function.comp_def, measure_univ, one_smul] using h + +end Law + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Probability/FiniteAssignments.lean b/lean/OAI/Combinatorics/EditApproximation/Probability/FiniteAssignments.lean new file mode 100644 index 0000000000000000000000000000000000000000..620a12555280be85cc852b6c9c27da8d1ea9c6b0 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Probability/FiniteAssignments.lean @@ -0,0 +1,68 @@ +import Mathlib +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! +# Executable finite products of child-state lists + +The wide-action lists use this literal recursive Cartesian product. +Their coordinates are child labels, so duplicate interval labels remain +distinct coordinates. +-/ + +namespace EditApproximation + + + +theorem finiteAssignments_complete {α : Type*} (M : ℕ) (choices : Fin M → List α) + (action : Fin M → α) (ha : ∀ i, action i ∈ choices i) : + action ∈ finiteAssignments M choices := by + induction M with + | zero => + have haction : action = Fin.elim0 := by funext i; exact Fin.elim0 i + simp only [finiteAssignments, haction, List.mem_singleton] + | succ M ih => + apply List.mem_flatMap.mpr + refine ⟨action 0, ha 0, List.mem_map.mpr ?_⟩ + refine ⟨fun i => action i.succ, ih _ _ (fun i => ha i.succ), ?_⟩ + funext i + refine Fin.cases ?_ (fun j => ?_) i <;> rfl + +theorem finiteAssignments_sound {α : Type*} (M : ℕ) (choices : Fin M → List α) + (action : Fin M → α) (ha : action ∈ finiteAssignments M choices) : + ∀ i, action i ∈ choices i := by + induction M with + | zero => intro i; exact Fin.elim0 i + | succ M ih => + obtain ⟨head, hhead, hrest⟩ := List.mem_flatMap.mp ha + obtain ⟨tail, htail, rfl⟩ := List.mem_map.mp hrest + intro i + refine Fin.cases ?_ (fun j => ?_) i + · exact hhead + · exact ih _ _ htail _ + +theorem finiteAssignments_length_le {α : Type*} (M K : ℕ) + (choices : Fin M → List α) (hchoices : ∀ i, (choices i).length ≤ K) : + (finiteAssignments M choices).length ≤ K ^ M := by + induction M with + | zero => simp only [finiteAssignments, List.length_singleton, pow_zero, le_refl] + | succ M ih => + have htail := ih (fun i => choices i.succ) (fun i => hchoices i.succ) + have hflat (entries : List α) : + (entries.flatMap fun head => + (finiteAssignments M (fun i => choices i.succ)).map + fun tail => (Fin.cons head tail : Fin (M + 1) → α)).length = + entries.length * (finiteAssignments M (fun i => choices i.succ)).length := by + induction entries with + | nil => simp + | cons head rest ih => + simp only [List.flatMap_cons, List.length_append, List.length_map, List.length_cons, ih] + ring + rw [finiteAssignments, hflat, pow_succ] + nlinarith [hchoices 0] + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Probability/FiniteBitPolynomial.lean b/lean/OAI/Combinatorics/EditApproximation/Probability/FiniteBitPolynomial.lean new file mode 100644 index 0000000000000000000000000000000000000000..124823b3e73c608660c63ada65b59b45c9b63dde --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Probability/FiniteBitPolynomial.lean @@ -0,0 +1,80 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryAffineGuard + +namespace OAI + +/-! A structural polynomial bound for finite Boolean arithmetic loops. +The expression language includes only operations whose magnitude is bounded +by a fixed power of a common input bound. -/ + +namespace EditApproximation + +inductive FiniteBitPolynomial (ι : Type*) where + | input (i : ι) + | constant (n : ℕ) + | add (a b : FiniteBitPolynomial ι) + | mul (a b : FiniteBitPolynomial ι) + | pow (a : FiniteBitPolynomial ι) (n : ℕ) + | maximum (a b : FiniteBitPolynomial ι) + | minimum (a b : FiniteBitPolynomial ι) + | bitLength (a : FiniteBitPolynomial ι) + +namespace FiniteBitPolynomial + +instance {ι : Type*} (n : ℕ) : OfNat (FiniteBitPolynomial ι) n := ⟨.constant n⟩ +instance {ι : Type*} : Add (FiniteBitPolynomial ι) := ⟨.add⟩ +instance {ι : Type*} : Mul (FiniteBitPolynomial ι) := ⟨.mul⟩ +instance {ι : Type*} : Pow (FiniteBitPolynomial ι) ℕ := ⟨.pow⟩ + +def eval {ι : Type*} (env : ι → ℕ) : FiniteBitPolynomial ι → ℕ + | .input i => env i + | .constant n => n + | .add a b => a.eval env + b.eval env + | .mul a b => a.eval env * b.eval env + | .pow a n => a.eval env ^ n + | .maximum a b => max (a.eval env) (b.eval env) + | .minimum a b => min (a.eval env) (b.eval env) + | .bitLength a => Nat.size (a.eval env) + +def degree {ι : Type*} : FiniteBitPolynomial ι → ℕ + | .input _ => 1 + | .constant n => Nat.size n + | .add a b => max a.degree b.degree + 1 + | .mul a b => a.degree + b.degree + | .pow a n => a.degree * n + | .maximum a b => max a.degree b.degree + | .minimum a b => max a.degree b.degree + | .bitLength a => a.degree + +theorem eval_le_pow {ι : Type*} (p : FiniteBitPolynomial ι) (env : ι → ℕ) + (S : ℕ) (hS : 2 ≤ S) (henv : ∀ i, env i ≤ S) : + p.eval env ≤ S ^ p.degree := by + induction p with + | input i => simpa only [eval, degree, pow_one] using henv i + | constant n => + exact (Nat.lt_size_self n).le.trans (Nat.pow_le_pow_left hS _) + | add a b ha hb => + have ha' := ha.trans (Nat.pow_le_pow_right (by omega : 0 < S) (Nat.le_max_left a.degree b.degree)) + have hb' := hb.trans (Nat.pow_le_pow_right (by omega : 0 < S) (Nat.le_max_right a.degree b.degree)) + change a.eval env + b.eval env ≤ S ^ (max a.degree b.degree + 1) + calc + _ ≤ 2 * S ^ max a.degree b.degree := by omega + _ ≤ S * S ^ max a.degree b.degree := Nat.mul_le_mul_right _ hS + _ = _ := (pow_succ' S _).symm + | mul a b ha hb => + exact (Nat.mul_le_mul ha hb).trans_eq (pow_add S a.degree b.degree).symm + | pow a n ha => + exact (Nat.pow_le_pow_left ha n).trans_eq (pow_mul S a.degree n).symm + | maximum a b ha hb => + exact max_le + (ha.trans (Nat.pow_le_pow_right (by omega) (Nat.le_max_left a.degree b.degree))) + (hb.trans (Nat.pow_le_pow_right (by omega) (Nat.le_max_right a.degree b.degree))) + | minimum a b ha _ => + exact (Nat.min_le_left _ _).trans + (ha.trans (Nat.pow_le_pow_right (by omega) (Nat.le_max_left a.degree b.degree))) + | bitLength a ha => + exact (Nat.size_le.mpr Nat.lt_two_pow_self).trans ha + +end FiniteBitPolynomial +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Probability/FiniteBufferRanges.lean b/lean/OAI/Combinatorics/EditApproximation/Probability/FiniteBufferRanges.lean new file mode 100644 index 0000000000000000000000000000000000000000..8fd54f0326c1d23db9e711a32dd8a3b3b6b84aaf --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Probability/FiniteBufferRanges.lean @@ -0,0 +1,56 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryGatheredValues + +namespace OAI + +/-! The default-zero finite buffers preserve the nonnegative bounds of +paired initial/history coordinates when the initial buffer covers them. -/ + +namespace EditApproximation + +theorem finiteAnswerTable_eq_zero_of_not_mem {κ : Type*} [DecidableEq κ] + (keys : List κ) (values : List ℚ) (query : κ) (hq : query ∉ keys) : + finiteAnswerTable keys values query = 0 := by + induction keys generalizing values with + | nil => rfl + | cons key keys ih => + cases values with + | nil => rfl + | cons value values => + have hk : query ≠ key := fun he => hq (List.mem_cons.mpr (Or.inl he)) + have ht : query ∉ keys := fun he => hq (List.mem_cons_of_mem key he) + simpa only [finiteAnswerTable, ite_eq_right hk] using ih values ht + +theorem finiteAnswerTable_nonneg {κ : Type*} [DecidableEq κ] + (keys : List κ) (values : List ℚ) (query : κ) (hv : ∀ value ∈ values, 0 ≤ value) : + 0 ≤ finiteAnswerTable keys values query := by + induction keys generalizing values with + | nil => exact le_rfl + | cons key keys ih => + cases values with + | nil => exact le_rfl + | cons value values => + unfold finiteAnswerTable + split_ifs + · exact hv value List.mem_cons_self + · exact ih values (fun v h => hv v (List.mem_cons_of_mem _ h)) + +theorem finiteAnswerTable_map_le_of_subset {κ : Type*} [DecidableEq κ] + (keys initialKeys : List κ) (history initial : κ → ℚ) + (hkeys : ∀ key ∈ keys, key ∈ initialKeys) + (hi : ∀ key, 0 ≤ initial key) + (hle : ∀ key, history key ≤ initial key) (query : κ) : + finiteAnswerTable keys (keys.map history) query ≤ + finiteAnswerTable initialKeys (initialKeys.map initial) query := by + by_cases hq : query ∈ keys + · rw [finiteAnswerTable_map keys history query hq, + finiteAnswerTable_map initialKeys initial query (hkeys query hq)] + exact hle query + · rw [finiteAnswerTable_eq_zero_of_not_mem keys _ query hq] + apply finiteAnswerTable_nonneg + intro value hv + obtain ⟨key, _, rfl⟩ := List.mem_map.mp hv + exact hi key + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Probability/FiniteEnumerationWork.lean b/lean/OAI/Combinatorics/EditApproximation/Probability/FiniteEnumerationWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..ddb3ba7c6f393a3bc1d3aba1ee3033ebbaa96b10 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Probability/FiniteEnumerationWork.lean @@ -0,0 +1,161 @@ +import OAI.Combinatorics.EditApproximation.Numerics.VectorOptimizerWork +import OAI.Combinatorics.EditApproximation.Geometry.WideActions +import OAI.Combinatorics.EditApproximation.Geometry.BandDimension +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Literal finite enumeration with counters. Each callback is evaluated +once and its returned work is charged; list cells and copied output cells +are charged separately. -/ + +namespace EditApproximation + + + +theorem arithmeticMapWithWork_value {α β : Type*} (f : α → β × ℕ) (values : List α) : + (arithmeticMapWithWork f values).1 = values.map (fun a => (f a).1) := by + induction values with + | nil => rfl + | cons a rest ih => simp only [arithmeticMapWithWork, ih, List.map_cons] + +theorem arithmeticMapWithWork_cost {α β : Type*} (f : α → β × ℕ) (values : List α) + (C : ℕ) (hC : ∀ a ∈ values, (f a).2 ≤ C) : + (arithmeticMapWithWork f values).2 ≤ values.length * (C + 3) := by + induction values with + | nil => simp only [arithmeticMapWithWork, List.length_nil, Nat.zero_mul, le_refl] + | cons a rest ih => + have ha := hC a List.mem_cons_self + have htail := ih (fun b hb => hC b (List.mem_cons_of_mem a hb)) + simp only [arithmeticMapWithWork, List.length_cons] + nlinarith only [ha, htail] + + + +theorem arithmeticFlatMapWithWork_value {α β : Type*} (f : α → List β × ℕ) (values : List α) : + (arithmeticFlatMapWithWork f values).1 = values.flatMap (fun a => (f a).1) := by + induction values with + | nil => rfl + | cons a rest ih => simp only [arithmeticFlatMapWithWork, ih, List.flatMap_cons] + +theorem arithmeticFlatMapWithWork_cost {α β : Type*} (f : α → List β × ℕ) (values : List α) + (C L : ℕ) (hC : ∀ a ∈ values, (f a).2 ≤ C) (hL : ∀ a ∈ values, (f a).1.length ≤ L) : + (arithmeticFlatMapWithWork f values).2 ≤ values.length * (C + L + 3) := by + induction values with + | nil => simp only [arithmeticFlatMapWithWork, List.length_nil, Nat.zero_mul, le_refl] + | cons a rest ih => + have ha := hC a List.mem_cons_self + have hla := hL a List.mem_cons_self + have htail := ih (fun b hb => hC b (List.mem_cons_of_mem a hb)) + (fun b hb => hL b (List.mem_cons_of_mem a hb)) + simp only [arithmeticFlatMapWithWork, List.length_cons] + nlinarith only [ha, hla, htail] + +/-- Each complete assignment is stored in an array, so later coordinate +access is constant time. The recursive tail is constructed once. -/ + + +theorem materializedAssignmentsWithWork_value {α : Type*} (M : ℕ) (choices : Fin M → List α) : + ((materializedAssignmentsWithWork M choices).1.map Vector.get) = finiteAssignments M choices := by + have hget {m : ℕ} (f : Fin m → α) : (Vector.ofFn f).get = f := funext (vector_get_ofFn f) + induction M with + | zero => simp only [materializedAssignmentsWithWork, finiteAssignments, List.map_cons, + List.map_nil, hget] + | succ M ih => + simp only [materializedAssignmentsWithWork, arithmeticFlatMapWithWork_value, + arithmeticMapWithWork_value, List.map_flatMap, List.map_map, Function.comp_def, hget] + unfold finiteAssignments + apply List.flatMap_congr + intro head _ + rw [← ih (fun i => choices i.succ), List.map_map] + rfl + +theorem materializedAssignmentsWithWork_cost {α : Type*} (M K : ℕ) + (choices : Fin M → List α) (hchoices : ∀ i, (choices i).length ≤ K) : + (materializedAssignmentsWithWork M choices).2 ≤ + (M + 1) * (6 * M + 10) * (K + 1) ^ (M + 1) := by + induction M with + | zero => + simp only [materializedAssignmentsWithWork, Nat.zero_add, Nat.mul_zero, pow_one, Nat.one_mul] + omega + | succ M ih => + let previous := materializedAssignmentsWithWork M (fun i => choices i.succ) + have hprevious := ih (fun i => choices i.succ) (fun i => hchoices i.succ) + have hlength : previous.1.length ≤ K ^ M := by + have heq := congrArg List.length + (materializedAssignmentsWithWork_value M (fun i => choices i.succ)) + simp only [List.length_map] at heq + exact heq.trans_le (finiteAssignments_length_le M K _ (fun i => hchoices i.succ)) + have hmap (head : α) : + (arithmeticMapWithWork (fun tail : Vector α M => + (Vector.ofFn (Fin.cons head tail.get), 3 * (M + 1))) previous.1).2 ≤ + previous.1.length * (3 * (M + 1) + 3) := + arithmeticMapWithWork_cost _ _ _ (fun _ _ => le_rfl) + have hmaplength (head : α) : + (arithmeticMapWithWork (fun tail : Vector α M => + (Vector.ofFn (Fin.cons head tail.get), 3 * (M + 1))) previous.1).1.length ≤ + previous.1.length := by + rw [arithmeticMapWithWork_value, List.length_map] + have hflat := arithmeticFlatMapWithWork_cost (fun head => + arithmeticMapWithWork (fun tail : Vector α M => + (Vector.ofFn (Fin.cons head tail.get), 3 * (M + 1))) previous.1) (choices 0) + (previous.1.length * (3 * (M + 1) + 3)) previous.1.length + (fun head _ => hmap head) (fun head _ => hmaplength head) + have hchoice := hchoices 0 + have hL : previous.1.length ≤ (K + 1) ^ M := + hlength.trans (Nat.pow_le_pow_left (by omega) M) + have hscale : K * (K + 1) ^ M ≤ (K + 1) ^ (M + 1) := by + rw [pow_succ] + nlinarith + have hZ : K + 1 ≤ (K + 1) ^ (M + 1) := Nat.le_pow (by omega) + have hexp : (K + 1) ^ (M + 1) ≤ (K + 1) ^ (M + 2) := + Nat.pow_le_pow_right (by omega) (by omega) + have hexpanded : + (arithmeticFlatMapWithWork (fun head => + arithmeticMapWithWork (fun tail : Vector α M => + (Vector.ofFn (Fin.cons head tail.get), 3 * (M + 1))) previous.1) (choices 0)).2 ≤ + (3 * M + 11) * (K + 1) ^ (M + 1) := by + apply hflat.trans + calc + _ ≤ K * ((K + 1) ^ M * (3 * (M + 1) + 3) + (K + 1) ^ M + 3) := + Nat.mul_le_mul hchoice (by nlinarith only [hL]) + _ = (3 * M + 7) * (K * (K + 1) ^ M) + 3 * K := by ring + _ ≤ (3 * M + 7) * (K + 1) ^ (M + 1) + 3 * K := + Nat.add_le_add_right (Nat.mul_le_mul_left _ hscale) _ + _ ≤ _ := by nlinarith only [hZ] + change previous.2 + _ + 1 ≤ _ + have hcoefficient : + (M + 1) * (6 * M + 10) + (3 * M + 11) + 1 ≤ (M + 2) * (6 * (M + 1) + 10) := by + nlinarith + have hone : 1 ≤ (K + 1) ^ (M + 1) := Nat.one_le_pow _ _ (by omega) + calc + _ ≤ ((M + 1) * (6 * M + 10) + (3 * M + 11) + 1) * (K + 1) ^ (M + 1) := by + dsimp only [previous] at * + nlinarith only [hprevious, hexpanded, hone] + _ ≤ (M + 2) * (6 * (M + 1) + 10) * (K + 1) ^ (M + 2) := + Nat.mul_le_mul hcoefficient hexp + _ = _ := by rfl + +def materializedWideActionsWithWork {nx ny : ℕ} (M : ℕ) (parent : TargetInterval nx) + (r : TargetInterval ny) (b P : ℕ) : List (Vector (TargetInterval ny) M) × ℕ := + materializedAssignmentsWithWork M (wideChildStateList parent r b P) + +theorem materializedWideActionsWithWork_value {nx ny : ℕ} (M : ℕ) (parent : TargetInterval nx) + (r : TargetInterval ny) (b P : ℕ) : + ((materializedWideActionsWithWork M parent r b P).1.map Vector.get) = + wideActionList M parent r b P := + materializedAssignmentsWithWork_value M _ + +/-- Cartesian-product construction after the endpoint lists are present. +Each returned action supports direct indexed reads from its stored array. -/ +theorem materializedWideActionsWithWork_cost {nx ny : ℕ} (M : ℕ) (parent : TargetInterval nx) + (r : TargetInterval ny) (b P : ℕ) (hP : 0 < P) : + (materializedWideActionsWithWork M parent r b P).2 ≤ + (M + 1) * (6 * M + 10) * ((40 * P + 2) ^ 2 + 1) ^ (M + 1) := + materializedAssignmentsWithWork_cost M ((40 * P + 2) ^ 2) _ + (wideChildStateList_length_le parent r hP) + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Probability/FiniteKeyRestriction.lean b/lean/OAI/Combinatorics/EditApproximation/Probability/FiniteKeyRestriction.lean new file mode 100644 index 0000000000000000000000000000000000000000..f856475dbbc9b03bd307f792ac80278b214f37eb --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Probability/FiniteKeyRestriction.lean @@ -0,0 +1,74 @@ +import Mathlib + +namespace OAI + +/-! Restricting independent finite key streams preserves their exact +product law. Unused keys need not be allocated by a lazy implementation. -/ + +namespace EditApproximation + +open MeasureTheory ProbabilityTheory + +theorem finite_pi_restrict_map {ι κ : Type*} [Fintype ι] [Fintype κ] + {X : ι → Type*} [∀ i, MeasurableSpace (X i)] + (mu : ∀ i, Measure (X i)) [∀ i, IsProbabilityMeasure (mu i)] + (key : κ → ι) (hinjective : Function.Injective key) : + (Measure.pi mu).map (fun draw k => draw (key k)) = + Measure.pi (fun k => mu (key k)) := by + have hindependent : iIndepFun (fun i (draw : ∀ j, X j) => draw i) (Measure.pi mu) := + iIndepFun_pi (fun _ => measurable_id.aemeasurable) + have hrestricted := hindependent.precomp hinjective + have hmap := hrestricted.map_fun_eq_pi_map + (fun k => (measurable_pi_apply (key k)).aemeasurable) + simpa only [(measurePreserving_eval mu _).map_eq] using hmap + +theorem finite_pi_restrict_image_map {ι κ : Type*} [Fintype ι] [Fintype κ] + {X : ι → Type*} [∀ i, MeasurableSpace (X i)] + {Y : κ → Type*} [∀ k, MeasurableSpace (Y k)] + (mu : ∀ i, Measure (X i)) [∀ i, IsProbabilityMeasure (mu i)] + (key : κ → ι) (hinjective : Function.Injective key) + (image : ∀ k, X (key k) → Y k) (himage : ∀ k, Measurable (image k)) : + (Measure.pi mu).map (fun draw k => image k (draw (key k))) = + Measure.pi (fun k => (mu (key k)).map (image k)) := by + have hrestrict := finite_pi_restrict_map mu key hinjective + have hproject : Measurable (fun draw : ∀ i, X i => fun k => draw (key k)) := + Measurable.of_eval (fun k => measurable_pi_apply (key k)) + have htransform : Measurable (fun draw : ∀ k, X (key k) => fun k => image k (draw k)) := + Measurable.of_eval (fun k => (himage k).comp (measurable_pi_apply k)) + refine (Measure.map_map htransform hproject).symm.trans ?_ + rw [hrestrict] + exact Measure.pi_map_pi (fun k => (himage k).aemeasurable) + +theorem finite_uniform_array_cast (R n m : ℕ) [NeZero n] [NeZero m] (h : n = m) : + (Measure.pi (fun _ : Fin R => (PMF.uniformOfFintype (Fin n)).toMeasure)).map + (fun draw t => Fin.cast h (draw t)) = + Measure.pi (fun _ : Fin R => (PMF.uniformOfFintype (Fin m)).toMeasure) := by + subst m + simp only [Fin.cast_refl, id_eq, Measure.map_id'] + +/-- The accepted finite sampler outputs can be keyed by a larger bounded +universe. Restriction and the range equalities give the original independent +time arrays exactly. -/ +theorem finite_uniform_arrays_restrict_cast {ι κ : Type*} [Fintype ι] [Fintype κ] + (R : ℕ) (n : ι → ℕ) (m : κ → ℕ) + [∀ i, NeZero (n i)] [∀ k, NeZero (m k)] + (key : κ → ι) (hinjective : Function.Injective key) + (hrange : ∀ k, n (key k) = m k) : + (Measure.pi (fun i => Measure.pi (fun _ : Fin R => + (PMF.uniformOfFintype (Fin (n i))).toMeasure))).map + (fun draw k t => Fin.cast (hrange k) (draw (key k) t)) = + Measure.pi (fun k => Measure.pi (fun _ : Fin R => + (PMF.uniformOfFintype (Fin (m k))).toMeasure)) := by + have hmap := finite_pi_restrict_image_map + (fun i => Measure.pi (fun _ : Fin R => (PMF.uniformOfFintype (Fin (n i))).toMeasure)) + key hinjective + (fun k (draw : Fin R → Fin (n (key k))) t => Fin.cast (hrange k) (draw t)) + (fun _ => measurable_of_finite _) + refine hmap.trans ?_ + congr 1 + funext k + exact finite_uniform_array_cast R (n (key k)) (m k) (hrange k) + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Probability/FiniteProductWork.lean b/lean/OAI/Combinatorics/EditApproximation/Probability/FiniteProductWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..3f12109a64c447bed8847ae51ff00b46d246aecb --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Probability/FiniteProductWork.lean @@ -0,0 +1,76 @@ +import OAI.Combinatorics.EditApproximation.Probability.RejectionSelectedCost + +namespace OAI + +/-! The executed sampler law supports both selected rejection work and +work depending only on the accepted finite draws. -/ + +namespace EditApproximation +open MeasureTheory + + theorem finite_outer_integrable {α β : Type*} [Fintype α] [Countable β] + [MeasurableSpace α] [MeasurableSingletonClass α] + [MeasurableSpace β] [MeasurableSingletonClass β] + (μ : Measure α) [IsFiniteMeasure μ] (ν : Measure β) [SFinite ν] + (f : α × β → ℝ) (hsections : ∀ a, Integrable (fun b => f (a, b)) ν) : + Integrable f (μ.prod ν) := by + apply (integrable_prod_iff (measurable_of_countable f).aestronglyMeasurable).2 + exact ⟨Filter.Eventually.of_forall hsections, Integrable.of_finite⟩ + + theorem finite_outer_expected_le {α β : Type*} [Fintype α] [Countable β] + [MeasurableSpace α] [MeasurableSingletonClass α] + [MeasurableSpace β] [MeasurableSingletonClass β] + (μ : Measure α) [IsProbabilityMeasure μ] (ν : Measure β) [SFinite ν] + (f : α × β → ℝ) (hsections : ∀ a, Integrable (fun b => f (a, b)) ν) + (budget : ℝ) (hbudget : ∀ a, (∫ b, f (a, b) ∂ν) ≤ budget) : + (∫ outcome, f outcome ∂μ.prod ν) ≤ budget := by + rw [integral_prod f (finite_outer_integrable μ ν f hsections)] + calc + _ ≤ ∫ _ : α, budget ∂μ := integral_mono Integrable.of_finite (integrable_const _) hbudget + _ = _ := by simp + +section Accepted +variable {α ι : Type*} [Fintype α] [Fintype ι] + [MeasurableSpace α] [MeasurableSingletonClass α] + (range : ι → ℕ) [∀ i, NeZero (range i)] + (μ : Measure α) [IsFiniteMeasure μ] + + def rejectionProductAccepted (outcome : α × RejectionRuntimeArray range) : α × (∀ i, Fin (range i)) := + (outcome.1, outcome.2.2) + +omit [Fintype α] [Fintype ι] [MeasurableSingletonClass α] [∀ i, NeZero (range i)] in + theorem rejectionProductAccepted_measurable : Measurable (rejectionProductAccepted (α := α) range) := + measurable_fst.prodMk (measurable_snd.comp measurable_snd) + +omit [MeasurableSingletonClass α] [IsFiniteMeasure μ] in + theorem rejectionProductAccepted_law : + (μ.prod (rejectionRuntimeArrayLaw range)).map (rejectionProductAccepted range) = + μ.prod (rejectionAcceptedLaw range) := by + change (μ.prod _).map (Prod.map id Prod.snd) = _ + rw [← Measure.map_prod_map _ _ measurable_id measurable_snd, Measure.map_id, + rejectionRuntimeArrayLaw_accepted] + +omit [IsFiniteMeasure μ] in + theorem rejectionProductWork_integral (f : α × (∀ i, Fin (range i)) → ℝ) : + (∫ outcome, f (rejectionProductAccepted range outcome) + ∂μ.prod (rejectionRuntimeArrayLaw range)) = ∫ outcome, f outcome ∂μ.prod (rejectionAcceptedLaw range) := by + rw [← rejectionProductAccepted_law range μ] + exact (integral_map (rejectionProductAccepted_measurable range).aemeasurable + (measurable_of_finite f).aestronglyMeasurable).symm + +omit [IsFiniteMeasure μ] in + theorem rejectionProductWork_expected_le [IsProbabilityMeasure μ] + (f : α × (∀ i, Fin (range i)) → ℝ) (budget : ℝ) + (hbudget : ∀ draw, (∫ a, f (a, draw) ∂μ) ≤ budget) : + (∫ outcome, f (rejectionProductAccepted range outcome) + ∂μ.prod (rejectionRuntimeArrayLaw range)) ≤ budget := by + rw [rejectionProductWork_integral range μ f, integral_prod_symm f Integrable.of_finite] + calc + _ ≤ ∫ _ : (∀ i, Fin (range i)), budget ∂rejectionAcceptedLaw range := + integral_mono Integrable.of_finite (integrable_const _) hbudget + _ = _ := by simp + +end Accepted +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Probability/FiniteQueryCostOrder.lean b/lean/OAI/Combinatorics/EditApproximation/Probability/FiniteQueryCostOrder.lean new file mode 100644 index 0000000000000000000000000000000000000000..2ed9bf35727a1c04037895604d4e2d265a249176 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Probability/FiniteQueryCostOrder.lean @@ -0,0 +1,27 @@ +import OAI.Combinatorics.EditApproximation.Geometry.GlobalQueryCost + +namespace OAI + +namespace EditApproximation.FiniteQuery + +theorem cost_mono_weights {ι : Type*} (oracle : ι → ℚ) (program : FiniteQuery ι) + (left right : ι → ℕ) (hle : ∀ key, left key ≤ right key) : + program.cost oracle left ≤ program.cost oracle right := by + induction program with + | done result => exact le_rfl + | read key next ih => exact Nat.add_le_add (hle key) (ih (oracle key)) + +theorem cost_zero {ι : Type*} (oracle : ι → ℚ) (program : FiniteQuery ι) : + program.cost oracle (fun _ => 0) = 0 := by + induction program with + | done result => rfl + | read key next ih => simpa only [cost, Nat.zero_add] using ih (oracle key) + +theorem cost_eq_zero_of_keys {ι : Type*} (oracle : ι → ℚ) (program : FiniteQuery ι) + (weight : ι → ℕ) (hzero : ∀ key ∈ program.keys oracle, weight key = 0) : + program.cost oracle weight = 0 := + (cost_congr_weights oracle program weight (fun _ => 0) hzero).trans (cost_zero oracle program) + +end EditApproximation.FiniteQuery + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Probability/FiniteQueryRestriction.lean b/lean/OAI/Combinatorics/EditApproximation/Probability/FiniteQueryRestriction.lean new file mode 100644 index 0000000000000000000000000000000000000000..6b759aec35ce030f51e18e2a007a800e7280e60f --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Probability/FiniteQueryRestriction.lean @@ -0,0 +1,90 @@ +import OAI.Combinatorics.EditApproximation.Probability.FiniteQueryWork +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Restriction of adaptive read programs to a proved finite request domain. +The restriction visits the same reads whenever the original execution stays +in that domain. It does not enumerate the domain. -/ + +namespace EditApproximation.FiniteQuery + + + + theorem mapKeys_id {ι : Type*} (program : FiniteQuery ι) : mapKeys id program = program := by + induction program with + | done result => rfl + | read key next ih => + simp only [mapKeys, id_eq] + congr + funext answer + exact ih answer + + + theorem mapKeys_value {ι κ : Type*} (f : ι → κ) (oracle : κ → ℚ) (program : FiniteQuery ι) : + (mapKeys f program).value oracle = program.value (oracle ∘ f) := by + induction program with + | done result => rfl + | read key next ih => exact ih (oracle (f key)) + + theorem mapKeys_cost {ι κ : Type*} (f : ι → κ) (oracle : κ → ℚ) (weight : κ → ℕ) + (program : FiniteQuery ι) : + (mapKeys f program).cost oracle weight = program.cost (oracle ∘ f) (weight ∘ f) := by + induction program with + | done result => rfl + | read key next ih => exact congrArg (fun rest => weight (f key) + rest) (ih (oracle (f key))) + + theorem mapKeys_keys {ι κ : Type*} (f : ι → κ) (oracle : κ → ℚ) (program : FiniteQuery ι) : + (mapKeys f program).keys oracle = (program.keys (oracle ∘ f)).map f := by + induction program with + | done result => rfl + | read key next ih => exact congrArg (List.cons (f key)) (ih (oracle (f key))) + + + + theorem restrict_value {ι : Type*} (P : ι → Prop) [DecidablePred P] + (oracle : ι → ℚ) (program : FiniteQuery ι) + (hvalid : ∀ key ∈ program.keys oracle, P key) : + (restrict P program).value (fun key => oracle key.val) = program.value oracle := by + induction program with + | done result => rfl + | read key next ih => + have hk : P key := hvalid key (by simp only [keys, List.mem_cons, true_or]) + have hnext : ∀ other ∈ (next (oracle key)).keys oracle, P other := by + intro other hother + exact hvalid other (List.mem_cons_of_mem key hother) + simpa only [restrict, dite_eq_left hk, value] using ih (oracle key) hnext + + theorem restrict_cost {ι : Type*} (P : ι → Prop) [DecidablePred P] + (oracle : ι → ℚ) (weight : ι → ℕ) (program : FiniteQuery ι) + (hvalid : ∀ key ∈ program.keys oracle, P key) : + (restrict P program).cost (fun key => oracle key.val) (fun key => weight key.val) = + program.cost oracle weight := by + induction program with + | done result => rfl + | read key next ih => + have hk : P key := hvalid key (by simp only [keys, List.mem_cons, true_or]) + have hnext : ∀ other ∈ (next (oracle key)).keys oracle, P other := by + intro other hother + exact hvalid other (List.mem_cons_of_mem key hother) + simpa only [restrict, dite_eq_left hk, cost] using + congrArg (fun rest => weight key + rest) (ih (oracle key) hnext) + + theorem restrict_keys {ι : Type*} (P : ι → Prop) [DecidablePred P] + (oracle : ι → ℚ) (program : FiniteQuery ι) + (hvalid : ∀ key ∈ program.keys oracle, P key) : + ((restrict P program).keys (fun key => oracle key.val)).map Subtype.val = program.keys oracle := by + induction program with + | done result => rfl + | read key next ih => + have hk : P key := hvalid key (by simp only [keys, List.mem_cons, true_or]) + have hnext : ∀ other ∈ (next (oracle key)).keys oracle, P other := by + intro other hother + exact hvalid other (List.mem_cons_of_mem key hother) + simpa only [restrict, dite_eq_left hk, keys, List.map_cons] using + congrArg (List.cons key) (ih (oracle key) hnext) + +end EditApproximation.FiniteQuery + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Probability/FiniteQueryWork.lean b/lean/OAI/Combinatorics/EditApproximation/Probability/FiniteQueryWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..00c852b3d18ce3f0e14d1644b7415ee6c4903a54 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Probability/FiniteQueryWork.lean @@ -0,0 +1,84 @@ +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalWarmupQuery +import OAI.Combinatorics.EditApproximation.Geometry.RankedMemoWork + +namespace OAI + +/-! Exact read costs for the finite query combinators used in warmup +and refinement. In particular, a collected value is computed once and +is reused by the continuation's local arithmetic. -/ + +namespace EditApproximation.FiniteQuery + +theorem keys_bind {ι : Type*} (oracle : ι → ℚ) + (program : FiniteQuery ι) (next : ℚ → FiniteQuery ι) : + (bind program next).keys oracle = program.keys oracle ++ + (next (program.value oracle)).keys oracle := by + induction program with + | done result => rfl + | read key continuation ih => + simpa only [bind, keys, value, List.cons_append] using + congrArg (List.cons key) (ih (oracle key)) + +theorem keys_collect {ι κ : Type*} (oracle : ι → ℚ) + (reader : κ → FiniteQuery ι) (inputs : List κ) (next : List ℚ → FiniteQuery ι) : + (collect reader inputs next).keys oracle = + inputs.flatMap (fun input => (reader input).keys oracle) ++ + (next (inputs.map fun input => (reader input).value oracle)).keys oracle := by + induction inputs generalizing next with + | nil => rfl + | cons input inputs ih => + simp only [collect, keys_bind, ih, List.flatMap_cons, List.map_cons, List.append_assoc] + +theorem keys_all_collect {ι κ : Type*} (oracle : ι → ℚ) (predicate : ι → Prop) + (reader : κ → FiniteQuery ι) (inputs : List κ) (next : List ℚ → FiniteQuery ι) + (hreader : ∀ input ∈ inputs, ∀ key ∈ (reader input).keys oracle, predicate key) + (hnext : ∀ values key, key ∈ (next values).keys oracle → predicate key) : + ∀ key ∈ (collect reader inputs next).keys oracle, predicate key := by + rw [keys_collect] + intro key hkey + rcases List.mem_append.mp hkey with hreaderKey | hnextKey + · obtain ⟨input, hi, hk⟩ := List.mem_flatMap.mp hreaderKey + exact hreader input hi key hk + · exact hnext _ key hnextKey + +theorem cost_bind {ι : Type*} (oracle : ι → ℚ) (weight : ι → ℕ) + (program : FiniteQuery ι) (next : ℚ → FiniteQuery ι) : + (bind program next).cost oracle weight = program.cost oracle weight + + (next (program.value oracle)).cost oracle weight := by + induction program with + | done result => simp only [bind, cost, value, Nat.zero_add] + | read key continuation ih => + simp only [bind, cost, value, ih, Nat.add_assoc] + +theorem cost_collect {ι κ : Type*} (oracle : ι → ℚ) (weight : ι → ℕ) + (reader : κ → FiniteQuery ι) (keys : List κ) (next : List ℚ → FiniteQuery ι) : + (collect reader keys next).cost oracle weight = + (keys.map fun key => (reader key).cost oracle weight).sum + + (next (keys.map fun key => (reader key).value oracle)).cost oracle weight := by + induction keys generalizing next with + | nil => simp only [collect, List.map_nil, List.sum_nil, Nat.zero_add] + | cons key keys ih => + simp only [collect, cost_bind, ih, List.map_cons, List.sum_cons, Nat.add_assoc] + +theorem keys_length_eq_cost_one {ι : Type*} (oracle : ι → ℚ) (program : FiniteQuery ι) : + (program.keys oracle).length = program.cost oracle (fun _ => 1) := by + rw [cost_eq_sum] + simp only [List.map_const', List.sum_replicate, smul_eq_mul, Nat.mul_one] + +theorem collect_cost_le {ι κ : Type*} (oracle : ι → ℚ) (weight : ι → ℕ) + (reader : κ → FiniteQuery ι) (keys : List κ) (next : List ℚ → FiniteQuery ι) + (readerBound continuationBound : ℕ) + (hreader : ∀ key ∈ keys, (reader key).cost oracle weight ≤ readerBound) + (hnext : (next (keys.map fun key => (reader key).value oracle)).cost oracle weight ≤ + continuationBound) : + (collect reader keys next).cost oracle weight ≤ keys.length * readerBound + continuationBound := by + rw [cost_collect] + apply Nat.add_le_add _ hnext + calc + (keys.map fun key => (reader key).cost oracle weight).sum ≤ + (keys.map fun _ => readerBound).sum := List.sum_le_sum (by simpa using hreader) + _ = keys.length * readerBound := by simp + +end EditApproximation.FiniteQuery + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Probability/FiniteResampling.lean b/lean/OAI/Combinatorics/EditApproximation/Probability/FiniteResampling.lean new file mode 100644 index 0000000000000000000000000000000000000000..0450a06a40f324feaaf51251b405050fc79cba32 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Probability/FiniteResampling.lean @@ -0,0 +1,99 @@ +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalParentDraw + +namespace OAI + +/-! Exact coordinate-refresh identities for finite product probability laws. -/ + +namespace EditApproximation + +open Finset MeasureTheory ProbabilityTheory + +section FiniteProduct + +variable {ι : Type*} [Fintype ι] [DecidableEq ι] + {X : ι → Type*} [∀ i, Fintype (X i)] [∀ i, MeasurableSpace (X i)] + [∀ i, MeasurableSingletonClass (X i)] + (μ : ∀ i, Measure (X i)) [∀ i, IsProbabilityMeasure (μ i)] + +/-- Refreshing one coordinate with its own independent law preserves the +complete finite product law. -/ +theorem finite_pi_update_map (i : ι) : + ((Measure.pi μ).prod (μ i)).map + (fun pair : (∀ j, X j) × X i => Function.update pair.1 i pair.2) = Measure.pi μ := by + apply Eq.symm + apply Measure.pi_eq + intro sets hsets + have hpreimage : (fun pair : (∀ j, X j) × X i => Function.update pair.1 i pair.2) ⁻¹' + Set.univ.pi sets = (Set.univ.pi (Function.update sets i Set.univ)) ×ˢ sets i := by + ext pair + constructor + · intro h + constructor + · intro j _ + by_cases hji : j = i + · subst j + simp only [Function.update_self, Set.mem_univ] + · simpa only [Function.update_of_ne hji] using h j (Set.mem_univ j) + · simpa only [Function.update_self] using h i (Set.mem_univ i) + · rintro ⟨hold, hfresh⟩ j _ + by_cases hji : j = i + · subst j + simpa only [Function.update_self] using hfresh + · simpa only [Function.update_of_ne hji] using hold j (Set.mem_univ j) + rw [Measure.map_apply (measurable_of_finite _) (MeasurableSet.univ_pi hsets), + hpreimage, Measure.prod_prod, Measure.pi_pi] + rw [← prod_erase_mul (s := univ) (fun j => μ j (Function.update sets i Set.univ j)) (mem_univ i), + ← prod_erase_mul (s := univ) (fun j => μ j (sets j)) (mem_univ i)] + simp only [Function.update_self, measure_univ, mul_one] + congr 1 + apply prod_congr rfl + intro j hj + simp only [Function.update_of_ne (ne_of_mem_erase hj)] + +/-- Integrating a fresh coordinate, then the complete original array, is +exactly integration in the original product law. -/ +theorem finite_pi_integral_update (i : ι) (payoff : (∀ j, X j) → ℝ) : + (∫ original, ∫ fresh, payoff (Function.update original i fresh) ∂μ i ∂Measure.pi μ) = + ∫ original, payoff original ∂Measure.pi μ := by + rw [← integral_prod (fun pair : (∀ j, X j) × X i => + payoff (Function.update pair.1 i pair.2)) (.of_finite)] + have hmap := finite_pi_update_map μ i + have hintegral := integral_map_of_stronglyMeasurable + (μ := (Measure.pi μ).prod (μ i)) + (measurable_of_finite (fun pair : (∀ j, X j) × X i => Function.update pair.1 i pair.2)) + (measurable_of_finite payoff).stronglyMeasurable + rw [hmap] at hintegral + exact hintegral.symm + +/-- Two independent refreshed coordinates provide the local parent law. +The original arrays may still contain their previous values at those keys. -/ +theorem finite_pi_integral_update_pair (i j : ι) (payoff : (∀ k, X k) → ℝ) : + (∫ original, ∫ fresh : X i × X j, + payoff (Function.update (Function.update original i fresh.1) j fresh.2) + ∂(μ i).prod (μ j) ∂Measure.pi μ) = + ∫ original, payoff original ∂Measure.pi μ := by + have hinner original : (∫ fresh : X i × X j, + payoff (Function.update (Function.update original i fresh.1) j fresh.2) ∂(μ i).prod (μ j)) = + ∫ first, ∫ second, payoff (Function.update (Function.update original i first) j second) ∂μ j ∂μ i := + integral_prod _ (.of_finite) + simp_rw [hinner] + rw [finite_pi_integral_update μ i + (fun original => ∫ second, payoff (Function.update original j second) ∂μ j)] + exact finite_pi_integral_update μ j payoff + +/-- A pointwise bound after exact coordinate refresh integrates to the +unconditional bound in the original global product. -/ +theorem finite_pi_integral_bound_of_update_pair (i j : ι) + (payoff budget : (∀ k, X k) → ℝ) + (hbound : ∀ original, (∫ fresh : X i × X j, + payoff (Function.update (Function.update original i fresh.1) j fresh.2) ∂(μ i).prod (μ j)) ≤ + budget original) : + (∫ original, payoff original ∂Measure.pi μ) ≤ ∫ original, budget original ∂Measure.pi μ := by + rw [← finite_pi_integral_update_pair μ i j payoff] + exact integral_mono (.of_finite) (.of_finite) hbound + +end FiniteProduct + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Probability/FiniteSampling.lean b/lean/OAI/Combinatorics/EditApproximation/Probability/FiniteSampling.lean new file mode 100644 index 0000000000000000000000000000000000000000..565777cfa0ecc3fc09a98dd6f68853d994c4fb16 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Probability/FiniteSampling.lean @@ -0,0 +1,147 @@ +import OAI.Combinatorics.EditApproximation.Geometry.PublishedInputs + +namespace OAI + +/-! +# Finite uniform sampling + +The shared group estimator samples child labels uniformly with replacement. +These lemmas use that finite distribution, including its product law; +they do not assume that different group representatives are independent. +-/ + +namespace EditApproximation + +open Finset MeasureTheory ProbabilityTheory + +noncomputable def uniformMean {ι : Type*} [Fintype ι] (value : ι → ℝ) : ℝ := + (∑ i, value i) / Fintype.card ι + +theorem uniform_integral {ι : Type*} [Fintype ι] [Nonempty ι] + [MeasurableSpace ι] [MeasurableSingletonClass ι] (value : ι → ℝ) : + (∫ i, value i ∂(PMF.uniformOfFintype ι).toMeasure) = uniformMean value := by + rw [PMF.integral_eq_sum] + simp only [PMF.uniformOfFintype_apply, ENNReal.toReal_inv, ENNReal.toReal_natCast, + smul_eq_mul, ← mul_sum, uniformMean] + ring + +theorem uniformMean_bounds {ι : Type*} [Fintype ι] [Nonempty ι] + (value : ι → ℝ) {bound : ℝ} (hvalue : ∀ i, 0 ≤ value i ∧ value i ≤ bound) : + 0 ≤ uniformMean value ∧ uniformMean value ≤ bound := by + have hc : (0 : ℝ) < Fintype.card ι := by exact_mod_cast Fintype.card_pos + constructor + · exact div_nonneg (sum_nonneg fun i _ => (hvalue i).1) hc.le + · apply (div_le_iff₀ hc).2 + have hsum := sum_le_sum (s := univ) fun i _ => (hvalue i).2 + simpa only [sum_const, card_univ, nsmul_eq_mul, mul_comm] using hsum + +theorem uniform_centered_bound {ι : Type*} [Fintype ι] [Nonempty ι] + (value : ι → ℝ) {bound : ℝ} (hvalue : ∀ i, 0 ≤ value i ∧ value i ≤ bound) + (i : ι) : |value i - uniformMean value| ≤ bound := by + have hm := uniformMean_bounds value hvalue + exact abs_le.mpr ⟨by linarith [(hvalue i).1], by linarith [(hvalue i).2]⟩ + +theorem uniform_centered_integral {ι : Type*} [Fintype ι] [Nonempty ι] + [MeasurableSpace ι] [MeasurableSingletonClass ι] (value : ι → ℝ) : + (∫ i, (value i - uniformMean value) + ∂(PMF.uniformOfFintype ι).toMeasure) = 0 := by + rw [integral_sub (.of_finite) (integrable_const _), uniform_integral, integral_const] + simp + +theorem uniform_variance_bound {ι : Type*} [Fintype ι] [Nonempty ι] + [MeasurableSpace ι] [MeasurableSingletonClass ι] + (value : ι → ℝ) {bound : ℝ} (hvalue : ∀ i, 0 ≤ value i ∧ value i ≤ bound) : + (∫ i, (value i - uniformMean value) ^ 2 + ∂(PMF.uniformOfFintype ι).toMeasure) ≤ bound * uniformMean value := by + let μ := (PMF.uniformOfFintype ι).toMeasure + have hmean : (∫ i, value i ∂μ) = uniformMean value := uniform_integral value + have hexpand : (∫ i, (value i - uniformMean value) ^ 2 ∂μ) = + (∫ i, value i ^ 2 ∂μ) - (uniformMean value) ^ 2 := by + calc + _ = ∫ i, (value i ^ 2 - 2 * uniformMean value * value i + + (uniformMean value) ^ 2) ∂μ := by congr 1; funext i; ring + _ = _ := by + rw [integral_add (.of_finite) (integrable_const _), + integral_sub (.of_finite) (.of_finite), integral_const_mul, hmean, integral_const] + simp only [probReal_univ, one_smul] + ring + have hsecond : (∫ i, value i ^ 2 ∂μ) ≤ bound * uniformMean value := by + rw [← hmean, ← integral_const_mul] + apply integral_mono (.of_finite) (.of_finite) + intro i + nlinarith [(hvalue i).1, (hvalue i).2] + rw [hexpand] + nlinarith [sq_nonneg (uniformMean value)] + +/-- Actual independent uniform draws, centered and divided by the sample +count. All measurability, centering and variance obligations for Bernstein +are derived from this product distribution. -/ +theorem uniform_sample_average_concentration + {ι : Type*} [Fintype ι] [Nonempty ι] + [MeasurableSpace ι] [MeasurableSingletonClass ι] + (n : ℕ) (hn : 0 < n) (value : ι → ℝ) (bound meanBound deviation : ℝ) + (hbound : 0 < bound) (hmeanBound : 0 < meanBound) (hdev : 0 < deviation) + (hvalue : ∀ i, 0 ≤ value i ∧ value i ≤ bound) + (hmean : uniformMean value ≤ meanBound) + (bernstein : FiniteBernsteinInput + (Measure.pi fun _ : Fin n => (PMF.uniformOfFintype ι).toMeasure)) : + (Measure.pi fun _ : Fin n => (PMF.uniformOfFintype ι).toMeasure).real + {ω | deviation ≤ |(∑ j : Fin n, value (ω j)) / n - uniformMean value|} ≤ + 2 * Real.exp (-(n : ℝ) * deviation ^ 2 / + (2 * bound * meanBound + (2 / 3 : ℝ) * bound * deviation)) := by + let μ := (PMF.uniformOfFintype ι).toMeasure + let X : Fin n → (Fin n → ι) → ℝ := + fun j ω => (value (ω j) - uniformMean value) / n + have hnr : (0 : ℝ) < n := by exact_mod_cast hn + have hindep : iIndepFun X (Measure.pi fun _ : Fin n => μ) := by + exact iIndepFun_pi (μ := fun _ : Fin n => μ) + (X := fun _ i => (value i - uniformMean value) / n) + (fun _ => (measurable_of_finite _).aemeasurable) + have hcenter : ∀ j, (∫ ω, X j ω ∂Measure.pi (fun _ : Fin n => μ)) = 0 := by + intro j + dsimp [X] + rw [integral_comp_eval (μ := fun _ : Fin n => μ) (i := j) + (f := fun i => (value i - uniformMean value) / n) + (measurable_of_finite _).aestronglyMeasurable] + rw [integral_div, uniform_centered_integral, zero_div] + have hbounded : ∀ j, ∀ᵐ ω ∂Measure.pi (fun _ : Fin n => μ), + |X j ω| ≤ bound / n := by + intro j + filter_upwards [] with ω + dsimp [X] + rw [abs_div, abs_of_pos hnr] + exact div_le_div_of_nonneg_right (uniform_centered_bound value hvalue _) hnr.le + have hvariance : (∑ j : Fin n, ∫ ω, (X j ω) ^ 2 + ∂Measure.pi (fun _ : Fin n => μ)) ≤ bound * meanBound / n := by + have hpoint (j : Fin n) : (∫ ω, (X j ω) ^ 2 + ∂Measure.pi (fun _ : Fin n => μ)) ≤ bound * meanBound / n ^ 2 := by + dsimp [X] + rw [integral_comp_eval (μ := fun _ : Fin n => μ) (i := j) + (f := fun i => ((value i - uniformMean value) / n) ^ 2) + (measurable_of_finite _).aestronglyMeasurable] + simp_rw [div_pow] + rw [integral_div] + apply div_le_div_of_nonneg_right _ (sq_nonneg _) + exact (uniform_variance_bound value hvalue).trans + (mul_le_mul_of_nonneg_left hmean hbound.le) + have hsum := sum_le_sum (s := univ) fun j _ => hpoint j + simp only [sum_const, card_univ, Fintype.card_fin, nsmul_eq_mul] at hsum + apply hsum.trans_eq + field_simp + have htail := bernstein n X (bound / n) (bound * meanBound / n) deviation + (div_pos hbound hnr) (div_pos (mul_pos hbound hmeanBound) hnr) hdev hindep + (fun _ => measurable_of_finite _) (fun _ => .of_finite) hcenter hbounded hvariance + have hsum (ω : Fin n → ι) : (∑ j : Fin n, X j ω) = + (∑ j : Fin n, value (ω j)) / n - uniformMean value := by + dsimp [X] + rw [← sum_div, sum_sub_distrib] + simp only [sum_const, card_univ, Fintype.card_fin, nsmul_eq_mul] + field_simp + simp_rw [hsum] at htail + convert htail using 2 + congr 1 + field_simp + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Probability/FiniteSeedFinal.lean b/lean/OAI/Combinatorics/EditApproximation/Probability/FiniteSeedFinal.lean new file mode 100644 index 0000000000000000000000000000000000000000..38f99ba5369dcfb40128b2baa143e38beacb096d --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Probability/FiniteSeedFinal.lean @@ -0,0 +1,87 @@ +import OAI.Combinatorics.EditApproximation.Probability.AdaptiveSeedLaw +import OAI.Combinatorics.EditApproximation.Geometry.Accuracy + +namespace OAI + +/-! The final fresh draw selects the coordinate of the actual incoming seed. +This keeps the dependence of the finite draw type on that table explicit. -/ + +namespace EditApproximation + +open MeasureTheory ProbabilityTheory + +section Final + +variable {Seed : Type*} [Fintype Seed] + [MeasurableSpace Seed] [MeasurableSingletonClass Seed] + {Draw : Seed → Type*} [∀ seed, Finite (Draw seed)] + [∀ seed, MeasurableSpace (Draw seed)] [∀ seed, MeasurableSingletonClass (Draw seed)] + (drawLaw : ∀ seed, Measure (Draw seed)) [∀ seed, IsProbabilityMeasure (drawLaw seed)] + (incoming : Measure Seed) [IsProbabilityMeasure incoming] + +def freshSeedValue (value : ∀ seed, Draw seed → ℝ) + (pair : Seed × (∀ seed, Draw seed)) : ℝ := value pair.1 (pair.2 pair.1) + +theorem freshSeed_bad_probability (good : Seed → Prop) : + (incoming.prod (Measure.pi drawLaw)).real + {pair : Seed × (∀ seed, Draw seed) | ¬ good pair.1} = incoming.real {seed | ¬ good seed} := by + classical + let : Fintype (Seed × (∀ seed, Draw seed)) := Fintype.ofFinite _ + rw [← finite_integral_test (incoming.prod (Measure.pi drawLaw)) (fun pair => ¬ good pair.1)] + rw [integral_prod _ (.of_finite)] + change (∫ seed, (∫ _ : ∀ seed, Draw seed, if ¬ good seed then (1 : ℝ) else 0 + ∂Measure.pi drawLaw) ∂incoming) = _ + simp only [integral_const, probReal_univ, one_smul] + exact finite_integral_test incoming (fun seed => ¬ good seed) + +theorem freshSeed_good_excess (good : Seed → Prop) (value : ∀ seed, Draw seed → ℝ) + (D : ℕ) (ell : ℝ) (hell : 0 < ell) + (hmoment : ∀ seed, good seed → + (∫ draw, max (value seed draw - D) 0 ∂drawLaw seed) ≤ (D : ℝ) / ell) : + (∫ pair, goodExcess {pair : Seed × (∀ seed, Draw seed) | good pair.1} + (freshSeedValue value) D pair ∂incoming.prod (Measure.pi drawLaw)) ≤ (D : ℝ) / ell := by + classical + rw [integral_prod _ (.of_finite)] + have hinner (seed : Seed) : + (∫ draws : ∀ seed, Draw seed, + goodExcess {pair : Seed × (∀ seed, Draw seed) | good pair.1} + (freshSeedValue value) D (seed, draws) ∂Measure.pi drawLaw) ≤ (D : ℝ) / ell := by + by_cases hg : good seed + · simp only [goodExcess, Set.indicator, Set.mem_ofPred_eq, hg, ite_true, + freshSeedValue] + rw [integral_comp_eval (μ := drawLaw) (i := seed) + (f := fun draw => max (value seed draw - D) 0) + (measurable_of_finite _).aestronglyMeasurable] + exact hmoment seed hg + · simp only [goodExcess, Set.indicator, Set.mem_ofPred_eq, hg, ite_false, + integral_zero] + exact div_nonneg (Nat.cast_nonneg _) hell.le + have h := integral_mono (μ := incoming) (.of_finite) (integrable_const _) hinner + simpa only [integral_const, probReal_univ, one_smul] using h + +theorem freshSeed_answer_accuracy (good : Seed → Prop) (value : ∀ seed, Draw seed → ℝ) + {N D : ℕ} {ell epsilon : ℝ} (hDN : D ≤ N) (hD : 0 < D) + (hell : 0 < ell) (hepsilon : 0 < epsilon) (haccuracy : 10 ≤ ell * epsilon) + (hseed : incoming.real {seed | ¬ good seed} ≤ 1 / 10) + (hlower : ∀ seed, good seed → ∀ draw, (D : ℝ) ≤ value seed draw) + (hmoment : ∀ seed, good seed → + (∫ draw, max (value seed draw - D) 0 ∂drawLaw seed) ≤ (D : ℝ) / ell) : + (4 / 5 : ℝ) ≤ (incoming.prod (Measure.pi drawLaw)).real + {pair | D ≤ integerAnswer N (freshSeedValue value pair) ∧ + (integerAnswer N (freshSeedValue value pair) : ℝ) ≤ (1 + epsilon) * D} := by + classical + apply final_answer_accuracy (incoming.prod (Measure.pi drawLaw)) (measurable_of_finite _) + hDN hD hell hepsilon haccuracy + · change (incoming.prod (Measure.pi drawLaw)).real {pair | ¬ good pair.1} ≤ 1 / 10 + rw [freshSeed_bad_probability] + exact hseed + · intro pair hg + exact hlower pair.1 hg (pair.2 pair.1) + · exact .of_finite + · exact freshSeed_good_excess drawLaw incoming good value D ell hell hmoment + +end Final + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Probability/FreshCoordinateCost.lean b/lean/OAI/Combinatorics/EditApproximation/Probability/FreshCoordinateCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..2a871dcc4436d6fd74f1574fc5d688a8a33aeaf0 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Probability/FreshCoordinateCost.lean @@ -0,0 +1,170 @@ +import OAI.Combinatorics.EditApproximation.Geometry.RankedMemoWork +import Mathlib.Probability.Independence.Integration +import Mathlib.MeasureTheory.Integral.Pi +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! A first request can depend on earlier answers, but cannot depend on +its own unexposed coordinate. Finite product independence then preserves +that coordinate's unconditional expected cost. -/ + +namespace EditApproximation + +open MeasureTheory ProbabilityTheory Finset + +attribute [local instance] Classical.propDecidable + + + +namespace FiniteQuery + +/-- Changing an oracle only at `key` does not change whether `key` is +requested. The two executions agree up to its first request. -/ +theorem mem_keys_iff_of_agree_off {ι : Type*} [DecidableEq ι] + (left right : ι → ℚ) (key : ι) + (hagrees : ∀ other, other ≠ key → left other = right other) + (query : FiniteQuery ι) : key ∈ query.keys left ↔ key ∈ query.keys right := by + induction query with + | done value => rfl + | read first next ih => + by_cases heq : first = key + · subst first + simp only [keys, List.mem_cons, true_or] + · have hvalue := hagrees first heq + simp only [keys, List.mem_cons, Ne.symm heq, false_or, hvalue] + exact ih (right first) + +end FiniteQuery + +theorem sum_distinct_requests_le {ι : Type*} [Fintype ι] [DecidableEq ι] + (keys : List ι) (weight : ι → ℕ) : + (∑ i, if i ∈ keys then weight i else 0) ≤ (keys.map weight).sum := by + have hset : univ.filter (fun i => i ∈ keys) = keys.toFinset := by ext i; simp + rw [← sum_filter, hset] + clear hset + induction keys with + | nil => simp + | cons key keys ih => + by_cases hmem : key ∈ keys + · simp only [List.toFinset_cons, insert_eq_of_mem (List.mem_toFinset.mpr hmem), + List.map_cons, List.sum_cons] + omega + · rw [List.toFinset_cons, sum_insert (by simpa only [List.mem_toFinset] using hmem), + List.map_cons, List.sum_cons] + exact Nat.add_le_add_left ih _ + +theorem sum_selected_nat_weights_le {ι : Type*} [Fintype ι] [DecidableEq ι] + (keys : List ι) (weight : ι → ℕ) : + (∑ i, selectionIndicator (i ∈ keys) * (weight i : ℝ)) ≤ + ((keys.map weight).sum : ℕ) := by + calc + _ = ∑ i, if i ∈ keys then (weight i : ℝ) else 0 := by + apply sum_congr rfl + intro i _ + by_cases hi : i ∈ keys <;> simp [selectionIndicator, hi] + _ ≤ _ := by exact_mod_cast sum_distinct_requests_le keys weight + +section IndependentCost + +variable {ι : Type*} [Fintype ι] [DecidableEq ι] + {X : ι → Type*} [∀ i, Fintype (X i)] [∀ i, Nonempty (X i)] + [∀ i, MeasurableSpace (X i)] [∀ i, MeasurableSingletonClass (X i)] + (μ : (i : ι) → Measure (X i)) [∀ i, IsProbabilityMeasure (μ i)] + +/-- Selection stable under replacing its own coordinate is independent +of that coordinate. No accuracy event is used. -/ +theorem fresh_coordinate_independent (i : ι) (selected : (∀ j, X j) → Prop) + (hstable : ∀ left right : ∀ j, X j, + (∀ j, j ≠ i → left j = right j) → (selected left ↔ selected right)) + (cost : X i → ℝ) : + IndepFun (fun draw => selectionIndicator (selected draw)) + (fun draw => cost (draw i)) (Measure.pi μ) := by + classical + let S : Finset ι := univ.erase i + let restore : (∀ j : S, X j) → ∀ j, X j := fun rest j => + if h : j = i then h.symm ▸ Classical.choice (inferInstance : Nonempty (X i)) + else rest ⟨j, by simp [S, h]⟩ + let choose : (∀ j : S, X j) → ℝ := fun rest => selectionIndicator (selected (restore rest)) + let charge : (∀ j : ({i} : Finset ι), X j) → ℝ := fun rest => cost (rest ⟨i, by simp⟩) + have hrestore (draw : ∀ j, X j) : selected (restore (fun j : S => draw j)) ↔ selected draw := by + apply hstable + intro j hj + dsimp only [restore] + rw [dite_eq_right hj] + have hind := (iIndepFun_pi (μ := μ) (X := fun _ => id) + (fun _ => measurable_id.aemeasurable)).indepFun_finset S {i} (by simp [S]) + (fun _ => measurable_pi_apply _) + have hcomp := hind.comp (measurable_of_finite choose) (measurable_of_finite charge) + convert hcomp using 1 + · ext draw + exact congrArg selectionIndicator (propext (hrestore draw).symm) + · rfl + +theorem fresh_coordinate_expected_cost (i : ι) (selected : (∀ j, X j) → Prop) + (hstable : ∀ left right : ∀ j, X j, + (∀ j, j ≠ i → left j = right j) → (selected left ↔ selected right)) + (cost : X i → ℝ) : + (∫ draw, (selectionIndicator (selected draw)) * cost (draw i) ∂Measure.pi μ) = + (∫ draw, (selectionIndicator (selected draw)) ∂Measure.pi μ) * + (∫ value, cost value ∂μ i) := by + classical + rw [(fresh_coordinate_independent μ i selected hstable cost).integral_fun_mul_eq_mul_integral + (measurable_of_finite _).aestronglyMeasurable (measurable_of_finite _).aestronglyMeasurable] + rw [integral_comp_eval (measurable_of_finite cost).aestronglyMeasurable] + +/-- Summing the first-request charges costs at most the expected selected +width budget times the common per-width cost. -/ +theorem fresh_coordinates_expected_sum_le + (selected : ι → (∀ j, X j) → Prop) + (hstable : ∀ i left right, + (∀ j, j ≠ i → left j = right j) → (selected i left ↔ selected i right)) + (cost : (i : ι) → X i → ℝ) (width : ι → ℝ) (overhead budget : ℝ) + (hoverhead : 0 ≤ overhead) + (hcost : ∀ i, (∫ value, cost i value ∂μ i) ≤ width i * overhead) + (hbudget : ∀ draw, ∑ i, (selectionIndicator (selected i draw)) * width i ≤ budget) : + (∫ draw, ∑ i, (selectionIndicator (selected i draw)) * cost i (draw i) ∂Measure.pi μ) ≤ + budget * overhead := by + classical + rw [integral_finsetSum _ (fun _ _ => Integrable.of_finite)] + simp_rw [fresh_coordinate_expected_cost μ _ _ (hstable _) (cost _)] + calc + _ ≤ ∑ i, (∫ draw, (selectionIndicator (selected i draw)) ∂Measure.pi μ) * + (width i * overhead) := by + apply sum_le_sum + intro i _ + exact mul_le_mul_of_nonneg_left (hcost i) (integral_nonneg fun draw => by unfold selectionIndicator; split_ifs <;> norm_num) + _ = (∫ draw, ∑ i, (selectionIndicator (selected i draw)) * width i ∂Measure.pi μ) * overhead := by + rw [integral_finsetSum _ (fun _ _ => Integrable.of_finite), sum_mul] + apply sum_congr rfl + intro i _ + rw [integral_mul_const] + ring + _ ≤ budget * overhead := by + apply mul_le_mul_of_nonneg_right _ hoverhead + exact (integral_mono (Integrable.of_finite) (integrable_const _) hbudget).trans_eq (by simp) + +/-- Concrete specialization to a finite adaptive read program. A key is +charged once even if later continuation code requests it repeatedly. -/ +theorem finiteQuery_fresh_expected_cost_le (query : FiniteQuery ι) + (answer : (i : ι) → X i → ℚ) (cost : (i : ι) → X i → ℝ) + (width : ι → ℝ) (overhead budget : ℝ) (hoverhead : 0 ≤ overhead) + (hcost : ∀ i, (∫ value, cost i value ∂μ i) ≤ width i * overhead) + (hbudget : ∀ draw : ∀ j, X j, + ∑ i, (selectionIndicator (i ∈ query.keys (fun j => answer j (draw j)))) * width i ≤ budget) : + (∫ draw, ∑ i, + (selectionIndicator (i ∈ query.keys (fun j => answer j (draw j)))) * cost i (draw i) + ∂Measure.pi μ) ≤ budget * overhead := by + apply fresh_coordinates_expected_sum_le μ + (fun i (draw : ∀ j, X j) => i ∈ query.keys (fun j => answer j (draw j))) + _ cost width overhead budget hoverhead hcost hbudget + intro i left right hagree + exact FiniteQuery.mem_keys_iff_of_agree_off _ _ i + (fun j hj => congrArg (answer j) (hagree j hj)) query + +end IndependentCost + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Probability/Median.lean b/lean/OAI/Combinatorics/EditApproximation/Probability/Median.lean new file mode 100644 index 0000000000000000000000000000000000000000..40c342fa9f1e620a7415d64d345ac73da63e7b4c --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Probability/Median.lean @@ -0,0 +1,80 @@ +import OAI.Combinatorics.EditApproximation.Probability.Amplification +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! +# The executable upper middle order statistic + +The seed pass sorts its integer copy outputs and takes index `length/2`. +Strictly more than half the outputs below an upper bound suffice; ties +and repeated values are retained by the list representation. +-/ + +namespace EditApproximation + + + +theorem upperMedian_lower (values : List ℕ) (hvalues : values ≠ []) (c : ℕ) + (hlower : ∀ value ∈ values, c ≤ value) : c ≤ upperMedian values := by + have hlength : 0 < values.length := List.length_pos_iff.mpr hvalues + have hindex : values.length / 2 < (values.mergeSort (· ≤ ·)).length := by + rw [List.length_mergeSort] + omega + have hmem : (values.mergeSort (· ≤ ·))[values.length / 2] ∈ values := + (List.mergeSort_perm values (· ≤ ·)).mem_iff.mp (List.getElem_mem hindex) + have hmedian : upperMedian values = (values.mergeSort (· ≤ ·))[values.length / 2] := by + exact (List.getElem_eq_getD 0).symm + rw [hmedian] + exact hlower _ hmem + +theorem upperMedian_upper (values : List ℕ) (hvalues : values ≠ []) (upper : ℕ) + (hmajority : values.length / 2 < values.countP (fun value => value ≤ upper)) : + upperMedian values ≤ upper := by + let sorted := values.mergeSort (· ≤ ·) + have hlength : sorted.length = values.length := List.length_mergeSort values + have hpositive : 0 < values.length := List.length_pos_iff.mpr hvalues + have hindex : values.length / 2 < sorted.length := by omega + have hmedian : upperMedian values = sorted[values.length / 2] := + (List.getElem_eq_getD 0).symm + by_contra hnot + have habove : upper < sorted[values.length / 2] := by omega + have hdrop : (sorted.drop (values.length / 2)).filter (fun value => value ≤ upper) = [] := by + apply List.filter_eq_nil_iff.mpr + intro value hvalue + obtain ⟨j, hj, heq⟩ := List.mem_iff_getElem.mp hvalue + have hj' : values.length / 2 + j < sorted.length := by + simp only [List.length_drop] at hj + omega + have hge : sorted[values.length / 2] ≤ sorted[values.length / 2 + j] := + (List.sortedLE_mergeSort (l := values)).getElem_le_getElem_of_le + (hi := hindex) (hj := hj') + (show values.length / 2 ≤ values.length / 2 + j by omega) + have hget : (sorted.drop (values.length / 2))[j] = sorted[values.length / 2 + j] := by + simp only [List.getElem_drop] + rw [hget] at heq + have haboveValue : upper < value := habove.trans_le (hge.trans_eq heq) + simpa only [decide_eq_true_eq] using not_le_of_gt haboveValue + have hdropCount : (sorted.drop (values.length / 2)).countP (fun value => value ≤ upper) = 0 := by + rw [List.countP_eq_length_filter, hdrop] + rfl + have hcount : sorted.countP (fun value => value ≤ upper) ≤ values.length / 2 := by + have hsplit := List.take_append_drop (values.length / 2) sorted + rw [← hsplit, List.countP_append, hdropCount, Nat.add_zero] + exact List.countP_le_length.trans (List.length_take_le _ _) + have hperm := (List.mergeSort_perm values (· ≤ ·)).countP_eq (fun value => value ≤ upper) + change sorted.countP (fun value => value ≤ upper) = values.countP (fun value => value ≤ upper) at hperm + omega + +theorem clamped_upperMedian_spec (values : List ℕ) (hvalues : values ≠ []) + (c upper N : ℕ) (hcN : c ≤ N) + (hlower : ∀ value ∈ values, c ≤ value) + (hmajority : values.length / 2 < values.countP (fun value => value ≤ upper)) : + c ≤ min N (upperMedian values) ∧ min N (upperMedian values) ≤ upper := + ⟨le_min hcN (upperMedian_lower values hvalues c hlower), + (min_le_right _ _).trans (upperMedian_upper values hvalues upper hmajority)⟩ + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Probability/RejectionArrayLaw.lean b/lean/OAI/Combinatorics/EditApproximation/Probability/RejectionArrayLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..a9e741b6729d41e4bdca179d6a44a1893cc8375b --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Probability/RejectionArrayLaw.lean @@ -0,0 +1,103 @@ +import OAI.Combinatorics.EditApproximation.Probability.RejectionRuntimeLaw +import Mathlib.MeasureTheory.Integral.Pi + +namespace OAI + +/-! Independent finite arrays of exact rejection executions. The accepted +array has the required product law; all discarded trial words are charged. -/ + +namespace EditApproximation + +open MeasureTheory ProbabilityTheory + +section Array + +variable {ι : Type*} [Fintype ι] (range : ι → ℕ) [∀ i, NeZero (range i)] + +abbrev RejectionArrayExecution := ∀ i, ℕ × Fin (range i) + +noncomputable def rejectionArrayCoordinateLaw (i : ι) : Measure (ℕ × Fin (range i)) := + rejectionExecutionLaw (range i) (2 ^ rejectionBitCount (range i)) + (Nat.pos_of_ne_zero (NeZero.ne (range i))) + (rejectionWord_range (range i) (Nat.pos_of_ne_zero (NeZero.ne (range i)))).1 + +instance rejectionArrayCoordinateLaw_probability (i : ι) : + IsProbabilityMeasure (rejectionArrayCoordinateLaw range i) := by + unfold rejectionArrayCoordinateLaw + infer_instance + +noncomputable def rejectionArrayLaw : Measure (RejectionArrayExecution range) := + Measure.pi (rejectionArrayCoordinateLaw range) + +instance rejectionArrayLaw_probability : IsProbabilityMeasure (rejectionArrayLaw range) := by + unfold rejectionArrayLaw + infer_instance + +def rejectionArrayAccepted (execution : RejectionArrayExecution range) : ∀ i, Fin (range i) := + fun i => (execution i).2 + +theorem rejectionArrayLaw_accepted : + (rejectionArrayLaw range).map (rejectionArrayAccepted range) = + Measure.pi (fun i => (PMF.uniformOfFintype (Fin (range i))).toMeasure) := by + have hout (i : ι) : (rejectionArrayCoordinateLaw range i).map + (Prod.snd : ℕ × Fin (range i) → Fin (range i)) = + (PMF.uniformOfFintype (Fin (range i))).toMeasure := + rejectionExecutionLaw_output _ _ _ _ + let (i : ι) : SigmaFinite ((rejectionArrayCoordinateLaw range i).map + (Prod.snd : ℕ × Fin (range i) → Fin (range i))) := by + rw [hout] + infer_instance + have h := Measure.pi_map_pi (X := fun i => ℕ × Fin (range i)) (Y := fun i => Fin (range i)) + (f := fun _ => Prod.snd) (μ := rejectionArrayCoordinateLaw range) + (fun _ => measurable_snd.aemeasurable) + refine h.trans ?_ + congr 1 + funext i + exact rejectionExecutionLaw_output _ _ _ _ + +noncomputable def rejectionArrayConsumedBits (execution : RejectionArrayExecution range) : ℝ := + ∑ i, (((execution i).1 : ℝ) + 1) * rejectionBitCount (range i) + +omit [Fintype ι] in +theorem rejectionArrayCoordinate_bits_integrable (i : ι) : + Integrable (fun value : ℕ × Fin (range i) => + ((value.1 : ℝ) + 1) * rejectionBitCount (range i)) (rejectionArrayCoordinateLaw range i) := + ((rejection_trials_integrable (range i) (2 ^ rejectionBitCount (range i)) + (Nat.pos_of_ne_zero (NeZero.ne (range i))) + (rejectionWord_range (range i) (Nat.pos_of_ne_zero (NeZero.ne (range i)))).1).comp_fst + (PMF.uniformOfFintype (Fin (range i))).toMeasure).mul_const _ + +theorem rejectionArrayLaw_bits_integrable : + Integrable (rejectionArrayConsumedBits range) (rejectionArrayLaw range) := by + unfold rejectionArrayConsumedBits rejectionArrayLaw + apply integrable_finsetSum + intro i _ + exact integrable_comp_eval (X := fun i => ℕ × Fin (range i)) + (μ := rejectionArrayCoordinateLaw range) (i := i) (rejectionArrayCoordinate_bits_integrable range i) + +theorem rejectionArrayLaw_bits_le : + (∫ execution, rejectionArrayConsumedBits range execution ∂rejectionArrayLaw range) ≤ + 2 * ∑ i, (rejectionBitCount (range i) : ℝ) := by + unfold rejectionArrayConsumedBits rejectionArrayLaw + rw [integral_finsetSum] + · rw [Finset.mul_sum] + apply Finset.sum_le_sum + intro i _ + rw [integral_comp_eval (X := fun i => ℕ × Fin (range i)) + (μ := rejectionArrayCoordinateLaw range) (i := i) + (f := fun value : ℕ × Fin (range i) => ((value.1 : ℝ) + 1) * rejectionBitCount (range i)) + (rejectionArrayCoordinate_bits_integrable range i).aestronglyMeasurable] + unfold rejectionArrayCoordinateLaw rejectionExecutionLaw + rw [integral_fun_fst (ν := (PMF.uniformOfFintype (Fin (range i))).toMeasure) + (fun failures : ℕ => ((failures : ℝ) + 1) * rejectionBitCount (range i)), + probReal_univ, one_smul] + exact rejection_consumed_bits_moment (range i) (Nat.pos_of_ne_zero (NeZero.ne (range i))) + · intro i _ + exact integrable_comp_eval (X := fun i => ℕ × Fin (range i)) + (μ := rejectionArrayCoordinateLaw range) (i := i) (rejectionArrayCoordinate_bits_integrable range i) + +end Array + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Probability/RejectionMemoCost.lean b/lean/OAI/Combinatorics/EditApproximation/Probability/RejectionMemoCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..4799f788811d2545bc87ab24c185dc8af843e1be --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Probability/RejectionMemoCost.lean @@ -0,0 +1,75 @@ +import OAI.Combinatorics.EditApproximation.Probability.RejectionSelectedLaw + +namespace OAI + +/-! Literal rejection trials are charged only for source coordinates +encountered by the shared memo execution. The accepted coordinates may +influence the entire request list; failure counts remain independent. -/ + +namespace EditApproximation + +open MeasureTheory ProbabilityTheory + +section Memo + +variable {σ κ : Type*} [Fintype σ] [DecidableEq σ] [Fintype κ] [DecidableEq κ] + (range : σ → ℕ) [∀ key, NeZero (range key)] + +omit [∀ key, NeZero (range key)] in + theorem memo_selected_source_bits_le (keys : List (Sum σ κ)) (bits : ℕ) + (hbits : ∀ key, rejectionBitCount (range key) ≤ bits) : + (∑ key, (rejectionBitCount (range key) : ℝ) * + selectionIndicator (Sum.inl key ∈ keys)) ≤ keys.length * bits := by + let weight : Sum σ κ → ℕ := Sum.elim (fun key => rejectionBitCount (range key)) (fun _ => 0) + have hs := sum_selected_nat_weights_le keys weight + rw [Fintype.sum_sum_type] at hs + simp only [weight, Sum.elim_inl, Sum.elim_inr, Nat.cast_zero, mul_zero, + Finset.sum_const_zero, add_zero] at hs + have hb : (keys.map weight).sum ≤ keys.length * bits := by + clear hs + induction keys with + | nil => simp + | cons key keys ih => + have hk : weight key ≤ bits := by cases key <;> simp only [weight, Sum.elim_inl, Sum.elim_inr]; exact hbits _; omega + simp only [List.map_cons, List.sum_cons, List.length_cons, Nat.add_mul] + omega + calc + _ = ∑ key, selectionIndicator (Sum.inl key ∈ keys) * (rejectionBitCount (range key) : ℝ) := by + apply Finset.sum_congr rfl + intro key _ + ring + _ ≤ ((keys.map weight).sum : ℕ) := hs + _ ≤ (keys.length * bits : ℕ) := by exact_mod_cast hb + _ = _ := by push_cast; rfl + + theorem memo_rejectionBits_expected_le + (freshKeys : (∀ key, Fin (range key)) → List (Sum σ κ)) + (requests bits : ℕ) + (hrequests : ∀ accepted, (freshKeys accepted).length ≤ requests) + (hbits : ∀ key, rejectionBitCount (range key) ≤ bits) : + (∫ execution, rejectionSelectedBits range + (fun key accepted => Sum.inl key ∈ freshKeys accepted) execution + ∂rejectionRuntimeArrayLaw range) ≤ 2 * (requests * bits : ℕ) := by + apply rejectionSelectedBits_expected_le + intro accepted + exact (memo_selected_source_bits_le range (freshKeys accepted) bits hbits).trans + (by exact_mod_cast Nat.mul_le_mul_right bits (hrequests accepted)) + +theorem memo_rejectionBits_expected_le_real + (freshKeys : (∀ key, Fin (range key)) → List (Sum σ κ)) + (budget : ℝ) (bits : ℕ) + (hrequests : ∀ accepted, ((freshKeys accepted).length : ℝ) ≤ budget) + (hbits : ∀ key, rejectionBitCount (range key) ≤ bits) : + (∫ execution, rejectionSelectedBits range + (fun key accepted => Sum.inl key ∈ freshKeys accepted) execution + ∂rejectionRuntimeArrayLaw range) ≤ 2 * (budget * bits) := by + apply rejectionSelectedBits_expected_le + intro accepted + exact (memo_selected_source_bits_le range (freshKeys accepted) bits hbits).trans + (mul_le_mul_of_nonneg_right (hrequests accepted) (Nat.cast_nonneg _)) + +end Memo + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Probability/RejectionRuntimeLaw.lean b/lean/OAI/Combinatorics/EditApproximation/Probability/RejectionRuntimeLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fe537902d865703f8f8004d9cbbd11f329fd8f1 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Probability/RejectionRuntimeLaw.lean @@ -0,0 +1,130 @@ +import OAI.Combinatorics.EditApproximation.Probability.ExactSampling +import Mathlib.Probability.Distributions.Geometric +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! A probability law for terminating fair-word rejection executions. +It records the failed trial count and accepted integer, identifies their +joint masses with literal finite fair-word traces, and charges all trials. -/ + +namespace EditApproximation + +open MeasureTheory ProbabilityTheory + + + +theorem rejectionSuccessParameter_ne_zero (N R : ℕ) (hN : 0 < N) (hNR : N ≤ R) : + rejectionSuccessParameter N R hN hNR ≠ 0 := by + intro h + have heq := congrArg (fun p : unitInterval => (p : ℝ)) h + have hpos : (0 : ℝ) < (N : ℝ) / R := + div_pos (by exact_mod_cast hN) (by exact_mod_cast hN.trans_le hNR) + change (N : ℝ) / R = 0 at heq + linarith + +theorem rejectionSuccessParameter_complement (N R : ℕ) (hN : 0 < N) (hNR : N ≤ R) : + 1 - (rejectionSuccessParameter N R hN hNR : ℝ) = ((R - N : ℕ) : ℝ) / R := by + change 1 - (N : ℝ) / R = _ + rw [Nat.cast_sub hNR] + have hR : (R : ℝ) ≠ 0 := by exact_mod_cast (hN.trans_le hNR).ne' + field_simp [hR] + +noncomputable def rejectionExecutionLaw (N R : ℕ) [NeZero N] + (hN : 0 < N) (hNR : N ≤ R) : Measure (ℕ × Fin N) := + (geometricMeasure (rejectionSuccessParameter N R hN hNR)).prod + (PMF.uniformOfFintype (Fin N)).toMeasure + +instance rejectionExecutionLaw_probability (N R : ℕ) [NeZero N] + (hN : 0 < N) (hNR : N ≤ R) : + IsProbabilityMeasure (rejectionExecutionLaw N R hN hNR) := by + unfold rejectionExecutionLaw + infer_instance + +/-- The accepted value has exactly the uniform law, independently of the +number of failed trials. -/ +theorem rejectionExecutionLaw_output (N R : ℕ) [NeZero N] + (hN : 0 < N) (hNR : N ≤ R) : + (rejectionExecutionLaw N R hN hNR).map Prod.snd = + (PMF.uniformOfFintype (Fin N)).toMeasure := by + simp [rejectionExecutionLaw] + +/-- Each execution atom has the probability of the corresponding literal +finite first-success trace event. -/ +theorem rejectionExecutionLaw_atom (N R : ℕ) [NeZero N] + (hN : 0 < N) (hNR : N ≤ R) (failures : ℕ) (accepted : Fin N) : + (rejectionExecutionLaw N R hN hNR).real {(failures, accepted)} = + ((R - N : ℕ) : ℝ) ^ failures / ((R : ℝ) ^ failures * R) := by + have hu : ((PMF.uniformOfFintype (Fin N)).toMeasure).real {accepted} = (1 : ℝ) / N := by + rw [measureReal_def, PMF.toMeasure_apply_singleton _ _ (measurableSet_singleton _)] + simp [PMF.uniformOfFintype_apply] + rw [rejectionExecutionLaw, ← Set.singleton_prod_singleton, measureReal_prod_prod, + geometricMeasure_real_singleton (rejectionSuccessParameter_ne_zero N R hN hNR), hu, + rejectionSuccessParameter_complement] + change ((((R - N : ℕ) : ℝ) / R) ^ failures * ((N : ℝ) / R)) * (1 / N) = _ + rw [div_pow] + have hn : (N : ℝ) ≠ 0 := by exact_mod_cast hN.ne' + field_simp + +theorem rejectionExecutionLaw_literal_trace (N R : ℕ) [NeZero N] + (hN : 0 < N) (hNR : N ≤ R) (failures : ℕ) (accepted : Fin N) : + let : NeZero R := ⟨by omega⟩ + (rejectionExecutionLaw N R hN hNR).real {(failures, accepted)} = + ((PMF.uniformOfFintype ((Fin failures → Fin R) × Fin R)).toMeasure).real + (firstSuccessEvent N R failures accepted) := by + let : NeZero R := ⟨by omega⟩ + dsimp only + rw [rejectionExecutionLaw_atom, firstSuccessEvent_probability N R failures hN hNR accepted] + +theorem rejection_trial_moment (N R : ℕ) (hN : 0 < N) (hNR : N ≤ R) : + (∫ failures : ℕ, ((failures : ℝ) + 1) + ∂geometricMeasure (rejectionSuccessParameter N R hN hNR)) = (R : ℝ) / N := by + rw [integral_geometricMeasure (rejectionSuccessParameter_ne_zero N R hN hNR)] + have hterm (k : ℕ) : + ((1 - (rejectionSuccessParameter N R hN hNR : ℝ)) ^ k * + (rejectionSuccessParameter N R hN hNR : ℝ)) * ((k : ℝ) + 1) = + ((k : ℝ) + 1) * N * (((R - N : ℕ) : ℝ) ^ k / ((R : ℝ) ^ k * R)) := by + rw [rejectionSuccessParameter_complement] + change (((R - N : ℕ) : ℝ) / R) ^ k * ((N : ℝ) / R) * ((k : ℝ) + 1) = _ + rw [div_pow] + ring + simp_rw [smul_eq_mul, hterm] + exact (rejection_first_success_expected_trials N R hN hNR).tsum_eq + +theorem rejection_trials_integrable (N R : ℕ) (hN : 0 < N) (hNR : N ≤ R) : + Integrable (fun failures : ℕ => (failures : ℝ) + 1) + (geometricMeasure (rejectionSuccessParameter N R hN hNR)) := by + apply (integrable_geometricMeasure_iff (rejectionSuccessParameter_ne_zero N R hN hNR)).mpr + have hterm (k : ℕ) : + (1 - (rejectionSuccessParameter N R hN hNR : ℝ)) ^ k * + (rejectionSuccessParameter N R hN hNR : ℝ) * ‖(k : ℝ) + 1‖ = + ((k : ℝ) + 1) * N * (((R - N : ℕ) : ℝ) ^ k / ((R : ℝ) ^ k * R)) := by + rw [Real.norm_of_nonneg (by positivity), rejectionSuccessParameter_complement] + change (((R - N : ℕ) : ℝ) / R) ^ k * ((N : ℝ) / R) * ((k : ℝ) + 1) = _ + rw [div_pow] + ring + simpa only [hterm] using (rejection_first_success_expected_trials N R hN hNR).summable + +/-- All failed trials are included in this strict factor-two bound. -/ +theorem rejection_fair_word_trial_moment (N : ℕ) (hN : 0 < N) : + (∫ failures : ℕ, ((failures : ℝ) + 1) + ∂geometricMeasure (rejectionSuccessParameter N (2 ^ rejectionBitCount N) + hN (rejectionWord_range N hN).1)) < 2 := by + rw [rejection_trial_moment] + apply (div_lt_iff₀ (by exact_mod_cast hN : (0 : ℝ) < N)).mpr + exact_mod_cast (rejectionWord_range N hN).2 + +/-- Exact expected number of consumed fair bits, including failed words. -/ +theorem rejection_consumed_bits_moment (N : ℕ) (hN : 0 < N) : + (∫ failures : ℕ, (((failures : ℝ) + 1) * rejectionBitCount N) + ∂geometricMeasure (rejectionSuccessParameter N (2 ^ rejectionBitCount N) + hN (rejectionWord_range N hN).1)) ≤ 2 * rejectionBitCount N := by + rw [integral_mul_const] + exact mul_le_mul_of_nonneg_right + (rejection_fair_word_trial_moment N hN).le (Nat.cast_nonneg _) + + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Probability/RejectionSelectedCost.lean b/lean/OAI/Combinatorics/EditApproximation/Probability/RejectionSelectedCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..d245f7d4bca6743661a584df7a6a456dcd40c0e2 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Probability/RejectionSelectedCost.lean @@ -0,0 +1,121 @@ +import OAI.Combinatorics.EditApproximation.Probability.RejectionArrayLaw +import OAI.Combinatorics.EditApproximation.Probability.FreshCoordinateCost +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Rejection counts are independent of all accepted values. Thus even +an adaptive choice of coordinates incurs fewer than two word trials per +selected coordinate in expectation. No unused source is charged. -/ + +namespace EditApproximation + +open MeasureTheory ProbabilityTheory + +section Selected + +variable {ι : Type*} [Fintype ι] (range : ι → ℕ) [∀ i, NeZero (range i)] + + + +instance rejectionAcceptedLaw_probability : IsProbabilityMeasure (rejectionAcceptedLaw range) := by + unfold rejectionAcceptedLaw + infer_instance + + + +instance rejectionFailureLaw_probability (i : ι) : IsProbabilityMeasure (rejectionFailureLaw range i) := by + unfold rejectionFailureLaw + infer_instance + + + + + +instance rejectionRuntimeArrayLaw_probability : IsProbabilityMeasure (rejectionRuntimeArrayLaw range) := by + unfold rejectionRuntimeArrayLaw rejectionAcceptedLaw + infer_instance + + theorem rejectionRuntimeArrayLaw_accepted : + (rejectionRuntimeArrayLaw range).map Prod.snd = rejectionAcceptedLaw range := by + unfold rejectionRuntimeArrayLaw + simp + + + + theorem rejectionFailureArray_bits_integrable (i : ι) : + Integrable (fun failures : ι → ℕ => ((failures i : ℝ) + 1) * rejectionBitCount (range i)) + (Measure.pi (rejectionFailureLaw range)) := by + apply integrable_comp_eval (X := fun _ : ι => ℕ) (μ := rejectionFailureLaw range) (i := i) + (f := fun failures : ℕ => ((failures : ℝ) + 1) * rejectionBitCount (range i)) + exact (rejection_trials_integrable (range i) (2 ^ rejectionBitCount (range i)) + (Nat.pos_of_ne_zero (NeZero.ne (range i))) + (rejectionWord_range (range i) (Nat.pos_of_ne_zero (NeZero.ne (range i)))).1).mul_const _ + + theorem rejectionSelectedBits_integrable (selected : ι → (∀ i, Fin (range i)) → Prop) : + Integrable (rejectionSelectedBits range selected) (rejectionRuntimeArrayLaw range) := by + classical + unfold rejectionSelectedBits rejectionRuntimeArrayLaw + apply integrable_finsetSum + intro i _ + exact (rejectionFailureArray_bits_integrable range i).mul_prod (Integrable.of_finite (μ := rejectionAcceptedLaw range) + (f := fun accepted => selectionIndicator (selected i accepted))) + + theorem rejectionSelectedBits_expected_le + (selected : ι → (∀ i, Fin (range i)) → Prop) (budget : ℝ) + (hbudget : ∀ accepted, ∑ i, (rejectionBitCount (range i) : ℝ) * + selectionIndicator (selected i accepted) ≤ budget) : + (∫ execution, rejectionSelectedBits range selected execution ∂rejectionRuntimeArrayLaw range) ≤ + 2 * budget := by + classical + unfold rejectionSelectedBits rejectionRuntimeArrayLaw + rw [integral_finsetSum] + · have hprod (i : ι) : + (∫ execution : RejectionRuntimeArray range, + (((execution.1 i : ℝ) + 1) * rejectionBitCount (range i)) * + selectionIndicator (selected i execution.2) + ∂(Measure.pi (rejectionFailureLaw range)).prod (rejectionAcceptedLaw range)) = + (∫ failures : ι → ℕ, ((failures i : ℝ) + 1) * rejectionBitCount (range i) + ∂Measure.pi (rejectionFailureLaw range)) * + (∫ accepted, selectionIndicator (selected i accepted) ∂rejectionAcceptedLaw range) := + integral_prod_mul (μ := Measure.pi (rejectionFailureLaw range)) + (ν := rejectionAcceptedLaw range) + (fun failures : ι → ℕ => ((failures i : ℝ) + 1) * rejectionBitCount (range i)) + (fun accepted : ∀ i, Fin (range i) => selectionIndicator (selected i accepted)) + simp_rw [hprod] + have hcost (i : ι) : + (∫ failures : ι → ℕ, ((failures i : ℝ) + 1) * rejectionBitCount (range i) + ∂Measure.pi (rejectionFailureLaw range)) ≤ 2 * rejectionBitCount (range i) := by + rw [integral_comp_eval (X := fun _ : ι => ℕ) (μ := rejectionFailureLaw range) (i := i) + (f := fun failures : ℕ => ((failures : ℝ) + 1) * rejectionBitCount (range i)) + (by fun_prop)] + exact rejection_consumed_bits_moment (range i) (Nat.pos_of_ne_zero (NeZero.ne (range i))) + calc + _ ≤ ∑ i, (2 * rejectionBitCount (range i)) * + (∫ accepted, selectionIndicator (selected i accepted) ∂rejectionAcceptedLaw range) := by + apply Finset.sum_le_sum + intro i _ + apply mul_le_mul_of_nonneg_right (hcost i) + exact integral_nonneg (fun _ => by unfold selectionIndicator; split_ifs <;> norm_num) + _ = 2 * (∫ accepted, ∑ i, (rejectionBitCount (range i) : ℝ) * + selectionIndicator (selected i accepted) ∂rejectionAcceptedLaw range) := by + rw [integral_finsetSum] + · simp only [integral_const_mul, Finset.mul_sum] + apply Finset.sum_congr rfl + intro i _ + ring + · intro i _ + exact Integrable.of_finite + _ ≤ 2 * budget := by + apply mul_le_mul_of_nonneg_left _ (by norm_num) + exact (integral_mono Integrable.of_finite (integrable_const _) hbudget).trans_eq (by simp [rejectionAcceptedLaw]) + · intro i _ + exact (rejectionFailureArray_bits_integrable range i).mul_prod (Integrable.of_finite (μ := rejectionAcceptedLaw range) + (f := fun accepted => selectionIndicator (selected i accepted))) + +end Selected + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Probability/RejectionSelectedLaw.lean b/lean/OAI/Combinatorics/EditApproximation/Probability/RejectionSelectedLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..7cde47da334c8397c85f4823da81cac180a54780 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Probability/RejectionSelectedLaw.lean @@ -0,0 +1,93 @@ +import OAI.Combinatorics.EditApproximation.Probability.RejectionSelectedCost + +namespace OAI + +/-! The independent failure-count/accepted-value representation is exactly + the law of the literal rejection executions, including discarded trials. -/ + +namespace EditApproximation + +open MeasureTheory ProbabilityTheory + +section Law + +variable {ι : Type*} [Fintype ι] (range : ι → ℕ) [∀ i, NeZero (range i)] + +def rejectionRuntimeToExecution (execution : RejectionRuntimeArray range) : + RejectionArrayExecution range := fun i => (execution.1 i, execution.2 i) + +def rejectionExecutionToRuntime (execution : RejectionArrayExecution range) : + RejectionRuntimeArray range := (fun i => (execution i).1, fun i => (execution i).2) + + theorem rejectionRuntimeToExecution_law : + (rejectionRuntimeArrayLaw range).map (rejectionRuntimeToExecution range) = + rejectionArrayLaw range := by + classical + apply Measure.ext_of_singleton + intro execution + rw [Measure.map_apply (by fun_prop) (measurableSet_singleton _)] + have hpre : rejectionRuntimeToExecution range ⁻¹' {execution} = + {rejectionExecutionToRuntime range execution} := by + ext pair + simp only [Set.mem_preimage, Set.mem_singleton_iff] + constructor + · intro h + apply Prod.ext + · funext i + exact congrArg (fun x => (x i).1) h + · funext i + exact congrArg (fun x => (x i).2) h + · rintro rfl + rfl + rw [hpre] + change ((Measure.pi (rejectionFailureLaw range)).prod (rejectionAcceptedLaw range)) + {(fun i => (execution i).1, fun i => (execution i).2)} = _ + rw [← Set.singleton_prod_singleton, Measure.prod_prod] + simp only [rejectionAcceptedLaw, rejectionArrayLaw, Measure.pi_singleton] + rw [← Finset.prod_mul_distrib] + apply Finset.prod_congr rfl + intro i _ + unfold rejectionArrayCoordinateLaw rejectionExecutionLaw rejectionFailureLaw + rw [← Set.singleton_prod_singleton, Measure.prod_prod] + +omit [Fintype ι] [∀ i, NeZero (range i)] in + theorem rejectionRuntime_roundtrip (execution : RejectionRuntimeArray range) : + rejectionExecutionToRuntime range (rejectionRuntimeToExecution range execution) = execution := rfl + +omit [Fintype ι] [∀ i, NeZero (range i)] in + theorem rejectionExecution_roundtrip (execution : RejectionArrayExecution range) : + rejectionRuntimeToExecution range (rejectionExecutionToRuntime range execution) = execution := by + funext i + exact Prod.eta (execution i) + + +/-- Only distinct requested coordinates are sampled. The bound includes +all failed rejection trials, even when the query depends on accepted values. -/ + theorem rejectionRequestedBits_expected_le [DecidableEq ι] + (program : FiniteQuery ι) (budget : ℕ) + (hbudget : ∀ accepted : ∀ i, Fin (range i), + program.cost (fun i => (accepted i).val) (fun i => rejectionBitCount (range i)) ≤ budget) : + (∫ execution, rejectionSelectedBits range + (fun i accepted => i ∈ program.keys (fun j => (accepted j).val)) execution + ∂rejectionRuntimeArrayLaw range) ≤ 2 * (budget : ℝ) := by + apply rejectionSelectedBits_expected_le + intro accepted + have hselected := sum_selected_nat_weights_le + (program.keys (fun j => (accepted j).val)) (fun i => rejectionBitCount (range i)) + calc + _ = ∑ i, selectionIndicator (i ∈ program.keys (fun j => (accepted j).val)) * + (rejectionBitCount (range i) : ℝ) := by + apply Finset.sum_congr rfl + intro i _ + ring + _ ≤ ((program.keys (fun j => (accepted j).val)).map + (fun i => rejectionBitCount (range i))).sum := hselected + _ = (program.cost (fun j => (accepted j).val) (fun i => rejectionBitCount (range i)) : ℝ) := by + rw [FiniteQuery.cost_eq_sum] + _ ≤ (budget : ℝ) := by exact_mod_cast hbudget accepted + +end Law + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Probability/RejectionSpace.lean b/lean/OAI/Combinatorics/EditApproximation/Probability/RejectionSpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..d0cc6d3b436d98bf8f82676f84e1a96bfc7dc121 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Probability/RejectionSpace.lean @@ -0,0 +1,55 @@ +import OAI.Combinatorics.EditApproximation.Refinement.ComputedFamilySampling +import OAI.Combinatorics.EditApproximation.Probability.ExactSampling + +namespace OAI + +namespace EditApproximation + +/-- The stream keeps the current word and one optional accepted value; +failed words are overwritten and the failure count belongs only to the +probability-space description, not to the machine state. -/ +def rejectionStateCells (N bits : ℕ) (state : Option (Fin N)) (word : Fin (2 ^ bits)) : ℕ := + (state.map fun value => value.val.bits.length).getD 0 + word.val.bits.length + 4 + +theorem rejectionStateCells_bound (N bits : ℕ) (hN : N ≤ 2 ^ bits) + (state : Option (Fin N)) (word : Fin (2 ^ bits)) : + rejectionStateCells N bits state word ≤ 2 * bits + 4 := by + have hw : word.val.bits.length ≤ bits := by + rw [Nat.size_eq_bits_len] + exact Nat.size_le.mpr word.isLt + have hs : (state.map fun value => value.val.bits.length).getD 0 ≤ bits := by + cases state with + | none => exact Nat.zero_le _ + | some value => + change value.val.bits.length ≤ bits + rw [Nat.size_eq_bits_len] + exact Nat.size_le.mpr (value.isLt.trans_le hN) + unfold rejectionStateCells + omega + +/-- This bound holds after every transition, regardless of how many +failed trials preceded it. -/ +theorem rejectionTransition_cells (N bits : ℕ) (hN : N ≤ 2 ^ bits) + (state : Option (Fin N)) (word nextWord : Fin (2 ^ bits)) : + rejectionStateCells N bits (rejectionTransition N (2 ^ bits) state word) nextWord ≤ 2 * bits + 4 := + rejectionStateCells_bound N bits hN _ _ + +theorem computedFamilySampler_cells (source target : List ℕ) (N R : ℕ) + (hMass : Nat.size (localOnlineMassBound (integerParameters N).M (integerParameters N).P + (inputHeight N)) ≤ inputHeight N) + (key : ComputedFamilyScalarKey source target N R) + (state : Option (Fin (physicalFamilyRange target N (integerParameters N).P (inputSmallLog N) + (40 * smallLogExponent N) (inputHeight N) (inputSmallLog N ^ 80) + (computedSeedPassCount N) (inputHeight N ^ 2) key))) + (word : Fin (2 ^ rejectionBitCount (physicalFamilyRange target N (integerParameters N).P (inputSmallLog N) + (40 * smallLogExponent N) (inputHeight N) (inputSmallLog N ^ 80) + (computedSeedPassCount N) (inputHeight N ^ 2) key))) : + rejectionStateCells _ _ state word ≤ 2 * inputHeight N + 4 := by + have h := rejectionStateCells_bound _ _ (Nat.le_pow_clog (by decide : 1 < (2 : ℕ)) _) state word + have hb := computedFamilyRange_bits_le source target N R hMass key + dsimp only [rejectionBitCount] at hb + exact h.trans (by omega) + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Probability/SampledRegret.lean b/lean/OAI/Combinatorics/EditApproximation/Probability/SampledRegret.lean new file mode 100644 index 0000000000000000000000000000000000000000..e15dd1ef688f824659615c8e2143740bec5a5f23 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Probability/SampledRegret.lean @@ -0,0 +1,99 @@ +import OAI.Combinatorics.EditApproximation.Geometry.ChildIncrements +import OAI.Combinatorics.EditApproximation.Probability.ExactSampling +import OAI.Combinatorics.EditApproximation.Probability.FiniteSampling + +namespace OAI + +/-! +# Exact sampled action costs + +The sampler's finite law translates the computed rational vector into its +expected linear cost. Correlation with a group-estimation failure is not +excluded or needed in this identity. +-/ + +namespace EditApproximation + +open Finset + +theorem uniformMean_mono {Ω : Type*} [Fintype Ω] (f g : Ω → ℝ) + (h : ∀ ω, f ω ≤ g ω) : uniformMean f ≤ uniformMean g := by + exact div_le_div_of_nonneg_right (sum_le_sum fun ω _ => h ω) (Nat.cast_nonneg _) + +theorem uniformMean_add {Ω : Type*} [Fintype Ω] (f g : Ω → ℝ) : + uniformMean (fun ω => f ω + g ω) = uniformMean f + uniformMean g := by + simp only [uniformMean, sum_add_distrib, add_div] + +theorem uniformMean_mul {Ω : Type*} [Fintype Ω] (a : ℝ) (f : Ω → ℝ) : + uniformMean (fun ω => a * f ω) = a * uniformMean f := by + simp only [uniformMean, ← mul_sum, mul_div_assoc] + +theorem uniformMean_const {Ω : Type*} [Fintype Ω] [Nonempty Ω] (a : ℝ) : + uniformMean (fun _ : Ω => a) = a := by + simp only [uniformMean, sum_const, card_univ, nsmul_eq_mul] + have hcard : (Fintype.card Ω : ℝ) ≠ 0 := by exact_mod_cast Fintype.card_ne_zero + exact mul_div_cancel_left₀ a hcard + +theorem uniformMean_sum {Ω ι : Type*} [Fintype Ω] (indices : Finset ι) (f : ι → Ω → ℝ) : + uniformMean (fun ω => ∑ i ∈ indices, f i ω) = ∑ i ∈ indices, uniformMean (f i) := by + unfold uniformMean + rw [sum_comm, sum_div] + +theorem finiteRationalOptimizer_sampler_linear_mean {ι : Type*} + (coordinates : Finset ι) (vertices : List (ι → ℚ)) (linear : ι → ℚ) + (G K : ℕ) (hK : 0 < K) (payoff : ι → ℝ) : + let : NeZero (optimizerTriangularMass K) := ⟨Nat.ne_of_gt (optimizerTriangularMass_positive K hK)⟩ + uniformMean (fun integer : Fin (optimizerTriangularMass K) => + ∑ i ∈ coordinates, payoff i * + (finiteOptimizerSelection coordinates vertices linear G (triangularChoice K integer).val i : ℝ)) = + ∑ i ∈ coordinates, payoff i * (finiteRationalOptimizer coordinates vertices linear G K i : ℝ) := by + let : NeZero (optimizerTriangularMass K) := ⟨Nat.ne_of_gt (optimizerTriangularMass_positive K hK)⟩ + dsimp only + unfold uniformMean + rw [Fintype.card_fin, sum_comm, sum_div] + apply sum_congr rfl + intro i _ + rw [← mul_sum, mul_div_assoc] + congr 1 + have hmean := finiteRationalOptimizer_sampler_mean coordinates vertices linear G K hK i + exact_mod_cast hmean + +theorem actionVector_child_cost_identity {β σ : Type*} [Fintype β] [Nonempty β] + [DecidableEq β] [DecidableEq σ] (band : Finset (β → σ)) + (mass : β → ℚ) (hpos : ∀ child, 0 < mass child) + (table : ℕ → β × σ → ℚ) (κ : ℚ) (t : ℕ) + {action : β → σ} (ha : action ∈ band) : + -((∑ child, mass child : ℚ) : ℝ) * + (∑ i ∈ bandCoordinates band, + ((childGain mass table t i : ℝ) + (1 - (κ : ℝ)) * childDecrement mass table t i) * + (actionVector mass action i : ℝ)) = + (∑ child, (table (t + 1) (child, action child) : ℝ)) + + (κ : ℝ) * ((∑ child, (table t (child, action child) : ℝ)) - + ∑ child, (table (t + 1) (child, action child) : ℝ)) := by + have hidentity := actionVector_cost_identity band mass hpos + (fun i => (κ : ℝ) * table t i + (1 - (κ : ℝ)) * table (t + 1) i) ha + have hgain i : (childGain mass table t i : ℝ) + (1 - (κ : ℝ)) * childDecrement mass table t i = + -((κ : ℝ) * table t i + (1 - (κ : ℝ)) * table (t + 1) i) / (mass i.1 : ℝ) := by + have hid := childGain_decrement_identity mass table κ t i + exact_mod_cast hid + simp_rw [hgain] + rw [hidentity] + simp only [sum_add_distrib, ← mul_sum] + ring + +theorem actionVector_comparator_cost_identity {β σ : Type*} [Fintype β] [Nonempty β] + [DecidableEq β] [DecidableEq σ] (band : Finset (β → σ)) + (mass : β → ℚ) (hpos : ∀ child, 0 < mass child) + (table : ℕ → β × σ → ℚ) (t : ℕ) + {action : β → σ} (ha : action ∈ band) : + -((∑ child, mass child : ℚ) : ℝ) * + (∑ i ∈ bandCoordinates band, + ((childGain mass table t i : ℝ) + childDecrement mass table t i) * + (actionVector mass action i : ℝ)) = + ∑ child, (table (t + 1) (child, action child) : ℝ) := by + simpa only [Rat.cast_zero, sub_zero, one_mul, zero_mul, add_zero] using + actionVector_child_cost_identity band mass hpos table 0 t ha + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Probability/ThresholdMoments.lean b/lean/OAI/Combinatorics/EditApproximation/Probability/ThresholdMoments.lean new file mode 100644 index 0000000000000000000000000000000000000000..3e3de8a3d0eeef4d274255c8ea91c34bb5354902 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Probability/ThresholdMoments.lean @@ -0,0 +1,129 @@ +import OAI.Combinatorics.EditApproximation.Geometry.Seed + +namespace OAI + +/-! +# Discrete threshold moments + +The initial estimator samples an integer uniformly from `1, …, B`. +The finite count below proves its rounding bias exactly; no continuous +threshold distribution is substituted for the executable sampler. +-/ + +namespace EditApproximation + +open Finset + +theorem threshold_count (B : ℕ) (scale value : ℝ) + (hB : 0 < B) (hscale : 0 < scale) (hvalue : 0 ≤ value) (hupper : value < scale) : + ((Icc 1 B).filter fun (r : ℕ) => scale * (r : ℝ) / B ≤ value).card = + ⌊(B : ℝ) * value / scale⌋₊ := by + have hBr : (0 : ℝ) < B := by exact_mod_cast hB + have hq : 0 ≤ (B : ℝ) * value / scale := by positivity + have hqB : (B : ℝ) * value / scale < B := by + apply (div_lt_iff₀ hscale).2 + nlinarith + have hfloor : ⌊(B : ℝ) * value / scale⌋₊ < B := (Nat.floor_lt hq).2 hqB + have hiff (r : ℕ) : scale * r / B ≤ value ↔ r ≤ ⌊(B : ℝ) * value / scale⌋₊ := by + rw [Nat.le_floor_iff hq, div_le_iff₀ hBr, le_div_iff₀ hscale] + constructor <;> intro h <;> nlinarith + have hfilter : (Icc 1 B).filter (fun (r : ℕ) => scale * (r : ℝ) / B ≤ value) = + Icc 1 ⌊(B : ℝ) * value / scale⌋₊ := by + ext r + simp only [mem_filter, mem_Icc, hiff] + constructor + · intro h + exact ⟨h.1.1, h.2⟩ + · intro h + exact ⟨⟨h.1, h.2.trans hfloor.le⟩, h.2⟩ + rw [hfilter] + simp only [Nat.card_Icc, Nat.add_sub_cancel] + +/-- Exact discrete first moment below the scale; dividing the sum by `B` +gives `scale * floor(B * value / scale) / B`. -/ +theorem threshold_sum (B : ℕ) (scale value : ℝ) + (hB : 0 < B) (hscale : 0 < scale) (hvalue : 0 ≤ value) (hupper : value < scale) : + (∑ r ∈ Icc 1 B, thresholdContribution (scale * r / B) scale value) = + (⌊(B : ℝ) * value / scale⌋₊ : ℝ) * scale := by + have hpoint (r : ℕ) : thresholdContribution (scale * r / B) scale value = + if scale * r / B ≤ value then scale else 0 := by + simp only [thresholdContribution, max_eq_right hupper.le] + simp_rw [hpoint] + rw [← sum_filter] + simp only [sum_const, nsmul_eq_mul, + threshold_count B scale value hB hscale hvalue hupper] + +/-- Bias bound used in the coarse estimator: the discrete mean is below +the true argument by at most one grid unit. -/ +theorem threshold_bias (B : ℕ) (scale value : ℝ) + (hB : 0 < B) (hscale : 0 < scale) (hvalue : 0 ≤ value) (hupper : value < scale) : + 0 ≤ value - (∑ r ∈ Icc 1 B, + thresholdContribution (scale * r / B) scale value) / B ∧ + value - (∑ r ∈ Icc 1 B, + thresholdContribution (scale * r / B) scale value) / B ≤ scale / B := by + rw [threshold_sum B scale value hB hscale hvalue hupper] + have hBr : (0 : ℝ) < B := by exact_mod_cast hB + have hq : 0 ≤ (B : ℝ) * value / scale := by positivity + have hflo := Nat.floor_le hq + have hfhi := Nat.lt_floor_add_one ((B : ℝ) * value / scale) + have hl := (le_div_iff₀ hscale).1 hflo + have hh := (div_lt_iff₀ hscale).1 hfhi + constructor + · apply sub_nonneg.mpr + exact (div_le_iff₀ hBr).2 (by nlinarith) + · apply (le_div_iff₀ hBr).2 + have hid : (value - (⌊(B : ℝ) * value / scale⌋₊ : ℝ) * scale / B) * B = + value * B - (⌊(B : ℝ) * value / scale⌋₊ : ℝ) * scale := by + field_simp + rw [hid] + nlinarith + +theorem uniform_centered_square_identity {ι : Type*} (samples : Finset ι) + (value : ι → ℝ) (hcard : 0 < samples.card) : + (∑ i ∈ samples, (value i - (∑ j ∈ samples, value j) / samples.card) ^ 2) / + samples.card = + (∑ i ∈ samples, value i ^ 2) / samples.card - + ((∑ i ∈ samples, value i) / samples.card) ^ 2 := by + let mean := (∑ i ∈ samples, value i) / samples.card + have hcardr : (0 : ℝ) < samples.card := by exact_mod_cast hcard + have hexpand : (∑ i ∈ samples, (value i - mean) ^ 2) = + (∑ i ∈ samples, value i ^ 2) - 2 * mean * (∑ i ∈ samples, value i) + + (samples.card : ℝ) * mean ^ 2 := by + calc + _ = ∑ i ∈ samples, (value i ^ 2 - 2 * mean * value i + mean ^ 2) := + sum_congr rfl fun _ _ => by ring + _ = _ := by + rw [sum_add_distrib, sum_sub_distrib, ← mul_sum, sum_const, nsmul_eq_mul] + change (∑ i ∈ samples, (value i - mean) ^ 2) / samples.card = _ + rw [hexpand] + dsimp [mean] + field_simp + ring + +/-- The centered second moment of the actual finite threshold sampler is +at most `scale * value`, as used in the Bernstein variance proxy. -/ +theorem threshold_variance_bound (B : ℕ) (scale value : ℝ) + (hB : 0 < B) (hscale : 0 < scale) (hvalue : 0 ≤ value) (hupper : value < scale) : + (∑ r ∈ Icc 1 B, + (thresholdContribution (scale * r / B) scale value - + (∑ s ∈ Icc 1 B, thresholdContribution (scale * s / B) scale value) / B) ^ 2) / B ≤ + scale * value := by + have hcard : (Icc 1 B).card = B := by simp only [Nat.card_Icc, Nat.add_sub_cancel] + have hvariance := uniform_centered_square_identity (Icc 1 B) + (fun r => thresholdContribution (scale * r / B) scale value) (by omega) + rw [hcard] at hvariance + rw [hvariance] + have hpoint (r : ℕ) : thresholdContribution (scale * r / B) scale value ^ 2 = + scale * thresholdContribution (scale * r / B) scale value := by + simp only [thresholdContribution, max_eq_right hupper.le] + split_ifs <;> ring + simp_rw [hpoint] + rw [← mul_sum, mul_div_assoc] + have hmean := (threshold_bias B scale value hB hscale hvalue hupper).1 + have hscaled := mul_le_mul_of_nonneg_left (sub_nonneg.mp hmean) hscale.le + nlinarith [sq_nonneg ((∑ r ∈ Icc 1 B, + thresholdContribution (scale * r / B) scale value) / B)] + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryActionInputCost.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryActionInputCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..dcfbee06925fd51611f2683a943002cd5f381eab --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryActionInputCost.lean @@ -0,0 +1,73 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryActionInputs +import OAI.Combinatorics.EditApproximation.Queries.QueryCodeBounds +import OAI.Combinatorics.EditApproximation.Queries.QueryHistoryBounds + +namespace OAI + +/-! Bounds for the final adaptive child gather. The temporary list and +its sorting work depend on emitted actions, rather than the full table. -/ + +namespace EditApproximation + +theorem queryActionInputsWithWork_bounds {Parent Child : Type*} {M : ℕ} + (actions : List (BinaryBellmanAction Parent Child M)) : + (queryActionInputsWithWork actions).1.length = actions.length * M ∧ + (queryActionInputsWithWork actions).2 ≤ actions.length * (5 * M + 3) + M + 1 := by + let run := fun action : BinaryBellmanAction Parent Child M => + arithmeticMapWithWork (fun i : Fin M => (action.childState i, 1)) (List.finRange M) + have hlen (action : BinaryBellmanAction Parent Child M) : (run action).1.length = M := by + simp only [run, arithmeticMapWithWork_value, List.length_map, List.length_finRange] + have hc (action : BinaryBellmanAction Parent Child M) : (run action).2 ≤ 4 * M := by + have h := arithmeticMapWithWork_cost (fun i : Fin M => (action.childState i, 1)) + (List.finRange M) 1 (fun _ _ => le_rfl) + simpa only [List.length_finRange, Nat.reduceAdd, Nat.mul_comm] using h + constructor + · simp only [queryActionInputsWithWork, arithmeticFlatMapWithWork_value, List.length_flatMap, + arithmeticMapWithWork_value, List.length_map, List.length_finRange, List.map_const', + List.sum_replicate, smul_eq_mul] + · have h := arithmeticFlatMapWithWork_cost run actions (4 * M) M + (fun action _ => hc action) (fun action _ => (hlen action).le) + change (arithmeticFlatMapWithWork run actions).2 + M + 1 ≤ _ + have heq : 4 * M + M + 3 = 5 * M + 3 := by omega + rw [heq] at h + omega + +theorem queryOrderedChildInputsWithWork_length {M n : ℕ} (inputs : List (Fin M × TargetInterval n)) : + (queryOrderedChildInputsWithWork inputs).1.length ≤ inputs.length := by + rw [queryOrderedChildInputsWithWork_value, orderedInputs_length] + exact List.toFinset_card_le inputs + +def queryNeededInputsBitBudget (actions M B : ℕ) : ℕ := + actions * (5 * M + 3) + 2 * M + actions * M + + (actions * M + 1) ^ 2 * (202000 * (B + 1) ^ 2) + 4 + +theorem queryNeededInputsWithWork_bounds {n M : ℕ} + (selected online : List (BinaryBellmanAction (TargetInterval n) (Fin M × TargetInterval n) M)) + (B : ℕ) (hM : Nat.size M ≤ B) (hn : Nat.size n ≤ B) : + (queryNeededInputsWithWork selected online).1.length ≤ (selected.length + online.length) * M ∧ + (queryNeededInputsWithWork selected online).2 ≤ + queryNeededInputsBitBudget (selected.length + online.length) M B := by + let first := queryActionInputsWithWork selected + let second := queryActionInputsWithWork online + have hf := queryActionInputsWithWork_bounds selected + have hs := queryActionInputsWithWork_bounds online + have hl : (first.1 ++ second.1).length = (selected.length + online.length) * M := by + rw [List.length_append, hf.1, hs.1, Nat.add_mul] + have hsort := queryOrderedChildInputsWithWork_cost (first.1 ++ second.1) B hM hn + rw [hl] at hsort + constructor + · exact (queryOrderedChildInputsWithWork_length (first.1 ++ second.1)).trans_eq hl + · change first.2 + second.2 + first.1.length + + (queryOrderedChildInputsWithWork (first.1 ++ second.1)).2 + 2 ≤ _ + have hfc : first.2 ≤ selected.length * (5 * M + 3) + M + 1 := hf.2 + have hsc : second.2 ≤ online.length * (5 * M + 3) + M + 1 := hs.2 + unfold queryNeededInputsBitBudget + rw [Nat.add_mul] + have hfl : first.1.length ≤ (selected.length + online.length) * M := by + rw [hf.1, Nat.add_mul] + omega + omega + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryActionInputs.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryActionInputs.lean new file mode 100644 index 0000000000000000000000000000000000000000..ff51de62e69a34ad21e6d295ac9d56331bc461fd --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryActionInputs.lean @@ -0,0 +1,54 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryInputCodes +import OAI.Combinatorics.EditApproximation.Binary.BinaryBellmanKernel +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Once the selected group and online actions have been computed, the +last adaptive gather lists exactly their child coordinates, sorted by +the same injective encoding as the reference query. -/ + +namespace EditApproximation + +theorem query_mem_action_cover {Parent Child : Type*} [DecidableEq Child] {M : ℕ} + (actions : List (RationalBellmanAction Parent Child M)) (input : Child) : + input ∈ actionCurrentInputCover actions ↔ + ∃ action ∈ actions, ∃ i, action.childState i = input := by + constructor + · intro h + obtain ⟨index, _, hi⟩ := Finset.mem_biUnion.mp h + obtain ⟨i, _, heq⟩ := Finset.mem_image.mp hi + exact ⟨actions.get index, List.get_mem actions index, i, heq⟩ + · rintro ⟨action, ha, i, rfl⟩ + exact actionCurrentInputCover_mem actions action ha i + + + +theorem queryActionInputsWithWork_value {Parent Child : Type*} [DecidableEq Child] {M : ℕ} + (actions : List (BinaryBellmanAction Parent Child M)) : + (queryActionInputsWithWork actions).1.toFinset = + actionCurrentInputCover (actions.map BinaryBellmanAction.decode) := by + ext input + simp only [queryActionInputsWithWork, arithmeticFlatMapWithWork_value, arithmeticMapWithWork_value, + List.mem_toFinset, List.mem_flatMap, List.mem_map, List.mem_finRange, true_and, query_mem_action_cover] + constructor + · rintro ⟨action, ha, i, hi⟩ + exact ⟨action.decode, ⟨action, ha, rfl⟩, i, hi⟩ + · rintro ⟨action, ⟨word, hw, rfl⟩, i, hi⟩ + exact ⟨word, hw, i, hi⟩ + + + +theorem queryNeededInputsWithWork_value {n M : ℕ} + (selected online : List (BinaryBellmanAction (TargetInterval n) (Fin M × TargetInterval n) M)) : + (queryNeededInputsWithWork selected online).1 = + orderedInputs childInputCode (childInputCode_injective M n) + (actionCurrentInputCover (selected.map BinaryBellmanAction.decode) ∪ + actionCurrentInputCover (online.map BinaryBellmanAction.decode)) := by + simp only [queryNeededInputsWithWork, queryOrderedChildInputsWithWork_value, + List.toFinset_append, queryActionInputsWithWork_value] + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryActiveCost.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryActiveCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..db49c00dfcdb43005942705e2fc1762dc1e4ca0d --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryActiveCost.lean @@ -0,0 +1,131 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryFamilyActive +import OAI.Combinatorics.EditApproximation.Queries.QueryFamilyRefinementCost +import OAI.Combinatorics.EditApproximation.Queries.QueryPhysicalProgramWidth +import OAI.Combinatorics.EditApproximation.Queries.QuerySemanticRestriction + +namespace OAI + +namespace EditApproximation + +section Transport +variable {M J n : ℕ} (T : ℕ) (request : PhysicalTableRequest M J n) + (hindex : T < request.index) + +include hindex in +theorem queryRefinementRequest_eq : + PhysicalTableRequest.refinement request.pass request.copy request.node T (request.index - T) + request.state = request := by + have hi : T + (request.index - T) = request.index := by omega + unfold PhysicalTableRequest.refinement + rw [hi] + +def queryActiveChildMap {σ : Type*} (S : ℕ) : + Sum σ {child : PhysicalTableRequest M J n // child.combinedRank T S < + (PhysicalTableRequest.refinement request.pass request.copy request.node T (request.index - T) + request.state).combinedRank T S} → + Sum σ {child : PhysicalTableRequest M J n // child.combinedRank T S < request.combinedRank T S} := + Sum.map id (fun child => ⟨child.val, by simpa only [queryRefinementRequest_eq T request hindex] using child.property⟩) + +def queryActiveOracle {σ : Type*} (S : ℕ) + (oracle : Sum σ {child : PhysicalTableRequest M J n // child.combinedRank T S < request.combinedRank T S} → + BinaryFraction) := fun key => oracle (queryActiveChildMap T request hindex S key) + +def queryActiveReadWork {σ : Type*} (S : ℕ) + (readWork : Sum σ {child : PhysicalTableRequest M J n // child.combinedRank T S < request.combinedRank T S} → + ℕ) := fun key => 1 + readWork (queryActiveChildMap T request hindex S key) + +end Transport + +section Active +variable {α : Type*} {M J R : ℕ} [NeZero M] [NeZero R] + (source target : List α) (N P F exponent H Q eM eF B E Scale : ℕ) + (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) + (tau a eta kappa delta : BinaryFraction) (T S passes copies : ℕ) + (request : PhysicalTableRequest M J target.length) + (hindex : T < request.index) (hbelow : request.node.1.val < J) + (oracle : Sum (PhysicalFamilyScalarKey (M := M) (J := J) (R := R) + target N P F exponent H Q passes copies) + {child : PhysicalTableRequest M J target.length // child.combinedRank T S < request.combinedRank T S} → BinaryFraction) + (readWork : Sum (PhysicalFamilyScalarKey (M := M) (J := J) (R := R) + target N P F exponent H Q passes copies) + {child : PhysicalTableRequest M J target.length // child.combinedRank T S < request.combinedRank T S} → ℕ) + +local notation "tableOracle" => (fun key => queryActiveOracle T request hindex S oracle (Sum.inr key)) +open BinaryFraction + +theorem queryFamilyActive_work_bound (V C : ℕ) + (hn : PreparedKernelNumericBounds (nx := source.length) (ny := target.length) (M := M) + N P F exponent H Q eM eF B E Scale (request.index - T - 1) tau a eta kappa delta (fun _ _ => 0)) + (htime : Nat.size (request.index - T) ≤ B) (hPd : ∃ j : ℕ, P = 2 ^ j) + (hV : 2 ≤ V) (hVB : V ≤ B) (hMean : warmupAverageWordBudget T V ≤ B) + (hc : ∀ key, key.val.pass = request.pass → key.val.copy = request.copy → readWork (Sum.inr key) ≤ C) + (hs : ∀ key, readWork (Sum.inl key) ≤ C) + (hv : ∀ key, (oracle (Sum.inr key)).width ≤ V) + (hsv : ∀ key, (oracle (Sum.inl key)).width ≤ B) + (hnonneg : ∀ key, 0 ≤ (oracle (Sum.inr key)).value) + (hprior : ∀ input : Fin M × ℕ × TargetInterval target.length, + ((queryPhysicalEarlierRead copies request.pass request.copy T S (request.index - T) + request.node hbelow request.state input).value tableOracle).value ≤ + ((queryPhysicalWarmupRead copies request.pass request.copy T S (request.index - T) + (Nat.sub_pos_of_lt hindex) request.node request.state + (physicalChild request.node hbelow input.1) (by change request.node.1.val ≤ request.node.1.val + 1; omega) + 0 (Nat.zero_le T) input.2.2).value tableOracle).value) + (hp : Nat.size request.pass ≤ B) (hcopy : Nat.size request.copy ≤ B) + (hps : Nat.size (passes + 1) ≤ B) (hcs : Nat.size (copies + 1) ≤ B) + (hbound : Nat.size (localOnlineMassBound M P H) ≤ B) : + (queryFamilyActive (R := R) source target N P F exponent H Q eM eF hP hM hF + tau a eta kappa delta T S passes copies request hindex hbelow).work oracle readWork ≤ + queryLocalProgramBitBudget M N P F exponent eM eF B Scale (request.index - T) + (queryPhysicalDataBudget T J B V (C + 1) (queryFamilySourceReadBudget J B (C + 1 + 1))) := by + rw [queryFamilyActive, BitQuery.mapKeysWithWork_work] + change (queryFamilyRefinement (R := R) source target N P F exponent H Q eM eF hP hM hF + tau a eta kappa delta passes copies request.pass request.copy T S (request.index - T) + (Nat.sub_pos_of_lt hindex) request.node hbelow (Fin.ofNat R (request.index - T - 1)) request.state).work + (queryActiveOracle T request hindex S oracle) (queryActiveReadWork T request hindex S readWork) ≤ _ + apply queryFamilyRefinement_work_bound source target N P F exponent H Q eM eF B E Scale hP hM hF + tau a eta kappa delta passes copies request.pass request.copy T S (request.index - T) + (Nat.sub_pos_of_lt hindex) request.node hbelow (Fin.ofNat R (request.index - T - 1)) request.state + _ _ V (C + 1) hn htime hPd hV hVB hMean + · intro key hpass hcopy' + have h := hc ⟨key.val, by simpa only [queryRefinementRequest_eq T request hindex] using key.property⟩ hpass hcopy' + change 1 + readWork (Sum.inr ⟨key.val, _⟩) ≤ C + 1 + omega + · intro key + change 1 + readWork (Sum.inl key) ≤ C + 1 + have := hs key + omega + · intro key + exact hv _ + · exact hsv + · intro key + exact hnonneg _ + · exact hprior + · exact hp + · exact hcopy + · exact hps + · exact hcs + · exact hbound + +theorem queryFamilyActive_width + (hn : PreparedKernelNumericBounds (nx := source.length) (ny := target.length) (M := M) + N P F exponent H Q eM eF B E Scale (request.index - T - 1) tau a eta kappa delta (fun _ _ => 0)) + (htime : Nat.size (request.index - T) ≤ B) + (hv : ∀ key, (oracle (Sum.inr key)).width ≤ B) + (hnonneg : ∀ key, 0 ≤ (oracle (Sum.inr key)).value) : + ((queryFamilyActive (R := R) source target N P F exponent H Q eM eF hP hM hF + tau a eta kappa delta T S passes copies request hindex hbelow).value oracle).width ≤ + preparedKernelWordBudget M B := by + rw [queryFamilyActive, BitQuery.mapKeysWithWork_value] + apply queryFamilyRefinement_width source target N P F exponent H Q eM eF B E Scale hP hM hF + tau a eta kappa delta passes copies request.pass request.copy T S (request.index - T) + (Nat.sub_pos_of_lt hindex) request.node hbelow (Fin.ofNat R (request.index - T - 1)) request.state + _ hn htime + · intro key + exact hv _ + · intro key + exact hnonneg _ + +end Active +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryBandGather.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryBandGather.lean new file mode 100644 index 0000000000000000000000000000000000000000..f2cb8bb43c9f16859be14aecbe999ea7ea4d546f --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryBandGather.lean @@ -0,0 +1,65 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryInitialGather +import OAI.Combinatorics.EditApproximation.Queries.QueryRepresentatives +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! The band-data stage constructs its keys by counted Boolean routines, +then gathers mass and initial words in the reference order. -/ + +namespace EditApproximation + + + +theorem queryBandGather_refines {ι β : Type*} {nx ny : ℕ} {relation : β → ℚ → Prop} + (M : ℕ) (parent : TargetInterval nx) (N P F exponent : ℕ) (hP : 0 < P) + (a : BinaryFraction) (initial : TargetInterval ny → BinaryFraction × ℕ) (q : TargetInterval ny) + (R : ℕ) (hR : ∀ r, (initial r).2 ≤ R) + (massReader initialReader : (Fin M × TargetInterval ny) → BitQuery ι BinaryFraction) + (expectedMass expectedInitial : (Fin M × TargetInterval ny) → FiniteQuery ι) + (next : List (Fin M × TargetInterval ny) → List BinaryFraction → List BinaryFraction → + BitQuery ι β) + (expectedNext : List (Fin M × TargetInterval ny) → List ℚ → List ℚ → FiniteQuery ι) + (hm : ∀ key, BitQuery.Refines (fun word value => word.value = value) + (massReader key) (expectedMass key)) + (hi : ∀ key, BitQuery.Refines (fun word value => word.value = value) + (initialReader key) (expectedInitial key)) + (hn : ∀ mass words, + let keys := refinementBandInputList (M := M) parent N P F exponent a.value + (fun r => (initial r).1.value) q + BitQuery.Refines relation (next keys mass words) + (expectedNext keys (mass.map BinaryFraction.value) (words.map BinaryFraction.value))) : + BitQuery.Refines relation + (queryBandGather M parent N P F exponent hP a initial q massReader initialReader next) + (let keys := refinementBandInputList (M := M) parent N P F exponent a.value + (fun r => (initial r).1.value) q + FiniteQuery.collect expectedMass keys fun mass => + FiniteQuery.collect expectedInitial keys (expectedNext keys mass)) := by + change BitQuery.Refines relation (.charge _ _) _ + apply BitQuery.Refines.charge + change BitQuery.Refines relation (BitQuery.collect massReader _ _) _ + rw [BinaryFraction.queryBandInputsWithWork_value M parent N P F exponent hP a initial q R hR] + apply BitQuery.Refines.collect massReader expectedMass hm + intro mass + exact BitQuery.Refines.collect initialReader expectedInitial hi _ _ _ (hn mass) + +theorem queryBandGather_work {ι β : Type*} {nx ny : ℕ} (M : ℕ) (parent : TargetInterval nx) + (N P F exponent : ℕ) (hP : 0 < P) (a : BinaryFraction) + (initial : TargetInterval ny → BinaryFraction × ℕ) (q : TargetInterval ny) + (massReader initialReader : (Fin M × TargetInterval ny) → BitQuery ι BinaryFraction) + (next : List (Fin M × TargetInterval ny) → List BinaryFraction → List BinaryFraction → + BitQuery ι β) (oracle : ι → BinaryFraction) (readWork : ι → ℕ) : + let keys := BinaryFraction.queryBandInputsWithWork M parent N P F exponent hP a initial q + (queryBandGather M parent N P F exponent hP a initial q massReader initialReader next).work + oracle readWork = keys.2 + + (keys.1.map fun key => (massReader key).work oracle readWork + 3).sum + + (keys.1.map fun key => (initialReader key).work oracle readWork + 3).sum + + (next keys.1 (keys.1.map fun key => (massReader key).value oracle) + (keys.1.map fun key => (initialReader key).value oracle)).work oracle readWork := by + simp only [queryBandGather, BitQuery.work_bind, BitQuery.compute, + BitQuery.work, BitQuery.value, BitQuery.work_collect, Nat.add_zero, Nat.add_assoc] + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryBandInputCost.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryBandInputCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..107553420dcfcc28556c618d80530633d0cb39b5 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryBandInputCost.lean @@ -0,0 +1,67 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryRepresentativeCost +import OAI.Combinatorics.EditApproximation.Queries.QueryRepresentativeScales +import OAI.Combinatorics.EditApproximation.Queries.QueryWideBounds + +namespace OAI + +namespace EditApproximation.BinaryFraction + +def queryWideInputsBitBudget (M P count B : ℕ) : ℕ := + let G := (40 * P + 2) ^ 2 + let C := wideChildGridBitBudget P (B + 1) + count * (M * (C + 4 * G + 1 + G + 3) + M * G + 3) + + (count * (M * G) + 1) ^ 2 * (24 * B + 12) + M + 2 + +theorem queryWideInputsWithWork_dyadic_bounds {nx ny : ℕ} + (M N P count B : ℕ) (parent : TargetInterval nx) (hP : 0 < P) + (representatives : List (ℕ × TargetInterval ny)) + (hl : representatives.length ≤ count) + (hs : ∀ br ∈ representatives, br.1 ∈ dyadicScales N) + (hN : Nat.size N ≤ B) (hnx : Nat.size nx ≤ B) (hny : Nat.size ny ≤ B) + (hM : Nat.size M ≤ B) (hPb : Nat.size P ≤ B) : + (queryWideInputsWithWork M parent P representatives).1.length ≤ count * (M * (40 * P + 2) ^ 2) ∧ + (queryWideInputsWithWork M parent P representatives).2 ≤ queryWideInputsBitBudget M P count B := by + have hb := queryWideInputsWithWork_bounds M parent P representatives ((40 * P + 2) ^ 2) + (wideChildGridBitBudget P (B + 1)) B hM hny + (fun br _ i => by rw [wideChildGridWithWork_value _ _ _ _ _ hP]; exact wideChildStateList_length_le parent br.2 hP i) + (fun br hbr i => wideChildGridWithWork_cost parent br.2 br.1 P (B + 1) i hP + (by omega) (by omega) (by omega) + ((dyadicScales_size_bound N br.1 (hs br hbr)).trans (by omega)) (by omega)) + constructor + · exact hb.1.trans (Nat.mul_le_mul_right _ hl) + · apply hb.2.trans + unfold queryWideInputsBitBudget + dsimp only + gcongr + +def queryBandInputsBitBudget (M P F exponent B R : ℕ) : ℕ := + queryEarlierRepresentativesBitBudget P F exponent B R + + queryWideInputsBitBudget M P (queryEarlierRepresentativesLength P F exponent B) B + 1 + +theorem queryBandInputsWithWork_bounds {nx ny : ℕ} (M N P F exponent B R : ℕ) + (parent : TargetInterval nx) (hP : 0 < P) (a : BinaryFraction) + (initial : TargetInterval ny → BinaryFraction × ℕ) (q : TargetInterval ny) + (hB : 8 ≤ B) (hN : Nat.size N ≤ B) (hF : Nat.size F + 2 ≤ B) (hFpos : 1 ≤ F) + (hPb : Nat.size P ≤ B) (hnx : Nat.size nx ≤ B) (hny : Nat.size ny ≤ B) + (hM : Nat.size M ≤ B) (he : exponent + 1 ≤ B) (ha : a.width ≤ B) + (hi : ∀ r, (initial r).1.width ≤ B) (hR : ∀ r, (initial r).2 ≤ R) + (hw : 0 ≤ (initial q).1.value) (hPd : ∃ e : ℕ, P = 2 ^ e) : + (queryBandInputsWithWork M parent N P F exponent hP a initial q).1.length ≤ + queryEarlierRepresentativesLength P F exponent B * (M * (40 * P + 2) ^ 2) ∧ + (queryBandInputsWithWork M parent N P F exponent hP a initial q).2 ≤ + queryBandInputsBitBudget M P F exponent B R := by + have hr := queryEarlierRepresentativesWithWork_bounds N P F exponent B R hP a initial q + hB hN hF hFpos hPb hny he ha hi hR hw hPd + have hwide := queryWideInputsWithWork_dyadic_bounds M N P + (queryEarlierRepresentativesLength P F exponent B) B parent hP + (queryEarlierRepresentativesWithWork N P F exponent hP a initial q).1 hr.1 + (fun br hb => queryEarlierRepresentativesWithWork_scale N P F exponent hP a initial q R hR br hb) + hN hnx hny hM hPb + constructor + · simpa only [queryBandInputsWithWork] using hwide.1 + · simpa only [queryBandInputsWithWork, queryBandInputsBitBudget] using + Nat.add_le_add_right (Nat.add_le_add hr.2 hwide.2) 1 + +end EditApproximation.BinaryFraction + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryBoundedActiveCost.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryBoundedActiveCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..19ef5165c88931ac6701b042c76422d25f550d62 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryBoundedActiveCost.lean @@ -0,0 +1,94 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryActiveCost + +namespace OAI + +namespace EditApproximation +section Bounded +variable {α : Type*} {M J R : ℕ} [NeZero M] [NeZero R] + (source target : List α) (N P F exponent H Q eM eF B E Scale : ℕ) + (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) + (tau a eta kappa delta : BinaryFraction) (T S passes copies : ℕ) + (parent : {r : PhysicalTableRequest M J target.length // r.Bounded (passes + 1) copies T S}) + (hindex : T < parent.val.index) (hbelow : parent.val.node.1.val < J) + (oracle : QueryBoundedChild (σ := PhysicalFamilyScalarKey (M := M) (J := J) (R := R) + target N P F exponent H Q passes copies) (passes + 1) copies T S parent → BinaryFraction) + (readWork : QueryBoundedChild (σ := PhysicalFamilyScalarKey (M := M) (J := J) (R := R) + target N P F exponent H Q passes copies) (passes + 1) copies T S parent → ℕ) + +local notation "rawOracle" => queryRestrictedPhysicalOracle (passes + 1) copies T S parent oracle +local notation "rawWork" => queryRestrictedPhysicalReadWork (passes + 1) copies T S parent readWork +local notation "tableOracle" => (fun key => queryActiveOracle T parent.val hindex S rawOracle (Sum.inr key)) +open BinaryFraction + +theorem queryFamilyBoundedActive_work_bound (V C : ℕ) + (hn : PreparedKernelNumericBounds (nx := source.length) (ny := target.length) (M := M) + N P F exponent H Q eM eF B E Scale (parent.val.index - T - 1) tau a eta kappa delta (fun _ _ => 0)) + (htime : Nat.size (parent.val.index - T) ≤ B) (hPd : ∃ j : ℕ, P = 2 ^ j) + (hV : 2 ≤ V) (hVB : V ≤ B) (hMean : warmupAverageWordBudget T V ≤ B) + (hc : ∀ key, readWork key ≤ C) + (hv : ∀ key, (oracle (Sum.inr key)).width ≤ V) + (hsv : ∀ key, (oracle (Sum.inl key)).width ≤ B) + (hnonneg : ∀ key, 0 ≤ (oracle (Sum.inr key)).value) + (hprior : ∀ input : Fin M × ℕ × TargetInterval target.length, + ((queryPhysicalEarlierRead copies parent.val.pass parent.val.copy T S (parent.val.index - T) + parent.val.node hbelow parent.val.state input).value tableOracle).value ≤ + ((queryPhysicalWarmupRead copies parent.val.pass parent.val.copy T S (parent.val.index - T) + (Nat.sub_pos_of_lt hindex) parent.val.node parent.val.state + (physicalChild parent.val.node hbelow input.1) (by change parent.val.node.1.val ≤ parent.val.node.1.val + 1; omega) + 0 (Nat.zero_le T) input.2.2).value tableOracle).value) + (hp : Nat.size parent.val.pass ≤ B) (hcopy : Nat.size parent.val.copy ≤ B) + (hps : Nat.size (passes + 1) ≤ B) (hcs : Nat.size (copies + 1) ≤ B) + (hT : Nat.size T ≤ B) (hS : Nat.size S ≤ B) + (hrank : Nat.size (parent.val.combinedRank T S) ≤ B) + (hbound : Nat.size (localOnlineMassBound M P H) ≤ B) : + (queryFamilyBoundedActive (R := R) source target N P F exponent H Q eM eF hP hM hF + tau a eta kappa delta T S passes copies parent hindex hbelow).work oracle readWork ≤ + queryLocalProgramBitBudget M N P F exponent eM eF B Scale (parent.val.index - T) + (queryPhysicalDataBudget T J B V (50 * B + 21 + C + 1) + (queryFamilySourceReadBudget J B (50 * B + 21 + C + 1 + 1))) := by + rw [queryFamilyBoundedActive, queryRestrictPhysicalBody_work] + apply queryFamilyActive_work_bound source target N P F exponent H Q eM eF B E Scale hP hM hF + tau a eta kappa delta T S passes copies parent.val hindex hbelow rawOracle rawWork V + (50 * B + 21 + C) hn htime hPd hV hVB hMean + · intro key _ hcopy' + apply queryRestrictedPhysicalReadWork_bound (passes + 1) copies T S parent readWork B C + hps ((Nat.size_le_size (Nat.le_succ copies)).trans hcs) hT hS hrank hcopy hc (Sum.inr key) + intro child heq + cases heq + exact hcopy' + · intro key + apply queryRestrictedPhysicalReadWork_bound (passes + 1) copies T S parent readWork B C + hps ((Nat.size_le_size (Nat.le_succ copies)).trans hcs) hT hS hrank hcopy hc (Sum.inl key) + intro child heq + cases heq + · exact queryRestrictedPhysicalOracle_table_width (passes + 1) copies T S parent oracle V hV hv + · intro key + exact hsv key + · exact queryRestrictedPhysicalOracle_table_nonneg (passes + 1) copies T S parent oracle hnonneg + · exact hprior + · exact hp + · exact hcopy + · exact hps + · exact hcs + · exact hbound + +theorem queryFamilyBoundedActive_width + (hn : PreparedKernelNumericBounds (nx := source.length) (ny := target.length) (M := M) + N P F exponent H Q eM eF B E Scale (parent.val.index - T - 1) tau a eta kappa delta (fun _ _ => 0)) + (htime : Nat.size (parent.val.index - T) ≤ B) + (hv : ∀ key, (oracle (Sum.inr key)).width ≤ B) + (hnonneg : ∀ key, 0 ≤ (oracle (Sum.inr key)).value) : + ((queryFamilyBoundedActive (R := R) source target N P F exponent H Q eM eF hP hM hF + tau a eta kappa delta T S passes copies parent hindex hbelow).value oracle).width ≤ + preparedKernelWordBudget M B := by + rw [queryFamilyBoundedActive, queryRestrictPhysicalBody_value] + apply queryFamilyActive_width source target N P F exponent H Q eM eF B E Scale hP hM hF + tau a eta kappa delta T S passes copies parent.val hindex hbelow rawOracle hn htime + · exact queryRestrictedPhysicalOracle_table_width (passes + 1) copies T S parent oracle B + (by have := hn.largeBits; omega) hv + · exact queryRestrictedPhysicalOracle_table_nonneg (passes + 1) copies T S parent oracle hnonneg + +end Bounded +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryBoundedBody.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryBoundedBody.lean new file mode 100644 index 0000000000000000000000000000000000000000..16d4b58982c7515deee84cb4e8e096541dca985a --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryBoundedBody.lean @@ -0,0 +1,67 @@ +import OAI.Combinatorics.EditApproximation.Binary.BitQueryKeys +import OAI.Combinatorics.EditApproximation.Geometry.SourceRankedRestriction +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalDependencyRank +import OAI.Combinatorics.EditApproximation.Queries.QueryPhysicalScalarGuards +import OAI.Combinatorics.EditApproximation.Binary.BinaryArithmeticWork +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Finite-domain guards execute binary comparisons on table coordinates. +Random-source coordinates pass through the guard unchanged. -/ + +namespace EditApproximation + +@[simp] theorem queryNaturalLEWithWork_value (a b : ℕ) : + (wordLEWithWork a.bits b.bits).1 = true ↔ a ≤ b := by + simp only [wordLEWithWork_value, bitWordValue_bits] + + + +@[simp] theorem queryPhysicalBoundedWithWork_value {M J n : ℕ} + (passes copies T S : ℕ) (request : PhysicalTableRequest M J n) : + (queryPhysicalBoundedWithWork passes copies T S request).1 = true ↔ + request.Bounded passes copies T S := by + simp only [queryPhysicalBoundedWithWork, Bool.and_eq_true, decide_eq_true_eq, + binaryNaturalCompareWithWork_lt, wordLEWithWork_value, bitWordValue_bits, + binaryNaturalAddWithWork_value, PhysicalTableRequest.Bounded] + tauto + +section Body +variable {σ : Type*} {M J n : ℕ} (passes copies T S : ℕ) + (parent : {r : PhysicalTableRequest M J n // r.Bounded passes copies T S}) + + + + + +@[simp] theorem querySupportedChildWithWork_value + (key : QueryPhysicalChild (σ := σ) passes copies T S parent) : + (querySupportedChildWithWork passes copies T S parent key).1 = true ↔ + SourceRanked.supportedChild (PhysicalTableRequest.combinedRank T S) + (PhysicalTableRequest.Bounded passes copies T S) parent.val key := by + cases key with + | inl source => exact iff_of_true rfl trivial + | inr child => exact queryPhysicalBoundedWithWork_value passes copies T S child.val + + + +theorem queryRestrictPhysicalBody_refines + (program : BitQuery (QueryPhysicalChild (σ := σ) passes copies T S parent) BinaryFraction) + (expected : (request : PhysicalTableRequest M J n) → + FiniteQuery (Sum σ {child : PhysicalTableRequest M J n // + child.combinedRank T S < request.combinedRank T S})) + (h : BitQuery.Refines (fun word value => word.value = value) program (expected parent.val)) : + BitQuery.Refines (fun word value => word.value = value) + (queryRestrictPhysicalBody passes copies T S parent program) + (SourceRanked.restrictBody (PhysicalTableRequest.combinedRank T S) + (PhysicalTableRequest.Bounded passes copies T S) expected parent) := by + classical + exact (h.restrictWithWork _ _ (querySupportedChildWithWork_value passes copies T S parent)).mapKeysWithWork + _ _ (fun _ => rfl) + +end Body +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryBoundedSemanticCost.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryBoundedSemanticCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..5b4051383a45470a1fa455e0d33e5aafe9dfa89e --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryBoundedSemanticCost.lean @@ -0,0 +1,49 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryBoundedActiveCost + +namespace OAI + +namespace EditApproximation +section History +variable {σ α : Type*} [DecidableEq α] {M J R : ℕ} [NeZero R] + (source target : List α) (N P F exponent H Q T S passes copies : ℕ) + (factor : ℕ → ℚ) (multiplier : ℕ → ℕ) (tau eta kappa delta : ℚ) + (group : ℕ → ℕ → PhysicalInternalNode M J → Fin R → CellGroupDraws M F Q) + (integer : ℕ → ℕ → PhysicalInternalNode M J → Fin R → ℕ → TargetInterval target.length → ℕ) + (initial : PhysicalEntry M J target.length → ℕ) + (parent : {r : PhysicalTableRequest M J target.length // r.Bounded (passes + 1) copies T S}) + (hindex : T < parent.val.index) (hbelow : parent.val.node.1.val < J) + (oracle : QueryBoundedChild (σ := σ) (passes + 1) copies T S parent → BinaryFraction) + +local notation "requestValue" => localRequestValue source target N P F exponent H Q T S copies + factor multiplier tau eta kappa delta group integer initial +local notation "rawOracle" => queryRestrictedPhysicalOracle (passes + 1) copies T S parent oracle +local notation "tableOracle" => (fun key => queryActiveOracle T parent.val hindex S rawOracle (Sum.inr key)) + +theorem queryBoundedSemantic_nonneg (hdelta : 0 ≤ delta) + (hread : ∀ key, (oracle (Sum.inr key)).value = requestValue key.val.val) + (key) : 0 ≤ (oracle (Sum.inr key)).value := by + rw [hread] + exact (localRequestValue_bounds source target N P F exponent H Q T S copies factor multiplier + tau eta kappa delta group integer initial hdelta key.val.val).1 + +theorem queryFamilyBoundedActive_history_bound (hdelta : 0 ≤ delta) + (hread : ∀ key, (oracle (Sum.inr key)).value = requestValue key.val.val) + (input : Fin M × ℕ × TargetInterval target.length) : + ((queryPhysicalEarlierRead copies parent.val.pass parent.val.copy T S (parent.val.index - T) + parent.val.node hbelow parent.val.state input).value tableOracle).value ≤ + ((queryPhysicalWarmupRead copies parent.val.pass parent.val.copy T S (parent.val.index - T) + (Nat.sub_pos_of_lt hindex) parent.val.node parent.val.state + (physicalChild parent.val.node hbelow input.1) (by change parent.val.node.1.val ≤ parent.val.node.1.val + 1; omega) + 0 (Nat.zero_le T) input.2.2).value tableOracle).value := by + have ht : parent.val.index - T ≤ S := by have := parent.property.2.2; omega + have h := queryRestrictedPhysicalOracle_history_bound source target N P F exponent H Q T S copies + factor multiplier tau eta kappa delta group integer initial (passes + 1) parent.val.pass parent.val.copy + (parent.val.index - T) (Nat.sub_pos_of_lt hindex) ht parent.property.1 parent.property.2.1 hdelta + parent.val.node hbelow parent.val.state parent (queryRefinementRequest_eq T parent.val hindex).symm + oracle hread input + exact h + +end History +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryBoundedWork.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryBoundedWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..dac358bb4d93eacf47d1fdaba4413b8f192b4ca2 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryBoundedWork.lean @@ -0,0 +1,130 @@ +import OAI.Combinatorics.EditApproximation.Queries.QuerySourceWidths +import OAI.Combinatorics.EditApproximation.Queries.QueryRestrictionCost + +namespace OAI + +namespace EditApproximation +section Body +variable {σ : Type*} {M J n : ℕ} (passes copies T S : ℕ) + (parent : {r : PhysicalTableRequest M J n // r.Bounded passes copies T S}) + +abbrev QueryBoundedChild := Sum σ {child : {r : PhysicalTableRequest M J n // + r.Bounded passes copies T S} // child.val.combinedRank T S < parent.val.combinedRank T S} + +def queryRestrictedPhysicalOracle (oracle : QueryBoundedChild (σ := σ) passes copies T S parent → BinaryFraction) : + QueryPhysicalChild (σ := σ) passes copies T S parent → BinaryFraction := + BitQuery.restrictedOracle _ (querySupportedChildWithWork passes copies T S parent) + (querySupportedChildWithWork_value passes copies T S parent) + (fun key => oracle (SourceRanked.supportedChildMap (PhysicalTableRequest.combinedRank T S) + (PhysicalTableRequest.Bounded passes copies T S) parent key)) + +def queryRestrictedPhysicalReadWork (readWork : QueryBoundedChild (σ := σ) passes copies T S parent → ℕ) : + QueryPhysicalChild (σ := σ) passes copies T S parent → ℕ := + BitQuery.restrictedReadWork _ (querySupportedChildWithWork passes copies T S parent) + (querySupportedChildWithWork_value passes copies T S parent) + (fun key => 1 + readWork (SourceRanked.supportedChildMap (PhysicalTableRequest.combinedRank T S) + (PhysicalTableRequest.Bounded passes copies T S) parent key)) + +theorem queryRestrictPhysicalBody_work + (program : BitQuery (QueryPhysicalChild (σ := σ) passes copies T S parent) BinaryFraction) + (oracle : QueryBoundedChild (σ := σ) passes copies T S parent → BinaryFraction) + (readWork : QueryBoundedChild (σ := σ) passes copies T S parent → ℕ) : + (queryRestrictPhysicalBody passes copies T S parent program).work oracle readWork = + program.work (queryRestrictedPhysicalOracle passes copies T S parent oracle) + (queryRestrictedPhysicalReadWork passes copies T S parent readWork) := by + rw [queryRestrictPhysicalBody, BitQuery.mapKeysWithWork_work, BitQuery.restrictWithWork_work] + rfl + +theorem queryRestrictPhysicalBody_value + (program : BitQuery (QueryPhysicalChild (σ := σ) passes copies T S parent) BinaryFraction) + (oracle : QueryBoundedChild (σ := σ) passes copies T S parent → BinaryFraction) : + (queryRestrictPhysicalBody passes copies T S parent program).value oracle = + program.value (queryRestrictedPhysicalOracle passes copies T S parent oracle) := by + rw [queryRestrictPhysicalBody, BitQuery.mapKeysWithWork_value, BitQuery.restrictWithWork_value] + rfl + +theorem queryRestrictedPhysicalOracle_table_width + (oracle : QueryBoundedChild (σ := σ) passes copies T S parent → BinaryFraction) + (B : ℕ) (hB : 2 ≤ B) (hw : ∀ key, (oracle (Sum.inr key)).width ≤ B) (child) : + (queryRestrictedPhysicalOracle passes copies T S parent oracle (Sum.inr child)).width ≤ B := by + unfold queryRestrictedPhysicalOracle BitQuery.restrictedOracle + split + · exact hw _ + · exact (BinaryFraction.nat_width_le 0).trans (by simpa only [Nat.size_zero, Nat.zero_add] using hB) + +theorem queryRestrictedPhysicalOracle_table_nonneg + (oracle : QueryBoundedChild (σ := σ) passes copies T S parent → BinaryFraction) + (hn : ∀ key, 0 ≤ (oracle (Sum.inr key)).value) (child) : + 0 ≤ (queryRestrictedPhysicalOracle passes copies T S parent oracle (Sum.inr child)).value := by + unfold queryRestrictedPhysicalOracle BitQuery.restrictedOracle + split + · exact hn _ + · simp only [BinaryFraction.nat_value, Nat.cast_zero, le_refl] + +theorem queryRestrictedPhysicalOracle_width + (oracle : QueryBoundedChild (σ := σ) passes copies T S parent → BinaryFraction) + (B : ℕ) (hB : 2 ≤ B) (hw : ∀ key, (oracle key).width ≤ B) (key) : + (queryRestrictedPhysicalOracle passes copies T S parent oracle key).width ≤ B := + BitQuery.restrictedOracle_width _ _ _ _ B hB (fun _ => hw _) key + +@[simp] theorem queryRestrictedPhysicalOracle_source + (oracle : QueryBoundedChild (σ := σ) passes copies T S parent → BinaryFraction) (source : σ) : + queryRestrictedPhysicalOracle passes copies T S parent oracle (Sum.inl source) = oracle (Sum.inl source) := rfl + +theorem queryRestrictedPhysicalOracle_table + (oracle : QueryBoundedChild (σ := σ) passes copies T S parent → BinaryFraction) + (child : {r : PhysicalTableRequest M J n // r.combinedRank T S < parent.val.combinedRank T S}) + (hb : child.val.Bounded passes copies T S) : + queryRestrictedPhysicalOracle passes copies T S parent oracle (Sum.inr child) = + oracle (Sum.inr ⟨⟨child.val, hb⟩, child.property⟩) := by + unfold queryRestrictedPhysicalOracle BitQuery.restrictedOracle + rw [dite_eq_left ((querySupportedChildWithWork_value passes copies T S parent (Sum.inr child)).mpr hb)] + rfl + +private theorem index_le_combinedRank (request : PhysicalTableRequest M J n) : + request.index ≤ request.combinedRank T S := by + unfold PhysicalTableRequest.combinedRank PhysicalTableRequest.rank + omega + +private theorem pass_le_combinedRank (request : PhysicalTableRequest M J n) : + request.pass ≤ request.combinedRank T S := by + have hmul : request.pass ≤ request.pass * (T + S + 1) := Nat.le_mul_of_pos_right _ (by omega) + unfold PhysicalTableRequest.combinedRank PhysicalTableRequest.rank + omega + +theorem queryRestrictedPhysicalReadWork_bound + (readWork : QueryBoundedChild (σ := σ) passes copies T S parent → ℕ) (B W : ℕ) + (hp : Nat.size passes ≤ B) (hc : Nat.size copies ≤ B) (hT : Nat.size T ≤ B) (hS : Nat.size S ≤ B) + (hr : Nat.size (parent.val.combinedRank T S) ≤ B) (hcopy : Nat.size parent.val.copy ≤ B) + (hW : ∀ key, readWork key ≤ W) + (key : QueryPhysicalChild (σ := σ) passes copies T S parent) + (hk : ∀ child, key = Sum.inr child → child.val.copy = parent.val.copy) : + queryRestrictedPhysicalReadWork passes copies T S parent readWork key ≤ 50 * B + 21 + W := by + have hread (k) := hW (SourceRanked.supportedChildMap (PhysicalTableRequest.combinedRank T S) + (PhysicalTableRequest.Bounded passes copies T S) parent k) + cases key with + | inl source => + change 1 + (1 + readWork _) ≤ _ + have := hread ⟨Sum.inl source, trivial⟩ + omega + | inr child => + have hpass : Nat.size child.val.pass ≤ B := + (Nat.size_le_size ((pass_le_combinedRank T S child.val).trans child.property.le)).trans hr + have hindex : Nat.size child.val.index ≤ B := + (Nat.size_le_size ((index_le_combinedRank T S child.val).trans child.property.le)).trans hr + have hcopy' : Nat.size child.val.copy ≤ B := by rw [hk child rfl]; exact hcopy + have hguard := queryPhysicalBoundedWithWork_cost passes copies T S B child.val hp hc hT hS hpass hcopy' hindex + unfold queryRestrictedPhysicalReadWork BitQuery.restrictedReadWork + change (querySupportedChildWithWork (σ := σ) passes copies T S parent (Sum.inr child)).2 ≤ 50 * B + 20 at hguard + by_cases hgate : (querySupportedChildWithWork (σ := σ) passes copies T S parent (Sum.inr child)).1 = true + · rw [dite_eq_left hgate] + dsimp only + have := hread ⟨Sum.inr child, (querySupportedChildWithWork_value passes copies T S parent _).mp hgate⟩ + omega + · rw [dite_eq_right hgate] + omega + +end Body +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryBufferSpace.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryBufferSpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..4becf6ffec9ac572ac6848bc86360ebeba832410 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryBufferSpace.lean @@ -0,0 +1,197 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryDataBuffers +import OAI.Combinatorics.EditApproximation.Binary.BinaryBufferSpace +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation + +/-- Materializing the two natural-word encodings fits the comparison loop. -/ +theorem bitCompareWithWork_input_cells (left right : List Bool) : + left.length + right.length ≤ (bitCompareWithWork left right).2 := by + induction left generalizing right with + | nil => + simp only [bitCompareWithWork] + induction right with + | nil => decide + | cons bit rest ih => + simp only [bitCompareNilLeftWithWork, List.length_nil, List.length_cons] at * + omega + | cons bit rest ih => + cases right with + | nil => + have h := ih [] + simp only [bitCompareWithWork, List.length_nil, List.length_cons] at * + omega + | cons bit' rest' => + have h := ih rest' + simp only [bitCompareWithWork, List.length_cons] at * + omega + + + +theorem naturalEqualAllocation_le_work (a b : ℕ) : + naturalEqualAllocation a b ≤ (naturalEqualWithWork a b).2 := + Nat.add_le_add_right (bitCompareWithWork_input_cells a.bits b.bits) 1 + + + +theorem coordinateEqualAllocation_le_work {M n : ℕ} (a b : Fin M × TargetInterval n) : + coordinateEqualAllocation a b ≤ (coordinateEqualWithWork a b).2 := by + have hi := naturalEqualAllocation_le_work a.1.val b.1.val + have hl := naturalEqualAllocation_le_work a.2.lo b.2.lo + have hh := naturalEqualAllocation_le_work a.2.hi b.2.hi + unfold coordinateEqualAllocation coordinateEqualWithWork + dsimp only + omega + + + +theorem queryHistoryEqualAllocation_le_work {M n : ℕ} (a b : Fin M × ℕ × TargetInterval n) : + queryHistoryEqualAllocation a b ≤ (queryHistoryEqualWithWork a b).2 := by + have hc := coordinateEqualAllocation_le_work (a.1, a.2.2) (b.1, b.2.2) + have ht := naturalEqualAllocation_le_work a.2.1 b.2.1 + unfold queryHistoryEqualAllocation queryHistoryEqualWithWork + dsimp only + omega + + + +theorem queryIntervalEqualAllocation_le_work {n : ℕ} (a b : TargetInterval n) : + queryIntervalEqualAllocation a b ≤ (queryIntervalEqualWithWork a b).2 := by + have hl := naturalEqualAllocation_le_work a.lo b.lo + have hh := naturalEqualAllocation_le_work a.hi b.hi + unfold queryIntervalEqualAllocation queryIntervalEqualWithWork + dsimp only + omega + + + +theorem queryOnlineKeyEqualAllocation_le_work {n : ℕ} (a b : ℕ × TargetInterval n) : + queryOnlineKeyEqualAllocation a b ≤ (queryOnlineKeyEqualWithWork a b).2 := by + have hs := naturalEqualAllocation_le_work a.1 b.1 + have hi := queryIntervalEqualAllocation_le_work a.2 b.2 + unfold queryOnlineKeyEqualAllocation queryOnlineKeyEqualWithWork + dsimp only + omega + + + +theorem queryGroupKeyEqualAllocation_le_work {M F Q : ℕ} (a b : GroupScalarKey M F Q) : + queryGroupKeyEqualAllocation a b ≤ (queryGroupKeyEqualWithWork a b).2 := by + have h1 := naturalEqualAllocation_le_work a.1.1 b.1.1 + have h2 := naturalEqualAllocation_le_work a.1.2.1 b.1.2.1 + have h3 := naturalEqualAllocation_le_work a.1.2.2 b.1.2.2 + have h4 := naturalEqualAllocation_le_work a.2.1.val b.2.1.val + have h5 := naturalEqualAllocation_le_work a.2.2.val b.2.2.val + unfold queryGroupKeyEqualAllocation queryGroupKeyEqualWithWork + dsimp only + omega + +def naturalEqualInvocations (a b : ℕ) : ℕ := bitCompareInvocations a.bits b.bits + 1 + +theorem naturalEqualInvocations_le_work (a b : ℕ) : + naturalEqualInvocations a b ≤ (naturalEqualWithWork a b).2 := + Nat.add_le_add_right (bitCompareInvocations_le_work a.bits b.bits) 1 + +def coordinateEqualInvocations {M n : ℕ} (a b : Fin M × TargetInterval n) : ℕ := + naturalEqualInvocations a.1.val b.1.val + naturalEqualInvocations a.2.lo b.2.lo + + naturalEqualInvocations a.2.hi b.2.hi + 1 + +theorem coordinateEqualInvocations_le_work {M n : ℕ} (a b : Fin M × TargetInterval n) : + coordinateEqualInvocations a b ≤ (coordinateEqualWithWork a b).2 := by + have hi := naturalEqualInvocations_le_work a.1.val b.1.val + have hl := naturalEqualInvocations_le_work a.2.lo b.2.lo + have hh := naturalEqualInvocations_le_work a.2.hi b.2.hi + unfold coordinateEqualInvocations coordinateEqualWithWork + dsimp only + omega + +def queryHistoryEqualInvocations {M n : ℕ} (a b : Fin M × ℕ × TargetInterval n) : ℕ := + coordinateEqualInvocations (a.1, a.2.2) (b.1, b.2.2) + naturalEqualInvocations a.2.1 b.2.1 + 1 + +theorem queryHistoryEqualInvocations_le_work {M n : ℕ} (a b : Fin M × ℕ × TargetInterval n) : + queryHistoryEqualInvocations a b ≤ (queryHistoryEqualWithWork a b).2 := by + have hc := coordinateEqualInvocations_le_work (a.1, a.2.2) (b.1, b.2.2) + have ht := naturalEqualInvocations_le_work a.2.1 b.2.1 + unfold queryHistoryEqualInvocations queryHistoryEqualWithWork + dsimp only + omega + +namespace BinaryFraction + + + +theorem queryChildReadAllocation_le_work {M n : ℕ} (keys : List (Fin M × TargetInterval n)) + (values : List BinaryFraction) (i : Fin M) (q : TargetInterval n) : + queryChildReadAllocation keys values i q ≤ (queryChildReadWithWork keys values i q).2 := + gatheredLookupAllocation_le_work _ _ _ _ _ (fun key _ => coordinateEqualAllocation_le_work _ key) + + + +theorem queryHistoryReadAllocation_le_work {M n : ℕ} (keys : List (Fin M × ℕ × TargetInterval n)) + (values : List BinaryFraction) (s : ℕ) (input : Fin M × TargetInterval n) : + queryHistoryReadAllocation keys values s input ≤ (queryHistoryReadWithWork keys values s input).2 := + gatheredLookupAllocation_le_work _ _ _ _ _ (fun key _ => queryHistoryEqualAllocation_le_work _ key) + + + +theorem naturalFloorAllocation_le_work (a : BinaryFraction) : + naturalFloorAllocation a ≤ (naturalFloorWithWork a).2 := by + have h := bitDivModAllocation_le_work a.denominator a.numerator.bits + unfold naturalFloorAllocation naturalFloorWithWork + split_ifs <;> dsimp only <;> omega + + + +theorem queryOnlineIntegerReadAllocation_le_work {n : ℕ} (keys : List (ℕ × TargetInterval n)) + (values : List BinaryFraction) (b : ℕ) (q : TargetInterval n) : + queryOnlineIntegerReadAllocation keys values b q ≤ (queryOnlineIntegerReadWithWork keys values b q).2 := by + have hl := gatheredLookupAllocation_le_work queryOnlineKeyEqualWithWork queryOnlineKeyEqualAllocation + keys values (b, q) (fun key _ => queryOnlineKeyEqualAllocation_le_work _ key) + have hf := naturalFloorAllocation_le_work (gatheredWordLookupWithWork queryOnlineKeyEqualWithWork keys values (b, q)).1 + unfold queryOnlineIntegerReadAllocation queryOnlineIntegerReadWithWork + dsimp only + omega + + + +theorem queryGroupDrawReadAllocation_le_work {M F Q : ℕ} [NeZero M] + (keys : List (GroupScalarKey M F Q)) (values : List BinaryFraction) + (b : ℕ) (cell : ℕ × ℕ) (scale : Fin (groupDyadicScales M b F).length) + (sample : Fin (groupSampleCount M Q b (groupDyadicScaleAt M b F scale))) : + queryGroupDrawReadAllocation keys values b cell scale sample ≤ + (queryGroupDrawReadWithWork keys values b cell scale sample).2 := by + let key : GroupScalarKey M F Q := ⟨(b, cell), scale, sample⟩ + have hl := gatheredLookupAllocation_le_work queryGroupKeyEqualWithWork queryGroupKeyEqualAllocation + keys values key (fun key' _ => queryGroupKeyEqualAllocation_le_work key key') + have hf := naturalFloorAllocation_le_work (gatheredWordLookupWithWork queryGroupKeyEqualWithWork keys values key).1 + have hd := bitDivModAllocation_le_work M.bits + (bitWordValue (naturalFloorWithWork (gatheredWordLookupWithWork queryGroupKeyEqualWithWork keys values key).1).1).bits + unfold queryGroupDrawReadAllocation queryGroupDrawReadWithWork binaryNaturalDivModWithWork + dsimp only [key] at hl hf hd ⊢ + omega + +def queryChildReadInvocations {M n : ℕ} (keys : List (Fin M × TargetInterval n)) + (values : List BinaryFraction) (i : Fin M) (q : TargetInterval n) : ℕ := + gatheredLookupInvocations coordinateEqualWithWork coordinateEqualInvocations keys values (i, q) + +theorem queryChildReadInvocations_le_work {M n : ℕ} (keys : List (Fin M × TargetInterval n)) + (values : List BinaryFraction) (i : Fin M) (q : TargetInterval n) : + queryChildReadInvocations keys values i q ≤ (queryChildReadWithWork keys values i q).2 := + gatheredLookupInvocations_le_work _ _ _ _ _ (fun key _ => coordinateEqualInvocations_le_work _ key) + +def queryHistoryReadInvocations {M n : ℕ} (keys : List (Fin M × ℕ × TargetInterval n)) + (values : List BinaryFraction) (s : ℕ) (input : Fin M × TargetInterval n) : ℕ := + gatheredLookupInvocations queryHistoryEqualWithWork queryHistoryEqualInvocations keys values (input.1, s, input.2) + +theorem queryHistoryReadInvocations_le_work {M n : ℕ} (keys : List (Fin M × ℕ × TargetInterval n)) + (values : List BinaryFraction) (s : ℕ) (input : Fin M × TargetInterval n) : + queryHistoryReadInvocations keys values s input ≤ (queryHistoryReadWithWork keys values s input).2 := + gatheredLookupInvocations_le_work _ _ _ _ _ (fun key _ => queryHistoryEqualInvocations_le_work _ key) + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryBufferedInputBounds.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryBufferedInputBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..9f476d1ab1628af2ea125c640686c0e3c1f4cbcf --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryBufferedInputBounds.lean @@ -0,0 +1,91 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryBufferInputBounds +import OAI.Combinatorics.EditApproximation.Queries.QueryLocalBuffers +import OAI.Combinatorics.EditApproximation.Queries.QueryHistoryInputs + +namespace OAI + +/-! Numeric input records for the actual adaptive buffers. Earlier values +are bounded by the separately gathered child-initial table, including at +keys absent from the buffers, where the executable lookup returns zero. -/ + +namespace EditApproximation.BinaryFraction + +theorem queryGatheredRefinementHistory_range {nx ny M : ℕ} (parent : TargetInterval nx) + (N P F exponent t Rp : ℕ) (hP : 0 < P) (a : BinaryFraction) + (parentInitial : TargetInterval ny → BinaryFraction × ℕ) + (hp : ∀ r, (parentInitial r).2 ≤ Rp) (q : TargetInterval ny) + (historical : Fin M × ℕ × TargetInterval ny → BinaryFraction) + (initial : Fin M × TargetInterval ny → BinaryFraction) + (hnonneg : ∀ input, 0 ≤ (historical input).value) + (hinitial : ∀ input, 0 ≤ (initial input).value) + (hbound : ∀ input, (historical input).value ≤ (initial (input.1, input.2.2)).value) + (s : ℕ) (input : Fin M × TargetInterval ny) : + let earlier := (queryEarlierInputsWithWork M parent N P F exponent t hP a parentInitial q).1 + let band := (queryBandInputsWithWork M parent N P F exponent hP a parentInitial q).1 + 0 ≤ (queryHistoryReadWithWork earlier (earlier.map historical) s input).1.value ∧ + (queryHistoryReadWithWork earlier (earlier.map historical) s input).1.value ≤ + (queryChildReadWithWork band (band.map initial) input.1 input.2).1.value := by + have h := gatheredRefinementHistory_range parent N P F exponent t a.value + (fun r => (parentInitial r).1.value) q queryHistoryEqualWithWork coordinateEqualWithWork + queryHistoryEqualWithWork_value coordinateEqualWithWork_value historical initial + hnonneg hinitial hbound (input.1, s, input.2) + simpa only [queryHistoryReadWithWork, queryChildReadWithWork, + queryEarlierInputsWithWork_value M parent N P F exponent t hP a parentInitial q Rp hp, + queryBandInputsWithWork_value M parent N P F exponent hP a parentInitial q Rp hp] using h + +theorem queryBufferedRefinementInputBounds {nx ny M : ℕ} (parent : TargetInterval nx) + (N P F exponent H Q eM eF B E S t Rp : ℕ) (hP : 0 < P) + (tau a eta kappa delta : BinaryFraction) + (parentInitial : TargetInterval ny → BinaryFraction × ℕ) + (hp : ∀ r, (parentInitial r).2 ≤ Rp) (q : TargetInterval ny) + (massWords currentWords : List BinaryFraction) (currentKeys : List (Fin M × TargetInterval ny)) + (historical : Fin M × ℕ × TargetInterval ny → BinaryFraction) + (initial : Fin M × TargetInterval ny → BinaryFraction) + (integer : ℕ → TargetInterval ny → ℕ) + (hn : PreparedKernelNumericBounds (nx := nx) (M := M) N P F exponent H Q eM eF B E S (t - 1) + tau a eta kappa delta integer) + (hpw : ∀ r, (parentInitial r).1.width ≤ B) (hpn : ∀ r, 0 ≤ (parentInitial r).1.value) + (hmw : ∀ w ∈ massWords, w.width ≤ B) (hcw : ∀ w ∈ currentWords, w.width ≤ B) + (hiw : ∀ input, (initial input).width ≤ B) (hhw : ∀ input, (historical input).width ≤ B) + (hin : ∀ input, 0 ≤ (initial input).value) (hhn : ∀ input, 0 ≤ (historical input).value) + (hbound : ∀ input, (historical input).value ≤ (initial (input.1, input.2.2)).value) : + let earlier := (queryEarlierInputsWithWork M parent N P F exponent t hP a parentInitial q).1 + let band := (queryBandInputsWithWork M parent N P F exponent hP a parentInitial q).1 + PreparedKernelInputBounds (nx := nx) N P F exponent H Q eM eF B E S (t - 1) + tau a eta kappa delta (fun r => (parentInitial r).1) + (fun i r => (queryChildReadWithWork band massWords i r).1) + (fun i r => (queryChildReadWithWork band (band.map initial) i r).1) + (fun input => (queryHistoryReadWithWork earlier (earlier.map historical) (t - 1) input).1) + (fun input => (queryChildReadWithWork currentKeys currentWords input.1 input.2).1) + (fun s input => (queryHistoryReadWithWork earlier (earlier.map historical) s input).1) integer := by + let earlier := (queryEarlierInputsWithWork M parent N P F exponent t hP a parentInitial q).1 + let band := (queryBandInputsWithWork M parent N P F exponent hP a parentInitial q).1 + have hB : 2 ≤ B := by have := hn.largeBits; omega + have hew : ∀ w ∈ earlier.map historical, w.width ≤ B := by + intro w hw + obtain ⟨key, _, rfl⟩ := List.mem_map.mp hw + exact hhw key + have hiw' : ∀ w ∈ band.map initial, w.width ≤ B := by + intro w hw + obtain ⟨key, _, rfl⟩ := List.mem_map.mp hw + exact hiw key + apply hn.with_independent_cached_values + · exact hpw + · intro i r + exact gatheredWordLookupWithWork_width _ band massWords (i, r) B hB hmw + · intro i r + exact gatheredWordLookupWithWork_width _ band (band.map initial) (i, r) B hB hiw' + · intro input + exact queryHistoryReadWithWork_width earlier (earlier.map historical) (t - 1) input B hB hew + · intro input + exact gatheredWordLookupWithWork_width _ currentKeys currentWords input B hB hcw + · intro s _ i r + exact queryHistoryReadWithWork_width earlier (earlier.map historical) s (i, r) B hB hew + · exact hpn + · intro s _ i r + exact queryGatheredRefinementHistory_range parent N P F exponent t Rp hP a parentInitial hp q + historical initial hhn hin hbound s (i, r) + +end EditApproximation.BinaryFraction + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryBufferedSharedCost.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryBufferedSharedCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..bb5c2edddea174c14e5bb67d8082407da1e9be38 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryBufferedSharedCost.lean @@ -0,0 +1,51 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryScopedSourceCost +import OAI.Combinatorics.EditApproximation.Queries.QuerySharedInputCost + +namespace OAI + +/-! Shared-state generation using the actual gathered scalar buffer. +The lookup bound is instantiated at visited keys, including discarded cells. -/ + +namespace EditApproximation.BinaryFraction + +def queryBufferedGroupReadBudget (M F exponent eM eF B V : ℕ) : ℕ := + queryGroupBufferReadBudget (queryGroupSourceKeysLength M F exponent eM eF B) B V + +theorem querySharedInputsWithWork_buffered_bounds {nx ny M N F Q : ℕ} [NeZero M] + (exponent eM eF B V : ℕ) (hMdef : M = 2 ^ eM) (hFdef : F = 2 ^ eF) + (parent : TargetInterval nx) (a value : BinaryFraction) (q : TargetInterval ny) + (words : List BinaryFraction) + (hB : 7 ≤ B) (hN : Nat.size N ≤ B) (hF : Nat.size F + 2 ≤ B) + (hM : Nat.size M + 2 ≤ B) (hQ : Nat.size Q + 2 ≤ B) (hes : eM + eF + 7 ≤ B) + (he : exponent + 1 ≤ B) (hnx : Nat.size nx ≤ B) (hny : Nat.size ny ≤ B) + (ha : a.width ≤ B) (hv : value.width ≤ B) (hw : 0 ≤ value.value) + (hV : 2 ≤ V) (hwords : ∀ v ∈ words, v.width ≤ V) : + let keys := (queryGroupSourceKeysWithWork M N F Q exponent eM eF hMdef hFdef a value q).1 + let result := querySharedInputsWithWork M N F Q exponent eM eF hMdef hFdef parent a value q + (queryGroupDrawReadWithWork keys words) + result.1.length ≤ querySharedInputsLength M F exponent eM eF B ∧ + result.2 ≤ querySharedInputsBitBudget M F exponent eM eF B + (queryBufferedGroupReadBudget M F exponent eM eF B V) := by + have hk := (queryGroupSourceKeysWithWork_bounds M N F Q exponent eM eF B hMdef hFdef a value q + hB hN hF hM hQ hes he hny ha hv hw).1 + apply querySharedInputsWithWork_bounds_on M N F Q exponent eM eF B + (queryBufferedGroupReadBudget M F exponent eM eF B V) hMdef hFdef parent a value q + (queryGroupDrawReadWithWork _ words) hB hN hF hM hQ hes he hnx hny ha hv hw + intro eb heb cell hcell scale sample + have hguard : (refinementScaleGuardWithWork F (2 ^ eb) a value).1 = true := by + have h := heb + simp only [queryExponentsWithWork, filterWithWork_value, List.mem_filter] at h + exact h.2 + have hrange : eb ∈ List.range (max 1 N.bits.length) := by + have h := heb + simp only [queryExponentsWithWork, filterWithWork_value, List.mem_filter] at h + exact h.1 + have hc := queryGroupDrawReadWithWork_scoped_cost exponent eM eF B V hMdef hFdef a value q words + hB hN hF (by omega) (by omega) he hny ha hv hw hV hwords eb hrange hguard cell hcell scale sample + apply hc.trans + unfold queryBufferedGroupReadBudget queryGroupBufferReadBudget + gcongr + +end EditApproximation.BinaryFraction + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryBufferedSourceBounds.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryBufferedSourceBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..955f80e53812efba04fc850b21f6108bfbed5eb6 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryBufferedSourceBounds.lean @@ -0,0 +1,65 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryBufferedSharedCost + +namespace OAI + +namespace EditApproximation.BinaryFraction + +theorem queryBufferedGroupReadCost {n M N F Q : ℕ} [NeZero M] + (exponent eM eF B V : ℕ) (hMdef : M = 2 ^ eM) (hFdef : F = 2 ^ eF) + (a value : BinaryFraction) (q : TargetInterval n) (words : List BinaryFraction) + (hB : 7 ≤ B) (hN : Nat.size N ≤ B) (hF : Nat.size F + 2 ≤ B) + (hM : Nat.size M + 2 ≤ B) (hQ : Nat.size Q + 2 ≤ B) (hes : eM + eF + 7 ≤ B) + (he : exponent + 1 ≤ B) (hn : Nat.size n ≤ B) (ha : a.width ≤ B) + (hv : value.width ≤ B) (hw : 0 ≤ value.value) (hV : 2 ≤ V) + (hwords : ∀ v ∈ words, v.width ≤ V) : + let keys := (queryGroupSourceKeysWithWork M N F Q exponent eM eF hMdef hFdef a value q).1 + ∀ eb ∈ List.range (max 1 N.bits.length), + (refinementScaleGuardWithWork F (2 ^ eb) a value).1 = true → + ∀ cell ∈ (targetCellsWithWork + (canonicalMulWithWork (inversePowerTwo exponent) (nat (2 ^ eb))).1 + (bitWordValue (naturalCeilingWithWork value).1) q).1, + ∀ scale sample, (queryGroupDrawReadWithWork keys words (2 ^ eb) cell scale sample).2 ≤ + queryBufferedGroupReadBudget M F exponent eM eF B V := by + dsimp only + intro eb heb hg cell hc scale sample + have hk := (queryGroupSourceKeysWithWork_bounds M N F Q exponent eM eF B hMdef hFdef a value q + hB hN hF hM hQ hes he hn ha hv hw).1 + have hr := queryGroupDrawReadWithWork_scoped_cost exponent eM eF B V hMdef hFdef a value q words + hB hN hF (by omega) (by omega) he hn ha hv hw hV hwords eb heb hg cell hc scale sample + apply hr.trans + unfold queryBufferedGroupReadBudget queryGroupBufferReadBudget + gcongr + +theorem queryBufferedOnlineReadCost {n : ℕ} (N P F B V : ℕ) (hP : 0 < P) + (a value : BinaryFraction) (q : TargetInterval n) (words : List BinaryFraction) + (hB : 7 ≤ B) (hN : Nat.size N ≤ B) (hF : Nat.size F + 2 ≤ B) (hFpos : 1 ≤ F) + (hPb : Nat.size P ≤ B) (hn : Nat.size n ≤ B) (ha : a.width ≤ B) (hv : value.width ≤ B) + (hV : 2 ≤ V) (hwords : ∀ v ∈ words, v.width ≤ V) : + let keys := (queryOnlineKeysWithWork N P F hP a value q).1 + ∀ e ∈ (queryExponentsWithWork N F a value).1, + (queryOnlineIntegerReadWithWork keys words (2 ^ e) + (roundStateWithWork (bitWordValue (seedGridSpacingWithWork (2 ^ e) P).1) + (seedGridSpacingWithWork_pos (2 ^ e) P hP) q).1).2 ≤ + queryOnlineBufferReadBudget (B + 1) B V := by + dsimp only + intro e he + have hk := (queryOnlineKeysWithWork_bounds N P F B hP a value q hB hN hF hFpos hPb hn ha hv).1 + have hr := queryOnlineIntegerReadWithWork_scoped_cost N P F B V hP a value q words + hN hFpos hn hV hwords e he + apply hr.trans + unfold queryOnlineBufferReadBudget + gcongr + +theorem queryOnlineIntegerReadWithWork_size {n : ℕ} + (keys : List (ℕ × TargetInterval n)) (words : List BinaryFraction) (b : ℕ) (q : TargetInterval n) + (V : ℕ) (hV : 2 ≤ V) (hwords : ∀ v ∈ words, v.width ≤ V) : + Nat.size (queryOnlineIntegerReadWithWork keys words b q).1 ≤ V := by + let word := gatheredWordLookupWithWork queryOnlineKeyEqualWithWork keys words (b, q) + have hw : word.1.width ≤ V := gatheredWordLookupWithWork_width _ keys words _ V hV hwords + have hf := (naturalFloorWithWork_bounds word.1).1 + change Nat.size (bitWordValue (naturalFloorWithWork word.1).1) ≤ V + exact (Nat.size_le.mpr (bitWordValue_lt_pow_length _)).trans (hf.trans hw) + +end EditApproximation.BinaryFraction + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryCallbackPolynomial.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryCallbackPolynomial.lean new file mode 100644 index 0000000000000000000000000000000000000000..fa34cfd4fd8ddbf7e1ef7438e277ad55d54f2b47 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryCallbackPolynomial.lean @@ -0,0 +1,79 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryFamilyRefinementCost +import OAI.Combinatorics.EditApproximation.Binary.BinaryPowerStorage +import OAI.Combinatorics.EditApproximation.Probability.FiniteBitPolynomial + +namespace OAI + +namespace EditApproximation + +private abbrev GP := FiniteBitPolynomial (Fin 6) + +private def gp_storedSumWordBudget (n B : GP) : GP := + (B + 1) + FiniteBitPolynomial.bitLength n + 2 * (B + 2) + 2 * (1 + n * ((B + 1) + (B + 1))) + 1 + +private def gp_storedSumBitBudget (n B : GP) : GP := + 1 + n * (100000 * (gp_storedSumWordBudget n B + 1) ^ 2) + +private def gp_bandMassTotalStorageBudget (M B : GP) : GP := + FiniteBitPolynomial.bitLength M + B + 2 * (1 + M * (B + 1)) + 2 + +private def gp_warmupAverageBitBudget (n B : GP) : GP := + gp_storedSumBitBudget n B + 6 * n + + 2100 * (gp_bandMassTotalStorageBudget n B + FiniteBitPolynomial.bitLength n + 4) ^ 2 + FiniteBitPolynomial.bitLength n + 2 + +private def gp_queryPhysicalDataBudget (T J B V C W : GP) : GP := + W + (T + 1 + T * (7 * J + 30 + (C + 1) + 3) + gp_warmupAverageBitBudget T V) + + (8 * B + 7 * J + 32 + (C + 1)) + 1 + +private def gp_queryFamilySourceReadBudget (J B W : GP) : GP := + 200 * (1000 * (B + 1) + 1000 + 2) ^ 2 + 120 * (B + 1) ^ 2 + 10 * J + 100 + W + +private def gp_bitPowerBitBudget (n B : GP) : GP := + 1 + n * (200 * ((n + 1) * (B + 1) + 1) ^ 2) + +private def gp_powerDenominatorBitBudget (n A B : GP) : GP := + gp_bitPowerBitBudget n B + 5000 * (A + (n * B + 1) + 2) ^ 2 + 1 + +private def callbackPolynomial : GP := + gp_queryPhysicalDataBudget (.input 0) (.input 1) (.input 2) (.input 3) (.input 4) + (gp_queryFamilySourceReadBudget (.input 1) (.input 2) (.input 5)) + +def queryCallbackShellDegree : ℕ := callbackPolynomial.degree + +theorem queryCallbackShell_fixedPower (T J B V C W X : ℕ) (hX : 2 ≤ X) + (hT : T ≤ X) (hJ : J ≤ X) (hB : B ≤ X) (hV : V ≤ X) (hC : C ≤ X) (hW : W ≤ X) : + BinaryFraction.queryPhysicalDataBudget T J B V C (BinaryFraction.queryFamilySourceReadBudget J B W) ≤ + X ^ queryCallbackShellDegree := by + have h := callbackPolynomial.eval_le_pow ![T, J, B, V, C, W] X hX (by + intro i + fin_cases i + · exact hT + · exact hJ + · exact hB + · exact hV + · exact hC + · exact hW) + exact h + +private def normalizationPolynomial : GP := + gp_powerDenominatorBitBudget (.input 0) (.input 1) (.input 2) + +def queryNormalizationBitDegree : ℕ := normalizationPolynomial.degree + +theorem queryNormalization_fixedPower (n A B X : ℕ) (hX : 2 ≤ X) + (hn : n ≤ X) (hA : A ≤ X) (hB : B ≤ X) : + BinaryFraction.powerDenominatorBitBudget n A B ≤ X ^ queryNormalizationBitDegree := by + have h := normalizationPolynomial.eval_le_pow ![n, A, B, 0, 0, 0] X hX (by + intro i + fin_cases i + · exact hn + · exact hA + · exact hB + · exact Nat.zero_le _ + · exact Nat.zero_le _ + · exact Nat.zero_le _) + exact h + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryCellCost.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryCellCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..aec9c29c9da26a2096adedcdfaa42b27493874c8 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryCellCost.lean @@ -0,0 +1,93 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryRawCenterCost +import OAI.Combinatorics.EditApproximation.Binary.BinaryCellCentersWork + +namespace OAI + +/-! Uniform bounds for the actual cell scan at an accepted query scale. +The scale-window test controls its count; the binary arithmetic controls +its coordinate widths independently of the numeric target length. -/ + +namespace EditApproximation.BinaryFraction + +theorem queryCellCoordinates_count (F b exponent p : ℕ) (w : ℚ) + (hF : 1 ≤ F) (hb : 1 ≤ b) (hw : 0 ≤ w) (hwindow : w / (16 * F) ≤ b) : + (localCellCoordinates ((2 : ℚ) ^ (-(exponent : ℤ)) * b) p ⌈w⌉₊).length ≤ + (32 * F + 2) * 2 ^ exponent + 2 := by + have hbR : (1 : ℚ) ≤ b := by exact_mod_cast hb + have hs : 0 < (2 : ℚ) ^ (-(exponent : ℤ)) * b := by + have hbp : (0 : ℚ) < b := by exact_mod_cast (show 0 < b by omega) + positivity + apply localCellCoordinates_length_le _ hs _ _ ((32 * F + 2) * 2 ^ exponent) + apply (div_le_iff₀ hs).2 + have hw' : w ≤ 16 * (F : ℚ) * b := by + have hf : (0 : ℚ) < F := by exact_mod_cast (show 0 < F by omega) + nlinarith only [(div_le_iff₀ (by positivity : (0 : ℚ) < 16 * F)).mp hwindow] + have hc : (⌈w⌉₊ : ℚ) < w + 1 := Nat.ceil_lt_add_one hw + have heq : (((32 * F + 2) * 2 ^ exponent : ℕ) : ℚ) * + ((2 : ℚ) ^ (-(exponent : ℤ)) * b) = (32 * (F : ℚ) + 2) * b := by + push_cast + rw [zpow_neg, zpow_natCast] + field_simp + rw [heq] + nlinarith only [hc, hw', hbR] + +theorem queryScalesWithWork_window (N F : ℕ) (a value : BinaryFraction) (b : ℕ) + (hb : b ∈ (queryScalesWithWork N F a value).1) : + (∃ e : ℕ, b = 2 ^ e) ∧ value.value / (16 * F) ≤ b := by + rw [queryScalesWithWork_value] at hb + obtain ⟨hd, hg⟩ := List.mem_filter.mp hb + refine ⟨?_, (of_decide_eq_true hg).1⟩ + obtain ⟨e, _, rfl⟩ := List.mem_map.mp hd + exact ⟨e, rfl⟩ + +def queryCellScanBitBudget (F exponent B : ℕ) : ℕ := + let K := (32 * F + 2) * 2 ^ exponent + 2 + 2000 * (B + 4) ^ 2 + targetCellsBitBudget K K (4 * B + 40) + +theorem queryCellScan_bounds {n : ℕ} (F b exponent B : ℕ) + (value : BinaryFraction) (q : TargetInterval n) + (hF : 1 ≤ F) (hb : 1 ≤ b) (hbs : Nat.size b ≤ B + 1) + (he : exponent + 1 ≤ B) (hn : Nat.size n ≤ B) (hv : value.width ≤ B) + (hw : 0 ≤ value.value) (hwindow : value.value / (16 * F) ≤ b) : + let side := canonicalMulWithWork (inversePowerTwo exponent) (nat b) + let radius := naturalCeilingWithWork value + let cells := targetCellsWithWork side.1 (bitWordValue radius.1) q + cells.1.length ≤ ((32 * F + 2) * 2 ^ exponent + 2) ^ 2 ∧ + side.2 + cells.2 ≤ queryCellScanBitBudget F exponent B ∧ + ∀ cell ∈ cells.1, Nat.size cell.1 ≤ 16 * B + 183 ∧ Nat.size cell.2 ≤ 16 * B + 183 := by + let side := canonicalMulWithWork (inversePowerTwo exponent) (nat b) + let radius := naturalCeilingWithWork value + let cells := targetCellsWithWork side.1 (bitWordValue radius.1) q + let K := (32 * F + 2) * 2 ^ exponent + 2 + have htheta : (inversePowerTwo exponent).width ≤ B := by rw [inversePowerTwo_width]; exact he + have hbn : (nat b).width ≤ B + 3 := (nat_width_le b).trans (by omega) + have hsw := canonicalMulWithWork_width (inversePowerTwo exponent) (nat b) (B + 3) (by omega) hbn + have hsc := canonicalMulWithWork_cost (inversePowerTwo exponent) (nat b) (B + 3) (by omega) hbn + have hrw : Nat.size (bitWordValue radius.1) ≤ B + 2 := + (Nat.size_le.mpr (bitWordValue_lt_pow_length radius.1)).trans + ((naturalCeilingWithWork_length value).trans (by omega)) + have hcoords (p : ℕ) : (localCellCoordinates side.1.value p (bitWordValue radius.1)).length ≤ K := by + simp only [side, canonicalMulWithWork_value, inversePowerTwo_value, nat_value, + radius, naturalCeilingWithWork_value] + exact queryCellCoordinates_count F b exponent p value.value hF hb hw hwindow + have hcc := targetCellsWithWork_cost side.1 (bitWordValue radius.1) (4 * B + 40) + q (by change side.1.width ≤ _ at hsw; omega) (by omega) (by omega) + have hcells : cells.2 ≤ targetCellsBitBudget K K (4 * B + 40) := hcc.trans (by + unfold targetCellsBitBudget + gcongr <;> apply hcoords) + refine ⟨?_, ?_, ?_⟩ + · rw [targetCellsWithWork_value] + simp only [canonicalMulWithWork_value, inversePowerTwo_value, nat_value, + naturalCeilingWithWork_value] + exact localTargetCells_query_length F b exponent q value.value hF hb hw hwindow + · change side.2 + cells.2 ≤ _ + change side.2 ≤ _ at hsc + exact Nat.add_le_add hsc hcells + · intro cell hc + have hk := targetCellsWithWork_keys side.1 (bitWordValue radius.1) (4 * B + 40) q + (by change side.1.width ≤ _ at hsw; omega) (by omega) (by omega) cell hc + constructor <;> omega + +end EditApproximation.BinaryFraction + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryCellStateCost.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryCellStateCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..5c22852267889b90525f0e6ba406c42064bac6e2 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryCellStateCost.lean @@ -0,0 +1,67 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryGroupKeyCost + +namespace OAI + +namespace EditApproximation.BinaryFraction + +def queryCellStatesWithWork (n P b exponent : ℕ) (cell : ℕ × ℕ) : + List (TargetInterval n) × ℕ := + let spacing := seedGridSpacingWithWork b P + let side := canonicalMulWithWork (inversePowerTwo exponent) (nat b) + let states := cellStatesWithWork n (bitWordValue spacing.1) side.1 cell + (states.1, spacing.2 + side.2 + states.2 + exponent + 3) + +def queryCellStatesBitBudget (P exponent B : ℕ) : ℕ := + 100 * (B + 5) ^ 2 + 2000 * (B + 4) ^ 2 + + cellStatesBitBudget P P (16 * B + 200) + exponent + 3 + +theorem queryCellStatesWithWork_bounds (n P b exponent B : ℕ) (cell : ℕ × ℕ) + (hP : 0 < P) (hPb : Nat.size P ≤ B) (hb : Nat.size b ≤ B + 1) + (he : exponent + 1 ≤ B) (hn : Nat.size n ≤ B) + (hc : Nat.size cell.1 ≤ 16 * B + 183 ∧ Nat.size cell.2 ≤ 16 * B + 183) + (hbd : ∃ e : ℕ, b = 2 ^ e) (hPd : ∃ e : ℕ, P = 2 ^ e) : + (queryCellStatesWithWork n P b exponent cell).1.length ≤ P ^ 2 ∧ + (queryCellStatesWithWork n P b exponent cell).2 ≤ queryCellStatesBitBudget P exponent B := by + let spacing := seedGridSpacingWithWork b P + let theta := inversePowerTwo exponent + let side := canonicalMulWithWork theta (nat b) + let states := cellStatesWithWork n (bitWordValue spacing.1) side.1 cell + let C := 16 * B + 200 + have hsp := seedGridSpacingWithWork_bounds b P (B + 3) (by omega) (by omega) + have hgs : Nat.size (bitWordValue spacing.1) ≤ B + 4 := + (Nat.size_le.mpr (bitWordValue_lt_pow_length _)).trans hsp.1 + have ht : theta.width ≤ B + 3 := by dsimp only [theta]; rw [inversePowerTwo_width]; omega + have hsw := canonicalMulWithWork_width theta (nat b) (B + 3) ht ((nat_width_le b).trans (by omega)) + have hsc := canonicalMulWithWork_cost theta (nat b) (B + 3) ht ((nat_width_le b).trans (by omega)) + have htheta : 0 ≤ theta.value ∧ theta.value ≤ 1 := by + rw [inversePowerTwo_value] + exact ⟨by positivity, zpow_le_one_of_nonpos₀ (by norm_num) (by omega)⟩ + have hv : side.1.value = theta.value * b := by rw [canonicalMulWithWork_value, nat_value] + have hg : (0 : ℚ) < seedGridSpacing b P := by + exact_mod_cast (show 0 < seedGridSpacing b P by unfold seedGridSpacing; omega) + have hcover : (b : ℚ) ≤ P * (seedGridSpacing b P : ℚ) := by + exact_mod_cast seedGridSpacing_covers_dyadic hbd hPd + have hratio : theta.value * b / seedGridSpacing b P ≤ (P : ℚ) := by + apply (div_le_iff₀ hg).2 + exact (mul_le_mul_of_nonneg_right htheta.2 (Nat.cast_nonneg b)).trans (by simpa only [one_mul] using hcover) + have hlen (j : ℕ) : (cellGridPoints side.1.value (bitWordValue spacing.1) j).length ≤ P := by + rw [hv, seedGridSpacingWithWork_value b P hP] + exact cellGridPoints_length_le (mul_nonneg htheta.1 (Nat.cast_nonneg _)) hratio + have hstate := cellStatesWithWork_cost n (bitWordValue spacing.1) C side.1 cell + (by dsimp only [C]; omega) (by dsimp only [C]; omega) + (by dsimp only [C]; change side.1.width ≤ _ at hsw; omega) + (by dsimp only [C]; omega) (by dsimp only [C]; omega) + have hstate' : states.2 ≤ cellStatesBitBudget P P C := hstate.trans (by + unfold cellStatesBitBudget cellGridPointsBitBudget + gcongr <;> apply hlen) + constructor + · have hlength := (cellStatesWithWork_length n (bitWordValue spacing.1) side.1 cell).trans + (Nat.mul_le_mul (hlen cell.1) (hlen cell.2)) + simpa only [queryCellStatesWithWork, spacing, theta, side, states, pow_two] using hlength + · change spacing.2 + side.2 + states.2 + exponent + 3 ≤ _ + exact Nat.add_le_add_right (Nat.add_le_add_right + (Nat.add_le_add (Nat.add_le_add hsp.2 hsc) hstate') exponent) 3 + +end EditApproximation.BinaryFraction + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryChargedFamily.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryChargedFamily.lean new file mode 100644 index 0000000000000000000000000000000000000000..89956e95c34a41dc992c1dcef7d2a5b4b08aa8be --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryChargedFamily.lean @@ -0,0 +1,140 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryFamilyActive +import OAI.Combinatorics.EditApproximation.Queries.QueryChargedWarmup +import OAI.Combinatorics.EditApproximation.Geometry.ChargedRandomGlobalQuery +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! All physical table branches run Boolean arithmetic and issue +address-charged adaptive requests. Coarse entries are supplied by the +separately executed coarse initializer. -/ + +namespace EditApproximation + +section Family +variable {M J R passes copies T S : ℕ} [NeZero M] [NeZero R] + (source target : List ℕ) (N P F exponent H Q eM eF : ℕ) + (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) + (A a : ℕ → BinaryFraction) (tau eta kappa delta : BinaryFraction) (multiplier : ℕ → ℕ) + (occurrence : BinaryMemo PositionCounts) (symbolBits positionBits : ℕ) + + + +def queryChargedFamilyTable + (parent : {r : PhysicalTableRequest M J target.length // r.Bounded (passes + 1) copies T S}) : + BitQuery (ChargedFamilyQueryKey (R := R) target N P F exponent H Q (.inr parent)) BinaryFraction := + let index := wordLEWithWork parent.val.index.bits T.bits + .charge (index.2 + 1) + (if hi : index.1 = true then + BitQuery.mapKeysWithWork (fun key => (Sum.inr key, 1)) + (queryChargedWarmup source target N P F (A parent.val.pass) (a parent.val.pass) multiplier + parent occurrence symbolBits positionBits) + else let depth := binaryNaturalCompareWithWork parent.val.node.1.val J + .charge (depth.2 + 1) + (if hb : depth.1 = .lt then + let interval := physicalSourceInterval source.length parent.val.node + let length := saturatingSubtractWithWork interval.hi interval.lo + let short := wordLEWithWork length.1 [true] + .charge (length.2 + short.2 + 1) + (if short.1 then + BitQuery.mapKeysWithWork (fun key => (Sum.inr key, 1)) + (queryPhysicalInitial source target N P F (A parent.val.pass) (a parent.val.pass) + multiplier parent occurrence symbolBits positionBits parent.val.state) + else BitQuery.mapKeysWithWork + (fun key => (Sum.map id (fun child => + ⟨Sum.inr child.val, ChargedPhysicalRequest.table_rank_lt parent child.val child.property⟩) + key, 1)) + (queryFamilyBoundedActive (R := R) source target N P F exponent H Q eM eF hP hM hF + tau (a parent.val.pass) eta kappa delta T S passes copies parent + (Nat.lt_of_not_ge (fun h => hi ((queryNaturalLEWithWork_value parent.val.index T).mpr h))) + ((binaryNaturalCompareWithWork_lt _ _).mp hb))) + else BitQuery.mapKeysWithWork (fun key => (Sum.inr key, 1)) + (queryPhysicalInitial source target N P F (A parent.val.pass) (a parent.val.pass) + multiplier parent occurrence symbolBits positionBits parent.val.state))) + +theorem queryChargedFamilyTable_refines + (ha : ∀ pass, pass ≤ passes → (a pass).value = refinementFactor (A pass).value F) + (hs : ∀ z ∈ source, z < 2 ^ symbolBits) (ht : ∀ z ∈ target, z < 2 ^ symbolBits) + (hp : target.length ≤ 2 ^ positionBits) + (htable : occurrence = occurrenceBuild symbolBits positionBits target.zipIdx) + (initial : PhysicalEntry M J target.length → ℕ) + (parent : {r : PhysicalTableRequest M J target.length // r.Bounded (passes + 1) copies T S}) : + BitQuery.Refines (fun word value => word.value = value) + (queryChargedFamilyTable (R := R) source target N P F exponent H Q eM eF hP hM hF + A a tau eta kappa delta multiplier occurrence symbolBits positionBits parent) + (chargedRandomGlobalQuery (R := R) source target N P F exponent H Q T S (passes + 1) copies + (fun pass => (A pass).value) multiplier tau.value eta.value kappa.value delta.value + (physicalFamilyGroupRead target N P F exponent H Q passes copies) + (physicalFamilyOnlineRead target N P F exponent H Q passes copies) initial (.inr parent)) := by + have hinit := queryPhysicalInitial_refines source target N P F (A parent.val.pass) + (a parent.val.pass) multiplier parent occurrence symbolBits positionBits parent.val.state hP + (ha parent.val.pass (by have := parent.property.1; omega)) hs ht hp htable + unfold queryChargedFamilyTable chargedRandomGlobalQuery + dsimp only + apply BitQuery.Refines.charge + by_cases hi : parent.val.index ≤ T + · rw [ite_eq_left hi, dite_eq_left ((queryNaturalLEWithWork_value parent.val.index T).mpr hi)] + apply BitQuery.Refines.mapKeysWithWork _ _ (fun _ => rfl) + exact queryChargedWarmup_refines source target N P F (A parent.val.pass) (a parent.val.pass) + multiplier parent occurrence symbolBits positionBits (fun pass => (A pass).value) rfl hP + (ha parent.val.pass (by have := parent.property.1; omega)) hs ht hp htable + · rw [ite_eq_right hi, dite_eq_right (fun h => hi ((queryNaturalLEWithWork_value parent.val.index T).mp h))] + apply BitQuery.Refines.charge + by_cases hb : parent.val.node.1.val < J + · rw [ite_eq_left hb, dite_eq_left ((binaryNaturalCompareWithWork_lt _ _).mpr hb)] + apply BitQuery.Refines.charge + have hshort : (wordLEWithWork + (saturatingSubtractWithWork (physicalSourceInterval source.length parent.val.node).hi + (physicalSourceInterval source.length parent.val.node).lo).1 [true]).1 = true ↔ + (physicalSourceInterval source.length parent.val.node).hi - + (physicalSourceInterval source.length parent.val.node).lo ≤ 1 := by + rw [wordLEWithWork_value, saturatingSubtractWithWork_value] + rfl + by_cases hw : (physicalSourceInterval source.length parent.val.node).hi - + (physicalSourceInterval source.length parent.val.node).lo ≤ 1 + · rw [ite_eq_left hw, ite_eq_left (hshort.mpr hw)] + exact hinit.mapKeysWithWork _ _ (fun _ => rfl) + · rw [ite_eq_right hw, ite_eq_right (fun h => hw (hshort.mp h))] + apply BitQuery.Refines.mapKeysWithWork _ _ (fun _ => rfl) + exact queryFamilyBoundedActive_refines (R := R) source target N P F exponent H Q eM eF + hP hM hF tau (a parent.val.pass) eta kappa delta T S passes copies parent + (Nat.lt_of_not_ge hi) hb (fun pass => (A pass).value) multiplier initial (ha parent.val.pass (by have := parent.property.1; omega)) hw + · rw [ite_eq_right hb, dite_eq_right (fun h => hb ((binaryNaturalCompareWithWork_lt _ _).mp h))] + exact hinit.mapKeysWithWork _ _ (fun _ => rfl) + +def queryChargedFamilyGlobal + (coarse : PhysicalEntry M J target.length → BinaryFraction × ℕ) + (request : ChargedPhysicalRequest M J target.length (passes + 1) copies T S) : + BitQuery (ChargedFamilyQueryKey (R := R) target N P F exponent H Q request) BinaryFraction := + match request with + | .inl entry => BitQuery.compute (coarse entry) + | .inr parent => queryChargedFamilyTable (R := R) source target N P F exponent H Q eM eF hP hM hF + A a tau eta kappa delta multiplier occurrence symbolBits positionBits parent + +theorem queryChargedFamilyGlobal_refines + (ha : ∀ pass, pass ≤ passes → (a pass).value = refinementFactor (A pass).value F) + (hs : ∀ z ∈ source, z < 2 ^ symbolBits) (ht : ∀ z ∈ target, z < 2 ^ symbolBits) + (hp : target.length ≤ 2 ^ positionBits) + (htable : occurrence = occurrenceBuild symbolBits positionBits target.zipIdx) + (coarse : PhysicalEntry M J target.length → BinaryFraction × ℕ) + (initial : PhysicalEntry M J target.length → ℕ) + (hc : ∀ entry, (coarse entry).1.value = initial entry) + (request : ChargedPhysicalRequest M J target.length (passes + 1) copies T S) : + BitQuery.Refines (fun word value => word.value = value) + (queryChargedFamilyGlobal (R := R) source target N P F exponent H Q eM eF hP hM hF + A a tau eta kappa delta multiplier occurrence symbolBits positionBits coarse request) + (chargedRandomGlobalQuery (R := R) source target N P F exponent H Q T S (passes + 1) copies + (fun pass => (A pass).value) multiplier tau.value eta.value kappa.value delta.value + (physicalFamilyGroupRead target N P F exponent H Q passes copies) + (physicalFamilyOnlineRead target N P F exponent H Q passes copies) initial request) := by + cases request with + | inl entry => exact .charge _ (.done (hc entry)) + | inr parent => + exact queryChargedFamilyTable_refines (R := R) source target N P F exponent H Q eM eF hP hM hF + A a tau eta kappa delta multiplier occurrence symbolBits positionBits ha hs ht hp htable initial parent + +end Family +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryChargedFamilySpace.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryChargedFamilySpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..008aec97045942ae525ec31650b00b6d98280bfb --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryChargedFamilySpace.lean @@ -0,0 +1,62 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryFamilySpace +import OAI.Combinatorics.EditApproximation.Queries.QueryChargedWarmupSpace +import OAI.Combinatorics.EditApproximation.Queries.QueryChargedFamily + +namespace OAI + +namespace EditApproximation +open BitQuery + +section Family +variable {M J R passes copies T S : ℕ} [NeZero M] [NeZero R] + (source target : List ℕ) (N P F exponent H Q eM eF : ℕ) + (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) + (A a : ℕ → BinaryFraction) (tau eta kappa delta : BinaryFraction) (multiplier : ℕ → ℕ) + (occurrence : BinaryMemo PositionCounts) (symbolBits positionBits : ℕ) + +def queryChargedFamilyTableHeap + (parent : {r : PhysicalTableRequest M J target.length // r.Bounded (passes + 1) copies T S}) : + Heap (queryChargedFamilyTable (R := R) source target N P F exponent H Q eM eF hP hM hF + A a tau eta kappa delta multiplier occurrence symbolBits positionBits parent) := by + have hinit := queryPhysicalInitialHeap source target N P F (A parent.val.pass) (a parent.val.pass) + multiplier parent occurrence symbolBits positionBits parent.val.state + unfold queryChargedFamilyTable + refine Heap.chargeOf (naturalWordLEAllocation parent.val.index.bits T.bits) + ((naturalWordLEAllocation_le_work _ _).trans (Nat.le_succ _)) ?_ + split + · exact (queryChargedWarmupHeap source target N P F (A parent.val.pass) (a parent.val.pass) + multiplier parent occurrence symbolBits positionBits).mapKeysWithWork _ (fun _ => 1) (fun _ => le_rfl) + · refine Heap.chargeOf (parent.val.node.1.val.bits.length + J.bits.length) + ((bitCompareWithWork_input_cells _ _).trans (Nat.le_succ _)) ?_ + split + · let interval := physicalSourceInterval source.length parent.val.node + have hl := saturatingSubtractAllocation_le_work interval.hi interval.lo + have ht := naturalWordLEAllocation_le_work (saturatingSubtractWithWork interval.hi interval.lo).1 [true] + refine Heap.chargeOf (saturatingSubtractAllocation interval.hi interval.lo + + naturalWordLEAllocation (saturatingSubtractWithWork interval.hi interval.lo).1 [true]) (by + dsimp only [interval] at hl ht ⊢ + omega) ?_ + split + · exact hinit.mapKeysWithWork _ (fun _ => 1) (fun _ => le_rfl) + · exact (queryFamilyBoundedActiveHeap (R := R) source target N P F exponent H Q eM eF hP hM hF + tau (a parent.val.pass) eta kappa delta T S passes copies parent _ _).mapKeysWithWork _ + (fun _ => 1) (fun _ => le_rfl) + · exact hinit.mapKeysWithWork _ (fun _ => 1) (fun _ => le_rfl) + +def queryChargedFamilyGlobalHeap + (coarse : PhysicalEntry M J target.length → BinaryFraction × ℕ) + (allocation : PhysicalEntry M J target.length → ℕ) + (hc : ∀ entry, allocation entry ≤ 3 * (coarse entry).2) + (request : ChargedPhysicalRequest M J target.length (passes + 1) copies T S) : + Heap (queryChargedFamilyGlobal (R := R) source target N P F exponent H Q eM eF hP hM hF + A a tau eta kappa delta multiplier occurrence symbolBits positionBits coarse request) := by + cases request with + | inl entry => exact Heap.compute (coarse entry) (allocation entry) (hc entry) + | inr parent => + exact queryChargedFamilyTableHeap (R := R) source target N P F exponent H Q eM eF hP hM hF + A a tau eta kappa delta multiplier occurrence symbolBits positionBits parent + +end Family +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryChargedSeed.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryChargedSeed.lean new file mode 100644 index 0000000000000000000000000000000000000000..daddda1157c093e3d1268047e237043a97a929e3 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryChargedSeed.lean @@ -0,0 +1,69 @@ +import OAI.Combinatorics.EditApproximation.Binary.BitQuery +import OAI.Combinatorics.EditApproximation.Geometry.ChargedSeedQuery +import OAI.Combinatorics.EditApproximation.Binary.BinaryInitialKernel +import OAI.Combinatorics.EditApproximation.Binary.BinarySeedMedianWork +import OAI.Combinatorics.EditApproximation.Geometry.MemoCodeWork +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Seed values are computed by actual coarse-cache or previous-pass +requests. The copy median and the pass-zero test have explicit work. -/ + +namespace EditApproximation +namespace BinaryFraction + + + +@[simp] theorem querySeedMedianWithWork_value (N multiplier : ℕ) (words : List BinaryFraction) : + (querySeedMedianWithWork N multiplier words).1.value = + (min N (upperMedian (words.map fun word => ⌈(multiplier : ℚ) * word.value⌉₊)) : ℕ) := by + simp only [querySeedMedianWithWork, ofNaturalWord_value, seedMedianWithWork_value] + +end BinaryFraction + +section Seed +variable {M J n passes copies T S : ℕ} + (parent : {r : PhysicalTableRequest M J n // r.Bounded passes copies T S}) + + + +theorem queryChargedRead_refines + (key : {child : ChargedPhysicalRequest M J n passes copies T S // + child.rank < ChargedPhysicalRequest.rank (.inr parent)}) : + BitQuery.Refines (fun word value => word.value = value) (queryChargedRead parent key) (.read key .done) := + .charge _ (.read key _ _ (fun _ => .done rfl)) + + + +theorem queryChargedPreviousRead_refines (hp : 0 < parent.val.pass) (q : TargetInterval n) + (copy : Fin copies) : + BitQuery.Refines (fun word value => word.value = value) + (queryChargedPreviousRead parent hp q copy) (chargedPreviousRead parent hp q copy) := + queryChargedRead_refines parent _ + + + +theorem queryChargedSeedAt_refines (N : ℕ) (multiplier : ℕ → ℕ) (q : TargetInterval n) : + BitQuery.Refines (fun word value => word.value = value) + (queryChargedSeedAt parent N multiplier q) + (chargedSeedQuery N multiplier parent (parent.val.node, q)) := by + unfold queryChargedSeedAt chargedSeedQuery + rw [dite_eq_left rfl] + apply BitQuery.Refines.charge + by_cases hp : parent.val.pass = 0 + · rw [dite_eq_left hp, dite_eq_left ((naturalEqualWithWork_value _ _).mpr hp)] + exact queryChargedRead_refines parent _ + · rw [dite_eq_right hp, dite_eq_right (fun h => hp ((naturalEqualWithWork_value _ _).mp h))] + apply BitQuery.Refines.charge + apply BitQuery.Refines.collect _ _ (fun copy => queryChargedPreviousRead_refines parent _ q copy) + intro words + apply BitQuery.Refines.charge + apply BitQuery.Refines.done + simp only [BinaryFraction.querySeedMedianWithWork_value, List.map_map, Function.comp_def] + +end Seed +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryChargedSeedCost.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryChargedSeedCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..1901478a7fa8b72f89c4a10bcad50e9a8c11cea0 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryChargedSeedCost.lean @@ -0,0 +1,84 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryChargedSeed + +namespace OAI + +namespace EditApproximation + +section Seed +variable {M J n passes copies T S : ℕ} + (parent : {r : PhysicalTableRequest M J n // r.Bounded passes copies T S}) + (oracle : {child : ChargedPhysicalRequest M J n passes copies T S // + child.rank < ChargedPhysicalRequest.rank (.inr parent)} → BinaryFraction) + (readWork : {child : ChargedPhysicalRequest M J n passes copies T S // + child.rank < ChargedPhysicalRequest.rank (.inr parent)} → ℕ) + +theorem queryChargedRead_work_bound (C : ℕ) (hc : ∀ key, readWork key ≤ C) (key) : + (queryChargedRead parent key).work oracle readWork ≤ 7 * J + 33 + C := by + have h := chargedPhysicalCodeWithWork_cost key.val + have hr := hc key + simp only [queryChargedRead, BitQuery.work] + omega + +private theorem seed_sum_bound {κ : Type*} (keys : List κ) (cost : κ → ℕ) (C : ℕ) + (hc : ∀ key, cost key ≤ C) : (keys.map cost).sum ≤ keys.length * C := by + induction keys with + | nil => simp + | cons key keys ih => + have h := hc key + simp only [List.map_cons, List.sum_cons, List.length_cons, Nat.add_mul, Nat.one_mul] + omega + +def queryChargedSeedBitBudget (copies J B C : ℕ) : ℕ := + 8 * B + 3 + (7 * J + 33 + C) + copies + 1 + + copies * (7 * J + 33 + C + 3) + BinaryFraction.seedMedianBitBudget copies B + B + 1 + +theorem queryChargedSeedAt_bounds (N B C : ℕ) (multiplier : ℕ → ℕ) (q : TargetInterval n) + (hB : 1 ≤ B) (hN : Nat.size N ≤ B) (hp : Nat.size parent.val.pass ≤ B) + (hm : Nat.size (multiplier (parent.val.pass - 1)) + 2 ≤ B) + (hv : ∀ key, (oracle key).width ≤ B) (hc : ∀ key, readWork key ≤ C) : + ((queryChargedSeedAt parent N multiplier q).value oracle).width ≤ B ∧ + (queryChargedSeedAt parent N multiplier q).work oracle readWork ≤ + queryChargedSeedBitBudget copies J B C := by + have heq := naturalEqualWithWork_cost parent.val.pass 0 B hp (by simp) + have hr (key) := queryChargedRead_work_bound parent oracle readWork C hc key + unfold queryChargedSeedAt + split + · constructor + · exact hv _ + · simp only [BitQuery.work] + have := hr ⟨.inl (parent.val.node, q), ChargedPhysicalRequest.coarse_rank_lt _ parent rfl⟩ + change (naturalEqualWithWork parent.val.pass 0).2 + 1 + + (queryChargedRead parent _).work oracle readWork ≤ _ + unfold queryChargedSeedBitBudget + omega + · rename_i hpass + let hpos := Nat.pos_of_ne_zero (fun h => hpass ((naturalEqualWithWork_value _ _).mpr h)) + let reader := queryChargedPreviousRead parent hpos q + let words := (List.finRange copies).map fun copy => (reader copy).value oracle + have hlen : words.length = copies := by simp only [words, List.length_map, List.length_finRange] + have hwords : ∀ word ∈ words, word.width ≤ B := by + intro word hw + obtain ⟨copy, _, rfl⟩ := List.mem_map.mp hw + exact hv _ + have hmedian := BinaryFraction.seedMedianWithWork_cost N (multiplier (parent.val.pass - 1)) words B hN hm hwords + have hlength := BinaryFraction.seedMedianWithWork_length N (multiplier (parent.val.pass - 1)) words + have hsum := seed_sum_bound (List.finRange copies) (fun copy => (reader copy).work oracle readWork + 3) + (7 * J + 33 + C + 3) (fun copy => Nat.add_le_add_right (hr _) 3) + simp only [List.length_finRange] at hsum + rw [hlen] at hmedian + constructor + · simp only [BitQuery.value, BitQuery.value_collect, BitQuery.compute, + BinaryFraction.querySeedMedianWithWork, BinaryFraction.ofNaturalWord_width] + exact max_le (hlength.trans hN) hB + · simp only [BitQuery.work, BitQuery.work_collect, BitQuery.compute, Nat.add_zero] + change (naturalEqualWithWork parent.val.pass 0).2 + 1 + + (copies + 1 + (((List.finRange copies).map fun copy => (reader copy).work oracle readWork + 3).sum + + (BinaryFraction.querySeedMedianWithWork N (multiplier (parent.val.pass - 1)) words).2)) ≤ _ + unfold BinaryFraction.querySeedMedianWithWork queryChargedSeedBitBudget + dsimp only + omega + +end Seed +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryChargedSeedSpace.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryChargedSeedSpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..107ffb75947b051c84c97adf6f7473c224aacbc6 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryChargedSeedSpace.lean @@ -0,0 +1,60 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryPhysicalReaderSpace +import OAI.Combinatorics.EditApproximation.Queries.QueryChargedSeed +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation + +/-- Scalar cells of the actual coarse/table address construction. -/ + + +theorem chargedPhysicalCodeAllocation_le_work {M J n passes copies T S : ℕ} + (request : ChargedPhysicalRequest M J n passes copies T S) : + chargedPhysicalCodeAllocation request ≤ (chargedPhysicalCodeWithWork request).2 := by + have entryBound (d J : ℕ) : + 2 * d + J + 12 ≤ 3 * d + 1 + (2 * J + 1) + 3 + 8 + 2 := by + omega + cases request with + | inl entry => + simp only [chargedPhysicalCodeAllocation, chargedPhysicalCodeWithWork, physicalEntryCodeWithWork, + physicalNodeCodeWithWork, treeLayerCodeWithWork_cost, parameterPowerWithWork_spec] + exact entryBound _ _ + | inr request => + have h := physicalTableCodeAllocation_le_work copies T S request.val + change physicalTableCodeAllocation request.val + 2 ≤ (physicalTableCodeWithWork copies T S request.val).2 + 3 + exact Nat.add_le_add h (by decide : 2 ≤ 3) + +open BitQuery + +section Seed +variable {M J n passes copies T S : ℕ} + (parent : {r : PhysicalTableRequest M J n // r.Bounded passes copies T S}) + +def queryChargedReadHeap + (key : {child : ChargedPhysicalRequest M J n passes copies T S // + child.rank < ChargedPhysicalRequest.rank (.inr parent)}) : Heap (queryChargedRead parent key) := + Heap.chargeOf (chargedPhysicalCodeAllocation key.val + 1) + (Nat.add_le_add_right (chargedPhysicalCodeAllocation_le_work key.val) 1) (.read key _ fun word => .done word) + +def queryChargedSeedAtHeap (N : ℕ) (multiplier : ℕ → ℕ) (q : TargetInterval n) : + Heap (queryChargedSeedAt parent N multiplier q) := by + refine Heap.chargeOf (naturalEqualAllocation parent.val.pass 0) + ((naturalEqualAllocation_le_work _ _).trans (Nat.le_succ _)) ?_ + split + · exact queryChargedReadHeap parent _ + · refine Heap.chargeOf copies (Nat.le_succ _) ?_ + refine Heap.collect _ (fun _ => queryChargedReadHeap parent _) _ _ fun words => ?_ + let factor := multiplier (parent.val.pass - 1) + refine Heap.computeOf (BinaryFraction.querySeedMedianWithWork N factor words) + (BinaryFraction.seedMedianAllocation N factor words + (BinaryFraction.seedMedianWithWork N factor words).1.length + 1) ?_ + have hm := BinaryFraction.seedMedianAllocation_le_work N factor words + unfold BinaryFraction.querySeedMedianWithWork + dsimp only + omega + +end Seed +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryChargedTableCost.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryChargedTableCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..9153027e6eba6b95329d26809206f6b75f18e1f5 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryChargedTableCost.lean @@ -0,0 +1,91 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryChargedFamily +import OAI.Combinatorics.EditApproximation.Queries.QueryChargedWarmupCost + +namespace OAI + +namespace EditApproximation +open BinaryFraction + +def queryChargedTableBitBudget (M P F Amax copies J symbolBits positionBits B C active : ℕ) : ℕ := + 80 * (B + 1) + queryChargedWarmupBitBudget M P F Amax copies J symbolBits positionBits B (C + 1) + active + +section Table +variable {M J R passes copies T S : ℕ} [NeZero M] [NeZero R] + (source target : List ℕ) (N P F exponent H Q eM eF Amax B C active : ℕ) + (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) + (A a : ℕ → BinaryFraction) (tau eta kappa delta : BinaryFraction) (multiplier : ℕ → ℕ) + (occurrence : BinaryMemo PositionCounts) (symbolBits positionBits : ℕ) + (parent : {r : PhysicalTableRequest M J target.length // r.Bounded (passes + 1) copies T S}) + (oracle : ChargedFamilyQueryKey (R := R) target N P F exponent H Q (.inr parent) → BinaryFraction) + (readWork : ChargedFamilyQueryKey (R := R) target N P F exponent H Q (.inr parent) → ℕ) + +local notation "tableOracle" => (fun key => oracle (Sum.inr key)) +local notation "tableWork" => (fun key => 1 + readWork (Sum.inr key)) + +theorem queryChargedFamilyTable_work_bound + (hB : 10 ≤ B) (hN : Nat.size N ≤ B) (hPb : Nat.size P ≤ B) + (hFb : Nat.size F + 2 ≤ B) (hFpos : 1 ≤ F) + (hs : Nat.size source.length + 2 ≤ B) (ht : Nat.size target.length + 2 ≤ B) + (ht' : Nat.size (target.length + 1) + 2 ≤ B) + (hinit : Nat.size ((32 * F + 1) * N) + 3 ≤ B) + (hMb : Nat.size M ≤ B) (hJ : Nat.size J ≤ B) (hi : Nat.size parent.val.index ≤ B) + (hT : Nat.size T ≤ B) + (hA : (A parent.val.pass).width ≤ B) (ha : (a parent.val.pass).width ≤ B) + (hAone : 1 ≤ (A parent.val.pass).value) (hAmax : (A parent.val.pass).value ≤ Amax) + (hp : Nat.size parent.val.pass ≤ B) (hm : Nat.size (multiplier (parent.val.pass - 1)) + 2 ≤ B) + (hv : ∀ key, (oracle (Sum.inr key)).width ≤ B) (hc : ∀ key, readWork key ≤ C) + (hactive : ∀ (hindex : T < parent.val.index) (hbelow : parent.val.node.1.val < J), + (queryFamilyBoundedActive (R := R) source target N P F exponent H Q eM eF hP hM hF + tau (a parent.val.pass) eta kappa delta T S passes copies parent hindex hbelow).work + (fun key => oracle (Sum.map id (fun child => + ⟨Sum.inr child.val, ChargedPhysicalRequest.table_rank_lt parent child.val child.property⟩) key)) + (fun key => 1 + readWork (Sum.map id (fun child => + ⟨Sum.inr child.val, ChargedPhysicalRequest.table_rank_lt parent child.val child.property⟩) key)) ≤ active) : + (queryChargedFamilyTable (R := R) source target N P F exponent H Q eM eF hP hM hF A a tau eta kappa + delta multiplier occurrence symbolBits positionBits parent).work oracle readWork ≤ + queryChargedTableBitBudget M P F Amax copies J symbolBits positionBits B C active := by + have hw := queryChargedWarmup_work_bound source target N P F Amax B (C + 1) + (A parent.val.pass) (a parent.val.pass) multiplier parent occurrence symbolBits positionBits + tableOracle tableWork hB hP hN hPb hFb hFpos hs ht ht' hinit hMb hJ hi hA ha hAone hAmax hp hm hv + (fun key => by have := hc (Sum.inr key); omega) + have hinitial := queryPhysicalInitial_work_bound source target N P F Amax B (C + 1) + (A parent.val.pass) (a parent.val.pass) multiplier parent occurrence symbolBits positionBits + tableOracle tableWork parent.val.state (by omega) hP hN hPb (by omega) (by omega) (by omega) + hA ha hAone hAmax hp hm hv (fun key => by have := hc (Sum.inr key); omega) + have hiw : (queryPhysicalInitial source target N P F (A parent.val.pass) (a parent.val.pass) + multiplier parent occurrence symbolBits positionBits parent.val.state).work tableOracle tableWork ≤ + queryChargedWarmupBitBudget M P F Amax copies J symbolBits positionBits B (C + 1) := by + apply hinitial.trans + unfold queryChargedWarmupBitBudget + dsimp only + omega + have hindexcost := wordLEWithWork_cost parent.val.index.bits T.bits + rw [Nat.size_eq_bits_len, Nat.size_eq_bits_len] at hindexcost + have hdepth := binaryNaturalCompareWithWork_cost parent.val.node.1.val J + have hn := (Nat.size_le_size (Nat.le_of_lt_succ parent.val.node.1.isLt)).trans hJ + have htest := querySliceTest_cost source (physicalSourceInterval source.length parent.val.node) B (by omega) + unfold queryChargedFamilyTable + simp only [BitQuery.work] + split + · simp only [BitQuery.mapKeysWithWork_work] + unfold queryChargedTableBitBudget + omega + · split + · split + · simp only [BitQuery.work, BitQuery.mapKeysWithWork_work] + unfold queryChargedTableBitBudget + omega + · rename_i hindex hbelow hlong + simp only [BitQuery.work, BitQuery.mapKeysWithWork_work] + have h := hactive (Nat.lt_of_not_ge (fun h => hindex ((queryNaturalLEWithWork_value _ _).mpr h))) + ((binaryNaturalCompareWithWork_lt _ _).mp hbelow) + unfold queryChargedTableBitBudget + omega + · simp only [BitQuery.work, BitQuery.mapKeysWithWork_work] + unfold queryChargedTableBitBudget + omega + +end Table +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryChargedTableWidth.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryChargedTableWidth.lean new file mode 100644 index 0000000000000000000000000000000000000000..c25bddc210117164a62316a8a6f2907221b89a83 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryChargedTableWidth.lean @@ -0,0 +1,64 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryChargedFamily +import OAI.Combinatorics.EditApproximation.Queries.QueryWarmupWidth +import OAI.Combinatorics.EditApproximation.Queries.QueryBoundedActiveCost + +namespace OAI + +namespace EditApproximation +open BinaryFraction + +section Table +variable {M J R passes copies T S : ℕ} [NeZero M] [NeZero R] + (source target : List ℕ) (N P F exponent H Q eM eF B : ℕ) + (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) + (A a : ℕ → BinaryFraction) (tau eta kappa delta : BinaryFraction) (multiplier : ℕ → ℕ) + (occurrence : BinaryMemo PositionCounts) (symbolBits positionBits : ℕ) + (parent : {r : PhysicalTableRequest M J target.length // r.Bounded (passes + 1) copies T S}) + (oracle : ChargedFamilyQueryKey (R := R) target N P F exponent H Q (.inr parent) → BinaryFraction) + +theorem queryChargedFamilyTable_width + (hB : 10 ≤ B) (hN : Nat.size N ≤ B) (hPb : Nat.size P ≤ B) + (hFb : Nat.size F + 2 ≤ B) (hFpos : 1 ≤ F) + (hs : Nat.size source.length + 2 ≤ B) (ht : Nat.size target.length + 2 ≤ B) + (ht' : Nat.size (target.length + 1) + 2 ≤ B) + (hinit : Nat.size ((32 * F + 1) * N) + 3 ≤ B) + (hMb : Nat.size M ≤ B) (ha : (a parent.val.pass).width ≤ B) + (hv : ∀ key, (oracle (Sum.inr key)).width ≤ B) + (hactive : ∀ (hindex : T < parent.val.index) (hbelow : parent.val.node.1.val < J), + ((queryFamilyBoundedActive (R := R) source target N P F exponent H Q eM eF hP hM hF + tau (a parent.val.pass) eta kappa delta T S passes copies parent hindex hbelow).value + (fun key => oracle (Sum.map id (fun child => + ⟨Sum.inr child.val, ChargedPhysicalRequest.table_rank_lt parent child.val child.property⟩) key))).width ≤ + preparedKernelWordBudget M B) : + ((queryChargedFamilyTable (R := R) source target N P F exponent H Q eM eF hP hM hF A a tau eta kappa + delta multiplier occurrence symbolBits positionBits parent).value oracle).width ≤ + localWarmupWordBudget M B + preparedKernelWordBudget M B := by + let tableOracle := fun key => oracle (Sum.inr key) + have hw := queryChargedWarmup_width source target N P F B (A parent.val.pass) (a parent.val.pass) + multiplier parent occurrence symbolBits positionBits tableOracle hB hP hN hPb hFb hFpos hs ht ht' + hinit hMb ha hv + have hi := queryPhysicalInitial_width source target N P F B (A parent.val.pass) (a parent.val.pass) + multiplier parent occurrence symbolBits positionBits tableOracle parent.val.state hP ht' hinit + have hsmall : B ≤ localWarmupWordBudget M B := by + unfold localWarmupWordBudget physicalContinuationInputBudget + dsimp only + omega + unfold queryChargedFamilyTable + simp only [BitQuery.value] + split + · simp only [BitQuery.mapKeysWithWork_value] + exact hw.trans (Nat.le_add_right _ _) + · split + · split + · simp only [BitQuery.value, BitQuery.mapKeysWithWork_value] + exact hi.trans (hsmall.trans (Nat.le_add_right _ _)) + · rename_i hindex hbelow hlong + simp only [BitQuery.value, BitQuery.mapKeysWithWork_value] + exact (hactive _ _).trans (Nat.le_add_left _ _) + · simp only [BitQuery.value, BitQuery.mapKeysWithWork_value] + exact hi.trans (hsmall.trans (Nat.le_add_right _ _)) + +end Table +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryChargedWarmup.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryChargedWarmup.lean new file mode 100644 index 0000000000000000000000000000000000000000..96a03e6401fe91ced444903021c5fd10f2f13f41 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryChargedWarmup.lean @@ -0,0 +1,82 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryPhysicalInitial +import OAI.Combinatorics.EditApproximation.Queries.QueryWarmupProgram +import OAI.Combinatorics.EditApproximation.Geometry.ChargedGlobalQuery +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Executed warmup dispatch and ranked child reads. Both the terminal +and positive-depth branches use the same adaptive initial-cone program. -/ + +namespace EditApproximation + +section Child +variable {M J ny passes copies T S : ℕ} + (parent : {r : PhysicalTableRequest M J ny // r.Bounded passes copies T S}) + (hbelow : parent.val.node.1.val < J) (hindex : 0 < parent.val.index) + (input : Fin M × TargetInterval ny) + + + +theorem queryChargedWarmupChild_refines : + BitQuery.Refines (fun word value => word.value = value) + (queryChargedWarmupChild parent hbelow hindex input) + (chargedWarmupChild parent hbelow hindex input) := + queryChargedRead_refines parent _ + +end Child + +section Warmup +variable (source target : List ℕ) {M J passes copies T S : ℕ} + (N P F : ℕ) (A a : BinaryFraction) (multiplier : ℕ → ℕ) + (parent : {r : PhysicalTableRequest M J target.length // r.Bounded passes copies T S}) + (occurrence : BinaryMemo PositionCounts) (symbolBits positionBits : ℕ) + + + +theorem queryChargedWarmup_refines (factor : ℕ → ℚ) (hA : A.value = factor parent.val.pass) (hP : 0 < P) + (ha : a.value = refinementFactor A.value F) + (hs : ∀ z ∈ source, z < 2 ^ symbolBits) (ht : ∀ z ∈ target, z < 2 ^ symbolBits) + (hp : target.length ≤ 2 ^ positionBits) + (htable : occurrence = occurrenceBuild symbolBits positionBits target.zipIdx) : + BitQuery.Refines (fun word value => word.value = value) + (queryChargedWarmup source target N P F A a multiplier parent occurrence symbolBits positionBits) + (chargedWarmupQuery source target N P F factor multiplier parent) := by + have hi (q : TargetInterval target.length) := queryPhysicalInitial_refines source target N P F A a + multiplier parent occurrence symbolBits positionBits q hP ha hs ht hp htable + unfold queryChargedWarmup chargedWarmupQuery + rw [← hA] + apply BitQuery.Refines.charge + by_cases hz : parent.val.index = 0 + · rw [dite_eq_left hz, dite_eq_left ((naturalEqualWithWork_value _ _).mpr hz)] + exact hi _ + · rw [dite_eq_right hz, dite_eq_right (fun h => hz ((naturalEqualWithWork_value _ _).mp h))] + apply BitQuery.Refines.charge + by_cases hb : parent.val.node.1.val < J + · rw [dite_eq_left hb, dite_eq_left ((binaryNaturalCompareWithWork_lt _ _).mpr hb)] + dsimp only + apply BitQuery.Refines.charge + have htest : (wordLEWithWork + (saturatingSubtractWithWork (physicalSourceInterval source.length parent.val.node).hi + (physicalSourceInterval source.length parent.val.node).lo).1 [true]).1 = true ↔ + (physicalSourceInterval source.length parent.val.node).hi - + (physicalSourceInterval source.length parent.val.node).lo ≤ 1 := by + rw [wordLEWithWork_value, saturatingSubtractWithWork_value] + rfl + by_cases hshort : (physicalSourceInterval source.length parent.val.node).hi - + (physicalSourceInterval source.length parent.val.node).lo ≤ 1 + · rw [ite_eq_left hshort, ite_eq_left (htest.mpr hshort)] + exact hi _ + · rw [ite_eq_right hshort, ite_eq_right (fun h => hshort (htest.mp h))] + unfold physicalWarmupStepQuery + rw [← ha] + exact queryWarmupProgram_refines _ N P F hP a _ _ _ _ _ hi + (fun input => queryChargedWarmupChild_refines parent hb _ input) + · rw [dite_eq_right hb, dite_eq_right (fun h => hb ((binaryNaturalCompareWithWork_lt _ _).mp h))] + exact hi _ + +end Warmup +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryChargedWarmupCost.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryChargedWarmupCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..fcc17cc1aa5a84b1f86abbba6f8316839ee7de64 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryChargedWarmupCost.lean @@ -0,0 +1,101 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryPhysicalInitialCost +import OAI.Combinatorics.EditApproximation.Queries.QueryChargedWarmup +import OAI.Combinatorics.EditApproximation.Queries.QueryWarmupProgramCost + +namespace OAI + +namespace EditApproximation + +def queryChargedWarmupBitBudget (M P F Amax copies J symbolBits positionBits B C : ℕ) : ℕ := + let I := queryPhysicalInitialBitBudget P F Amax copies J symbolBits positionBits B C + 80 * (B + 1) + I + + BinaryFraction.queryWarmupProgramBitBudget M P F B (I + 7 * J + 33 + C) + +section Warmup +variable (source target : List ℕ) {M J passes copies T S : ℕ} + (N P F Amax B C : ℕ) (A a : BinaryFraction) (multiplier : ℕ → ℕ) + (parent : {r : PhysicalTableRequest M J target.length // r.Bounded passes copies T S}) + (occurrence : BinaryMemo PositionCounts) (symbolBits positionBits : ℕ) + (oracle : {child : ChargedPhysicalRequest M J target.length passes copies T S // + child.rank < ChargedPhysicalRequest.rank (.inr parent)} → BinaryFraction) + (readWork : {child : ChargedPhysicalRequest M J target.length passes copies T S // + child.rank < ChargedPhysicalRequest.rank (.inr parent)} → ℕ) + +theorem queryChargedWarmup_work_bound + (hB : 10 ≤ B) (hP : 0 < P) (hN : Nat.size N ≤ B) (hPb : Nat.size P ≤ B) + (hF : Nat.size F + 2 ≤ B) (hFpos : 1 ≤ F) + (hs : Nat.size source.length + 2 ≤ B) (ht : Nat.size target.length + 2 ≤ B) + (ht' : Nat.size (target.length + 1) + 2 ≤ B) + (hinit : Nat.size ((32 * F + 1) * N) + 3 ≤ B) + (hM : Nat.size M ≤ B) (hJ : Nat.size J ≤ B) (hi : Nat.size parent.val.index ≤ B) + (hA : A.width ≤ B) (ha : a.width ≤ B) (hAone : 1 ≤ A.value) (hAmax : A.value ≤ Amax) + (hp : Nat.size parent.val.pass ≤ B) (hm : Nat.size (multiplier (parent.val.pass - 1)) + 2 ≤ B) + (hv : ∀ key, (oracle key).width ≤ B) (hc : ∀ key, readWork key ≤ C) : + (queryChargedWarmup source target N P F A a multiplier parent occurrence symbolBits positionBits).work + oracle readWork ≤ queryChargedWarmupBitBudget M P F Amax copies J symbolBits positionBits B C := by + let I := queryPhysicalInitialBitBudget P F Amax copies J symbolBits positionBits B C + let reader := queryPhysicalInitial source target N P F A a multiplier parent occurrence symbolBits positionBits + have hiR (q : TargetInterval target.length) : (reader q).work oracle readWork ≤ I := + queryPhysicalInitial_work_bound source target N P F Amax B C A a multiplier parent occurrence + symbolBits positionBits oracle readWork q (by omega) hP hN hPb (by omega) (by omega) (by omega) + hA ha hAone hAmax hp hm hv hc + have hiW (q : TargetInterval target.length) : ((reader q).value oracle).width ≤ B := + queryPhysicalInitial_width source target N P F B A a multiplier parent occurrence symbolBits positionBits + oracle q hP ht' hinit + have hzero := naturalEqualWithWork_cost parent.val.index 0 B hi (by simp) + have hn := (Nat.size_le_size (Nat.le_of_lt_succ parent.val.node.1.isLt)).trans hJ + have hdepth := binaryNaturalCompareWithWork_cost parent.val.node.1.val J + have hdepth' : (binaryNaturalCompareWithWork parent.val.node.1.val J).2 ≤ 8 * B + 10 := by omega + have htest := querySliceTest_cost source (physicalSourceInterval source.length parent.val.node) B (by omega) + unfold queryChargedWarmup + simp only [BitQuery.work] + split + · change (naturalEqualWithWork parent.val.index 0).2 + 1 + (reader parent.val.state).work oracle readWork ≤ _ + have h := hiR parent.val.state + unfold queryChargedWarmupBitBudget + dsimp only + dsimp only [I] at h + omega + · rename_i hnonzero + have hindex : 0 < parent.val.index := + Nat.pos_of_ne_zero (fun h => hnonzero ((naturalEqualWithWork_value _ _).mpr h)) + split + · split + · have h := hiR parent.val.state + change (naturalEqualWithWork parent.val.index 0).2 + 1 + + ((binaryNaturalCompareWithWork parent.val.node.1.val J).2 + 1 + + (_ + (reader parent.val.state).work oracle readWork)) ≤ _ + unfold queryChargedWarmupBitBudget + dsimp only + dsimp only [I] at h + omega + · rename_i hbelow hlong + have hcR (input : Fin M × TargetInterval target.length) : + (queryChargedWarmupChild parent ((binaryNaturalCompareWithWork_lt _ _).mp hbelow) hindex input).work + oracle readWork ≤ I + 7 * J + 33 + C := by + exact (queryChargedRead_work_bound parent oracle readWork C hc _).trans (by omega) + have hw := queryWarmupProgram_work_bound (physicalSourceInterval source.length parent.val.node) + N P F B (I + 7 * J + 33 + C) hP a reader + (queryChargedWarmupChild parent ((binaryNaturalCompareWithWork_lt _ _).mp hbelow) hindex) parent.val.state + oracle readWork hB hN hF hFpos hPb hs ht hM ha hiW (fun input => hv _) + (fun r => (hiR r).trans (by omega)) hcR + change (naturalEqualWithWork parent.val.index 0).2 + 1 + + ((binaryNaturalCompareWithWork parent.val.node.1.val J).2 + 1 + + (_ + (queryWarmupProgram _ N P F a reader _ parent.val.state).work oracle readWork)) ≤ _ + unfold queryChargedWarmupBitBudget + dsimp only + dsimp only [I] at hw + omega + · have h := hiR parent.val.state + change (naturalEqualWithWork parent.val.index 0).2 + 1 + + ((binaryNaturalCompareWithWork parent.val.node.1.val J).2 + 1 + + (reader parent.val.state).work oracle readWork) ≤ _ + unfold queryChargedWarmupBitBudget + dsimp only + dsimp only [I] at h + omega + +end Warmup +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryChargedWarmupSpace.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryChargedWarmupSpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..33628174341ca9a199b6dd6366ecf915ac9b148e --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryChargedWarmupSpace.lean @@ -0,0 +1,62 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryInitialConeSpace +import OAI.Combinatorics.EditApproximation.Queries.QueryIndexedSpace +import OAI.Combinatorics.EditApproximation.Queries.QueryChargedSeedSpace +import OAI.Combinatorics.EditApproximation.Queries.QueryWarmupSpace +import OAI.Combinatorics.EditApproximation.Queries.QueryChargedWarmup + +namespace OAI + +namespace EditApproximation +open BitQuery + +section Initial +variable (source target : List ℕ) {M J passes copies T S : ℕ} + (N P F : ℕ) (A a : BinaryFraction) (multiplier : ℕ → ℕ) + (parent : {r : PhysicalTableRequest M J target.length // r.Bounded passes copies T S}) + (occurrence : BinaryMemo PositionCounts) (symbolBits positionBits : ℕ) + +def queryPhysicalInitialHeap (q : TargetInterval target.length) : + Heap (queryPhysicalInitial source target N P F A a multiplier parent occurrence symbolBits positionBits q) := by + let interval := physicalSourceInterval source.length parent.val.node + have hl := saturatingSubtractAllocation_le_work interval.hi interval.lo + have ht := naturalWordLEAllocation_le_work (saturatingSubtractWithWork interval.hi interval.lo).1 [true] + refine Heap.chargeOf (saturatingSubtractAllocation interval.hi interval.lo + + naturalWordLEAllocation (saturatingSubtractWithWork interval.hi interval.lo).1 [true]) (by + dsimp only [interval] at hl ht ⊢ + omega) ?_ + split + · exact Heap.computeOf _ (queryIndexedSliceAllocation source interval target.length q occurrence symbolBits positionBits) + (queryIndexedSliceAllocation_le_work source interval target.length q occurrence symbolBits positionBits) + · exact queryInitialConeProgramAtHeap _ N P F A a (queryChargedSeedAt parent N multiplier) q + (queryChargedSeedAtHeap parent N multiplier) + +def queryChargedWarmupHeap : + Heap (queryChargedWarmup source target N P F A a multiplier parent occurrence symbolBits positionBits) := by + have hinit := queryPhysicalInitialHeap source target N P F A a multiplier parent occurrence symbolBits positionBits + unfold queryChargedWarmup + refine Heap.chargeOf (naturalEqualAllocation parent.val.index 0) + ((naturalEqualAllocation_le_work _ _).trans (Nat.le_succ _)) ?_ + split + · exact hinit _ + · refine Heap.chargeOf (parent.val.node.1.val.bits.length + J.bits.length) + ((bitCompareWithWork_input_cells _ _).trans (Nat.le_succ _)) ?_ + split + · let interval := physicalSourceInterval source.length parent.val.node + have hl := saturatingSubtractAllocation_le_work interval.hi interval.lo + have ht := naturalWordLEAllocation_le_work (saturatingSubtractWithWork interval.hi interval.lo).1 [true] + refine Heap.chargeOf (saturatingSubtractAllocation interval.hi interval.lo + + naturalWordLEAllocation (saturatingSubtractWithWork interval.hi interval.lo).1 [true]) (by + dsimp only [interval] at hl ht ⊢ + omega) ?_ + split + · exact hinit _ + · apply queryWarmupProgramHeap + · exact hinit + · intro input + exact queryChargedReadHeap parent _ + · exact hinit _ + +end Initial +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryCodeBounds.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryCodeBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..fdd836f3d5e94ce9d115f6e0fd0d6fe4cb282c05 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryCodeBounds.lean @@ -0,0 +1,109 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryOrderBounds + +namespace OAI + +/-! Key encoding uses only a fixed number of natural-word operations. +Its word sizes and Boolean work are polynomial in the coordinate widths. -/ + +namespace EditApproximation + +theorem queryNaturalAdd_size (a b : ℕ) : Nat.size (a + b) ≤ Nat.size a + Nat.size b + 1 := by + have h := bitAddWithWork_length a.bits b.bits false + have hs := Nat.size_le.mpr (bitWordValue_lt_pow_length (binaryNaturalAddWithWork a b).1) + rw [binaryNaturalAddWithWork_value] at hs + simp only [binaryNaturalAddWithWork] at hs + simp only [Nat.size_eq_bits_len] at h + omega + +theorem queryNaturalMul_size (a b : ℕ) : Nat.size (a * b) ≤ 2 * Nat.size a + Nat.size b + 1 := by + have h := bitMulWithWork_length a.bits b.bits + have hs := Nat.size_le.mpr (bitWordValue_lt_pow_length (binaryNaturalMulWithWork a b).1) + rw [binaryNaturalMulWithWork_value] at hs + simp only [binaryNaturalMulWithWork] at hs + simp only [Nat.size_eq_bits_len] at h + omega + +theorem queryNaturalAdd_cost (a b K : ℕ) (ha : Nat.size a ≤ K) (hb : Nat.size b ≤ K) : + (binaryNaturalAddWithWork a b).2 ≤ 18 * K + 1 := by + have h := binaryNaturalAddWithWork_cost a b + omega + +theorem queryNaturalMul_cost (a b K : ℕ) (ha : Nat.size a ≤ K) (hb : Nat.size b ≤ K) : + (binaryNaturalMulWithWork a b).2 ≤ 20 * (K + 1) * (2 * K + 1) := by + apply (binaryNaturalMulWithWork_cost a b).trans + gcongr + omega + +theorem queryChildCodeWithWork_bounds {M n : ℕ} (input : Fin M × TargetInterval n) + (B : ℕ) (hM : Nat.size M ≤ B) (hn : Nat.size n ≤ B) : + Nat.size (queryChildCodeWithWork input).1 ≤ 8 * (B + 1) ∧ + (queryChildCodeWithWork input).2 ≤ 100000 * (B + 1) ^ 2 := by + have hi : Nat.size input.1.val ≤ B := (Nat.size_le_size input.1.isLt.le).trans hM + have hl : Nat.size input.2.lo ≤ B := + (Nat.size_le_size (input.2.ordered.trans input.2.valid)).trans hn + have hh : Nat.size input.2.hi ≤ B := (Nat.size_le_size input.2.valid).trans hn + have hw : Nat.size (n + 1) ≤ B + 2 := by + have h := queryNaturalAdd_size n 1 + norm_num only [Nat.size_one] at h + omega + have hhigh : Nat.size ((n + 1) * input.2.hi) ≤ 3 * B + 5 := by + have h := queryNaturalMul_size (n + 1) input.2.hi + omega + have hcoord : Nat.size (input.2.lo + (n + 1) * input.2.hi) ≤ 4 * B + 6 := by + have h := queryNaturalAdd_size input.2.lo ((n + 1) * input.2.hi) + omega + have hscaled : Nat.size (M * (input.2.lo + (n + 1) * input.2.hi)) ≤ 6 * B + 7 := by + have h := queryNaturalMul_size M (input.2.lo + (n + 1) * input.2.hi) + omega + have hout : Nat.size (input.1.val + M * (input.2.lo + (n + 1) * input.2.hi)) ≤ 7 * B + 8 := by + have h := queryNaturalAdd_size input.1.val (M * (input.2.lo + (n + 1) * input.2.hi)) + omega + constructor + · rw [queryChildCodeWithWork_value] + exact hout.trans (by omega) + · let K := 8 * (B + 1) + have h1 : Nat.size 1 ≤ K := by norm_num only [Nat.size_one]; dsimp [K]; omega + have hN : Nat.size n ≤ K := by dsimp [K]; omega + have hW : Nat.size (n + 1) ≤ K := by dsimp [K]; omega + have hI : Nat.size input.1.val ≤ K := by dsimp [K]; omega + have hL : Nat.size input.2.lo ≤ K := by dsimp [K]; omega + have hH : Nat.size input.2.hi ≤ K := by dsimp [K]; omega + have hM' : Nat.size M ≤ K := by dsimp [K]; omega + have hHigh : Nat.size ((n + 1) * input.2.hi) ≤ K := by dsimp [K]; omega + have hCoord : Nat.size (input.2.lo + (n + 1) * input.2.hi) ≤ K := by dsimp [K]; omega + have hScaled : Nat.size (M * (input.2.lo + (n + 1) * input.2.hi)) ≤ K := by dsimp [K]; omega + have c1 := queryNaturalAdd_cost n 1 K hN h1 + have c2 := queryNaturalMul_cost (n + 1) input.2.hi K hW hH + have c3 := queryNaturalAdd_cost input.2.lo ((n + 1) * input.2.hi) K hL hHigh + have c4 := queryNaturalMul_cost M (input.2.lo + (n + 1) * input.2.hi) K hM' hCoord + have c5 := queryNaturalAdd_cost input.1.val (M * (input.2.lo + (n + 1) * input.2.hi)) K hI hScaled + simp only [queryChildCodeWithWork, binaryNaturalAddWithWork_value, binaryNaturalMulWithWork_value] + dsimp only [K] at c1 c2 c3 c4 c5 + nlinarith only [c1, c2, c3, c4, c5, Nat.zero_le B] + +theorem queryChildOrderWithWork_cost {M n : ℕ} (a b : Fin M × TargetInterval n) + (B : ℕ) (hM : Nat.size M ≤ B) (hn : Nat.size n ≤ B) : + (queryEncodedLEWithWork queryChildCodeWithWork a b).2 ≤ 201000 * (B + 1) ^ 2 := by + have ha := queryChildCodeWithWork_bounds a B hM hn + have hb := queryChildCodeWithWork_bounds b B hM hn + have h := queryEncodedLEWithWork_cost queryChildCodeWithWork a b + (100000 * (B + 1) ^ 2) (8 * (B + 1)) ha.2 hb.2 ha.1 hb.1 + nlinarith only [h, Nat.zero_le B] + +theorem queryOrderedChildInputsWithWork_cost {M n : ℕ} (inputs : List (Fin M × TargetInterval n)) + (B : ℕ) (hM : Nat.size M ≤ B) (hn : Nat.size n ≤ B) : + (queryOrderedChildInputsWithWork inputs).2 ≤ + (inputs.length + 1) ^ 2 * (202000 * (B + 1) ^ 2) := by + have h := queryOrderedInputsWithWork_cost childInputCode coordinateEqualWithWork + (queryEncodedLEWithWork queryChildCodeWithWork) + (fun a b => by simp only [queryEncodedLEWithWork_value, queryChildCodeWithWork_value]) + (24 * B + 8) (201000 * (B + 1) ^ 2) + (fun a b => coordinateEqualWithWork_cost a b B hM hn) + (fun a b => queryChildOrderWithWork_cost a b B hM hn) inputs + apply h.trans + gcongr + nlinarith only [Nat.zero_le B] + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryContinuationSpace.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryContinuationSpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..d44d954b319d9cf4f3cfbde97128f6887876c3ee --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryContinuationSpace.lean @@ -0,0 +1,111 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryLocalRepresentativeSpace +import OAI.Combinatorics.EditApproximation.Binary.BinaryContinuationSpace +import OAI.Combinatorics.EditApproximation.Queries.QueryRefinementFinish +import OAI.Combinatorics.EditApproximation.Binary.BinaryWarmupReads +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation.BinaryFraction + + + +theorem endpointActionAllocation_le_work {ny M : ℕ} (center : TargetInterval ny) + (states : Fin M → TargetInterval ny) : + endpointActionAllocation center states ≤ (endpointActionWithWork center states).2 := by + have h := endpointConnectionAllocation_le_work center states + unfold endpointActionAllocation endpointActionWithWork + dsimp only + omega + + + +theorem wideActionsFromRepresentativesAllocation_le_work {nx ny : ℕ} (M : ℕ) (parent : TargetInterval nx) + (representatives : List (ℕ × TargetInterval ny)) (P : ℕ) : + wideActionsFromRepresentativesAllocation M parent representatives P ≤ + (wideActionsFromRepresentativesWithWork M parent representatives P).2 := by + apply arithmeticFlatMapAllocation_le_work + intro br _ + have hw := wideActionGridAllocation_le_work M parent br.2 br.1 P + have ha := arithmeticMapAllocation_le_work (fun states : Vector (TargetInterval ny) M => endpointActionWithWork br.2 states.get) + (fun states => endpointActionAllocation br.2 states.get) + (wideActionGridWithWork M parent br.2 br.1 P).1 (fun states _ => endpointActionAllocation_le_work br.2 states.get) + dsimp only + omega + + + +theorem physicalContinuationReadAllocation_le_work {nx ny M : ℕ} (parent : TargetInterval nx) + (representatives : List (ℕ × TargetInterval ny)) (P F : ℕ) (delta fallback : BinaryFraction) + (old current : Fin M × TargetInterval ny → BinaryFraction × ℕ) + (oldAllocation currentAllocation : Fin M × TargetInterval ny → ℕ) + (groups online : List (BinaryBellmanAction (TargetInterval ny) (Fin M × TargetInterval ny) M)) + (query : TargetInterval ny) + (ho : ∀ input, oldAllocation input ≤ (old input).2) + (hc : ∀ input, currentAllocation input ≤ (current input).2) : + physicalContinuationReadAllocation parent representatives P F delta fallback old current oldAllocation currentAllocation groups online query ≤ + (physicalContinuationReadWithWork parent representatives P F delta fallback old current groups online query).2 := by + have hw := wideActionsFromRepresentativesAllocation_le_work M parent representatives P + have hl := canonicalMulAllocation_le_work (nat 128) (nat F) + have hf := localContinuationReadAllocation_le_work endpointDistanceWithWork endpointDistanceAllocation + (canonicalMulWithWork (nat 128) (nat F)).1 delta fallback old current oldAllocation currentAllocation query + (wideActionsFromRepresentativesWithWork M parent representatives P).1 groups online + (endpointDistanceAllocation_le_work query) ho hc + unfold physicalContinuationReadAllocation physicalContinuationReadWithWork + dsimp only + omega + + + +theorem queryRefinementFinishAllocation_le_work {nx ny M : ℕ} (parent : TargetInterval nx) (N P F : ℕ) + (a delta : BinaryFraction) (initial : TargetInterval ny → BinaryFraction × ℕ) + (initialAllocation : TargetInterval ny → ℕ) (t : ℕ) + (earlierKeys : List (Fin M × ℕ × TargetInterval ny)) (earlierWords : List BinaryFraction) + (groups online : List (BinaryBellmanAction (TargetInterval ny) (Fin M × TargetInterval ny) M)) + (currentKeys : List (Fin M × TargetInterval ny)) (currentWords : List BinaryFraction) + (query : TargetInterval ny) (hi : ∀ r, initialAllocation r ≤ (initial r).2) : + queryRefinementFinishAllocation parent N P F a delta initial initialAllocation t earlierKeys earlierWords + groups online currentKeys currentWords query ≤ + (queryRefinementFinishWithWork parent N P F a delta initial t earlierKeys earlierWords groups online currentKeys currentWords query).2 := by + have hq := hi query + have hr := localRepresentativeReadAllocation_le_work N P F a initial initialAllocation query hi + have hf := physicalContinuationReadAllocation_le_work parent (localRepresentativeReadWithWork N P F a initial query).1 + P F delta (initial query).1 + (queryHistoryReadWithWork earlierKeys earlierWords (t - 1)) + (fun input => queryChildReadWithWork currentKeys currentWords input.1 input.2) + (queryHistoryReadAllocation earlierKeys earlierWords (t - 1)) + (fun input => queryChildReadAllocation currentKeys currentWords input.1 input.2) groups online query + (queryHistoryReadAllocation_le_work earlierKeys earlierWords (t - 1)) + (fun input => queryChildReadAllocation_le_work currentKeys currentWords input.1 input.2) + unfold queryRefinementFinishAllocation queryRefinementFinishWithWork + dsimp only + omega + + + +theorem localWarmupReadAllocation_le_work {nx ny M : ℕ} (parent : TargetInterval nx) + (N P F : ℕ) (a : BinaryFraction) (initial : TargetInterval ny → BinaryFraction × ℕ) + (initialAllocation : TargetInterval ny → ℕ) (child : Fin M × TargetInterval ny → BinaryFraction × ℕ) + (childAllocation : Fin M × TargetInterval ny → ℕ) (query : TargetInterval ny) + (hi : ∀ r, initialAllocation r ≤ (initial r).2) + (hc : ∀ input, childAllocation input ≤ (child input).2) : + localWarmupReadAllocation parent N P F a initial initialAllocation child childAllocation query ≤ + (localWarmupReadKernelWithWork parent N P F a initial child query).2 := by + have hq := hi query + have hr := localRepresentativeReadAllocation_le_work N P F a initial initialAllocation query hi + have hw := wideActionsFromRepresentativesAllocation_le_work M parent + (localRepresentativeReadWithWork N P F a initial query).1 P + have hl := canonicalMulAllocation_le_work (nat 128) (nat F) + have hb := bellmanReadAllocation_le_work endpointDistanceWithWork endpointDistanceAllocation + (canonicalMulWithWork (nat 128) (nat F)).1 (initial query).1 child childAllocation query + (wideActionsFromRepresentativesWithWork M parent (localRepresentativeReadWithWork N P F a initial query).1 P).1 + (fun action _ => endpointDistanceAllocation_le_work query action.center) + (fun action _ i => hc (action.childState i)) + unfold localWarmupReadAllocation localWarmupReadKernelWithWork + dsimp only + omega + +end EditApproximation.BinaryFraction + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryCoordinateSpace.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryCoordinateSpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..53461f5abbe06579178a075975a4c6cb89837274 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryCoordinateSpace.lean @@ -0,0 +1,79 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryBufferSpace +import OAI.Combinatorics.EditApproximation.Binary.BinaryCoordinateAction +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation + +/-- The spare loop charge also covers the input index-list spine. -/ +theorem arithmeticMapAllocation_with_spine {α β : Type*} (f : α → β × ℕ) + (allocation : α → ℕ) (values : List α) (h : ∀ a ∈ values, allocation a ≤ (f a).2) : + arithmeticMapAllocation allocation values + values.length ≤ (arithmeticMapWithWork f values).2 := by + induction values with + | nil => exact Nat.zero_le _ + | cons a rest ih => + have ha := h a List.mem_cons_self + have ht := ih (fun b hb => h b (List.mem_cons_of_mem _ hb)) + simp only [arithmeticMapAllocation, arithmeticMapWithWork, List.length_cons] + omega + + + +theorem memberByAllocation_le_work {α : Type*} (equal : α → α → Bool × ℕ) + (allocation : α → α → ℕ) (a : α) (values : List α) + (h : ∀ b ∈ values, allocation a b ≤ (equal a b).2) : + memberByAllocation allocation a values ≤ (memberByWithWork equal a values).2 := by + induction values with + | nil => exact Nat.zero_le _ + | cons b rest ih => + have hb := h b List.mem_cons_self + have ht := ih (fun c hc => h c (List.mem_cons_of_mem _ hc)) + simp only [memberByAllocation, memberByWithWork] + omega + + + +theorem dedupByAllocation_le_work {α : Type*} (equal : α → α → Bool × ℕ) + (allocation : α → α → ℕ) (values : List α) (h : ∀ a b, allocation a b ≤ (equal a b).2) : + dedupByAllocation equal allocation values ≤ (dedupByWithWork equal values).2 := by + induction values with + | nil => exact Nat.zero_le _ + | cons a rest ih => + have hm := memberByAllocation_le_work equal allocation a rest (fun b _ => h a b) + simp only [dedupByAllocation, dedupByWithWork] + split_ifs <;> omega + +namespace BinaryFraction + + + +theorem bandCoordinatesAllocation_le_work {M n : ℕ} (band : List (Fin M → TargetInterval n)) : + bandCoordinatesAllocation band ≤ (bandCoordinatesWithWork band).2 := by + let build := fun action : Fin M → TargetInterval n => + arithmeticMapWithWork (fun i : Fin M => ((i, action i), 1)) (List.finRange M) + have hr := arithmeticFlatMapAllocation_le_work build + (fun _ => arithmeticMapAllocation (fun _ : Fin M => 1) (List.finRange M) + M) band (by + intro action _ + simpa only [List.length_finRange] using arithmeticMapAllocation_with_spine + (fun i : Fin M => ((i, action i), 1)) (fun _ => 1) (List.finRange M) (fun _ _ => le_rfl)) + have hd := dedupByAllocation_le_work coordinateEqualWithWork coordinateEqualAllocation + (arithmeticFlatMapWithWork build band).1 coordinateEqualAllocation_le_work + unfold bandCoordinatesAllocation bandCoordinatesWithWork + dsimp only [build] at hr hd ⊢ + omega + + + +theorem coordinateVectorAllocation_le_work {M n : ℕ} (band : List (Fin M → TargetInterval n)) : + coordinateVectorAllocation band ≤ (coordinateVectorWithWork band).2 := by + have h := bandCoordinatesAllocation_le_work band + unfold coordinateVectorAllocation coordinateVectorWithWork + dsimp only + omega + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryDataBuffers.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryDataBuffers.lean new file mode 100644 index 0000000000000000000000000000000000000000..cd500390c8e50b1390624c7490b223ed15b952ff --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryDataBuffers.lean @@ -0,0 +1,81 @@ +import OAI.Combinatorics.EditApproximation.Queries.QuerySourceBuffers +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Counted local data buffers for the adaptive gathers. Bounds depend on +stored keys and the requested key, not on an unbounded ambient key type. -/ + +namespace EditApproximation +namespace BinaryFraction + +theorem gatheredWordLookupWithWork_cost_on {κ : Type*} + (equal : κ → κ → Bool × ℕ) (C : ℕ) (keys : List κ) + (values : List BinaryFraction) (query : κ) + (hC : ∀ key ∈ keys, (equal query key).2 ≤ C) : + (gatheredWordLookupWithWork equal keys values query).2 ≤ + 1 + keys.length * (C + 1) := by + induction keys generalizing values with + | nil => simp only [gatheredWordLookupWithWork, List.length_nil, Nat.zero_mul, Nat.add_zero, le_rfl] + | cons key keys ih => + have hc := hC key List.mem_cons_self + have ht := ih (values.drop 1) (fun k hk => hC k (List.mem_cons_of_mem _ hk)) + cases values with + | nil => simp only [gatheredWordLookupWithWork]; omega + | cons value values => + simp only [List.drop_succ_cons, List.drop_zero] at ht + simp only [gatheredWordLookupWithWork] + split_ifs <;> simp only [List.length_cons, Nat.add_mul, Nat.one_mul] <;> omega + + + +@[simp] theorem queryChildReadWithWork_value {M n : ℕ} + (keys : List (Fin M × TargetInterval n)) (values : List BinaryFraction) + (i : Fin M) (q : TargetInterval n) : + (queryChildReadWithWork keys values i q).1.value = + finiteAnswerTable keys (values.map value) (i, q) := + gatheredWordLookupWithWork_value _ coordinateEqualWithWork_value keys values (i, q) + +theorem queryChildReadWithWork_cost {M n : ℕ} (keys : List (Fin M × TargetInterval n)) + (values : List BinaryFraction) (i : Fin M) (q : TargetInterval n) + (B : ℕ) (hM : Nat.size M ≤ B) (hn : Nat.size n ≤ B) : + (queryChildReadWithWork keys values i q).2 ≤ 1 + keys.length * (24 * B + 9) := by + exact gatheredWordLookupWithWork_cost coordinateEqualWithWork (24 * B + 8) + (fun a b => coordinateEqualWithWork_cost a b B hM hn) keys values (i, q) + + + +@[simp] theorem queryHistoryReadWithWork_value {M n : ℕ} + (keys : List (Fin M × ℕ × TargetInterval n)) (values : List BinaryFraction) + (s : ℕ) (input : Fin M × TargetInterval n) : + (queryHistoryReadWithWork keys values s input).1.value = + finiteAnswerTable keys (values.map value) (input.1, s, input.2) := + gatheredWordLookupWithWork_value _ queryHistoryEqualWithWork_value keys values (input.1, s, input.2) + +theorem queryHistoryReadWithWork_cost {M n : ℕ} + (keys : List (Fin M × ℕ × TargetInterval n)) (values : List BinaryFraction) + (s : ℕ) (input : Fin M × TargetInterval n) (B : ℕ) + (hM : Nat.size M ≤ B) (hn : Nat.size n ≤ B) (hs : Nat.size s ≤ B) + (ht : ∀ key ∈ keys, Nat.size key.2.1 ≤ B) : + (queryHistoryReadWithWork keys values s input).2 ≤ + 1 + keys.length * (32 * B + 12) := by + apply gatheredWordLookupWithWork_cost_on queryHistoryEqualWithWork (32 * B + 11) + intro key hk + have hc := coordinateEqualWithWork_cost input (key.1, key.2.2) B hM hn + have he := naturalEqualWithWork_cost s key.2.1 B hs (ht key hk) + change (coordinateEqualWithWork input (key.1, key.2.2)).2 + + (naturalEqualWithWork s key.2.1).2 + 1 ≤ _ + omega + +theorem queryHistoryReadWithWork_width {M n : ℕ} + (keys : List (Fin M × ℕ × TargetInterval n)) (values : List BinaryFraction) + (s : ℕ) (input : Fin M × TargetInterval n) (B : ℕ) + (hB : 2 ≤ B) (hv : ∀ v ∈ values, v.width ≤ B) : + (queryHistoryReadWithWork keys values s input).1.width ≤ B := + gatheredWordLookupWithWork_width _ keys values _ B hB hv + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryDependencyCosts.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryDependencyCosts.lean new file mode 100644 index 0000000000000000000000000000000000000000..05290d4b7384d4b2dbd99ab261da140e9af4a68f --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryDependencyCosts.lean @@ -0,0 +1,57 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryDependencyExpansion +import OAI.Combinatorics.EditApproximation.Geometry.RankedMemoSimulation + +namespace OAI + +/-! Weighted read counts are the actual same-index and earlier-index +lengths used by the dependency expansion, after identifying its values +with the local mathematical recurrence. -/ + +namespace EditApproximation + +theorem list_filter_length_eq_sum {κ : Type*} (keys : List κ) (predicate : κ → Bool) : + (keys.filter predicate).length = (keys.map fun key => if predicate key then 1 else 0).sum := by + induction keys with + | nil => rfl + | cons key keys ih => + cases hp : predicate key <;> simp [hp, ih, Nat.add_comm] + + +section Queries + +variable {κ : Type*} (depth index : κ → ℕ) + (program : (key : κ) → FiniteQuery {child : κ // depth child + index child < depth key + index key}) + (expected : κ → ℚ) + (hstep : ∀ key, (program key).value (fun child => expected child.val) = expected key) + +include hstep + +theorem queryRequestList_expected (key : κ) : + queryRequestList depth index program key = + ((program key).keys (fun child => expected child.val)).map Subtype.val := by + unfold queryRequestList + simp only [rankedProgramValue_eq (fun key => depth key + index key) program expected hstep] + +theorem querySameRequests_length_eq_cost (key : κ) : + (querySameRequests depth index program key).length = + (program key).cost (fun child => expected child.val) + (fun child => if ¬ index child.val < index key then 1 else 0) := by + unfold querySameRequests + rw [queryRequestList_expected depth index program expected hstep, + list_filter_length_eq_sum, FiniteQuery.cost_eq_sum, List.map_map] + simp only [Function.comp_def, Bool.not_eq_true', decide_eq_false_iff_not] + +theorem queryEarlierRequests_length_eq_cost (key : κ) : + (queryEarlierRequests depth index program key).length = + (program key).cost (fun child => expected child.val) + (fun child => if index child.val < index key then 1 else 0) := by + unfold queryEarlierRequests + rw [queryRequestList_expected depth index program expected hstep, + list_filter_length_eq_sum, FiniteQuery.cost_eq_sum, List.map_map] + simp only [Function.comp_def, decide_eq_true_eq] + +end Queries + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryDependencyExpansion.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryDependencyExpansion.lean new file mode 100644 index 0000000000000000000000000000000000000000..82a1a6ba1d015ee7a7cd6e6a5f9269bd067d1b56 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryDependencyExpansion.lean @@ -0,0 +1,183 @@ +import OAI.Combinatorics.EditApproximation.Geometry.RankedMemoWork +import OAI.Combinatorics.EditApproximation.Geometry.DependencyExpansion + +namespace OAI + +/-! The dependency tree here is obtained from the requests made by the +finite adaptive program at its actual answers. Local depth/index progress +therefore bounds execution, rather than an independently supplied tree. -/ + +namespace EditApproximation + +open Finset + +section Queries + +variable {κ : Type*} (depth index : κ → ℕ) + (program : (key : κ) → FiniteQuery + {child : κ // depth child + index child < depth key + index key}) + +def queryRequestList (key : κ) : List κ := + ((program key).keys (fun child => + rankedProgramValue (fun x => depth x + index x) program child.val)).map Subtype.val + +def querySameRequests (key : κ) : List κ := + (queryRequestList depth index program key).filter (fun child => !(index child < index key)) + +def queryEarlierRequests (key : κ) : List κ := + (queryRequestList depth index program key).filter (fun child => index child < index key) + +theorem queryRequestList_cost (key : κ) (weight : κ → ℕ) : + (program key).cost + (fun child => rankedProgramValue (fun x => depth x + index x) program child.val) + (fun child => weight child.val) = + ((queryRequestList depth index program key).map weight).sum := by + rw [FiniteQuery.cost_eq_sum] + simp only [queryRequestList, List.map_map, Function.comp_def] + +theorem sum_map_partition (predicate : κ → Bool) (weight : κ → ℕ) (keys : List κ) : + ((keys.filter (fun key => !predicate key)).map weight).sum + + ((keys.filter predicate).map weight).sum = (keys.map weight).sum := by + induction keys with + | nil => rfl + | cons key keys ih => + cases hp : predicate key <;> simp only [List.filter_cons, hp, Bool.not_false, + Bool.not_true, Bool.false_eq_true, reduceIte, List.map_cons, List.sum_cons] + all_goals omega + +variable (progress : ∀ key child, child ∈ queryRequestList depth index program key → + (depth child < depth key ∧ index child ≤ index key) ∨ + (depth child ≤ depth key ∧ index child < index key)) + +include progress + +theorem querySameRequests_progress (key : κ) + (i : Fin (querySameRequests depth index program key).length) : + depth ((querySameRequests depth index program key).get i) < depth key ∧ + index ((querySameRequests depth index program key).get i) ≤ index key := by + have hm := List.mem_filter.mp (List.get_mem (querySameRequests depth index program key) i) + have hnot : ¬ index ((querySameRequests depth index program key).get i) < index key := by + simpa using hm.2 + rcases progress key _ hm.1 with h | h + · exact h + · exact False.elim (hnot h.2) + +theorem queryEarlierRequests_progress (key : κ) + (i : Fin (queryEarlierRequests depth index program key).length) : + depth ((queryEarlierRequests depth index program key).get i) ≤ depth key ∧ + index ((queryEarlierRequests depth index program key).get i) < index key := by + have hm := List.mem_filter.mp (List.get_mem (queryEarlierRequests depth index program key) i) + have hi : index ((queryEarlierRequests depth index program key).get i) < index key := by + simpa only [decide_eq_true_eq] using hm.2 + refine ⟨?_, hi⟩ + rcases progress key _ hm.1 with h | h + · exact h.1.le + · exact h.1 + +def queryDependencyExpansion (root : κ) : DependencyExpansion := + DependencyExpansion.build depth index + (fun key => (querySameRequests depth index program key).length) + (fun key => (queryEarlierRequests depth index program key).length) + (fun key i => (querySameRequests depth index program key).get i) + (fun key i => (queryEarlierRequests depth index program key).get i) + (querySameRequests_progress depth index program progress) + (queryEarlierRequests_progress depth index program progress) root + +theorem queryDependencyExpansion_depth (root : κ) : + (queryDependencyExpansion depth index program progress root).depth = depth root := + DependencyExpansion.build_depth _ _ _ _ _ _ _ _ root + +theorem queryDependencyExpansion_index (root : κ) : + (queryDependencyExpansion depth index program progress root).rank = index root := + DependencyExpansion.build_rank _ _ _ _ _ _ _ _ root + +theorem queryDependencyExpansion_valid (a b : ℕ) + (hsame : ∀ key, (querySameRequests depth index program key).length ≤ a) + (hearlier : ∀ key, (queryEarlierRequests depth index program key).length ≤ b) (root : κ) : + DependencyExpansion.Valid a b (queryDependencyExpansion depth index program progress root) := + DependencyExpansion.build_valid _ _ _ _ _ _ _ _ a b hsame hearlier root + +theorem queryDependencyExpansion_nodes (root : κ) : + (queryDependencyExpansion depth index program progress root).nodeCount = + rankedUncachedCalls (fun key => depth key + index key) program root := by + have hall : ∀ level root, depth root + index root = level → + (queryDependencyExpansion depth index program progress root).nodeCount = + rankedUncachedCalls (fun key => depth key + index key) program root := by + intro level + induction level using Nat.strong_induction_on with + | h level ih => + intro root hroot + conv_lhs => unfold queryDependencyExpansion + rw [DependencyExpansion.build] + change 1 + (∑ i : Fin (querySameRequests depth index program root).length, + (queryDependencyExpansion depth index program progress + ((querySameRequests depth index program root).get i)).nodeCount) + + (∑ i : Fin (queryEarlierRequests depth index program root).length, + (queryDependencyExpansion depth index program progress + ((queryEarlierRequests depth index program root).get i)).nodeCount) = _ + have hs (i : Fin (querySameRequests depth index program root).length) := + querySameRequests_progress depth index program progress root i + have he (i : Fin (queryEarlierRequests depth index program root).length) := + queryEarlierRequests_progress depth index program progress root i + have hsame : (∑ i : Fin (querySameRequests depth index program root).length, + (queryDependencyExpansion depth index program progress + ((querySameRequests depth index program root).get i)).nodeCount) = + (((querySameRequests depth index program root).map + (rankedUncachedCalls (fun key => depth key + index key) program)).sum) := by + calc + _ = ∑ i : Fin (querySameRequests depth index program root).length, + rankedUncachedCalls (fun key => depth key + index key) program + ((querySameRequests depth index program root).get i) := by + apply sum_congr rfl + intro i hi + apply ih _ _ _ rfl + rw [← hroot] + exact Nat.add_lt_add_of_lt_of_le (hs i).1 (hs i).2 + _ = _ := Fin.sum_univ_fun_getElem _ _ + have hearlier : (∑ i : Fin (queryEarlierRequests depth index program root).length, + (queryDependencyExpansion depth index program progress + ((queryEarlierRequests depth index program root).get i)).nodeCount) = + (((queryEarlierRequests depth index program root).map + (rankedUncachedCalls (fun key => depth key + index key) program)).sum) := by + calc + _ = ∑ i : Fin (queryEarlierRequests depth index program root).length, + rankedUncachedCalls (fun key => depth key + index key) program + ((queryEarlierRequests depth index program root).get i) := by + apply sum_congr rfl + intro i hi + apply ih _ _ _ rfl + rw [← hroot] + exact Nat.add_lt_add_of_le_of_lt (he i).1 (he i).2 + _ = _ := Fin.sum_univ_fun_getElem _ _ + rw [hsame, hearlier, rankedUncachedCalls, queryRequestList_cost] + have hp := sum_map_partition (fun child => decide (index child < index root)) + (rankedUncachedCalls (fun key => depth key + index key) program) + (queryRequestList depth index program root) + change 1 + _ + _ = _ + 1 + change _ + _ = _ at hp + dsimp only [querySameRequests, queryEarlierRequests] + omega + exact hall (depth root + index root) root rfl + +theorem rankedMemoEvaluate_dependency_bound (a b bits : ℕ) (encode : κ → ℕ) + (hinjective : Function.Injective encode) (hbounded : ∀ key, encode key < 2 ^ bits) + (hsame : ∀ key, (querySameRequests depth index program key).length ≤ a) + (hearlier : ∀ key, (queryEarlierRequests depth index program key).length ≤ b) (root : κ) : + (rankedMemoEvaluate (fun key => depth key + index key) program bits encode root .empty).requests ≤ + dependencyPathBudget (depth root) (index root) a b := by + calc + _ ≤ rankedUncachedCalls (fun key => depth key + index key) program root := + rankedMemoEvaluate_requests_le _ _ bits encode hinjective hbounded root .empty + (memoSound_empty bits encode _) + _ = (queryDependencyExpansion depth index program progress root).nodeCount := + (queryDependencyExpansion_nodes depth index program progress root).symm + _ ≤ dependencyPathBudget (depth root) (index root) a b := by + simpa only [queryDependencyExpansion_depth, queryDependencyExpansion_index] using + DependencyExpansion.nodeCount_le_budget a b _ + (queryDependencyExpansion_valid depth index program progress a b hsame hearlier root) + +end Queries + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryEarlierInputs.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryEarlierInputs.lean new file mode 100644 index 0000000000000000000000000000000000000000..ef1950a79b847e791cb105a413aabb02906fce10 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryEarlierInputs.lean @@ -0,0 +1,83 @@ +import OAI.Combinatorics.EditApproximation.Geometry.WideEarlierInputs +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! All wide-coordinate requests needed for one local query can be gathered +from bounded representative lists, including complete requested cells and +the rounded online center at every applicable scale. -/ + +namespace EditApproximation + +open Finset + + + +theorem queryEarlierRepresentatives_length {n : ℕ} (N P F exponent : ℕ) (a : ℚ) + (initial : TargetInterval n → ℚ) (q : TargetInterval n) (hP : ∃ e : ℕ, P = 2 ^ e) + (hF : 1 ≤ F) (hw : 0 ≤ initial q) : + (queryEarlierRepresentatives N P F exponent a initial q).length ≤ + (dyadicQueryWindow N (initial q) a F).length * + ((64 * F * P + 2) ^ 2 + + ((32 * F + 2) * 2 ^ exponent + 2) ^ 2 * (P + 1) ^ 2 + 1) := by + have hPpos : 0 < P := by obtain ⟨e, rfl⟩ := hP; positivity + have hlocal := localRefinementRepresentatives_length N P F a initial q hPpos hF + have hcells := localGroupQueryKeys_length N F exponent a initial q hF hw + have hmembers : ((localGroupQueryKeys N F exponent a initial q).flatMap fun key => + (cellRepresentativeStates n P F key.1 a initial ((2 : ℚ) ^ (-(exponent : ℤ))) key.2).map + fun r => (key.1, r)).length ≤ + (localGroupQueryKeys N F exponent a initial q).length * (P + 1) ^ 2 := by + apply list_flatMap_length_le + intro key hkey + have hscale := localGroupQueryKeys_scale hkey + obtain ⟨e, _, heq⟩ := List.mem_map.mp hscale + simpa only [List.length_map] using cellRepresentativeStates_length_le a initial + ((2 : ℚ) ^ (-(exponent : ℤ))) key.2 + ⟨by positivity, zpow_le_one_of_nonpos₀ (by norm_num : (1 : ℚ) ≤ 2) (by omega)⟩ + ⟨e, heq.symm⟩ hP + unfold queryEarlierRepresentatives + simp only [List.length_append, List.length_map] + nlinarith only [hlocal, hmembers, Nat.mul_le_mul_right ((P + 1) ^ 2) hcells] + +theorem queryEarlierRepresentatives_local {n : ℕ} (N P F exponent : ℕ) (a : ℚ) + (initial : TargetInterval n → ℚ) (q : TargetInterval n) (br : ℕ × TargetInterval n) + (hbr : br ∈ localRefinementRepresentatives N P F a initial q) : + br ∈ queryEarlierRepresentatives N P F exponent a initial q := by + exact List.mem_append_left _ (List.mem_append_left _ hbr) + +theorem queryEarlierRepresentatives_cell {n : ℕ} (N P F exponent : ℕ) (a : ℚ) + (initial : TargetInterval n → ℚ) (q : TargetInterval n) (key : ℕ × (ℕ × ℕ)) + (hkey : key ∈ localGroupQueryKeys N F exponent a initial q) (r : TargetInterval n) + (hr : r ∈ cellRepresentativeStates n P F key.1 a initial ((2 : ℚ) ^ (-(exponent : ℤ))) key.2) : + (key.1, r) ∈ queryEarlierRepresentatives N P F exponent a initial q := by + apply List.mem_append_left + apply List.mem_append_right + exact List.mem_flatMap.mpr ⟨key, hkey, List.mem_map.mpr ⟨r, hr, rfl⟩⟩ + +theorem queryEarlierRepresentatives_online {n : ℕ} (N P F exponent : ℕ) (a : ℚ) + (initial : TargetInterval n → ℚ) (q : TargetInterval n) (b : ℕ) + (hb : b ∈ dyadicQueryWindow N (initial q) a F) : + (b, roundInterval (seedGridSpacing b P) q) ∈ + queryEarlierRepresentatives N P F exponent a initial q := by + exact List.mem_append_right _ (List.mem_map.mpr ⟨b, hb, rfl⟩) + + + +theorem queryEarlierInputCover_card {nx ny M : ℕ} (parent : TargetInterval nx) + (N P F exponent history : ℕ) (a : ℚ) + (initial : TargetInterval ny → ℚ) (q : TargetInterval ny) (hP : ∃ e : ℕ, P = 2 ^ e) + (hF : 1 ≤ F) (hw : 0 ≤ initial q) : + (queryEarlierInputCover (M := M) parent N P F exponent history a initial q).card ≤ + (dyadicQueryWindow N (initial q) a F).length * + ((64 * F * P + 2) ^ 2 + + ((32 * F + 2) * 2 ^ exponent + 2) ^ 2 * (P + 1) ^ 2 + 1) * + M * history * (40 * P + 2) ^ 2 := by + have hPpos : 0 < P := by obtain ⟨e, rfl⟩ := hP; positivity + apply (wideEarlierInputCover_card parent P history _ hPpos).trans + exact Nat.mul_le_mul_right ((40 * P + 2) ^ 2) (Nat.mul_le_mul_right history + (Nat.mul_le_mul_right M (queryEarlierRepresentatives_length N P F exponent a initial q hP hF hw))) + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryEligibilitySpace.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryEligibilitySpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..815a4227cf72798d9070e03b525a71118af9e7fc --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryEligibilitySpace.lean @@ -0,0 +1,57 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryGuardSpace +import OAI.Combinatorics.EditApproximation.Binary.BinaryRefinementLists +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation.BinaryFraction + + + +theorem centerEligibilityAllocation_le_work (b F : ℕ) (a initial : BinaryFraction) : + centerEligibilityAllocation b F a initial ≤ (centerEligibilityWithWork b F a initial).2 := by + have hd := canonicalMulAllocation_le_work (nat 4) a + have hlo := divAllocation_le_work (nat b) (canonicalMulWithWork (nat 4) a).1 + have hfac := canonicalMulAllocation_le_work (nat 8) (nat F) + have hup := canonicalMulAllocation_le_work (canonicalMulWithWork (nat 8) (nat F)).1 (nat b) + have hl := leAllocation_le_work (divWithWork (nat b) (canonicalMulWithWork (nat 4) a).1).1 initial + have hh := leAllocation_le_work initial (canonicalMulWithWork (canonicalMulWithWork (nat 8) (nat F)).1 (nat b)).1 + unfold centerEligibilityAllocation centerEligibilityWithWork + dsimp only + omega + + + +theorem refinementScaleGuardAllocation_le_work (F b : ℕ) (a w : BinaryFraction) : + refinementScaleGuardAllocation F b a w ≤ (refinementScaleGuardWithWork F b a w).2 := by + have hd := canonicalMulAllocation_le_work (nat 16) (nat F) + have hlo := divAllocation_le_work w (canonicalMulWithWork (nat 16) (nat F)).1 + have hfac := canonicalMulAllocation_le_work (nat 8) a + have hup := canonicalMulAllocation_le_work (canonicalMulWithWork (nat 8) a).1 w + have hl := leAllocation_le_work (divWithWork w (canonicalMulWithWork (nat 16) (nat F)).1).1 (nat b) + have hh := leAllocation_le_work (nat b) (canonicalMulWithWork (canonicalMulWithWork (nat 8) a).1 w).1 + unfold refinementScaleGuardAllocation refinementScaleGuardWithWork + dsimp only + omega + + + +theorem queryExponentsAllocation_le_work (N F : ℕ) (a w : BinaryFraction) : + queryExponentsAllocation N F a w ≤ (queryExponentsWithWork N F a w).2 := by + have hf := filterAllocation_le_work + (fun e => ((refinementScaleGuardWithWork F (2 ^ e) a w).1, + (refinementScaleGuardWithWork F (2 ^ e) a w).2 + e + 2)) + (fun e => refinementScaleGuardAllocation F (2 ^ e) a w + e + 1) + (List.range (max 1 N.bits.length)) (by + intro e _ + have h := refinementScaleGuardAllocation_le_work F (2 ^ e) a w + dsimp only + omega) + unfold queryExponentsAllocation queryExponentsWithWork + dsimp only + omega + +end EditApproximation.BinaryFraction + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryFamilyActive.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryFamilyActive.lean new file mode 100644 index 0000000000000000000000000000000000000000..3f5c28b2058fbb1d60db083672c59f7b8c599ac5 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryFamilyActive.lean @@ -0,0 +1,99 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryFamilyRefinement +import OAI.Combinatorics.EditApproximation.Queries.QueryBoundedBody +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalRandomBoundedQuery + +namespace OAI + +/-! Positive internal refinement steps expose exactly the independent +scalar family and smaller physical table requests of the reference body. -/ + +namespace EditApproximation + +section Active +variable {α : Type*} [DecidableEq α] {M J R : ℕ} [NeZero M] [NeZero R] + (source target : List α) (N P F exponent H Q eM eF : ℕ) + (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) + (tau a eta kappa delta : BinaryFraction) (T S passes copies : ℕ) + (request : PhysicalTableRequest M J target.length) + (hindex : T < request.index) (hbelow : request.node.1.val < J) + +include hindex in +omit [DecidableEq α] [NeZero M] in +private theorem active_request_eq : + PhysicalTableRequest.refinement request.pass request.copy request.node T (request.index - T) + request.state = request := by + have hi : T + (request.index - T) = request.index := by omega + unfold PhysicalTableRequest.refinement + rw [hi] + +def queryFamilyActive : + BitQuery (Sum (PhysicalFamilyScalarKey (M := M) (J := J) (R := R) + target N P F exponent H Q passes copies) + {child : PhysicalTableRequest M J target.length // + child.combinedRank T S < request.combinedRank T S}) BinaryFraction := + BitQuery.mapKeysWithWork + (fun key => (Sum.map id (fun child => ⟨child.val, by + simpa only [active_request_eq (target := target) (T := T) (request := request) (hindex := hindex)] using child.property⟩) key, 1)) + (queryFamilyRefinement (R := R) source target N P F exponent H Q eM eF hP hM hF tau a eta kappa delta + passes copies request.pass request.copy T S (request.index - T) (Nat.sub_pos_of_lt hindex) + request.node hbelow (Fin.ofNat R (request.index - T - 1)) request.state) + +theorem queryFamilyActive_refines (factor : ℕ → ℚ) (multiplier : ℕ → ℕ) + (initial : PhysicalEntry M J target.length → ℕ) + (ha : a.value = refinementFactor (factor request.pass) F) + (hlong : ¬ (physicalSourceInterval source.length request.node).hi - + (physicalSourceInterval source.length request.node).lo ≤ 1) : + BitQuery.Refines (fun word value => word.value = value) + (queryFamilyActive (R := R) source target N P F exponent H Q eM eF hP hM hF tau a eta kappa delta + T S passes copies request hindex hbelow) + (physicalRandomGlobalQuery (R := R) source target N P F exponent H Q T S copies factor multiplier + tau.value eta.value kappa.value delta.value + (physicalFamilyGroupRead target N P F exponent H Q passes copies) + (physicalFamilyOnlineRead target N P F exponent H Q passes copies) initial request) := by + unfold queryFamilyActive physicalRandomGlobalQuery + rw [dite_eq_left ⟨hindex, hbelow, hlong⟩] + apply BitQuery.Refines.mapKeysWithWork _ _ (fun _ => rfl) + simpa only [ha] using queryFamilyRefinement_refines (R := R) source target N P F exponent H Q eM eF + hP hM hF tau a eta kappa delta passes copies request.pass request.copy T S + (request.index - T) (Nat.sub_pos_of_lt hindex) request.node hbelow + (Fin.ofNat R (request.index - T - 1)) request.state + +end Active + +section Bounded +variable {α : Type*} [DecidableEq α] {M J R : ℕ} [NeZero M] [NeZero R] + (source target : List α) (N P F exponent H Q eM eF : ℕ) + (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) + (tau a eta kappa delta : BinaryFraction) (T S passes copies : ℕ) + (parent : {r : PhysicalTableRequest M J target.length // r.Bounded (passes + 1) copies T S}) + (hindex : T < parent.val.index) (hbelow : parent.val.node.1.val < J) + +def queryFamilyBoundedActive : + BitQuery (Sum (PhysicalFamilyScalarKey (M := M) (J := J) (R := R) + target N P F exponent H Q passes copies) + {child : {r : PhysicalTableRequest M J target.length // r.Bounded (passes + 1) copies T S} // + child.val.combinedRank T S < parent.val.combinedRank T S}) BinaryFraction := + queryRestrictPhysicalBody (passes + 1) copies T S parent + (queryFamilyActive (R := R) source target N P F exponent H Q eM eF hP hM hF tau a eta kappa delta + T S passes copies parent.val hindex hbelow) + +theorem queryFamilyBoundedActive_refines (factor : ℕ → ℚ) (multiplier : ℕ → ℕ) + (initial : PhysicalEntry M J target.length → ℕ) + (ha : a.value = refinementFactor (factor parent.val.pass) F) + (hlong : ¬ (physicalSourceInterval source.length parent.val.node).hi - + (physicalSourceInterval source.length parent.val.node).lo ≤ 1) : + BitQuery.Refines (fun word value => word.value = value) + (queryFamilyBoundedActive (R := R) source target N P F exponent H Q eM eF hP hM hF tau a eta kappa delta + T S passes copies parent hindex hbelow) + (physicalRandomBoundedQuery (R := R) source target N P F exponent H Q T S (passes + 1) copies factor multiplier + tau.value eta.value kappa.value delta.value + (physicalFamilyGroupRead target N P F exponent H Q passes copies) + (physicalFamilyOnlineRead target N P F exponent H Q passes copies) initial parent) := by + apply queryRestrictPhysicalBody_refines + exact queryFamilyActive_refines (R := R) source target N P F exponent H Q eM eF hP hM hF + tau a eta kappa delta T S passes copies parent.val hindex hbelow factor multiplier initial ha hlong + +end Bounded +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryFamilyMemo.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryFamilyMemo.lean new file mode 100644 index 0000000000000000000000000000000000000000..a00273a3ab750662596394bba3aa0cdce3a21c7b --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryFamilyMemo.lean @@ -0,0 +1,80 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryChargedFamily +import OAI.Combinatorics.EditApproximation.Binary.BitSourceRanked +import OAI.Combinatorics.EditApproximation.Binary.BitRankedNormalize +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalRequestGrid +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalFamilyProgram +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! One binary memo stores independent scalar draws, coarse values, and +all recursive tables. The raw implementation preserves the exact +reference trace; normalization is justified on its reachable values. -/ + +namespace EditApproximation + +section Family +variable {M J R passes copies T S : ℕ} [NeZero M] [NeZero R] + (source target : List ℕ) (N P F exponent H Q eM eF : ℕ) + (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) + (A a : ℕ → BinaryFraction) (tau eta kappa delta : BinaryFraction) (multiplier : ℕ → ℕ) + (occurrence : BinaryMemo PositionCounts) (symbolBits positionBits : ℕ) + (coarse : PhysicalEntry M J target.length → BinaryFraction × ℕ) + (draw : PhysicalFamilyScalarDraw (M := M) (J := J) (R := R) + target N P F exponent H Q passes copies) + + + + + +def queryFamilyMemoRaw (key : QueryFamilyMemoKey (M := M) (J := J) (R := R) (passes := passes) (copies := copies) (T := T) (S := S) target N P F exponent H Q) := + SourceRanked.bitBody ChargedPhysicalRequest.rank + (queryChargedFamilyGlobal (R := R) source target N P F exponent H Q eM eF hP hM hF + A a tau eta kappa delta multiplier occurrence symbolBits positionBits coarse) + (queryFamilySourceWordWithWork target N P F exponent H Q draw) key + +theorem queryFamilyMemoRaw_refines + (ha : ∀ pass, pass ≤ passes → (a pass).value = refinementFactor (A pass).value F) + (hs : ∀ z ∈ source, z < 2 ^ symbolBits) (ht : ∀ z ∈ target, z < 2 ^ symbolBits) + (hp : target.length ≤ 2 ^ positionBits) + (htable : occurrence = occurrenceBuild symbolBits positionBits target.zipIdx) + (initial : PhysicalEntry M J target.length → ℕ) + (hc : ∀ entry, (coarse entry).1.value = initial entry) + (key : QueryFamilyMemoKey (M := M) (J := J) (R := R) (passes := passes) (copies := copies) (T := T) (S := S) target N P F exponent H Q) : + BitQuery.Refines (fun word value => word.value = value) + (queryFamilyMemoRaw source target N P F exponent H Q eM eF hP hM hF + A a tau eta kappa delta multiplier occurrence symbolBits positionBits coarse draw key) + (SourceRanked.body ChargedPhysicalRequest.rank + (physicalFamilyProgram source target N P F exponent H Q T S passes copies + (fun pass => (A pass).value) multiplier tau.value eta.value kappa.value delta.value initial) + (physicalFamilyAnswer target N P F exponent H Q passes copies draw) key) := by + have hr := SourceRanked.bitBody_refines ChargedPhysicalRequest.rank + (queryChargedFamilyGlobal (R := R) source target N P F exponent H Q eM eF hP hM hF + A a tau eta kappa delta multiplier occurrence symbolBits positionBits coarse) + (physicalFamilyProgram source target N P F exponent H Q T S passes copies + (fun pass => (A pass).value) multiplier tau.value eta.value kappa.value delta.value initial) + (queryFamilySourceWordWithWork target N P F exponent H Q draw) + (fun parent => queryChargedFamilyGlobal_refines source target N P F exponent H Q eM eF hP hM hF + A a tau eta kappa delta multiplier occurrence symbolBits positionBits ha hs ht hp htable + coarse initial hc parent) key + have hsources : (fun key => (queryFamilySourceWordWithWork target N P F exponent H Q draw key).1.value) = + physicalFamilyAnswer target N P F exponent H Q passes copies draw := by + funext key + exact BinaryFraction.nat_value _ + rw [hsources] at hr + exact hr + + + +def queryFamilyMemoNormalized (base : List Bool) (hbase : 0 < bitWordValue base) + (key : QueryFamilyMemoKey (M := M) (J := J) (R := R) (passes := passes) (copies := copies) (T := T) (S := S) target N P F exponent H Q) := + rankedNormalizeBody (SourceRanked.rank ChargedPhysicalRequest.rank) + (queryFamilyMemoRaw source target N P F exponent H Q eM eF hP hM hF + A a tau eta kappa delta multiplier occurrence symbolBits positionBits coarse draw) + base hbase (queryFamilyMemoRemaining (M := M) (J := J) (R := R) (passes := passes) (copies := copies) (T := T) (S := S) target N P F exponent H Q) key + +end Family +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryFamilyMemoSpace.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryFamilyMemoSpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..34f293c9696fcb74a96a50e62cf43e5650b7b5c5 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryFamilyMemoSpace.lean @@ -0,0 +1,48 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryChargedFamilySpace +import OAI.Combinatorics.EditApproximation.Binary.BinaryNormalizationSpace +import OAI.Combinatorics.EditApproximation.Queries.QueryFamilyMemo + +namespace OAI + +namespace EditApproximation +open BitQuery + +section Family +variable {M J R passes copies T S : ℕ} [NeZero M] [NeZero R] + (source target : List ℕ) (N P F exponent H Q eM eF : ℕ) + (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) + (A a : ℕ → BinaryFraction) (tau eta kappa delta : BinaryFraction) (multiplier : ℕ → ℕ) + (occurrence : BinaryMemo PositionCounts) (symbolBits positionBits : ℕ) + (coarse : PhysicalEntry M J target.length → BinaryFraction × ℕ) + (allocation : PhysicalEntry M J target.length → ℕ) + (hc : ∀ entry, allocation entry ≤ 3 * (coarse entry).2) + (draw : PhysicalFamilyScalarDraw (M := M) (J := J) (R := R) + target N P F exponent H Q passes copies) + +def queryFamilyMemoRawHeap + (key : QueryFamilyMemoKey (M := M) (J := J) (R := R) (passes := passes) + (copies := copies) (T := T) (S := S) target N P F exponent H Q) : + Heap (queryFamilyMemoRaw source target N P F exponent H Q eM eF hP hM hF + A a tau eta kappa delta multiplier occurrence symbolBits positionBits coarse draw key) := by + cases key with + | inl scalar => + exact Heap.computeOf (queryFamilySourceWordWithWork target N P F exponent H Q draw scalar) + (Nat.size (draw scalar).val + 2) (by simp only [queryFamilySourceWordWithWork]; omega) + | inr request => + exact (queryChargedFamilyGlobalHeap source target N P F exponent H Q eM eF hP hM hF + A a tau eta kappa delta multiplier occurrence symbolBits positionBits coarse allocation hc request).mapKeysWithWork + _ (fun _ => 1) (fun _ => le_rfl) + +def queryFamilyMemoNormalizedHeap (base : List Bool) (hbase : 0 < bitWordValue base) + (key : QueryFamilyMemoKey (M := M) (J := J) (R := R) (passes := passes) + (copies := copies) (T := T) (S := S) target N P F exponent H Q) : + Heap (queryFamilyMemoNormalized source target N P F exponent H Q eM eF hP hM hF + A a tau eta kappa delta multiplier occurrence symbolBits positionBits coarse draw base hbase key) := + (queryFamilyMemoRawHeap source target N P F exponent H Q eM eF hP hM hF + A a tau eta kappa delta multiplier occurrence symbolBits positionBits coarse allocation hc draw key).normalize + base hbase (queryFamilyMemoRemaining target N P F exponent H Q key) + +end Family +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryFamilyNormalize.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryFamilyNormalize.lean new file mode 100644 index 0000000000000000000000000000000000000000..ca287a047fefd2e179cc5d3761ef1d6b5f97d8b2 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryFamilyNormalize.lean @@ -0,0 +1,165 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryFamilyMemo +import OAI.Combinatorics.EditApproximation.Binary.BitMemoWorkOn + +namespace OAI + +/-! The complete mixed memo is normalized on the physical +table grid. Its actual ranked binary values and adaptive reference trace +agree on every coarse seed and every finite scalar draw. -/ + +namespace EditApproximation + +private theorem familyBase_pos (ell : ℕ) (base : List Bool) + (hbase : bitWordValue base = ell ^ 10 + 1) : 0 < bitWordValue base := by + rw [hbase] + omega + +section Family +variable {M J R passes copies T S : ℕ} [NeZero M] [NeZero R] + (source target : List ℕ) (N P F exponent H Q eM eF : ℕ) + (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) + (A a : ℕ → BinaryFraction) (tau eta kappa delta : BinaryFraction) (multiplier : ℕ → ℕ) + (occurrence : BinaryMemo PositionCounts) (symbolBits positionBits : ℕ) + (coarse : PhysicalEntry M J target.length → BinaryFraction × ℕ) + (draw : PhysicalFamilyScalarDraw (M := M) (J := J) (R := R) + target N P F exponent H Q passes copies) + (initial : PhysicalEntry M J target.length → ℕ) + (ha : ∀ pass, pass ≤ passes → (a pass).value = refinementFactor (BinaryFraction.value (A pass)) F) + (hs : ∀ z ∈ source, z < 2 ^ symbolBits) (ht : ∀ z ∈ target, z < 2 ^ symbolBits) + (hp : target.length ≤ 2 ^ positionBits) + (htable : occurrence = occurrenceBuild symbolBits positionBits target.zipIdx) + (hc : ∀ entry, (coarse entry).1.value = initial entry) + (ell : ℕ) (hell : 0 < ell) (hdelta : delta.value = 1 / (ell : ℚ) ^ 10) + (base : List Bool) (hbase : bitWordValue base = ell ^ 10 + 1) + +local notation "raw" => queryFamilyMemoRaw source target N P F exponent H Q eM eF hP hM hF + A a tau eta kappa delta multiplier occurrence symbolBits positionBits coarse draw +local notation "reference" => SourceRanked.body ChargedPhysicalRequest.rank + (physicalFamilyProgram source target N P F exponent H Q T S passes copies + (fun pass => BinaryFraction.value (A pass)) multiplier tau.value eta.value kappa.value delta.value initial) + (physicalFamilyAnswer target N P F exponent H Q passes copies draw) +local notation "semantic" => SourceRanked.value + (physicalFamilyAnswer target N P F exponent H Q passes copies draw) + (physicalFamilyRequestValue source target N P F exponent H Q T S passes copies + (fun pass => BinaryFraction.value (A pass)) multiplier tau.value eta.value kappa.value delta.value initial hP draw) +local notation "normalized" => queryFamilyMemoNormalized source target N P F exponent H Q eM eF hP hM hF + A a tau eta kappa delta multiplier occurrence symbolBits positionBits coarse draw + base (familyBase_pos ell base hbase) + +include ha hs ht hp htable hc hell hdelta in +theorem queryFamilyMemoNormalized_correct + (key : QueryFamilyMemoKey (M := M) (J := J) (R := R) (passes := passes) (copies := copies) (T := T) (S := S) target N P F exponent H Q) : + (rankedBitProgramValue (SourceRanked.rank ChargedPhysicalRequest.rank) normalized key).value = + semantic key ∧ + BitQuery.RefinesOn + (fun child => rankedBitProgramValue (SourceRanked.rank ChargedPhysicalRequest.rank) + normalized child.val) + (fun word value => word.value = value) (normalized key) (reference key) := by + have hraw (key : QueryFamilyMemoKey (M := M) (J := J) (R := R) (passes := passes) (copies := copies) (T := T) (S := S) target N P F exponent H Q) : + BitQuery.Refines (fun word value => word.value = value) (raw key) (reference key) := + queryFamilyMemoRaw_refines source target N P F exponent H Q eM eF hP hM hF + A a tau eta kappa delta multiplier occurrence symbolBits positionBits coarse draw + ha hs ht hp htable initial hc key + have hbody (key : QueryFamilyMemoKey (M := M) (J := J) (R := R) (passes := passes) (copies := copies) (T := T) (S := S) target N P F exponent H Q) : + (reference key).value (fun child => semantic child.val) = semantic key := by + apply SourceRanked.body_value + intro request + exact physicalFamilyProgram_value source target N P F exponent H Q T S passes copies + (fun pass => BinaryFraction.value (A pass)) multiplier tau.value eta.value kappa.value delta.value initial hP draw request + have hd (key : QueryFamilyMemoKey (M := M) (J := J) (R := R) (passes := passes) (copies := copies) (T := T) (S := S) target N P F exponent H Q) : + (semantic key).den ∣ bitWordValue base ^ queryFamilyMemoRemaining (M := M) (J := J) (R := R) (passes := passes) (copies := copies) (T := T) (S := S) target N P F exponent H Q key := by + cases key with + | inl source => + change ((draw source).val : ℚ).den ∣ _ + rw [Rat.den_natCast] + exact one_dvd _ + | inr request => + change (physicalFamilyRequestValue source target N P F exponent H Q T S passes copies + (fun pass => BinaryFraction.value (A pass)) multiplier tau.value eta.value kappa.value delta.value initial hP draw + request).den ∣ bitWordValue base ^ chargedPhysicalRemaining request + unfold physicalFamilyRequestValue + rw [hdelta, hbase] + exact chargedRequestValue_den_dvd source target N P F exponent H Q T S (passes + 1) copies ell + (fun pass => BinaryFraction.value (A pass)) multiplier tau.value eta.value kappa.value _ _ initial hell request + exact rankedNormalizeBody_correct (SourceRanked.rank ChargedPhysicalRequest.rank) raw reference + semantic hraw hbody base (familyBase_pos ell base hbase) + (queryFamilyMemoRemaining (M := M) (J := J) (R := R) (passes := passes) (copies := copies) (T := T) (S := S) target N P F exponent H Q) hd key + +include ha hs ht hp htable hc hell hdelta in +theorem queryFamilyMemoNormalized_width + (key : QueryFamilyMemoKey (M := M) (J := J) (R := R) (passes := passes) (copies := copies) (T := T) (S := S) target N P F exponent H Q) + (B V : ℕ) (hB : base.length ≤ B) (hV : |semantic key| ≤ (V : ℚ)) : + (rankedBitProgramValue (SourceRanked.rank ChargedPhysicalRequest.rank) normalized key).width ≤ + Nat.size V + 2 * (queryFamilyMemoRemaining (M := M) (J := J) (R := R) + (passes := passes) (copies := copies) (T := T) (S := S) target N P F exponent H Q key * B + 1) + 1 := by + have hraw (key : QueryFamilyMemoKey (M := M) (J := J) (R := R) (passes := passes) (copies := copies) (T := T) (S := S) target N P F exponent H Q) : + BitQuery.Refines (fun word value => word.value = value) (raw key) (reference key) := + queryFamilyMemoRaw_refines source target N P F exponent H Q eM eF hP hM hF + A a tau eta kappa delta multiplier occurrence symbolBits positionBits coarse draw + ha hs ht hp htable initial hc key + have hbody (key : QueryFamilyMemoKey (M := M) (J := J) (R := R) (passes := passes) (copies := copies) (T := T) (S := S) target N P F exponent H Q) : + (reference key).value (fun child => semantic child.val) = semantic key := by + apply SourceRanked.body_value + intro request + exact physicalFamilyProgram_value source target N P F exponent H Q T S passes copies + (fun pass => BinaryFraction.value (A pass)) multiplier tau.value eta.value kappa.value delta.value initial hP draw request + have hd (key : QueryFamilyMemoKey (M := M) (J := J) (R := R) (passes := passes) (copies := copies) (T := T) (S := S) target N P F exponent H Q) : + (semantic key).den ∣ bitWordValue base ^ queryFamilyMemoRemaining (M := M) (J := J) (R := R) (passes := passes) (copies := copies) (T := T) (S := S) target N P F exponent H Q key := by + cases key with + | inl source => + change ((draw source).val : ℚ).den ∣ _ + rw [Rat.den_natCast] + exact one_dvd _ + | inr request => + change (physicalFamilyRequestValue source target N P F exponent H Q T S passes copies + (fun pass => BinaryFraction.value (A pass)) multiplier tau.value eta.value kappa.value delta.value initial hP draw + request).den ∣ bitWordValue base ^ chargedPhysicalRemaining request + unfold physicalFamilyRequestValue + rw [hdelta, hbase] + exact chargedRequestValue_den_dvd source target N P F exponent H Q T S (passes + 1) copies ell + (fun pass => BinaryFraction.value (A pass)) multiplier tau.value eta.value kappa.value _ _ initial hell request + exact rankedNormalizeBody_width (SourceRanked.rank ChargedPhysicalRequest.rank) raw reference + semantic hraw hbody base (familyBase_pos ell base hbase) + (queryFamilyMemoRemaining (M := M) (J := J) (R := R) (passes := passes) (copies := copies) (T := T) (S := S) target N P F exponent H Q) + hd key B V hB hV + + +include ha hs ht hp htable hc hell hdelta in +theorem queryFamilyMemoNormalized_decode (bits : ℕ) + (encode : QueryFamilyMemoKey (M := M) (J := J) (R := R) (passes := passes) (copies := copies) + (T := T) (S := S) target N P F exponent H Q → ℕ) + (hinjective : Function.Injective encode) (hbounded : ∀ key, encode key < 2 ^ bits) + (key : QueryFamilyMemoKey (M := M) (J := J) (R := R) (passes := passes) (copies := copies) + (T := T) (S := S) target N P F exponent H Q) : + (rankedBitMemoEvaluate (SourceRanked.rank ChargedPhysicalRequest.rank) normalized bits encode key + .empty).decode = + rankedMemoEvaluate (SourceRanked.rank ChargedPhysicalRequest.rank) reference bits encode key .empty := by + apply rankedBitMemoEvaluate_decode_on _ _ _ _ bits encode hinjective hbounded key .empty + (bitMemoSound_empty _ _ _) + intro next + exact (queryFamilyMemoNormalized_correct source target N P F exponent H Q eM eF hP hM hF + A a tau eta kappa delta multiplier occurrence symbolBits positionBits coarse draw initial + ha hs ht hp htable hc ell hell hdelta base hbase next).2 + +include ha hs ht hp htable hc hell hdelta in +theorem queryFamilyMemoNormalized_work_transfer (bits : ℕ) + (encode : QueryFamilyMemoKey (M := M) (J := J) (R := R) (passes := passes) (copies := copies) + (T := T) (S := S) target N P F exponent H Q → ℕ) + (hinjective : Function.Injective encode) (hbounded : ∀ key, encode key < 2 ^ bits) + (key : QueryFamilyMemoKey (M := M) (J := J) (R := R) (passes := passes) (copies := copies) + (T := T) (S := S) target N P F exponent H Q) : + (rankedBitMemoEvaluate (SourceRanked.rank ChargedPhysicalRequest.rank) normalized bits encode key + .empty).localWork = + rankedMemoKernelWork (SourceRanked.rank ChargedPhysicalRequest.rank) reference bits encode + (rankedBitLocalWork (SourceRanked.rank ChargedPhysicalRequest.rank) normalized) key .empty := by + apply rankedBitMemoEvaluate_work_transfer_on _ _ _ _ bits encode hinjective hbounded key .empty + (bitMemoSound_empty _ _ _) + intro next + exact (queryFamilyMemoNormalized_correct source target N P F exponent H Q eM eF hP hM hF + A a tau eta kappa delta multiplier occurrence symbolBits positionBits coarse draw initial + ha hs ht hp htable hc ell hell hdelta base hbase next).2 + +end Family +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryFamilyReaderBounds.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryFamilyReaderBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..bb1850dde6189a2cfd9e9b0d071762eea76ca2d0 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryFamilyReaderBounds.lean @@ -0,0 +1,71 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryFamilySourceCosts +import OAI.Combinatorics.EditApproximation.Queries.QuerySourceKeyWidths + +namespace OAI + +namespace EditApproximation.BinaryFraction + +def queryFamilySourceReadBudget (J B W : ℕ) : ℕ := + 200 * (1000 * (B + 1) + 1000 + 2) ^ 2 + 120 * (B + 1) ^ 2 + 10 * J + 100 + W + +end EditApproximation.BinaryFraction + +namespace EditApproximation +section Family +variable {α : Type*} {M J R : ℕ} (target : List α) + (N P F exponent H Q passes copies pass copy B W : ℕ) + (oracle : PhysicalFamilyScalarKey (M := M) (J := J) (R := R) + target N P F exponent H Q passes copies → BinaryFraction) + (readWork : PhysicalFamilyScalarKey (M := M) (J := J) (R := R) + target N P F exponent H Q passes copies → ℕ) + (hN : Nat.size N ≤ B) (hp : Nat.size pass ≤ B) (hc : Nat.size copy ≤ B) + (hps : Nat.size (passes + 1) ≤ B) (hcs : Nat.size (copies + 1) ≤ B) + (hW : ∀ key, readWork key ≤ W) + +include hN hp hc hps hcs hW in +theorem queryFamilyGroupRead_bounded_work + (hn : Nat.size target.length ≤ B) (he : exponent + 1 ≤ B) + (node : PhysicalInternalNode M J) (time : Fin R) (key : GroupScalarKey M F Q) + (hk : queryGroupKeySize key ≤ 40 * B + 500) : + (queryFamilyGroupRead target N P F exponent H Q passes copies pass copy node time key).work oracle readWork ≤ + BinaryFraction.queryFamilySourceReadBudget J B W := by + let D := 1000 * (B + 1) + 1000 + let K := 120 * (B + 1) ^ 2 + 5 * J + 55 + have hb : B ≤ D := by dsimp only [D]; omega + have hkey : queryGroupKeySize key ≤ D := by dsimp only [D]; omega + have hscale := queryScalePresentWithWork_cost N key.1.1 D (hN.trans hb) + (by unfold queryGroupKeySize at hkey; omega) + have hcell := queryCellValidWithWork_cost target.length exponent D key.1.2 + (hn.trans hb) (he.trans hb) (by unfold queryGroupKeySize at hkey; omega) + (by unfold queryGroupKeySize at hkey; omega) + have hr := queryFamilyGroupRead_work target N P F exponent H Q passes copies pass copy oracle readWork K W + (fun scalar => queryFamilyTagWithWork_cost target N P F exponent H Q passes copies pass copy B hp hc hps hcs scalar) + hW node time key + change _ ≤ 200 * (D + 2) ^ 2 + 120 * (B + 1) ^ 2 + 10 * J + 100 + W + dsimp only [K] at hr + nlinarith only [hscale, hcell, hr, Nat.zero_le D] + +include hN hp hc hps hcs hW in +theorem queryFamilyOnlineRead_bounded_work + (hbound : Nat.size (localOnlineMassBound M P H) ≤ B) + (node : PhysicalInternalNode M J) (time : Fin R) (key : ℕ × TargetInterval target.length) + (range : ℕ) (hk : Nat.size key.1 ≤ B + 1) (hrange : Nat.size range ≤ 240 * (B + 5) + 7) : + (queryFamilyOnlineRead target N P F exponent H Q passes copies pass copy node time key range).work oracle readWork ≤ + BinaryFraction.queryFamilySourceReadBudget J B W := by + let D := 1000 * (B + 1) + 1000 + let K := 120 * (B + 1) ^ 2 + 5 * J + 55 + have hb : B ≤ D := by dsimp only [D]; omega + have hs := queryScalePresentWithWork_cost N key.1 D (hN.trans hb) (by dsimp only [D]; omega) + have hv := queryRangeValidWithWork_cost (localOnlineMassBound M P H) range D + (hbound.trans hb) (by dsimp only [D]; omega) + have hr := queryFamilyOnlineRead_work target N P F exponent H Q passes copies pass copy oracle readWork K W + (fun scalar => queryFamilyTagWithWork_cost target N P F exponent H Q passes copies pass copy B hp hc hps hcs scalar) + hW node time key range + change _ ≤ 200 * (D + 2) ^ 2 + 120 * (B + 1) ^ 2 + 10 * J + 100 + W + dsimp only [K] at hr + nlinarith only [hs, hv, hr, Nat.zero_le D] + +end Family +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryFamilyRefinement.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryFamilyRefinement.lean new file mode 100644 index 0000000000000000000000000000000000000000..10ae065afae4bbfd9bf6d0427c567fb6dd00a2d6 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryFamilyRefinement.lean @@ -0,0 +1,45 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryPhysicalProgram +import OAI.Combinatorics.EditApproximation.Queries.QueryFamilyScalarReads + +namespace OAI + +/-! The charged local refinement uses the independent source +family, with computed scalar guards and pass/copy addresses. -/ + +namespace EditApproximation + +section Family +variable {α : Type*} {M J R : ℕ} [NeZero M] (source target : List α) + (N P F exponent H Q eM eF : ℕ) (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) + (tau a eta kappa delta : BinaryFraction) (passes copies pass copy T S t : ℕ) (ht : 0 < t) + (node : PhysicalNode M J) (hbelow : node.1.val < J) (time : Fin R) + (q : TargetInterval target.length) + +def queryFamilyRefinement : + BitQuery (Sum (PhysicalFamilyScalarKey (M := M) (J := J) (R := R) + target N P F exponent H Q passes copies) + {child : PhysicalTableRequest M J target.length // child.combinedRank T S < + (PhysicalTableRequest.refinement pass copy node T t q).combinedRank T S}) BinaryFraction := + queryPhysicalRandomDataRequest source target N P F exponent H Q eM eF hP hM hF + tau a eta kappa delta copies pass copy T S t ht node hbelow + (queryFamilyGroupRead target N P F exponent H Q passes copies pass copy ⟨node, hbelow⟩ time) + (queryFamilyOnlineRead target N P F exponent H Q passes copies pass copy ⟨node, hbelow⟩ time) q + +theorem queryFamilyRefinement_refines : + BitQuery.Refines (fun word value => word.value = value) + (queryFamilyRefinement source target N P F exponent H Q eM eF hP hM hF tau a eta kappa delta + passes copies pass copy T S t ht node hbelow time q) + (physicalRandomDataRequestQuery source target N P F exponent H Q tau.value a.value eta.value + kappa.value delta.value pass copy T S t ht node hbelow + (physicalFamilyGroupRead target N P F exponent H Q passes copies pass copy ⟨node, hbelow⟩ time) + (physicalFamilyOnlineRead target N P F exponent H Q passes copies pass copy ⟨node, hbelow⟩ time) q) := by + apply queryPhysicalRandomDataRequest_refines + · intro key + exact queryFamilyGroupRead_refines target N P F exponent H Q passes copies pass copy _ time key + · intro key range + exact queryFamilyOnlineRead_refines target N P F exponent H Q passes copies pass copy _ time key range + +end Family +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryFamilyRefinementCost.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryFamilyRefinementCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..8901667b4da7b9980dadf3317571e086ebaa4535 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryFamilyRefinementCost.lean @@ -0,0 +1,73 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryFamilyRefinement +import OAI.Combinatorics.EditApproximation.Queries.QueryPhysicalProgramCost +import OAI.Combinatorics.EditApproximation.Queries.QueryFamilyReaderBounds + +namespace OAI + +namespace EditApproximation +section Family +variable {α : Type*} {M J R : ℕ} [NeZero M] (source target : List α) + (N P F exponent H Q eM eF B E Scale : ℕ) (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) + (tau a eta kappa delta : BinaryFraction) (passes copies pass copy T S t : ℕ) (ht : 0 < t) + (node : PhysicalNode M J) (hbelow : node.1.val < J) (time : Fin R) (q : TargetInterval target.length) + (oracle : Sum (PhysicalFamilyScalarKey (M := M) (J := J) (R := R) + target N P F exponent H Q passes copies) + {child : PhysicalTableRequest M J target.length // child.combinedRank T S < + (PhysicalTableRequest.refinement pass copy node T t q).combinedRank T S} → BinaryFraction) + (readWork : Sum (PhysicalFamilyScalarKey (M := M) (J := J) (R := R) + target N P F exponent H Q passes copies) + {child : PhysicalTableRequest M J target.length // child.combinedRank T S < + (PhysicalTableRequest.refinement pass copy node T t q).combinedRank T S} → ℕ) + +local notation "tableOracle" => (fun key => oracle (Sum.inr key)) +open BinaryFraction + +theorem queryFamilyRefinement_work_bound (V C : ℕ) + (hn : PreparedKernelNumericBounds (nx := source.length) (ny := target.length) (M := M) + N P F exponent H Q eM eF B E Scale (t - 1) tau a eta kappa delta (fun _ _ => 0)) + (htime : Nat.size t ≤ B) (hPd : ∃ j : ℕ, P = 2 ^ j) + (hV : 2 ≤ V) (hVB : V ≤ B) (hMean : warmupAverageWordBudget T V ≤ B) + (hc : ∀ key, key.val.pass = pass → key.val.copy = copy → readWork (Sum.inr key) ≤ C) + (hs : ∀ key, readWork (Sum.inl key) ≤ C) + (hv : ∀ key, (tableOracle key).width ≤ V) + (hsv : ∀ key, (oracle (Sum.inl key)).width ≤ B) + (hnonneg : ∀ key, 0 ≤ (tableOracle key).value) + (hprior : ∀ input : Fin M × ℕ × TargetInterval target.length, + ((queryPhysicalEarlierRead copies pass copy T S t node hbelow q input).value tableOracle).value ≤ + ((queryPhysicalWarmupRead copies pass copy T S t ht node q + (physicalChild node hbelow input.1) (by change node.1.val ≤ node.1.val + 1; omega) + 0 (Nat.zero_le T) input.2.2).value tableOracle).value) + (hp : Nat.size pass ≤ B) (hcopy : Nat.size copy ≤ B) + (hps : Nat.size (passes + 1) ≤ B) (hcs : Nat.size (copies + 1) ≤ B) + (hbound : Nat.size (localOnlineMassBound M P H) ≤ B) : + (queryFamilyRefinement source target N P F exponent H Q eM eF hP hM hF tau a eta kappa delta + passes copies pass copy T S t ht node hbelow time q).work oracle readWork ≤ + queryLocalProgramBitBudget M N P F exponent eM eF B Scale t + (queryPhysicalDataBudget T J B V C (queryFamilySourceReadBudget J B (C + 1))) := by + have hB : 2 ≤ B := by have := hn.largeBits; omega + have htarget : Nat.size target.length ≤ B := by have := hn.targetSize; omega + unfold queryFamilyRefinement + apply queryPhysicalRandomDataRequest_work_bound source target N P F exponent H Q eM eF B E Scale + hP hM hF tau a eta kappa delta copies pass copy T S t ht node hbelow _ _ q oracle readWork + V C (queryFamilySourceReadBudget J B (C + 1)) hn htime hPd hV hVB hMean hc hv hnonneg hprior + · intro key + exact queryFamilyGroupRead_width target N P F exponent H Q passes copies pass copy B + (fun key => oracle (Sum.inl key)) hB hsv ⟨node, hbelow⟩ time key + · intro key range + exact queryFamilyOnlineRead_width target N P F exponent H Q passes copies pass copy B + (fun key => oracle (Sum.inl key)) hB hsv ⟨node, hbelow⟩ time key range + · intro key hk + exact queryFamilyGroupRead_bounded_work target N P F exponent H Q passes copies pass copy B (C + 1) + (fun key => oracle (Sum.inl key)) (fun key => 1 + readWork (Sum.inl key)) + hn.inputSize hp hcopy hps hcs (fun key => by have := hs key; omega) + htarget hn.thetaSize ⟨node, hbelow⟩ time key hk + · intro key range hk hr + exact queryFamilyOnlineRead_bounded_work target N P F exponent H Q passes copies pass copy B (C + 1) + (fun key => oracle (Sum.inl key)) (fun key => 1 + readWork (Sum.inl key)) + hn.inputSize hp hcopy hps hcs (fun key => by have := hs key; omega) + hbound ⟨node, hbelow⟩ time key range hk hr + +end Family +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryFamilyScalarReads.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryFamilyScalarReads.lean new file mode 100644 index 0000000000000000000000000000000000000000..e0d7df454eb74f5ae3286086853924bd80eefea4 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryFamilyScalarReads.lean @@ -0,0 +1,63 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryPhysicalScalarReads +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Counted pass/copy indexing for the independent scalar family. Both +remainders and the complete family address are computed before lookup. -/ + +namespace EditApproximation + + + +theorem queryFinOfNatWithWork_value (bound value : ℕ) (hb : 0 < bound) [NeZero bound] : + (queryFinOfNatWithWork bound value hb).1 = Fin.ofNat bound value := by + apply Fin.ext + exact (binaryNaturalDivModWithWork_spec value bound hb).2 + +theorem queryFinOfNatWithWork_cost (bound value B : ℕ) (hb : 0 < bound) + (hbound : Nat.size bound ≤ B) (hvalue : Nat.size value ≤ B) : + (queryFinOfNatWithWork bound value hb).2 ≤ 60 * (B + 1) ^ 2 + 1 := by + have h := binaryNaturalDivModWithWork_cost value bound + change (binaryNaturalDivModWithWork value bound).2.2 + 1 ≤ _ + nlinarith only [h, hbound, hvalue, Nat.zero_le B] + +section Family +variable {α : Type*} {M J R : ℕ} (target : List α) + (N P F exponent H Q passes copies pass copy : ℕ) + + + +theorem queryFamilyTagWithWork_value + (scalar : PhysicalScalarKey M J N target.length exponent F Q R (localOnlineMassBound M P H)) : + (queryFamilyTagWithWork target N P F exponent H Q passes copies pass copy scalar).1 = + (Fin.ofNat (passes + 1) pass, Fin.ofNat (copies + 1) copy, scalar) := by + simp only [queryFamilyTagWithWork, queryFinOfNatWithWork_value] + + + +theorem queryFamilyGroupRead_refines (node : PhysicalInternalNode M J) (time : Fin R) + (key : GroupScalarKey M F Q) : + BitQuery.Refines (fun word value => word.value = value) + (queryFamilyGroupRead target N P F exponent H Q passes copies pass copy node time key) + (physicalFamilyGroupRead target N P F exponent H Q passes copies pass copy node time key) := by + exact (queryPhysicalScalarGroupRead_refines M J N target.length exponent F Q R + (localOnlineMassBound M P H) node time key).mapKeysWithWork _ _ + (queryFamilyTagWithWork_value target N P F exponent H Q passes copies pass copy) + + + +theorem queryFamilyOnlineRead_refines (node : PhysicalInternalNode M J) (time : Fin R) + (key : ℕ × TargetInterval target.length) (range : ℕ) : + BitQuery.Refines (fun word value => word.value = value) + (queryFamilyOnlineRead target N P F exponent H Q passes copies pass copy node time key range) + (physicalFamilyOnlineRead target N P F exponent H Q passes copies pass copy node time key range) := by + exact (queryPhysicalScalarOnlineRead_refines M J N target.length exponent F Q R + (localOnlineMassBound M P H) node time key range).mapKeysWithWork _ _ + (queryFamilyTagWithWork_value target N P F exponent H Q passes copies pass copy) + +end Family +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryFamilySourceCosts.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryFamilySourceCosts.lean new file mode 100644 index 0000000000000000000000000000000000000000..a25cc8cf95b10769185e4c95d7e1826c16c30b8e --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryFamilySourceCosts.lean @@ -0,0 +1,64 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryFamilyScalarReads +import OAI.Combinatorics.EditApproximation.Queries.QueryPhysicalSourceCosts + +namespace OAI + +namespace EditApproximation + +section Family +variable {α : Type*} {M J R : ℕ} (target : List α) + (N P F exponent H Q passes copies pass copy : ℕ) + +theorem queryFamilyTagWithWork_cost (B : ℕ) + (hp : Nat.size pass ≤ B) (hc : Nat.size copy ≤ B) + (hps : Nat.size (passes + 1) ≤ B) (hcs : Nat.size (copies + 1) ≤ B) + (scalar : PhysicalScalarKey M J N target.length exponent F Q R (localOnlineMassBound M P H)) : + (queryFamilyTagWithWork target N P F exponent H Q passes copies pass copy scalar).2 ≤ + 120 * (B + 1) ^ 2 + 5 * J + 55 := by + have h1 := queryFinOfNatWithWork_cost (passes + 1) pass B (Nat.succ_pos _) hps hp + have h2 := queryFinOfNatWithWork_cost (copies + 1) copy B (Nat.succ_pos _) hcs hc + have h3 := physicalFamilyCodeWithWork_cost target N P F exponent H Q passes copies + ((queryFinOfNatWithWork (passes + 1) pass (Nat.succ_pos _)).1, + (queryFinOfNatWithWork (copies + 1) copy (Nat.succ_pos _)).1, scalar) + change (queryFinOfNatWithWork (passes + 1) pass (Nat.succ_pos _)).2 + + (queryFinOfNatWithWork (copies + 1) copy (Nat.succ_pos _)).2 + _ + 1 ≤ _ + omega + +variable + (oracle : PhysicalFamilyScalarKey (M := M) (J := J) (R := R) + target N P F exponent H Q passes copies → BinaryFraction) + (readWork : PhysicalFamilyScalarKey (M := M) (J := J) (R := R) + target N P F exponent H Q passes copies → ℕ) + (K W : ℕ) + (hK : ∀ scalar : PhysicalScalarKey M J N target.length exponent F Q R (localOnlineMassBound M P H), + (queryFamilyTagWithWork target N P F exponent H Q passes copies pass copy scalar).2 ≤ K) + (hW : ∀ key, readWork key ≤ W) + +include hK hW in +theorem queryFamilyGroupRead_work (node : PhysicalInternalNode M J) (time : Fin R) + (key : GroupScalarKey M F Q) : + (queryFamilyGroupRead target N P F exponent H Q passes copies pass copy node time key).work + oracle readWork ≤ (queryScalePresentWithWork N key.1.1).2 + + (queryCellValidWithWork target.length exponent key.1.2).2 + 5 * J + 43 + (K + W) := by + unfold queryFamilyGroupRead + rw [BitQuery.mapKeysWithWork_work] + apply queryPhysicalScalarGroupRead_work + intro scalar + exact Nat.add_le_add (hK scalar) (hW _) + +include hK hW in +theorem queryFamilyOnlineRead_work (node : PhysicalInternalNode M J) (time : Fin R) + (key : ℕ × TargetInterval target.length) (range : ℕ) : + (queryFamilyOnlineRead target N P F exponent H Q passes copies pass copy node time key range).work + oracle readWork ≤ (queryScalePresentWithWork N key.1).2 + + (queryRangeValidWithWork (localOnlineMassBound M P H) range).2 + 5 * J + 43 + (K + W) := by + unfold queryFamilyOnlineRead + rw [BitQuery.mapKeysWithWork_work] + apply queryPhysicalScalarOnlineRead_work + intro scalar + exact Nat.add_le_add (hK scalar) (hW _) + +end Family +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryFamilySpace.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryFamilySpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..48d0e4d4cec92238e0f80bc00bfac1aac52f4cc1 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryFamilySpace.lean @@ -0,0 +1,59 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryScalarReadSpace +import OAI.Combinatorics.EditApproximation.Queries.QueryRestrictionSpace +import OAI.Combinatorics.EditApproximation.Queries.QueryFamilyActive + +namespace OAI + +namespace EditApproximation +open BitQuery + +section Family +variable {α : Type*} {M J R : ℕ} [NeZero M] (source target : List α) + (N P F exponent H Q eM eF : ℕ) (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) + (tau a eta kappa delta : BinaryFraction) (passes copies pass copy T S t : ℕ) (ht : 0 < t) + (node : PhysicalNode M J) (hbelow : node.1.val < J) (time : Fin R) + (q : TargetInterval target.length) + +def queryFamilyRefinementHeap : Heap (queryFamilyRefinement source target N P F exponent H Q eM eF hP hM hF + tau a eta kappa delta passes copies pass copy T S t ht node hbelow time q) := + queryPhysicalRandomDataRequestHeap source target N P F exponent H Q eM eF hP hM hF + tau a eta kappa delta copies pass copy T S t ht node hbelow _ _ q + (queryFamilyGroupReadHeap target N P F exponent H Q passes copies pass copy ⟨node, hbelow⟩ time) + (queryFamilyOnlineReadHeap target N P F exponent H Q passes copies pass copy ⟨node, hbelow⟩ time) + +end Family + +section Active +variable {α : Type*} [DecidableEq α] {M J R : ℕ} [NeZero M] [NeZero R] + (source target : List α) (N P F exponent H Q eM eF : ℕ) + (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) + (tau a eta kappa delta : BinaryFraction) (T S passes copies : ℕ) + (request : PhysicalTableRequest M J target.length) + (hindex : T < request.index) (hbelow : request.node.1.val < J) + +def queryFamilyActiveHeap : Heap (queryFamilyActive (R := R) source target N P F exponent H Q eM eF hP hM hF + tau a eta kappa delta T S passes copies request hindex hbelow) := + (queryFamilyRefinementHeap source target N P F exponent H Q eM eF hP hM hF tau a eta kappa delta + passes copies request.pass request.copy T S (request.index - T) (Nat.sub_pos_of_lt hindex) + request.node hbelow (Fin.ofNat R (request.index - T - 1)) request.state).mapKeysWithWork _ (fun _ => 1) (fun _ => le_rfl) + +end Active + +section Bounded +variable {α : Type*} [DecidableEq α] {M J R : ℕ} [NeZero M] [NeZero R] + (source target : List α) (N P F exponent H Q eM eF : ℕ) + (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) + (tau a eta kappa delta : BinaryFraction) (T S passes copies : ℕ) + (parent : {r : PhysicalTableRequest M J target.length // r.Bounded (passes + 1) copies T S}) + (hindex : T < parent.val.index) (hbelow : parent.val.node.1.val < J) + +def queryFamilyBoundedActiveHeap : Heap (queryFamilyBoundedActive (R := R) source target N P F exponent H Q eM eF + hP hM hF tau a eta kappa delta T S passes copies parent hindex hbelow) := + queryRestrictPhysicalBodyHeap (passes + 1) copies T S parent _ + (queryFamilyActiveHeap (R := R) source target N P F exponent H Q eM eF hP hM hF + tau a eta kappa delta T S passes copies parent.val hindex hbelow) + +end Bounded +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryFinishCost.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryFinishCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..b128394f2a427faca8c6cda90a257b2cc1d268e6 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryFinishCost.lean @@ -0,0 +1,80 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryRefinementFinish +import OAI.Combinatorics.EditApproximation.Binary.BinaryPreparedKernelWork +import OAI.Combinatorics.EditApproximation.Binary.BinaryContinuationReadCosts + +namespace OAI + +namespace EditApproximation.BinaryFraction + +private theorem continuationBudget_mono (M P nr ng no nr' ng' no' B : ℕ) + (hr : nr ≤ nr') (hg : ng ≤ ng') (ho : no ≤ no') : + physicalContinuationBitBudget M P nr ng no B ≤ physicalContinuationBitBudget M P nr' ng' no' B := by + unfold physicalContinuationBitBudget wideActionsBitBudget localContinuationBitBudget bellmanBitBudget + dsimp only + gcongr + +def queryRefinementFinishBitBudget (M P F B R G O : ℕ) : ℕ := + R + localRepresentativesBitBudget P F B * (R + 2) + + physicalContinuationBitBudget M P ((B + 1) * (64 * F * P + 2) ^ 2) G O (B + 4) * tableReadFactor R + 2 + +theorem queryRefinementFinishWithWork_bounds {nx ny M : ℕ} (parent : TargetInterval nx) + (N P F B R G O : ℕ) (a delta : BinaryFraction) + (initial : TargetInterval ny → BinaryFraction × ℕ) (t : ℕ) + (earlierKeys : List (Fin M × ℕ × TargetInterval ny)) (earlierWords : List BinaryFraction) + (groups online : List (BinaryBellmanAction (TargetInterval ny) (Fin M × TargetInterval ny) M)) + (currentKeys : List (Fin M × TargetInterval ny)) (currentWords : List BinaryFraction) + (q : TargetInterval ny) (hB : 10 ≤ B) (hP : 0 < P) (hFpos : 1 ≤ F) + (hN : Nat.size N ≤ B) (hnx : Nat.size nx ≤ B) (hny : Nat.size ny + 2 ≤ B) + (hM : Nat.size M ≤ B) (hPb : Nat.size P ≤ B) (hF : Nat.size F + 2 ≤ B) + (ha : a.width ≤ B) (hd : delta.width ≤ B) + (hi : ∀ r, (initial r).1.width ≤ B) (hR : ∀ r, (initial r).2 ≤ R) + (he : ∀ input, (queryHistoryReadWithWork earlierKeys earlierWords (t - 1) input).1.width ≤ B) + (heR : ∀ input, (queryHistoryReadWithWork earlierKeys earlierWords (t - 1) input).2 ≤ R) + (hc : ∀ i r, (queryChildReadWithWork currentKeys currentWords i r).1.width ≤ B) + (hcR : ∀ i r, (queryChildReadWithWork currentKeys currentWords i r).2 ≤ R) + (hgroups : ∀ action ∈ groups, action.connection.width ≤ connectionWordBudget M (B + 4)) + (honline : ∀ action ∈ online, action.connection.width ≤ connectionWordBudget M (B + 4)) + (hglen : groups.length ≤ G) (holen : online.length ≤ O) : + (queryRefinementFinishWithWork parent N P F a delta initial t earlierKeys earlierWords groups online + currentKeys currentWords q).1.width ≤ preparedKernelWordBudget M B ∧ + (queryRefinementFinishWithWork parent N P F a delta initial t earlierKeys earlierWords groups online + currentKeys currentWords q).2 ≤ queryRefinementFinishBitBudget M P F B R G O := by + let reps := localRepresentativeReadWithWork N P F a initial q + let old := queryHistoryReadWithWork earlierKeys earlierWords (t - 1) + let current := fun input : Fin M × TargetInterval ny => queryChildReadWithWork currentKeys currentWords input.1 input.2 + have hr := localRepresentativeReadWithWork_eq_cost N P F a initial q R hR + have hrCost := localRepresentativesWithWork_cost N P F B a (fun r => (initial r).1) q + (by omega) hN hF hFpos hPb hP (by omega) ha hi + have hrlen : reps.1.length ≤ (B + 1) * (64 * F * P + 2) ^ 2 := by + rw [show reps.1 = (localRepresentativesWithWork N P F a (fun r => (initial r).1) q).1 from hr.1] + exact localRepresentativesWithWork_length_le N P F B hP hFpos a (fun r => (initial r).1) q hN + have hrwidth : ∀ br ∈ reps.1, Nat.size br.1 ≤ B + 4 := by + intro br hbr + rw [show reps.1 = (localRepresentativesWithWork N P F a (fun r => (initial r).1) q).1 from hr.1] at hbr + exact (localRepresentativesWithWork_scale_bits N P F B hP a (fun r => (initial r).1) q hN br hbr).trans (by omega) + have htail := physicalContinuationWithWork_bounds parent reps.1 P F (B + 4) delta (initial q).1 + (fun input => (old input).1) (fun input => (current input).1) groups online q hP (by omega) + (by omega) (by omega) (by omega) (by omega) (by omega) hrwidth (hd.trans (by omega)) + ((hi q).trans (by omega)) (fun input => (he input).trans (by omega)) + (fun input => (hc input.1 input.2).trans (by omega)) hgroups honline + have htailValue := (physicalContinuationReadWithWork_eq_cost parent reps.1 P F delta (initial q).1 + old current groups online q R heR (fun input => hcR input.1 input.2)).1 + have htailRead := physicalContinuationReadWithWork_factor parent reps.1 P F delta (initial q).1 + old current groups online q R heR (fun input => hcR input.1 input.2) + have htailCost := htail.2.trans (continuationBudget_mono M P _ _ _ _ _ _ (B + 4) hrlen hglen holen) + have hrTotal : reps.2 ≤ localRepresentativesBitBudget P F B * (R + 2) := + hr.2.trans (Nat.mul_le_mul_right _ hrCost) + have htTotal := htailRead.trans (Nat.mul_le_mul_right (tableReadFactor R) htailCost) + constructor + · change (physicalContinuationReadWithWork parent reps.1 P F delta (initial q).1 old current groups online q).1.width ≤ _ + rw [htailValue] + exact htail.1 + · change (initial q).2 + reps.2 + + (physicalContinuationReadWithWork parent reps.1 P F delta (initial q).1 old current groups online q).2 + 2 ≤ _ + have hq := hR q + unfold queryRefinementFinishBitBudget + omega + +end EditApproximation.BinaryFraction + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryGapStateCost.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryGapStateCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..bbf03f549fcc1a768d2d6081414a7f18ed209526 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryGapStateCost.lean @@ -0,0 +1,152 @@ +import OAI.Combinatorics.EditApproximation.Queries.QuerySharedGeometry +import OAI.Combinatorics.EditApproximation.Queries.QueryHistoryBounds + +namespace OAI + +namespace EditApproximation + +theorem gridPointsBetween_radius_count (g p radius : ℕ) (hg : 0 < g) : + (gridPointsBetween g (p - radius) (p + radius)).length ≤ 2 * radius / g + 2 := + (gridPointsBetween_length_le g _ _ hg).trans + (Nat.add_le_add_right (Nat.div_le_div_right (by omega : p + radius - (p - radius) ≤ 2 * radius)) 2) + +def queryGapStatesBitBudget (left right B : ℕ) : ℕ := + let C := 1000 * (B + 10) ^ 2 + C + gridPointsBitBudget left (B + 2) + + left * (C + gridPointsBitBudget right (B + 6) + right * (16 * (B + 6) + 11) + right + 7) + 3 + +private theorem queryGapStates_arithmetic_bound (B u v w : ℕ) + (hu : u ≤ 26 * (B + 4) + 4) (hv : v ≤ 26 * (B + 4) + 4) + (hw : w ≤ 26 * (B + 4) + 4) : + u + v + w ≤ 1000 * (B + 10) ^ 2 := by + nlinarith only [hu, hv, hw, Nat.zero_le B] + +theorem queryGapStatesWithWork_bounds (n g anchor radius sourceLength gapRadius left right B : ℕ) + (hg : 0 < g) (hn : Nat.size n ≤ B) (hgs : Nat.size g ≤ B) + (ha : Nat.size anchor ≤ B) (hr : Nat.size radius ≤ B) + (hl : Nat.size sourceLength ≤ B) (hgap : Nat.size gapRadius ≤ B) + (hleft : 2 * radius / g + 2 ≤ left) (hright : 2 * gapRadius / g + 2 ≤ right) : + (queryGapStatesWithWork n g anchor radius sourceLength gapRadius).1.length ≤ left * right ∧ + (queryGapStatesWithWork n g anchor radius sourceLength gapRadius).2 ≤ + queryGapStatesBitBudget left right B := by + let lo := saturatingSubtractWithWork anchor radius + let hi := binaryNaturalAddWithWork anchor radius + let firsts := gridPointsWithWork g (bitWordValue lo.1) (bitWordValue hi.1) + let run := fun first => + let center := binaryNaturalAddWithWork first sourceLength + let lower := saturatingSubtractWithWork (bitWordValue center.1) gapRadius + let upper := binaryNaturalAddWithWork (bitWordValue center.1) gapRadius + let last := gridPointsWithWork g (bitWordValue lower.1) (bitWordValue upper.1) + let valid := filterMapWithWork (makeStateWithWork n first) last.1 + (valid.1, center.2 + lower.2 + upper.2 + last.2 + valid.2 + 4) + let C := 1000 * (B + 10) ^ 2 + have hv : firsts.1 = gridPointsBetween g (anchor - radius) (anchor + radius) := by + simp only [firsts, gridPointsWithWork_value _ _ _ hg, lo, hi, + saturatingSubtractWithWork_value, binaryNaturalAddWithWork_value] + have hflen : firsts.1.length ≤ left := by rw [hv]; exact (gridPointsBetween_radius_count g anchor radius hg).trans hleft + have hlow : Nat.size (bitWordValue lo.1) ≤ B := by + rw [saturatingSubtractWithWork_value] + exact (Nat.size_le_size (Nat.sub_le _ _)).trans ha + have hhigh : Nat.size (bitWordValue hi.1) ≤ B + 2 := by + rw [binaryNaturalAddWithWork_value] + exact (binaryNaturalAdd_size_le anchor radius).trans (by omega) + have hfc := gridPointsWithWork_cost g (bitWordValue lo.1) (bitWordValue hi.1) (B + 2) hg + (by omega) (by omega) hhigh + rw [← gridPointsWithWork_value g (bitWordValue lo.1) (bitWordValue hi.1) hg] at hfc + have hfc' : firsts.2 ≤ gridPointsBitBudget left (B + 2) := hfc.trans (by + unfold gridPointsBitBudget + gcongr) + have hfirst (first : ℕ) (hf : first ∈ firsts.1) : Nat.size first ≤ B + 2 := by + rw [hv] at hf + exact (Nat.size_le_size (gridPointsBetween_sound hg hf).2.1).trans + ((binaryNaturalAdd_size_le anchor radius).trans (by omega)) + have hrun (first : ℕ) (hf : first ∈ firsts.1) : + (run first).1.length ≤ right ∧ + (run first).2 ≤ C + gridPointsBitBudget right (B + 6) + right * (16 * (B + 6) + 11) + 4 := by + let center := binaryNaturalAddWithWork first sourceLength + let lower := saturatingSubtractWithWork (bitWordValue center.1) gapRadius + let upper := binaryNaturalAddWithWork (bitWordValue center.1) gapRadius + let last := gridPointsWithWork g (bitWordValue lower.1) (bitWordValue upper.1) + have hsfirst := hfirst first hf + have hcenter : Nat.size (bitWordValue center.1) ≤ B + 4 := by + rw [binaryNaturalAddWithWork_value] + exact (binaryNaturalAdd_size_le first sourceLength).trans (by omega) + have hslow : Nat.size (bitWordValue lower.1) ≤ B + 4 := by + rw [saturatingSubtractWithWork_value] + exact (Nat.size_le_size (Nat.sub_le _ _)).trans hcenter + have hsup : Nat.size (bitWordValue upper.1) ≤ B + 6 := by + rw [binaryNaturalAddWithWork_value] + exact (binaryNaturalAdd_size_le (bitWordValue center.1) gapRadius).trans (by omega) + have hlv : last.1 = gridPointsBetween g (bitWordValue center.1 - gapRadius) + (bitWordValue center.1 + gapRadius) := by + simp only [last, gridPointsWithWork_value _ _ _ hg, lower, upper, + saturatingSubtractWithWork_value, binaryNaturalAddWithWork_value] + have hllen : last.1.length ≤ right := by + rw [hlv] + exact (gridPointsBetween_radius_count g (bitWordValue center.1) gapRadius hg).trans hright + have hlastCost := gridPointsWithWork_cost g (bitWordValue lower.1) + (bitWordValue upper.1) (B + 6) hg (by omega) (by omega) hsup + rw [← gridPointsWithWork_value g (bitWordValue lower.1) (bitWordValue upper.1) hg] at hlastCost + have hlast : last.2 ≤ gridPointsBitBudget right (B + 6) := by + have hmono : gridPointsBitBudget last.1.length (B + 6) ≤ gridPointsBitBudget right (B + 6) := by + unfold gridPointsBitBudget + gcongr + have hcost : last.2 ≤ gridPointsBitBudget last.1.length (B + 6) := by + simpa only [last] using hlastCost + exact hcost.trans hmono + have hvalid := (filterMapWithWork_cost (makeStateWithWork n first) last.1 + (16 * (B + 6) + 8) (fun second hsecond => + makeStateWithWork_cost n first second (B + 6) (by omega) (by omega) (by + rw [hlv] at hsecond + exact (Nat.size_le_size (gridPointsBetween_sound hg hsecond).2.1).trans (by + simpa only [upper, binaryNaturalAddWithWork_value] using hsup)))).trans + (Nat.mul_le_mul_right _ hllen) + have hcc : center.2 ≤ 9 * (Nat.size first + Nat.size sourceLength) + 1 := by + simpa only [center] using binaryNaturalAddWithWork_cost first sourceLength + have hlc : lower.2 ≤ 13 * (Nat.size (bitWordValue center.1) + Nat.size gapRadius) + 4 := by + simpa only [lower] using saturatingSubtractWithWork_cost (bitWordValue center.1) gapRadius + have huc : upper.2 ≤ 9 * (Nat.size (bitWordValue center.1) + Nat.size gapRadius) + 1 := by + simpa only [upper] using binaryNaturalAddWithWork_cost (bitWordValue center.1) gapRadius + have harith : center.2 + lower.2 + upper.2 ≤ C := by + exact queryGapStates_arithmetic_bound B center.2 lower.2 upper.2 + (hcc.trans (by omega)) (hlc.trans (by omega)) (huc.trans (by omega)) + constructor + · have hlen : (filterMapWithWork (makeStateWithWork n first) last.1).1.length ≤ right := by + rw [filterMapWithWork_value] + exact (List.length_filterMap_le _ _).trans hllen + simpa only [run, center, lower, upper, last] using hlen + · have hcost : center.2 + lower.2 + upper.2 + last.2 + + (filterMapWithWork (makeStateWithWork n first) last.1).2 + 4 ≤ + C + gridPointsBitBudget right (B + 6) + right * (16 * (B + 6) + 11) + 4 := by + simp only [Nat.add_assoc, Nat.reduceAdd] at hvalid + omega + simpa only [run, center, lower, upper, last] using hcost + have hflat := (arithmeticFlatMapWithWork_cost run firsts.1 + (C + gridPointsBitBudget right (B + 6) + right * (16 * (B + 6) + 11) + 4) right + (fun first hf => (hrun first hf).2) (fun first hf => (hrun first hf).1)).trans + (Nat.mul_le_mul_right _ hflen) + have hlc : lo.2 ≤ 13 * (Nat.size anchor + Nat.size radius) + 4 := by + simpa only [lo] using saturatingSubtractWithWork_cost anchor radius + have huc : hi.2 ≤ 9 * (Nat.size anchor + Nat.size radius) + 1 := by + simpa only [hi] using binaryNaturalAddWithWork_cost anchor radius + have hsetup : lo.2 + hi.2 ≤ C := by + have h := queryGapStates_arithmetic_bound B lo.2 hi.2 0 + (hlc.trans (by omega)) (huc.trans (by omega)) (by omega) + simpa only [Nat.add_zero] using h + constructor + · have hlen := (arithmeticFlatMapWithWork_length run firsts.1 right + (fun first hf => (hrun first hf).1)).trans (Nat.mul_le_mul_right _ hflen) + simpa only [queryGapStatesWithWork, lo, hi, firsts, run] using hlen + · have hcost : lo.2 + hi.2 + firsts.2 + (arithmeticFlatMapWithWork run firsts.1).2 + 3 ≤ + queryGapStatesBitBudget left right B := by + unfold queryGapStatesBitBudget + change _ ≤ C + gridPointsBitBudget left (B + 2) + + left * (C + gridPointsBitBudget right (B + 6) + right * (16 * (B + 6) + 11) + right + 7) + 3 + rw [show C + gridPointsBitBudget right (B + 6) + right * (16 * (B + 6) + 11) + 4 + right + 3 = + C + gridPointsBitBudget right (B + 6) + right * (16 * (B + 6) + 11) + right + 7 by omega] at hflat + omega + simpa only [queryGapStatesWithWork, lo, hi, firsts, run] using hcost + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryGatherPolynomial.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryGatherPolynomial.lean new file mode 100644 index 0000000000000000000000000000000000000000..784ce22945f94fe2ec4f145bec2c26ab01f1c561 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryGatherPolynomial.lean @@ -0,0 +1,373 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryLocalProgramCost +import OAI.Combinatorics.EditApproximation.Geometry.PreparedKernelPolynomial + +namespace OAI + +/-! A finite polynomial certificate for the complete adaptive gather cost. +The four kernel bounds and the two Cartesian counts +are explicit inputs. Every remaining operation is addition, multiplication, +fixed natural power, or bit length. -/ + +namespace EditApproximation + +private abbrev GP := FiniteBitPolynomial (Fin 16) + +private def gp_localEligibilityBitBudget (B : GP) : GP := + 4000 * (B + 1) ^ 2 + 2100 * (4 * B + 4) ^ 2 + 2000 * (4 * B + 3) ^ 2 + + 2 * (1000 * (16 * B + 13) ^ 2 + 1) + 2 * B + 8 + +private def gp_queryExponentsBitBudget (B : GP) : GP := + (B + 1) * (gp_localEligibilityBitBudget (B + 4) + B + 5) + 2 * B + 3 + +private def gp_queryScalesBitBudget (B : GP) : GP := + gp_queryExponentsBitBudget B + (B + 1) * (B + 6) + 1 + +private def gp_gridPointsBitBudget (n B : GP) : GP := + 1000 * (B + 2) ^ 2 + n * (100 * (B + 3) ^ 2 + 5) + +private def gp_gridStateBoxBitBudget (count B : GP) : GP := + 96 * (B + 1) + 2 * gp_gridPointsBitBudget count (B + 2) + + count * (count * (16 * (B + 2) + 11) + count + 3) + 6 + +private def gp_queryGridPointsBitBudget (P K B : GP) : GP := + 100 * (B + 2) ^ 2 + gp_gridStateBoxBitBudget (4 * K * P + 2) (B + 1) + 1 + +private def gp_queryRawCentersBitBudget (P F B : GP) : GP := + let L := (64 * F * P + 2) ^ 2 + let count := (B + 1) * L + gp_queryScalesBitBudget B + 500 * (B + 1) ^ 2 + + (B + 1) * (gp_queryGridPointsBitBudget P (16 * F) (B + 2) + L + 3) + + (count + 1) ^ 2 * (16 * B + 9) + 3 + +private def gp_cellCoordinateSetupBitBudget (B : GP) : GP := + 100 * (B + 1) + 4200 * (B + 6) ^ 2 + 400 * (4 * B + 21) ^ 2 + 100 * (4 * B + 25) + +private def gp_targetCellsBitBudget (left right B : GP) : GP := + 2 * gp_cellCoordinateSetupBitBudget B + left + right + left * (5 * right + 3) + 2 + +private def gp_queryCellScanBitBudget (aux : Fin 7 → GP) (F _exponent B : GP) : GP := + let K := (32 * F + 2) * (aux 0) + 2 + 2000 * (B + 4) ^ 2 + gp_targetCellsBitBudget K K (4 * B + 40) + +private def gp_queryGroupKeysBitBudget (aux : Fin 7 → GP) (F exponent B : GP) : GP := + let L := ((32 * F + 2) * (aux 0) + 2) ^ 2 + gp_queryScalesBitBudget B + 500 * (B + 1) ^ 2 + + (B + 1) * ((gp_queryCellScanBitBudget aux) F exponent B + 5 * L + 5) + exponent + 4 + +private def gp_cellGridSetupBitBudget (B : GP) : GP := + 2000000 * (B + 100) ^ 2 + +private def gp_cellGridPointBitBudget (B : GP) : GP := + 1000 * (B + 100) ^ 2 + +private def gp_cellGridPointsBitBudget (count B : GP) : GP := + gp_cellGridSetupBitBudget B + count * (gp_cellGridPointBitBudget B + 5) + +private def gp_cellStatesBitBudget (left right B : GP) : GP := + gp_cellGridPointsBitBudget left B + gp_cellGridPointsBitBudget right B + + left * (right * (16 * (17 * B + 78) + 11) + right + 3) + 2 + +private def gp_queryCellStatesBitBudget (P exponent B : GP) : GP := + 100 * (B + 5) ^ 2 + 2000 * (B + 4) ^ 2 + + gp_cellStatesBitBudget P P (16 * B + 200) + exponent + 3 + +private def gp_queryOnlineKeysBitBudget (B : GP) : GP := + gp_queryScalesBitBudget B + (B + 1) * (600 * (B + 3) ^ 2 + 6) + 1 + +private def gp_queryInitialSupportBitBudget (aux : Fin 7 → GP) (P F exponent B : GP) : GP := + let raw := (B + 1) * (64 * F * P + 2) ^ 2 + let groups := (B + 1) * ((32 * F + 2) * (aux 0) + 2) ^ 2 + gp_queryRawCentersBitBudget P F B + (gp_queryGroupKeysBitBudget aux) F exponent B + + groups * (gp_queryCellStatesBitBudget P exponent B + P ^ 2 + 3) + + gp_queryOnlineKeysBitBudget B + 4 * (B + 1) + 2 * raw + groups * P ^ 2 + 5 + +private def gp_queryInitialSupportLength (aux : Fin 7 → GP) (P F _exponent B : GP) : GP := + let raw := (B + 1) * (64 * F * P + 2) ^ 2 + let groups := (B + 1) * ((32 * F + 2) * (aux 0) + 2) ^ 2 + 1 + raw + groups * P ^ 2 + (B + 1) + +private def gp_queryInitialGatherBitBudget (aux : Fin 7 → GP) (P F exponent B R K : GP) : GP := + R + (gp_queryInitialSupportBitBudget aux) P F exponent B + (gp_queryInitialSupportLength aux) P F exponent B * (R + 3) + K + +private def gp_localRepresentativeScaleBitBudget (P F B : GP) : GP := + let C := B + 4 + let L := 64 * F * P + 2 + 100 * (C + 2) ^ 2 + gp_gridStateBoxBitBudget L C + + L ^ 2 * (gp_localEligibilityBitBudget C + 3) + L ^ 2 * 4 + B + 6 + +private def gp_localRepresentativesBitBudget (P F B : GP) : GP := + gp_queryExponentsBitBudget B + 500 * (B + 1) ^ 2 + + (B + 1) * (gp_localRepresentativeScaleBitBudget P F B + (64 * F * P + 2) ^ 2 + 3) + 3 + +private def gp_cellCentersBitBudget (left right B : GP) : GP := + 100 * (B + 2) ^ 2 + 2000 * (B + 1) ^ 2 + + gp_cellStatesBitBudget left right (4 * B + 40) + + left * right * (gp_localEligibilityBitBudget B + 3) + 3 + +private def gp_queryEarlierRepresentativesBitBudget (aux : Fin 7 → GP) (P F exponent B R : GP) : GP := + let groups := (B + 1) * ((32 * F + 2) * (aux 0) + 2) ^ 2 + let L := (P + 1) ^ 2 + R + gp_localRepresentativesBitBudget P F B * (R + 2) + (gp_queryGroupKeysBitBudget aux) F exponent B + + groups * (gp_cellCentersBitBudget P P (16 * B + 200) * (R + 1) + 5 * L + 4) + + gp_queryOnlineKeysBitBudget B + 2 * ((B + 1) * (64 * F * P + 2) ^ 2) + groups * L + 4 + +private def gp_wideChildGridBitBudget (P B : GP) : GP := + 10000 * (B + 12) ^ 2 + gp_gridStateBoxBitBudget (40 * P + 2) (B + 12) + +private def gp_queryWideInputsBitBudget (M P count B : GP) : GP := + let G := (40 * P + 2) ^ 2 + let C := gp_wideChildGridBitBudget P (B + 1) + count * (M * (C + 4 * G + 1 + G + 3) + M * G + 3) + + (count * (M * G) + 1) ^ 2 * (24 * B + 12) + M + 2 + +private def gp_queryEarlierRepresentativesLength (aux : Fin 7 → GP) (P F _exponent B : GP) : GP := + (B + 1) * ((64 * F * P + 2) ^ 2 + + ((32 * F + 2) * (aux 0) + 2) ^ 2 * (P + 1) ^ 2 + 1) + +private def gp_queryBandInputsBitBudget (aux : Fin 7 → GP) (M P F exponent B R : GP) : GP := + (gp_queryEarlierRepresentativesBitBudget aux) P F exponent B R + + gp_queryWideInputsBitBudget M P ((gp_queryEarlierRepresentativesLength aux) P F exponent B) B + 1 + +private def gp_queryBandGatherBitBudget (aux : Fin 7 → GP) (M P F exponent B Rp W K : GP) : GP := + (gp_queryBandInputsBitBudget aux) M P F exponent B Rp + + 2 * ((gp_queryEarlierRepresentativesLength aux) P F exponent B * (M * (40 * P + 2) ^ 2) * (W + 3)) + K + +private def gp_groupScalesBitBudget (eM eb eF : GP) : GP := + (7 + eM + eF) * (eM + eb + eF + 13) + + FiniteBitPolynomial.bitLength eM + FiniteBitPolynomial.bitLength eb + FiniteBitPolynomial.bitLength eF + 8 + +private def gp_groupSampleCountBitBudget (B : GP) : GP := + 2000 * (B + 1) ^ 2 + 2000 * (4 * B + 3) ^ 2 + + 2100 * (16 * B + 12) ^ 2 + 500 * (64 * B + 45) ^ 2 + + 4 * (65 * B + 46) + 3 * B + 8 + +private def gp_queryGroupSamplesBitBudget (M eM eb eF B : GP) : GP := + let L := 7 + eM + eF + gp_groupScalesBitBudget eM eb eF + 4 * L + + L * (L + gp_groupSampleCountBitBudget B + 7 * M + 6) + eb + 4 + +private def gp_queryGroupSourceKeysBitBudget (aux : Fin 7 → GP) (M F exponent eM eF B : GP) : GP := + let cells := ((32 * F + 2) * (aux 0) + 2) ^ 2 + let samples := (7 + eM + eF) * M + let sampleWork := gp_queryGroupSamplesBitBudget M eM B eF (2 * B + 10) + let scaleWork := (gp_queryCellScanBitBudget aux) F exponent B + + cells * (sampleWork + samples + 3) + B + exponent + 4 + gp_queryExponentsBitBudget B + 500 * (B + 1) ^ 2 + + (B + 1) * (scaleWork + cells * samples + 3) + 2 + +private def gp_queryGroupSourceKeysLength (aux : Fin 7 → GP) (M F _exponent eM eF B : GP) : GP := + (B + 1) * ((((32 * F + 2) * (aux 0) + 2) ^ 2) * ((7 + eM + eF) * M)) + +private def gp_queryGroupGatherBitBudget (aux : Fin 7 → GP) (M F exponent eM eF B Rp W K : GP) : GP := + Rp + (gp_queryGroupSourceKeysBitBudget aux) M F exponent eM eF B + + (gp_queryGroupSourceKeysLength aux) M F exponent eM eF B * (W + 3) + K + +private def gp_wideMaterializationBitBudget (aux : Fin 7 → GP) (M P B : GP) : GP := + M * (gp_wideChildGridBitBudget P B + 6) + + (M + 1) * (6 * M + 10) * (aux 2) + 1 + +private def gp_tableReadFactor (R : GP) : GP := + 4 * (R + 4) + +private def gp_bandCoordinatesBitBudget (M vertices B : GP) : GP := + vertices * (5 * M + 3) + (vertices * M + 1) ^ 2 * (24 * B + 12) + 1 + +private def gp_bitPowerBitBudget (n B : GP) : GP := + 1 + n * (200 * ((n + 1) * (B + 1) + 1) ^ 2) + +private def gp_onlineIndexBitBudget (M vertices B : GP) : GP := + gp_bandCoordinatesBitBudget M vertices B + 40 * (B + 4) + + gp_bitPowerBitBudget 80 (B + 4) + 3 + +private def gp_queryOnlineRangeBitBudget (aux : Fin 7 → GP) (M P B R : GP) : GP := + let V := (aux 1) + 26 * B + 4 + + ((gp_wideMaterializationBitBudget aux) M P B + (aux 6) + V + 1) * + gp_tableReadFactor R + gp_onlineIndexBitBudget M V B + gp_bitPowerBitBudget 80 (B + 4) + + 10000 * (80 * (B + 4) + 4) ^ 2 + 4 + +private def gp_queryOnlineGatherBitBudget (aux : Fin 7 → GP) (M P B Rp R W K : GP) : GP := + Rp + gp_queryOnlineKeysBitBudget B + + (B + 1) * ((gp_queryOnlineRangeBitBudget aux) M P (B + 1) R + W + 3) + K + +private def gp_queryHistoryInputsLength (M P history count : GP) : GP := + count * (M * (history * (40 * P + 2) ^ 2)) + +private def gp_queryGroupInputsLength (aux : Fin 7 → GP) (M _exponent : GP) : GP := + M * ((24 * (aux 0) * M + 2) * (4 * (aux 0) + 4)) + +private def gp_querySharedCellInputsLength (aux : Fin 7 → GP) (M exponent eM eF : GP) : GP := + (7 + eM + eF) * (gp_queryGroupInputsLength aux) M exponent + +private def gp_querySharedInputsLength (aux : Fin 7 → GP) (M F exponent eM eF B : GP) : GP := + (B + 1) * ((((32 * F + 2) * (aux 0) + 2) ^ 2) * (gp_querySharedCellInputsLength aux) M exponent eM eF) + +private def gp_queryRefinementReadBudget (B Rp R earlier shared : GP) : GP := + R + Rp + (1 + earlier * (32 * B + 12)) + (1 + shared * (24 * B + 9)) + +private def gp_queryNeededInputsBitBudget (actions M B : GP) : GP := + actions * (5 * M + 3) + 2 * M + actions * M + + (actions * M + 1) ^ 2 * (202000 * (B + 1) ^ 2) + 4 + +private def gp_queryRefinementStagesBudget (M B readCost earlierLength earlierCost onlineLength onlineCost sharedLength sharedCost groupLength groupCost parentCost finishCost : GP) : GP := + earlierCost + earlierLength * (readCost + 3) + onlineCost + parentCost + sharedCost + + sharedLength * (readCost + 3) + groupCost + + gp_queryNeededInputsBitBudget (groupLength + onlineLength) M B + + (groupLength + onlineLength) * M * (readCost + 3) + finishCost + +private def gp_queryRawHistoryInputsBitBudget (M P history count B : GP) : GP := + let G := (40 * P + 2) ^ 2 + let C := gp_wideChildGridBitBudget P (B + 1) + count * (M * (C + history * (5 * G + 3) + history + 2 + history * G + 3) + + M * (history * G) + 3) + M + 1 + +private def gp_queryEarlierInputsBitBudget (aux : Fin 7 → GP) (M P F exponent history B R : GP) : GP := + let count := (gp_queryEarlierRepresentativesLength aux) P F exponent B + (gp_queryEarlierRepresentativesBitBudget aux) P F exponent B R + + gp_queryRawHistoryInputsBitBudget M P history count B + + (gp_queryHistoryInputsLength M P history count + 1) ^ 2 * (2002000 * (B + 1) ^ 2) + 2 + +private def gp_groupSampleCountWordBudget (B : GP) : GP := + 64 * B + 46 + +private def gp_queryGroupLabelsBitBudget (M B R : GP) : GP := + gp_groupSampleCountBitBudget B + 8 * (gp_groupSampleCountWordBudget B) + + M * (R + 4) + 4 + +private def gp_queryGapStatesBitBudget (left right B : GP) : GP := + let C := 1000 * (B + 10) ^ 2 + C + gp_gridPointsBitBudget left (B + 2) + + left * (C + gp_gridPointsBitBudget right (B + 6) + right * (16 * (B + 6) + 11) + right + 7) + 3 + +private def gp_queryRoundedStatesBitBudget (left right exponent B : GP) : GP := + 100000 * (32 * B + 210) ^ 2 + gp_queryGapStatesBitBudget left right (32 * B + 200) + exponent + 12 + +private def gp_queryGroupInputsBitBudget (aux : Fin 7 → GP) (M exponent B R : GP) : GP := + let L := (24 * (aux 0) * M + 2) * (4 * (aux 0) + 4) + gp_queryGroupLabelsBitBudget M B R + + M * (gp_queryRoundedStatesBitBudget (24 * (aux 0) * M + 2) (4 * (aux 0) + 4) exponent B + + 5 * L + 4) + 1 + +private def gp_querySharedCellInputsBitBudget (aux : Fin 7 → GP) (M exponent eM eb eF B R : GP) : GP := + let L := 7 + eM + eF + gp_groupScalesBitBudget eM eb eF + 4 * L + + L * ((gp_queryGroupInputsBitBudget aux) M exponent B R + L + (gp_queryGroupInputsLength aux) M exponent + 4) + eb + 4 + +private def gp_querySharedInputsBitBudget (aux : Fin 7 → GP) (M F exponent eM eF B R : GP) : GP := + let cells := ((32 * F + 2) * (aux 0) + 2) ^ 2 + let samples := (gp_querySharedCellInputsLength aux) M exponent eM eF + let sampleWork := (gp_querySharedCellInputsBitBudget aux) M exponent eM B eF (16 * B + 200) R + let scaleWork := (gp_queryCellScanBitBudget aux) F exponent B + + cells * (sampleWork + samples + 3) + B + exponent + 4 + gp_queryExponentsBitBudget B + 500 * (B + 1) ^ 2 + (B + 1) * (scaleWork + cells * samples + 3) + + ((gp_querySharedInputsLength aux) M F exponent eM eF B + 1) ^ 2 * (202000 * (B + 1) ^ 2) + 3 + +private def gp_queryRefinementFinishBitBudget (aux : Fin 7 → GP) (_M P F B R _G _O : GP) : GP := + R + gp_localRepresentativesBitBudget P F B * (R + 2) + + (aux 5) * gp_tableReadFactor R + 2 + +private def gp_queryFinishReadBudget (M B Rp earlierCount groups online : GP) : GP := + Rp + 2 + earlierCount * (32 * B + 12) + (groups + online) * M * (24 * B + 9) + +private def gp_queryLocalRefinementBitBudget (aux : Fin 7 → GP) (M _N P F exponent eM eF B _S t Rp R W Dg Do : GP) : GP := + let earlier := gp_queryHistoryInputsLength M P t ((gp_queryEarlierRepresentativesLength aux) P F exponent B) + let shared := (gp_querySharedInputsLength aux) M F exponent eM eF B + let groups := (B + 1) * ((32 * F + 2) * (aux 0) + 2) ^ 2 + let U := gp_queryRefinementReadBudget B Rp R earlier shared + gp_queryRefinementStagesBudget M B W earlier ((gp_queryEarlierInputsBitBudget aux) M P F exponent t B Rp) + (B + 1) ((aux 4) * gp_tableReadFactor U * (Do + 4)) + shared ((gp_querySharedInputsBitBudget aux) M F exponent eM eF B Dg) + groups ((aux 3) * gp_tableReadFactor U * (Dg + 4)) Rp + ((gp_queryRefinementFinishBitBudget aux) M P F B (gp_queryFinishReadBudget M B Rp earlier groups (B + 1)) groups (B + 1)) + +private def gp_queryGroupBufferReadBudget (count B V : GP) : GP := + count * (40 * (40 * B + 500) + 15) + 200 * (V + 1) ^ 2 + + 30 * (V + 1) * (V + (40 * B + 500) + 1) + 4 + +private def gp_queryBufferedGroupReadBudget (aux : Fin 7 → GP) (M F exponent eM eF B V : GP) : GP := + gp_queryGroupBufferReadBudget ((gp_queryGroupSourceKeysLength aux) M F exponent eM eF B) B V + +private def gp_queryOnlineBufferReadBudget (count B V : GP) : GP := + count * (24 * (B + 1) + 9) + 200 * (V + 1) ^ 2 + 2 + +private def gp_queryLocalSourcesBitBudget (aux : Fin 7 → GP) (M N P F exponent eM eF B S t Rp R W : GP) : GP := + (gp_queryGroupGatherBitBudget aux) M F exponent eM eF B Rp W + ((gp_queryOnlineGatherBitBudget aux) M P B Rp R W + ((gp_queryLocalRefinementBitBudget aux) M N P F exponent eM eF B S t Rp R W + ((gp_queryBufferedGroupReadBudget aux) M F exponent eM eF B B) + (gp_queryOnlineBufferReadBudget (B + 1) B B))) + +private def gp_queryBandReadBudget (aux : Fin 7 → GP) (M P F exponent B : GP) : GP := + 1 + (gp_queryEarlierRepresentativesLength aux) P F exponent B * (M * (40 * P + 2) ^ 2) * (24 * B + 9) + +private def gp_queryLocalBandBitBudget (aux : Fin 7 → GP) (M N P F exponent eM eF B S t Rp W : GP) : GP := + (gp_queryBandGatherBitBudget aux) M P F exponent B Rp W + ((gp_queryLocalSourcesBitBudget aux) M N P F exponent eM eF B S t Rp + ((gp_queryBandReadBudget aux) M P F exponent B) W) + +private def gp_queryParentBufferReadBudget (aux : Fin 7 → GP) (P F exponent B : GP) : GP := + 1 + (gp_queryInitialSupportLength aux) P F exponent B * (16 * B + 6) + +private def gp_queryLocalProgramBitBudget (aux : Fin 7 → GP) (M N P F exponent eM eF B S t W : GP) : GP := + (gp_queryInitialGatherBitBudget aux) P F exponent B W + ((gp_queryLocalBandBitBudget aux) M N P F exponent eM eF B S t + ((gp_queryParentBufferReadBudget aux) P F exponent B) W) + +private def queryGatherPolynomial : GP := + let aux : Fin 7 → GP := ![.input 9, .input 10, .input 11, .input 12, .input 13, .input 14, .input 15] + gp_queryLocalProgramBitBudget aux (.input 0) 0 (.input 1) (.input 2) (.input 3) + (.input 4) (.input 5) (.input 6) 0 (.input 7) (.input 8) + +def queryGatherBitDegree : ℕ := queryGatherPolynomial.degree + +private def queryGatherEnvironment (M N P F exponent eM eF B S t W : ℕ) : Fin 16 → ℕ := + ![M, P, F, exponent, eM, eF, B, t, W, 2 ^ exponent, + (40 * P + 2) ^ (2 * M), ((40 * P + 2) ^ 2 + 1) ^ (M + 1), + BinaryFraction.preparedLocalGroupsBitBudget N M P F exponent eM eF B, + BinaryFraction.preparedLocalOnlineBitBudget M P B S, + BinaryFraction.physicalContinuationBitBudget M P ((B + 1) * (64 * F * P + 2) ^ 2) + ((B + 1) * ((32 * F + 2) * 2 ^ exponent + 2) ^ 2) (B + 1) (B + 4), + BinaryFraction.representativeCompleteBitBudget M ((40 * P + 2) ^ (2 * M)) (4 * (B + 1) + 20)] + +private theorem queryGatherPolynomial_eval (M N P F exponent eM eF B S t W : ℕ) : + queryGatherPolynomial.eval (queryGatherEnvironment M N P F exponent eM eF B S t W) = + BinaryFraction.queryLocalProgramBitBudget M N P F exponent eM eF B S t W := by + rfl + +theorem queryLocalProgramBitBudget_fixedPower (M N P F exponent eM eF B S t W X : ℕ) + (hX : 2 ≤ X) (hM : M ≤ X) (hP : P ≤ X) (hF : F ≤ X) (he : exponent ≤ X) + (heM : eM ≤ X) (heF : eF ≤ X) (hB : B ≤ X) (ht : t ≤ X) (hW : W ≤ X) + (hTheta : 2 ^ exponent ≤ X) (hV : (40 * P + 2) ^ (2 * M) ≤ X) + (hCart : ((40 * P + 2) ^ 2 + 1) ^ (M + 1) ≤ X) + (hGroups : BinaryFraction.preparedLocalGroupsBitBudget N M P F exponent eM eF B ≤ X) + (hOnline : BinaryFraction.preparedLocalOnlineBitBudget M P B S ≤ X) + (hFinish : BinaryFraction.physicalContinuationBitBudget M P ((B + 1) * (64 * F * P + 2) ^ 2) + ((B + 1) * ((32 * F + 2) * 2 ^ exponent + 2) ^ 2) (B + 1) (B + 4) ≤ X) + (hRange : BinaryFraction.representativeCompleteBitBudget M ((40 * P + 2) ^ (2 * M)) + (4 * (B + 1) + 20) ≤ X) : + BinaryFraction.queryLocalProgramBitBudget M N P F exponent eM eF B S t W ≤ X ^ queryGatherBitDegree := by + have henv : ∀ i, queryGatherEnvironment M N P F exponent eM eF B S t W i ≤ X := by + intro i + fin_cases i + · exact hM + · exact hP + · exact hF + · exact he + · exact heM + · exact heF + · exact hB + · exact ht + · exact hW + · exact hTheta + · exact hV + · exact hCart + · exact hGroups + · exact hOnline + · exact hFinish + · exact hRange + simpa only [queryGatherPolynomial_eval, queryGatherBitDegree] using + queryGatherPolynomial.eval_le_pow (queryGatherEnvironment M N P F exponent eM eF B S t W) X hX henv + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryGatherSpace.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryGatherSpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..08acd1c981567b2a6e365543ab0b11a736442af1 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryGatherSpace.lean @@ -0,0 +1,121 @@ +import OAI.Combinatorics.EditApproximation.Binary.BitQuerySpace +import OAI.Combinatorics.EditApproximation.Queries.QueryInitialSupportSpace +import OAI.Combinatorics.EditApproximation.Queries.QueryHistorySpace +import OAI.Combinatorics.EditApproximation.Queries.QueryGroupSourceSpace +import OAI.Combinatorics.EditApproximation.Queries.QueryOnlineRangeSpace +import OAI.Combinatorics.EditApproximation.Queries.QueryBandGather +import OAI.Combinatorics.EditApproximation.Queries.QueryLocalBuffers +import OAI.Combinatorics.EditApproximation.Queries.QueryWarmupBuffers +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation +namespace BinaryFraction + + + +theorem queryParentReadAllocation_le_work {n : ℕ} (keys : List (TargetInterval n)) + (words : List BinaryFraction) (r : TargetInterval n) : + queryParentReadAllocation keys words r ≤ (queryParentReadWithWork keys words r).2 := + gatheredLookupAllocation_le_work _ _ _ _ _ (fun k _ => queryIntervalEqualAllocation_le_work r k) + + + +theorem queryBandInputsAllocation_le_work {nx ny : ℕ} (M : ℕ) (parent : TargetInterval nx) + (N P F exponent : ℕ) (hP : 0 < P) (a : BinaryFraction) + (initial : TargetInterval ny → BinaryFraction × ℕ) (allocation : TargetInterval ny → ℕ) + (q : TargetInterval ny) (ha : ∀ r, allocation r ≤ (initial r).2) : + queryBandInputsAllocation M parent N P F exponent hP a initial allocation q ≤ + (queryBandInputsWithWork M parent N P F exponent hP a initial q).2 := by + have hr := queryEarlierRepresentativesAllocation_le_work N P F exponent hP a initial allocation q ha + have hw := queryWideInputsAllocation_le_work M parent P + (queryEarlierRepresentativesWithWork N P F exponent hP a initial q).1 + unfold queryBandInputsAllocation queryBandInputsWithWork + dsimp only + omega + + + +theorem queryWarmupInputsAllocation_le_work {nx ny : ℕ} (M : ℕ) (parent : TargetInterval nx) + (N P F : ℕ) (a : BinaryFraction) + (initial : TargetInterval ny → BinaryFraction × ℕ) (allocation : TargetInterval ny → ℕ) + (q : TargetInterval ny) (ha : ∀ r, allocation r ≤ (initial r).2) : + queryWarmupInputsAllocation M parent N P F a initial allocation q ≤ + (queryWarmupInputsWithWork M parent N P F a initial q).2 := by + have hr := localRepresentativeReadAllocation_le_work N P F a initial allocation q ha + have hw := queryWideInputsAllocation_le_work M parent P (localRepresentativeReadWithWork N P F a initial q).1 + unfold queryWarmupInputsAllocation queryWarmupInputsWithWork + dsimp only + omega + +end BinaryFraction + +open BitQuery + +def queryInitialGatherHeap {ι β : Type*} {n : ℕ} (N P F exponent : ℕ) (hP : 0 < P) + (a : BinaryFraction) (q : TargetInterval n) + (reader : TargetInterval n → BitQuery ι BinaryFraction) (hr : ∀ key, Heap (reader key)) + (next : List (TargetInterval n) → List BinaryFraction → BitQuery ι β) + (hn : ∀ keys words, Heap (next keys words)) : + Heap (queryInitialGather N P F exponent hP a q reader next) := + (hr q).bind _ fun value => + (Heap.computeOf (BinaryFraction.queryInitialSupportWithWork N P F exponent hP a value q) + (BinaryFraction.queryInitialSupportAllocation N P F exponent hP a value q) + (BinaryFraction.queryInitialSupportAllocation_le_work N P F exponent hP a value q)).bind _ fun keys => + Heap.collect reader hr keys (next keys) (hn keys) + +def queryBandGatherHeap {ι β : Type*} {nx ny : ℕ} (M : ℕ) (parent : TargetInterval nx) + (N P F exponent : ℕ) (hP : 0 < P) (a : BinaryFraction) + (initial : TargetInterval ny → BinaryFraction × ℕ) (allocation : TargetInterval ny → ℕ) + (ha : ∀ r, allocation r ≤ (initial r).2) (q : TargetInterval ny) + (massReader initialReader : (Fin M × TargetInterval ny) → BitQuery ι BinaryFraction) + (hm : ∀ key, Heap (massReader key)) (hi : ∀ key, Heap (initialReader key)) + (next : List (Fin M × TargetInterval ny) → List BinaryFraction → List BinaryFraction → BitQuery ι β) + (hn : ∀ keys mass words, Heap (next keys mass words)) : + Heap (queryBandGather M parent N P F exponent hP a initial q massReader initialReader next) := + (Heap.computeOf (BinaryFraction.queryBandInputsWithWork M parent N P F exponent hP a initial q) + (BinaryFraction.queryBandInputsAllocation M parent N P F exponent hP a initial allocation q) + (BinaryFraction.queryBandInputsAllocation_le_work M parent N P F exponent hP a initial allocation q ha)).bind _ fun keys => + Heap.collect massReader hm keys _ fun mass => Heap.collect initialReader hi keys _ (hn keys mass) + +def queryGroupSourceGatherHeap {ι β : Type*} {n : ℕ} (M N F Q exponent eM eF : ℕ) + (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (a : BinaryFraction) + (initial : TargetInterval n → BinaryFraction × ℕ) (allocation : TargetInterval n → ℕ) + (ha : ∀ r, allocation r ≤ (initial r).2) (q : TargetInterval n) + (reader : GroupScalarKey M F Q → BitQuery ι BinaryFraction) (hr : ∀ key, Heap (reader key)) + (next : List (GroupScalarKey M F Q) → List BinaryFraction → BitQuery ι β) + (hn : ∀ keys words, Heap (next keys words)) : + Heap (queryGroupSourceGather M N F Q exponent eM eF hM hF a initial q reader next) := + Heap.chargeOf (allocation q) (ha q) + ((Heap.computeOf (BinaryFraction.queryGroupSourceKeysWithWork M N F Q exponent eM eF hM hF a (initial q).1 q) + (BinaryFraction.queryGroupSourceKeysAllocation M N F Q exponent eM eF hM hF a (initial q).1 q) + (BinaryFraction.queryGroupSourceKeysAllocation_le_work M N F Q exponent eM eF hM hF a (initial q).1 q)).bind _ fun keys => + Heap.collect reader hr keys (next keys) (hn keys)) + +def queryOnlineSourceGatherHeap {ι β : Type*} {nx ny M : ℕ} (parent : TargetInterval nx) + (N P F exponent H : ℕ) (hP : 0 < P) (tau a : BinaryFraction) + (initial : TargetInterval ny → BinaryFraction × ℕ) (initialAllocation : TargetInterval ny → ℕ) + (child : Fin M → TargetInterval ny → BinaryFraction × ℕ) + (childAllocation : Fin M → TargetInterval ny → ℕ) + (hi : ∀ r, initialAllocation r ≤ (initial r).2) + (hc : ∀ i r, childAllocation i r ≤ (child i r).2) (q : TargetInterval ny) + (reader : (ℕ × TargetInterval ny) → ℕ → BitQuery ι BinaryFraction) + (hr : ∀ key range, Heap (reader key range)) + (next : List (ℕ × TargetInterval ny) → List BinaryFraction → BitQuery ι β) + (hn : ∀ keys words, Heap (next keys words)) : + Heap (queryOnlineSourceGather parent N P F exponent H hP tau a initial child q reader next) := + Heap.chargeOf (initialAllocation q) (hi q) + ((Heap.computeOf (BinaryFraction.queryOnlineKeysWithWork N P F hP a (initial q).1 q) + (BinaryFraction.queryOnlineKeysAllocation N P F hP a (initial q).1 q) + (BinaryFraction.queryOnlineKeysAllocation_le_work N P F hP a (initial q).1 q)).bind _ fun keys => + Heap.collect _ (fun key => + (Heap.computeOf (BinaryFraction.queryOnlineRangeWithWork parent P exponent H tau child key) + (BinaryFraction.queryOnlineRangeAllocation parent P exponent H tau child childAllocation key) + (BinaryFraction.queryOnlineRangeAllocation_le_work parent P exponent H tau child childAllocation key hc)).bind _ (hr key)) + keys (next keys) (hn keys)) + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryGridCost.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryGridCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..cc2d98d7184c498c50960366b7c88e83027c7997 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryGridCost.lean @@ -0,0 +1,64 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryInitialSupport +import OAI.Combinatorics.EditApproximation.Binary.BinaryLocalRepresentativeWork + +namespace OAI + +/-! A scale guard bounds the number of grid points even when the center +radius is as large as the input. These bounds include construction of +all points, before subsequent eligibility filtering. -/ + +namespace EditApproximation + +theorem queryGridSpacing_count (P b radius K : ℕ) (hP : 0 < P) (hr : radius ≤ K * b) : + 2 * radius / seedGridSpacing b P + 2 ≤ 4 * K * P + 2 := by + have hg : 0 < seedGridSpacing b P := by unfold seedGridSpacing; omega + have hq : b / P ≤ seedGridSpacing b P := le_max_right _ _ + have hdiv := Nat.lt_mul_div_succ b hP + have hb : b ≤ 2 * P * seedGridSpacing b P := by nlinarith only [hq, hdiv, hg] + have hn : 2 * radius ≤ 4 * K * P * seedGridSpacing b P := by + nlinarith only [hr, Nat.mul_le_mul_left (2 * K) hb] + have hfloor := Nat.div_mul_le_self (2 * radius) (seedGridSpacing b P) + nlinarith only [hfloor, hn, hg] + +def queryGridPointsWithWork {n : ℕ} (P b radius : ℕ) (q : TargetInterval n) : + List (TargetInterval n) × ℕ := + let spacing := seedGridSpacingWithWork b P + let points := gridStateBoxWithWork n (bitWordValue spacing.1) radius q.lo q.hi + (points.1, spacing.2 + points.2 + 1) + +def queryGridPointsBitBudget (P K B : ℕ) : ℕ := + 100 * (B + 2) ^ 2 + gridStateBoxBitBudget (4 * K * P + 2) (B + 1) + 1 + +theorem queryGridPointsWithWork_bounds {n : ℕ} (P b radius K B : ℕ) (q : TargetInterval n) + (hP : 0 < P) (hPb : Nat.size P ≤ B) (hb : Nat.size b ≤ B) + (hr : Nat.size radius ≤ B) (hn : Nat.size n ≤ B) (hcount : radius ≤ K * b) : + (queryGridPointsWithWork P b radius q).1.length ≤ (4 * K * P + 2) ^ 2 ∧ + (queryGridPointsWithWork P b radius q).2 ≤ queryGridPointsBitBudget P K B := by + let spacing := seedGridSpacingWithWork b P + have hs := seedGridSpacingWithWork_bounds b P B hb hPb + have hp := seedGridSpacingWithWork_pos b P hP + have hsp : Nat.size (bitWordValue spacing.1) ≤ B + 1 := + (Nat.size_le.mpr (bitWordValue_lt_pow_length spacing.1)).trans hs.1 + have hc := queryGridSpacing_count P b radius K hP hcount + have hv : bitWordValue spacing.1 = seedGridSpacing b P := seedGridSpacingWithWork_value b P hP + have hgc := gridStateBoxWithWork_cost n (bitWordValue spacing.1) radius q.lo q.hi (B + 1) + hp (by omega) hsp (by omega) + ((Nat.size_le_size (q.ordered.trans q.valid)).trans (by omega)) + ((Nat.size_le_size q.valid).trans (by omega)) + rw [hv] at hgc + have hgc' := hgc.trans (gridStateBoxBitBudget_mono_count _ _ (B + 1) hc) + have hlength : (gridStateBoxWithWork n (bitWordValue spacing.1) radius q.lo q.hi).1.length ≤ + (4 * K * P + 2) ^ 2 := by + rw [gridStateBoxWithWork_value _ _ _ _ _ hp, hv] + exact (localTargetStates_length_le (by unfold seedGridSpacing; omega) q).trans + (Nat.pow_le_pow_left hc 2) + have hcost : spacing.2 + + (gridStateBoxWithWork n (bitWordValue spacing.1) radius q.lo q.hi).2 + 1 ≤ + queryGridPointsBitBudget P K B := by + rw [hv] + exact Nat.add_le_add_right (Nat.add_le_add hs.2 hgc') 1 + simpa only [queryGridPointsWithWork, spacing] using And.intro hlength hcost + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryGroupInputCost.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryGroupInputCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..6be60f2cd55937341ad4043371ad540d9de67db1 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryGroupInputCost.lean @@ -0,0 +1,69 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryGroupLabelCost +import OAI.Combinatorics.EditApproximation.Queries.QueryRoundedStateCost +import OAI.Combinatorics.EditApproximation.Queries.QueryRoundedCounts + +namespace OAI + +namespace EditApproximation.BinaryFraction + +def queryGroupInputsLength (M exponent : ℕ) : ℕ := + M * ((24 * 2 ^ exponent * M + 2) * (4 * 2 ^ exponent + 4)) + +def queryGroupInputsBitBudget (M exponent B R : ℕ) : ℕ := + let L := (24 * 2 ^ exponent * M + 2) * (4 * 2 ^ exponent + 4) + queryGroupLabelsBitBudget M B R + + M * (queryRoundedStatesBitBudget (24 * 2 ^ exponent * M + 2) (4 * 2 ^ exponent + 4) exponent B + + 5 * L + 4) + 1 + +theorem queryGroupInputsWithWork_bounds {nx ny M : ℕ} (parent : TargetInterval nx) + (b exponent Q B R : ℕ) (cell : ℕ × ℕ) (h : BinaryFraction) + (draw : Fin (groupSampleCount M Q b h.value) → Fin M × ℕ) + (hB : 4 ≤ B) (hMpos : 0 < M) (hnx : Nat.size nx ≤ B) (hny : Nat.size ny ≤ B) + (hM : Nat.size M + 2 ≤ B) (hQ : Nat.size Q + 2 ≤ B) (hb : Nat.size b + 2 ≤ B) + (hc : Nat.size cell.1 ≤ B) (he : exponent + 1 ≤ B) (hh : h.width ≤ B) + (hhv : 0 ≤ h.value) (hfloor : (b : ℚ) / M ≤ h.value) (hR : ∀ i, (draw i).2 ≤ R) : + (queryGroupInputsWithWork (ny := ny) parent b exponent Q cell h draw).1.length ≤ + queryGroupInputsLength M exponent ∧ + (queryGroupInputsWithWork (ny := ny) parent b exponent Q cell h draw).2 ≤ + queryGroupInputsBitBudget M exponent B R := by + let labels := queryGroupLabelsWithWork M Q b h draw + let L := (24 * 2 ^ exponent * M + 2) * (4 * 2 ^ exponent + 4) + let C := queryRoundedStatesBitBudget (24 * 2 ^ exponent * M + 2) (4 * 2 ^ exponent + 4) exponent B + let run := fun i : Fin M => + let states := queryGroupRoundedStatesWithWork (ny := ny) parent b exponent cell i h + let tagged := arithmeticMapWithWork (fun r => ((i, r), 1)) states.1 + (tagged.1, states.2 + tagged.2 + 1) + have hl := queryGroupLabelsWithWork_bounds M Q b B R h draw hM hQ hb hh hR + have hcounts := groupRoundSpacing_endpoint_counts M b exponent h.value hMpos hhv hfloor + have hs (i : Fin M) := queryGroupRoundedStatesWithWork_bounds (ny := ny) parent b exponent B + (24 * 2 ^ exponent * M + 2) (4 * 2 ^ exponent + 4) cell i h hB hnx hny (by omega) + (by omega) hc he hh hcounts.1 hcounts.2 + have hrun (i : Fin M) : (run i).1.length ≤ L ∧ (run i).2 ≤ C + 4 * L + 1 := by + have hm := (arithmeticMapWithWork_cost (fun r => ((i, r), 1)) + (queryGroupRoundedStatesWithWork (ny := ny) parent b exponent cell i h).1 1 + (fun _ _ => le_rfl)).trans (Nat.mul_le_mul_right _ (hs i).1) + constructor + · simpa only [run, arithmeticMapWithWork_value, List.length_map] using (hs i).1 + · change (queryGroupRoundedStatesWithWork (ny := ny) parent b exponent cell i h).2 + + (arithmeticMapWithWork (fun r => ((i, r), 1)) + (queryGroupRoundedStatesWithWork (ny := ny) parent b exponent cell i h).1).2 + 1 ≤ _ + have hsc : (queryGroupRoundedStatesWithWork (ny := ny) parent b exponent cell i h).2 ≤ C := (hs i).2 + change _ ≤ L * 4 at hm + rw [Nat.mul_comm L 4] at hm + omega + have hlen := (arithmeticFlatMapWithWork_length run labels.1 L + (fun i _ => (hrun i).1)).trans (Nat.mul_le_mul_right _ hl.1) + have hcost := (arithmeticFlatMapWithWork_cost run labels.1 (C + 4 * L + 1) L + (fun i _ => (hrun i).2) (fun i _ => (hrun i).1)).trans (Nat.mul_le_mul_right _ hl.1) + rw [show C + 4 * L + 1 + L + 3 = C + 5 * L + 4 by omega] at hcost + have hinputCost : labels.2 + (arithmeticFlatMapWithWork run labels.1).2 + 1 ≤ + queryGroupInputsBitBudget M exponent B R := by + have hlc : labels.2 ≤ queryGroupLabelsBitBudget M B R := hl.2 + simpa only [queryGroupInputsBitBudget, C, L] using + Nat.add_le_add_right (Nat.add_le_add hlc hcost) 1 + simpa only [queryGroupInputsWithWork, labels, run, queryGroupInputsLength, L] using + And.intro hlen hinputCost + +end EditApproximation.BinaryFraction + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryGroupInputs.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryGroupInputs.lean new file mode 100644 index 0000000000000000000000000000000000000000..07c7e10fdefb85b5c4505972e5aa9db6683be704 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryGroupInputs.lean @@ -0,0 +1,52 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryGroupSamples +import OAI.Combinatorics.EditApproximation.Queries.QuerySharedGeometry +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! A shared estimator requests every child when its exact sample count +equals the arity; otherwise it requests the sampled child labels. The +Boolean test and each draw-table lookup are included in the counter. -/ + +namespace EditApproximation +namespace BinaryFraction + + + +theorem queryGroupLabelsWithWork_value (M Q b : ℕ) (h : BinaryFraction) + (draw : Fin (groupSampleCount M Q b h.value) → Fin M × ℕ) : + (queryGroupLabelsWithWork M Q b h draw).1.toFinset = + groupQueriedChildLabels M Q b h.value (fun i => (draw i).1) := by + have ht : (naturalEqualWithWork (bitWordValue (groupSampleCountWithWork M Q b h).1) M).1 = true ↔ + groupSampleCount M Q b h.value = M := by + rw [naturalEqualWithWork_value, groupSampleCountWithWork_value] + unfold queryGroupLabelsWithWork groupQueriedChildLabels + by_cases he : groupSampleCount M Q b h.value = M + · rw [ite_eq_left (ht.mpr he), ite_eq_left he] + ext i + simp + · rw [ite_eq_right (fun hx => he (ht.mp hx)), ite_eq_right he] + simp only [arithmeticMapWithWork_value] + ext i + simp + + + +theorem queryGroupInputsWithWork_value {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (b exponent Q : ℕ) (cell : ℕ × ℕ) + (h : BinaryFraction) (draw : Fin (groupSampleCount M Q b h.value) → Fin M × ℕ) : + (queryGroupInputsWithWork (ny := target.length) parent b exponent Q cell h draw).1.toFinset = + groupCurrentInputCover source target parent b exponent Q cell h.value (fun i => (draw i).1) := by + have hl := queryGroupLabelsWithWork_value M Q b h draw + simp only [queryGroupInputsWithWork, arithmeticFlatMapWithWork_value, + arithmeticMapWithWork_value, queryGroupRoundedStatesWithWork_value source target] + ext input + simp only [List.mem_toFinset, List.mem_flatMap, List.mem_map, groupCurrentInputCover, + Finset.mem_biUnion, Finset.mem_image] + simp only [← hl, List.mem_toFinset] + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryGroupKeyCost.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryGroupKeyCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..4eaaeb585dcb70d0cba1b02eb4c53cb0dd824047 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryGroupKeyCost.lean @@ -0,0 +1,84 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryCellCost + +namespace OAI + +/-! Size, construction work and coordinate widths of the actual group +key list, including the binary dyadic scale enumeration. -/ + +namespace EditApproximation.BinaryFraction + +def queryGroupKeysBitBudget (F exponent B : ℕ) : ℕ := + let L := ((32 * F + 2) * 2 ^ exponent + 2) ^ 2 + queryScalesBitBudget B + 500 * (B + 1) ^ 2 + + (B + 1) * (queryCellScanBitBudget F exponent B + 5 * L + 5) + exponent + 4 + +theorem queryGroupKeysWithWork_bounds {n : ℕ} (N F exponent B : ℕ) + (a value : BinaryFraction) (q : TargetInterval n) + (hB : 7 ≤ B) (hN : Nat.size N ≤ B) (hF : Nat.size F + 2 ≤ B) + (hFpos : 1 ≤ F) (he : exponent + 1 ≤ B) (hn : Nat.size n ≤ B) + (ha : a.width ≤ B) (hv : value.width ≤ B) (hw : 0 ≤ value.value) : + (queryGroupKeysWithWork N F exponent a value q).1.length ≤ + (B + 1) * ((32 * F + 2) * 2 ^ exponent + 2) ^ 2 ∧ + (queryGroupKeysWithWork N F exponent a value q).2 ≤ queryGroupKeysBitBudget F exponent B ∧ + ∀ key ∈ (queryGroupKeysWithWork N F exponent a value q).1, + Nat.size key.1 ≤ B + 1 ∧ (∃ e : ℕ, key.1 = 2 ^ e) ∧ + Nat.size key.2.1 ≤ 16 * B + 183 ∧ Nat.size key.2.2 ≤ 16 * B + 183 := by + let scales := queryScalesWithWork N F a value + let radius := naturalCeilingWithWork value + let cells := fun b => targetCellsWithWork + (canonicalMulWithWork (inversePowerTwo exponent) (nat b)).1 (bitWordValue radius.1) q + let run := fun b => + let side := canonicalMulWithWork (inversePowerTwo exponent) (nat b) + let labeled := arithmeticMapWithWork (fun cell => ((b, cell), 1)) (cells b).1 + (labeled.1, side.2 + (cells b).2 + labeled.2 + 2) + let L := ((32 * F + 2) * 2 ^ exponent + 2) ^ 2 + have hs := queryScalesWithWork_bounds N F B a value hB hN hF ha hv + have hc (b : ℕ) (hb : b ∈ scales.1) : + (cells b).1.length ≤ L ∧ + (canonicalMulWithWork (inversePowerTwo exponent) (nat b)).2 + (cells b).2 ≤ + queryCellScanBitBudget F exponent B ∧ + ∀ cell ∈ (cells b).1, Nat.size cell.1 ≤ 16 * B + 183 ∧ Nat.size cell.2 ≤ 16 * B + 183 := by + have hm := queryScalesWithWork_member N F B a value hN hFpos b hb + have hw' := queryScalesWithWork_window N F a value b hb + have hbp : 1 ≤ b := by obtain ⟨e, rfl⟩ := hw'.1; exact Nat.succ_le_of_lt (Nat.two_pow_pos e) + exact queryCellScan_bounds F b exponent B value q hFpos hbp hm.1 he hn hv hw hw'.2 + have hlen (b : ℕ) (hb : b ∈ scales.1) : (run b).1.length ≤ L := by + simpa only [run, arithmeticMapWithWork_value, List.length_map] using (hc b hb).1 + have hwork (b : ℕ) (hb : b ∈ scales.1) : + (run b).2 ≤ queryCellScanBitBudget F exponent B + 4 * L + 2 := by + have hm := arithmeticMapWithWork_cost (fun cell => ((b, cell), 1)) (cells b).1 1 + (fun _ _ => le_rfl) + have hh := hc b hb + have hm' := hm.trans (Nat.mul_le_mul_right _ hh.1) + change _ + _ + _ + 2 ≤ _ + simp only [Nat.reduceAdd] at hm' + rw [Nat.mul_comm L 4] at hm' + omega + have hl := (arithmeticFlatMapWithWork_length run scales.1 L hlen).trans + (Nat.mul_le_mul_right L hs.1) + have hf := (arithmeticFlatMapWithWork_cost run scales.1 + (queryCellScanBitBudget F exponent B + 4 * L + 2) L hwork hlen).trans + (Nat.mul_le_mul_right _ hs.1) + have hrad := (naturalCeilingWithWork_cost value).trans + (Nat.mul_le_mul_left 500 (Nat.pow_le_pow_left (Nat.add_le_add_right hv 1) 2)) + refine ⟨hl, ?_, ?_⟩ + · change scales.2 + radius.2 + (arithmeticFlatMapWithWork run scales.1).2 + exponent + 4 ≤ _ + change _ ≤ queryScalesBitBudget B + 500 * (B + 1) ^ 2 + + (B + 1) * (queryCellScanBitBudget F exponent B + 5 * L + 5) + exponent + 4 + rw [show queryCellScanBitBudget F exponent B + 4 * L + 2 + L + 3 = + queryCellScanBitBudget F exponent B + 5 * L + 5 by omega] at hf + have hsc : scales.2 ≤ queryScalesBitBudget B := hs.2 + change radius.2 ≤ _ at hrad + omega + · intro key hk + change key ∈ (arithmeticFlatMapWithWork run scales.1).1 at hk + rw [arithmeticFlatMapWithWork_value] at hk + obtain ⟨b, hb, hk⟩ := List.mem_flatMap.mp hk + simp only [run, arithmeticMapWithWork_value] at hk + obtain ⟨cell, hcell, rfl⟩ := List.mem_map.mp hk + exact ⟨(queryScalesWithWork_member N F B a value hN hFpos b hb).1, + (queryScalesWithWork_window N F a value b hb).1, (hc b hb).2.2 cell hcell⟩ + +end EditApproximation.BinaryFraction + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryGroupLabelCost.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryGroupLabelCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..1444223372ba93b05c12fd5185f4bd48779c5213 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryGroupLabelCost.lean @@ -0,0 +1,59 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryGroupInputs +import OAI.Combinatorics.EditApproximation.Binary.BinaryGroupSetupWork +import OAI.Combinatorics.EditApproximation.Binary.BinaryBandGuardWork + +namespace OAI + +namespace EditApproximation.BinaryFraction + +def queryGroupLabelsBitBudget (M B R : ℕ) : ℕ := + groupSampleCountBitBudget B + 8 * (groupSampleCountWordBudget B) + + M * (R + 4) + 4 + +theorem queryGroupLabelsWithWork_bounds (M Q b B R : ℕ) (h : BinaryFraction) + (draw : Fin (groupSampleCount M Q b h.value) → Fin M × ℕ) + (hM : Nat.size M + 2 ≤ B) (hQ : Nat.size Q + 2 ≤ B) + (hb : Nat.size b + 2 ≤ B) (hh : h.width ≤ B) + (hR : ∀ i, (draw i).2 ≤ R) : + (queryGroupLabelsWithWork M Q b h draw).1.length ≤ M ∧ + (queryGroupLabelsWithWork M Q b h draw).2 ≤ queryGroupLabelsBitBudget M B R := by + let count := groupSampleCountWithWork M Q b h + let test := naturalEqualWithWork (bitWordValue count.1) M + have hc := groupSampleCountWithWork_bounds M Q b h B hM hQ hb hh + have hsize : Nat.size (bitWordValue count.1) ≤ groupSampleCountWordBudget B := + (Nat.size_le.mpr (bitWordValue_lt_pow_length _)).trans hc.1 + have ht := naturalEqualWithWork_cost (bitWordValue count.1) M (groupSampleCountWordBudget B) + hsize (by unfold groupSampleCountWordBudget; omega) + by_cases he : (naturalEqualWithWork (bitWordValue (groupSampleCountWithWork M Q b h).1) M).1 = true + · simp only [queryGroupLabelsWithWork, he, ↓reduceIte, List.length_finRange] + refine ⟨le_rfl, ?_⟩ + change count.2 + test.2 + M + 2 ≤ _ + have hcc : count.2 ≤ groupSampleCountBitBudget B := hc.2 + change test.2 ≤ _ at ht + unfold queryGroupLabelsBitBudget + nlinarith only [hcc, ht, Nat.zero_le R, Nat.zero_le M] + · have hlabels := arithmeticMapWithWork_cost draw (List.finRange (groupSampleCount M Q b h.value)) R + (fun i _ => hR i) + have hlen : groupSampleCount M Q b h.value ≤ M := Nat.min_le_left _ _ + simp only [List.length_finRange] at hlabels + have hlabels' := hlabels.trans (Nat.mul_le_mul_right _ hlen) + simp only [queryGroupLabelsWithWork, he, Bool.false_eq_true, ↓reduceIte] + let indices := queryFinRange (bitWordValue count.1) (groupSampleCount M Q b h.value) + (groupSampleCountWithWork_value M Q b h) + change (arithmeticMapWithWork draw indices).1.length ≤ M ∧ + count.2 + test.2 + (arithmeticMapWithWork draw indices).2 + indices.length + 2 ≤ _ + have hindices : indices = List.finRange (groupSampleCount M Q b h.value) := + queryFinRange_value _ _ _ + rw [hindices] + simp only [arithmeticMapWithWork_value, List.length_map, List.length_finRange] + refine ⟨hlen, ?_⟩ + have hcc : count.2 ≤ groupSampleCountBitBudget B := hc.2 + change test.2 ≤ _ at ht + unfold queryGroupLabelsBitBudget + have heq : M * (R + 4) = M * (R + 3) + M := by ring + rw [heq] + omega + +end EditApproximation.BinaryFraction + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryGroupSampleCost.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryGroupSampleCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..163c2af5700bffb569f85f71451d12ae2498c9eb --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryGroupSampleCost.lean @@ -0,0 +1,99 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryGroupSamples +import OAI.Combinatorics.EditApproximation.Binary.BinaryGroupSetupWork +import OAI.Combinatorics.EditApproximation.Queries.QueryHistoryBounds + +namespace OAI + +/-! The source-key builder executes all scale/sample loops. Their cost +is bounded using the computed count, which is capped by the arity. -/ + +namespace EditApproximation.BinaryFraction + +def queryGroupSamplesBitBudget (M eM eb eF B : ℕ) : ℕ := + let L := 7 + eM + eF + groupScalesBitBudget eM eb eF + 4 * L + + L * (L + groupSampleCountBitBudget B + 7 * M + 6) + eb + 4 + +theorem queryGroupKeySamplesWithWork_bounds (M F Q eM eb eF B : ℕ) + (hMdef : M = 2 ^ eM) (hFdef : F = 2 ^ eF) (cell : ℕ × ℕ) + (hM : Nat.size M + 2 ≤ B) (hQ : Nat.size Q + 2 ≤ B) + (heb : eb + 3 ≤ B) (hsb : eM + eb + eF + 7 ≤ B) : + (queryGroupKeySamplesWithWork M F Q eM eb eF hMdef hFdef cell).1.length ≤ + (7 + eM + eF) * M ∧ + (queryGroupKeySamplesWithWork M F Q eM eb eF hMdef hFdef cell).2 ≤ + queryGroupSamplesBitBudget M eM eb eF B := by + let b := 2 ^ eb + let scales := groupScalesWithWork eM eb eF + have hs : scales.1.map value = groupDyadicScales M b F := by + simpa only [nat_value] using computedGroupScales_value M b F eM eb eF hMdef rfl hFdef + have hlen : scales.1.length = (groupDyadicScales M b F).length := by + simpa only [List.length_map] using congrArg List.length hs + let indices := queryFinRange scales.1.length (groupDyadicScales M b F).length hlen + let run := fun scale : Fin (groupDyadicScales M b F).length => + let word := queryScaleAt scales.1 (groupDyadicScales M b F) hs scale + let count := groupSampleCountWithWork M Q b word + let hc : bitWordValue count.1 = groupSampleCount M Q b (groupDyadicScaleAt M b F scale) := by + rw [groupSampleCountWithWork_value, queryScaleAt_value] + rfl + let coordinates := queryFinRange (bitWordValue count.1) + (groupSampleCount M Q b (groupDyadicScaleAt M b F scale)) hc + let labeled := arithmeticMapWithWork (fun sample => + ((⟨(b, cell), scale, sample⟩ : GroupScalarKey M F Q), 2)) coordinates + (labeled.1, scales.1.length + count.2 + labeled.2 + coordinates.length + 3) + have hslen : scales.1.length = 7 + eM + eF := groupScalesWithWork_length eM eb eF + have hilen : indices.length = 7 + eM + eF := by + dsimp only [indices] + rw [queryFinRange_value, List.length_finRange, ← hlen, hslen] + have hsbounds := groupScalesWithWork_bounds eM eb eF + have hword (scale : Fin (groupDyadicScales M b F).length) : + (queryScaleAt scales.1 (groupDyadicScales M b F) hs scale).width ≤ B := by + apply (hsbounds.1 _ ?_).trans hsb + exact List.getElem_mem _ + have hcount (scale : Fin (groupDyadicScales M b F).length) := + (groupSampleCountWithWork_bounds M Q b + (queryScaleAt scales.1 (groupDyadicScales M b F) hs scale) B hM hQ + (by dsimp only [b]; rw [Nat.size_pow]; omega) (hword scale)).2 + have hrlen (scale : Fin (groupDyadicScales M b F).length) : (run scale).1.length ≤ M := by + simp only [run, arithmeticMapWithWork_value, List.length_map, queryFinRange_value, + List.length_finRange] + exact Nat.min_le_left _ _ + have hrcost (scale : Fin (groupDyadicScales M b F).length) : + (run scale).2 ≤ (7 + eM + eF) + groupSampleCountBitBudget B + 6 * M + 3 := by + have hlabel := arithmeticMapWithWork_cost + (fun sample : Fin (groupSampleCount M Q b (groupDyadicScaleAt M b F scale)) => + ((⟨(b, cell), scale, sample⟩ : GroupScalarKey M F Q), 2)) + (List.finRange _) 2 (fun _ _ => le_rfl) + simp only [List.length_finRange, Nat.reduceAdd] at hlabel + have hlen' : groupSampleCount M Q b (groupDyadicScaleAt M b F scale) ≤ M := Nat.min_le_left _ _ + have hlabel' := hlabel.trans (Nat.mul_le_mul_right 5 hlen') + dsimp only [run] + simp only [queryFinRange_value, List.length_finRange, hslen] + have hh := hcount scale + nlinarith only [hlabel', hh, hlen'] + have hl := arithmeticFlatMapWithWork_length run indices M (fun scale _ => hrlen scale) + have hc := arithmeticFlatMapWithWork_cost run indices + ((7 + eM + eF) + groupSampleCountBitBudget B + 6 * M + 3) M + (fun scale _ => hrcost scale) (fun scale _ => hrlen scale) + rw [hilen] at hl hc + constructor + · exact hl + · change scales.2 + 4 * scales.1.length + (arithmeticFlatMapWithWork run indices).2 + eb + 4 ≤ _ + rw [hslen] + have hswork : scales.2 ≤ groupScalesBitBudget eM eb eF := hsbounds.2 + change _ ≤ groupScalesBitBudget eM eb eF + 4 * (7 + eM + eF) + + (7 + eM + eF) * ((7 + eM + eF) + groupSampleCountBitBudget B + 7 * M + 6) + eb + 4 + rw [show 7 + eM + eF + groupSampleCountBitBudget B + 6 * M + 3 + M + 3 = + (7 + eM + eF) + groupSampleCountBitBudget B + 7 * M + 6 by omega] at hc + omega + +theorem queryGroupSamplesBitBudget_mono (M eM eb eb' eF B B' : ℕ) + (he : eb ≤ eb') (hB : B ≤ B') : + queryGroupSamplesBitBudget M eM eb eF B ≤ queryGroupSamplesBitBudget M eM eb' eF B' := by + unfold queryGroupSamplesBitBudget groupScalesBitBudget groupSampleCountBitBudget + dsimp only + gcongr + exact Nat.size_le_size he + +end EditApproximation.BinaryFraction + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryGroupSamples.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryGroupSamples.lean new file mode 100644 index 0000000000000000000000000000000000000000..16229300e140f8286e40b2746f0f3de06dfcf908 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryGroupSamples.lean @@ -0,0 +1,50 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryInitialSupport +import OAI.Combinatorics.EditApproximation.Geometry.LocalGroupSourceQuery +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Group sample coordinates are enumerated from the computed dyadic +scale array and binary sample counts. Equalities used in index casts are +proofs only; the loop bounds are the values just computed. -/ + +namespace EditApproximation + + + +@[simp] theorem queryFinRange_value (n m : ℕ) (h : n = m) : + queryFinRange n m h = List.finRange m := by + subst m + simp only [queryFinRange, Fin.eta, List.map_id'] + +namespace BinaryFraction + + + +@[simp] theorem queryScaleAt_value (words : List BinaryFraction) (scales : List ℚ) + (h : words.map value = scales) (i : Fin scales.length) : + (queryScaleAt words scales h i).value = scales[i.val] := by + subst scales + simp only [queryScaleAt, List.getElem_map] + +theorem queryGroupScaleAt_value (M b F : ℕ) (words : List BinaryFraction) + (h : words.map value = groupDyadicScales M b F) + (i : Fin (groupDyadicScales M b F).length) : + (queryScaleAt words (groupDyadicScales M b F) h i).value = groupDyadicScaleAt M b F i := + queryScaleAt_value words (groupDyadicScales M b F) h i + + + +theorem queryGroupKeySamplesWithWork_value (M F Q eM eb eF : ℕ) + (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (cell : ℕ × ℕ) : + (queryGroupKeySamplesWithWork M F Q eM eb eF hM hF cell).1 = + groupScalarKeys M F Q [(2 ^ eb, cell)] := by + simp only [queryGroupKeySamplesWithWork, arithmeticFlatMapWithWork_value, + arithmeticMapWithWork_value, queryFinRange_value, groupScalarKeys, + List.flatMap_cons, List.flatMap_nil, List.append_nil] + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryGroupSetupSpace.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryGroupSetupSpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..b337a2c2c4e6c09c36b5913236f9b5ec12d9ddee --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryGroupSetupSpace.lean @@ -0,0 +1,81 @@ +import OAI.Combinatorics.EditApproximation.Queries.QuerySharedGeometrySpace +import OAI.Combinatorics.EditApproximation.Queries.QueryInputSpace +import OAI.Combinatorics.EditApproximation.Queries.QueryGroupInputs +import OAI.Combinatorics.EditApproximation.Binary.BinaryGroupSpace +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation.BinaryFraction + + + +theorem signedPowerTwoAllocation_le_work (e : ℤ) : + signedPowerTwoAllocation e ≤ (signedPowerTwoWithWork e).2 := by + unfold signedPowerTwoAllocation signedPowerTwoWithWork + split_ifs <;> dsimp only <;> exact Nat.le_succ _ + + + +theorem groupScalesAllocation_le_work (eM eb eF : ℕ) : + groupScalesAllocation eM eb eF ≤ (groupScalesWithWork eM eb eF).2 := by + have h := arithmeticMapAllocation_le_work signedPowerTwoWithWork signedPowerTwoAllocation + (integerClosedRange ((eb : ℤ) - eM) ((6 + eF + eb : ℕ) : ℤ)) + (fun e _ => signedPowerTwoAllocation_le_work e) + unfold groupScalesAllocation groupScalesWithWork + dsimp only + omega + + + +theorem queryGroupLabelsAllocation_le_work (M Q b : ℕ) (h : BinaryFraction) + (draw : Fin (groupSampleCount M Q b h.value) → Fin M × ℕ) + (allocation : Fin (groupSampleCount M Q b h.value) → ℕ) + (ha : ∀ i, allocation i ≤ (draw i).2) : + queryGroupLabelsAllocation M Q b h draw allocation ≤ (queryGroupLabelsWithWork M Q b h draw).2 := by + have costBound (c c' t t' a a' l : ℕ) (hc : c ≤ c') (ht : t ≤ t') + (ha : a + l ≤ a') : c + t + (a + 2 * l) ≤ c' + t' + a' + l + 2 := by + omega + have hc := groupSampleCountAllocation_le_work M Q b h + have ht := naturalEqualAllocation_le_work (bitWordValue (groupSampleCountWithWork M Q b h).1) M + have hm := arithmeticMapAllocation_with_spine draw allocation + (queryFinRange (bitWordValue (groupSampleCountWithWork M Q b h).1) + (groupSampleCount M Q b h.value) (groupSampleCountWithWork_value M Q b h)) (fun i _ => ha i) + unfold queryGroupLabelsAllocation queryGroupLabelsWithWork + dsimp only + split_ifs <;> dsimp only + · exact (Nat.add_le_add_right (Nat.add_le_add hc ht) M).trans (Nat.le_add_right _ 2) + · exact costBound _ _ _ _ _ _ _ hc ht hm + + + +theorem queryGroupInputsAllocation_le_work {nx ny M : ℕ} (parent : TargetInterval nx) + (b exponent Q : ℕ) (cell : ℕ × ℕ) (h : BinaryFraction) + (draw : Fin (groupSampleCount M Q b h.value) → Fin M × ℕ) + (allocation : Fin (groupSampleCount M Q b h.value) → ℕ) + (ha : ∀ i, allocation i ≤ (draw i).2) : + queryGroupInputsAllocation (ny := ny) parent b exponent Q cell h draw allocation ≤ + (queryGroupInputsWithWork (ny := ny) parent b exponent Q cell h draw).2 := by + let build := fun i : Fin M => + let states := queryGroupRoundedStatesWithWork (ny := ny) parent b exponent cell i h + let tagged := arithmeticMapWithWork (fun r => ((i, r), 1)) states.1 + (tagged.1, states.2 + tagged.2 + 1) + have hl := queryGroupLabelsAllocation_le_work M Q b h draw allocation ha + have hg := arithmeticFlatMapAllocation_le_work build + (fun i => queryGroupRoundedStatesAllocation (ny := ny) parent b exponent cell i h + + arithmeticMapAllocation (fun _ => 1) (queryGroupRoundedStatesWithWork (ny := ny) parent b exponent cell i h).1) + (queryGroupLabelsWithWork M Q b h draw).1 (by + intro i _ + have hs := queryGroupRoundedStatesAllocation_le_work (ny := ny) parent b exponent cell i h + have hm := arithmeticMapAllocation_le_work (fun r => ((i, r), 1)) (fun _ => 1) + (queryGroupRoundedStatesWithWork (ny := ny) parent b exponent cell i h).1 (fun _ _ => le_rfl) + dsimp only [build] + omega) + unfold queryGroupInputsAllocation queryGroupInputsWithWork + dsimp only [build] at hg ⊢ + omega + +end EditApproximation.BinaryFraction + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryGroupSourceCost.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryGroupSourceCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..326b989e02a5568f17cb07d7f04357bc933a1a62 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryGroupSourceCost.lean @@ -0,0 +1,98 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryGroupSources +import OAI.Combinatorics.EditApproximation.Queries.QueryGroupSampleCost +import OAI.Combinatorics.EditApproximation.Queries.QueryCellCost + +namespace OAI + +namespace EditApproximation.BinaryFraction + +theorem queryExponentsWithWork_member (N F B : ℕ) (a value : BinaryFraction) + (hN : Nat.size N ≤ B) (eb : ℕ) (heb : eb ∈ (queryExponentsWithWork N F a value).1) : + eb ≤ B ∧ 2 ^ eb ∈ (queryScalesWithWork N F a value).1 := by + constructor + · simp only [queryExponentsWithWork, filterWithWork_value] at heb + have h := List.mem_range.mp (List.mem_filter.mp heb).1 + rw [Nat.size_eq_bits_len] at h + omega + · rw [queryScalesWithWork_value, ← queryExponentsWithWork_value] + exact List.mem_map.mpr ⟨eb, heb, rfl⟩ + +def queryGroupSourceKeysLength (M F exponent eM eF B : ℕ) : ℕ := + (B + 1) * ((((32 * F + 2) * 2 ^ exponent + 2) ^ 2) * ((7 + eM + eF) * M)) + +def queryGroupSourceKeysBitBudget (M F exponent eM eF B : ℕ) : ℕ := + let cells := ((32 * F + 2) * 2 ^ exponent + 2) ^ 2 + let samples := (7 + eM + eF) * M + let sampleWork := queryGroupSamplesBitBudget M eM B eF (2 * B + 10) + let scaleWork := queryCellScanBitBudget F exponent B + + cells * (sampleWork + samples + 3) + B + exponent + 4 + queryExponentsBitBudget B + 500 * (B + 1) ^ 2 + + (B + 1) * (scaleWork + cells * samples + 3) + 2 + +theorem queryGroupSourceKeysWithWork_bounds {n : ℕ} (M N F Q exponent eM eF B : ℕ) + (hMdef : M = 2 ^ eM) (hFdef : F = 2 ^ eF) (a value : BinaryFraction) (q : TargetInterval n) + (hB : 7 ≤ B) (hN : Nat.size N ≤ B) (hF : Nat.size F + 2 ≤ B) + (hM : Nat.size M + 2 ≤ B) (hQ : Nat.size Q + 2 ≤ B) (hes : eM + eF + 7 ≤ B) + (he : exponent + 1 ≤ B) (hn : Nat.size n ≤ B) (ha : a.width ≤ B) + (hv : value.width ≤ B) (hw : 0 ≤ value.value) : + (queryGroupSourceKeysWithWork M N F Q exponent eM eF hMdef hFdef a value q).1.length ≤ + queryGroupSourceKeysLength M F exponent eM eF B ∧ + (queryGroupSourceKeysWithWork M N F Q exponent eM eF hMdef hFdef a value q).2 ≤ + queryGroupSourceKeysBitBudget M F exponent eM eF B := by + let scales := queryExponentsWithWork N F a value + let radius := naturalCeilingWithWork value + let cells := fun eb => targetCellsWithWork + (canonicalMulWithWork (inversePowerTwo exponent) (nat (2 ^ eb))).1 (bitWordValue radius.1) q + let sources := fun eb => arithmeticFlatMapWithWork + (queryGroupKeySamplesWithWork M F Q eM eb eF hMdef hFdef) (cells eb).1 + let run := fun eb => + let side := canonicalMulWithWork (inversePowerTwo exponent) (nat (2 ^ eb)) + ((sources eb).1, side.2 + (cells eb).2 + (sources eb).2 + eb + exponent + 4) + let K := ((32 * F + 2) * 2 ^ exponent + 2) ^ 2 + let L := (7 + eM + eF) * M + let W := queryGroupSamplesBitBudget M eM B eF (2 * B + 10) + let C := queryCellScanBitBudget F exponent B + K * (W + L + 3) + B + exponent + 4 + have hs := queryExponentsWithWork_bounds N F B a value hB hN hF ha hv + have hFpos : 1 ≤ F := by rw [hFdef]; exact Nat.succ_le_of_lt (Nat.two_pow_pos _) + have hrun (eb : ℕ) (heb : eb ∈ scales.1) : (run eb).1.length ≤ K * L ∧ (run eb).2 ≤ C := by + have hm := queryExponentsWithWork_member N F B a value hN eb heb + have hwindow := queryScalesWithWork_window N F a value (2 ^ eb) hm.2 + have hcell := queryCellScan_bounds F (2 ^ eb) exponent B value q hFpos + (Nat.succ_le_of_lt (Nat.two_pow_pos _)) + (by rw [Nat.size_pow]; omega) he hn hv hw hwindow.2 + have hsample (cell : ℕ × ℕ) : + (queryGroupKeySamplesWithWork M F Q eM eb eF hMdef hFdef cell).1.length ≤ L ∧ + (queryGroupKeySamplesWithWork M F Q eM eb eF hMdef hFdef cell).2 ≤ W := by + have hh := queryGroupKeySamplesWithWork_bounds M F Q eM eb eF (2 * B + 10) + hMdef hFdef cell (by omega) (by omega) (by omega) (by omega) + exact ⟨hh.1, hh.2.trans (queryGroupSamplesBitBudget_mono M eM eb B eF + (2 * B + 10) (2 * B + 10) hm.1 le_rfl)⟩ + have hl := (arithmeticFlatMapWithWork_length + (queryGroupKeySamplesWithWork M F Q eM eb eF hMdef hFdef) (cells eb).1 L + (fun cell _ => (hsample cell).1)).trans (Nat.mul_le_mul_right _ hcell.1) + have hc := (arithmeticFlatMapWithWork_cost + (queryGroupKeySamplesWithWork M F Q eM eb eF hMdef hFdef) (cells eb).1 W L + (fun cell _ => (hsample cell).2) (fun cell _ => (hsample cell).1)).trans + (Nat.mul_le_mul_right _ hcell.1) + have hsourcec : (sources eb).2 ≤ K * (W + L + 3) := by + simpa only [sources] using hc + have hcellc : (canonicalMulWithWork (inversePowerTwo exponent) (nat (2 ^ eb))).2 + + (cells eb).2 ≤ queryCellScanBitBudget F exponent B := by + simpa only [cells, radius] using hcell.2.1 + have hcost := Nat.add_le_add_right + (Nat.add_le_add_right (Nat.add_le_add (Nat.add_le_add hcellc hsourcec) hm.1) exponent) 4 + simpa only [run, C] using And.intro hl hcost + have hl := (arithmeticFlatMapWithWork_length run scales.1 (K * L) + (fun eb heb => (hrun eb heb).1)).trans (Nat.mul_le_mul_right _ hs.2) + have hc := (arithmeticFlatMapWithWork_cost run scales.1 C (K * L) + (fun eb heb => (hrun eb heb).2) (fun eb heb => (hrun eb heb).1)).trans + (Nat.mul_le_mul_right _ hs.2) + have hr := (naturalCeilingWithWork_cost value).trans + (Nat.mul_le_mul_left 500 (Nat.pow_le_pow_left (Nat.add_le_add_right hv 1) 2)) + have hcost := Nat.add_le_add_right (Nat.add_le_add (Nat.add_le_add hs.1 hr) hc) 2 + simpa only [queryGroupSourceKeysWithWork, scales, radius, run, cells, sources, + queryGroupSourceKeysLength, queryGroupSourceKeysBitBudget, K, L, W, C] using And.intro hl hcost + +end EditApproximation.BinaryFraction + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryGroupSourceSpace.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryGroupSourceSpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..37be0a4d90ba26195356d34e0d88d3b42f9f60ef --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryGroupSourceSpace.lean @@ -0,0 +1,97 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryGroupSetupSpace +import OAI.Combinatorics.EditApproximation.Queries.QueryGroupSources +import OAI.Combinatorics.EditApproximation.Queries.QueryInitialSpace +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation.BinaryFraction + + + + + +theorem groupKeySampleBlockAllocation_le_work {M F Q : ℕ} (b : ℕ) (raw : List BinaryFraction) + (hs : raw.map value = groupDyadicScales M b F) (cell : ℕ × ℕ) + (scale : Fin (groupDyadicScales M b F).length) : + groupKeySampleBlockAllocation (Q := Q) b raw hs cell scale ≤ (groupKeySampleBlock (Q := Q) b raw hs cell scale).2 := by + let word := queryScaleAt raw (groupDyadicScales M b F) hs scale + let count := groupSampleCountWithWork M Q b word + have hc : bitWordValue count.1 = groupSampleCount M Q b (groupDyadicScaleAt M b F scale) := by + rw [groupSampleCountWithWork_value, queryScaleAt_value] + rfl + let coordinates := queryFinRange (bitWordValue count.1) + (groupSampleCount M Q b (groupDyadicScaleAt M b F scale)) hc + have hg := groupSampleCountAllocation_le_work M Q b word + have hm := arithmeticMapAllocation_with_spine (fun sample => + ((⟨(b, cell), scale, sample⟩ : GroupScalarKey M F Q), 2)) (fun _ => 2) coordinates (fun _ _ => le_rfl) + unfold groupKeySampleBlockAllocation groupKeySampleBlock + dsimp only [word, count, coordinates] at hg hm ⊢ + omega + + + +theorem queryGroupKeySamplesAllocation_le_work (M F Q eM eb eF : ℕ) + (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (cell : ℕ × ℕ) : + queryGroupKeySamplesAllocation M F Q eM eb eF hM hF cell ≤ + (queryGroupKeySamplesWithWork M F Q eM eb eF hM hF cell).2 := by + let b := 2 ^ eb + let scales := groupScalesWithWork eM eb eF + have hs : scales.1.map value = groupDyadicScales M b F := by + simpa only [nat_value] using computedGroupScales_value M b F eM eb eF hM rfl hF + have hlen : scales.1.length = (groupDyadicScales M b F).length := by + simpa only [List.length_map] using congrArg List.length hs + have hg := groupScalesAllocation_le_work eM eb eF + have hm := arithmeticFlatMapAllocation_le_work (groupKeySampleBlock (Q := Q) b scales.1 hs cell) + (groupKeySampleBlockAllocation (Q := Q) b scales.1 hs cell) + (queryFinRange scales.1.length (groupDyadicScales M b F).length hlen) + (fun scale _ => groupKeySampleBlockAllocation_le_work (Q := Q) b scales.1 hs cell scale) + change groupScalesAllocation eM eb eF + 2 * scales.1.length + eb + 1 + + arithmeticFlatMapAllocation (groupKeySampleBlock (Q := Q) b scales.1 hs cell) + (groupKeySampleBlockAllocation (Q := Q) b scales.1 hs cell) + (queryFinRange scales.1.length (groupDyadicScales M b F).length hlen) ≤ + scales.2 + 4 * scales.1.length + + (arithmeticFlatMapWithWork (groupKeySampleBlock (Q := Q) b scales.1 hs cell) + (queryFinRange scales.1.length (groupDyadicScales M b F).length hlen)).2 + eb + 4 + change groupScalesAllocation eM eb eF ≤ scales.2 at hg + omega + + + +theorem queryGroupSourceKeysAllocation_le_work {n : ℕ} (M N F Q exponent eM eF : ℕ) + (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (a value : BinaryFraction) (q : TargetInterval n) : + queryGroupSourceKeysAllocation M N F Q exponent eM eF hM hF a value q ≤ + (queryGroupSourceKeysWithWork M N F Q exponent eM eF hM hF a value q).2 := by + let radius := (naturalCeilingWithWork value).1 + let build := fun eb => + let side := canonicalMulWithWork (inversePowerTwo exponent) (nat (2 ^ eb)) + let cells := targetCellsWithWork side.1 (bitWordValue radius) q + let sources := arithmeticFlatMapWithWork (queryGroupKeySamplesWithWork M F Q eM eb eF hM hF) cells.1 + (sources.1, side.2 + cells.2 + sources.2 + eb + exponent + 4) + let allocation := fun eb => + let side := (canonicalMulWithWork (inversePowerTwo exponent) (nat (2 ^ eb))).1 + let cells := (targetCellsWithWork side (bitWordValue radius) q).1 + canonicalMulAllocation (inversePowerTwo exponent) (nat (2 ^ eb)) + targetCellsAllocation side (bitWordValue radius) q + + arithmeticFlatMapAllocation (queryGroupKeySamplesWithWork M F Q eM eb eF hM hF) + (queryGroupKeySamplesAllocation M F Q eM eb eF hM hF) cells + eb + exponent + 2 + have he := queryExponentsAllocation_le_work N F a value + have hr := naturalCeilingAllocation_le_work value + have hg := arithmeticFlatMapAllocation_le_work build allocation (queryExponentsWithWork N F a value).1 (by + intro eb _ + let side := (canonicalMulWithWork (inversePowerTwo exponent) (nat (2 ^ eb))).1 + have hs := canonicalMulAllocation_le_work (inversePowerTwo exponent) (nat (2 ^ eb)) + have hc := targetCellsAllocation_le_work side (bitWordValue radius) q + have hm := arithmeticFlatMapAllocation_le_work (queryGroupKeySamplesWithWork M F Q eM eb eF hM hF) + (queryGroupKeySamplesAllocation M F Q eM eb eF hM hF) + (targetCellsWithWork side (bitWordValue radius) q).1 + (fun cell _ => queryGroupKeySamplesAllocation_le_work M F Q eM eb eF hM hF cell) + dsimp only [build, allocation, side] at hc hm ⊢ + omega) + unfold queryGroupSourceKeysAllocation queryGroupSourceKeysWithWork + dsimp only [build, allocation, radius] at hg ⊢ + omega + +end EditApproximation.BinaryFraction + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryGroupSources.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryGroupSources.lean new file mode 100644 index 0000000000000000000000000000000000000000..729a722f5d46b746154295afdea07381d674a9c7 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryGroupSources.lean @@ -0,0 +1,60 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryGroupSamples +import OAI.Combinatorics.EditApproximation.Binary.BitQuery +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Complete scalar-source key generation uses the original dyadic +query window, cell order, scale order, and sample order. -/ + +namespace EditApproximation +namespace BinaryFraction + + + +theorem queryGroupSourceKeysWithWork_value {n : ℕ} (M N F Q exponent eM eF : ℕ) + (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (a value : BinaryFraction) + (q : TargetInterval n) : + (queryGroupSourceKeysWithWork M N F Q exponent eM eF hM hF a value q).1 = + groupScalarKeys M F Q (localGroupQueryKeys N F exponent a.value (fun _ => value.value) q) := by + simp only [queryGroupSourceKeysWithWork, arithmeticFlatMapWithWork_value, + targetCellsWithWork_value, canonicalMulWithWork_value, inversePowerTwo_value, nat_value, + naturalCeilingWithWork_value, queryGroupKeySamplesWithWork_value] + conv_rhs => unfold localGroupQueryKeys + rw [← queryExponentsWithWork_value N F a value] + simp only [groupScalarKeys, List.flatMap_map, List.flatMap_assoc, + List.flatMap_cons, List.flatMap_nil, List.append_nil] + +end BinaryFraction + + + +theorem queryGroupSourceGather_refines {ι β : Type*} {n : ℕ} {relation : β → ℚ → Prop} + (M N F Q exponent eM eF : ℕ) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) + (a : BinaryFraction) (initial : TargetInterval n → BinaryFraction × ℕ) (q : TargetInterval n) + (reader : GroupScalarKey M F Q → BitQuery ι BinaryFraction) + (expectedReader : GroupScalarKey M F Q → FiniteQuery ι) + (next : List (GroupScalarKey M F Q) → List BinaryFraction → BitQuery ι β) + (expectedNext : List (GroupScalarKey M F Q) → List ℚ → FiniteQuery ι) + (hr : ∀ key, BitQuery.Refines (fun word value => word.value = value) + (reader key) (expectedReader key)) + (hn : ∀ words, + let keys := groupScalarKeys M F Q + (localGroupQueryKeys N F exponent a.value (fun r => (initial r).1.value) q) + BitQuery.Refines relation (next keys words) (expectedNext keys (words.map BinaryFraction.value))) : + BitQuery.Refines relation + (queryGroupSourceGather M N F Q exponent eM eF hM hF a initial q reader next) + (let keys := groupScalarKeys M F Q + (localGroupQueryKeys N F exponent a.value (fun r => (initial r).1.value) q) + FiniteQuery.collect expectedReader keys (expectedNext keys)) := by + apply BitQuery.Refines.charge + change BitQuery.Refines relation (.charge _ _) _ + apply BitQuery.Refines.charge + change BitQuery.Refines relation (BitQuery.collect reader _ _) _ + rw [BinaryFraction.queryGroupSourceKeysWithWork_value] + exact BitQuery.Refines.collect reader expectedReader hr _ _ _ hn + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryHistoryBounds.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryHistoryBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..0157862b4150c84deb194f34f74e41b2d4346ca0 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryHistoryBounds.lean @@ -0,0 +1,100 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryHistoryInputs +import OAI.Combinatorics.EditApproximation.Binary.BinaryReadComposition + +namespace OAI + +/-! Cost of generating the earlier-history input list from child grids. +The bound counts the actual nested lists before duplicate removal. -/ + +namespace EditApproximation + +theorem arithmeticFlatMapWithWork_length {α β : Type*} (f : α → List β × ℕ) + (xs : List α) (L : ℕ) (hL : ∀ x ∈ xs, (f x).1.length ≤ L) : + (arithmeticFlatMapWithWork f xs).1.length ≤ xs.length * L := by + induction xs with + | nil => simp only [arithmeticFlatMapWithWork, List.length_nil, Nat.zero_mul, le_rfl] + | cons x xs ih => + have hx := hL x List.mem_cons_self + have ht := ih (fun y hy => hL y (List.mem_cons_of_mem _ hy)) + simp only [arithmeticFlatMapWithWork, List.length_append, List.length_cons, + Nat.add_mul, Nat.one_mul] + omega + +namespace BinaryFraction + +section History +variable {nx ny : ℕ} (M : ℕ) (parent : TargetInterval nx) (P history : ℕ) + (representatives : List (ℕ × TargetInterval ny)) (G C : ℕ) + (hgrid : ∀ br ∈ representatives, ∀ i : Fin M, + (wideChildGridWithWork parent br.2 br.1 P i).1.length ≤ G) + (hwork : ∀ br ∈ representatives, ∀ i : Fin M, + (wideChildGridWithWork parent br.2 br.1 P i).2 ≤ C) + +private def historyChildRun (br : ℕ × TargetInterval ny) (i : Fin M) := + let states := wideChildGridWithWork parent br.2 br.1 P i + let times := arithmeticFlatMapWithWork (fun t => + arithmeticMapWithWork (fun r => ((i, t, r), 1)) states.1) (List.range history) + (times.1, states.2 + times.2 + history + 2) + +include hgrid hwork in +private theorem historyChildRun_bounds (br : ℕ × TargetInterval ny) (hbr : br ∈ representatives) + (i : Fin M) : + (historyChildRun M parent P history br i).1.length ≤ history * G ∧ + (historyChildRun M parent P history br i).2 ≤ C + history * (5 * G + 3) + history + 2 := by + let states := wideChildGridWithWork parent br.2 br.1 P i + have hs : states.1.length ≤ G := hgrid br hbr i + have hc : states.2 ≤ C := hwork br hbr i + have hlen (t : ℕ) : + (arithmeticMapWithWork (fun r => ((i, t, r), 1)) states.1).1.length ≤ G := by + simpa only [arithmeticMapWithWork_value, List.length_map] using hs + have hcost (t : ℕ) : + (arithmeticMapWithWork (fun r => ((i, t, r), 1)) states.1).2 ≤ 4 * G := by + have h := arithmeticMapWithWork_cost (fun r => ((i, t, r), 1)) states.1 1 (fun _ _ => le_rfl) + simpa only [Nat.reduceAdd, Nat.mul_comm] using h.trans (Nat.mul_le_mul_right 4 hs) + have hl := arithmeticFlatMapWithWork_length + (fun t => arithmeticMapWithWork (fun r => ((i, t, r), 1)) states.1) + (List.range history) G (fun t _ => hlen t) + have hw := arithmeticFlatMapWithWork_cost + (fun t => arithmeticMapWithWork (fun r => ((i, t, r), 1)) states.1) + (List.range history) (4 * G) G (fun t _ => hcost t) (fun t _ => hlen t) + simp only [List.length_range] at hl hw + refine ⟨hl, ?_⟩ + change states.2 + (arithmeticFlatMapWithWork + (fun t => arithmeticMapWithWork (fun r => ((i, t, r), 1)) states.1) + (List.range history)).2 + history + 2 ≤ _ + have heq : 4 * G + G + 3 = 5 * G + 3 := by omega + rw [heq] at hw + omega + +include hgrid hwork in +theorem queryRawHistoryInputsWithWork_bounds : + (queryRawHistoryInputsWithWork M parent P history representatives).1.length ≤ + representatives.length * (M * (history * G)) ∧ + (queryRawHistoryInputsWithWork M parent P history representatives).2 ≤ + representatives.length * + (M * (C + history * (5 * G + 3) + history + 2 + history * G + 3) + + M * (history * G) + 3) + M + 1 := by + let run := fun br : ℕ × TargetInterval ny => arithmeticFlatMapWithWork (historyChildRun M parent P history br) (List.finRange M) + have one (br : ℕ × TargetInterval ny) (hbr : br ∈ representatives) : + (run br).1.length ≤ M * (history * G) ∧ + (run br).2 ≤ M * (C + history * (5 * G + 3) + history + 2 + history * G + 3) := by + have hl := arithmeticFlatMapWithWork_length (historyChildRun M parent P history br) + (List.finRange M) (history * G) + (fun i _ => (historyChildRun_bounds M parent P history representatives G C hgrid hwork br hbr i).1) + have hw := arithmeticFlatMapWithWork_cost (historyChildRun M parent P history br) + (List.finRange M) (C + history * (5 * G + 3) + history + 2) (history * G) + (fun i _ => (historyChildRun_bounds M parent P history representatives G C hgrid hwork br hbr i).2) + (fun i _ => (historyChildRun_bounds M parent P history representatives G C hgrid hwork br hbr i).1) + simpa only [List.length_finRange] using And.intro hl hw + have hl := arithmeticFlatMapWithWork_length run representatives (M * (history * G)) + (fun br hbr => (one br hbr).1) + have hw := arithmeticFlatMapWithWork_cost run representatives + (M * (C + history * (5 * G + 3) + history + 2 + history * G + 3)) (M * (history * G)) + (fun br hbr => (one br hbr).2) (fun br hbr => (one br hbr).1) + exact ⟨hl, Nat.add_le_add_right (Nat.add_le_add_right hw M) 1⟩ + +end History +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryHistoryBufferCost.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryHistoryBufferCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..0afd90f357c318aa762e35d9967150fafe5490d4 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryHistoryBufferCost.lean @@ -0,0 +1,46 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryHistoryInputCost +import OAI.Combinatorics.EditApproximation.Queries.QueryDataBuffers + +namespace OAI + +namespace EditApproximation.BinaryFraction + +theorem queryEarlierInputsWithWork_time {nx ny : ℕ} (M : ℕ) (parent : TargetInterval nx) + (N P F exponent history : ℕ) (hP : 0 < P) (a : BinaryFraction) + (initial : TargetInterval ny → BinaryFraction × ℕ) (q : TargetInterval ny) + (input : Fin M × ℕ × TargetInterval ny) + (hi : input ∈ (queryEarlierInputsWithWork M parent N P F exponent history hP a initial q).1) : + input.2.1 < history := by + simp only [queryEarlierInputsWithWork, queryOrderedHistoryInputsWithWork_value] at hi + have hm := (mem_orderedInputs historyInputCode (historyInputCode_injective M ny) _ input).mp hi + rw [List.mem_toFinset] at hm + exact queryRawHistoryInputsWithWork_time M parent P history hP _ input hm + +def queryEarlierBufferReadBudget (M P F exponent history B : ℕ) : ℕ := + 1 + queryHistoryInputsLength M P history (queryEarlierRepresentativesLength P F exponent B) * (32 * B + 12) + +theorem queryEarlierInputsWithWork_readCost {nx ny : ℕ} (M N P F exponent history B Rp : ℕ) + (parent : TargetInterval nx) (hP : 0 < P) (a : BinaryFraction) + (initial : TargetInterval ny → BinaryFraction × ℕ) (q : TargetInterval ny) + (words : List BinaryFraction) + (hB : 8 ≤ B) (hN : Nat.size N ≤ B) (hF : Nat.size F + 2 ≤ B) (hFpos : 1 ≤ F) + (hPb : Nat.size P ≤ B) (hnx : Nat.size nx ≤ B) (hny : Nat.size ny ≤ B) + (hM : Nat.size M ≤ B) (ht : Nat.size history ≤ B) (he : exponent + 1 ≤ B) (ha : a.width ≤ B) + (hi : ∀ r, (initial r).1.width ≤ B) (hR : ∀ r, (initial r).2 ≤ Rp) + (hw : 0 ≤ (initial q).1.value) (hPd : ∃ e : ℕ, P = 2 ^ e) : + ∀ s ≤ history, ∀ input, + (queryHistoryReadWithWork + (queryEarlierInputsWithWork M parent N P F exponent history hP a initial q).1 words s input).2 ≤ + queryEarlierBufferReadBudget M P F exponent history B := by + intro s hs input + have hlen := (queryEarlierInputsWithWork_bounds M N P F exponent history B Rp parent hP a initial q + hB hN hF hFpos hPb hnx hny hM ht he ha hi hR hw hPd).1 + have hread := queryHistoryReadWithWork_cost + (queryEarlierInputsWithWork M parent N P F exponent history hP a initial q).1 words s input B hM hny + ((Nat.size_le_size hs).trans ht) (fun key hk => + (Nat.size_le_size (queryEarlierInputsWithWork_time M parent N P F exponent history hP a initial q key hk).le).trans ht) + exact hread.trans (Nat.add_le_add_left (Nat.mul_le_mul_right _ hlen) 1) + +end EditApproximation.BinaryFraction + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryHistoryCodeBounds.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryHistoryCodeBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..f5f8733e70e7a1c101de0d4350cb195ac86bd5eb --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryHistoryCodeBounds.lean @@ -0,0 +1,99 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryCodeBounds +import OAI.Combinatorics.EditApproximation.Queries.QueryScopedOrder + +namespace OAI + +/-! Word and comparison bounds for the actual finite history-key lists. -/ + +namespace EditApproximation + +theorem queryPairWithWork_bounds (a b B : ℕ) (ha : Nat.size a ≤ B) (hb : Nat.size b ≤ B) : + Nat.size (queryPairWithWork a b).1 ≤ 5 * (B + 1) ∧ + (queryPairWithWork a b).2 ≤ 10000 * (B + 1) ^ 2 := by + have haa : Nat.size (a * a) ≤ 3 * B + 1 := by + have h := queryNaturalMul_size a a + omega + have hbb : Nat.size (b * b) ≤ 3 * B + 1 := by + have h := queryNaturalMul_size b b + omega + have hl : Nat.size (a * a + a) ≤ 4 * B + 2 := by + have h := queryNaturalAdd_size (a * a) a + omega + have ho : Nat.size (a * a + a + b) ≤ 5 * B + 3 := by + have h := queryNaturalAdd_size (a * a + a) b + omega + have hp : Nat.size (b * b + a) ≤ 4 * B + 2 := by + have h := queryNaturalAdd_size (b * b) a + omega + let K := 5 * (B + 1) + have haK : Nat.size a ≤ K := by dsimp [K]; omega + have hbK : Nat.size b ≤ K := by dsimp [K]; omega + have haaK : Nat.size (a * a) ≤ K := by dsimp [K]; omega + have hbbK : Nat.size (b * b) ≤ K := by dsimp [K]; omega + have hlK : Nat.size (a * a + a) ≤ K := by dsimp [K]; omega + have ca := queryNaturalMul_cost a a K haK haK + have cb := queryNaturalMul_cost b b K hbK hbK + have cl := queryNaturalAdd_cost (a * a) a K haaK haK + have co := queryNaturalAdd_cost (a * a + a) b K hlK hbK + have cp := queryNaturalAdd_cost (b * b) a K hbbK haK + have ct := binaryNaturalCompareWithWork_cost a b + dsimp only [K] at ca cb cl co cp + unfold queryPairWithWork + dsimp only + split_ifs <;> simp only [binaryNaturalMulWithWork_value, binaryNaturalAddWithWork_value] + · exact ⟨by omega, by nlinarith only [cb, cp, ct, ha, hb, Nat.zero_le B]⟩ + · exact ⟨by omega, by nlinarith only [ca, cl, co, ct, ha, hb, Nat.zero_le B]⟩ + +theorem queryHistoryCodeWithWork_bounds {M n : ℕ} (input : Fin M × ℕ × TargetInterval n) + (B : ℕ) (hM : Nat.size M ≤ B) (hn : Nat.size n ≤ B) (ht : Nat.size input.2.1 ≤ B) : + Nat.size (queryHistoryCodeWithWork input).1 ≤ 50 * (B + 1) ∧ + (queryHistoryCodeWithWork input).2 ≤ 1000000 * (B + 1) ^ 2 := by + have hc := queryChildCodeWithWork_bounds (input.1, input.2.2) B hM hn + have ht' : Nat.size input.2.1 ≤ 8 * (B + 1) := by omega + have hp := queryPairWithWork_bounds input.2.1 + (queryChildCodeWithWork (input.1, input.2.2)).1 (8 * (B + 1)) ht' hc.1 + constructor + · exact hp.1.trans (by omega) + · change (queryChildCodeWithWork (input.1, input.2.2)).2 + + (queryPairWithWork input.2.1 (queryChildCodeWithWork (input.1, input.2.2)).1).2 + 1 ≤ _ + nlinarith only [hc.2, hp.2, Nat.zero_le B] + +theorem queryHistoryEqualWithWork_cost {M n : ℕ} (a b : Fin M × ℕ × TargetInterval n) + (B : ℕ) (hM : Nat.size M ≤ B) (hn : Nat.size n ≤ B) + (ha : Nat.size a.2.1 ≤ B) (hb : Nat.size b.2.1 ≤ B) : + (queryHistoryEqualWithWork a b).2 ≤ 32 * B + 11 := by + have hc := coordinateEqualWithWork_cost (a.1, a.2.2) (b.1, b.2.2) B hM hn + have ht := naturalEqualWithWork_cost a.2.1 b.2.1 B ha hb + change _ + _ + 1 ≤ _ + omega + +theorem queryHistoryOrderWithWork_cost {M n : ℕ} (a b : Fin M × ℕ × TargetInterval n) + (B : ℕ) (hM : Nat.size M ≤ B) (hn : Nat.size n ≤ B) + (ha : Nat.size a.2.1 ≤ B) (hb : Nat.size b.2.1 ≤ B) : + (queryEncodedLEWithWork queryHistoryCodeWithWork a b).2 ≤ 2001000 * (B + 1) ^ 2 := by + have ca := queryHistoryCodeWithWork_bounds a B hM hn ha + have cb := queryHistoryCodeWithWork_bounds b B hM hn hb + have h := queryEncodedLEWithWork_cost queryHistoryCodeWithWork a b + (1000000 * (B + 1) ^ 2) (50 * (B + 1)) ca.2 cb.2 ca.1 cb.1 + nlinarith only [h, Nat.zero_le B] + +theorem queryOrderedHistoryInputsWithWork_cost {M n : ℕ} + (inputs : List (Fin M × ℕ × TargetInterval n)) (B : ℕ) + (hM : Nat.size M ≤ B) (hn : Nat.size n ≤ B) + (ht : ∀ input ∈ inputs, Nat.size input.2.1 ≤ B) : + (queryOrderedHistoryInputsWithWork inputs).2 ≤ + (inputs.length + 1) ^ 2 * (2002000 * (B + 1) ^ 2) := by + have h := queryOrderedInputsWithWork_cost_on (fun input : Fin M × ℕ × TargetInterval n => + Nat.size input.2.1 ≤ B) historyInputCode queryHistoryEqualWithWork + (queryEncodedLEWithWork queryHistoryCodeWithWork) queryHistoryEqualWithWork_value + (fun a b => by simp only [queryEncodedLEWithWork_value, queryHistoryCodeWithWork_value]) + (32 * B + 11) (2001000 * (B + 1) ^ 2) + (fun a ha b hb => queryHistoryEqualWithWork_cost a b B hM hn ha hb) + (fun a ha b hb => queryHistoryOrderWithWork_cost a b B hM hn ha hb) inputs ht + apply h.trans + gcongr + nlinarith only [Nat.zero_le B] + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryHistoryInputCost.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryHistoryInputCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..05e27b55df7c0be0fd000f0bf20cb43f5ae2558b --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryHistoryInputCost.lean @@ -0,0 +1,98 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryBandInputCost +import OAI.Combinatorics.EditApproximation.Queries.QueryHistoryCodeBounds + +namespace OAI + +namespace EditApproximation.BinaryFraction + +theorem queryRawHistoryInputsWithWork_time {nx ny : ℕ} (M : ℕ) (parent : TargetInterval nx) + (P history : ℕ) (hP : 0 < P) (representatives : List (ℕ × TargetInterval ny)) + (input : Fin M × ℕ × TargetInterval ny) + (hi : input ∈ (queryRawHistoryInputsWithWork M parent P history representatives).1) : + input.2.1 < history := by + rw [queryRawHistoryInputsWithWork_value M parent P history hP] at hi + obtain ⟨br, _, hi⟩ := List.mem_flatMap.mp hi + obtain ⟨i, _, hi⟩ := List.mem_flatMap.mp hi + obtain ⟨t, ht, hi⟩ := List.mem_flatMap.mp hi + obtain ⟨r, _, rfl⟩ := List.mem_map.mp hi + exact List.mem_range.mp ht + +def queryHistoryInputsLength (M P history count : ℕ) : ℕ := + count * (M * (history * (40 * P + 2) ^ 2)) + +def queryRawHistoryInputsBitBudget (M P history count B : ℕ) : ℕ := + let G := (40 * P + 2) ^ 2 + let C := wideChildGridBitBudget P (B + 1) + count * (M * (C + history * (5 * G + 3) + history + 2 + history * G + 3) + + M * (history * G) + 3) + M + 1 + +theorem queryRawHistoryInputsWithWork_dyadic_bounds {nx ny : ℕ} + (M N P history count B : ℕ) (parent : TargetInterval nx) (hP : 0 < P) + (representatives : List (ℕ × TargetInterval ny)) (hl : representatives.length ≤ count) + (hs : ∀ br ∈ representatives, br.1 ∈ dyadicScales N) + (hN : Nat.size N ≤ B) (hnx : Nat.size nx ≤ B) (hny : Nat.size ny ≤ B) + (hM : Nat.size M ≤ B) (hPb : Nat.size P ≤ B) : + (queryRawHistoryInputsWithWork M parent P history representatives).1.length ≤ + queryHistoryInputsLength M P history count ∧ + (queryRawHistoryInputsWithWork M parent P history representatives).2 ≤ + queryRawHistoryInputsBitBudget M P history count B := by + have hb := queryRawHistoryInputsWithWork_bounds M parent P history representatives + ((40 * P + 2) ^ 2) (wideChildGridBitBudget P (B + 1)) + (fun br _ i => by rw [wideChildGridWithWork_value _ _ _ _ _ hP]; exact wideChildStateList_length_le parent br.2 hP i) + (fun br hbr i => wideChildGridWithWork_cost parent br.2 br.1 P (B + 1) i hP + (by omega) (by omega) (by omega) + ((dyadicScales_size_bound N br.1 (hs br hbr)).trans (by omega)) (by omega)) + constructor + · exact hb.1.trans (Nat.mul_le_mul_right _ hl) + · apply hb.2.trans + unfold queryRawHistoryInputsBitBudget + dsimp only + gcongr + +theorem queryOrderedHistoryInputsWithWork_length {M n : ℕ} + (inputs : List (Fin M × ℕ × TargetInterval n)) : + (queryOrderedHistoryInputsWithWork inputs).1.length ≤ inputs.length := by + rw [queryOrderedHistoryInputsWithWork_value, orderedInputs_length] + exact List.toFinset_card_le _ + +def queryEarlierInputsBitBudget (M P F exponent history B R : ℕ) : ℕ := + let count := queryEarlierRepresentativesLength P F exponent B + queryEarlierRepresentativesBitBudget P F exponent B R + + queryRawHistoryInputsBitBudget M P history count B + + (queryHistoryInputsLength M P history count + 1) ^ 2 * (2002000 * (B + 1) ^ 2) + 2 + +theorem queryEarlierInputsWithWork_bounds {nx ny : ℕ} (M N P F exponent history B R : ℕ) + (parent : TargetInterval nx) (hP : 0 < P) (a : BinaryFraction) + (initial : TargetInterval ny → BinaryFraction × ℕ) (q : TargetInterval ny) + (hB : 8 ≤ B) (hN : Nat.size N ≤ B) (hF : Nat.size F + 2 ≤ B) (hFpos : 1 ≤ F) + (hPb : Nat.size P ≤ B) (hnx : Nat.size nx ≤ B) (hny : Nat.size ny ≤ B) + (hM : Nat.size M ≤ B) (ht : Nat.size history ≤ B) (he : exponent + 1 ≤ B) (ha : a.width ≤ B) + (hi : ∀ r, (initial r).1.width ≤ B) (hR : ∀ r, (initial r).2 ≤ R) + (hw : 0 ≤ (initial q).1.value) (hPd : ∃ e : ℕ, P = 2 ^ e) : + (queryEarlierInputsWithWork M parent N P F exponent history hP a initial q).1.length ≤ + queryHistoryInputsLength M P history (queryEarlierRepresentativesLength P F exponent B) ∧ + (queryEarlierInputsWithWork M parent N P F exponent history hP a initial q).2 ≤ + queryEarlierInputsBitBudget M P F exponent history B R := by + let representatives := queryEarlierRepresentativesWithWork N P F exponent hP a initial q + let raw := queryRawHistoryInputsWithWork M parent P history representatives.1 + let count := queryEarlierRepresentativesLength P F exponent B + have hr := queryEarlierRepresentativesWithWork_bounds N P F exponent B R hP a initial q + hB hN hF hFpos hPb hny he ha hi hR hw hPd + have hraw := queryRawHistoryInputsWithWork_dyadic_bounds M N P history count B parent hP + representatives.1 hr.1 + (fun br hb => queryEarlierRepresentativesWithWork_scale N P F exponent hP a initial q R hR br hb) + hN hnx hny hM hPb + have hsort := queryOrderedHistoryInputsWithWork_cost raw.1 B hM hny (fun input hin => + (Nat.size_le_size (queryRawHistoryInputsWithWork_time M parent P history hP + representatives.1 input hin).le).trans ht) + have hsort' := hsort.trans (Nat.mul_le_mul_right _ + (Nat.pow_le_pow_left (Nat.add_le_add_right hraw.1 1) 2)) + constructor + · simpa only [queryEarlierInputsWithWork] using + (queryOrderedHistoryInputsWithWork_length raw.1).trans hraw.1 + · simpa only [queryEarlierInputsWithWork, queryEarlierInputsBitBudget] using + Nat.add_le_add_right (Nat.add_le_add (Nat.add_le_add hr.2 hraw.2) hsort') 2 + +end EditApproximation.BinaryFraction + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryHistoryInputs.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryHistoryInputs.lean new file mode 100644 index 0000000000000000000000000000000000000000..1d50b7a07c2111b11ffbab2f8d1390f879344853 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryHistoryInputs.lean @@ -0,0 +1,55 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryInputCodes +import OAI.Combinatorics.EditApproximation.Queries.QueryRepresentatives +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! The earlier-history cover is materialized from its small coordinate +lists, then sorted by the original history encoding. It never enumerates +the much larger Cartesian set of complete wide actions. -/ + +namespace EditApproximation +namespace BinaryFraction + + + +@[simp] theorem queryRawHistoryInputsWithWork_value {nx ny : ℕ} (M : ℕ) + (parent : TargetInterval nx) (P history : ℕ) (hP : 0 < P) + (representatives : List (ℕ × TargetInterval ny)) : + (queryRawHistoryInputsWithWork M parent P history representatives).1 = + representatives.flatMap (fun br => (List.finRange M).flatMap fun i => + (List.range history).flatMap fun t => + (wideChildStateList parent br.2 br.1 P i).map fun r => (i, t, r)) := by + simp only [queryRawHistoryInputsWithWork, arithmeticFlatMapWithWork_value, + arithmeticMapWithWork_value, wideChildGridWithWork_value _ _ _ _ _ hP] + +theorem queryRawHistoryInputsWithWork_cover {nx ny : ℕ} (M : ℕ) + (parent : TargetInterval nx) (P history : ℕ) (hP : 0 < P) + (representatives : List (ℕ × TargetInterval ny)) : + (queryRawHistoryInputsWithWork M parent P history representatives).1.toFinset = + wideEarlierInputCover parent P history representatives := by + rw [queryRawHistoryInputsWithWork_value M parent P history hP] + ext input + simp only [List.mem_toFinset, List.mem_flatMap, List.mem_finRange, true_and, + List.mem_range, List.mem_map, wideEarlierInputCover, Finset.mem_biUnion, + Finset.mem_univ, Finset.mem_range, Finset.mem_image] + + + +theorem queryEarlierInputsWithWork_value {nx ny : ℕ} (M : ℕ) (parent : TargetInterval nx) + (N P F exponent history : ℕ) (hP : 0 < P) (a : BinaryFraction) + (initial : TargetInterval ny → BinaryFraction × ℕ) (q : TargetInterval ny) + (R : ℕ) (hR : ∀ r, (initial r).2 ≤ R) : + (queryEarlierInputsWithWork M parent N P F exponent history hP a initial q).1 = + orderedInputs historyInputCode (historyInputCode_injective M ny) + (queryEarlierInputCover parent N P F exponent history a.value + (fun r => (initial r).1.value) q) := by + simp only [queryEarlierInputsWithWork, queryOrderedHistoryInputsWithWork_value, + queryRawHistoryInputsWithWork_cover _ _ _ _ hP, + queryEarlierRepresentativesWithWork_value _ _ _ _ hP _ _ _ R hR, queryEarlierInputCover] + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryHistorySemantic.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryHistorySemantic.lean new file mode 100644 index 0000000000000000000000000000000000000000..750bd6c71d89ef8c502dd562d925690aededda0c --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryHistorySemantic.lean @@ -0,0 +1,68 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryPhysicalReaders +import OAI.Combinatorics.EditApproximation.Geometry.LocalSeedSequence + +namespace OAI + +namespace EditApproximation +section History +variable {α : Type*} [DecidableEq α] {M J R : ℕ} [NeZero R] + (source target : List α) (N P F exponent H Q T S copies : ℕ) + (factor : ℕ → ℚ) (multiplier : ℕ → ℕ) (tau eta kappa delta : ℚ) + (group : ℕ → ℕ → PhysicalInternalNode M J → Fin R → CellGroupDraws M F Q) + (integer : ℕ → ℕ → PhysicalInternalNode M J → Fin R → ℕ → TargetInterval target.length → ℕ) + (initial : PhysicalEntry M J target.length → ℕ) + +local notation "requestValue" => localRequestValue source target N P F exponent H Q T S copies + factor multiplier tau eta kappa delta group integer initial +local notation "seed" pass => localSeedSequence source target N P F exponent H Q T S copies + factor multiplier tau eta kappa delta group integer initial pass + +theorem localRequestValue_bounds (hdelta : 0 ≤ delta) (request : PhysicalTableRequest M J target.length) : + 0 ≤ requestValue request ∧ requestValue request ≤ + stageInitial source target (seed request.pass) N P F (factor request.pass) (request.node, request.state) := by + unfold localRequestValue unifiedPhysicalValue + dsimp only + split + · exact physicalLocalWarmup_bounds source target _ N P F _ _ _ + · exact physicalLocalRefinement_bounds source target _ N P F exponent Q _ tau delta T hdelta _ _ _ _ _ + +theorem queryPhysicalEarlierRead_history_bound + (passes pass copy t : ℕ) (ht : 0 < t) (htS : t ≤ S) + (hpass : pass < passes) (hcopy : copy < copies) (hdelta : 0 ≤ delta) + (node : PhysicalNode M J) (hbelow : node.1.val < J) (q : TargetInterval target.length) + (oracle : {child : PhysicalTableRequest M J target.length // child.combinedRank T S < + (PhysicalTableRequest.refinement pass copy node T t q).combinedRank T S} → BinaryFraction) + (hread : ∀ key, key.val.Bounded passes copies T S → (oracle key).value = requestValue key.val) + (input : Fin M × ℕ × TargetInterval target.length) : + ((queryPhysicalEarlierRead copies pass copy T S t node hbelow q input).value oracle).value ≤ + ((queryPhysicalWarmupRead copies pass copy T S t ht node q + (physicalChild node hbelow input.1) (by change node.1.val ≤ node.1.val + 1; omega) + 0 (Nat.zero_le T) input.2.2).value oracle).value := by + have hinit : + ((queryPhysicalWarmupRead copies pass copy T S t ht node q + (physicalChild node hbelow input.1) (by change node.1.val ≤ node.1.val + 1; omega) + 0 (Nat.zero_le T) input.2.2).value oracle).value = + stageInitial source target (seed pass) N P F (factor pass) + (physicalChild node hbelow input.1, input.2.2) := by + change (oracle _).value = _ + rw [hread _ ⟨hpass, hcopy, Nat.zero_le _⟩] + rw [localRequestValue_warmup source target N P F exponent H Q T S copies factor multiplier + tau eta kappa delta group integer initial pass copy _ 0 (Nat.zero_le T)] + rfl + rw [hinit] + unfold queryPhysicalEarlierRead + simp only [BitQuery.value] + split + · rename_i htime + have htime' := (binaryNaturalCompareWithWork_lt _ _).mp htime + change (oracle _).value ≤ _ + rw [hread _ ⟨hpass, hcopy, by change T + input.2.1 ≤ T + S; omega⟩] + exact (localRequestValue_bounds source target N P F exponent H Q T S copies factor multiplier + tau eta kappa delta group integer initial hdelta _).2 + · simp only [BitQuery.value, BinaryFraction.nat_value, Nat.cast_zero] + exact stageInitial_nonneg_all_seeds source target (seed pass) N P F (factor pass) _ + +end History +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryHistorySpace.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryHistorySpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..6375f47c22f55e02e5e6b2ee8de7ff70d52d1dd5 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryHistorySpace.lean @@ -0,0 +1,123 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryInitialSpace +import OAI.Combinatorics.EditApproximation.Queries.QueryLocalRepresentativeSpace +import OAI.Combinatorics.EditApproximation.Queries.QueryHistoryInputs +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation.BinaryFraction + + + +theorem queryEarlierRepresentativesAllocation_le_work {n : ℕ} (N P F exponent : ℕ) (hP : 0 < P) + (a : BinaryFraction) (initial : TargetInterval n → BinaryFraction × ℕ) + (allocation : TargetInterval n → ℕ) (q : TargetInterval n) + (h : ∀ r, allocation r ≤ (initial r).2) : + queryEarlierRepresentativesAllocation N P F exponent hP a initial allocation q ≤ + (queryEarlierRepresentativesWithWork N P F exponent hP a initial q).2 := by + let build := fun key : ℕ × ℕ × ℕ => + let centers := cellCentersReadWithWork P F key.1 a (inversePowerTwo exponent) initial key.2 + let labeled := arithmeticMapWithWork (fun r => ((key.1, r), 1)) centers.1 + (labeled.1, centers.2 + labeled.2 + 1) + have hq := h q + have hr := localRepresentativeReadAllocation_le_work N P F a initial allocation q h + have hg := queryGroupKeysAllocation_le_work N F exponent a (initial q).1 q + have hc := arithmeticFlatMapAllocation_le_work build (fun key => + cellCentersReadAllocation P F key.1 a (inversePowerTwo exponent) initial allocation key.2 + + arithmeticMapAllocation (fun _ => 1) + (cellCentersReadWithWork P F key.1 a (inversePowerTwo exponent) initial key.2).1) + (queryGroupKeysWithWork N F exponent a (initial q).1 q).1 (by + intro key _ + have hh := cellCentersReadAllocation_le_work P F key.1 a (inversePowerTwo exponent) initial allocation key.2 h + have hm := arithmeticMapAllocation_le_work (fun r => ((key.1, r), 1)) (fun _ => 1) + (cellCentersReadWithWork P F key.1 a (inversePowerTwo exponent) initial key.2).1 (fun _ _ => le_rfl) + dsimp only [build] + omega) + have ho := queryOnlineKeysAllocation_le_work N P F hP a (initial q).1 q + unfold queryEarlierRepresentativesAllocation queryEarlierRepresentativesWithWork + dsimp only [build] at hc ⊢ + omega + + + +theorem queryWideInputsAllocation_le_work {nx ny : ℕ} (M : ℕ) (parent : TargetInterval nx) (P : ℕ) + (representatives : List (ℕ × TargetInterval ny)) : + queryWideInputsAllocation M parent P representatives ≤ (queryWideInputsWithWork M parent P representatives).2 := by + let child := fun (br : ℕ × TargetInterval ny) (i : Fin M) => + let states := wideChildGridWithWork parent br.2 br.1 P i + let labeled := arithmeticMapWithWork (fun r => ((i, r), 1)) states.1 + (labeled.1, states.2 + labeled.2 + 1) + let one := fun (br : ℕ × TargetInterval ny) (i : Fin M) => + wideChildGridAllocation parent br.2 br.1 P i + + arithmeticMapAllocation (fun _ => 1) (wideChildGridWithWork parent br.2 br.1 P i).1 + have hchild (br : ℕ × TargetInterval ny) (i : Fin M) : one br i ≤ (child br i).2 := by + have hw := wideChildGridAllocation_le_work parent br.2 br.1 P i + have hm := arithmeticMapAllocation_le_work (fun r => ((i, r), 1)) (fun _ => 1) + (wideChildGridWithWork parent br.2 br.1 P i).1 (fun _ _ => le_rfl) + dsimp only [one, child] + omega + have hw := arithmeticFlatMapAllocation_le_work + (fun br => arithmeticFlatMapWithWork (child br) (List.finRange M)) + (fun br => arithmeticFlatMapAllocation (child br) (one br) (List.finRange M)) representatives + (fun br _ => arithmeticFlatMapAllocation_le_work (child br) (one br) (List.finRange M) (fun i _ => hchild br i)) + have he := queryEraseAllocation_le_work coordinateEqualWithWork coordinateEqualAllocation + (arithmeticFlatMapWithWork (fun br => arithmeticFlatMapWithWork (child br) (List.finRange M)) representatives).1 + coordinateEqualAllocation_le_work + unfold queryWideInputsAllocation queryWideInputsWithWork + dsimp only [child, one] at hw he ⊢ + omega + + + +theorem queryRawHistoryInputsAllocation_le_work {nx ny : ℕ} (M : ℕ) (parent : TargetInterval nx) + (P history : ℕ) (representatives : List (ℕ × TargetInterval ny)) : + queryRawHistoryInputsAllocation M parent P history representatives ≤ + (queryRawHistoryInputsWithWork M parent P history representatives).2 := by + let child := fun (br : ℕ × TargetInterval ny) (i : Fin M) => + let states := wideChildGridWithWork parent br.2 br.1 P i + let times := arithmeticFlatMapWithWork (fun t => + arithmeticMapWithWork (fun r => ((i, t, r), 1)) states.1) (List.range history) + (times.1, states.2 + times.2 + history + 2) + let one := fun (br : ℕ × TargetInterval ny) (i : Fin M) => + wideChildGridAllocation parent br.2 br.1 P i + history + + arithmeticFlatMapAllocation (fun t => arithmeticMapWithWork (fun r => ((i, t, r), 1)) + (wideChildGridWithWork parent br.2 br.1 P i).1) + (fun _ => arithmeticMapAllocation (fun _ => 1) (wideChildGridWithWork parent br.2 br.1 P i).1) + (List.range history) + have hchild (br : ℕ × TargetInterval ny) (i : Fin M) : one br i ≤ (child br i).2 := by + have hw := wideChildGridAllocation_le_work parent br.2 br.1 P i + have ht := arithmeticFlatMapAllocation_le_work + (fun t => arithmeticMapWithWork (fun r => ((i, t, r), 1)) (wideChildGridWithWork parent br.2 br.1 P i).1) + (fun _ => arithmeticMapAllocation (fun _ => 1) (wideChildGridWithWork parent br.2 br.1 P i).1) + (List.range history) (fun _ _ => arithmeticMapAllocation_le_work _ _ _ (fun _ _ => le_rfl)) + dsimp only [one, child] + omega + have hall := arithmeticFlatMapAllocation_le_work + (fun br => arithmeticFlatMapWithWork (child br) (List.finRange M)) + (fun br => arithmeticFlatMapAllocation (child br) (one br) (List.finRange M)) representatives + (fun br _ => arithmeticFlatMapAllocation_le_work (child br) (one br) (List.finRange M) (fun i _ => hchild br i)) + unfold queryRawHistoryInputsAllocation queryRawHistoryInputsWithWork + dsimp only [child, one] at hall ⊢ + omega + + + +theorem queryEarlierInputsAllocation_le_work {nx ny : ℕ} (M : ℕ) (parent : TargetInterval nx) + (N P F exponent history : ℕ) (hP : 0 < P) (a : BinaryFraction) + (initial : TargetInterval ny → BinaryFraction × ℕ) (allocation : TargetInterval ny → ℕ) + (q : TargetInterval ny) (h : ∀ r, allocation r ≤ (initial r).2) : + queryEarlierInputsAllocation M parent N P F exponent history hP a initial allocation q ≤ + (queryEarlierInputsWithWork M parent N P F exponent history hP a initial q).2 := by + have hr := queryEarlierRepresentativesAllocation_le_work N P F exponent hP a initial allocation q h + have hw := queryRawHistoryInputsAllocation_le_work M parent P history + (queryEarlierRepresentativesWithWork N P F exponent hP a initial q).1 + have ho := queryOrderedHistoryInputsAllocation_le_work + (queryRawHistoryInputsWithWork M parent P history (queryEarlierRepresentativesWithWork N P F exponent hP a initial q).1).1 + unfold queryEarlierInputsAllocation queryEarlierInputsWithWork + dsimp only + omega + +end EditApproximation.BinaryFraction + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryIndexedSlice.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryIndexedSlice.lean new file mode 100644 index 0000000000000000000000000000000000000000..3ed28361bb39b1bd93ba9b08e05135a35507573b --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryIndexedSlice.lean @@ -0,0 +1,65 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryIndexedLeaf +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalLeaves +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! A terminal source interval is accessed through its stored endpoint. +Its substring is used only in the specification, never materialized. -/ + +namespace EditApproximation + + + +@[simp] theorem querySliceHeadWithWork_value {α : Type*} (source : List α) + (interval : TargetInterval source.length) : + (querySliceHeadWithWork source interval).1 = (substring source interval.lo interval.hi).head? := by + unfold querySliceHeadWithWork substring + dsimp only + rw [List.head?_drop, List.getElem?_take] + by_cases h : interval.lo < interval.hi + · rw [ite_eq_left ((binaryNaturalCompareWithWork_lt _ _).mpr h), ite_eq_left h] + · rw [ite_eq_right (fun hc => h ((binaryNaturalCompareWithWork_lt _ _).mp hc)), ite_eq_right h] + +theorem querySliceHeadWithWork_cost {α : Type*} (source : List α) + (interval : TargetInterval source.length) (B : ℕ) (hB : Nat.size source.length ≤ B) : + (querySliceHeadWithWork source interval).2 ≤ 10 * B + 4 := by + have hl := (Nat.size_le_size (interval.ordered.trans interval.valid)).trans hB + have hh := (Nat.size_le_size interval.valid).trans hB + have hc := binaryNaturalCompareWithWork_cost interval.lo interval.hi + change _ + _ + _ + 3 ≤ _ + omega + + + +theorem queryIndexedSliceWithWork_value (source target : List ℕ) + (interval : TargetInterval source.length) (q : TargetInterval target.length) + (symbolBits positionBits : ℕ) + (hs : ∀ a ∈ source, a < 2 ^ symbolBits) (ht : ∀ a ∈ target, a < 2 ^ symbolBits) + (hp : target.length ≤ 2 ^ positionBits) : + (queryIndexedSliceWithWork source interval target.length q + (occurrenceBuild symbolBits positionBits target.zipIdx) symbolBits positionBits).1.value = + (shortSourceCost (substring source interval.lo interval.hi) (substring target q.lo q.hi) : ℚ) := by + simp only [queryIndexedSliceWithWork, binaryIndexedLeafWithWork_value, querySliceHeadWithWork_value] + congr 1 + apply indexedLeafCost_eq symbolBits positionBits _ target _ ht hp q.lo q.hi q.ordered q.valid + intro a ha + exact hs a (List.mem_of_mem_take (List.mem_of_mem_drop ha)) + +theorem queryIndexedSliceWithWork_cost (source : List ℕ) + (interval : TargetInterval source.length) (targetLength : ℕ) (q : TargetInterval targetLength) + (occurrence : BinaryMemo PositionCounts) (symbolBits positionBits B : ℕ) + (hB : Nat.size source.length ≤ B) : + (queryIndexedSliceWithWork source interval targetLength q occurrence symbolBits positionBits).2 ≤ + 10 * B + 2 * symbolBits + 4 * positionBits + Nat.size (targetLength + 1) + 17 := by + have hs := querySliceHeadWithWork_cost source interval B hB + have hr := (binaryIndexedLeafWithWork_bounds occurrence symbolBits positionBits + (querySliceHeadWithWork source interval).1 q.lo q.hi).2 + have hh := Nat.size_le_size (Nat.add_le_add_right q.valid 1) + change (querySliceHeadWithWork source interval).2 + _ + 1 ≤ _ + omega + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryIndexedSpace.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryIndexedSpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..fef2b2fecd2dbc8ab173f3e848959166e8c24a5d --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryIndexedSpace.lean @@ -0,0 +1,54 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryGatherSpace +import OAI.Combinatorics.EditApproximation.Queries.QueryIndexedSlice +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation + +/-- The occurrence key, two prefix traversals and scalar result cells. +The occurrence trie itself is borrowed from preprocessing. -/ + + +theorem indexedLeafAllocation_le_work (table : BinaryMemo PositionCounts) (symbolBits positionBits : ℕ) + (symbol : Option ℕ) (lo hi : ℕ) : + indexedLeafAllocation symbolBits positionBits symbol lo hi ≤ + (indexedLeafWithWork table symbolBits positionBits symbol lo hi).2 := by + cases symbol with + | none => change 1 ≤ 2; omega + | some a => + unfold indexedLeafAllocation indexedLeafWithWork indexedSingletonCostWithWork + split_ifs <;> simp only [occurrenceQueryWithWork_spec] <;> omega + + + +theorem binaryIndexedLeafAllocation_le_work (table : BinaryMemo PositionCounts) (symbolBits positionBits : ℕ) + (symbol : Option ℕ) (lo hi : ℕ) : + binaryIndexedLeafAllocation table symbolBits positionBits symbol lo hi ≤ + (binaryIndexedLeafWithWork table symbolBits positionBits symbol lo hi).2 := + Nat.add_le_add_right (Nat.add_le_add_right (indexedLeafAllocation_le_work table symbolBits positionBits symbol lo hi) _) _ + + + +theorem queryIndexedSliceAllocation_le_work (source : List ℕ) (interval : TargetInterval source.length) + (targetLength : ℕ) (q : TargetInterval targetLength) + (occurrence : BinaryMemo PositionCounts) (symbolBits positionBits : ℕ) : + queryIndexedSliceAllocation source interval targetLength q occurrence symbolBits positionBits ≤ + (queryIndexedSliceWithWork source interval targetLength q occurrence symbolBits positionBits).2 := by + have hc := bitCompareWithWork_input_cells interval.lo.bits interval.hi.bits + have hl := binaryIndexedLeafAllocation_le_work occurrence symbolBits positionBits + (querySliceHeadWithWork source interval).1 q.lo q.hi + have hs : interval.lo.bits.length + interval.hi.bits.length + 1 ≤ + (querySliceHeadWithWork source interval).2 := by + unfold querySliceHeadWithWork + dsimp only + change _ ≤ (bitCompareWithWork interval.lo.bits interval.hi.bits).2 + _ + _ + 3 + omega + unfold queryIndexedSliceAllocation queryIndexedSliceWithWork + dsimp only + omega + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryInitialCenterCost.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryInitialCenterCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..5bc0a530760edf9ea69ec588b244bbfba2b732de --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryInitialCenterCost.lean @@ -0,0 +1,100 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryGridCost +import OAI.Combinatorics.EditApproximation.Queries.QueryInitialConeCenters +import OAI.Combinatorics.EditApproximation.Queries.QueryScalarDispatch +import OAI.Combinatorics.EditApproximation.Queries.QueryHistoryBounds +import OAI.Combinatorics.EditApproximation.Binary.BinaryInitialGuardWork + +namespace OAI + +/-! The initial gather pays for all candidate centers, including those +whose eligibility is tested only after their seed value has been read. -/ + +namespace EditApproximation.BinaryFraction + +theorem queryInitialScale_radius (radius b Amax : ℕ) (A : BinaryFraction) + (hA : 1 ≤ A.value) (hmax : A.value ≤ Amax) + (hguard : (initialScaleGuardWithWork radius b A).1 = true) : + radius ≤ (16 * Amax ^ 2) * b := by + have hw := (initialScaleGuardWithWork_value radius b A).mp hguard + have hp : 0 < A.value := by linarith + have hd := (div_le_iff₀ (show (0 : ℚ) < 16 * A.value ^ 2 by positivity)).mp hw.1 + have hs := pow_le_pow_left₀ hp.le hmax 2 + have hm := mul_le_mul_of_nonneg_right hs (show (0 : ℚ) ≤ 16 * b by positivity) + have h : (radius : ℚ) ≤ ((16 * Amax ^ 2) * b : ℕ) := by + push_cast + nlinarith only [hd, hm] + exact_mod_cast h + +def queryInitialCentersBitBudget (P Amax B : ℕ) : ℕ := + let L := (64 * Amax ^ 2 * P + 2) ^ 2 + 500 * (B + 1) ^ 2 + (B + 1) * (B + 9) + 2 + + (B + 1) * (initialScaleGuardBitBudget (B + 4) + 3) + + (B + 1) * (queryGridPointsBitBudget P (16 * Amax ^ 2) (B + 2) + L + 3) + 2 + +theorem queryInitialConeCentersWithWork_bounds {n : ℕ} (N P Amax B : ℕ) + (A value : BinaryFraction) (q : TargetInterval n) + (hB : 8 ≤ B) (hP : 0 < P) (hN : Nat.size N ≤ B) (hPb : Nat.size P ≤ B) + (hn : Nat.size n ≤ B) (hAb : A.width ≤ B) (hvb : value.width ≤ B) + (hA : 1 ≤ A.value) (hmax : A.value ≤ Amax) : + (queryInitialConeCentersWithWork N P A value q).1.length ≤ + (B + 1) * (64 * Amax ^ 2 * P + 2) ^ 2 ∧ + (queryInitialConeCentersWithWork N P A value q).2 ≤ queryInitialCentersBitBudget P Amax B := by + let radius := naturalCeilingWithWork value + let scales := dyadicScalesWithWork N + let guard := fun b => initialScaleGuardWithWork (bitWordValue radius.1) b A + let active := filterWithWork guard scales.1 + let run := fun b => queryGridPointsWithWork P b (bitWordValue radius.1) q + let centers := arithmeticFlatMapWithWork run active.1 + let L := (64 * Amax ^ 2 * P + 2) ^ 2 + have hrad : Nat.size (bitWordValue radius.1) ≤ B + 2 := + (Nat.size_le.mpr (bitWordValue_lt_pow_length radius.1)).trans + ((naturalCeilingWithWork_length value).trans (by omega)) + have hrwork := (naturalCeilingWithWork_cost value).trans + (Nat.mul_le_mul_left 500 (Nat.pow_le_pow_left (Nat.add_le_add_right hvb 1) 2)) + have hsc : scales.1.length ≤ B + 1 := by + simp only [scales, dyadicScalesWithWork, arithmeticMapWithWork_value, List.length_map, List.length_range, + Nat.size_eq_bits_len] + omega + have hswork : scales.2 ≤ (B + 1) * (B + 9) + 2 := + (dyadicScalesWithWork_cost N).trans + (Nat.add_le_add_right (Nat.mul_le_mul (by omega) (by omega)) 2) + have hb (b : ℕ) (hb : b ∈ scales.1) : Nat.size b ≤ B + 1 := by + rw [dyadicScalesWithWork_value] at hb + exact (dyadicScales_size_bound N b hb).trans (by omega) + have hg := filterWithWork_cost guard scales.1 (initialScaleGuardBitBudget (B + 4)) (by + intro b hmem + exact initialScaleGuardWithWork_cost _ b (B + 4) A (by omega) (by omega) + (by have := hb b hmem; omega) (by omega)) + have hgwork : active.2 ≤ (B + 1) * (initialScaleGuardBitBudget (B + 4) + 3) := + hg.trans (Nat.mul_le_mul_right _ hsc) + have hactive : active.1.length ≤ B + 1 := by + rw [filterWithWork_value] + exact (List.length_filter_le _ _).trans hsc + have hrun (b : ℕ) (hmem : b ∈ active.1) : + (run b).1.length ≤ L ∧ + (run b).2 ≤ queryGridPointsBitBudget P (16 * Amax ^ 2) (B + 2) := by + rw [filterWithWork_value] at hmem + obtain ⟨hbmem, hbguard⟩ := List.mem_filter.mp hmem + have hsize := hb b hbmem + have hr := queryInitialScale_radius (bitWordValue radius.1) b Amax A hA hmax hbguard + have h := queryGridPointsWithWork_bounds P b (bitWordValue radius.1) (16 * Amax ^ 2) (B + 2) q + hP (by omega) (by omega) hrad (by omega) hr + simpa only [run, L, show 4 * (16 * Amax ^ 2) * P = 64 * Amax ^ 2 * P by ring] using h + have hl := (arithmeticFlatMapWithWork_length run active.1 L + (fun b hb => (hrun b hb).1)).trans (Nat.mul_le_mul_right L hactive) + have hc := (arithmeticFlatMapWithWork_cost run active.1 + (queryGridPointsBitBudget P (16 * Amax ^ 2) (B + 2)) L + (fun b hb => (hrun b hb).2) (fun b hb => (hrun b hb).1)).trans + (Nat.mul_le_mul_right _ hactive) + change centers.2 ≤ _ at hc + change radius.2 ≤ _ at hrwork + refine ⟨hl, ?_⟩ + change radius.2 + scales.2 + active.2 + centers.2 + 2 ≤ _ + change _ ≤ 500 * (B + 1) ^ 2 + (B + 1) * (B + 9) + 2 + + (B + 1) * (initialScaleGuardBitBudget (B + 4) + 3) + + (B + 1) * (queryGridPointsBitBudget P (16 * Amax ^ 2) (B + 2) + L + 3) + 2 + omega + +end EditApproximation.BinaryFraction + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryInitialConeCenters.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryInitialConeCenters.lean new file mode 100644 index 0000000000000000000000000000000000000000..825ff36ab59af273644099d5ab8a1707a125684b --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryInitialConeCenters.lean @@ -0,0 +1,59 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryLocalBuffers +import OAI.Combinatorics.EditApproximation.Binary.BinaryInitialReads +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! The initial-cone gather uses the unfiltered center list: a seed at a +center must be read before the eligibility test at that center is known. -/ + +namespace EditApproximation.BinaryFraction + + + +@[simp] theorem queryInitialConeCentersWithWork_value {n : ℕ} (N P : ℕ) (hP : 0 < P) + (A value : BinaryFraction) (q : TargetInterval n) : + (queryInitialConeCentersWithWork N P A value q).1 = + rawInitialConeCenters N P A.value ⌈value.value⌉₊ q := by + have hg (b : ℕ) : (gridStateBoxWithWork n (seedGridSpacing b P) ⌈value.value⌉₊ q.lo q.hi).1 = + localTargetStates n (seedGridSpacing b P) ⌈value.value⌉₊ q := by + rw [gridStateBoxWithWork_value _ _ _ _ _ (by unfold seedGridSpacing; omega)] + rfl + have hguard (b : ℕ) : (initialScaleGuardWithWork ⌈value.value⌉₊ b A).1 = + decide ((⌈value.value⌉₊ : ℚ) / (16 * A.value ^ 2) ≤ b ∧ + (b : ℚ) ≤ 4 * A.value * ⌈value.value⌉₊) := + Bool.eq_iff_iff.mpr (by simp only [initialScaleGuardWithWork_value, decide_eq_true_eq]) + simp only [queryInitialConeCentersWithWork, naturalCeilingWithWork_value, + arithmeticFlatMapWithWork_value, filterWithWork_value, dyadicScalesWithWork_value, + hguard, seedGridSpacingWithWork_value _ _ hP, hg, + rawInitialConeCenters] + + + +@[simp] theorem queryInitialSeedReadWithWork_value {n : ℕ} (value : BinaryFraction) (q : TargetInterval n) + (keys : List (TargetInterval n)) (words : List BinaryFraction) (r : TargetInterval n) : + bitWordValue (queryInitialSeedReadWithWork value q keys words r).1 = + if r = q then ⌈value.value⌉₊ else ⌈finiteAnswerTable keys (words.map BinaryFraction.value) r⌉₊ := by + unfold queryInitialSeedReadWithWork + by_cases hr : r = q + · rw [ite_eq_left ((queryIntervalEqualWithWork_value r q).mpr hr), ite_eq_left hr] + exact naturalCeilingWithWork_value value + · rw [ite_eq_right (fun h => hr ((queryIntervalEqualWithWork_value r q).mp h)), ite_eq_right hr] + simp only [naturalCeilingWithWork_value, queryParentReadWithWork_value] + +theorem cachedInitialProgramReadWithWork_value_only {α : Type*} (source target : List α) + (N P F : ℕ) (hP : 0 < P) (A a : BinaryFraction) + (read : TargetInterval target.length → List Bool × ℕ) (q : TargetInterval target.length) : + (cachedInitialProgramReadWithWork source.length N P F A a read q).1.value = + localInitialConeTable source target (fun r => bitWordValue (read r).1) N P F A.value a.value q := by + let R := ∑ r : TargetInterval target.length, (read r).2 + have hR (r : TargetInterval target.length) : (read r).2 ≤ R := + Finset.single_le_sum (f := fun r : TargetInterval target.length => (read r).2) + (fun _ _ => Nat.zero_le _) (Finset.mem_univ r) + rw [(cachedInitialProgramReadWithWork_eq_cost source.length N P F A a read q R hR).1] + exact (cachedInitialProgramWithWork_value_width source target N P F A a _ q hP).1 + +end EditApproximation.BinaryFraction + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryInitialConeProgram.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryInitialConeProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..b98a914570d63e05406b9065939100bce98da815 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryInitialConeProgram.lean @@ -0,0 +1,67 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryInitialConeCenters +import OAI.Combinatorics.EditApproximation.Binary.BitQuery +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! The initial-cone program first reads its seed, constructs the actual +raw-center list, gathers its answers, and executes the cached Boolean +initial kernel with that finite buffer. -/ + +namespace EditApproximation + +section Initial +variable {ι α : Type*} (source target : List α) + (N P F : ℕ) (hP : 0 < P) (A a : BinaryFraction) + (reader : TargetInterval target.length → BitQuery ι BinaryFraction) + (q : TargetInterval target.length) + + + +def queryInitialConeProgram : BitQuery ι BinaryFraction := + queryInitialConeProgramAt source.length N P F A a reader q + +include hP in +theorem queryInitialConeProgram_refines + (expected : TargetInterval target.length → FiniteQuery ι) + (hr : ∀ r, BitQuery.Refines (fun word value => word.value = value) (reader r) (expected r)) + (ha : a.value = refinementFactor A.value F) : + BitQuery.Refines (fun word value => word.value = value) + (queryInitialConeProgram source target N P F A a reader q) + (FiniteQuery.bind (expected q) fun answer => + let value := ⌈answer⌉₊ + let keys := rawInitialConeCenters N P A.value value q + FiniteQuery.collect expected keys fun answers => + let localTable := fun r => if r = q then value else ⌈finiteAnswerTable keys answers r⌉₊ + .done (localInitialConeTable source target localTable N P F A.value (refinementFactor A.value F) q)) := by + unfold queryInitialConeProgram queryInitialConeProgramAt + apply (hr q).bind + intro value answer hv + subst answer + apply BitQuery.Refines.charge + change BitQuery.Refines _ (BitQuery.collect reader _ _) _ + rw [BinaryFraction.queryInitialConeCentersWithWork_value N P hP] + apply BitQuery.Refines.collect reader expected hr + intro words + apply BitQuery.Refines.charge + apply BitQuery.Refines.done + rw [BinaryFraction.cachedInitialProgramReadWithWork_value_only source target N P F hP] + simp only [BinaryFraction.queryInitialSeedReadWithWork_value, ha] + +theorem queryInitialConeProgram_work (oracle : ι → BinaryFraction) (readWork : ι → ℕ) : + let value := (reader q).value oracle + let keys := BinaryFraction.queryInitialConeCentersWithWork N P A value q + let words := keys.1.map fun r => (reader r).value oracle + (queryInitialConeProgram source target N P F A a reader q).work oracle readWork = + (reader q).work oracle readWork + keys.2 + + (keys.1.map fun r => (reader r).work oracle readWork + 3).sum + + (BinaryFraction.cachedInitialProgramReadWithWork source.length N P F A a + (BinaryFraction.queryInitialSeedReadWithWork value q keys.1 words) q).2 := by + simp only [queryInitialConeProgram, queryInitialConeProgramAt, BitQuery.work_bind, BitQuery.work_collect, + BitQuery.compute, BitQuery.work, BitQuery.value, Nat.add_zero, Nat.add_assoc] + +end Initial +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryInitialConeSpace.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryInitialConeSpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..7c9ca11a3cc11d00bdcee3c8bcb983c430ee7a88 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryInitialConeSpace.lean @@ -0,0 +1,75 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryInitialReadSpace +import OAI.Combinatorics.EditApproximation.Queries.QueryGatherSpace +import OAI.Combinatorics.EditApproximation.Queries.QueryInitialConeProgram +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation.BinaryFraction + + + +theorem queryInitialConeCentersAllocation_le_work {n : ℕ} (N P : ℕ) (A value : BinaryFraction) + (q : TargetInterval n) : + queryInitialConeCentersAllocation N P A value q ≤ (queryInitialConeCentersWithWork N P A value q).2 := by + let radius := (naturalCeilingWithWork value).1 + let build := fun b => + let spacing := (seedGridSpacingWithWork b P).1 + let states := gridStateBoxWithWork n (bitWordValue spacing) (bitWordValue radius) q.lo q.hi + (states.1, (seedGridSpacingWithWork b P).2 + states.2 + 1) + have hr := naturalCeilingAllocation_le_work value + have hd := dyadicScalesAllocation_le_work N + have hf := filterAllocation_le_work (fun b => initialScaleGuardWithWork (bitWordValue radius) b A) + (fun b => initialScaleGuardAllocation (bitWordValue radius) b A) (dyadicScalesWithWork N).1 + (fun b _ => initialScaleGuardAllocation_le_work (bitWordValue radius) b A) + have hm := arithmeticFlatMapAllocation_le_work build + (fun b => seedGridSpacingAllocation b P + gridStateBoxAllocation n + (bitWordValue (seedGridSpacingWithWork b P).1) (bitWordValue radius) q.lo q.hi) + (filterWithWork (fun b => initialScaleGuardWithWork (bitWordValue radius) b A) (dyadicScalesWithWork N).1).1 (by + intro b _ + have hs := seedGridSpacingAllocation_le_work b P + have hg := gridStateBoxAllocation_le_work n (bitWordValue (seedGridSpacingWithWork b P).1) (bitWordValue radius) q.lo q.hi + dsimp only [build] + omega) + unfold queryInitialConeCentersAllocation queryInitialConeCentersWithWork + dsimp only [build, radius] at hf hm ⊢ + omega + + + +theorem queryInitialSeedReadAllocation_le_work {n : ℕ} (value : BinaryFraction) (q : TargetInterval n) + (keys : List (TargetInterval n)) (words : List BinaryFraction) (r : TargetInterval n) : + queryInitialSeedReadAllocation value q keys words r ≤ (queryInitialSeedReadWithWork value q keys words r).2 := by + have he := queryIntervalEqualAllocation_le_work r q + have hv := naturalCeilingAllocation_le_work value + have hp := queryParentReadAllocation_le_work keys words r + have hc := naturalCeilingAllocation_le_work (queryParentReadWithWork keys words r).1 + unfold queryInitialSeedReadAllocation queryInitialSeedReadWithWork + dsimp only + split_ifs <;> dsimp only <;> omega + +end EditApproximation.BinaryFraction + +namespace EditApproximation +open BitQuery BinaryFraction + +def queryInitialConeProgramAtHeap {ι : Type*} {n : ℕ} (sourceLength N P F : ℕ) (A a : BinaryFraction) + (reader : TargetInterval n → BitQuery ι BinaryFraction) (q : TargetInterval n) + (hr : ∀ r, Heap (reader r)) : Heap (queryInitialConeProgramAt sourceLength N P F A a reader q) := + (hr q).bind _ fun value => + (Heap.computeOf (queryInitialConeCentersWithWork N P A value q) + (queryInitialConeCentersAllocation N P A value q) + (queryInitialConeCentersAllocation_le_work N P A value q)).bind _ fun keys => + Heap.collect reader hr keys _ fun words => + Heap.computeOf (cachedInitialProgramReadWithWork sourceLength N P F A a + (queryInitialSeedReadWithWork value q keys words) q) + (cachedInitialProgramReadAllocation (queryInitialSeedReadWithWork value q keys words) + (queryInitialSeedReadAllocation value q keys words) sourceLength N P F A a q) + (cachedInitialProgramReadAllocation_le_work (queryInitialSeedReadWithWork value q keys words) + (queryInitialSeedReadAllocation value q keys words) sourceLength N P F A a q + (queryInitialSeedReadAllocation_le_work value q keys words)) + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryInitialGather.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryInitialGather.lean new file mode 100644 index 0000000000000000000000000000000000000000..0b29e75c9a5df1776f0dcfc15be7514b7edce8eb --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryInitialGather.lean @@ -0,0 +1,57 @@ +import OAI.Combinatorics.EditApproximation.Binary.BitQuery +import OAI.Combinatorics.EditApproximation.Queries.QueryInitialSupport +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! The first adaptive gather executes its binary support construction +after reading the parent value, then requests those keys in their original +order. Its continuation receives only the stored words actually read. -/ + +namespace EditApproximation + + + +theorem queryInitialGather_refines {ι β : Type*} {n : ℕ} {relation : β → ℚ → Prop} + (N P F exponent : ℕ) (hP : 0 < P) (a : BinaryFraction) (q : TargetInterval n) + (reader : TargetInterval n → BitQuery ι BinaryFraction) + (expectedReader : TargetInterval n → FiniteQuery ι) + (next : List (TargetInterval n) → List BinaryFraction → BitQuery ι β) + (expectedNext : List (TargetInterval n) → List ℚ → FiniteQuery ι) + (hr : ∀ key, BitQuery.Refines (fun word value => word.value = value) + (reader key) (expectedReader key)) + (hn : ∀ (value : BinaryFraction) (words : List BinaryFraction), BitQuery.Refines relation + (next (refinementInitialSupport N P F exponent a.value value.value q) words) + (expectedNext (refinementInitialSupport N P F exponent a.value value.value q) + (words.map BinaryFraction.value))) : + BitQuery.Refines relation (queryInitialGather N P F exponent hP a q reader next) + (FiniteQuery.bind (expectedReader q) fun value => + let keys := refinementInitialSupport N P F exponent a.value value q + FiniteQuery.collect expectedReader keys (expectedNext keys)) := by + apply (hr q).bind + intro value expected hv + subst expected + change BitQuery.Refines relation (.charge _ _) _ + apply BitQuery.Refines.charge + change BitQuery.Refines relation (BitQuery.collect reader _ _) _ + rw [BinaryFraction.queryInitialSupportWithWork_value] + exact BitQuery.Refines.collect reader expectedReader hr _ _ _ (hn value) + +theorem queryInitialGather_work {ι β : Type*} {n : ℕ} + (N P F exponent : ℕ) (hP : 0 < P) (a : BinaryFraction) (q : TargetInterval n) + (reader : TargetInterval n → BitQuery ι BinaryFraction) + (next : List (TargetInterval n) → List BinaryFraction → BitQuery ι β) + (oracle : ι → BinaryFraction) (readWork : ι → ℕ) : + let value := (reader q).value oracle + let support := BinaryFraction.queryInitialSupportWithWork N P F exponent hP a value q + (queryInitialGather N P F exponent hP a q reader next).work oracle readWork = + (reader q).work oracle readWork + support.2 + + (support.1.map fun key => (reader key).work oracle readWork + 3).sum + + (next support.1 (support.1.map fun key => (reader key).value oracle)).work oracle readWork := by + simp only [queryInitialGather, BitQuery.work_bind, BitQuery.compute, + BitQuery.work, BitQuery.value, BitQuery.work_collect, Nat.add_zero, Nat.add_assoc] + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryInitialProgramCost.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryInitialProgramCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..98913cec7916f7e91b5ed7c3fa3d76cece7e2a52 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryInitialProgramCost.lean @@ -0,0 +1,148 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryInitialConeProgram +import OAI.Combinatorics.EditApproximation.Queries.QueryInitialCenterCost + +namespace OAI + +namespace EditApproximation.BinaryFraction + +def queryInitialSeedReadBudget (count B : ℕ) : ℕ := + 16 * B + 7 + count * (16 * B + 6) + 500 * (B + 1) ^ 2 + +theorem queryInitialSeedReadWithWork_bounds {n : ℕ} (value : BinaryFraction) (q : TargetInterval n) + (keys : List (TargetInterval n)) (words : List BinaryFraction) (r : TargetInterval n) + (B : ℕ) (hB : 2 ≤ B) (hn : Nat.size n ≤ B) (hv : value.width ≤ B) + (hw : ∀ w ∈ words, w.width ≤ B) : + Nat.size (bitWordValue (queryInitialSeedReadWithWork value q keys words r).1) ≤ B + 2 ∧ + (queryInitialSeedReadWithWork value q keys words r).2 ≤ queryInitialSeedReadBudget keys.length B := by + have htest := queryIntervalEqualWithWork_cost r q B hn + have hread := queryParentReadWithWork_cost keys words r + have hwidth : (queryParentReadWithWork keys words r).1.width ≤ B := + gatheredWordLookupWithWork_width _ keys words r B hB hw + have hsize (v : BinaryFraction) (h : v.width ≤ B) : + Nat.size (bitWordValue (naturalCeilingWithWork v).1) ≤ B + 2 := + (Nat.size_le.mpr (bitWordValue_lt_pow_length _)).trans ((naturalCeilingWithWork_length v).trans (by omega)) + have hcost (v : BinaryFraction) (h : v.width ≤ B) : + (naturalCeilingWithWork v).2 ≤ 500 * (B + 1) ^ 2 := + (naturalCeilingWithWork_cost v).trans (Nat.mul_le_mul_left _ (Nat.pow_le_pow_left (by omega) 2)) + unfold queryInitialSeedReadWithWork queryInitialSeedReadBudget + dsimp only + split_ifs + · exact ⟨hsize value hv, by have := hcost value hv; omega⟩ + · exact ⟨hsize _ hwidth, by + have := hcost _ hwidth + have hread' : (queryParentReadWithWork keys words r).2 ≤ 1 + keys.length * (16 * B + 6) := + hread.trans (by gcongr) + omega⟩ + +def queryInitialProgramBitBudget (P Amax B C : ℕ) : ℕ := + let count := (B + 1) * (64 * Amax ^ 2 * P + 2) ^ 2 + C + queryInitialCentersBitBudget P Amax B + count * (C + 3) + + cachedInitialProgramBitBudget P Amax (B + 2) * (queryInitialSeedReadBudget count B + 2) + +end EditApproximation.BinaryFraction + +namespace EditApproximation + +private theorem initial_program_sum_bound {κ : Type*} (keys : List κ) (f : κ → ℕ) (C : ℕ) + (hf : ∀ key ∈ keys, f key ≤ C) : (keys.map f).sum ≤ keys.length * C := by + induction keys with + | nil => simp + | cons key keys ih => + have hh := hf key List.mem_cons_self + have ht := ih (fun k hk => hf k (List.mem_cons_of_mem key hk)) + simp only [List.map_cons, List.sum_cons, List.length_cons, Nat.add_mul, Nat.one_mul] + omega + +open BinaryFraction + +theorem queryInitialConeProgramAt_work {ι : Type*} {n : ℕ} + (sourceLength N P F : ℕ) (A a : BinaryFraction) + (reader : TargetInterval n → BitQuery ι BinaryFraction) (q : TargetInterval n) + (oracle : ι → BinaryFraction) (readWork : ι → ℕ) : + let value := (reader q).value oracle + let keys := queryInitialConeCentersWithWork N P A value q + let words := keys.1.map fun r => (reader r).value oracle + (queryInitialConeProgramAt sourceLength N P F A a reader q).work oracle readWork = + (reader q).work oracle readWork + keys.2 + + (keys.1.map fun r => (reader r).work oracle readWork + 3).sum + + (cachedInitialProgramReadWithWork sourceLength N P F A a + (queryInitialSeedReadWithWork value q keys.1 words) q).2 := by + simp only [queryInitialConeProgramAt, BitQuery.work_bind, BitQuery.work_collect, + BitQuery.compute, BitQuery.work, BitQuery.value, Nat.add_zero, Nat.add_assoc] + +theorem queryInitialConeProgramAt_width {ι : Type*} {n : ℕ} + (sourceLength N P F : ℕ) (A a : BinaryFraction) + (reader : TargetInterval n → BitQuery ι BinaryFraction) (q : TargetInterval n) + (oracle : ι → BinaryFraction) (hP : 0 < P) : + ((queryInitialConeProgramAt sourceLength N P F A a reader q).value oracle).width ≤ + Nat.size ((32 * F + 1) * N) + 3 := by + classical + let value := (reader q).value oracle + let keys := queryInitialConeCentersWithWork N P A value q + let words := keys.1.map fun r => (reader r).value oracle + let seed := queryInitialSeedReadWithWork value q keys.1 words + let R := Finset.univ.sup (fun r => (seed r).2) + have hR (r : TargetInterval n) : (seed r).2 ≤ R := + Finset.le_sup (f := fun r => (seed r).2) (Finset.mem_univ r) + have heq := (cachedInitialProgramReadWithWork_eq_cost sourceLength N P F A a seed q R hR).1 + have hw0 := fun (U : TargetInterval (List.replicate n ()).length → ℕ) r => + (cachedInitialProgramWithWork_value_width (List.replicate sourceLength ()) + (List.replicate n ()) N P F A a U r hP).2 + generalize hy : (List.replicate n ()).length = ny at hw0 + simp only [List.length_replicate] at hy + subst ny + have hw := hw0 (fun r => bitWordValue (seed r).1) q + simp only [List.length_replicate] at hw + simp only [queryInitialConeProgramAt, BitQuery.value_bind, BitQuery.value_collect, + BitQuery.compute, BitQuery.value] + change (cachedInitialProgramReadWithWork sourceLength N P F A a seed q).1.width ≤ _ + rw [heq] + exact hw + +theorem queryInitialConeProgramAt_work_bound {ι : Type*} {n : ℕ} + (sourceLength N P F Amax B C : ℕ) (hP : 0 < P) (A a : BinaryFraction) + (reader : TargetInterval n → BitQuery ι BinaryFraction) (q : TargetInterval n) + (oracle : ι → BinaryFraction) (readWork : ι → ℕ) + (hB : 8 ≤ B) (hN : Nat.size N ≤ B) (hPb : Nat.size P ≤ B) (hF : Nat.size F ≤ B) + (hnx : Nat.size sourceLength ≤ B) (hny : Nat.size n ≤ B) + (hA : A.width ≤ B) (ha : a.width ≤ B) (hAone : 1 ≤ A.value) (hAmax : A.value ≤ Amax) + (hw : ∀ r, ((reader r).value oracle).width ≤ B) + (hc : ∀ r, (reader r).work oracle readWork ≤ C) : + (queryInitialConeProgramAt sourceLength N P F A a reader q).work oracle readWork ≤ + queryInitialProgramBitBudget P Amax B C := by + let value := (reader q).value oracle + let keys := queryInitialConeCentersWithWork N P A value q + let words := keys.1.map fun r => (reader r).value oracle + let seed := queryInitialSeedReadWithWork value q keys.1 words + have hk := queryInitialConeCentersWithWork_bounds N P Amax B A value q hB hP hN hPb hny hA (hw q) hAone hAmax + have hs (r : TargetInterval n) := queryInitialSeedReadWithWork_bounds value q keys.1 words r B + (by omega) hny (hw q) (by + intro w hmem + obtain ⟨key, _, rfl⟩ := List.mem_map.mp hmem + exact hw key) + have hseed : ∀ r, (seed r).2 ≤ queryInitialSeedReadBudget ((B + 1) * (64 * Amax ^ 2 * P + 2) ^ 2) B := by + intro r + apply (hs r).2.trans + unfold queryInitialSeedReadBudget + exact Nat.add_le_add_right (Nat.add_le_add_left + (Nat.mul_le_mul_right (16 * B + 6) hk.1) _) _ + have hkernel := (cachedInitialProgramReadWithWork_eq_cost sourceLength N P F A a seed q _ hseed).2 + have hplain := cachedInitialProgramWithWork_cost sourceLength N P F Amax (B + 2) A a + (fun r => bitWordValue (seed r).1) q (by omega) hP (by omega) (by omega) (by omega) + (by omega) (by omega) (fun r => (hs r).1) (by omega) (by omega) hAone hAmax + have hkernel' := hkernel.trans (Nat.mul_le_mul_right _ hplain) + have hsum := (initial_program_sum_bound keys.1 (fun r => (reader r).work oracle readWork + 3) (C + 3) + (fun r _ => Nat.add_le_add_right (hc r) 3)).trans (Nat.mul_le_mul_right _ hk.1) + rw [queryInitialConeProgramAt_work] + change (reader q).work oracle readWork + keys.2 + + (keys.1.map fun r => (reader r).work oracle readWork + 3).sum + + (cachedInitialProgramReadWithWork sourceLength N P F A a seed q).2 ≤ _ + have hcq := hc q + have hkc : keys.2 ≤ queryInitialCentersBitBudget P Amax B := hk.2 + unfold queryInitialProgramBitBudget + dsimp only + omega + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryInitialSpace.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryInitialSpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..c3841841119f8d684e5a0de31c08726da379aaca --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryInitialSpace.lean @@ -0,0 +1,104 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryInitialSupport +import OAI.Combinatorics.EditApproximation.Queries.QueryEligibilitySpace +import OAI.Combinatorics.EditApproximation.Queries.QueryInputSpace +import OAI.Combinatorics.EditApproximation.Binary.BinaryRoundingSpace +import OAI.Combinatorics.EditApproximation.Binary.BinaryCellSpace +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation.BinaryFraction + + + +theorem queryScalesAllocation_le_work (N F : ℕ) (a value : BinaryFraction) : + queryScalesAllocation N F a value ≤ (queryScalesWithWork N F a value).2 := by + have he := queryExponentsAllocation_le_work N F a value + have hm := arithmeticMapAllocation_le_work (fun e => (bitWordValue (powerTwoWord e), e + 3)) + (fun e => e + 1) (queryExponentsWithWork N F a value).1 (fun _ _ => by dsimp only; omega) + unfold queryScalesAllocation queryScalesWithWork + dsimp only + omega + + + +theorem queryRawCentersAllocation_le_work {n : ℕ} (N P F : ℕ) (a value : BinaryFraction) (q : TargetInterval n) : + queryRawCentersAllocation N P F a value q ≤ (queryRawCentersWithWork N P F a value q).2 := by + let build := fun b => + let spacing := seedGridSpacingWithWork b P + let states := gridStateBoxWithWork n (bitWordValue spacing.1) (bitWordValue (naturalCeilingWithWork value).1) q.lo q.hi + (states.1, spacing.2 + states.2 + 1) + have hs := queryScalesAllocation_le_work N F a value + have hr := naturalCeilingAllocation_le_work value + have hc := arithmeticFlatMapAllocation_le_work build (fun b => seedGridSpacingAllocation b P + + gridStateBoxAllocation n (bitWordValue (seedGridSpacingWithWork b P).1) + (bitWordValue (naturalCeilingWithWork value).1) q.lo q.hi) (queryScalesWithWork N F a value).1 (by + intro b _ + have hg := gridStateBoxAllocation_le_work n (bitWordValue (seedGridSpacingWithWork b P).1) + (bitWordValue (naturalCeilingWithWork value).1) q.lo q.hi + have hs := seedGridSpacingAllocation_le_work b P + dsimp only [build] + omega) + have he := queryEraseAllocation_le_work queryIntervalEqualWithWork queryIntervalEqualAllocation + (arithmeticFlatMapWithWork build (queryScalesWithWork N F a value).1).1 queryIntervalEqualAllocation_le_work + unfold queryRawCentersAllocation queryRawCentersWithWork + dsimp only [build] at hc he ⊢ + omega + + + +theorem queryGroupKeysAllocation_le_work {n : ℕ} (N F exponent : ℕ) (a value : BinaryFraction) (q : TargetInterval n) : + queryGroupKeysAllocation N F exponent a value q ≤ (queryGroupKeysWithWork N F exponent a value q).2 := by + let radius := (naturalCeilingWithWork value).1 + let build := fun b => + let side := canonicalMulWithWork (inversePowerTwo exponent) (nat b) + let cells := targetCellsWithWork side.1 (bitWordValue radius) q + let labeled := arithmeticMapWithWork (fun cell => ((b, cell), 1)) cells.1 + (labeled.1, side.2 + cells.2 + labeled.2 + 2) + have hs := queryScalesAllocation_le_work N F a value + have hr := naturalCeilingAllocation_le_work value + have hk := arithmeticFlatMapAllocation_le_work build (fun b => + let side := (canonicalMulWithWork (inversePowerTwo exponent) (nat b)).1 + canonicalMulAllocation (inversePowerTwo exponent) (nat b) + targetCellsAllocation side (bitWordValue radius) q + + arithmeticMapAllocation (fun _ => 1) (targetCellsWithWork side (bitWordValue radius) q).1) + (queryScalesWithWork N F a value).1 (by + intro b _ + have hm := canonicalMulAllocation_le_work (inversePowerTwo exponent) (nat b) + have hc := targetCellsAllocation_le_work (canonicalMulWithWork (inversePowerTwo exponent) (nat b)).1 + (bitWordValue radius) q + have hl := arithmeticMapAllocation_le_work (fun cell => ((b, cell), 1)) (fun _ => 1) + (targetCellsWithWork (canonicalMulWithWork (inversePowerTwo exponent) (nat b)).1 (bitWordValue radius) q).1 + (fun _ _ => le_rfl) + dsimp only [build] + omega) + unfold queryGroupKeysAllocation queryGroupKeysWithWork + dsimp only [radius, build] at hk ⊢ + omega + + + +theorem queryOnlineKeysAllocation_le_work {n : ℕ} (N P F : ℕ) (hP : 0 < P) + (a value : BinaryFraction) (q : TargetInterval n) : + queryOnlineKeysAllocation N P F hP a value q ≤ (queryOnlineKeysWithWork N P F hP a value q).2 := by + have hs := queryScalesAllocation_le_work N F a value + have hk := arithmeticMapAllocation_le_work (fun b => + let spacing := seedGridSpacingWithWork b P + let center := roundStateWithWork (bitWordValue spacing.1) (seedGridSpacingWithWork_pos b P hP) q + ((b, center.1), spacing.2 + center.2 + 2)) (fun b => + seedGridSpacingAllocation b P + roundStateAllocation (bitWordValue (seedGridSpacingWithWork b P).1) q + 1) + (queryScalesWithWork N F a value).1 (by + intro b _ + have hs := seedGridSpacingAllocation_le_work b P + have hr := roundStateAllocation_le_work (bitWordValue (seedGridSpacingWithWork b P).1) + (seedGridSpacingWithWork_pos b P hP) q + dsimp only + omega) + dsimp only at hk + unfold queryOnlineKeysAllocation queryOnlineKeysWithWork + dsimp only + omega + +end EditApproximation.BinaryFraction + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryInitialSupport.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryInitialSupport.lean new file mode 100644 index 0000000000000000000000000000000000000000..79db8e0bb865b5549be9f04efbc129f23aa815f3 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryInitialSupport.lean @@ -0,0 +1,71 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryListWork +import OAI.Combinatorics.EditApproximation.Binary.BinaryRefinementLists +import OAI.Combinatorics.EditApproximation.Geometry.LocalOnlineSourceQuery +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Executed Boolean construction of the first adaptive refinement lists. +Their values are the original lists, including ordering and repetitions. -/ + +namespace EditApproximation +namespace BinaryFraction + + + +@[simp] theorem queryScalesWithWork_value (N F : ℕ) (a value : BinaryFraction) : + (queryScalesWithWork N F a value).1 = dyadicQueryWindow N value.value a.value F := by + simp only [queryScalesWithWork, arithmeticMapWithWork_value, powerTwoWord_value, + queryExponentsWithWork_value] + + + +@[simp] theorem queryRawCentersWithWork_value {n : ℕ} (N P F : ℕ) (hP : 0 < P) + (a value : BinaryFraction) (q : TargetInterval n) : + (queryRawCentersWithWork N P F a value q).1 = + rawRefinementCenters N P F a.value value.value q := by + have hg (b : ℕ) : (gridStateBoxWithWork n (seedGridSpacing b P) + ⌈value.value⌉₊ q.lo q.hi).1 = localTargetStates n (seedGridSpacing b P) ⌈value.value⌉₊ q := by + rw [gridStateBoxWithWork_value _ _ _ _ _ (by unfold seedGridSpacing; omega)] + rfl + simp only [queryRawCentersWithWork, queryEraseWithWork_value _ queryIntervalEqualWithWork_value, + arithmeticFlatMapWithWork_value, seedGridSpacingWithWork_value _ _ hP, + naturalCeilingWithWork_value, hg, queryScalesWithWork_value, rawRefinementCenters] + + + +@[simp] theorem queryGroupKeysWithWork_value {n : ℕ} (N F exponent : ℕ) + (a value : BinaryFraction) (q : TargetInterval n) : + (queryGroupKeysWithWork N F exponent a value q).1 = + localGroupQueryKeys N F exponent a.value (fun _ => value.value) q := by + simp only [queryGroupKeysWithWork, arithmeticFlatMapWithWork_value, arithmeticMapWithWork_value, + queryScalesWithWork_value, targetCellsWithWork_value, naturalCeilingWithWork_value, + canonicalMulWithWork_value, inversePowerTwo_value, nat_value, localGroupQueryKeys] + + + +@[simp] theorem queryOnlineKeysWithWork_value {n : ℕ} (N P F : ℕ) (hP : 0 < P) + (a value : BinaryFraction) (q : TargetInterval n) : + (queryOnlineKeysWithWork N P F hP a value q).1 = + localOnlineSourceKeys N P F a.value (fun _ => value.value) q := by + simp only [queryOnlineKeysWithWork, arithmeticMapWithWork_value, queryScalesWithWork_value, + roundStateWithWork_value, seedGridSpacingWithWork_value _ _ hP, localOnlineSourceKeys] + + + +@[simp] theorem queryInitialSupportWithWork_value {n : ℕ} (N P F exponent : ℕ) (hP : 0 < P) + (a value : BinaryFraction) (q : TargetInterval n) : + (queryInitialSupportWithWork N P F exponent hP a value q).1 = + refinementInitialSupport N P F exponent a.value value.value q := by + simp only [queryInitialSupportWithWork, queryRawCentersWithWork_value _ _ _ hP, + arithmeticFlatMapWithWork_value, arithmeticMapWithWork_value, cellStatesWithWork_value, + seedGridSpacingWithWork_value _ _ hP, canonicalMulWithWork_value, inversePowerTwo_value, + nat_value, queryGroupKeysWithWork_value, queryOnlineKeysWithWork_value, + localOnlineSourceKeys, List.map_map, refinementInitialSupport] + rfl + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryInitialSupportCost.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryInitialSupportCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..4b35cf311e31a467f373ae33db09792f272edfd7 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryInitialSupportCost.lean @@ -0,0 +1,82 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryCellStateCost +import OAI.Combinatorics.EditApproximation.Queries.QueryOnlineKeyCost + +namespace OAI + +/-! The complete initial-support gather, including repeated cells and +unfiltered raw centers, has a local-parameter bound. -/ + +namespace EditApproximation.BinaryFraction + +def queryInitialSupportLength (P F exponent B : ℕ) : ℕ := + let raw := (B + 1) * (64 * F * P + 2) ^ 2 + let groups := (B + 1) * ((32 * F + 2) * 2 ^ exponent + 2) ^ 2 + 1 + raw + groups * P ^ 2 + (B + 1) + +def queryInitialSupportBitBudget (P F exponent B : ℕ) : ℕ := + let raw := (B + 1) * (64 * F * P + 2) ^ 2 + let groups := (B + 1) * ((32 * F + 2) * 2 ^ exponent + 2) ^ 2 + queryRawCentersBitBudget P F B + queryGroupKeysBitBudget F exponent B + + groups * (queryCellStatesBitBudget P exponent B + P ^ 2 + 3) + + queryOnlineKeysBitBudget B + 4 * (B + 1) + 2 * raw + groups * P ^ 2 + 5 + +theorem queryInitialSupportWithWork_bounds {n : ℕ} (N P F exponent B : ℕ) (hP : 0 < P) + (a value : BinaryFraction) (q : TargetInterval n) + (hB : 8 ≤ B) (hN : Nat.size N ≤ B) (hF : Nat.size F + 2 ≤ B) + (hFpos : 1 ≤ F) (hPb : Nat.size P ≤ B) (hn : Nat.size n ≤ B) + (he : exponent + 1 ≤ B) (ha : a.width ≤ B) (hv : value.width ≤ B) + (hw : 0 ≤ value.value) (hPd : ∃ e : ℕ, P = 2 ^ e) : + (queryInitialSupportWithWork N P F exponent hP a value q).1.length ≤ + queryInitialSupportLength P F exponent B ∧ + (queryInitialSupportWithWork N P F exponent hP a value q).2 ≤ + queryInitialSupportBitBudget P F exponent B := by + let raw := queryRawCentersWithWork N P F a value q + let groups := queryGroupKeysWithWork N F exponent a value q + let run := fun key : ℕ × (ℕ × ℕ) => queryCellStatesWithWork n P key.1 exponent key.2 + let cells := arithmeticFlatMapWithWork run groups.1 + let online := queryOnlineKeysWithWork N P F hP a value q + let onlineStates := arithmeticMapWithWork (fun key : ℕ × TargetInterval n => (key.2, 1)) online.1 + let R := (B + 1) * (64 * F * P + 2) ^ 2 + let G := (B + 1) * ((32 * F + 2) * 2 ^ exponent + 2) ^ 2 + have hr := queryRawCentersWithWork_bounds N P F B a value q hB hN hF hFpos hP hPb hn ha hv + have hg := queryGroupKeysWithWork_bounds N F exponent B a value q (by omega) hN hF hFpos he hn ha hv hw + have ho := queryOnlineKeysWithWork_bounds N P F B hP a value q (by omega) hN hF hFpos hPb hn ha hv + have hrun (key : ℕ × (ℕ × ℕ)) (hk : key ∈ groups.1) : + (run key).1.length ≤ P ^ 2 ∧ (run key).2 ≤ queryCellStatesBitBudget P exponent B := by + obtain ⟨hb, hd, hc⟩ := hg.2.2 key hk + exact queryCellStatesWithWork_bounds n P key.1 exponent B key.2 hP hPb hb he hn hc hd hPd + have hcl : cells.1.length ≤ G * P ^ 2 := + (arithmeticFlatMapWithWork_length run groups.1 (P ^ 2) (fun key hk => (hrun key hk).1)).trans + (Nat.mul_le_mul_right _ hg.1) + have hcw := (arithmeticFlatMapWithWork_cost run groups.1 + (queryCellStatesBitBudget P exponent B) (P ^ 2) + (fun key hk => (hrun key hk).2) (fun key hk => (hrun key hk).1)).trans + (Nat.mul_le_mul_right _ hg.1) + change cells.2 ≤ G * (queryCellStatesBitBudget P exponent B + P ^ 2 + 3) at hcw + have hom := (arithmeticMapWithWork_cost (fun key : ℕ × TargetInterval n => (key.2, 1)) + online.1 1 (fun _ _ => le_rfl)).trans (Nat.mul_le_mul_right _ ho.1) + change onlineStates.2 ≤ (B + 1) * (1 + 3) at hom + have hol : onlineStates.1.length ≤ B + 1 := by + simpa only [onlineStates, arithmeticMapWithWork_value, List.length_map] using ho.1 + have hrl : raw.1.length ≤ R := hr.1 + have hrw : raw.2 ≤ queryRawCentersBitBudget P F B := hr.2 + have hgw : groups.2 ≤ queryGroupKeysBitBudget F exponent B := hg.2.1 + have how : online.2 ≤ queryOnlineKeysBitBudget B := ho.2 + constructor + · change (q :: (raw.1 ++ cells.1 ++ onlineStates.1)).length ≤ _ + simp only [List.length_cons, List.length_append] + change _ ≤ 1 + R + G * P ^ 2 + (B + 1) + omega + · change raw.2 + groups.2 + cells.2 + online.2 + onlineStates.2 + + 2 * raw.1.length + cells.1.length + 5 ≤ _ + have hr2 := Nat.mul_le_mul_left 2 hrl + change _ ≤ queryRawCentersBitBudget P F B + queryGroupKeysBitBudget F exponent B + + G * (queryCellStatesBitBudget P exponent B + P ^ 2 + 3) + + queryOnlineKeysBitBudget B + 4 * (B + 1) + 2 * R + G * P ^ 2 + 5 + rw [Nat.mul_comm (B + 1) (1 + 3)] at hom + norm_num only at hom + omega + +end EditApproximation.BinaryFraction + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryInitialSupportSpace.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryInitialSupportSpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..03b121d79957b227c686624bcabd284e9e9b64d6 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryInitialSupportSpace.lean @@ -0,0 +1,48 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryInitialSpace +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation.BinaryFraction + + + +theorem initialCellAllocation_le_work (n P exponent : ℕ) (key : ℕ × ℕ × ℕ) : + initialCellAllocation n P exponent key ≤ + (seedGridSpacingWithWork key.1 P).2 + + (canonicalMulWithWork (inversePowerTwo exponent) (nat key.1)).2 + + (cellStatesWithWork n (bitWordValue (seedGridSpacingWithWork key.1 P).1) + (canonicalMulWithWork (inversePowerTwo exponent) (nat key.1)).1 key.2).2 + exponent + 3 := by + have hs := seedGridSpacingAllocation_le_work key.1 P + have hm := canonicalMulAllocation_le_work (inversePowerTwo exponent) (nat key.1) + have hc := cellStatesAllocation_le_work n (bitWordValue (seedGridSpacingWithWork key.1 P).1) + (canonicalMulWithWork (inversePowerTwo exponent) (nat key.1)).1 key.2 + unfold initialCellAllocation + omega + + + +theorem queryInitialSupportAllocation_le_work {n : ℕ} (N P F exponent : ℕ) (hP : 0 < P) + (a value : BinaryFraction) (q : TargetInterval n) : + queryInitialSupportAllocation N P F exponent hP a value q ≤ + (queryInitialSupportWithWork N P F exponent hP a value q).2 := by + let build := fun key : ℕ × ℕ × ℕ => + let spacing := seedGridSpacingWithWork key.1 P + let side := canonicalMulWithWork (inversePowerTwo exponent) (nat key.1) + let states := cellStatesWithWork n (bitWordValue spacing.1) side.1 key.2 + (states.1, spacing.2 + side.2 + states.2 + exponent + 3) + have hr := queryRawCentersAllocation_le_work N P F a value q + have hg := queryGroupKeysAllocation_le_work N F exponent a value q + have hc := arithmeticFlatMapAllocation_le_work build (initialCellAllocation n P exponent) + (queryGroupKeysWithWork N F exponent a value q).1 (fun key _ => initialCellAllocation_le_work n P exponent key) + have ho := queryOnlineKeysAllocation_le_work N P F hP a value q + have hm := arithmeticMapAllocation_le_work (fun key : ℕ × TargetInterval n => (key.2, 1)) (fun _ => 1) + (queryOnlineKeysWithWork N P F hP a value q).1 (fun _ _ => le_rfl) + unfold queryInitialSupportAllocation queryInitialSupportWithWork + dsimp only [build] at hc ⊢ + omega + +end EditApproximation.BinaryFraction + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryInitialWarmupPolynomial.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryInitialWarmupPolynomial.lean new file mode 100644 index 0000000000000000000000000000000000000000..fdd3973497da8cd69dabcdfe05ed3ecc9d1a0210 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryInitialWarmupPolynomial.lean @@ -0,0 +1,157 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryChargedWarmupCost +import OAI.Combinatorics.EditApproximation.Geometry.PreparedInitialPolynomial +import OAI.Combinatorics.EditApproximation.Geometry.PreparedWarmupPolynomial + +namespace OAI + +/-! Polynomial certificate for the complete initial and warmup dispatch, +including actual gathers, buffer scans, and the previous-pass median. -/ + +namespace EditApproximation + +private abbrev GP := FiniteBitPolynomial (Fin 13) + +private def gp_initialScaleGuardBitBudget (B : GP) : GP := + 4000 * (B + 1) ^ 2 + 4000 * (4 * B + 3) ^ 2 + 2100 * (16 * B + 12) ^ 2 + + 2 * (1000 * (64 * B + 45) ^ 2 + 1) + 2 * B + 7 + +private def gp_gridPointsBitBudget (n B : GP) : GP := + 1000 * (B + 2) ^ 2 + n * (100 * (B + 3) ^ 2 + 5) + +private def gp_gridStateBoxBitBudget (count B : GP) : GP := + 96 * (B + 1) + 2 * gp_gridPointsBitBudget count (B + 2) + + count * (count * (16 * (B + 2) + 11) + count + 3) + 6 + +private def gp_queryGridPointsBitBudget (P K B : GP) : GP := + 100 * (B + 2) ^ 2 + gp_gridStateBoxBitBudget (4 * K * P + 2) (B + 1) + 1 + +private def gp_queryInitialCentersBitBudget (P Amax B : GP) : GP := + let L := (64 * Amax ^ 2 * P + 2) ^ 2 + 500 * (B + 1) ^ 2 + (B + 1) * (B + 9) + 2 + + (B + 1) * (gp_initialScaleGuardBitBudget (B + 4) + 3) + + (B + 1) * (gp_queryGridPointsBitBudget P (16 * Amax ^ 2) (B + 2) + L + 3) + 2 + +private def gp_queryInitialSeedReadBudget (count B : GP) : GP := + 16 * B + 7 + count * (16 * B + 6) + 500 * (B + 1) ^ 2 + +private def gp_queryInitialProgramBitBudget (aux : Fin 3 → GP) (P Amax B C : GP) : GP := + let count := (B + 1) * (64 * Amax ^ 2 * P + 2) ^ 2 + C + gp_queryInitialCentersBitBudget P Amax B + count * (C + 3) + + (aux 0) * (gp_queryInitialSeedReadBudget count B + 2) + +private def gp_queryChargedSeedBitBudget (aux : Fin 3 → GP) (copies J B C : GP) : GP := + 8 * B + 3 + (7 * J + 33 + C) + copies + 1 + + copies * (7 * J + 33 + C + 3) + (aux 1) + B + 1 + +private def gp_queryPhysicalInitialBitBudget (aux : Fin 3 → GP) (P __F Amax copies J symbolBits positionBits B C : GP) : GP := + 30 * B + 20 + (10 * B + 2 * symbolBits + 4 * positionBits + B + 17) + + (gp_queryInitialProgramBitBudget aux) P Amax B ((gp_queryChargedSeedBitBudget aux) copies J B C) + +private def gp_localEligibilityBitBudget (B : GP) : GP := + 4000 * (B + 1) ^ 2 + 2100 * (4 * B + 4) ^ 2 + 2000 * (4 * B + 3) ^ 2 + + 2 * (1000 * (16 * B + 13) ^ 2 + 1) + 2 * B + 8 + +private def gp_queryExponentsBitBudget (B : GP) : GP := + (B + 1) * (gp_localEligibilityBitBudget (B + 4) + B + 5) + 2 * B + 3 + +private def gp_queryScalesBitBudget (B : GP) : GP := + gp_queryExponentsBitBudget B + (B + 1) * (B + 6) + 1 + +private def gp_queryRawCentersBitBudget (P F B : GP) : GP := + let L := (64 * F * P + 2) ^ 2 + let count := (B + 1) * L + gp_queryScalesBitBudget B + 500 * (B + 1) ^ 2 + + (B + 1) * (gp_queryGridPointsBitBudget P (16 * F) (B + 2) + L + 3) + + (count + 1) ^ 2 * (16 * B + 9) + 3 + +private def gp_queryWarmupRepresentatives (P F B : GP) : GP := + (B + 1) * (64 * F * P + 2) ^ 2 + +private def gp_localRepresentativeScaleBitBudget (P F B : GP) : GP := + let C := B + 4 + let L := 64 * F * P + 2 + 100 * (C + 2) ^ 2 + gp_gridStateBoxBitBudget L C + + L ^ 2 * (gp_localEligibilityBitBudget C + 3) + L ^ 2 * 4 + B + 6 + +private def gp_localRepresentativesBitBudget (P F B : GP) : GP := + gp_queryExponentsBitBudget B + 500 * (B + 1) ^ 2 + + (B + 1) * (gp_localRepresentativeScaleBitBudget P F B + (64 * F * P + 2) ^ 2 + 3) + 3 + +private def gp_wideChildGridBitBudget (P B : GP) : GP := + 10000 * (B + 12) ^ 2 + gp_gridStateBoxBitBudget (40 * P + 2) (B + 12) + +private def gp_queryWideInputsBitBudget (M P count B : GP) : GP := + let G := (40 * P + 2) ^ 2 + let C := gp_wideChildGridBitBudget P (B + 1) + count * (M * (C + 4 * G + 1 + G + 3) + M * G + 3) + + (count * (M * G) + 1) ^ 2 * (24 * B + 12) + M + 2 + +private def gp_queryWarmupInputsBitBudget (M P F B I : GP) : GP := + gp_localRepresentativesBitBudget P F B * (I + 2) + + gp_queryWideInputsBitBudget M P (gp_queryWarmupRepresentatives P F B) B + 1 + +private def gp_queryWarmupParentReadBudget (P F B : GP) : GP := + 16 * B + 7 + gp_queryWarmupRepresentatives P F B * (16 * B + 6) + +private def gp_queryWarmupChildReadBudget (M P F B : GP) : GP := + 1 + (gp_queryWarmupRepresentatives P F B * (M * (40 * P + 2) ^ 2)) * (24 * B + 9) + +private def gp_queryWarmupProgramBitBudget (aux : Fin 3 → GP) (M P F B C : GP) : GP := + C + gp_queryRawCentersBitBudget P F B + gp_queryWarmupRepresentatives P F B * (C + 3) + + gp_queryWarmupInputsBitBudget M P F B (gp_queryWarmupParentReadBudget P F B) + + (gp_queryWarmupRepresentatives P F B * (M * (40 * P + 2) ^ 2)) * (C + 3) + + (aux 2) * + (gp_queryWarmupParentReadBudget P F B + M * (gp_queryWarmupChildReadBudget M P F B + 3) + 4) + +private def gp_queryChargedWarmupBitBudget (aux : Fin 3 → GP) (M P F Amax copies J symbolBits positionBits B C : GP) : GP := + let I := (gp_queryPhysicalInitialBitBudget aux) P F Amax copies J symbolBits positionBits B C + 80 * (B + 1) + I + + (gp_queryWarmupProgramBitBudget aux) M P F B (I + 7 * J + 33 + C) + +private def initialWarmupPolynomial : GP := + gp_queryChargedWarmupBitBudget ![.input 10, .input 11, .input 12] + (.input 0) (.input 1) (.input 2) (.input 3) (.input 4) (.input 5) + (.input 6) (.input 7) (.input 8) (.input 9) + +def queryInitialWarmupBitDegree : ℕ := initialWarmupPolynomial.degree + +private def initialWarmupEnvironment (M P F Amax copies J symbolBits positionBits B C : ℕ) : Fin 13 → ℕ := + ![M, P, F, Amax, copies, J, symbolBits, positionBits, B, C, + BinaryFraction.cachedInitialProgramBitBudget P Amax (B + 2), + BinaryFraction.seedMedianBitBudget copies B, BinaryFraction.localWarmupBitBudget M P F B] + +private theorem initialWarmupPolynomial_eval (M P F Amax copies J symbolBits positionBits B C : ℕ) : + initialWarmupPolynomial.eval (initialWarmupEnvironment M P F Amax copies J symbolBits positionBits B C) = + queryChargedWarmupBitBudget M P F Amax copies J symbolBits positionBits B C := by + rfl + +theorem queryChargedWarmupBitBudget_fixedPower (M P F Amax copies J symbolBits positionBits B C X : ℕ) + (hX : 2 ≤ X) + (hM : M ≤ X) (hP : P ≤ X) (hF : F ≤ X) (hA : Amax ≤ X) (hc : copies ≤ X) + (hJ : J ≤ X) (hs : symbolBits ≤ X) (hp : positionBits ≤ X) (hB : B ≤ X) (hC : C ≤ X) + (hi : BinaryFraction.cachedInitialProgramBitBudget P Amax (B + 2) ≤ X) + (hm : BinaryFraction.seedMedianBitBudget copies B ≤ X) + (hw : BinaryFraction.localWarmupBitBudget M P F B ≤ X) : + queryChargedWarmupBitBudget M P F Amax copies J symbolBits positionBits B C ≤ + X ^ queryInitialWarmupBitDegree := by + rw [← initialWarmupPolynomial_eval] + apply initialWarmupPolynomial.eval_le_pow _ X hX + intro i + fin_cases i + · exact hM + · exact hP + · exact hF + · exact hA + · exact hc + · exact hJ + · exact hs + · exact hp + · exact hB + · exact hC + · exact hi + · exact hm + · exact hw + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryInputCodes.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryInputCodes.lean new file mode 100644 index 0000000000000000000000000000000000000000..3283724ae6920bb74620d06480ecccc5b4512219 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryInputCodes.lean @@ -0,0 +1,82 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryOrderedInputs +import OAI.Combinatorics.EditApproximation.Geometry.LocalRefinementQuery +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Boolean arithmetic for the existing child/history key encodings. +The sorting comparison charges both encodings and the word comparison. -/ + +namespace EditApproximation + + + +@[simp] theorem queryChildCodeWithWork_value {M n : ℕ} (input : Fin M × TargetInterval n) : + (queryChildCodeWithWork input).1 = childInputCode input := by + simp only [queryChildCodeWithWork, binaryNaturalAddWithWork_value, + binaryNaturalMulWithWork_value, childInputCode] + + + +@[simp] theorem queryPairWithWork_value (a b : ℕ) : + (queryPairWithWork a b).1 = Nat.pair a b := by + unfold queryPairWithWork Nat.pair + by_cases h : a < b + · rw [ite_eq_left ((binaryNaturalCompareWithWork_lt a b).mpr h), ite_eq_left h] + simp only [binaryNaturalAddWithWork_value, binaryNaturalMulWithWork_value] + · rw [ite_eq_right (fun ht => h ((binaryNaturalCompareWithWork_lt a b).mp ht)), ite_eq_right h] + simp only [binaryNaturalAddWithWork_value, binaryNaturalMulWithWork_value] + + + +@[simp] theorem queryHistoryCodeWithWork_value {M n : ℕ} (input : Fin M × ℕ × TargetInterval n) : + (queryHistoryCodeWithWork input).1 = historyInputCode input := by + simp only [queryHistoryCodeWithWork, queryPairWithWork_value, queryChildCodeWithWork_value, + historyInputCode] + + + +theorem queryEncodedLEWithWork_value {α : Type*} (code : α → ℕ × ℕ) (a b : α) : + (queryEncodedLEWithWork code a b).1 = decide ((code a).1 ≤ (code b).1) := by + apply Bool.eq_iff_iff.mpr + simp only [queryEncodedLEWithWork, wordLEWithWork_value, bitWordValue_bits, decide_eq_true_eq] + + + +@[simp] theorem queryOrderedChildInputsWithWork_value {M n : ℕ} + (inputs : List (Fin M × TargetInterval n)) : + (queryOrderedChildInputsWithWork inputs).1 = + orderedInputs childInputCode (childInputCode_injective M n) inputs.toFinset := by + apply queryOrderedInputsWithWork_value childInputCode (childInputCode_injective M n) + _ _ coordinateEqualWithWork_value + intro a b + simp only [queryEncodedLEWithWork_value, queryChildCodeWithWork_value] + + + +@[simp] theorem queryHistoryEqualWithWork_value {M n : ℕ} (a b : Fin M × ℕ × TargetInterval n) : + (queryHistoryEqualWithWork a b).1 = true ↔ a = b := by + simp only [queryHistoryEqualWithWork, Bool.and_eq_true, coordinateEqualWithWork_value, + naturalEqualWithWork_value, Prod.mk.injEq] + constructor + · rintro ⟨⟨hi, hq⟩, ht⟩ + exact Prod.ext hi (Prod.ext ht hq) + · intro h + subst b + exact ⟨⟨rfl, rfl⟩, rfl⟩ + + + +@[simp] theorem queryOrderedHistoryInputsWithWork_value {M n : ℕ} + (inputs : List (Fin M × ℕ × TargetInterval n)) : + (queryOrderedHistoryInputsWithWork inputs).1 = + orderedInputs historyInputCode (historyInputCode_injective M n) inputs.toFinset := by + apply queryOrderedInputsWithWork_value historyInputCode (historyInputCode_injective M n) + _ _ queryHistoryEqualWithWork_value + intro a b + simp only [queryEncodedLEWithWork_value, queryHistoryCodeWithWork_value] + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryInputSpace.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryInputSpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..6d5fc6a2e134990e9015df816471b032379c33da --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryInputSpace.lean @@ -0,0 +1,110 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryOrderedSpace +import OAI.Combinatorics.EditApproximation.Binary.BinaryGridSpace +import OAI.Combinatorics.EditApproximation.Queries.QueryActionInputs +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation + + + +theorem queryChildCodeAllocation_le_work {M n : ℕ} (input : Fin M × TargetInterval n) : + queryChildCodeAllocation input ≤ (queryChildCodeWithWork input).2 := by + have h1 := binaryNaturalAddAllocation_le_work n 1 + have h2 := binaryNaturalMulAllocation_le_work (bitWordValue (binaryNaturalAddWithWork n 1).1) input.2.hi + have h3 := binaryNaturalAddAllocation_le_work input.2.lo + (bitWordValue (binaryNaturalMulWithWork (bitWordValue (binaryNaturalAddWithWork n 1).1) input.2.hi).1) + have h4 := binaryNaturalMulAllocation_le_work M + (bitWordValue (binaryNaturalAddWithWork input.2.lo + (bitWordValue (binaryNaturalMulWithWork (bitWordValue (binaryNaturalAddWithWork n 1).1) input.2.hi).1)).1) + have h5 := binaryNaturalAddAllocation_le_work input.1.val + (bitWordValue (binaryNaturalMulWithWork M (bitWordValue (binaryNaturalAddWithWork input.2.lo + (bitWordValue (binaryNaturalMulWithWork (bitWordValue (binaryNaturalAddWithWork n 1).1) input.2.hi).1)).1)).1) + unfold queryChildCodeAllocation queryChildCodeWithWork + dsimp only + omega + + + +theorem queryPairAllocation_le_work (a b : ℕ) : queryPairAllocation a b ≤ (queryPairWithWork a b).2 := by + have hc := bitCompareWithWork_input_cells a.bits b.bits + have h1 := binaryNaturalMulAllocation_le_work b b + have h2 := binaryNaturalAddAllocation_le_work (bitWordValue (binaryNaturalMulWithWork b b).1) a + have h3 := binaryNaturalMulAllocation_le_work a a + have h4 := binaryNaturalAddAllocation_le_work (bitWordValue (binaryNaturalMulWithWork a a).1) a + have h5 := binaryNaturalAddAllocation_le_work + (bitWordValue (binaryNaturalAddWithWork (bitWordValue (binaryNaturalMulWithWork a a).1) a).1) b + change a.bits.length + b.bits.length ≤ (binaryNaturalCompareWithWork a b).2 at hc + unfold queryPairAllocation queryPairWithWork + dsimp only + split_ifs <;> dsimp only <;> omega + + + +theorem queryHistoryCodeAllocation_le_work {M n : ℕ} (input : Fin M × ℕ × TargetInterval n) : + queryHistoryCodeAllocation input ≤ (queryHistoryCodeWithWork input).2 := by + have hc := queryChildCodeAllocation_le_work (input.1, input.2.2) + have hp := queryPairAllocation_le_work input.2.1 (queryChildCodeWithWork (input.1, input.2.2)).1 + unfold queryHistoryCodeAllocation queryHistoryCodeWithWork + dsimp only + omega + + + +theorem queryEncodedLEAllocation_le_work {α : Type*} (code : α → ℕ × ℕ) (allocation : α → ℕ) + (a b : α) (h : ∀ x, allocation x ≤ (code x).2) : + queryEncodedLEAllocation code allocation a b ≤ (queryEncodedLEWithWork code a b).2 := by + have ha := h a + have hb := h b + have hc := naturalWordLEAllocation_le_work (code a).1.bits (code b).1.bits + unfold queryEncodedLEAllocation queryEncodedLEWithWork + dsimp only + omega + + + +theorem queryOrderedChildInputsAllocation_le_work {M n : ℕ} (inputs : List (Fin M × TargetInterval n)) : + queryOrderedChildInputsAllocation inputs ≤ (queryOrderedChildInputsWithWork inputs).2 := + queryOrderedInputsAllocation_le_work _ _ _ _ inputs coordinateEqualAllocation_le_work + (fun a b => queryEncodedLEAllocation_le_work _ _ a b queryChildCodeAllocation_le_work) + + + +theorem queryOrderedHistoryInputsAllocation_le_work {M n : ℕ} (inputs : List (Fin M × ℕ × TargetInterval n)) : + queryOrderedHistoryInputsAllocation inputs ≤ (queryOrderedHistoryInputsWithWork inputs).2 := + queryOrderedInputsAllocation_le_work _ _ _ _ inputs queryHistoryEqualAllocation_le_work + (fun a b => queryEncodedLEAllocation_le_work _ _ a b queryHistoryCodeAllocation_le_work) + + + +theorem queryActionInputsAllocation_le_work {Parent Child : Type*} {M : ℕ} + (actions : List (BinaryBellmanAction Parent Child M)) : + queryActionInputsAllocation actions ≤ (queryActionInputsWithWork actions).2 := by + have h := arithmeticFlatMapAllocation_le_work + (fun action => arithmeticMapWithWork (fun i : Fin M => (action.childState i, 1)) (List.finRange M)) + (fun _ => arithmeticMapAllocation (fun _ : Fin M => 1) (List.finRange M) + M) actions (by + intro action _ + simpa only [List.length_finRange] using arithmeticMapAllocation_with_spine + (fun i : Fin M => (action.childState i, 1)) (fun _ => 1) (List.finRange M) (fun _ _ => le_rfl)) + unfold queryActionInputsAllocation queryActionInputsWithWork + dsimp only + omega + + + +theorem queryNeededInputsAllocation_le_work {n M : ℕ} + (selected online : List (BinaryBellmanAction (TargetInterval n) (Fin M × TargetInterval n) M)) : + queryNeededInputsAllocation selected online ≤ (queryNeededInputsWithWork selected online).2 := by + have hf := queryActionInputsAllocation_le_work selected + have hs := queryActionInputsAllocation_le_work online + have ho := queryOrderedChildInputsAllocation_le_work + ((queryActionInputsWithWork selected).1 ++ (queryActionInputsWithWork online).1) + unfold queryNeededInputsAllocation queryNeededInputsWithWork + dsimp only + omega + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryListWork.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryListWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..ca84f886fa88356a6043325ef9d120fa86a4ad8c --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryListWork.lean @@ -0,0 +1,115 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryBandCoordinates +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! First-occurrence duplicate removal for the literal adaptive query lists. +The equality tests, accumulated list, and final reversal are charged. -/ + +namespace EditApproximation + + + + + +theorem queryEraseLoopWithWork_value {α : Type*} [BEq α] [LawfulBEq α] + (equal : α → α → Bool × ℕ) (heq : ∀ a b, (equal a b).1 = true ↔ a = b) + (xs seen : List α) : + (queryEraseLoopWithWork equal xs seen).1 = List.eraseDupsBy.loop (· == ·) xs seen := by + induction xs generalizing seen with + | nil => rfl + | cons a xs ih => + have ht : (memberByWithWork equal a seen).1 = seen.any (a == ·) := by + apply Bool.eq_iff_iff.mpr + simp only [memberByWithWork_value equal heq, List.any_eq_true, beq_iff_eq] + exact ⟨fun h => ⟨a, h, rfl⟩, fun ⟨b, hb, hab⟩ => hab ▸ hb⟩ + simp only [queryEraseLoopWithWork, ht, ih, List.eraseDupsBy.loop] + cases seen.any (a == ·) <;> rfl + +@[simp] theorem queryEraseWithWork_value {α : Type*} [BEq α] [LawfulBEq α] + (equal : α → α → Bool × ℕ) (heq : ∀ a b, (equal a b).1 = true ↔ a = b) + (xs : List α) : (queryEraseWithWork equal xs).1 = xs.eraseDups := + queryEraseLoopWithWork_value equal heq xs [] + +theorem queryEraseLoopWithWork_nodup {α : Type*} + (equal : α → α → Bool × ℕ) (heq : ∀ a b, (equal a b).1 = true ↔ a = b) + (xs seen : List α) (hs : seen.Nodup) : + (queryEraseLoopWithWork equal xs seen).1.Nodup := by + induction xs generalizing seen with + | nil => simpa only [queryEraseLoopWithWork, List.nodup_reverse] using hs + | cons a xs ih => + change (queryEraseLoopWithWork equal xs + (if (memberByWithWork equal a seen).1 then seen else a :: seen)).1.Nodup + by_cases h : (memberByWithWork equal a seen).1 = true + · rw [ite_eq_left h] + exact ih seen hs + · rw [ite_eq_right h] + apply ih + exact List.nodup_cons.mpr ⟨fun ha => h ((memberByWithWork_value equal heq a seen).mpr ha), hs⟩ + +theorem queryEraseWithWork_nodup {α : Type*} + (equal : α → α → Bool × ℕ) (heq : ∀ a b, (equal a b).1 = true ↔ a = b) + (xs : List α) : (queryEraseWithWork equal xs).1.Nodup := + queryEraseLoopWithWork_nodup equal heq xs [] (by simp) + +theorem queryEraseLoopWithWork_cost {α : Type*} (equal : α → α → Bool × ℕ) + (C : ℕ) (hC : ∀ a b, (equal a b).2 ≤ C) (xs seen : List α) : + (queryEraseLoopWithWork equal xs seen).2 ≤ + (xs.length + 1) * (xs.length + seen.length + 1) * (C + 4) := by + induction xs generalizing seen with + | nil => + simp only [queryEraseLoopWithWork, List.length_nil, zero_add, one_mul] + nlinarith + | cons a xs ih => + have hm := memberByWithWork_cost equal C hC a seen + have hs : (if (memberByWithWork equal a seen).1 then seen else a :: seen).length ≤ + seen.length + 1 := by + split + · omega + · simp only [List.length_cons]; omega + have hi := ih (if (memberByWithWork equal a seen).1 then seen else a :: seen) + have hh : (queryEraseLoopWithWork equal xs + (if (memberByWithWork equal a seen).1 then seen else a :: seen)).2 ≤ + (xs.length + 1) * (xs.length + (seen.length + 1) + 1) * (C + 4) := + hi.trans (Nat.mul_le_mul_right _ (Nat.mul_le_mul_left _ (by omega))) + change (memberByWithWork equal a seen).2 + _ + 2 ≤ _ + simp only [List.length_cons] + nlinarith only [hm, hh, Nat.zero_le xs.length, Nat.zero_le seen.length, Nat.zero_le C] + +theorem queryEraseWithWork_cost {α : Type*} (equal : α → α → Bool × ℕ) + (C : ℕ) (hC : ∀ a b, (equal a b).2 ≤ C) (xs : List α) : + (queryEraseWithWork equal xs).2 ≤ (xs.length + 1) ^ 2 * (C + 4) := by + simpa only [queryEraseWithWork, List.length_nil, Nat.add_zero, pow_two] using + queryEraseLoopWithWork_cost equal C hC xs [] + + + +@[simp] theorem queryIntervalEqualWithWork_value {n : ℕ} (a b : TargetInterval n) : + (queryIntervalEqualWithWork a b).1 = true ↔ a = b := by + simp only [queryIntervalEqualWithWork, Bool.and_eq_true, naturalEqualWithWork_value] + constructor + · rintro ⟨hl, hh⟩ + cases a + cases b + cases hl + cases hh + rfl + · intro h + subst b + exact ⟨rfl, rfl⟩ + +theorem queryIntervalEqualWithWork_cost {n : ℕ} (a b : TargetInterval n) + (B : ℕ) (hn : Nat.size n ≤ B) : + (queryIntervalEqualWithWork a b).2 ≤ 16 * B + 5 := by + have hl := naturalEqualWithWork_cost a.lo b.lo B + ((Nat.size_le_size (a.ordered.trans a.valid)).trans hn) + ((Nat.size_le_size (b.ordered.trans b.valid)).trans hn) + have hh := naturalEqualWithWork_cost a.hi b.hi B + ((Nat.size_le_size a.valid).trans hn) ((Nat.size_le_size b.valid).trans hn) + change _ + _ + 1 ≤ _ + omega + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryLocalBand.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryLocalBand.lean new file mode 100644 index 0000000000000000000000000000000000000000..a9be82125f5176ebee9b0598b79562bac55b6df7 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryLocalBand.lean @@ -0,0 +1,97 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryLocalSources +import OAI.Combinatorics.EditApproximation.Queries.QueryLocalBuffers +import OAI.Combinatorics.EditApproximation.Queries.QueryBandGather +import OAI.Combinatorics.EditApproximation.Geometry.LocalRandomDataQuery + +namespace OAI + +/-! Mass and initial words are read into counted finite buffers before +any random source range or local action is constructed. -/ + +namespace EditApproximation + +section Band +variable {ι α : Type*} (source target : List α) {M : ℕ} [NeZero M] + (parent : TargetInterval source.length) (N P F exponent H Q eM eF : ℕ) + (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) + (tau a eta kappa delta : BinaryFraction) (t : ℕ) + (parentInitial : TargetInterval target.length → BinaryFraction × ℕ) + (readMass readInitial : (Fin M × TargetInterval target.length) → BitQuery ι BinaryFraction) + (readGroup : GroupScalarKey M F Q → BitQuery ι BinaryFraction) + (readInteger : (ℕ × TargetInterval target.length) → ℕ → BitQuery ι BinaryFraction) + (q : TargetInterval target.length) + (readEarlier : (Fin M × ℕ × TargetInterval target.length) → BitQuery ι BinaryFraction) + (readCurrent : (Fin M × TargetInterval target.length) → BitQuery ι BinaryFraction) + +def queryLocalBand : BitQuery ι BinaryFraction := + queryBandGather M parent N P F exponent hP a parentInitial q readMass readInitial + fun keys massWords initialWords => + queryLocalRandomSources source target parent N P F exponent H Q eM eF hP hM hF + tau a eta kappa delta t parentInitial + (BinaryFraction.queryChildReadWithWork keys massWords) + (BinaryFraction.queryChildReadWithWork keys initialWords) + (BinaryFraction.queryDataReadBudget M target.length keys) + (BinaryFraction.queryChildReadWithWork_budget keys massWords) + (BinaryFraction.queryChildReadWithWork_budget keys initialWords) + q readGroup readInteger readEarlier readCurrent + +theorem queryLocalBand_refines + (expectedMass expectedInitial : (Fin M × TargetInterval target.length) → FiniteQuery ι) + (expectedGroup : GroupScalarKey M F Q → FiniteQuery ι) + (expectedInteger : (ℕ × TargetInterval target.length) → ℕ → FiniteQuery ι) + (expectedEarlier : (Fin M × ℕ × TargetInterval target.length) → FiniteQuery ι) + (expectedCurrent : (Fin M × TargetInterval target.length) → FiniteQuery ι) + (hm : ∀ key, BitQuery.Refines (fun word value => word.value = value) + (readMass key) (expectedMass key)) + (hi : ∀ key, BitQuery.Refines (fun word value => word.value = value) + (readInitial key) (expectedInitial key)) + (hg : ∀ key, BitQuery.Refines (fun word value => word.value = value) + (readGroup key) (expectedGroup key)) + (hz : ∀ key range, BitQuery.Refines (fun word value => word.value = value) + (readInteger key range) (expectedInteger key range)) + (he : ∀ key, BitQuery.Refines (fun word value => word.value = value) + (readEarlier key) (expectedEarlier key)) + (hr : ∀ key, BitQuery.Refines (fun word value => word.value = value) + (readCurrent key) (expectedCurrent key)) : + BitQuery.Refines (fun word value => word.value = value) + (queryLocalBand source target parent N P F exponent H Q eM eF hP hM hF + tau a eta kappa delta t parentInitial readMass readInitial readGroup readInteger + q readEarlier readCurrent) + (localRandomBandDataQuery source target parent N P F exponent H Q + tau.value a.value eta.value kappa.value delta.value t + (fun r => (parentInitial r).1.value) expectedMass expectedInitial expectedGroup expectedInteger + q expectedEarlier expectedCurrent) := by + classical + let Rp := ∑ r, (parentInitial r).2 + have hp : ∀ r, (parentInitial r).2 ≤ Rp := fun r => + Finset.single_le_sum (f := fun r => (parentInitial r).2) (fun _ _ => Nat.zero_le _) + (Finset.mem_univ r) + unfold queryLocalBand localRandomBandDataQuery + apply queryBandGather_refines M parent N P F exponent hP a parentInitial q Rp hp + readMass readInitial expectedMass expectedInitial + (expectedNext := fun keys massWords initialWords => + localRandomSourceStepQuery source target parent N P F exponent H Q + tau.value a.value eta.value kappa.value delta.value t + (fun r => (parentInitial r).1.value) + (fun i r => finiteAnswerTable keys massWords (i, r)) + (fun i r => finiteAnswerTable keys initialWords (i, r)) q + expectedGroup expectedInteger expectedEarlier expectedCurrent) + (hm := hm) (hi := hi) + intro massWords initialWords + let keys := refinementBandInputList (M := M) parent N P F exponent a.value + (fun r => (parentInitial r).1.value) q + have h := queryLocalRandomSources_refines source target parent N P F exponent H Q eM eF hP hM hF + tau a eta kappa delta t parentInitial + (BinaryFraction.queryChildReadWithWork keys massWords) + (BinaryFraction.queryChildReadWithWork keys initialWords) + (BinaryFraction.queryDataReadBudget M target.length keys) + (BinaryFraction.queryChildReadWithWork_budget keys massWords) + (BinaryFraction.queryChildReadWithWork_budget keys initialWords) + q readGroup readInteger readEarlier readCurrent expectedGroup expectedInteger expectedEarlier + expectedCurrent hg hz he hr + simpa only [BinaryFraction.queryChildReadWithWork_value] using h + +end Band +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryLocalBandCost.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryLocalBandCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..c039e184ce1ec3a773fccab4f98bf0e78d34f064 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryLocalBandCost.lean @@ -0,0 +1,131 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryLocalBand +import OAI.Combinatorics.EditApproximation.Queries.QueryLocalSourcesCost +import OAI.Combinatorics.EditApproximation.Queries.QueryOuterGatherCost +import OAI.Combinatorics.EditApproximation.Queries.QueryBufferedInputBounds +import OAI.Combinatorics.EditApproximation.Queries.QueryNumericInteger + +namespace OAI + +namespace EditApproximation.BinaryFraction + +def queryBandReadBudget (M P F exponent B : ℕ) : ℕ := + 1 + queryEarlierRepresentativesLength P F exponent B * (M * (40 * P + 2) ^ 2) * (24 * B + 9) + +theorem queryLocalSourcesBitBudget_mono_reads (M N P F exponent eM eF B S t Rp W R R' : ℕ) + (hR : R ≤ R') : + queryLocalSourcesBitBudget M N P F exponent eM eF B S t Rp R W ≤ + queryLocalSourcesBitBudget M N P F exponent eM eF B S t Rp R' W := by + unfold queryLocalSourcesBitBudget queryGroupGatherBitBudget queryOnlineGatherBitBudget + queryOnlineRangeBitBudget queryLocalRefinementBitBudget queryRefinementStagesBudget + queryRefinementReadBudget tableReadFactor + dsimp only + gcongr + +def queryLocalBandBitBudget (M N P F exponent eM eF B S t Rp W : ℕ) : ℕ := + queryBandGatherBitBudget M P F exponent B Rp W + (queryLocalSourcesBitBudget M N P F exponent eM eF B S t Rp + (queryBandReadBudget M P F exponent B) W) + +end EditApproximation.BinaryFraction + +namespace EditApproximation +section Band +variable {ι α : Type*} (source target : List α) {M : ℕ} [NeZero M] + (parent : TargetInterval source.length) (N P F exponent H Q eM eF B E S : ℕ) + (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) + (tau a eta kappa delta : BinaryFraction) (t : ℕ) + (parentInitial : TargetInterval target.length → BinaryFraction × ℕ) + (readMass readInitial : (Fin M × TargetInterval target.length) → BitQuery ι BinaryFraction) + (readGroup : GroupScalarKey M F Q → BitQuery ι BinaryFraction) + (readInteger : (ℕ × TargetInterval target.length) → ℕ → BitQuery ι BinaryFraction) + (q : TargetInterval target.length) + (readEarlier : (Fin M × ℕ × TargetInterval target.length) → BitQuery ι BinaryFraction) + (readCurrent : (Fin M × TargetInterval target.length) → BitQuery ι BinaryFraction) + (oracle : ι → BinaryFraction) (readWork : ι → ℕ) + +open BinaryFraction + +theorem queryLocalBand_work_bound (Rp W : ℕ) + (hn : PreparedKernelNumericBounds (nx := source.length) (ny := target.length) (M := M) + N P F exponent H Q eM eF B E S (t - 1) tau a eta kappa delta (fun _ _ => 0)) + (htime : 0 < t) (ht : Nat.size t ≤ B) (hPd : ∃ j : ℕ, P = 2 ^ j) + (hp : ∀ r, (parentInitial r).2 ≤ Rp) + (hpW : ∀ r, (parentInitial r).1.width ≤ B) + (hpN : ∀ r, 0 ≤ (parentInitial r).1.value) + (hmW : ∀ key, ((readMass key).value oracle).width ≤ B) + (hiW : ∀ key, ((readInitial key).value oracle).width ≤ B) + (hgW : ∀ key, ((readGroup key).value oracle).width ≤ B) + (hzW : ∀ key range, ((readInteger key range).value oracle).width ≤ B) + (heW : ∀ key, ((readEarlier key).value oracle).width ≤ B) + (hcW : ∀ key, ((readCurrent key).value oracle).width ≤ B) + (hiN : ∀ key, 0 ≤ ((readInitial key).value oracle).value) + (heN : ∀ key, 0 ≤ ((readEarlier key).value oracle).value) + (heI : ∀ key, ((readEarlier key).value oracle).value ≤ + ((readInitial (key.1, key.2.2)).value oracle).value) + (hmR : ∀ key, (readMass key).work oracle readWork ≤ W) + (hiR : ∀ key, (readInitial key).work oracle readWork ≤ W) + (hgR : ∀ key, queryGroupKeySize key ≤ 40 * B + 500 → + (readGroup key).work oracle readWork ≤ W) + (hzR : ∀ key range, Nat.size key.1 ≤ B + 1 → Nat.size range ≤ 240 * (B + 5) + 7 → + (readInteger key range).work oracle readWork ≤ W) + (heR : ∀ key, Nat.size key.2.1 ≤ B → (readEarlier key).work oracle readWork ≤ W) + (hcR : ∀ key, (readCurrent key).work oracle readWork ≤ W) : + (queryLocalBand source target parent N P F exponent H Q eM eF hP hM hF + tau a eta kappa delta t parentInitial readMass readInitial readGroup readInteger + q readEarlier readCurrent).work oracle readWork ≤ + queryLocalBandBitBudget M N P F exponent eM eF B S t Rp W := by + have hB : 10 ≤ B := hn.largeBits + have hnx : Nat.size source.length ≤ B := by have := hn.sourceSize; omega + have hny : Nat.size target.length ≤ B := by have := hn.targetSize; omega + have hMb : Nat.size M ≤ B := by have := hn.aritySize; omega + have hFpos : 1 ≤ F := by rw [hF]; exact Nat.one_le_two_pow + let keys := (queryBandInputsWithWork M parent N P F exponent hP a parentInitial q).1 + let massWords := keys.map fun key => (readMass key).value oracle + let initialWords := keys.map fun key => (readInitial key).value oracle + let R := queryDataReadBudget M target.length keys + have hk := (queryBandInputsWithWork_bounds M N P F exponent B Rp parent hP a parentInitial q + (by omega) hn.inputSize hn.factorSize hFpos hn.precisionSize hnx hny hMb hn.thetaSize + hn.factorWidth hpW hp (hpN q) hPd).1 + have hR : R ≤ queryBandReadBudget M P F exponent B := by + dsimp only [R, queryDataReadBudget, queryBandReadBudget] + apply Nat.add_le_add_left + exact Nat.mul_le_mul hk (by omega) + unfold queryLocalBand queryLocalBandBitBudget + apply queryBandGather_work_bound M N P F exponent B Rp W _ parent hP a parentInitial q + readMass readInitial _ oracle readWork (by omega) hn.inputSize hn.factorSize hFpos + hn.precisionSize hnx hny hMb hn.thetaSize hn.factorWidth hpW hp (hpN q) hPd hmR hiR + apply le_trans _ (queryLocalSourcesBitBudget_mono_reads M N P F exponent eM eF B S t Rp W R _ hR) + apply queryLocalRandomSources_work_bound source target parent N P F exponent H Q eM eF B E S hP hM hF + tau a eta kappa delta t parentInitial (queryChildReadWithWork keys massWords) + (queryChildReadWithWork keys initialWords) R + (queryChildReadWithWork_budget keys massWords) (queryChildReadWithWork_budget keys initialWords) + q readGroup readInteger readEarlier readCurrent oracle readWork Rp W htime ht hPd hp + hgW hzW heW hcW hgR hzR heR hcR + dsimp only + apply queryBufferedRefinementInputBounds parent N P F exponent H Q eM eF B E S t Rp hP + tau a eta kappa delta parentInitial hp q massWords _ _ + (fun key => (readEarlier key).value oracle) (fun key => (readInitial key).value oracle) _ + · apply hn.with_integer + intro b r + apply queryOnlineIntegerReadWithWork_size _ _ b r B (by omega) + intro w hw + obtain ⟨key, _, rfl⟩ := List.mem_map.mp hw + exact hzW key _ + · exact hpW + · exact hpN + · intro w hw + obtain ⟨key, _, rfl⟩ := List.mem_map.mp hw + exact hmW key + · intro w hw + obtain ⟨key, _, rfl⟩ := List.mem_map.mp hw + exact hcW key + · exact hiW + · exact heW + · exact hiN + · exact heN + · exact heI + +end Band +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryLocalBuffers.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryLocalBuffers.lean new file mode 100644 index 0000000000000000000000000000000000000000..f8e30eb6a82c882afed22459d555741a4ed88a7e --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryLocalBuffers.lean @@ -0,0 +1,34 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryDataBuffers +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Finite reader budgets for the executable adaptive program. These +uniform bounds follow from stored-key widths, regardless of answer values. -/ + +namespace EditApproximation.BinaryFraction + + + +theorem queryChildReadWithWork_budget {M n : ℕ} (keys : List (Fin M × TargetInterval n)) + (words : List BinaryFraction) (i : Fin M) (r : TargetInterval n) : + (queryChildReadWithWork keys words i r).2 ≤ queryDataReadBudget M n keys := by + exact queryChildReadWithWork_cost keys words i r _ (Nat.le_max_left _ _) (Nat.le_max_right _ _) + + + +@[simp] theorem queryParentReadWithWork_value {n : ℕ} (keys : List (TargetInterval n)) + (words : List BinaryFraction) (r : TargetInterval n) : + (queryParentReadWithWork keys words r).1.value = finiteAnswerTable keys (words.map value) r := + gatheredWordLookupWithWork_value _ queryIntervalEqualWithWork_value keys words r + +theorem queryParentReadWithWork_cost {n : ℕ} (keys : List (TargetInterval n)) + (words : List BinaryFraction) (r : TargetInterval n) : + (queryParentReadWithWork keys words r).2 ≤ 1 + keys.length * (16 * Nat.size n + 6) := by + exact gatheredWordLookupWithWork_cost queryIntervalEqualWithWork (16 * Nat.size n + 5) + (fun a b => queryIntervalEqualWithWork_cost a b _ le_rfl) keys words r + +end EditApproximation.BinaryFraction + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryLocalFinishCost.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryLocalFinishCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..dc6f2f1493d3f67172e77050df8e0c553962e8d5 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryLocalFinishCost.lean @@ -0,0 +1,99 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryFinishCost +import OAI.Combinatorics.EditApproximation.Queries.QuerySelectorGeometry +import OAI.Combinatorics.EditApproximation.Queries.QueryActionInputCost + +namespace OAI + +/-! The executed refinement tail, with its actual selected actions and +its final deduplicated current-input buffer. -/ + +namespace EditApproximation.BinaryFraction + +def queryFinishReadBudget (M B Rp earlierCount groups online : ℕ) : ℕ := + Rp + 2 + earlierCount * (32 * B + 12) + (groups + online) * M * (24 * B + 9) + +section Finish +variable {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (N P F exponent H Q eM eF : ℕ) + (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) + (tau a eta kappa delta : BinaryFraction) (t : ℕ) + (parentInitial : TargetInterval target.length → BinaryFraction × ℕ) + (child initial : Fin M → TargetInterval target.length → BinaryFraction × ℕ) + (R : ℕ) (hc : ∀ i r, (child i r).2 ≤ R) (hi : ∀ i r, (initial i r).2 ≤ R) + (draw : CountedCellGroupDraws M F Q) + (integer : ℕ → TargetInterval target.length → ℕ × ℕ) + (earlierKeys : List (Fin M × ℕ × TargetInterval target.length)) (earlierWords : List BinaryFraction) + (sharedKeys : List (Fin M × TargetInterval target.length)) (sharedWords currentWords : List BinaryFraction) + (q : TargetInterval target.length) + +theorem queryLocalRefinement_finish_bounds (B Rp earlierCount : ℕ) + (hB : 10 ≤ B) (hN : Nat.size N ≤ B) (hnx : Nat.size source.length ≤ B) + (hny : Nat.size target.length + 2 ≤ B) (hMb : Nat.size M ≤ B) (hPb : Nat.size P ≤ B) + (hFb : Nat.size F + 2 ≤ B) (ht : Nat.size t ≤ B) (ha : a.width ≤ B) (hd : delta.width ≤ B) + (hpw : ∀ r, (parentInitial r).1.width ≤ B) (hpr : ∀ r, (parentInitial r).2 ≤ Rp) + (hpn : 0 ≤ (parentInitial q).1.value) + (hew : ∀ w ∈ earlierWords, w.width ≤ B) (hcw : ∀ w ∈ currentWords, w.width ≤ B) + (het : ∀ key ∈ earlierKeys, Nat.size key.2.1 ≤ B) (hel : earlierKeys.length ≤ earlierCount) : + let groups := (queryGroupSelectWithWork source target parent N P F exponent Q eM eF hP hM hF + tau a parentInitial child initial R hc hi draw sharedKeys sharedWords q).1 + let online := (queryOnlineSelectWithWork source target parent N P F exponent H hP tau a eta kappa + parentInitial child initial R hc hi t integer earlierKeys earlierWords q).1 + let keys := (queryNeededInputsWithWork groups online).1 + let G := (B + 1) * ((32 * F + 2) * 2 ^ exponent + 2) ^ 2 + let lookup := queryFinishReadBudget M B Rp earlierCount G (B + 1) + (queryRefinementFinishWithWork parent N P F a delta parentInitial t earlierKeys earlierWords + groups online keys currentWords q).1.width ≤ preparedKernelWordBudget M B ∧ + (queryRefinementFinishWithWork parent N P F a delta parentInitial t earlierKeys earlierWords + groups online keys currentWords q).2 ≤ queryRefinementFinishBitBudget M P F B lookup G (B + 1) := by + let groups := (queryGroupSelectWithWork source target parent N P F exponent Q eM eF hP hM hF + tau a parentInitial child initial R hc hi draw sharedKeys sharedWords q).1 + let online := (queryOnlineSelectWithWork source target parent N P F exponent H hP tau a eta kappa + parentInitial child initial R hc hi t integer earlierKeys earlierWords q).1 + let keys := (queryNeededInputsWithWork groups online).1 + let G := (B + 1) * ((32 * F + 2) * 2 ^ exponent + 2) ^ 2 + let lookup := queryFinishReadBudget M B Rp earlierCount G (B + 1) + have hg := queryGroupSelectWithWork_geometry source target parent N P F exponent Q eM eF hP hM hF + tau a parentInitial child initial R hc hi draw sharedKeys sharedWords q B hN hny hpn + have hgc := (queryGroupSelectWithWork_geometry source target parent N P F exponent Q eM eF hP hM hF + tau a parentInitial child initial R hc hi draw sharedKeys sharedWords q (B + 4) + (by omega) (by omega) hpn).2 + have ho := queryOnlineSelectWithWork_geometry source target parent N P F exponent H hP tau a eta kappa + parentInitial child initial R hc hi t integer earlierKeys earlierWords q B hN + have hk := (queryNeededInputsWithWork_bounds groups online B hMb (by omega)).1 + have hkl : keys.length ≤ (G + (B + 1)) * M := by + exact hk.trans (Nat.mul_le_mul_right M (Nat.add_le_add hg.1 ho.1)) + apply queryRefinementFinishWithWork_bounds parent N P F B lookup G (B + 1) a delta parentInitial t + earlierKeys earlierWords groups online keys currentWords q hB hP + (by rw [hF]; exact Nat.one_le_two_pow) hN hnx hny hMb hPb hFb ha hd hpw + · intro r + have hr := hpr r + dsimp only [lookup, queryFinishReadBudget] + omega + · intro input + exact queryHistoryReadWithWork_width earlierKeys earlierWords (t - 1) input B (by omega) hew + · intro input + have hr := queryHistoryReadWithWork_cost earlierKeys earlierWords (t - 1) input B hMb (by omega) + ((Nat.size_le_size (Nat.sub_le t 1)).trans ht) het + have hm := Nat.mul_le_mul_right (32 * B + 12) hel + dsimp only [lookup, queryFinishReadBudget] + omega + · intro i r + exact gatheredWordLookupWithWork_width _ keys currentWords (i, r) B (by omega) hcw + · intro i r + have hr := queryChildReadWithWork_cost keys currentWords i r B hMb (by omega) + have hm := Nat.mul_le_mul_right (24 * B + 9) hkl + dsimp only [lookup, queryFinishReadBudget] + omega + · exact hgc + · intro action haction + rw [ho.2 action haction] + change 1 ≤ connectionWordBudget M (B + 4) + unfold connectionWordBudget bandMassTotalStorageBudget + omega + · exact hg.1 + · exact ho.1 + +end Finish +end EditApproximation.BinaryFraction + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryLocalProgram.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryLocalProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..c78da8f0aaf0ef1d957190de4db1f28705ddf413 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryLocalProgram.lean @@ -0,0 +1,78 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryLocalBand + +namespace OAI + +/-! The concrete adaptive local program, beginning with the parent query. +Every intermediate buffer is constructed after the answers determining +its support, and every scalar source range is computed before its read. -/ + +namespace EditApproximation + +section Program +variable {ι α : Type*} (source target : List α) {M : ℕ} [NeZero M] + (parent : TargetInterval source.length) (N P F exponent H Q eM eF : ℕ) + (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) + (tau a eta kappa delta : BinaryFraction) (t : ℕ) + (readParent : TargetInterval target.length → BitQuery ι BinaryFraction) + (readMass readInitial : (Fin M × TargetInterval target.length) → BitQuery ι BinaryFraction) + (readGroup : GroupScalarKey M F Q → BitQuery ι BinaryFraction) + (readInteger : (ℕ × TargetInterval target.length) → ℕ → BitQuery ι BinaryFraction) + (q : TargetInterval target.length) + (readEarlier : (Fin M × ℕ × TargetInterval target.length) → BitQuery ι BinaryFraction) + (readCurrent : (Fin M × TargetInterval target.length) → BitQuery ι BinaryFraction) + +def queryLocalProgram : BitQuery ι BinaryFraction := + queryInitialGather N P F exponent hP a q readParent fun keys words => + queryLocalBand source target parent N P F exponent H Q eM eF hP hM hF + tau a eta kappa delta t (BinaryFraction.queryParentReadWithWork keys words) + readMass readInitial readGroup readInteger q readEarlier readCurrent + +theorem queryLocalProgram_refines + (expectedParent : TargetInterval target.length → FiniteQuery ι) + (expectedMass expectedInitial : (Fin M × TargetInterval target.length) → FiniteQuery ι) + (expectedGroup : GroupScalarKey M F Q → FiniteQuery ι) + (expectedInteger : (ℕ × TargetInterval target.length) → ℕ → FiniteQuery ι) + (expectedEarlier : (Fin M × ℕ × TargetInterval target.length) → FiniteQuery ι) + (expectedCurrent : (Fin M × TargetInterval target.length) → FiniteQuery ι) + (hp : ∀ key, BitQuery.Refines (fun word value => word.value = value) + (readParent key) (expectedParent key)) + (hm : ∀ key, BitQuery.Refines (fun word value => word.value = value) + (readMass key) (expectedMass key)) + (hi : ∀ key, BitQuery.Refines (fun word value => word.value = value) + (readInitial key) (expectedInitial key)) + (hg : ∀ key, BitQuery.Refines (fun word value => word.value = value) + (readGroup key) (expectedGroup key)) + (hz : ∀ key range, BitQuery.Refines (fun word value => word.value = value) + (readInteger key range) (expectedInteger key range)) + (he : ∀ key, BitQuery.Refines (fun word value => word.value = value) + (readEarlier key) (expectedEarlier key)) + (hr : ∀ key, BitQuery.Refines (fun word value => word.value = value) + (readCurrent key) (expectedCurrent key)) : + BitQuery.Refines (fun word value => word.value = value) + (queryLocalProgram source target parent N P F exponent H Q eM eF hP hM hF + tau a eta kappa delta t readParent readMass readInitial readGroup readInteger + q readEarlier readCurrent) + (localRandomDataQuery source target parent N P F exponent H Q + tau.value a.value eta.value kappa.value delta.value t + expectedParent expectedMass expectedInitial expectedGroup expectedInteger + q expectedEarlier expectedCurrent) := by + unfold queryLocalProgram localRandomDataQuery + apply queryInitialGather_refines N P F exponent hP a q readParent expectedParent + (expectedNext := fun keys words => + localRandomBandDataQuery source target parent N P F exponent H Q + tau.value a.value eta.value kappa.value delta.value t + (finiteAnswerTable keys words) expectedMass expectedInitial expectedGroup expectedInteger + q expectedEarlier expectedCurrent) (hr := hp) + intro value words + let keys := refinementInitialSupport N P F exponent a.value value.value q + have h := queryLocalBand_refines source target parent N P F exponent H Q eM eF hP hM hF + tau a eta kappa delta t (BinaryFraction.queryParentReadWithWork keys words) + readMass readInitial readGroup readInteger q readEarlier readCurrent + expectedMass expectedInitial expectedGroup expectedInteger expectedEarlier expectedCurrent + hm hi hg hz he hr + simpa only [BinaryFraction.queryParentReadWithWork_value] using h + +end Program +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryLocalProgramCost.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryLocalProgramCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..147d967967c3e8082f386747bb3940445a22696a --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryLocalProgramCost.lean @@ -0,0 +1,106 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryLocalProgram +import OAI.Combinatorics.EditApproximation.Queries.QueryLocalBandCost + +namespace OAI + +/-! A complete work bound for the actual adaptive local program. Premises +are numeric parameter bounds, stored-word sizes, and the existing history +range invariant; all intermediate enumeration and scans are included. -/ + +namespace EditApproximation.BinaryFraction + +def queryParentBufferReadBudget (P F exponent B : ℕ) : ℕ := + 1 + queryInitialSupportLength P F exponent B * (16 * B + 6) + +def queryLocalProgramBitBudget (M N P F exponent eM eF B S t W : ℕ) : ℕ := + queryInitialGatherBitBudget P F exponent B W + (queryLocalBandBitBudget M N P F exponent eM eF B S t + (queryParentBufferReadBudget P F exponent B) W) + +end EditApproximation.BinaryFraction + +namespace EditApproximation +section Program +variable {ι α : Type*} (source target : List α) {M : ℕ} [NeZero M] + (parent : TargetInterval source.length) (N P F exponent H Q eM eF B E S : ℕ) + (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) + (tau a eta kappa delta : BinaryFraction) (t : ℕ) + (readParent : TargetInterval target.length → BitQuery ι BinaryFraction) + (readMass readInitial : (Fin M × TargetInterval target.length) → BitQuery ι BinaryFraction) + (readGroup : GroupScalarKey M F Q → BitQuery ι BinaryFraction) + (readInteger : (ℕ × TargetInterval target.length) → ℕ → BitQuery ι BinaryFraction) + (q : TargetInterval target.length) + (readEarlier : (Fin M × ℕ × TargetInterval target.length) → BitQuery ι BinaryFraction) + (readCurrent : (Fin M × TargetInterval target.length) → BitQuery ι BinaryFraction) + (oracle : ι → BinaryFraction) (readWork : ι → ℕ) + +open BinaryFraction + +theorem queryLocalProgram_work_bound (W : ℕ) + (hn : PreparedKernelNumericBounds (nx := source.length) (ny := target.length) (M := M) + N P F exponent H Q eM eF B E S (t - 1) tau a eta kappa delta (fun _ _ => 0)) + (htime : 0 < t) (ht : Nat.size t ≤ B) (hPd : ∃ j : ℕ, P = 2 ^ j) + (hpW : ∀ key, ((readParent key).value oracle).width ≤ B) + (hmW : ∀ key, ((readMass key).value oracle).width ≤ B) + (hiW : ∀ key, ((readInitial key).value oracle).width ≤ B) + (hgW : ∀ key, ((readGroup key).value oracle).width ≤ B) + (hzW : ∀ key range, ((readInteger key range).value oracle).width ≤ B) + (heW : ∀ key, ((readEarlier key).value oracle).width ≤ B) + (hcW : ∀ key, ((readCurrent key).value oracle).width ≤ B) + (hpN : ∀ key, 0 ≤ ((readParent key).value oracle).value) + (hiN : ∀ key, 0 ≤ ((readInitial key).value oracle).value) + (heN : ∀ key, 0 ≤ ((readEarlier key).value oracle).value) + (heI : ∀ key, ((readEarlier key).value oracle).value ≤ + ((readInitial (key.1, key.2.2)).value oracle).value) + (hpR : ∀ key, (readParent key).work oracle readWork ≤ W) + (hmR : ∀ key, (readMass key).work oracle readWork ≤ W) + (hiR : ∀ key, (readInitial key).work oracle readWork ≤ W) + (hgR : ∀ key, queryGroupKeySize key ≤ 40 * B + 500 → + (readGroup key).work oracle readWork ≤ W) + (hzR : ∀ key range, Nat.size key.1 ≤ B + 1 → Nat.size range ≤ 240 * (B + 5) + 7 → + (readInteger key range).work oracle readWork ≤ W) + (heR : ∀ key, Nat.size key.2.1 ≤ B → (readEarlier key).work oracle readWork ≤ W) + (hcR : ∀ key, (readCurrent key).work oracle readWork ≤ W) : + (queryLocalProgram source target parent N P F exponent H Q eM eF hP hM hF + tau a eta kappa delta t readParent readMass readInitial readGroup readInteger + q readEarlier readCurrent).work oracle readWork ≤ + queryLocalProgramBitBudget M N P F exponent eM eF B S t W := by + have hB : 10 ≤ B := hn.largeBits + have hny : Nat.size target.length ≤ B := by have := hn.targetSize; omega + have hFpos : 1 ≤ F := by rw [hF]; exact Nat.one_le_two_pow + let keys := (queryInitialSupportWithWork N P F exponent hP a ((readParent q).value oracle) q).1 + let words := keys.map fun key => (readParent key).value oracle + have hkeys := (queryInitialSupportWithWork_bounds N P F exponent B hP a ((readParent q).value oracle) q + (by omega) hn.inputSize hn.factorSize hFpos hn.precisionSize hny hn.thetaSize + hn.factorWidth (hpW q) (hpN q) hPd).1 + have hpw : ∀ w ∈ words, w.width ≤ B := by + intro w hw + obtain ⟨key, _, rfl⟩ := List.mem_map.mp hw + exact hpW key + have hpr : ∀ r, (queryParentReadWithWork keys words r).2 ≤ queryParentBufferReadBudget P F exponent B := by + intro r + apply (queryParentReadWithWork_cost keys words r).trans + unfold queryParentBufferReadBudget + exact Nat.add_le_add_left (Nat.mul_le_mul hkeys (by omega)) 1 + have hpn : ∀ r, 0 ≤ (queryParentReadWithWork keys words r).1.value := by + intro r + rw [queryParentReadWithWork_value] + apply finiteAnswerTable_nonneg + intro v hv + obtain ⟨w, hw, rfl⟩ := List.mem_map.mp hv + obtain ⟨key, _, rfl⟩ := List.mem_map.mp hw + exact hpN key + unfold queryLocalProgram queryLocalProgramBitBudget + apply queryInitialGather_work_bound N P F exponent B W _ hP a q readParent _ oracle readWork + (by omega) hn.inputSize hn.factorSize hFpos hn.precisionSize hny hn.thetaSize + hn.factorWidth (hpW q) (hpN q) hPd hpR + apply queryLocalBand_work_bound source target parent N P F exponent H Q eM eF B E S hP hM hF + tau a eta kappa delta t (queryParentReadWithWork keys words) readMass readInitial readGroup readInteger + q readEarlier readCurrent oracle readWork _ W hn htime ht hPd hpr + (fun r => gatheredWordLookupWithWork_width _ keys words r B (by omega) hpw) hpn + hmW hiW hgW hzW heW hcW hiN heN heI hmR hiR hgR hzR heR hcR + +end Program +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryLocalProgramSpace.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryLocalProgramSpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..a34cfb482d8a9a19edadffccf5c1ecad04042be5 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryLocalProgramSpace.lean @@ -0,0 +1,112 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryRefinementSpace +import OAI.Combinatorics.EditApproximation.Queries.QueryLocalProgram + +namespace OAI + +namespace EditApproximation +open BitQuery + +section Sources +variable {ι α : Type*} (source target : List α) {M : ℕ} [NeZero M] + (parent : TargetInterval source.length) (N P F exponent H Q eM eF : ℕ) + (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) + (tau a eta kappa delta : BinaryFraction) (t : ℕ) + (parentInitial : TargetInterval target.length → BinaryFraction × ℕ) + (child initial : Fin M → TargetInterval target.length → BinaryFraction × ℕ) + (R : ℕ) (hc : ∀ i r, (child i r).2 ≤ R) (hi : ∀ i r, (initial i r).2 ≤ R) + (parentAllocation : TargetInterval target.length → ℕ) + (childAllocation initialAllocation : Fin M → TargetInterval target.length → ℕ) + (hp : ∀ r, parentAllocation r ≤ (parentInitial r).2) + (hca : ∀ i r, childAllocation i r ≤ (child i r).2) + (hia : ∀ i r, initialAllocation i r ≤ (initial i r).2) + (q : TargetInterval target.length) + (readGroup : GroupScalarKey M F Q → BitQuery ι BinaryFraction) + (readInteger : (ℕ × TargetInterval target.length) → ℕ → BitQuery ι BinaryFraction) + (readEarlier : (Fin M × ℕ × TargetInterval target.length) → BitQuery ι BinaryFraction) + (readCurrent : (Fin M × TargetInterval target.length) → BitQuery ι BinaryFraction) + (hg : ∀ key, Heap (readGroup key)) (hz : ∀ key range, Heap (readInteger key range)) + (he : ∀ key, Heap (readEarlier key)) (hr : ∀ key, Heap (readCurrent key)) + +open BinaryFraction in +def queryLocalRandomSourcesHeap : Heap (queryLocalRandomSources source target parent N P F exponent H Q eM eF + hP hM hF tau a eta kappa delta t parentInitial child initial R hc hi q + readGroup readInteger readEarlier readCurrent) := + queryGroupSourceGatherHeap M N F Q exponent eM eF hM hF a parentInitial parentAllocation hp q + readGroup hg _ fun groupKeys groupWords => + queryOnlineSourceGatherHeap parent N P F exponent H hP tau a parentInitial parentAllocation + child childAllocation hp hca q readInteger hz _ fun onlineKeys onlineWords => + queryLocalRefinementHeap source target parent N P F exponent H Q eM eF hP hM hF + tau a eta kappa delta t parentInitial child initial R hc hi + (queryGroupDrawReadWithWork groupKeys groupWords) + (queryOnlineIntegerReadWithWork onlineKeys onlineWords) + parentAllocation childAllocation initialAllocation + (queryGroupDrawReadAllocation groupKeys groupWords) + (queryOnlineIntegerReadAllocation onlineKeys onlineWords) + hp hca hia (queryGroupDrawReadAllocation_le_work groupKeys groupWords) + (queryOnlineIntegerReadAllocation_le_work onlineKeys onlineWords) q readEarlier readCurrent he hr + +end Sources + +section Band +variable {ι α : Type*} (source target : List α) {M : ℕ} [NeZero M] + (parent : TargetInterval source.length) (N P F exponent H Q eM eF : ℕ) + (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) + (tau a eta kappa delta : BinaryFraction) (t : ℕ) + (parentInitial : TargetInterval target.length → BinaryFraction × ℕ) + (parentAllocation : TargetInterval target.length → ℕ) + (hp : ∀ r, parentAllocation r ≤ (parentInitial r).2) + (readMass readInitial : (Fin M × TargetInterval target.length) → BitQuery ι BinaryFraction) + (readGroup : GroupScalarKey M F Q → BitQuery ι BinaryFraction) + (readInteger : (ℕ × TargetInterval target.length) → ℕ → BitQuery ι BinaryFraction) + (q : TargetInterval target.length) + (readEarlier : (Fin M × ℕ × TargetInterval target.length) → BitQuery ι BinaryFraction) + (readCurrent : (Fin M × TargetInterval target.length) → BitQuery ι BinaryFraction) + (hm : ∀ key, Heap (readMass key)) (hi : ∀ key, Heap (readInitial key)) + (hg : ∀ key, Heap (readGroup key)) (hz : ∀ key range, Heap (readInteger key range)) + (he : ∀ key, Heap (readEarlier key)) (hr : ∀ key, Heap (readCurrent key)) + +open BinaryFraction in +def queryLocalBandHeap : Heap (queryLocalBand source target parent N P F exponent H Q eM eF hP hM hF + tau a eta kappa delta t parentInitial readMass readInitial readGroup readInteger q readEarlier readCurrent) := + queryBandGatherHeap M parent N P F exponent hP a parentInitial parentAllocation hp q readMass readInitial hm hi _ + fun keys massWords initialWords => + queryLocalRandomSourcesHeap source target parent N P F exponent H Q eM eF hP hM hF + tau a eta kappa delta t parentInitial + (queryChildReadWithWork keys massWords) (queryChildReadWithWork keys initialWords) + (queryDataReadBudget M target.length keys) + (queryChildReadWithWork_budget keys massWords) (queryChildReadWithWork_budget keys initialWords) + parentAllocation (queryChildReadAllocation keys massWords) (queryChildReadAllocation keys initialWords) + hp (queryChildReadAllocation_le_work keys massWords) (queryChildReadAllocation_le_work keys initialWords) + q readGroup readInteger readEarlier readCurrent hg hz he hr + +end Band + +section Program +variable {ι α : Type*} (source target : List α) {M : ℕ} [NeZero M] + (parent : TargetInterval source.length) (N P F exponent H Q eM eF : ℕ) + (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) + (tau a eta kappa delta : BinaryFraction) (t : ℕ) + (readParent : TargetInterval target.length → BitQuery ι BinaryFraction) + (readMass readInitial : (Fin M × TargetInterval target.length) → BitQuery ι BinaryFraction) + (readGroup : GroupScalarKey M F Q → BitQuery ι BinaryFraction) + (readInteger : (ℕ × TargetInterval target.length) → ℕ → BitQuery ι BinaryFraction) + (q : TargetInterval target.length) + (readEarlier : (Fin M × ℕ × TargetInterval target.length) → BitQuery ι BinaryFraction) + (readCurrent : (Fin M × TargetInterval target.length) → BitQuery ι BinaryFraction) + (hp : ∀ key, Heap (readParent key)) + (hm : ∀ key, Heap (readMass key)) (hi : ∀ key, Heap (readInitial key)) + (hg : ∀ key, Heap (readGroup key)) (hz : ∀ key range, Heap (readInteger key range)) + (he : ∀ key, Heap (readEarlier key)) (hr : ∀ key, Heap (readCurrent key)) + +open BinaryFraction in +def queryLocalProgramHeap : Heap (queryLocalProgram source target parent N P F exponent H Q eM eF hP hM hF + tau a eta kappa delta t readParent readMass readInitial readGroup readInteger q readEarlier readCurrent) := + queryInitialGatherHeap N P F exponent hP a q readParent hp _ fun keys words => + queryLocalBandHeap source target parent N P F exponent H Q eM eF hP hM hF tau a eta kappa delta t + (queryParentReadWithWork keys words) (queryParentReadAllocation keys words) (queryParentReadAllocation_le_work keys words) + readMass readInitial readGroup readInteger q readEarlier readCurrent hm hi hg hz he hr + +end Program +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryLocalRefinement.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryLocalRefinement.lean new file mode 100644 index 0000000000000000000000000000000000000000..cf07204871e2a8819611b3bedafba772127b4f2c --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryLocalRefinement.lean @@ -0,0 +1,100 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryLocalSelectors +import OAI.Combinatorics.EditApproximation.Queries.QueryRefinementGather +import OAI.Combinatorics.EditApproximation.Queries.QueryRefinementFinish + +namespace OAI + +/-! The complete charged local refinement request: earlier history, shared +samples, selected current inputs and the final binary continuation. -/ + +namespace EditApproximation + +section Local +variable {ι α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (N P F exponent H Q eM eF : ℕ) + (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) + (tau a eta kappa delta : BinaryFraction) (t : ℕ) + (parentInitial : TargetInterval target.length → BinaryFraction × ℕ) + (child initial : Fin M → TargetInterval target.length → BinaryFraction × ℕ) + (R : ℕ) (hc : ∀ i r, (child i r).2 ≤ R) (hi : ∀ i r, (initial i r).2 ≤ R) + (draw : CountedCellGroupDraws M F Q) + (integer : ℕ → TargetInterval target.length → ℕ × ℕ) + (q : TargetInterval target.length) + (readEarlier : (Fin M × ℕ × TargetInterval target.length) → BitQuery ι BinaryFraction) + (readCurrent : (Fin M × TargetInterval target.length) → BitQuery ι BinaryFraction) + +def queryLocalRefinement : BitQuery ι BinaryFraction := + queryRefinementGather source target parent N P F exponent Q eM eF hP hM hF a t parentInitial draw q + readEarlier readCurrent + (fun keys words => BinaryFraction.queryOnlineSelectWithWork source target parent N P F exponent H hP + tau a eta kappa parentInitial child initial R hc hi t integer keys words q) + (fun keys words => BinaryFraction.queryGroupSelectWithWork source target parent N P F exponent Q + eM eF hP hM hF tau a parentInitial child initial R hc hi draw keys words q) + (fun earlierKeys earlierWords groups online currentKeys currentWords => + BitQuery.compute (BinaryFraction.queryRefinementFinishWithWork parent N P F a delta parentInitial + t earlierKeys earlierWords groups online currentKeys currentWords q)) + +theorem queryLocalRefinement_refines + (expectedEarlier : (Fin M × ℕ × TargetInterval target.length) → FiniteQuery ι) + (expectedCurrent : (Fin M × TargetInterval target.length) → FiniteQuery ι) + (he : ∀ key, BitQuery.Refines (fun word value => word.value = value) + (readEarlier key) (expectedEarlier key)) + (hr : ∀ key, BitQuery.Refines (fun word value => word.value = value) + (readCurrent key) (expectedCurrent key)) : + BitQuery.Refines (fun word value => word.value = value) + (queryLocalRefinement source target parent N P F exponent H Q eM eF hP hM hF + tau a eta kappa delta t parentInitial child initial R hc hi draw integer q readEarlier readCurrent) + (localRefinementStepQuery source target parent N P F exponent H Q + tau.value a.value eta.value kappa.value delta.value t + (fun r => (parentInitial r).1.value) (fun i r => (child i r).1.value) + (fun i r => (initial i r).1.value) (fun b cell scale sample => (draw b cell scale sample).1) + (fun b r => (integer b r).1) q expectedEarlier expectedCurrent) := by + classical + let Rp := ∑ r, (parentInitial r).2 + have hp : ∀ r, (parentInitial r).2 ≤ Rp := fun r => + Finset.single_le_sum (f := fun r => (parentInitial r).2) (fun _ _ => Nat.zero_le _) + (Finset.mem_univ r) + unfold queryLocalRefinement localRefinementStepQuery + apply queryRefinementGather_refines (expectedEarlier := expectedEarlier) + (expectedCurrent := expectedCurrent) + (expectedOnline := fun keys words => localOnlineCandidates source target parent N P F exponent H + tau.value a.value eta.value kappa.value (fun r => (parentInitial r).1.value) + (fun i r => (child i r).1.value) (fun i r => (initial i r).1.value) + (fun i s r => finiteAnswerTable keys words (i, s, r)) (t - 1) + (fun b r => (integer b r).1) q) + (expectedSelected := fun keys words => localCellGroupActions source target parent N P F exponent Q + tau.value a.value (fun r => (parentInitial r).1.value) + (fun i r => (child i r).1.value) (fun i r => (initial i r).1.value) + (fun i r => finiteAnswerTable keys words (i, r)) + (fun b cell scale sample => (draw b cell scale sample).1) q) + (expectedNext := fun earlierKeys earlierWords groups online currentKeys currentWords => + .done (rationalRefinementUpdate delta.value + (rationalMinimum + (rationalBellman (fun r => (parentInitial r).1.value) + (fun q r => targetEndpointDistance q r) (128 * F) + (rationalActualWideActions parent + (localRefinementRepresentatives N P F a.value (fun r => (parentInitial r).1.value) q) P) + (fun input => finiteAnswerTable earlierKeys earlierWords (input.1, t - 1, input.2)) q) + (groups.map (rationalActionValue (fun q r => targetEndpointDistance q r) (128 * F) + (finiteAnswerTable currentKeys currentWords) q))) + (rationalOnlineMinimum (online.map + (rationalActionValue (fun q r => targetEndpointDistance q r) (128 * F) + (finiteAnswerTable currentKeys currentWords) q))))) + (R := Rp) (hR := hp) (he := he) (hc := hr) + · intro keys words + exact BinaryFraction.queryOnlineSelectWithWork_value source target parent N P F exponent H hP + tau a eta kappa parentInitial child initial R hc hi t integer keys words q + · intro keys words + exact BinaryFraction.queryGroupSelectWithWork_value source target parent N P F exponent Q eM eF + hP hM hF tau a parentInitial child initial R hc hi draw keys words q + · intro earlierKeys earlierWords groups online currentKeys currentWords + apply BitQuery.Refines.charge + apply BitQuery.Refines.done + simpa only [rationalWideStep, rationalWideStepCone, rationalBellman] using + BinaryFraction.queryRefinementFinishWithWork_value_only parent N P F a delta parentInitial + t earlierKeys earlierWords groups online currentKeys currentWords q hP + +end Local +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryLocalRefinementCost.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryLocalRefinementCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..fc1aa7d07b55193256c8560b1670a964c718383d --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryLocalRefinementCost.lean @@ -0,0 +1,179 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryLocalRefinement +import OAI.Combinatorics.EditApproximation.Queries.QuerySelectorCost +import OAI.Combinatorics.EditApproximation.Queries.QueryLocalFinishCost +import OAI.Combinatorics.EditApproximation.Queries.QueryHistoryBufferCost +import OAI.Combinatorics.EditApproximation.Queries.QuerySharedInputCost +import OAI.Combinatorics.EditApproximation.Queries.QueryRefinementWorkBound + +namespace OAI + +namespace EditApproximation.BinaryFraction + +def queryRefinementReadBudget (B Rp R earlier shared : ℕ) : ℕ := + R + Rp + (1 + earlier * (32 * B + 12)) + (1 + shared * (24 * B + 9)) + +def queryLocalRefinementBitBudget (M N P F exponent eM eF B S t Rp R W Dg Do : ℕ) : ℕ := + let earlier := queryHistoryInputsLength M P t (queryEarlierRepresentativesLength P F exponent B) + let shared := querySharedInputsLength M F exponent eM eF B + let groups := (B + 1) * ((32 * F + 2) * 2 ^ exponent + 2) ^ 2 + let U := queryRefinementReadBudget B Rp R earlier shared + queryRefinementStagesBudget M B W earlier (queryEarlierInputsBitBudget M P F exponent t B Rp) + (B + 1) (preparedLocalOnlineBitBudget M P B S * tableReadFactor U * (Do + 4)) + shared (querySharedInputsBitBudget M F exponent eM eF B Dg) + groups (preparedLocalGroupsBitBudget N M P F exponent eM eF B * tableReadFactor U * (Dg + 4)) Rp + (queryRefinementFinishBitBudget M P F B (queryFinishReadBudget M B Rp earlier groups (B + 1)) groups (B + 1)) + +end EditApproximation.BinaryFraction + +namespace EditApproximation +section Local +variable {ι α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (N P F exponent H Q eM eF B E S : ℕ) + (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) + (tau a eta kappa delta : BinaryFraction) (t : ℕ) + (parentInitial : TargetInterval target.length → BinaryFraction × ℕ) + (child initial : Fin M → TargetInterval target.length → BinaryFraction × ℕ) + (R : ℕ) (hc : ∀ i r, (child i r).2 ≤ R) (hi : ∀ i r, (initial i r).2 ≤ R) + (draw : CountedCellGroupDraws M F Q) (integer : ℕ → TargetInterval target.length → ℕ × ℕ) + (q : TargetInterval target.length) + (readEarlier : (Fin M × ℕ × TargetInterval target.length) → BitQuery ι BinaryFraction) + (readCurrent : (Fin M × TargetInterval target.length) → BitQuery ι BinaryFraction) + (oracle : ι → BinaryFraction) (readWork : ι → ℕ) + +open BinaryFraction + +theorem queryLocalRefinement_work_bound (Rp W Dg Do : ℕ) + (htime : 0 < t) (ht : Nat.size t ≤ B) (hPd : ∃ j : ℕ, P = 2 ^ j) + (hp : ∀ r, (parentInitial r).2 ≤ Rp) + (heW : ∀ key, ((readEarlier key).value oracle).width ≤ B) + (hcW : ∀ key, ((readCurrent key).value oracle).width ≤ B) + (heR : ∀ key ∈ (queryEarlierInputsWithWork M parent N P F exponent t hP a parentInitial q).1, + (readEarlier key).work oracle readWork ≤ W) + (hcR : ∀ key, (readCurrent key).work oracle readWork ≤ W) + (hdg : ∀ eb ∈ List.range (max 1 N.bits.length), + (refinementScaleGuardWithWork F (2 ^ eb) a (parentInitial q).1).1 = true → + ∀ cell ∈ (targetCellsWithWork + (canonicalMulWithWork (inversePowerTwo exponent) (nat (2 ^ eb))).1 + (bitWordValue (naturalCeilingWithWork (parentInitial q).1).1) q).1, + ∀ scale sample, (draw (2 ^ eb) cell scale sample).2 ≤ Dg) + (hdo : ∀ e ∈ (queryExponentsWithWork N F a (parentInitial q).1).1, + (centerEligibilityWithWork (2 ^ e) F a + (parentInitial (roundStateWithWork (bitWordValue (seedGridSpacingWithWork (2 ^ e) P).1) + (seedGridSpacingWithWork_pos (2 ^ e) P hP) q).1).1).1 = true → + (integer (2 ^ e) (roundStateWithWork (bitWordValue (seedGridSpacingWithWork (2 ^ e) P).1) + (seedGridSpacingWithWork_pos (2 ^ e) P hP) q).1).2 ≤ Do) + (hb : + let earlier := (queryEarlierInputsWithWork M parent N P F exponent t hP a parentInitial q).1 + let earlierWords := earlier.map fun key => (readEarlier key).value oracle + let shared := (querySharedInputsWithWork M N F Q exponent eM eF hM hF parent a + (parentInitial q).1 q draw).1 + let sharedWords := shared.map fun key => (readCurrent key).value oracle + PreparedKernelInputBounds (nx := source.length) N P F exponent H Q eM eF B E S (t - 1) + tau a eta kappa delta (fun r => (parentInitial r).1) + (fun i r => (child i r).1) (fun i r => (initial i r).1) + (fun input => (queryHistoryReadWithWork earlier earlierWords (t - 1) input).1) + (fun input => (queryChildReadWithWork shared sharedWords input.1 input.2).1) + (fun s input => (queryHistoryReadWithWork earlier earlierWords s input).1) + (fun b r => (integer b r).1)) : + (queryLocalRefinement source target parent N P F exponent H Q eM eF hP hM hF tau a eta kappa delta t + parentInitial child initial R hc hi draw integer q readEarlier readCurrent).work oracle readWork ≤ + queryLocalRefinementBitBudget M N P F exponent eM eF B S t Rp R W Dg Do := by + let earlier := queryEarlierInputsWithWork M parent N P F exponent t hP a parentInitial q + let earlierWords := earlier.1.map fun key => (readEarlier key).value oracle + let shared := querySharedInputsWithWork M N F Q exponent eM eF hM hF parent a (parentInitial q).1 q draw + let sharedWords := shared.1.map fun key => (readCurrent key).value oracle + let EL := queryHistoryInputsLength M P t (queryEarlierRepresentativesLength P F exponent B) + let SL := querySharedInputsLength M F exponent eM eF B + let G := (B + 1) * ((32 * F + 2) * 2 ^ exponent + 2) ^ 2 + let U := queryRefinementReadBudget B Rp R EL SL + change PreparedKernelInputBounds (nx := source.length) N P F exponent H Q eM eF B E S (t - 1) + tau a eta kappa delta (fun r => (parentInitial r).1) (fun i r => (child i r).1) (fun i r => (initial i r).1) + (fun input => (queryHistoryReadWithWork earlier.1 earlierWords (t - 1) input).1) + (fun input => (queryChildReadWithWork shared.1 sharedWords input.1 input.2).1) + (fun s input => (queryHistoryReadWithWork earlier.1 earlierWords s input).1) (fun b r => (integer b r).1) at hb + have hB : 10 ≤ B := hb.largeBits + have hFpos : 1 ≤ F := by rw [hF]; exact Nat.one_le_two_pow + have hnx : Nat.size source.length ≤ B := by have := hb.sourceSize; omega + have hny : Nat.size target.length ≤ B := by have := hb.targetSize; omega + have hMb : Nat.size M ≤ B := by have := hb.aritySize; omega + have hE := queryEarlierInputsWithWork_bounds M N P F exponent t B Rp parent hP a parentInitial q + (by omega) hb.inputSize hb.factorSize hFpos hb.precisionSize hnx hny hMb ht hb.thetaSize + hb.factorWidth hb.parentSize hp (hb.parentNonneg q) hPd + have hSh := querySharedInputsWithWork_bounds_on M N F Q exponent eM eF B Dg hM hF parent a + (parentInitial q).1 q draw (by omega) hb.inputSize hb.factorSize hb.aritySize hb.sampleSize hb.scaleSizes + hb.thetaSize hnx hny hb.factorWidth (hb.parentSize q) (hb.parentNonneg q) (by + intro eb heb cell hcell + have hmem := heb + simp only [queryExponentsWithWork, filterWithWork_value, List.mem_filter] at hmem + exact hdg eb hmem.1 hmem.2 cell hcell) + have hEU : ∀ s ≤ t - 1 + 1, ∀ input, + (queryHistoryReadWithWork earlier.1 earlierWords s input).2 ≤ U := by + intro s hs input + have hs' : s ≤ t := by omega + have hr := queryHistoryReadWithWork_cost earlier.1 earlierWords s input B hMb hny + ((Nat.size_le_size hs').trans ht) (fun key hk => + (Nat.size_le_size (queryEarlierInputsWithWork_time M parent N P F exponent t hP a parentInitial q key hk).le).trans ht) + have hm := Nat.mul_le_mul_right (32 * B + 12) hE.1 + change earlier.1.length * (32 * B + 12) ≤ EL * (32 * B + 12) at hm + dsimp only [U, queryRefinementReadBudget] + omega + have hSU : ∀ i r, (queryChildReadWithWork shared.1 sharedWords i r).2 ≤ U := by + intro i r + have hr := queryChildReadWithWork_cost shared.1 sharedWords i r B hMb hny + have hm := Nat.mul_le_mul_right (24 * B + 9) hSh.1 + change shared.1.length * (24 * B + 9) ≤ SL * (24 * B + 9) at hm + dsimp only [U, queryRefinementReadBudget] + omega + have hRU : R ≤ U := by dsimp only [U, queryRefinementReadBudget]; omega + have hpU : ∀ r, (parentInitial r).2 ≤ U := by + intro r + exact (hp r).trans (by dsimp only [U, queryRefinementReadBudget]; omega) + have hcU : ∀ i r, (child i r).2 ≤ U := fun i r => (hc i r).trans hRU + have hiU : ∀ i r, (initial i r).2 ≤ U := fun i r => (hi i r).trans hRU + have hg := queryGroupSelectWithWork_bounds source target parent N P F exponent H Q eM eF B E S + hP hM hF tau a eta kappa delta t parentInitial child initial R U hc hi hcU hiU hpU draw integer + earlier.1 earlierWords shared.1 sharedWords q hb hPd hSU Dg hdg + have ho := queryOnlineSelectWithWork_bounds source target parent N P F exponent H Q eM eF B E S + hP hM tau a eta kappa delta t parentInitial child initial R U hc hi hcU hiU hpU integer + earlier.1 earlierWords shared.1 sharedWords q hb hEU Do hdo + have heWords : ∀ w ∈ earlierWords, w.width ≤ B := by + intro w hw + obtain ⟨key, _, rfl⟩ := List.mem_map.mp hw + exact heW key + have heTimes : ∀ key ∈ earlier.1, Nat.size key.2.1 ≤ B := by + intro key hk + exact (Nat.size_le_size (queryEarlierInputsWithWork_time M parent N P F exponent t hP a parentInitial q key hk).le).trans ht + unfold queryLocalRefinement + apply queryRefinementGather_work_bound source target parent N P F exponent Q eM eF hP hM hF a t + parentInitial draw q readEarlier readCurrent _ _ _ oracle readWork B W EL _ (B + 1) _ SL _ G _ _ Rp hMb hny + · exact hE.1 + · exact hE.2 + · exact ho.1 + · exact ho.2 + · exact hSh.1 + · exact hSh.2 + · exact hg.1 + · exact hg.2 + · exact heR + · exact hcR + · let current := queryNeededInputsWithWork + (queryGroupSelectWithWork source target parent N P F exponent Q eM eF hP hM hF tau a + parentInitial child initial R hc hi draw shared.1 sharedWords q).1 + (queryOnlineSelectWithWork source target parent N P F exponent H hP tau a eta kappa + parentInitial child initial R hc hi t integer earlier.1 earlierWords q).1 + have hw : ∀ w ∈ current.1.map (fun key => (readCurrent key).value oracle), w.width ≤ B := by + intro w hw + obtain ⟨key, _, rfl⟩ := List.mem_map.mp hw + exact hcW key + have hf := queryLocalRefinement_finish_bounds source target parent N P F exponent H Q eM eF + hP hM hF tau a eta kappa delta t parentInitial child initial R hc hi draw integer + earlier.1 earlierWords shared.1 sharedWords (current.1.map fun key => (readCurrent key).value oracle) q + B Rp EL hB hb.inputSize hnx hb.targetSize hMb hb.precisionSize hb.factorSize ht hb.factorWidth + hb.decrementSize hb.parentSize hp (hb.parentNonneg q) heWords hw heTimes hE.1 + simpa only [BitQuery.compute, BitQuery.work, Nat.add_zero] using hf.2 + · exact hp q + +end Local +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryLocalRepresentativeSpace.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryLocalRepresentativeSpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..2e426d1ad4250cbc0c3204cf9be144d8b56efccb --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryLocalRepresentativeSpace.lean @@ -0,0 +1,80 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryEligibilitySpace +import OAI.Combinatorics.EditApproximation.Binary.BinaryWideSpace +import OAI.Combinatorics.EditApproximation.Binary.BinaryRepresentativeReads +import OAI.Combinatorics.EditApproximation.Binary.BinaryCellSpace +import OAI.Combinatorics.EditApproximation.Binary.BinaryCellReads +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation.BinaryFraction + + + +theorem representativeScaleReadAllocation_le_work {n : ℕ} (P F : ℕ) (a : BinaryFraction) + (read : TargetInterval n → BinaryFraction × ℕ) (allocation : TargetInterval n → ℕ) + (radius : List Bool) (query : TargetInterval n) (e : ℕ) + (h : ∀ r, allocation r ≤ (read r).2) : + representativeScaleReadAllocation P F a read allocation radius query e ≤ + (representativeScaleReadWithWork P F a read radius query e).2 := by + let b := 2 ^ e + let spacing := (seedGridSpacingWithWork b P).1 + let points := (gridStateBoxWithWork n (bitWordValue spacing) (bitWordValue radius) query.lo query.hi).1 + let test := fun r => ((centerEligibilityWithWork b F a (read r).1).1, + (centerEligibilityWithWork b F a (read r).1).2 + (read r).2) + have hs := seedGridSpacingAllocation_le_work b P + have hg := gridStateBoxAllocation_le_work n (bitWordValue spacing) (bitWordValue radius) query.lo query.hi + have hf := filterAllocation_le_work test + (fun r => centerEligibilityAllocation b F a (read r).1 + allocation r) points (by + intro r _ + exact Nat.add_le_add (centerEligibilityAllocation_le_work b F a (read r).1) (h r)) + have hm := arithmeticMapAllocation_le_work (fun r => ((b, r), 1)) (fun _ => 1) + (filterWithWork test points).1 (fun _ _ => le_rfl) + unfold representativeScaleReadAllocation representativeScaleReadWithWork + dsimp only [b, spacing, points, test] at hs hg hf hm ⊢ + omega + + + +theorem localRepresentativeReadAllocation_le_work {n : ℕ} (N P F : ℕ) (a : BinaryFraction) + (read : TargetInterval n → BinaryFraction × ℕ) (allocation : TargetInterval n → ℕ) + (query : TargetInterval n) (h : ∀ r, allocation r ≤ (read r).2) : + localRepresentativeReadAllocation N P F a read allocation query ≤ + (localRepresentativeReadWithWork N P F a read query).2 := by + have hq := h query + have hs := queryExponentsAllocation_le_work N F a (read query).1 + have hr := naturalCeilingAllocation_le_work (read query).1 + have hl := arithmeticFlatMapAllocation_le_work + (representativeScaleReadWithWork P F a read (naturalCeilingWithWork (read query).1).1 query) + (representativeScaleReadAllocation P F a read allocation (naturalCeilingWithWork (read query).1).1 query) + (queryExponentsWithWork N F a (read query).1).1 + (fun e _ => representativeScaleReadAllocation_le_work P F a read allocation _ query e h) + unfold localRepresentativeReadAllocation localRepresentativeReadWithWork + dsimp only + omega + + + +theorem cellCentersReadAllocation_le_work {n : ℕ} (P F b : ℕ) (a theta : BinaryFraction) + (initial : TargetInterval n → BinaryFraction × ℕ) (allocation : TargetInterval n → ℕ) + (cell : ℕ × ℕ) (h : ∀ r, allocation r ≤ (initial r).2) : + cellCentersReadAllocation P F b a theta initial allocation cell ≤ + (cellCentersReadWithWork P F b a theta initial cell).2 := by + let spacing := (seedGridSpacingWithWork b P).1 + let side := (canonicalMulWithWork theta (nat b)).1 + let states := (cellStatesWithWork n (bitWordValue spacing) side cell).1 + let test := fun r => ((centerEligibilityWithWork b F a (initial r).1).1, + (initial r).2 + (centerEligibilityWithWork b F a (initial r).1).2) + have hs := seedGridSpacingAllocation_le_work b P + have hm := canonicalMulAllocation_le_work theta (nat b) + have hg := cellStatesAllocation_le_work n (bitWordValue spacing) side cell + have hf := filterAllocation_le_work test (fun r => allocation r + centerEligibilityAllocation b F a (initial r).1) + states (fun r _ => Nat.add_le_add (h r) (centerEligibilityAllocation_le_work b F a (initial r).1)) + unfold cellCentersReadAllocation cellCentersReadWithWork + dsimp only [spacing, side, states, test] at hg hf ⊢ + omega + +end EditApproximation.BinaryFraction + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryLocalSelectorSpace.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryLocalSelectorSpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..b9c05ebcd76984db682d638a9b29034c11d7f10b --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryLocalSelectorSpace.lean @@ -0,0 +1,79 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryLocalGroupSourceSpace +import OAI.Combinatorics.EditApproximation.Binary.BinaryLocalOnlineSourceSpace +import OAI.Combinatorics.EditApproximation.Queries.QueryLocalSelectors + +namespace OAI + +namespace EditApproximation.BinaryFraction + +section Selectors +variable {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (N P F exponent H Q eM eF : ℕ) + (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) + (tau a eta kappa : BinaryFraction) + (parentInitial : TargetInterval target.length → BinaryFraction × ℕ) + (child initial : Fin M → TargetInterval target.length → BinaryFraction × ℕ) + (R : ℕ) (hc : ∀ i r, (child i r).2 ≤ R) (hi : ∀ i r, (initial i r).2 ≤ R) + (parentAllocation : TargetInterval target.length → ℕ) + (childAllocation initialAllocation : Fin M → TargetInterval target.length → ℕ) + +def queryOnlineSelectAllocation (t : ℕ) + (integer : ℕ → TargetInterval target.length → ℕ × ℕ) + (integerAllocation : ℕ → TargetInterval target.length → ℕ) + (keys : List (Fin M × ℕ × TargetInterval target.length)) (words : List BinaryFraction) + (q : TargetInterval target.length) : ℕ := + preparedLocalOnlineActionsSourceAllocation source target parent P F exponent H hP tau a eta kappa + parentInitial child initial (queryHistoryReadWithWork keys words) R hc hi (t - 1) integer + parentAllocation childAllocation initialAllocation (queryHistoryReadAllocation keys words) + integerAllocation N q + +theorem queryOnlineSelectAllocation_le_work (t : ℕ) + (integer : ℕ → TargetInterval target.length → ℕ × ℕ) + (integerAllocation : ℕ → TargetInterval target.length → ℕ) + (keys : List (Fin M × ℕ × TargetInterval target.length)) (words : List BinaryFraction) + (q : TargetInterval target.length) + (hp : ∀ r, parentAllocation r ≤ (parentInitial r).2) + (hca : ∀ i r, childAllocation i r ≤ (child i r).2) + (hia : ∀ i r, initialAllocation i r ≤ (initial i r).2) + (hint : ∀ b r, integerAllocation b r ≤ (integer b r).2) : + queryOnlineSelectAllocation source target parent N P F exponent H hP tau a eta kappa + parentInitial child initial R hc hi parentAllocation childAllocation initialAllocation + t integer integerAllocation keys words q ≤ + 3 * (queryOnlineSelectWithWork source target parent N P F exponent H hP tau a eta kappa + parentInitial child initial R hc hi t integer keys words q).2 := + preparedLocalOnlineActionsSourceAllocation_le_work source target parent P F exponent H hP tau a eta kappa + parentInitial child initial (queryHistoryReadWithWork keys words) R hc hi (t - 1) integer + parentAllocation childAllocation initialAllocation (queryHistoryReadAllocation keys words) + integerAllocation N q hp hca hia (queryHistoryReadAllocation_le_work keys words) hint + +def queryGroupSelectAllocation (draw : CountedCellGroupDraws M F Q) + (drawAllocation : CellGroupSourceAllocations M F Q) + (keys : List (Fin M × TargetInterval target.length)) (words : List BinaryFraction) + (q : TargetInterval target.length) : ℕ := + preparedLocalCellGroupsSourceAllocation source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial (queryChildReadWithWork keys words) R hc hi + parentAllocation childAllocation initialAllocation (queryChildReadAllocation keys words) + draw drawAllocation N q + +theorem queryGroupSelectAllocation_le_work (draw : CountedCellGroupDraws M F Q) + (drawAllocation : CellGroupSourceAllocations M F Q) + (keys : List (Fin M × TargetInterval target.length)) (words : List BinaryFraction) + (q : TargetInterval target.length) + (hp : ∀ r, parentAllocation r ≤ (parentInitial r).2) + (hca : ∀ i r, childAllocation i r ≤ (child i r).2) + (hia : ∀ i r, initialAllocation i r ≤ (initial i r).2) + (hd : ∀ b cell t i, drawAllocation b cell t i ≤ (draw b cell t i).2) : + queryGroupSelectAllocation source target parent N P F exponent Q eM eF hP hM hF tau a + parentInitial child initial R hc hi parentAllocation childAllocation initialAllocation + draw drawAllocation keys words q ≤ + (queryGroupSelectWithWork source target parent N P F exponent Q eM eF hP hM hF tau a + parentInitial child initial R hc hi draw keys words q).2 := + preparedLocalCellGroupsSourceAllocation_le_work source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial (queryChildReadWithWork keys words) R hc hi + parentAllocation childAllocation initialAllocation (queryChildReadAllocation keys words) + draw drawAllocation N q hp hca hia (queryChildReadAllocation_le_work keys words) hd + +end Selectors +end EditApproximation.BinaryFraction + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryLocalSelectors.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryLocalSelectors.lean new file mode 100644 index 0000000000000000000000000000000000000000..54682ebc1693b79d38d80ecab3e486abf5341ea2 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryLocalSelectors.lean @@ -0,0 +1,70 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryLocalSourceValues +import OAI.Combinatorics.EditApproximation.Queries.QueryDataBuffers + +namespace OAI + +/-! The concrete selectors of the adaptive local program. Source and table +lookups are evaluated by their counted finite-buffer routines. Their value +identities hold even for arbitrary gathered answer lists. -/ + +namespace EditApproximation +namespace BinaryFraction + +section Selectors +variable {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (N P F exponent H Q eM eF : ℕ) + (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) + (tau a eta kappa : BinaryFraction) + (parentInitial : TargetInterval target.length → BinaryFraction × ℕ) + (child initial : Fin M → TargetInterval target.length → BinaryFraction × ℕ) + (R : ℕ) (hc : ∀ i r, (child i r).2 ≤ R) (hi : ∀ i r, (initial i r).2 ≤ R) + +def queryOnlineSelectWithWork (t : ℕ) + (integer : ℕ → TargetInterval target.length → ℕ × ℕ) + (keys : List (Fin M × ℕ × TargetInterval target.length)) (words : List BinaryFraction) + (q : TargetInterval target.length) := + preparedLocalOnlineActionsSourceWithWork source target parent P F exponent H hP tau a eta kappa + parentInitial child initial (queryHistoryReadWithWork keys words) R hc hi (t - 1) integer N q + +theorem queryOnlineSelectWithWork_value (t : ℕ) + (integer : ℕ → TargetInterval target.length → ℕ × ℕ) + (keys : List (Fin M × ℕ × TargetInterval target.length)) (words : List BinaryFraction) + (q : TargetInterval target.length) : + ((queryOnlineSelectWithWork source target parent N P F exponent H hP tau a eta kappa + parentInitial child initial R hc hi t integer keys words q).1.map BinaryBellmanAction.decode) = + localOnlineCandidates source target parent N P F exponent H tau.value a.value eta.value kappa.value + (fun r => (parentInitial r).1.value) (fun i r => (child i r).1.value) + (fun i r => (initial i r).1.value) + (fun i s r => finiteAnswerTable keys (words.map value) (i, s, r)) + (t - 1) (fun b r => (integer b r).1) q := by + unfold queryOnlineSelectWithWork + rw [preparedLocalOnlineActionsSourceWithWork_semantic_value] + rw [preparedLocalOnlineActionsWithWork_value] + simp only [queryHistoryReadWithWork_value] + +def queryGroupSelectWithWork (draw : CountedCellGroupDraws M F Q) + (keys : List (Fin M × TargetInterval target.length)) (words : List BinaryFraction) + (q : TargetInterval target.length) := + preparedLocalCellGroupsSourceWithWork source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial (queryChildReadWithWork keys words) R hc hi N draw q + +theorem queryGroupSelectWithWork_value (draw : CountedCellGroupDraws M F Q) + (keys : List (Fin M × TargetInterval target.length)) (words : List BinaryFraction) + (q : TargetInterval target.length) : + ((queryGroupSelectWithWork source target parent N P F exponent Q eM eF hP hM hF tau a + parentInitial child initial R hc hi draw keys words q).1.map BinaryBellmanAction.decode) = + localCellGroupActions source target parent N P F exponent Q tau.value a.value + (fun r => (parentInitial r).1.value) (fun i r => (child i r).1.value) + (fun i r => (initial i r).1.value) + (fun i r => finiteAnswerTable keys (words.map value) (i, r)) + (fun b cell scale sample => (draw b cell scale sample).1) q := by + unfold queryGroupSelectWithWork + rw [preparedLocalCellGroupsSourceWithWork_semantic_value] + rw [preparedLocalCellGroupsWithWork_value] + simp only [queryChildReadWithWork_value] + +end Selectors +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryLocalSources.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryLocalSources.lean new file mode 100644 index 0000000000000000000000000000000000000000..f56a92bc1e4a56cdb6706a99d471e96d9bd1cd4d --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryLocalSources.lean @@ -0,0 +1,95 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryLocalRefinement +import OAI.Combinatorics.EditApproximation.Queries.QueryGroupSources +import OAI.Combinatorics.EditApproximation.Queries.QueryOnlineSources +import OAI.Combinatorics.EditApproximation.Geometry.LocalRandomSourceQuery + +namespace OAI + +/-! Random words are gathered before the adaptive local selectors run. +The online sampling range is computed from the gathered mass words. -/ + +namespace EditApproximation + +section Sources +variable {ι α : Type*} (source target : List α) {M : ℕ} [NeZero M] + (parent : TargetInterval source.length) (N P F exponent H Q eM eF : ℕ) + (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) + (tau a eta kappa delta : BinaryFraction) (t : ℕ) + (parentInitial : TargetInterval target.length → BinaryFraction × ℕ) + (child initial : Fin M → TargetInterval target.length → BinaryFraction × ℕ) + (R : ℕ) (hc : ∀ i r, (child i r).2 ≤ R) (hi : ∀ i r, (initial i r).2 ≤ R) + (q : TargetInterval target.length) + (readGroup : GroupScalarKey M F Q → BitQuery ι BinaryFraction) + (readInteger : (ℕ × TargetInterval target.length) → ℕ → BitQuery ι BinaryFraction) + (readEarlier : (Fin M × ℕ × TargetInterval target.length) → BitQuery ι BinaryFraction) + (readCurrent : (Fin M × TargetInterval target.length) → BitQuery ι BinaryFraction) + +def queryLocalRandomSources : BitQuery ι BinaryFraction := + queryGroupSourceGather M N F Q exponent eM eF hM hF a parentInitial q readGroup + fun groupKeys groupWords => + queryOnlineSourceGather parent N P F exponent H hP tau a parentInitial child q readInteger + fun onlineKeys onlineWords => + queryLocalRefinement source target parent N P F exponent H Q eM eF hP hM hF + tau a eta kappa delta t parentInitial child initial R hc hi + (BinaryFraction.queryGroupDrawReadWithWork groupKeys groupWords) + (BinaryFraction.queryOnlineIntegerReadWithWork onlineKeys onlineWords) + q readEarlier readCurrent + +theorem queryLocalRandomSources_refines + (expectedGroup : GroupScalarKey M F Q → FiniteQuery ι) + (expectedInteger : (ℕ × TargetInterval target.length) → ℕ → FiniteQuery ι) + (expectedEarlier : (Fin M × ℕ × TargetInterval target.length) → FiniteQuery ι) + (expectedCurrent : (Fin M × TargetInterval target.length) → FiniteQuery ι) + (hg : ∀ key, BitQuery.Refines (fun word value => word.value = value) + (readGroup key) (expectedGroup key)) + (hz : ∀ key range, BitQuery.Refines (fun word value => word.value = value) + (readInteger key range) (expectedInteger key range)) + (he : ∀ key, BitQuery.Refines (fun word value => word.value = value) + (readEarlier key) (expectedEarlier key)) + (hr : ∀ key, BitQuery.Refines (fun word value => word.value = value) + (readCurrent key) (expectedCurrent key)) : + BitQuery.Refines (fun word value => word.value = value) + (queryLocalRandomSources source target parent N P F exponent H Q eM eF hP hM hF + tau a eta kappa delta t parentInitial child initial R hc hi q + readGroup readInteger readEarlier readCurrent) + (localRandomSourceStepQuery source target parent N P F exponent H Q + tau.value a.value eta.value kappa.value delta.value t + (fun r => (parentInitial r).1.value) (fun i r => (child i r).1.value) + (fun i r => (initial i r).1.value) q + expectedGroup expectedInteger expectedEarlier expectedCurrent) := by + unfold queryLocalRandomSources localRandomSourceStepQuery + apply queryGroupSourceGather_refines M N F Q exponent eM eF hM hF a parentInitial q readGroup + expectedGroup (expectedNext := fun keys values => + localOnlineSourceStepQuery source target parent N P F exponent H Q + tau.value a.value eta.value kappa.value delta.value t + (fun r => (parentInitial r).1.value) (fun i r => (child i r).1.value) + (fun i r => (initial i r).1.value) (groupDrawFromValues keys values) + q expectedInteger expectedEarlier expectedCurrent) (hr := hg) + intro groupWords + let groupKeys := groupScalarKeys M F Q + (localGroupQueryKeys N F exponent a.value (fun r => (parentInitial r).1.value) q) + unfold localOnlineSourceStepQuery + apply queryOnlineSourceGather_refines source target parent N P F exponent H hP tau a + parentInitial child q R hc readInteger expectedInteger + (expectedNext := fun keys values => + localRefinementStepQuery source target parent N P F exponent H Q + tau.value a.value eta.value kappa.value delta.value t + (fun r => (parentInitial r).1.value) (fun i r => (child i r).1.value) + (fun i r => (initial i r).1.value) + (groupDrawFromValues groupKeys (groupWords.map BinaryFraction.value)) + (fun b r => ⌊finiteAnswerTable keys values (b, r)⌋₊) q expectedEarlier expectedCurrent) + (hr := hz) + intro onlineWords + let onlineKeys := localOnlineSourceKeys N P F a.value (fun r => (parentInitial r).1.value) q + have h := queryLocalRefinement_refines source target parent N P F exponent H Q eM eF hP hM hF + tau a eta kappa delta t parentInitial child initial R hc hi + (BinaryFraction.queryGroupDrawReadWithWork groupKeys groupWords) + (BinaryFraction.queryOnlineIntegerReadWithWork onlineKeys onlineWords) + q readEarlier readCurrent expectedEarlier expectedCurrent he hr + simpa only [BinaryFraction.queryGroupDrawReadWithWork_value, + BinaryFraction.queryOnlineIntegerReadWithWork_value] using h + +end Sources +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryLocalSourcesCost.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryLocalSourcesCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..bbd5ae02bb76a137dc03d0d5f1464cf236228fba --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryLocalSourcesCost.lean @@ -0,0 +1,142 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryLocalSources +import OAI.Combinatorics.EditApproximation.Queries.QueryLocalRefinementCost +import OAI.Combinatorics.EditApproximation.Queries.QuerySourceGatherCost +import OAI.Combinatorics.EditApproximation.Queries.QueryBufferedSourceBounds + +namespace OAI + +/-! The complete random-source stage: source enumeration and range construction, +physical source reads, finite-buffer scans, and the inner local refinement. -/ + +namespace EditApproximation.BinaryFraction + +def queryLocalSourcesBitBudget (M N P F exponent eM eF B S t Rp R W : ℕ) : ℕ := + queryGroupGatherBitBudget M F exponent eM eF B Rp W + (queryOnlineGatherBitBudget M P B Rp R W + (queryLocalRefinementBitBudget M N P F exponent eM eF B S t Rp R W + (queryBufferedGroupReadBudget M F exponent eM eF B B) + (queryOnlineBufferReadBudget (B + 1) B B))) + +end EditApproximation.BinaryFraction + +namespace EditApproximation +section Sources +variable {ι α : Type*} (source target : List α) {M : ℕ} [NeZero M] + (parent : TargetInterval source.length) (N P F exponent H Q eM eF B E S : ℕ) + (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) + (tau a eta kappa delta : BinaryFraction) (t : ℕ) + (parentInitial : TargetInterval target.length → BinaryFraction × ℕ) + (child initial : Fin M → TargetInterval target.length → BinaryFraction × ℕ) + (R : ℕ) (hc : ∀ i r, (child i r).2 ≤ R) (hi : ∀ i r, (initial i r).2 ≤ R) + (q : TargetInterval target.length) + (readGroup : GroupScalarKey M F Q → BitQuery ι BinaryFraction) + (readInteger : (ℕ × TargetInterval target.length) → ℕ → BitQuery ι BinaryFraction) + (readEarlier : (Fin M × ℕ × TargetInterval target.length) → BitQuery ι BinaryFraction) + (readCurrent : (Fin M × TargetInterval target.length) → BitQuery ι BinaryFraction) + (oracle : ι → BinaryFraction) (readWork : ι → ℕ) + +open BinaryFraction + +theorem queryLocalRandomSources_work_bound (Rp W : ℕ) + (htime : 0 < t) (ht : Nat.size t ≤ B) (hPd : ∃ j : ℕ, P = 2 ^ j) + (hp : ∀ r, (parentInitial r).2 ≤ Rp) + (hgW : ∀ key, ((readGroup key).value oracle).width ≤ B) + (hzW : ∀ key range, ((readInteger key range).value oracle).width ≤ B) + (heW : ∀ key, ((readEarlier key).value oracle).width ≤ B) + (hcW : ∀ key, ((readCurrent key).value oracle).width ≤ B) + (hgR : ∀ key, queryGroupKeySize key ≤ 40 * B + 500 → + (readGroup key).work oracle readWork ≤ W) + (hzR : ∀ key range, Nat.size key.1 ≤ B + 1 → Nat.size range ≤ 240 * (B + 5) + 7 → + (readInteger key range).work oracle readWork ≤ W) + (heR : ∀ key, Nat.size key.2.1 ≤ B → (readEarlier key).work oracle readWork ≤ W) + (hcR : ∀ key, (readCurrent key).work oracle readWork ≤ W) + (hb : + let groupKeys := (queryGroupSourceKeysWithWork M N F Q exponent eM eF hM hF a (parentInitial q).1 q).1 + let groupWords := groupKeys.map fun key => (readGroup key).value oracle + let onlineKeys := (queryOnlineKeysWithWork N P F hP a (parentInitial q).1 q).1 + let onlineWords := onlineKeys.map fun key => + (readInteger key (queryOnlineRangeWithWork parent P exponent H tau child key).1).value oracle + let draw := queryGroupDrawReadWithWork groupKeys groupWords + let integer := queryOnlineIntegerReadWithWork onlineKeys onlineWords + let earlier := (queryEarlierInputsWithWork M parent N P F exponent t hP a parentInitial q).1 + let earlierWords := earlier.map fun key => (readEarlier key).value oracle + let shared := (querySharedInputsWithWork M N F Q exponent eM eF hM hF parent a + (parentInitial q).1 q draw).1 + let sharedWords := shared.map fun key => (readCurrent key).value oracle + PreparedKernelInputBounds (nx := source.length) N P F exponent H Q eM eF B E S (t - 1) + tau a eta kappa delta (fun r => (parentInitial r).1) + (fun i r => (child i r).1) (fun i r => (initial i r).1) + (fun input => (queryHistoryReadWithWork earlier earlierWords (t - 1) input).1) + (fun input => (queryChildReadWithWork shared sharedWords input.1 input.2).1) + (fun s input => (queryHistoryReadWithWork earlier earlierWords s input).1) + (fun b r => (integer b r).1)) : + (queryLocalRandomSources source target parent N P F exponent H Q eM eF hP hM hF + tau a eta kappa delta t parentInitial child initial R hc hi q + readGroup readInteger readEarlier readCurrent).work oracle readWork ≤ + queryLocalSourcesBitBudget M N P F exponent eM eF B S t Rp R W := by + let groupKeys := (queryGroupSourceKeysWithWork M N F Q exponent eM eF hM hF a (parentInitial q).1 q).1 + let groupWords := groupKeys.map fun key => (readGroup key).value oracle + let onlineKeys := (queryOnlineKeysWithWork N P F hP a (parentInitial q).1 q).1 + let onlineWords := onlineKeys.map fun key => + (readInteger key (queryOnlineRangeWithWork parent P exponent H tau child key).1).value oracle + let draw := queryGroupDrawReadWithWork groupKeys groupWords + let integer := queryOnlineIntegerReadWithWork onlineKeys onlineWords + have hB : 10 ≤ B := hb.largeBits + have hnx : Nat.size source.length ≤ B := by have := hb.sourceSize; omega + have hny : Nat.size target.length ≤ B := by have := hb.targetSize; omega + have hMb : Nat.size M ≤ B := by have := hb.aritySize; omega + have hFpos : 1 ≤ F := by rw [hF]; exact Nat.one_le_two_pow + have hgw : ∀ w ∈ groupWords, w.width ≤ B := by + intro w hw + obtain ⟨key, _, rfl⟩ := List.mem_map.mp hw + exact hgW key + have how : ∀ w ∈ onlineWords, w.width ≤ B := by + intro w hw + obtain ⟨key, _, rfl⟩ := List.mem_map.mp hw + exact hzW key _ + have hdg := queryBufferedGroupReadCost exponent eM eF B B hM hF a (parentInitial q).1 q groupWords + (by omega) hb.inputSize hb.factorSize hb.aritySize hb.sampleSize + (by have := hb.scaleSizes; omega) hb.thetaSize hny hb.factorWidth (hb.parentSize q) + (hb.parentNonneg q) (by omega) hgw + have hdo := queryBufferedOnlineReadCost N P F B B hP a (parentInitial q).1 q onlineWords + (by omega) hb.inputSize hb.factorSize hFpos hb.precisionSize hny hb.factorWidth + (hb.parentSize q) (by omega) how + have hlocal := queryLocalRefinement_work_bound source target parent N P F exponent H Q eM eF B E S + hP hM hF tau a eta kappa delta t parentInitial child initial R hc hi draw integer q + readEarlier readCurrent oracle readWork Rp W _ _ htime ht hPd hp heW hcW + (fun key hk => heR key ((Nat.size_le_size + (queryEarlierInputsWithWork_time M parent N P F exponent t hP a parentInitial q key hk).le).trans ht)) + hcR hdg (fun e he _ => hdo e he) hb + have hgCost : ∀ key ∈ groupKeys, (readGroup key).work oracle readWork ≤ W := by + intro key hk + apply hgR key + exact queryGroupSourceKeysWithWork_width M N F Q exponent eM eF B hM hF a (parentInitial q).1 q + (by omega) hb.inputSize hb.factorSize hMb (by have := hb.scaleSizes; omega) + hb.thetaSize hny hb.factorWidth (hb.parentSize q) (hb.parentNonneg q) key hk + have hzCost : ∀ key ∈ onlineKeys, + (readInteger key (queryOnlineRangeWithWork parent P exponent H tau child key).1).work oracle readWork ≤ W := by + intro key hk + have hscale := queryOnlineKeysWithWork_scale N P F B hP a (parentInitial q).1 q + hb.inputSize hFpos key hk + apply hzR key _ hscale + have hr := (queryOnlineRangeWithWork_bounds source target parent P exponent H (B + 1) R hP tau child key + (by omega) (by omega) (by omega) (by omega) hscale (by have := hb.precisionSize; omega) + (by have := hb.thetaSize; omega) (by have := hb.heightSize; omega) + (by have := hb.coordinateSize; omega) (hb.tauSize.trans (by omega)) + (fun i r => (hb.massSize i r).trans (by omega)) hc).1 + simpa only [Nat.add_assoc] using hr + unfold queryLocalRandomSources queryLocalSourcesBitBudget + apply queryGroupSourceGather_work_bound M N F Q exponent eM eF B Rp W _ hM hF a parentInitial q + readGroup _ oracle readWork (by omega) hb.inputSize hb.factorSize hb.aritySize hb.sampleSize + (by have := hb.scaleSizes; omega) hb.thetaSize hny hb.factorWidth (hb.parentSize q) + (hb.parentNonneg q) (hp q) hgCost + apply queryOnlineSourceGather_work_bound source target parent N P F exponent H B Rp R W _ hP tau a + parentInitial child q readInteger _ oracle readWork (by omega) hb.inputSize hb.factorSize hFpos + hMb hb.precisionSize hb.thetaSize hnx hny hb.heightSize hb.coordinateSize hb.tauSize hb.factorWidth + (hb.parentSize q) (hp q) hb.massSize hc hzCost + exact hlocal + +end Sources +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryMeanRead.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryMeanRead.lean new file mode 100644 index 0000000000000000000000000000000000000000..720d3e8c3b601e78d9f7ccf82fc9f1afca0bb8db --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryMeanRead.lean @@ -0,0 +1,54 @@ +import OAI.Combinatorics.EditApproximation.Binary.BitQuery +import OAI.Combinatorics.EditApproximation.Binary.BinaryWarmupAverage +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Counted averaging of the warmup words actually requested. The fixed +requested denominator is retained even in the simulation of arbitrary +intermediate answer lists. -/ + +namespace EditApproximation +namespace BinaryFraction + + + +@[simp] theorem queryMeanWithWork_value (count : ℕ) (words : List BinaryFraction) : + (queryMeanWithWork count words).1.value = (words.map value).sum / count := by + simp only [queryMeanWithWork, divWithWork_value, sumListWithWork_value, nat_value] + +theorem queryMeanWithWork_eq_average (count : ℕ) (words : List BinaryFraction) + (h : words.length = count) : queryMeanWithWork count words = warmupAverageWithWork words := by + subst count + rfl + +end BinaryFraction + + + +theorem queryMeanRead_refines {ι : Type*} (count : ℕ) + (reader : Fin count → BitQuery ι BinaryFraction) (expected : Fin count → FiniteQuery ι) + (hr : ∀ i, BitQuery.Refines (fun word value => word.value = value) (reader i) (expected i)) : + BitQuery.Refines (fun word value => word.value = value) (queryMeanRead count reader) + (FiniteQuery.collect expected (List.ofFn fun i : Fin count => i) + (fun words => .done (words.sum / count))) := by + apply BitQuery.Refines.charge + apply BitQuery.Refines.collect reader expected hr + intro words + exact .charge _ (.done (BinaryFraction.queryMeanWithWork_value count words)) + +theorem queryMeanRead_work {ι : Type*} (count : ℕ) + (reader : Fin count → BitQuery ι BinaryFraction) + (oracle : ι → BinaryFraction) (readWork : ι → ℕ) : + (queryMeanRead count reader).work oracle readWork = + count + 1 + ((List.ofFn fun i : Fin count => i).map + (fun i => (reader i).work oracle readWork + 3)).sum + + (BinaryFraction.queryMeanWithWork count + ((List.ofFn fun i : Fin count => i).map fun i => (reader i).value oracle)).2 := by + simp only [queryMeanRead, BitQuery.work_collect, BitQuery.compute, BitQuery.work, + Nat.add_zero, Nat.add_assoc] + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryNumericInteger.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryNumericInteger.lean new file mode 100644 index 0000000000000000000000000000000000000000..070516748b3a11e16df67d2557b809a5039f0645 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryNumericInteger.lean @@ -0,0 +1,20 @@ +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalPreparedInputBounds + +namespace OAI + +namespace EditApproximation.BinaryFraction + +/-- Changing the sampled integers changes only their explicit width premise. -/ +theorem PreparedKernelNumericBounds.with_integer {nx ny M : ℕ} + {N P F exponent H Q eM eF B E S t : ℕ} + {tau a eta kappa delta : BinaryFraction} {integer : ℕ → TargetInterval ny → ℕ} + (hn : PreparedKernelNumericBounds (nx := nx) (M := M) + N P F exponent H Q eM eF B E S t tau a eta kappa delta integer) + (integer' : ℕ → TargetInterval ny → ℕ) (hi : ∀ b r, Nat.size (integer' b r) ≤ B) : + PreparedKernelNumericBounds (nx := nx) (M := M) + N P F exponent H Q eM eF B E S t tau a eta kappa delta integer' := by + exact { hn with drawSize := hi } + +end EditApproximation.BinaryFraction + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryOnlineKeyCost.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryOnlineKeyCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..9c755bd305fd91419c3561c25c631ea7a91ad9e8 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryOnlineKeyCost.lean @@ -0,0 +1,47 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryRawCenterCost +import OAI.Combinatorics.EditApproximation.Binary.BinaryRoundedWork + +namespace OAI + +namespace EditApproximation.BinaryFraction + +def queryOnlineKeysBitBudget (B : ℕ) : ℕ := + queryScalesBitBudget B + (B + 1) * (600 * (B + 3) ^ 2 + 6) + 1 + +theorem queryOnlineKeysWithWork_bounds {n : ℕ} (N P F B : ℕ) (hP : 0 < P) + (a value : BinaryFraction) (q : TargetInterval n) + (hB : 7 ≤ B) (hN : Nat.size N ≤ B) (hF : Nat.size F + 2 ≤ B) + (hFpos : 1 ≤ F) (hPb : Nat.size P ≤ B) (hn : Nat.size n ≤ B) + (ha : a.width ≤ B) (hv : value.width ≤ B) : + (queryOnlineKeysWithWork N P F hP a value q).1.length ≤ B + 1 ∧ + (queryOnlineKeysWithWork N P F hP a value q).2 ≤ queryOnlineKeysBitBudget B := by + let scales := queryScalesWithWork N F a value + let run := fun b => + let spacing := seedGridSpacingWithWork b P + let center := roundStateWithWork (bitWordValue spacing.1) (seedGridSpacingWithWork_pos b P hP) q + ((b, center.1), spacing.2 + center.2 + 2) + have hs := queryScalesWithWork_bounds N F B a value hB hN hF ha hv + have hc (b : ℕ) (hb : b ∈ scales.1) : (run b).2 ≤ 600 * (B + 3) ^ 2 + 3 := by + have hm := queryScalesWithWork_member N F B a value hN hFpos b hb + have hsp := seedGridSpacingWithWork_bounds b P (B + 1) hm.1 (by omega) + have hsize : Nat.size (bitWordValue (seedGridSpacingWithWork b P).1) ≤ B + 2 := + (Nat.size_le.mpr (bitWordValue_lt_pow_length _)).trans hsp.1 + have hr := roundStateWithWork_cost (bitWordValue (seedGridSpacingWithWork b P).1) + (seedGridSpacingWithWork_pos b P hP) q (B + 2) hsize (by omega) + have hspc := hsp.2 + dsimp only [run] + simp only [Nat.add_assoc, Nat.reduceAdd] at hspc hr + omega + have hm := (arithmeticMapWithWork_cost run scales.1 (600 * (B + 3) ^ 2 + 3) hc).trans + (Nat.mul_le_mul_right _ hs.1) + simp only [Nat.add_assoc, Nat.reduceAdd] at hm + constructor + · simpa only [queryOnlineKeysWithWork, arithmeticMapWithWork_value, List.length_map] using hs.1 + · change scales.2 + (arithmeticMapWithWork run scales.1).2 + 1 ≤ _ + have hsc : scales.2 ≤ queryScalesBitBudget B := hs.2 + unfold queryOnlineKeysBitBudget + omega + +end EditApproximation.BinaryFraction + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryOnlineRangeCost.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryOnlineRangeCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..9d5a748befe48751fc30a5051b0e58a6c4c69fcc --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryOnlineRangeCost.lean @@ -0,0 +1,112 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryOnlineSources +import OAI.Combinatorics.EditApproximation.Binary.BinaryPreparedOnlineWork +import OAI.Combinatorics.EditApproximation.Binary.BinaryBandReadCosts + +namespace OAI + +/-! Online source ranges are computed before their random draws. This +charges the actual band, coordinate set, two powers, and triangular mass. -/ + +namespace EditApproximation.BinaryFraction + +def queryOnlineRangeBitBudget (M P B R : ℕ) : ℕ := + let V := (40 * P + 2) ^ (2 * M) + 26 * B + 4 + + (wideMaterializationBitBudget M P B + representativeCompleteBitBudget M V (4 * B + 20) + V + 1) * + tableReadFactor R + onlineIndexBitBudget M V B + bitPowerBitBudget 80 (B + 4) + + 10000 * (80 * (B + 4) + 4) ^ 2 + 4 + +theorem queryOnlineRangeWithWork_bounds {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (P exponent H B R : ℕ) (hP : 0 < P) + (tau : BinaryFraction) (child : Fin M → TargetInterval target.length → BinaryFraction × ℕ) + (key : ℕ × TargetInterval target.length) + (hB : 2 ≤ B) (hnx : Nat.size source.length ≤ B) (hny : Nat.size target.length ≤ B) + (hM : Nat.size M ≤ B) (hb : Nat.size key.1 ≤ B) (hPb : Nat.size P ≤ B) + (he : exponent + 1 ≤ B) (hH : Nat.size H ≤ B) + (hd : Nat.size (M * (40 * P + 2) ^ 2) ≤ B) + (htau : tau.width ≤ B) (hchild : ∀ i q, (child i q).1.width ≤ B) + (hR : ∀ i q, (child i q).2 ≤ R) : + Nat.size (queryOnlineRangeWithWork parent P exponent H tau child key).1 ≤ 240 * (B + 4) + 7 ∧ + (queryOnlineRangeWithWork parent P exponent H tau child key).2 ≤ queryOnlineRangeBitBudget M P B R := by + let V := (40 * P + 2) ^ (2 * M) + let band := preparedRepresentativeReadWithWork parent key.2 (parent.hi - parent.lo) key.1 P + tau (inversePowerTwo exponent) child + let setup := onlineIndexSetupWithWork H band.1 + let power := bitPowerWithWork setup.1.bits 80 + let mass := triangularMassWithWork (bitWordValue power.1) + have hvalue := (preparedRepresentativeReadWithWork_eq_cost parent key.2 (parent.hi - parent.lo) + key.1 P tau (inversePowerTwo exponent) child R hR).1 + have hsemantic : band.1 = representativeBandActions source target parent key.2 key.1 P tau.value + (inversePowerTwo exponent).value (fun i q => (child i q).1.value) := by + exact hvalue.trans (preparedRepresentativeWithWork_value source target parent key.2 key.1 P hP + tau (inversePowerTwo exponent) (fun i q => (child i q).1)) + have hlen : band.1.length ≤ V := by + rw [hsemantic] + exact (representativeBandActions_length_le source target parent key.2 key.1 P tau.value + (inversePowerTwo exponent).value (fun i q => (child i q).1.value)).trans + (wideActionList_length_le M parent key.2 key.1 P hP) + have hdim : (listedBandCoordinates band.1).length ≤ M * (40 * P + 2) ^ 2 := by + rw [listedBandCoordinates_length, hsemantic] + exact bandCoordinates_card_le parent key.2 hP _ + (fun action ha => representativeBandActions_wide source target parent key.2 key.1 P tau.value + (inversePowerTwo exponent).value (fun i q => (child i q).1.value) action ha) + have hwide : (wideActionGridWithWork M parent key.2 key.1 P).1.length ≤ V := by + have hh := congrArg List.length (wideActionGridWithWork_value M parent key.2 key.1 P hP) + simp only [List.length_map] at hh + rw [hh] + exact wideActionList_length_le M parent key.2 key.1 P hP + have hplain := preparedRepresentativeWithWork_complete_cost parent key.2 key.1 P B hP tau + (inversePowerTwo exponent) (fun i q => (child i q).1) hnx hny hM hb hPb htau + (by rw [inversePowerTwo_width]; exact he) hchild + have hmono := representativeCompleteBitBudget_mono_vertices M _ V (4 * B + 20) hwide + have hband := preparedRepresentativeReadWithWork_factor parent key.2 (parent.hi - parent.lo) + key.1 P tau (inversePowerTwo exponent) child R hR + have hbandCost : band.2 ≤ + (wideMaterializationBitBudget M P B + representativeCompleteBitBudget M V (4 * B + 20) + V + 1) * + tableReadFactor R := by + apply hband.trans + apply Nat.mul_le_mul_right + omega + have hsetup := onlineIndexSetupWithWork_bounds H B band.1 hB hH hM hny + ((Nat.size_le_size hdim).trans hd) + have hsetupWork : setup.2 ≤ onlineIndexBitBudget M band.1.length B := by + simpa only [setup] using hsetup.2 + have hsetupCost : setup.2 ≤ onlineIndexBitBudget M V B := + hsetupWork.trans (onlineIndexBitBudget_mono_vertices M B band.1.length V hlen) + have hsetupSize : setup.1.bits.length ≤ B + 4 := by + simpa only [setup, Nat.size_eq_bits_len] using hsetup.1 + have hpower : power.2 ≤ bitPowerBitBudget 80 (B + 4) := by + simpa only [power] using bitPowerWithWork_cost setup.1.bits 80 (B + 4) hsetupSize + have hpowerLength : power.1.length ≤ 80 * (B + 4) + 1 := by + simpa only [power] using bitPowerWithWork_length_le setup.1.bits 80 (B + 4) hsetupSize + have hpowerSize : Nat.size (bitWordValue power.1) ≤ 80 * (B + 4) + 1 := + (Nat.size_le.mpr (bitWordValue_lt_pow_length power.1)).trans hpowerLength + have hmass := triangularMassWithWork_bounds (bitWordValue power.1) (80 * (B + 4) + 1) hpowerSize + have hmassLength : mass.1.length ≤ 3 * (80 * (B + 4) + 1) + 4 := by + simpa only [mass] using hmass.1 + have hmassCost : mass.2 ≤ 10000 * (80 * (B + 4) + 4) ^ 2 := by + simpa only [mass, Nat.add_assoc, Nat.reduceAdd] using hmass.2 + have hwidth : (saturatingSubtractWithWork parent.hi parent.lo).2 ≤ 26 * B + 4 := by + have hhi := (Nat.size_le_size parent.valid).trans hnx + have hlo := (Nat.size_le_size (parent.ordered.trans parent.valid)).trans hnx + have hh := saturatingSubtractWithWork_cost parent.hi parent.lo + omega + constructor + · have hm : Nat.size (bitWordValue mass.1) ≤ 3 * (80 * (B + 4) + 1) + 4 := + (Nat.size_le.mpr (bitWordValue_lt_pow_length mass.1)).trans hmassLength + have hsize : Nat.size (bitWordValue mass.1) ≤ 240 * (B + 4) + 7 := + hm.trans_eq (by ring) + simpa only [queryOnlineRangeWithWork, saturatingSubtractWithWork_value, + band, setup, power, mass] using hsize + · have hcost : (saturatingSubtractWithWork parent.hi parent.lo).2 + + band.2 + setup.2 + power.2 + mass.2 + 4 ≤ queryOnlineRangeBitBudget M P B R := by + have hsum := Nat.add_le_add_right + (Nat.add_le_add (Nat.add_le_add (Nat.add_le_add (Nat.add_le_add hwidth hbandCost) + hsetupCost) hpower) hmassCost) 4 + simpa only [queryOnlineRangeBitBudget, V] using hsum + simpa only [queryOnlineRangeWithWork, saturatingSubtractWithWork_value, + band, setup, power, mass] using hcost + +end EditApproximation.BinaryFraction + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryOnlineRangeSpace.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryOnlineRangeSpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..1e1caf19b48b3d52d04b12a281679b59b1a1ed4b --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryOnlineRangeSpace.lean @@ -0,0 +1,50 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryOnlineSources +import OAI.Combinatorics.EditApproximation.Binary.BinaryRepresentativeSpace +import OAI.Combinatorics.EditApproximation.Binary.BinaryTriangularSpace +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation.BinaryFraction + + + +theorem onlineIndexSetupAllocation_le_work {M n : ℕ} (H : ℕ) (band : List (Fin M → TargetInterval n)) : + onlineIndexSetupAllocation H band ≤ (onlineIndexSetupWithWork H band).2 := by + have hc := bandCoordinatesAllocation_le_work band + have hs := binaryNaturalAddAllocation_le_work H (bandCoordinatesWithWork band).1.length + have ho := binaryNaturalAddAllocation_le_work (bitWordValue (binaryNaturalAddWithWork H + (bandCoordinatesWithWork band).1.length).1) 2 + have hp := bitPowerAllocation_le_work (binaryNaturalAddWithWork + (bitWordValue (binaryNaturalAddWithWork H (bandCoordinatesWithWork band).1.length).1) 2).1 80 + unfold onlineIndexSetupAllocation onlineIndexSetupWithWork + dsimp only + omega + + + +theorem queryOnlineRangeAllocation_le_work {nx ny M : ℕ} (parent : TargetInterval nx) + (P exponent H : ℕ) (tau : BinaryFraction) + (child : Fin M → TargetInterval ny → BinaryFraction × ℕ) + (allocation : Fin M → TargetInterval ny → ℕ) (key : ℕ × TargetInterval ny) + (h : ∀ i q, allocation i q ≤ (child i q).2) : + queryOnlineRangeAllocation parent P exponent H tau child allocation key ≤ + (queryOnlineRangeWithWork parent P exponent H tau child key).2 := by + let width := (saturatingSubtractWithWork parent.hi parent.lo).1 + let band := (preparedRepresentativeReadWithWork parent key.2 (bitWordValue width) key.1 P + tau (inversePowerTwo exponent) child).1 + let setup := (onlineIndexSetupWithWork H band).1 + have hw := saturatingSubtractAllocation_le_work parent.hi parent.lo + have hb := preparedRepresentativeReadAllocation_le_work parent key.2 (bitWordValue width) key.1 P + tau (inversePowerTwo exponent) child allocation h + have hs := onlineIndexSetupAllocation_le_work H band + have hp := bitPowerAllocation_le_work setup.bits 80 + have hm := triangularMassAllocation_le_work (bitWordValue (bitPowerWithWork setup.bits 80).1) + unfold queryOnlineRangeAllocation queryOnlineRangeWithWork + dsimp only [width, band, setup] at hb hs hp hm ⊢ + omega + +end EditApproximation.BinaryFraction + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryOnlineSources.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryOnlineSources.lean new file mode 100644 index 0000000000000000000000000000000000000000..038ddfbd305874e66006e84c24be7b7d804bc2c6 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryOnlineSources.lean @@ -0,0 +1,73 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryInitialGather +import OAI.Combinatorics.EditApproximation.Binary.BinaryBandReads +import OAI.Combinatorics.EditApproximation.Binary.BinaryKeyedOnline +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! An online random-source range is computed from the gathered mass +words before the source is requested. Band construction, dimension, +eighty-fold power, and triangular mass are all charged. -/ + +namespace EditApproximation +namespace BinaryFraction + + + +theorem queryOnlineRangeWithWork_value {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (P exponent H : ℕ) (hP : 0 < P) + (tau : BinaryFraction) (child : Fin M → TargetInterval target.length → BinaryFraction × ℕ) + (key : ℕ × TargetInterval target.length) (R : ℕ) (hR : ∀ i r, (child i r).2 ≤ R) : + (queryOnlineRangeWithWork parent P exponent H tau child key).1 = + keyedOnlineSourceRange source target parent P exponent H tau.value + (fun i r => (child i r).1.value) key := by + have hb := (preparedRepresentativeReadWithWork_eq_cost parent key.2 + (parent.hi - parent.lo) key.1 P tau (inversePowerTwo exponent) child R hR).1 + simp only [queryOnlineRangeWithWork, saturatingSubtractWithWork_value, hb, + triangularMassWithWork_value, bitPowerWithWork_value, bitWordValue_bits, + onlineIndexSetupWithWork_value, listedBandCoordinates_length, + preparedRepresentativeWithWork_value source target parent key.2 key.1 P hP, + inversePowerTwo_value, keyedOnlineSourceRange, keyedOnlineBandG] + +end BinaryFraction + + + +theorem queryOnlineSourceGather_refines {ι β α : Type*} (source target : List α) {M : ℕ} + {relation : β → ℚ → Prop} (parent : TargetInterval source.length) + (N P F exponent H : ℕ) (hP : 0 < P) (tau a : BinaryFraction) + (initial : TargetInterval target.length → BinaryFraction × ℕ) + (child : Fin M → TargetInterval target.length → BinaryFraction × ℕ) + (q : TargetInterval target.length) (R : ℕ) (hR : ∀ i r, (child i r).2 ≤ R) + (reader : (ℕ × TargetInterval target.length) → ℕ → BitQuery ι BinaryFraction) + (expectedReader : (ℕ × TargetInterval target.length) → ℕ → FiniteQuery ι) + (next : List (ℕ × TargetInterval target.length) → List BinaryFraction → BitQuery ι β) + (expectedNext : List (ℕ × TargetInterval target.length) → List ℚ → FiniteQuery ι) + (hr : ∀ key range, BitQuery.Refines (fun word value => word.value = value) + (reader key range) (expectedReader key range)) + (hn : ∀ words, + let keys := localOnlineSourceKeys N P F a.value (fun r => (initial r).1.value) q + BitQuery.Refines relation (next keys words) (expectedNext keys (words.map BinaryFraction.value))) : + BitQuery.Refines relation + (queryOnlineSourceGather parent N P F exponent H hP tau a initial child q reader next) + (let keys := localOnlineSourceKeys N P F a.value (fun r => (initial r).1.value) q + FiniteQuery.collect (fun key => expectedReader key + (keyedOnlineSourceRange source target parent P exponent H tau.value + (fun i r => (child i r).1.value) key)) keys (expectedNext keys)) := by + apply BitQuery.Refines.charge + change BitQuery.Refines relation (.charge _ _) _ + apply BitQuery.Refines.charge + change BitQuery.Refines relation (BitQuery.collect _ _ _) _ + rw [BinaryFraction.queryOnlineKeysWithWork_value] + apply BitQuery.Refines.collect + · intro key + change BitQuery.Refines _ (.charge _ _) _ + apply BitQuery.Refines.charge + rw [BinaryFraction.queryOnlineRangeWithWork_value source target parent P exponent H hP tau child key R hR] + exact hr key _ + · exact hn + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryOrderBounds.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryOrderBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..4c7587825aa24d37358e2f8134e8ab7acf2cab25 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryOrderBounds.lean @@ -0,0 +1,55 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryInputCodes + +namespace OAI + +/-! Quadratic work bounds for actual duplicate removal and encoded sorting. +The bound counts comparisons and list allocation, including duplicates. -/ + +namespace EditApproximation + +theorem queryEraseLoopWithWork_length {α : Type*} (equal : α → α → Bool × ℕ) + (xs seen : List α) : + (queryEraseLoopWithWork equal xs seen).1.length ≤ xs.length + seen.length := by + induction xs generalizing seen with + | nil => simp only [queryEraseLoopWithWork, List.length_reverse, List.length_nil, Nat.zero_add, le_refl] + | cons a xs ih => + change (queryEraseLoopWithWork equal xs + (if (memberByWithWork equal a seen).1 then seen else a :: seen)).1.length ≤ _ + split_ifs + · exact (ih seen).trans (by simp only [List.length_cons]; omega) + · exact (ih (a :: seen)).trans (by simp only [List.length_cons]; omega) + +theorem queryEraseWithWork_length {α : Type*} (equal : α → α → Bool × ℕ) (xs : List α) : + (queryEraseWithWork equal xs).1.length ≤ xs.length := by + simpa only [queryEraseWithWork, List.length_nil, Nat.add_zero] using + queryEraseLoopWithWork_length equal xs [] + +theorem queryOrderedInputsWithWork_cost {α : Type*} + (encode : α → ℕ) (equal le : α → α → Bool × ℕ) + (hle : ∀ a b, (le a b).1 = decide (encode a ≤ encode b)) + (C D : ℕ) (hequal : ∀ a b, (equal a b).2 ≤ C) (horder : ∀ a b, (le a b).2 ≤ D) + (xs : List α) : + (queryOrderedInputsWithWork equal le xs).2 ≤ + (xs.length + 1) ^ 2 * (C + D + 8) := by + have he := queryEraseWithWork_cost equal C hequal xs + have hs := querySortWithWork_cost (fun a b => encode a ≤ encode b) le hle D horder + (queryEraseWithWork equal xs).1 + have hl := queryEraseWithWork_length equal xs + have hp : ((queryEraseWithWork equal xs).1.length + 1) ^ 2 ≤ (xs.length + 1) ^ 2 := by + gcongr + have hb := hs.trans (Nat.mul_le_mul_right (D + 3) hp) + change (queryEraseWithWork equal xs).2 + _ + 1 ≤ _ + nlinarith only [he, hb, Nat.zero_le C, Nat.zero_le D, Nat.zero_le xs.length] + +theorem queryEncodedLEWithWork_cost {α : Type*} (code : α → ℕ × ℕ) + (a b : α) (C B : ℕ) (ha : (code a).2 ≤ C) (hb : (code b).2 ≤ C) + (hva : Nat.size (code a).1 ≤ B) (hvb : Nat.size (code b).1 ≤ B) : + (queryEncodedLEWithWork code a b).2 ≤ 2 * C + 10 * B + 5 := by + have hc := wordLEWithWork_cost (code a).1.bits (code b).1.bits + rw [Nat.size_eq_bits_len, Nat.size_eq_bits_len] at hc + change _ + _ + _ + _ + _ + 3 ≤ _ + omega + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryOrderedInputs.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryOrderedInputs.lean new file mode 100644 index 0000000000000000000000000000000000000000..ed50962be2505d024a072eefa7ded3873f3194be --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryOrderedInputs.lean @@ -0,0 +1,88 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryListWork +import OAI.Combinatorics.EditApproximation.Geometry.GatheredLocalStep +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Counted insertion sorting for the distinct-key lists. The numerical +encoding determines exactly the order used by the reference query. -/ + +namespace EditApproximation + + + + + +theorem queryInsertWithWork_value {α : Type*} (r : α → α → Prop) [DecidableRel r] + (le : α → α → Bool × ℕ) (hle : ∀ a b, (le a b).1 = decide (r a b)) + (a : α) (xs : List α) : + (queryInsertWithWork le a xs).1 = List.orderedInsert r a xs := by + induction xs with + | nil => rfl + | cons b xs ih => + simp only [queryInsertWithWork, hle, List.orderedInsert_cons, decide_eq_true_eq] + split <;> simp only [ih] + +theorem querySortWithWork_value {α : Type*} (r : α → α → Prop) [DecidableRel r] + (le : α → α → Bool × ℕ) (hle : ∀ a b, (le a b).1 = decide (r a b)) (xs : List α) : + (querySortWithWork le xs).1 = xs.insertionSort r := by + induction xs with + | nil => rfl + | cons a xs ih => + simp only [querySortWithWork, queryInsertWithWork_value r le hle, ih, List.insertionSort_cons] + +theorem queryInsertWithWork_cost {α : Type*} (le : α → α → Bool × ℕ) + (C : ℕ) (hC : ∀ a b, (le a b).2 ≤ C) (a : α) (xs : List α) : + (queryInsertWithWork le a xs).2 ≤ (xs.length + 1) * (C + 2) := by + induction xs with + | nil => simp only [queryInsertWithWork, List.length_nil]; omega + | cons b xs ih => + have h := hC a b + simp only [queryInsertWithWork, List.length_cons] + split <;> dsimp only + · nlinarith only [h, Nat.zero_le xs.length, Nat.zero_le C] + · nlinarith only [h, ih] + +theorem querySortWithWork_cost {α : Type*} (r : α → α → Prop) [DecidableRel r] + (le : α → α → Bool × ℕ) (hle : ∀ a b, (le a b).1 = decide (r a b)) + (C : ℕ) (hC : ∀ a b, (le a b).2 ≤ C) (xs : List α) : + (querySortWithWork le xs).2 ≤ (xs.length + 1) ^ 2 * (C + 3) := by + induction xs with + | nil => simp only [querySortWithWork, List.length_nil]; omega + | cons a xs ih => + have hi := queryInsertWithWork_cost le C hC a (querySortWithWork le xs).1 + have hl : (querySortWithWork le xs).1.length = xs.length := by + rw [querySortWithWork_value r le hle, List.length_insertionSort] + rw [hl] at hi + change (querySortWithWork le xs).2 + _ + 1 ≤ _ + simp only [List.length_cons] + nlinarith only [ih, hi, Nat.zero_le xs.length, Nat.zero_le C] + + + +theorem queryOrderedInputsWithWork_value {α : Type*} [DecidableEq α] + (encode : α → ℕ) (hinjective : Function.Injective encode) + (equal le : α → α → Bool × ℕ) + (heq : ∀ a b, (equal a b).1 = true ↔ a = b) + (hle : ∀ a b, (le a b).1 = decide (encode a ≤ encode b)) (xs : List α) : + (queryOrderedInputsWithWork equal le xs).1 = orderedInputs encode hinjective xs.toFinset := by + let : LinearOrder α := LinearOrder.lift' encode hinjective + have hle' : ∀ a b, (le a b).1 = decide (a ≤ b) := hle + rw [queryOrderedInputsWithWork, querySortWithWork_value (· ≤ ·) le hle', + queryEraseWithWork_value equal heq] + have hd := queryEraseWithWork_nodup equal heq xs + rw [queryEraseWithWork_value equal heq] at hd + have hn : (xs.eraseDups.insertionSort (· ≤ ·)).Nodup := + (List.perm_insertionSort (· ≤ ·) xs.eraseDups).nodup_iff.mpr hd + have hs := (List.toFinset_sort (r := (· ≤ ·)) hn).mpr + (List.pairwise_insertionSort (· ≤ ·) xs.eraseDups) + have hf : (xs.eraseDups.insertionSort (· ≤ ·)).toFinset = xs.toFinset := by + ext x + simp only [List.mem_toFinset, List.mem_insertionSort, List.mem_eraseDups] + rw [hf] at hs + exact hs.symm + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryOrderedSpace.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryOrderedSpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..a56f221d92cfea40b56b239f922d54f02f507c2f --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryOrderedSpace.lean @@ -0,0 +1,74 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryCoordinateSpace +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation + + + +theorem queryEraseLoopAllocation_le_work {α : Type*} (equal : α → α → Bool × ℕ) + (allocation : α → α → ℕ) (xs seen : List α) (h : ∀ a b, allocation a b ≤ (equal a b).2) : + queryEraseLoopAllocation equal allocation xs seen ≤ (queryEraseLoopWithWork equal xs seen).2 := by + induction xs generalizing seen with + | nil => exact Nat.le_succ _ + | cons a xs ih => + have hm := memberByAllocation_le_work equal allocation a seen (fun b _ => h a b) + have ht := ih (if (memberByWithWork equal a seen).1 then seen else a :: seen) + unfold queryEraseLoopAllocation queryEraseLoopWithWork + dsimp only + exact Nat.add_le_add (Nat.add_le_add hm ht) (by split <;> decide) + + + +theorem queryEraseAllocation_le_work {α : Type*} (equal : α → α → Bool × ℕ) + (allocation : α → α → ℕ) (xs : List α) (h : ∀ a b, allocation a b ≤ (equal a b).2) : + queryEraseAllocation equal allocation xs ≤ (queryEraseWithWork equal xs).2 := + queryEraseLoopAllocation_le_work equal allocation xs [] h + + + +theorem queryInsertAllocation_le_work {α : Type*} (le : α → α → Bool × ℕ) + (allocation : α → α → ℕ) (a : α) (xs : List α) (h : ∀ b, allocation a b ≤ (le a b).2) : + queryInsertAllocation le allocation a xs ≤ (queryInsertWithWork le a xs).2 := by + induction xs with + | nil => rfl + | cons b xs ih => + have hb := h b + simp only [queryInsertAllocation, queryInsertWithWork] + split_ifs <;> dsimp only + · exact Nat.add_le_add_right hb 2 + · calc + _ = (allocation a b + queryInsertAllocation le allocation a xs) + 1 := (Nat.add_assoc _ _ _).symm + _ ≤ _ := Nat.add_le_add (Nat.add_le_add hb ih) (by decide : 1 ≤ 2) + + + +theorem querySortAllocation_le_work {α : Type*} (le : α → α → Bool × ℕ) + (allocation : α → α → ℕ) (xs : List α) (h : ∀ a b, allocation a b ≤ (le a b).2) : + querySortAllocation le allocation xs ≤ (querySortWithWork le xs).2 := by + induction xs with + | nil => exact Nat.zero_le _ + | cons a xs ih => + have hi := queryInsertAllocation_le_work le allocation a (querySortWithWork le xs).1 (h a) + simp only [querySortAllocation, querySortWithWork] + exact (Nat.add_le_add ih hi).trans (Nat.le_succ _) + + + +theorem queryOrderedInputsAllocation_le_work {α : Type*} (equal le : α → α → Bool × ℕ) + (equalAllocation leAllocation : α → α → ℕ) (xs : List α) + (he : ∀ a b, equalAllocation a b ≤ (equal a b).2) + (hl : ∀ a b, leAllocation a b ≤ (le a b).2) : + queryOrderedInputsAllocation equal le equalAllocation leAllocation xs ≤ + (queryOrderedInputsWithWork equal le xs).2 := by + have he' := queryEraseAllocation_le_work equal equalAllocation xs he + have hl' := querySortAllocation_le_work le leAllocation (queryEraseWithWork equal xs).1 hl + unfold queryOrderedInputsAllocation queryOrderedInputsWithWork + dsimp only + omega + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryOuterGatherCost.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryOuterGatherCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..da038117cc9b33cc55962ac4c900d5e2ac287820 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryOuterGatherCost.lean @@ -0,0 +1,98 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryInitialSupportCost +import OAI.Combinatorics.EditApproximation.Queries.QueryBandInputCost +import OAI.Combinatorics.EditApproximation.Queries.QueryBandGather + +namespace OAI + +namespace EditApproximation + +private theorem outer_read_sum_bound {κ : Type*} (keys : List κ) (cost : κ → ℕ) (B : ℕ) + (h : ∀ key ∈ keys, cost key ≤ B) : (keys.map cost).sum ≤ keys.length * B := by + induction keys with + | nil => simp + | cons key keys ih => + have hh := h key List.mem_cons_self + have ht := ih (fun k hk => h k (List.mem_cons_of_mem key hk)) + simp only [List.map_cons, List.sum_cons, List.length_cons, Nat.add_mul, Nat.one_mul] + omega + +namespace BinaryFraction + +def queryInitialGatherBitBudget (P F exponent B R K : ℕ) : ℕ := + R + queryInitialSupportBitBudget P F exponent B + queryInitialSupportLength P F exponent B * (R + 3) + K + +def queryBandGatherBitBudget (M P F exponent B Rp W K : ℕ) : ℕ := + queryBandInputsBitBudget M P F exponent B Rp + + 2 * (queryEarlierRepresentativesLength P F exponent B * (M * (40 * P + 2) ^ 2) * (W + 3)) + K + +end BinaryFraction +open BinaryFraction + +theorem queryInitialGather_work_bound {ι β : Type*} {n : ℕ} + (N P F exponent B R K : ℕ) (hP : 0 < P) (a : BinaryFraction) (q : TargetInterval n) + (reader : TargetInterval n → BitQuery ι BinaryFraction) + (next : List (TargetInterval n) → List BinaryFraction → BitQuery ι β) + (oracle : ι → BinaryFraction) (readWork : ι → ℕ) + (hB : 8 ≤ B) (hN : Nat.size N ≤ B) (hF : Nat.size F + 2 ≤ B) (hFpos : 1 ≤ F) + (hPb : Nat.size P ≤ B) (hn : Nat.size n ≤ B) (he : exponent + 1 ≤ B) (ha : a.width ≤ B) + (hv : ((reader q).value oracle).width ≤ B) (hw : 0 ≤ ((reader q).value oracle).value) + (hPd : ∃ e : ℕ, P = 2 ^ e) (hR : ∀ r, (reader r).work oracle readWork ≤ R) + (hnext : + let keys := (queryInitialSupportWithWork N P F exponent hP a ((reader q).value oracle) q).1 + (next keys (keys.map fun r => (reader r).value oracle)).work oracle readWork ≤ K) : + (queryInitialGather N P F exponent hP a q reader next).work oracle readWork ≤ + queryInitialGatherBitBudget P F exponent B R K := by + let support := queryInitialSupportWithWork N P F exponent hP a ((reader q).value oracle) q + have hs := queryInitialSupportWithWork_bounds N P F exponent B hP a ((reader q).value oracle) q + hB hN hF hFpos hPb hn he ha hv hw hPd + have hr := (outer_read_sum_bound support.1 (fun r => (reader r).work oracle readWork + 3) (R + 3) + (fun r _ => Nat.add_le_add_right (hR r) 3)).trans (Nat.mul_le_mul_right _ hs.1) + have hsc : support.2 ≤ queryInitialSupportBitBudget P F exponent B := hs.2 + change (next support.1 (support.1.map fun r => (reader r).value oracle)).work oracle readWork ≤ K at hnext + rw [queryInitialGather_work] + change (reader q).work oracle readWork + support.2 + + (support.1.map fun r => (reader r).work oracle readWork + 3).sum + + (next support.1 (support.1.map fun r => (reader r).value oracle)).work oracle readWork ≤ _ + have hq := hR q + unfold queryInitialGatherBitBudget + omega + +theorem queryBandGather_work_bound {ι β : Type*} {nx ny : ℕ} + (M N P F exponent B Rp W K : ℕ) (parent : TargetInterval nx) (hP : 0 < P) + (a : BinaryFraction) (initial : TargetInterval ny → BinaryFraction × ℕ) (q : TargetInterval ny) + (massReader initialReader : (Fin M × TargetInterval ny) → BitQuery ι BinaryFraction) + (next : List (Fin M × TargetInterval ny) → List BinaryFraction → List BinaryFraction → BitQuery ι β) + (oracle : ι → BinaryFraction) (readWork : ι → ℕ) + (hB : 8 ≤ B) (hN : Nat.size N ≤ B) (hF : Nat.size F + 2 ≤ B) (hFpos : 1 ≤ F) + (hPb : Nat.size P ≤ B) (hnx : Nat.size nx ≤ B) (hny : Nat.size ny ≤ B) (hM : Nat.size M ≤ B) + (he : exponent + 1 ≤ B) (ha : a.width ≤ B) (hi : ∀ r, (initial r).1.width ≤ B) + (hR : ∀ r, (initial r).2 ≤ Rp) (hw : 0 ≤ (initial q).1.value) (hPd : ∃ e : ℕ, P = 2 ^ e) + (hm : ∀ key, (massReader key).work oracle readWork ≤ W) + (hr : ∀ key, (initialReader key).work oracle readWork ≤ W) + (hnext : + let keys := (queryBandInputsWithWork M parent N P F exponent hP a initial q).1 + (next keys (keys.map fun key => (massReader key).value oracle) + (keys.map fun key => (initialReader key).value oracle)).work oracle readWork ≤ K) : + (queryBandGather M parent N P F exponent hP a initial q massReader initialReader next).work oracle readWork ≤ + queryBandGatherBitBudget M P F exponent B Rp W K := by + let keys := queryBandInputsWithWork M parent N P F exponent hP a initial q + have hk := queryBandInputsWithWork_bounds M N P F exponent B Rp parent hP a initial q + hB hN hF hFpos hPb hnx hny hM he ha hi hR hw hPd + have hmass := (outer_read_sum_bound keys.1 (fun key => (massReader key).work oracle readWork + 3) + (W + 3) (fun key _ => Nat.add_le_add_right (hm key) 3)).trans (Nat.mul_le_mul_right _ hk.1) + have hinit := (outer_read_sum_bound keys.1 (fun key => (initialReader key).work oracle readWork + 3) + (W + 3) (fun key _ => Nat.add_le_add_right (hr key) 3)).trans (Nat.mul_le_mul_right _ hk.1) + have hkc : keys.2 ≤ queryBandInputsBitBudget M P F exponent B Rp := hk.2 + change (next keys.1 (keys.1.map fun key => (massReader key).value oracle) + (keys.1.map fun key => (initialReader key).value oracle)).work oracle readWork ≤ K at hnext + rw [queryBandGather_work] + change keys.2 + (keys.1.map fun key => (massReader key).work oracle readWork + 3).sum + + (keys.1.map fun key => (initialReader key).work oracle readWork + 3).sum + + (next keys.1 (keys.1.map fun key => (massReader key).value oracle) + (keys.1.map fun key => (initialReader key).value oracle)).work oracle readWork ≤ _ + unfold queryBandGatherBitBudget + omega + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryPhysicalInitial.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryPhysicalInitial.lean new file mode 100644 index 0000000000000000000000000000000000000000..e666a0f062724b8dbedea041bc5ab2a05f714c59 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryPhysicalInitial.lean @@ -0,0 +1,60 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryInitialConeProgram +import OAI.Combinatorics.EditApproximation.Queries.QueryChargedSeed +import OAI.Combinatorics.EditApproximation.Queries.QueryIndexedSlice +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! The complete physical initial branch. It reads terminal symbols +through the original array and uses a length descriptor for the nonterminal +initial-cone computation. Seed reads remain adaptive ranked requests. -/ + +namespace EditApproximation + +section Initial +variable (source target : List ℕ) {M J passes copies T S : ℕ} + (N P F : ℕ) (A a : BinaryFraction) (multiplier : ℕ → ℕ) + (parent : {r : PhysicalTableRequest M J target.length // r.Bounded passes copies T S}) + (occurrence : BinaryMemo PositionCounts) (symbolBits positionBits : ℕ) + (q : TargetInterval target.length) + + + +theorem queryPhysicalInitial_refines (hP : 0 < P) + (ha : a.value = refinementFactor A.value F) + (hs : ∀ z ∈ source, z < 2 ^ symbolBits) (ht : ∀ z ∈ target, z < 2 ^ symbolBits) + (hp : target.length ≤ 2 ^ positionBits) + (htable : occurrence = occurrenceBuild symbolBits positionBits target.zipIdx) : + BitQuery.Refines (fun word value => word.value = value) + (queryPhysicalInitial source target N P F A a multiplier parent occurrence symbolBits positionBits q) + (physicalInitialQuery source target N P F A.value (chargedSeedQuery N multiplier parent) + (parent.val.node, q)) := by + have htest : (wordLEWithWork + (saturatingSubtractWithWork (physicalSourceInterval source.length parent.val.node).hi + (physicalSourceInterval source.length parent.val.node).lo).1 [true]).1 = true ↔ + (physicalSource source parent.val.node).length ≤ 1 := by + rw [wordLEWithWork_value, saturatingSubtractWithWork_value, physicalSource_length_eq] + rfl + unfold queryPhysicalInitial + apply BitQuery.Refines.charge + unfold physicalInitialQuery + dsimp only + by_cases hshort : (physicalSource source parent.val.node).length ≤ 1 + · rw [ite_eq_left hshort, ite_eq_left (htest.mpr hshort)] + apply BitQuery.Refines.charge + apply BitQuery.Refines.done + rw [htable, queryIndexedSliceWithWork_value source target _ _ symbolBits positionBits hs ht hp] + rfl + · rw [ite_eq_right hshort, ite_eq_right (fun h => hshort (htest.mp h))] + simp only [saturatingSubtractWithWork_value] + rw [← physicalSource_length_eq source parent.val.node] + exact queryInitialConeProgram_refines (physicalSource source parent.val.node) target N P F hP A a + (queryChargedSeedAt parent N multiplier) q + (fun r => chargedSeedQuery N multiplier parent (parent.val.node, r)) + (fun r => queryChargedSeedAt_refines parent N multiplier r) ha + +end Initial +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryPhysicalInitialCost.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryPhysicalInitialCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..319ca7965216a7b7600fe8ab7cd31f9f23a051ae --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryPhysicalInitialCost.lean @@ -0,0 +1,88 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryPhysicalInitial +import OAI.Combinatorics.EditApproximation.Queries.QueryInitialProgramCost +import OAI.Combinatorics.EditApproximation.Queries.QueryChargedSeedCost +import OAI.Combinatorics.EditApproximation.Coarse.CoarseDescriptorWork + +namespace OAI + +namespace EditApproximation + +/-- The slice test reads only the stored endpoints; it does not materialize the substring. -/ +theorem querySliceTest_cost {α : Type*} (source : List α) (interval : TargetInterval source.length) + (B : ℕ) (hB : Nat.size source.length ≤ B) : + (saturatingSubtractWithWork interval.hi interval.lo).2 + + (wordLEWithWork (saturatingSubtractWithWork interval.hi interval.lo).1 [true]).2 + 2 ≤ 30 * B + 20 := by + have hlo := (Nat.size_le_size (interval.ordered.trans interval.valid)).trans hB + have hhi := (Nat.size_le_size interval.valid).trans hB + have hs := saturatingSubtractWithWork_cost interval.hi interval.lo + have hl := (saturatingSubtractWithWork_length interval.hi interval.lo).trans (max_le hhi hlo) + have ht := wordLEWithWork_cost (saturatingSubtractWithWork interval.hi interval.lo).1 [true] + simp only [List.length_cons, List.length_nil] at ht + omega + +def queryPhysicalInitialBitBudget (P _F Amax copies J symbolBits positionBits B C : ℕ) : ℕ := + 30 * B + 20 + (10 * B + 2 * symbolBits + 4 * positionBits + B + 17) + + BinaryFraction.queryInitialProgramBitBudget P Amax B (queryChargedSeedBitBudget copies J B C) + +section Initial +variable (source target : List ℕ) {M J passes copies T S : ℕ} + (N P F Amax B C : ℕ) (A a : BinaryFraction) (multiplier : ℕ → ℕ) + (parent : {r : PhysicalTableRequest M J target.length // r.Bounded passes copies T S}) + (occurrence : BinaryMemo PositionCounts) (symbolBits positionBits : ℕ) + (oracle : {child : ChargedPhysicalRequest M J target.length passes copies T S // + child.rank < ChargedPhysicalRequest.rank (.inr parent)} → BinaryFraction) + (readWork : {child : ChargedPhysicalRequest M J target.length passes copies T S // + child.rank < ChargedPhysicalRequest.rank (.inr parent)} → ℕ) + +theorem queryPhysicalInitial_work_bound (q : TargetInterval target.length) + (hB : 8 ≤ B) (hP : 0 < P) (hN : Nat.size N ≤ B) (hPb : Nat.size P ≤ B) + (hF : Nat.size F ≤ B) (hs : Nat.size source.length ≤ B) (ht : Nat.size (target.length + 1) ≤ B) + (hA : A.width ≤ B) (ha : a.width ≤ B) (hAone : 1 ≤ A.value) (hAmax : A.value ≤ Amax) + (hp : Nat.size parent.val.pass ≤ B) (hm : Nat.size (multiplier (parent.val.pass - 1)) + 2 ≤ B) + (hv : ∀ key, (oracle key).width ≤ B) (hc : ∀ key, readWork key ≤ C) : + (queryPhysicalInitial source target N P F A a multiplier parent occurrence symbolBits positionBits q).work + oracle readWork ≤ queryPhysicalInitialBitBudget P F Amax copies J symbolBits positionBits B C := by + let interval := physicalSourceInterval source.length parent.val.node + have htest := querySliceTest_cost source interval B hs + have hseed (r : TargetInterval target.length) := + queryChargedSeedAt_bounds parent oracle readWork N B C multiplier r (by omega) hN hp hm hv hc + have hlength : Nat.size (bitWordValue (saturatingSubtractWithWork interval.hi interval.lo).1) ≤ B := by + rw [saturatingSubtractWithWork_value] + exact (Nat.size_le_size ((Nat.sub_le _ _).trans interval.valid)).trans hs + have hi := queryInitialConeProgramAt_work_bound + (bitWordValue (saturatingSubtractWithWork interval.hi interval.lo).1) N P F Amax B + (queryChargedSeedBitBudget copies J B C) hP A a (queryChargedSeedAt parent N multiplier) q + oracle readWork hB hN hPb hF hlength + ((Nat.size_le_size (Nat.le_succ target.length)).trans ht) hA ha hAone hAmax + (fun r => (hseed r).1) (fun r => (hseed r).2) + have hl := (queryIndexedSliceWithWork_cost source interval target.length q occurrence symbolBits positionBits B hs).trans + (Nat.add_le_add_right (Nat.add_le_add_left ht _) 17) + unfold queryPhysicalInitial + simp only [BitQuery.work] + split + · simp only [BitQuery.compute, BitQuery.work, Nat.add_zero] + change (saturatingSubtractWithWork interval.hi interval.lo).2 + + (wordLEWithWork (saturatingSubtractWithWork interval.hi interval.lo).1 [true]).2 + 2 + + (queryIndexedSliceWithWork source interval target.length q occurrence symbolBits positionBits).2 ≤ _ + exact (Nat.add_le_add htest hl).trans (by unfold queryPhysicalInitialBitBudget; omega) + · change (saturatingSubtractWithWork interval.hi interval.lo).2 + + (wordLEWithWork (saturatingSubtractWithWork interval.hi interval.lo).1 [true]).2 + 2 + _ ≤ _ + exact (Nat.add_le_add htest hi).trans (by unfold queryPhysicalInitialBitBudget; omega) + +theorem queryPhysicalInitial_width (q : TargetInterval target.length) + (hP : 0 < P) (hleaf : Nat.size (target.length + 1) + 2 ≤ B) + (hinit : Nat.size ((32 * F + 1) * N) + 3 ≤ B) : + ((queryPhysicalInitial source target N P F A a multiplier parent occurrence symbolBits positionBits q).value + oracle).width ≤ B := by + unfold queryPhysicalInitial + simp only [BitQuery.value] + split + · exact (binaryIndexedLeafWithWork_bounds occurrence symbolBits positionBits _ q.lo q.hi).1.trans + ((Nat.add_le_add_right (Nat.size_le_size (Nat.add_le_add_right q.valid 1)) 2).trans hleaf) + · exact (queryInitialConeProgramAt_width _ N P F A a (queryChargedSeedAt parent N multiplier) q + oracle hP).trans hinit + +end Initial +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryPhysicalProgram.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryPhysicalProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..b84985467e0385ce39bd4166d1566f904c2440a6 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryPhysicalProgram.lean @@ -0,0 +1,82 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryLocalProgram +import OAI.Combinatorics.EditApproximation.Queries.QueryPhysicalReaders + +namespace OAI + +/-! The full charged refinement program on physical ranked requests and +scalar source requests. This connects the local Boolean implementation +to the same adaptive query used in the accuracy and dependency proofs. -/ + +namespace EditApproximation + +section Physical +variable {σ α : Type*} (source target : List α) {M J : ℕ} [NeZero M] + (N P F exponent H Q eM eF : ℕ) (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) + (tau a eta kappa delta : BinaryFraction) + (copies pass copy T S t : ℕ) (ht : 0 < t) + (node : PhysicalNode M J) (hbelow : node.1.val < J) + (readGroup : GroupScalarKey M F Q → BitQuery σ BinaryFraction) + (readInteger : (ℕ × TargetInterval target.length) → ℕ → BitQuery σ BinaryFraction) + (q : TargetInterval target.length) + +def queryPhysicalRandomDataRequest : + BitQuery (Sum σ {child : PhysicalTableRequest M J target.length // + child.combinedRank T S < (PhysicalTableRequest.refinement pass copy node T t q).combinedRank T S}) + BinaryFraction := + queryLocalProgram source target (physicalSourceInterval source.length node) + N P F exponent H Q eM eF hP hM hF tau a eta kappa delta t + (fun r => BitQuery.mapKeysWithWork (fun key => (Sum.inr key, 1)) + (queryPhysicalWarmupRead copies pass copy T S t ht node q node le_rfl 0 (Nat.zero_le T) r)) + (fun input => BitQuery.mapKeysWithWork (fun key => (Sum.inr key, 1)) + (queryPhysicalMassRead copies pass copy T S t ht node hbelow q input)) + (fun input => BitQuery.mapKeysWithWork (fun key => (Sum.inr key, 1)) + (queryPhysicalWarmupRead copies pass copy T S t ht node q + (physicalChild node hbelow input.1) (by change node.1.val ≤ node.1.val + 1; omega) + 0 (Nat.zero_le T) input.2)) + (fun key => BitQuery.mapKeysWithWork (fun key => (Sum.inl key, 1)) (readGroup key)) + (fun key range => BitQuery.mapKeysWithWork (fun key => (Sum.inl key, 1)) (readInteger key range)) q + (fun input => BitQuery.mapKeysWithWork (fun key => (Sum.inr key, 1)) + (queryPhysicalEarlierRead copies pass copy T S t node hbelow q input)) + (fun input => BitQuery.mapKeysWithWork (fun key => (Sum.inr key, 1)) + (queryPhysicalCurrentRead copies pass copy T S t node hbelow q input)) + +theorem queryPhysicalRandomDataRequest_refines + (expectedGroup : GroupScalarKey M F Q → FiniteQuery σ) + (expectedInteger : (ℕ × TargetInterval target.length) → ℕ → FiniteQuery σ) + (hg : ∀ key, BitQuery.Refines (fun word value => word.value = value) + (readGroup key) (expectedGroup key)) + (hz : ∀ key range, BitQuery.Refines (fun word value => word.value = value) + (readInteger key range) (expectedInteger key range)) : + BitQuery.Refines (fun word value => word.value = value) + (queryPhysicalRandomDataRequest source target N P F exponent H Q eM eF hP hM hF + tau a eta kappa delta copies pass copy T S t ht node hbelow readGroup readInteger q) + (physicalRandomDataRequestQuery source target N P F exponent H Q + tau.value a.value eta.value kappa.value delta.value pass copy T S t ht node hbelow + expectedGroup expectedInteger q) := by + unfold queryPhysicalRandomDataRequest physicalRandomDataRequestQuery + apply queryLocalProgram_refines + · intro r + exact (queryPhysicalWarmupRead_refines copies pass copy T S t ht node q node le_rfl + 0 (Nat.zero_le T) r).mapKeysWithWork _ _ (fun _ => rfl) + · intro input + exact (queryPhysicalMassRead_refines copies pass copy T S t ht node hbelow q input).mapKeysWithWork + _ _ (fun _ => rfl) + · intro input + exact (queryPhysicalWarmupRead_refines copies pass copy T S t ht node q + (physicalChild node hbelow input.1) (by change node.1.val ≤ node.1.val + 1; omega) + 0 (Nat.zero_le T) input.2).mapKeysWithWork _ _ (fun _ => rfl) + · intro key + exact (hg key).mapKeysWithWork _ _ (fun _ => rfl) + · intro key range + exact (hz key range).mapKeysWithWork _ _ (fun _ => rfl) + · intro input + exact (queryPhysicalEarlierRead_refines copies pass copy T S t node hbelow q input).mapKeysWithWork + _ _ (fun _ => rfl) + · intro input + exact (queryPhysicalCurrentRead_refines copies pass copy T S t node hbelow q input).mapKeysWithWork + _ _ (fun _ => rfl) + +end Physical +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryPhysicalProgramCost.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryPhysicalProgramCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..8716ebbd155d5090a57ed65de31de37f65e98c30 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryPhysicalProgramCost.lean @@ -0,0 +1,133 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryPhysicalProgram +import OAI.Combinatorics.EditApproximation.Queries.QueryLocalProgramCost +import OAI.Combinatorics.EditApproximation.Queries.QueryPhysicalReaderBounds +import OAI.Combinatorics.EditApproximation.Queries.QuerySourceWidths + +namespace OAI + +namespace EditApproximation.BinaryFraction + +def queryPhysicalDataBudget (T J B V C W : ℕ) : ℕ := + W + (T + 1 + T * (7 * J + 30 + (C + 1) + 3) + warmupAverageBitBudget T V) + + (8 * B + 7 * J + 32 + (C + 1)) + 1 + +end EditApproximation.BinaryFraction + +namespace EditApproximation +section Physical +variable {σ α : Type*} (source target : List α) {M J : ℕ} [NeZero M] + (N P F exponent H Q eM eF B E Scale : ℕ) (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) + (tau a eta kappa delta : BinaryFraction) + (copies pass copy T S t : ℕ) (ht : 0 < t) + (node : PhysicalNode M J) (hbelow : node.1.val < J) + (readGroup : GroupScalarKey M F Q → BitQuery σ BinaryFraction) + (readInteger : (ℕ × TargetInterval target.length) → ℕ → BitQuery σ BinaryFraction) + (q : TargetInterval target.length) + (oracle : Sum σ {child : PhysicalTableRequest M J target.length // child.combinedRank T S < + (PhysicalTableRequest.refinement pass copy node T t q).combinedRank T S} → BinaryFraction) + (readWork : Sum σ {child : PhysicalTableRequest M J target.length // child.combinedRank T S < + (PhysicalTableRequest.refinement pass copy node T t q).combinedRank T S} → ℕ) + +local notation "tableOracle" => (fun key => oracle (Sum.inr key)) +local notation "sourceOracle" => (fun key => oracle (Sum.inl key)) +local notation "sourceWork" => (fun key => 1 + readWork (Sum.inl key)) + +open BinaryFraction + +theorem queryPhysicalRandomDataRequest_work_bound (V C W : ℕ) + (hn : PreparedKernelNumericBounds (nx := source.length) (ny := target.length) (M := M) + N P F exponent H Q eM eF B E Scale (t - 1) tau a eta kappa delta (fun _ _ => 0)) + (htime : Nat.size t ≤ B) (hPd : ∃ j : ℕ, P = 2 ^ j) + (hV : 2 ≤ V) (hVB : V ≤ B) (hMean : warmupAverageWordBudget T V ≤ B) + (hc : ∀ key, key.val.pass = pass → key.val.copy = copy → readWork (Sum.inr key) ≤ C) + (hv : ∀ key, (tableOracle key).width ≤ V) + (hnonneg : ∀ key, 0 ≤ (tableOracle key).value) + (hprior : ∀ input : Fin M × ℕ × TargetInterval target.length, + ((queryPhysicalEarlierRead copies pass copy T S t node hbelow q input).value tableOracle).value ≤ + ((queryPhysicalWarmupRead copies pass copy T S t ht node q + (physicalChild node hbelow input.1) (by change node.1.val ≤ node.1.val + 1; omega) + 0 (Nat.zero_le T) input.2.2).value tableOracle).value) + (hgW : ∀ key, ((readGroup key).value sourceOracle).width ≤ B) + (hzW : ∀ key range, ((readInteger key range).value sourceOracle).width ≤ B) + (hgR : ∀ key, queryGroupKeySize key ≤ 40 * B + 500 → + (readGroup key).work sourceOracle sourceWork ≤ W) + (hzR : ∀ key range, Nat.size key.1 ≤ B + 1 → Nat.size range ≤ 240 * (B + 5) + 7 → + (readInteger key range).work sourceOracle sourceWork ≤ W) : + (queryPhysicalRandomDataRequest source target N P F exponent H Q eM eF hP hM hF + tau a eta kappa delta copies pass copy T S t ht node hbelow readGroup readInteger q).work oracle readWork ≤ + queryLocalProgramBitBudget M N P F exponent eM eF B Scale t (queryPhysicalDataBudget T J B V C W) := by + have htable : ∀ key, key.val.pass = pass → key.val.copy = copy → + 1 + readWork (Sum.inr key) ≤ C + 1 := fun key hp hc' => by have := hc key hp hc'; omega + have hsmall : 7 * J + 30 + (C + 1) ≤ queryPhysicalDataBudget T J B V C W := by + unfold queryPhysicalDataBudget; omega + have hearlier : 8 * B + 7 * J + 32 + (C + 1) ≤ queryPhysicalDataBudget T J B V C W := by + unfold queryPhysicalDataBudget; omega + have hmass : T + 1 + T * (7 * J + 30 + (C + 1) + 3) + warmupAverageBitBudget T V ≤ + queryPhysicalDataBudget T J B V C W := by unfold queryPhysicalDataBudget; omega + have hsource : W ≤ queryPhysicalDataBudget T J B V C W := by unfold queryPhysicalDataBudget; omega + unfold queryPhysicalRandomDataRequest + apply queryLocalProgram_work_bound source target (physicalSourceInterval source.length node) + N P F exponent H Q eM eF B E Scale hP hM hF tau a eta kappa delta t _ _ _ _ _ q _ _ + oracle readWork _ hn ht htime hPd + · intro r + rw [BitQuery.mapKeysWithWork_value] + exact (hv _).trans hVB + · intro input + rw [BitQuery.mapKeysWithWork_value] + exact (queryPhysicalMassRead_bounds copies pass copy T S t ht node hbelow q tableOracle + (fun key => 1 + readWork (Sum.inr key)) V (C + 1) htable hv input).1.trans hMean + · intro input + rw [BitQuery.mapKeysWithWork_value] + exact (hv _).trans hVB + · intro key + simpa only [BitQuery.mapKeysWithWork_value] using hgW key + · intro key range + simpa only [BitQuery.mapKeysWithWork_value] using hzW key range + · intro input + rw [BitQuery.mapKeysWithWork_value] + exact (queryPhysicalEarlierRead_width copies pass copy T S t node hbelow q tableOracle V hV hv input).trans hVB + · intro input + rw [BitQuery.mapKeysWithWork_value] + exact (hv _).trans hVB + · intro r + rw [BitQuery.mapKeysWithWork_value] + exact hnonneg _ + · intro input + rw [BitQuery.mapKeysWithWork_value] + exact hnonneg _ + · intro input + rw [BitQuery.mapKeysWithWork_value] + exact queryPhysicalEarlierRead_nonneg copies pass copy T S t node hbelow q tableOracle hnonneg input + · intro input + simpa only [BitQuery.mapKeysWithWork_value] using hprior input + · intro r + rw [BitQuery.mapKeysWithWork_work] + exact (queryPhysicalWarmupRead_work_bound copies pass copy T S t ht node q tableOracle + (fun key => 1 + readWork (Sum.inr key)) (C + 1) htable node le_rfl 0 (Nat.zero_le T) r).trans hsmall + · intro input + rw [BitQuery.mapKeysWithWork_work] + exact (queryPhysicalMassRead_bounds copies pass copy T S t ht node hbelow q tableOracle + (fun key => 1 + readWork (Sum.inr key)) V (C + 1) htable hv input).2.trans hmass + · intro input + rw [BitQuery.mapKeysWithWork_work] + exact (queryPhysicalWarmupRead_work_bound copies pass copy T S t ht node q tableOracle + (fun key => 1 + readWork (Sum.inr key)) (C + 1) htable _ _ 0 (Nat.zero_le T) input.2).trans hsmall + · intro key hk + rw [BitQuery.mapKeysWithWork_work] + exact (hgR key hk).trans hsource + · intro key range hk hr + rw [BitQuery.mapKeysWithWork_work] + exact (hzR key range hk hr).trans hsource + · intro input hi + rw [BitQuery.mapKeysWithWork_work] + exact (queryPhysicalEarlierRead_work_bound copies pass copy T S t node hbelow q tableOracle + (fun key => 1 + readWork (Sum.inr key)) B (C + 1) htable htime input hi).trans hearlier + · intro input + rw [BitQuery.mapKeysWithWork_work] + exact (queryPhysicalCurrentRead_work_bound copies pass copy T S t node hbelow q tableOracle + (fun key => 1 + readWork (Sum.inr key)) (C + 1) htable input).trans hsmall + +end Physical +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryPhysicalProgramWidth.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryPhysicalProgramWidth.lean new file mode 100644 index 0000000000000000000000000000000000000000..f481a7ba8d8f144db1148630eaa27b8e0ace713e --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryPhysicalProgramWidth.lean @@ -0,0 +1,77 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryProgramWidth +import OAI.Combinatorics.EditApproximation.Queries.QueryFamilyRefinementCost + +namespace OAI + +namespace EditApproximation +open BinaryFraction + +section Physical +variable {σ α : Type*} (source target : List α) {M J : ℕ} [NeZero M] + (N P F exponent H Q eM eF B E Scale : ℕ) (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) + (tau a eta kappa delta : BinaryFraction) + (copies pass copy T S t : ℕ) (ht : 0 < t) + (node : PhysicalNode M J) (hbelow : node.1.val < J) + (readGroup : GroupScalarKey M F Q → BitQuery σ BinaryFraction) + (readInteger : (ℕ × TargetInterval target.length) → ℕ → BitQuery σ BinaryFraction) + (q : TargetInterval target.length) + (oracle : Sum σ {child : PhysicalTableRequest M J target.length // child.combinedRank T S < + (PhysicalTableRequest.refinement pass copy node T t q).combinedRank T S} → BinaryFraction) + +theorem queryPhysicalRandomDataRequest_width + (hn : PreparedKernelNumericBounds (nx := source.length) (ny := target.length) (M := M) + N P F exponent H Q eM eF B E Scale (t - 1) tau a eta kappa delta (fun _ _ => 0)) + (htime : Nat.size t ≤ B) + (hv : ∀ key, (oracle (Sum.inr key)).width ≤ B) + (hnonneg : ∀ key, 0 ≤ (oracle (Sum.inr key)).value) : + ((queryPhysicalRandomDataRequest source target N P F exponent H Q eM eF hP hM hF + tau a eta kappa delta copies pass copy T S t ht node hbelow readGroup readInteger q).value oracle).width ≤ + preparedKernelWordBudget M B := by + unfold queryPhysicalRandomDataRequest + apply queryLocalProgram_width source target (physicalSourceInterval source.length node) + N P F exponent H Q eM eF hP hM hF tau a eta kappa delta t _ _ _ _ _ q _ _ oracle B + hn.largeBits hn.inputSize (by have := hn.sourceSize; omega) hn.targetSize + (by have := hn.aritySize; omega) (by have := hn.precisionSize; omega) hn.factorSize htime hn.factorWidth hn.decrementSize + · intro r + rw [BitQuery.mapKeysWithWork_value] + exact hv _ + · intro r + rw [BitQuery.mapKeysWithWork_value] + exact hnonneg _ + · intro key + rw [BitQuery.mapKeysWithWork_value] + exact queryPhysicalEarlierRead_width copies pass copy T S t node hbelow q + (fun key => oracle (Sum.inr key)) B (by have := hn.largeBits; omega) hv key + · intro key + rw [BitQuery.mapKeysWithWork_value] + exact hv _ + +end Physical + +section Family +variable {α : Type*} {M J R : ℕ} [NeZero M] (source target : List α) + (N P F exponent H Q eM eF B E Scale : ℕ) (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) + (tau a eta kappa delta : BinaryFraction) (passes copies pass copy T S t : ℕ) (ht : 0 < t) + (node : PhysicalNode M J) (hbelow : node.1.val < J) (time : Fin R) (q : TargetInterval target.length) + (oracle : Sum (PhysicalFamilyScalarKey (M := M) (J := J) (R := R) + target N P F exponent H Q passes copies) + {child : PhysicalTableRequest M J target.length // child.combinedRank T S < + (PhysicalTableRequest.refinement pass copy node T t q).combinedRank T S} → BinaryFraction) + +theorem queryFamilyRefinement_width + (hn : PreparedKernelNumericBounds (nx := source.length) (ny := target.length) (M := M) + N P F exponent H Q eM eF B E Scale (t - 1) tau a eta kappa delta (fun _ _ => 0)) + (htime : Nat.size t ≤ B) + (hv : ∀ key, (oracle (Sum.inr key)).width ≤ B) + (hnonneg : ∀ key, 0 ≤ (oracle (Sum.inr key)).value) : + ((queryFamilyRefinement source target N P F exponent H Q eM eF hP hM hF tau a eta kappa delta + passes copies pass copy T S t ht node hbelow time q).value oracle).width ≤ + preparedKernelWordBudget M B := by + unfold queryFamilyRefinement + exact queryPhysicalRandomDataRequest_width source target N P F exponent H Q eM eF B E Scale + hP hM hF tau a eta kappa delta copies pass copy T S t ht node hbelow _ _ q oracle hn htime hv hnonneg + +end Family +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryPhysicalReaderBounds.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryPhysicalReaderBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..9746abcf7f4d7a1bde11d2f6676a07f653aaf9cc --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryPhysicalReaderBounds.lean @@ -0,0 +1,120 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryPhysicalReaders + +namespace OAI + +namespace EditApproximation + +private theorem reader_cost_sum {κ : Type*} (keys : List κ) (cost : κ → ℕ) (C : ℕ) + (h : ∀ key ∈ keys, cost key ≤ C) : (keys.map cost).sum ≤ keys.length * C := by + induction keys with + | nil => simp + | cons key keys ih => + have hh := h key List.mem_cons_self + have ht := ih (fun k hk => h k (List.mem_cons_of_mem key hk)) + simp only [List.map_cons, List.sum_cons, List.length_cons, Nat.add_mul, Nat.one_mul] + omega + +theorem queryMeanRead_bounds {ι : Type*} (count B C : ℕ) + (reader : Fin count → BitQuery ι BinaryFraction) + (oracle : ι → BinaryFraction) (readWork : ι → ℕ) + (hw : ∀ i, ((reader i).value oracle).width ≤ B) + (hc : ∀ i, (reader i).work oracle readWork ≤ C) : + ((queryMeanRead count reader).value oracle).width ≤ BinaryFraction.warmupAverageWordBudget count B ∧ + (queryMeanRead count reader).work oracle readWork ≤ + count + 1 + count * (C + 3) + BinaryFraction.warmupAverageBitBudget count B := by + let inputs := List.ofFn fun i : Fin count => i + let words := inputs.map fun i => (reader i).value oracle + have hlen : words.length = count := by simp only [words, inputs, List.length_map, List.length_ofFn] + have havg := BinaryFraction.warmupAverageWithWork_bounds words B (by + intro w hw' + obtain ⟨i, _, rfl⟩ := List.mem_map.mp hw' + exact hw i) + rw [← BinaryFraction.queryMeanWithWork_eq_average count words hlen] at havg + rw [hlen] at havg + have hs := reader_cost_sum inputs (fun i => (reader i).work oracle readWork + 3) (C + 3) + (fun i _ => Nat.add_le_add_right (hc i) 3) + simp only [inputs, List.length_ofFn] at hs + change (inputs.map fun i => (reader i).work oracle readWork + 3).sum ≤ count * (C + 3) at hs + constructor + · simpa only [queryMeanRead, BitQuery.value, BitQuery.value_collect, BitQuery.compute, words, inputs] using havg.1 + · rw [queryMeanRead_work] + change count + 1 + (inputs.map fun i => (reader i).work oracle readWork + 3).sum + + (BinaryFraction.queryMeanWithWork count words).2 ≤ _ + omega + +section Physical +variable {M J n : ℕ} (copies pass copy T S t : ℕ) (ht : 0 < t) + (node : PhysicalNode M J) (hbelow : node.1.val < J) (q : TargetInterval n) + (oracle : {child : PhysicalTableRequest M J n // child.combinedRank T S < + (PhysicalTableRequest.refinement pass copy node T t q).combinedRank T S} → BinaryFraction) + (readWork : {child : PhysicalTableRequest M J n // child.combinedRank T S < + (PhysicalTableRequest.refinement pass copy node T t q).combinedRank T S} → ℕ) + +theorem queryPhysicalWarmupRead_work_bound (W : ℕ) (hW : ∀ key, key.val.pass = pass → key.val.copy = copy → readWork key ≤ W) + (other : PhysicalNode M J) (hnode : node.1.val ≤ other.1.val) (j : ℕ) (hj : j ≤ T) + (r : TargetInterval n) : + (queryPhysicalWarmupRead copies pass copy T S t ht node q other hnode j hj r).work oracle readWork ≤ + 7 * J + 30 + W := by + exact (queryPhysicalTableRead_work copies T S _ _ oracle readWork).trans + (Nat.add_le_add_left (hW _ rfl rfl) _) + +theorem queryPhysicalCurrentRead_work_bound (W : ℕ) (hW : ∀ key, key.val.pass = pass → key.val.copy = copy → readWork key ≤ W) + (input : Fin M × TargetInterval n) : + (queryPhysicalCurrentRead copies pass copy T S t node hbelow q input).work oracle readWork ≤ + 7 * J + 30 + W := by + exact (queryPhysicalTableRead_work copies T S _ _ oracle readWork).trans + (Nat.add_le_add_left (hW _ rfl rfl) _) + +theorem queryPhysicalEarlierRead_work_bound (B W : ℕ) (hW : ∀ key, key.val.pass = pass → key.val.copy = copy → readWork key ≤ W) + (htime : Nat.size t ≤ B) (input : Fin M × ℕ × TargetInterval n) (hi : Nat.size input.2.1 ≤ B) : + (queryPhysicalEarlierRead copies pass copy T S t node hbelow q input).work oracle readWork ≤ + 8 * B + 7 * J + 32 + W := by + have hcmp := binaryNaturalCompareWithWork_cost input.2.1 t + have hr (child : {r : PhysicalTableRequest M J n // r.combinedRank T S < + (PhysicalTableRequest.refinement pass copy node T t q).combinedRank T S}) + (hp : child.val.pass = pass) (hc : child.val.copy = copy) : + (queryPhysicalTableRead copies T S _ child).work oracle readWork ≤ 7 * J + 30 + W := + (queryPhysicalTableRead_work copies T S _ child oracle readWork).trans + (Nat.add_le_add_left (hW child hp hc) _) + unfold queryPhysicalEarlierRead + simp only [BitQuery.work] + split + · apply (Nat.add_le_add_left (hr _ rfl rfl) _).trans + omega + · simp only [BitQuery.work] + omega + +theorem queryPhysicalMassRead_bounds (B W : ℕ) (hW : ∀ key, key.val.pass = pass → key.val.copy = copy → readWork key ≤ W) + (hw : ∀ key, (oracle key).width ≤ B) (input : Fin M × TargetInterval n) : + ((queryPhysicalMassRead copies pass copy T S t ht node hbelow q input).value oracle).width ≤ + BinaryFraction.warmupAverageWordBudget T B ∧ + (queryPhysicalMassRead copies pass copy T S t ht node hbelow q input).work oracle readWork ≤ + T + 1 + T * (7 * J + 30 + W + 3) + BinaryFraction.warmupAverageBitBudget T B := by + apply queryMeanRead_bounds T B (7 * J + 30 + W) + · intro j + exact hw _ + · intro j + exact queryPhysicalWarmupRead_work_bound copies pass copy T S t ht node q oracle readWork W hW _ _ _ _ _ + +theorem queryPhysicalEarlierRead_width (B : ℕ) (hB : 2 ≤ B) + (hw : ∀ key, (oracle key).width ≤ B) (input : Fin M × ℕ × TargetInterval n) : + ((queryPhysicalEarlierRead copies pass copy T S t node hbelow q input).value oracle).width ≤ B := by + unfold queryPhysicalEarlierRead + simp only [BitQuery.value] + split + · exact hw _ + · exact (BinaryFraction.nat_width_le 0).trans (by simpa only [Nat.size_zero, Nat.zero_add] using hB) + +theorem queryPhysicalEarlierRead_nonneg (hw : ∀ key, 0 ≤ (oracle key).value) + (input : Fin M × ℕ × TargetInterval n) : + 0 ≤ ((queryPhysicalEarlierRead copies pass copy T S t node hbelow q input).value oracle).value := by + unfold queryPhysicalEarlierRead + simp only [BitQuery.value] + split + · exact hw _ + · simp only [BitQuery.value, BinaryFraction.nat_value, Nat.cast_zero, le_refl] + +end Physical +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryPhysicalReaderSpace.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryPhysicalReaderSpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..b23f4cec736a6d92a8a94b294301f0e5ad3a5713 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryPhysicalReaderSpace.lean @@ -0,0 +1,91 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryLocalProgramSpace +import OAI.Combinatorics.EditApproximation.Binary.BitQueryKeysSpace +import OAI.Combinatorics.EditApproximation.Queries.QueryPhysicalProgram +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation + +/-- Scalar RAM cells created by the node-code recurrence, two powers and +entry/table arithmetic. The path and input request are borrowed. -/ + + +theorem physicalTableCodeAllocation_le_work {M J n : ℕ} (copies T S : ℕ) + (request : PhysicalTableRequest M J n) : + physicalTableCodeAllocation request ≤ (physicalTableCodeWithWork copies T S request).2 := by + have tableBound (d J : ℕ) : + 2 * d + 2 * J + 20 ≤ + 3 * d + 1 + (2 * J + 1) + 3 + 8 + (2 * J + 1) + 15 := by + omega + simp only [physicalTableCodeAllocation, physicalTableCodeWithWork, physicalEntryCodeWithWork, + physicalNodeCodeWithWork, treeLayerCodeWithWork_cost, parameterPowerWithWork_spec] + exact tableBound _ _ + +open BitQuery + +def queryPhysicalTableReadHeap {M J n : ℕ} (copies T S : ℕ) + (parent : PhysicalTableRequest M J n) + (child : {r : PhysicalTableRequest M J n // r.combinedRank T S < parent.combinedRank T S}) : + Heap (queryPhysicalTableRead copies T S parent child) := + Heap.chargeOf (physicalTableCodeAllocation child.val + 1) + (Nat.add_le_add_right (physicalTableCodeAllocation_le_work copies T S child.val) 1) + (.read child _ fun word => .done word) + +def queryMeanReadHeap {ι : Type*} (count : ℕ) (reader : Fin count → BitQuery ι BinaryFraction) + (hr : ∀ i, Heap (reader i)) : Heap (queryMeanRead count reader) := by + refine Heap.chargeOf count (by omega) (Heap.collect reader hr _ _ fun words => ?_) + refine Heap.computeOf (BinaryFraction.queryMeanWithWork count words) + (BinaryFraction.sumListAllocation words + BinaryFraction.divAllocation + (BinaryFraction.sumListWithWork words).1 (BinaryFraction.nat count) + Nat.size count) ?_ + have hs := BinaryFraction.sumListAllocation_le_work words + have hd := BinaryFraction.divAllocation_le_work (BinaryFraction.sumListWithWork words).1 (BinaryFraction.nat count) + unfold BinaryFraction.queryMeanWithWork + dsimp only + omega + +def queryPhysicalEarlierReadHeap {M J n : ℕ} (copies pass copy T S t : ℕ) + (node : PhysicalNode M J) (hbelow : node.1.val < J) (q : TargetInterval n) + (input : Fin M × ℕ × TargetInterval n) : + Heap (queryPhysicalEarlierRead copies pass copy T S t node hbelow q input) := by + refine Heap.chargeOf (input.2.1.bits.length + t.bits.length) ?_ ?_ + · exact (bitCompareWithWork_input_cells _ _).trans (Nat.le_succ _) + · split + · exact queryPhysicalTableReadHeap copies T S _ _ + · exact .done _ + +def queryPhysicalRandomDataRequestHeap {σ α : Type*} (source target : List α) {M J : ℕ} [NeZero M] + (N P F exponent H Q eM eF : ℕ) (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) + (tau a eta kappa delta : BinaryFraction) (copies pass copy T S t : ℕ) (ht : 0 < t) + (node : PhysicalNode M J) (hbelow : node.1.val < J) + (readGroup : GroupScalarKey M F Q → BitQuery σ BinaryFraction) + (readInteger : (ℕ × TargetInterval target.length) → ℕ → BitQuery σ BinaryFraction) + (q : TargetInterval target.length) + (hg : ∀ key, Heap (readGroup key)) (hz : ∀ key range, Heap (readInteger key range)) : + Heap (queryPhysicalRandomDataRequest source target N P F exponent H Q eM eF hP hM hF + tau a eta kappa delta copies pass copy T S t ht node hbelow readGroup readInteger q) := by + unfold queryPhysicalRandomDataRequest + apply queryLocalProgramHeap + · intro r + exact (queryPhysicalTableReadHeap copies T S _ _).mapKeysWithWork _ (fun _ => 1) (fun _ => le_rfl) + · intro input + apply Heap.mapKeysWithWork _ (fun _ => 1) (fun _ => le_rfl) + apply queryMeanReadHeap + intro j + exact queryPhysicalTableReadHeap copies T S _ _ + · intro input + exact (queryPhysicalTableReadHeap copies T S _ _).mapKeysWithWork _ (fun _ => 1) (fun _ => le_rfl) + · intro key + exact (hg key).mapKeysWithWork _ (fun _ => 1) (fun _ => le_rfl) + · intro key range + exact (hz key range).mapKeysWithWork _ (fun _ => 1) (fun _ => le_rfl) + · intro input + exact (queryPhysicalEarlierReadHeap copies pass copy T S t node hbelow q input).mapKeysWithWork _ + (fun _ => 1) (fun _ => le_rfl) + · intro input + exact (queryPhysicalTableReadHeap copies T S _ _).mapKeysWithWork _ (fun _ => 1) (fun _ => le_rfl) + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryPhysicalReaders.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryPhysicalReaders.lean new file mode 100644 index 0000000000000000000000000000000000000000..aae2a71bef2ebe2604766076511cc1857f81446b --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryPhysicalReaders.lean @@ -0,0 +1,87 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryMeanRead +import OAI.Combinatorics.EditApproximation.Binary.BitQueryKeys +import OAI.Combinatorics.EditApproximation.Geometry.MemoCodeWork +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalRandomDataRequest +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Actual ranked physical reads for the charged local program. Table +addresses are constructed before lookup, mass reads execute their mean, +and the total history reader executes its natural-word guard. -/ + +namespace EditApproximation + + + +theorem queryPhysicalTableRead_refines {M J n : ℕ} (copies T S : ℕ) + (parent : PhysicalTableRequest M J n) + (child : {r : PhysicalTableRequest M J n // r.combinedRank T S < parent.combinedRank T S}) : + BitQuery.Refines (fun word value => word.value = value) + (queryPhysicalTableRead copies T S parent child) (.read child .done) := + .charge _ (.read child _ _ (fun _ => .done rfl)) + +theorem queryPhysicalTableRead_work {M J n : ℕ} (copies T S : ℕ) + (parent : PhysicalTableRequest M J n) + (child : {r : PhysicalTableRequest M J n // r.combinedRank T S < parent.combinedRank T S}) + (oracle : {r : PhysicalTableRequest M J n // r.combinedRank T S < parent.combinedRank T S} → BinaryFraction) + (readWork : {r : PhysicalTableRequest M J n // r.combinedRank T S < parent.combinedRank T S} → ℕ) : + (queryPhysicalTableRead copies T S parent child).work oracle readWork ≤ + 7 * J + 30 + readWork child := by + have h := physicalTableCodeWithWork_cost copies T S child.val + change _ + 1 + (readWork child + 0) ≤ _ + omega + + + +theorem queryPhysicalWarmupRead_refines {M J n : ℕ} (copies pass copy T S t : ℕ) (ht : 0 < t) + (node : PhysicalNode M J) (q : TargetInterval n) + (otherNode : PhysicalNode M J) (hnode : node.1.val ≤ otherNode.1.val) + (j : ℕ) (hj : j ≤ T) (r : TargetInterval n) : + BitQuery.Refines (fun word value => word.value = value) + (queryPhysicalWarmupRead copies pass copy T S t ht node q otherNode hnode j hj r) + (physicalRefinementWarmupRead pass copy T S t ht node q otherNode hnode j hj r) := + queryPhysicalTableRead_refines copies T S _ _ + + + +theorem queryPhysicalMassRead_refines {M J n : ℕ} (copies pass copy T S t : ℕ) (ht : 0 < t) + (node : PhysicalNode M J) (hbelow : node.1.val < J) (q : TargetInterval n) + (input : Fin M × TargetInterval n) : + BitQuery.Refines (fun word value => word.value = value) + (queryPhysicalMassRead copies pass copy T S t ht node hbelow q input) + (physicalRefinementMassQuery pass copy T S t ht node hbelow q input) := + queryMeanRead_refines T _ _ (fun _ => queryPhysicalWarmupRead_refines copies pass copy T S t ht + node q _ _ _ _ _) + + + +theorem queryPhysicalCurrentRead_refines {M J n : ℕ} (copies pass copy T S t : ℕ) + (node : PhysicalNode M J) (hbelow : node.1.val < J) (q : TargetInterval n) + (input : Fin M × TargetInterval n) : + BitQuery.Refines (fun word value => word.value = value) + (queryPhysicalCurrentRead copies pass copy T S t node hbelow q input) + (physicalRefinementCurrentQuery pass copy T S t node hbelow q input) := + queryPhysicalTableRead_refines copies T S _ _ + + + +theorem queryPhysicalEarlierRead_refines {M J n : ℕ} (copies pass copy T S t : ℕ) + (node : PhysicalNode M J) (hbelow : node.1.val < J) (q : TargetInterval n) + (input : Fin M × ℕ × TargetInterval n) : + BitQuery.Refines (fun word value => word.value = value) + (queryPhysicalEarlierRead copies pass copy T S t node hbelow q input) + (physicalRefinementEarlierQuery pass copy T S t node hbelow q input) := by + unfold queryPhysicalEarlierRead + apply BitQuery.Refines.charge + unfold physicalRefinementEarlierQuery + by_cases hs : input.2.1 < t + · rw [dite_eq_left hs, dite_eq_left ((binaryNaturalCompareWithWork_lt _ _).mpr hs)] + exact queryPhysicalTableRead_refines copies T S _ _ + · rw [dite_eq_right hs, dite_eq_right (fun h => hs ((binaryNaturalCompareWithWork_lt _ _).mp h))] + exact .done (by simp only [BinaryFraction.nat_value, Nat.cast_zero]) + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryPhysicalScalarCosts.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryPhysicalScalarCosts.lean new file mode 100644 index 0000000000000000000000000000000000000000..4f7cb950c9540de303b77c14b5732825399e5a92 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryPhysicalScalarCosts.lean @@ -0,0 +1,68 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryPhysicalScalarReads + +namespace OAI + +/-! Polynomial bit costs for the three physical source guards. Bounds +use only the words in the request, not the size of the ambient source set. -/ + +namespace EditApproximation + +theorem queryScalePresentWithWork_cost (N b B : ℕ) + (hN : Nat.size N ≤ B) (hb : Nat.size b ≤ B) : + (queryScalePresentWithWork N b).2 ≤ 40 * (B + 2) ^ 2 := by + have hs := queryScaleDispatchWithWork_cost N b B hN hb + have hl : (dyadicScales N).length ≤ B + 1 := by + rw [← dyadicScalesWithWork_value N] + simp only [dyadicScalesWithWork, arithmeticMapWithWork_value, List.length_map, List.length_range] + rw [Nat.size_eq_bits_len] + omega + have hi : (queryScaleDispatchWithWork N b).1 ≤ B + 1 := by + rw [queryScaleDispatchWithWork_value] + exact (List.idxOf_le_length (a := b) (l := dyadicScales N)).trans hl + have hidx : Nat.size (queryScaleDispatchWithWork N b).1 ≤ B + 1 := + Nat.size_le.mpr (hi.trans_lt Nat.lt_two_pow_self) + have hc : max 1 N.bits.length ≤ B + 1 := by + rw [Nat.size_eq_bits_len] + omega + have hlen : Nat.size (max 1 N.bits.length) ≤ B + 1 := + Nat.size_le.mpr (hc.trans_lt Nat.lt_two_pow_self) + have ht := binaryNaturalCompareWithWork_cost (queryScaleDispatchWithWork N b).1 (max 1 N.bits.length) + change (queryScaleDispatchWithWork N b).2 + + (binaryNaturalCompareWithWork (queryScaleDispatchWithWork N b).1 (max 1 N.bits.length)).2 + 2 ≤ _ + nlinarith only [hs, ht, hidx, hlen, Nat.zero_le B] + +theorem queryRangeValidWithWork_cost (bound range B : ℕ) + (hb : Nat.size bound ≤ B) (hr : Nat.size range ≤ B) : + (queryRangeValidWithWork bound range).2 ≤ 12 * B + 5 := by + have hp := binaryNaturalCompareWithWork_cost 0 range + have hu := wordLEWithWork_cost range.bits bound.bits + simp only [Nat.size_zero] at hp + simp only [Nat.size_eq_bits_len] at hu + change _ + _ + 2 ≤ _ + omega + +theorem queryCellValidWithWork_cost (n exponent B : ℕ) (cell : ℕ × ℕ) + (hn : Nat.size n ≤ B) (he : exponent + 1 ≤ B) + (hl : Nat.size cell.1 ≤ B) (hr : Nat.size cell.2 ≤ B) : + (queryCellValidWithWork n exponent cell).2 ≤ 100 * (B + 1) ^ 2 := by + have hp : Nat.size (bitWordValue (powerTwoWord exponent)) ≤ B := by + rw [powerTwoWord_value, Nat.size_pow] + exact he + have hm := queryNaturalMul_cost n (bitWordValue (powerTwoWord exponent)) B hn hp + have hlength := bitMulWithWork_length n.bits (bitWordValue (powerTwoWord exponent)).bits + change (binaryNaturalMulWithWork n (bitWordValue (powerTwoWord exponent))).1.length ≤ _ at hlength + simp only [Nat.size_eq_bits_len] at hlength + have hleft := wordLEWithWork_cost cell.1.bits + (binaryNaturalMulWithWork n (bitWordValue (powerTwoWord exponent))).1 + have hright := wordLEWithWork_cost cell.2.bits + (binaryNaturalMulWithWork n (bitWordValue (powerTwoWord exponent))).1 + simp only [Nat.size_eq_bits_len] at hleft hright + change (binaryNaturalMulWithWork n (bitWordValue (powerTwoWord exponent))).2 + + (wordLEWithWork cell.1.bits (binaryNaturalMulWithWork n (bitWordValue (powerTwoWord exponent))).1).2 + + (wordLEWithWork cell.2.bits (binaryNaturalMulWithWork n (bitWordValue (powerTwoWord exponent))).1).2 + + exponent + 4 ≤ _ + nlinarith only [hm, hlength, hleft, hright, hn, hp, hl, hr, he, Nat.zero_le B] + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryPhysicalScalarGuards.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryPhysicalScalarGuards.lean new file mode 100644 index 0000000000000000000000000000000000000000..555347481bbbdd6feda3aa73d6f0a55a87abd86b --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryPhysicalScalarGuards.lean @@ -0,0 +1,40 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryScalarDispatch +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Executed natural-word guards for finite physical source requests. -/ + +namespace EditApproximation + + + +@[simp] theorem queryScalePresentWithWork_value (N b : ℕ) : + (queryScalePresentWithWork N b).1 = true ↔ b ∈ dyadicScales N := by + simp only [queryScalePresentWithWork, decide_eq_true_eq, binaryNaturalCompareWithWork_lt, + queryScaleDispatchWithWork_value] + have hl : (dyadicScales N).length = max 1 N.bits.length := by + rw [← dyadicScalesWithWork_value N] + simp only [dyadicScalesWithWork, arithmeticMapWithWork_value, List.length_map, List.length_range] + rw [← hl] + exact List.idxOf_lt_length_iff + + + +@[simp] theorem queryCellValidWithWork_value (n exponent : ℕ) (cell : ℕ × ℕ) : + (queryCellValidWithWork n exponent cell).1 = true ↔ + cell.1 ≤ n * 2 ^ exponent ∧ cell.2 ≤ n * 2 ^ exponent := by + simp only [queryCellValidWithWork, Bool.and_eq_true, wordLEWithWork_value, bitWordValue_bits, + binaryNaturalMulWithWork_value, powerTwoWord_value] + + + +@[simp] theorem queryRangeValidWithWork_value (B range : ℕ) : + (queryRangeValidWithWork B range).1 = true ↔ 0 < range ∧ range ≤ B := by + simp only [queryRangeValidWithWork, Bool.and_eq_true, decide_eq_true_eq, + binaryNaturalCompareWithWork_lt, wordLEWithWork_value, bitWordValue_bits] + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryPhysicalScalarReads.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryPhysicalScalarReads.lean new file mode 100644 index 0000000000000000000000000000000000000000..9784bc410ef23f70c4a60d09b4b0f38a65018351 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryPhysicalScalarReads.lean @@ -0,0 +1,88 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryPhysicalScalarGuards +import OAI.Combinatorics.EditApproximation.Binary.BitQueryKeys +import OAI.Combinatorics.EditApproximation.Geometry.MemoCodeWork +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Concrete scalar-source adapters. Guards, finite source addresses and +tag construction are executed before each read; rejected requests return +the original zero value without exposing a random coordinate. -/ + +namespace EditApproximation + +section Scalar +variable (M J N n exponent F Q R B : ℕ) + + + + + +theorem queryPhysicalScalarRead_refines (key : PhysicalScalarKey M J N n exponent F Q R B) : + BitQuery.Refines (fun word value => word.value = value) + (queryPhysicalScalarRead M J N n exponent F Q R B key) (.read key .done) := + .charge _ (.read key _ _ (fun _ => .done rfl)) + + + + + + + +private theorem queryGroup_transport (b c : ℕ) (h : b = c) + (actual : BitPhysicalGroupQueries M J N n exponent F Q R B b) + (expected : PhysicalGroupQueries M J N n exponent F Q R B b) + (he : ∀ scale sample, BitQuery.Refines (fun word value => word.value = value) + (actual scale sample) (expected scale sample)) : + ∀ scale sample, BitQuery.Refines (fun word value => word.value = value) + ((Eq.mp (congrArg (BitPhysicalGroupQueries M J N n exponent F Q R B) h) actual) scale sample) + ((Eq.mp (congrArg (PhysicalGroupQueries M J N n exponent F Q R B) h) expected) scale sample) := by + subst c + exact he + +theorem queryPhysicalScalarGroupRead_refines (node : PhysicalInternalNode M J) (time : Fin R) + (key : GroupScalarKey M F Q) : + BitQuery.Refines (fun word value => word.value = value) + (queryPhysicalScalarGroupRead M J N n exponent F Q R B node time key) + (physicalScalarGroupRead M J N n exponent F Q R B node time key) := by + apply BitQuery.Refines.charge + rcases key with ⟨⟨b, cell⟩, scale, sample⟩ + unfold queryPhysicalScalarGroupQueries physicalScalarGroupRead physicalScalarGroupQueries + dsimp only + by_cases hb : b ∈ dyadicScales N + · rw [dite_eq_left hb, dite_eq_left ((queryScalePresentWithWork_value N b).mpr hb)] + by_cases hc : cell.1 ≤ n * 2 ^ exponent ∧ cell.2 ≤ n * 2 ^ exponent + · rw [dite_eq_left hc, dite_eq_left ((queryCellValidWithWork_value n exponent cell).mpr hc)] + exact queryGroup_transport M J N n exponent F Q R B _ b (physicalScaleIndex_get N b hb) + _ _ (fun _ _ => queryPhysicalScalarRead_refines M J N n exponent F Q R B _) scale sample + · rw [dite_eq_right hc, dite_eq_right + (fun h => hc ((queryCellValidWithWork_value n exponent cell).mp h))] + exact .done (by simp only [BinaryFraction.nat_value, Nat.cast_zero]) + · rw [dite_eq_right hb, dite_eq_right + (fun h => hb ((queryScalePresentWithWork_value N b).mp h))] + exact .done (by simp only [BinaryFraction.nat_value, Nat.cast_zero]) + + + +theorem queryPhysicalScalarOnlineRead_refines (node : PhysicalInternalNode M J) (time : Fin R) + (key : ℕ × TargetInterval n) (range : ℕ) : + BitQuery.Refines (fun word value => word.value = value) + (queryPhysicalScalarOnlineRead M J N n exponent F Q R B node time key range) + (physicalScalarOnlineRead M J N n exponent F Q R B node time key range) := by + apply BitQuery.Refines.charge + unfold physicalScalarOnlineRead + by_cases hb : key.1 ∈ dyadicScales N + · rw [dite_eq_left hb, dite_eq_left ((queryScalePresentWithWork_value N key.1).mpr hb)] + by_cases hr : 0 < range ∧ range ≤ B + · rw [dite_eq_left hr, dite_eq_left ((queryRangeValidWithWork_value B range).mpr hr)] + exact queryPhysicalScalarRead_refines M J N n exponent F Q R B _ + · rw [dite_eq_right hr, dite_eq_right (fun h => hr ((queryRangeValidWithWork_value B range).mp h))] + exact .done (by simp only [BinaryFraction.nat_value, Nat.cast_zero]) + · rw [dite_eq_right hb, dite_eq_right (fun h => hb ((queryScalePresentWithWork_value N key.1).mp h))] + exact .done (by simp only [BinaryFraction.nat_value, Nat.cast_zero]) + +end Scalar +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryPhysicalSourceCosts.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryPhysicalSourceCosts.lean new file mode 100644 index 0000000000000000000000000000000000000000..7c424893fde6dea5b7cbfff369f24d410a22bd56 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryPhysicalSourceCosts.lean @@ -0,0 +1,70 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryPhysicalScalarCosts + +namespace OAI + +/-! Complete execution costs of guarded scalar source queries, including +the actual finite address construction and the source lookup. -/ + +namespace EditApproximation + +section Scalar +variable (M J N n exponent F Q R B : ℕ) + (oracle : PhysicalScalarKey M J N n exponent F Q R B → BinaryFraction) + (readWork : PhysicalScalarKey M J N n exponent F Q R B → ℕ) + (W : ℕ) (hW : ∀ key, readWork key ≤ W) + +include hW in +theorem queryPhysicalScalarRead_work (key : PhysicalScalarKey M J N n exponent F Q R B) : + (queryPhysicalScalarRead M J N n exponent F Q R B key).work oracle readWork ≤ 5 * J + 41 + W := by + have hc := physicalScalarCodeWithWork_cost key + have hw := hW key + change _ + 1 + (readWork key + 0) ≤ _ + omega + +private theorem queryGroup_cost_transport (b c : ℕ) (h : b = c) + (actual : BitPhysicalGroupQueries M J N n exponent F Q R B b) + (K : ℕ) (he : ∀ scale sample, (actual scale sample).work oracle readWork ≤ K) : + ∀ scale sample, + ((Eq.mp (congrArg (BitPhysicalGroupQueries M J N n exponent F Q R B) h) actual) + scale sample).work oracle readWork ≤ K := by + subst c + exact he + +include hW in +theorem queryPhysicalScalarGroupRead_work (node : PhysicalInternalNode M J) (time : Fin R) + (key : GroupScalarKey M F Q) : + (queryPhysicalScalarGroupRead M J N n exponent F Q R B node time key).work oracle readWork ≤ + (queryScalePresentWithWork N key.1.1).2 + (queryCellValidWithWork n exponent key.1.2).2 + + 5 * J + 43 + W := by + have hc : (queryPhysicalScalarGroupQueries M J N n exponent F Q R B node time + key.1.1 key.1.2 key.2.1 key.2.2).work oracle readWork ≤ 5 * J + 41 + W := by + unfold queryPhysicalScalarGroupQueries + split_ifs with hb hcell + · exact queryGroup_cost_transport M J N n exponent F Q R B oracle readWork _ _ + (physicalScaleIndex_get N key.1.1 ((queryScalePresentWithWork_value N key.1.1).mp hb)) + _ (5 * J + 41 + W) + (fun _ _ => queryPhysicalScalarRead_work M J N n exponent F Q R B oracle readWork W hW _) + key.2.1 key.2.2 + · exact Nat.zero_le _ + · exact Nat.zero_le _ + change _ + _ ≤ _ + omega + +include hW in +theorem queryPhysicalScalarOnlineRead_work (node : PhysicalInternalNode M J) (time : Fin R) + (key : ℕ × TargetInterval n) (range : ℕ) : + (queryPhysicalScalarOnlineRead M J N n exponent F Q R B node time key range).work oracle readWork ≤ + (queryScalePresentWithWork N key.1).2 + (queryRangeValidWithWork B range).2 + 5 * J + 43 + W := by + unfold queryPhysicalScalarOnlineRead + simp only [BitQuery.work] + split_ifs + · apply (Nat.add_le_add_left + (queryPhysicalScalarRead_work M J N n exponent F Q R B oracle readWork W hW _) _).trans + omega + · simp only [BitQuery.work]; omega + · simp only [BitQuery.work]; omega + +end Scalar +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryProgramPolynomial.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryProgramPolynomial.lean new file mode 100644 index 0000000000000000000000000000000000000000..2305c5b6450e35236e5ce03c92df83f43b22ffc2 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryProgramPolynomial.lean @@ -0,0 +1,112 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryGatherPolynomial + +namespace OAI + +namespace EditApproximation + +attribute [local irreducible] preparedLocalGroupBitDegree onlineShellDegree physicalShellDegree + representativeCompleteBitDegree queryGatherBitDegree + +def queryPrimitiveBitDegree : ℕ := + max 1 (max preparedLocalGroupBitDegree + (max onlineShellDegree (max physicalShellDegree representativeCompleteBitDegree))) + +def queryLocalProgramBitDegree : ℕ := queryPrimitiveBitDegree * queryGatherBitDegree + +theorem queryLocalProgramBitBudget_shell_cap (M N P F exponent eM eF B S t W X : ℕ) + (hX : 2 ≤ X) (hN : Nat.size N ≤ B) (hM : M ≤ X) (hP : P ≤ X) (hF : F ≤ X) + (he : exponent ≤ X) (hTheta : 2 ^ exponent ≤ X) (hword : 16 * B + 200 ≤ X) + (hscales : 7 + eM + eF ≤ X) (hS : S ≤ X) (ht : t ≤ X) (hW : W ≤ X) + (hV : (40 * P + 2) ^ (2 * M) ≤ X) + (hCart : ((40 * P + 2) ^ 2 + 1) ^ (M + 1) ≤ X) + (hrep : (B + 1) * (64 * F * P + 2) ^ 2 ≤ X) + (hgroup : (B + 1) * ((32 * F + 2) * 2 ^ exponent + 2) ^ 2 ≤ X) : + BinaryFraction.queryLocalProgramBitBudget M N P F exponent eM eF B S t W ≤ + X ^ queryLocalProgramBitDegree := by + have hp : 0 < X := by omega + have hD : 1 ≤ queryPrimitiveBitDegree := Nat.le_max_left _ _ + have hbase : X ≤ X ^ queryPrimitiveBitDegree := Nat.le_pow hD + have hY : 2 ≤ X ^ queryPrimitiveBitDegree := hX.trans hbase + have hB : B ≤ X := by omega + have hg := preparedLocalGroupsBitBudget_fixedPower N M P F exponent eM eF B X + hX hN hM hP hF he hTheta hword hscales hV hCart + have ho := preparedLocalOnlineBitBudget_fixedPower M P B X hX hM hB hV + have hos : BinaryFraction.preparedLocalOnlineBitBudget M P B S ≤ + BinaryFraction.preparedLocalOnlineBitBudget M P B X := by + unfold BinaryFraction.preparedLocalOnlineBitBudget BinaryFraction.preparedLocalOnlineScaleBitBudget + BinaryFraction.preparedOnlineBitBudget + dsimp only + gcongr + have hf := physicalContinuationBitBudget_fixedPower M P _ _ (B + 1) (B + 4) X + hX hM hP hrep hgroup (by omega) (by omega) hV hCart + have hr := representativeCompleteBitBudget_fixedPower M ((40 * P + 2) ^ (2 * M)) + (4 * (B + 1) + 20) X hX hM hV (by omega) + have hgd : preparedLocalGroupBitDegree ≤ queryPrimitiveBitDegree := by + unfold queryPrimitiveBitDegree; omega + have hod : onlineShellDegree ≤ queryPrimitiveBitDegree := by + unfold queryPrimitiveBitDegree; omega + have hfd : physicalShellDegree ≤ queryPrimitiveBitDegree := by + unfold queryPrimitiveBitDegree; omega + have hrd : representativeCompleteBitDegree ≤ queryPrimitiveBitDegree := by + unfold queryPrimitiveBitDegree; omega + have h := queryLocalProgramBitBudget_fixedPower M N P F exponent eM eF B S t W + (X ^ queryPrimitiveBitDegree) hY (hM.trans hbase) (hP.trans hbase) (hF.trans hbase) + (he.trans hbase) ((by omega : eM ≤ X).trans hbase) ((by omega : eF ≤ X).trans hbase) + (hB.trans hbase) (ht.trans hbase) (hW.trans hbase) (hTheta.trans hbase) + (hV.trans hbase) (hCart.trans hbase) + (hg.trans (Nat.pow_le_pow_right hp hgd)) + (hos.trans (ho.trans (Nat.pow_le_pow_right hp hod))) + (hf.trans (Nat.pow_le_pow_right hp hfd)) + (hr.trans (Nat.pow_le_pow_right hp hrd)) + simpa only [← pow_mul, queryLocalProgramBitDegree] using h + +/-- A uniform cap absorbs the finite counts before applying the cost polynomial. -/ +theorem queryLocalProgramBitBudget_uniform_cap (M N P F exponent eM eF B S t W X : ℕ) + (hX : 64 ≤ X) (hN : Nat.size N ≤ B) + (hM : M ≤ X) (hP : P ≤ X) (hF : F ≤ X) (he : exponent ≤ X) + (heM : eM ≤ X) (heF : eF ≤ X) (hB : B ≤ X) (hS : S ≤ X) (ht : t ≤ X) (hW : W ≤ X) + (hTheta : 2 ^ exponent ≤ X) (hV : (40 * P + 2) ^ (2 * M) ≤ X) + (hCart : ((40 * P + 2) ^ 2 + 1) ^ (M + 1) ≤ X) : + BinaryFraction.queryLocalProgramBitBudget M N P F exponent eM eF B S t W ≤ + X ^ (16 * queryLocalProgramBitDegree) := by + have hp : 0 < X := by omega + have hunit : 1 ≤ X := by omega + have hXX : X ≤ X ^ 16 := Nat.le_pow (by decide) + have hx2 : X + 1 ≤ X ^ 2 := by nlinarith only [hX] + have hword : 16 * B + 200 ≤ X ^ 16 := by + calc + _ ≤ 216 * X := by omega + _ ≤ X ^ 2 * X := Nat.mul_le_mul_right _ (by nlinarith only [hX]) + _ = X ^ 3 := by ring + _ ≤ _ := Nat.pow_le_pow_right hp (by decide) + have hscales : 7 + eM + eF ≤ X ^ 16 := by + calc + _ ≤ 9 * X := by omega + _ ≤ X ^ 2 := by nlinarith only [hX] + _ ≤ _ := Nat.pow_le_pow_right hp (by decide) + have hrepSide : 64 * F * P + 2 ≤ X ^ 4 := by + have hfp := Nat.mul_le_mul hF hP + calc + _ ≤ 66 * X ^ 2 := by nlinarith only [hfp, hX] + _ ≤ X ^ 2 * X ^ 2 := Nat.mul_le_mul_right _ (by nlinarith only [hX]) + _ = _ := by ring + have hgroupSide : (32 * F + 2) * 2 ^ exponent + 2 ≤ X ^ 4 := by + have hft := Nat.mul_le_mul (show 32 * F + 2 ≤ 34 * X by omega) hTheta + calc + _ ≤ 36 * X ^ 2 := by nlinarith only [hft, hX] + _ ≤ X ^ 2 * X ^ 2 := Nat.mul_le_mul_right _ (by nlinarith only [hX]) + _ = _ := by ring + have hcounts (side : ℕ) (hs : side ≤ X ^ 4) : (B + 1) * side ^ 2 ≤ X ^ 16 := by + calc + _ ≤ X ^ 2 * (X ^ 4) ^ 2 := Nat.mul_le_mul (by omega) (Nat.pow_le_pow_left hs 2) + _ = X ^ 10 := by ring + _ ≤ _ := Nat.pow_le_pow_right hp (by decide) + have h := queryLocalProgramBitBudget_shell_cap M N P F exponent eM eF B S t W (X ^ 16) + ((by omega : 2 ≤ X).trans hXX) hN (hM.trans hXX) (hP.trans hXX) (hF.trans hXX) + (he.trans hXX) (hTheta.trans hXX) hword hscales (hS.trans hXX) (ht.trans hXX) (hW.trans hXX) + (hV.trans hXX) (hCart.trans hXX) (hcounts _ hrepSide) (hcounts _ hgroupSide) + simpa only [← pow_mul] using h + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryProgramWidth.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryProgramWidth.lean new file mode 100644 index 0000000000000000000000000000000000000000..a8ef8434213a769435cc139590402c0f26681c2c --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryProgramWidth.lean @@ -0,0 +1,202 @@ +import OAI.Combinatorics.EditApproximation.Probability.FiniteBufferRanges +import OAI.Combinatorics.EditApproximation.Queries.QueryHistoryBufferCost +import OAI.Combinatorics.EditApproximation.Queries.QueryLocalProgram +import OAI.Combinatorics.EditApproximation.Queries.QueryLocalFinishCost + +namespace OAI + +/-! Intermediate output widths for the executed adaptive refinement. These +bounds concern the words produced before memo-table normalization. -/ + +namespace EditApproximation +open BinaryFraction + +section Refinement +variable {ι α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (N P F exponent H Q eM eF : ℕ) + (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) + (tau a eta kappa delta : BinaryFraction) (t : ℕ) + (parentInitial : TargetInterval target.length → BinaryFraction × ℕ) + (child initial : Fin M → TargetInterval target.length → BinaryFraction × ℕ) + (R : ℕ) (hc : ∀ i r, (child i r).2 ≤ R) (hi : ∀ i r, (initial i r).2 ≤ R) + (draw : CountedCellGroupDraws M F Q) + (integer : ℕ → TargetInterval target.length → ℕ × ℕ) + (q : TargetInterval target.length) + (readEarlier : (Fin M × ℕ × TargetInterval target.length) → BitQuery ι BinaryFraction) + (readCurrent : (Fin M × TargetInterval target.length) → BitQuery ι BinaryFraction) + (oracle : ι → BinaryFraction) + +theorem queryLocalRefinement_width (B Rp : ℕ) + (hB : 10 ≤ B) (hN : Nat.size N ≤ B) (hnx : Nat.size source.length ≤ B) + (hny : Nat.size target.length + 2 ≤ B) (hMb : Nat.size M ≤ B) (hPb : Nat.size P ≤ B) + (hFb : Nat.size F + 2 ≤ B) (ht : Nat.size t ≤ B) (ha : a.width ≤ B) (hd : delta.width ≤ B) + (hpw : ∀ r, (parentInitial r).1.width ≤ B) (hpr : ∀ r, (parentInitial r).2 ≤ Rp) + (hpn : 0 ≤ (parentInitial q).1.value) + (hew : ∀ key, ((readEarlier key).value oracle).width ≤ B) + (hcw : ∀ key, ((readCurrent key).value oracle).width ≤ B) : + ((queryLocalRefinement source target parent N P F exponent H Q eM eF hP hM hF + tau a eta kappa delta t parentInitial child initial R hc hi draw integer q + readEarlier readCurrent).value oracle).width ≤ preparedKernelWordBudget M B := by + let earlier := (queryEarlierInputsWithWork M parent N P F exponent t hP a parentInitial q).1 + let ew := earlier.map fun key => (readEarlier key).value oracle + let shared := (querySharedInputsWithWork M N F Q exponent eM eF hM hF parent a + (parentInitial q).1 q draw).1 + let sw := shared.map fun key => (readCurrent key).value oracle + let groups := (queryGroupSelectWithWork source target parent N P F exponent Q eM eF hP hM hF + tau a parentInitial child initial R hc hi draw shared sw q).1 + let online := (queryOnlineSelectWithWork source target parent N P F exponent H hP tau a eta kappa + parentInitial child initial R hc hi t integer earlier ew q).1 + let keys := (queryNeededInputsWithWork groups online).1 + let cw := keys.map fun key => (readCurrent key).value oracle + have he : ∀ w ∈ ew, w.width ≤ B := by + intro w hw + obtain ⟨key, _, rfl⟩ := List.mem_map.mp hw + exact hew key + have hcur : ∀ w ∈ cw, w.width ≤ B := by + intro w hw + obtain ⟨key, _, rfl⟩ := List.mem_map.mp hw + exact hcw key + have het : ∀ key ∈ earlier, Nat.size key.2.1 ≤ B := by + intro key hk + exact (Nat.size_le_size (queryEarlierInputsWithWork_time M parent N P F exponent t hP a + parentInitial q key hk).le).trans ht + have h := (queryLocalRefinement_finish_bounds source target parent N P F exponent H Q eM eF + hP hM hF tau a eta kappa delta t parentInitial child initial R hc hi draw integer earlier ew + shared sw cw q B Rp earlier.length hB hN hnx hny hMb hPb hFb ht ha hd hpw hpr hpn he hcur het + (Nat.le_refl _)).1 + simpa only [queryLocalRefinement, queryRefinementGather, BitQuery.value_bind, + BitQuery.value_collect, BitQuery.compute, BitQuery.value] using h + +end Refinement + +section Sources +variable {ι α : Type*} (source target : List α) {M : ℕ} [NeZero M] + (parent : TargetInterval source.length) (N P F exponent H Q eM eF : ℕ) + (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) + (tau a eta kappa delta : BinaryFraction) (t : ℕ) + (parentInitial : TargetInterval target.length → BinaryFraction × ℕ) + (child initial : Fin M → TargetInterval target.length → BinaryFraction × ℕ) + (R : ℕ) (hc : ∀ i r, (child i r).2 ≤ R) (hi : ∀ i r, (initial i r).2 ≤ R) + (q : TargetInterval target.length) + (readGroup : GroupScalarKey M F Q → BitQuery ι BinaryFraction) + (readInteger : (ℕ × TargetInterval target.length) → ℕ → BitQuery ι BinaryFraction) + (readEarlier : (Fin M × ℕ × TargetInterval target.length) → BitQuery ι BinaryFraction) + (readCurrent : (Fin M × TargetInterval target.length) → BitQuery ι BinaryFraction) + (oracle : ι → BinaryFraction) + +theorem queryLocalRandomSources_width (B Rp : ℕ) + (hB : 10 ≤ B) (hN : Nat.size N ≤ B) (hnx : Nat.size source.length ≤ B) + (hny : Nat.size target.length + 2 ≤ B) (hMb : Nat.size M ≤ B) (hPb : Nat.size P ≤ B) + (hFb : Nat.size F + 2 ≤ B) (ht : Nat.size t ≤ B) (ha : a.width ≤ B) (hd : delta.width ≤ B) + (hpw : ∀ r, (parentInitial r).1.width ≤ B) (hpr : ∀ r, (parentInitial r).2 ≤ Rp) + (hpn : 0 ≤ (parentInitial q).1.value) + (hew : ∀ key, ((readEarlier key).value oracle).width ≤ B) + (hcw : ∀ key, ((readCurrent key).value oracle).width ≤ B) : + ((queryLocalRandomSources source target parent N P F exponent H Q eM eF hP hM hF + tau a eta kappa delta t parentInitial child initial R hc hi q readGroup readInteger + readEarlier readCurrent).value oracle).width ≤ preparedKernelWordBudget M B := by + let gk := (queryGroupSourceKeysWithWork M N F Q exponent eM eF hM hF a (parentInitial q).1 q).1 + let gw := gk.map fun key => (readGroup key).value oracle + let ok := (queryOnlineKeysWithWork N P F hP a (parentInitial q).1 q).1 + let ow := ok.map fun key => + (readInteger key (queryOnlineRangeWithWork parent P exponent H tau child key).1).value oracle + have h := queryLocalRefinement_width source target parent N P F exponent H Q eM eF hP hM hF + tau a eta kappa delta t parentInitial child initial R hc hi (queryGroupDrawReadWithWork gk gw) + (queryOnlineIntegerReadWithWork ok ow) q readEarlier readCurrent oracle B Rp hB hN hnx hny hMb + hPb hFb ht ha hd hpw hpr hpn hew hcw + simpa only [queryLocalRandomSources, queryGroupSourceGather, queryOnlineSourceGather, + BitQuery.value_bind, BitQuery.value_collect, BitQuery.compute, BitQuery.value] using h + +end Sources + +section Band +variable {ι α : Type*} (source target : List α) {M : ℕ} [NeZero M] + (parent : TargetInterval source.length) (N P F exponent H Q eM eF : ℕ) + (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) + (tau a eta kappa delta : BinaryFraction) (t : ℕ) + (parentInitial : TargetInterval target.length → BinaryFraction × ℕ) + (readMass readInitial : (Fin M × TargetInterval target.length) → BitQuery ι BinaryFraction) + (readGroup : GroupScalarKey M F Q → BitQuery ι BinaryFraction) + (readInteger : (ℕ × TargetInterval target.length) → ℕ → BitQuery ι BinaryFraction) + (q : TargetInterval target.length) + (readEarlier : (Fin M × ℕ × TargetInterval target.length) → BitQuery ι BinaryFraction) + (readCurrent : (Fin M × TargetInterval target.length) → BitQuery ι BinaryFraction) + (oracle : ι → BinaryFraction) + +theorem queryLocalBand_width (B Rp : ℕ) + (hB : 10 ≤ B) (hN : Nat.size N ≤ B) (hnx : Nat.size source.length ≤ B) + (hny : Nat.size target.length + 2 ≤ B) (hMb : Nat.size M ≤ B) (hPb : Nat.size P ≤ B) + (hFb : Nat.size F + 2 ≤ B) (ht : Nat.size t ≤ B) (ha : a.width ≤ B) (hd : delta.width ≤ B) + (hpw : ∀ r, (parentInitial r).1.width ≤ B) (hpr : ∀ r, (parentInitial r).2 ≤ Rp) + (hpn : 0 ≤ (parentInitial q).1.value) + (hew : ∀ key, ((readEarlier key).value oracle).width ≤ B) + (hcw : ∀ key, ((readCurrent key).value oracle).width ≤ B) : + ((queryLocalBand source target parent N P F exponent H Q eM eF hP hM hF + tau a eta kappa delta t parentInitial readMass readInitial readGroup readInteger q + readEarlier readCurrent).value oracle).width ≤ preparedKernelWordBudget M B := by + let keys := (queryBandInputsWithWork M parent N P F exponent hP a parentInitial q).1 + let mw := keys.map fun key => (readMass key).value oracle + let iw := keys.map fun key => (readInitial key).value oracle + have h := queryLocalRandomSources_width source target parent N P F exponent H Q eM eF hP hM hF + tau a eta kappa delta t parentInitial (queryChildReadWithWork keys mw) + (queryChildReadWithWork keys iw) (queryDataReadBudget M target.length keys) + (queryChildReadWithWork_budget keys mw) (queryChildReadWithWork_budget keys iw) + q readGroup readInteger readEarlier readCurrent oracle B Rp hB hN hnx hny hMb hPb hFb ht ha hd + hpw hpr hpn hew hcw + simpa only [queryLocalBand, queryBandGather, BitQuery.value_bind, + BitQuery.value_collect, BitQuery.compute, BitQuery.value] using h + +end Band + +section Program +variable {ι α : Type*} (source target : List α) {M : ℕ} [NeZero M] + (parent : TargetInterval source.length) (N P F exponent H Q eM eF : ℕ) + (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) + (tau a eta kappa delta : BinaryFraction) (t : ℕ) + (readParent : TargetInterval target.length → BitQuery ι BinaryFraction) + (readMass readInitial : (Fin M × TargetInterval target.length) → BitQuery ι BinaryFraction) + (readGroup : GroupScalarKey M F Q → BitQuery ι BinaryFraction) + (readInteger : (ℕ × TargetInterval target.length) → ℕ → BitQuery ι BinaryFraction) + (q : TargetInterval target.length) + (readEarlier : (Fin M × ℕ × TargetInterval target.length) → BitQuery ι BinaryFraction) + (readCurrent : (Fin M × TargetInterval target.length) → BitQuery ι BinaryFraction) + (oracle : ι → BinaryFraction) + +theorem queryLocalProgram_width (B : ℕ) + (hB : 10 ≤ B) (hN : Nat.size N ≤ B) (hnx : Nat.size source.length ≤ B) + (hny : Nat.size target.length + 2 ≤ B) (hMb : Nat.size M ≤ B) (hPb : Nat.size P ≤ B) + (hFb : Nat.size F + 2 ≤ B) (ht : Nat.size t ≤ B) (ha : a.width ≤ B) (hd : delta.width ≤ B) + (hpw : ∀ key, ((readParent key).value oracle).width ≤ B) + (hpn : ∀ key, 0 ≤ ((readParent key).value oracle).value) + (hew : ∀ key, ((readEarlier key).value oracle).width ≤ B) + (hcw : ∀ key, ((readCurrent key).value oracle).width ≤ B) : + ((queryLocalProgram source target parent N P F exponent H Q eM eF hP hM hF + tau a eta kappa delta t readParent readMass readInitial readGroup readInteger q + readEarlier readCurrent).value oracle).width ≤ preparedKernelWordBudget M B := by + let keys := (queryInitialSupportWithWork N P F exponent hP a ((readParent q).value oracle) q).1 + let words := keys.map fun key => (readParent key).value oracle + have hw : ∀ w ∈ words, w.width ≤ B := by + intro w hw + obtain ⟨key, _, rfl⟩ := List.mem_map.mp hw + exact hpw key + have hn : ∀ r, 0 ≤ (queryParentReadWithWork keys words r).1.value := by + intro r + rw [queryParentReadWithWork_value] + apply finiteAnswerTable_nonneg + intro v hv + obtain ⟨w, hw, rfl⟩ := List.mem_map.mp hv + obtain ⟨key, _, rfl⟩ := List.mem_map.mp hw + exact hpn key + have h := queryLocalBand_width source target parent N P F exponent H Q eM eF hP hM hF + tau a eta kappa delta t (queryParentReadWithWork keys words) readMass readInitial + readGroup readInteger q readEarlier readCurrent oracle B + (1 + keys.length * (16 * Nat.size target.length + 6)) hB hN hnx hny hMb hPb hFb ht ha hd + (fun r => gatheredWordLookupWithWork_width _ keys words r B (by omega) hw) + (queryParentReadWithWork_cost keys words) (hn q) hew hcw + simpa only [queryLocalProgram, queryInitialGather, BitQuery.value_bind, + BitQuery.value_collect, BitQuery.compute, BitQuery.value] using h + +end Program +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryRawCenterCost.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryRawCenterCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..a6d6789a01a82ff0bcb17c234014136ac847981f --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryRawCenterCost.lean @@ -0,0 +1,116 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryGridCost +import OAI.Combinatorics.EditApproximation.Queries.QueryScalarDispatch +import OAI.Combinatorics.EditApproximation.Queries.QueryHistoryBounds +import OAI.Combinatorics.EditApproximation.Queries.QueryOrderBounds + +namespace OAI + +/-! Complete work of scale enumeration and unfiltered center construction. +Quadratic duplicate removal is bounded by the actual local grid sizes. -/ + +namespace EditApproximation.BinaryFraction + +def queryScalesBitBudget (B : ℕ) : ℕ := + queryExponentsBitBudget B + (B + 1) * (B + 6) + 1 + +theorem queryScalesWithWork_bounds (N F B : ℕ) (a value : BinaryFraction) + (hB : 7 ≤ B) (hN : Nat.size N ≤ B) (hF : Nat.size F + 2 ≤ B) + (ha : a.width ≤ B) (hv : value.width ≤ B) : + (queryScalesWithWork N F a value).1.length ≤ B + 1 ∧ + (queryScalesWithWork N F a value).2 ≤ queryScalesBitBudget B := by + let exponents := queryExponentsWithWork N F a value + have he := queryExponentsWithWork_bounds N F B a value hB hN hF ha hv + have hc := arithmeticMapWithWork_cost (fun e => (bitWordValue (powerTwoWord e), e + 3)) + exponents.1 (B + 3) (by + intro e he + change e ∈ (queryExponentsWithWork N F a value).1 at he + simp only [queryExponentsWithWork, filterWithWork_value] at he + have hr := List.mem_range.mp (List.mem_filter.mp he).1 + rw [Nat.size_eq_bits_len] at hr + change e + 3 ≤ B + 3 + omega) + constructor + · simpa only [queryScalesWithWork, arithmeticMapWithWork_value, List.length_map] using he.2 + · have hm := hc.trans (Nat.mul_le_mul_right _ he.2) + change exponents.2 + + (arithmeticMapWithWork (fun e => (bitWordValue (powerTwoWord e), e + 3)) exponents.1).2 + 1 ≤ _ + dsimp only [queryScalesBitBudget] + simp only [Nat.add_assoc, Nat.reduceAdd] at hm + have hex : exponents.2 ≤ queryExponentsBitBudget B := he.1 + omega + +theorem queryScalesWithWork_member (N F B : ℕ) (a value : BinaryFraction) + (hN : Nat.size N ≤ B) (hF : 1 ≤ F) (b : ℕ) + (hb : b ∈ (queryScalesWithWork N F a value).1) : + Nat.size b ≤ B + 1 ∧ ⌈value.value⌉₊ ≤ (16 * F) * b := by + rw [queryScalesWithWork_value] at hb + obtain ⟨hdyadic, hguard⟩ := List.mem_filter.mp hb + have hguard' := of_decide_eq_true hguard + refine ⟨(dyadicScales_size_bound N b hdyadic).trans (by omega), ?_⟩ + apply Nat.ceil_le.mpr + have hp : (0 : ℚ) < 16 * F := by + have hf : (0 : ℚ) < F := by exact_mod_cast (show 0 < F by omega) + positivity + have h := (div_le_iff₀ hp).mp hguard'.1 + simpa only [Nat.cast_mul, Nat.cast_ofNat, mul_comm] using h + +def queryRawCentersBitBudget (P F B : ℕ) : ℕ := + let L := (64 * F * P + 2) ^ 2 + let count := (B + 1) * L + queryScalesBitBudget B + 500 * (B + 1) ^ 2 + + (B + 1) * (queryGridPointsBitBudget P (16 * F) (B + 2) + L + 3) + + (count + 1) ^ 2 * (16 * B + 9) + 3 + +theorem queryRawCentersWithWork_bounds {n : ℕ} (N P F B : ℕ) + (a value : BinaryFraction) (q : TargetInterval n) + (hB : 8 ≤ B) (hN : Nat.size N ≤ B) (hF : Nat.size F + 2 ≤ B) (hFpos : 1 ≤ F) + (hP : 0 < P) (hPb : Nat.size P ≤ B) (hn : Nat.size n ≤ B) + (ha : a.width ≤ B) (hv : value.width ≤ B) : + (queryRawCentersWithWork N P F a value q).1.length ≤ (B + 1) * (64 * F * P + 2) ^ 2 ∧ + (queryRawCentersWithWork N P F a value q).2 ≤ queryRawCentersBitBudget P F B := by + let scales := queryScalesWithWork N F a value + let radius := naturalCeilingWithWork value + let run := fun b => queryGridPointsWithWork P b (bitWordValue radius.1) q + let centers := arithmeticFlatMapWithWork run scales.1 + let L := (64 * F * P + 2) ^ 2 + let count := (B + 1) * L + have hs := queryScalesWithWork_bounds N F B a value (by omega) hN hF ha hv + have hr : Nat.size (bitWordValue radius.1) ≤ B + 2 := + (Nat.size_le.mpr (bitWordValue_lt_pow_length radius.1)).trans + ((naturalCeilingWithWork_length value).trans (by omega)) + have hrun (b : ℕ) (hb : b ∈ scales.1) : + (run b).1.length ≤ L ∧ (run b).2 ≤ queryGridPointsBitBudget P (16 * F) (B + 2) := by + have hm := queryScalesWithWork_member N F B a value hN hFpos b hb + have hc : bitWordValue radius.1 ≤ (16 * F) * b := by + rw [naturalCeilingWithWork_value] + exact hm.2 + have hg := queryGridPointsWithWork_bounds P b (bitWordValue radius.1) (16 * F) (B + 2) q + hP (by omega) (by omega) hr (by omega) hc + simpa only [run, L, show 4 * (16 * F) * P = 64 * F * P by ring] using hg + have hl := arithmeticFlatMapWithWork_length run scales.1 L (fun b hb => (hrun b hb).1) + have hw := arithmeticFlatMapWithWork_cost run scales.1 + (queryGridPointsBitBudget P (16 * F) (B + 2)) L + (fun b hb => (hrun b hb).2) (fun b hb => (hrun b hb).1) + have hl' : centers.1.length ≤ count := hl.trans (Nat.mul_le_mul_right L hs.1) + have hw' := hw.trans (Nat.mul_le_mul_right _ hs.1) + change centers.2 ≤ (B + 1) * (queryGridPointsBitBudget P (16 * F) (B + 2) + L + 3) at hw' + have he := queryEraseWithWork_cost queryIntervalEqualWithWork (16 * B + 5) + (fun r s => queryIntervalEqualWithWork_cost r s B hn) centers.1 + have he' := he.trans (Nat.mul_le_mul_right _ (Nat.pow_le_pow_left (Nat.add_le_add_right hl' 1) 2)) + rw [show 16 * B + 5 + 4 = 16 * B + 9 by omega] at he' + have hu := (queryEraseWithWork_length queryIntervalEqualWithWork centers.1).trans hl' + have hrad := (naturalCeilingWithWork_cost value).trans + (Nat.mul_le_mul_left 500 (Nat.pow_le_pow_left (Nat.add_le_add_right hv 1) 2)) + refine ⟨hu, ?_⟩ + change scales.2 + radius.2 + centers.2 + + (queryEraseWithWork queryIntervalEqualWithWork centers.1).2 + 3 ≤ _ + change _ ≤ queryScalesBitBudget B + 500 * (B + 1) ^ 2 + + (B + 1) * (queryGridPointsBitBudget P (16 * F) (B + 2) + L + 3) + + (count + 1) ^ 2 * (16 * B + 9) + 3 + have hsc : scales.2 ≤ queryScalesBitBudget B := hs.2 + change radius.2 ≤ _ at hrad + omega + +end EditApproximation.BinaryFraction + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryRawWidthPolynomial.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryRawWidthPolynomial.lean new file mode 100644 index 0000000000000000000000000000000000000000..e36a52715ebbe416bf29a555807f5833a1dd953f --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryRawWidthPolynomial.lean @@ -0,0 +1,58 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryLocalWarmupWork +import OAI.Combinatorics.EditApproximation.Binary.BinaryPreparedKernelWork +import OAI.Combinatorics.EditApproximation.Probability.FiniteBitPolynomial + +namespace OAI + +namespace EditApproximation + +private abbrev GP := FiniteBitPolynomial (Fin 2) + +private def gp_bandMassTotalStorageBudget (M B : GP) : GP := + FiniteBitPolynomial.bitLength M + B + 2 * (1 + M * (B + 1)) + 2 + +private def gp_connectionWordBudget (k B : GP) : GP := + gp_bandMassTotalStorageBudget (k + 1) (8 * B + 6) + +private def gp_endpointDistanceWordBudget (B : GP) : GP := + 64 * B + 54 + +private def gp_physicalContinuationInputBudget (M B : GP) : GP := + B + gp_connectionWordBudget M B + gp_endpointDistanceWordBudget B + 4 * B + 2 + +private def gp_bellmanActionWordBudget (M B : GP) : GP := + 8 * (40 * B + 22 + gp_bandMassTotalStorageBudget M B) + 6 + +private def gp_localWarmupWordBudget (M B : GP) : GP := + let W := gp_physicalContinuationInputBudget M (B + 4) + W + gp_bellmanActionWordBudget M W + +private def gp_refinementUpdateWordBudget (B : GP) : GP := + 32 * B + 28 + +private def gp_localContinuationInputBudget (M B : GP) : GP := + B + 2 * gp_bellmanActionWordBudget M B + 1 + +private def gp_localContinuationWordBudget (M B : GP) : GP := + gp_refinementUpdateWordBudget (gp_localContinuationInputBudget M B) + +private def gp_preparedKernelWordBudget (M B : GP) : GP := + gp_localContinuationWordBudget M (gp_physicalContinuationInputBudget M (B + 4)) + +private def rawWordPolynomial : GP := + gp_localWarmupWordBudget (.input 0) (.input 1) + gp_preparedKernelWordBudget (.input 0) (.input 1) + +def queryRawWordDegree : ℕ := rawWordPolynomial.degree + +theorem queryRawWord_fixedPower (M B X : ℕ) (hX : 2 ≤ X) (hM : M ≤ X) (hB : B ≤ X) : + BinaryFraction.localWarmupWordBudget M B + BinaryFraction.preparedKernelWordBudget M B ≤ + X ^ queryRawWordDegree := by + exact rawWordPolynomial.eval_le_pow ![M, B] X hX (by + intro i + fin_cases i + · exact hM + · exact hB) + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryReadBoundIrrelevance.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryReadBoundIrrelevance.lean new file mode 100644 index 0000000000000000000000000000000000000000..c3afa966d9715daa51d4a04b869d62d15ee55444 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryReadBoundIrrelevance.lean @@ -0,0 +1,41 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryLocalSelectors + +namespace OAI + +/-! Read budgets certify fixed buffer algorithms. Enlarging the +budget changes proof arguments only, and preserves both values and work. -/ + +namespace EditApproximation.BinaryFraction +section Selectors +variable {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (N P F exponent H Q eM eF : ℕ) + (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) + (tau a eta kappa : BinaryFraction) + (parentInitial : TargetInterval target.length → BinaryFraction × ℕ) + (child initial : Fin M → TargetInterval target.length → BinaryFraction × ℕ) + (R R' : ℕ) (hc : ∀ i r, (child i r).2 ≤ R) (hi : ∀ i r, (initial i r).2 ≤ R) + (hc' : ∀ i r, (child i r).2 ≤ R') (hi' : ∀ i r, (initial i r).2 ≤ R') + +theorem queryGroupSelectWithWork_readBound_irrel (draw : CountedCellGroupDraws M F Q) + (keys : List (Fin M × TargetInterval target.length)) (words : List BinaryFraction) + (q : TargetInterval target.length) : + queryGroupSelectWithWork source target parent N P F exponent Q eM eF hP hM hF tau a + parentInitial child initial R hc hi draw keys words q = + queryGroupSelectWithWork source target parent N P F exponent Q eM eF hP hM hF tau a + parentInitial child initial R' hc' hi' draw keys words q := by + rfl + +theorem queryOnlineSelectWithWork_readBound_irrel (t : ℕ) + (integer : ℕ → TargetInterval target.length → ℕ × ℕ) + (keys : List (Fin M × ℕ × TargetInterval target.length)) (words : List BinaryFraction) + (q : TargetInterval target.length) : + queryOnlineSelectWithWork source target parent N P F exponent H hP tau a eta kappa + parentInitial child initial R hc hi t integer keys words q = + queryOnlineSelectWithWork source target parent N P F exponent H hP tau a eta kappa + parentInitial child initial R' hc' hi' t integer keys words q := by + rfl + +end Selectors +end EditApproximation.BinaryFraction + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryRefinementFinish.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryRefinementFinish.lean new file mode 100644 index 0000000000000000000000000000000000000000..a0804e575e8d5f7b1dd7aff30ba56f53bbad7818 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryRefinementFinish.lean @@ -0,0 +1,91 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryDataBuffers +import OAI.Combinatorics.EditApproximation.Binary.BinaryContinuationReads +import OAI.Combinatorics.EditApproximation.Binary.BinaryRepresentativeReads +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! The final local continuation consumes the two gathered data buffers. +It recomputes the local representative list with counted initial reads and +runs the Boolean Bellman/online minima on the already selected actions. -/ + +namespace EditApproximation +namespace BinaryFraction + +section Finish +variable {nx ny M : ℕ} (parent : TargetInterval nx) (N P F : ℕ) + (a delta : BinaryFraction) (initial : TargetInterval ny → BinaryFraction × ℕ) + (t : ℕ) (earlierKeys : List (Fin M × ℕ × TargetInterval ny)) (earlierWords : List BinaryFraction) + (groups online : List (BinaryBellmanAction (TargetInterval ny) (Fin M × TargetInterval ny) M)) + (currentKeys : List (Fin M × TargetInterval ny)) (currentWords : List BinaryFraction) + (query : TargetInterval ny) + + + +theorem queryRefinementFinishWithWork_value (hP : 0 < P) + (R : ℕ) (hp : ∀ r, (initial r).2 ≤ R) + (he : ∀ input, (queryHistoryReadWithWork earlierKeys earlierWords (t - 1) input).2 ≤ R) + (hc : ∀ i r, (queryChildReadWithWork currentKeys currentWords i r).2 ≤ R) : + (queryRefinementFinishWithWork parent N P F a delta initial t earlierKeys earlierWords + groups online currentKeys currentWords query).1.value = + rationalWideStep parent + (localRefinementRepresentatives N P F a.value (fun r => (initial r).1.value) query) + P (fun _ => (initial query).1.value) (128 * F) delta.value + (fun input => finiteAnswerTable earlierKeys (earlierWords.map value) (input.1, t - 1, input.2)) + (finiteAnswerTable currentKeys (currentWords.map value)) + (groups.map BinaryBellmanAction.decode) (online.map BinaryBellmanAction.decode) query := by + have hr := (localRepresentativeReadWithWork_eq_cost N P F a initial query R hp).1 + have hv := (physicalContinuationReadWithWork_eq_cost parent + (localRepresentativeReadWithWork N P F a initial query).1 P F delta (initial query).1 + (queryHistoryReadWithWork earlierKeys earlierWords (t - 1)) + (fun input => queryChildReadWithWork currentKeys currentWords input.1 input.2) + groups online query R he (fun input => hc input.1 input.2)).1 + simp only [queryRefinementFinishWithWork] + rw [hv, hr, physicalContinuationWithWork_value parent + (localRepresentativesWithWork N P F a (fun r => (initial r).1) query).1 P F delta + (initial query).1 (fun input => (queryHistoryReadWithWork earlierKeys earlierWords (t - 1) input).1) + (fun input => (queryChildReadWithWork currentKeys currentWords input.1 input.2).1) + groups online query hP] + simp only [localRepresentativesWithWork_value N P F hP a (fun r => (initial r).1) query, + queryHistoryReadWithWork_value, queryChildReadWithWork_value] + + +theorem queryRefinementFinishWithWork_value_only (hP : 0 < P) : + (queryRefinementFinishWithWork parent N P F a delta initial t earlierKeys earlierWords + groups online currentKeys currentWords query).1.value = + rationalWideStep parent + (localRefinementRepresentatives N P F a.value (fun r => (initial r).1.value) query) + P (fun _ => (initial query).1.value) (128 * F) delta.value + (fun input => finiteAnswerTable earlierKeys (earlierWords.map value) (input.1, t - 1, input.2)) + (finiteAnswerTable currentKeys (currentWords.map value)) + (groups.map BinaryBellmanAction.decode) (online.map BinaryBellmanAction.decode) query := by + classical + let p := ∑ r, (initial r).2 + let e := ∑ input : Fin M × TargetInterval ny, + (queryHistoryReadWithWork earlierKeys earlierWords (t - 1) input).2 + let c := ∑ input : Fin M × TargetInterval ny, + (queryChildReadWithWork currentKeys currentWords input.1 input.2).2 + apply queryRefinementFinishWithWork_value parent N P F a delta initial t earlierKeys earlierWords + groups online currentKeys currentWords query hP (p + e + c) + · intro r + have h : (initial r).2 ≤ p := Finset.single_le_sum (f := fun r => (initial r).2) (fun _ _ => Nat.zero_le _) (Finset.mem_univ r) + omega + · intro input + have h : (queryHistoryReadWithWork earlierKeys earlierWords (t - 1) input).2 ≤ e := + Finset.single_le_sum (f := fun input => + (queryHistoryReadWithWork earlierKeys earlierWords (t - 1) input).2) + (fun _ _ => Nat.zero_le _) (Finset.mem_univ input) + omega + · intro i r + have h : (queryChildReadWithWork currentKeys currentWords i r).2 ≤ c := + Finset.single_le_sum (f := fun input : Fin M × TargetInterval ny => + (queryChildReadWithWork currentKeys currentWords input.1 input.2).2) + (fun _ _ => Nat.zero_le _) (Finset.mem_univ (i, r)) + omega + +end Finish +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryRefinementGather.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryRefinementGather.lean new file mode 100644 index 0000000000000000000000000000000000000000..6050a2ba40aeba37982effdb880848b79aa6add7 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryRefinementGather.lean @@ -0,0 +1,162 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryHistoryInputs +import OAI.Combinatorics.EditApproximation.Queries.QuerySharedInputs +import OAI.Combinatorics.EditApproximation.Queries.QueryActionInputs +import OAI.Combinatorics.EditApproximation.Binary.BitQuery +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! The last three adaptive gathers of a refinement request. Each request +list is constructed after the answers on which it depends. The selected +actions, list construction, sorting and buffer cells all carry work. -/ + +namespace EditApproximation + +section Gather +variable {ι β α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (N P F exponent Q eM eF : ℕ) + (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) + (a : BinaryFraction) (t : ℕ) + (initial : TargetInterval target.length → BinaryFraction × ℕ) + (draw : CountedCellGroupDraws M F Q) (q : TargetInterval target.length) + (readEarlier : (Fin M × ℕ × TargetInterval target.length) → BitQuery ι BinaryFraction) + (readCurrent : (Fin M × TargetInterval target.length) → BitQuery ι BinaryFraction) + (online : List (Fin M × ℕ × TargetInterval target.length) → List BinaryFraction → + List (BinaryBellmanAction (TargetInterval target.length) + (Fin M × TargetInterval target.length) M) × ℕ) + (selected : List (Fin M × TargetInterval target.length) → List BinaryFraction → + List (BinaryBellmanAction (TargetInterval target.length) + (Fin M × TargetInterval target.length) M) × ℕ) + (next : List (Fin M × ℕ × TargetInterval target.length) → List BinaryFraction → + List (BinaryBellmanAction (TargetInterval target.length) (Fin M × TargetInterval target.length) M) → + List (BinaryBellmanAction (TargetInterval target.length) (Fin M × TargetInterval target.length) M) → + List (Fin M × TargetInterval target.length) → List BinaryFraction → BitQuery ι β) + + + + +theorem queryRefinementGather_work (oracle : ι → BinaryFraction) (readWork : ι → ℕ) : + let earlier := BinaryFraction.queryEarlierInputsWithWork M parent N P F exponent t hP a initial q + let earlierWords := earlier.1.map fun key => (readEarlier key).value oracle + let actions := online earlier.1 earlierWords + let shared := BinaryFraction.querySharedInputsWithWork M N F Q exponent eM eF hM hF + parent a (initial q).1 q draw + let sharedWords := shared.1.map fun key => (readCurrent key).value oracle + let groups := selected shared.1 sharedWords + let current := queryNeededInputsWithWork groups.1 actions.1 + let currentWords := current.1.map fun key => (readCurrent key).value oracle + (queryRefinementGather source target parent N P F exponent Q eM eF hP hM hF + a t initial draw q readEarlier readCurrent online selected next).work oracle readWork = + earlier.2 + (earlier.1.map fun key => (readEarlier key).work oracle readWork + 3).sum + + actions.2 + (initial q).2 + shared.2 + + (shared.1.map fun key => (readCurrent key).work oracle readWork + 3).sum + + groups.2 + current.2 + + (current.1.map fun key => (readCurrent key).work oracle readWork + 3).sum + + (next earlier.1 earlierWords groups.1 actions.1 current.1 currentWords).work oracle readWork := by + simp only [queryRefinementGather, BitQuery.work_bind, BitQuery.compute, + BitQuery.work, BitQuery.value, BitQuery.work_collect, + Nat.add_zero, Nat.add_assoc] + +end Gather + +section Simulation +variable {ι β α : Type*} {relation : β → ℚ → Prop} + (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (N P F exponent Q eM eF : ℕ) + (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) + (a : BinaryFraction) (t : ℕ) + (initial : TargetInterval target.length → BinaryFraction × ℕ) + (draw : CountedCellGroupDraws M F Q) (q : TargetInterval target.length) + (readEarlier : (Fin M × ℕ × TargetInterval target.length) → BitQuery ι BinaryFraction) + (readCurrent : (Fin M × TargetInterval target.length) → BitQuery ι BinaryFraction) + (expectedEarlier : (Fin M × ℕ × TargetInterval target.length) → FiniteQuery ι) + (expectedCurrent : (Fin M × TargetInterval target.length) → FiniteQuery ι) + (online : List (Fin M × ℕ × TargetInterval target.length) → List BinaryFraction → + List (BinaryBellmanAction (TargetInterval target.length) + (Fin M × TargetInterval target.length) M) × ℕ) + (selected : List (Fin M × TargetInterval target.length) → List BinaryFraction → + List (BinaryBellmanAction (TargetInterval target.length) + (Fin M × TargetInterval target.length) M) × ℕ) + (expectedOnline : List (Fin M × ℕ × TargetInterval target.length) → List ℚ → + List (RationalBellmanAction (TargetInterval target.length) + (Fin M × TargetInterval target.length) M)) + (expectedSelected : List (Fin M × TargetInterval target.length) → List ℚ → + List (RationalBellmanAction (TargetInterval target.length) + (Fin M × TargetInterval target.length) M)) + (next : List (Fin M × ℕ × TargetInterval target.length) → List BinaryFraction → + List (BinaryBellmanAction (TargetInterval target.length) (Fin M × TargetInterval target.length) M) → + List (BinaryBellmanAction (TargetInterval target.length) (Fin M × TargetInterval target.length) M) → + List (Fin M × TargetInterval target.length) → List BinaryFraction → BitQuery ι β) + (expectedNext : List (Fin M × ℕ × TargetInterval target.length) → List ℚ → + List (RationalBellmanAction (TargetInterval target.length) (Fin M × TargetInterval target.length) M) → + List (RationalBellmanAction (TargetInterval target.length) (Fin M × TargetInterval target.length) M) → + List (Fin M × TargetInterval target.length) → List ℚ → FiniteQuery ι) + +theorem queryRefinementGather_refines + (R : ℕ) (hR : ∀ r, (initial r).2 ≤ R) + (he : ∀ key, BitQuery.Refines (fun word value => word.value = value) + (readEarlier key) (expectedEarlier key)) + (hc : ∀ key, BitQuery.Refines (fun word value => word.value = value) + (readCurrent key) (expectedCurrent key)) + (ho : ∀ keys words, ((online keys words).1.map BinaryBellmanAction.decode) = + expectedOnline keys (words.map BinaryFraction.value)) + (hs : ∀ keys words, ((selected keys words).1.map BinaryBellmanAction.decode) = + expectedSelected keys (words.map BinaryFraction.value)) + (hn : ∀ earlierKeys earlierWords groups actions keys words, + BitQuery.Refines relation (next earlierKeys earlierWords groups actions keys words) + (expectedNext earlierKeys (earlierWords.map BinaryFraction.value) + (groups.map BinaryBellmanAction.decode) (actions.map BinaryBellmanAction.decode) + keys (words.map BinaryFraction.value))) : + BitQuery.Refines relation + (queryRefinementGather source target parent N P F exponent Q eM eF hP hM hF + a t initial draw q readEarlier readCurrent online selected next) + (let earlierKeys := orderedInputs historyInputCode (historyInputCode_injective M target.length) + (queryEarlierInputCover parent N P F exponent t a.value (fun r => (initial r).1.value) q) + FiniteQuery.collect expectedEarlier earlierKeys fun earlierWords => + let actions := expectedOnline earlierKeys earlierWords + let sharedKeys := orderedInputs childInputCode (childInputCode_injective M target.length) + (querySharedInputCover source target parent N F exponent Q a.value + (fun r => (initial r).1.value) q (fun b cell scale sample => (draw b cell scale sample).1)) + FiniteQuery.collect expectedCurrent sharedKeys fun sharedWords => + let groups := expectedSelected sharedKeys sharedWords + let keys := orderedInputs childInputCode (childInputCode_injective M target.length) + (actionCurrentInputCover groups ∪ actionCurrentInputCover actions) + FiniteQuery.collect expectedCurrent keys + (expectedNext earlierKeys earlierWords groups actions keys)) := by + have hshared : querySharedInputCover source target parent N F exponent Q a.value + (fun _ => (initial q).1.value) q (fun b cell scale sample => (draw b cell scale sample).1) = + querySharedInputCover source target parent N F exponent Q a.value + (fun r => (initial r).1.value) q (fun b cell scale sample => (draw b cell scale sample).1) := rfl + unfold queryRefinementGather + dsimp only [BitQuery.compute, BitQuery.bind] + apply BitQuery.Refines.charge + rw [BinaryFraction.queryEarlierInputsWithWork_value M parent N P F exponent t hP a initial q R hR] + apply BitQuery.Refines.collect readEarlier expectedEarlier he + intro earlierWords + apply BitQuery.Refines.charge + apply BitQuery.Refines.charge + apply BitQuery.Refines.charge + rw [BinaryFraction.querySharedInputsWithWork_value source target, hshared] + apply BitQuery.Refines.collect readCurrent expectedCurrent hc + intro sharedWords + apply BitQuery.Refines.charge + apply BitQuery.Refines.charge + rw [queryNeededInputsWithWork_value, ho, hs] + apply BitQuery.Refines.collect readCurrent expectedCurrent hc + intro words + let ek := orderedInputs historyInputCode (historyInputCode_injective M target.length) + (queryEarlierInputCover parent N P F exponent t a.value (fun r => (initial r).1.value) q) + let sk := orderedInputs childInputCode (childInputCode_injective M target.length) + (querySharedInputCover source target parent N F exponent Q a.value + (fun r => (initial r).1.value) q (fun b cell scale sample => (draw b cell scale sample).1)) + let ck := orderedInputs childInputCode (childInputCode_injective M target.length) + (actionCurrentInputCover (expectedSelected sk (sharedWords.map BinaryFraction.value)) ∪ + actionCurrentInputCover (expectedOnline ek (earlierWords.map BinaryFraction.value))) + have hnext := hn ek earlierWords (selected sk sharedWords).1 (online ek earlierWords).1 ck words + simpa only [ek, sk, ck, ho, hs] using hnext + +end Simulation +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryRefinementSpace.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryRefinementSpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..ccf809c0de05db821b89d8069dc41e042098f4b8 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryRefinementSpace.lean @@ -0,0 +1,77 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryGatherSpace +import OAI.Combinatorics.EditApproximation.Queries.QueryLocalSelectorSpace +import OAI.Combinatorics.EditApproximation.Queries.QuerySharedSpace +import OAI.Combinatorics.EditApproximation.Queries.QueryContinuationSpace +import OAI.Combinatorics.EditApproximation.Queries.QueryLocalRefinement + +namespace OAI + +namespace EditApproximation +open BitQuery + +section Local +variable {ι α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (N P F exponent H Q eM eF : ℕ) + (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) + (tau a eta kappa delta : BinaryFraction) (t : ℕ) + (parentInitial : TargetInterval target.length → BinaryFraction × ℕ) + (child initial : Fin M → TargetInterval target.length → BinaryFraction × ℕ) + (R : ℕ) (hc : ∀ i r, (child i r).2 ≤ R) (hi : ∀ i r, (initial i r).2 ≤ R) + (draw : CountedCellGroupDraws M F Q) + (integer : ℕ → TargetInterval target.length → ℕ × ℕ) + (parentAllocation : TargetInterval target.length → ℕ) + (childAllocation initialAllocation : Fin M → TargetInterval target.length → ℕ) + (drawAllocation : CountedCellGroupAllocations M F Q) + (integerAllocation : ℕ → TargetInterval target.length → ℕ) + (hp : ∀ r, parentAllocation r ≤ (parentInitial r).2) + (hca : ∀ i r, childAllocation i r ≤ (child i r).2) + (hia : ∀ i r, initialAllocation i r ≤ (initial i r).2) + (hd : ∀ b cell s j, drawAllocation b cell s j ≤ (draw b cell s j).2) + (hz : ∀ b r, integerAllocation b r ≤ (integer b r).2) + (q : TargetInterval target.length) + (readEarlier : (Fin M × ℕ × TargetInterval target.length) → BitQuery ι BinaryFraction) + (readCurrent : (Fin M × TargetInterval target.length) → BitQuery ι BinaryFraction) + (he : ∀ key, Heap (readEarlier key)) (hr : ∀ key, Heap (readCurrent key)) + +open BinaryFraction in +def queryLocalRefinementHeap : Heap (queryLocalRefinement source target parent N P F exponent H Q eM eF + hP hM hF tau a eta kappa delta t parentInitial child initial R hc hi draw integer q readEarlier readCurrent) := + (Heap.computeOf (queryEarlierInputsWithWork M parent N P F exponent t hP a parentInitial q) + (queryEarlierInputsAllocation M parent N P F exponent t hP a parentInitial parentAllocation q) + (queryEarlierInputsAllocation_le_work M parent N P F exponent t hP a parentInitial parentAllocation q hp)).bind _ + fun earlierKeys => Heap.collect readEarlier he earlierKeys _ fun earlierWords => + (Heap.compute (queryOnlineSelectWithWork source target parent N P F exponent H hP + tau a eta kappa parentInitial child initial R hc hi t integer earlierKeys earlierWords q) + (queryOnlineSelectAllocation source target parent N P F exponent H hP tau a eta kappa + parentInitial child initial R hc hi parentAllocation childAllocation initialAllocation + t integer integerAllocation earlierKeys earlierWords q) + (queryOnlineSelectAllocation_le_work source target parent N P F exponent H hP tau a eta kappa + parentInitial child initial R hc hi parentAllocation childAllocation initialAllocation + t integer integerAllocation earlierKeys earlierWords q hp hca hia hz)).bind _ fun online => + Heap.chargeOf (parentAllocation q) (hp q) + ((Heap.computeOf (querySharedInputsWithWork M N F Q exponent eM eF hM hF parent a (parentInitial q).1 q draw) + (querySharedInputsAllocation M N F Q exponent eM eF hM hF parent a (parentInitial q).1 q draw drawAllocation) + (querySharedInputsAllocation_le_work M N F Q exponent eM eF hM hF parent a (parentInitial q).1 q draw drawAllocation hd)).bind _ + fun sharedKeys => Heap.collect readCurrent hr sharedKeys _ fun sharedWords => + (Heap.computeOf (queryGroupSelectWithWork source target parent N P F exponent Q eM eF hP hM hF + tau a parentInitial child initial R hc hi draw sharedKeys sharedWords q) + (queryGroupSelectAllocation source target parent N P F exponent Q eM eF hP hM hF tau a + parentInitial child initial R hc hi parentAllocation childAllocation initialAllocation + draw drawAllocation sharedKeys sharedWords q) + (queryGroupSelectAllocation_le_work source target parent N P F exponent Q eM eF hP hM hF tau a + parentInitial child initial R hc hi parentAllocation childAllocation initialAllocation + draw drawAllocation sharedKeys sharedWords q hp hca hia hd)).bind _ fun groups => + (Heap.computeOf (queryNeededInputsWithWork groups online) + (queryNeededInputsAllocation groups online) (queryNeededInputsAllocation_le_work groups online)).bind _ + fun currentKeys => Heap.collect readCurrent hr currentKeys _ fun currentWords => + Heap.computeOf (queryRefinementFinishWithWork parent N P F a delta parentInitial t + earlierKeys earlierWords groups online currentKeys currentWords q) + (queryRefinementFinishAllocation parent N P F a delta parentInitial parentAllocation t + earlierKeys earlierWords groups online currentKeys currentWords q) + (queryRefinementFinishAllocation_le_work parent N P F a delta parentInitial parentAllocation t + earlierKeys earlierWords groups online currentKeys currentWords q hp)) + +end Local +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryRefinementWorkBound.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryRefinementWorkBound.lean new file mode 100644 index 0000000000000000000000000000000000000000..8cfb891dbe7d072e3e947cc8bb4853a092c4cadc --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryRefinementWorkBound.lean @@ -0,0 +1,117 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryRefinementGather +import OAI.Combinatorics.EditApproximation.Queries.QueryActionInputCost + +namespace OAI + +/-! Composition of the seven executed refinement stages. Recursive reads, +list construction, sorting, both selectors and the final continuation are +all included in this counter. -/ + +namespace EditApproximation + +private theorem query_sum_map_bound {κ : Type*} (xs : List κ) (f : κ → ℕ) (C : ℕ) + (h : ∀ x ∈ xs, f x ≤ C) : (xs.map f).sum ≤ xs.length * C := by + induction xs with + | nil => simp + | cons x xs ih => + have hx := h x List.mem_cons_self + have ht := ih (fun y hy => h y (List.mem_cons_of_mem x hy)) + simp only [List.map_cons, List.sum_cons, List.length_cons, Nat.add_mul, Nat.one_mul] + omega + +namespace BinaryFraction + +def queryRefinementStagesBudget (M B readCost earlierLength earlierCost onlineLength onlineCost + sharedLength sharedCost groupLength groupCost parentCost finishCost : ℕ) : ℕ := + earlierCost + earlierLength * (readCost + 3) + onlineCost + parentCost + sharedCost + + sharedLength * (readCost + 3) + groupCost + + queryNeededInputsBitBudget (groupLength + onlineLength) M B + + (groupLength + onlineLength) * M * (readCost + 3) + finishCost + +end BinaryFraction + +section Work +variable {ι β α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (N P F exponent Q eM eF : ℕ) + (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) + (a : BinaryFraction) (t : ℕ) + (initial : TargetInterval target.length → BinaryFraction × ℕ) + (draw : CountedCellGroupDraws M F Q) (q : TargetInterval target.length) + (readEarlier : (Fin M × ℕ × TargetInterval target.length) → BitQuery ι BinaryFraction) + (readCurrent : (Fin M × TargetInterval target.length) → BitQuery ι BinaryFraction) + (online : List (Fin M × ℕ × TargetInterval target.length) → List BinaryFraction → + List (BinaryBellmanAction (TargetInterval target.length) (Fin M × TargetInterval target.length) M) × ℕ) + (selected : List (Fin M × TargetInterval target.length) → List BinaryFraction → + List (BinaryBellmanAction (TargetInterval target.length) (Fin M × TargetInterval target.length) M) × ℕ) + (next : List (Fin M × ℕ × TargetInterval target.length) → List BinaryFraction → + List (BinaryBellmanAction (TargetInterval target.length) (Fin M × TargetInterval target.length) M) → + List (BinaryBellmanAction (TargetInterval target.length) (Fin M × TargetInterval target.length) M) → + List (Fin M × TargetInterval target.length) → List BinaryFraction → BitQuery ι β) + +theorem queryRefinementGather_work_bound (oracle : ι → BinaryFraction) (readWork : ι → ℕ) + (B W EL EC OL OC SL SC groupLen GC FC PC : ℕ) + (hMb : Nat.size M ≤ B) (hny : Nat.size target.length ≤ B) : + let earlier := BinaryFraction.queryEarlierInputsWithWork M parent N P F exponent t hP a initial q + let earlierWords := earlier.1.map fun key => (readEarlier key).value oracle + let actions := online earlier.1 earlierWords + let shared := BinaryFraction.querySharedInputsWithWork M N F Q exponent eM eF hM hF + parent a (initial q).1 q draw + let sharedWords := shared.1.map fun key => (readCurrent key).value oracle + let groups := selected shared.1 sharedWords + let current := queryNeededInputsWithWork groups.1 actions.1 + let currentWords := current.1.map fun key => (readCurrent key).value oracle + earlier.1.length ≤ EL → earlier.2 ≤ EC → actions.1.length ≤ OL → actions.2 ≤ OC → + shared.1.length ≤ SL → shared.2 ≤ SC → groups.1.length ≤ groupLen → groups.2 ≤ GC → + (∀ key ∈ earlier.1, (readEarlier key).work oracle readWork ≤ W) → + (∀ key, (readCurrent key).work oracle readWork ≤ W) → + (next earlier.1 earlierWords groups.1 actions.1 current.1 currentWords).work oracle readWork ≤ FC → + (initial q).2 ≤ PC → + (queryRefinementGather source target parent N P F exponent Q eM eF hP hM hF + a t initial draw q readEarlier readCurrent online selected next).work oracle readWork ≤ + BinaryFraction.queryRefinementStagesBudget M B W EL EC OL OC SL SC groupLen GC PC FC := by + let earlier := BinaryFraction.queryEarlierInputsWithWork M parent N P F exponent t hP a initial q + let earlierWords := earlier.1.map fun key => (readEarlier key).value oracle + let actions := online earlier.1 earlierWords + let shared := BinaryFraction.querySharedInputsWithWork M N F Q exponent eM eF hM hF + parent a (initial q).1 q draw + let sharedWords := shared.1.map fun key => (readCurrent key).value oracle + let groups := selected shared.1 sharedWords + let current := queryNeededInputsWithWork groups.1 actions.1 + let currentWords := current.1.map fun key => (readCurrent key).value oracle + dsimp only + intro heL heC hoL hoC hsL hsC hgL hgC heR hcR hfinish hparent + change earlier.1.length ≤ EL at heL + change earlier.2 ≤ EC at heC + change actions.1.length ≤ OL at hoL + change actions.2 ≤ OC at hoC + change shared.1.length ≤ SL at hsL + change shared.2 ≤ SC at hsC + change groups.1.length ≤ groupLen at hgL + change groups.2 ≤ GC at hgC + change (next earlier.1 earlierWords groups.1 actions.1 current.1 currentWords).work oracle readWork ≤ FC at hfinish + have heRead := (query_sum_map_bound earlier.1 (fun key => (readEarlier key).work oracle readWork + 3) + (W + 3) (fun key hk => Nat.add_le_add_right (heR key hk) 3)).trans (Nat.mul_le_mul_right _ heL) + have hsRead := (query_sum_map_bound shared.1 (fun key => (readCurrent key).work oracle readWork + 3) + (W + 3) (fun key _ => Nat.add_le_add_right (hcR key) 3)).trans (Nat.mul_le_mul_right _ hsL) + have hc := queryNeededInputsWithWork_bounds groups.1 actions.1 B hMb hny + have hcL : current.1.length ≤ (groupLen + OL) * M := + hc.1.trans (Nat.mul_le_mul_right M (Nat.add_le_add hgL hoL)) + have hcC : current.2 ≤ queryNeededInputsBitBudget (groupLen + OL) M B := by + apply hc.2.trans + unfold queryNeededInputsBitBudget + gcongr + have hcRead := (query_sum_map_bound current.1 (fun key => (readCurrent key).work oracle readWork + 3) + (W + 3) (fun key _ => Nat.add_le_add_right (hcR key) 3)).trans (Nat.mul_le_mul_right _ hcL) + rw [queryRefinementGather_work] + change earlier.2 + (earlier.1.map fun key => (readEarlier key).work oracle readWork + 3).sum + + actions.2 + (initial q).2 + shared.2 + + (shared.1.map fun key => (readCurrent key).work oracle readWork + 3).sum + + groups.2 + current.2 + (current.1.map fun key => (readCurrent key).work oracle readWork + 3).sum + + (next earlier.1 earlierWords groups.1 actions.1 current.1 currentWords).work oracle readWork ≤ _ + unfold BinaryFraction.queryRefinementStagesBudget + omega + +end Work +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryRepresentativeCost.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryRepresentativeCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..a20344c95b34b8290051cb060d30f4cf2e5053a6 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryRepresentativeCost.lean @@ -0,0 +1,112 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryInitialSupportCost +import OAI.Combinatorics.EditApproximation.Binary.BinaryCellReads +import OAI.Combinatorics.EditApproximation.Binary.BinaryRepresentativeReads + +namespace OAI + +namespace EditApproximation.BinaryFraction + +def queryEarlierRepresentativesLength (P F exponent B : ℕ) : ℕ := + (B + 1) * ((64 * F * P + 2) ^ 2 + + ((32 * F + 2) * 2 ^ exponent + 2) ^ 2 * (P + 1) ^ 2 + 1) + +def queryEarlierRepresentativesBitBudget (P F exponent B R : ℕ) : ℕ := + let groups := (B + 1) * ((32 * F + 2) * 2 ^ exponent + 2) ^ 2 + let L := (P + 1) ^ 2 + R + localRepresentativesBitBudget P F B * (R + 2) + queryGroupKeysBitBudget F exponent B + + groups * (cellCentersBitBudget P P (16 * B + 200) * (R + 1) + 5 * L + 4) + + queryOnlineKeysBitBudget B + 2 * ((B + 1) * (64 * F * P + 2) ^ 2) + groups * L + 4 + +theorem queryEarlierRepresentativesWithWork_bounds {n : ℕ} (N P F exponent B R : ℕ) + (hP : 0 < P) (a : BinaryFraction) (initial : TargetInterval n → BinaryFraction × ℕ) + (q : TargetInterval n) (hB : 8 ≤ B) (hN : Nat.size N ≤ B) + (hF : Nat.size F + 2 ≤ B) (hFpos : 1 ≤ F) (hPb : Nat.size P ≤ B) + (hn : Nat.size n ≤ B) (he : exponent + 1 ≤ B) (ha : a.width ≤ B) + (hi : ∀ r, (initial r).1.width ≤ B) (hR : ∀ r, (initial r).2 ≤ R) + (hw : 0 ≤ (initial q).1.value) (hPd : ∃ e : ℕ, P = 2 ^ e) : + (queryEarlierRepresentativesWithWork N P F exponent hP a initial q).1.length ≤ + queryEarlierRepresentativesLength P F exponent B ∧ + (queryEarlierRepresentativesWithWork N P F exponent hP a initial q).2 ≤ + queryEarlierRepresentativesBitBudget P F exponent B R := by + let reps := localRepresentativeReadWithWork N P F a initial q + let groups := queryGroupKeysWithWork N F exponent a (initial q).1 q + let centers := fun key : ℕ × (ℕ × ℕ) => + cellCentersReadWithWork P F key.1 a (inversePowerTwo exponent) initial key.2 + let run := fun key : ℕ × (ℕ × ℕ) => + let labeled := arithmeticMapWithWork (fun r => ((key.1, r), 1)) (centers key).1 + (labeled.1, (centers key).2 + labeled.2 + 1) + let cells := arithmeticFlatMapWithWork run groups.1 + let online := queryOnlineKeysWithWork N P F hP a (initial q).1 q + let L := (P + 1) ^ 2 + let G := (B + 1) * ((32 * F + 2) * 2 ^ exponent + 2) ^ 2 + let C := cellCentersBitBudget P P (16 * B + 200) * (R + 1) + have hs := queryScalesWithWork_bounds N F B a (initial q).1 (by omega) hN hF ha (hi q) + have hwlen : (dyadicQueryWindow N (initial q).1.value a.value F).length ≤ B + 1 := by + simpa only [queryScalesWithWork_value] using hs.1 + have hrlen : reps.1.length ≤ (B + 1) * (64 * F * P + 2) ^ 2 := by + rw [(localRepresentativeReadWithWork_eq_cost N P F a initial q R hR).1, + localRepresentativesWithWork_value N P F hP a (fun r => (initial r).1) q] + exact (localRefinementRepresentatives_length N P F a.value (fun r => (initial r).1.value) q hP hFpos).trans + (Nat.mul_le_mul_right _ hwlen) + have hrc := localRepresentativeReadWithWork_cost N P F B R a initial q + (by omega) hN hF hFpos hPb hP hn ha hi hR + have hg := queryGroupKeysWithWork_bounds N F exponent B a (initial q).1 q + (by omega) hN hF hFpos he hn ha (hi q) hw + have ho := queryOnlineKeysWithWork_bounds N P F B hP a (initial q).1 q + (by omega) hN hF hFpos hPb hn ha (hi q) + have ht : 0 ≤ (inversePowerTwo exponent).value ∧ (inversePowerTwo exponent).value ≤ 1 := by + rw [inversePowerTwo_value] + exact ⟨by positivity, zpow_le_one_of_nonpos₀ (by norm_num) (by omega)⟩ + have hc (key : ℕ × (ℕ × ℕ)) (hk : key ∈ groups.1) : + (centers key).1.length ≤ L ∧ (centers key).2 ≤ C := by + obtain ⟨hb, hd, hleft, hright⟩ := hg.2.2 key hk + have hv := cellCentersReadWithWork_eq_cost P F key.1 a (inversePowerTwo exponent) initial key.2 R hR + constructor + · rw [hv.1, cellCentersWithWork_value P F key.1 a (inversePowerTwo exponent) + (fun r => (initial r).1) key.2 hP] + exact cellRepresentativeStates_length_le a.value (fun r => (initial r).1.value) + (inversePowerTwo exponent).value key.2 ht hd hPd + · apply hv.2.trans + apply Nat.mul_le_mul_right + apply cellCentersWithWork_uniform_cost P F key.1 (16 * B + 200) a (inversePowerTwo exponent) + (fun r => (initial r).1) key.2 (by omega) (by omega) (by omega) (by omega) (by omega) + (by omega) (by rw [inversePowerTwo_width]; omega) + (fun r => (hi r).trans (by omega)) (by omega) (by omega) ht hd hPd + have hrun (key : ℕ × (ℕ × ℕ)) (hk : key ∈ groups.1) : + (run key).1.length ≤ L ∧ (run key).2 ≤ C + 4 * L + 1 := by + have hh := hc key hk + have hm := (arithmeticMapWithWork_cost (fun r => ((key.1, r), 1)) (centers key).1 1 + (fun _ _ => le_rfl)).trans (Nat.mul_le_mul_right _ hh.1) + constructor + · simpa only [run, arithmeticMapWithWork_value, List.length_map] using hh.1 + · change (centers key).2 + _ + 1 ≤ _ + simp only [Nat.reduceAdd] at hm + rw [Nat.mul_comm L 4] at hm + omega + have hcl := (arithmeticFlatMapWithWork_length run groups.1 L + (fun key hk => (hrun key hk).1)).trans (Nat.mul_le_mul_right _ hg.1) + have hcc := (arithmeticFlatMapWithWork_cost run groups.1 (C + 4 * L + 1) L + (fun key hk => (hrun key hk).2) (fun key hk => (hrun key hk).1)).trans + (Nat.mul_le_mul_right _ hg.1) + change cells.2 ≤ G * (C + 4 * L + 1 + L + 3) at hcc + rw [show C + 4 * L + 1 + L + 3 = C + 5 * L + 4 by omega] at hcc + have hgw : groups.2 ≤ queryGroupKeysBitBudget F exponent B := hg.2.1 + have how : online.2 ≤ queryOnlineKeysBitBudget B := ho.2 + have hrepw : reps.2 ≤ localRepresentativesBitBudget P F B * (R + 2) := hrc + constructor + · rw [queryEarlierRepresentativesWithWork_value N P F exponent hP a initial q R hR] + exact (queryEarlierRepresentatives_length N P F exponent a.value (fun r => (initial r).1.value) + q hPd hFpos hw).trans (Nat.mul_le_mul_right _ hwlen) + · change (initial q).2 + reps.2 + groups.2 + cells.2 + online.2 + + 2 * reps.1.length + cells.1.length + 4 ≤ _ + change _ ≤ R + localRepresentativesBitBudget P F B * (R + 2) + queryGroupKeysBitBudget F exponent B + + G * (C + 5 * L + 4) + queryOnlineKeysBitBudget B + + 2 * ((B + 1) * (64 * F * P + 2) ^ 2) + G * L + 4 + have hr2 := Nat.mul_le_mul_left 2 hrlen + have hq := hR q + change cells.1.length ≤ G * L at hcl + omega + +end EditApproximation.BinaryFraction + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryRepresentativeScales.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryRepresentativeScales.lean new file mode 100644 index 0000000000000000000000000000000000000000..51c496d41d52a5340b7ecc2f23c8681d3e9d60b2 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryRepresentativeScales.lean @@ -0,0 +1,33 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryRepresentatives +import OAI.Combinatorics.EditApproximation.Queries.QueryScalarDispatch + +namespace OAI + +namespace EditApproximation + +theorem queryEarlierRepresentatives_scale {n : ℕ} (N P F exponent : ℕ) (a : ℚ) + (initial : TargetInterval n → ℚ) (q : TargetInterval n) (br : ℕ × TargetInterval n) + (hb : br ∈ queryEarlierRepresentatives N P F exponent a initial q) : + br.1 ∈ dyadicScales N := by + simp only [queryEarlierRepresentatives, List.mem_append] at hb + rcases hb with (hlocal | hcell) | honline + · exact (representativeList_conditions a initial + (localRefinementRepresentatives_subset N P F a initial q br hlocal)).1 + · obtain ⟨key, hkey, hbr⟩ := List.mem_flatMap.mp hcell + obtain ⟨r, _, rfl⟩ := List.mem_map.mp hbr + exact localGroupQueryKeys_scale hkey + · obtain ⟨b, hb, rfl⟩ := List.mem_map.mp honline + exact (List.mem_filter.mp hb).1 + +theorem BinaryFraction.queryEarlierRepresentativesWithWork_scale {n : ℕ} + (N P F exponent : ℕ) (hP : 0 < P) (a : BinaryFraction) + (initial : TargetInterval n → BinaryFraction × ℕ) (q : TargetInterval n) + (R : ℕ) (hR : ∀ r, (initial r).2 ≤ R) (br : ℕ × TargetInterval n) + (hb : br ∈ (queryEarlierRepresentativesWithWork N P F exponent hP a initial q).1) : + br.1 ∈ dyadicScales N := by + rw [queryEarlierRepresentativesWithWork_value N P F exponent hP a initial q R hR] at hb + exact queryEarlierRepresentatives_scale N P F exponent a.value (fun r => (initial r).1.value) q br hb + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryRepresentatives.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryRepresentatives.lean new file mode 100644 index 0000000000000000000000000000000000000000..fc6f92406a2c29eec0c0ecbb745267b2fefb851c --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryRepresentatives.lean @@ -0,0 +1,55 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryInitialSupport +import OAI.Combinatorics.EditApproximation.Binary.BinaryRepresentativeReads +import OAI.Combinatorics.EditApproximation.Binary.BinaryCellReads +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Counted representative and child-coordinate lists for adaptive band +data gathers. All initial-table lookups are included in the work counter. -/ + +namespace EditApproximation +namespace BinaryFraction + + + +theorem queryEarlierRepresentativesWithWork_value {n : ℕ} (N P F exponent : ℕ) + (hP : 0 < P) (a : BinaryFraction) (initial : TargetInterval n → BinaryFraction × ℕ) + (q : TargetInterval n) (R : ℕ) (hR : ∀ r, (initial r).2 ≤ R) : + (queryEarlierRepresentativesWithWork N P F exponent hP a initial q).1 = + queryEarlierRepresentatives N P F exponent a.value (fun r => (initial r).1.value) q := by + have hl := (localRepresentativeReadWithWork_eq_cost N P F a initial q R hR).1 + have hc (b : ℕ) (cell : ℕ × ℕ) := + (cellCentersReadWithWork_eq_cost P F b a (inversePowerTwo exponent) initial cell R hR).1 + simp only [queryEarlierRepresentativesWithWork, hl, hc, localRepresentativesWithWork_value _ _ _ hP, + arithmeticFlatMapWithWork_value, arithmeticMapWithWork_value, + cellCentersWithWork_value _ _ _ _ _ _ _ hP, inversePowerTwo_value, + queryGroupKeysWithWork_value, queryOnlineKeysWithWork_value, + queryEarlierRepresentatives, localGroupQueryKeys, localOnlineSourceKeys] + + + +@[simp] theorem queryWideInputsWithWork_value {nx ny : ℕ} (M : ℕ) + (parent : TargetInterval nx) (P : ℕ) (hP : 0 < P) + (representatives : List (ℕ × TargetInterval ny)) : + (queryWideInputsWithWork M parent P representatives).1 = wideWarmupInputs parent P representatives := by + simp only [queryWideInputsWithWork, queryEraseWithWork_value _ coordinateEqualWithWork_value, + arithmeticFlatMapWithWork_value, arithmeticMapWithWork_value, + wideChildGridWithWork_value _ _ _ _ _ hP, wideWarmupInputs] + + + +theorem queryBandInputsWithWork_value {nx ny : ℕ} (M : ℕ) (parent : TargetInterval nx) + (N P F exponent : ℕ) (hP : 0 < P) (a : BinaryFraction) + (initial : TargetInterval ny → BinaryFraction × ℕ) (q : TargetInterval ny) + (R : ℕ) (hR : ∀ r, (initial r).2 ≤ R) : + (queryBandInputsWithWork M parent N P F exponent hP a initial q).1 = + refinementBandInputList parent N P F exponent a.value (fun r => (initial r).1.value) q := by + simp only [queryBandInputsWithWork, queryWideInputsWithWork_value _ _ _ hP, + queryEarlierRepresentativesWithWork_value _ _ _ _ hP _ _ _ R hR, refinementBandInputList] + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryRestrictionCost.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryRestrictionCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..dec67cbf5cd3607f26c18aec4a99f017fcc366d3 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryRestrictionCost.lean @@ -0,0 +1,85 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryBoundedBody + +namespace OAI + +namespace EditApproximation.BitQuery + +/-- A failed domain test supplies the same zero word to the adaptive continuation. -/ +def restrictedOracle {ι : Type*} (P : ι → Prop) (test : ι → Bool × ℕ) + (htest : ∀ key, (test key).1 = true ↔ P key) + (oracle : {key // P key} → BinaryFraction) (key : ι) : BinaryFraction := + if h : (test key).1 = true then oracle ⟨key, (htest key).mp h⟩ else BinaryFraction.nat 0 + +def restrictedReadWork {ι : Type*} (P : ι → Prop) (test : ι → Bool × ℕ) + (htest : ∀ key, (test key).1 = true ↔ P key) + (readWork : {key // P key} → ℕ) (key : ι) : ℕ := + (test key).2 + if h : (test key).1 = true then readWork ⟨key, (htest key).mp h⟩ else 0 + +theorem restrictWithWork_work {ι : Type*} (P : ι → Prop) (test : ι → Bool × ℕ) + (htest : ∀ key, (test key).1 = true ↔ P key) + (program : BitQuery ι BinaryFraction) (oracle : {key // P key} → BinaryFraction) + (readWork : {key // P key} → ℕ) : + (restrictWithWork P test htest program).work oracle readWork = + program.work (restrictedOracle P test htest oracle) (restrictedReadWork P test htest readWork) := by + induction program with + | done result => rfl + | charge steps next ih => exact congrArg (steps + ·) ih + | read key next ih => + by_cases h : (test key).1 = true + · simp only [restrictWithWork, h, dite_true, work, restrictedOracle, restrictedReadWork, ih, + Nat.add_assoc] + · simp only [restrictWithWork, h, Bool.false_eq_true, dite_false, work, restrictedOracle, restrictedReadWork, ih, + Nat.add_zero] + +theorem restrictWithWork_value {ι : Type*} (P : ι → Prop) (test : ι → Bool × ℕ) + (htest : ∀ key, (test key).1 = true ↔ P key) + (program : BitQuery ι BinaryFraction) (oracle : {key // P key} → BinaryFraction) : + (restrictWithWork P test htest program).value oracle = + program.value (restrictedOracle P test htest oracle) := by + induction program with + | done result => rfl + | charge steps next ih => exact ih + | read key next ih => + by_cases h : (test key).1 = true + · simp only [restrictWithWork, h, dite_true, value, restrictedOracle, ih] + · simp only [restrictWithWork, h, Bool.false_eq_true, dite_false, value, restrictedOracle, ih] + +theorem restrictedOracle_width {ι : Type*} (P : ι → Prop) (test : ι → Bool × ℕ) + (htest : ∀ key, (test key).1 = true ↔ P key) + (oracle : {key // P key} → BinaryFraction) (B : ℕ) (hB : 2 ≤ B) + (hw : ∀ key, (oracle key).width ≤ B) (key : ι) : + (restrictedOracle P test htest oracle key).width ≤ B := by + unfold restrictedOracle + split + · exact hw _ + · exact (BinaryFraction.nat_width_le 0).trans (by simpa only [Nat.size_zero, Nat.zero_add] using hB) + +end EditApproximation.BitQuery + +namespace EditApproximation + +theorem queryPhysicalBoundedWithWork_cost {M J n : ℕ} (passes copies T S B : ℕ) + (request : PhysicalTableRequest M J n) + (hp : Nat.size passes ≤ B) (hc : Nat.size copies ≤ B) + (hT : Nat.size T ≤ B) (hS : Nat.size S ≤ B) + (hrp : Nat.size request.pass ≤ B) (hrc : Nat.size request.copy ≤ B) + (hri : Nat.size request.index ≤ B) : + (queryPhysicalBoundedWithWork passes copies T S request).2 ≤ 50 * B + 20 := by + have hpass := binaryNaturalCompareWithWork_cost request.pass passes + have hcopy := binaryNaturalCompareWithWork_cost request.copy copies + have hcap := binaryNaturalAddWithWork_cost T S + have hlen := bitAddWithWork_length T.bits S.bits false + have hlen' : (binaryNaturalAddWithWork T S).1.length ≤ B + 1 := by + change (bitAddWithWork T.bits S.bits false).1.length ≤ _ + apply hlen.trans + simpa only [Nat.size_eq_bits_len] using Nat.add_le_add_right (max_le hT hS) 1 + have hindex := wordLEWithWork_cost request.index.bits (binaryNaturalAddWithWork T S).1 + rw [Nat.size_eq_bits_len] at hindex + change (binaryNaturalCompareWithWork request.pass passes).2 + + (binaryNaturalCompareWithWork request.copy copies).2 + (binaryNaturalAddWithWork T S).2 + + (wordLEWithWork request.index.bits (binaryNaturalAddWithWork T S).1).2 + 4 ≤ _ + omega + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryRestrictionSpace.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryRestrictionSpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..405f91cbd075d0318041a47c0f50f88dcdc23407 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryRestrictionSpace.lean @@ -0,0 +1,47 @@ +import OAI.Combinatorics.EditApproximation.Binary.BitQueryKeysSpace +import OAI.Combinatorics.EditApproximation.Queries.QueryGatherSpace +import OAI.Combinatorics.EditApproximation.Queries.QueryBoundedBody +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation + + + +theorem queryPhysicalBoundedAllocation_le_work {M J n : ℕ} (passes copies T S : ℕ) + (request : PhysicalTableRequest M J n) : + queryPhysicalBoundedAllocation passes copies T S request ≤ (queryPhysicalBoundedWithWork passes copies T S request).2 := by + have hp := bitCompareWithWork_input_cells request.pass.bits passes.bits + have hc := bitCompareWithWork_input_cells request.copy.bits copies.bits + have ha := binaryNaturalAddAllocation_le_work T S + have hi := naturalWordLEAllocation_le_work request.index.bits (binaryNaturalAddWithWork T S).1 + unfold queryPhysicalBoundedAllocation queryPhysicalBoundedWithWork + dsimp only + unfold binaryNaturalCompareWithWork + omega + + + +theorem querySupportedChildAllocation_le_work {σ : Type*} {M J n : ℕ} (passes copies T S : ℕ) + (parent : {r : PhysicalTableRequest M J n // r.Bounded passes copies T S}) + (key : QueryPhysicalChild (σ := σ) passes copies T S parent) : + querySupportedChildAllocation passes copies T S parent key ≤ (querySupportedChildWithWork passes copies T S parent key).2 := by + cases key with + | inl source => exact Nat.zero_le _ + | inr child => exact queryPhysicalBoundedAllocation_le_work passes copies T S child.val + +open BitQuery + +def queryRestrictPhysicalBodyHeap {σ : Type*} {M J n : ℕ} (passes copies T S : ℕ) + (parent : {r : PhysicalTableRequest M J n // r.Bounded passes copies T S}) + (program : BitQuery (QueryPhysicalChild (σ := σ) passes copies T S parent) BinaryFraction) + (heap : Heap program) : Heap (queryRestrictPhysicalBody passes copies T S parent program) := + (heap.restrictWithWork _ _ (querySupportedChildWithWork_value passes copies T S parent) + (querySupportedChildAllocation passes copies T S parent) + (querySupportedChildAllocation_le_work passes copies T S parent)).mapKeysWithWork _ (fun _ => 1) (fun _ => le_rfl) + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryRoundedCounts.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryRoundedCounts.lean new file mode 100644 index 0000000000000000000000000000000000000000..e7cc5462c975b243f12808ebb840d156ee967a30 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryRoundedCounts.lean @@ -0,0 +1,42 @@ +import OAI.Combinatorics.EditApproximation.Geometry.ActualRoundedGroupInputs + +namespace OAI + +namespace EditApproximation + +/-- Every envelope queried by a shared group bounds both endpoint loops, +including the fractional-envelope, unit-spacing case. -/ +theorem groupRoundSpacing_endpoint_counts (M b exponent : ℕ) (h : ℚ) + (hM : 0 < M) (_hh : 0 ≤ h) (hfloor : (b : ℚ) / M ≤ h) : + 2 * (12 * b) / groupRoundSpacing exponent h + 2 ≤ 24 * 2 ^ exponent * M + 2 ∧ + 2 * ⌈2 * h⌉₊ / groupRoundSpacing exponent h + 2 ≤ 4 * 2 ^ exponent + 4 := by + let K := 2 ^ exponent + let g := groupRoundSpacing exponent h + have hg : 0 < g := groupRoundSpacing_pos exponent h + have hMr : (0 : ℚ) < M := by exact_mod_cast hM + have hspacing : h ≤ (K : ℚ) * g := by + simpa only [K, Nat.cast_pow, Nat.cast_ofNat] using groupRoundSpacing_envelope_bound exponent h + have hb : (b : ℚ) ≤ M * h := by + nlinarith only [(div_le_iff₀ hMr).mp hfloor] + have hbN : b ≤ K * M * g := by + have hx := mul_le_mul_of_nonneg_left hspacing (Nat.cast_nonneg M) + have hr : (b : ℚ) ≤ ((K * M * g : ℕ) : ℚ) := by push_cast; nlinarith only [hb, hx] + exact_mod_cast hr + have hfirst : 2 * (12 * b) / g ≤ 24 * K * M := by + have hd := Nat.div_mul_le_self (2 * (12 * b)) g + have hn : 2 * (12 * b) ≤ (24 * K * M) * g := by nlinarith only [Nat.mul_le_mul_left 24 hbN] + nlinarith only [hd, hn, hg] + have hceil : ⌈2 * h⌉₊ ≤ 2 * K * g + 1 := by + apply Nat.ceil_le.mpr + push_cast + linarith only [hspacing] + have hsecond : 2 * ⌈2 * h⌉₊ / g ≤ 4 * K + 2 := by + have hd := Nat.div_mul_le_self (2 * ⌈2 * h⌉₊) g + have hn : 2 * ⌈2 * h⌉₊ ≤ (4 * K + 2) * g := by + nlinarith only [hceil, hg] + nlinarith only [hd, hn, hg] + exact ⟨Nat.add_le_add_right hfirst 2, by simpa only [K, g, Nat.add_assoc, Nat.reduceAdd] using Nat.add_le_add_right hsecond 2⟩ + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryRoundedStateCost.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryRoundedStateCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..a82be4dd5c732ed02c60754d4880ff0b858f7902 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryRoundedStateCost.lean @@ -0,0 +1,157 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryGapStateCost +import OAI.Combinatorics.EditApproximation.Binary.BinaryCellGridWork +import OAI.Combinatorics.EditApproximation.Queries.QueryCodeBounds + +namespace OAI + +namespace EditApproximation.BinaryFraction + +def queryRoundedStatesBitBudget (left right exponent B : ℕ) : ℕ := + 100000 * (32 * B + 210) ^ 2 + queryGapStatesBitBudget left right (32 * B + 200) + exponent + 12 + +private theorem rounded_square_bound (k c B : ℕ) (hk : k ≤ 32 * B + 210) (hc : c ≤ 5000) : + c * k ^ 2 ≤ 5000 * (32 * B + 210) ^ 2 := + Nat.mul_le_mul hc (Nat.pow_le_pow_left hk 2) + +private theorem rounded_spacing_budget_bound (B : ℕ) : + roundedSpacingBitBudget B ≤ 5000 * (32 * B + 210) ^ 2 := by + unfold roundedSpacingBitBudget + nlinarith only [Nat.zero_le B] + +private theorem rounded_add_bound (a b B : ℕ) + (ha : Nat.size a ≤ 32 * B + 200) (hb : Nat.size b ≤ 32 * B + 200) : + (binaryNaturalAddWithWork a b).2 ≤ 5000 * (32 * B + 210) ^ 2 := by + have h := binaryNaturalAddWithWork_cost a b + nlinarith only [h, ha, hb, Nat.zero_le B] + +private theorem rounded_sub_bound (a b B : ℕ) + (ha : Nat.size a ≤ 32 * B + 200) (hb : Nat.size b ≤ 32 * B + 200) : + (saturatingSubtractWithWork a b).2 ≤ 5000 * (32 * B + 210) ^ 2 := by + have h := saturatingSubtractWithWork_cost a b + nlinarith only [h, ha, hb, Nat.zero_le B] + +private theorem rounded_mul_bound (a b B : ℕ) + (ha : Nat.size a ≤ 32 * B + 200) (hb : Nat.size b ≤ 32 * B + 200) : + (binaryNaturalMulWithWork a b).2 ≤ 5000 * (32 * B + 210) ^ 2 := by + have h := queryNaturalMul_cost a b (32 * B + 200) ha hb + nlinarith only [h, Nat.zero_le B] + +theorem queryGroupRoundedStatesWithWork_bounds {nx ny M : ℕ} (parent : TargetInterval nx) + (b exponent B left right : ℕ) (cell : ℕ × ℕ) (i : Fin M) (h : BinaryFraction) + (hB : 4 ≤ B) (hnx : Nat.size nx ≤ B) (hny : Nat.size ny ≤ B) + (hM : Nat.size M ≤ B) (hb : Nat.size b ≤ B) (hc : Nat.size cell.1 ≤ B) + (he : exponent + 1 ≤ B) (hh : h.width ≤ B) + (hleft : 2 * (12 * b) / groupRoundSpacing exponent h.value + 2 ≤ left) + (hright : 2 * ⌈2 * h.value⌉₊ / groupRoundSpacing exponent h.value + 2 ≤ right) : + (queryGroupRoundedStatesWithWork (ny := ny) parent b exponent cell i h).1.length ≤ left * right ∧ + (queryGroupRoundedStatesWithWork (ny := ny) parent b exponent cell i h).2 ≤ + queryRoundedStatesBitBudget left right exponent B := by + let theta := inversePowerTwo exponent + let spacing := roundedSpacingWithWork theta h + let child := sourceChildWithWork parent i + let offset := saturatingSubtractWithWork child.1.lo parent.lo + let base := canonicalMulWithWork (nat cell.1) theta + let position := canonicalMulWithWork base.1 (nat b) + let floor := naturalFloorWithWork position.1 + let anchor := binaryNaturalAddWithWork (bitWordValue floor.1) (bitWordValue offset.1) + let radius := binaryNaturalMulWithWork 12 b + let length := saturatingSubtractWithWork child.1.hi child.1.lo + let twice := canonicalMulWithWork (nat 2) h + let gap := naturalCeilingWithWork twice.1 + let C := 32 * B + 200 + have ht : theta.width ≤ B := by rw [inversePowerTwo_width]; exact he + have hsp := roundedSpacingWithWork_bounds theta h B ht hh + have hchild := sourceChildWithWork_cost parent i B hnx hM + have hcl : Nat.size child.1.lo ≤ B := (Nat.size_le_size (child.1.ordered.trans child.1.valid)).trans hnx + have hch : Nat.size child.1.hi ≤ B := (Nat.size_le_size child.1.valid).trans hnx + have hplo : Nat.size parent.lo ≤ B := (Nat.size_le_size (parent.ordered.trans parent.valid)).trans hnx + have hoff : Nat.size (bitWordValue offset.1) ≤ B := by + rw [saturatingSubtractWithWork_value] + exact (Nat.size_le_size (Nat.sub_le _ _)).trans hcl + have hbase := canonicalMulWithWork_width (nat cell.1) theta (B + 2) + ((nat_width_le _).trans (by omega)) (by omega) + have hpos := canonicalMulWithWork_width base.1 (nat b) (4 * B + 10) + (by change base.1.width ≤ _ at hbase; omega) ((nat_width_le _).trans (by omega)) + have hfloor := naturalFloorWithWork_bounds position.1 + have hfsize : Nat.size (bitWordValue floor.1) ≤ 16 * B + 42 := + (Nat.size_le.mpr (bitWordValue_lt_pow_length _)).trans + (hfloor.1.trans (by change position.1.width ≤ _ at hpos; omega)) + have hasize : Nat.size (bitWordValue anchor.1) ≤ C := by + rw [binaryNaturalAddWithWork_value] + apply (binaryNaturalAdd_size_le _ _).trans + dsimp only [C] + omega + have hrsize : Nat.size (bitWordValue radius.1) ≤ C := by + rw [binaryNaturalMulWithWork_value] + have htwelve : Nat.size 12 = 4 := by decide + have hp := queryNaturalMul_size 12 b + rw [htwelve] at hp + dsimp only [C] + omega + have hlsize : Nat.size (bitWordValue length.1) ≤ C := by + rw [saturatingSubtractWithWork_value] + exact (Nat.size_le_size (Nat.sub_le _ _)).trans (hch.trans (by dsimp only [C]; omega)) + have htwice := canonicalMulWithWork_width (nat 2) h B + (by exact (nat_width_le 2).trans (by rw [show Nat.size 2 = 2 by decide]; omega)) hh + have hgsize : Nat.size (bitWordValue gap.1) ≤ C := + (Nat.size_le.mpr (bitWordValue_lt_pow_length _)).trans + ((naturalCeilingWithWork_length twice.1).trans (by + change twice.1.width ≤ _ at htwice + dsimp only [C] + omega)) + have hspsize : Nat.size (bitWordValue spacing.1) ≤ C := + (Nat.size_le.mpr (bitWordValue_lt_pow_length _)).trans (hsp.1.trans (by + unfold roundedSpacingWordBudget + dsimp only [C] + omega)) + have hspvalue : bitWordValue spacing.1 = groupRoundSpacing exponent h.value := by + simp only [spacing, roundedSpacingWithWork_value, theta, inversePowerTwo_value, groupRoundSpacing] + have hradvalue : bitWordValue radius.1 = 12 * b := binaryNaturalMulWithWork_value _ _ + have hgapvalue : bitWordValue gap.1 = ⌈2 * h.value⌉₊ := by + simp only [gap, naturalCeilingWithWork_value, twice, canonicalMulWithWork_value, nat_value, Nat.cast_ofNat] + have hstates := queryGapStatesWithWork_bounds ny (bitWordValue spacing.1) (bitWordValue anchor.1) + (bitWordValue radius.1) (bitWordValue length.1) (bitWordValue gap.1) left right C + (roundedSpacingWithWork_pos theta h) (by dsimp only [C]; omega) hspsize hasize hrsize hlsize hgsize + (by simpa only [hspvalue, hradvalue] using hleft) (by simpa only [hspvalue, hgapvalue] using hright) + have hbasec := canonicalMulWithWork_cost (nat cell.1) theta (B + 2) + ((nat_width_le _).trans (by omega)) (by omega) + have hposc := canonicalMulWithWork_cost base.1 (nat b) (4 * B + 10) + (by change base.1.width ≤ _ at hbase; omega) ((nat_width_le _).trans (by omega)) + have hfloorc := hfloor.2.trans (Nat.mul_le_mul_left 200 + (Nat.pow_le_pow_left (by change position.1.width ≤ _ at hpos; omega : position.1.width + 1 ≤ 16 * B + 43) 2)) + have htc := canonicalMulWithWork_cost (nat 2) h B + (by exact (nat_width_le 2).trans (by rw [show Nat.size 2 = 2 by decide]; omega)) hh + have hgc := (naturalCeilingWithWork_cost twice.1).trans (Nat.mul_le_mul_left 500 + (Nat.pow_le_pow_left (by change twice.1.width ≤ _ at htwice; omega : twice.1.width + 1 ≤ 4 * B + 3) 2)) + have hs1 : spacing.2 ≤ 5000 * (32 * B + 210) ^ 2 := hsp.2.trans (rounded_spacing_budget_bound B) + have hs2 : child.2 ≤ 5000 * (32 * B + 210) ^ 2 := + hchild.trans (rounded_square_bound (B + 3) 2200 B (by omega) (by decide)) + have hs3 : offset.2 ≤ 5000 * (32 * B + 210) ^ 2 := + rounded_sub_bound child.1.lo parent.lo B (by omega) (by omega) + have hs4 : base.2 ≤ 5000 * (32 * B + 210) ^ 2 := + hbasec.trans (rounded_square_bound (B + 2 + 1) 2000 B (by omega) (by decide)) + have hs5 : position.2 ≤ 5000 * (32 * B + 210) ^ 2 := + hposc.trans (rounded_square_bound (4 * B + 10 + 1) 2000 B (by omega) (by decide)) + have hs6 : floor.2 ≤ 5000 * (32 * B + 210) ^ 2 := + hfloorc.trans (rounded_square_bound (16 * B + 43) 200 B (by omega) (by decide)) + have hs7 : anchor.2 ≤ 5000 * (32 * B + 210) ^ 2 := + rounded_add_bound (bitWordValue floor.1) (bitWordValue offset.1) B (by omega) (by omega) + have hs8 : radius.2 ≤ 5000 * (32 * B + 210) ^ 2 := + rounded_mul_bound 12 b B (by rw [show Nat.size 12 = 4 by decide]; omega) (by omega) + have hs9 : length.2 ≤ 5000 * (32 * B + 210) ^ 2 := + rounded_sub_bound child.1.hi child.1.lo B (by omega) (by omega) + have hs10 : twice.2 ≤ 5000 * (32 * B + 210) ^ 2 := + htc.trans (rounded_square_bound (B + 1) 2000 B (by omega) (by decide)) + have hs11 : gap.2 ≤ 5000 * (32 * B + 210) ^ 2 := + hgc.trans (rounded_square_bound (4 * B + 3) 500 B (by omega) (by decide)) + have hsetup : spacing.2 + child.2 + offset.2 + base.2 + position.2 + floor.2 + anchor.2 + + radius.2 + length.2 + twice.2 + gap.2 ≤ 100000 * (32 * B + 210) ^ 2 := by omega + constructor + · simpa only [queryGroupRoundedStatesWithWork] using hstates.1 + · simpa only [queryGroupRoundedStatesWithWork, queryRoundedStatesBitBudget, C, + Nat.add_assoc, Nat.reduceAdd] using + Nat.add_le_add_right (Nat.add_le_add_right (Nat.add_le_add hsetup hstates.2) exponent) 12 + +end EditApproximation.BinaryFraction + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryScalarDispatch.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryScalarDispatch.lean new file mode 100644 index 0000000000000000000000000000000000000000..feb732a04c7bccab525af311b093b8d48761b838 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryScalarDispatch.lean @@ -0,0 +1,74 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryHistoryCodeBounds +import OAI.Combinatorics.EditApproximation.Binary.BinaryScaleGrid +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! The physical scalar sources locate a dyadic scale by a counted scan. +The scan computes the original first index and works also for absent scales. -/ + +namespace EditApproximation + + + +@[simp] theorem queryNaturalIndexWithWork_value (a : ℕ) (xs : List ℕ) : + (queryNaturalIndexWithWork a xs).1 = xs.idxOf a := by + induction xs with + | nil => rfl + | cons b xs ih => + unfold queryNaturalIndexWithWork + by_cases hab : a = b + · subst b + rw [ite_eq_left ((naturalEqualWithWork_value a a).mpr rfl)] + simp + · rw [ite_eq_right (fun h => hab ((naturalEqualWithWork_value a b).mp h))] + simp only [ih, List.idxOf_cons, beq_iff_eq] + rw [ite_eq_right (Ne.symm hab)] + +theorem queryNaturalIndexWithWork_cost (a B : ℕ) (ha : Nat.size a ≤ B) + (xs : List ℕ) (hx : ∀ b ∈ xs, Nat.size b ≤ B) : + (queryNaturalIndexWithWork a xs).2 ≤ 1 + xs.length * (8 * B + 4) := by + induction xs with + | nil => simp only [queryNaturalIndexWithWork, List.length_nil, Nat.zero_mul, Nat.add_zero, le_refl] + | cons b xs ih => + have hc := naturalEqualWithWork_cost a b B ha (hx b (by simp)) + have ht := ih (fun c hc => hx c (List.mem_cons_of_mem b hc)) + simp only [queryNaturalIndexWithWork, List.length_cons] + split <;> dsimp only + · nlinarith only [hc, Nat.zero_le xs.length, Nat.zero_le B] + · nlinarith only [hc, ht] + + + +@[simp] theorem queryScaleDispatchWithWork_value (N b : ℕ) : + (queryScaleDispatchWithWork N b).1 = (dyadicScales N).idxOf b := by + simp only [queryScaleDispatchWithWork, queryNaturalIndexWithWork_value, dyadicScalesWithWork_value] + +theorem dyadicScales_size_bound (N b : ℕ) (hb : b ∈ dyadicScales N) : + Nat.size b ≤ Nat.size N + 1 := by + rw [← dyadicScalesWithWork_value N] at hb + simp only [dyadicScalesWithWork, arithmeticMapWithWork_value, List.mem_map] at hb + obtain ⟨e, he, rfl⟩ := hb + rw [powerTwoWord_value, Nat.size_pow] + have he' := List.mem_range.mp he + rw [Nat.size_eq_bits_len] at he' + omega + +theorem queryScaleDispatchWithWork_cost (N b B : ℕ) + (hN : Nat.size N ≤ B) (hb : Nat.size b ≤ B) : + (queryScaleDispatchWithWork N b).2 ≤ 20 * (B + 2) ^ 2 := by + have hs := dyadicScalesWithWork_cost N + have hl : (dyadicScalesWithWork N).1.length ≤ B + 1 := by + simp only [dyadicScalesWithWork, arithmeticMapWithWork_value, List.length_map, List.length_range] + rw [Nat.size_eq_bits_len] + omega + have hi := queryNaturalIndexWithWork_cost b (B + 1) (by omega) (dyadicScalesWithWork N).1 + (fun c hc => (dyadicScales_size_bound N c (by simpa only [dyadicScalesWithWork_value] using hc)).trans (by omega)) + change (dyadicScalesWithWork N).2 + (queryNaturalIndexWithWork b (dyadicScalesWithWork N).1).2 + + (dyadicScalesWithWork N).1.length + 2 ≤ _ + nlinarith only [hs, hi, hl, hN, Nat.zero_le B] + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryScalarGuardSpace.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryScalarGuardSpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..db832972f7d4d8642c0bf616d1d43e6948997988 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryScalarGuardSpace.lean @@ -0,0 +1,66 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryInitialGuardSpace +import OAI.Combinatorics.EditApproximation.Queries.QueryPhysicalScalarGuards +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation + + + +theorem queryNaturalIndexAllocation_le_work (a : ℕ) (xs : List ℕ) : + queryNaturalIndexAllocation a xs ≤ (queryNaturalIndexWithWork a xs).2 := by + induction xs with + | nil => exact Nat.zero_le _ + | cons b rest ih => + have he := naturalEqualAllocation_le_work a b + simp only [queryNaturalIndexAllocation, queryNaturalIndexWithWork] + split_ifs <;> dsimp only <;> omega + + + +theorem queryScaleDispatchAllocation_le_work (N b : ℕ) : + queryScaleDispatchAllocation N b ≤ (queryScaleDispatchWithWork N b).2 := by + have hd := dyadicScalesAllocation_le_work N + have hi := queryNaturalIndexAllocation_le_work b (dyadicScalesWithWork N).1 + unfold queryScaleDispatchAllocation queryScaleDispatchWithWork + dsimp only + omega + + + +theorem queryScalePresentAllocation_le_work (N b : ℕ) : + queryScalePresentAllocation N b ≤ (queryScalePresentWithWork N b).2 := by + have hd := queryScaleDispatchAllocation_le_work N b + have hc := bitCompareWithWork_input_cells (queryScaleDispatchWithWork N b).1.bits (max 1 N.bits.length).bits + unfold queryScalePresentAllocation queryScalePresentWithWork + dsimp only + change _ ≤ _ + (bitCompareWithWork (queryScaleDispatchWithWork N b).1.bits (max 1 N.bits.length).bits).2 + 2 + omega + + + +theorem queryCellValidAllocation_le_work (n exponent : ℕ) (cell : ℕ × ℕ) : + queryCellValidAllocation n exponent cell ≤ (queryCellValidWithWork n exponent cell).2 := by + have hm := binaryNaturalMulAllocation_le_work n (bitWordValue (powerTwoWord exponent)) + have hl := naturalWordLEAllocation_le_work cell.1.bits (binaryNaturalMulWithWork n (bitWordValue (powerTwoWord exponent))).1 + have hr := naturalWordLEAllocation_le_work cell.2.bits (binaryNaturalMulWithWork n (bitWordValue (powerTwoWord exponent))).1 + unfold queryCellValidAllocation queryCellValidWithWork + dsimp only + omega + + + +theorem queryRangeValidAllocation_le_work (B range : ℕ) : + queryRangeValidAllocation B range ≤ (queryRangeValidWithWork B range).2 := by + have hp := bitCompareWithWork_input_cells (0 : ℕ).bits range.bits + have hb := naturalWordLEAllocation_le_work range.bits B.bits + unfold queryRangeValidAllocation queryRangeValidWithWork + dsimp only + change _ ≤ (bitCompareWithWork (0 : ℕ).bits range.bits).2 + _ + 2 + omega + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryScalarReadSpace.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryScalarReadSpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..a70228a115fe0ff6093adc35c760bf8c435aa1b9 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryScalarReadSpace.lean @@ -0,0 +1,163 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryScalarGuardSpace +import OAI.Combinatorics.EditApproximation.Queries.QueryPhysicalReaderSpace +import OAI.Combinatorics.EditApproximation.Queries.QueryFamilyScalarReads +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation + +private theorem naturalPairWithWork_lower (a b : ℕ) : 4 ≤ (naturalPairWithWork a b).2 := by + unfold naturalPairWithWork + split_ifs <;> omega + +/-- Address-recurrence and pairing cells; source data and node paths are borrowed. -/ + + +theorem physicalScalarCodeAllocation_le_work {M J N n exponent F Q R B : ℕ} + (key : PhysicalScalarKey M J N n exponent F Q R B) : + physicalScalarCodeAllocation key ≤ (physicalScalarCodeWithWork key).2 := by + have onlineBound (d J a b c : ℕ) (ha : 4 ≤ a) (hb : 4 ≤ b) (hc : 4 ≤ c) : + 2 * d + J + 20 ≤ 3 * d + 1 + (2 * J + 1) + 3 + 8 + a + b + c + 2 := by + omega + have groupBound (d J a b c e f g : ℕ) + (ha : 4 ≤ a) (hb : 4 ≤ b) (hc : 4 ≤ c) (he : 4 ≤ e) (hf : 4 ≤ f) (hg : 4 ≤ g) : + 2 * d + J + 25 ≤ 3 * d + 1 + (2 * J + 1) + 3 + a + b + c + e + f + g + 3 := by + omega + rcases key with ⟨online | group, index⟩ + · have h1 := naturalPairWithWork_lower online.2.val.val index.val + have h2 := naturalPairWithWork_lower online.1.2.1.val (naturalPairWithWork online.2.val.val index.val).1 + have h3 := naturalPairWithWork_lower (physicalEntryCodeWithWork (online.1.1.val, online.1.2.2)).1 + (naturalPairWithWork online.1.2.1.val (naturalPairWithWork online.2.val.val index.val).1).1 + simp only [physicalScalarCodeAllocation, physicalScalarCodeWithWork, physicalEntryCodeWithWork, + physicalNodeCodeWithWork, treeLayerCodeWithWork_cost, parameterPowerWithWork_spec] at h3 ⊢ + exact onlineBound _ _ _ _ _ h1 h2 h3 + · have h1 := naturalPairWithWork_lower index.2.1.val index.2.2.val + have h2 := naturalPairWithWork_lower index.1.val (naturalPairWithWork index.2.1.val index.2.2.val).1 + have h3 := naturalPairWithWork_lower group.2.2.2.val + (naturalPairWithWork index.1.val (naturalPairWithWork index.2.1.val index.2.2.val).1).1 + have h4 := naturalPairWithWork_lower group.2.2.1.val + (naturalPairWithWork group.2.2.2.val (naturalPairWithWork index.1.val (naturalPairWithWork index.2.1.val index.2.2.val).1).1).1 + have h5 := naturalPairWithWork_lower group.2.1.val + (naturalPairWithWork group.2.2.1.val (naturalPairWithWork group.2.2.2.val + (naturalPairWithWork index.1.val (naturalPairWithWork index.2.1.val index.2.2.val).1).1).1).1 + have h6 := naturalPairWithWork_lower (physicalNodeCodeWithWork group.1.val).1 + (naturalPairWithWork group.2.1.val (naturalPairWithWork group.2.2.1.val + (naturalPairWithWork group.2.2.2.val (naturalPairWithWork index.1.val + (naturalPairWithWork index.2.1.val index.2.2.val).1).1).1).1).1 + simp only [physicalScalarCodeAllocation, physicalScalarCodeWithWork, + physicalNodeCodeWithWork, treeLayerCodeWithWork_cost, parameterPowerWithWork_spec] at h6 ⊢ + exact groupBound _ _ _ _ _ _ _ _ h1 h2 h3 h4 h5 h6 + +open BitQuery + +section Scalar +variable (M J N n exponent F Q R B : ℕ) + +def queryPhysicalScalarReadHeap (key : PhysicalScalarKey M J N n exponent F Q R B) : + Heap (queryPhysicalScalarRead M J N n exponent F Q R B key) := + Heap.chargeOf (physicalScalarCodeAllocation key + 1) + (Nat.add_le_add_right (physicalScalarCodeAllocation_le_work key) 1) (.read key _ fun word => .done word) + +private def groupHeapTransport (b c : ℕ) (h : b = c) + (actual : BitPhysicalGroupQueries M J N n exponent F Q R B b) + (heap : ∀ s j, Heap (actual s j)) : + ∀ s j, Heap ((Eq.mp (congrArg (BitPhysicalGroupQueries M J N n exponent F Q R B) h) actual) s j) := by + cases h + exact heap + +def queryPhysicalScalarGroupQueriesHeap (node : PhysicalInternalNode M J) (time : Fin R) + (b : ℕ) (cell : ℕ × ℕ) : + ∀ s j, Heap (queryPhysicalScalarGroupQueries M J N n exponent F Q R B node time b cell s j) := by + intro s j + refine (congrArg BitQuery.Heap (congrArg + (fun f : BitPhysicalGroupQueries M J N n exponent F Q R B b => f s j) + (queryPhysicalScalarGroupQueries.eq_1 M J N n exponent F Q R B node time b cell))).mpr ?_ + split + · rename_i hb + split + · rename_i hc + let key : PhysicalLocalGroupKey M J N n exponent := + (node, physicalScaleIndex N b ((queryScalePresentWithWork_value N b).mp hb), + ⟨cell.1, Nat.lt_succ_of_le ((queryCellValidWithWork_value n exponent cell).mp hc).1⟩, + ⟨cell.2, Nat.lt_succ_of_le ((queryCellValidWithWork_value n exponent cell).mp hc).2⟩) + exact groupHeapTransport M J N n exponent F Q R B _ _ + (physicalScaleIndex_get N b ((queryScalePresentWithWork_value N b).mp hb)) + (queryPhysicalScalarGroupQueriesAt M J N n exponent F Q R B key time) + (fun s j => (congrArg BitQuery.Heap + (queryPhysicalScalarGroupQueriesAt.eq_1 M J N n exponent F Q R B key time s j)).mpr + (queryPhysicalScalarReadHeap M J N n exponent F Q R B + ⟨Sum.inr key, ⟨time, ⟨s, j⟩⟩⟩)) s j + · exact .done _ + · exact .done _ + +def queryPhysicalScalarGroupReadHeap (node : PhysicalInternalNode M J) (time : Fin R) + (key : GroupScalarKey M F Q) : Heap (queryPhysicalScalarGroupRead M J N n exponent F Q R B node time key) := + Heap.chargeOf (queryScalePresentAllocation N key.1.1 + queryCellValidAllocation n exponent key.1.2) + (by have h1 := queryScalePresentAllocation_le_work N key.1.1 + have h2 := queryCellValidAllocation_le_work n exponent key.1.2 + omega) + (queryPhysicalScalarGroupQueriesHeap M J N n exponent F Q R B node time key.1.1 key.1.2 key.2.1 key.2.2) + +def queryPhysicalScalarOnlineReadHeap (node : PhysicalInternalNode M J) (time : Fin R) + (key : ℕ × TargetInterval n) (range : ℕ) : + Heap (queryPhysicalScalarOnlineRead M J N n exponent F Q R B node time key range) := by + refine (congrArg BitQuery.Heap + (queryPhysicalScalarOnlineRead.eq_1 M J N n exponent F Q R B node time key range)).mpr ?_ + refine BitQuery.Heap.chargeOf (queryScalePresentAllocation N key.1 + queryRangeValidAllocation B range) ?_ ?_ + · have h1 := queryScalePresentAllocation_le_work N key.1 + have h2 := queryRangeValidAllocation_le_work B range + omega + · split + · rename_i hb + split + · rename_i hr + exact queryPhysicalScalarReadHeap M J N n exponent F Q R B + ⟨.inl ((node, physicalScaleIndex N key.1 ((queryScalePresentWithWork_value N key.1).mp hb), key.2), + positiveDrawRangeOfLE B range ((queryRangeValidWithWork_value B range).mp hr).1 + ((queryRangeValidWithWork_value B range).mp hr).2), time⟩ + · exact .done _ + · exact .done _ + +end Scalar + +section Family +variable {α : Type*} {M J R : ℕ} (target : List α) + (N P F exponent H Q passes copies pass copy : ℕ) + + + +theorem queryFamilyTagAllocation_le_work + (scalar : PhysicalScalarKey M J N target.length exponent F Q R (localOnlineMassBound M P H)) : + queryFamilyTagAllocation target N P F exponent H Q passes copies pass copy scalar ≤ + (queryFamilyTagWithWork target N P F exponent H Q passes copies pass copy scalar).2 := by + let p := (queryFinOfNatWithWork (passes + 1) pass (Nat.succ_pos _)).1 + let c := (queryFinOfNatWithWork (copies + 1) copy (Nat.succ_pos _)).1 + have hp := binaryNaturalDivAllocation_le_work pass (passes + 1) + have hc := binaryNaturalDivAllocation_le_work copy (copies + 1) + have hs := physicalScalarCodeAllocation_le_work scalar + have hcp := naturalPairWithWork_lower c.val (physicalScalarCodeWithWork scalar).1 + have hpp := naturalPairWithWork_lower p.val (naturalPairWithWork c.val (physicalScalarCodeWithWork scalar).1).1 + unfold queryFamilyTagAllocation queryFamilyTagWithWork physicalFamilyCodeWithWork + dsimp only + dsimp only [p, c, queryFinOfNatWithWork] at hcp hpp ⊢ + omega + +def queryFamilyGroupReadHeap (node : PhysicalInternalNode M J) (time : Fin R) (key : GroupScalarKey M F Q) : + Heap (queryFamilyGroupRead target N P F exponent H Q passes copies pass copy node time key) := + (queryPhysicalScalarGroupReadHeap M J N target.length exponent F Q R (localOnlineMassBound M P H) node time key).mapKeysWithWork + _ (queryFamilyTagAllocation target N P F exponent H Q passes copies pass copy) + (queryFamilyTagAllocation_le_work target N P F exponent H Q passes copies pass copy) + +def queryFamilyOnlineReadHeap (node : PhysicalInternalNode M J) (time : Fin R) + (key : ℕ × TargetInterval target.length) (range : ℕ) : + Heap (queryFamilyOnlineRead target N P F exponent H Q passes copies pass copy node time key range) := + (queryPhysicalScalarOnlineReadHeap M J N target.length exponent F Q R (localOnlineMassBound M P H) node time key range).mapKeysWithWork + _ (queryFamilyTagAllocation target N P F exponent H Q passes copies pass copy) + (queryFamilyTagAllocation_le_work target N P F exponent H Q passes copies pass copy) + +end Family +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryScopedOrder.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryScopedOrder.lean new file mode 100644 index 0000000000000000000000000000000000000000..8dc028c7211ed70716a0a0991d598a37227d980f --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryScopedOrder.lean @@ -0,0 +1,127 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryOrderBounds + +namespace OAI + +/-! Sorting costs only require bounded comparisons between keys actually +present in the input. This is needed for the natural-valued history time. -/ + +namespace EditApproximation + +theorem memberByWithWork_cost_on {α : Type*} (P : α → Prop) + (equal : α → α → Bool × ℕ) (C : ℕ) + (hC : ∀ a, P a → ∀ b, P b → (equal a b).2 ≤ C) + (a : α) (ha : P a) (xs : List α) (hx : ∀ b ∈ xs, P b) : + (memberByWithWork equal a xs).2 ≤ 1 + xs.length * (C + 1) := by + induction xs with + | nil => simp only [memberByWithWork, List.length_nil, Nat.zero_mul, Nat.add_zero, le_refl] + | cons b xs ih => + have h := hC a ha b (hx b (by simp)) + have ht := ih (fun c hc => hx c (List.mem_cons_of_mem b hc)) + change _ + _ + 1 ≤ _ + simp only [List.length_cons, Nat.add_mul, Nat.one_mul] + omega + +theorem queryEraseLoopWithWork_cost_on {α : Type*} (P : α → Prop) + (equal : α → α → Bool × ℕ) (C : ℕ) + (hC : ∀ a, P a → ∀ b, P b → (equal a b).2 ≤ C) + (xs seen : List α) (hx : ∀ a ∈ xs, P a) (hs : ∀ a ∈ seen, P a) : + (queryEraseLoopWithWork equal xs seen).2 ≤ + (xs.length + 1) * (xs.length + seen.length + 1) * (C + 4) := by + induction xs generalizing seen with + | nil => + simp only [queryEraseLoopWithWork, List.length_nil, zero_add, one_mul] + nlinarith + | cons a xs ih => + have ha := hx a (by simp) + have hm := memberByWithWork_cost_on P equal C hC a ha seen hs + let next := if (memberByWithWork equal a seen).1 then seen else a :: seen + have hn : ∀ b ∈ next, P b := by + intro b hb + dsimp only [next] at hb + split_ifs at hb + · exact hs b hb + · rcases List.mem_cons.mp hb with rfl | hb + · exact ha + · exact hs b hb + have hl : next.length ≤ seen.length + 1 := by + dsimp only [next] + split <;> (try simp only [List.length_cons]) <;> omega + have hi := ih next (fun b hb => hx b (List.mem_cons_of_mem a hb)) hn + have hh : (queryEraseLoopWithWork equal xs next).2 ≤ + (xs.length + 1) * (xs.length + (seen.length + 1) + 1) * (C + 4) := + hi.trans (Nat.mul_le_mul_right _ (Nat.mul_le_mul_left _ (by omega))) + change (memberByWithWork equal a seen).2 + (queryEraseLoopWithWork equal xs next).2 + 2 ≤ _ + simp only [List.length_cons] + nlinarith only [hm, hh, Nat.zero_le xs.length, Nat.zero_le seen.length, Nat.zero_le C] + +theorem queryEraseWithWork_cost_on {α : Type*} (P : α → Prop) + (equal : α → α → Bool × ℕ) (C : ℕ) + (hC : ∀ a, P a → ∀ b, P b → (equal a b).2 ≤ C) + (xs : List α) (hx : ∀ a ∈ xs, P a) : + (queryEraseWithWork equal xs).2 ≤ (xs.length + 1) ^ 2 * (C + 4) := by + simpa only [queryEraseWithWork, List.length_nil, Nat.add_zero, pow_two] using + queryEraseLoopWithWork_cost_on P equal C hC xs [] hx (by simp) + +theorem queryInsertWithWork_cost_on {α : Type*} (P : α → Prop) + (le : α → α → Bool × ℕ) (C : ℕ) + (hC : ∀ a, P a → ∀ b, P b → (le a b).2 ≤ C) + (a : α) (ha : P a) (xs : List α) (hx : ∀ b ∈ xs, P b) : + (queryInsertWithWork le a xs).2 ≤ (xs.length + 1) * (C + 2) := by + induction xs with + | nil => simp only [queryInsertWithWork, List.length_nil]; omega + | cons b xs ih => + have h := hC a ha b (hx b (by simp)) + have ht := ih (fun c hc => hx c (List.mem_cons_of_mem b hc)) + simp only [queryInsertWithWork, List.length_cons] + split <;> dsimp only + · nlinarith only [h, Nat.zero_le xs.length, Nat.zero_le C] + · nlinarith only [h, ht] + +theorem querySortWithWork_cost_on {α : Type*} (P : α → Prop) + (r : α → α → Prop) [DecidableRel r] + (le : α → α → Bool × ℕ) (hle : ∀ a b, (le a b).1 = decide (r a b)) + (C : ℕ) (hC : ∀ a, P a → ∀ b, P b → (le a b).2 ≤ C) + (xs : List α) (hx : ∀ a ∈ xs, P a) : + (querySortWithWork le xs).2 ≤ (xs.length + 1) ^ 2 * (C + 3) := by + induction xs with + | nil => simp only [querySortWithWork, List.length_nil]; omega + | cons a xs ih => + have ht := ih (fun b hb => hx b (List.mem_cons_of_mem a hb)) + have hs : ∀ b ∈ (querySortWithWork le xs).1, P b := by + intro b hb + rw [querySortWithWork_value r le hle, List.mem_insertionSort] at hb + exact hx b (List.mem_cons_of_mem a hb) + have hi := queryInsertWithWork_cost_on P le C hC a (hx a (by simp)) + (querySortWithWork le xs).1 hs + have hl : (querySortWithWork le xs).1.length = xs.length := by + rw [querySortWithWork_value r le hle, List.length_insertionSort] + rw [hl] at hi + change (querySortWithWork le xs).2 + _ + 1 ≤ _ + simp only [List.length_cons] + nlinarith only [ht, hi, Nat.zero_le xs.length, Nat.zero_le C] + +theorem queryOrderedInputsWithWork_cost_on {α : Type*} [DecidableEq α] + (P : α → Prop) (encode : α → ℕ) (equal le : α → α → Bool × ℕ) + (heq : ∀ a b, (equal a b).1 = true ↔ a = b) + (hle : ∀ a b, (le a b).1 = decide (encode a ≤ encode b)) + (C D : ℕ) (hequal : ∀ a, P a → ∀ b, P b → (equal a b).2 ≤ C) + (horder : ∀ a, P a → ∀ b, P b → (le a b).2 ≤ D) + (xs : List α) (hx : ∀ a ∈ xs, P a) : + (queryOrderedInputsWithWork equal le xs).2 ≤ (xs.length + 1) ^ 2 * (C + D + 8) := by + have he := queryEraseWithWork_cost_on P equal C hequal xs hx + have hu : ∀ a ∈ (queryEraseWithWork equal xs).1, P a := by + intro a ha + rw [queryEraseWithWork_value equal heq, List.mem_eraseDups] at ha + exact hx a ha + have hs := querySortWithWork_cost_on P (fun a b => encode a ≤ encode b) + le hle D horder (queryEraseWithWork equal xs).1 hu + have hl := queryEraseWithWork_length equal xs + have hp : ((queryEraseWithWork equal xs).1.length + 1) ^ 2 ≤ (xs.length + 1) ^ 2 := by + gcongr + have hb := hs.trans (Nat.mul_le_mul_right (D + 3) hp) + change (queryEraseWithWork equal xs).2 + _ + 1 ≤ _ + nlinarith only [he, hb, Nat.zero_le C, Nat.zero_le D, Nat.zero_le xs.length] + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryScopedSourceCost.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryScopedSourceCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..7f557699770ed407413198d5a75b2d5622e5fee8 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryScopedSourceCost.lean @@ -0,0 +1,91 @@ +import OAI.Combinatorics.EditApproximation.Queries.QuerySourceKeyWidths +import OAI.Combinatorics.EditApproximation.Queries.QueryOnlineKeyCost + +namespace OAI + +/-! The source ports are bounded only at keys visited by the adaptive local +loops. Unused natural-number coordinates require no uniform size assumption. -/ + +namespace EditApproximation.BinaryFraction + +theorem queryGroupKeysWithWork_mem_of_guard {n : ℕ} (N F exponent : ℕ) + (a value : BinaryFraction) (q : TargetInterval n) (eb : ℕ) + (heb : eb ∈ List.range (max 1 N.bits.length)) + (hg : (refinementScaleGuardWithWork F (2 ^ eb) a value).1 = true) + (cell : ℕ × ℕ) + (hc : cell ∈ (targetCellsWithWork + (canonicalMulWithWork (inversePowerTwo exponent) (nat (2 ^ eb))).1 + (bitWordValue (naturalCeilingWithWork value).1) q).1) : + (2 ^ eb, cell) ∈ (queryGroupKeysWithWork N F exponent a value q).1 := by + have he : eb ∈ (queryExponentsWithWork N F a value).1 := by + simp only [queryExponentsWithWork, filterWithWork_value, List.mem_filter] + exact ⟨heb, hg⟩ + have hs : 2 ^ eb ∈ (queryScalesWithWork N F a value).1 := by + simp only [queryScalesWithWork, arithmeticMapWithWork_value, List.mem_map] + exact ⟨eb, he, powerTwoWord_value eb⟩ + simp only [queryGroupKeysWithWork, arithmeticFlatMapWithWork_value, + arithmeticMapWithWork_value, List.mem_flatMap, List.mem_map] + exact ⟨2 ^ eb, hs, cell, hc, rfl⟩ + +def queryGroupBufferReadBudget (count B V : ℕ) : ℕ := + count * (40 * (40 * B + 500) + 15) + 200 * (V + 1) ^ 2 + + 30 * (V + 1) * (V + (40 * B + 500) + 1) + 4 + +theorem queryGroupDrawReadWithWork_scoped_cost {n M N F Q : ℕ} [NeZero M] + (exponent eM eF B V : ℕ) (hMdef : M = 2 ^ eM) (hFdef : F = 2 ^ eF) + (a value : BinaryFraction) (q : TargetInterval n) (words : List BinaryFraction) + (hB : 7 ≤ B) (hN : Nat.size N ≤ B) (hF : Nat.size F + 2 ≤ B) + (hM : Nat.size M ≤ B) (hes : 7 + eM + eF ≤ B) (he : exponent + 1 ≤ B) + (hn : Nat.size n ≤ B) (ha : a.width ≤ B) (hv : value.width ≤ B) (hw : 0 ≤ value.value) + (hV : 2 ≤ V) (hwords : ∀ v ∈ words, v.width ≤ V) + (eb : ℕ) (heb : eb ∈ List.range (max 1 N.bits.length)) + (hg : (refinementScaleGuardWithWork F (2 ^ eb) a value).1 = true) + (cell : ℕ × ℕ) + (hc : cell ∈ (targetCellsWithWork + (canonicalMulWithWork (inversePowerTwo exponent) (nat (2 ^ eb))).1 + (bitWordValue (naturalCeilingWithWork value).1) q).1) + (scale : Fin (groupDyadicScales M (2 ^ eb) F).length) + (sample : Fin (groupSampleCount M Q (2 ^ eb) (groupDyadicScaleAt M (2 ^ eb) F scale))) : + let keys := (queryGroupSourceKeysWithWork M N F Q exponent eM eF hMdef hFdef a value q).1 + (queryGroupDrawReadWithWork keys words (2 ^ eb) cell scale sample).2 ≤ + queryGroupBufferReadBudget keys.length B V := by + dsimp only + apply queryGroupDrawReadWithWork_cost _ words _ cell scale sample (40 * B + 500) V hV + (by omega) + (queryGroupSourceKeysWithWork_width M N F Q exponent eM eF B hMdef hFdef a value q + hB hN hF hM hes he hn ha hv hw) _ hwords + apply queryGroupKeySize_bound M N F Q exponent eM eF B hMdef hFdef a value q + hB hN hF hM hes he hn ha hv hw + exact queryGroupKeysWithWork_mem_of_guard N F exponent a value q eb heb hg cell hc + +theorem queryOnlineKeysWithWork_scale {n : ℕ} (N P F B : ℕ) (hP : 0 < P) + (a value : BinaryFraction) (q : TargetInterval n) (hN : Nat.size N ≤ B) (hF : 1 ≤ F) + (key : ℕ × TargetInterval n) (hk : key ∈ (queryOnlineKeysWithWork N P F hP a value q).1) : + Nat.size key.1 ≤ B + 1 := by + simp only [queryOnlineKeysWithWork, arithmeticMapWithWork_value, List.mem_map] at hk + obtain ⟨b, hb, rfl⟩ := hk + exact (queryScalesWithWork_member N F B a value hN hF b hb).1 + +def queryOnlineBufferReadBudget (count B V : ℕ) : ℕ := + count * (24 * (B + 1) + 9) + 200 * (V + 1) ^ 2 + 2 + +theorem queryOnlineIntegerReadWithWork_scoped_cost {n : ℕ} (N P F B V : ℕ) + (hP : 0 < P) (a value : BinaryFraction) (q : TargetInterval n) (words : List BinaryFraction) + (hN : Nat.size N ≤ B) (hF : 1 ≤ F) (hn : Nat.size n ≤ B) + (hV : 2 ≤ V) (hwords : ∀ v ∈ words, v.width ≤ V) + (e : ℕ) (he : e ∈ (queryExponentsWithWork N F a value).1) : + let keys := (queryOnlineKeysWithWork N P F hP a value q).1 + let center := (roundStateWithWork (bitWordValue (seedGridSpacingWithWork (2 ^ e) P).1) + (seedGridSpacingWithWork_pos (2 ^ e) P hP) q).1 + (queryOnlineIntegerReadWithWork keys words (2 ^ e) center).2 ≤ + queryOnlineBufferReadBudget keys.length B V := by + have hs : 2 ^ e ∈ (queryScalesWithWork N F a value).1 := by + simp only [queryScalesWithWork, arithmeticMapWithWork_value, List.mem_map] + exact ⟨e, he, powerTwoWord_value e⟩ + apply queryOnlineIntegerReadWithWork_cost _ words _ _ (B + 1) V hV (by omega) + (queryScalesWithWork_member N F B a value hN hF _ hs).1 + (queryOnlineKeysWithWork_scale N P F B hP a value q hN hF) hwords + +end EditApproximation.BinaryFraction + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QuerySelectorCost.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QuerySelectorCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..f09d28e775032b98b974d6f3aa2aadeb1ccea92f --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QuerySelectorCost.lean @@ -0,0 +1,82 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinarySourceSelectorBounds +import OAI.Combinatorics.EditApproximation.Queries.QueryReadBoundIrrelevance + +namespace OAI + +/-! Selector bounds for the actual separate history and shared-current +buffers. The original child-reader budget is preserved in the program. -/ + +namespace EditApproximation.BinaryFraction +section Selectors +variable {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (N P F exponent H Q eM eF B E S : ℕ) + (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) + (tau a eta kappa delta : BinaryFraction) (t : ℕ) + (parentInitial : TargetInterval target.length → BinaryFraction × ℕ) + (child initial : Fin M → TargetInterval target.length → BinaryFraction × ℕ) + (R U : ℕ) (hc : ∀ i r, (child i r).2 ≤ R) (hi : ∀ i r, (initial i r).2 ≤ R) + (hcU : ∀ i r, (child i r).2 ≤ U) (hiU : ∀ i r, (initial i r).2 ≤ U) + (hp : ∀ r, (parentInitial r).2 ≤ U) + (draw : CountedCellGroupDraws M F Q) + (integer : ℕ → TargetInterval target.length → ℕ × ℕ) + (earlierKeys : List (Fin M × ℕ × TargetInterval target.length)) (earlierWords : List BinaryFraction) + (sharedKeys : List (Fin M × TargetInterval target.length)) (sharedWords : List BinaryFraction) + (q : TargetInterval target.length) + (hb : PreparedKernelInputBounds (nx := source.length) N P F exponent H Q eM eF B E S (t - 1) + tau a eta kappa delta (fun r => (parentInitial r).1) + (fun i r => (child i r).1) (fun i r => (initial i r).1) + (fun input => (queryHistoryReadWithWork earlierKeys earlierWords (t - 1) input).1) + (fun input => (queryChildReadWithWork sharedKeys sharedWords input.1 input.2).1) + (fun s input => (queryHistoryReadWithWork earlierKeys earlierWords s input).1) + (fun b r => (integer b r).1)) + +include hb hp hcU hiU in +theorem queryGroupSelectWithWork_bounds (hPdyadic : ∃ j : ℕ, P = 2 ^ j) + (hshared : ∀ i r, (queryChildReadWithWork sharedKeys sharedWords i r).2 ≤ U) (D : ℕ) + (hd : ∀ eb ∈ List.range (max 1 N.bits.length), + (refinementScaleGuardWithWork F (2 ^ eb) a (parentInitial q).1).1 = true → + ∀ cell ∈ (targetCellsWithWork + (canonicalMulWithWork (inversePowerTwo exponent) (nat (2 ^ eb))).1 + (bitWordValue (naturalCeilingWithWork (parentInitial q).1).1) q).1, + ∀ scale sample, (draw (2 ^ eb) cell scale sample).2 ≤ D) : + let selected := queryGroupSelectWithWork source target parent N P F exponent Q eM eF hP hM hF + tau a parentInitial child initial R hc hi draw sharedKeys sharedWords q + selected.1.length ≤ (B + 1) * ((32 * F + 2) * 2 ^ exponent + 2) ^ 2 ∧ + selected.2 ≤ preparedLocalGroupsBitBudget N M P F exponent eM eF B * tableReadFactor U * (D + 4) := by + have h := preparedLocalCellGroupsSourceWithWork_bounds source target parent N P F exponent H Q eM eF B E S + hP hM hF tau a eta kappa delta parentInitial child initial + (queryHistoryReadWithWork earlierKeys earlierWords (t - 1)) + (fun input => queryChildReadWithWork sharedKeys sharedWords input.1 input.2) + (queryHistoryReadWithWork earlierKeys earlierWords) U hcU hiU (t - 1) draw integer q hb hp hPdyadic + (fun input => hshared input.1 input.2) D hd + rw [queryGroupSelectWithWork_readBound_irrel source target parent N P F exponent Q eM eF hP hM hF + tau a parentInitial child initial R U hc hi hcU hiU draw sharedKeys sharedWords q] + simpa only [queryGroupSelectWithWork] using h + +include hb hp hcU hiU hM in +theorem queryOnlineSelectWithWork_bounds + (hh : ∀ s ≤ t - 1 + 1, ∀ input, (queryHistoryReadWithWork earlierKeys earlierWords s input).2 ≤ U) + (D : ℕ) + (hd : ∀ e ∈ (queryExponentsWithWork N F a (parentInitial q).1).1, + (centerEligibilityWithWork (2 ^ e) F a + (parentInitial (roundStateWithWork (bitWordValue (seedGridSpacingWithWork (2 ^ e) P).1) + (seedGridSpacingWithWork_pos (2 ^ e) P hP) q).1).1).1 = true → + (integer (2 ^ e) (roundStateWithWork (bitWordValue (seedGridSpacingWithWork (2 ^ e) P).1) + (seedGridSpacingWithWork_pos (2 ^ e) P hP) q).1).2 ≤ D) : + let selected := queryOnlineSelectWithWork source target parent N P F exponent H hP tau a eta kappa + parentInitial child initial R hc hi t integer earlierKeys earlierWords q + selected.1.length ≤ B + 1 ∧ + selected.2 ≤ preparedLocalOnlineBitBudget M P B S * tableReadFactor U * (D + 4) := by + have h := preparedLocalOnlineActionsSourceWithWork_bounds source target parent N P F exponent H Q eM eF B E S + hP hM tau a eta kappa delta parentInitial child initial + (queryHistoryReadWithWork earlierKeys earlierWords (t - 1)) + (fun input => queryChildReadWithWork sharedKeys sharedWords input.1 input.2) + (queryHistoryReadWithWork earlierKeys earlierWords) U hcU hiU (t - 1) integer q hb hp hh D hd + rw [queryOnlineSelectWithWork_readBound_irrel source target parent N P F exponent H hP + tau a eta kappa parentInitial child initial R U hc hi hcU hiU t integer earlierKeys earlierWords q] + simpa only [queryOnlineSelectWithWork] using h + +end Selectors +end EditApproximation.BinaryFraction + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QuerySelectorGeometry.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QuerySelectorGeometry.lean new file mode 100644 index 0000000000000000000000000000000000000000..9ba8be9be68f6bc17bb41214e43448815578da3a --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QuerySelectorGeometry.lean @@ -0,0 +1,60 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryLocalSelectors +import OAI.Combinatorics.EditApproximation.Binary.BinaryPreparedActionStorage +import OAI.Combinatorics.EditApproximation.Binary.BinaryPreparedListBounds + +namespace OAI + +namespace EditApproximation.BinaryFraction +section Selectors +variable {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (N P F exponent H Q eM eF : ℕ) + (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) + (tau a eta kappa : BinaryFraction) + (parentInitial : TargetInterval target.length → BinaryFraction × ℕ) + (child initial : Fin M → TargetInterval target.length → BinaryFraction × ℕ) + (R : ℕ) (hc : ∀ i r, (child i r).2 ≤ R) (hi : ∀ i r, (initial i r).2 ≤ R) + +theorem queryGroupSelectWithWork_geometry (draw : CountedCellGroupDraws M F Q) + (keys : List (Fin M × TargetInterval target.length)) (words : List BinaryFraction) + (q : TargetInterval target.length) (B : ℕ) (hN : Nat.size N ≤ B) + (hn : Nat.size target.length + 2 ≤ B) (hw : 0 ≤ (parentInitial q).1.value) : + let selected := queryGroupSelectWithWork source target parent N P F exponent Q eM eF hP hM hF + tau a parentInitial child initial R hc hi draw keys words q + selected.1.length ≤ (B + 1) * ((32 * F + 2) * 2 ^ exponent + 2) ^ 2 ∧ + ∀ action ∈ selected.1, action.connection.width ≤ connectionWordBudget M B := by + have hv := preparedLocalCellGroupsSourceWithWork_semantic_value source target parent P F exponent Q + eM eF hM hF hP tau a parentInitial child initial (queryChildReadWithWork keys words) R hc hi N draw q + have hl := preparedLocalCellGroupsWithWork_length_le source target parent N P F exponent Q eM eF B + hM hF hP tau a (fun r => (parentInitial r).1) (fun i r => (child i r).1) + (fun i r => (initial i r).1) (fun i r => (queryChildReadWithWork keys words i r).1) + (fun b cell scale sample => (draw b cell scale sample).1) q hN hw + have hc' := preparedLocalCellGroupsWithWork_connection source target parent N P F exponent Q eM eF + hM hF hP tau a (fun r => (parentInitial r).1) (fun i r => (child i r).1) + (fun i r => (initial i r).1) (fun i r => (queryChildReadWithWork keys words i r).1) + (fun b cell scale sample => (draw b cell scale sample).1) q B hn + simpa only [queryGroupSelectWithWork, hv] using And.intro hl hc' + +theorem queryOnlineSelectWithWork_geometry (t : ℕ) + (integer : ℕ → TargetInterval target.length → ℕ × ℕ) + (keys : List (Fin M × ℕ × TargetInterval target.length)) (words : List BinaryFraction) + (q : TargetInterval target.length) (B : ℕ) (hN : Nat.size N ≤ B) : + let selected := queryOnlineSelectWithWork source target parent N P F exponent H hP tau a eta kappa + parentInitial child initial R hc hi t integer keys words q + selected.1.length ≤ B + 1 ∧ ∀ action ∈ selected.1, action.connection = zero := by + have hv := preparedLocalOnlineActionsSourceWithWork_semantic_value source target parent P F exponent H + hP tau a eta kappa parentInitial child initial (queryHistoryReadWithWork keys words) R hc hi + (t - 1) integer N q + have hl := preparedLocalOnlineActionsWithWork_length_le source target parent N P F exponent H B hP + tau a eta kappa (fun r => (parentInitial r).1) (fun i r => (child i r).1) + (fun i r => (initial i r).1) (fun s input => (queryHistoryReadWithWork keys words s input).1) + (t - 1) (fun b r => (integer b r).1) q hN + have hc' := preparedLocalOnlineActionsWithWork_connection source target parent N P F exponent H hP + tau a eta kappa (fun r => (parentInitial r).1) (fun i r => (child i r).1) + (fun i r => (initial i r).1) (fun s input => (queryHistoryReadWithWork keys words s input).1) + (t - 1) (fun b r => (integer b r).1) q + simpa only [queryOnlineSelectWithWork, hv] using And.intro hl hc' + +end Selectors +end EditApproximation.BinaryFraction + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QuerySemanticRestriction.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QuerySemanticRestriction.lean new file mode 100644 index 0000000000000000000000000000000000000000..b2b8b6c922d35005124613a522c438b1c746d9fe --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QuerySemanticRestriction.lean @@ -0,0 +1,58 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryBoundedWork +import OAI.Combinatorics.EditApproximation.Queries.QueryHistorySemantic + +namespace OAI + +namespace EditApproximation + +theorem queryRestrictedPhysicalOracle_nonneg {σ : Type*} {M J n : ℕ} (passes copies T S : ℕ) + (parent : {r : PhysicalTableRequest M J n // r.Bounded passes copies T S}) + (oracle : QueryBoundedChild (σ := σ) passes copies T S parent → BinaryFraction) + (hn : ∀ key, 0 ≤ (oracle key).value) + (key : QueryPhysicalChild (σ := σ) passes copies T S parent) : + 0 ≤ (queryRestrictedPhysicalOracle passes copies T S parent oracle key).value := by + unfold queryRestrictedPhysicalOracle BitQuery.restrictedOracle + split + · exact hn _ + · simp only [BinaryFraction.nat_value, Nat.cast_zero, le_refl] + +section History +variable {σ α : Type*} [DecidableEq α] {M J R : ℕ} [NeZero R] + (source target : List α) (N P F exponent H Q T S copies : ℕ) + (factor : ℕ → ℚ) (multiplier : ℕ → ℕ) (tau eta kappa delta : ℚ) + (group : ℕ → ℕ → PhysicalInternalNode M J → Fin R → CellGroupDraws M F Q) + (integer : ℕ → ℕ → PhysicalInternalNode M J → Fin R → ℕ → TargetInterval target.length → ℕ) + (initial : PhysicalEntry M J target.length → ℕ) + +local notation "requestValue" => localRequestValue source target N P F exponent H Q T S copies + factor multiplier tau eta kappa delta group integer initial + +theorem queryRestrictedPhysicalOracle_history_bound + (passes pass copy t : ℕ) (ht : 0 < t) (htS : t ≤ S) + (hpass : pass < passes) (hcopy : copy < copies) (hdelta : 0 ≤ delta) + (node : PhysicalNode M J) (hbelow : node.1.val < J) (q : TargetInterval target.length) + (parent : {r : PhysicalTableRequest M J target.length // r.Bounded passes copies T S}) + (heq : parent.val = PhysicalTableRequest.refinement pass copy node T t q) + (oracle : QueryBoundedChild (σ := σ) passes copies T S parent → BinaryFraction) + (hread : ∀ key, (oracle (Sum.inr key)).value = requestValue key.val.val) + (input : Fin M × ℕ × TargetInterval target.length) : + let rawOracle := fun child : {r : PhysicalTableRequest M J target.length // r.combinedRank T S < + (PhysicalTableRequest.refinement pass copy node T t q).combinedRank T S} => + queryRestrictedPhysicalOracle passes copies T S parent oracle + (Sum.inr ⟨child.val, by rw [heq]; exact child.property⟩) + ((queryPhysicalEarlierRead copies pass copy T S t node hbelow q input).value rawOracle).value ≤ + ((queryPhysicalWarmupRead copies pass copy T S t ht node q + (physicalChild node hbelow input.1) (by change node.1.val ≤ node.1.val + 1; omega) + 0 (Nat.zero_le T) input.2.2).value rawOracle).value := by + dsimp only + apply queryPhysicalEarlierRead_history_bound source target N P F exponent H Q T S copies + factor multiplier tau eta kappa delta group integer initial passes pass copy t ht htS + hpass hcopy hdelta node hbelow q _ _ input + intro child hb + rw [queryRestrictedPhysicalOracle_table passes copies T S parent oracle _ hb] + exact hread _ + +end History +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QuerySharedCellCost.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QuerySharedCellCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..bc29cd97fa0df20ecbd49ab3e4394ed2dfba8bdf --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QuerySharedCellCost.lean @@ -0,0 +1,97 @@ +import OAI.Combinatorics.EditApproximation.Queries.QuerySharedInputs +import OAI.Combinatorics.EditApproximation.Queries.QueryGroupInputCost + +namespace OAI + +namespace EditApproximation.BinaryFraction + +def querySharedCellInputsLength (M exponent eM eF : ℕ) : ℕ := + (7 + eM + eF) * queryGroupInputsLength M exponent + +def querySharedCellInputsBitBudget (M exponent eM eb eF B R : ℕ) : ℕ := + let L := 7 + eM + eF + groupScalesBitBudget eM eb eF + 4 * L + + L * (queryGroupInputsBitBudget M exponent B R + L + queryGroupInputsLength M exponent + 4) + eb + 4 + +theorem querySharedCellInputsBitBudget_mono_eb (M exponent eM eb eb' eF B R : ℕ) (he : eb ≤ eb') : + querySharedCellInputsBitBudget M exponent eM eb eF B R ≤ + querySharedCellInputsBitBudget M exponent eM eb' eF B R := by + unfold querySharedCellInputsBitBudget groupScalesBitBudget + dsimp only + gcongr + exact Nat.size_le_size he + +theorem querySharedCellInputsWithWork_bounds {nx ny : ℕ} (M F Q eM eb eF : ℕ) + (hMdef : M = 2 ^ eM) (hFdef : F = 2 ^ eF) (parent : TargetInterval nx) + (exponent B R : ℕ) (cell : ℕ × ℕ) + (draw : ∀ scale : Fin (groupDyadicScales M (2 ^ eb) F).length, + Fin (groupSampleCount M Q (2 ^ eb) (groupDyadicScaleAt M (2 ^ eb) F scale)) → Fin M × ℕ) + (hB : 4 ≤ B) (hnx : Nat.size nx ≤ B) (hny : Nat.size ny ≤ B) + (hM : Nat.size M + 2 ≤ B) (hQ : Nat.size Q + 2 ≤ B) + (heb : eb + 3 ≤ B) (hsb : eM + eb + eF + 7 ≤ B) + (hc : Nat.size cell.1 ≤ B) (he : exponent + 1 ≤ B) + (hR : ∀ scale sample, (draw scale sample).2 ≤ R) : + (querySharedCellInputsWithWork (ny := ny) M F Q eM eb eF hMdef hFdef parent exponent cell draw).1.length ≤ + querySharedCellInputsLength M exponent eM eF ∧ + (querySharedCellInputsWithWork (ny := ny) M F Q eM eb eF hMdef hFdef parent exponent cell draw).2 ≤ + querySharedCellInputsBitBudget M exponent eM eb eF B R := by + let b := 2 ^ eb + let scales := groupScalesWithWork eM eb eF + have hs : scales.1.map value = groupDyadicScales M b F := by + simpa only [nat_value] using computedGroupScales_value M b F eM eb eF hMdef rfl hFdef + have hlen : scales.1.length = (groupDyadicScales M b F).length := by + simpa only [List.length_map] using congrArg List.length hs + let indices := queryFinRange scales.1.length (groupDyadicScales M b F).length hlen + let run := fun scale : Fin (groupDyadicScales M b F).length => + let word := queryScaleAt scales.1 (groupDyadicScales M b F) hs scale + let hv : word.value = groupDyadicScaleAt M b F scale := queryGroupScaleAt_value M b F _ hs scale + let states := queryGroupInputsTransportWithWork (ny := ny) parent b exponent Q cell word + (groupDyadicScaleAt M b F scale) hv (draw scale) + (states.1, states.2 + scales.1.length + 1) + have hslen : scales.1.length = 7 + eM + eF := groupScalesWithWork_length eM eb eF + have hilen : indices.length = 7 + eM + eF := by + dsimp only [indices] + rw [queryFinRange_value, List.length_finRange, ← hlen, hslen] + have hscales := groupScalesWithWork_bounds eM eb eF + have hMpos : 0 < M := by rw [hMdef]; exact Nat.two_pow_pos _ + have hFpos : 0 < F := by rw [hFdef]; exact Nat.two_pow_pos _ + have hrun (scale : Fin (groupDyadicScales M b F).length) : + (run scale).1.length ≤ queryGroupInputsLength M exponent ∧ + (run scale).2 ≤ queryGroupInputsBitBudget M exponent B R + (7 + eM + eF) + 1 := by + let word := queryScaleAt scales.1 (groupDyadicScales M b F) hs scale + have hw : word.width ≤ B := (hscales.1 _ (List.getElem_mem _)).trans hsb + have hmem : word.value ∈ groupDyadicScales M b F := by + rw [← hs] + exact List.mem_map.mpr ⟨word, List.getElem_mem _, rfl⟩ + have hp : 0 < word.value := groupDyadicScales_pos hmem + have hf : (b : ℚ) / M ≤ word.value := groupDyadicScales_lower hMpos (Nat.two_pow_pos _) hFpos word.value hmem + have hr := queryGroupInputsWithWork_bounds (ny := ny) parent b exponent Q B R cell word + (fun sample => draw scale (Fin.cast (congrArg (groupSampleCount M Q b) + (queryGroupScaleAt_value M b F _ hs scale)) sample)) hB hMpos hnx hny hM hQ + (by dsimp only [b]; rw [Nat.size_pow]; omega) hc he hw hp.le hf + (fun sample => hR scale _) + simpa only [run, word, queryGroupInputsTransportWithWork, hslen] using + And.intro hr.1 (Nat.add_le_add_right (Nat.add_le_add_right hr.2 scales.1.length) 1) + have hl := arithmeticFlatMapWithWork_length run indices (queryGroupInputsLength M exponent) + (fun scale _ => (hrun scale).1) + have hw := arithmeticFlatMapWithWork_cost run indices + (queryGroupInputsBitBudget M exponent B R + (7 + eM + eF) + 1) + (queryGroupInputsLength M exponent) (fun scale _ => (hrun scale).2) (fun scale _ => (hrun scale).1) + rw [hilen] at hl hw + rw [show queryGroupInputsBitBudget M exponent B R + (7 + eM + eF) + 1 + + queryGroupInputsLength M exponent + 3 = queryGroupInputsBitBudget M exponent B R + + (7 + eM + eF) + queryGroupInputsLength M exponent + 4 by omega] at hw + have hinputsCost : scales.2 + 4 * scales.1.length + + (arithmeticFlatMapWithWork run indices).2 + eb + 4 ≤ + querySharedCellInputsBitBudget M exponent eM eb eF B R := by + rw [hslen] + have hsc : scales.2 ≤ groupScalesBitBudget eM eb eF := hscales.2 + simpa only [querySharedCellInputsBitBudget] using + Nat.add_le_add_right (Nat.add_le_add_right + (Nat.add_le_add (Nat.add_le_add_right hsc (4 * (7 + eM + eF))) hw) eb) 4 + simpa only [querySharedCellInputsWithWork, b, scales, indices, run, + querySharedCellInputsLength] using And.intro hl hinputsCost + +end EditApproximation.BinaryFraction + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QuerySharedGeometry.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QuerySharedGeometry.lean new file mode 100644 index 0000000000000000000000000000000000000000..062b785cd63f30f3dd75b2547404cbc93780116b --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QuerySharedGeometry.lean @@ -0,0 +1,46 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryHistoryInputs +import OAI.Combinatorics.EditApproximation.Geometry.ActualRoundedGroupInputs +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Boolean endpoint enumeration for the whole-cell shared-read cover. +The inner interval is centered at each computed left endpoint plus the +child length, exactly as in the published query's gap guard. -/ + +namespace EditApproximation + + + +@[simp] theorem queryGapStatesWithWork_value (n g anchor radius sourceLength gapRadius : ℕ) + (hg : 0 < g) : + (queryGapStatesWithWork n g anchor radius sourceLength gapRadius).1 = + gridGapStates n g anchor radius sourceLength gapRadius := by + simp only [queryGapStatesWithWork, arithmeticFlatMapWithWork_value, filterMapWithWork_value, + makeStateWithWork_value, gridPointsWithWork_value _ _ _ hg, + saturatingSubtractWithWork_value, binaryNaturalAddWithWork_value, gridGapStates] + +namespace BinaryFraction + + + +theorem queryGroupRoundedStatesWithWork_value {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (b exponent : ℕ) (cell : ℕ × ℕ) + (i : Fin M) (h : BinaryFraction) : + (queryGroupRoundedStatesWithWork (ny := target.length) parent b exponent cell i h).1 = + groupRoundedStateList source target parent b exponent cell i h.value := by + unfold queryGroupRoundedStatesWithWork + dsimp only + rw [queryGapStatesWithWork_value _ _ _ _ _ _ (roundedSpacingWithWork_pos _ _)] + simp only [roundedSpacingWithWork_value, sourceChildWithWork_value, saturatingSubtractWithWork_value, + canonicalMulWithWork_value, nat_value, naturalFloorWithWork_value, inversePowerTwo_value, + binaryNaturalAddWithWork_value, binaryNaturalMulWithWork_value, naturalCeilingWithWork_value, + groupRoundedStateList, groupRoundSpacing, + substring_length source _ _ (sourceChild parent i).valid] + simp only [Nat.cast_ofNat, mul_assoc] + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QuerySharedGeometrySpace.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QuerySharedGeometrySpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..f5f03ac68cd243300fb4a3b494b47a4cb644f59e --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QuerySharedGeometrySpace.lean @@ -0,0 +1,95 @@ +import OAI.Combinatorics.EditApproximation.Queries.QuerySharedGeometry +import OAI.Combinatorics.EditApproximation.Binary.BinaryRoundingSpace +import OAI.Combinatorics.EditApproximation.Binary.BinaryWideSpace +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation + + + +theorem queryGapStatesAllocation_le_work (n g anchor radius sourceLength gapRadius : ℕ) : + queryGapStatesAllocation n g anchor radius sourceLength gapRadius ≤ + (queryGapStatesWithWork n g anchor radius sourceLength gapRadius).2 := by + let lo := (saturatingSubtractWithWork anchor radius).1 + let hi := (binaryNaturalAddWithWork anchor radius).1 + let build := fun first => + let center := binaryNaturalAddWithWork first sourceLength + let lower := saturatingSubtractWithWork (bitWordValue center.1) gapRadius + let upper := binaryNaturalAddWithWork (bitWordValue center.1) gapRadius + let right := gridPointsWithWork g (bitWordValue lower.1) (bitWordValue upper.1) + let valid := filterMapWithWork (makeStateWithWork n first) right.1 + (valid.1, center.2 + lower.2 + upper.2 + right.2 + valid.2 + 4) + let allocation := fun first => + let center := (binaryNaturalAddWithWork first sourceLength).1 + let lower := (saturatingSubtractWithWork (bitWordValue center) gapRadius).1 + let upper := (binaryNaturalAddWithWork (bitWordValue center) gapRadius).1 + let right := (gridPointsWithWork g (bitWordValue lower) (bitWordValue upper)).1 + binaryNaturalAddAllocation first sourceLength + saturatingSubtractAllocation (bitWordValue center) gapRadius + + binaryNaturalAddAllocation (bitWordValue center) gapRadius + gridPointsAllocation g (bitWordValue lower) (bitWordValue upper) + + filterMapAllocation (makeStateWithWork n first) (makeStateAllocation n first) right + have hl := saturatingSubtractAllocation_le_work anchor radius + have hh := binaryNaturalAddAllocation_le_work anchor radius + have hg := gridPointsAllocation_le_work g (bitWordValue lo) (bitWordValue hi) + have hb := arithmeticFlatMapAllocation_le_work build allocation + (gridPointsWithWork g (bitWordValue lo) (bitWordValue hi)).1 (by + intro first _ + let center := (binaryNaturalAddWithWork first sourceLength).1 + let lower := (saturatingSubtractWithWork (bitWordValue center) gapRadius).1 + let upper := (binaryNaturalAddWithWork (bitWordValue center) gapRadius).1 + have hc := binaryNaturalAddAllocation_le_work first sourceLength + have hl := saturatingSubtractAllocation_le_work (bitWordValue center) gapRadius + have hu := binaryNaturalAddAllocation_le_work (bitWordValue center) gapRadius + have hg := gridPointsAllocation_le_work g (bitWordValue lower) (bitWordValue upper) + have hf := filterMapAllocation_le_work (makeStateWithWork n first) (makeStateAllocation n first) + (gridPointsWithWork g (bitWordValue lower) (bitWordValue upper)).1 (fun last _ => makeStateAllocation_le_work n first last) + dsimp only [build, allocation, center, lower, upper] at hl hu hg hf ⊢ + omega) + unfold queryGapStatesAllocation queryGapStatesWithWork + dsimp only [lo, hi, build, allocation] at hg hb ⊢ + omega + +namespace BinaryFraction + + + +theorem queryGroupRoundedStatesAllocation_le_work {nx ny M : ℕ} (parent : TargetInterval nx) + (b exponent : ℕ) (cell : ℕ × ℕ) (i : Fin M) (h : BinaryFraction) : + queryGroupRoundedStatesAllocation (ny := ny) parent b exponent cell i h ≤ + (queryGroupRoundedStatesWithWork (ny := ny) parent b exponent cell i h).2 := by + let theta := inversePowerTwo exponent + let spacing := (roundedSpacingWithWork theta h).1 + let child := (sourceChildWithWork parent i).1 + let offset := (saturatingSubtractWithWork child.lo parent.lo).1 + let base := (canonicalMulWithWork (nat cell.1) theta).1 + let position := (canonicalMulWithWork base (nat b)).1 + let floor := (naturalFloorWithWork position).1 + let anchor := (binaryNaturalAddWithWork (bitWordValue floor) (bitWordValue offset)).1 + let radius := (binaryNaturalMulWithWork 12 b).1 + let length := (saturatingSubtractWithWork child.hi child.lo).1 + let twice := (canonicalMulWithWork (nat 2) h).1 + let gap := (naturalCeilingWithWork twice).1 + have h1 := roundedSpacingAllocation_le_work theta h + have h2 := sourceChildAllocation_le_work parent i + have h3 := saturatingSubtractAllocation_le_work child.lo parent.lo + have h4 := canonicalMulAllocation_le_work (nat cell.1) theta + have h5 := canonicalMulAllocation_le_work base (nat b) + have h6 := naturalFloorAllocation_le_work position + have h7 := binaryNaturalAddAllocation_le_work (bitWordValue floor) (bitWordValue offset) + have h8 := binaryNaturalMulAllocation_le_work 12 b + have h9 := saturatingSubtractAllocation_le_work child.hi child.lo + have h10 := canonicalMulAllocation_le_work (nat 2) h + have h11 := naturalCeilingAllocation_le_work twice + have h12 := queryGapStatesAllocation_le_work ny (bitWordValue spacing) (bitWordValue anchor) + (bitWordValue radius) (bitWordValue length) (bitWordValue gap) + unfold queryGroupRoundedStatesAllocation queryGroupRoundedStatesWithWork + dsimp only [theta, spacing, child, offset, base, position, floor, anchor, radius, length, twice, gap] + at h1 h3 h4 h5 h6 h7 h9 h11 h12 ⊢ + omega + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QuerySharedInputCost.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QuerySharedInputCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..1417f2cfb39b7a5f0544f2d81247816cf0dbf6a0 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QuerySharedInputCost.lean @@ -0,0 +1,125 @@ +import OAI.Combinatorics.EditApproximation.Queries.QuerySharedCellCost +import OAI.Combinatorics.EditApproximation.Queries.QueryGroupSourceCost +import OAI.Combinatorics.EditApproximation.Queries.QueryActionInputCost + +namespace OAI + +namespace EditApproximation.BinaryFraction + +def querySharedInputsLength (M F exponent eM eF B : ℕ) : ℕ := + (B + 1) * ((((32 * F + 2) * 2 ^ exponent + 2) ^ 2) * querySharedCellInputsLength M exponent eM eF) + +def querySharedInputsBitBudget (M F exponent eM eF B R : ℕ) : ℕ := + let cells := ((32 * F + 2) * 2 ^ exponent + 2) ^ 2 + let samples := querySharedCellInputsLength M exponent eM eF + let sampleWork := querySharedCellInputsBitBudget M exponent eM B eF (16 * B + 200) R + let scaleWork := queryCellScanBitBudget F exponent B + + cells * (sampleWork + samples + 3) + B + exponent + 4 + queryExponentsBitBudget B + 500 * (B + 1) ^ 2 + (B + 1) * (scaleWork + cells * samples + 3) + + (querySharedInputsLength M F exponent eM eF B + 1) ^ 2 * (202000 * (B + 1) ^ 2) + 3 + +theorem querySharedInputsWithWork_bounds_on {nx ny : ℕ} (M N F Q exponent eM eF B R : ℕ) + (hMdef : M = 2 ^ eM) (hFdef : F = 2 ^ eF) (parent : TargetInterval nx) + (a value : BinaryFraction) (q : TargetInterval ny) (draw : CountedCellGroupDraws M F Q) + (hB : 7 ≤ B) (hN : Nat.size N ≤ B) (hF : Nat.size F + 2 ≤ B) + (hM : Nat.size M + 2 ≤ B) (hQ : Nat.size Q + 2 ≤ B) (hes : eM + eF + 7 ≤ B) + (he : exponent + 1 ≤ B) (hnx : Nat.size nx ≤ B) (hny : Nat.size ny ≤ B) + (ha : a.width ≤ B) (hv : value.width ≤ B) (hw : 0 ≤ value.value) + (hR : ∀ eb ∈ (queryExponentsWithWork N F a value).1, + ∀ cell ∈ (targetCellsWithWork + (canonicalMulWithWork (inversePowerTwo exponent) (nat (2 ^ eb))).1 + (bitWordValue (naturalCeilingWithWork value).1) q).1, + ∀ scale sample, (draw (2 ^ eb) cell scale sample).2 ≤ R) : + (querySharedInputsWithWork M N F Q exponent eM eF hMdef hFdef parent a value q draw).1.length ≤ + querySharedInputsLength M F exponent eM eF B ∧ + (querySharedInputsWithWork M N F Q exponent eM eF hMdef hFdef parent a value q draw).2 ≤ + querySharedInputsBitBudget M F exponent eM eF B R := by + let scales := queryExponentsWithWork N F a value + let radius := naturalCeilingWithWork value + let cells := fun eb => targetCellsWithWork + (canonicalMulWithWork (inversePowerTwo exponent) (nat (2 ^ eb))).1 (bitWordValue radius.1) q + let sources := fun eb => arithmeticFlatMapWithWork (fun cell => + querySharedCellInputsWithWork (ny := ny) M F Q eM eb eF hMdef hFdef parent exponent cell (draw (2 ^ eb) cell)) (cells eb).1 + let run := fun eb => + let side := canonicalMulWithWork (inversePowerTwo exponent) (nat (2 ^ eb)) + ((sources eb).1, side.2 + (cells eb).2 + (sources eb).2 + eb + exponent + 4) + let K := ((32 * F + 2) * 2 ^ exponent + 2) ^ 2 + let L := querySharedCellInputsLength M exponent eM eF + let W := querySharedCellInputsBitBudget M exponent eM B eF (16 * B + 200) R + let C := queryCellScanBitBudget F exponent B + K * (W + L + 3) + B + exponent + 4 + let raw := arithmeticFlatMapWithWork run scales.1 + have hs := queryExponentsWithWork_bounds N F B a value hB hN hF ha hv + have hFpos : 1 ≤ F := by rw [hFdef]; exact Nat.succ_le_of_lt (Nat.two_pow_pos _) + have hrun (eb : ℕ) (heb : eb ∈ scales.1) : (run eb).1.length ≤ K * L ∧ (run eb).2 ≤ C := by + have hm := queryExponentsWithWork_member N F B a value hN eb heb + have hwindow := queryScalesWithWork_window N F a value (2 ^ eb) hm.2 + have hcell := queryCellScan_bounds F (2 ^ eb) exponent B value q hFpos + (Nat.succ_le_of_lt (Nat.two_pow_pos _)) (by rw [Nat.size_pow]; omega) he hny hv hw hwindow.2 + have hsample (cell : ℕ × ℕ) (hc : cell ∈ (cells eb).1) : + (querySharedCellInputsWithWork (ny := ny) M F Q eM eb eF hMdef hFdef parent exponent cell + (draw (2 ^ eb) cell)).1.length ≤ L ∧ + (querySharedCellInputsWithWork (ny := ny) M F Q eM eb eF hMdef hFdef parent exponent cell + (draw (2 ^ eb) cell)).2 ≤ W := by + have hcoord := hcell.2.2 cell hc + have hh := querySharedCellInputsWithWork_bounds (ny := ny) M F Q eM eb eF hMdef hFdef parent + exponent (16 * B + 200) R cell (draw (2 ^ eb) cell) + (by omega) (by omega) (by omega) (by omega) (by omega) (by omega) (by omega) + (by omega) (by omega) (hR eb heb cell hc) + exact ⟨hh.1, hh.2.trans (querySharedCellInputsBitBudget_mono_eb M exponent eM eb B eF + (16 * B + 200) R hm.1)⟩ + have hl := (arithmeticFlatMapWithWork_length _ (cells eb).1 L + (fun cell hc => (hsample cell hc).1)).trans (Nat.mul_le_mul_right _ hcell.1) + have hc := (arithmeticFlatMapWithWork_cost _ (cells eb).1 W L + (fun cell hc => (hsample cell hc).2) (fun cell hc => (hsample cell hc).1)).trans + (Nat.mul_le_mul_right _ hcell.1) + have hsourceCost : (sources eb).2 ≤ K * (W + L + 3) := by + simpa only [sources, K] using hc + have hcellCost : (canonicalMulWithWork (inversePowerTwo exponent) (nat (2 ^ eb))).2 + + (cells eb).2 ≤ queryCellScanBitBudget F exponent B := by + simpa only [cells, radius] using hcell.2.1 + have hrunCost : (canonicalMulWithWork (inversePowerTwo exponent) (nat (2 ^ eb))).2 + + (cells eb).2 + (sources eb).2 + eb + exponent + 4 ≤ C := by + simpa only [C] using Nat.add_le_add_right + (Nat.add_le_add_right (Nat.add_le_add (Nat.add_le_add hcellCost hsourceCost) hm.1) exponent) 4 + simpa only [run, sources] using And.intro hl hrunCost + have hl := (arithmeticFlatMapWithWork_length run scales.1 (K * L) + (fun eb heb => (hrun eb heb).1)).trans (Nat.mul_le_mul_right _ hs.2) + have hc := (arithmeticFlatMapWithWork_cost run scales.1 C (K * L) + (fun eb heb => (hrun eb heb).2) (fun eb heb => (hrun eb heb).1)).trans + (Nat.mul_le_mul_right _ hs.2) + have hr := (naturalCeilingWithWork_cost value).trans + (Nat.mul_le_mul_left 500 (Nat.pow_le_pow_left (Nat.add_le_add_right hv 1) 2)) + have hsort := (queryOrderedChildInputsWithWork_cost raw.1 B (by omega) hny).trans + (Nat.mul_le_mul_right _ (Nat.pow_le_pow_left (Nat.add_le_add_right hl 1) 2)) + have hlength := (queryOrderedChildInputsWithWork_length raw.1).trans hl + have hsc : scales.2 ≤ queryExponentsBitBudget B := hs.1 + have hradius : radius.2 ≤ 500 * (B + 1) ^ 2 := by + simpa only [radius] using hr + have hraw : raw.2 ≤ (B + 1) * (C + K * L + 3) := by + simpa only [raw] using hc + have hcost : scales.2 + radius.2 + raw.2 + (queryOrderedChildInputsWithWork raw.1).2 + 3 ≤ + querySharedInputsBitBudget M F exponent eM eF B R := by + simpa only [querySharedInputsBitBudget, querySharedInputsLength, C, K, L, W] using + Nat.add_le_add_right (Nat.add_le_add (Nat.add_le_add (Nat.add_le_add hsc hradius) hraw) hsort) 3 + simpa only [querySharedInputsWithWork, scales, radius, cells, sources, run, raw, + querySharedInputsLength, K, L] using And.intro hlength hcost + + +theorem querySharedInputsWithWork_bounds {nx ny : ℕ} (M N F Q exponent eM eF B R : ℕ) + (hMdef : M = 2 ^ eM) (hFdef : F = 2 ^ eF) (parent : TargetInterval nx) + (a value : BinaryFraction) (q : TargetInterval ny) (draw : CountedCellGroupDraws M F Q) + (hB : 7 ≤ B) (hN : Nat.size N ≤ B) (hF : Nat.size F + 2 ≤ B) + (hM : Nat.size M + 2 ≤ B) (hQ : Nat.size Q + 2 ≤ B) (hes : eM + eF + 7 ≤ B) + (he : exponent + 1 ≤ B) (hnx : Nat.size nx ≤ B) (hny : Nat.size ny ≤ B) + (ha : a.width ≤ B) (hv : value.width ≤ B) (hw : 0 ≤ value.value) + (hR : ∀ b cell scale sample, (draw b cell scale sample).2 ≤ R) : + (querySharedInputsWithWork M N F Q exponent eM eF hMdef hFdef parent a value q draw).1.length ≤ + querySharedInputsLength M F exponent eM eF B ∧ + (querySharedInputsWithWork M N F Q exponent eM eF hMdef hFdef parent a value q draw).2 ≤ + querySharedInputsBitBudget M F exponent eM eF B R := + querySharedInputsWithWork_bounds_on M N F Q exponent eM eF B R hMdef hFdef parent a value q draw + hB hN hF hM hQ hes he hnx hny ha hv hw (fun eb _ cell _ => hR (2 ^ eb) cell) + +end EditApproximation.BinaryFraction + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QuerySharedInputs.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QuerySharedInputs.lean new file mode 100644 index 0000000000000000000000000000000000000000..d930761e84e70a8482c2820b51872fb5bf7695ab --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QuerySharedInputs.lean @@ -0,0 +1,77 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryGroupInputs +import OAI.Combinatorics.EditApproximation.Queries.QueryInputCodes +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! The shared-current request list is built from counted whole-cell +enumerations and sorted by the original child encoding. -/ + +namespace EditApproximation + + + +namespace BinaryFraction + + + +theorem queryGroupInputsTransportWithWork_value {α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (b exponent Q : ℕ) (cell : ℕ × ℕ) + (word : BinaryFraction) (scale : ℚ) (hv : word.value = scale) + (draw : Fin (groupSampleCount M Q b scale) → Fin M × ℕ) : + (queryGroupInputsTransportWithWork (ny := target.length) parent b exponent Q cell word scale hv draw).1.toFinset = + groupCurrentInputCover source target parent b exponent Q cell scale (fun i => (draw i).1) := by + subst scale + exact queryGroupInputsWithWork_value source target parent b exponent Q cell word draw + + + +theorem querySharedCellInputsWithWork_value {α : Type*} (source target : List α) + (M F Q eM eb eF : ℕ) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) + (parent : TargetInterval source.length) (exponent : ℕ) (cell : ℕ × ℕ) + (draw : ∀ scale : Fin (groupDyadicScales M (2 ^ eb) F).length, + Fin (groupSampleCount M Q (2 ^ eb) (groupDyadicScaleAt M (2 ^ eb) F scale)) → Fin M × ℕ) : + (querySharedCellInputsWithWork (ny := target.length) M F Q eM eb eF hM hF parent exponent cell draw).1.toFinset = + Finset.univ.biUnion (fun scale => groupCurrentInputCover source target parent (2 ^ eb) exponent Q cell + (groupDyadicScaleAt M (2 ^ eb) F scale) (fun sample => (draw scale sample).1)) := by + simp only [querySharedCellInputsWithWork, arithmeticFlatMapWithWork_value, queryFinRange_value] + ext input + simp only [List.mem_toFinset, List.mem_flatMap, List.mem_finRange, true_and, + Finset.mem_biUnion, Finset.mem_univ] + apply exists_congr + intro scale + rw [← List.mem_toFinset, queryGroupInputsTransportWithWork_value source target] + + + +theorem querySharedInputsWithWork_value {α : Type*} (source target : List α) + (M N F Q exponent eM eF : ℕ) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) + (parent : TargetInterval source.length) (a value : BinaryFraction) + (query : TargetInterval target.length) (draw : CountedCellGroupDraws M F Q) : + (querySharedInputsWithWork M N F Q exponent eM eF hM hF parent a value query draw).1 = + orderedInputs childInputCode (childInputCode_injective M target.length) + (querySharedInputCover source target parent N F exponent Q a.value (fun _ => value.value) query + (fun b cell scale sample => (draw b cell scale sample).1)) := by + have hc (e : ℕ) (cell : ℕ × ℕ) (input : Fin M × TargetInterval target.length) : + input ∈ (querySharedCellInputsWithWork (ny := target.length) M F Q eM e eF hM hF parent + exponent cell (draw (2 ^ e) cell)).1 ↔ + ∃ scale, input ∈ groupCurrentInputCover source target parent (2 ^ e) exponent Q cell + (groupDyadicScaleAt M (2 ^ e) F scale) (fun sample => (draw (2 ^ e) cell scale sample).1) := by + rw [← List.mem_toFinset, querySharedCellInputsWithWork_value source target] + simp only [Finset.mem_biUnion, Finset.mem_univ, true_and] + simp only [querySharedInputsWithWork, queryOrderedChildInputsWithWork_value] + apply congrArg (orderedInputs childInputCode (childInputCode_injective M target.length)) + unfold querySharedInputCover localGroupQueryKeys + rw [← queryExponentsWithWork_value N F a value] + ext input + simp only [arithmeticFlatMapWithWork_value, targetCellsWithWork_value, + canonicalMulWithWork_value, inversePowerTwo_value, nat_value, naturalCeilingWithWork_value, + List.mem_toFinset, List.mem_flatMap, List.flatMap_map, List.mem_map, Finset.mem_biUnion, + Finset.mem_univ, true_and, hc] + aesop + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QuerySharedSpace.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QuerySharedSpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..883d81f60933ec2a69f806992a55f66f02d8779e --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QuerySharedSpace.lean @@ -0,0 +1,116 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryGroupSetupSpace +import OAI.Combinatorics.EditApproximation.Queries.QuerySharedInputs +import OAI.Combinatorics.EditApproximation.Queries.QueryInitialSpace +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation + + + +namespace BinaryFraction + + + +theorem queryGroupInputsTransportAllocation_le_work {nx ny M : ℕ} (parent : TargetInterval nx) + (b exponent Q : ℕ) (cell : ℕ × ℕ) (word : BinaryFraction) (scale : ℚ) + (hv : word.value = scale) (draw : Fin (groupSampleCount M Q b scale) → Fin M × ℕ) + (allocation : Fin (groupSampleCount M Q b scale) → ℕ) + (ha : ∀ sample, allocation sample ≤ (draw sample).2) : + queryGroupInputsTransportAllocation (ny := ny) parent b exponent Q cell word scale hv draw allocation ≤ + (queryGroupInputsTransportWithWork (ny := ny) parent b exponent Q cell word scale hv draw).2 := + queryGroupInputsAllocation_le_work _ _ _ _ _ _ _ _ (fun _ => ha _) + + + +theorem querySharedCellInputsAllocation_le_work {nx ny : ℕ} (M F Q eM eb eF : ℕ) + (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (parent : TargetInterval nx) + (exponent : ℕ) (cell : ℕ × ℕ) + (draw : ∀ scale : Fin (groupDyadicScales M (2 ^ eb) F).length, + Fin (groupSampleCount M Q (2 ^ eb) (groupDyadicScaleAt M (2 ^ eb) F scale)) → Fin M × ℕ) + (allocation : ∀ scale : Fin (groupDyadicScales M (2 ^ eb) F).length, + Fin (groupSampleCount M Q (2 ^ eb) (groupDyadicScaleAt M (2 ^ eb) F scale)) → ℕ) + (ha : ∀ scale sample, allocation scale sample ≤ (draw scale sample).2) : + querySharedCellInputsAllocation (ny := ny) M F Q eM eb eF hM hF parent exponent cell draw allocation ≤ + (querySharedCellInputsWithWork (ny := ny) M F Q eM eb eF hM hF parent exponent cell draw).2 := by + let b := 2 ^ eb + let scales := groupScalesWithWork eM eb eF + have hs : scales.1.map value = groupDyadicScales M b F := by + simpa only [nat_value] using computedGroupScales_value M b F eM eb eF hM rfl hF + have hlen : scales.1.length = (groupDyadicScales M b F).length := by + simpa only [List.length_map] using congrArg List.length hs + let indices := queryFinRange scales.1.length (groupDyadicScales M b F).length hlen + let build := fun scale => + let word := queryScaleAt scales.1 (groupDyadicScales M b F) hs scale + let hv : word.value = groupDyadicScaleAt M b F scale := queryGroupScaleAt_value M b F _ hs scale + let states := queryGroupInputsTransportWithWork (ny := ny) parent b exponent Q cell word + (groupDyadicScaleAt M b F scale) hv (draw scale) + (states.1, states.2 + scales.1.length + 1) + let alloc := fun scale => + let word := queryScaleAt scales.1 (groupDyadicScales M b F) hs scale + let hv : word.value = groupDyadicScaleAt M b F scale := queryGroupScaleAt_value M b F _ hs scale + queryGroupInputsTransportAllocation (ny := ny) parent b exponent Q cell word + (groupDyadicScaleAt M b F scale) hv (draw scale) (allocation scale) + have hg := groupScalesAllocation_le_work eM eb eF + have hi := arithmeticFlatMapAllocation_le_work build alloc indices (by + intro scale _ + have hh := queryGroupInputsTransportAllocation_le_work (ny := ny) parent b exponent Q cell + (queryScaleAt scales.1 (groupDyadicScales M b F) hs scale) (groupDyadicScaleAt M b F scale) + (queryGroupScaleAt_value M b F _ hs scale) (draw scale) (allocation scale) (ha scale) + dsimp only [alloc, build] + omega) + unfold querySharedCellInputsAllocation querySharedCellInputsWithWork + dsimp only [build, alloc, b, scales, indices] at hi ⊢ + omega + + + +theorem querySharedInputsAllocation_le_work {nx ny : ℕ} (M N F Q exponent eM eF : ℕ) + (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (parent : TargetInterval nx) + (a value : BinaryFraction) (query : TargetInterval ny) (draw : CountedCellGroupDraws M F Q) + (allocation : CountedCellGroupAllocations M F Q) + (ha : ∀ b cell scale sample, allocation b cell scale sample ≤ (draw b cell scale sample).2) : + querySharedInputsAllocation M N F Q exponent eM eF hM hF parent a value query draw allocation ≤ + (querySharedInputsWithWork M N F Q exponent eM eF hM hF parent a value query draw).2 := by + let scales := (queryExponentsWithWork N F a value).1 + let radius := (naturalCeilingWithWork value).1 + let build := fun eb => + let side := canonicalMulWithWork (inversePowerTwo exponent) (nat (2 ^ eb)) + let cells := targetCellsWithWork side.1 (bitWordValue radius) query + let states := arithmeticFlatMapWithWork (fun cell => + querySharedCellInputsWithWork (ny := ny) M F Q eM eb eF hM hF parent exponent cell (draw (2 ^ eb) cell)) cells.1 + (states.1, side.2 + cells.2 + states.2 + eb + exponent + 4) + let alloc := fun eb => + let side := (canonicalMulWithWork (inversePowerTwo exponent) (nat (2 ^ eb))).1 + let cells := (targetCellsWithWork side (bitWordValue radius) query).1 + canonicalMulAllocation (inversePowerTwo exponent) (nat (2 ^ eb)) + targetCellsAllocation side (bitWordValue radius) query + + arithmeticFlatMapAllocation + (fun cell => querySharedCellInputsWithWork (ny := ny) M F Q eM eb eF hM hF parent exponent cell (draw (2 ^ eb) cell)) + (fun cell => querySharedCellInputsAllocation (ny := ny) M F Q eM eb eF hM hF parent exponent cell + (draw (2 ^ eb) cell) (allocation (2 ^ eb) cell)) cells + eb + exponent + 2 + have he := queryExponentsAllocation_le_work N F a value + have hr := naturalCeilingAllocation_le_work value + have hi := arithmeticFlatMapAllocation_le_work build alloc scales (by + intro eb _ + let side := (canonicalMulWithWork (inversePowerTwo exponent) (nat (2 ^ eb))).1 + have hs := canonicalMulAllocation_le_work (inversePowerTwo exponent) (nat (2 ^ eb)) + have hc := targetCellsAllocation_le_work side (bitWordValue radius) query + have hm := arithmeticFlatMapAllocation_le_work + (fun cell => querySharedCellInputsWithWork (ny := ny) M F Q eM eb eF hM hF parent exponent cell (draw (2 ^ eb) cell)) + (fun cell => querySharedCellInputsAllocation (ny := ny) M F Q eM eb eF hM hF parent exponent cell + (draw (2 ^ eb) cell) (allocation (2 ^ eb) cell)) (targetCellsWithWork side (bitWordValue radius) query).1 + (fun cell _ => querySharedCellInputsAllocation_le_work (ny := ny) M F Q eM eb eF hM hF parent exponent cell + (draw (2 ^ eb) cell) (allocation (2 ^ eb) cell) (ha (2 ^ eb) cell)) + dsimp only [build, alloc, side] at hc hm ⊢ + omega) + have ho := queryOrderedChildInputsAllocation_le_work (arithmeticFlatMapWithWork build scales).1 + unfold querySharedInputsAllocation querySharedInputsWithWork + dsimp only [build, alloc, scales, radius] at hi ho ⊢ + omega + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QuerySourceBufferBounds.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QuerySourceBufferBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..d7423262a5ed7469bbc7d2bdf02789cf0b888d06 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QuerySourceBufferBounds.lean @@ -0,0 +1,93 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryDataBuffers + +namespace OAI + +/-! Random-source lookups are charged at the bounded coordinates actually +consumed by the local loops. No bound is assumed on all natural keys. -/ + +namespace EditApproximation + +def queryGroupKeySize {M F Q : ℕ} (key : GroupScalarKey M F Q) : ℕ := + Nat.size key.1.1 + Nat.size key.1.2.1 + Nat.size key.1.2.2 + + Nat.size key.2.1.val + Nat.size key.2.2.val + +theorem queryGroupKeyEqualWithWork_cost {M F Q : ℕ} + (a b : GroupScalarKey M F Q) (B : ℕ) + (ha : queryGroupKeySize a ≤ B) (hb : queryGroupKeySize b ≤ B) : + (queryGroupKeyEqualWithWork a b).2 ≤ 40 * B + 14 := by + unfold queryGroupKeySize at ha hb + have h1 := naturalEqualWithWork_cost a.1.1 b.1.1 B (by omega) (by omega) + have h2 := naturalEqualWithWork_cost a.1.2.1 b.1.2.1 B (by omega) (by omega) + have h3 := naturalEqualWithWork_cost a.1.2.2 b.1.2.2 B (by omega) (by omega) + have h4 := naturalEqualWithWork_cost a.2.1.val b.2.1.val B (by omega) (by omega) + have h5 := naturalEqualWithWork_cost a.2.2.val b.2.2.val B (by omega) (by omega) + change _ + _ + _ + _ + _ + 4 ≤ _ + omega + +theorem queryOnlineKeyEqualWithWork_cost {n : ℕ} (a b : ℕ × TargetInterval n) + (B : ℕ) (ha : Nat.size a.1 ≤ B) (hb : Nat.size b.1 ≤ B) (hn : Nat.size n ≤ B) : + (queryOnlineKeyEqualWithWork a b).2 ≤ 24 * B + 8 := by + have hs := naturalEqualWithWork_cost a.1 b.1 B ha hb + have hi := queryIntervalEqualWithWork_cost a.2 b.2 B hn + change _ + _ + 1 ≤ _ + omega + +namespace BinaryFraction + +theorem queryGroupDrawReadWithWork_cost {M F Q : ℕ} [NeZero M] + (keys : List (GroupScalarKey M F Q)) (values : List BinaryFraction) + (b : ℕ) (cell : ℕ × ℕ) (scale : Fin (groupDyadicScales M b F).length) + (sample : Fin (groupSampleCount M Q b (groupDyadicScaleAt M b F scale))) + (B V : ℕ) (hV : 2 ≤ V) (hM : Nat.size M ≤ B) + (hkeys : ∀ key ∈ keys, queryGroupKeySize key ≤ B) + (hquery : queryGroupKeySize (⟨(b, cell), scale, sample⟩ : GroupScalarKey M F Q) ≤ B) + (hvalues : ∀ v ∈ values, v.width ≤ V) : + (queryGroupDrawReadWithWork keys values b cell scale sample).2 ≤ + keys.length * (40 * B + 15) + 200 * (V + 1) ^ 2 + + 30 * (V + 1) * (V + B + 1) + 4 := by + let query : GroupScalarKey M F Q := ⟨(b, cell), scale, sample⟩ + let word := gatheredWordLookupWithWork queryGroupKeyEqualWithWork keys values query + have hl := gatheredWordLookupWithWork_cost_on queryGroupKeyEqualWithWork (40 * B + 14) + keys values query (fun key hk => queryGroupKeyEqualWithWork_cost query key B hquery (hkeys key hk)) + have hw : word.1.width ≤ V := gatheredWordLookupWithWork_width _ keys values query V hV hvalues + have hf := naturalFloorWithWork_bounds word.1 + have hs : Nat.size (bitWordValue (naturalFloorWithWork word.1).1) ≤ V := + (Nat.size_le.mpr (bitWordValue_lt_pow_length _)).trans (hf.1.trans hw) + have hd := binaryNaturalDivModWithWork_cost (bitWordValue (naturalFloorWithWork word.1).1) M + have hd' : (binaryNaturalDivModWithWork (bitWordValue (naturalFloorWithWork word.1).1) M).2.2 ≤ + 30 * (V + 1) * (V + B + 1) := by + apply hd.trans + gcongr + have hf' : (naturalFloorWithWork word.1).2 ≤ 200 * (V + 1) ^ 2 := by + apply hf.2.trans + gcongr + have hl' : word.2 ≤ 1 + keys.length * (40 * B + 15) := by + simpa only [word, query, Nat.add_assoc, Nat.reduceAdd] using hl + change word.2 + (naturalFloorWithWork word.1).2 + + (binaryNaturalDivModWithWork (bitWordValue (naturalFloorWithWork word.1).1) M).2.2 + 3 ≤ _ + omega + +theorem queryOnlineIntegerReadWithWork_cost {n : ℕ} + (keys : List (ℕ × TargetInterval n)) (values : List BinaryFraction) + (b : ℕ) (q : TargetInterval n) (B V : ℕ) (hV : 2 ≤ V) + (hn : Nat.size n ≤ B) (hb : Nat.size b ≤ B) + (hkeys : ∀ key ∈ keys, Nat.size key.1 ≤ B) (hvalues : ∀ v ∈ values, v.width ≤ V) : + (queryOnlineIntegerReadWithWork keys values b q).2 ≤ + keys.length * (24 * B + 9) + 200 * (V + 1) ^ 2 + 2 := by + let word := gatheredWordLookupWithWork queryOnlineKeyEqualWithWork keys values (b, q) + have hl := gatheredWordLookupWithWork_cost_on queryOnlineKeyEqualWithWork (24 * B + 8) + keys values (b, q) (fun key hk => queryOnlineKeyEqualWithWork_cost (b, q) key B hb (hkeys key hk) hn) + have hw : word.1.width ≤ V := gatheredWordLookupWithWork_width _ keys values (b, q) V hV hvalues + have hf := (naturalFloorWithWork_bounds word.1).2 + have hf' : (naturalFloorWithWork word.1).2 ≤ 200 * (V + 1) ^ 2 := by + apply hf.trans + gcongr + have hl' : word.2 ≤ 1 + keys.length * (24 * B + 9) := by + simpa only [word, Nat.add_assoc, Nat.reduceAdd] using hl + change word.2 + (naturalFloorWithWork word.1).2 + 1 ≤ _ + omega + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QuerySourceBuffers.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QuerySourceBuffers.lean new file mode 100644 index 0000000000000000000000000000000000000000..2c704cde7104bd85e8039f1545199c398e36a035 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QuerySourceBuffers.lean @@ -0,0 +1,71 @@ +import OAI.Combinatorics.EditApproximation.Queries.QuerySharedInputs +import OAI.Combinatorics.EditApproximation.Binary.BinaryGatheredValues +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Source words are decoded only by counted buffer lookups, natural +floor and remainder routines. The resulting draws are exactly the draws +used by the semantic adaptive query, for every stored answer list. -/ + +namespace EditApproximation + + + +@[simp] theorem queryGroupKeyEqualWithWork_value {M F Q : ℕ} (a b : GroupScalarKey M F Q) : + (queryGroupKeyEqualWithWork a b).1 = true ↔ a = b := by + simp only [queryGroupKeyEqualWithWork, Bool.and_eq_true, naturalEqualWithWork_value] + constructor + · rcases a with ⟨⟨a, c, d⟩, s, i⟩ + rcases b with ⟨⟨b, e, f⟩, t, j⟩ + rintro ⟨⟨⟨⟨hab, hce⟩, hdf⟩, hst⟩, hij⟩ + dsimp only at hab hce hdf hst hij + cases hab + cases hce + cases hdf + have hs : s = t := Fin.ext hst + cases hs + have hi : i = j := Fin.ext hij + cases hi + rfl + · intro h + subst b + exact ⟨⟨⟨⟨rfl, rfl⟩, rfl⟩, rfl⟩, rfl⟩ + + + +@[simp] theorem queryOnlineKeyEqualWithWork_value {n : ℕ} (a b : ℕ × TargetInterval n) : + (queryOnlineKeyEqualWithWork a b).1 = true ↔ a = b := by + simp only [queryOnlineKeyEqualWithWork, Bool.and_eq_true, naturalEqualWithWork_value, + queryIntervalEqualWithWork_value, Prod.ext_iff] + +namespace BinaryFraction + + + +theorem queryGroupDrawReadWithWork_value {M F Q : ℕ} [NeZero M] + (keys : List (GroupScalarKey M F Q)) (values : List BinaryFraction) + (b : ℕ) (cell : ℕ × ℕ) (scale : Fin (groupDyadicScales M b F).length) + (sample : Fin (groupSampleCount M Q b (groupDyadicScaleAt M b F scale))) : + (queryGroupDrawReadWithWork keys values b cell scale sample).1 = + groupDrawFromValues keys (values.map value) b cell scale sample := by + apply Fin.ext + simp only [queryGroupDrawReadWithWork, + (binaryNaturalDivModWithWork_spec _ M (NeZero.pos M)).2, + naturalFloorWithWork_value, gatheredWordLookupWithWork_value _ queryGroupKeyEqualWithWork_value, + groupDrawFromValues, Fin.val_ofNat] + + + +@[simp] theorem queryOnlineIntegerReadWithWork_value {n : ℕ} (keys : List (ℕ × TargetInterval n)) + (values : List BinaryFraction) (b : ℕ) (q : TargetInterval n) : + (queryOnlineIntegerReadWithWork keys values b q).1 = + ⌊finiteAnswerTable keys (values.map value) (b, q)⌋₊ := by + simp only [queryOnlineIntegerReadWithWork, naturalFloorWithWork_value, + gatheredWordLookupWithWork_value _ queryOnlineKeyEqualWithWork_value] + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QuerySourceGatherCost.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QuerySourceGatherCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..e98eb2ac95e18eaeb4c52856c7ba65f4b6dbbc9d --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QuerySourceGatherCost.lean @@ -0,0 +1,114 @@ +import OAI.Combinatorics.EditApproximation.Queries.QuerySourceWork +import OAI.Combinatorics.EditApproximation.Queries.QueryGroupSourceCost +import OAI.Combinatorics.EditApproximation.Queries.QueryOnlineKeyCost +import OAI.Combinatorics.EditApproximation.Queries.QueryOnlineRangeCost +import OAI.Combinatorics.EditApproximation.Queries.QueryScopedSourceCost + +namespace OAI + +namespace EditApproximation + +private theorem source_read_sum_bound {κ : Type*} (keys : List κ) (cost : κ → ℕ) (B : ℕ) + (h : ∀ key ∈ keys, cost key ≤ B) : (keys.map cost).sum ≤ keys.length * B := by + induction keys with + | nil => simp + | cons key keys ih => + have hh := h key List.mem_cons_self + have ht := ih (fun k hk => h k (List.mem_cons_of_mem key hk)) + simp only [List.map_cons, List.sum_cons, List.length_cons, Nat.add_mul, Nat.one_mul] + omega + +namespace BinaryFraction + +def queryGroupGatherBitBudget (M F exponent eM eF B Rp W K : ℕ) : ℕ := + Rp + queryGroupSourceKeysBitBudget M F exponent eM eF B + + queryGroupSourceKeysLength M F exponent eM eF B * (W + 3) + K + +def queryOnlineGatherBitBudget (M P B Rp R W K : ℕ) : ℕ := + Rp + queryOnlineKeysBitBudget B + + (B + 1) * (queryOnlineRangeBitBudget M P (B + 1) R + W + 3) + K + +end BinaryFraction + +open BinaryFraction + +theorem queryGroupSourceGather_work_bound {ι β : Type*} {n : ℕ} + (M N F Q exponent eM eF B Rp W K : ℕ) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) + (a : BinaryFraction) (initial : TargetInterval n → BinaryFraction × ℕ) (q : TargetInterval n) + (reader : GroupScalarKey M F Q → BitQuery ι BinaryFraction) + (next : List (GroupScalarKey M F Q) → List BinaryFraction → BitQuery ι β) + (oracle : ι → BinaryFraction) (readWork : ι → ℕ) + (hB : 7 ≤ B) (hN : Nat.size N ≤ B) (hFb : Nat.size F + 2 ≤ B) + (hMb : Nat.size M + 2 ≤ B) (hQ : Nat.size Q + 2 ≤ B) (hes : eM + eF + 7 ≤ B) + (he : exponent + 1 ≤ B) (hn : Nat.size n ≤ B) (ha : a.width ≤ B) + (hv : (initial q).1.width ≤ B) (hw : 0 ≤ (initial q).1.value) (hp : (initial q).2 ≤ Rp) + (hr : ∀ key ∈ (queryGroupSourceKeysWithWork M N F Q exponent eM eF hM hF a (initial q).1 q).1, + (reader key).work oracle readWork ≤ W) + (hnext : + let keys := (queryGroupSourceKeysWithWork M N F Q exponent eM eF hM hF a (initial q).1 q).1 + (next keys (keys.map fun key => (reader key).value oracle)).work oracle readWork ≤ K) : + (queryGroupSourceGather M N F Q exponent eM eF hM hF a initial q reader next).work oracle readWork ≤ + queryGroupGatherBitBudget M F exponent eM eF B Rp W K := by + let keys := queryGroupSourceKeysWithWork M N F Q exponent eM eF hM hF a (initial q).1 q + have hk := queryGroupSourceKeysWithWork_bounds M N F Q exponent eM eF B hM hF a (initial q).1 q + hB hN hFb hMb hQ hes he hn ha hv hw + have hs := (source_read_sum_bound keys.1 (fun key => (reader key).work oracle readWork + 3) (W + 3) + (fun key hkey => Nat.add_le_add_right (hr key hkey) 3)).trans (Nat.mul_le_mul_right _ hk.1) + change (next keys.1 (keys.1.map fun key => (reader key).value oracle)).work oracle readWork ≤ K at hnext + have hkc : keys.2 ≤ queryGroupSourceKeysBitBudget M F exponent eM eF B := hk.2 + rw [queryGroupSourceGather_work] + change (initial q).2 + keys.2 + (keys.1.map fun key => (reader key).work oracle readWork + 3).sum + + (next keys.1 (keys.1.map fun key => (reader key).value oracle)).work oracle readWork ≤ _ + unfold queryGroupGatherBitBudget + omega + +theorem queryOnlineSourceGather_work_bound {ι β α : Type*} (source target : List α) {M : ℕ} + (parent : TargetInterval source.length) (N P F exponent H B Rp R W K : ℕ) (hP : 0 < P) + (tau a : BinaryFraction) (initial : TargetInterval target.length → BinaryFraction × ℕ) + (child : Fin M → TargetInterval target.length → BinaryFraction × ℕ) (q : TargetInterval target.length) + (reader : (ℕ × TargetInterval target.length) → ℕ → BitQuery ι BinaryFraction) + (next : List (ℕ × TargetInterval target.length) → List BinaryFraction → BitQuery ι β) + (oracle : ι → BinaryFraction) (readWork : ι → ℕ) + (hB : 7 ≤ B) (hN : Nat.size N ≤ B) (hFb : Nat.size F + 2 ≤ B) (hF : 1 ≤ F) + (hMb : Nat.size M ≤ B) (hPb : Nat.size P ≤ B) (he : exponent + 1 ≤ B) + (hnx : Nat.size source.length ≤ B) (hny : Nat.size target.length ≤ B) + (hH : Nat.size H ≤ B) (hd : Nat.size (M * (40 * P + 2) ^ 2) ≤ B) + (htau : tau.width ≤ B) (ha : a.width ≤ B) (hv : (initial q).1.width ≤ B) + (hp : (initial q).2 ≤ Rp) (hc : ∀ i r, (child i r).1.width ≤ B) + (hR : ∀ i r, (child i r).2 ≤ R) + (hr : ∀ key ∈ (queryOnlineKeysWithWork N P F hP a (initial q).1 q).1, + (reader key (queryOnlineRangeWithWork parent P exponent H tau child key).1).work oracle readWork ≤ W) + (hnext : + let keys := (queryOnlineKeysWithWork N P F hP a (initial q).1 q).1 + (next keys (keys.map fun key => + (reader key (queryOnlineRangeWithWork parent P exponent H tau child key).1).value oracle)).work oracle readWork ≤ K) : + (queryOnlineSourceGather parent N P F exponent H hP tau a initial child q reader next).work oracle readWork ≤ + queryOnlineGatherBitBudget M P B Rp R W K := by + let keys := queryOnlineKeysWithWork N P F hP a (initial q).1 q + let range := queryOnlineRangeWithWork parent P exponent H tau child + have hk := queryOnlineKeysWithWork_bounds N P F B hP a (initial q).1 q hB hN hFb hF hPb hny ha hv + have hs := source_read_sum_bound keys.1 + (fun key => (range key).2 + (reader key (range key).1).work oracle readWork + 3) + (queryOnlineRangeBitBudget M P (B + 1) R + W + 3) (by + intro key hkey + have hb := queryOnlineKeysWithWork_scale N P F B hP a (initial q).1 q hN hF key hkey + have hc' := (queryOnlineRangeWithWork_bounds source target parent P exponent H (B + 1) R hP tau child key + (by omega) (by omega) (by omega) (by omega) hb (by omega) (by omega) (by omega) (by omega) + (htau.trans (by omega)) (fun i r => (hc i r).trans (by omega)) hR).2 + have hread := hr key hkey + change (range key).2 ≤ queryOnlineRangeBitBudget M P (B + 1) R at hc' + change (reader key (range key).1).work oracle readWork ≤ W at hread + omega) + have hs' := hs.trans (Nat.mul_le_mul_right _ hk.1) + have hkc : keys.2 ≤ queryOnlineKeysBitBudget B := hk.2 + change (next keys.1 (keys.1.map fun key => (reader key (range key).1).value oracle)).work oracle readWork ≤ K at hnext + rw [queryOnlineSourceGather_work] + change (initial q).2 + keys.2 + + (keys.1.map fun key => (range key).2 + (reader key (range key).1).work oracle readWork + 3).sum + + (next keys.1 (keys.1.map fun key => (reader key (range key).1).value oracle)).work oracle readWork ≤ _ + unfold queryOnlineGatherBitBudget + omega + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QuerySourceKeyWidths.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QuerySourceKeyWidths.lean new file mode 100644 index 0000000000000000000000000000000000000000..1348986ef79e27c0103c95a3c43b6ac27ab41af6 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QuerySourceKeyWidths.lean @@ -0,0 +1,62 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryGroupSourceCost +import OAI.Combinatorics.EditApproximation.Queries.QueryGroupKeyCost +import OAI.Combinatorics.EditApproximation.Queries.QuerySourceBufferBounds + +namespace OAI + +namespace EditApproximation + +theorem groupScalarKeys_fst_mem (M F Q : ℕ) (groups : List (ℕ × (ℕ × ℕ))) + (key : GroupScalarKey M F Q) (hk : key ∈ groupScalarKeys M F Q groups) : key.1 ∈ groups := by + obtain ⟨group, hg, hk⟩ := List.mem_flatMap.mp hk + obtain ⟨scale, _, hk⟩ := List.mem_flatMap.mp hk + obtain ⟨sample, _, rfl⟩ := List.mem_map.mp hk + exact hg + +namespace BinaryFraction + +theorem queryGroupKeySize_bound {n : ℕ} (M N F Q exponent eM eF B : ℕ) + (hMdef : M = 2 ^ eM) (hFdef : F = 2 ^ eF) (a value : BinaryFraction) (q : TargetInterval n) + (hB : 7 ≤ B) (hN : Nat.size N ≤ B) (hF : Nat.size F + 2 ≤ B) + (hM : Nat.size M ≤ B) (hes : 7 + eM + eF ≤ B) (he : exponent + 1 ≤ B) + (hn : Nat.size n ≤ B) (ha : a.width ≤ B) (hv : value.width ≤ B) (hw : 0 ≤ value.value) + (key : GroupScalarKey M F Q) + (hk : key.1 ∈ (queryGroupKeysWithWork N F exponent a value q).1) : + queryGroupKeySize key ≤ 40 * B + 500 := by + have hFpos : 1 ≤ F := by rw [hFdef]; exact Nat.succ_le_of_lt (Nat.two_pow_pos _) + have hk' := (queryGroupKeysWithWork_bounds N F exponent B a value q hB hN hF hFpos he hn ha hv hw).2.2 key.1 hk + obtain ⟨hb, ⟨eb, heb⟩, hleft, hright⟩ := hk' + have hlen : (groupDyadicScales M key.1.1 F).length = 7 + eM + eF := by + have h := congrArg List.length (computedGroupScales_value M key.1.1 F eM eb eF hMdef heb hFdef) + simpa only [List.length_map, groupScalesWithWork_length, nat_value] using h.symm + have hscale : Nat.size key.2.1.val ≤ B := by + have hv' : key.2.1.val ≤ B := by + have hi : key.2.1.val < (groupDyadicScales M key.1.1 F).length := key.2.1.isLt + have hl : (groupDyadicScales M key.1.1 F).length ≤ B := by rw [hlen]; exact hes + exact (Nat.le_of_lt hi).trans hl + exact (Nat.size_le_size hv').trans (Nat.size_le.mpr (Nat.lt_two_pow_self)) + have hsample : Nat.size key.2.2.val ≤ B := by + have hi := key.2.2.isLt + have hc : groupSampleCount M Q key.1.1 (groupDyadicScaleAt M key.1.1 F key.2.1) ≤ M := Nat.min_le_left _ _ + exact (Nat.size_le_size (show key.2.2.val ≤ M by omega)).trans hM + unfold queryGroupKeySize + omega + +theorem queryGroupSourceKeysWithWork_width {n : ℕ} (M N F Q exponent eM eF B : ℕ) + (hMdef : M = 2 ^ eM) (hFdef : F = 2 ^ eF) (a value : BinaryFraction) (q : TargetInterval n) + (hB : 7 ≤ B) (hN : Nat.size N ≤ B) (hF : Nat.size F + 2 ≤ B) + (hM : Nat.size M ≤ B) (hes : 7 + eM + eF ≤ B) (he : exponent + 1 ≤ B) + (hn : Nat.size n ≤ B) (ha : a.width ≤ B) (hv : value.width ≤ B) (hw : 0 ≤ value.value) : + ∀ key ∈ (queryGroupSourceKeysWithWork M N F Q exponent eM eF hMdef hFdef a value q).1, + queryGroupKeySize key ≤ 40 * B + 500 := by + intro key hk + rw [queryGroupSourceKeysWithWork_value] at hk + apply queryGroupKeySize_bound M N F Q exponent eM eF B hMdef hFdef a value q + hB hN hF hM hes he hn ha hv hw key + rw [queryGroupKeysWithWork_value] + exact groupScalarKeys_fst_mem M F Q _ key hk + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QuerySourceWidths.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QuerySourceWidths.lean new file mode 100644 index 0000000000000000000000000000000000000000..7f0fcf928179fbba1a63f2b4bd6888a858639fd4 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QuerySourceWidths.lean @@ -0,0 +1,84 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryFamilyScalarReads + +namespace OAI + +namespace EditApproximation.BitQuery + +theorem mapKeysWithWork_value {ι κ β : Type*} (f : ι → κ × ℕ) + (program : BitQuery ι β) (oracle : κ → BinaryFraction) : + (mapKeysWithWork f program).value oracle = program.value (fun key => oracle (f key).1) := by + induction program with + | done result => rfl + | charge steps next ih => exact ih + | read key next ih => exact ih (oracle (f key).1) + +end EditApproximation.BitQuery + +namespace EditApproximation +section Scalar +variable (M J N n exponent F Q R B : ℕ) + (oracle : PhysicalScalarKey M J N n exponent F Q R B → BinaryFraction) + (V : ℕ) (hV : 2 ≤ V) (hv : ∀ key, (oracle key).width ≤ V) + +private theorem group_width_transport (b c : ℕ) (h : b = c) + (actual : BitPhysicalGroupQueries M J N n exponent F Q R B b) + (hwidth : ∀ scale sample, ((actual scale sample).value oracle).width ≤ V) : + ∀ scale sample, + (((Eq.mp (congrArg (BitPhysicalGroupQueries M J N n exponent F Q R B) h) actual) + scale sample).value oracle).width ≤ V := by + subst c + exact hwidth + +include hV hv in +theorem queryPhysicalScalarGroupRead_width (node : PhysicalInternalNode M J) (time : Fin R) + (key : GroupScalarKey M F Q) : + ((queryPhysicalScalarGroupRead M J N n exponent F Q R B node time key).value oracle).width ≤ V := by + simp only [queryPhysicalScalarGroupRead, BitQuery.value] + unfold queryPhysicalScalarGroupQueries + split_ifs with hb hcell + · refine group_width_transport M J N n exponent F Q R B oracle V _ _ + (physicalScaleIndex_get N key.1.1 ((queryScalePresentWithWork_value N key.1.1).mp hb)) + _ ?_ key.2.1 key.2.2 + intro scale sample + exact hv _ + · exact (BinaryFraction.nat_width_le 0).trans (by simpa only [Nat.size_zero, Nat.zero_add] using hV) + · exact (BinaryFraction.nat_width_le 0).trans (by simpa only [Nat.size_zero, Nat.zero_add] using hV) + +include hV hv in +theorem queryPhysicalScalarOnlineRead_width (node : PhysicalInternalNode M J) (time : Fin R) + (key : ℕ × TargetInterval n) (range : ℕ) : + ((queryPhysicalScalarOnlineRead M J N n exponent F Q R B node time key range).value oracle).width ≤ V := by + unfold queryPhysicalScalarOnlineRead + simp only [BitQuery.value] + split_ifs + · exact hv _ + · exact (BinaryFraction.nat_width_le 0).trans (by simpa only [Nat.size_zero, Nat.zero_add] using hV) + · exact (BinaryFraction.nat_width_le 0).trans (by simpa only [Nat.size_zero, Nat.zero_add] using hV) + +end Scalar + +section Family +variable {α : Type*} {M J R : ℕ} (target : List α) + (N P F exponent H Q passes copies pass copy V : ℕ) + (oracle : PhysicalFamilyScalarKey (M := M) (J := J) (R := R) + target N P F exponent H Q passes copies → BinaryFraction) + (hV : 2 ≤ V) (hv : ∀ key, (oracle key).width ≤ V) + +include hV hv in +theorem queryFamilyGroupRead_width (node : PhysicalInternalNode M J) (time : Fin R) + (key : GroupScalarKey M F Q) : + ((queryFamilyGroupRead target N P F exponent H Q passes copies pass copy node time key).value oracle).width ≤ V := by + rw [queryFamilyGroupRead, BitQuery.mapKeysWithWork_value] + exact queryPhysicalScalarGroupRead_width M J N target.length exponent F Q R _ _ V hV (fun _ => hv _) node time key + +include hV hv in +theorem queryFamilyOnlineRead_width (node : PhysicalInternalNode M J) (time : Fin R) + (key : ℕ × TargetInterval target.length) (range : ℕ) : + ((queryFamilyOnlineRead target N P F exponent H Q passes copies pass copy node time key range).value oracle).width ≤ V := by + rw [queryFamilyOnlineRead, BitQuery.mapKeysWithWork_value] + exact queryPhysicalScalarOnlineRead_width M J N target.length exponent F Q R _ _ V hV (fun _ => hv _) node time key range + +end Family +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QuerySourceWork.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QuerySourceWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..eb379b1fa35d940fc84fc382a238013e27e5e0e0 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QuerySourceWork.lean @@ -0,0 +1,45 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryGroupSources +import OAI.Combinatorics.EditApproximation.Queries.QueryOnlineSources + +namespace OAI + +/-! Exact execution counters for both source gathers. The online counter +includes construction of every range before issuing its random read. -/ + +namespace EditApproximation + +theorem queryGroupSourceGather_work {ι β : Type*} {n : ℕ} + (M N F Q exponent eM eF : ℕ) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) + (a : BinaryFraction) (initial : TargetInterval n → BinaryFraction × ℕ) (q : TargetInterval n) + (reader : GroupScalarKey M F Q → BitQuery ι BinaryFraction) + (next : List (GroupScalarKey M F Q) → List BinaryFraction → BitQuery ι β) + (oracle : ι → BinaryFraction) (readWork : ι → ℕ) : + let keys := BinaryFraction.queryGroupSourceKeysWithWork M N F Q exponent eM eF hM hF a + (initial q).1 q + (queryGroupSourceGather M N F Q exponent eM eF hM hF a initial q reader next).work oracle readWork = + (initial q).2 + keys.2 + + (keys.1.map fun key => (reader key).work oracle readWork + 3).sum + + (next keys.1 (keys.1.map fun key => (reader key).value oracle)).work oracle readWork := by + simp only [queryGroupSourceGather, BitQuery.work_bind, BitQuery.work_collect, + BitQuery.compute, BitQuery.work, BitQuery.value, Nat.add_zero, Nat.add_assoc] + +theorem queryOnlineSourceGather_work {ι β : Type*} {nx ny M : ℕ} + (parent : TargetInterval nx) (N P F exponent H : ℕ) (hP : 0 < P) + (tau a : BinaryFraction) (initial : TargetInterval ny → BinaryFraction × ℕ) + (child : Fin M → TargetInterval ny → BinaryFraction × ℕ) (q : TargetInterval ny) + (reader : (ℕ × TargetInterval ny) → ℕ → BitQuery ι BinaryFraction) + (next : List (ℕ × TargetInterval ny) → List BinaryFraction → BitQuery ι β) + (oracle : ι → BinaryFraction) (readWork : ι → ℕ) : + let keys := BinaryFraction.queryOnlineKeysWithWork N P F hP a (initial q).1 q + let range := BinaryFraction.queryOnlineRangeWithWork parent P exponent H tau child + (queryOnlineSourceGather parent N P F exponent H hP tau a initial child q reader next).work + oracle readWork = + (initial q).2 + keys.2 + + (keys.1.map fun key => (range key).2 + (reader key (range key).1).work oracle readWork + 3).sum + + (next keys.1 (keys.1.map fun key => (reader key (range key).1).value oracle)).work oracle readWork := by + simp only [queryOnlineSourceGather, BitQuery.work_bind, BitQuery.value_bind, BitQuery.work_collect, + BitQuery.compute, BitQuery.work, BitQuery.value, Nat.add_zero, Nat.add_assoc] + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryTableSemanticCost.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryTableSemanticCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..0c1aec855f60982a231d8b115b2e26e0334777e9 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryTableSemanticCost.lean @@ -0,0 +1,129 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryChargedTableCost +import OAI.Combinatorics.EditApproximation.Queries.QueryChargedTableWidth +import OAI.Combinatorics.EditApproximation.Queries.QueryBoundedSemanticCost + +namespace OAI + +namespace EditApproximation +attribute [local irreducible] queryFamilyBoundedActive queryFamilyActive queryFamilyRefinement + queryPhysicalRandomDataRequest queryLocalProgram localRequestValue +open BinaryFraction + +section Table +variable {M J R passes copies T S : ℕ} [NeZero M] [NeZero R] + (source target : List ℕ) (N P F exponent H Q eM eF Amax B E Scale V C : ℕ) + (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) + (A a : ℕ → BinaryFraction) (tau eta kappa delta : BinaryFraction) (multiplier : ℕ → ℕ) + (occurrence : BinaryMemo PositionCounts) (symbolBits positionBits : ℕ) + (parent : {r : PhysicalTableRequest M J target.length // r.Bounded (passes + 1) copies T S}) + (oracle : ChargedFamilyQueryKey (R := R) target N P F exponent H Q (.inr parent) → BinaryFraction) + (readWork : ChargedFamilyQueryKey (R := R) target N P F exponent H Q (.inr parent) → ℕ) + (factor : ℕ → ℚ) + (group : ℕ → ℕ → PhysicalInternalNode M J → Fin R → CellGroupDraws M F Q) + (integer : ℕ → ℕ → PhysicalInternalNode M J → Fin R → ℕ → TargetInterval target.length → ℕ) + (initial : PhysicalEntry M J target.length → ℕ) + +local notation "requestValue" => localRequestValue source target N P F exponent H Q T S copies + factor multiplier tau.value eta.value kappa.value delta.value group integer initial +local notation "activeBudget" => queryLocalProgramBitBudget M N P F exponent eM eF B Scale (parent.val.index - T) + (queryPhysicalDataBudget T J B V (50 * B + 21 + (C + 1) + 1) + (queryFamilySourceReadBudget J B (50 * B + 21 + (C + 1) + 1 + 1))) + +theorem queryChargedFamilyTable_semantic_work_bound + (hn : PreparedKernelNumericBounds (nx := source.length) (ny := target.length) (M := M) + N P F exponent H Q eM eF B E Scale (parent.val.index - T - 1) + tau (a parent.val.pass) eta kappa delta (fun _ _ => 0)) + (hPd : ∃ j : ℕ, P = 2 ^ j) + (hV : 2 ≤ V) (hVB : V ≤ B) (hMean : warmupAverageWordBudget T V ≤ B) + (ht' : Nat.size (target.length + 1) + 2 ≤ B) + (hinit : Nat.size ((32 * F + 1) * N) + 3 ≤ B) + (hJ : Nat.size J ≤ B) (hi : Nat.size parent.val.index ≤ B) + (hT : Nat.size T ≤ B) (hS : Nat.size S ≤ B) + (hrank : Nat.size (parent.val.combinedRank T S) ≤ B) + (hA : (A parent.val.pass).width ≤ B) + (hAone : 1 ≤ (A parent.val.pass).value) (hAmax : (A parent.val.pass).value ≤ Amax) + (hp : Nat.size parent.val.pass ≤ B) (hcopy : Nat.size parent.val.copy ≤ B) + (hps : Nat.size (passes + 1) ≤ B) (hcs : Nat.size (copies + 1) ≤ B) + (hm : Nat.size (multiplier (parent.val.pass - 1)) + 2 ≤ B) + (hbound : Nat.size (localOnlineMassBound M P H) ≤ B) + (hv : ∀ key, (oracle (Sum.inr key)).width ≤ V) + (hsv : ∀ key, (oracle (Sum.inl key)).width ≤ B) + (hc : ∀ key, readWork key ≤ C) (hdelta : 0 ≤ delta.value) + (hread : ∀ child : {r : {r : PhysicalTableRequest M J target.length // r.Bounded (passes + 1) copies T S} // + r.val.combinedRank T S < parent.val.combinedRank T S}, + (oracle (Sum.inr ⟨Sum.inr child.val, ChargedPhysicalRequest.table_rank_lt parent child.val child.property⟩)).value = + requestValue child.val.val) : + (queryChargedFamilyTable (R := R) source target N P F exponent H Q eM eF hP hM hF A a tau eta kappa + delta multiplier occurrence symbolBits positionBits parent).work oracle readWork ≤ + queryChargedTableBitBudget M P F Amax copies J symbolBits positionBits B C activeBudget := by + have hMb : Nat.size M ≤ B := by have := hn.aritySize; omega + have hFpos : 1 ≤ F := by rw [hF]; exact Nat.one_le_two_pow + apply queryChargedFamilyTable_work_bound source target N P F exponent H Q eM eF Amax B C activeBudget + hP hM hF A a tau eta kappa delta multiplier occurrence symbolBits positionBits parent oracle readWork + hn.largeBits hn.inputSize hn.precisionSize hn.factorSize hFpos hn.sourceSize hn.targetSize ht' hinit + hMb hJ hi hT hA hn.factorWidth hAone hAmax hp hm (fun key => (hv key).trans hVB) hc + intro hindex hbelow + apply queryFamilyBoundedActive_work_bound source target N P F exponent H Q eM eF B E Scale hP hM hF + tau (a parent.val.pass) eta kappa delta T S passes copies parent hindex hbelow _ _ V (C + 1) hn + ((Nat.size_le_size (Nat.sub_le _ _)).trans hi) hPd hV hVB hMean + · intro key + have h := hc (Sum.map id (fun child => + ⟨Sum.inr child.val, ChargedPhysicalRequest.table_rank_lt parent child.val child.property⟩) key) + omega + · intro key + exact hv _ + · exact hsv + · intro child + change (oracle (Sum.inr ⟨Sum.inr child.val, _⟩)).value ≥ 0 + rw [hread child] + exact (localRequestValue_bounds source target N P F exponent H Q T S copies factor multiplier + tau.value eta.value kappa.value delta.value group integer initial hdelta child.val.val).1 + · exact queryFamilyBoundedActive_history_bound source target N P F exponent H Q T S passes copies + factor multiplier tau.value eta.value kappa.value delta.value group integer initial parent hindex hbelow + _ hdelta hread + · exact hp + · exact hcopy + · exact hps + · exact hcs + · exact hT + · exact hS + · exact hrank + · exact hbound + + +theorem queryChargedFamilyTable_semantic_width + (hn : PreparedKernelNumericBounds (nx := source.length) (ny := target.length) (M := M) + N P F exponent H Q eM eF B E Scale (parent.val.index - T - 1) + tau (a parent.val.pass) eta kappa delta (fun _ _ => 0)) + (ht' : Nat.size (target.length + 1) + 2 ≤ B) + (hinit : Nat.size ((32 * F + 1) * N) + 3 ≤ B) + (hi : Nat.size parent.val.index ≤ B) + (hv : ∀ key, (oracle (Sum.inr key)).width ≤ B) (hdelta : 0 ≤ delta.value) + (hread : ∀ child : {r : {r : PhysicalTableRequest M J target.length // r.Bounded (passes + 1) copies T S} // + r.val.combinedRank T S < parent.val.combinedRank T S}, + (oracle (Sum.inr ⟨Sum.inr child.val, ChargedPhysicalRequest.table_rank_lt parent child.val child.property⟩)).value = + requestValue child.val.val) : + ((queryChargedFamilyTable (R := R) source target N P F exponent H Q eM eF hP hM hF A a tau eta kappa + delta multiplier occurrence symbolBits positionBits parent).value oracle).width ≤ + localWarmupWordBudget M B + preparedKernelWordBudget M B := by + have hFpos : 1 ≤ F := by rw [hF]; exact Nat.one_le_two_pow + apply queryChargedFamilyTable_width source target N P F exponent H Q eM eF B hP hM hF A a tau eta kappa + delta multiplier occurrence symbolBits positionBits parent oracle hn.largeBits hn.inputSize + hn.precisionSize hn.factorSize hFpos hn.sourceSize hn.targetSize ht' hinit + (by have := hn.aritySize; omega) hn.factorWidth hv + intro hindex hbelow + apply queryFamilyBoundedActive_width source target N P F exponent H Q eM eF B E Scale hP hM hF + tau (a parent.val.pass) eta kappa delta T S passes copies parent hindex hbelow _ hn + ((Nat.size_le_size (Nat.sub_le _ _)).trans hi) + · intro child + exact hv _ + · intro child + change (oracle (Sum.inr ⟨Sum.inr child.val, _⟩)).value ≥ 0 + rw [hread child] + exact (localRequestValue_bounds source target N P F exponent H Q T S copies factor multiplier + tau.value eta.value kappa.value delta.value group integer initial hdelta child.val.val).1 + +end Table +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryWarmupBuffers.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryWarmupBuffers.lean new file mode 100644 index 0000000000000000000000000000000000000000..3cc37d656ad7d4304f1656092f7f3b01d6f169b2 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryWarmupBuffers.lean @@ -0,0 +1,63 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryLocalBuffers +import OAI.Combinatorics.EditApproximation.Queries.QueryRepresentatives +import OAI.Combinatorics.EditApproximation.Binary.BinaryWarmupReads +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation.BinaryFraction + + + +@[simp] theorem queryOverrideParentReadWithWork_value {n : ℕ} (value : BinaryFraction) + (q : TargetInterval n) (keys : List (TargetInterval n)) (words : List BinaryFraction) + (r : TargetInterval n) : + (queryOverrideParentReadWithWork value q keys words r).1.value = + if r = q then value.value else finiteAnswerTable keys (words.map BinaryFraction.value) r := by + unfold queryOverrideParentReadWithWork + by_cases hr : r = q + · rw [ite_eq_left ((queryIntervalEqualWithWork_value r q).mpr hr), ite_eq_left hr] + · rw [ite_eq_right (fun h => hr ((queryIntervalEqualWithWork_value r q).mp h)), ite_eq_right hr] + exact queryParentReadWithWork_value keys words r + +theorem queryOverrideParentReadWithWork_cost {n : ℕ} (value : BinaryFraction) + (q : TargetInterval n) (keys : List (TargetInterval n)) (words : List BinaryFraction) + (r : TargetInterval n) : + (queryOverrideParentReadWithWork value q keys words r).2 ≤ + 16 * Nat.size n + 7 + keys.length * (16 * Nat.size n + 6) := by + have ht := queryIntervalEqualWithWork_cost r q (Nat.size n) le_rfl + have hr := queryParentReadWithWork_cost keys words r + unfold queryOverrideParentReadWithWork + dsimp only + split_ifs <;> dsimp only <;> omega + + + +theorem queryWarmupInputsWithWork_value {nx ny : ℕ} (M : ℕ) (parent : TargetInterval nx) + (N P F : ℕ) (hP : 0 < P) (a : BinaryFraction) + (initial : TargetInterval ny → BinaryFraction × ℕ) (q : TargetInterval ny) + (I : ℕ) (hi : ∀ r, (initial r).2 ≤ I) : + (queryWarmupInputsWithWork M parent N P F a initial q).1 = + wideWarmupInputs parent P + (localRefinementRepresentatives N P F a.value (fun r => (initial r).1.value) q) := by + simp only [queryWarmupInputsWithWork, queryWideInputsWithWork_value _ _ _ hP, + (localRepresentativeReadWithWork_eq_cost N P F a initial q I hi).1, + localRepresentativesWithWork_value N P F hP] + +theorem localWarmupReadKernelWithWork_value_only {nx ny M : ℕ} (parent : TargetInterval nx) + (N P F : ℕ) (hP : 0 < P) (a : BinaryFraction) + (initial : TargetInterval ny → BinaryFraction × ℕ) + (child : Fin M × TargetInterval ny → BinaryFraction × ℕ) (q : TargetInterval ny) + (I : ℕ) (hi : ∀ r, (initial r).2 ≤ I) : + (localWarmupReadKernelWithWork parent N P F a initial child q).1.value = + rationalBellman (fun r => (initial r).1.value) (fun q r => targetEndpointDistance q r) (128 * F) + (rationalActualWideActions parent + (localRefinementRepresentatives N P F a.value (fun r => (initial r).1.value) q) P) + (fun input => (child input).1.value) q := by + rw [localWarmupReadKernelWithWork_eq parent N P F a initial child q I hi] + exact localWarmupKernelWithWork_value parent N P F hP a _ _ q + +end EditApproximation.BinaryFraction + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryWarmupProgram.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryWarmupProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..063ca71349ecf924ef942a09adcc9f04820df20d --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryWarmupProgram.lean @@ -0,0 +1,62 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryWarmupBuffers +import OAI.Combinatorics.EditApproximation.Binary.BitQuery +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! A warmup step uses two adaptive gathers. The first determines its +representatives; the second requests exactly their distinct child states. -/ + +namespace EditApproximation + +section Warmup +variable {ι : Type*} {nx ny M : ℕ} (parent : TargetInterval nx) + (N P F : ℕ) (hP : 0 < P) (a : BinaryFraction) + (initialRead : TargetInterval ny → BitQuery ι BinaryFraction) + (childRead : (Fin M × TargetInterval ny) → BitQuery ι BinaryFraction) + (q : TargetInterval ny) + + + +include hP in +theorem queryWarmupProgram_refines + (expectedInitial : TargetInterval ny → FiniteQuery ι) + (expectedChild : (Fin M × TargetInterval ny) → FiniteQuery ι) + (hi : ∀ r, BitQuery.Refines (fun word value => word.value = value) (initialRead r) (expectedInitial r)) + (hc : ∀ input, BitQuery.Refines (fun word value => word.value = value) + (childRead input) (expectedChild input)) : + BitQuery.Refines (fun word value => word.value = value) + (queryWarmupProgram parent N P F a initialRead childRead q) + (localWarmupStepQuery parent N P F a.value expectedInitial expectedChild q) := by + unfold queryWarmupProgram localWarmupStepQuery + apply (hi q).bind + intro value answer hv + subst answer + apply BitQuery.Refines.charge + change BitQuery.Refines _ (BitQuery.collect initialRead _ _) _ + rw [BinaryFraction.queryRawCentersWithWork_value N P F hP] + apply BitQuery.Refines.collect initialRead expectedInitial hi + intro words + let centers := rawRefinementCenters N P F a.value value.value q + let initial := BinaryFraction.queryOverrideParentReadWithWork value q centers words + let I := 16 * Nat.size ny + 7 + centers.length * (16 * Nat.size ny + 6) + have hI (r : TargetInterval ny) : (initial r).2 ≤ I := + BinaryFraction.queryOverrideParentReadWithWork_cost value q centers words r + apply BitQuery.Refines.charge + change BitQuery.Refines _ (BitQuery.collect childRead _ _) _ + rw [BinaryFraction.queryWarmupInputsWithWork_value M parent N P F hP a initial q I hI] + simp only [initial, BinaryFraction.queryOverrideParentReadWithWork_value] + apply BitQuery.Refines.collect childRead expectedChild hc + intro childWords + apply BitQuery.Refines.charge + apply BitQuery.Refines.done + rw [BinaryFraction.localWarmupReadKernelWithWork_value_only parent N P F hP a initial _ q I hI] + simp only [initial, BinaryFraction.queryOverrideParentReadWithWork_value, + BinaryFraction.queryChildReadWithWork_value] + rfl + +end Warmup +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryWarmupProgramCost.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryWarmupProgramCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..3bae5de225988409bc0aad1e258382e006993978 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryWarmupProgramCost.lean @@ -0,0 +1,148 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryWarmupProgram +import OAI.Combinatorics.EditApproximation.Queries.QueryBandInputCost +import OAI.Combinatorics.EditApproximation.Binary.BinaryLocalWarmupWork + +namespace OAI + +namespace EditApproximation.BinaryFraction + +def queryWarmupRepresentatives (P F B : ℕ) : ℕ := (B + 1) * (64 * F * P + 2) ^ 2 + +def queryWarmupInputsBitBudget (M P F B I : ℕ) : ℕ := + localRepresentativesBitBudget P F B * (I + 2) + + queryWideInputsBitBudget M P (queryWarmupRepresentatives P F B) B + 1 + +theorem queryWarmupInputsWithWork_bounds {nx ny : ℕ} (M N P F B I : ℕ) + (parent : TargetInterval nx) (hP : 0 < P) (a : BinaryFraction) + (initial : TargetInterval ny → BinaryFraction × ℕ) (q : TargetInterval ny) + (hB : 8 ≤ B) (hN : Nat.size N ≤ B) (hF : Nat.size F + 2 ≤ B) (hFpos : 1 ≤ F) + (hPb : Nat.size P ≤ B) (hnx : Nat.size nx ≤ B) (hny : Nat.size ny ≤ B) + (hM : Nat.size M ≤ B) (ha : a.width ≤ B) + (hi : ∀ r, (initial r).1.width ≤ B) (hI : ∀ r, (initial r).2 ≤ I) : + (queryWarmupInputsWithWork M parent N P F a initial q).1.length ≤ + queryWarmupRepresentatives P F B * (M * (40 * P + 2) ^ 2) ∧ + (queryWarmupInputsWithWork M parent N P F a initial q).2 ≤ + queryWarmupInputsBitBudget M P F B I := by + let reps := localRepresentativeReadWithWork N P F a initial q + have heq := (localRepresentativeReadWithWork_eq_cost N P F a initial q I hI).1 + have hlen : reps.1.length ≤ queryWarmupRepresentatives P F B := by + rw [show reps.1 = _ from heq] + exact localRepresentativesWithWork_length_le N P F B hP hFpos a _ q hN + have hscale : ∀ br ∈ reps.1, br.1 ∈ dyadicScales N := by + intro br hb + rw [show reps.1 = _ from heq, localRepresentativesWithWork_value N P F hP] at hb + exact (representativeList_conditions a.value (fun r => (initial r).1.value) + (localRefinementRepresentatives_subset N P F a.value (fun r => (initial r).1.value) q br hb)).1 + have hw := queryWideInputsWithWork_dyadic_bounds M N P (queryWarmupRepresentatives P F B) B + parent hP reps.1 hlen hscale hN hnx hny hM hPb + have hr := localRepresentativeReadWithWork_cost N P F B I a initial q (by omega) + hN hF hFpos hPb hP hny ha hi hI + exact ⟨hw.1, Nat.add_le_add_right (Nat.add_le_add hr hw.2) 1⟩ + +def queryWarmupParentReadBudget (P F B : ℕ) : ℕ := + 16 * B + 7 + queryWarmupRepresentatives P F B * (16 * B + 6) + +def queryWarmupChildReadBudget (M P F B : ℕ) : ℕ := + 1 + (queryWarmupRepresentatives P F B * (M * (40 * P + 2) ^ 2)) * (24 * B + 9) + +def queryWarmupProgramBitBudget (M P F B C : ℕ) : ℕ := + C + queryRawCentersBitBudget P F B + queryWarmupRepresentatives P F B * (C + 3) + + queryWarmupInputsBitBudget M P F B (queryWarmupParentReadBudget P F B) + + (queryWarmupRepresentatives P F B * (M * (40 * P + 2) ^ 2)) * (C + 3) + + localWarmupBitBudget M P F B * + (queryWarmupParentReadBudget P F B + M * (queryWarmupChildReadBudget M P F B + 3) + 4) + +end EditApproximation.BinaryFraction + +namespace EditApproximation +open BinaryFraction + +private theorem warmup_read_sum {κ : Type*} (keys : List κ) (cost : κ → ℕ) (C : ℕ) + (hc : ∀ key, cost key ≤ C) : (keys.map cost).sum ≤ keys.length * C := by + induction keys with + | nil => simp + | cons key keys ih => + have h := hc key + simp only [List.map_cons, List.sum_cons, List.length_cons, Nat.add_mul, Nat.one_mul] + omega + +theorem queryWarmupProgram_work_bound {ι : Type*} {nx ny M : ℕ} + (parent : TargetInterval nx) (N P F B C : ℕ) (hP : 0 < P) (a : BinaryFraction) + (initialRead : TargetInterval ny → BitQuery ι BinaryFraction) + (childRead : (Fin M × TargetInterval ny) → BitQuery ι BinaryFraction) + (q : TargetInterval ny) (oracle : ι → BinaryFraction) (readWork : ι → ℕ) + (hB : 10 ≤ B) (hN : Nat.size N ≤ B) (hF : Nat.size F + 2 ≤ B) (hFpos : 1 ≤ F) + (hPb : Nat.size P ≤ B) (hnx : Nat.size nx + 2 ≤ B) (hny : Nat.size ny + 2 ≤ B) + (hM : Nat.size M ≤ B) (ha : a.width ≤ B) + (hi : ∀ r, ((initialRead r).value oracle).width ≤ B) + (hc : ∀ r, ((childRead r).value oracle).width ≤ B) + (hiC : ∀ r, (initialRead r).work oracle readWork ≤ C) + (hcC : ∀ r, (childRead r).work oracle readWork ≤ C) : + (queryWarmupProgram parent N P F a initialRead childRead q).work oracle readWork ≤ + queryWarmupProgramBitBudget M P F B C := by + let value := (initialRead q).value oracle + let centers := queryRawCentersWithWork N P F a value q + let words := centers.1.map fun r => (initialRead r).value oracle + let initial := queryOverrideParentReadWithWork value q centers.1 words + let inputs := queryWarmupInputsWithWork M parent N P F a initial q + let childWords := inputs.1.map fun input => (childRead input).value oracle + let child := fun input : Fin M × TargetInterval ny => queryChildReadWithWork inputs.1 childWords input.1 input.2 + have hcenters := queryRawCentersWithWork_bounds N P F B a value q (by omega) hN hF hFpos hP hPb + (by omega) ha (hi q) + have hiW : ∀ r, (initial r).1.width ≤ B := by + intro r + unfold initial queryOverrideParentReadWithWork + dsimp only + split_ifs + · exact hi q + · exact gatheredWordLookupWithWork_width _ centers.1 words r B (by omega) (by + intro w hw + obtain ⟨key, _, rfl⟩ := List.mem_map.mp hw + exact hi key) + have hiR : ∀ r, (initial r).2 ≤ queryWarmupParentReadBudget P F B := by + intro r + apply (queryOverrideParentReadWithWork_cost value q centers.1 words r).trans + unfold queryWarmupParentReadBudget + exact Nat.add_le_add (by omega) (Nat.mul_le_mul hcenters.1 (by omega)) + have hinputs := queryWarmupInputsWithWork_bounds M N P F B _ parent hP a initial q (by omega) + hN hF hFpos hPb (by omega) (by omega) hM ha hiW hiR + have hcW : ∀ input, (child input).1.width ≤ B := by + intro input + exact gatheredWordLookupWithWork_width _ inputs.1 childWords input B (by omega) (by + intro w hw + obtain ⟨key, _, rfl⟩ := List.mem_map.mp hw + exact hc key) + have hcR : ∀ input, (child input).2 ≤ queryWarmupChildReadBudget M P F B := by + intro input + exact (queryChildReadWithWork_cost inputs.1 childWords input.1 input.2 B hM (by omega)).trans + (Nat.add_le_add_left (Nat.mul_le_mul_right _ hinputs.1) 1) + have hkernel := (localWarmupReadKernelWithWork_cost parent N P F a initial child q _ _ hiR hcR).trans + (Nat.mul_le_mul_right _ (localWarmupKernelWithWork_bounds parent N P F B hP hFpos a + (fun r => (initial r).1) (fun input => (child input).1) q hB hN hnx hny hM hPb hF ha hiW hcW).2) + have hsumI := (warmup_read_sum centers.1 (fun r => (initialRead r).work oracle readWork + 3) + (C + 3) (fun r => Nat.add_le_add_right (hiC r) 3)).trans (Nat.mul_le_mul_right _ hcenters.1) + have hsumC := (warmup_read_sum inputs.1 (fun r => (childRead r).work oracle readWork + 3) + (C + 3) (fun r => Nat.add_le_add_right (hcC r) 3)).trans (Nat.mul_le_mul_right _ hinputs.1) + have hq := hiC q + have hcentercost : centers.2 ≤ queryRawCentersBitBudget P F B := hcenters.2 + have hinputcost : inputs.2 ≤ queryWarmupInputsBitBudget M P F B (queryWarmupParentReadBudget P F B) := hinputs.2 + simp only [queryWarmupProgram, BitQuery.work_bind, BitQuery.work_collect, + BitQuery.compute, BitQuery.work, BitQuery.value, Nat.add_zero] + change (initialRead q).work oracle readWork + (centers.2 + + ((centers.1.map fun r => (initialRead r).work oracle readWork + 3).sum + + (inputs.2 + ((inputs.1.map fun r => (childRead r).work oracle readWork + 3).sum + + (localWarmupReadKernelWithWork parent N P F a initial child q).2)))) ≤ _ + calc + _ ≤ C + (queryRawCentersBitBudget P F B + + (queryWarmupRepresentatives P F B * (C + 3) + + (queryWarmupInputsBitBudget M P F B (queryWarmupParentReadBudget P F B) + + ((queryWarmupRepresentatives P F B * (M * (40 * P + 2) ^ 2)) * (C + 3) + + localWarmupBitBudget M P F B * + (queryWarmupParentReadBudget P F B + M * (queryWarmupChildReadBudget M P F B + 3) + 4))))) := + Nat.add_le_add hq (Nat.add_le_add hcentercost + (Nat.add_le_add hsumI (Nat.add_le_add hinputcost (Nat.add_le_add hsumC hkernel)))) + _ = _ := by unfold queryWarmupProgramBitBudget; omega + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryWarmupSpace.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryWarmupSpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..120c6b278219bed959e7123252cc4300fa1e855e --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryWarmupSpace.lean @@ -0,0 +1,56 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryGatherSpace +import OAI.Combinatorics.EditApproximation.Queries.QueryContinuationSpace +import OAI.Combinatorics.EditApproximation.Queries.QueryWarmupProgram +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation +namespace BinaryFraction + + + +theorem queryOverrideParentReadAllocation_le_work {n : ℕ} (value : BinaryFraction) (q : TargetInterval n) + (keys : List (TargetInterval n)) (words : List BinaryFraction) (r : TargetInterval n) : + queryOverrideParentReadAllocation q keys words r ≤ + (queryOverrideParentReadWithWork value q keys words r).2 := by + have he := queryIntervalEqualAllocation_le_work r q + have hp := queryParentReadAllocation_le_work keys words r + unfold queryOverrideParentReadAllocation queryOverrideParentReadWithWork + dsimp only + split_ifs <;> dsimp only <;> omega + +end BinaryFraction +open BitQuery BinaryFraction + +def queryWarmupProgramHeap {ι : Type*} {nx ny M : ℕ} (parent : TargetInterval nx) + (N P F : ℕ) (a : BinaryFraction) + (initialRead : TargetInterval ny → BitQuery ι BinaryFraction) + (childRead : (Fin M × TargetInterval ny) → BitQuery ι BinaryFraction) (q : TargetInterval ny) + (hi : ∀ r, Heap (initialRead r)) (hc : ∀ key, Heap (childRead key)) : + Heap (queryWarmupProgram parent N P F a initialRead childRead q) := + (hi q).bind _ fun value => + (Heap.computeOf (queryRawCentersWithWork N P F a value q) + (queryRawCentersAllocation N P F a value q) (queryRawCentersAllocation_le_work N P F a value q)).bind _ fun centers => + Heap.collect initialRead hi centers _ fun words => + let initial := queryOverrideParentReadWithWork value q centers words + let allocation := queryOverrideParentReadAllocation q centers words + let halloc := queryOverrideParentReadAllocation_le_work value q centers words + (Heap.computeOf (queryWarmupInputsWithWork M parent N P F a initial q) + (queryWarmupInputsAllocation M parent N P F a initial allocation q) + (queryWarmupInputsAllocation_le_work M parent N P F a initial allocation q halloc)).bind _ fun inputs => + Heap.collect childRead hc inputs _ fun childWords => + Heap.computeOf (localWarmupReadKernelWithWork parent N P F a initial + (fun input => queryChildReadWithWork inputs childWords input.1 input.2) q) + (localWarmupReadAllocation parent N P F a initial allocation + (fun input => queryChildReadWithWork inputs childWords input.1 input.2) + (fun input => queryChildReadAllocation inputs childWords input.1 input.2) q) + (localWarmupReadAllocation_le_work parent N P F a initial allocation + (fun input => queryChildReadWithWork inputs childWords input.1 input.2) + (fun input => queryChildReadAllocation inputs childWords input.1 input.2) q halloc + (fun input => queryChildReadAllocation_le_work inputs childWords input.1 input.2)) + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryWarmupUniformCost.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryWarmupUniformCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..b70c41853661f16962f407b8283d13daec78529a --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryWarmupUniformCost.lean @@ -0,0 +1,79 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryInitialWarmupPolynomial + +namespace OAI + +namespace EditApproximation + +attribute [local irreducible] preparedCachedInitialBitDegree preparedMedianBitDegree + preparedWarmupBitDegree queryInitialWarmupBitDegree + +def queryInitialWarmupPrimitiveDegree : ℕ := + max 1 (max preparedCachedInitialBitDegree (max preparedMedianBitDegree preparedWarmupBitDegree)) + +def queryInitialWarmupDegree : ℕ := + 16 * queryInitialWarmupPrimitiveDegree * queryInitialWarmupBitDegree + +theorem queryChargedWarmupBitBudget_uniform_cap (M P F Amax copies J symbolBits positionBits B C X : ℕ) + (hX : 64 ≤ X) (hM : M ≤ X) (hP : P ≤ X) (hF : F ≤ X) (hA : Amax ≤ X) + (hc : copies ≤ X) (hJ : J ≤ X) (hs : symbolBits ≤ X) (hp : positionBits ≤ X) + (hB : B ≤ X) (hC : C ≤ X) + (hV : (40 * P + 2) ^ (2 * M) ≤ X) + (hCart : ((40 * P + 2) ^ 2 + 1) ^ (M + 1) ≤ X) : + queryChargedWarmupBitBudget M P F Amax copies J symbolBits positionBits B C ≤ + X ^ queryInitialWarmupDegree := by + have hpos : 0 < X := by omega + have hXX : X ≤ X ^ 16 := Nat.le_pow (by decide) + have hB4 : B + 4 ≤ X ^ 16 := by + have : B + 4 ≤ X ^ 2 := by nlinarith only [hB, hX] + exact this.trans (Nat.pow_le_pow_right hpos (by decide)) + have hside : 64 * Amax ^ 2 * P + 2 ≤ X ^ 16 := by + have hprod := Nat.mul_le_mul (Nat.pow_le_pow_left hA 2) hP + have hcoef : 66 ≤ X ^ 2 := by nlinarith only [hX] + calc + _ ≤ 66 * (X ^ 2 * X) := by nlinarith only [hprod, hX] + _ ≤ X ^ 2 * (X ^ 2 * X) := Nat.mul_le_mul_right _ hcoef + _ = X ^ 5 := by ring + _ ≤ _ := Nat.pow_le_pow_right hpos (by decide) + have hrepSide : 64 * F * P + 2 ≤ X ^ 4 := by + have hprod := Nat.mul_le_mul hF hP + have hcoef : 66 ≤ X ^ 2 := by nlinarith only [hX] + calc + _ ≤ 66 * X ^ 2 := by nlinarith only [hprod, hX] + _ ≤ X ^ 2 * X ^ 2 := Nat.mul_le_mul_right _ hcoef + _ = _ := by ring + have hrep : (B + 1) * (64 * F * P + 2) ^ 2 ≤ X ^ 16 := by + calc + _ ≤ X ^ 2 * (X ^ 4) ^ 2 := Nat.mul_le_mul (by nlinarith only [hB, hX]) + (Nat.pow_le_pow_left hrepSide 2) + _ = X ^ 10 := by ring + _ ≤ _ := Nat.pow_le_pow_right hpos (by decide) + have h16 : 2 ≤ X ^ 16 := (by omega : 2 ≤ X).trans hXX + have hi := cachedInitialProgramBitBudget_fixedPower P Amax (B + 2) (X ^ 16) h16 (by omega) hside + have hm := seedMedianBitBudget_fixedPower copies B (X ^ 16) h16 (hc.trans hXX) (hB.trans hXX) + have hw := cachedWarmupBitBudget_fixedPower M P F B (X ^ 16) h16 (hM.trans hXX) + (hP.trans hXX) (hF.trans hXX) hB4 hrep (hV.trans hXX) (hCart.trans hXX) + have hid : preparedCachedInitialBitDegree ≤ queryInitialWarmupPrimitiveDegree := by + unfold queryInitialWarmupPrimitiveDegree; omega + have hmd : preparedMedianBitDegree ≤ queryInitialWarmupPrimitiveDegree := by + unfold queryInitialWarmupPrimitiveDegree; omega + have hwd : preparedWarmupBitDegree ≤ queryInitialWarmupPrimitiveDegree := by + unfold queryInitialWarmupPrimitiveDegree; omega + have hbase : X ≤ (X ^ 16) ^ queryInitialWarmupPrimitiveDegree := + hXX.trans (Nat.le_pow (Nat.le_max_left _ _)) + have hY : 2 ≤ (X ^ 16) ^ queryInitialWarmupPrimitiveDegree := (by omega : 2 ≤ X).trans hbase + have hw0 : BinaryFraction.localWarmupBitBudget M P F B ≤ (X ^ 16) ^ preparedWarmupBitDegree := by + omega + have hwp : BinaryFraction.localWarmupBitBudget M P F B ≤ + (X ^ 16) ^ queryInitialWarmupPrimitiveDegree := + hw0.trans (Nat.pow_le_pow_right (pow_pos hpos 16) hwd) + have h := queryChargedWarmupBitBudget_fixedPower M P F Amax copies J symbolBits positionBits B C + ((X ^ 16) ^ queryInitialWarmupPrimitiveDegree) hY + (hM.trans hbase) (hP.trans hbase) (hF.trans hbase) (hA.trans hbase) (hc.trans hbase) + (hJ.trans hbase) (hs.trans hbase) (hp.trans hbase) (hB.trans hbase) (hC.trans hbase) + (hi.trans (Nat.pow_le_pow_right (by positivity) hid)) + (hm.trans (Nat.pow_le_pow_right (by positivity) hmd)) hwp + simpa only [← pow_mul, queryInitialWarmupDegree] using h + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryWarmupWidth.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryWarmupWidth.lean new file mode 100644 index 0000000000000000000000000000000000000000..ea70015eb346aeb7c85398de1ea526521cbc9e85 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryWarmupWidth.lean @@ -0,0 +1,86 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryWarmupProgramCost +import OAI.Combinatorics.EditApproximation.Queries.QueryChargedWarmupCost + +namespace OAI + +namespace EditApproximation +open BinaryFraction + +theorem queryWarmupProgram_width {ι : Type*} {nx ny M : ℕ} + (parent : TargetInterval nx) (N P F B : ℕ) (hP : 0 < P) (a : BinaryFraction) + (initialRead : TargetInterval ny → BitQuery ι BinaryFraction) + (childRead : (Fin M × TargetInterval ny) → BitQuery ι BinaryFraction) + (q : TargetInterval ny) (oracle : ι → BinaryFraction) + (hB : 10 ≤ B) (hN : Nat.size N ≤ B) (hF : Nat.size F + 2 ≤ B) (hFpos : 1 ≤ F) + (hPb : Nat.size P ≤ B) (hnx : Nat.size nx + 2 ≤ B) (hny : Nat.size ny + 2 ≤ B) + (hM : Nat.size M ≤ B) (ha : a.width ≤ B) + (hi : ∀ r, ((initialRead r).value oracle).width ≤ B) + (hc : ∀ r, ((childRead r).value oracle).width ≤ B) : + ((queryWarmupProgram parent N P F a initialRead childRead q).value oracle).width ≤ + localWarmupWordBudget M B := by + let value := (initialRead q).value oracle + let centers := queryRawCentersWithWork N P F a value q + let words := centers.1.map fun r => (initialRead r).value oracle + let initial := queryOverrideParentReadWithWork value q centers.1 words + let inputs := queryWarmupInputsWithWork M parent N P F a initial q + let childWords := inputs.1.map fun input => (childRead input).value oracle + let child := fun input : Fin M × TargetInterval ny => queryChildReadWithWork inputs.1 childWords input.1 input.2 + have hiW : ∀ r, (initial r).1.width ≤ B := by + intro r + unfold initial queryOverrideParentReadWithWork + dsimp only + split_ifs + · exact hi q + · exact gatheredWordLookupWithWork_width _ centers.1 words r B (by omega) (by + intro w hw + obtain ⟨key, _, rfl⟩ := List.mem_map.mp hw + exact hi key) + have hcW : ∀ input, (child input).1.width ≤ B := by + intro input + exact gatheredWordLookupWithWork_width _ inputs.1 childWords input B (by omega) (by + intro w hw + obtain ⟨key, _, rfl⟩ := List.mem_map.mp hw + exact hc key) + have hw := (localWarmupKernelWithWork_bounds parent N P F B hP hFpos a + (fun r => (initial r).1) (fun input => (child input).1) q hB hN hnx hny hM hPb hF ha hiW hcW).1 + rw [← localWarmupReadKernelWithWork_eq parent N P F a initial child q + (16 * Nat.size ny + 7 + centers.1.length * (16 * Nat.size ny + 6)) + (queryOverrideParentReadWithWork_cost value q centers.1 words)] at hw + simpa only [queryWarmupProgram, BitQuery.value_bind, BitQuery.value_collect, + BitQuery.compute, BitQuery.value] using hw + +theorem queryChargedWarmup_width (source target : List ℕ) {M J passes copies T S : ℕ} + (N P F B : ℕ) (A a : BinaryFraction) (multiplier : ℕ → ℕ) + (parent : {r : PhysicalTableRequest M J target.length // r.Bounded passes copies T S}) + (occurrence : BinaryMemo PositionCounts) (symbolBits positionBits : ℕ) + (oracle : {child : ChargedPhysicalRequest M J target.length passes copies T S // + child.rank < ChargedPhysicalRequest.rank (.inr parent)} → BinaryFraction) + (hB : 10 ≤ B) (hP : 0 < P) (hN : Nat.size N ≤ B) (hPb : Nat.size P ≤ B) + (hF : Nat.size F + 2 ≤ B) (hFpos : 1 ≤ F) + (hs : Nat.size source.length + 2 ≤ B) (ht : Nat.size target.length + 2 ≤ B) + (ht' : Nat.size (target.length + 1) + 2 ≤ B) + (hinit : Nat.size ((32 * F + 1) * N) + 3 ≤ B) + (hM : Nat.size M ≤ B) (ha : a.width ≤ B) + (hv : ∀ key, (oracle key).width ≤ B) : + ((queryChargedWarmup source target N P F A a multiplier parent occurrence symbolBits positionBits).value + oracle).width ≤ localWarmupWordBudget M B := by + have hi (q : TargetInterval target.length) := queryPhysicalInitial_width source target N P F B A a + multiplier parent occurrence symbolBits positionBits oracle q hP ht' hinit + have hsmall : B ≤ localWarmupWordBudget M B := by + unfold localWarmupWordBudget physicalContinuationInputBudget + dsimp only + omega + unfold queryChargedWarmup + simp only [BitQuery.value] + split + · exact (hi _).trans hsmall + · split + · split + · exact (hi _).trans hsmall + · exact queryWarmupProgram_width _ N P F B hP a _ _ _ oracle hB hN hF hFpos hPb hs ht hM ha hi + (fun _ => hv _) + · exact (hi _).trans hsmall + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryWeightedWork.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryWeightedWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..964b6d8a6dfd4d817097f527db9127c793baecd5 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryWeightedWork.lean @@ -0,0 +1,95 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryDependencyExpansion + +namespace OAI + +/-! Per-request local work summed along the actual adaptive expansion. +This is a weighted analogue of the uncached request count. -/ + +namespace EditApproximation + +open Finset + +def rankedUncachedWork {κ : Type*} (rank : κ → ℕ) + (program : (key : κ) → FiniteQuery {child : κ // rank child < rank key}) + (weight : κ → ℕ) (key : κ) : ℕ := + (program key).cost (fun child => rankedProgramValue rank program child.val) + (fun child => rankedUncachedWork rank program weight child.val) + weight key +termination_by rank key +decreasing_by exact child.property + +section Weighted + +variable {κ : Type*} (depth index : κ → ℕ) + (program : (key : κ) → FiniteQuery + {child : κ // depth child + index child < depth key + index key}) + (progress : ∀ key child, child ∈ queryRequestList depth index program key → + (depth child < depth key ∧ index child ≤ index key) ∨ + (depth child ≤ depth key ∧ index child < index key)) + +theorem queryDependencyExpansion_weighted (weight : ℕ → ℕ) (root : κ) : + (queryDependencyExpansion depth index program progress root).depthWeightedCount weight = + rankedUncachedWork (fun key => depth key + index key) program (fun key => weight (depth key)) root := by + have hall : ∀ level root, depth root + index root = level → + (queryDependencyExpansion depth index program progress root).depthWeightedCount weight = + rankedUncachedWork (fun key => depth key + index key) program (fun key => weight (depth key)) root := by + intro level + induction level using Nat.strong_induction_on with + | h level ih => + intro root hroot + conv_lhs => unfold queryDependencyExpansion + rw [DependencyExpansion.build] + change weight (depth root) + (∑ i : Fin (querySameRequests depth index program root).length, + (queryDependencyExpansion depth index program progress + ((querySameRequests depth index program root).get i)).depthWeightedCount weight) + + (∑ i : Fin (queryEarlierRequests depth index program root).length, + (queryDependencyExpansion depth index program progress + ((queryEarlierRequests depth index program root).get i)).depthWeightedCount weight) = _ + have hs (i : Fin (querySameRequests depth index program root).length) := + querySameRequests_progress depth index program progress root i + have he (i : Fin (queryEarlierRequests depth index program root).length) := + queryEarlierRequests_progress depth index program progress root i + have hsame : (∑ i : Fin (querySameRequests depth index program root).length, + (queryDependencyExpansion depth index program progress + ((querySameRequests depth index program root).get i)).depthWeightedCount weight) = + (((querySameRequests depth index program root).map + (rankedUncachedWork (fun key => depth key + index key) program (fun key => weight (depth key)))).sum) := by + calc + _ = ∑ i : Fin (querySameRequests depth index program root).length, + rankedUncachedWork (fun key => depth key + index key) program (fun key => weight (depth key)) + ((querySameRequests depth index program root).get i) := by + apply sum_congr rfl + intro i hi + apply ih _ _ _ rfl + rw [← hroot] + exact Nat.add_lt_add_of_lt_of_le (hs i).1 (hs i).2 + _ = _ := Fin.sum_univ_fun_getElem _ _ + have hearlier : (∑ i : Fin (queryEarlierRequests depth index program root).length, + (queryDependencyExpansion depth index program progress + ((queryEarlierRequests depth index program root).get i)).depthWeightedCount weight) = + (((queryEarlierRequests depth index program root).map + (rankedUncachedWork (fun key => depth key + index key) program (fun key => weight (depth key)))).sum) := by + calc + _ = ∑ i : Fin (queryEarlierRequests depth index program root).length, + rankedUncachedWork (fun key => depth key + index key) program (fun key => weight (depth key)) + ((queryEarlierRequests depth index program root).get i) := by + apply sum_congr rfl + intro i hi + apply ih _ _ _ rfl + rw [← hroot] + exact Nat.add_lt_add_of_le_of_lt (he i).1 (he i).2 + _ = _ := Fin.sum_univ_fun_getElem _ _ + rw [hsame, hearlier, rankedUncachedWork, queryRequestList_cost] + have hp := sum_map_partition (fun child => decide (index child < index root)) + (rankedUncachedWork (fun key => depth key + index key) program (fun key => weight (depth key))) + (queryRequestList depth index program root) + change weight (depth root) + _ + _ = _ + weight (depth root) + change _ + _ = _ at hp + dsimp only [querySameRequests, queryEarlierRequests] + omega + exact hall (depth root + index root) root rfl + +end Weighted + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Queries/QueryWideBounds.lean b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryWideBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..751b2e95255c2d3fc2d7e8c2370cd87e2e684087 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Queries/QueryWideBounds.lean @@ -0,0 +1,71 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryHistoryBounds +import OAI.Combinatorics.EditApproximation.Queries.QueryOrderBounds + +namespace OAI + +/-! Band-buffer input construction has a polynomial counter in the +number of representatives, emitted child-grid cells and key width. -/ + +namespace EditApproximation.BinaryFraction + +section Wide +variable {nx ny : ℕ} (M : ℕ) (parent : TargetInterval nx) (P : ℕ) + (representatives : List (ℕ × TargetInterval ny)) (G C B : ℕ) + (hM : Nat.size M ≤ B) (hny : Nat.size ny ≤ B) + (hgrid : ∀ br ∈ representatives, ∀ i : Fin M, + (wideChildGridWithWork parent br.2 br.1 P i).1.length ≤ G) + (hwork : ∀ br ∈ representatives, ∀ i : Fin M, + (wideChildGridWithWork parent br.2 br.1 P i).2 ≤ C) + +include hM hny hgrid hwork in +theorem queryWideInputsWithWork_bounds : + (queryWideInputsWithWork M parent P representatives).1.length ≤ representatives.length * (M * G) ∧ + (queryWideInputsWithWork M parent P representatives).2 ≤ + representatives.length * (M * (C + 4 * G + 1 + G + 3) + M * G + 3) + + (representatives.length * (M * G) + 1) ^ 2 * (24 * B + 12) + M + 2 := by + let childRun := fun (br : ℕ × TargetInterval ny) (i : Fin M) => + let states := wideChildGridWithWork parent br.2 br.1 P i + let labeled := arithmeticMapWithWork (fun r => ((i, r), 1)) states.1 + (labeled.1, states.2 + labeled.2 + 1) + let run := fun br : ℕ × TargetInterval ny => arithmeticFlatMapWithWork (childRun br) (List.finRange M) + let raw := arithmeticFlatMapWithWork run representatives + have child (br : ℕ × TargetInterval ny) (hbr : br ∈ representatives) (i : Fin M) : + (childRun br i).1.length ≤ G ∧ (childRun br i).2 ≤ C + 4 * G + 1 := by + have hl := hgrid br hbr i + have hw := hwork br hbr i + have hc := arithmeticMapWithWork_cost (fun r => ((i, r), 1)) + (wideChildGridWithWork parent br.2 br.1 P i).1 1 (fun _ _ => le_rfl) + constructor + · simpa only [childRun, arithmeticMapWithWork_value, List.length_map] using hl + · change (wideChildGridWithWork parent br.2 br.1 P i).2 + + (arithmeticMapWithWork (fun r => ((i, r), 1)) + (wideChildGridWithWork parent br.2 br.1 P i).1).2 + 1 ≤ _ + simp only [Nat.reduceAdd] at hc + have hh := hc.trans (Nat.mul_le_mul_right 4 hl) + omega + have one (br : ℕ × TargetInterval ny) (hbr : br ∈ representatives) : + (run br).1.length ≤ M * G ∧ (run br).2 ≤ M * (C + 4 * G + 1 + G + 3) := by + have hl := arithmeticFlatMapWithWork_length (childRun br) (List.finRange M) G + (fun i _ => (child br hbr i).1) + have hw := arithmeticFlatMapWithWork_cost (childRun br) (List.finRange M) (C + 4 * G + 1) G + (fun i _ => (child br hbr i).2) (fun i _ => (child br hbr i).1) + simpa only [List.length_finRange] using And.intro hl hw + have hl : raw.1.length ≤ representatives.length * (M * G) := + arithmeticFlatMapWithWork_length run representatives (M * G) (fun br hb => (one br hb).1) + have hw : raw.2 ≤ representatives.length * (M * (C + 4 * G + 1 + G + 3) + M * G + 3) := + arithmeticFlatMapWithWork_cost run representatives (M * (C + 4 * G + 1 + G + 3)) (M * G) + (fun br hb => (one br hb).2) (fun br hb => (one br hb).1) + have he := queryEraseWithWork_cost coordinateEqualWithWork (24 * B + 8) + (fun a b => coordinateEqualWithWork_cost a b B hM hny) raw.1 + have hsq : (raw.1.length + 1) ^ 2 ≤ (representatives.length * (M * G) + 1) ^ 2 := by gcongr + have he' := he.trans (Nat.mul_le_mul_right (24 * B + 8 + 4) hsq) + simp only [Nat.add_assoc, Nat.reduceAdd] at he' + have hu := (queryEraseWithWork_length coordinateEqualWithWork raw.1).trans hl + refine ⟨hu, ?_⟩ + change raw.2 + (queryEraseWithWork coordinateEqualWithWork raw.1).2 + M + 2 ≤ _ + omega + +end Wide +end EditApproximation.BinaryFraction + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedActualBandWork.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedActualBandWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..d787629c61fe5125a7f8a9e5b2cd3e2e927cc10d --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedActualBandWork.lean @@ -0,0 +1,145 @@ +import OAI.Combinatorics.EditApproximation.Geometry.ActualBandBitEnvelope +import OAI.Combinatorics.EditApproximation.Refinement.ComputedOptimizerBitWork +import OAI.Combinatorics.EditApproximation.Refinement.ComputedCacheWords + +namespace OAI + +/-! The same grid and dependency exponents control the full Boolean call, +including exact envelope construction, vertices and the optimistic-history input. -/ + +namespace EditApproximation + +open Filter +open scoped Topology + +theorem computed_dyadicScale_bits (N b : ℕ) (hN : 0 < N) (hb : b ∈ dyadicScales N) : + Nat.size b ≤ inputHeight N := by + obtain ⟨k, hk, rfl⟩ := List.mem_map.mp hb + have hk' : k ≤ Nat.log 2 N := by + have := List.mem_range.mp hk + omega + have hvalue := (Nat.pow_le_pow_right (by decide : 0 < (2 : ℕ)) hk').trans + (Nat.pow_log_le_self 2 hN.ne') + exact (Nat.size_le_size hvalue).trans (computed_input_size_le_height N) + +def localActualBandBitExponent (M p C : ℕ) : ℕ := + ((44 * M + C + 4000) * (p + 1)) * actualBandOptimizerBitDegree + +theorem actualBandOptimizerBitBudget_grid_cap (H M P p C d b v G K t Be Bk Bi Bt E : ℕ) + (hH : 64 ≤ H) (hM : M ≤ H) (hP : 1 ≤ P) (hPcap : P ≤ H ^ (p + 20)) + (hd : d ≤ M * (40 * P + 2) ^ 2) (hv : v ≤ (40 * P + 2) ^ (2 * M)) + (hG : G ≤ H + M * (40 * P + 2) ^ 2 + 4) (hK : K ≤ G ^ 80) (ht : t ≤ H) (hb : Nat.size b ≤ H) + (hBe : Be ≤ H ^ (C * (p + 1))) (hBk : Bk ≤ H ^ (C * (p + 1))) + (hBi : Bi ≤ H ^ (C * (p + 1))) (hBt : Bt ≤ H ^ (C * (p + 1))) + (hE : E ≤ H ^ (C * (p + 1))) : + BinaryFraction.actualBandOptimizerBitBudget M d b v G K t Be Bk Bi Bt E ≤ + H ^ localActualBandBitExponent M p C := by + let exponent := (44 * M + C + 4000) * (p + 1) + have hHpos : 0 < H := by omega + have hbox : 40 * P + 2 ≤ H ^ (p + 22) := by + have hc : 42 ≤ H ^ 2 := by nlinarith + calc + _ ≤ 42 * P := by omega + _ ≤ H ^ 2 * H ^ (p + 20) := Nat.mul_le_mul hc hPcap + _ = H ^ (2 + (p + 20)) := (pow_add H _ _).symm + _ = _ := by congr 1; omega + have hv' : v ≤ H ^ exponent := by + calc + _ ≤ (H ^ (p + 22)) ^ (2 * M) := hv.trans (Nat.pow_le_pow_left hbox _) + _ = H ^ ((p + 22) * (2 * M)) := (pow_mul H _ _).symm + _ ≤ _ := Nat.pow_le_pow_right hHpos (by dsimp only [exponent]; nlinarith) + have hd' : d ≤ H ^ exponent := + (hd.trans (wide_coordinate_budget_le H M P p hH hM hP hPcap)).trans + (Nat.pow_le_pow_right hHpos (by dsimp only [exponent]; nlinarith)) + have hG0 := hG.trans (optimizer_parameter_budget_le H M P p hH hM hP hPcap) + have hG' : G ≤ H ^ exponent := hG0.trans + (Nat.pow_le_pow_right hHpos (by dsimp only [exponent]; nlinarith)) + have hK' : K ≤ H ^ exponent := by + calc + _ ≤ (H ^ (2 * p + 46)) ^ 80 := hK.trans (Nat.pow_le_pow_left hG0 _) + _ = H ^ ((2 * p + 46) * 80) := (pow_mul H _ _).symm + _ ≤ _ := Nat.pow_le_pow_right hHpos (by dsimp only [exponent]; nlinarith) + have hC : C * (p + 1) ≤ exponent := by dsimp only [exponent]; nlinarith + have hheight : H ≤ H ^ exponent := Nat.le_pow (by dsimp only [exponent]; nlinarith) + have hS : 64 ≤ H ^ exponent := hH.trans hheight + have h := actualBandOptimizerBitBudget_le_fixed_power M d b v G K t Be Bk Bi Bt E + (H ^ exponent) hS (hM.trans hheight) hd' (hb.trans hheight) hv' hG' hK' (ht.trans hheight) + (hBe.trans (Nat.pow_le_pow_right hHpos hC)) + (hBk.trans (Nat.pow_le_pow_right hHpos hC)) + (hBi.trans (Nat.pow_le_pow_right hHpos hC)) + (hBt.trans (Nat.pow_le_pow_right hHpos hC)) + (hE.trans (Nat.pow_le_pow_right hHpos hC)) + simpa only [← pow_mul, exponent, localActualBandBitExponent] using h + +noncomputable def computedActualBandBitExponent (C N : ℕ) : ℝ := + (actualBandOptimizerBitDegree : ℝ) * + ((44 * Real.log 2) * ((integerParameters N).M : ℝ) * + ((coarseExponent (inputSmallLog N) : ℝ) + 1) * inputSmallLog N + + ((C : ℝ) + 4000) * ((coarseExponent (inputSmallLog N) : ℝ) + 1) * + Real.log (inputHeight N : ℝ)) + +theorem computedActualBandBitExponent_tendsto (C : ℕ) : + Tendsto (fun N => computedActualBandBitExponent C N / inputHeight N) atTop (𝓝 0) := by + have h := ((local_enumeration_exponent_div_height_tendsto.const_mul (44 * Real.log 2)).add + (encoding_exponent_div_height_tendsto.const_mul ((C : ℝ) + 4000))).const_mul + (actualBandOptimizerBitDegree : ℝ) + simp only [mul_zero, zero_add] at h + convert h using 1 + ext N + unfold computedActualBandBitExponent + ring + +def computedActualBandBitBudget (C N : ℕ) : ℕ := + inputHeight N ^ localActualBandBitExponent (integerParameters N).M + (coarseExponent (inputSmallLog N)) C + +private theorem actualBandBitBudget_exp_scalar (D C H M p ell : ℕ) (hH : 0 < H) + (hlog : Real.log (H : ℝ) ≤ (ell : ℝ) * Real.log 2) : + ((H ^ (((44 * M + C + 4000) * (p + 1)) * D) : ℕ) : ℝ) ≤ + Real.exp ((D : ℝ) * ((44 * Real.log 2) * (M : ℝ) * ((p : ℝ) + 1) * ell + + ((C : ℝ) + 4000) * ((p : ℝ) + 1) * Real.log (H : ℝ))) := by + rw [Nat.cast_pow, nat_pow_eq_exp_log H _ hH] + apply Real.exp_le_exp.mpr + have hM : (0 : ℝ) ≤ (M : ℝ) := Nat.cast_nonneg _ + have hp : (0 : ℝ) ≤ (p : ℝ) + 1 := by have h := Nat.cast_nonneg (α := ℝ) p; linarith + have hmul := mul_le_mul_of_nonneg_left hlog + (mul_nonneg (mul_nonneg (by norm_num : (0 : ℝ) ≤ 44) hM) hp) + have hD : (0 : ℝ) ≤ (D : ℝ) := Nat.cast_nonneg _ + push_cast + nlinarith only [mul_nonneg hD (sub_nonneg.mpr hmul)] + +theorem computedActualBandBitBudget_exp_bound (C N : ℕ) (hN : 0 < N) : + (computedActualBandBitBudget C N : ℝ) ≤ Real.exp (computedActualBandBitExponent C N) := by + have hH : 0 < inputHeight N := by + dsimp only [inputHeight] + exact Nat.pow_pos (by decide : 0 < (2 : ℕ)) + have hlog : Real.log (inputHeight N : ℝ) ≤ (inputSmallLog N : ℝ) * Real.log 2 := by + rw [inputHeight_real_log] + exact mul_le_mul_of_nonneg_right (by exact_mod_cast (inputSmallLog_bounds N hN).1) + (Real.log_nonneg (by norm_num)) + exact actualBandBitBudget_exp_scalar actualBandOptimizerBitDegree C (inputHeight N) + (integerParameters N).M (coarseExponent (inputSmallLog N)) (inputSmallLog N) hH hlog + +theorem computedActualBandBitBudget_subpolynomial (C : ℕ) (epsilon : ℝ) (hepsilon : 0 < epsilon) : + ∀ᶠ N in atTop, (computedActualBandBitBudget C N : ℝ) ≤ (N + 2 : ℝ) ^ epsilon := by + filter_upwards [subexponential_height_to_input (computedActualBandBitExponent C) + (computedActualBandBitExponent_tendsto C) epsilon hepsilon, eventually_ge_atTop 1] with N he hN + exact (computedActualBandBitBudget_exp_bound C N (by omega)).trans he + +theorem computedActualBandBitBudget_widthWork_near_linear (C : ℕ) (epsilon : ℝ) (hepsilon : 0 < epsilon) : + ∀ᶠ N in atTop, ∀ n ≤ N, ∀ tree : DependencyExpansion, + tree.Valid ((integerParameters N).M * inputSmallLog N ^ 257) + (inputHeight N ^ (512 * (coarseExponent (inputSmallLog N) + 1))) → + tree.depth = intervalTreeDepth (integerParameters N).M n → + tree.rank ≤ computedDependencyIndexCount N → + (tree.widthWork (integerParameters N).M n : ℝ) * computedActualBandBitBudget C N ≤ + (N + 2 : ℝ) ^ (1 + epsilon) := by + filter_upwards [computed_widthWork_subexponential (computedActualBandBitExponent C) + (computedActualBandBitExponent_tendsto C) epsilon hepsilon, eventually_ge_atTop 1] with N he hN + intro n hn tree hv hd hk + exact (mul_le_mul_of_nonneg_left (computedActualBandBitBudget_exp_bound C N (by omega)) + (Nat.cast_nonneg _)).trans (he n hn tree hv hd hk) + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedAddressWork.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedAddressWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..2c53c6ad67da90dc3ffbe5d9172e4c1505148271 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedAddressWork.lean @@ -0,0 +1,53 @@ +import OAI.Combinatorics.EditApproximation.Geometry.RankedMemoAddressWork +import OAI.Combinatorics.EditApproximation.Refinement.ComputedExecutionWork +import OAI.Combinatorics.EditApproximation.Geometry.HeightPowerWork +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation +open Filter + + + + theorem computedFamilyAddressWork_le (source target : List ℕ) (N : ℕ) + (input : ComputedFamilyInput source target N) : + computedFamilyAddressWork source target N input ≤ + 2 * (7 * intervalTreeDepth (integerParameters N).M source.length + 60) * + (computedFamilyResult source target N input).requests := + rankedMemoAddressWork_le _ _ _ _ _ _ + (computedFamilyMemoCodeWithWork_cost source target N (inputHeight N ^ 2)) _ _ + +private theorem address_factor_bound (H J : ℕ) (hH : 100 ≤ H) (hJ : J ≤ H) : + 2 * (7 * J + 60) ≤ H ^ 2 := by nlinarith only [hH, hJ] + + theorem computedFamilyAddressWork_near_linear (epsilon : ℝ) (hepsilon : 0 < epsilon) : + ∀ᶠ N in atTop, ∀ source target : List ℕ, source.length + target.length ≤ N → + ∀ input : ComputedFamilyInput source target N, + (computedFamilyAddressWork source target N input : ℝ) ≤ (N + 2 : ℝ) ^ (1 + epsilon) := by + have hh : 0 < epsilon / 2 := half_pos hepsilon + filter_upwards [computedFamilyResult_requests_near_linear (epsilon / 2) hh, + fixed_height_power_subpolynomial 2 (epsilon / 2) hh, + eventually_ge_atTop 1, inputSmallLog_tendsto.eventually (eventually_ge_atTop 200)] + with N hr hp hN hell + intro source target hsize input + have hdepth := computed_tree_depth_bound N source.length (by omega) (by omega) hell + have hJ : intervalTreeDepth (integerParameters N).M source.length ≤ inputHeight N := by + nlinarith only [hdepth, hell] + have hH : 100 ≤ inputHeight N := (by omega : 100 ≤ inputSmallLog N).trans + (computed_smallLog_le_height N) + have hfactor := address_factor_bound (inputHeight N) _ hH hJ + have ha := computedFamilyAddressWork_le source target N input + have haR : (computedFamilyAddressWork source target N input : ℝ) ≤ + (inputHeight N : ℝ) ^ 2 * (computedFamilyResult source target N input).requests := by + exact_mod_cast ha.trans (Nat.mul_le_mul_right _ hfactor) + calc + _ ≤ (inputHeight N : ℝ) ^ 2 * (computedFamilyResult source target N input).requests := haR + _ ≤ (N + 2 : ℝ) ^ (epsilon / 2) * (N + 2 : ℝ) ^ (1 + epsilon / 2) := + mul_le_mul hp (hr source target hsize input) (Nat.cast_nonneg _) (Real.rpow_nonneg (by positivity) _) + _ = _ := by rw [← Real.rpow_add (by positivity)]; congr 1; ring + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedBandSpacing.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedBandSpacing.lean new file mode 100644 index 0000000000000000000000000000000000000000..21827f8f602c9bd0d25c97903cc479d4b05c8c0f --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedBandSpacing.lean @@ -0,0 +1,91 @@ +import OAI.Combinatorics.EditApproximation.Geometry.BandRounding +import OAI.Combinatorics.EditApproximation.Geometry.Parameters + +namespace OAI + +/-! The input-computed dyadic parameters discharge all spacing and basic rounding premises. -/ + +namespace EditApproximation + +theorem computed_theta_dyadic (N : ℕ) : + (rationalParameters (inputSmallLog N)).theta = + (2 : ℚ) ^ (-((40 * smallLogExponent N : ℕ) : ℤ)) := by + change 1 / (((2 ^ smallLogExponent N : ℕ) : ℚ) ^ 40) = _ + rw [Nat.cast_pow, Nat.cast_ofNat, ← pow_mul] + rw [zpow_neg, zpow_natCast] + rw [Nat.mul_comm (smallLogExponent N) 40, one_div] + +theorem computed_P_dyadic (N : ℕ) : + (integerParameters N).P = + 2 ^ (heightExponent N * (coarseExponent (inputSmallLog N) + 20)) := by + change (2 ^ heightExponent N) ^ (coarseExponent (inputSmallLog N) + 20) = _ + rw [pow_mul] + +theorem basic_band_small_constants {ell : ℚ} (hell : 2 ≤ ell) : + 0 < 1 / ell ^ 4 ∧ 0 < 1 / ell ^ 40 ∧ 1 / ell ^ 40 ≤ 1 / 2 ∧ + 32 * ell * (1 / ell ^ 40) ≤ 1 ∧ 64 * ell * (1 / ell ^ 40) ≤ 1 := by + have hellpos : 0 < ell := by linarith + have hellone : 1 ≤ ell := by linarith + have hcoef : (64 : ℚ) ≤ ell ^ 6 := by + have h := pow_le_pow_left₀ (by norm_num : (0 : ℚ) ≤ 2) hell 6 + norm_num at h + exact h + have hpower : (64 : ℚ) ≤ ell ^ 39 := + hcoef.trans (pow_le_pow_right₀ hellone (by decide : 6 ≤ 39)) + have hscale : 64 * ell ≤ ell ^ 40 := by + calc + 64 * ell ≤ ell ^ 39 * ell := mul_le_mul_of_nonneg_right hpower hellpos.le + _ = ell ^ 40 := (pow_succ ell 39).symm + have h64 : 64 * ell * (1 / ell ^ 40) ≤ 1 := by + rw [mul_one_div] + exact (div_le_one₀ (pow_pos hellpos 40)).2 hscale + have h32 : 32 * ell * (1 / ell ^ 40) ≤ 1 := by + have hnonneg : 0 ≤ ell * (1 / ell ^ 40) := by positivity + nlinarith only [h64, hnonneg] + have htheta : 1 / ell ^ 40 ≤ 1 / 2 := by + apply (div_le_div_iff₀ (pow_pos hellpos 40) (by norm_num : (0 : ℚ) < 2)).2 + have h := pow_le_pow_right₀ hellone (by decide : 1 ≤ 40) + simp only [pow_one] at h + linarith only [hell, h] + exact ⟨by positivity, by positivity, htheta, h32, h64⟩ + +theorem computed_band_basic_constants (N : ℕ) (hell : 2 ≤ inputSmallLog N) : + 0 < (rationalParameters (inputSmallLog N)).tau ∧ + 0 < (rationalParameters (inputSmallLog N)).theta ∧ + (rationalParameters (inputSmallLog N)).theta ≤ 1 / 2 ∧ + (32 * inputSmallLog N : ℚ) * (rationalParameters (inputSmallLog N)).theta ≤ 1 ∧ + (64 * inputSmallLog N : ℚ) * (rationalParameters (inputSmallLog N)).theta ≤ 4 := by + have h := basic_band_small_constants (show (2 : ℚ) ≤ inputSmallLog N by exact_mod_cast hell) + exact ⟨h.1, h.2.1, h.2.2.1, h.2.2.2.1, h.2.2.2.2.trans (by norm_num)⟩ + +theorem computed_band_spacing_dominates (N : ℕ) (hN : 0 < N) + (hell : 2 ^ 1000 ≤ inputSmallLog N) : + ((integerParameters N).M : ℚ) ≤ + (rationalParameters (inputSmallLog N)).theta * (integerParameters N).P := by + have hellone : (1 : ℝ) ≤ inputSmallLog N := by + have h : 1 ≤ inputSmallLog N := Nat.one_le_two_pow + exact_mod_cast h + have hH40 : (inputSmallLog N : ℝ) ^ 40 ≤ inputHeight N := + (pow_le_pow_right₀ hellone (by decide : 40 ≤ 20000)).trans (inputHeight_polynomial_slack N hN hell) + have hH40Q : (inputSmallLog N : ℚ) ^ 40 ≤ inputHeight N := by exact_mod_cast hH40 + have hM : (integerParameters N).M ≤ inputHeight N := + pow_le_pow_right₀ (by decide : 1 ≤ (2 : ℕ)) (Nat.div_le_self _ _) + have hMQ : ((integerParameters N).M : ℚ) ≤ inputHeight N := by exact_mod_cast hM + have hHone : 1 ≤ inputHeight N := Nat.one_le_two_pow + have hPtwo : inputHeight N ^ 2 ≤ (integerParameters N).P := + pow_le_pow_right₀ hHone (by omega : 2 ≤ coarseExponent (inputSmallLog N) + 20) + have hPtwoQ : (inputHeight N : ℚ) ^ 2 ≤ (integerParameters N).P := by exact_mod_cast hPtwo + have hproduct : ((integerParameters N).M : ℚ) * (inputSmallLog N : ℚ) ^ 40 ≤ + (integerParameters N).P := by + have h := mul_le_mul hMQ hH40Q (pow_nonneg (Nat.cast_nonneg (inputSmallLog N)) 40) + (Nat.cast_nonneg (inputHeight N)) + exact h.trans (by simpa only [pow_two] using hPtwoQ) + change ((integerParameters N).M : ℚ) ≤ (1 / (inputSmallLog N : ℚ) ^ 40) * (integerParameters N).P + rw [one_div_mul_eq_div] + have hellpos : (0 : ℚ) < inputSmallLog N := by exact_mod_cast (Nat.two_pow_pos (smallLogExponent N)) + apply (le_div_iff₀ (pow_pos hellpos 40)).2 + exact hproduct + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedBands.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedBands.lean new file mode 100644 index 0000000000000000000000000000000000000000..a2074b0368d2a1aca98db6bd2c8486aac333f406 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedBands.lean @@ -0,0 +1,94 @@ +import OAI.Combinatorics.EditApproximation.Numerics.RationalPrefix +import OAI.Combinatorics.EditApproximation.Geometry.Bands +import OAI.Combinatorics.EditApproximation.Geometry.WideActions +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! +# The literal finite predicted band + +The band is a rationally decidable filter of the enumerated wide actions. +Its internal-cut diameter follows from the actual finite prefix predictor, +without assuming a predictor Lipschitz contract. +-/ + +namespace EditApproximation + + + + + + + + + +theorem computedBandActions_mem {nx ny M : ℕ} (parent : TargetInterval nx) + (r : TargetInterval ny) (b P : ℕ) (tau theta velocity : ℚ) + (child : Fin M → TargetInterval ny → ℚ) (states : Fin M → TargetInterval ny) + (hstates : states ∈ computedBandActions parent r b P tau theta velocity child) : + ∃ hnonempty : wideActionList M parent r b P ≠ [], + states ∈ wideActionList M parent r b P ∧ |velocity| ≤ 1 - tau ∧ + bandActionPredicate parent r b tau theta velocity (wideActionList M parent r b P) hnonempty child states := by + by_cases hempty : wideActionList M parent r b P = [] + · simp only [computedBandActions, dite_eq_left hempty, List.not_mem_nil] at hstates + · by_cases hvelocity : |velocity| ≤ 1 - tau + · simp only [computedBandActions, dite_eq_right hempty, ite_eq_left hvelocity] at hstates + obtain ⟨hmem, hpredicate⟩ := List.mem_filter.mp hstates + exact ⟨hempty, hmem, hvelocity, of_decide_eq_true hpredicate⟩ + · simp only [computedBandActions, dite_eq_right hempty, ite_eq_right hvelocity, + List.not_mem_nil] at hstates + +theorem computedBandActions_complete {nx ny M : ℕ} (parent : TargetInterval nx) + (r : TargetInterval ny) (b P : ℕ) (tau theta velocity : ℚ) + (child : Fin M → TargetInterval ny → ℚ) (states : Fin M → TargetInterval ny) + (hnonempty : wideActionList M parent r b P ≠ []) + (hstates : states ∈ wideActionList M parent r b P) (hvelocity : |velocity| ≤ 1 - tau) + (hpredicate : bandActionPredicate parent r b tau theta velocity + (wideActionList M parent r b P) hnonempty child states) : + states ∈ computedBandActions parent r b P tau theta velocity child := by + simp only [computedBandActions, dite_eq_right hnonempty, ite_eq_left hvelocity] + exact List.mem_filter.mpr ⟨hstates, decide_eq_true hpredicate⟩ + +theorem computedBand_cut_diameter {nx ny M : ℕ} (parent : TargetInterval nx) + (r : TargetInterval ny) (b P : ℕ) (tau theta velocity : ℚ) (htau : 0 < tau) + (child : Fin M → TargetInterval ny → ℚ) (states states' : Fin M → TargetInterval ny) + (hstates : states ∈ computedBandActions parent r b P tau theta velocity child) + (hstates' : states' ∈ computedBandActions parent r b P tau theta velocity child) + (j : Fin M) (hj : 0 < j.val) : + (Nat.dist (states j).lo (states' j).lo : ℝ) ≤ 2 * (theta : ℝ) * b / M := by + obtain ⟨hnonempty, hmem, hvelocity, hpredicate⟩ := + computedBandActions_mem parent r b P tau theta velocity child states hstates + obtain ⟨hnonempty', hmem', hvelocity', hpredicate'⟩ := + computedBandActions_mem parent r b P tau theta velocity child states' hstates' + let predictor := fun p : ℝ => widePrefixMinimum parent r (wideActionList M parent r b P) + hnonempty (fun i s => (child i s : ℝ)) j.val p + have hvelocityR : |(velocity : ℝ)| ≤ 1 - (tau : ℝ) := by exact_mod_cast hvelocity + have htauR : (0 : ℝ) < tau := by exact_mod_cast htau + have hband (s : Fin M → TargetInterval ny) + (hs : bandActionPredicate parent r b tau theta velocity (wideActionList M parent r b P) hnonempty child s) : + inPredictedBand predictor ((r.lo : ℝ) - parent.lo) velocity tau + ((theta : ℝ) * b / M) (bandCutShift parent s j) := by + have h := hs.2.2 j hj + have hR : ((|bandCutShift parent s j - ((r.lo : ℚ) - parent.lo) - velocity * + rationalWidePrefixMinimum parent r (wideActionList M parent r b P) hnonempty child j.val + (bandCutShift parent s j)| : ℚ) : ℝ) ≤ ((tau * theta * b / M : ℚ) : ℝ) := + Rat.cast_le.mpr h + simp only [Rat.cast_abs, Rat.cast_sub, Rat.cast_natCast, Rat.cast_mul, Rat.cast_div, + rationalWidePrefixMinimum_cast] at hR + simpa only [inPredictedBand, predictor, mul_assoc, mul_div_assoc] using hR + have hdiam := predicted_band_diameter htauR hvelocityR + (widePrefixMinimum_lipschitz parent r (wideActionList M parent r b P) hnonempty + (fun i s => (child i s : ℝ)) j.val _ _) + (hband states hpredicate) (hband states' hpredicate') + have hpoint : ((bandCutShift parent states j : ℚ) : ℝ) - + ((bandCutShift parent states' j : ℚ) : ℝ) = (states j).lo - ((states' j).lo : ℝ) := by + simp only [bandCutShift, Rat.cast_sub, Rat.cast_natCast] + ring + rw [hpoint, natural_distance_cast] at hdiam + simpa only [mul_div_assoc, mul_assoc] using hdiam + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedBaseStorage.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedBaseStorage.lean new file mode 100644 index 0000000000000000000000000000000000000000..6bcf93377e05f49537953b668ef982cd91cb0fd0 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedBaseStorage.lean @@ -0,0 +1,68 @@ +import OAI.Combinatorics.EditApproximation.Refinement.ComputedCoarseCopySpace +import OAI.Combinatorics.EditApproximation.Refinement.ComputedCoarseHistorySpace + +namespace OAI + +namespace EditApproximation +open Filter + +/-- Retained dictionary, all copied coarse inputs, all coarse-array +capacities, and all local workspace allocations. Summing all allocations +is a conservative bound on simultaneous storage. -/ +noncomputable def computedFamilyStorageCapacity (source target : List ℕ) (N : ℕ) + (input : ComputedFamilyInput source target N) + (localSpace : ComputedFamilyMemoKey source target N → ℕ) : ℕ := + (computedFamilyResult source target N input).memory.rationalStorage + + computedFamilyCoarseCopyStorage source target N input + + computedFamilyCoarseArrayCapacity source target N input + + computedFamilyKernelWork source target N input localSpace + +theorem computedFamilyKernelWork_polynomial (D : ℕ) : + ∀ᶠ N : ℕ in atTop, ∀ source target : List ℕ, source.length + target.length ≤ N → + ∀ (input : ComputedFamilyInput source target N) + (cost : ComputedFamilyMemoKey source target N → ℕ), + (∀ key, cost key ≤ computedLocalKernelBudget D N) → + computedFamilyKernelWork source target N input cost ≤ (N + 2) ^ 2 := by + filter_upwards [computedFamilyKernelWork_near_linear D 1 (by norm_num)] with N hN + intro source target hsize input cost hcost + have h := hN source target hsize input cost hcost + norm_num at h + exact_mod_cast h + +private theorem storage_sum_bound (X K cache copied arrays localWork : ℕ) + (hX : 2 ≤ X) (hK : 39 ≤ K) + (hcache : cache ≤ X ^ K) (hcopy : copied ≤ X ^ 18) + (harray : arrays ≤ X ^ 39) (hlocal : localWork ≤ X ^ 2) : + cache + copied + arrays + localWork ≤ X ^ (K + 2) := by + have hbase : 0 < X := by omega + have hc := hcopy.trans (Nat.pow_le_pow_right hbase (show 18 ≤ K by omega)) + have ha := harray.trans (Nat.pow_le_pow_right hbase hK) + have hl := hlocal.trans (Nat.pow_le_pow_right hbase (show 2 ≤ K by omega)) + calc + _ ≤ 4 * X ^ K := by omega + _ ≤ X ^ 2 * X ^ K := Nat.mul_le_mul_right _ (by nlinarith only [hX]) + _ = _ := by rw [← pow_add]; congr 1; omega + +theorem computedFamilyStorageCapacity_polynomial (D : ℕ) : + ∀ᶠ N : ℕ in atTop, ∀ source target : List ℕ, source.length + target.length ≤ N → + (∀ a ∈ source ++ target, Nat.size a ≤ inputHeight N ^ 3) → + ∀ (input : ComputedFamilyInput source target N) + (localSpace : ComputedFamilyMemoKey source target N → ℕ), + (∀ key, localSpace key ≤ computedLocalKernelBudget D N) → + computedFamilyStorageCapacity source target N input localSpace ≤ (N + 2) ^ (65556 + 2) := by + filter_upwards [computedFamilyCoarseCopyStorage_polynomial, + computedFamilyCoarseArrayCapacity_polynomial, computedFamilyKernelWork_polynomial D, + computed_localOnlineMassBound_word, eventually_ge_atTop 1, + inputSmallLog_tendsto.eventually (eventually_ge_atTop (2 ^ 1000))] + with N hcopy harray hlocal hmass hN hell + intro source target hsize hsymbols input localSpace hcost + have hcache := computedFamilyResult_retained_storage source target N (by omega) hell hsize hmass input + have hc := hcopy source target hsize hsymbols input + have ha := harray source target hsize input + have hl := hlocal source target hsize input localSpace hcost + exact storage_sum_bound (N + 2) 65556 _ _ _ _ (by omega) (by decide) + hcache hc ha hl + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedBinaryOnlineParameters.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedBinaryOnlineParameters.lean new file mode 100644 index 0000000000000000000000000000000000000000..3d8903daa9b6e9ac97bf6ae80327b7e2094902d0 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedBinaryOnlineParameters.lean @@ -0,0 +1,63 @@ +import OAI.Combinatorics.EditApproximation.Binary.BinaryOnlineParameters +import OAI.Combinatorics.EditApproximation.Refinement.ComputedCacheWords + +namespace OAI + +/-! The actual binary online constants fit the same polynomial word cap as +the normalized local cache. No input-probability or good-seed assumption is +used here. -/ + +namespace EditApproximation + +private theorem online_parameter_width_cap (H B : ℕ) (hH : 64 ≤ H) (hB : B ≤ H) : + 5 * B + 1 ≤ H ^ 2 ∧ 4 * B + 1 ≤ H ^ 2 := by + constructor <;> nlinarith + +theorem computedBinaryOnlineParameters_caps (N : ℕ) (word : List Bool) + (hvalue : bitWordValue word = inputSmallLog N) + (hwidth : word.length ≤ Nat.size (inputSmallLog N)) (hH : 64 ≤ inputHeight N) + (hpositive : 0 < bitWordValue word) : + (BinaryFraction.onlineParametersWithWork word hpositive).1.1.width ≤ inputHeight N ^ 2 ∧ + (BinaryFraction.onlineParametersWithWork word hpositive).1.2.width ≤ inputHeight N ^ 2 ∧ + |(BinaryFraction.onlineParametersWithWork word hpositive).1.1.value| ≤ + ((inputHeight N ^ 5 : ℕ) : ℚ) ∧ + 0 ≤ (BinaryFraction.onlineParametersWithWork word hpositive).1.2.value ∧ + (BinaryFraction.onlineParametersWithWork word hpositive).1.2.value ≤ 1 := by + have hsmall : Nat.size (inputSmallLog N) ≤ inputHeight N := + (Nat.size_le.mpr Nat.lt_two_pow_self).trans (computed_smallLog_le_height N) + have hw := BinaryFraction.onlineParametersWithWork_width word hpositive + (Nat.size (inputSmallLog N)) hwidth + have hr := BinaryFraction.onlineParametersWithWork_range word hpositive (inputHeight N) + (by rw [hvalue]; exact computed_smallLog_le_height N) + have hc := online_parameter_width_cap _ _ hH hsmall + exact ⟨hw.1.trans hc.1, hw.2.trans hc.2, hr.1, hr.2⟩ + +theorem computedBinaryOnlineParameters_cost (N : ℕ) (word : List Bool) + (hwidth : word.length ≤ Nat.size (inputSmallLog N)) (hH : 64 ≤ inputHeight N) + (hpositive : 0 < bitWordValue word) : + (BinaryFraction.onlineParametersWithWork word hpositive).2 ≤ inputHeight N ^ 8 := by + have hsmall : Nat.size (inputSmallLog N) ≤ inputHeight N := + (Nat.size_le.mpr Nat.lt_two_pow_self).trans (computed_smallLog_le_height N) + have hw : word.length ≤ inputHeight N := hwidth.trans hsmall + have hc := BinaryFraction.onlineParametersWithWork_cost word hpositive (inputHeight N) hw + have hbound (H : ℕ) (h : 64 ≤ H) : + bitPowerBitBudget 5 H + bitPowerBitBudget 4 H + 2 ≤ H ^ 8 := by + have h5 : 6 * (H + 1) + 1 ≤ 7 * H := by omega + have h4 : 5 * (H + 1) + 1 ≤ 6 * H := by omega + have hs5 := Nat.pow_le_pow_left h5 2 + have hs4 := Nat.pow_le_pow_left h4 2 + have hc : 5 * (200 * (6 * (H + 1) + 1) ^ 2) + + 4 * (200 * (5 * (H + 1) + 1) ^ 2) + 4 ≤ 100000 * H ^ 2 := by nlinarith + have h6 : 100000 ≤ H ^ 6 := by + exact (by norm_num : 100000 ≤ 64 ^ 6).trans (Nat.pow_le_pow_left h 6) + change 1 + 5 * (200 * (6 * (H + 1) + 1) ^ 2) + + (1 + 4 * (200 * (5 * (H + 1) + 1) ^ 2)) + 2 ≤ H ^ 8 + calc + _ ≤ 100000 * H ^ 2 := by omega + _ ≤ H ^ 6 * H ^ 2 := Nat.mul_le_mul_right _ h6 + _ = _ := by ring + exact hc.trans (hbound _ hH) + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedCacheWords.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedCacheWords.lean new file mode 100644 index 0000000000000000000000000000000000000000..35b5c6d017db6e1413206d766732b2edebd80043 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedCacheWords.lean @@ -0,0 +1,48 @@ +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalCachedWords +import OAI.Combinatorics.EditApproximation.Refinement.ComputedEarlierInputBudget + +namespace OAI + +/-! Explicit multiword cache storage after substituting the computed height. -/ + +namespace EditApproximation + +theorem cacheWordBudget_le_cube (H N F r B : ℕ) (hH : 64 ≤ H) + (hN : Nat.size N ≤ H) (hF : F ≤ H) (hr : r ≤ H) (hB : B ≤ 13 * H) : + Nat.size ((32 * F + 1) * N) + 2 * r * B + 3 ≤ H ^ 3 := by + have hFsize : Nat.size F ≤ H := (Nat.size_le.mpr Nat.lt_two_pow_self).trans hF + have hm := natural_product_bit_length 32 F + have ha := natural_sum_bit_length (32 * F) 1 + have hp := natural_product_bit_length (32 * F + 1) N + have h32 : Nat.size 32 = 6 := by decide + simp only [h32, Nat.size_one] at hm ha + have hbits : Nat.size ((32 * F + 1) * N) ≤ 2 * H + 8 := by omega + have hmul := Nat.mul_le_mul hr hB + have hsquare : 2 * H + 11 ≤ H ^ 2 := by nlinarith + have hcube := Nat.mul_le_mul_right (H ^ 2) hH + have hc : 64 * H ^ 2 ≤ H ^ 3 := by + simpa only [pow_succ'] using hcube + nlinarith only [hbits, hmul, hsquare, hc, Nat.zero_le (H ^ 2)] + +theorem computed_input_size_le_height (N : ℕ) : Nat.size N ≤ inputHeight N := by + apply Nat.size_le.mpr + exact (show N < N + 2 by omega).trans_le (inputHeight_covers_length N) + +theorem computed_cacheWordBudget_le_cube (N r B : ℕ) (hH : 64 ≤ inputHeight N) + (hr : r ≤ inputHeight N) (hB : B ≤ 10 * Nat.size (inputSmallLog N) + 3) : + Nat.size ((32 * inputSmallLog N + 1) * N) + 2 * r * B + 3 ≤ inputHeight N ^ 3 := by + apply cacheWordBudget_le_cube _ _ _ _ _ hH (computed_input_size_le_height N) + (computed_smallLog_le_height N) hr + have hs : Nat.size (inputSmallLog N) ≤ inputHeight N := + (Nat.size_le.mpr Nat.lt_two_pow_self).trans (computed_smallLog_le_height N) + omega + +theorem computed_refinementBase_length (N : ℕ) (ell : List Bool) + (hell : bitWordValue ell = inputSmallLog N) : + (refinementBaseWithWork ell).1.length ≤ 10 * Nat.size (inputSmallLog N) + 3 := by + rw [refinementBaseWithWork_length, hell] + exact refinement_denominator_base_bits _ + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedChargedQueryBudget.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedChargedQueryBudget.lean new file mode 100644 index 0000000000000000000000000000000000000000..17ddd0819b21abd68e2474e3dc0748f09f36745b --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedChargedQueryBudget.lean @@ -0,0 +1,136 @@ +import OAI.Combinatorics.EditApproximation.Geometry.ChargedTerminalCost +import OAI.Combinatorics.EditApproximation.Refinement.ComputedRefinementReadBudget +import OAI.Combinatorics.EditApproximation.Refinement.ComputedWarmupReadBudget + +namespace OAI + +/-! Uniform edge budgets for the actual charged global interpreter. +The bounds hold for every initial seed and every draw, including failed +approximation events. -/ + +namespace EditApproximation + +section Current + +variable {α : Type*} [DecidableEq α] {M J R : ℕ} [NeZero R] + (source target : List α) (N P H T S passes copies : ℕ) + (factor : ℕ → ℚ) (multiplier : ℕ → ℕ) (tau eta kappa delta : ℚ) + (group : ℕ → ℕ → PhysicalInternalNode M J → Fin R → + CellGroupDraws M (inputSmallLog N) (inputSmallLog N ^ 80)) + (integer : ℕ → ℕ → PhysicalInternalNode M J → Fin R → ℕ → TargetInterval target.length → ℕ) + (initial : PhysicalEntry M J target.length → ℕ) + +variable (hN : 0 < N) (hell : 200 ≤ inputSmallLog N) + (hM : M = (integerParameters N).M) + (hAmax : ∀ pass, factor pass ≤ ((integerParameters N).initialFactor : ℚ)) + +include hN hell hM hAmax in + theorem computed_chargedGlobalQuery_current_reads + (request : ChargedPhysicalRequest M J target.length passes copies T S) : + (chargedGlobalQuery source target N P (inputSmallLog N) (40 * smallLogExponent N) + H (inputSmallLog N ^ 80) T S passes copies factor multiplier tau eta kappa delta + group integer initial request).cost + (fun child => chargedRequestValue source target N P (inputSmallLog N) (40 * smallLogExponent N) + H (inputSmallLog N ^ 80) T S passes copies factor multiplier tau eta kappa delta + group integer initial child.val) + (fun child => chargedSameWeight request child.val) ≤ 2 * M * inputSmallLog N ^ 256 := by + cases request with + | inl entry => exact Nat.zero_le _ + | inr parent => + by_cases hi : parent.val.index ≤ T + · unfold chargedGlobalQuery + dsimp only + rw [ite_eq_left hi, chargedWarmupQuery_same_cost_zero] + exact Nat.zero_le _ + · by_cases hb : parent.val.node.1.val < J + · by_cases hs : (physicalSourceInterval source.length parent.val.node).hi - + (physicalSourceInterval source.length parent.val.node).lo ≤ 1 + · unfold chargedGlobalQuery + dsimp only + rw [ite_eq_right hi, ite_eq_left hb, ite_eq_left hs, chargedInitialQuery_same_cost_zero] + exact Nat.zero_le _ + · rw [chargedGlobalQuery_current_cost source target N P (inputSmallLog N) + (40 * smallLogExponent N) H (inputSmallLog N ^ 80) T S passes copies factor multiplier + tau eta kappa delta group integer initial parent (by omega) hb hs] + apply computed_physicalRefinement_current_reads source target N P H hN hell hM + (factor parent.val.pass) tau eta kappa delta (hAmax _) parent.val.pass parent.val.copy + T S (parent.val.index - T) (by omega) parent.val.node hb + rw [localRequestValue_initial] + exact stageInitial_nonneg_all_seeds _ _ _ _ _ _ _ _ + · unfold chargedGlobalQuery + dsimp only + rw [ite_eq_right hi, ite_eq_right hb, chargedInitialQuery_same_cost_zero] + exact Nat.zero_le _ + + +variable (hP : P = (integerParameters N).P) (hT : T = (integerParameters N).T) + (hS : S = (integerParameters N).S) (hcopies : copies ≤ inputHeight N ^ 2) + (hAmin : ∀ pass, 1 ≤ factor pass) + +include hN hell hM hAmax hP hT hS hcopies hAmin in + theorem computed_chargedGlobalQuery_earlier_reads + (request : ChargedPhysicalRequest M J target.length passes copies T S) : + (chargedGlobalQuery source target N P (inputSmallLog N) (40 * smallLogExponent N) + H (inputSmallLog N ^ 80) T S passes copies factor multiplier tau eta kappa delta + group integer initial request).cost + (fun child => chargedRequestValue source target N P (inputSmallLog N) (40 * smallLogExponent N) + H (inputSmallLog N ^ 80) T S passes copies factor multiplier tau eta kappa delta + group integer initial child.val) + (fun child => chargedEarlierWeight request child.val) ≤ + inputHeight N ^ (512 * (coarseExponent (inputSmallLog N) + 1)) := by + cases request with + | inl entry => exact Nat.zero_le _ + | inr parent => + let oracle := fun child : {child : ChargedPhysicalRequest M J target.length passes copies T S // + child.rank < ChargedPhysicalRequest.rank (Sum.inr parent)} => + chargedRequestValue source target N P (inputSmallLog N) (40 * smallLogExponent N) + H (inputSmallLog N ^ 80) T S passes copies factor multiplier tau eta kappa delta + group integer initial child.val + have hmono (program : FiniteQuery {child : ChargedPhysicalRequest M J target.length passes copies T S // + child.rank < ChargedPhysicalRequest.rank (Sum.inr parent)}) : + program.cost oracle (fun child => chargedEarlierWeight (Sum.inr parent) child.val) ≤ + program.cost oracle (fun _ => 1) := by + apply FiniteQuery.cost_mono_weights + intro child + unfold chargedEarlierWeight + split_ifs <;> omega + by_cases hi : parent.val.index ≤ T + · unfold chargedGlobalQuery + dsimp only + rw [ite_eq_left hi] + exact (hmono _).trans (computed_chargedWarmupQuery_reads source target N P hN hell hM hP hcopies + factor multiplier parent oracle (hAmin _) (hAmax _)) + · by_cases hb : parent.val.node.1.val < J + · by_cases hs : (physicalSourceInterval source.length parent.val.node).hi - + (physicalSourceInterval source.length parent.val.node).lo ≤ 1 + · unfold chargedGlobalQuery + dsimp only + rw [ite_eq_right hi, ite_eq_left hb, ite_eq_left hs] + exact (hmono _).trans (computed_chargedInitialQuery_reads source target N P hN hell hM hP hcopies + factor multiplier parent oracle (hAmin _) (hAmax _)) + · rw [chargedGlobalQuery_earlier_cost source target N P (inputSmallLog N) + (40 * smallLogExponent N) H (inputSmallLog N ^ 80) T S passes copies factor multiplier + tau eta kappa delta group integer initial parent (by omega) hb hs] + calc + _ ≤ inputHeight N ^ (257 * (coarseExponent (inputSmallLog N) + 1)) := by + apply computed_physicalRefinement_earlier_reads source target N P H hN hell hM hP + (factor parent.val.pass) tau eta kappa delta (hAmax _) parent.val.pass parent.val.copy + T S (parent.val.index - T) hT (by omega) + (by + have h := parent.property.2.2 + have htime : parent.val.index - T ≤ S := by omega + exact htime.trans_eq hS) parent.val.node hb + rw [localRequestValue_initial] + exact stageInitial_nonneg_all_seeds _ _ _ _ _ _ _ _ + _ ≤ _ := pow_le_pow_right₀ (Nat.one_le_two_pow) (by omega) + · unfold chargedGlobalQuery + dsimp only + rw [ite_eq_right hi, ite_eq_right hb] + exact (hmono _).trans (computed_chargedInitialQuery_reads source target N P hN hell hM hP hcopies + factor multiplier parent oracle (hAmin _) (hAmax _)) + +end Current + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedChargedRandomBudget.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedChargedRandomBudget.lean new file mode 100644 index 0000000000000000000000000000000000000000..d7a1e712f6b61e271afab45a9f67946d7bad8eff --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedChargedRandomBudget.lean @@ -0,0 +1,173 @@ +import OAI.Combinatorics.EditApproximation.Geometry.ChargedTerminalCost +import OAI.Combinatorics.EditApproximation.Refinement.ComputedRandomPhysicalCost +import OAI.Combinatorics.EditApproximation.Geometry.ChargedRandomIndexCost +import OAI.Combinatorics.EditApproximation.Refinement.ComputedWarmupReadBudget + +namespace OAI + +/-! Uniform edge budgets for the actual charged global interpreter. +The bounds hold for every initial seed and every draw, including failed +approximation events. -/ + +namespace EditApproximation + +section Current + +variable {σ α : Type*} [DecidableEq α] {M J R : ℕ} [NeZero M] [NeZero R] + (source target : List α) (N P H T S passes copies : ℕ) + (factor : ℕ → ℚ) (multiplier : ℕ → ℕ) (tau eta kappa delta : ℚ) + (group : ℕ → ℕ → PhysicalInternalNode M J → Fin R → + CellGroupDraws M (inputSmallLog N) (inputSmallLog N ^ 80)) + (integer : ℕ → ℕ → PhysicalInternalNode M J → Fin R → ℕ → TargetInterval target.length → ℕ) + (initial : PhysicalEntry M J target.length → ℕ) + +variable + (readGroup : ℕ → ℕ → PhysicalInternalNode M J → Fin R → + GroupScalarKey M (inputSmallLog N) (inputSmallLog N ^ 80) → FiniteQuery σ) + (readInteger : ℕ → ℕ → PhysicalInternalNode M J → Fin R → + (ℕ × TargetInterval target.length) → ℕ → FiniteQuery σ) + (sourceAnswer : σ → ℚ) + +local notation "values" => localRequestValue source target N P (inputSmallLog N) + (40 * smallLogExponent N) H (inputSmallLog N ^ 80) T S copies factor multiplier + tau eta kappa delta group integer initial + +variable (hN : 0 < N) (hell : 200 ≤ inputSmallLog N) + (hM : M = (integerParameters N).M) + (hAmax : ∀ pass, factor pass ≤ ((integerParameters N).initialFactor : ℚ)) + (hP : P = (integerParameters N).P) (hT : T = (integerParameters N).T) + (hS : S = (integerParameters N).S) + +include hN hell hM hAmax hP hT hS in + theorem computed_chargedRandomGlobalQuery_current_reads + (request : ChargedPhysicalRequest M J target.length passes copies T S) : + (chargedRandomGlobalQuery source target N P (inputSmallLog N) (40 * smallLogExponent N) + H (inputSmallLog N ^ 80) T S passes copies factor multiplier tau eta kappa delta + readGroup readInteger initial request).cost + (Sum.elim sourceAnswer (fun child => chargedRequestValue source target N P (inputSmallLog N) (40 * smallLogExponent N) + H (inputSmallLog N ^ 80) T S passes copies factor multiplier tau eta kappa delta + group integer initial child.val)) + (Sum.elim (fun _ => 0) (fun child => chargedSameWeight request child.val)) ≤ 2 * M * inputSmallLog N ^ 256 := by + cases request with + | inl entry => exact Nat.zero_le _ + | inr parent => + by_cases hi : parent.val.index ≤ T + · unfold chargedRandomGlobalQuery + dsimp only + rw [ite_eq_left hi, FiniteQuery.mapKeys_cost] + simp only [Function.comp_def, Sum.elim_inr] + rw [chargedWarmupQuery_same_cost_zero] + exact Nat.zero_le _ + · by_cases hb : parent.val.node.1.val < J + · by_cases hs : (physicalSourceInterval source.length parent.val.node).hi - + (physicalSourceInterval source.length parent.val.node).lo ≤ 1 + · unfold chargedRandomGlobalQuery + dsimp only + rw [ite_eq_right hi, ite_eq_left hb, ite_eq_left hs, FiniteQuery.mapKeys_cost] + simp only [Function.comp_def, Sum.elim_inr] + rw [chargedInitialQuery_same_cost_zero] + exact Nat.zero_le _ + · have hanswer : chargedRequestValue source target N P (inputSmallLog N) + (40 * smallLogExponent N) H (inputSmallLog N ^ 80) T S passes copies factor multiplier + tau eta kappa delta group integer initial = + Sum.elim (fun entry => (initial entry : ℚ)) (fun r => values r.val) := by + funext key + cases key <;> rfl + rw [hanswer] + rw [chargedRandomGlobalQuery_current_cost source target N P (inputSmallLog N) + (40 * smallLogExponent N) H (inputSmallLog N ^ 80) T S passes copies factor multiplier + tau eta kappa delta readGroup readInteger sourceAnswer values initial parent (by omega) hb hs] + apply computed_physicalRandom_current_reads source target N P H hN hell hM hP + (factor parent.val.pass) tau eta kappa delta (hAmax _) parent.val.pass parent.val.copy + T S (parent.val.index - T) hT (by omega) + (by have hi := parent.property.2.2; omega) parent.val.node hb + rw [localRequestValue_initial] + exact stageInitial_nonneg_all_seeds _ _ _ _ _ _ _ _ + · unfold chargedRandomGlobalQuery + dsimp only + rw [ite_eq_right hi, ite_eq_right hb, FiniteQuery.mapKeys_cost] + simp only [Function.comp_def, Sum.elim_inr] + rw [chargedInitialQuery_same_cost_zero] + exact Nat.zero_le _ + + +variable (hcopies : copies ≤ inputHeight N ^ 2) + (hAmin : ∀ pass, 1 ≤ factor pass) + +include hN hell hM hAmax hP hT hS hcopies hAmin in + theorem computed_chargedRandomGlobalQuery_earlier_reads + (request : ChargedPhysicalRequest M J target.length passes copies T S) : + (chargedRandomGlobalQuery source target N P (inputSmallLog N) (40 * smallLogExponent N) + H (inputSmallLog N ^ 80) T S passes copies factor multiplier tau eta kappa delta + readGroup readInteger initial request).cost + (Sum.elim sourceAnswer (fun child => chargedRequestValue source target N P (inputSmallLog N) (40 * smallLogExponent N) + H (inputSmallLog N ^ 80) T S passes copies factor multiplier tau eta kappa delta + group integer initial child.val)) + (Sum.elim (fun _ => 0) (fun child => chargedEarlierWeight request child.val)) ≤ + inputHeight N ^ (512 * (coarseExponent (inputSmallLog N) + 1)) := by + cases request with + | inl entry => exact Nat.zero_le _ + | inr parent => + let oracle := fun child : {child : ChargedPhysicalRequest M J target.length passes copies T S // + child.rank < ChargedPhysicalRequest.rank (Sum.inr parent)} => + chargedRequestValue source target N P (inputSmallLog N) (40 * smallLogExponent N) + H (inputSmallLog N ^ 80) T S passes copies factor multiplier tau eta kappa delta + group integer initial child.val + have hmono (program : FiniteQuery {child : ChargedPhysicalRequest M J target.length passes copies T S // + child.rank < ChargedPhysicalRequest.rank (Sum.inr parent)}) : + program.cost oracle (fun child => chargedEarlierWeight (Sum.inr parent) child.val) ≤ + program.cost oracle (fun _ => 1) := by + apply FiniteQuery.cost_mono_weights + intro child + unfold chargedEarlierWeight + split_ifs <;> omega + by_cases hi : parent.val.index ≤ T + · unfold chargedRandomGlobalQuery + dsimp only + rw [ite_eq_left hi, FiniteQuery.mapKeys_cost] + simp only [Function.comp_def, Sum.elim_inr] + exact (hmono _).trans (computed_chargedWarmupQuery_reads source target N P hN hell hM hP hcopies + factor multiplier parent oracle (hAmin _) (hAmax _)) + · by_cases hb : parent.val.node.1.val < J + · by_cases hs : (physicalSourceInterval source.length parent.val.node).hi - + (physicalSourceInterval source.length parent.val.node).lo ≤ 1 + · unfold chargedRandomGlobalQuery + dsimp only + rw [ite_eq_right hi, ite_eq_left hb, ite_eq_left hs, FiniteQuery.mapKeys_cost] + simp only [Function.comp_def, Sum.elim_inr] + exact (hmono _).trans (computed_chargedInitialQuery_reads source target N P hN hell hM hP hcopies + factor multiplier parent oracle (hAmin _) (hAmax _)) + · have hanswer : chargedRequestValue source target N P (inputSmallLog N) + (40 * smallLogExponent N) H (inputSmallLog N ^ 80) T S passes copies factor multiplier + tau eta kappa delta group integer initial = + Sum.elim (fun entry => (initial entry : ℚ)) (fun r => values r.val) := by + funext key + cases key <;> rfl + rw [hanswer] + rw [chargedRandomGlobalQuery_earlier_cost source target N P (inputSmallLog N) + (40 * smallLogExponent N) H (inputSmallLog N ^ 80) T S passes copies factor multiplier + tau eta kappa delta readGroup readInteger sourceAnswer values initial parent (by omega) hb hs] + calc + _ ≤ inputHeight N ^ (257 * (coarseExponent (inputSmallLog N) + 1)) := by + apply computed_physicalRandom_earlier_reads source target N P H hN hell hM hP + (factor parent.val.pass) tau eta kappa delta (hAmax _) parent.val.pass parent.val.copy + T S (parent.val.index - T) hT (by omega) + (by + have h := parent.property.2.2 + have htime : parent.val.index - T ≤ S := by omega + exact htime.trans_eq hS) parent.val.node hb + rw [localRequestValue_initial] + exact stageInitial_nonneg_all_seeds _ _ _ _ _ _ _ _ + _ ≤ _ := pow_le_pow_right₀ (Nat.one_le_two_pow) (by omega) + · unfold chargedRandomGlobalQuery + dsimp only + rw [ite_eq_right hi, ite_eq_right hb, FiniteQuery.mapKeys_cost] + simp only [Function.comp_def, Sum.elim_inr] + exact (hmono _).trans (computed_chargedInitialQuery_reads source target N P hN hell hM hP hcopies + factor multiplier parent oracle (hAmin _) (hAmax _)) + +end Current + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedChargedRandomSourceCost.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedChargedRandomSourceCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..5d6620e6ae611f88e25d542c54a94af5218fe18b --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedChargedRandomSourceCost.lean @@ -0,0 +1,100 @@ +import OAI.Combinatorics.EditApproximation.Refinement.ComputedGlobalSourceCost +import OAI.Combinatorics.EditApproximation.Geometry.ChargedRandomCost +import OAI.Combinatorics.EditApproximation.Geometry.ChargedTerminalCost + +namespace OAI + +namespace EditApproximation + +section Cost + +variable {σ α : Type*} [DecidableEq α] {M J R : ℕ} [NeZero M] [NeZero R] + (source target : List α) (N P H T S passes copies : ℕ) + (factor : ℕ → ℚ) (multiplier : ℕ → ℕ) (tau eta kappa delta : ℚ) + (group : ℕ → ℕ → PhysicalInternalNode M J → Fin R → + CellGroupDraws M (inputSmallLog N) (inputSmallLog N ^ 80)) + (integer : ℕ → ℕ → PhysicalInternalNode M J → Fin R → ℕ → TargetInterval target.length → ℕ) + (initial : PhysicalEntry M J target.length → ℕ) + (readGroup : ℕ → ℕ → PhysicalInternalNode M J → Fin R → + GroupScalarKey M (inputSmallLog N) (inputSmallLog N ^ 80) → FiniteQuery σ) + (readInteger : ℕ → ℕ → PhysicalInternalNode M J → Fin R → + (ℕ × TargetInterval target.length) → ℕ → FiniteQuery σ) + (sourceAnswer : σ → ℚ) (weight : σ → ℕ) (bound : ℕ) + (hN : 0 < N) (hell : 200 ≤ inputSmallLog N) (hM : M = (integerParameters N).M) + (hA : ∀ pass, factor pass ≤ ((integerParameters N).initialFactor : ℚ)) + (hgroup : ∀ pass copy node time key, (readGroup pass copy node time key).cost sourceAnswer weight ≤ bound) + (honline : ∀ pass copy node time key range, + (readInteger pass copy node time key range).cost sourceAnswer weight ≤ bound) + +local notation "tableValue" => localRequestValue source target N P (inputSmallLog N) + (40 * smallLogExponent N) H (inputSmallLog N ^ 80) T S copies factor multiplier + tau eta kappa delta group integer initial + +include hN hell hM hA hgroup honline in + theorem computed_chargedRandomGlobalQuery_source_cost + (request : ChargedPhysicalRequest M J target.length passes copies T S) : + (chargedRandomGlobalQuery source target N P (inputSmallLog N) (40 * smallLogExponent N) + H (inputSmallLog N ^ 80) T S passes copies factor multiplier tau eta kappa delta + readGroup readInteger initial request).cost + (Sum.elim sourceAnswer (fun child => chargedRequestValue source target N P (inputSmallLog N) + (40 * smallLogExponent N) H (inputSmallLog N ^ 80) T S passes copies factor multiplier + tau eta kappa delta group integer initial child.val)) + (Sum.elim weight (fun _ => 0)) ≤ inputHeight N ^ 91 * bound := by + cases request with + | inl entry => exact Nat.zero_le _ + | inr parent => + by_cases hi : parent.val.index ≤ T + · unfold chargedRandomGlobalQuery + dsimp only + rw [ite_eq_left hi, FiniteQuery.mapKeys_cost] + simp only [Function.comp_def, Sum.elim_inr] + rw [FiniteQuery.cost_zero] + exact Nat.zero_le _ + · by_cases hb : parent.val.node.1.val < J + · by_cases hs : (physicalSourceInterval source.length parent.val.node).hi - + (physicalSourceInterval source.length parent.val.node).lo ≤ 1 + · unfold chargedRandomGlobalQuery + dsimp only + rw [ite_eq_right hi, ite_eq_left hb, ite_eq_left hs, FiniteQuery.mapKeys_cost] + simp only [Function.comp_def, Sum.elim_inr] + rw [FiniteQuery.cost_zero] + exact Nat.zero_le _ + · have hanswer : chargedRequestValue source target N P (inputSmallLog N) + (40 * smallLogExponent N) H (inputSmallLog N ^ 80) T S passes copies factor multiplier + tau eta kappa delta group integer initial = + Sum.elim (fun entry => (initial entry : ℚ)) (fun r => tableValue r.val) := by + funext key + cases key <;> rfl + have hz : (fun _ : ChargedPhysicalRequest M J target.length passes copies T S => 0) = + chargedTableWeight 0 (fun _ => 0) := by + funext key + cases key <;> rfl + rw [hanswer] + have hcost := chargedRandomGlobalQuery_refinement_cost source target N P (inputSmallLog N) + (40 * smallLogExponent N) H (inputSmallLog N ^ 80) T S passes copies factor multiplier + tau eta kappa delta readGroup readInteger initial sourceAnswer tableValue weight 0 (fun _ => 0) + parent (by omega) hb hs + simp only [← hz] at hcost + rw [hcost] + rw [← physicalRandomGlobalQuery_refinement_cost source target N P (inputSmallLog N) + (40 * smallLogExponent N) H (inputSmallLog N ^ 80) T S copies factor multiplier + tau eta kappa delta readGroup readInteger initial sourceAnswer tableValue weight (fun _ => 0) + parent.val (by omega) hb hs] + apply computed_physicalRandomGlobalQuery_source_cost source target N P H T S copies + hN hell hM factor multiplier tau eta kappa delta hA readGroup readInteger initial + sourceAnswer tableValue weight bound hgroup honline + intro pass copy node q + rw [localRequestValue_initial] + exact stageInitial_nonneg_all_seeds _ _ _ _ _ _ _ _ + · unfold chargedRandomGlobalQuery + dsimp only + rw [ite_eq_right hi, ite_eq_right hb, FiniteQuery.mapKeys_cost] + simp only [Function.comp_def, Sum.elim_inr] + rw [FiniteQuery.cost_zero] + exact Nat.zero_le _ + +end Cost + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedCoarseArrayStorage.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedCoarseArrayStorage.lean new file mode 100644 index 0000000000000000000000000000000000000000..92dc860f68b9428b8c0ca272c7812b22fbba931a --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedCoarseArrayStorage.lean @@ -0,0 +1,90 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseArrayStorage +import OAI.Combinatorics.EditApproximation.Refinement.ComputedCoarsePolynomial + +namespace OAI + +namespace EditApproximation +namespace BinaryFraction +open Filter + +theorem computedCoarseRootArray_storage : + ∀ᶠ N : ℕ in atTop, ∀ B d : ℕ, ∀ x y : List ℕ, + B = (integerParameters N).B → d = computedCoarseDepth N (coarseEntryWidth x y) → + coarseEntryWidth x y ≤ N → + ∀ (hB : 0 < B) (hq : 0 < inputHeight N ^ 4) (hL : 0 < 64 * inputHeight N) + (i : CoarseGuessIndex (coarseEntryWidth x y)) (draws : CoarseThresholdDraws B d), + coarseArrayStorage (coarseIndexedRootArray (coarseGuess (coarseEntryWidth x y) i) + (inputHeight N ^ 4) (64 * inputHeight N) hB hq hL x y draws) ≤ + 1 + (2 * coarseGuess (coarseEntryWidth x y) i + 1) * (2 * inputHeight N ^ 3 + 3) := by + filter_upwards [computedCoarse_bitParameters, eventually_ge_atTop 1, + inputSmallLog_tendsto.eventually (eventually_ge_atTop 200)] with N hbits hN hell + intro B d x y hBdef hddef hsize hB hq hL i draws + let H := inputHeight N + let k := coarseGuess (coarseEntryWidth x y) i + have hk : k ≤ 2 * (N + 2) := (coarseGuess_le _ i).trans (by omega) + obtain ⟨hden, hbound, hBbits, hqbits, hLbits, hNbits, _hD⟩ := + hbits B d (coarseEntryWidth x y) k hBdef hddef hsize hk + have hcap : coarseEntryWidth x y ≤ B ^ d := by + rw [hBdef, hddef] + exact (computed_coarse_depth N _ (by omega) hsize hell).1 + have htree : 0 + (coarseEntryTree B d x y).word.length ≤ N := by + rw [coarseEntryTree_word B d x y hcap, coarsePadTo_length _ _ (le_max_left _ _)] + simpa only [Nat.zero_add] using hsize + rw [coarseIndexedRootArray_eq] + exact coarseRootArray_storage k (H ^ 4) (64 * H) N (10 * H ^ 2) (H ^ 3) + hB hq hL _ _ draws 0 hBbits hqbits hLbits hNbits hden hbound htree + +theorem coarseRootArrayStorage_polynomial_scalar (N k : ℕ) (hk : k ≤ 2 * (N + 2)) : + 1 + (2 * k + 1) * (2 * inputHeight N ^ 3 + 3) ≤ (N + 2) ^ 20 := by + let X := N + 2 + have hX : 2 ≤ X := by dsimp only [X]; omega + have hH := Nat.pow_le_pow_left (computed_height_polynomial N) 3 + rw [← pow_mul] at hH + change inputHeight N ^ 3 ≤ X ^ 12 at hH + have hone : 1 ≤ X ^ 12 := one_le_pow₀ (by omega) + have hm : (2 * k + 1) * (2 * inputHeight N ^ 3 + 3) ≤ (5 * X) * (5 * X ^ 12) := + Nat.mul_le_mul (by dsimp only [X]; omega) (by omega) + have hp : 1 ≤ X ^ 13 := one_le_pow₀ (by omega) + have hc : 26 ≤ X ^ 7 := (by decide : 26 ≤ (2 : ℕ) ^ 7).trans (Nat.pow_le_pow_left hX 7) + calc + _ ≤ 26 * X ^ 13 := by nlinarith only [hm, hp] + _ ≤ X ^ 7 * X ^ 13 := Nat.mul_le_mul_right _ hc + _ = _ := by rw [← pow_add] + +/-- Even retaining the final array from every candidate uses polynomial +space; the implementation may release each array after its root lookup. -/ +theorem computedCoarseAllRootArrays_storage : + ∀ᶠ N : ℕ in atTop, ∀ B d : ℕ, ∀ x y : List ℕ, + B = (integerParameters N).B → d = computedCoarseDepth N (coarseEntryWidth x y) → + coarseEntryWidth x y ≤ N → + ∀ (hB : 0 < B) (hq : 0 < inputHeight N ^ 4) (hL : 0 < 64 * inputHeight N) + (draws : CoarseGuessIndex (coarseEntryWidth x y) → CoarseThresholdDraws B d), + (∑ i : CoarseGuessIndex (coarseEntryWidth x y), + coarseArrayStorage (coarseIndexedRootArray (coarseGuess (coarseEntryWidth x y) i) + (inputHeight N ^ 4) (64 * inputHeight N) hB hq hL x y (draws i))) ≤ + (N + 2) ^ 25 := by + filter_upwards [computedCoarseRootArray_storage] with N hroot + intro B d x y hBdef hddef hsize hB hq hL draws + have hclog : Nat.clog 2 (coarseEntryWidth x y) ≤ inputHeight N := + (Nat.clog_le_iff_le_pow (by decide : 1 < (2 : ℕ))).mpr + (hsize.trans ((Nat.le_add_right N 2).trans (inputHeight_covers_length N))) + have hcount : Nat.clog 2 (coarseEntryWidth x y) + 1 ≤ (N + 2) ^ 5 := by + have hh := computed_height_polynomial N + have hp : 1 ≤ (N + 2) ^ 4 := one_le_pow₀ (by omega) + have hm := Nat.mul_le_mul_right ((N + 2) ^ 4) (show 2 ≤ N + 2 by omega) + nlinarith only [hclog, hh, hp, hm] + calc + _ ≤ ∑ _i : CoarseGuessIndex (coarseEntryWidth x y), (N + 2) ^ 20 := by + apply Finset.sum_le_sum + intro i _ + exact (hroot B d x y hBdef hddef hsize hB hq hL i (draws i)).trans + (coarseRootArrayStorage_polynomial_scalar N _ ((coarseGuess_le _ i).trans (by omega))) + _ = (Nat.clog 2 (coarseEntryWidth x y) + 1) * (N + 2) ^ 20 := by + simp only [Finset.sum_const, Finset.card_univ, Fintype.card_fin, smul_eq_mul] + _ ≤ (N + 2) ^ 5 * (N + 2) ^ 20 := Nat.mul_le_mul_right _ hcount + _ = _ := by rw [← pow_add] + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedCoarseBitParameters.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedCoarseBitParameters.lean new file mode 100644 index 0000000000000000000000000000000000000000..d2ff49bd5114d558c7e9e926e31d8c7da9429e0a --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedCoarseBitParameters.lean @@ -0,0 +1,61 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseBitParameters +import OAI.Combinatorics.EditApproximation.Refinement.ComputedCoarseBits + +namespace OAI + +namespace EditApproximation +open Filter +namespace BinaryFraction + + theorem computedCoarse_bitParameters : + ∀ᶠ N : ℕ in atTop, ∀ B d n k : ℕ, + B = (integerParameters N).B → d = computedCoarseDepth N n → n ≤ N → k ≤ 2 * (N + 2) → + Nat.size (coarseCommonDenominator 1 (inputHeight N ^ 4) (64 * inputHeight N) B d) ≤ + 10 * inputHeight N ^ 2 ∧ + Nat.size (coarseLevelMagnitude N k B d + 2) + 2 * (10 * inputHeight N ^ 2) + 1 ≤ inputHeight N ^ 3 ∧ + Nat.size B + 2 ≤ inputHeight N ^ 3 ∧ + Nat.size (inputHeight N ^ 4) + 2 ≤ inputHeight N ^ 3 ∧ + Nat.size (64 * inputHeight N) + 2 ≤ inputHeight N ^ 3 ∧ + Nat.size N + 2 ≤ inputHeight N ^ 3 ∧ + 10 * inputHeight N ^ 2 ≤ inputHeight N ^ 3 := by + filter_upwards [computedParameterPower_word, eventually_ge_atTop 1, + inputSmallLog_tendsto.eventually (eventually_ge_atTop 200)] with N hpower hN hell + intro B d n k hBdef hddef hn hk + have hH := computed_coarse_height_large N (by omega) hell + have hD : d ≤ inputHeight N := hddef.symm ▸ (computed_coarse_depth N n (by omega) hn hell).2 + have hb : Nat.size B ≤ 2 * inputHeight N := by + have hb' := Nat.size_le_size (computed_coarse_B_upper N (by omega) hell) + simp only [Nat.size_pow] at hb' + rw [hBdef] + omega + have hq : Nat.size (inputHeight N ^ 4) ≤ 2 * inputHeight N := by + have h := hpower 4 (by omega) + omega + have hHsize : Nat.size (inputHeight N) ≤ inputHeight N := + Nat.size_le.mpr (Nat.lt_pow_self (by decide : 1 < (2 : ℕ))) + have hL : Nat.size (64 * inputHeight N) ≤ 2 * inputHeight N := by + have h := natural_product_bit_length 64 (inputHeight N) + rw [show Nat.size 64 = 7 by decide] at h + omega + have hnsize : Nat.size N ≤ 2 * inputHeight N := by + have h := (Nat.size_le_size (Nat.le_add_right N 2)).trans (inputLength_register_word N) + omega + have hksize : Nat.size k ≤ 2 * inputHeight N := by + have h := (Nat.size_le_size hk).trans (natural_product_bit_length 2 (N + 2)) + have hn' := inputLength_register_word N + rw [show Nat.size 2 = 2 by decide] at h + omega + have hgrid := coarseBitParameters_grid (inputHeight N) N k B (inputHeight N ^ 4) + (64 * inputHeight N) d (by omega) hD hnsize hksize hb hq hL + have hcube : 100 * inputHeight N ^ 2 ≤ inputHeight N ^ 3 := by + have h := Nat.mul_le_mul_right (inputHeight N ^ 2) (show 100 ≤ inputHeight N by omega) + nlinarith only [h] + have hsquare : inputHeight N ≤ inputHeight N ^ 2 := Nat.le_pow (by decide) + exact ⟨hgrid.1, hgrid.2, by nlinarith only [hb, hcube, hsquare, hH], + by nlinarith only [hq, hcube, hsquare, hH], by nlinarith only [hL, hcube, hsquare, hH], + by nlinarith only [hnsize, hcube, hsquare, hH], by nlinarith only [hcube]⟩ + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedCoarseBitWork.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedCoarseBitWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..c0c2fa32c20c862e1c056c99b10b78e5a52aa7d2 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedCoarseBitWork.lean @@ -0,0 +1,162 @@ +import OAI.Combinatorics.EditApproximation.Refinement.ComputedCoarseInputWork +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalCoarseBitWork + +namespace OAI + +namespace EditApproximation +open Filter MeasureTheory + +theorem physicalSource_mem {α : Type*} {M J : ℕ} (source : List α) + (node : PhysicalNode M J) (a : α) (ha : a ∈ physicalSource source node) : a ∈ source := by + exact List.mem_of_mem_take (List.mem_of_mem_drop ha) + +section Symbolic +variable {M J R B : ℕ} [NeZero M] [NeZero R] [NeZero B] + (source target : List ℕ) (N : ℕ) + (depth : PhysicalEntry M J target.length → ℕ) + (encode : Sum (PhysicalFamilyScalarKey (M := M) (J := J) (R := R) + target N (integerParameters N).P (inputSmallLog N) (40 * smallLogExponent N) + (inputHeight N) (inputSmallLog N ^ 80) (computedSeedPassCount N) (inputHeight N ^ 2)) + (ChargedPhysicalRequest M J target.length (computedSeedPassCount N + 1) + (inputHeight N ^ 2) (integerParameters N).T (integerParameters N).S) → ℕ) + +noncomputable def symbolicComputedExecutionCoarseBitWork + (execution : PhysicalCoarseExecution (R := R) source target N + (integerParameters N).P (inputHeight N) B depth) : ℝ := + physicalFamilyCoarseBitWork source target N (integerParameters N).P (inputHeight N) + (integerParameters N).T (integerParameters N).S (computedSeedPassCount N) + (inputHeight N ^ 2) (scheduledSeedFactor N) (scheduledSeedMultiplier N) + (rationalParameters (inputSmallLog N)).tau (rationalParameters (inputSmallLog N)).eta + (rationalParameters (inputSmallLog N)).kappa (rationalParameters (inputSmallLog N)).delta + execution.2.2 depth (16384 * inputHeight N + 5) encode + (localFinalRootRequest target N (integerParameters N).T (integerParameters N).S + (inputHeight N) (Nat.two_pow_pos _) (finalTargetState target.length)) execution.1 + +theorem symbolicComputedExecutionCoarseBitWork_integrable : + Integrable (symbolicComputedExecutionCoarseBitWork source target N depth encode) + (physicalCoarseExecutionLaw (R := R) source target N (integerParameters N).P + (inputHeight N) B depth) := by + let μ := coarseFullSeedMeasure B depth + (fun entry => physicalSource source entry.1) + (fun entry => substring target entry.2.lo entry.2.hi) + let range := physicalFamilyRange (M := M) (J := J) (R := R) + target N (integerParameters N).P (inputSmallLog N) (40 * smallLogExponent N) + (inputHeight N) (inputSmallLog N ^ 80) (computedSeedPassCount N) (inputHeight N ^ 2) + let f := fun outcome : PhysicalCoarseDraw source target B depth × (∀ key, Fin (range key)) => + symbolicComputedExecutionCoarseBitWork source target N depth encode + (outcome.1, (fun _ => 0, outcome.2)) + have hf : Integrable f ((μ.prod (rejectionRuntimeArrayLaw range)).map + (rejectionProductAccepted range)) := by + rw [rejectionProductAccepted_law] + exact Integrable.of_finite + exact hf.comp_measurable (rejectionProductAccepted_measurable range) +theorem symbolicComputedExecutionCoarseBitWork_bound + (hcost : ∀ B d : ℕ, ∀ x y : List ℕ, + B = (integerParameters N).B → d = computedCoarseDepth N (coarseEntryWidth x y) → + coarseEntryWidth x y ≤ N → (∀ a ∈ x ++ y, Nat.size a ≤ inputHeight N ^ 3) → + ∀ (_hB : NeZero B) (draw : CoarseGuessIndex (coarseEntryWidth x y) → CoarseThresholdDraws B d), + (coarseEntryBinaryCost N B d x y draw : ℝ) ≤ (inputHeight N : ℝ) ^ 36 * + ((coarseInitialArrayWork B d (initialThresholdQ N) (initialLambda N) x y draw : ℝ) + + (x.length + 1 : ℕ))) + (hB : B = (integerParameters N).B) + (hdepth : ∀ entry, depth entry = computedCoarseDepth N + (coarseEntryWidth (physicalSource source entry.1) (substring target entry.2.lo entry.2.hi))) + (hsize : source.length + target.length ≤ N) + (hsymbols : ∀ a ∈ source ++ target, Nat.size a ≤ inputHeight N ^ 3) + (execution : PhysicalCoarseExecution (R := R) source target N + (integerParameters N).P (inputHeight N) B depth) : + symbolicComputedExecutionCoarseBitWork source target N depth encode execution ≤ + (inputHeight N : ℝ) ^ 36 * + (symbolicComputedExecutionCoarseWork source target N depth encode execution + + physicalFamilyCoarseInputWork source target N (integerParameters N).P (inputHeight N) + (integerParameters N).T (integerParameters N).S (computedSeedPassCount N) + (inputHeight N ^ 2) (scheduledSeedFactor N) (scheduledSeedMultiplier N) + (rationalParameters (inputSmallLog N)).tau (rationalParameters (inputSmallLog N)).eta + (rationalParameters (inputSmallLog N)).kappa (rationalParameters (inputSmallLog N)).delta + (clampedSeedNat (physicalCoarseSeedTable source target N B depth execution.1)) execution.2.2 + (16384 * inputHeight N + 5) encode + (localFinalRootRequest target N (integerParameters N).T (integerParameters N).S + (inputHeight N) (Nat.two_pow_pos _) (finalTargetState target.length))) := by + apply physicalFamilyCoarseBitWork_bound + intro entry + have hx := physicalSource_length_le source entry.1 + have hy : (substring target entry.2.lo entry.2.hi).length ≤ target.length := by + simp only [substring, List.length_drop, List.length_take] + exact (Nat.sub_le _ _).trans (min_le_right _ _) + have hxy : coarseEntryWidth (physicalSource source entry.1) + (substring target entry.2.lo entry.2.hi) ≤ N := max_le (by omega) (by omega) + have hsy : ∀ a ∈ physicalSource source entry.1 ++ substring target entry.2.lo entry.2.hi, + Nat.size a ≤ inputHeight N ^ 3 := by + intro a ha + rcases List.mem_append.mp ha with ha | ha + · exact hsymbols a (List.mem_append_left _ (physicalSource_mem source entry.1 a ha)) + · exact hsymbols a (List.mem_append_right _ + (List.mem_of_mem_take (List.mem_of_mem_drop ha))) + exact hcost B (depth entry) _ _ hB (hdepth entry) hxy hsy inferInstance (execution.1 entry) +end Symbolic + +noncomputable def computedExecutionCoarseBitWork (source target : List ℕ) (N : ℕ) := + symbolicComputedExecutionCoarseBitWork (M := (integerParameters N).M) + (J := intervalTreeDepth (integerParameters N).M source.length) (R := inputHeight N ^ 2) + (B := (integerParameters N).B) source target N (computedPhysicalCoarseDepth source target N) + (computedFamilyMemoCode source target N (inputHeight N ^ 2)) + +theorem computedExecutionCoarseBitWork_bound : + ∀ᶠ N : ℕ in atTop, ∀ source target : List ℕ, source.length + target.length ≤ N → + (∀ a ∈ source ++ target, Nat.size a ≤ inputHeight N ^ 3) → + ∀ execution : ComputedExecutionOutcome source target N, + computedExecutionCoarseBitWork source target N execution ≤ + (inputHeight N : ℝ) ^ 36 * (computedExecutionCoarseWork source target N execution + + computedExecutionCoarseInputWork source target N execution) := by + filter_upwards [coarseEntryBinaryCost_computed_bound] with N hN + intro source target hsize hsymbols execution + exact symbolicComputedExecutionCoarseBitWork_bound source target N + (computedPhysicalCoarseDepth source target N) (computedFamilyMemoCode source target N (inputHeight N ^ 2)) + hN rfl (fun _ => rfl) hsize hsymbols execution + +theorem computedExecutionCoarseBitWork_integrable (source target : List ℕ) (N : ℕ) : + Integrable (computedExecutionCoarseBitWork source target N) (computedExecutionLaw source target N) := + symbolicComputedExecutionCoarseBitWork_integrable source target N + (computedPhysicalCoarseDepth source target N) (computedFamilyMemoCode source target N (inputHeight N ^ 2)) + +theorem computedExecutionCoarseBitWork_expected_near_linear (epsilon : ℝ) (hepsilon : 0 < epsilon) : + ∀ᶠ N in atTop, ∀ source target : List ℕ, source.length + target.length ≤ N → + (∀ a ∈ source ++ target, Nat.size a ≤ inputHeight N ^ 3) → + (∫ execution, computedExecutionCoarseBitWork source target N execution + ∂computedExecutionLaw source target N) ≤ (N + 2 : ℝ) ^ (1 + epsilon) := by + have he : 0 < epsilon / 3 := by positivity + filter_upwards [computedExecutionCoarseBitWork_bound, + computedExecutionCoarseWork_expected_near_linear (epsilon / 3) he, + computedExecutionCoarseInputWork_expected_near_linear (epsilon / 3) he, + fixed_height_power_subpolynomial 36 (epsilon / 3) he, + constant_le_rpow_eventually 2 (epsilon / 3) he] with N hb hc hi hp ht + intro source target hsize hsymbols + let μ := computedExecutionLaw source target N + have hic := computedExecutionCoarseWork_integrable source target N + have hii := computedExecutionCoarseInputWork_integrable source target N + have hbound : (∫ execution, computedExecutionCoarseBitWork source target N execution ∂μ) ≤ + (inputHeight N : ℝ) ^ 36 * ((∫ execution, computedExecutionCoarseWork source target N execution ∂μ) + + ∫ execution, computedExecutionCoarseInputWork source target N execution ∂μ) := by + calc + _ ≤ ∫ execution, (inputHeight N : ℝ) ^ 36 * + (computedExecutionCoarseWork source target N execution + + computedExecutionCoarseInputWork source target N execution) ∂μ := + integral_mono (computedExecutionCoarseBitWork_integrable source target N) + ((hic.add hii).const_mul _) (hb source target hsize hsymbols) + _ = _ := by rw [integral_const_mul, integral_add hic hii] + have hsum := add_le_add (hc source target hsize) (hi source target hsize) + calc + _ ≤ (inputHeight N : ℝ) ^ 36 * (2 * (N + 2 : ℝ) ^ (1 + epsilon / 3)) := + hbound.trans (mul_le_mul_of_nonneg_left (by linarith only [hsum]) (by positivity)) + _ ≤ (N + 2 : ℝ) ^ (epsilon / 3) * (2 * (N + 2 : ℝ) ^ (1 + epsilon / 3)) := + mul_le_mul_of_nonneg_right hp (by positivity) + _ ≤ (N + 2 : ℝ) ^ (epsilon / 3) * + ((N + 2 : ℝ) ^ (epsilon / 3) * (N + 2 : ℝ) ^ (1 + epsilon / 3)) := by gcongr + _ = _ := by + rw [← Real.rpow_add (by positivity), ← Real.rpow_add (by positivity)] + congr 1 + ring + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedCoarseBits.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedCoarseBits.lean new file mode 100644 index 0000000000000000000000000000000000000000..847cb8c8a7d32f6955fd673be775dda4d76434a5 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedCoarseBits.lean @@ -0,0 +1,84 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarsePrecision +import OAI.Combinatorics.EditApproximation.Coarse.CoarseGlobalSeed +import OAI.Combinatorics.EditApproximation.Refinement.ComputedParameterRegisters + +namespace OAI + +namespace EditApproximation +open Filter + +private theorem coarseEncoding_scalar (H B D q L n k : ℕ) + (hH : 100 ≤ H) (hB : 2 ≤ B) (hD : D ≤ H) + (hb : Nat.size B ≤ 2 * H) (hq : Nat.size q ≤ 2 * H) + (hL : Nat.size L ≤ 2 * H) (hn : Nat.size n ≤ 2 * H) (hk : Nat.size k ≤ 2 * H) : + Nat.size (n + B * k * coarseInternalNodes B D) + + 2 * (Nat.size q + D * (Nat.size L + Nat.size B + Nat.size q) + 2) + 1 ≤ H ^ 3 := by + have hnodes := (Nat.size_le_size (show coarseInternalNodes B D ≤ B ^ D from + Nat.le_of_succ_le (coarseInternalNodes_add_one_le_pow B D hB))).trans + (natural_power_bit_length B D) + have hprod := natural_product_bit_length (B * k) (coarseInternalNodes B D) + have hbk := natural_product_bit_length B k + have hsum := natural_sum_bit_length n (B * k * coarseInternalNodes B D) + have hdh := Nat.mul_le_mul hD hb + have hsuminputs : Nat.size L + Nat.size B + Nat.size q ≤ 6 * H := by omega + have hcoeff := Nat.mul_le_mul hD hsuminputs + have hhsq : H ≤ H ^ 2 := Nat.le_pow (by decide) + have hcub : 100 * H ^ 2 ≤ H ^ 3 := by + have hh := Nat.mul_le_mul_right (H ^ 2) hH + nlinarith only [hh] + nlinarith only [hnodes, hprod, hbk, hsum, hdh, hcoeff, hb, hq, hL, hn, hk, + hH, hhsq, hcub] + +/-- Every root cell of every computed coarse call has polynomial bit width, +without conditioning on the accuracy event or on its threshold labels. -/ + theorem computedCoarse_root_encoding_bits : + ∀ᶠ N : ℕ in atTop, ∀ B d n k : ℕ, + B = (integerParameters N).B → d = computedCoarseDepth N n → + n ≤ N → k ≤ 2 * (N + 2) → + ∀ {α : Type} [DecidableEq α] (frame : List (Option α)) + (tree : CoarseSourceTree B α d) (draws : CoarseThresholdDraws B d), + tree.word.length ≤ N → ∀ start shift, + rationalEncodingBits (coarseThresholdEstimate k (initialThresholdQ N) (initialLambda N) + frame tree draws k start shift) ≤ inputHeight N ^ 3 := by + filter_upwards [computedParameterPower_word, eventually_ge_atTop 1, + inputSmallLog_tendsto.eventually (eventually_ge_atTop 200)] with N hpower hN hell + intro B d n k hBdef hddef hn hk α inst frame tree draws htree start shift + have hH := computed_coarse_height_large N (by omega) hell + have hbranch := computed_coarse_branching N (by omega) hell + have hB : 0 < B := by omega + have hq : 0 < inputHeight N ^ 4 := pow_pos (Nat.two_pow_pos _) _ + have hL : 0 < 64 * inputHeight N := Nat.mul_pos (by decide) (Nat.two_pow_pos _) + have hraw := coarseThresholdEstimate_encoding_bits k (inputHeight N ^ 4) + (64 * inputHeight N) frame tree draws hB hq hL start shift + have hbSize : Nat.size B ≤ 2 * inputHeight N := by + have hb := Nat.size_le_size (computed_coarse_B_upper N (by omega) hell) + simp only [Nat.size_pow] at hb + rw [hBdef] + omega + have hqSize : Nat.size (inputHeight N ^ 4) ≤ 2 * inputHeight N := by + have h := hpower 4 (by omega) + omega + have hHSize : Nat.size (inputHeight N) ≤ inputHeight N := + Nat.size_le.mpr (Nat.lt_pow_self (by decide : 1 < (2 : ℕ))) + have hLSize : Nat.size (64 * inputHeight N) ≤ 2 * inputHeight N := by + have h := natural_product_bit_length 64 (inputHeight N) + rw [show Nat.size 64 = 7 by decide] at h + omega + have hnSize : Nat.size tree.word.length ≤ 2 * inputHeight N := by + have h := (Nat.size_le_size (htree.trans (Nat.le_add_right N 2))).trans (inputLength_register_word N) + omega + have hkSize : Nat.size k ≤ 2 * inputHeight N := by + have h := (Nat.size_le_size hk).trans (natural_product_bit_length 2 (N + 2)) + have hn := inputLength_register_word N + rw [show Nat.size 2 = 2 by decide] at h + omega + have hscalar := coarseEncoding_scalar (inputHeight N) B d + (inputHeight N ^ 4) (64 * inputHeight N) tree.word.length k + (by omega) (by omega) (hddef.symm ▸ (computed_coarse_depth N n (by omega) hn hell).2) + hbSize hqSize hLSize hnSize hkSize + simpa only [initialThresholdQ, initialLambda, Nat.cast_pow, Nat.cast_mul, Nat.cast_ofNat] + using hraw.trans hscalar + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedCoarseBudget.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedCoarseBudget.lean new file mode 100644 index 0000000000000000000000000000000000000000..35522ce558bd03a4255a98eb62c0cc01e2327ed4 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedCoarseBudget.lean @@ -0,0 +1,91 @@ +import OAI.Combinatorics.EditApproximation.Refinement.ComputedPhysicalWork +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalFamilyMemoCoarse +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! Polynomial coarse-sampling budgets for the computed dimensions. -/ + +namespace EditApproximation +open MeasureTheory Filter + +section Coarse +variable {M J R B : ℕ} [NeZero M] [NeZero R] [NeZero B] + (source target : List ℕ) (N : ℕ) + (depth : PhysicalEntry M J target.length → ℕ) + (encode : Sum (PhysicalFamilyScalarKey (M := M) (J := J) (R := R) + target N (integerParameters N).P (inputSmallLog N) (40 * smallLogExponent N) + (inputHeight N) (inputSmallLog N ^ 80) (computedSeedPassCount N) (inputHeight N ^ 2)) + (ChargedPhysicalRequest M J target.length (computedSeedPassCount N + 1) + (inputHeight N ^ 2) (integerParameters N).T (integerParameters N).S) → ℕ) + + + + def SymbolicComputedCoarseBudget (budget : ℝ) : Prop := + ∀ draw, integral (coarseFullSeedMeasure B depth + (fun entry => physicalSource source entry.1) + (fun entry => substring target entry.2.lo entry.2.hi)) + (symbolicComputedCoarseWork (B := B) source target N depth encode draw) ≤ budget + + theorem symbolicComputedCoarseWork_expected_le + (hN : 0 < N) (hell : 200 ≤ inputSmallLog N) (hsize : source.length + target.length ≤ N) + (hM : M = (integerParameters N).M) (hJ : J = intervalTreeDepth M source.length) + (hB : B = (integerParameters N).B) + (hdepth : ∀ entry, depth entry = computedCoarseDepth N + (coarseEntryWidth (physicalSource source entry.1) (substring target entry.2.lo entry.2.hi))) + (hinjective : Function.Injective encode) + (hbounded : ∀ key, encode key < 2 ^ (16384 * inputHeight N + 5)) + (hinverse : coarseInverseAllowanceFactor B (initialThresholdQ N) (initialLambda N) ≤ + (inputHeight N : ℝ) ^ 8) : + SymbolicComputedCoarseBudget (B := B) source target N depth encode + (computedWidthEnvelope N * computedCoarseWidthOverhead N) := by + intro draw + have hH : 105 ≤ inputHeight N := (by omega : 105 ≤ inputSmallLog N).trans + (computed_smallLog_le_height N) + apply physicalFamilyMemoCoarseWork_expected_le source target N (integerParameters N).P + (inputHeight N) (integerParameters N).T (integerParameters N).S (computedSeedPassCount N) + (inputHeight N ^ 2) (scheduledSeedFactor N) (scheduledSeedMultiplier N) + (rationalParameters (inputSmallLog N)).tau (rationalParameters (inputSmallLog N)).eta + (rationalParameters (inputSmallLog N)).kappa (rationalParameters (inputSmallLog N)).delta + draw B depth (computedParameterP_pos N) hN hell hB hsize hdepth hinverse + (16384 * inputHeight N + 5) encode hinjective hbounded _ (by rfl) (computedWidthEnvelope N) + intro coarse + let initial := clampedSeedNat (physicalCoarseSeedTable source target N B depth coarse) + let root := localFinalRootRequest (M := M) (J := J) target N (integerParameters N).T + (integerParameters N).S (inputHeight N) (Nat.two_pow_pos _) (finalTargetState target.length) + let tree := physicalFamilyDependencyTree source target N (integerParameters N).P + (inputHeight N) (integerParameters N).T (integerParameters N).S (computedSeedPassCount N) + (inputHeight N ^ 2) (scheduledSeedFactor N) (scheduledSeedMultiplier N) + (rationalParameters (inputSmallLog N)).tau (rationalParameters (inputSmallLog N)).eta + (rationalParameters (inputSmallLog N)).kappa (rationalParameters (inputSmallLog N)).delta + initial (computedParameterP_pos N) draw root + have hv := physicalFamilyDependencyTree_valid source target N (integerParameters N).P + (inputHeight N) (integerParameters N).T (integerParameters N).S (computedSeedPassCount N) + (inputHeight N ^ 2) (scheduledSeedFactor N) (scheduledSeedMultiplier N) + (rationalParameters (inputSmallLog N)).tau (rationalParameters (inputSmallLog N)).eta + (rationalParameters (inputSmallLog N)).kappa (rationalParameters (inputSmallLog N)).delta + initial (computedParameterP_pos N) draw hN hell hM rfl rfl rfl le_rfl + (fun pass => (scheduledSeedFactor_bounds N pass).1) + (fun pass => (scheduledSeedFactor_bounds N pass).2) root + have hd : tree.depth = intervalTreeDepth (integerParameters N).M source.length := by + rw [physicalFamilyDependencyTree_depth] + exact hJ.trans (congrArg (fun m => intervalTreeDepth m source.length) hM) + have hk := physicalFamilyDependencyTree_rank source target N (integerParameters N).P + (inputHeight N) (integerParameters N).T (integerParameters N).S (computedSeedPassCount N) + (inputHeight N ^ 2) (scheduledSeedFactor N) (scheduledSeedMultiplier N) + (rationalParameters (inputSmallLog N)).tau (rationalParameters (inputSmallLog N)).eta + (rationalParameters (inputSmallLog N)).kappa (rationalParameters (inputSmallLog N)).delta + initial (computedParameterP_pos N) draw rfl rfl rfl root + have hw := computed_widthWork_le_envelope N source.length hN (by omega) hell hH tree + (by simpa only [hM] using hv) hd hk + simpa only [hM] using hw + + theorem symbolicComputedCoarseBudget_mono (a b : ℝ) (hab : a ≤ b) + (h : SymbolicComputedCoarseBudget (B := B) source target N depth encode a) : + SymbolicComputedCoarseBudget (B := B) source target N depth encode b := fun draw => (h draw).trans hab + +end Coarse +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedCoarseCandidateWork.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedCoarseCandidateWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..548e9df81ae1e126fe0b3b6c6d4c1ad573c6a640 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedCoarseCandidateWork.lean @@ -0,0 +1,158 @@ +import OAI.Combinatorics.EditApproximation.Refinement.ComputedCoarseBitParameters +import OAI.Combinatorics.EditApproximation.Coarse.CoarseNumericalUnit +import OAI.Combinatorics.EditApproximation.Coarse.CoarseRootBounds +import OAI.Combinatorics.EditApproximation.Coarse.CoarseInitialCost + +namespace OAI + +namespace EditApproximation +open Filter +namespace BinaryFraction + +theorem coarseGuess_le (n : ℕ) (i : CoarseGuessIndex n) : coarseGuess n i ≤ 2 * (n + 1) := by + have hi : i.val ≤ Nat.clog 2 n := by omega + have hp := Nat.pow_le_pow_right (by decide : 0 < (2 : ℕ)) hi + by_cases hn : n = 0 + · subst n + simp only [Nat.clog_zero_right, pow_zero] at hp + exact hp.trans (by decide) + · have hr := (rejectionWord_range n (by omega)).2 + unfold rejectionBitCount at hr + exact hp.trans (by omega) + +private theorem coarseCandidate_scalar (H a root add mul size : ℕ) (hH : 100 ≤ H) + (hr : root ≤ H ^ 30 * (2 * a + 1)) + (ha : add ≤ 6000 * (H ^ 3 + 1) ^ 2) + (hm : mul ≤ 2000 * (8 * H ^ 3 + 7) ^ 2) (hs : size ≤ H ^ 3) : + root + add + mul + size + 3 ≤ H ^ 32 * (a + 1) := by + have ht : 1 ≤ H ^ 3 := one_le_pow₀ (by omega) + have hb : add + mul + size + 3 ≤ 1000000 * H ^ 6 := by + nlinarith only [ha, hm, hs, ht] + have hc : 1000000 ≤ H ^ 4 := by + have h := Nat.pow_le_pow_left hH 4 + norm_num at h + omega + have hbig : 1000000 * H ^ 6 ≤ H ^ 10 := by + calc + _ ≤ H ^ 4 * H ^ 6 := Nat.mul_le_mul_right _ hc + _ = _ := by rw [← pow_add] + have hexp : H ^ 10 ≤ H ^ 30 := Nat.pow_le_pow_right (by omega) (by omega) + have htwo : 2 * H ^ 30 ≤ H ^ 32 := by + have hh : 2 ≤ H ^ 2 := by nlinarith + have hz := Nat.mul_le_mul_left (H ^ 30) hh + simpa only [← pow_add, Nat.mul_comm] using hz + nlinarith only [hr, hb, hbig, hexp, Nat.mul_le_mul_right (a + 1) htwo] + +theorem computedCoarseRoot_for_candidate : + ∀ᶠ N : ℕ in atTop, ∀ B d : ℕ, ∀ x y : List ℕ, + B = (integerParameters N).B → d = computedCoarseDepth N (coarseEntryWidth x y) → + coarseEntryWidth x y ≤ N → ∀ (hB : 0 < B) (hq : 0 < inputHeight N ^ 4) + (hL : 0 < 64 * inputHeight N) + (i : CoarseGuessIndex (coarseEntryWidth x y)) (draws : CoarseThresholdDraws B d), + let k := coarseGuess (coarseEntryWidth x y) i + let root := coarseRootWithWork k (inputHeight N ^ 4) (64 * inputHeight N) hB hq hL + (coarseTargetFrame k (coarsePadTo (coarseEntryWidth x y) y)) + (coarseEntryTree B d x y) draws 0 (coarseRootShift k) + root.1.width ≤ inputHeight N ^ 3 ∧ + root.2 ≤ inputHeight N ^ 30 * (2 * coarseActiveArrayWork k + (initialThresholdQ N) (initialLambda N) (coarseEntryTree B d x y) draws k + 1) := by + filter_upwards [computedCoarse_bitParameters, eventually_ge_atTop 1, + inputSmallLog_tendsto.eventually (eventually_ge_atTop 200)] with N hbits hN hell + intro B d x y hBdef hddef hsize hB hq hL i draws + let H := inputHeight N + let k := coarseGuess (coarseEntryWidth x y) i + let frame := coarseTargetFrame k (coarsePadTo (coarseEntryWidth x y) y) + let tree := coarseEntryTree B d x y + let root := coarseRootWithWork k (H ^ 4) (64 * H) hB hq hL frame tree draws 0 (coarseRootShift k) + have hH : 100 ≤ H := by + exact (by decide : 100 ≤ 256).trans + (computed_coarse_height_large N (by omega) hell) + have hk : k ≤ 2 * (N + 2) := + (coarseGuess_le _ i).trans (by omega) + obtain ⟨hden, hbound, hBbits, hqbits, hLbits, hNbits, hD⟩ := + hbits B d (coarseEntryWidth x y) k hBdef hddef hsize hk + have hcap : coarseEntryWidth x y ≤ B ^ d := by + rw [hBdef, hddef] + exact (computed_coarse_depth N _ (by omega) hsize hell).1 + have htree : 0 + tree.word.length ≤ N := by + dsimp only [tree] + rw [coarseEntryTree_word B d x y hcap, coarsePadTo_length _ _ (le_max_left _ _)] + simpa only [Nat.zero_add] using hsize + have hdepth : d ≤ H := hddef.symm ▸ (computed_coarse_depth N _ (by omega) hsize hell).2 + have hrw : root.1.width ≤ H ^ 3 := + coarseRootWithWork_width k (H ^ 4) (64 * H) N (10 * H ^ 2) (H ^ 3) + hB hq hL frame tree draws 0 (coarseRootShift k) + hBbits hqbits hLbits hNbits hden hbound htree + have hrc := coarseRootWithWork_height_bound k (H ^ 4) (64 * H) N (10 * H ^ 2) H + hB hq hL frame tree draws 0 (coarseRootShift k) + hBbits hqbits hLbits hNbits hden hD hdepth hbound htree + have hrc' : root.2 ≤ H ^ 30 * + (2 * coarseActiveArrayWork k (initialThresholdQ N) (initialLambda N) tree draws k + 1) := by + have hc := hrc.trans (Nat.mul_le_mul_right _ (coarseNumericalUnit_le_power H (by omega))) + simpa only [initialThresholdQ, initialLambda, H, Nat.cast_pow, Nat.cast_mul, Nat.cast_ofNat] using hc + exact ⟨hrw, hrc'⟩ + +private theorem coarseCandidate_k_bits (N k B d : ℕ) + (hb : Nat.size (coarseLevelMagnitude N k B d + 2) + + 2 * (10 * inputHeight N ^ 2) + 1 ≤ inputHeight N ^ 3) : + Nat.size k + 2 ≤ inputHeight N ^ 3 := by + have h := Nat.size_le_size (coarseLevelMagnitude_ge N k B d) + have h' := Nat.size_le_size (show coarseLevelMagnitude N k B d ≤ + coarseLevelMagnitude N k B d + 2 by omega) + have hh : 0 < inputHeight N := Nat.two_pow_pos _ + have hdpos : 0 < 10 * inputHeight N ^ 2 := by positivity + omega + +/-- Every executed dyadic candidate has a short binary value and its complete +arithmetic cost is bounded by a fixed height power times its active-array work. -/ +theorem computedCoarseCandidate_bounds : + ∀ᶠ N : ℕ in atTop, ∀ B d : ℕ, ∀ x y : List ℕ, + B = (integerParameters N).B → d = computedCoarseDepth N (coarseEntryWidth x y) → + coarseEntryWidth x y ≤ N → ∀ (hB : 0 < B) (hq : 0 < inputHeight N ^ 4) + (hL : 0 < 64 * inputHeight N) + (i : CoarseGuessIndex (coarseEntryWidth x y)) (draws : CoarseThresholdDraws B d), + (coarseCandidateWithWork (inputHeight N ^ 4) (64 * inputHeight N) hB hq hL x y i draws).1.width ≤ + inputHeight N ^ 4 ∧ + (coarseCandidateWithWork (inputHeight N ^ 4) (64 * inputHeight N) hB hq hL x y i draws).2 ≤ + inputHeight N ^ 32 * (coarseActiveArrayWork (coarseGuess (coarseEntryWidth x y) i) + (initialThresholdQ N) (initialLambda N) (coarseEntryTree B d x y) draws + (coarseGuess (coarseEntryWidth x y) i) + 1) := by + filter_upwards [computedCoarseRoot_for_candidate, computedCoarse_bitParameters, + eventually_ge_atTop 1, + inputSmallLog_tendsto.eventually (eventually_ge_atTop 200)] with N hroot hbits hN hell + intro B d x y hBdef hddef hsize hB hq hL i draws + let H := inputHeight N + let k := coarseGuess (coarseEntryWidth x y) i + let root := coarseRootWithWork k (H ^ 4) (64 * H) hB hq hL + (coarseTargetFrame k (coarsePadTo (coarseEntryWidth x y) y)) + (coarseEntryTree B d x y) draws 0 (coarseRootShift k) + have hH : 100 ≤ H := (by decide : 100 ≤ 256).trans + (computed_coarse_height_large N (by omega) hell) + obtain ⟨hrw, hrc'⟩ := hroot B d x y hBdef hddef hsize hB hq hL i draws + change root.1.width ≤ H ^ 3 at hrw + change root.2 ≤ H ^ 30 * (2 * coarseActiveArrayWork k + (initialThresholdQ N) (initialLambda N) (coarseEntryTree B d x y) draws k + 1) at hrc' + have hk : k ≤ 2 * (N + 2) := (coarseGuess_le _ i).trans (by omega) + have hbound := (hbits B d (coarseEntryWidth x y) k hBdef hddef hsize hk).2.1 + have hkw : Nat.size k + 2 ≤ H ^ 3 := coarseCandidate_k_bits N k B d hbound + have hnw : (nat k).width ≤ H ^ 3 := (nat_width_le k).trans hkw + have hsw := canonicalAddWithWork_width root.1 (nat k) (H ^ 3) hrw hnw + have hsc := canonicalAddWithWork_cost root.1 (nat k) (H ^ 3) hrw hnw + have htw : (nat 2).width ≤ 8 * H ^ 3 + 6 := (nat_width_le 2).trans (by rw [show Nat.size 2 = 2 by decide]; omega) + have hmw := canonicalMulWithWork_width (nat 2) (canonicalAddWithWork root.1 (nat k)).1 + (8 * H ^ 3 + 6) htw hsw + have hmc := canonicalMulWithWork_cost (nat 2) (canonicalAddWithWork root.1 (nat k)).1 + (8 * H ^ 3 + 6) htw hsw + constructor + · change (canonicalMulWithWork (nat 2) (canonicalAddWithWork root.1 (nat k)).1).1.width ≤ H ^ 4 + have hh := Nat.mul_le_mul_right (H ^ 3) hH + have ht : 1 ≤ H ^ 3 := one_le_pow₀ (by omega) + nlinarith only [hmw, hh, ht] + · change root.2 + (canonicalAddWithWork root.1 (nat k)).2 + + (canonicalMulWithWork (nat 2) (canonicalAddWithWork root.1 (nat k)).1).2 + Nat.size k + 3 ≤ _ + exact coarseCandidate_scalar H _ _ _ _ _ hH hrc' hsc hmc (by omega) + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedCoarseControlSpace.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedCoarseControlSpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..b3f07440e9c609320c25bfec1906ea866eef7e3a --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedCoarseControlSpace.lean @@ -0,0 +1,91 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseInitialControlSpace +import OAI.Combinatorics.EditApproximation.Refinement.ComputedCoarseHistorySpace +import OAI.Combinatorics.EditApproximation.Refinement.ComputedCoarseBitWork +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation +open Filter + +def physicalCoarseControlEntry {M J B : ℕ} [NeZero B] (source target : List ℕ) (N : ℕ) + (depth : PhysicalEntry M J target.length → ℕ) (draw : PhysicalCoarseDraw source target B depth) + (entry : PhysicalEntry M J target.length) : ℕ := + 64 * BinaryFraction.coarseIndexedInitialInvocations (inputHeight N ^ 4) (64 * inputHeight N) N + (Nat.pos_of_neZero B) (pow_pos (Nat.two_pow_pos _) _) + (Nat.mul_pos (by decide) (Nat.two_pow_pos _)) + (physicalSource source entry.1) (substring target entry.2.lo entry.2.hi) (draw entry) + +theorem physicalCoarseControlEntry_fits {M J : ℕ} : + ∀ᶠ N : ℕ in atTop, ∀ B : ℕ, ∀ (_hB : NeZero B), + ∀ (source target : List ℕ) (depth : PhysicalEntry M J target.length → ℕ), + B = (integerParameters N).B → + (∀ entry, depth entry = computedCoarseDepth N + (coarseEntryWidth (physicalSource source entry.1) (substring target entry.2.lo entry.2.hi))) → + source.length + target.length ≤ N → + (∀ a ∈ source ++ target, Nat.size a ≤ inputHeight N ^ 3) → + ∀ (draw : PhysicalCoarseDraw source target B depth) (entry : PhysicalEntry M J target.length), + physicalCoarseControlEntry source target N depth draw entry ≤ (N + 2) ^ 182 := by + filter_upwards [BinaryFraction.computedCoarseIndexedInitialInvocations_polynomial, eventually_ge_atTop 64] with N hN hlarge + intro B inst source target depth hB hd hsize hsymbols draw entry + have hx := physicalSource_length_le source entry.1 + have hy : (substring target entry.2.lo entry.2.hi).length ≤ target.length := by + simp only [substring, List.length_drop, List.length_take] + exact (Nat.sub_le _ _).trans (min_le_right _ _) + have hs : ∀ a ∈ physicalSource source entry.1 ++ substring target entry.2.lo entry.2.hi, + Nat.size a ≤ inputHeight N ^ 3 := by + intro a ha + rcases List.mem_append.mp ha with ha | ha + · exact hsymbols a (List.mem_append_left _ (physicalSource_mem source entry.1 a ha)) + · exact hsymbols a (List.mem_append_right _ (List.mem_of_mem_take (List.mem_of_mem_drop ha))) + have h := hN B (depth entry) (physicalSource source entry.1) + (substring target entry.2.lo entry.2.hi) hB (hd entry) + (max_le (by omega) (by omega)) hs (Nat.pos_of_neZero B) + (pow_pos (Nat.two_pow_pos _) _) (Nat.mul_pos (by decide) (Nat.two_pow_pos _)) (draw entry) + change 64 * BinaryFraction.coarseIndexedInitialInvocations + (inputHeight N ^ 4) (64 * inputHeight N) N (Nat.pos_of_neZero B) + (pow_pos (Nat.two_pow_pos _) _) (Nat.mul_pos (by decide) (Nat.two_pow_pos _)) + (physicalSource source entry.1) (substring target entry.2.lo entry.2.hi) (draw entry) ≤ _ + calc + _ ≤ 64 * (N + 2) ^ 181 := Nat.mul_le_mul_left 64 h + _ ≤ (N + 2) * (N + 2) ^ 181 := Nat.mul_le_mul_right _ (by omega) + _ = _ := (pow_succ' (N + 2) 181).symm + +/-- A 64-word control-frame allowance for every recursive invocation of +every coarse cache miss, conservatively retained until termination. -/ + + +theorem computedFamilyCoarseControlCapacity_eq (source target : List ℕ) (N : ℕ) + (input : ComputedFamilyInput source target N) : + computedFamilyCoarseControlCapacity source target N input = + ((computedFamilyResult source target N input).freshKeys.map + (coarseHistoryKeyCost (fun _ => (N + 2) ^ 182))).sum := + computedFamilyKernelWork_eq_fresh_sum source target N input _ + +theorem computedFamilyCoarseControlCapacity_bound (source target : List ℕ) (N : ℕ) + (input : ComputedFamilyInput source target N) : + computedFamilyCoarseControlCapacity source target N input ≤ + (N + 2) ^ 182 * (computedFamilyResult source target N input).requests := by + apply computedFamilyKernelWork_le + exact coarseHistoryKeyCost_le _ _ (fun _ => le_rfl) + +theorem computedFamilyCoarseControlCapacity_polynomial : + ∀ᶠ N : ℕ in atTop, ∀ source target : List ℕ, source.length + target.length ≤ N → + ∀ input : ComputedFamilyInput source target N, + computedFamilyCoarseControlCapacity source target N input ≤ (N + 2) ^ 184 := by + filter_upwards [computedFamilyResult_requests_near_linear 1 (by norm_num)] with N hr + intro source target hsize input + have hrequests : (computedFamilyResult source target N input).requests ≤ (N + 2) ^ 2 := by + have h := hr source target hsize input + norm_num at h + exact_mod_cast h + calc + _ ≤ (N + 2) ^ 182 * (computedFamilyResult source target N input).requests := + computedFamilyCoarseControlCapacity_bound source target N input + _ ≤ (N + 2) ^ 182 * (N + 2) ^ 2 := Nat.mul_le_mul_left _ hrequests + _ = _ := by rw [← pow_add] + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedCoarseCopySpace.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedCoarseCopySpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..67d32692598dc9e2d60eb1d523ea625d92553beb --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedCoarseCopySpace.lean @@ -0,0 +1,66 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseInputStorage +import OAI.Combinatorics.EditApproximation.Coarse.CoarseInitialStorage +import OAI.Combinatorics.EditApproximation.Refinement.ComputedFreshWork +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation +open Filter + + + +theorem physicalCoarseInputStorage_polynomial {M J : ℕ} (source target : List ℕ) (N : ℕ) + (hsize : source.length + target.length ≤ N) + (hsymbol : ∀ a ∈ source ++ target, Nat.size a ≤ inputHeight N ^ 3) + (entry : PhysicalEntry M J target.length) : + physicalCoarseInputStorage source target entry ≤ (N + 2) ^ 16 := by + unfold physicalCoarseInputStorage + exact coarsePreparedInputStorage_polynomial source target N + (physicalSourceInterval source.length entry.1).lo + (physicalSourceInterval source.length entry.1).hi entry.2.lo entry.2.hi + (physicalSourceInterval source.length entry.1).ordered + (physicalSourceInterval source.length entry.1).valid entry.2.ordered entry.2.valid hsize hsymbol + + + +theorem computedFamilyCoarseCopyStorage_eq (source target : List ℕ) (N : ℕ) + (input : ComputedFamilyInput source target N) : + computedFamilyCoarseCopyStorage source target N input = + ((computedFamilyResult source target N input).freshKeys.map (coarseHistoryKeyCost + (physicalCoarseInputStorage (M := (integerParameters N).M) + (J := intervalTreeDepth (integerParameters N).M source.length) source target))).sum := + computedFamilyKernelWork_eq_fresh_sum source target N input _ + +theorem computedFamilyCoarseCopyStorage_bound (source target : List ℕ) (N : ℕ) + (hsize : source.length + target.length ≤ N) + (hsymbol : ∀ a ∈ source ++ target, Nat.size a ≤ inputHeight N ^ 3) + (input : ComputedFamilyInput source target N) : + computedFamilyCoarseCopyStorage source target N input ≤ + (N + 2) ^ 16 * (computedFamilyResult source target N input).requests := by + apply computedFamilyKernelWork_le + apply coarseHistoryKeyCost_le + intro entry + exact physicalCoarseInputStorage_polynomial source target N hsize hsymbol entry + +theorem computedFamilyCoarseCopyStorage_polynomial : + ∀ᶠ N : ℕ in atTop, ∀ source target : List ℕ, source.length + target.length ≤ N → + (∀ a ∈ source ++ target, Nat.size a ≤ inputHeight N ^ 3) → + ∀ input : ComputedFamilyInput source target N, + computedFamilyCoarseCopyStorage source target N input ≤ (N + 2) ^ 18 := by + filter_upwards [computedFamilyResult_requests_near_linear 1 (by norm_num)] with N hr + intro source target hsize hsymbol input + have hrequests : (computedFamilyResult source target N input).requests ≤ (N + 2) ^ 2 := by + have h := hr source target hsize input + norm_num at h + exact_mod_cast h + calc + _ ≤ (N + 2) ^ 16 * (computedFamilyResult source target N input).requests := + computedFamilyCoarseCopyStorage_bound source target N hsize hsymbol input + _ ≤ (N + 2) ^ 16 * (N + 2) ^ 2 := Nat.mul_le_mul_left _ hrequests + _ = _ := by rw [← pow_add] + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedCoarseExecution.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedCoarseExecution.lean new file mode 100644 index 0000000000000000000000000000000000000000..500d5299f910dd3ebdcd55d7bc5a2eb084281ccc --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedCoarseExecution.lean @@ -0,0 +1,28 @@ +import OAI.Combinatorics.EditApproximation.Refinement.ComputedPhysicalWork +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalCoarseExecution +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation + +open MeasureTheory + + + + + +instance computedPhysicalCoarseLaw_probability (source target : List ℕ) (N : ℕ) : + IsProbabilityMeasure (computedPhysicalCoarseLaw source target N) := by + unfold computedPhysicalCoarseLaw + infer_instance + +noncomputable def computedPhysicalCoarseSeed (source target : List ℕ) (N : ℕ) := + physicalCoarseSeedTable (M := (integerParameters N).M) + (J := intervalTreeDepth (integerParameters N).M source.length) + source target N (integerParameters N).B (computedPhysicalCoarseDepth source target N) + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedCoarseHistory.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedCoarseHistory.lean new file mode 100644 index 0000000000000000000000000000000000000000..ab3daaaede1094999f8f30601c35931eba8821be --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedCoarseHistory.lean @@ -0,0 +1,112 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseRootHistory +import OAI.Combinatorics.EditApproximation.Refinement.ComputedCoarseArrayStorage + +namespace OAI + +namespace EditApproximation +namespace BinaryFraction +open Filter + +theorem computedCoarseRootHistory_bound : + ∀ᶠ N : ℕ in atTop, ∀ B d : ℕ, ∀ x y : List ℕ, + B = (integerParameters N).B → d = computedCoarseDepth N (coarseEntryWidth x y) → + coarseEntryWidth x y ≤ N → + ∀ (hB : 0 < B) (hq : 0 < inputHeight N ^ 4) (hL : 0 < 64 * inputHeight N) + (i : CoarseGuessIndex (coarseEntryWidth x y)) (draws : CoarseThresholdDraws B d), + coarseRootArrayHistory (coarseGuess (coarseEntryWidth x y) i) + (inputHeight N ^ 4) (64 * inputHeight N) hB hq hL + (coarseTargetFrame (coarseGuess (coarseEntryWidth x y) i) + (coarsePadTo (coarseEntryWidth x y) y)) (coarseEntryTree B d x y) draws 0 ≤ + (32 * (inputHeight N ^ 3 + 1)) * + ((B * (2 * coarseGuess (coarseEntryWidth x y) i + 1) + 1) * coarseCompleteNodes B d) := by + filter_upwards [computedCoarse_bitParameters, eventually_ge_atTop 1, + inputSmallLog_tendsto.eventually (eventually_ge_atTop 200)] with N hbits hN hell + intro B d x y hBdef hddef hsize hB hq hL i draws + let H := inputHeight N + let k := coarseGuess (coarseEntryWidth x y) i + have hk : k ≤ 2 * (N + 2) := (coarseGuess_le _ i).trans (by omega) + obtain ⟨hden, hbound, hBbits, hqbits, hLbits, hNbits, _hD⟩ := + hbits B d (coarseEntryWidth x y) k hBdef hddef hsize hk + have hcap : coarseEntryWidth x y ≤ B ^ d := by + rw [hBdef, hddef] + exact (computed_coarse_depth N _ (by omega) hsize hell).1 + have htree : 0 + (coarseEntryTree B d x y).word.length ≤ N := by + rw [coarseEntryTree_word B d x y hcap, coarsePadTo_length _ _ (le_max_left _ _)] + simpa only [Nat.zero_add] using hsize + exact coarseRootArrayHistory_bound k (H ^ 4) (64 * H) N (10 * H ^ 2) (H ^ 3) + hB hq hL _ _ draws 0 hBbits hqbits hLbits hNbits hden hbound htree + +theorem computedCoarseRootHistory_polynomial (N B d k n : ℕ) + (hN : 0 < N) (hell : 200 ≤ inputSmallLog N) + (hBdef : B = (integerParameters N).B) (hddef : d = computedCoarseDepth N n) + (hn : n ≤ N) (hk : k ≤ 2 * (N + 2)) : + (32 * (inputHeight N ^ 3 + 1)) * + ((B * (2 * k + 1) + 1) * coarseCompleteNodes B d) ≤ (N + 2) ^ 32 := by + let X := N + 2 + have hX : 2 ≤ X := by dsimp only [X]; omega + have hH := Nat.pow_le_pow_left (computed_height_polynomial N) 3 + rw [← pow_mul] at hH + change inputHeight N ^ 3 ≤ X ^ 12 at hH + have hone : 1 ≤ X ^ 12 := one_le_pow₀ (by omega) + have hc : 64 ≤ X ^ 6 := (by decide : 64 ≤ (2 : ℕ) ^ 6).trans (Nat.pow_le_pow_left hX 6) + have hu : 32 * (inputHeight N ^ 3 + 1) ≤ X ^ 18 := by + calc + _ ≤ 64 * X ^ 12 := by omega + _ ≤ X ^ 6 * X ^ 12 := Nat.mul_le_mul_right _ hc + _ = _ := by rw [← pow_add] + have hB : 2 ≤ B := by + have h := computed_coarse_branching N hN hell + omega + have hBP : B ≤ (N + 2) ^ 4 := by + rw [hBdef] + exact computedCoarseBranching_polynomial N hN hell + have hd : d = intervalTreeDepth B n := by + simp only [hddef, computedCoarseDepth, intervalTreeDepth, hBdef] + have hnodes := coarseCompleteNodes_polynomial N B n hB hn hBP + rw [← hd] at hnodes + have hw := coarseRootWidth_polynomial N B k hBP hk + calc + _ ≤ X ^ 18 * (X ^ 8 * X ^ 6) := Nat.mul_le_mul hu (Nat.mul_le_mul hw hnodes) + _ = _ := by ring + +/-- Total stored bits of all recursive array results from all guesses. +This bound holds for every draw, without a successful-approximation premise. -/ +theorem computedCoarseAllHistories_polynomial : + ∀ᶠ N : ℕ in atTop, ∀ B d : ℕ, ∀ x y : List ℕ, + B = (integerParameters N).B → d = computedCoarseDepth N (coarseEntryWidth x y) → + coarseEntryWidth x y ≤ N → + ∀ (hB : 0 < B) (hq : 0 < inputHeight N ^ 4) (hL : 0 < 64 * inputHeight N) + (draws : CoarseGuessIndex (coarseEntryWidth x y) → CoarseThresholdDraws B d), + (∑ i : CoarseGuessIndex (coarseEntryWidth x y), + coarseRootArrayHistory (coarseGuess (coarseEntryWidth x y) i) + (inputHeight N ^ 4) (64 * inputHeight N) hB hq hL + (coarseTargetFrame (coarseGuess (coarseEntryWidth x y) i) + (coarsePadTo (coarseEntryWidth x y) y)) (coarseEntryTree B d x y) (draws i) 0) ≤ + (N + 2) ^ 37 := by + filter_upwards [computedCoarseRootHistory_bound, eventually_ge_atTop 1, + inputSmallLog_tendsto.eventually (eventually_ge_atTop 200)] with N hroot hN hell + intro B d x y hBdef hddef hsize hB hq hL draws + have hclog : Nat.clog 2 (coarseEntryWidth x y) ≤ inputHeight N := + (Nat.clog_le_iff_le_pow (by decide : 1 < (2 : ℕ))).mpr + (hsize.trans ((Nat.le_add_right N 2).trans (inputHeight_covers_length N))) + have hcount : Nat.clog 2 (coarseEntryWidth x y) + 1 ≤ (N + 2) ^ 5 := by + have hh := computed_height_polynomial N + have hp : 1 ≤ (N + 2) ^ 4 := one_le_pow₀ (by omega) + have hm := Nat.mul_le_mul_right ((N + 2) ^ 4) (show 2 ≤ N + 2 by omega) + nlinarith only [hclog, hh, hp, hm] + calc + _ ≤ ∑ _i : CoarseGuessIndex (coarseEntryWidth x y), (N + 2) ^ 32 := by + apply Finset.sum_le_sum + intro i _ + exact (hroot B d x y hBdef hddef hsize hB hq hL i (draws i)).trans + (computedCoarseRootHistory_polynomial N B d _ (coarseEntryWidth x y) + (by omega) hell hBdef hddef hsize ((coarseGuess_le _ i).trans (by omega))) + _ = (Nat.clog 2 (coarseEntryWidth x y) + 1) * (N + 2) ^ 32 := by + simp only [Finset.sum_const, Finset.card_univ, Fintype.card_fin, smul_eq_mul] + _ ≤ (N + 2) ^ 5 * (N + 2) ^ 32 := Nat.mul_le_mul_right _ hcount + _ = _ := by rw [← pow_add] + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedCoarseHistorySpace.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedCoarseHistorySpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..5565b9aeb2d017553983f5042aa079560dd2821b --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedCoarseHistorySpace.lean @@ -0,0 +1,74 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseIndexedHistory +import OAI.Combinatorics.EditApproximation.Refinement.ComputedFreshWork +import OAI.Combinatorics.EditApproximation.Refinement.ComputedCoarseExecution +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation +open Filter + +def physicalCoarseHistoryEntry {M J B : ℕ} [NeZero B] (source target : List ℕ) (N : ℕ) + (depth : PhysicalEntry M J target.length → ℕ) (draw : PhysicalCoarseDraw source target B depth) + (entry : PhysicalEntry M J target.length) : ℕ := + BinaryFraction.coarseIndexedInitialArrayHistory N B (depth entry) (physicalSource source entry.1) + (substring target entry.2.lo entry.2.hi) (draw entry) + +/-- The complete indexed history of each call fits the reserved capacity. -/ +theorem physicalCoarseHistoryEntry_fits {M J : ℕ} : + ∀ᶠ N : ℕ in atTop, ∀ B : ℕ, ∀ (_hB : NeZero B), + ∀ (source target : List ℕ) (depth : PhysicalEntry M J target.length → ℕ), + B = (integerParameters N).B → + (∀ entry, depth entry = computedCoarseDepth N + (coarseEntryWidth (physicalSource source entry.1) (substring target entry.2.lo entry.2.hi))) → + source.length + target.length ≤ N → + ∀ (draw : PhysicalCoarseDraw source target B depth) (entry : PhysicalEntry M J target.length), + physicalCoarseHistoryEntry source target N depth draw entry ≤ (N + 2) ^ 37 := by + filter_upwards [BinaryFraction.coarseIndexedInitialArrayHistory_polynomial] with N hN + intro B inst source target depth hB hd hsize draw entry + have hx := physicalSource_length_le source entry.1 + have hy : (substring target entry.2.lo entry.2.hi).length ≤ target.length := by + simp only [substring, List.length_drop, List.length_take] + exact (Nat.sub_le _ _).trans (min_le_right _ _) + exact hN B (depth entry) (physicalSource source entry.1) + (substring target entry.2.lo entry.2.hi) hB (hd entry) + (max_le (by omega) (by omega)) inst (draw entry) + +/-- Reserve a complete-history buffer at each actual coarse cache miss. +This conservatively retains those buffers until the memo run finishes. -/ + + +theorem computedFamilyCoarseArrayCapacity_eq (source target : List ℕ) (N : ℕ) + (input : ComputedFamilyInput source target N) : + computedFamilyCoarseArrayCapacity source target N input = + ((computedFamilyResult source target N input).freshKeys.map + (coarseHistoryKeyCost (fun _ => (N + 2) ^ 37))).sum := + computedFamilyKernelWork_eq_fresh_sum source target N input _ + +theorem computedFamilyCoarseArrayCapacity_bound (source target : List ℕ) (N : ℕ) + (input : ComputedFamilyInput source target N) : + computedFamilyCoarseArrayCapacity source target N input ≤ + (N + 2) ^ 37 * (computedFamilyResult source target N input).requests := by + apply computedFamilyKernelWork_le + exact coarseHistoryKeyCost_le _ _ (fun _ => le_rfl) + +theorem computedFamilyCoarseArrayCapacity_polynomial : + ∀ᶠ N : ℕ in atTop, ∀ source target : List ℕ, source.length + target.length ≤ N → + ∀ input : ComputedFamilyInput source target N, + computedFamilyCoarseArrayCapacity source target N input ≤ (N + 2) ^ 39 := by + filter_upwards [computedFamilyResult_requests_near_linear 1 (by norm_num)] with N hr + intro source target hsize input + have hrequests : (computedFamilyResult source target N input).requests ≤ (N + 2) ^ 2 := by + have h := hr source target hsize input + norm_num at h + exact_mod_cast h + calc + _ ≤ (N + 2) ^ 37 * (computedFamilyResult source target N input).requests := + computedFamilyCoarseArrayCapacity_bound source target N input + _ ≤ (N + 2) ^ 37 * (N + 2) ^ 2 := Nat.mul_le_mul_left _ hrequests + _ = _ := by rw [← pow_add] + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedCoarseIndexedWork.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedCoarseIndexedWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..8a8563a86aed68cededb864c6b241a3de116a877 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedCoarseIndexedWork.lean @@ -0,0 +1,137 @@ +import OAI.Combinatorics.EditApproximation.Refinement.ComputedCoarseReadBudget +import OAI.Combinatorics.EditApproximation.Coarse.CoarseIndexedRootBound +import OAI.Combinatorics.EditApproximation.Coarse.CoarseIndexedInitialCost +import OAI.Combinatorics.EditApproximation.Refinement.ComputedCoarseInitialWork + +namespace OAI + +namespace EditApproximation +open Filter +namespace BinaryFraction + +attribute [local irreducible] coarseRootReadExtra coarseInitialReadExtra + coarseIndexedInitialWithWork coarseInitialWithWork + +theorem computedCoarseRootReadExtra_bound : + ∀ᶠ N : ℕ in atTop, ∀ B d : ℕ, ∀ x y : List ℕ, + B = (integerParameters N).B → d = computedCoarseDepth N (coarseEntryWidth x y) → + coarseEntryWidth x y ≤ N → (∀ a ∈ x ++ y, Nat.size a ≤ inputHeight N ^ 3) → + ∀ (hB : 0 < B) (hq : 0 < inputHeight N ^ 4) (hL : 0 < 64 * inputHeight N) + (i : CoarseGuessIndex (coarseEntryWidth x y)) (draws : CoarseThresholdDraws B d), + coarseRootReadExtra (coarseGuess (coarseEntryWidth x y) i) + (inputHeight N ^ 4) (64 * inputHeight N) hB hq hL x y draws ≤ + inputHeight N ^ 32 * (coarseActiveArrayWork (coarseGuess (coarseEntryWidth x y) i) + (initialThresholdQ N) (initialLambda N) (coarseEntryTree B d x y) draws + (coarseGuess (coarseEntryWidth x y) i) + 1) := by + filter_upwards [computedCoarseReadBudget, eventually_ge_atTop 1, + inputSmallLog_tendsto.eventually (eventually_ge_atTop 200)] with N hbudget hN hell + intro B d x y hBdef hddef hsize hsymbol hB hq hL i draws + let H := inputHeight N + have hH : 100 ≤ H := (by decide : 100 ≤ 256).trans + (computed_coarse_height_large N (by omega) hell) + have hc := coarseRootReadExtra_bound (coarseGuess (coarseEntryWidth x y) i) + (H ^ 4) (64 * H) (H ^ 30) hB hq hL (one_le_pow₀ (by omega)) x y draws + (hbudget B d x y hBdef hddef hsize hsymbol i) + have hscale : 64 * H ^ 30 ≤ H ^ 32 := by + calc + _ ≤ H ^ 2 * H ^ 30 := Nat.mul_le_mul_right _ (by nlinarith only [hH]) + _ = _ := by rw [← pow_add] + have hs := Nat.mul_le_mul_right + (coarseActiveArrayWork (coarseGuess (coarseEntryWidth x y) i) (initialThresholdQ N) + (initialLambda N) (coarseEntryTree B d x y) draws (coarseGuess (coarseEntryWidth x y) i) + 1) hscale + simp only [H, initialThresholdQ, initialLambda, Nat.cast_pow, Nat.cast_mul, Nat.cast_ofNat] at hc hs ⊢ + nlinarith only [hc, hs] + +theorem computedCoarseInitialReadExtra_bound : + ∀ᶠ N : ℕ in atTop, ∀ B d : ℕ, ∀ x y : List ℕ, + B = (integerParameters N).B → d = computedCoarseDepth N (coarseEntryWidth x y) → + coarseEntryWidth x y ≤ N → (∀ a ∈ x ++ y, Nat.size a ≤ inputHeight N ^ 3) → + ∀ (hB : 0 < B) (hq : 0 < inputHeight N ^ 4) (hL : 0 < 64 * inputHeight N) + (draws : CoarseGuessIndex (coarseEntryWidth x y) → CoarseThresholdDraws B d), + coarseInitialReadExtra (inputHeight N ^ 4) (64 * inputHeight N) hB hq hL x y draws ≤ + inputHeight N ^ 34 * (coarseInitialArrayWork B d (initialThresholdQ N) (initialLambda N) + x y draws + 1) := by + filter_upwards [computedCoarseRootReadExtra_bound, eventually_ge_atTop 1, + inputSmallLog_tendsto.eventually (eventually_ge_atTop 200)] with N hroot hN hell + intro B d x y hBdef hddef hsize hsymbol hB hq hL draws + let H := inputHeight N + have hH : 100 ≤ H := (by decide : 100 ≤ 256).trans + (computed_coarse_height_large N (by omega) hell) + unfold coarseInitialReadExtra + split_ifs with hlong hequal + · exact Nat.zero_le _ + · exact Nat.zero_le _ + · have hlong' : ¬ 2 * x.length < y.length := + fun h => hlong ((binaryNaturalCompareWithWork_lt _ _).mpr h) + have hequal' : x ≠ y := fun h => hequal ((naturalListEqualWithWork_value x y).mpr h) + have hclog : Nat.clog 2 (coarseEntryWidth x y) ≤ H := + (Nat.clog_le_iff_le_pow (by decide : 1 < (2 : ℕ))).mpr + (hsize.trans ((Nat.le_add_right N 2).trans (inputHeight_covers_length N))) + have hsum : ((List.finRange (Nat.clog 2 (coarseEntryWidth x y) + 1)).map fun i => + coarseRootReadExtra (coarseGuess (coarseEntryWidth x y) i) (inputHeight N ^ 4) + (64 * inputHeight N) hB hq hL x y (draws i)).sum ≤ + H ^ 32 * (coarseInitialArrayWork B d (initialThresholdQ N) (initialLambda N) + x y draws + (Nat.clog 2 (coarseEntryWidth x y) + 1)) := by + rw [← List.ofFn_eq_map, List.sum_ofFn] + calc + _ ≤ ∑ i : CoarseGuessIndex (coarseEntryWidth x y), H ^ 32 * + (coarseActiveArrayWork (coarseGuess (coarseEntryWidth x y) i) + (initialThresholdQ N) (initialLambda N) (coarseEntryTree B d x y) (draws i) + (coarseGuess (coarseEntryWidth x y) i) + 1) := + Finset.sum_le_sum (fun i _ => hroot B d x y hBdef hddef hsize hsymbol hB hq hL i (draws i)) + _ = _ := by + simp only [coarseInitialArrayWork, ite_eq_right hlong', ite_eq_right hequal', + ← Finset.mul_sum, Finset.sum_add_distrib, Finset.sum_const, Finset.card_univ, + Fintype.card_fin, smul_eq_mul, mul_one] + have ha : coarseInitialArrayWork B d (initialThresholdQ N) (initialLambda N) x y draws + + (Nat.clog 2 (coarseEntryWidth x y) + 1) ≤ + H ^ 2 * (coarseInitialArrayWork B d (initialThresholdQ N) (initialLambda N) x y draws + 1) := by + have hs : H + 1 ≤ H ^ 2 := by nlinarith only [hH] + have hm := Nat.mul_le_mul_right + (coarseInitialArrayWork B d (initialThresholdQ N) (initialLambda N) x y draws) + (show 1 ≤ H ^ 2 from one_le_pow₀ (by omega)) + nlinarith only [hs, hm, hclog] + calc + _ ≤ _ := hsum + _ ≤ H ^ 32 * (H ^ 2 * (coarseInitialArrayWork B d (initialThresholdQ N) + (initialLambda N) x y draws + 1)) := Nat.mul_le_mul_left _ ha + _ = _ := by ring + +theorem computedCoarseIndexedInitialWithWork_bound : + ∀ᶠ N : ℕ in atTop, ∀ B d : ℕ, ∀ x y : List ℕ, + B = (integerParameters N).B → d = computedCoarseDepth N (coarseEntryWidth x y) → + coarseEntryWidth x y ≤ N → (∀ a ∈ x ++ y, Nat.size a ≤ inputHeight N ^ 3) → + ∀ (hB : 0 < B) (hq : 0 < inputHeight N ^ 4) (hL : 0 < 64 * inputHeight N) + (draws : CoarseGuessIndex (coarseEntryWidth x y) → CoarseThresholdDraws B d), + (coarseIndexedInitialWithWork (inputHeight N ^ 4) (64 * inputHeight N) N hB hq hL x y draws).2 ≤ + inputHeight N ^ 40 * (coarseInitialArrayWork B d (initialThresholdQ N) (initialLambda N) + x y draws + x.length + 1) := by + filter_upwards [computedCoarseInitialWithWork_bound, computedCoarseInitialReadExtra_bound, + eventually_ge_atTop 1, inputSmallLog_tendsto.eventually (eventually_ge_atTop 200)] + with N hold hextra hN hell + intro B d x y hBdef hddef hsize hsymbol hB hq hL draws + have h1 := hold B d x y hBdef hddef hsize hsymbol hB hq hL draws + have h2 := hextra B d x y hBdef hddef hsize hsymbol hB hq hL draws + have hc := coarseIndexedInitialWithWork_cost_compare (inputHeight N ^ 4) (64 * inputHeight N) + N hB hq hL x y draws + let H := inputHeight N + have hH : 100 ≤ H := (by decide : 100 ≤ 256).trans + (computed_coarse_height_large N (by omega) hell) + have hp : H ^ 34 ≤ H ^ 36 := Nat.pow_le_pow_right (by omega) (by decide) + have hs : 2 * H ^ 36 ≤ H ^ 40 := by + calc + _ ≤ H ^ 4 * H ^ 36 := Nat.mul_le_mul_right _ + ((by omega : 2 ≤ H).trans (Nat.le_pow (by decide))) + _ = _ := by rw [← pow_add] + have hm := Nat.mul_le_mul_right + (coarseInitialArrayWork B d (initialThresholdQ N) (initialLambda N) x y draws + x.length + 1) hs + have he := Nat.mul_le_mul hp + (show coarseInitialArrayWork B d (initialThresholdQ N) (initialLambda N) x y draws + 1 ≤ + coarseInitialArrayWork B d (initialThresholdQ N) (initialLambda N) x y draws + x.length + 1 by omega) + dsimp only [H] at hm he + nlinarith only [h1, h2, hc, hm, he] + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedCoarseInitialWork.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedCoarseInitialWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..0825805ddbc3439ee64da9a2857c34b12d0b730e --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedCoarseInitialWork.lean @@ -0,0 +1,113 @@ +import OAI.Combinatorics.EditApproximation.Refinement.ComputedCoarseCandidateWork +import OAI.Combinatorics.EditApproximation.Coarse.CoarseInitialScalar + +namespace OAI + +namespace EditApproximation +open Filter +namespace BinaryFraction + +/-- All actual initial-estimator branches have the same source-width charging +form. In the long-target branch no target scan or root is executed. -/ +theorem computedCoarseInitialWithWork_bound : + ∀ᶠ N : ℕ in atTop, ∀ B d : ℕ, ∀ x y : List ℕ, + B = (integerParameters N).B → d = computedCoarseDepth N (coarseEntryWidth x y) → + coarseEntryWidth x y ≤ N → + (∀ a ∈ x ++ y, Nat.size a ≤ inputHeight N ^ 3) → + ∀ (hB : 0 < B) (hq : 0 < inputHeight N ^ 4) (hL : 0 < 64 * inputHeight N) + (draws : CoarseGuessIndex (coarseEntryWidth x y) → CoarseThresholdDraws B d), + (coarseInitialWithWork (inputHeight N ^ 4) (64 * inputHeight N) N hB hq hL x y draws).2 ≤ + inputHeight N ^ 36 * (coarseInitialArrayWork B d (initialThresholdQ N) (initialLambda N) + x y draws + x.length + 1) := by + filter_upwards [computedCoarseCandidate_bounds, eventually_ge_atTop 1, + inputSmallLog_tendsto.eventually (eventually_ge_atTop 200)] with N hcandidate hN hell + intro B d x y hBdef hddef hsize hsymbols hB hq hL draws + let H := inputHeight N + change (coarseInitialWithWork (H ^ 4) (64 * H) N hB hq hL x y draws).2 ≤ + H ^ 36 * (coarseInitialArrayWork B d (initialThresholdQ N) (initialLambda N) x y draws + x.length + 1) + have hH : 100 ≤ H := (by decide : 100 ≤ 256).trans + (computed_coarse_height_large N (by omega) hell) + have hlength : Nat.size N ≤ H + 1 := + (Nat.size_le_size (Nat.le_add_right N 2)).trans (inputLength_register_word N) + have hxlen : x.length ≤ N := (le_max_left _ _).trans hsize + have hylen : y.length ≤ N := (le_max_right _ _).trans hsize + have hx : Nat.size x.length ≤ H + 1 := (Nat.size_le_size hxlen).trans hlength + have hy : Nat.size y.length ≤ H + 1 := (Nat.size_le_size hylen).trans hlength + have hlongcost : (binaryNaturalCompareWithWork (2 * x.length) y.length).2 ≤ 8 * H + 17 := by + have hc := binaryNaturalCompareWithWork_cost (2 * x.length) y.length + have hp := natural_product_bit_length 2 x.length + rw [show Nat.size 2 = 2 by decide] at hp + omega + have hpow36 : 100 * H ^ 3 ≤ H ^ 36 := by + have hh := Nat.mul_le_mul_right (H ^ 3) hH + have hp := Nat.pow_le_pow_right (by omega : 0 < H) (by decide : 4 ≤ 36) + nlinarith only [hh, hp] + have hH3 : H ≤ H ^ 3 := Nat.le_pow (by decide) + have hmul := Nat.mul_le_mul_left (H ^ 36) + (show 1 ≤ coarseInitialArrayWork B d (initialThresholdQ N) (initialLambda N) x y draws + + x.length + 1 by omega) + by_cases hlong : 2 * x.length < y.length + · have hb := (binaryNaturalCompareWithWork_lt (2 * x.length) y.length).mpr hlong + change (coarseInitialWithWork _ _ _ _ _ _ _ _ _).2 ≤ _ + simp only [coarseInitialWithWork, hb, ite_true] + nlinarith only [hlongcost, hlength, hy, hH, hpow36, hmul, hH3] + have hb : ¬ (binaryNaturalCompareWithWork (2 * x.length) y.length).1 = Ordering.lt := + fun h => hlong ((binaryNaturalCompareWithWork_lt _ _).mp h) + by_cases he : x = y + · have heq := (naturalListEqualWithWork_value x y).mpr he + have hc := naturalListEqualWithWork_cost x y (H ^ 3) hsymbols + have hsource : y.length = x.length := congrArg List.length he.symm + have hf : (2 * x.length + 1) * (8 * H ^ 3 + 4) + (8 * H + 17) + 3 ≤ + H ^ 36 * (x.length + 1) := by + have ha := Nat.mul_le_mul_right (x.length + 1) hpow36 + have h3 : 1 ≤ H ^ 3 := one_le_pow₀ (by omega) + nlinarith only [ha, hH, h3, hH3] + simp only [coarseInitialWithWork, ite_eq_right hb, heq, ite_true] + rw [hsource] at hc + have hz : coarseInitialArrayWork B d (initialThresholdQ N) (initialLambda N) x y draws = 0 := by + simp only [coarseInitialArrayWork, ite_eq_right hlong, ite_eq_left he] + rw [hz, zero_add] + nlinarith only [hc, hf, hlongcost] + have hclog : Nat.clog 2 (coarseEntryWidth x y) ≤ H := + (Nat.clog_le_iff_le_pow (by decide : 1 < (2 : ℕ))).mpr + (hsize.trans ((Nat.le_add_right N 2).trans (inputHeight_covers_length N))) + have hN4 : Nat.size N ≤ H ^ 4 := by + have hp2 : H + 1 ≤ H ^ 2 := by nlinarith + have hp : H + 1 ≤ H ^ 4 := hp2.trans + (Nat.pow_le_pow_right (by omega : 0 < H) (by decide : 2 ≤ 4)) + exact hlength.trans hp + have hw := coarseInitialWithWork_cost (inputHeight N ^ 4) (64 * inputHeight N) N + (H ^ 4) (H ^ 3) hB hq hL x y draws (by + have hp : H ≤ H ^ 4 := Nat.le_pow (by decide) + omega) hN4 + ((Nat.size_le_size hxlen).trans hN4) ((Nat.size_le_size hylen).trans hN4) hsymbols + (fun i => (hcandidate B d x y hBdef hddef hsize hB hq hL i (draws i)).1) + let f := fun i : CoarseGuessIndex (coarseEntryWidth x y) => + (coarseCandidateWithWork (H ^ 4) (64 * H) hB hq hL x y i (draws i)).2 + have hsum : ((List.finRange (Nat.clog 2 (coarseEntryWidth x y) + 1)).map f).sum = + ∑ i, f i := by + rw [← List.ofFn_eq_map, List.sum_ofFn] + have hr : ((List.finRange (Nat.clog 2 (coarseEntryWidth x y) + 1)).map f).sum ≤ + H ^ 32 * (coarseInitialArrayWork B d (initialThresholdQ N) (initialLambda N) x y draws + + (Nat.clog 2 (coarseEntryWidth x y) + 1)) := by + rw [hsum] + calc + _ ≤ ∑ i : CoarseGuessIndex (coarseEntryWidth x y), H ^ 32 * + (coarseActiveArrayWork (coarseGuess (coarseEntryWidth x y) i) + (initialThresholdQ N) (initialLambda N) (coarseEntryTree B d x y) (draws i) + (coarseGuess (coarseEntryWidth x y) i) + 1) := + Finset.sum_le_sum (fun i _ => (hcandidate B d x y hBdef hddef hsize hB hq hL i (draws i)).2) + _ = _ := by + simp only [coarseInitialArrayWork, ite_eq_right hlong, ite_eq_right he, + ← Finset.mul_sum, Finset.sum_add_distrib, Finset.sum_const, Finset.card_univ, + Fintype.card_fin, smul_eq_mul, mul_one] + have hscan : x.length + y.length + 1 ≤ 3 * x.length + 1 := by omega + apply coarseInitial_aggregate_scalar H x.length _ (Nat.clog 2 (coarseEntryWidth x y) + 1) + _ _ hH (by omega) hr + exact hw.trans (Nat.add_le_add_right (Nat.add_le_add_left + (Nat.mul_le_mul_right (8 * H ^ 3 + 4) hscan) _) _) + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedCoarseInputWork.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedCoarseInputWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..0d5da483ab780c08d16fa23b440b45f55ad8e517 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedCoarseInputWork.lean @@ -0,0 +1,76 @@ +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalCoarseInputWork +import OAI.Combinatorics.EditApproximation.Refinement.ComputedExecutionCosts + +namespace OAI + +namespace EditApproximation +open Filter MeasureTheory + +noncomputable def computedFamilyCoarseInputWork (source target : List ℕ) (N : ℕ) + (input : ComputedFamilyInput source target N) : ℝ := + physicalFamilyCoarseInputWork source target N (integerParameters N).P (inputHeight N) + (integerParameters N).T (integerParameters N).S (computedSeedPassCount N) (inputHeight N ^ 2) + (scheduledSeedFactor N) (scheduledSeedMultiplier N) + (rationalParameters (inputSmallLog N)).tau (rationalParameters (inputSmallLog N)).eta + (rationalParameters (inputSmallLog N)).kappa (rationalParameters (inputSmallLog N)).delta + (clampedSeedNat input.1) input.2 (16384 * inputHeight N + 5) + (computedFamilyMemoCode source target N (inputHeight N ^ 2)) + (computedFinalRoot source target N) + +theorem computedFamilyCoarseInputWork_le (source target : List ℕ) (N : ℕ) + (hN : 0 < N) (hell : 2 ^ 1000 ≤ inputSmallLog N) + (hsize : source.length + target.length ≤ N) + (hB : Nat.size (localOnlineMassBound (integerParameters N).M (integerParameters N).P + (inputHeight N)) ≤ inputHeight N) + (input : ComputedFamilyInput source target N) : + computedFamilyCoarseInputWork source target N input ≤ computedWidthEnvelope N := by + have hc := physicalFamilyCoarseInputWork_le source target N (integerParameters N).P (inputHeight N) + (integerParameters N).T (integerParameters N).S (computedSeedPassCount N) (inputHeight N ^ 2) + (scheduledSeedFactor N) (scheduledSeedMultiplier N) + (rationalParameters (inputSmallLog N)).tau (rationalParameters (inputSmallLog N)).eta + (rationalParameters (inputSmallLog N)).kappa (rationalParameters (inputSmallLog N)).delta + (clampedSeedNat input.1) (computedParameterP_pos N) input.2 (16384 * inputHeight N + 5) + (computedFamilyMemoCode source target N (inputHeight N ^ 2)) + (computedFamilyMemoCode_injective source target N (inputHeight N ^ 2) hN + (two_hundred_le_two_pow_thousand.trans hell)) + (computedFamilyMemoCode_fits source target N (inputHeight N ^ 2) hN hell hsize le_rfl hB) + (computedFinalRoot source target N) rfl + have hh : 105 ≤ inputHeight N := + (by omega : 105 ≤ inputSmallLog N).trans (computed_smallLog_le_height N) + exact hc.trans (computedFamilyTree_width_le source target N hN + (two_hundred_le_two_pow_thousand.trans hell) hh hsize input) + +theorem computedFamilyCoarseInputWork_near_linear (epsilon : ℝ) (hepsilon : 0 < epsilon) : + ∀ᶠ N in atTop, ∀ source target : List ℕ, source.length + target.length ≤ N → + ∀ input : ComputedFamilyInput source target N, + computedFamilyCoarseInputWork source target N input ≤ (N + 2 : ℝ) ^ (1 + epsilon) := by + filter_upwards [computedWidthEnvelope_weighted_near_linear 0 epsilon hepsilon, + eventually_ge_atTop 1, inputSmallLog_tendsto.eventually (eventually_ge_atTop (2 ^ 1000)), + computed_localOnlineMassBound_word] with N hw hN hell hB + intro source target hsize input + exact (computedFamilyCoarseInputWork_le source target N (by omega) hell hsize hB input).trans (by simpa only [pow_zero, mul_one] using hw) + +noncomputable def computedExecutionCoarseInputWork (source target : List ℕ) (N : ℕ) + (execution : ComputedExecutionOutcome source target N) : ℝ := + computedFamilyCoarseInputWork source target N (computedExecutionAccepted source target N execution) + +theorem computedExecutionCoarseInputWork_integrable (source target : List ℕ) (N : ℕ) : + Integrable (computedExecutionCoarseInputWork source target N) (computedExecutionLaw source target N) := + computedExecutionAcceptedWork_integrable source target N (computedFamilyCoarseInputWork source target N) + +theorem computedExecutionCoarseInputWork_expected_near_linear (epsilon : ℝ) (hepsilon : 0 < epsilon) : + ∀ᶠ N in atTop, ∀ source target : List ℕ, source.length + target.length ≤ N → + (∫ execution, computedExecutionCoarseInputWork source target N execution + ∂computedExecutionLaw source target N) ≤ (N + 2 : ℝ) ^ (1 + epsilon) := by + filter_upwards [computedFamilyCoarseInputWork_near_linear epsilon hepsilon] with N hN + intro source target hsize + calc + _ ≤ ∫ _ : ComputedExecutionOutcome source target N, (N + 2 : ℝ) ^ (1 + epsilon) + ∂computedExecutionLaw source target N := + integral_mono (computedExecutionCoarseInputWork_integrable source target N) (integrable_const _) + (fun execution => hN source target hsize _) + _ = _ := by simp + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedCoarsePolynomial.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedCoarsePolynomial.lean new file mode 100644 index 0000000000000000000000000000000000000000..c42f0631bec2e653f10ec351efda184a4aedd45e --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedCoarsePolynomial.lean @@ -0,0 +1,100 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseCompletePolynomial +import OAI.Combinatorics.EditApproximation.Refinement.ComputedCoarseIndexedWork +import OAI.Combinatorics.EditApproximation.Refinement.ComputedRetainedValues + +namespace OAI + +namespace EditApproximation +namespace BinaryFraction +open Filter + +theorem computedCoarseBranching_polynomial (N : ℕ) (hN : 0 < N) + (hell : 200 ≤ inputSmallLog N) : (integerParameters N).B ≤ (N + 2) ^ 4 := by + have h4 : 4 ≤ (N + 2) ^ 2 := by nlinarith only [Nat.zero_le N] + calc + _ ≤ 2 ^ inputHeight N := computed_coarse_B_upper N hN hell + _ ≤ 4 * (N + 2) ^ 2 := two_pow_inputHeight_le N + _ ≤ (N + 2) ^ 2 * (N + 2) ^ 2 := Nat.mul_le_mul_right _ h4 + _ = _ := by rw [← pow_add] + +/-- A deterministic bound holds for every pruning outcome, including the +outcomes outside the accuracy event. -/ +theorem computedCoarseInitialArrayWork_polynomial (N B d : ℕ) (x y : List ℕ) + (hN : 0 < N) (hell : 200 ≤ inputSmallLog N) + (hBdef : B = (integerParameters N).B) + (hddef : d = computedCoarseDepth N (coarseEntryWidth x y)) + (hsize : coarseEntryWidth x y ≤ N) + (draws : CoarseGuessIndex (coarseEntryWidth x y) → CoarseThresholdDraws B d) : + coarseInitialArrayWork B d (initialThresholdQ N) (initialLambda N) x y draws ≤ + (N + 2) ^ 19 := by + have hB : 2 ≤ B := by + have h := computed_coarse_branching N hN hell + omega + have hBP : B ≤ (N + 2) ^ 4 := by + rw [hBdef] + exact computedCoarseBranching_polynomial N hN hell + have hd : d = intervalTreeDepth B (coarseEntryWidth x y) := by + simp only [hddef, computedCoarseDepth, intervalTreeDepth, hBdef] + have heach (i : CoarseGuessIndex (coarseEntryWidth x y)) : + coarseActiveArrayWork (coarseGuess (coarseEntryWidth x y) i) + (initialThresholdQ N) (initialLambda N) (coarseEntryTree B d x y) + (draws i) (coarseGuess (coarseEntryWidth x y) i) ≤ (N + 2) ^ 14 := by + have hk : coarseGuess (coarseEntryWidth x y) i ≤ 2 * (N + 2) := + (coarseGuess_le _ i).trans (by omega) + rcases hd with rfl + exact coarseActiveArrayWork_polynomial N B (coarseEntryWidth x y) _ _ _ _ + hB hsize hBP hk _ _ + have hclog : Nat.clog 2 (coarseEntryWidth x y) ≤ inputHeight N := + (Nat.clog_le_iff_le_pow (by decide : 1 < (2 : ℕ))).mpr + (hsize.trans ((Nat.le_add_right N 2).trans (inputHeight_covers_length N))) + have hcount : Nat.clog 2 (coarseEntryWidth x y) + 1 ≤ (N + 2) ^ 5 := by + have hh := computed_height_polynomial N + have hp : 1 ≤ (N + 2) ^ 4 := one_le_pow₀ (by omega) + have hm := Nat.mul_le_mul_right ((N + 2) ^ 4) (show 2 ≤ N + 2 by omega) + nlinarith only [hclog, hh, hp, hm] + unfold coarseInitialArrayWork + split_ifs + · exact Nat.zero_le _ + · exact Nat.zero_le _ + · calc + _ ≤ ∑ _i : CoarseGuessIndex (coarseEntryWidth x y), (N + 2) ^ 14 := + Finset.sum_le_sum (fun i _ => heach i) + _ = (Nat.clog 2 (coarseEntryWidth x y) + 1) * (N + 2) ^ 14 := by + simp only [Finset.sum_const, Finset.card_univ, Fintype.card_fin, smul_eq_mul] + _ ≤ (N + 2) ^ 5 * (N + 2) ^ 14 := Nat.mul_le_mul_right _ hcount + _ = _ := by rw [← pow_add] + +/-- The counted indexed implementation has polynomial work on every draw. -/ +theorem computedCoarseIndexedInitialWithWork_polynomial : + ∀ᶠ N : ℕ in atTop, ∀ B d : ℕ, ∀ x y : List ℕ, + B = (integerParameters N).B → d = computedCoarseDepth N (coarseEntryWidth x y) → + coarseEntryWidth x y ≤ N → (∀ a ∈ x ++ y, Nat.size a ≤ inputHeight N ^ 3) → + ∀ (hB : 0 < B) (hq : 0 < inputHeight N ^ 4) (hL : 0 < 64 * inputHeight N) + (draws : CoarseGuessIndex (coarseEntryWidth x y) → CoarseThresholdDraws B d), + (coarseIndexedInitialWithWork (inputHeight N ^ 4) (64 * inputHeight N) N + hB hq hL x y draws).2 ≤ (N + 2) ^ 180 := by + filter_upwards [computedCoarseIndexedInitialWithWork_bound, eventually_ge_atTop 1, + inputSmallLog_tendsto.eventually (eventually_ge_atTop 200)] with N hwork hN hell + intro B d x y hBdef hddef hsize hsymbol hB hq hL draws + have hw := hwork B d x y hBdef hddef hsize hsymbol hB hq hL draws + have ha := computedCoarseInitialArrayWork_polynomial N B d x y (by omega) hell + hBdef hddef hsize draws + have hx : x.length + 1 ≤ N + 2 := by + have h := (le_max_left x.length y.length).trans hsize + omega + have hp : N + 2 ≤ (N + 2) ^ 19 := Nat.le_pow (by decide) + have hm := Nat.mul_le_mul_right ((N + 2) ^ 19) (show 2 ≤ N + 2 by omega) + have hsum : coarseInitialArrayWork B d (initialThresholdQ N) (initialLambda N) + x y draws + x.length + 1 ≤ (N + 2) ^ 20 := by + nlinarith only [ha, hx, hp, hm] + have hh := Nat.pow_le_pow_left (computed_height_polynomial N) 40 + rw [← pow_mul] at hh + calc + _ ≤ _ := hw + _ ≤ (N + 2) ^ 160 * (N + 2) ^ 20 := Nat.mul_le_mul hh hsum + _ = _ := by rw [← pow_add] + +end BinaryFraction +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedCoarsePreparation.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedCoarsePreparation.lean new file mode 100644 index 0000000000000000000000000000000000000000..db4e336b26a73ee6e2bc8205cc2a009d332dbbf5 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedCoarsePreparation.lean @@ -0,0 +1,71 @@ +import OAI.Combinatorics.EditApproximation.Refinement.ComputedParameterRegisters +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalCoarsePreparation +import OAI.Combinatorics.EditApproximation.Refinement.ComputedCoarseInputWork +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation +open Filter MeasureTheory + + + + + +theorem computedExecutionCoarsePreparationWork_integrable (source target : List ℕ) (N : ℕ) : + Integrable (computedExecutionCoarsePreparationWork source target N) (computedExecutionLaw source target N) := + computedExecutionAcceptedWork_integrable source target N (computedFamilyCoarsePreparationWork source target N) + +theorem computedExecutionCoarsePreparationWork_bound : + ∀ᶠ N : ℕ in atTop, ∀ source target : List ℕ, source.length + target.length ≤ N → + (∀ a ∈ source ++ target, Nat.size a ≤ inputHeight N ^ 3) → + ∀ execution : ComputedExecutionOutcome source target N, + computedExecutionCoarsePreparationWork source target N execution ≤ + (inputHeight N : ℝ) ^ 6 * computedExecutionCoarseInputWork source target N execution := by + filter_upwards [eventually_ge_atTop 1, + inputSmallLog_tendsto.eventually (eventually_ge_atTop 200)] with N hN hell + intro source target hsize hsymbol execution + have hH : 100 ≤ inputHeight N := (by decide : 100 ≤ 256).trans + (computed_coarse_height_large N (by omega) hell) + have hl : Nat.size N ≤ inputHeight N + 1 := + (Nat.size_le_size (Nat.le_add_right N 2)).trans (inputLength_register_word N) + have hp : inputHeight N + 1 ≤ inputHeight N ^ 3 := by + have h : inputHeight N ≤ inputHeight N ^ 2 := Nat.le_pow (by decide) + have hh := Nat.mul_le_mul_right (inputHeight N ^ 2) (show 2 ≤ inputHeight N by omega) + nlinarith only [h, hh, hH] + exact physicalFamilyCoarsePreparationWork_bound source target N (integerParameters N).P (inputHeight N) + (integerParameters N).T (integerParameters N).S (computedSeedPassCount N) (inputHeight N ^ 2) + (scheduledSeedFactor N) (scheduledSeedMultiplier N) + (rationalParameters (inputSmallLog N)).tau (rationalParameters (inputSmallLog N)).eta + (rationalParameters (inputSmallLog N)).kappa (rationalParameters (inputSmallLog N)).delta + (clampedSeedNat (computedExecutionAccepted source target N execution).1) + (computedExecutionAccepted source target N execution).2 (16384 * inputHeight N + 5) + (computedFamilyMemoCode source target N (inputHeight N ^ 2)) (computedFinalRoot source target N) + hH ((Nat.size_le_size (by omega : source.length ≤ N)).trans (hl.trans hp)) + ((Nat.size_le_size (by omega : target.length ≤ N)).trans (hl.trans hp)) hsymbol + +theorem computedExecutionCoarsePreparationWork_expected_near_linear (epsilon : ℝ) (hepsilon : 0 < epsilon) : + ∀ᶠ N in atTop, ∀ source target : List ℕ, source.length + target.length ≤ N → + (∀ a ∈ source ++ target, Nat.size a ≤ inputHeight N ^ 3) → + (∫ execution, computedExecutionCoarsePreparationWork source target N execution + ∂computedExecutionLaw source target N) ≤ (N + 2 : ℝ) ^ (1 + epsilon) := by + have he : 0 < epsilon / 2 := half_pos hepsilon + filter_upwards [computedExecutionCoarsePreparationWork_bound, + computedExecutionCoarseInputWork_expected_near_linear (epsilon / 2) he, + fixed_height_power_subpolynomial 6 (epsilon / 2) he] with N hb hi hp + intro source target hsize hsymbol + have hm := integral_mono (computedExecutionCoarsePreparationWork_integrable source target N) + ((computedExecutionCoarseInputWork_integrable source target N).const_mul ((inputHeight N : ℝ) ^ 6)) + (hb source target hsize hsymbol) + rw [integral_const_mul] at hm + calc + _ ≤ (inputHeight N : ℝ) ^ 6 * (N + 2 : ℝ) ^ (1 + epsilon / 2) := + hm.trans (mul_le_mul_of_nonneg_left (hi source target hsize) (by positivity)) + _ ≤ (N + 2 : ℝ) ^ (epsilon / 2) * (N + 2 : ℝ) ^ (1 + epsilon / 2) := + mul_le_mul_of_nonneg_right hp (by positivity) + _ = _ := by rw [← Real.rpow_add (by positivity)]; congr 1; ring + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedCoarseReadBudget.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedCoarseReadBudget.lean new file mode 100644 index 0000000000000000000000000000000000000000..ffceebdcd0821239e62f2334fe85a172f07591d1 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedCoarseReadBudget.lean @@ -0,0 +1,64 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseReadBudget +import OAI.Combinatorics.EditApproximation.Refinement.ComputedCoarseCandidateWork + +namespace OAI + +namespace EditApproximation +open Filter + +/-- Every descriptor, stored-symbol comparison and frame operation used by a +computed coarse root has a uniform fixed-power bit budget. -/ +theorem computedCoarseReadBudget : + ∀ᶠ N : ℕ in atTop, ∀ B d : ℕ, ∀ x y : List ℕ, + B = (integerParameters N).B → d = computedCoarseDepth N (coarseEntryWidth x y) → + coarseEntryWidth x y ≤ N → (∀ a ∈ x ++ y, Nat.size a ≤ inputHeight N ^ 3) → + ∀ i : CoarseGuessIndex (coarseEntryWidth x y), + CoarseReadBudget B d (coarseGuess (coarseEntryWidth x y) i) (coarseEntryWidth x y) + x y (inputHeight N ^ 30) := by + filter_upwards [eventually_ge_atTop 1, + inputSmallLog_tendsto.eventually (eventually_ge_atTop 200)] with N hN hell + intro B d x y hBdef hddef hsize hsymbol i + let H := inputHeight N + let k := coarseGuess (coarseEntryWidth x y) i + have hH : 256 ≤ H := computed_coarse_height_large N (by omega) hell + have hdepth : d ≤ H := hddef.symm ▸ (computed_coarse_depth N _ (by omega) hsize hell).2 + have hBpos : 1 ≤ B := by + rw [hBdef] + change 1 ≤ inputHeight N ^ coarseExponent (inputSmallLog N) + exact one_le_pow₀ (Nat.succ_le_of_lt (Nat.two_pow_pos _)) + have hb : Nat.size B ≤ 2 * H := by + have h := Nat.size_le_size (computed_coarse_B_upper N (by omega) hell) + rw [← hBdef] at h + simp only [Nat.size_pow] at h + exact h.trans (by dsimp only [H]; omega) + have hcube : 100 * H ^ 2 ≤ H ^ 3 := by + have h := Nat.mul_le_mul_right (H ^ 2) (show 100 ≤ H by omega) + nlinarith only [h] + have hp : Nat.size (B ^ d) ≤ H ^ 3 := by + have h := natural_power_bit_length B d + have hh := Nat.mul_le_mul hdepth hb + have hsq := Nat.mul_le_mul_right (H ^ 2) (show 3 ≤ H by omega) + nlinarith only [h, hh, hsq, hH] + have hn : Nat.size (coarseEntryWidth x y) ≤ H ^ 3 := by + have h := (Nat.size_le_size hsize).trans + ((Nat.size_le_size (Nat.le_add_right N 2)).trans (inputLength_register_word N)) + change Nat.size (coarseEntryWidth x y) ≤ H + 1 at h + have hpow : H ≤ H ^ 3 := Nat.le_pow (by decide) + have hsq := Nat.mul_le_mul_right (H ^ 2) (show 3 ≤ H by omega) + nlinarith only [h, hpow, hsq, hH, hcube] + have hk : Nat.size (2 * k + 1) ≤ H ^ 3 := by + have hkn : k ≤ 2 * (N + 2) := (BinaryFraction.coarseGuess_le _ i).trans (by omega) + have hks := (Nat.size_le_size hkn).trans (natural_product_bit_length 2 (N + 2)) + have hn' := inputLength_register_word N + change Nat.size (N + 2) ≤ H + 1 at hn' + have hs := natural_sum_bit_length (2 * k) 1 + have hm := natural_product_bit_length 2 k + norm_num only [show Nat.size 2 = 2 by decide, show Nat.size 1 = 1 by decide] at hks hs hm + have hsq := Nat.mul_le_mul_right (H ^ 2) (show 3 ≤ H by omega) + nlinarith only [hks, hn', hs, hm, hsq, hH, hcube] + exact coarseReadBudget_height B d k (coarseEntryWidth x y) H x y (by omega) hdepth hBpos + (by have hpow : H ≤ H ^ 2 := Nat.le_pow (by decide); nlinarith only [hb, hpow, hH, hcube]) hp hn hk hsymbol + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedCoarseSamplingWork.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedCoarseSamplingWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..f95944558cc740bd8e1fc19c698ea037308a5fd4 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedCoarseSamplingWork.lean @@ -0,0 +1,108 @@ +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalCoarseSamplingWork +import OAI.Combinatorics.EditApproximation.Refinement.ComputedCoarseBitWork +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation +open MeasureTheory Filter + +section Symbolic +variable {M J R B : ℕ} [NeZero M] [NeZero R] [NeZero B] + (source target : List ℕ) (N : ℕ) + (depth : PhysicalEntry M J target.length → ℕ) + (encode : Sum (PhysicalFamilyScalarKey (M := M) (J := J) (R := R) + target N (integerParameters N).P (inputSmallLog N) (40 * smallLogExponent N) + (inputHeight N) (inputSmallLog N ^ 80) (computedSeedPassCount N) (inputHeight N ^ 2)) + (ChargedPhysicalRequest M J target.length (computedSeedPassCount N + 1) + (inputHeight N ^ 2) (integerParameters N).T (integerParameters N).S) → ℕ) + + + +theorem symbolicComputedExecutionCoarseSamplingWork_integrable : + Integrable (symbolicComputedExecutionCoarseSamplingWork source target N depth encode) + (physicalCoarseExecutionLaw (R := R) source target N (integerParameters N).P + (inputHeight N) B depth) := by + let μ := coarseFullSeedMeasure B depth + (fun entry => physicalSource source entry.1) + (fun entry => substring target entry.2.lo entry.2.hi) + let range := physicalFamilyRange (M := M) (J := J) (R := R) + target N (integerParameters N).P (inputSmallLog N) (40 * smallLogExponent N) + (inputHeight N) (inputSmallLog N ^ 80) (computedSeedPassCount N) (inputHeight N ^ 2) + let f := fun outcome : PhysicalCoarseDraw source target B depth × (∀ key, Fin (range key)) => + symbolicComputedExecutionCoarseSamplingWork source target N depth encode + (outcome.1, (fun _ => 0, outcome.2)) + have hf : Integrable f ((μ.prod (rejectionRuntimeArrayLaw range)).map + (rejectionProductAccepted range)) := by + rw [rejectionProductAccepted_law] + exact Integrable.of_finite + exact hf.comp_measurable (rejectionProductAccepted_measurable range) +omit [NeZero B] in +theorem symbolicComputedExecutionCoarseSamplingWork_bound + (execution : PhysicalCoarseExecution (R := R) source target N + (integerParameters N).P (inputHeight N) B depth) : + symbolicComputedExecutionCoarseSamplingWork source target N depth encode execution ≤ + (Nat.size B : ℝ) * symbolicComputedExecutionCoarseWork source target N depth encode execution := by + exact physicalFamilyCoarseSamplingWork_bound source target N (integerParameters N).P + (inputHeight N) (integerParameters N).T (integerParameters N).S (computedSeedPassCount N) + (inputHeight N ^ 2) (scheduledSeedFactor N) (scheduledSeedMultiplier N) + (rationalParameters (inputSmallLog N)).tau (rationalParameters (inputSmallLog N)).eta + (rationalParameters (inputSmallLog N)).kappa (rationalParameters (inputSmallLog N)).delta + execution.2.2 depth (16384 * inputHeight N + 5) encode + (localFinalRootRequest target N (integerParameters N).T (integerParameters N).S + (inputHeight N) (Nat.two_pow_pos _) (finalTargetState target.length)) execution.1 + +end Symbolic + + + +theorem computedExecutionCoarseSamplingWork_integrable (source target : List ℕ) (N : ℕ) : + Integrable (computedExecutionCoarseSamplingWork source target N) (computedExecutionLaw source target N) := + symbolicComputedExecutionCoarseSamplingWork_integrable source target N + (computedPhysicalCoarseDepth source target N) (computedFamilyMemoCode source target N (inputHeight N ^ 2)) + +theorem computedExecutionCoarseSamplingWork_bound (source target : List ℕ) (N : ℕ) + (execution : ComputedExecutionOutcome source target N) : + computedExecutionCoarseSamplingWork source target N execution ≤ + (Nat.size (integerParameters N).B : ℝ) * computedExecutionCoarseWork source target N execution := + symbolicComputedExecutionCoarseSamplingWork_bound source target N + (computedPhysicalCoarseDepth source target N) (computedFamilyMemoCode source target N (inputHeight N ^ 2)) execution + +theorem computedExecutionCoarseSamplingWork_expected_near_linear (epsilon : ℝ) (hepsilon : 0 < epsilon) : + ∀ᶠ N in atTop, ∀ source target : List ℕ, source.length + target.length ≤ N → + (∫ execution, computedExecutionCoarseSamplingWork source target N execution + ∂computedExecutionLaw source target N) ≤ (N + 2 : ℝ) ^ (1 + epsilon) := by + have he : 0 < epsilon / 2 := half_pos hepsilon + filter_upwards [computedExecutionCoarseWork_expected_near_linear (epsilon / 2) he, + fixed_height_power_subpolynomial 2 (epsilon / 2) he, + eventually_ge_atTop 1, inputSmallLog_tendsto.eventually (eventually_ge_atTop 200)] with N hc hp hN hell + intro source target hsize + have hB := Nat.size_le_size (computed_coarse_B_upper N (by omega) hell) + rw [Nat.size_pow] at hB + have hH := computed_coarse_height_large N (by omega) hell + have hsizeB : Nat.size (integerParameters N).B ≤ inputHeight N ^ 2 := by nlinarith only [hB, hH] + have hb : (∫ execution, computedExecutionCoarseSamplingWork source target N execution + ∂computedExecutionLaw source target N) ≤ + (Nat.size (integerParameters N).B : ℝ) * + (∫ execution, computedExecutionCoarseWork source target N execution ∂computedExecutionLaw source target N) := by + calc + _ ≤ ∫ execution, (Nat.size (integerParameters N).B : ℝ) * + computedExecutionCoarseWork source target N execution ∂computedExecutionLaw source target N := + integral_mono (computedExecutionCoarseSamplingWork_integrable source target N) + ((computedExecutionCoarseWork_integrable source target N).const_mul _) + (computedExecutionCoarseSamplingWork_bound source target N) + _ = _ := by rw [integral_const_mul] + have hsizeBReal : (Nat.size (integerParameters N).B : ℝ) ≤ (inputHeight N : ℝ) ^ 2 := by exact_mod_cast hsizeB + calc + _ ≤ (Nat.size (integerParameters N).B : ℝ) * (N + 2 : ℝ) ^ (1 + epsilon / 2) := + hb.trans (mul_le_mul_of_nonneg_left (hc source target hsize) (Nat.cast_nonneg _)) + _ ≤ (inputHeight N : ℝ) ^ 2 * (N + 2 : ℝ) ^ (1 + epsilon / 2) := + mul_le_mul_of_nonneg_right hsizeBReal (by positivity) + _ ≤ (N + 2 : ℝ) ^ (epsilon / 2) * (N + 2 : ℝ) ^ (1 + epsilon / 2) := + mul_le_mul_of_nonneg_right hp (by positivity) + _ = _ := by rw [← Real.rpow_add (by positivity)]; congr 1; ring + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedCoarseScratchSpace.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedCoarseScratchSpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..ec7f4812e9be3cd325396faa18bcccd53da57048 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedCoarseScratchSpace.lean @@ -0,0 +1,83 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseInitialAllocation +import OAI.Combinatorics.EditApproximation.Refinement.ComputedCoarseHistorySpace +import OAI.Combinatorics.EditApproximation.Refinement.ComputedCoarseBitWork +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation +open Filter + +def physicalCoarseAllocationEntry {M J B : ℕ} [NeZero B] (source target : List ℕ) (N : ℕ) + (depth : PhysicalEntry M J target.length → ℕ) (draw : PhysicalCoarseDraw source target B depth) + (entry : PhysicalEntry M J target.length) : ℕ := + BinaryFraction.coarseIndexedInitialAllocation (inputHeight N ^ 4) (64 * inputHeight N) N + (Nat.pos_of_neZero B) (pow_pos (Nat.two_pow_pos _) _) + (Nat.mul_pos (by decide) (Nat.two_pow_pos _)) + (physicalSource source entry.1) (substring target entry.2.lo entry.2.hi) (draw entry) + +theorem physicalCoarseAllocationEntry_fits {M J : ℕ} : + ∀ᶠ N : ℕ in atTop, ∀ B : ℕ, ∀ (_hB : NeZero B), + ∀ (source target : List ℕ) (depth : PhysicalEntry M J target.length → ℕ), + B = (integerParameters N).B → + (∀ entry, depth entry = computedCoarseDepth N + (coarseEntryWidth (physicalSource source entry.1) (substring target entry.2.lo entry.2.hi))) → + source.length + target.length ≤ N → + (∀ a ∈ source ++ target, Nat.size a ≤ inputHeight N ^ 3) → + ∀ (draw : PhysicalCoarseDraw source target B depth) (entry : PhysicalEntry M J target.length), + physicalCoarseAllocationEntry source target N depth draw entry ≤ (N + 2) ^ 181 := by + filter_upwards [BinaryFraction.computedCoarseIndexedInitialAllocation_polynomial] with N hN + intro B inst source target depth hB hd hsize hsymbols draw entry + have hx := physicalSource_length_le source entry.1 + have hy : (substring target entry.2.lo entry.2.hi).length ≤ target.length := by + simp only [substring, List.length_drop, List.length_take] + exact (Nat.sub_le _ _).trans (min_le_right _ _) + have hs : ∀ a ∈ physicalSource source entry.1 ++ substring target entry.2.lo entry.2.hi, + Nat.size a ≤ inputHeight N ^ 3 := by + intro a ha + rcases List.mem_append.mp ha with ha | ha + · exact hsymbols a (List.mem_append_left _ (physicalSource_mem source entry.1 a ha)) + · exact hsymbols a (List.mem_append_right _ (List.mem_of_mem_take (List.mem_of_mem_drop ha))) + exact hN B (depth entry) (physicalSource source entry.1) + (substring target entry.2.lo entry.2.hi) hB (hd entry) + (max_le (by omega) (by omega)) hs (Nat.pos_of_neZero B) + (pow_pos (Nat.two_pow_pos _) _) (Nat.mul_pos (by decide) (Nat.two_pow_pos _)) (draw entry) + +/-- Reserve every fresh cell allocated by every coarse cache miss until +termination. This deliberately bounds more than simultaneously live scratch. -/ + + +theorem computedFamilyCoarseScratchCapacity_eq (source target : List ℕ) (N : ℕ) + (input : ComputedFamilyInput source target N) : + computedFamilyCoarseScratchCapacity source target N input = + ((computedFamilyResult source target N input).freshKeys.map + (coarseHistoryKeyCost (fun _ => (N + 2) ^ 181))).sum := + computedFamilyKernelWork_eq_fresh_sum source target N input _ + +theorem computedFamilyCoarseScratchCapacity_bound (source target : List ℕ) (N : ℕ) + (input : ComputedFamilyInput source target N) : + computedFamilyCoarseScratchCapacity source target N input ≤ + (N + 2) ^ 181 * (computedFamilyResult source target N input).requests := by + apply computedFamilyKernelWork_le + exact coarseHistoryKeyCost_le _ _ (fun _ => le_rfl) + +theorem computedFamilyCoarseScratchCapacity_polynomial : + ∀ᶠ N : ℕ in atTop, ∀ source target : List ℕ, source.length + target.length ≤ N → + ∀ input : ComputedFamilyInput source target N, + computedFamilyCoarseScratchCapacity source target N input ≤ (N + 2) ^ 183 := by + filter_upwards [computedFamilyResult_requests_near_linear 1 (by norm_num)] with N hr + intro source target hsize input + have hrequests : (computedFamilyResult source target N input).requests ≤ (N + 2) ^ 2 := by + have h := hr source target hsize input + norm_num at h + exact_mod_cast h + calc + _ ≤ (N + 2) ^ 181 * (computedFamilyResult source target N input).requests := + computedFamilyCoarseScratchCapacity_bound source target N input + _ ≤ (N + 2) ^ 181 * (N + 2) ^ 2 := Nat.mul_le_mul_left _ hrequests + _ = _ := by rw [← pow_add] + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedCoarseWidthCost.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedCoarseWidthCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..31616dc98ac379b001d2ba5933557d514817b1fd --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedCoarseWidthCost.lean @@ -0,0 +1,109 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseWidthWork +import OAI.Combinatorics.EditApproximation.Geometry.DependencyPathEnvelope + +namespace OAI + +/-! The actual coarse array counter has a common source-width overhead. +Its exponent is sublinear in the computed logarithmic height. -/ + +namespace EditApproximation + +open MeasureTheory + +def computedCoarseWidthOverhead (N : ℕ) : ℕ := + 6 * (integerParameters N).B * (Nat.clog 2 N + 1) * (computedMaxCoarseDepth N + 1) * + inputHeight N ^ (8 * computedMaxCoarseDepth N) + +theorem coarse_width_overhead_le_power (H D p L : ℕ) (hH : 2 ≤ H) (hL : L ≤ H) : + 6 * H ^ p * (L + 1) * (D + 1) * H ^ (8 * D) ≤ H ^ (10 * (D + p + 1)) := by + have hsix : 6 ≤ H ^ 3 := by + have hpow := Nat.pow_le_pow_left hH 3 + norm_num at hpow + omega + have hlogtwo : L + 1 ≤ H ^ 2 := by nlinarith + have hdepth : D + 1 ≤ H ^ D := + (Nat.succ_le_of_lt (Nat.lt_pow_self (by decide : 1 < (2 : ℕ)))).trans + (Nat.pow_le_pow_left hH D) + calc + _ ≤ H ^ 3 * H ^ p * H ^ 2 * H ^ D * H ^ (8 * D) := by gcongr + _ = H ^ (p + 9 * D + 5) := by + simp only [← pow_add] + congr 1 + omega + _ ≤ _ := Nat.pow_le_pow_right (by omega : 0 < H) (by omega) + +theorem computedCoarseWidthOverhead_le (N : ℕ) (hN : 0 < N) : + computedCoarseWidthOverhead N ≤ inputHeight N ^ + (10 * (computedMaxCoarseDepth N + coarseExponent (inputSmallLog N) + 1)) := by + have hH : 2 ≤ inputHeight N := by + exact (show 2 ^ 1 ≤ 2 ^ heightExponent N from + Nat.pow_le_pow_right (by decide : 0 < (2 : ℕ)) (heightExponent_pos N hN)) + have hlog : Nat.clog 2 N ≤ inputHeight N := + (Nat.clog_le_iff_le_pow (by decide : 1 < (2 : ℕ))).2 + ((Nat.le_add_right N 2).trans (inputHeight_covers_length N)) + exact coarse_width_overhead_le_power (inputHeight N) (computedMaxCoarseDepth N) + (coarseExponent (inputSmallLog N)) (Nat.clog 2 N) hH hlog + +theorem computedCoarseWidthOverhead_exp_le (N : ℕ) (hN : 0 < N) : + (computedCoarseWidthOverhead N : ℝ) ≤ Real.exp (computedCoarseOverheadExponent 10 N) := by + have h := computedCoarseWidthOverhead_le N hN + have hcast : (computedCoarseWidthOverhead N : ℝ) ≤ (inputHeight N : ℝ) ^ + (10 * (computedMaxCoarseDepth N + coarseExponent (inputSmallLog N) + 1)) := by exact_mod_cast h + rw [nat_pow_eq_exp_log (inputHeight N) + (10 * (computedMaxCoarseDepth N + coarseExponent (inputSmallLog N) + 1)) + (show 0 < inputHeight N from Nat.two_pow_pos (heightExponent N))] at hcast + convert hcast using 1 + unfold computedCoarseOverheadExponent + push_cast + ring + +theorem coarse_array_bound_mono (B n L factor : ℝ) (D E : ℕ) + (hB : 0 ≤ B) (hn : 0 ≤ n) (hL : 0 ≤ L) (hfactor : 1 ≤ factor) (hD : D ≤ E) : + 6 * B * n * L * (D + 1 : ℕ) * factor ^ D ≤ + n * (6 * B * L * (E + 1 : ℕ) * factor ^ E) := by + have hcount : ((D + 1 : ℕ) : ℝ) ≤ (E + 1 : ℕ) := by exact_mod_cast Nat.add_le_add_right hD 1 + have hpower := pow_le_pow_right₀ hfactor hD + calc + _ ≤ 6 * B * n * L * (E + 1 : ℕ) * factor ^ E := by + apply mul_le_mul _ hpower (pow_nonneg (by linarith) _) (by positivity) + exact mul_le_mul_of_nonneg_left hcount (by positivity) + _ = _ := by ring + +/-- The common overhead dominates the actual expected coarse array work +at every source/target interval, including the direct long-target branch. -/ +theorem computed_coarse_expected_source_width {α : Type*} [DecidableEq α] + (N B : ℕ) [NeZero B] [MeasurableSpace (Fin B)] [MeasurableSingletonClass (Fin B)] + (hB : B = (integerParameters N).B) (hN : 0 < N) (hell : 200 ≤ inputSmallLog N) + (hinverse : coarseInverseAllowanceFactor B (initialThresholdQ N) (initialLambda N) ≤ + (inputHeight N : ℝ) ^ 8) + (x y : List α) (D : ℕ) (hDcomputed : D = computedCoarseDepth N (coarseEntryWidth x y)) + (hsize : coarseEntryWidth x y ≤ N) : + (∫ draw, (coarseInitialArrayWork B D + (initialThresholdQ N) (initialLambda N) x y draw : ℝ) + ∂coarseInitialMeasure B D (coarseEntryWidth x y)) ≤ + (x.length : ℝ) * computedCoarseWidthOverhead N := by + have hH : 1 ≤ inputHeight N := Nat.one_le_two_pow + have hD : D ≤ computedMaxCoarseDepth N := + hDcomputed.trans_le (computedCoarseDepth_le_max N (coarseEntryWidth x y) hsize) + have hcapacity : coarseEntryWidth x y ≤ B ^ D := by + rw [hB, hDcomputed] + exact (computed_coarse_depth N _ hN hsize hell).1 + have hHQ : (0 : ℚ) < inputHeight N := by + exact_mod_cast Nat.two_pow_pos (heightExponent N) + have hHR : (1 : ℝ) ≤ inputHeight N := by exact_mod_cast hH + have hQ : 0 < initialThresholdQ N := pow_pos hHQ 4 + have hlam : 0 < initialLambda N := div_pos (by norm_num) (mul_pos (by norm_num) hHQ) + have hc := coarseInitialArrayWork_expected_source_width (B := B) (D := D) + (initialThresholdQ N) (initialLambda N) x y N hsize hcapacity + hQ hlam ((inputHeight N : ℝ) ^ 8) (one_le_pow₀ hHR) hinverse + apply hc.trans + have hm := coarse_array_bound_mono (B : ℝ) (x.length : ℝ) (Nat.clog 2 N + 1 : ℕ) + ((inputHeight N : ℝ) ^ 8) D (computedMaxCoarseDepth N) + (Nat.cast_nonneg _) (Nat.cast_nonneg _) (Nat.cast_nonneg _) (one_le_pow₀ hHR) hD + apply hm.trans_eq + simp only [computedCoarseWidthOverhead, Nat.cast_mul, Nat.cast_ofNat, Nat.cast_pow, + Nat.cast_add, Nat.cast_one, hB, ← pow_mul] + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedComparisonBand.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedComparisonBand.lean new file mode 100644 index 0000000000000000000000000000000000000000..9464b4ec0356803cb58dec732087db7779020036 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedComparisonBand.lean @@ -0,0 +1,109 @@ +import OAI.Combinatorics.EditApproximation.Geometry.ComparisonBandCoverage +import OAI.Combinatorics.EditApproximation.Geometry.BandParameters + +namespace OAI + +/-! The comparison band uses the computed numerical parameters, with its error budget proved. -/ + +namespace EditApproximation + +open Finset + +theorem comparisonActionCurvature_nonneg {α : Type*} (source target : List α) + {M : ℕ} (hM : 0 < M) (parent : TargetInterval source.length) + (r : TargetInterval target.length) (comparison : Fin M → TargetInterval target.length) + (child : Fin M → TargetInterval target.length → ℝ) + (hgap : ∀ i, |stateLengthGap + (substring source (sourceChild parent i).lo (sourceChild parent i).hi) target (comparison i)| ≤ + child i (comparison i)) + (hzero : endpointActionConnection r comparison = 0) + (hW : 0 < comparisonActionMass comparison child) : + 0 ≤ comparisonActionCurvature source target parent r comparison child := by + let mass := fun i => child i (comparison i) + let gap := fun i => stateLengthGap + (substring source (sourceChild parent i).lo (sourceChild parent i).hi) target (comparison i) + have hmass (i : Fin M) : 0 ≤ mass i := (abs_nonneg _).trans (hgap i) + have hzeroMass (i : Fin M) (hi : mass i = 0) : gap i = 0 := by + have h := hgap i + change |gap i| ≤ mass i at h + rw [hi] at h + exact abs_eq_zero.mp (le_antisymm h (abs_nonneg _)) + have hsum := zero_connection_gap_sum source target hM parent r comparison hzero + have h := curvature_nonneg univ mass gap (fun i _ => hmass i) (fun i _ => hzeroMass i) hW + dsimp only [mass, gap] at h + rw [hsum] at h + exact h + +theorem computed_comparison_band_mem {α : Type*} (source target : List α) + (N : ℕ) (hN : 0 < N) (hell : 2 ^ 1000 ≤ inputSmallLog N) + {M b P : ℕ} (hM : 0 < M) (hMeq : M = (integerParameters N).M) + (parent : TargetInterval source.length) (r : TargetInterval target.length) + (comparison : Fin M → TargetInterval target.length) + (hcomparison : comparison ∈ wideActionList M parent r b P) + (hnonempty : wideActionList M parent r b P ≠ []) + (child : Fin M → TargetInterval target.length → ℚ) (a : ℝ) (ha : 1 ≤ a) + (hchild : ∀ i s, max ((stateEditCost + (substring source (sourceChild parent i).lo (sourceChild parent i).hi) target s : ℝ) / a) + |stateLengthGap (substring source (sourceChild parent i).lo (sourceChild parent i).hi) target s| ≤ + (child i s : ℝ)) + (hupper : ∀ i, (child i (comparison i) : ℝ) ≤ 2 * inputSmallLog N * stateEditCost + (substring source (sourceChild parent i).lo (sourceChild parent i).hi) target (comparison i)) + (hcostSum : (∑ i, (stateEditCost + (substring source (sourceChild parent i).lo (sourceChild parent i).hi) target (comparison i) : ℝ)) ≤ 4 * b) + (hpositive : 0 < stateEditCost (substring source parent.lo parent.hi) target r) + (hzero : endpointActionConnection r comparison = 0) + (hanchors : ∀ i, Nat.dist (r.lo + ((sourceChild parent i).lo - parent.lo)) (comparison i).lo ≤ 6 * b ∧ + Nat.dist (r.lo + ((sourceChild parent i).hi - parent.lo)) (comparison i).hi ≤ 6 * b) + (hvelocity : |rationalStateGap (substring source parent.lo parent.hi) target r / + rationalWideActionMinimum parent r b P hnonempty child| ≤ + 1 - (rationalParameters (inputSmallLog N)).tau) + (hKsmall : comparisonActionCurvature source target parent r comparison (fun i s => (child i s : ℝ)) ≤ + b / heightQuarterRoot N) + (hGsmall : comparisonActionMass comparison (fun i s => (child i s : ℝ)) - + wideActionMinimum parent r b P hnonempty (fun i s => (child i s : ℝ)) ≤ b / heightQuarterRoot N) : + comparison ∈ representativeBandActions source target parent r b P + (rationalParameters (inputSmallLog N)).tau (rationalParameters (inputSmallLog N)).theta child := by + let childR := fun i s => (child i s : ℝ) + let W := comparisonActionMass comparison childR + let Z := wideActionMinimum parent r b P hnonempty childR + let K := comparisonActionCurvature source target parent r comparison childR + have hgap (i : Fin M) : |stateLengthGap + (substring source (sourceChild parent i).lo (sourceChild parent i).hi) target (comparison i)| ≤ + childR i (comparison i) := (le_max_right _ _).trans (hchild i (comparison i)) + have hZlower : (stateEditCost (substring source parent.lo parent.hi) target r : ℝ) / a ≤ Z := + (le_max_left _ _).trans (wideActionMinimum_lower source target hM parent r b P hnonempty a ha childR hchild) + have hcpos : (0 : ℝ) < stateEditCost (substring source parent.lo parent.hi) target r := by exact_mod_cast hpositive + have hZpos : 0 < Z := (div_pos hcpos (by linarith only [ha] : 0 < a)).trans_le hZlower + have hZposQ : 0 < rationalWideActionMinimum parent r b P hnonempty child := by + have h := hZpos + change 0 < wideActionMinimum parent r b P hnonempty childR at h + rw [← rationalWideActionMinimum_cast] at h + exact_mod_cast h + have hZW : Z ≤ W := by + have h := wideActionMinimum_le_member parent r hnonempty childR comparison hcomparison + simpa only [Z, W, comparisonActionMass, endpointActionValue, hzero, Nat.cast_zero, zero_add] using h + have hWpos : 0 < W := hZpos.trans_le hZW + have hK : 0 ≤ K := comparisonActionCurvature_nonneg source target hM parent r comparison childR hgap hzero hWpos + have hG : 0 ≤ W - Z := sub_nonneg.mpr hZW + have hWupper : W ≤ 8 * inputSmallLog N * b := by + calc + W = ∑ i, childR i (comparison i) := rfl + _ ≤ ∑ i, 2 * (inputSmallLog N : ℝ) * stateEditCost + (substring source (sourceChild parent i).lo (sourceChild parent i).hi) target (comparison i) := + sum_le_sum fun i _ => hupper i + _ = 2 * (inputSmallLog N : ℝ) * ∑ i, (stateEditCost + (substring source (sourceChild parent i).lo (sourceChild parent i).hi) target (comparison i) : ℝ) := by rw [mul_sum] + _ ≤ 2 * (inputSmallLog N : ℝ) * (4 * b) := + mul_le_mul_of_nonneg_left hcostSum (by positivity) + _ = 8 * inputSmallLog N * b := by ring + have hnumerical := computed_nonbad_band_numerical_bound N hN hell (Nat.cast_nonneg b) + hK hG hWpos.le hKsmall hGsmall hWupper + rw [← hMeq] at hnumerical + apply comparison_representativeBandActions_mem source target hM parent r comparison hcomparison hnonempty + (rationalParameters (inputSmallLog N)).tau (rationalParameters (inputSmallLog N)).theta child + a ha hchild hzero hanchors hZposQ hvelocity + simpa only [mul_comm, W, Z, K, childR] using hnumerical + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedCurrentQueryBudget.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedCurrentQueryBudget.lean new file mode 100644 index 0000000000000000000000000000000000000000..55186a44e4c1d1ab42fc5cb06b74919d84c6ca38 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedCurrentQueryBudget.lean @@ -0,0 +1,169 @@ +import OAI.Combinatorics.EditApproximation.Geometry.CurrentQueryInputs +import OAI.Combinatorics.EditApproximation.Refinement.ComputedGroupNumerical + +namespace OAI + +/-! Explicit polynomial same-index call budget after substituting the +computed window, cell, scale-label, sampling and rounding parameters. -/ + +namespace EditApproximation + +def localCurrentBudget (window cells labels M Q inverseTheta : ℕ) : ℕ := + window * cells * labels * (624 * M * Q * inverseTheta ^ 2) + window * cells * M + window * M + +theorem localCurrentBudget_poly (ell M window cells labels : ℕ) (hell : 4 ≤ ell) + (hwindow : window ≤ 2 * ell ^ 2) (hcells : cells ≤ 1296 * ell ^ 82) + (hlabels : labels ≤ 2 * ell) : + localCurrentBudget window cells labels M (ell ^ 80) (ell ^ 40) ≤ M * ell ^ 256 := by + have hfirst := Nat.mul_le_mul + (Nat.mul_le_mul (Nat.mul_le_mul hwindow hcells) hlabels) + (le_rfl (a := 624 * M * ell ^ 80 * (ell ^ 40) ^ 2)) + have hsecond := Nat.mul_le_mul_right M (Nat.mul_le_mul hwindow hcells) + have hthird := Nat.mul_le_mul_right M hwindow + have h84 : ell ^ 84 ≤ ell ^ 245 := pow_le_pow_right₀ (by omega : 1 ≤ ell) (by decide : 84 ≤ 245) + have h2 : ell ^ 2 ≤ ell ^ 245 := pow_le_pow_right₀ (by omega : 1 ≤ ell) (by decide : 2 ≤ 245) + have hsecond' : 2 * ell ^ 2 * (1296 * ell ^ 82) * M ≤ 2592 * M * ell ^ 245 := by + calc + _ = 2592 * M * ell ^ 84 := by ring + _ ≤ _ := Nat.mul_le_mul_left _ h84 + have hthird' : 2 * ell ^ 2 * M ≤ 2 * M * ell ^ 245 := by + calc + _ = 2 * M * ell ^ 2 := by ring + _ ≤ _ := Nat.mul_le_mul_left _ h2 + have hsum : localCurrentBudget window cells labels M (ell ^ 80) (ell ^ 40) ≤ + 3237410 * M * ell ^ 245 := by + apply (Nat.add_le_add (Nat.add_le_add hfirst (hsecond.trans hsecond')) + (hthird.trans hthird')).trans_eq + ring + have hconstant : 3237410 ≤ ell ^ 11 := by + apply (show 3237410 ≤ (4 : ℕ) ^ 11 by norm_num).trans + exact Nat.pow_le_pow_left hell 11 + calc + _ ≤ 3237410 * M * ell ^ 245 := hsum + _ ≤ ell ^ 11 * M * ell ^ 245 := Nat.mul_le_mul_right _ (Nat.mul_le_mul_right M hconstant) + _ = M * ell ^ 256 := by ring + +theorem computed_window_exponent_bound (N : ℕ) (hN : 0 < N) (hell : 8 ≤ inputSmallLog N) : + computedSeedInitialExponent N + 8 ≤ 2 * inputSmallLog N ^ 2 := by + have hh := (inputSmallLog_bounds N hN).1 + have hp : coarseExponent (inputSmallLog N) ≤ inputSmallLog N := + (Nat.sqrt_le_self _).trans ((Nat.sqrt_le_self _).trans (Nat.log_le_self _ _)) + have hmul := Nat.mul_le_mul (Nat.add_le_add_right hp 4) hh + unfold computedSeedInitialExponent + have hslack : 4 * inputSmallLog N + 8 ≤ inputSmallLog N ^ 2 := by nlinarith + nlinarith only [hmul, hslack] + +theorem computed_local_cell_budget (N : ℕ) (hell : 1 ≤ inputSmallLog N) : + ((32 * inputSmallLog N + 2) * 2 ^ (40 * smallLogExponent N) + 2) ^ 2 ≤ + 1296 * inputSmallLog N ^ 82 := by + have hpower : 2 ^ (40 * smallLogExponent N) = inputSmallLog N ^ 40 := by + unfold inputSmallLog + rw [← pow_mul, Nat.mul_comm] + rw [hpower] + have hinner : (32 * inputSmallLog N + 2) * inputSmallLog N ^ 40 + 2 ≤ + 36 * inputSmallLog N ^ 41 := by + have ha := Nat.mul_le_mul_right (inputSmallLog N ^ 40) (show 32 * inputSmallLog N + 2 ≤ + 34 * inputSmallLog N by omega) + have hb : 2 ≤ 2 * inputSmallLog N ^ 41 := Nat.mul_le_mul_left 2 (one_le_pow₀ hell) + calc + _ ≤ 34 * inputSmallLog N * inputSmallLog N ^ 40 + 2 := Nat.add_le_add_right ha _ + _ ≤ 34 * inputSmallLog N * inputSmallLog N ^ 40 + 2 * inputSmallLog N ^ 41 := + Nat.add_le_add_left hb _ + _ = _ := by ring + calc + _ ≤ (36 * inputSmallLog N ^ 41) ^ 2 := Nat.pow_le_pow_left hinner 2 + _ = _ := by ring + +theorem computed_refinement_window (N : ℕ) (hN : 0 < N) (hell : 8 ≤ inputSmallLog N) + (A w : ℚ) (hA : A ≤ ((integerParameters N).initialFactor : ℚ)) : + (dyadicQueryWindow N w (refinementFactor A (inputSmallLog N)) (inputSmallLog N)).length ≤ + computedSeedInitialExponent N + 8 := by + have hh := inputSmallLog_bounds N hN + have hf : smallLogExponent N ≤ inputSmallLog N := (smallLogExponent N).lt_two_pow_self.le + have he0 : smallLogExponent N ≤ computedSeedInitialExponent N := by + have hfour := Nat.mul_le_mul_right (heightExponent N) + (show 4 ≤ coarseExponent (inputSmallLog N) + 4 by omega) + unfold computedSeedInitialExponent + nlinarith only [hh.2, hf, hfour] + apply refinement_query_window_length N (inputSmallLog N) (computedSeedInitialExponent N) A w (by omega) + · simpa only [inputSmallLog, Nat.cast_pow, Nat.cast_ofNat] using + pow_le_pow_right₀ (by norm_num : (1 : ℚ) ≤ 2) he0 + · exact hA.trans_eq (computedSeed_initial_factor N).symm + +/-- The actual finite local shared/selected/online input cover is bounded +by M*ell^256 on every seed. The online-loop length premise is the literal +one-action-per-applicable-scale property proved for the physical program. -/ +theorem computed_currentQueryInputCover_card {α : Type*} (source target : List α) + (N P : ℕ) (hN : 0 < N) (hell : 200 ≤ inputSmallLog N) + (parent : TargetInterval source.length) (A tau : ℚ) + (hA : A ≤ ((integerParameters N).initialFactor : ℚ)) + (parentInitial : TargetInterval target.length → ℚ) + (child initial current : Fin (integerParameters N).M → TargetInterval target.length → ℚ) + (draw : CellGroupDraws (integerParameters N).M (inputSmallLog N) (inputSmallLog N ^ 80)) + (q : TargetInterval target.length) (hw : 0 ≤ parentInitial q) + (online : List (PhysicalRationalAction (integerParameters N).M target.length)) + (honline : online.length ≤ + (dyadicQueryWindow N (parentInitial q) (refinementFactor A (inputSmallLog N)) (inputSmallLog N)).length) : + (currentQueryInputCover source target parent N P (inputSmallLog N) (40 * smallLogExponent N) + (inputSmallLog N ^ 80) tau (refinementFactor A (inputSmallLog N)) parentInitial + child initial current draw q online).card ≤ (integerParameters N).M * inputSmallLog N ^ 256 := by + let ell := inputSmallLog N + let M := (integerParameters N).M + let W := computedSeedInitialExponent N + 8 + let C := ((32 * ell + 2) * 2 ^ (40 * smallLogExponent N) + 2) ^ 2 + have hell8 : 8 ≤ ell := by omega + have hM : 0 < M := by have h := (computed_branching_bounds N hN hell).1; omega + have hlabels (b : ℕ) (hb : b ∈ dyadicScales N) : (groupDyadicScales M b ell).length ≤ 2 * ell := by + obtain ⟨eb, _, rfl⟩ := List.mem_map.mp hb + exact computed_group_scale_count N eb hN hell8 + have hwindow := computed_refinement_window N hN hell8 A (parentInitial q) hA + have hkeys : (localGroupQueryKeys N ell (40 * smallLogExponent N) + (refinementFactor A ell) parentInitial q).length ≤ W * C := + (localGroupQueryKeys_length N ell (40 * smallLogExponent N) (refinementFactor A ell) + parentInitial q (by omega) hw).trans (Nat.mul_le_mul_right C hwindow) + have hgroups := localCellGroupActions_length_refinement source target parent N P ell + (40 * smallLogExponent N) (ell ^ 80) (computedSeedInitialExponent N) tau A + parentInitial child initial current draw q (by omega) hw + have hraw := currentQueryInputCover_card source target parent N P ell (40 * smallLogExponent N) + (ell ^ 80) (2 * ell) tau (refinementFactor A ell) parentInitial child initial current draw q online + hM (by omega) (one_le_pow₀ (by omega)) hlabels + have hrawN : (currentQueryInputCover source target parent N P ell (40 * smallLogExponent N) + (ell ^ 80) tau (refinementFactor A ell) parentInitial child initial current draw q online).card ≤ + (localGroupQueryKeys N ell (40 * smallLogExponent N) (refinementFactor A ell) parentInitial q).length * + (2 * ell) * (624 * M * ell ^ 80 * (2 ^ (40 * smallLogExponent N)) ^ 2) + + (localCellGroupActions source target parent N P ell (40 * smallLogExponent N) (ell ^ 80) tau + (refinementFactor A ell) parentInitial child initial current draw q).length * M + online.length * M := by + exact_mod_cast hraw + have hFpower : (ell : ℚ) ≤ (2 : ℚ) ^ computedSeedInitialExponent N := by + have hh := inputSmallLog_bounds N hN + have hf : smallLogExponent N ≤ ell := (smallLogExponent N).lt_two_pow_self.le + have hfour := Nat.mul_le_mul_right (heightExponent N) + (show 4 ≤ coarseExponent ell + 4 by omega) + have he : smallLogExponent N ≤ computedSeedInitialExponent N := by + unfold computedSeedInitialExponent + nlinarith only [hh.2, hf, hfour] + simpa only [ell, inputSmallLog, Nat.cast_pow, Nat.cast_ofNat] using + pow_le_pow_right₀ (by norm_num : (1 : ℚ) ≤ 2) he + have hAbound : A ≤ (2 : ℚ) ^ computedSeedInitialExponent N := hA.trans_eq (computedSeed_initial_factor N).symm + have hg : (localCellGroupActions source target parent N P ell (40 * smallLogExponent N) (ell ^ 80) tau + (refinementFactor A ell) parentInitial child initial current draw q).length ≤ W * C := + hgroups hFpower hAbound + have hbudget : (currentQueryInputCover source target parent N P ell (40 * smallLogExponent N) + (ell ^ 80) tau (refinementFactor A ell) parentInitial child initial current draw q online).card ≤ + localCurrentBudget W C (2 * ell) M (ell ^ 80) (2 ^ (40 * smallLogExponent N)) := by + exact hrawN.trans (Nat.add_le_add (Nat.add_le_add + (Nat.mul_le_mul_right _ (Nat.mul_le_mul_right (2 * ell) hkeys)) + (Nat.mul_le_mul_right M hg)) (Nat.mul_le_mul_right M (honline.trans hwindow))) + have hpower : 2 ^ (40 * smallLogExponent N) = ell ^ 40 := by + dsimp only [ell] + unfold inputSmallLog + rw [← pow_mul, Nat.mul_comm] + rw [hpower] at hbudget + exact hbudget.trans (localCurrentBudget_poly ell M W C (2 * ell) + ((by decide : 4 ≤ (8 : ℕ)).trans hell8) + (computed_window_exponent_bound N hN hell8) + (computed_local_cell_budget N ((by decide : 1 ≤ (8 : ℕ)).trans hell8)) le_rfl) + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedEarlierHistory.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedEarlierHistory.lean new file mode 100644 index 0000000000000000000000000000000000000000..faff234ecba3b0bfa1f3d98b5c0195a2bccb04f3 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedEarlierHistory.lean @@ -0,0 +1,36 @@ +import OAI.Combinatorics.EditApproximation.Refinement.ComputedEarlierInputBudget + +namespace OAI + +/-! A query gathers only its preceding history, rather than allocating +the full time range used to bound that history's cardinality. -/ + +namespace EditApproximation + +theorem wideEarlierInputCover_mono_history {nx ny M : ℕ} (parent : TargetInterval nx) + (P small large : ℕ) (representatives : List (ℕ × TargetInterval ny)) (h : small ≤ large) : + wideEarlierInputCover (M := M) parent P small representatives ⊆ + wideEarlierInputCover parent P large representatives := by + intro input hinput + obtain ⟨br, hbr, hinput⟩ := Finset.mem_biUnion.mp hinput + obtain ⟨i, hi, hinput⟩ := Finset.mem_biUnion.mp hinput + obtain ⟨t, ht, hinput⟩ := Finset.mem_biUnion.mp hinput + exact Finset.mem_biUnion.mpr ⟨br, hbr, Finset.mem_biUnion.mpr ⟨i, hi, + Finset.mem_biUnion.mpr ⟨t, (Finset.mem_range.mpr ((Finset.mem_range.mp ht).trans_le h)), hinput⟩⟩⟩ + +theorem computed_queryEarlierHistory_card {nx ny : ℕ} + (parent : TargetInterval nx) (N P history : ℕ) (hN : 0 < N) + (hell : 200 ≤ inputSmallLog N) (hPeq : P = (integerParameters N).P) + (hhistory : history ≤ (integerParameters N).T + (integerParameters N).S + 1) + (A : ℚ) (hA : A ≤ ((integerParameters N).initialFactor : ℚ)) + (initial : TargetInterval ny → ℚ) (q : TargetInterval ny) (hw : 0 ≤ initial q) : + (queryEarlierInputCover (M := (integerParameters N).M) parent N P (inputSmallLog N) + (40 * smallLogExponent N) history (refinementFactor A (inputSmallLog N)) initial q).card ≤ + inputHeight N ^ (256 * (coarseExponent (inputSmallLog N) + 1)) := by + apply (Finset.card_le_card (wideEarlierInputCover_mono_history parent P history + ((integerParameters N).T + (integerParameters N).S + 1) _ hhistory)).trans + exact computed_queryEarlierInputCover_card parent N P hN hell hPeq A hA initial q hw + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedEarlierInputBudget.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedEarlierInputBudget.lean new file mode 100644 index 0000000000000000000000000000000000000000..4c0efa9b1f1ea7ab26e770f635df6bf9ad7c4007 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedEarlierInputBudget.lean @@ -0,0 +1,90 @@ +import OAI.Combinatorics.EditApproximation.Geometry.EarlierInputBudget +import OAI.Combinatorics.EditApproximation.Refinement.ComputedBandSpacing + +namespace OAI + +/-! The actual earlier-input cover satisfies the polynomial branching +budget at every seed, after substituting the computed time and grid +parameters. -/ + +namespace EditApproximation + +theorem computed_smallLog_le_height (N : ℕ) : inputSmallLog N ≤ inputHeight N := by + have hf : smallLogExponent N ≤ heightExponent N := by + unfold smallLogExponent + apply Nat.clog_le_of_le_pow + exact max_le Nat.one_le_two_pow (heightExponent N).lt_two_pow_self.le + exact pow_le_pow_right₀ (by decide : (1 : ℕ) ≤ 2) hf + +theorem computed_history_budget_le_height_sq (N : ℕ) (hH : 4 ≤ inputHeight N) : + (integerParameters N).T + (integerParameters N).S + 1 ≤ inputHeight N ^ 2 := by + have hT : (integerParameters N).T ≤ 2 * inputHeight N := by + change 2 ^ ((3 * heightExponent N + 3) / 4) ≤ 2 * 2 ^ heightExponent N + calc + _ ≤ 2 ^ (heightExponent N + 1) := + pow_le_pow_right₀ (by decide : (1 : ℕ) ≤ 2) (by omega) + _ = _ := by rw [pow_succ]; ring + have hS : (integerParameters N).S ≤ inputHeight N := Nat.div_le_self _ _ + nlinarith only [hT, hS, hH] + +theorem computed_window_le_height_cube (N : ℕ) (hN : 0 < N) + (hell : 8 ≤ inputSmallLog N) (hH : 2 ≤ inputHeight N) : + computedSeedInitialExponent N + 8 ≤ inputHeight N ^ 3 := by + calc + _ ≤ 2 * inputSmallLog N ^ 2 := computed_window_exponent_bound N hN hell + _ ≤ inputHeight N * inputHeight N ^ 2 := + Nat.mul_le_mul hH (Nat.pow_le_pow_left (computed_smallLog_le_height N) 2) + _ = _ := by ring + +theorem computed_cell_budget_le_height_pow (N : ℕ) (hH : 64 ≤ inputHeight N) : + ((32 * inputSmallLog N + 2) * 2 ^ (40 * smallLogExponent N) + 2) ^ 2 ≤ + inputHeight N ^ 84 := by + have hconstant : 1296 ≤ inputHeight N ^ 2 := + (by norm_num : 1296 ≤ (64 : ℕ) ^ 2).trans (Nat.pow_le_pow_left hH 2) + calc + _ ≤ 1296 * inputSmallLog N ^ 82 := + computed_local_cell_budget N Nat.one_le_two_pow + _ ≤ inputHeight N ^ 2 * inputHeight N ^ 82 := + Nat.mul_le_mul hconstant (Nat.pow_le_pow_left (computed_smallLog_le_height N) 82) + _ = _ := by ring + +/-- Every literal earlier-input request lies in a cover of cardinality +`H^(256(p+1))`. The only value premise is nonnegativity of the actual +initial query value; no good-seed event is required. -/ +theorem computed_queryEarlierInputCover_card {nx ny : ℕ} + (parent : TargetInterval nx) (N P : ℕ) (hN : 0 < N) + (hell : 200 ≤ inputSmallLog N) (hPeq : P = (integerParameters N).P) + (A : ℚ) (hA : A ≤ ((integerParameters N).initialFactor : ℚ)) + (initial : TargetInterval ny → ℚ) (q : TargetInterval ny) (hw : 0 ≤ initial q) : + (queryEarlierInputCover (M := (integerParameters N).M) parent N P (inputSmallLog N) + (40 * smallLogExponent N) ((integerParameters N).T + (integerParameters N).S + 1) + (refinementFactor A (inputSmallLog N)) initial q).card ≤ + inputHeight N ^ (256 * (coarseExponent (inputSmallLog N) + 1)) := by + let W := computedSeedInitialExponent N + 8 + let C := ((32 * inputSmallLog N + 2) * 2 ^ (40 * smallLogExponent N) + 2) ^ 2 + have hF : inputSmallLog N ≤ inputHeight N := computed_smallLog_le_height N + have hH : 64 ≤ inputHeight N := (by omega : 64 ≤ inputSmallLog N).trans hF + have hPpos : 1 ≤ P := by + rw [hPeq] + exact one_le_pow₀ Nat.one_le_two_pow + have hPpower : P ≤ inputHeight N ^ (coarseExponent (inputSmallLog N) + 20) := by + rw [hPeq] + exact le_rfl + have hM : (integerParameters N).M ≤ inputHeight N := + pow_le_pow_right₀ (by decide : (1 : ℕ) ≤ 2) (Nat.div_le_self _ _) + have hbudget := queryEarlierInputCover_le_budget (M := (integerParameters N).M) + parent N P (inputSmallLog N) (40 * smallLogExponent N) + ((integerParameters N).T + (integerParameters N).S + 1) W C + (refinementFactor A (inputSmallLog N)) initial q + ⟨_, hPeq.trans (computed_P_dyadic N)⟩ (by omega) hw + (computed_refinement_window N hN (by omega) A (initial q) hA) le_rfl + exact hbudget.trans (localEarlierBudget_poly (inputHeight N) + (coarseExponent (inputSmallLog N)) W C (integerParameters N).M P (inputSmallLog N) + ((integerParameters N).T + (integerParameters N).S + 1) + hH hPpos hPpower (computed_window_le_height_cube N hN (by omega) (by omega)) + (computed_cell_budget_le_height_pow N hH) hM hF + (computed_history_budget_le_height_sq N (by omega))) + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedExecutionCosts.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedExecutionCosts.lean new file mode 100644 index 0000000000000000000000000000000000000000..f49e8a0a0ce2c50c0eaaf32305c4aae7071908d3 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedExecutionCosts.lean @@ -0,0 +1,126 @@ +import Mathlib.Analysis.SpecialFunctions.Pow.Asymptotics +import OAI.Combinatorics.EditApproximation.Refinement.ComputedExecutionWork +import OAI.Combinatorics.EditApproximation.Refinement.ComputedJointCoarseWork +import OAI.Combinatorics.EditApproximation.Refinement.ComputedAddressWork +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation +open Filter MeasureTheory + + theorem computedExecutionRejectionWork_integrable (source target : List ℕ) (N : ℕ) : + Integrable (computedExecutionRejectionWork source target N) (computedExecutionLaw source target N) := by + let incoming := physicalCoarseSeedLaw (M := (integerParameters N).M) + (J := intervalTreeDepth (integerParameters N).M source.length) source target N + (integerParameters N).B (computedPhysicalCoarseDepth source target N) + have hi : Integrable (computedFamilyRejectionWork source target N) + (physicalFamilyRuntimeLaw (R := inputHeight N ^ 2) target N (integerParameters N).P + (inputHeight N) incoming) := + finite_outer_integrable incoming _ (computedFamilyRejectionWork source target N) + (computedFamilyRejectionWork_integrable source target N) + have hj : Integrable (computedFamilyRejectionWork source target N) + ((computedExecutionLaw source target N).map (computedExecutionProjection source target N)) := by + rw [computedExecutionProjection_law] + exact hi + exact hj.comp_measurable (computedExecutionProjection_measurable source target N) + + theorem computedExecutionAccepted_measurable (source target : List ℕ) (N : ℕ) : + Measurable (computedExecutionAccepted source target N) := measurable_of_countable _ + + theorem computedExecutionAcceptedWork_integrable (source target : List ℕ) (N : ℕ) + (f : ComputedFamilyInput source target N → ℝ) : + Integrable (f ∘ computedExecutionAccepted source target N) (computedExecutionLaw source target N) := by + have hi : Integrable f ((computedExecutionLaw source target N).map + (computedExecutionAccepted source target N)) := Integrable.of_finite + exact hi.comp_measurable (computedExecutionAccepted_measurable source target N) + + + + theorem computedExecutionDictionaryWork_integrable (source target : List ℕ) (N : ℕ) : + Integrable (computedExecutionDictionaryWork source target N) (computedExecutionLaw source target N) := + computedExecutionAcceptedWork_integrable source target N + (fun input => (computedFamilyResult source target N input).dictionaryVisits) + + theorem computedExecutionDictionaryWork_expected_near_linear (epsilon : ℝ) (hepsilon : 0 < epsilon) : + ∀ᶠ N in atTop, ∀ source target : List ℕ, source.length + target.length ≤ N → + (∫ execution, computedExecutionDictionaryWork source target N execution + ∂computedExecutionLaw source target N) ≤ (N + 2 : ℝ) ^ (1 + epsilon) := by + filter_upwards [computedFamilyResult_dictionary_near_linear epsilon hepsilon] with N hN + intro source target hsize + calc + _ ≤ ∫ _ : ComputedExecutionOutcome source target N, (N + 2 : ℝ) ^ (1 + epsilon) + ∂computedExecutionLaw source target N := + integral_mono (computedExecutionDictionaryWork_integrable source target N) (integrable_const _) + (fun execution => hN source target hsize _) + _ = _ := by simp + + + + theorem computedExecutionAddressWork_integrable (source target : List ℕ) (N : ℕ) : + Integrable (computedExecutionAddressWork source target N) (computedExecutionLaw source target N) := + computedExecutionAcceptedWork_integrable source target N + (fun input => (computedFamilyAddressWork source target N input : ℝ)) + + theorem computedExecutionAddressWork_expected_near_linear (epsilon : ℝ) (hepsilon : 0 < epsilon) : + ∀ᶠ N in atTop, ∀ source target : List ℕ, source.length + target.length ≤ N → + (∫ execution, computedExecutionAddressWork source target N execution + ∂computedExecutionLaw source target N) ≤ (N + 2 : ℝ) ^ (1 + epsilon) := by + filter_upwards [computedFamilyAddressWork_near_linear epsilon hepsilon] with N hN + intro source target hsize + calc + _ ≤ ∫ _ : ComputedExecutionOutcome source target N, (N + 2 : ℝ) ^ (1 + epsilon) + ∂computedExecutionLaw source target N := + integral_mono (computedExecutionAddressWork_integrable source target N) (integrable_const _) + (fun execution => hN source target hsize _) + _ = _ := by simp + +/-- These are the actual coarse, rejection-bit, dictionary and address-construction counters. +The local arithmetic counter is kept separate until its kernel is composed. -/ + + + theorem computedExecutionNonlocalWork_integrable (source target : List ℕ) (N : ℕ) : + Integrable (computedExecutionNonlocalWork source target N) (computedExecutionLaw source target N) := + (((computedExecutionCoarseWork_integrable source target N).add + (computedExecutionRejectionWork_integrable source target N)).add + (computedExecutionDictionaryWork_integrable source target N)).add + (computedExecutionAddressWork_integrable source target N) + + theorem constant_le_rpow_eventually (C epsilon : ℝ) (hepsilon : 0 < epsilon) : + ∀ᶠ N : ℕ in atTop, C ≤ (N + 2 : ℝ) ^ epsilon := by + have ht : Tendsto (fun N : ℕ => (N : ℝ) + 2) atTop atTop := + tendsto_atTop_add_const_right atTop 2 tendsto_natCast_atTop_atTop + exact ((tendsto_rpow_atTop hepsilon).comp ht).eventually (eventually_ge_atTop C) + + theorem computedExecutionNonlocalWork_expected_near_linear (epsilon : ℝ) (hepsilon : 0 < epsilon) : + ∀ᶠ N in atTop, ∀ source target : List ℕ, source.length + target.length ≤ N → + (∫ execution, computedExecutionNonlocalWork source target N execution + ∂computedExecutionLaw source target N) ≤ (N + 2 : ℝ) ^ (1 + epsilon) := by + have hhalf : 0 < epsilon / 2 := half_pos hepsilon + filter_upwards [computedExecutionCoarseWork_expected_near_linear (epsilon / 2) hhalf, + computedExecutionRejectionWork_expected_near_linear (epsilon / 2) hhalf, + computedExecutionDictionaryWork_expected_near_linear (epsilon / 2) hhalf, + computedExecutionAddressWork_expected_near_linear (epsilon / 2) hhalf, + constant_le_rpow_eventually 4 (epsilon / 2) hhalf] with N hc hr hd ha hfour + intro source target hsize + have hiC := computedExecutionCoarseWork_integrable source target N + have hiR := computedExecutionRejectionWork_integrable source target N + have hiD := computedExecutionDictionaryWork_integrable source target N + have hiA := computedExecutionAddressWork_integrable source target N + change integral (computedExecutionLaw source target N) + (((computedExecutionCoarseWork source target N + computedExecutionRejectionWork source target N) + + computedExecutionDictionaryWork source target N) + computedExecutionAddressWork source target N) ≤ _ + rw [integral_add' ((hiC.add hiR).add hiD) hiA, integral_add' (hiC.add hiR) hiD, + integral_add' hiC hiR] + calc + _ ≤ 4 * (N + 2 : ℝ) ^ (1 + epsilon / 2) := by + linarith only [hc source target hsize, hr source target hsize, hd source target hsize, + ha source target hsize] + _ ≤ (N + 2 : ℝ) ^ (epsilon / 2) * (N + 2 : ℝ) ^ (1 + epsilon / 2) := + mul_le_mul_of_nonneg_right hfour (Real.rpow_nonneg (by positivity) _) + _ = _ := by rw [← Real.rpow_add (by positivity)]; congr 1; ring + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedExecutionKernelWork.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedExecutionKernelWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..d97a012c011ffc76637e8efa139021e1aa375ba6 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedExecutionKernelWork.lean @@ -0,0 +1,73 @@ +import OAI.Combinatorics.EditApproximation.Refinement.ComputedKernelWork +import OAI.Combinatorics.EditApproximation.Refinement.ComputedReadChargedWork +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation +open MeasureTheory Filter + + + +theorem computedExecutionKernelWork_integrable (source target : List ℕ) (N : ℕ) + (cost : ComputedFamilyInput source target N → ComputedFamilyMemoKey source target N → ℕ) : + Integrable (computedExecutionKernelWork source target N cost) + (computedExecutionLaw source target N) := + computedExecutionAcceptedWork_integrable source target N + (fun input => (computedFamilyKernelWork source target N input (cost input) : ℝ)) + +theorem computedExecutionKernelWork_expected_near_linear (D : ℕ) + (epsilon : ℝ) (hepsilon : 0 < epsilon) : + ∀ᶠ N in atTop, ∀ source target : List ℕ, source.length + target.length ≤ N → + ∀ cost : ComputedFamilyInput source target N → ComputedFamilyMemoKey source target N → ℕ, + (∀ input key, cost input key ≤ computedLocalKernelBudget D N) → + (∫ execution, computedExecutionKernelWork source target N cost execution + ∂computedExecutionLaw source target N) ≤ (N + 2 : ℝ) ^ (1 + epsilon) := by + filter_upwards [computedFamilyKernelWork_near_linear D epsilon hepsilon] with N hN + intro source target hsize cost hcost + calc + _ ≤ ∫ _ : ComputedExecutionOutcome source target N, (N + 2 : ℝ) ^ (1 + epsilon) + ∂computedExecutionLaw source target N := + integral_mono (computedExecutionKernelWork_integrable source target N cost) + (integrable_const _) (fun execution => hN source target hsize + (computedExecutionAccepted source target N execution) _ (hcost _)) + _ = _ := by simp + +/-- Execution work combines the nonlocal charges with a local kernel annotation. -/ + + +theorem computedExecutionTotalWork_integrable (source target : List ℕ) (N : ℕ) + (cost : ComputedFamilyInput source target N → ComputedFamilyMemoKey source target N → ℕ) : + Integrable (computedExecutionTotalWork source target N cost) + (computedExecutionLaw source target N) := + (computedExecutionReadChargedWork_integrable source target N).add + (computedExecutionKernelWork_integrable source target N cost) + +theorem computedExecutionTotalWork_expected_near_linear (D : ℕ) + (epsilon : ℝ) (hepsilon : 0 < epsilon) : + ∀ᶠ N in atTop, ∀ source target : List ℕ, source.length + target.length ≤ N → + (∀ a ∈ source ++ target, Nat.size a ≤ inputHeight N ^ 3) → + ∀ cost : ComputedFamilyInput source target N → ComputedFamilyMemoKey source target N → ℕ, + (∀ input key, cost input key ≤ computedLocalKernelBudget D N) → + (∫ execution, computedExecutionTotalWork source target N cost execution + ∂computedExecutionLaw source target N) ≤ (N + 2 : ℝ) ^ (1 + epsilon) := by + have hh := half_pos hepsilon + filter_upwards [computedExecutionReadChargedWork_expected_near_linear (epsilon / 2) hh, + computedExecutionKernelWork_expected_near_linear D (epsilon / 2) hh, + constant_le_rpow_eventually 2 (epsilon / 2) hh] with N hn hk htwo + intro source target hsize hsymbol cost hcost + change integral (computedExecutionLaw source target N) + (computedExecutionReadChargedWork source target N + computedExecutionKernelWork source target N cost) ≤ _ + rw [integral_add' (computedExecutionReadChargedWork_integrable source target N) + (computedExecutionKernelWork_integrable source target N cost)] + calc + _ ≤ 2 * (N + 2 : ℝ) ^ (1 + epsilon / 2) := by + linarith only [hn source target hsize hsymbol, hk source target hsize cost hcost] + _ ≤ (N + 2 : ℝ) ^ (epsilon / 2) * (N + 2 : ℝ) ^ (1 + epsilon / 2) := + mul_le_mul_of_nonneg_right htwo (Real.rpow_nonneg (by positivity) _) + _ = _ := by rw [← Real.rpow_add (by positivity)]; congr 1; ring + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedExecutionLaw.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedExecutionLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..7ed32f4367736bacec45b26ebc36037ec72487f8 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedExecutionLaw.lean @@ -0,0 +1,114 @@ +import OAI.Combinatorics.EditApproximation.Refinement.ComputedCoarseExecution +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +/-! The coarse sampler execution and its returned seed share one probability space. -/ + +namespace EditApproximation + +open MeasureTheory + + + + + + + + +instance computedExecutionLaw_probability (source target : List ℕ) (N : ℕ) : + IsProbabilityMeasure (computedExecutionLaw source target N) := by + unfold computedExecutionLaw + infer_instance + + + + theorem computedExecutionProjection_measurable (source target : List ℕ) (N : ℕ) : + Measurable (computedExecutionProjection source target N) := + physicalCoarseExecutionProjection_measurable source target N (integerParameters N).P + (inputHeight N) (integerParameters N).B (computedPhysicalCoarseDepth source target N) + + theorem computedExecutionProjection_law (source target : List ℕ) (N : ℕ) : + (computedExecutionLaw source target N).map (computedExecutionProjection source target N) = + physicalFamilyRuntimeLaw (R := inputHeight N ^ 2) target N (integerParameters N).P + (inputHeight N) (physicalCoarseSeedLaw (M := (integerParameters N).M) + (J := intervalTreeDepth (integerParameters N).M source.length) source target N (integerParameters N).B + (computedPhysicalCoarseDepth source target N)) := + physicalCoarseExecutionProjection_law source target N (integerParameters N).P + (inputHeight N) (integerParameters N).B (computedPhysicalCoarseDepth source target N) + + + +instance computedFullOutcome_measurableSingleton (source target : List ℕ) (N : ℕ) : + MeasurableSingletonClass (ComputedFullOutcome source target N) := by + refine ⟨fun outcome => ?_⟩ + exact measurableSet_sum_iff.mpr + ⟨(Set.to_countable _).measurableSet, (Set.to_countable _).measurableSet⟩ + + + +instance computedFullLaw_probability (source target : List ℕ) (N : ℕ) (epsilon : BinaryFraction) : + IsProbabilityMeasure (computedFullLaw source target N epsilon) := by + classical + unfold computedFullLaw + split <;> infer_instance + +noncomputable def computedFullProjection (source target : List ℕ) (N : ℕ) : + ComputedFullOutcome source target N → ComputedPhysicalOutcome source target N + | .inl _ => .inl () + | .inr execution => .inr (computedExecutionProjection source target N execution) + + theorem computedFullProjection_measurable (source target : List ℕ) (N : ℕ) : + Measurable (computedFullProjection source target N) := by + apply measurable_fun_sum + · exact measurable_const + · exact measurable_inr.comp (computedExecutionProjection_measurable source target N) + +noncomputable def computedFullAnswer (source target : List ℕ) (N : ℕ) + (outcome : ComputedFullOutcome source target N) : ℕ := + computedPhysicalAnswer source target N (computedFullProjection source target N outcome) + + theorem computedFullProjection_law (source target : List ℕ) (N : ℕ) (epsilon : BinaryFraction) : + (computedFullLaw source target N epsilon).map (computedFullProjection source target N) = + computedPhysicalLaw source target N epsilon := by + unfold computedFullLaw computedPhysicalLaw physicalUniformLaw + split_ifs with hlarge + · rw [Measure.map_map (computedFullProjection_measurable source target N) measurable_inr] + have heq : computedFullProjection source target N ∘ Sum.inr = + Sum.inr ∘ computedExecutionProjection source target N := rfl + rw [heq, ← Measure.map_map measurable_inr (computedExecutionProjection_measurable source target N), + computedExecutionProjection_law] + · rw [Measure.map_dirac] + rfl + + theorem computedFullAnswer_equal (source target : List ℕ) (N : ℕ) (heq : source = target) + (outcome : ComputedFullOutcome source target N) : computedFullAnswer source target N outcome = 0 := + computedPhysicalAnswer_equal source target N heq _ + + + theorem computed_full_conditional_accuracy (source target : List ℕ) (N : ℕ) + (epsilon : BinaryFraction) (hepsilon : 0 < epsilon.value) + (hsize : source.length + target.length ≤ N) + (coarseBernstein : FiniteBernsteinInput (Measure.pi fun _ : Fin (integerParameters N).B => + (PMF.uniformOfFintype (Fin (integerParameters N).B)).toMeasure)) + (groupBernstein : ∀ b : ℕ, ∀ h : Fin + (groupDyadicScales (integerParameters N).M b (inputSmallLog N)).length, + FiniteBernsteinInput (Measure.pi fun _ : Fin + (groupSampleCount (integerParameters N).M (inputSmallLog N ^ 80) b + (groupDyadicScaleAt (integerParameters N).M b (inputSmallLog N) h)) => + (PMF.uniformOfFintype (Fin (integerParameters N).M)).toMeasure)) : + (2 / 3 : ℝ) ≤ (computedFullLaw source target N epsilon).real + {outcome | EditDistortion.edit source target ≤ computedFullAnswer source target N outcome ∧ + (computedFullAnswer source target N outcome : ℝ) ≤ + (1 + (epsilon.value : ℝ)) * EditDistortion.edit source target} := by + have h := computed_physical_uniform_conditional_accuracy source target N epsilon hepsilon hsize + coarseBernstein groupBernstein + rw [← computedFullProjection_law source target N epsilon, + map_measureReal_apply (computedFullProjection_measurable source target N) + (Set.to_countable _).measurableSet] at h + exact h + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedExecutionWork.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedExecutionWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..169def8b834ac140284236b3fc6f3a7fa68b4445 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedExecutionWork.lean @@ -0,0 +1,69 @@ +import OAI.Combinatorics.EditApproximation.Refinement.ComputedExecutionLaw +import OAI.Combinatorics.EditApproximation.Refinement.ComputedRetainedValues +import OAI.Combinatorics.EditApproximation.Probability.FiniteProductWork +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation +open MeasureTheory Filter + + + + + + theorem computedFamilyRejectionWork_integrable (source target : List ℕ) (N : ℕ) + (seed : ComputedFamilySeed source target N) : + Integrable (fun execution : ComputedRejectionRuntime source target N => + computedFamilyRejectionWork source target N (seed, execution)) + (rejectionRuntimeArrayLaw (physicalFamilyRange (M := (integerParameters N).M) + (J := intervalTreeDepth (integerParameters N).M source.length) (R := inputHeight N ^ 2) + target N (integerParameters N).P (inputSmallLog N) (40 * smallLogExponent N) + (inputHeight N) (inputSmallLog N ^ 80) (computedSeedPassCount N) (inputHeight N ^ 2))) := + physicalFamilyMemoBits_integrable source target N (integerParameters N).P + (integerParameters N).T (integerParameters N).S (inputHeight N) (Nat.two_pow_pos _) + (16384 * inputHeight N + 5) (computedFamilyMemoCode source target N (inputHeight N ^ 2)) + (finalTargetState target.length) seed + + theorem computedExecutionRejectionWork_expected_near_linear (epsilon : ℝ) (hepsilon : 0 < epsilon) : + ∀ᶠ N in atTop, ∀ source target : List ℕ, source.length + target.length ≤ N → + integral (computedExecutionLaw source target N) (computedExecutionRejectionWork source target N) ≤ + (N + 2 : ℝ) ^ (1 + epsilon) := by + filter_upwards [computedFamilyRejectionWork_expected_near_linear epsilon hepsilon] with N hN + intro source target hsize + let incoming := physicalCoarseSeedLaw (M := (integerParameters N).M) + (J := intervalTreeDepth (integerParameters N).M source.length) source target N + (integerParameters N).B (computedPhysicalCoarseDepth source target N) + have hmap := integral_map (μ := computedExecutionLaw source target N) + (computedExecutionProjection_measurable source target N).aemeasurable + (measurable_of_countable (computedFamilyRejectionWork source target N)).aestronglyMeasurable + rw [computedExecutionProjection_law] at hmap + change (∫ execution, computedFamilyRejectionWork source target N + (computedExecutionProjection source target N execution) ∂computedExecutionLaw source target N) ≤ _ + rw [← hmap] + apply finite_outer_expected_le incoming _ (computedFamilyRejectionWork source target N) + (computedFamilyRejectionWork_integrable source target N) _ + intro seed + exact hN source target hsize seed + + theorem computedExecution_requests_near_linear (epsilon : ℝ) (hepsilon : 0 < epsilon) : + ∀ᶠ N in atTop, ∀ source target : List ℕ, source.length + target.length ≤ N → + ∀ execution : ComputedExecutionOutcome source target N, + ((computedFamilyResult source target N (computedExecutionAccepted source target N execution)).requests : ℝ) ≤ + (N + 2 : ℝ) ^ (1 + epsilon) := by + filter_upwards [computedFamilyResult_requests_near_linear epsilon hepsilon] with N hN + intro source target hsize execution + exact hN source target hsize _ + + theorem computedExecution_retained_storage (source target : List ℕ) (N : ℕ) + (hN : 0 < N) (hell : 2 ^ 1000 ≤ inputSmallLog N) (hsize : source.length + target.length ≤ N) + (hB : Nat.size (localOnlineMassBound (integerParameters N).M (integerParameters N).P + (inputHeight N)) ≤ inputHeight N) (execution : ComputedExecutionOutcome source target N) : + (computedFamilyResult source target N (computedExecutionAccepted source target N execution)).memory.rationalStorage ≤ + (N + 2) ^ 65556 := + computedFamilyResult_retained_storage source target N hN hell hsize hB _ + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedFamilyEncoding.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedFamilyEncoding.lean new file mode 100644 index 0000000000000000000000000000000000000000..122287cd89ee7bbf9660cad1db69cc446a84c924 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedFamilyEncoding.lean @@ -0,0 +1,88 @@ +import OAI.Combinatorics.EditApproximation.Refinement.ComputedScalarCodeBits +import OAI.Combinatorics.EditApproximation.Geometry.SourceRankedEncoding +import OAI.Combinatorics.EditApproximation.Geometry.ChargedRequestSpace +import OAI.Combinatorics.EditApproximation.Geometry.SeedFactorSchedule + +namespace OAI + +namespace EditApproximation + + theorem computed_physicalFamilyCode_bound (N nx ny R : ℕ) + (hN : 0 < N) (hell : 2 ^ 1000 ≤ inputSmallLog N) (hnx : nx ≤ N) (hny : ny ≤ N) + (hR : R ≤ inputHeight N ^ 2) + (hB : Nat.size (localOnlineMassBound (integerParameters N).M (integerParameters N).P + (inputHeight N)) ≤ inputHeight N) + (target : List ℕ) (htarget : target.length = ny) + (key : PhysicalFamilyScalarKey (M := (integerParameters N).M) + (J := intervalTreeDepth (integerParameters N).M nx) (R := R) + target N (integerParameters N).P (inputSmallLog N) (40 * smallLogExponent N) + (inputHeight N) (inputSmallLog N ^ 80) (computedSeedPassCount N) (inputHeight N ^ 2)) : + physicalFamilyCode target N (integerParameters N).P (inputSmallLog N) (40 * smallLogExponent N) + (inputHeight N) (inputSmallLog N ^ 80) (computedSeedPassCount N) (inputHeight N ^ 2) key < + 2 ^ (16384 * inputHeight N + 4) := by + let H := inputHeight N + have hH : 2 ≤ H := (by omega : 2 ≤ inputSmallLog N).trans (computed_smallLog_le_height N) + have hlift {e : ℕ} (he : e ≤ 64 * H) : 2 ^ e ≤ 2 ^ (64 * H) := + Nat.pow_le_pow_right (by decide) he + have hp : computedSeedPassCount N + 1 ≤ 2 ^ (64 * H) := + ((Nat.add_le_add_right (computedSeedPassCount_le_height N hN hell) 1).trans + (Nat.lt_two_pow_self : H < 2 ^ H)).trans (hlift (by omega)) + have hc : H ^ 2 + 1 ≤ 2 ^ (64 * H) := by + have hh : H ^ 2 ≤ 2 ^ (2 * H) := by + calc + _ ≤ (2 ^ H) ^ 2 := Nat.pow_le_pow_left Nat.lt_two_pow_self.le 2 + _ = _ := by rw [← pow_mul]; congr 1; omega + calc + _ ≤ 2 ^ (2 * H) + 2 ^ (2 * H) := Nat.add_le_add hh Nat.one_le_two_pow + _ = 2 ^ (2 * H + 1) := by rw [pow_succ]; omega + _ ≤ _ := hlift (by omega) + have hscalar (scalar : PhysicalScalarKey (integerParameters N).M + (intervalTreeDepth (integerParameters N).M nx) N target.length (40 * smallLogExponent N) + (inputSmallLog N) (inputSmallLog N ^ 80) R + (localOnlineMassBound (integerParameters N).M (integerParameters N).P H)) : + physicalScalarCode scalar < 2 ^ (64 * (64 * H) + 1) := + computed_physicalScalarCode_bound N nx target.length R hN (by omega) hnx + (by omega) hR hB scalar + have h := physicalFamilyCode_bound (M := (integerParameters N).M) + (J := intervalTreeDepth (integerParameters N).M nx) (R := R) + target N (integerParameters N).P (inputSmallLog N) (40 * smallLogExponent N) H + (inputSmallLog N ^ 80) (computedSeedPassCount N) (H ^ 2) (64 * H) hp hc hscalar key + convert h using 1 + congr 1 + omega + + theorem mixedCode_lt_two_pow {σ κ : Type*} (sourceCode : σ → ℕ) (tableCode : κ → ℕ) + (b : ℕ) (hs : ∀ source, sourceCode source < 2 ^ b) + (ht : ∀ table, tableCode table < 2 ^ b) (key : Sum σ κ) : + SourceRanked.keyCode sourceCode tableCode key < 2 ^ (b + 1) := by + rw [pow_succ] + cases key with + | inl source => have h := hs source; change 2 * _ < _; omega + | inr table => have h := ht table; change 2 * _ + 1 < _; omega + + theorem computed_mixed_cache_nodes {κ : Type*} (N : ℕ) + (rank : κ → ℕ) (program : (key : κ) → FiniteQuery {child : κ // rank child < rank key}) + (encode : κ → ℕ) (key : κ) : + (rankedMemoEvaluate rank program (16384 * inputHeight N + 5) encode key .empty).memory.nodes + 1 ≤ + (N + 2) ^ 65542 := by + have hcache := rankedMemoEvaluate_nodes_bound rank program (16384 * inputHeight N + 5) encode key + apply hcache.trans + have h4 : 4 ≤ (N + 2) ^ 2 := by nlinarith [Nat.zero_le N] + have hbase : 2 ^ inputHeight N ≤ (N + 2) ^ 4 := by + apply (two_pow_inputHeight_le N).trans + calc + _ ≤ (N + 2) ^ 2 * (N + 2) ^ 2 := Nat.mul_le_mul_right _ h4 + _ = _ := by ring + calc + 2 ^ (16384 * inputHeight N + 5 + 1) = (2 ^ inputHeight N) ^ 16384 * 2 ^ 6 := by + rw [show 16384 * inputHeight N + 5 + 1 = inputHeight N * 16384 + 6 by omega, pow_add, pow_mul] + _ ≤ ((N + 2) ^ 4) ^ 16384 * (N + 2) ^ 6 := + Nat.mul_le_mul (Nat.pow_le_pow_left hbase _) (Nat.pow_le_pow_left (by omega) _) + _ = (N + 2) ^ (4 * 16384 + 6) := by + generalize (16384 : ℕ) = exponent + rw [← pow_mul, ← pow_add] + _ = (N + 2) ^ 65542 := congrArg (fun exponent : ℕ => (N + 2) ^ exponent) (by decide) + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedFamilyMemoCode.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedFamilyMemoCode.lean new file mode 100644 index 0000000000000000000000000000000000000000..5152ccda84f997e81a23aaedeb969859ffcea991 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedFamilyMemoCode.lean @@ -0,0 +1,52 @@ +import OAI.Combinatorics.EditApproximation.Refinement.ComputedFamilyEncoding +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation + + + + + + + + theorem computedFamilyMemoCode_injective (source target : List ℕ) (N R : ℕ) + (hN : 0 < N) (hell : 200 ≤ inputSmallLog N) : + Function.Injective (computedFamilyMemoCode source target N R) := by + have hM : 1 ≤ (integerParameters N).M := (by omega : 1 ≤ 2).trans + (computed_branching_bounds N hN hell).1 + exact SourceRanked.keyCode_injective _ _ + (physicalFamilyCode_injective target N (integerParameters N).P (inputSmallLog N) + (40 * smallLogExponent N) (inputHeight N) (inputSmallLog N ^ 80) + (computedSeedPassCount N) (inputHeight N ^ 2) hM) + (ChargedPhysicalRequest.code_injective hM) + + theorem computedFamilyMemoCode_fits (source target : List ℕ) (N R : ℕ) + (hN : 0 < N) (hell : 2 ^ 1000 ≤ inputSmallLog N) (hsize : source.length + target.length ≤ N) + (hR : R ≤ inputHeight N ^ 2) + (hB : Nat.size (localOnlineMassBound (integerParameters N).M (integerParameters N).P + (inputHeight N)) ≤ inputHeight N) + (key : Sum (ComputedFamilyScalarKey source target N R) (ComputedFamilyTableKey source target N)) : + computedFamilyMemoCode source target N R key < 2 ^ (16384 * inputHeight N + 5) := by + have hM : 1 ≤ (integerParameters N).M := (by omega : 1 ≤ 2).trans + (computed_branching_bounds N hN (by omega)).1 + have hH : 2 ≤ inputHeight N := (by omega : 2 ≤ inputSmallLog N).trans (computed_smallLog_le_height N) + have hpass : computedSeedPassCount N + 1 ≤ inputHeight N ^ 2 := by + have h := computedSeedPassCount_le_height N hN hell + nlinarith only [h, hH] + apply mixedCode_lt_two_pow _ _ (16384 * inputHeight N + 4) + · intro scalar + exact computed_physicalFamilyCode_bound N source.length target.length R hN hell + (by omega) (by omega) hR hB target rfl scalar + · intro table + have hb := computed_charged_request_bits_le N source.length target.length + (computedSeedPassCount N + 1) (inputHeight N ^ 2) hN (by omega) (by omega) (by omega) + hpass le_rfl + exact (ChargedPhysicalRequest.code_fits hM table).trans_le + (Nat.pow_le_pow_right (by decide) (hb.trans (by omega))) + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedFamilySampling.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedFamilySampling.lean new file mode 100644 index 0000000000000000000000000000000000000000..db6d2daa74473a7ed32d306705d62567bf718407 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedFamilySampling.lean @@ -0,0 +1,23 @@ +import OAI.Combinatorics.EditApproximation.Refinement.ComputedFamilyMemoCode +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalFamilySampling + +namespace OAI + +namespace EditApproximation + + theorem computedFamilyRange_bits_le (source target : List ℕ) (N R : ℕ) + (hB : Nat.size (localOnlineMassBound (integerParameters N).M (integerParameters N).P + (inputHeight N)) ≤ inputHeight N) + (key : ComputedFamilyScalarKey source target N R) : + rejectionBitCount (physicalFamilyRange target N (integerParameters N).P (inputSmallLog N) + (40 * smallLogExponent N) (inputHeight N) (inputSmallLog N ^ 80) + (computedSeedPassCount N) (inputHeight N ^ 2) key) ≤ inputHeight N := by + apply physicalFamilyRange_bits_le + · change 2 ^ (heightExponent N / 20) ≤ 2 ^ inputHeight N + apply Nat.pow_le_pow_right (by decide : 0 < (2 : ℕ)) + exact (Nat.div_le_self _ _).trans (Nat.lt_two_pow_self.le) + · exact (Nat.lt_size_self _).le.trans (Nat.pow_le_pow_right (by decide : 0 < (2 : ℕ)) hB) + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedFreshWork.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedFreshWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..f4c435517ecff1314fea82431b65ed588b465aa8 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedFreshWork.lean @@ -0,0 +1,17 @@ +import OAI.Combinatorics.EditApproximation.Geometry.RankedMemoKernelFresh +import OAI.Combinatorics.EditApproximation.Refinement.ComputedKernelWork + +namespace OAI + +namespace EditApproximation + +theorem computedFamilyKernelWork_eq_fresh_sum (source target : List ℕ) (N : ℕ) + (input : ComputedFamilyInput source target N) + (cost : ComputedFamilyMemoKey source target N → ℕ) : + computedFamilyKernelWork source target N input cost = + ((computedFamilyResult source target N input).freshKeys.map cost).sum := + rankedMemoKernelWork_eq_fresh_sum _ _ _ _ cost _ _ + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedGlobalSourceCost.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedGlobalSourceCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..00e90554aeaa5d1e725b692a264b973622faa716 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedGlobalSourceCost.lean @@ -0,0 +1,57 @@ +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalRandomGlobalQuery +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalRandomSourceCost +import OAI.Combinatorics.EditApproximation.Refinement.ComputedSourceReadBudget + +namespace OAI + +namespace EditApproximation + + theorem computed_physicalRandomGlobalQuery_source_cost {σ α : Type*} [DecidableEq α] + {M J R : ℕ} [NeZero M] [NeZero R] (source target : List α) + (N P H T S copies : ℕ) (hN : 0 < N) (hell : 200 ≤ inputSmallLog N) + (hM : M = (integerParameters N).M) (factor : ℕ → ℚ) (multiplier : ℕ → ℕ) + (tau eta kappa delta : ℚ) (hA : ∀ pass, factor pass ≤ ((integerParameters N).initialFactor : ℚ)) + (readGroup : ℕ → ℕ → PhysicalInternalNode M J → Fin R → + GroupScalarKey M (inputSmallLog N) (inputSmallLog N ^ 80) → FiniteQuery σ) + (readInteger : ℕ → ℕ → PhysicalInternalNode M J → Fin R → + (ℕ × TargetInterval target.length) → ℕ → FiniteQuery σ) + (initial : PhysicalEntry M J target.length → ℕ) (sourceAnswer : σ → ℚ) + (answer : PhysicalTableRequest M J target.length → ℚ) (weight : σ → ℕ) (bound : ℕ) + (hgroup : ∀ pass copy node time key, (readGroup pass copy node time key).cost sourceAnswer weight ≤ bound) + (honline : ∀ pass copy node time key range, + (readInteger pass copy node time key range).cost sourceAnswer weight ≤ bound) + (hpositive : ∀ pass copy node q, 0 ≤ answer (PhysicalTableRequest.warmup pass copy node 0 q)) + (request : PhysicalTableRequest M J target.length) : + (physicalRandomGlobalQuery source target N P (inputSmallLog N) (40 * smallLogExponent N) + H (inputSmallLog N ^ 80) T S copies factor multiplier tau eta kappa delta readGroup readInteger + initial request).cost (Sum.elim sourceAnswer (fun key => answer key.val)) + (Sum.elim weight (fun _ => 0)) ≤ inputHeight N ^ 91 * bound := by + unfold physicalRandomGlobalQuery + by_cases ha : T < request.index ∧ request.node.1.val < J ∧ + ¬ (physicalSourceInterval source.length request.node).hi - + (physicalSourceInterval source.length request.node).lo ≤ 1 + · rw [dite_eq_left ha, FiniteQuery.mapKeys_cost] + let node : PhysicalInternalNode M J := ⟨request.node, ha.2.1⟩ + let time : Fin R := Fin.ofNat R (request.index - T - 1) + have hlocal := physicalRandomDataRequest_source_cost_le source target N P (inputSmallLog N) + (40 * smallLogExponent N) H (inputSmallLog N ^ 80) tau + (refinementFactor (factor request.pass) (inputSmallLog N)) eta kappa delta + request.pass request.copy T S (request.index - T) (Nat.sub_pos_of_lt ha.1) + request.node ha.2.1 (readGroup request.pass request.copy node time) + (readInteger request.pass request.copy node time) request.state sourceAnswer answer weight bound bound + (hgroup request.pass request.copy node time) (honline request.pass request.copy node time) + have hkeys := computed_source_key_budget N P hN hell hM (factor request.pass) (hA _) + (fun r => answer (PhysicalTableRequest.warmup request.pass request.copy request.node 0 r)) + request.state (hpositive _ _ _ _) + have hbound := hlocal.trans (show _ ≤ inputHeight N ^ 91 * bound by + rw [← Nat.add_mul] + exact Nat.mul_le_mul_right bound hkeys) + convert hbound using 1 + congr 1 <;> (funext key; cases key <;> rfl) + · rw [dite_eq_right ha] + rw [FiniteQuery.mapRight_source_cost] + exact Nat.zero_le _ + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedGroupAccuracy.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedGroupAccuracy.lean new file mode 100644 index 0000000000000000000000000000000000000000..0aa213470608950d7bc8a705364b04ba759c060e --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedGroupAccuracy.lean @@ -0,0 +1,101 @@ +import OAI.Combinatorics.EditApproximation.Geometry.CellGroupSelection +import OAI.Combinatorics.EditApproximation.Refinement.ComputedGroupNumerical +import OAI.Combinatorics.EditApproximation.Refinement.ComputedBandSpacing + +namespace OAI + +/-! One actual whole cell has simultaneous gamma*b accuracy with failure at most H^-4. -/ + +namespace EditApproximation + +open MeasureTheory ProbabilityTheory + +theorem computed_cellGroupEstimate_failure {α : Type*} (source target : List α) + (N : ℕ) (hN : 0 < N) (hell : 1764 ≤ inputSmallLog N) + {M P b Q thetaExponent T : ℕ} [NeZero M] + [MeasurableSpace (Fin M)] [MeasurableSingletonClass (Fin M)] + (hM : 0 < M) (hMeq : M = (integerParameters N).M) + (hPeq : P = (integerParameters N).P) (eb : ℕ) (hbeq : b = 2 ^ eb) + (hQeq : Q = inputSmallLog N ^ 80) (hthetaeq : thetaExponent = 40 * smallLogExponent N) + (parent : TargetInterval source.length) (a : ℚ) + (parentInitial : TargetInterval target.length → ℚ) + (child initial value : Fin M → TargetInterval target.length → ℚ) (cell : ℕ × ℕ) + (scales : Fin T → ℚ) (count : Fin T → ℕ) + (hscales : List.ofFn scales = groupDyadicScales M b (inputSmallLog N)) + (hcount : ∀ scale, count scale = groupSampleCount M Q b (scales scale)) + (hspatial : ∀ i s t, initial i s ≤ initial i t + + (32 * inputSmallLog N : ℚ) * targetEndpointDistance s t) + (hvalue : ∀ i s, 0 ≤ value i s ∧ value i s ≤ initial i s) + (bernstein : ∀ scale : Fin T, FiniteBernsteinInput + (Measure.pi fun _ : Fin (count scale) => (PMF.uniformOfFintype (Fin M)).toMeasure)) : + let members := cellUnskippedBands source target parent b P (inputSmallLog N) thetaExponent + (rationalParameters (inputSmallLog N)).tau a parentInitial child initial cell + (groupSharedDrawLaw count).real + {draw | ∃ member ∈ members, ((rationalParameters (inputSmallLog N)).gamma : ℝ) * b < + |((unskippedGroupEstimate scales count value member draw - + rationalEndpointActionValue member.center member.rounded value : ℚ) : ℝ)|} ≤ + 1 / (inputHeight N : ℝ) ^ 4 := by + let ell := inputSmallLog N + let members := cellUnskippedBands source target parent b P ell thetaExponent + (rationalParameters ell).tau a parentInitial child initial cell + let deviation : ℚ := 1 / (2 * (ell : ℚ) ^ 21) + let μ := groupSharedDrawLaw (M := M) count + let : IsProbabilityMeasure μ := by dsimp only [μ]; infer_instance + have hellQ : (2 : ℚ) ≤ ell := by exact_mod_cast (show 2 ≤ ell from by omega) + have hellpos : (0 : ℚ) < ell := by linarith only [hellQ] + have hb : 0 < b := hbeq ▸ Nat.two_pow_pos eb + have hQ : 0 < Q := by rw [hQeq]; exact pow_pos (by omega : 0 < inputSmallLog N) 80 + have htheta : (2 : ℚ) ^ (-(thetaExponent : ℤ)) = 1 / (ell : ℚ) ^ 40 := by + rw [hthetaeq] + exact (computed_theta_dyadic N).symm + have hsmall : 2 * (32 * ell : ℚ) * (2 : ℚ) ^ (-(thetaExponent : ℤ)) ≤ 1 := by + rw [htheta] + have h := (basic_band_small_constants hellQ).2.2.2.2 + convert h using 1 + ring + have hdev : 0 < deviation := by dsimp only [deviation]; positivity + have htail := unskippedGroupEstimate_failure scales count Q hscales hcount value members hM hQ hb + hellpos (32 * ell) (mul_nonneg (by norm_num) (Nat.cast_nonneg _)) hsmall hspatial hvalue deviation hdev bernstein + have hT : T ≤ 2 * ell := by + have hlength := congrArg List.length hscales + simp only [List.length_ofFn] at hlength + rw [hlength, hMeq, hbeq] + exact computed_group_scale_count N eb hN (by omega) + have hTQ : (T : ℚ) ≤ 2 * ell := by exact_mod_cast hT + have hbudget : (T : ℚ) * deviation ≤ (rationalParameters ell).gamma := by + have h := mul_le_mul_of_nonneg_right hTQ hdev.le + have hid : (2 * ell : ℚ) * deviation = (rationalParameters ell).gamma := by + dsimp only [deviation, rationalParameters] + field_simp + exact h.trans_eq hid + have hbudgetR : (T : ℝ) * (deviation : ℝ) * b ≤ + ((rationalParameters ell).gamma : ℝ) * b := by + have h := mul_le_mul_of_nonneg_right hbudget (Nat.cast_nonneg (α := ℚ) b) + exact_mod_cast h + have hsubset : {draw | ∃ member ∈ members, ((rationalParameters ell).gamma : ℝ) * b < + |((unskippedGroupEstimate scales count value member draw - + rationalEndpointActionValue member.center member.rounded value : ℚ) : ℝ)|} ⊆ + {draw | ∃ member ∈ members, (T : ℝ) * (deviation : ℝ) * b < + |((unskippedGroupEstimate scales count value member draw - + rationalEndpointActionValue member.center member.rounded value : ℚ) : ℝ)|} := by + rintro draw ⟨member, hm, he⟩ + exact ⟨member, hm, hbudgetR.trans_lt he⟩ + have hmembers : members.length ≤ ((integerParameters N).P + 1) ^ 2 := by + rw [← hPeq] + exact cellUnskippedBands_length_le source target parent b P ell thetaExponent _ a parentInitial + child initial cell ⟨eb, hbeq⟩ ⟨_, hPeq.trans (computed_P_dyadic N)⟩ + have hnumerical := computed_group_union_failure N eb members.length hN hell hmembers + dsimp only at hnumerical + have hTeq : T = (groupDyadicScales (integerParameters N).M (2 ^ eb) ell).length := by + have hlength := congrArg List.length hscales + simpa only [List.length_ofFn, hMeq, hbeq] using hlength + change μ.real _ ≤ _ + apply (measureReal_mono hsubset (measure_ne_top μ _)).trans + apply htail.trans + rw [hQeq, hTeq] + simpa only [deviation, ell, Rat.cast_div, Rat.cast_mul, Rat.cast_ofNat, Rat.cast_pow, + Rat.cast_natCast, Rat.cast_one, Nat.cast_pow, neg_mul, neg_div] using hnumerical + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedGroupNumerical.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedGroupNumerical.lean new file mode 100644 index 0000000000000000000000000000000000000000..862e2e62f97cb56fd68a540572c0203c285c4747 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedGroupNumerical.lean @@ -0,0 +1,100 @@ +import OAI.Combinatorics.EditApproximation.Geometry.GroupNumerical +import OAI.Combinatorics.EditApproximation.Geometry.BandGroupSampling + +namespace OAI + +/-! Computed parameters discharge the group scale-count and H^-4 tail bounds. -/ + +namespace EditApproximation + +theorem computed_group_scale_count (N eb : ℕ) (hN : 0 < N) (hell : 8 ≤ inputSmallLog N) : + (groupDyadicScales (integerParameters N).M (2 ^ eb) (inputSmallLog N)).length ≤ + 2 * inputSmallLog N := by + have hlogs := (inputSmallLog_bounds N hN).1 + have hsmall : smallLogExponent N ≤ inputSmallLog N := + (smallLogExponent N).lt_two_pow_self.le + have hdiv := Nat.div_le_div_right (c := 20) hlogs + change (groupDyadicScales (2 ^ (heightExponent N / 20)) (2 ^ eb) + ((2 ^ smallLogExponent N : ℕ) : ℚ)).length ≤ _ + rw [Nat.cast_pow, Nat.cast_ofNat, groupDyadicScales_length_dyadic] + omega + +theorem computed_height_exp_upper (N : ℕ) (hN : 0 < N) : + (inputHeight N : ℝ) ≤ Real.exp (inputSmallLog N) := by + change ((2 ^ heightExponent N : ℕ) : ℝ) ≤ _ + rw [Nat.cast_pow, Nat.cast_ofNat] + have htwo : (2 : ℝ) ≤ Real.exp 1 := by + simpa only [one_add_one_eq_two] using Real.add_one_le_exp (1 : ℝ) + have hpower := pow_le_pow_left₀ (by norm_num : (0 : ℝ) ≤ 2) htwo (heightExponent N) + rw [← Real.exp_nat_mul, mul_one] at hpower + have hlogs : (heightExponent N : ℝ) ≤ inputSmallLog N := by + exact_mod_cast (inputSmallLog_bounds N hN).1 + exact hpower.trans (Real.exp_le_exp.mpr hlogs) + +theorem computed_group_member_exp_bound (N : ℕ) (hN : 0 < N) + (hell : 1764 ≤ inputSmallLog N) : + (((integerParameters N).P + 1 : ℕ) : ℝ) ^ 2 ≤ + 4 * Real.exp (2 * (inputSmallLog N : ℝ) ^ 2) := by + let ell := inputSmallLog N + let p := coarseExponent ell + have hp := coarseExponent_shift_square ell hell + have hp0 : (0 : ℝ) ≤ p := Nat.cast_nonneg _ + have hpell : (p : ℝ) + 20 ≤ ell := by + change ((p : ℝ) + 21) ^ 2 ≤ ell at hp + nlinarith only [hp, hp0] + have hell0 : (0 : ℝ) ≤ ell := Nat.cast_nonneg _ + have hP : ((integerParameters N).P : ℝ) ≤ Real.exp ((ell : ℝ) ^ 2) := by + change ((inputHeight N ^ (p + 20) : ℕ) : ℝ) ≤ _ + rw [Nat.cast_pow] + have h := pow_le_pow_left₀ (Nat.cast_nonneg (inputHeight N)) + (computed_height_exp_upper N hN) (p + 20) + rw [← Real.exp_nat_mul] at h + have hexponent : ((p + 20 : ℕ) : ℝ) * ell ≤ (ell : ℝ) ^ 2 := by + push_cast + nlinarith only [hpell, hell0] + exact h.trans (Real.exp_le_exp.mpr hexponent) + have hPone : (1 : ℝ) ≤ (integerParameters N).P := by + have hNat : 1 ≤ (integerParameters N).P := + one_le_pow₀ (Nat.one_le_two_pow (n := heightExponent N)) + exact_mod_cast hNat + have hplus : (((integerParameters N).P + 1 : ℕ) : ℝ) ≤ 2 * Real.exp ((ell : ℝ) ^ 2) := by + push_cast + linarith only [hP, hPone] + have hsquare := pow_le_pow_left₀ (Nat.cast_nonneg ((integerParameters N).P + 1)) hplus 2 + rw [mul_pow, ← Real.exp_nat_mul] at hsquare + norm_num only [Nat.cast_ofNat] at hsquare + exact hsquare + +theorem computed_group_union_failure (N eb members : ℕ) (hN : 0 < N) + (hell : 1764 ≤ inputSmallLog N) + (hmembers : members ≤ ((integerParameters N).P + 1) ^ 2) : + let ell := inputSmallLog N + let T := (groupDyadicScales (integerParameters N).M (2 ^ eb) ell).length + (members : ℝ) * T * + (2 * Real.exp (-((ell : ℝ) ^ 80 * (1 / (2 * (ell : ℝ) ^ 21)) ^ 2 / + (512 * ell + (4 / 3 : ℝ) * (1 / (2 * (ell : ℝ) ^ 21)))))) ≤ + 1 / (inputHeight N : ℝ) ^ 4 := by + dsimp only + let ell := inputSmallLog N + let T := (groupDyadicScales (integerParameters N).M (2 ^ eb) ell).length + have hellR : (8 : ℝ) ≤ ell := by exact_mod_cast (show 8 ≤ ell from by omega) + have hcount : (members : ℝ) ≤ 4 * Real.exp (2 * (ell : ℝ) ^ 2) := by + have hcast : (members : ℝ) ≤ (((integerParameters N).P + 1 : ℕ) : ℝ) ^ 2 := by + exact_mod_cast hmembers + exact hcast.trans (computed_group_member_exp_bound N hN hell) + have hscale : (T : ℝ) ≤ 2 * ell := by + exact_mod_cast computed_group_scale_count N eb hN (by omega) + have hnum := group_union_failure_numeric hellR + (by exact_mod_cast Nat.two_pow_pos (heightExponent N) : (0 : ℝ) < inputHeight N) + (computed_height_exp_upper N hN) (Nat.cast_nonneg members) hcount (Nat.cast_nonneg T) hscale + have hexponent := group_normalized_exponent (show (1 : ℝ) ≤ ell from by linarith only [hellR]) + have hexp : Real.exp (-((ell : ℝ) ^ 80 * (1 / (2 * (ell : ℝ) ^ 21)) ^ 2 / + (512 * ell + (4 / 3 : ℝ) * (1 / (2 * (ell : ℝ) ^ 21))))) ≤ + Real.exp (-((ell : ℝ) ^ 37 / 3000)) := + Real.exp_le_exp.mpr (neg_le_neg hexponent) + exact (mul_le_mul_of_nonneg_left (mul_le_mul_of_nonneg_left hexp (by norm_num : (0 : ℝ) ≤ 2)) + (mul_nonneg (Nat.cast_nonneg members) (Nat.cast_nonneg T))).trans hnum + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedIndexedCoarseWork.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedIndexedCoarseWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..62555cfd065772fb507ddc7a0bb7f07ca4c7e68b --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedIndexedCoarseWork.lean @@ -0,0 +1,146 @@ +import OAI.Combinatorics.EditApproximation.Refinement.ComputedCoarseBitWork +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalIndexedCoarseWork +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation +open Filter MeasureTheory + +section Symbolic +variable {M J R B : ℕ} [NeZero M] [NeZero R] [NeZero B] + (source target : List ℕ) (N : ℕ) + (depth : PhysicalEntry M J target.length → ℕ) + (encode : Sum (PhysicalFamilyScalarKey (M := M) (J := J) (R := R) + target N (integerParameters N).P (inputSmallLog N) (40 * smallLogExponent N) + (inputHeight N) (inputSmallLog N ^ 80) (computedSeedPassCount N) (inputHeight N ^ 2)) + (ChargedPhysicalRequest M J target.length (computedSeedPassCount N + 1) + (inputHeight N ^ 2) (integerParameters N).T (integerParameters N).S) → ℕ) + + + +theorem symbolicComputedExecutionIndexedCoarseWork_integrable : + Integrable (symbolicComputedExecutionIndexedCoarseWork source target N depth encode) + (physicalCoarseExecutionLaw (R := R) source target N (integerParameters N).P + (inputHeight N) B depth) := by + let μ := coarseFullSeedMeasure B depth + (fun entry => physicalSource source entry.1) + (fun entry => substring target entry.2.lo entry.2.hi) + let range := physicalFamilyRange (M := M) (J := J) (R := R) + target N (integerParameters N).P (inputSmallLog N) (40 * smallLogExponent N) + (inputHeight N) (inputSmallLog N ^ 80) (computedSeedPassCount N) (inputHeight N ^ 2) + let f := fun outcome : PhysicalCoarseDraw source target B depth × (∀ key, Fin (range key)) => + symbolicComputedExecutionIndexedCoarseWork source target N depth encode + (outcome.1, (fun _ => 0, outcome.2)) + have hf : Integrable f ((μ.prod (rejectionRuntimeArrayLaw range)).map + (rejectionProductAccepted range)) := by + rw [rejectionProductAccepted_law] + exact Integrable.of_finite + exact hf.comp_measurable (rejectionProductAccepted_measurable range) +theorem symbolicComputedExecutionIndexedCoarseWork_bound + (hcost : ∀ B d : ℕ, ∀ x y : List ℕ, + B = (integerParameters N).B → d = computedCoarseDepth N (coarseEntryWidth x y) → + coarseEntryWidth x y ≤ N → (∀ a ∈ x ++ y, Nat.size a ≤ inputHeight N ^ 3) → + ∀ (_hB : NeZero B) (draw : CoarseGuessIndex (coarseEntryWidth x y) → CoarseThresholdDraws B d), + (coarseIndexedEntryBinaryCost N B d x y draw : ℝ) ≤ (inputHeight N : ℝ) ^ 40 * + ((coarseInitialArrayWork B d (initialThresholdQ N) (initialLambda N) x y draw : ℝ) + + (x.length + 1 : ℕ))) + (hB : B = (integerParameters N).B) + (hdepth : ∀ entry, depth entry = computedCoarseDepth N + (coarseEntryWidth (physicalSource source entry.1) (substring target entry.2.lo entry.2.hi))) + (hsize : source.length + target.length ≤ N) + (hsymbols : ∀ a ∈ source ++ target, Nat.size a ≤ inputHeight N ^ 3) + (execution : PhysicalCoarseExecution (R := R) source target N + (integerParameters N).P (inputHeight N) B depth) : + symbolicComputedExecutionIndexedCoarseWork source target N depth encode execution ≤ + (inputHeight N : ℝ) ^ 40 * + (symbolicComputedExecutionCoarseWork source target N depth encode execution + + physicalFamilyCoarseInputWork source target N (integerParameters N).P (inputHeight N) + (integerParameters N).T (integerParameters N).S (computedSeedPassCount N) + (inputHeight N ^ 2) (scheduledSeedFactor N) (scheduledSeedMultiplier N) + (rationalParameters (inputSmallLog N)).tau (rationalParameters (inputSmallLog N)).eta + (rationalParameters (inputSmallLog N)).kappa (rationalParameters (inputSmallLog N)).delta + (clampedSeedNat (physicalCoarseSeedTable source target N B depth execution.1)) execution.2.2 + (16384 * inputHeight N + 5) encode + (localFinalRootRequest target N (integerParameters N).T (integerParameters N).S + (inputHeight N) (Nat.two_pow_pos _) (finalTargetState target.length))) := by + apply physicalFamilyIndexedCoarseWork_bound + intro entry + have hx := physicalSource_length_le source entry.1 + have hy : (substring target entry.2.lo entry.2.hi).length ≤ target.length := by + simp only [substring, List.length_drop, List.length_take] + exact (Nat.sub_le _ _).trans (min_le_right _ _) + have hxy : coarseEntryWidth (physicalSource source entry.1) + (substring target entry.2.lo entry.2.hi) ≤ N := max_le (by omega) (by omega) + have hsy : ∀ a ∈ physicalSource source entry.1 ++ substring target entry.2.lo entry.2.hi, + Nat.size a ≤ inputHeight N ^ 3 := by + intro a ha + rcases List.mem_append.mp ha with ha | ha + · exact hsymbols a (List.mem_append_left _ (physicalSource_mem source entry.1 a ha)) + · exact hsymbols a (List.mem_append_right _ + (List.mem_of_mem_take (List.mem_of_mem_drop ha))) + exact hcost B (depth entry) _ _ hB (hdepth entry) hxy hsy inferInstance (execution.1 entry) +end Symbolic + + + +theorem computedExecutionIndexedCoarseWork_bound : + ∀ᶠ N : ℕ in atTop, ∀ source target : List ℕ, source.length + target.length ≤ N → + (∀ a ∈ source ++ target, Nat.size a ≤ inputHeight N ^ 3) → + ∀ execution : ComputedExecutionOutcome source target N, + computedExecutionIndexedCoarseWork source target N execution ≤ + (inputHeight N : ℝ) ^ 40 * (computedExecutionCoarseWork source target N execution + + computedExecutionCoarseInputWork source target N execution) := by + filter_upwards [coarseIndexedEntryBinaryCost_computed_bound] with N hN + intro source target hsize hsymbols execution + exact symbolicComputedExecutionIndexedCoarseWork_bound source target N + (computedPhysicalCoarseDepth source target N) (computedFamilyMemoCode source target N (inputHeight N ^ 2)) + hN rfl (fun _ => rfl) hsize hsymbols execution + +theorem computedExecutionIndexedCoarseWork_integrable (source target : List ℕ) (N : ℕ) : + Integrable (computedExecutionIndexedCoarseWork source target N) (computedExecutionLaw source target N) := + symbolicComputedExecutionIndexedCoarseWork_integrable source target N + (computedPhysicalCoarseDepth source target N) (computedFamilyMemoCode source target N (inputHeight N ^ 2)) + +theorem computedExecutionIndexedCoarseWork_expected_near_linear (epsilon : ℝ) (hepsilon : 0 < epsilon) : + ∀ᶠ N in atTop, ∀ source target : List ℕ, source.length + target.length ≤ N → + (∀ a ∈ source ++ target, Nat.size a ≤ inputHeight N ^ 3) → + (∫ execution, computedExecutionIndexedCoarseWork source target N execution + ∂computedExecutionLaw source target N) ≤ (N + 2 : ℝ) ^ (1 + epsilon) := by + have he : 0 < epsilon / 3 := by positivity + filter_upwards [computedExecutionIndexedCoarseWork_bound, + computedExecutionCoarseWork_expected_near_linear (epsilon / 3) he, + computedExecutionCoarseInputWork_expected_near_linear (epsilon / 3) he, + fixed_height_power_subpolynomial 40 (epsilon / 3) he, + constant_le_rpow_eventually 2 (epsilon / 3) he] with N hb hc hi hp ht + intro source target hsize hsymbols + let μ := computedExecutionLaw source target N + have hic := computedExecutionCoarseWork_integrable source target N + have hii := computedExecutionCoarseInputWork_integrable source target N + have hbound : (∫ execution, computedExecutionIndexedCoarseWork source target N execution ∂μ) ≤ + (inputHeight N : ℝ) ^ 40 * ((∫ execution, computedExecutionCoarseWork source target N execution ∂μ) + + ∫ execution, computedExecutionCoarseInputWork source target N execution ∂μ) := by + calc + _ ≤ ∫ execution, (inputHeight N : ℝ) ^ 40 * + (computedExecutionCoarseWork source target N execution + + computedExecutionCoarseInputWork source target N execution) ∂μ := + integral_mono (computedExecutionIndexedCoarseWork_integrable source target N) + ((hic.add hii).const_mul _) (hb source target hsize hsymbols) + _ = _ := by rw [integral_const_mul, integral_add hic hii] + have hsum := add_le_add (hc source target hsize) (hi source target hsize) + calc + _ ≤ (inputHeight N : ℝ) ^ 40 * (2 * (N + 2 : ℝ) ^ (1 + epsilon / 3)) := + hbound.trans (mul_le_mul_of_nonneg_left (by linarith only [hsum]) (by positivity)) + _ ≤ (N + 2 : ℝ) ^ (epsilon / 3) * (2 * (N + 2 : ℝ) ^ (1 + epsilon / 3)) := + mul_le_mul_of_nonneg_right hp (by positivity) + _ ≤ (N + 2 : ℝ) ^ (epsilon / 3) * + ((N + 2 : ℝ) ^ (epsilon / 3) * (N + 2 : ℝ) ^ (1 + epsilon / 3)) := by gcongr + _ = _ := by + rw [← Real.rpow_add (by positivity), ← Real.rpow_add (by positivity)] + congr 1 + ring + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedJointCoarseWork.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedJointCoarseWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..315259000aa09628497a0d09052c472cee665fd5 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedJointCoarseWork.lean @@ -0,0 +1,71 @@ +import OAI.Combinatorics.EditApproximation.Refinement.ComputedPhysicalCoarseWork +import OAI.Combinatorics.EditApproximation.Refinement.ComputedExecutionLaw +import OAI.Combinatorics.EditApproximation.Probability.FiniteProductWork +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation +open MeasureTheory Filter + +section Symbolic +variable {M J R B : ℕ} [NeZero M] [NeZero R] [NeZero B] + (source target : List ℕ) (N : ℕ) + (depth : PhysicalEntry M J target.length → ℕ) + (encode : Sum (PhysicalFamilyScalarKey (M := M) (J := J) (R := R) + target N (integerParameters N).P (inputSmallLog N) (40 * smallLogExponent N) + (inputHeight N) (inputSmallLog N ^ 80) (computedSeedPassCount N) (inputHeight N ^ 2)) + (ChargedPhysicalRequest M J target.length (computedSeedPassCount N + 1) + (inputHeight N ^ 2) (integerParameters N).T (integerParameters N).S) → ℕ) + + + + theorem symbolicComputedExecutionCoarseWork_expected_le (budget : ℝ) + (hbudget : SymbolicComputedCoarseBudget (B := B) source target N depth encode budget) : + (∫ execution, symbolicComputedExecutionCoarseWork source target N depth encode execution + ∂physicalCoarseExecutionLaw (R := R) source target N (integerParameters N).P + (inputHeight N) B depth) ≤ budget := by + exact rejectionProductWork_expected_le _ _ + (fun outcome => symbolicComputedCoarseWork source target N depth encode outcome.2 outcome.1) + budget hbudget + + theorem symbolicComputedExecutionCoarseWork_integrable : + Integrable (symbolicComputedExecutionCoarseWork source target N depth encode) + (physicalCoarseExecutionLaw (R := R) source target N (integerParameters N).P + (inputHeight N) B depth) := by + let μ := coarseFullSeedMeasure B depth + (fun entry => physicalSource source entry.1) + (fun entry => substring target entry.2.lo entry.2.hi) + let range := physicalFamilyRange (M := M) (J := J) (R := R) + target N (integerParameters N).P (inputSmallLog N) (40 * smallLogExponent N) + (inputHeight N) (inputSmallLog N ^ 80) (computedSeedPassCount N) (inputHeight N ^ 2) + let f := fun outcome : PhysicalCoarseDraw source target B depth × (∀ key, Fin (range key)) => + symbolicComputedCoarseWork source target N depth encode outcome.2 outcome.1 + have hf : Integrable f ((μ.prod (rejectionRuntimeArrayLaw range)).map + (rejectionProductAccepted range)) := by + rw [rejectionProductAccepted_law] + exact Integrable.of_finite + exact hf.comp_measurable (rejectionProductAccepted_measurable range) +end Symbolic + + + + theorem computedExecutionCoarseWork_integrable (source target : List ℕ) (N : ℕ) : + Integrable (computedExecutionCoarseWork source target N) (computedExecutionLaw source target N) := + symbolicComputedExecutionCoarseWork_integrable source target N + (computedPhysicalCoarseDepth source target N) (computedFamilyMemoCode source target N (inputHeight N ^ 2)) + + theorem computedExecutionCoarseWork_expected_near_linear (epsilon : ℝ) (hepsilon : 0 < epsilon) : + ∀ᶠ N in atTop, ∀ source target : List ℕ, source.length + target.length ≤ N → + (∫ execution, computedExecutionCoarseWork source target N execution + ∂computedExecutionLaw source target N) ≤ (N + 2 : ℝ) ^ (1 + epsilon) := by + filter_upwards [computedPhysicalCoarseWork_expected_near_linear epsilon hepsilon] with N hN + intro source target hsize + exact symbolicComputedExecutionCoarseWork_expected_le source target N + (computedPhysicalCoarseDepth source target N) (computedFamilyMemoCode source target N (inputHeight N ^ 2)) + _ (hN source target hsize) + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedKernelWork.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedKernelWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..48753b20a144280c5e28f5856b67f6e2872694bd --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedKernelWork.lean @@ -0,0 +1,43 @@ +import OAI.Combinatorics.EditApproximation.Geometry.RankedMemoKernelWork +import OAI.Combinatorics.EditApproximation.Refinement.ComputedLocalKernelWork +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation +open Filter + + + +/-- Local arithmetic annotations follow the actual memo run, hence are +incurred once per cache miss, with the original program and draw values. -/ + + +theorem computedFamilyKernelWork_le (source target : List ℕ) (N : ℕ) + (input : ComputedFamilyInput source target N) + (cost : ComputedFamilyMemoKey source target N → ℕ) (C : ℕ) + (hcost : ∀ key, cost key ≤ C) : + computedFamilyKernelWork source target N input cost ≤ + C * (computedFamilyResult source target N input).requests := + rankedMemoKernelWork_le _ _ _ _ cost C hcost _ _ + +theorem computedFamilyKernelWork_near_linear (D : ℕ) (epsilon : ℝ) (hepsilon : 0 < epsilon) : + ∀ᶠ N in atTop, ∀ source target : List ℕ, source.length + target.length ≤ N → + ∀ (input : ComputedFamilyInput source target N) + (cost : ComputedFamilyMemoKey source target N → ℕ), + (∀ key, cost key ≤ computedLocalKernelBudget D N) → + (computedFamilyKernelWork source target N input cost : ℝ) ≤ + (N + 2 : ℝ) ^ (1 + epsilon) := by + filter_upwards [computedLocalKernelBudget_requests_near_linear D epsilon hepsilon] with N hN + intro source target hsize input cost hcost + have h := computedFamilyKernelWork_le source target N input cost + (computedLocalKernelBudget D N) hcost + have hr : (computedFamilyKernelWork source target N input cost : ℝ) ≤ + (computedLocalKernelBudget D N : ℝ) * (computedFamilyResult source target N input).requests := by + exact_mod_cast h + exact hr.trans (by simpa only [mul_comm] using hN source target hsize input) + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedLocalKernelWork.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedLocalKernelWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..c9fad13f316a48bb49cc3ec4e24066efe410bc86 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedLocalKernelWork.lean @@ -0,0 +1,100 @@ +import OAI.Combinatorics.EditApproximation.Refinement.ComputedWidthEnvelope +import OAI.Combinatorics.EditApproximation.Refinement.ComputedPhysicalWork + +namespace OAI + +namespace EditApproximation +open Filter +open scoped Topology + + def localKernelPowerExponent (M p D : ℕ) : ℕ := ((100 * M + 100000) * (p + 1)) * D + + def computedLocalKernelBudget (D N : ℕ) : ℕ := + inputHeight N ^ localKernelPowerExponent (integerParameters N).M + (coarseExponent (inputSmallLog N)) D + +noncomputable def computedLocalKernelExponent (D N : ℕ) : ℝ := + (D : ℝ) * ((100 * Real.log 2) * ((integerParameters N).M : ℝ) * + ((coarseExponent (inputSmallLog N) : ℝ) + 1) * inputSmallLog N + + 100000 * ((coarseExponent (inputSmallLog N) : ℝ) + 1) * Real.log (inputHeight N : ℝ)) + + theorem computedLocalKernelExponent_tendsto (D : ℕ) : + Tendsto (fun N => computedLocalKernelExponent D N / inputHeight N) atTop (𝓝 0) := by + have h := ((local_enumeration_exponent_div_height_tendsto.const_mul (100 * Real.log 2)).add + (encoding_exponent_div_height_tendsto.const_mul 100000)).const_mul (D : ℝ) + simp only [mul_zero, zero_add] at h + convert h using 1 + ext N + unfold computedLocalKernelExponent + ring + +private theorem localKernelBudget_exp_scalar (D H M p ell : ℕ) (hH : 0 < H) + (hlog : Real.log (H : ℝ) ≤ (ell : ℝ) * Real.log 2) : + ((H ^ localKernelPowerExponent M p D : ℕ) : ℝ) ≤ + Real.exp ((D : ℝ) * ((100 * Real.log 2) * (M : ℝ) * ((p : ℝ) + 1) * ell + + 100000 * ((p : ℝ) + 1) * Real.log (H : ℝ))) := by + rw [Nat.cast_pow, nat_pow_eq_exp_log H _ hH] + apply Real.exp_le_exp.mpr + have hM : (0 : ℝ) ≤ (M : ℝ) := Nat.cast_nonneg _ + have hp : (0 : ℝ) ≤ (p : ℝ) + 1 := by positivity + have hmul := mul_le_mul_of_nonneg_left hlog + (mul_nonneg (mul_nonneg (by norm_num : (0 : ℝ) ≤ 100) hM) hp) + have hD : (0 : ℝ) ≤ (D : ℝ) := Nat.cast_nonneg _ + unfold localKernelPowerExponent + push_cast + nlinarith only [mul_nonneg hD (sub_nonneg.mpr hmul)] + + theorem computedLocalKernelBudget_exp_bound (D N : ℕ) (hN : 0 < N) : + (computedLocalKernelBudget D N : ℝ) ≤ Real.exp (computedLocalKernelExponent D N) := by + have hlog : Real.log (inputHeight N : ℝ) ≤ (inputSmallLog N : ℝ) * Real.log 2 := by + rw [inputHeight_real_log] + exact mul_le_mul_of_nonneg_right (by exact_mod_cast (inputSmallLog_bounds N hN).1) + (Real.log_nonneg (by norm_num)) + exact localKernelBudget_exp_scalar D (inputHeight N) (integerParameters N).M + (coarseExponent (inputSmallLog N)) (inputSmallLog N) (Nat.two_pow_pos _) hlog + + theorem computedLocalKernelBudget_subpolynomial (D : ℕ) (epsilon : ℝ) (hepsilon : 0 < epsilon) : + ∀ᶠ N in atTop, (computedLocalKernelBudget D N : ℝ) ≤ (N + 2 : ℝ) ^ epsilon := by + filter_upwards [subexponential_height_to_input (computedLocalKernelExponent D) + (computedLocalKernelExponent_tendsto D) epsilon hepsilon, eventually_ge_atTop 1] with N he hN + exact (computedLocalKernelBudget_exp_bound D N (by omega)).trans he + + theorem computedLocalKernelBudget_envelope_near_linear (D : ℕ) (epsilon : ℝ) (hepsilon : 0 < epsilon) : + ∀ᶠ N in atTop, computedWidthEnvelope N * computedLocalKernelBudget D N ≤ + (N + 2 : ℝ) ^ (1 + epsilon) := by + filter_upwards [computedWidthEnvelope_mul_exp_near_linear (computedLocalKernelExponent D) + (computedLocalKernelExponent_tendsto D) epsilon hepsilon, eventually_ge_atTop 1] with N he hN + exact (mul_le_mul_of_nonneg_left (computedLocalKernelBudget_exp_bound D N (by omega)) + (computedWidthEnvelope_nonneg N)).trans he + + theorem computedLocalKernelBudget_widthWork_near_linear (D : ℕ) (epsilon : ℝ) (hepsilon : 0 < epsilon) : + ∀ᶠ N in atTop, ∀ n ≤ N, ∀ tree : DependencyExpansion, + tree.Valid ((integerParameters N).M * inputSmallLog N ^ 257) + (inputHeight N ^ (512 * (coarseExponent (inputSmallLog N) + 1))) → + tree.depth = intervalTreeDepth (integerParameters N).M n → + tree.rank ≤ computedDependencyIndexCount N → + (tree.widthWork (integerParameters N).M n : ℝ) * computedLocalKernelBudget D N ≤ + (N + 2 : ℝ) ^ (1 + epsilon) := by + filter_upwards [computed_widthWork_subexponential (computedLocalKernelExponent D) + (computedLocalKernelExponent_tendsto D) epsilon hepsilon, eventually_ge_atTop 1] with N he hN + intro n hn tree hv hd hk + exact (mul_le_mul_of_nonneg_left (computedLocalKernelBudget_exp_bound D N (by omega)) + (Nat.cast_nonneg _)).trans (he n hn tree hv hd hk) + + theorem computedLocalKernelBudget_requests_near_linear (D : ℕ) (epsilon : ℝ) (hepsilon : 0 < epsilon) : + ∀ᶠ N in atTop, ∀ source target : List ℕ, source.length + target.length ≤ N → + ∀ input : ComputedFamilyInput source target N, + ((computedFamilyResult source target N input).requests : ℝ) * computedLocalKernelBudget D N ≤ + (N + 2 : ℝ) ^ (1 + epsilon) := by + have hh : 0 < epsilon / 2 := half_pos hepsilon + filter_upwards [computedFamilyResult_requests_near_linear (epsilon / 2) hh, + computedLocalKernelBudget_subpolynomial D (epsilon / 2) hh] with N hr hk + intro source target hsize input + calc + _ ≤ (N + 2 : ℝ) ^ (1 + epsilon / 2) * (N + 2 : ℝ) ^ (epsilon / 2) := + mul_le_mul (hr source target hsize input) hk (Nat.cast_nonneg _) (Real.rpow_nonneg (by positivity) _) + _ = _ := by rw [← Real.rpow_add (by positivity)]; congr 1; ring + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedNumericalParameters.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedNumericalParameters.lean new file mode 100644 index 0000000000000000000000000000000000000000..839fa112e1fe1a14a4c08b073ca651e9b18a757a --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedNumericalParameters.lean @@ -0,0 +1,83 @@ +import OAI.Combinatorics.EditApproximation.Geometry.LocalOnlineMassBound +import OAI.Combinatorics.EditApproximation.Refinement.ComputedEarlierInputBudget +import OAI.Combinatorics.EditApproximation.Numerics.NumericalWork + +namespace OAI + +/-! All-seed numerical dimension and source-range bounds after substituting +the computed grid size. These bounds do not use an accuracy event. -/ + +namespace EditApproximation + +theorem wide_coordinate_budget_le (H M P p : ℕ) (hH : 64 ≤ H) (hM : M ≤ H) + (hP : 1 ≤ P) (hPcap : P ≤ H ^ (p + 20)) : + M * (40 * P + 2) ^ 2 ≤ H ^ (2 * p + 45) := by + have hbox : 40 * P + 2 ≤ H ^ (p + 22) := by + have hconstant : 42 ≤ H ^ 2 := by nlinarith + calc + _ ≤ 42 * P := by omega + _ ≤ H ^ 2 * H ^ (p + 20) := Nat.mul_le_mul hconstant hPcap + _ = H ^ (2 + (p + 20)) := (pow_add H 2 (p + 20)).symm + _ = _ := by congr 1; omega + calc + _ ≤ H * (H ^ (p + 22)) ^ 2 := Nat.mul_le_mul hM (Nat.pow_le_pow_left hbox 2) + _ = H * H ^ ((p + 22) * 2) := by rw [pow_mul] + _ = H ^ ((p + 22) * 2 + 1) := (pow_succ' H _).symm + _ = _ := by congr 1; omega + +theorem optimizer_parameter_budget_le (H M P p : ℕ) (hH : 64 ≤ H) (hM : M ≤ H) + (hP : 1 ≤ P) (hPcap : P ≤ H ^ (p + 20)) : + H + M * (40 * P + 2) ^ 2 + 4 ≤ H ^ (2 * p + 46) := by + have hdimension := wide_coordinate_budget_le H M P p hH hM hP hPcap + have hlarge : H ≤ H ^ (2 * p + 45) := Nat.le_pow (by omega) + have hfour : 4 ≤ H ^ (2 * p + 45) := (by omega : 4 ≤ H).trans hlarge + calc + _ ≤ 3 * H ^ (2 * p + 45) := by omega + _ ≤ H * H ^ (2 * p + 45) := Nat.mul_le_mul_right _ (by omega) + _ = H ^ (2 * p + 45 + 1) := (pow_succ' H _).symm + _ = _ := rfl + +theorem optimizerTriangularMass_le_square (K : ℕ) : optimizerTriangularMass K ≤ K ^ 2 := by + have htwice := optimizerTriangularMass_twice K + have hpower : K ≤ K ^ 2 := Nat.le_pow (by decide) + nlinarith only [htwice, hpower] + +theorem localOnlineMassBound_polynomial (H M P p : ℕ) (hH : 64 ≤ H) (hM : M ≤ H) + (hP : 1 ≤ P) (hPcap : P ≤ H ^ (p + 20)) : + localOnlineMassBound M P H ≤ H ^ (8000 * (p + 1)) := by + have hG : H + M * (40 * P + 2) ^ 2 + 2 ≤ H ^ (2 * p + 46) := + (by omega : H + M * (40 * P + 2) ^ 2 + 2 ≤ H + M * (40 * P + 2) ^ 2 + 4).trans + (optimizer_parameter_budget_le H M P p hH hM hP hPcap) + calc + _ ≤ ((H + M * (40 * P + 2) ^ 2 + 2) ^ 80) ^ 2 := optimizerTriangularMass_le_square _ + _ = (H + M * (40 * P + 2) ^ 2 + 2) ^ (80 * 2) := (pow_mul _ 80 2).symm + _ ≤ (H ^ (2 * p + 46)) ^ (80 * 2) := Nat.pow_le_pow_left hG _ + _ = H ^ ((2 * p + 46) * (80 * 2)) := (pow_mul H _ _).symm + _ ≤ _ := Nat.pow_le_pow_right (by omega) (by omega) + +theorem computed_localOnlineMassBound_polynomial (N : ℕ) (hH : 64 ≤ inputHeight N) : + localOnlineMassBound (integerParameters N).M (integerParameters N).P (inputHeight N) ≤ + inputHeight N ^ (8000 * (coarseExponent (inputSmallLog N) + 1)) := by + apply localOnlineMassBound_polynomial _ _ _ _ hH + · exact Nat.pow_le_pow_right (by decide : 0 < (2 : ℕ)) (Nat.div_le_self _ _) + · exact Nat.one_le_pow _ _ (by omega) + · exact le_rfl + +theorem computed_localOnlineMassBound_bits (N : ℕ) (hH : 64 ≤ inputHeight N) : + Nat.size (localOnlineMassBound (integerParameters N).M (integerParameters N).P (inputHeight N)) ≤ + 8000 * (coarseExponent (inputSmallLog N) + 1) * Nat.size (inputHeight N) + 1 := + (Nat.size_le_size (computed_localOnlineMassBound_polynomial N hH)).trans + (natural_power_bit_length _ _) + +theorem rejectionBitCount_le_size (B : ℕ) : rejectionBitCount B ≤ Nat.size B := by + apply Nat.clog_le_of_le_pow + exact (Nat.lt_size_self B).le + +theorem computed_localOnlineMassBound_rejection_bits (N : ℕ) (hH : 64 ≤ inputHeight N) : + rejectionBitCount (localOnlineMassBound (integerParameters N).M (integerParameters N).P (inputHeight N)) ≤ + 8000 * (coarseExponent (inputSmallLog N) + 1) * Nat.size (inputHeight N) + 1 := + (rejectionBitCount_le_size _).trans (computed_localOnlineMassBound_bits N hH) + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedOptimizerBitWork.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedOptimizerBitWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..d0d755884b206736fba11d3c69f673638e293acc --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedOptimizerBitWork.lean @@ -0,0 +1,133 @@ +import OAI.Combinatorics.EditApproximation.Numerics.OptimizerBitEnvelope +import OAI.Combinatorics.EditApproximation.Geometry.LocalWorkEnvelope + +namespace OAI + +/-! Substitution of the actual grid and optimizer parameters into the +Boolean-operation envelope. Input word bounds remain explicit here so +the local rational-value invariants can supply them without a unit-cost +rational arithmetic assumption. -/ + +namespace EditApproximation + +open Filter +open scoped Topology + +def localBooleanBitExponent (M p C : ℕ) : ℕ := + ((44 * M + C + 4000) * (p + 1)) * optimizerBitPolynomialDegree + +theorem optimizerBitBudget_grid_cap (H M P p C d v G K B Bv L V : ℕ) + (hH : 64 ≤ H) (hM : M ≤ H) (hP : 1 ≤ P) (hPcap : P ≤ H ^ (p + 20)) + (hd : d ≤ M * (40 * P + 2) ^ 2) (hv : v ≤ (40 * P + 2) ^ (2 * M)) + (hG : G ≤ H + M * (40 * P + 2) ^ 2 + 4) (hK : K ≤ G ^ 80) + (hB : B ≤ H ^ (C * (p + 1))) (hBv : Bv ≤ H ^ (C * (p + 1))) + (hL : L ≤ H ^ (C * (p + 1))) (hV : V ≤ H ^ (C * (p + 1))) : + BinaryFraction.optimizerBitBudget d v G K B Bv L V ≤ H ^ localBooleanBitExponent M p C := by + let E := (44 * M + C + 4000) * (p + 1) + have hHpos : 0 < H := by omega + have hbox : 40 * P + 2 ≤ H ^ (p + 22) := by + have hc : 42 ≤ H ^ 2 := by nlinarith + calc + _ ≤ 42 * P := by omega + _ ≤ H ^ 2 * H ^ (p + 20) := Nat.mul_le_mul hc hPcap + _ = H ^ (2 + (p + 20)) := (pow_add H _ _).symm + _ = _ := by congr 1; omega + have hv' : v ≤ H ^ E := by + calc + _ ≤ (H ^ (p + 22)) ^ (2 * M) := hv.trans (Nat.pow_le_pow_left hbox _) + _ = H ^ ((p + 22) * (2 * M)) := (pow_mul H _ _).symm + _ ≤ _ := Nat.pow_le_pow_right hHpos (by dsimp only [E]; nlinarith) + have hd' : d ≤ H ^ E := + (hd.trans (wide_coordinate_budget_le H M P p hH hM hP hPcap)).trans + (Nat.pow_le_pow_right hHpos (by dsimp only [E]; nlinarith)) + have hG0 := hG.trans (optimizer_parameter_budget_le H M P p hH hM hP hPcap) + have hG' : G ≤ H ^ E := hG0.trans + (Nat.pow_le_pow_right hHpos (by dsimp only [E]; nlinarith)) + have hK' : K ≤ H ^ E := by + calc + _ ≤ (H ^ (2 * p + 46)) ^ 80 := hK.trans (Nat.pow_le_pow_left hG0 _) + _ = H ^ ((2 * p + 46) * 80) := (pow_mul H _ _).symm + _ ≤ _ := Nat.pow_le_pow_right hHpos (by dsimp only [E]; nlinarith) + have hE : C * (p + 1) ≤ E := by dsimp only [E]; nlinarith + have hS : 2 ≤ H ^ E := by + have he : 1 ≤ E := by dsimp only [E]; nlinarith + exact (by omega : 2 ≤ H).trans (Nat.le_pow he) + have h := optimizerBitBudget_le_fixed_power d v G K B Bv L V (H ^ E) hS hd' hv' hG' hK' + (hB.trans (Nat.pow_le_pow_right hHpos hE)) + (hBv.trans (Nat.pow_le_pow_right hHpos hE)) + (hL.trans (Nat.pow_le_pow_right hHpos hE)) + (hV.trans (Nat.pow_le_pow_right hHpos hE)) + simpa only [← pow_mul, E, localBooleanBitExponent] using h + +noncomputable def computedBooleanBitExponent (C N : ℕ) : ℝ := + (optimizerBitPolynomialDegree : ℝ) * + ((44 * Real.log 2) * ((integerParameters N).M : ℝ) * + ((coarseExponent (inputSmallLog N) : ℝ) + 1) * inputSmallLog N + + ((C : ℝ) + 4000) * ((coarseExponent (inputSmallLog N) : ℝ) + 1) * + Real.log (inputHeight N : ℝ)) + +theorem computedBooleanBitExponent_tendsto (C : ℕ) : + Tendsto (fun N => computedBooleanBitExponent C N / inputHeight N) atTop (𝓝 0) := by + have h := ((local_enumeration_exponent_div_height_tendsto.const_mul (44 * Real.log 2)).add + (encoding_exponent_div_height_tendsto.const_mul ((C : ℝ) + 4000))).const_mul + (optimizerBitPolynomialDegree : ℝ) + simp only [mul_zero, zero_add] at h + convert h using 1 + ext N + unfold computedBooleanBitExponent + ring + +def computedBooleanBitBudget (C N : ℕ) : ℕ := + inputHeight N ^ localBooleanBitExponent (integerParameters N).M + (coarseExponent (inputSmallLog N)) C + +private theorem booleanBitBudget_exp_scalar (D C H M p ell : ℕ) (hH : 0 < H) + (hlog : Real.log (H : ℝ) ≤ (ell : ℝ) * Real.log 2) : + ((H ^ (((44 * M + C + 4000) * (p + 1)) * D) : ℕ) : ℝ) ≤ + Real.exp ((D : ℝ) * ((44 * Real.log 2) * (M : ℝ) * ((p : ℝ) + 1) * ell + + ((C : ℝ) + 4000) * ((p : ℝ) + 1) * Real.log (H : ℝ))) := by + rw [Nat.cast_pow, nat_pow_eq_exp_log H _ hH] + apply Real.exp_le_exp.mpr + have hM : (0 : ℝ) ≤ (M : ℝ) := Nat.cast_nonneg _ + have hp : (0 : ℝ) ≤ (p : ℝ) + 1 := by have h := Nat.cast_nonneg (α := ℝ) p; linarith + have hmul := mul_le_mul_of_nonneg_left hlog + (mul_nonneg (mul_nonneg (by norm_num : (0 : ℝ) ≤ 44) hM) hp) + have hD : (0 : ℝ) ≤ (D : ℝ) := Nat.cast_nonneg _ + push_cast + nlinarith only [mul_nonneg hD (sub_nonneg.mpr hmul)] + +theorem computedBooleanBitBudget_exp_bound (C N : ℕ) (hN : 0 < N) : + (computedBooleanBitBudget C N : ℝ) ≤ Real.exp (computedBooleanBitExponent C N) := by + have hH : 0 < inputHeight N := by + dsimp only [inputHeight] + exact Nat.pow_pos (by decide : 0 < (2 : ℕ)) + have hlog : Real.log (inputHeight N : ℝ) ≤ (inputSmallLog N : ℝ) * Real.log 2 := by + rw [inputHeight_real_log] + exact mul_le_mul_of_nonneg_right (by exact_mod_cast (inputSmallLog_bounds N hN).1) + (Real.log_nonneg (by norm_num)) + exact booleanBitBudget_exp_scalar optimizerBitPolynomialDegree C (inputHeight N) + (integerParameters N).M (coarseExponent (inputSmallLog N)) (inputSmallLog N) hH hlog + +theorem computedBooleanBitBudget_subpolynomial (C : ℕ) (epsilon : ℝ) (hepsilon : 0 < epsilon) : + ∀ᶠ N in atTop, (computedBooleanBitBudget C N : ℝ) ≤ (N + 2 : ℝ) ^ epsilon := by + filter_upwards [subexponential_height_to_input (computedBooleanBitExponent C) + (computedBooleanBitExponent_tendsto C) epsilon hepsilon, eventually_ge_atTop 1] with N he hN + exact (computedBooleanBitBudget_exp_bound C N (by omega)).trans he + +theorem computedBooleanBitBudget_widthWork_near_linear (C : ℕ) (epsilon : ℝ) (hepsilon : 0 < epsilon) : + ∀ᶠ N in atTop, ∀ n ≤ N, ∀ tree : DependencyExpansion, + tree.Valid ((integerParameters N).M * inputSmallLog N ^ 257) + (inputHeight N ^ (512 * (coarseExponent (inputSmallLog N) + 1))) → + tree.depth = intervalTreeDepth (integerParameters N).M n → + tree.rank ≤ computedDependencyIndexCount N → + (tree.widthWork (integerParameters N).M n : ℝ) * computedBooleanBitBudget C N ≤ + (N + 2 : ℝ) ^ (1 + epsilon) := by + filter_upwards [computed_widthWork_subexponential (computedBooleanBitExponent C) + (computedBooleanBitExponent_tendsto C) epsilon hepsilon, eventually_ge_atTop 1] with N he hN + intro n hn tree hv hd hk + exact (mul_le_mul_of_nonneg_left (computedBooleanBitBudget_exp_bound C N (by omega)) + (Nat.cast_nonneg _)).trans (he n hn tree hv hd hk) + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedOutputWork.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedOutputWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..20276750b409c2ed87d7c64e664169357ce0b2a4 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedOutputWork.lean @@ -0,0 +1,60 @@ +import OAI.Combinatorics.EditApproximation.Binary.IntegerKernelWork +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation +open MeasureTheory Filter + +/-- Execution cost including shared binary setup and the final conversion. +The exact branch keeps its own charged dynamic program. -/ + + +theorem computedFullOutputWork_expected_le (source target : List ℕ) (N : ℕ) + (cost : ComputedFamilyInput source target N → ComputedFamilyMemoKey source target N → ℕ) + (setup : ℝ) (shared : ℕ) (output : ComputedFamilyInput source target N → ℕ) + (fallbackOutput : ℕ) (epsilon : BinaryFraction) (hlarge : physicalLargeInput N epsilon) + (budget outputBudget : ℝ) + (hbudget : (∫ execution, computedExecutionTotalWork source target N cost execution + ∂computedExecutionLaw source target N) ≤ budget) + (houtput : ∀ input, (output input : ℝ) ≤ outputBudget) : + (∫ outcome, computedFullOutputWork source target N cost setup shared output fallbackOutput outcome + ∂computedFullLaw source target N epsilon) ≤ setup + shared + budget + outputBudget := by + have hmap := integral_map (μ := computedExecutionLaw source target N) + measurable_inr.aemeasurable + (measurable_of_countable + (computedFullOutputWork source target N cost setup shared output fallbackOutput)).aestronglyMeasurable + simp only [computedFullLaw, hlarge, ite_true] + rw [hmap] + change (∫ execution, (setup + shared) + computedExecutionTotalWork source target N cost execution + + (output (computedExecutionAccepted source target N execution) : ℝ) + ∂computedExecutionLaw source target N) ≤ _ + have ho := computedExecutionAcceptedWork_integrable source target N (fun input => (output input : ℝ)) + change Integrable (fun execution => (output (computedExecutionAccepted source target N execution) : ℝ)) + (computedExecutionLaw source target N) at ho + have ht := computedExecutionTotalWork_integrable source target N cost + have hconst : Integrable (fun _ : ComputedExecutionOutcome source target N => setup + (shared : ℝ)) + (computedExecutionLaw source target N) := integrable_const _ + have hfirst : Integrable (fun execution => setup + (shared : ℝ) + + computedExecutionTotalWork source target N cost execution) (computedExecutionLaw source target N) := hconst.add ht + have hsplit := integral_add hfirst ho + change (∫ execution, setup + (shared : ℝ) + computedExecutionTotalWork source target N cost execution + + (output (computedExecutionAccepted source target N execution) : ℝ) ∂computedExecutionLaw source target N) = _ at hsplit + rw [hsplit] + have hsplitFirst := integral_add hconst ht + change (∫ execution, setup + (shared : ℝ) + computedExecutionTotalWork source target N cost execution + ∂computedExecutionLaw source target N) = _ at hsplitFirst + rw [hsplitFirst] + have hb : (∫ execution, (output (computedExecutionAccepted source target N execution) : ℝ) + ∂computedExecutionLaw source target N) ≤ outputBudget := by + calc + _ ≤ ∫ _ : ComputedExecutionOutcome source target N, outputBudget ∂computedExecutionLaw source target N := + integral_mono ho (integrable_const _) (fun execution => houtput _) + _ = outputBudget := by simp + simp only [integral_const, probReal_univ, smul_eq_mul, one_mul] + linarith only [hbudget, hb] + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedParameterRegisters.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedParameterRegisters.lean new file mode 100644 index 0000000000000000000000000000000000000000..2199c7311f5ae872f3d6cbc5839f14314ccbc199 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedParameterRegisters.lean @@ -0,0 +1,24 @@ +import OAI.Combinatorics.EditApproximation.Geometry.ParameterNumericalConstruction + +namespace OAI + +namespace EditApproximation +open Filter + +/-- A single logarithmic word accommodates every power exponent needed +by the global integer and online-mass constructors. -/ + theorem computedParameterPower_word : + ∀ᶠ N in atTop, ∀ k : ℕ, + k ≤ 8000 * (coarseExponent (inputSmallLog N) + 1) → + Nat.size (inputHeight N ^ k) ≤ inputHeight N := by + filter_upwards [computed_sourceAddressBits_le_height 8000] with N hN + intro k hk + exact (natural_power_bit_length _ _).trans + ((Nat.add_le_add_right (Nat.mul_le_mul_right _ hk) 1).trans hN) + + theorem inputLength_register_word (N : ℕ) : Nat.size (N + 2) ≤ inputHeight N + 1 := + input_length_bits_le N + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedPhysicalCoarseWork.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedPhysicalCoarseWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..727bcb5fc92b2ce405b6ae426c8a763d0d23b454 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedPhysicalCoarseWork.lean @@ -0,0 +1,66 @@ +import OAI.Combinatorics.EditApproximation.Refinement.ComputedCoarseExecution +import OAI.Combinatorics.EditApproximation.Refinement.ComputedCoarseBudget +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation + +open MeasureTheory Filter + + + + +noncomputable def computedPhysicalCoarseWork (source target : List ℕ) (N : ℕ) : + ComputedFamilyDraw source target N → ComputedPhysicalCoarseDraw source target N → ℝ := by + intro draw + with_reducible + exact physicalFamilyMemoCoarseWork (M := (integerParameters N).M) + (J := intervalTreeDepth (integerParameters N).M source.length) (R := inputHeight N ^ 2) + source target N (integerParameters N).P (inputHeight N) (integerParameters N).T + (integerParameters N).S (computedSeedPassCount N) (inputHeight N ^ 2) + (scheduledSeedFactor N) (scheduledSeedMultiplier N) + (rationalParameters (inputSmallLog N)).tau (rationalParameters (inputSmallLog N)).eta + (rationalParameters (inputSmallLog N)).kappa (rationalParameters (inputSmallLog N)).delta + draw (integerParameters N).B (computedPhysicalCoarseDepth source target N) + (16384 * inputHeight N + 5) (computedFamilyMemoCode source target N (inputHeight N ^ 2)) + (computedFinalRoot source target N) + + +def ComputedPhysicalCoarseBudget (source target : List ℕ) (N : ℕ) (budget : ℝ) : Prop := + SymbolicComputedCoarseBudget (M := (integerParameters N).M) + (J := intervalTreeDepth (integerParameters N).M source.length) (R := inputHeight N ^ 2) + (B := (integerParameters N).B) source target N (computedPhysicalCoarseDepth source target N) + (computedFamilyMemoCode source target N (inputHeight N ^ 2)) budget + + theorem computedPhysicalCoarseWork_expected_le (source target : List ℕ) (N : ℕ) + (hN : 0 < N) (hell : 2 ^ 1000 ≤ inputSmallLog N) (hsize : source.length + target.length ≤ N) + (hB : Nat.size (localOnlineMassBound (integerParameters N).M (integerParameters N).P + (inputHeight N)) ≤ inputHeight N) + (hinverse : coarseInverseAllowanceFactor (integerParameters N).B + (initialThresholdQ N) (initialLambda N) ≤ (inputHeight N : ℝ) ^ 8) : + ComputedPhysicalCoarseBudget source target N + (computedWidthEnvelope N * computedCoarseWidthOverhead N) := + symbolicComputedCoarseWork_expected_le source target N (computedPhysicalCoarseDepth source target N) + (computedFamilyMemoCode source target N (inputHeight N ^ 2)) hN + (two_hundred_le_two_pow_thousand.trans hell) hsize rfl rfl rfl (fun _ => rfl) + (computedFamilyMemoCode_injective source target N (inputHeight N ^ 2) hN + (two_hundred_le_two_pow_thousand.trans hell)) + (computedFamilyMemoCode_fits source target N (inputHeight N ^ 2) hN hell hsize le_rfl hB) hinverse + + theorem computedPhysicalCoarseWork_expected_near_linear (epsilon : ℝ) (hepsilon : 0 < epsilon) : + ∀ᶠ N in atTop, ∀ source target : List ℕ, source.length + target.length ≤ N → + ComputedPhysicalCoarseBudget source target N ((N + 2 : ℝ) ^ (1 + epsilon)) := by + filter_upwards [computedWidthEnvelope_coarse_near_linear epsilon hepsilon, + eventually_ge_atTop 1, inputSmallLog_tendsto.eventually (eventually_ge_atTop (2 ^ 1000)), + computed_localOnlineMassBound_word, coarse_inverse_allowance_le_height_eight_eventually] + with N hw hN hell hB hinverse + intro source target hsize + exact symbolicComputedCoarseBudget_mono source target N (computedPhysicalCoarseDepth source target N) + (computedFamilyMemoCode source target N (inputHeight N ^ 2)) _ _ hw + (computedPhysicalCoarseWork_expected_le source target N (by omega) hell hsize hB hinverse) + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedPhysicalUniform.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedPhysicalUniform.lean new file mode 100644 index 0000000000000000000000000000000000000000..bde7df6a6c7a6077896c27b8e0f63182b95afa5f --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedPhysicalUniform.lean @@ -0,0 +1,80 @@ +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalUniformAccuracy +import OAI.Combinatorics.EditApproximation.Refinement.ComputedFamilyMemoCode +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation + +theorem two_hundred_le_two_pow_thousand : 200 ≤ (2 : ℕ) ^ 1000 := by + have h := pow_le_pow_right₀ (by decide : 1 ≤ (2 : ℕ)) (by decide : 8 ≤ 1000) + exact le_trans (by decide : 200 ≤ (2 : ℕ) ^ 8) h + +open MeasureTheory ProbabilityTheory + +theorem computedParameterP_pos (N : ℕ) : 0 < (integerParameters N).P := + Nat.pow_pos (Nat.two_pow_pos _) + + + + + + + + + +abbrev ComputedPhysicalOutcome (source target : List ℕ) (N : ℕ) := + PhysicalUniformOutcome (M := (integerParameters N).M) + (J := intervalTreeDepth (integerParameters N).M source.length) (R := inputHeight N ^ 2) + target N (integerParameters N).P (inputHeight N) + +noncomputable def computedPhysicalLaw (source target : List ℕ) (N : ℕ) (epsilon : BinaryFraction) : + Measure (ComputedPhysicalOutcome source target N) := + physicalUniformLaw (R := inputHeight N ^ 2) source target N (integerParameters N).P + (inputHeight N) (integerParameters N).B (computedPhysicalCoarseDepth source target N) epsilon + +noncomputable def computedPhysicalAnswer (source target : List ℕ) (N : ℕ) + (outcome : ComputedPhysicalOutcome source target N) : ℕ := + physicalUniformAnswer source target N (integerParameters N).P (integerParameters N).T + (integerParameters N).S (inputHeight N) (Nat.two_pow_pos _) + (16384 * inputHeight N + 5) (computedFamilyMemoCode source target N (inputHeight N ^ 2)) outcome + + theorem computedPhysicalAnswer_equal (source target : List ℕ) (N : ℕ) (heq : source = target) + (outcome : ComputedPhysicalOutcome source target N) : computedPhysicalAnswer source target N outcome = 0 := + physicalUniformAnswer_equal source target N (integerParameters N).P (integerParameters N).T + (integerParameters N).S (inputHeight N) (Nat.two_pow_pos _) _ _ heq outcome + + theorem computed_physical_uniform_conditional_accuracy (source target : List ℕ) (N : ℕ) + (epsilon : BinaryFraction) (hepsilon : 0 < epsilon.value) + (hsize : source.length + target.length ≤ N) + (coarseBernstein : FiniteBernsteinInput (Measure.pi fun _ : Fin (integerParameters N).B => + (PMF.uniformOfFintype (Fin (integerParameters N).B)).toMeasure)) + (groupBernstein : ∀ b : ℕ, ∀ h : Fin + (groupDyadicScales (integerParameters N).M b (inputSmallLog N)).length, + FiniteBernsteinInput (Measure.pi fun _ : Fin + (groupSampleCount (integerParameters N).M (inputSmallLog N ^ 80) b + (groupDyadicScaleAt (integerParameters N).M b (inputSmallLog N) h)) => + (PMF.uniformOfFintype (Fin (integerParameters N).M)).toMeasure)) : + (2 / 3 : ℝ) ≤ (computedPhysicalLaw source target N epsilon).real + {outcome | EditDistortion.edit source target ≤ computedPhysicalAnswer source target N outcome ∧ + (computedPhysicalAnswer source target N outcome : ℝ) ≤ + (1 + (epsilon.value : ℝ)) * EditDistortion.edit source target} := by + apply physical_uniform_conditional_accuracy source target N (integerParameters N).P + (integerParameters N).T (integerParameters N).S (inputHeight N) (integerParameters N).B + (computedPhysicalCoarseDepth source target N) epsilon (Nat.two_pow_pos _) + (16384 * inputHeight N + 5) (computedFamilyMemoCode source target N (inputHeight N ^ 2)) + ?_ ?_ hsize rfl rfl rfl rfl rfl rfl rfl (fun _ => rfl) coarseBernstein groupBernstein hepsilon + · intro hlarge + exact computedFamilyMemoCode_injective source target N (inputHeight N ^ 2) + (largeAccuracyInput_pos N epsilon.value hlarge.2.1) (by + have h := hlarge.2.1.1 + have hc := two_hundred_le_two_pow_thousand + omega) + · intro hlarge key + exact computedFamilyMemoCode_fits source target N (inputHeight N ^ 2) + (largeAccuracyInput_pos N epsilon.value hlarge.2.1) hlarge.2.1.1 hsize le_rfl hlarge.2.2 key + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedPhysicalWork.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedPhysicalWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..77ba2f3f7870619781598093aca22f7d464ab920 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedPhysicalWork.lean @@ -0,0 +1,243 @@ +import OAI.Combinatorics.EditApproximation.Refinement.ComputedPhysicalUniform +import OAI.Combinatorics.EditApproximation.Refinement.ComputedWidthEnvelope +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalFamilyWork +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalFamilyRejectionWork +import OAI.Combinatorics.EditApproximation.Refinement.ComputedFamilySampling +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation + +open Filter MeasureTheory + +private theorem power_succ_add_one (x : ℝ) (hx : 2 ≤ x) (n : ℕ) : + x ^ n + 1 ≤ x ^ (n + 1) := by + have hnonneg : 0 ≤ x ^ n := pow_nonneg (by linarith) _ + have hone : 1 ≤ x ^ n := one_le_pow₀ (by linarith) + calc + _ ≤ x ^ n + x ^ n := add_le_add le_rfl hone + _ = x ^ n * 2 := by ring + _ ≤ x ^ n * x := mul_le_mul_of_nonneg_left hx hnonneg + _ = _ := (pow_succ _ _).symm + +private theorem rejection_factor_le (x : ℝ) (hx : 2 ≤ x) (n : ℕ) : + 2 * (x ^ n + 1) * x ≤ x ^ (n + 3) := by + have hnonneg : 0 ≤ x := by linarith + have hone : 1 ≤ x ^ n := one_le_pow₀ (by linarith) + have hsum : x ^ n + 1 ≤ 2 * x ^ n := by linarith + have hsquare : 4 ≤ x ^ 2 := by nlinarith only [hx] + calc + _ ≤ 2 * (2 * x ^ n) * x := mul_le_mul_of_nonneg_right + (mul_le_mul_of_nonneg_left hsum (by norm_num)) hnonneg + _ = 4 * x ^ (n + 1) := by rw [pow_succ]; ring + _ ≤ x ^ 2 * x ^ (n + 1) := mul_le_mul_of_nonneg_right hsquare (pow_nonneg hnonneg _) + _ = x ^ (2 + (n + 1)) := (pow_add _ _ _).symm + _ = _ := by congr 1; omega + +private theorem dictionary_factor_le (H : ℕ) (hH : 32780 ≤ H) : + 2 * (16384 * H + 5 + 1) ≤ H ^ 2 := by nlinarith only [hH] + + theorem scheduledSeedFactor_bounds (N pass : ℕ) : + 1 ≤ scheduledSeedFactor N pass ∧ + scheduledSeedFactor N pass ≤ ((integerParameters N).initialFactor : ℚ) := by + constructor + · exact one_le_pow₀ (by norm_num) + · rw [← computedSeed_initial_factor] + exact pow_le_pow_right₀ (by norm_num : (1 : ℚ) ≤ 2) (Nat.sub_le _ _) + + + + + + + + + +noncomputable def computedFamilyTree (source target : List ℕ) (N : ℕ) + (input : ComputedFamilyInput source target N) : DependencyExpansion := + physicalFamilyDependencyTree source target N (integerParameters N).P (inputHeight N) + (integerParameters N).T (integerParameters N).S (computedSeedPassCount N) (inputHeight N ^ 2) + (scheduledSeedFactor N) (scheduledSeedMultiplier N) + (rationalParameters (inputSmallLog N)).tau (rationalParameters (inputSmallLog N)).eta + (rationalParameters (inputSmallLog N)).kappa (rationalParameters (inputSmallLog N)).delta + (clampedSeedNat input.1) (computedParameterP_pos N) input.2 + (localFinalRootRequest target N (integerParameters N).T (integerParameters N).S + (inputHeight N) (Nat.two_pow_pos _) (finalTargetState target.length)) + + theorem computedFamilyTree_valid (source target : List ℕ) (N : ℕ) + (hN : 0 < N) (hell : 200 ≤ inputSmallLog N) (input : ComputedFamilyInput source target N) : + (computedFamilyTree source target N input).Valid + ((integerParameters N).M * inputSmallLog N ^ 257) + (inputHeight N ^ (512 * (coarseExponent (inputSmallLog N) + 1))) := + physicalFamilyDependencyTree_valid source target N (integerParameters N).P (inputHeight N) + (integerParameters N).T (integerParameters N).S (computedSeedPassCount N) (inputHeight N ^ 2) + (scheduledSeedFactor N) (scheduledSeedMultiplier N) _ _ _ _ + (clampedSeedNat input.1) (computedParameterP_pos N) input.2 hN hell rfl rfl rfl rfl le_rfl + (fun p => (scheduledSeedFactor_bounds N p).1) (fun p => (scheduledSeedFactor_bounds N p).2) _ + + theorem computedFamilyTree_depth (source target : List ℕ) (N : ℕ) + (input : ComputedFamilyInput source target N) : + (computedFamilyTree source target N input).depth = + intervalTreeDepth (integerParameters N).M source.length := by + unfold computedFamilyTree + rw [physicalFamilyDependencyTree_depth] + rfl + + theorem computedFamilyTree_rank (source target : List ℕ) (N : ℕ) + (input : ComputedFamilyInput source target N) : + (computedFamilyTree source target N input).rank ≤ computedDependencyIndexCount N := by + unfold computedFamilyTree + exact physicalFamilyDependencyTree_rank source target N (integerParameters N).P (inputHeight N) + (integerParameters N).T (integerParameters N).S (computedSeedPassCount N) (inputHeight N ^ 2) + (scheduledSeedFactor N) (scheduledSeedMultiplier N) _ _ _ _ + (clampedSeedNat input.1) (computedParameterP_pos N) input.2 rfl rfl rfl _ + + theorem computedFamilyTree_width_le (source target : List ℕ) (N : ℕ) + (hN : 0 < N) (hell : 200 ≤ inputSmallLog N) (hH : 105 ≤ inputHeight N) + (hsize : source.length + target.length ≤ N) (input : ComputedFamilyInput source target N) : + ((computedFamilyTree source target N input).widthWork (integerParameters N).M source.length : ℝ) ≤ + computedWidthEnvelope N := + computed_widthWork_le_envelope N source.length hN (by omega) hell hH _ + (computedFamilyTree_valid source target N hN hell input) + (computedFamilyTree_depth source target N input) (computedFamilyTree_rank source target N input) + + theorem computedFamilyResult_requests_le (source target : List ℕ) (N : ℕ) + (hN : 0 < N) (hell : 2 ^ 1000 ≤ inputSmallLog N) (hsize : source.length + target.length ≤ N) + (hB : Nat.size (localOnlineMassBound (integerParameters N).M (integerParameters N).P + (inputHeight N)) ≤ inputHeight N) (input : ComputedFamilyInput source target N) : + ((computedFamilyResult source target N input).requests : ℝ) ≤ + ((inputHeight N : ℝ) ^ 91 + 1) * computedWidthEnvelope N := by + have hsmall : 200 ≤ inputSmallLog N := two_hundred_le_two_pow_thousand.trans hell + have hH : 105 ≤ inputHeight N := (by omega : 105 ≤ inputSmallLog N).trans + (computed_smallLog_le_height N) + have hr : (computedFamilyResult source target N input).requests ≤ + (inputHeight N ^ 91 + 1) * + (computedFamilyTree source target N input).widthWork (integerParameters N).M source.length := by + exact physicalFamilyMemo_requests_le_width source target N (integerParameters N).P + (inputHeight N) (integerParameters N).T (integerParameters N).S (computedSeedPassCount N) + (inputHeight N ^ 2) (scheduledSeedFactor N) (scheduledSeedMultiplier N) _ _ _ _ + (clampedSeedNat input.1) (computedParameterP_pos N) input.2 hN hsmall rfl + (fun p => (scheduledSeedFactor_bounds N p).2) (16384 * inputHeight N + 5) + (computedFamilyMemoCode source target N (inputHeight N ^ 2)) + (computedFamilyMemoCode_injective source target N (inputHeight N ^ 2) hN hsmall) + (computedFamilyMemoCode_fits source target N (inputHeight N ^ 2) hN hell hsize le_rfl hB) _ + have hrR : ((computedFamilyResult source target N input).requests : ℝ) ≤ + ((inputHeight N : ℝ) ^ 91 + 1) * + (computedFamilyTree source target N input).widthWork (integerParameters N).M source.length := by + exact_mod_cast hr + exact hrR.trans (mul_le_mul_of_nonneg_left + (computedFamilyTree_width_le source target N hN hsmall hH hsize input) (by positivity)) + + + theorem computedFamilyResult_requests_near_linear (epsilon : ℝ) (hepsilon : 0 < epsilon) : + ∀ᶠ N in atTop, ∀ source target : List ℕ, source.length + target.length ≤ N → + ∀ input : ComputedFamilyInput source target N, + ((computedFamilyResult source target N input).requests : ℝ) ≤ (N + 2 : ℝ) ^ (1 + epsilon) := by + filter_upwards [computedWidthEnvelope_weighted_near_linear 92 epsilon hepsilon, + eventually_ge_atTop 1, inputSmallLog_tendsto.eventually (eventually_ge_atTop (2 ^ 1000)), + computed_localOnlineMassBound_word] with N hw hN hell hB + intro source target hsize input + have hH : (2 : ℝ) ≤ inputHeight N := by + exact_mod_cast (show 2 ≤ inputHeight N from + ((by decide : 2 ≤ 200).trans two_hundred_le_two_pow_thousand).trans (hell.trans (computed_smallLog_le_height N))) + have hp : (inputHeight N : ℝ) ^ 91 + 1 ≤ (inputHeight N : ℝ) ^ 92 := by + exact power_succ_add_one (inputHeight N) hH 91 + calc + _ ≤ ((inputHeight N : ℝ) ^ 91 + 1) * computedWidthEnvelope N := + computedFamilyResult_requests_le source target N (by omega) hell hsize hB input + _ ≤ (inputHeight N : ℝ) ^ 92 * computedWidthEnvelope N := + mul_le_mul_of_nonneg_right hp (computedWidthEnvelope_nonneg N) + _ ≤ _ := by simpa only [mul_comm] using hw + + + + theorem computedFamilyRejectionWork_expected_le (source target : List ℕ) (N : ℕ) + (hN : 0 < N) (hell : 2 ^ 1000 ≤ inputSmallLog N) (hsize : source.length + target.length ≤ N) + (hB : Nat.size (localOnlineMassBound (integerParameters N).M (integerParameters N).P + (inputHeight N)) ≤ inputHeight N) + (seed : ClampedPhysicalSeed (integerParameters N).M + (intervalTreeDepth (integerParameters N).M source.length) target.length N) : + (∫ execution, computedFamilyRejectionWork source target N (seed, execution) + ∂rejectionRuntimeArrayLaw (physicalFamilyRange (M := (integerParameters N).M) + (J := intervalTreeDepth (integerParameters N).M source.length) (R := inputHeight N ^ 2) + target N (integerParameters N).P (inputSmallLog N) (40 * smallLogExponent N) + (inputHeight N) (inputSmallLog N ^ 80) (computedSeedPassCount N) (inputHeight N ^ 2))) ≤ + 2 * ((((inputHeight N : ℝ) ^ 91 + 1) * computedWidthEnvelope N) * inputHeight N) := by + apply physicalFamilyMemoBits_expected_le source target N (integerParameters N).P + (integerParameters N).T (integerParameters N).S (inputHeight N) (Nat.two_pow_pos _) + (16384 * inputHeight N + 5) (inputHeight N) + (computedFamilyMemoCode source target N (inputHeight N ^ 2)) (finalTargetState target.length) seed + · intro draw + exact computedFamilyResult_requests_le source target N hN hell hsize hB (seed, draw) + · exact computedFamilyRange_bits_le source target N (inputHeight N ^ 2) hB + + + theorem computedFamilyRejectionWork_expected_near_linear (epsilon : ℝ) (hepsilon : 0 < epsilon) : + ∀ᶠ N in atTop, ∀ source target : List ℕ, source.length + target.length ≤ N → + ∀ seed : ComputedFamilySeed source target N, + (∫ execution, computedFamilyRejectionWork source target N (seed, execution) + ∂rejectionRuntimeArrayLaw (physicalFamilyRange (M := (integerParameters N).M) + (J := intervalTreeDepth (integerParameters N).M source.length) (R := inputHeight N ^ 2) + target N (integerParameters N).P (inputSmallLog N) (40 * smallLogExponent N) + (inputHeight N) (inputSmallLog N ^ 80) (computedSeedPassCount N) (inputHeight N ^ 2))) ≤ + (N + 2 : ℝ) ^ (1 + epsilon) := by + filter_upwards [computedWidthEnvelope_weighted_near_linear 94 epsilon hepsilon, + eventually_ge_atTop 1, inputSmallLog_tendsto.eventually (eventually_ge_atTop (2 ^ 1000)), + computed_localOnlineMassBound_word] with N hw hN hell hB + intro source target hsize seed + have hH : (2 : ℝ) ≤ inputHeight N := by + exact_mod_cast (show 2 ≤ inputHeight N from + ((by decide : 2 ≤ 200).trans two_hundred_le_two_pow_thousand).trans (hell.trans (computed_smallLog_le_height N))) + have hfactor : 2 * ((inputHeight N : ℝ) ^ 91 + 1) * inputHeight N ≤ + (inputHeight N : ℝ) ^ 94 := rejection_factor_le (inputHeight N) hH 91 + calc + _ ≤ 2 * ((((inputHeight N : ℝ) ^ 91 + 1) * computedWidthEnvelope N) * inputHeight N) := + computedFamilyRejectionWork_expected_le source target N (by omega) hell hsize hB seed + _ = computedWidthEnvelope N * (2 * ((inputHeight N : ℝ) ^ 91 + 1) * inputHeight N) := by ring + _ ≤ computedWidthEnvelope N * (inputHeight N : ℝ) ^ 94 := + mul_le_mul_of_nonneg_left hfactor (computedWidthEnvelope_nonneg N) + _ ≤ _ := hw + + + theorem computedFamilyResult_dictionary_near_linear (epsilon : ℝ) (hepsilon : 0 < epsilon) : + ∀ᶠ N in atTop, ∀ source target : List ℕ, source.length + target.length ≤ N → + ∀ input : ComputedFamilyInput source target N, + ((computedFamilyResult source target N input).dictionaryVisits : ℝ) ≤ + (N + 2 : ℝ) ^ (1 + epsilon) := by + filter_upwards [computedWidthEnvelope_weighted_near_linear 94 epsilon hepsilon, + eventually_ge_atTop 1, inputSmallLog_tendsto.eventually (eventually_ge_atTop (2 ^ 1000)), + inputHeight_real_tendsto.eventually (eventually_ge_atTop 32780), + computed_localOnlineMassBound_word] with N hw hN hell hH hB + intro source target hsize input + have hd : (computedFamilyResult source target N input).dictionaryVisits ≤ + (computedFamilyResult source target N input).requests * + (2 * (16384 * inputHeight N + 5 + 1)) := + (rankedMemoEvaluate_resource_bounds _ _ _ _ _ _).2.1 + have hc : (2 * (16384 * inputHeight N + 5 + 1) : ℕ) ≤ inputHeight N ^ 2 := by + have hnat : 32780 ≤ inputHeight N := by exact_mod_cast hH + exact dictionary_factor_le (inputHeight N) hnat + have hcR : ((2 * (16384 * inputHeight N + 5 + 1) : ℕ) : ℝ) ≤ + (inputHeight N : ℝ) ^ 2 := by exact_mod_cast hc + have hr := computedFamilyResult_requests_le source target N (by omega) hell hsize hB input + have hpower : (inputHeight N : ℝ) ^ 91 + 1 ≤ (inputHeight N : ℝ) ^ 92 := by + exact power_succ_add_one (inputHeight N) (by linarith only [hH]) 91 + have hdR : ((computedFamilyResult source target N input).dictionaryVisits : ℝ) ≤ + ((computedFamilyResult source target N input).requests : ℝ) * + ((2 * (16384 * inputHeight N + 5 + 1) : ℕ) : ℝ) := by exact_mod_cast hd + calc + _ ≤ (((inputHeight N : ℝ) ^ 91 + 1) * computedWidthEnvelope N) * + (inputHeight N : ℝ) ^ 2 := hdR.trans (mul_le_mul hr hcR (by positivity) + (mul_nonneg (by positivity) (computedWidthEnvelope_nonneg N))) + _ ≤ ((inputHeight N : ℝ) ^ 92 * computedWidthEnvelope N) * (inputHeight N : ℝ) ^ 2 := + mul_le_mul_of_nonneg_right (mul_le_mul_of_nonneg_right hpower + (computedWidthEnvelope_nonneg N)) (by positivity) + _ = computedWidthEnvelope N * (inputHeight N : ℝ) ^ 94 := by + rw [show (94 : ℕ) = 92 + 2 from rfl, pow_add] + ring + _ ≤ _ := hw + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedPreevaluation.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedPreevaluation.lean new file mode 100644 index 0000000000000000000000000000000000000000..80d04f2a3fac4b91a5ab8911bf3403514ca6832c --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedPreevaluation.lean @@ -0,0 +1,69 @@ +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalInputGuard +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation +open Filter + +private theorem guard_scalar (H : ℕ) (hH : 1000000 ≤ H) : + 100000 * (H + 1005) ^ 2 ≤ H ^ 4 := by + have hplus : H + 1005 ≤ 2 * H := by omega + have hp := Nat.mul_le_mul_left 100000 (Nat.pow_le_pow_left hplus 2) + have hcoef : 400000 ≤ H ^ 2 := by nlinarith only [hH] + have hm := Nat.mul_le_mul_right (H ^ 2) hcoef + calc + _ ≤ 100000 * (2 * H) ^ 2 := hp + _ = 400000 * H ^ 2 := by ring + _ ≤ H ^ 2 * H ^ 2 := hm + _ = _ := by ring + + theorem physicalLargeInputWithWork_le_height (N : ℕ) (epsilon : BinaryFraction) + (hH : 1000000 ≤ inputHeight N) + (hmass : Nat.size (localOnlineMassBound (integerParameters N).M (integerParameters N).P + (inputHeight N)) ≤ inputHeight N) : + (physicalLargeInputWithWork N epsilon).2 ≤ inputHeight N ^ 4 := + (physicalLargeInputWithWork_cost N epsilon hmass).trans (guard_scalar _ hH) + +/-- All input scans, index construction, parameter arithmetic and the +bounded accuracy/word-cap decision occur before sampling. -/ + + +private theorem setup_scalar (N H a b c : ℕ) (hH : 1000000 ≤ H) + (ha : a ≤ (N + 2) * H ^ 4) (hb : b ≤ 2000 * (H + 1)) (hc : c ≤ H ^ 4) : + a + b + c ≤ (N + 2) * H ^ 5 := by + have hb' : 2000 * (H + 1) ≤ H ^ 2 := by nlinarith only [hH] + have hs : H ^ 2 ≤ H ^ 4 := Nat.pow_le_pow_right (by omega) (by decide) + have hcoef0 := Nat.mul_le_mul_left (N + 2) (show 2 ≤ H by omega) + have hcoef : N + 2 + 2 ≤ (N + 2) * H := by omega + calc + _ ≤ (N + 2) * H ^ 4 + H ^ 4 + H ^ 4 := by omega + _ = (N + 2 + 2) * H ^ 4 := by ring + _ ≤ ((N + 2) * H) * H ^ 4 := Nat.mul_le_mul_right _ hcoef + _ = _ := by ring + + theorem integerPreevaluationWork_near_linear (C : ℕ) (epsilonTime : ℝ) (htime : 0 < epsilonTime) : + ∀ᶠ N in atTop, ∀ source target : List ℤ, source.length + target.length ≤ N → + (∀ z ∈ source ++ target, z.natAbs ≤ (N + 2) ^ C) → + ∀ epsilon : BinaryFraction, + (integerPreevaluationWork source target N epsilon : ℝ) ≤ + (N + 2 : ℝ) ^ (1 + epsilonTime) := by + filter_upwards [fixed_height_power_near_linear 5 epsilonTime htime, + inputSmallLog_tendsto.eventually (eventually_ge_atTop (max 1000000 C)), + computed_localOnlineMassBound_word] with N ht hH hmass + intro source target hsize halphabet epsilon + have hheight : 1000000 ≤ inputHeight N := + (le_max_left _ _).trans (hH.trans (computed_smallLog_le_height N)) + have hC : C ≤ inputHeight N := + (le_max_right _ _).trans (hH.trans (computed_smallLog_le_height N)) + have hp := integerPreprocessingWork_le source target N C hsize halphabet (by omega) hC + have hg := globalParameterWork_le N + have hd := physicalLargeInputWithWork_le_height N epsilon hheight hmass + have hbound := setup_scalar N (inputHeight N) _ _ _ hheight hp hg hd + exact (show (integerPreevaluationWork source target N epsilon : ℝ) ≤ + (N + 2 : ℝ) * (inputHeight N : ℝ) ^ 5 by exact_mod_cast hbound).trans ht + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedPreparedInputBounds.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedPreparedInputBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..1fa854bf9885de1352daab6feb28f5bfd646fb47 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedPreparedInputBounds.lean @@ -0,0 +1,160 @@ +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalPreparedInputBounds +import OAI.Combinatorics.EditApproximation.Refinement.ComputedParameterRegisters +import OAI.Combinatorics.EditApproximation.Refinement.ComputedNumericalParameters + +namespace OAI + +namespace EditApproximation +open Filter + +private theorem precision_power_bound (p : ℕ) : p + 20 ≤ 8000 * (p + 1) := by omega + +private theorem prepared_loop_caps (H M P p : ℕ) (hH : 64 ≤ H) + (hM : M ≤ H) (hP : 1 ≤ P) (hPcap : P ≤ H ^ (p + 20)) : + (40 * P + 2) ^ (2 * M) ≤ H ^ ((100 * M + 100000) * (p + 1)) ∧ + ((40 * P + 2) ^ 2 + 1) ^ (M + 1) ≤ H ^ ((100 * M + 100000) * (p + 1)) ∧ + (H + M * (40 * P + 2) ^ 2 + 2) ^ 80 ≤ H ^ ((100 * M + 100000) * (p + 1)) := by + have hHp : 0 < H := by omega + have hbox : 40 * P + 2 ≤ H ^ (p + 22) := by + calc + _ ≤ 42 * P := by omega + _ ≤ H ^ 2 * H ^ (p + 20) := Nat.mul_le_mul (by nlinarith only [hH]) hPcap + _ = _ := by rw [← pow_add]; congr 1; omega + have hbase : (40 * P + 2) ^ 2 + 1 ≤ H ^ (2 * (p + 22) + 1) := by + have hs := Nat.pow_le_pow_left hbox 2 + have hunit : 1 ≤ (H ^ (p + 22)) ^ 2 := one_le_pow₀ (one_le_pow₀ (by omega)) + calc + _ ≤ 2 * (H ^ (p + 22)) ^ 2 := by omega + _ ≤ H * (H ^ (p + 22)) ^ 2 := Nat.mul_le_mul_right _ (by omega) + _ = _ := by rw [← pow_mul, ← pow_succ']; congr 1; omega + refine ⟨?_, ?_, ?_⟩ + · calc + _ ≤ (H ^ (p + 22)) ^ (2 * M) := Nat.pow_le_pow_left hbox _ + _ = H ^ ((p + 22) * (2 * M)) := (pow_mul H _ _).symm + _ ≤ _ := Nat.pow_le_pow_right hHp (by nlinarith only [Nat.zero_le (M * p), Nat.zero_le p, Nat.zero_le M]) + · calc + _ ≤ (H ^ (2 * (p + 22) + 1)) ^ (M + 1) := Nat.pow_le_pow_left hbase _ + _ = H ^ ((2 * (p + 22) + 1) * (M + 1)) := (pow_mul H _ _).symm + _ ≤ _ := Nat.pow_le_pow_right hHp (by nlinarith only [Nat.zero_le (M * p), Nat.zero_le p, Nat.zero_le M]) + · have hg := optimizer_parameter_budget_le H M P p hH hM hP hPcap + calc + _ ≤ (H ^ (2 * p + 46)) ^ 80 := Nat.pow_le_pow_left (by omega) 80 + _ = H ^ ((2 * p + 46) * 80) := (pow_mul H _ _).symm + _ ≤ _ := Nat.pow_le_pow_right hHp (by nlinarith only [Nat.zero_le (M * p), Nat.zero_le p, Nat.zero_le M]) + +/-- Every numeric premise of the prepared kernel follows from the computed +parameters. Width assumptions here concern only the five actual parameter +words; cached data are added by `physicalPreparedStep_inputBounds`. -/ +theorem computedPreparedNumericBounds : + ∀ᶠ N : ℕ in atTop, ∀ nx ny : ℕ, nx + ny ≤ N → ∀ t : ℕ, t ≤ inputHeight N ^ 2 → + ∀ tau a eta kappa delta : BinaryFraction, + tau.width ≤ inputHeight N ^ 8 → a.width ≤ inputHeight N ^ 8 → + eta.width ≤ inputHeight N ^ 8 → kappa.width ≤ inputHeight N ^ 8 → + delta.width ≤ inputHeight N ^ 8 → |eta.value| ≤ ((inputHeight N ^ 5 : ℕ) : ℚ) → + (0 ≤ kappa.value ∧ kappa.value ≤ 1) → + ∀ integer : ℕ → TargetInterval ny → ℕ, + (∀ b r, Nat.size (integer b r) ≤ inputHeight N) → + BinaryFraction.PreparedKernelNumericBounds (nx := nx) (M := (integerParameters N).M) + N (integerParameters N).P (inputSmallLog N) (40 * smallLogExponent N) + (inputHeight N) (inputSmallLog N ^ 80) (heightExponent N / 20) (smallLogExponent N) + (inputHeight N ^ 8) (inputHeight N ^ 5) + (inputHeight N ^ ((100 * (integerParameters N).M + 100000) * + (coarseExponent (inputSmallLog N) + 1))) t tau a eta kappa delta integer := by + filter_upwards [computedParameterPower_word, + inputSmallLog_tendsto.eventually (eventually_ge_atTop 64)] with N hpower hell + intro nx ny hsize t ht tau a eta kappa delta htau ha heta hk hd hrate hkRange integer hint + let H := inputHeight N + let p := coarseExponent (inputSmallLog N) + let M := (integerParameters N).M + let P := (integerParameters N).P + let L := (100 * M + 100000) * (p + 1) + have hpowers : ∀ k : ℕ, k ≤ 8000 * (p + 1) → Nat.size (H ^ k) ≤ H := hpower + change BinaryFraction.PreparedKernelNumericBounds (nx := nx) (M := M) + N P (inputSmallLog N) (40 * smallLogExponent N) H (inputSmallLog N ^ 80) + (heightExponent N / 20) (smallLogExponent N) (H ^ 8) (H ^ 5) (H ^ L) t + tau a eta kappa delta integer + have hH : 64 ≤ H := hell.trans (computed_smallLog_le_height N) + have hHp : 0 < H := by omega + have hM : M ≤ H := Nat.pow_le_pow_right (by decide : 0 < (2 : ℕ)) (Nat.div_le_self _ _) + have hP : 1 ≤ P := one_le_pow₀ (by omega) + have hPcap : P ≤ H ^ (p + 20) := le_rfl + have hH8 : H ^ 2 ≤ H ^ 8 := Nat.pow_le_pow_right hHp (by decide) + have hsmall : H + 2 ≤ H ^ 8 := (by nlinarith only [hH] : H + 2 ≤ H ^ 2).trans hH8 + have hHle : H ≤ H ^ 8 := by omega + have hL : p + 20 ≤ L := by dsimp only [L]; nlinarith only [Nat.zero_le (M * p), Nat.zero_le M, Nat.zero_le p] + have hL20 : 20 ≤ L := (Nat.le_add_left 20 p).trans hL + have hHL : H ≤ H ^ L := Nat.le_pow (by omega) + have hsizeN : Nat.size N ≤ H := computed_input_size_le_height N + have hMF : Nat.size M ≤ H := (Nat.size_le.mpr Nat.lt_two_pow_self).trans hM + have hF : Nat.size (inputSmallLog N) ≤ H := + (Nat.size_le.mpr Nat.lt_two_pow_self).trans (computed_smallLog_le_height N) + have hPs : Nat.size P ≤ H := by + change Nat.size (H ^ (p + 20)) ≤ H + exact hpowers (p + 20) (precision_power_bound p) + have hQs : Nat.size (inputSmallLog N ^ 80) ≤ H := + (Nat.size_le_size (Nat.pow_le_pow_left (computed_smallLog_le_height N) 80)).trans + (hpowers 80 (by omega)) + have he : smallLogExponent N ≤ H := + (Nat.lt_two_pow_self.le : smallLogExponent N ≤ inputSmallLog N).trans (computed_smallLog_le_height N) + have htheta : 40 * smallLogExponent N + 1 ≤ H ^ 8 := + (by nlinarith only [he, hH] : 40 * smallLogExponent N + 1 ≤ H ^ 2).trans hH8 + have hscale : heightExponent N / 20 + smallLogExponent N + 7 ≤ H ^ 8 := by + have heM : heightExponent N / 20 ≤ H := + (Nat.div_le_self _ _).trans Nat.lt_two_pow_self.le + exact (by nlinarith only [heM, he, hH] : + heightExponent N / 20 + smallLogExponent N + 7 ≤ H ^ 2).trans hH8 + have hcoord : Nat.size (M * (40 * P + 2) ^ 2) ≤ H := + (Nat.size_le_size (wide_coordinate_budget_le H M P p hH hM hP hPcap)).trans + (hpowers (2 * p + 45) (by omega)) + have hiter : Nat.size ((H + M * (40 * P + 2) ^ 2 + 2) ^ 80) ≤ H := by + have hg := optimizer_parameter_budget_le H M P p hH hM hP hPcap + have hi : (H + M * (40 * P + 2) ^ 2 + 2) ^ 80 ≤ H ^ ((2 * p + 46) * 80) := by + calc + _ ≤ (H ^ (2 * p + 46)) ^ 80 := Nat.pow_le_pow_left (by omega) 80 + _ = _ := (pow_mul H _ _).symm + exact (Nat.size_le_size hi).trans (hpowers ((2 * p + 46) * 80) (by omega)) + have hcaps := prepared_loop_caps H M P p hH hM hP hPcap + have hword : 3 * (H ^ 8 + 4) + 4 ≤ H ^ L := by + have hunit : 1 ≤ H ^ 8 := one_le_pow₀ (by omega) + calc + _ ≤ 19 * H ^ 8 := by omega + _ ≤ H ^ 2 * H ^ 8 := Nat.mul_le_mul_right _ (by nlinarith only [hH]) + _ = H ^ 10 := by rw [← pow_add] + _ ≤ _ := Nat.pow_le_pow_right hHp (by omega) + refine { + largeBits := (by nlinarith only [hH] : 10 ≤ H ^ 2).trans hH8 + inputSize := hsizeN.trans hHle + sourceSize := (Nat.add_le_add_right (Nat.size_le_size (show nx ≤ N by omega) |>.trans hsizeN) 2).trans hsmall + targetSize := (Nat.add_le_add_right (Nat.size_le_size (show ny ≤ N by omega) |>.trans hsizeN) 2).trans hsmall + aritySize := (Nat.add_le_add_right hMF 2).trans hsmall + precisionSize := hPs.trans hHle + factorSize := (Nat.add_le_add_right hF 2).trans hsmall + sampleSize := (Nat.add_le_add_right hQs 2).trans hsmall + thetaSize := htheta + scaleSizes := hscale + heightSize := (Nat.size_le.mpr Nat.lt_two_pow_self).trans hHle + coordinateSize := hcoord.trans hHle + iterationSize := hiter.trans hHle + drawSize := fun b r => (hint b r).trans hHle + tauSize := htau + factorWidth := ha + rateSize := heta + optimismSize := hk + decrementSize := hd + rateMagnitude := hrate + optimismRange := hkRange + scalePositive := ?_ + arityCap := hM.trans ?_ + precisionCap := hPcap.trans (Nat.pow_le_pow_right hHp hL) + rateCap := Nat.pow_le_pow_right hHp (by omega) + timeCap := ht.trans (Nat.pow_le_pow_right hHp (by omega)) + wordCap := hword + actionCap := hcaps.1 + cartesianCap := hcaps.2.1 + iterationCap := hcaps.2.2 } + · exact (by omega : 2 ≤ H).trans hHL + · exact hHL + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedPreparedWords.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedPreparedWords.lean new file mode 100644 index 0000000000000000000000000000000000000000..1b1da3b865796b08e7cb49c3fd1d41b482854c4d --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedPreparedWords.lean @@ -0,0 +1,34 @@ +import OAI.Combinatorics.EditApproximation.Refinement.ComputedPreparedInputBounds +import OAI.Combinatorics.EditApproximation.Refinement.ComputedRefinementWords + +namespace OAI + +namespace EditApproximation +open Filter + +/-- The numeric record is inhabited by the actual constructed scalar words. -/ +theorem computedPreparedWords_numeric : + ∀ᶠ N : ℕ in atTop, ∀ nx ny : ℕ, nx + ny ≤ N → ∀ t : ℕ, t ≤ inputHeight N ^ 2 → + ∀ (pass : ℕ) (word : List Bool) (hpositive : 0 < bitWordValue word), + bitWordValue word = inputSmallLog N → word.length ≤ Nat.size (inputSmallLog N) → + ∀ integer : ℕ → TargetInterval ny → ℕ, + (∀ b r, Nat.size (integer b r) ≤ inputHeight N) → + let values := (refinementParameterWordsWithWork N pass word hpositive).1 + BinaryFraction.PreparedKernelNumericBounds (nx := nx) (M := (integerParameters N).M) + N (integerParameters N).P (inputSmallLog N) (40 * smallLogExponent N) + (inputHeight N) (inputSmallLog N ^ 80) (heightExponent N / 20) (smallLogExponent N) + (inputHeight N ^ 8) (inputHeight N ^ 5) + (inputHeight N ^ ((100 * (integerParameters N).M + 100000) * + (coarseExponent (inputSmallLog N) + 1))) t + values.tau values.factor values.eta values.kappa values.delta integer := by + filter_upwards [computedPreparedNumericBounds, + inputSmallLog_tendsto.eventually (eventually_ge_atTop 64)] with N hn hell + intro nx ny hsize t ht pass word hpositive hvalue hwidth integer hint + have hH : 64 ≤ inputHeight N := hell.trans (computed_smallLog_le_height N) + have hw := computedRefinementWords_bounds N pass word hvalue hwidth hH hpositive + exact hn nx ny hsize t ht _ _ _ _ _ hw.1 hw.2.1 hw.2.2.1 hw.1 hw.2.2.2.1 + hw.2.2.2.2.1 hw.2.2.2.2.2 integer hint + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedQueryAnswer.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedQueryAnswer.lean new file mode 100644 index 0000000000000000000000000000000000000000..b7b9b75cd959c200a80e790cc5283536e3463f36 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedQueryAnswer.lean @@ -0,0 +1,90 @@ +import OAI.Combinatorics.EditApproximation.Refinement.ComputedQueryStorage +import OAI.Combinatorics.EditApproximation.Binary.BinaryFinalAnswer +import OAI.Combinatorics.EditApproximation.Binary.IntegerQueryWork + +namespace OAI + +namespace EditApproximation +attribute [local instance] queryArityNeZero queryRoundsNeZero + +/-- Binary output conversion, with the explicit equal-string guard. -/ +def computedQueryAnswerWithWork (source target : List ℕ) (N : ℕ) + (occurrence : BinaryMemo PositionCounts) (symbolBits positionBits : ℕ) + (input : ComputedFamilyInput source target N) : List Bool × ℕ := + if source = target then ([], source.length + target.length + 1) + else let result := computedQueryMemoResult source target N occurrence symbolBits positionBits input + let answer := BinaryFraction.finalAnswerWithWork N result.value + (answer.1, answer.2 + source.length + target.length + 1) + +theorem computedQueryAnswerWithWork_value (source target : List ℕ) (N : ℕ) + (occurrence : BinaryMemo PositionCounts) (symbolBits positionBits : ℕ) + (input : ComputedFamilyInput source target N) (hN : 0 < N) + (hell : 2 ^ 1000 ≤ inputSmallLog N) (hf : 3 ≤ smallLogExponent N) + (hsize : source.length + target.length ≤ N) + (hMass : Nat.size (localOnlineMassBound (integerParameters N).M (integerParameters N).P + (inputHeight N)) ≤ inputHeight N) + (hs : ∀ z ∈ source, z < 2 ^ symbolBits) (ht : ∀ z ∈ target, z < 2 ^ symbolBits) + (hp : target.length ≤ 2 ^ positionBits) + (htable : occurrence = occurrenceBuild symbolBits positionBits target.zipIdx) : + bitWordValue (computedQueryAnswerWithWork source target N occurrence symbolBits positionBits input).1 = + if source = target then 0 else integerAnswer N ((computedFamilyResult source target N input).value : ℝ) := by + have h := congrArg RecursiveMemoResult.value (computedQueryMemoResult_decode source target N occurrence + symbolBits positionBits input hN hell hf hsize hMass hs ht hp htable) + change (computedQueryMemoResult source target N occurrence symbolBits positionBits input).value.value = + (computedFamilyResult source target N input).value at h + unfold computedQueryAnswerWithWork + split_ifs + · rfl + · dsimp only + rw [BinaryFraction.finalAnswerWithWork_value, h] + +theorem computedQueryAnswerWithWork_cost (source target : List ℕ) (N : ℕ) + (occurrence : BinaryMemo PositionCounts) (symbolBits positionBits : ℕ) + (input : ComputedFamilyInput source target N) (hN : 0 < N) + (hell : 2 ^ 1000 ≤ inputSmallLog N) (hf : 3 ≤ smallLogExponent N) + (hsize : source.length + target.length ≤ N) + (hMass : Nat.size (localOnlineMassBound (integerParameters N).M (integerParameters N).P + (inputHeight N)) ≤ inputHeight N) + (hs : ∀ z ∈ source, z < 2 ^ symbolBits) (ht : ∀ z ∈ target, z < 2 ^ symbolBits) + (hp : target.length ≤ 2 ^ positionBits) + (htable : occurrence = occurrenceBuild symbolBits positionBits target.zipIdx) : + (computedQueryAnswerWithWork source target N occurrence symbolBits positionBits input).2 ≤ + N + inputHeight N ^ 10 := by + let H := inputHeight N + have hH : 64 ≤ H := (by have := two_hundred_le_two_pow_thousand.trans hell; omega : + 64 ≤ inputSmallLog N).trans (computed_smallLog_le_height N) + have hpH : 0 < H := by omega + have hw := computedQueryMemoResult_width source target N occurrence symbolBits positionBits input + hN hell hf hsize hMass hs ht hp htable + have hc := BinaryFraction.finalAnswerWithWork_cost N + (computedQueryMemoResult source target N occurrence symbolBits positionBits input).value + have hn := computed_input_size_le_height N + change _ ≤ H ^ 3 at hw + change Nat.size N ≤ H at hn + have hthree : H + 1 ≤ 2 * H ^ 3 := by + have h := (Nat.le_pow (by decide : 0 < 3) : H ≤ H ^ 3) + omega + have hsquare := Nat.pow_le_pow_left (show + (computedQueryMemoResult source target N occurrence symbolBits positionBits input).value.width + + Nat.size N + 1 ≤ 3 * H ^ 3 by omega) 2 + have hcoef : 3600 ≤ H ^ 3 := (by decide : 3600 ≤ (64 : ℕ) ^ 3).trans + (Nat.pow_le_pow_left hH 3) + have hfin : (BinaryFraction.finalAnswerWithWork N + (computedQueryMemoResult source target N occurrence symbolBits positionBits input).value).2 ≤ H ^ 9 := by + calc + _ ≤ 400 * (3 * H ^ 3) ^ 2 := hc.trans (Nat.mul_le_mul_left 400 hsquare) + _ = 3600 * H ^ 6 := by ring + _ ≤ H ^ 3 * H ^ 6 := Nat.mul_le_mul_right _ hcoef + _ = H ^ 9 := by ring + have hu : 1 ≤ H ^ 9 := one_le_pow₀ (by omega) + have hnext : H ^ 9 + 1 ≤ H ^ 10 := by + have hh := Nat.mul_le_mul_right (H ^ 9) (show 2 ≤ H by omega) + rw [show H * H ^ 9 = H ^ 10 by ring] at hh + omega + change (computedQueryAnswerWithWork source target N occurrence symbolBits positionBits input).2 ≤ N + H ^ 10 + unfold computedQueryAnswerWithWork + split_ifs <;> dsimp only <;> omega + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedQueryBudgetAlgebra.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedQueryBudgetAlgebra.lean new file mode 100644 index 0000000000000000000000000000000000000000..41c4c2e91d52f8f6b33e5e13ad3fff8f0604d13b --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedQueryBudgetAlgebra.lean @@ -0,0 +1,60 @@ +import OAI.Combinatorics.EditApproximation.Refinement.ComputedLocalKernelWork + +namespace OAI + +namespace EditApproximation + +/-- Enlarge the exponent of the common computed kernel scale. -/ +theorem computedLocalKernelBudget_mono (N D E : ℕ) (h : D ≤ E) : + computedLocalKernelBudget D N ≤ computedLocalKernelBudget E N := by + unfold computedLocalKernelBudget localKernelPowerExponent + apply Nat.pow_le_pow_right (Nat.two_pow_pos _) + exact Nat.mul_le_mul_left _ h + +theorem computedLocalKernelBudget_three (N D x y z : ℕ) (hH : 3 ≤ inputHeight N) + (hx : x ≤ computedLocalKernelBudget D N) (hy : y ≤ computedLocalKernelBudget D N) + (hz : z ≤ computedLocalKernelBudget D N) : + x + y + z ≤ computedLocalKernelBudget (D + 1) N := by + let L := (100 * (integerParameters N).M + 100000) * (coarseExponent (inputSmallLog N) + 1) + let S := inputHeight N ^ L + have hL : 1 ≤ L := by + have h := Nat.le_mul_of_pos_right (100 * (integerParameters N).M + 100000) + (by omega : 0 < coarseExponent (inputSmallLog N) + 1) + dsimp only [L] + omega + have hHS : inputHeight N ≤ S := Nat.le_pow hL + have hx' : x ≤ S ^ D := by simpa only [S, L, computedLocalKernelBudget, localKernelPowerExponent, ← pow_mul] using hx + have hy' : y ≤ S ^ D := by simpa only [S, L, computedLocalKernelBudget, localKernelPowerExponent, ← pow_mul] using hy + have hz' : z ≤ S ^ D := by simpa only [S, L, computedLocalKernelBudget, localKernelPowerExponent, ← pow_mul] using hz + have hsum : x + y + z ≤ 3 * S ^ D := by omega + have h3S : 3 ≤ S := hH.trans hHS + calc + _ ≤ 3 * S ^ D := hsum + _ ≤ S * S ^ D := Nat.mul_le_mul_right _ h3S + _ = S ^ (D + 1) := (pow_succ' S D).symm + _ = _ := by simp only [S, ← pow_mul]; rfl + +/-- The fixed guard overhead at the eight-power word bound. -/ +theorem computed_kernel_guard_cost (N : ℕ) (hH : 64 ≤ inputHeight N) : + 50 * inputHeight N ^ 8 + 100 ≤ computedLocalKernelBudget 1 N := by + let H := inputHeight N + let L := (100 * (integerParameters N).M + 100000) * (coarseExponent (inputSmallLog N) + 1) + have hL : 10 ≤ L := by + have h := Nat.le_mul_of_pos_right (100 * (integerParameters N).M + 100000) + (by omega : 0 < coarseExponent (inputSmallLog N) + 1) + dsimp only [L] + omega + have hpow : 50 * H ^ 8 + 100 ≤ H ^ 10 := by + have hone : 1 ≤ H ^ 8 := one_le_pow₀ (by omega) + have hcoef : 150 ≤ H ^ 2 := by nlinarith only [hH] + calc + _ ≤ 150 * H ^ 8 := by omega + _ ≤ H ^ 2 * H ^ 8 := Nat.mul_le_mul_right _ hcoef + _ = _ := by rw [← pow_add] + apply hpow.trans + change H ^ 10 ≤ H ^ (L * 1) + simpa only [Nat.mul_one] using Nat.pow_le_pow_right (by omega : 0 < H) hL + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedQueryConstants.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedQueryConstants.lean new file mode 100644 index 0000000000000000000000000000000000000000..bce1c70a340a98221629a3f1b7e69cdb60e27b50 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedQueryConstants.lean @@ -0,0 +1,49 @@ +import OAI.Combinatorics.EditApproximation.Refinement.ComputedQueryMemo +import OAI.Combinatorics.EditApproximation.Refinement.ComputedPreparedWords +import OAI.Combinatorics.EditApproximation.Refinement.ComputedQueryBudgetAlgebra + +namespace OAI + +namespace EditApproximation +open Filter + +/-- The prepared record for the precise shared constants used by the memo. -/ +theorem computedQueryParameters_numeric : + ∀ᶠ N : ℕ in atTop, ∀ nx ny, nx + ny ≤ N → ∀ t, t ≤ inputHeight N ^ 2 → ∀ pass, + BinaryFraction.PreparedKernelNumericBounds (nx := nx) (ny := ny) (M := (integerParameters N).M) + N (integerParameters N).P (inputSmallLog N) (40 * smallLogExponent N) + (inputHeight N) (inputSmallLog N ^ 80) (heightExponent N / 20) (smallLogExponent N) + (inputHeight N ^ 8) (inputHeight N ^ 5) + (inputHeight N ^ ((100 * (integerParameters N).M + 100000) * + (coarseExponent (inputSmallLog N) + 1))) t + (computedQueryParameters N 0).tau (computedQueryParameters N pass).factor + (computedQueryParameters N 0).eta (computedQueryParameters N 0).kappa + (computedQueryParameters N 0).delta (fun _ _ => 0) := by + filter_upwards [computedPreparedWords_numeric] with N hn + intro nx ny hsize t ht pass + exact hn nx ny hsize t ht pass (inputSmallLog N).bits _ (bitWordValue_bits _) + (by rw [← Nat.size_eq_bits_len]) (fun _ _ => 0) (by intros; simp) + +theorem computedQueryMass_word : + ∀ᶠ N : ℕ in atTop, Nat.size (localOnlineMassBound (integerParameters N).M + (integerParameters N).P (inputHeight N)) ≤ inputHeight N := by + filter_upwards [computedParameterPower_word, + inputSmallLog_tendsto.eventually (eventually_ge_atTop 64)] with N hp hell + have hH : 64 ≤ inputHeight N := hell.trans (computed_smallLog_le_height N) + exact (Nat.size_le_size (computed_localOnlineMassBound_polynomial N hH)).trans + (hp _ le_rfl) + +theorem computedQueryInitialFactor_cap (N : ℕ) : + (integerParameters N).initialFactor ≤ computedLocalKernelBudget 1 N := by + unfold computedLocalKernelBudget localKernelPowerExponent + change inputHeight N ^ (coarseExponent (inputSmallLog N) + 4) ≤ _ + apply Nat.pow_le_pow_right (Nat.two_pow_pos _) + have h : 1 ≤ (integerParameters N).M := + one_le_pow₀ (by decide : 1 ≤ (2 : ℕ)) + simp only [Nat.mul_one] + nlinarith only [h, Nat.zero_le (coarseExponent (inputSmallLog N)), + Nat.zero_le ((integerParameters N).M * coarseExponent (inputSmallLog N))] + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedQueryCorrect.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedQueryCorrect.lean new file mode 100644 index 0000000000000000000000000000000000000000..819253e4b1b7f766231b743e7c460e88992a709f --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedQueryCorrect.lean @@ -0,0 +1,113 @@ +import OAI.Combinatorics.EditApproximation.Refinement.ComputedQueryMemo +import OAI.Combinatorics.EditApproximation.Refinement.ComputedRetainedValues + +namespace OAI + +namespace EditApproximation + +attribute [local instance] queryArityNeZero queryRoundsNeZero + +theorem computedQueryParameters_values (N pass : ℕ) (hf : 3 ≤ smallLogExponent N) + (hpass : pass ≤ computedSeedPassCount N) : + (computedQueryParameters N pass).tau.value = (rationalParameters (inputSmallLog N)).tau ∧ + (computedQueryParameters N pass).factor.value = refinementFactor (scheduledSeedFactor N pass) (inputSmallLog N) ∧ + (computedQueryParameters N pass).eta.value = (rationalParameters (inputSmallLog N)).eta ∧ + (computedQueryParameters N pass).kappa.value = (rationalParameters (inputSmallLog N)).kappa ∧ + (computedQueryParameters N pass).delta.value = (rationalParameters (inputSmallLog N)).delta := + refinementParameterWordsWithWork_values N pass (inputSmallLog N).bits _ (bitWordValue_bits _) hf hpass + +noncomputable def computedQueryReference (source target : List ℕ) (N : ℕ) + (input : ComputedFamilyInput source target N) (key : ComputedFamilyMemoKey source target N) := + SourceRanked.body ChargedPhysicalRequest.rank + (physicalFamilyProgram source target N (integerParameters N).P (inputSmallLog N) + (40 * smallLogExponent N) (inputHeight N) (inputSmallLog N ^ 80) + (integerParameters N).T (integerParameters N).S (computedSeedPassCount N) (inputHeight N ^ 2) + (scheduledSeedFactor N) (scheduledSeedMultiplier N) + (rationalParameters (inputSmallLog N)).tau (rationalParameters (inputSmallLog N)).eta + (rationalParameters (inputSmallLog N)).kappa (rationalParameters (inputSmallLog N)).delta + (clampedSeedNat input.1)) + (physicalFamilyAnswer target N (integerParameters N).P (inputSmallLog N) + (40 * smallLogExponent N) (inputHeight N) (inputSmallLog N ^ 80) + (computedSeedPassCount N) (inputHeight N ^ 2) input.2) key + +theorem computedQueryMemoNormalized_correct (source target : List ℕ) (N : ℕ) + (occurrence : BinaryMemo PositionCounts) (symbolBits positionBits : ℕ) + (input : ComputedFamilyInput source target N) (hf : 3 ≤ smallLogExponent N) + (hs : ∀ z ∈ source, z < 2 ^ symbolBits) (ht : ∀ z ∈ target, z < 2 ^ symbolBits) + (hp : target.length ≤ 2 ^ positionBits) + (htable : occurrence = occurrenceBuild symbolBits positionBits target.zipIdx) + (key : ComputedFamilyMemoKey source target N) : + (rankedBitProgramValue (SourceRanked.rank ChargedPhysicalRequest.rank) + (computedQueryMemoNormalized source target N occurrence symbolBits positionBits input) key).value = + computedFamilyExpectedValue source target N input key ∧ + BitQuery.RefinesOn + (fun child => rankedBitProgramValue (SourceRanked.rank ChargedPhysicalRequest.rank) + (computedQueryMemoNormalized source target N occurrence symbolBits positionBits input) child.val) + (fun word value => word.value = value) + (computedQueryMemoNormalized source target N occurrence symbolBits positionBits input key) + (computedQueryReference source target N input key) := by + have hv := computedQueryParameters_values N 0 hf (Nat.zero_le _) + have ha (pass : ℕ) (hpass : pass ≤ computedSeedPassCount N) : + (computedQueryParameters N pass).factor.value = + refinementFactor (scheduledSeedWordWithWork N pass).1.value (inputSmallLog N) := by + rw [scheduledSeedWordWithWork_value] + exact (computedQueryParameters_values N pass hf hpass).2.1 + have hd : (computedQueryParameters N 0).delta.value = 1 / (inputSmallLog N : ℚ) ^ 10 := hv.2.2.2.2 + have h := queryFamilyMemoNormalized_correct source target N (integerParameters N).P (inputSmallLog N) + (40 * smallLogExponent N) (inputHeight N) (inputSmallLog N ^ 80) + (heightExponent N / 20) (smallLogExponent N) (computedParameterP_pos N) rfl rfl + (fun pass => (scheduledSeedWordWithWork N pass).1) (fun pass => (computedQueryParameters N pass).factor) + (computedQueryParameters N 0).tau (computedQueryParameters N 0).eta + (computedQueryParameters N 0).kappa (computedQueryParameters N 0).delta + (scheduledSeedMultiplier N) occurrence symbolBits positionBits + (fun entry => (BinaryFraction.nat (clampedSeedNat input.1 entry), 0)) input.2 + (clampedSeedNat input.1) ha hs ht hp htable (fun entry => BinaryFraction.nat_value _) + (inputSmallLog N) (Nat.two_pow_pos _) hd (computedQueryBase N) (computedQueryBase_value N) key + simp only [queryFamilyMemoNormalized, computedQueryMemoNormalized, + computedQueryReference, computedFamilyExpectedValue, + SourceRanked.value, scheduledSeedWordWithWork_value, + hv.1, hv.2.2.1, hv.2.2.2.1, hv.2.2.2.2] at h ⊢ + exact h + +/-- Width of the actual stored word. -/ +theorem computedQueryMemoNormalized_width_bound (source target : List ℕ) (N : ℕ) + (occurrence : BinaryMemo PositionCounts) (symbolBits positionBits : ℕ) + (input : ComputedFamilyInput source target N) (hf : 3 ≤ smallLogExponent N) + (hs : ∀ z ∈ source, z < 2 ^ symbolBits) (ht : ∀ z ∈ target, z < 2 ^ symbolBits) + (hp : target.length ≤ 2 ^ positionBits) + (htable : occurrence = occurrenceBuild symbolBits positionBits target.zipIdx) + (key : ComputedFamilyMemoKey source target N) (V : ℕ) + (hV : |computedFamilyExpectedValue source target N input key| ≤ (V : ℚ)) : + (rankedBitProgramValue (SourceRanked.rank ChargedPhysicalRequest.rank) + (computedQueryMemoNormalized source target N occurrence symbolBits positionBits input) key).width ≤ + Nat.size V + 2 * (queryFamilyMemoRemaining target N (integerParameters N).P (inputSmallLog N) + (40 * smallLogExponent N) (inputHeight N) (inputSmallLog N ^ 80) key * + (computedQueryBase N).length + 1) + 1 := by + have hV' := hV + simp only [computedFamilyExpectedValue] at hV' + have hv := computedQueryParameters_values N 0 hf (Nat.zero_le _) + have ha (pass : ℕ) (hpass : pass ≤ computedSeedPassCount N) : + (computedQueryParameters N pass).factor.value = + refinementFactor (scheduledSeedWordWithWork N pass).1.value (inputSmallLog N) := by + rw [scheduledSeedWordWithWork_value] + exact (computedQueryParameters_values N pass hf hpass).2.1 + have hd : (computedQueryParameters N 0).delta.value = 1 / (inputSmallLog N : ℚ) ^ 10 := hv.2.2.2.2 + have h := queryFamilyMemoNormalized_width source target N (integerParameters N).P (inputSmallLog N) + (40 * smallLogExponent N) (inputHeight N) (inputSmallLog N ^ 80) + (heightExponent N / 20) (smallLogExponent N) (computedParameterP_pos N) rfl rfl + (fun pass => (scheduledSeedWordWithWork N pass).1) (fun pass => (computedQueryParameters N pass).factor) + (computedQueryParameters N 0).tau (computedQueryParameters N 0).eta + (computedQueryParameters N 0).kappa (computedQueryParameters N 0).delta + (scheduledSeedMultiplier N) occurrence symbolBits positionBits + (fun entry => (BinaryFraction.nat (clampedSeedNat input.1 entry), 0)) input.2 + (clampedSeedNat input.1) ha hs ht hp htable (fun entry => BinaryFraction.nat_value _) + (inputSmallLog N) (Nat.two_pow_pos _) hd (computedQueryBase N) (computedQueryBase_value N) key (computedQueryBase N).length V le_rfl (by + simp only [SourceRanked.value, scheduledSeedWordWithWork_value, + hv.1, hv.2.2.1, hv.2.2.2.1, hv.2.2.2.2] + exact hV') + simp only [computedQueryMemoNormalized] at h ⊢ + exact h + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedQueryExecution.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedQueryExecution.lean new file mode 100644 index 0000000000000000000000000000000000000000..7f13586a37177376ff7cc433670ba85870c0e7fa --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedQueryExecution.lean @@ -0,0 +1,75 @@ +import OAI.Combinatorics.EditApproximation.Refinement.ComputedQueryCorrect + +namespace OAI + +namespace EditApproximation +attribute [local instance] queryArityNeZero queryRoundsNeZero + +/-- The executed mixed binary memo at the final refinement root. -/ +def computedQueryMemoResult (source target : List ℕ) (N : ℕ) + (occurrence : BinaryMemo PositionCounts) (symbolBits positionBits : ℕ) + (input : ComputedFamilyInput source target N) := + rankedBitMemoEvaluate (SourceRanked.rank ChargedPhysicalRequest.rank) + (computedQueryMemoNormalized source target N occurrence symbolBits positionBits input) + (16384 * inputHeight N + 5) (computedFamilyMemoCode source target N (inputHeight N ^ 2)) + (.inr (localFinalRootRequest target N (integerParameters N).T (integerParameters N).S + (inputHeight N) (Nat.two_pow_pos _) (finalTargetState target.length))) .empty + +def computedQueryLocalWork (source target : List ℕ) (N : ℕ) + (occurrence : BinaryMemo PositionCounts) (symbolBits positionBits : ℕ) + (input : ComputedFamilyInput source target N) : ComputedFamilyMemoKey source target N → ℕ := + rankedBitLocalWork (SourceRanked.rank ChargedPhysicalRequest.rank) + (computedQueryMemoNormalized source target N occurrence symbolBits positionBits input) + +section Correct +variable (source target : List ℕ) (N : ℕ) + (occurrence : BinaryMemo PositionCounts) (symbolBits positionBits : ℕ) + (input : ComputedFamilyInput source target N) (hN : 0 < N) + (hell : 2 ^ 1000 ≤ inputSmallLog N) (hf : 3 ≤ smallLogExponent N) + (hsize : source.length + target.length ≤ N) + (hMass : Nat.size (localOnlineMassBound (integerParameters N).M (integerParameters N).P + (inputHeight N)) ≤ inputHeight N) + (hs : ∀ z ∈ source, z < 2 ^ symbolBits) (ht : ∀ z ∈ target, z < 2 ^ symbolBits) + (hp : target.length ≤ 2 ^ positionBits) + (htable : occurrence = occurrenceBuild symbolBits positionBits target.zipIdx) + +include hN hell hf hsize hMass hs ht hp htable in +theorem computedQueryMemoResult_decode : + (computedQueryMemoResult source target N occurrence symbolBits positionBits input).decode = + computedFamilyResult source target N input := by + have h := rankedBitMemoEvaluate_decode_on (SourceRanked.rank ChargedPhysicalRequest.rank) + (computedQueryMemoNormalized source target N occurrence symbolBits positionBits input) + (computedQueryReference source target N input) + (fun key => (computedQueryMemoNormalized_correct source target N occurrence symbolBits positionBits + input hf hs ht hp htable key).2) + (16384 * inputHeight N + 5) (computedFamilyMemoCode source target N (inputHeight N ^ 2)) + (computedFamilyMemoCode_injective source target N (inputHeight N ^ 2) hN + (two_hundred_le_two_pow_thousand.trans hell)) + (computedFamilyMemoCode_fits source target N (inputHeight N ^ 2) hN hell hsize le_rfl hMass) + (.inr (localFinalRootRequest target N (integerParameters N).T (integerParameters N).S + (inputHeight N) (Nat.two_pow_pos _) (finalTargetState target.length))) .empty + (bitMemoSound_empty _ _ _) + exact h + +include hN hell hf hsize hMass hs ht hp htable in +theorem computedQueryMemoResult_localWork : + (computedQueryMemoResult source target N occurrence symbolBits positionBits input).localWork = + computedFamilyKernelWork source target N input + (computedQueryLocalWork source target N occurrence symbolBits positionBits input) := by + exact rankedBitMemoEvaluate_work_transfer_on (SourceRanked.rank ChargedPhysicalRequest.rank) + (computedQueryMemoNormalized source target N occurrence symbolBits positionBits input) + (computedQueryReference source target N input) + (fun key => (computedQueryMemoNormalized_correct source target N occurrence symbolBits positionBits + input hf hs ht hp htable key).2) + (16384 * inputHeight N + 5) (computedFamilyMemoCode source target N (inputHeight N ^ 2)) + (computedFamilyMemoCode_injective source target N (inputHeight N ^ 2) hN + (two_hundred_le_two_pow_thousand.trans hell)) + (computedFamilyMemoCode_fits source target N (inputHeight N ^ 2) hN hell hsize le_rfl hMass) + (.inr (localFinalRootRequest target N (integerParameters N).T (integerParameters N).S + (inputHeight N) (Nat.two_pow_pos _) (finalTargetState target.length))) .empty + (bitMemoSound_empty _ _ _) + +end Correct +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedQueryHeap.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedQueryHeap.lean new file mode 100644 index 0000000000000000000000000000000000000000..bb07481364a43f4685238a5453a8cba5c2b2f3d3 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedQueryHeap.lean @@ -0,0 +1,37 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryFamilyMemoSpace +import OAI.Combinatorics.EditApproximation.Refinement.ComputedQueryMemo + +namespace OAI + +namespace EditApproximation +attribute [local instance] queryArityNeZero queryRoundsNeZero + +/-- Coarse words are borrowed from the separately allocated initializer. +Every local buffer, guarded source read and final normalization is annotated. -/ +def computedQueryMemoRawHeap (source target : List ℕ) (N : ℕ) + (occurrence : BinaryMemo PositionCounts) (symbolBits positionBits : ℕ) + (input : ComputedFamilyInput source target N) (key : ComputedFamilyMemoKey source target N) : + BitQuery.Heap (computedQueryMemoRaw source target N occurrence symbolBits positionBits input key) := + queryFamilyMemoRawHeap source target N (integerParameters N).P (inputSmallLog N) + (40 * smallLogExponent N) (inputHeight N) (inputSmallLog N ^ 80) + (heightExponent N / 20) (smallLogExponent N) (computedParameterP_pos N) rfl rfl + (fun pass => (scheduledSeedWordWithWork N pass).1) + (fun pass => (computedQueryParameters N pass).factor) + (computedQueryParameters N 0).tau (computedQueryParameters N 0).eta + (computedQueryParameters N 0).kappa (computedQueryParameters N 0).delta + (scheduledSeedMultiplier N) occurrence symbolBits positionBits + (fun entry => (BinaryFraction.nat (clampedSeedNat input.1 entry), 0)) + (fun _ => 0) (fun _ => le_rfl) input.2 key + +def computedQueryMemoHeap (source target : List ℕ) (N : ℕ) + (occurrence : BinaryMemo PositionCounts) (symbolBits positionBits : ℕ) + (input : ComputedFamilyInput source target N) (key : ComputedFamilyMemoKey source target N) : + BitQuery.Heap (computedQueryMemoNormalized source target N occurrence symbolBits positionBits input key) := + (computedQueryMemoRawHeap source target N occurrence symbolBits positionBits input key).normalize + (computedQueryBase N) (computedQueryBase_pos N) + (queryFamilyMemoRemaining target N (integerParameters N).P (inputSmallLog N) + (40 * smallLogExponent N) (inputHeight N) (inputSmallLog N ^ 80) key) + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedQueryMemo.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedQueryMemo.lean new file mode 100644 index 0000000000000000000000000000000000000000..289bc264e6e73a1ce775f724590ea0718bd0fa86 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedQueryMemo.lean @@ -0,0 +1,62 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryFamilyNormalize +import OAI.Combinatorics.EditApproximation.Refinement.ComputedSeedWords +import OAI.Combinatorics.EditApproximation.Refinement.ComputedKernelWork +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation + +private theorem computed_small_word_pos (N : ℕ) : 0 < bitWordValue (inputSmallLog N).bits := by + rw [bitWordValue_bits] + exact Nat.two_pow_pos _ + +/-- The same materialized binary constants are shared by all requests of a pass. -/ + + + + +theorem computedQueryBase_value (N : ℕ) : + bitWordValue (computedQueryBase N) = inputSmallLog N ^ 10 + 1 := by + simp only [computedQueryBase, refinementBaseWithWork_value, bitWordValue_bits] + +theorem computedQueryBase_pos (N : ℕ) : 0 < bitWordValue (computedQueryBase N) := by + rw [computedQueryBase_value] + omega + +attribute [local instance] OAI.EditApproximation.queryArityNeZero + +attribute [local instance] OAI.EditApproximation.queryRoundsNeZero + +/-- Coarse words here are the stored outputs of the separately charged coarse +initializer. The adaptive mixed memo consumes them on demand. -/ +def computedQueryMemoRaw (source target : List ℕ) (N : ℕ) + (occurrence : BinaryMemo PositionCounts) (symbolBits positionBits : ℕ) + (input : ComputedFamilyInput source target N) (key : ComputedFamilyMemoKey source target N) := + queryFamilyMemoRaw source target N (integerParameters N).P (inputSmallLog N) + (40 * smallLogExponent N) (inputHeight N) (inputSmallLog N ^ 80) + (heightExponent N / 20) (smallLogExponent N) (computedParameterP_pos N) rfl rfl + (fun pass => (scheduledSeedWordWithWork N pass).1) + (fun pass => (computedQueryParameters N pass).factor) + (computedQueryParameters N 0).tau (computedQueryParameters N 0).eta + (computedQueryParameters N 0).kappa (computedQueryParameters N 0).delta + (scheduledSeedMultiplier N) occurrence symbolBits positionBits + (fun entry => (BinaryFraction.nat (clampedSeedNat input.1 entry), 0)) input.2 key + +def computedQueryMemoNormalized (source target : List ℕ) (N : ℕ) + (occurrence : BinaryMemo PositionCounts) (symbolBits positionBits : ℕ) + (input : ComputedFamilyInput source target N) : + (key : ComputedFamilyMemoKey source target N) → BitQuery + {child : ComputedFamilyMemoKey source target N // + SourceRanked.rank ChargedPhysicalRequest.rank child < SourceRanked.rank ChargedPhysicalRequest.rank key} + BinaryFraction := + rankedNormalizeBody (SourceRanked.rank ChargedPhysicalRequest.rank) + (computedQueryMemoRaw source target N occurrence symbolBits positionBits input) + (computedQueryBase N) (computedQueryBase_pos N) + (queryFamilyMemoRemaining target N (integerParameters N).P (inputSmallLog N) + (40 * smallLogExponent N) (inputHeight N) (inputSmallLog N ^ 80)) + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedQueryNormalizationBudget.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedQueryNormalizationBudget.lean new file mode 100644 index 0000000000000000000000000000000000000000..692b92dcb9e90c8c2b9e702902d89690a444e39d --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedQueryNormalizationBudget.lean @@ -0,0 +1,71 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryRawWidthPolynomial +import OAI.Combinatorics.EditApproximation.Queries.QueryCallbackPolynomial +import OAI.Combinatorics.EditApproximation.Refinement.ComputedLocalKernelWork + +namespace OAI + +namespace EditApproximation +open Filter +attribute [local irreducible] queryRawWordDegree queryNormalizationBitDegree + +def computedQueryNormalizationDegree (K : ℕ) : ℕ := (K + 1) * queryNormalizationBitDegree + +theorem computedQueryNormalizationBudget_cap (K : ℕ) : + ∀ᶠ N : ℕ in atTop, ∀ remaining A B : ℕ, remaining ≤ inputHeight N → B ≤ inputHeight N ^ 3 → + A ≤ computedLocalKernelBudget K N → + BinaryFraction.powerDenominatorBitBudget remaining A B ≤ + computedLocalKernelBudget (computedQueryNormalizationDegree K) N := by + filter_upwards [inputSmallLog_tendsto.eventually (eventually_ge_atTop 64)] with N hell + intro remaining A B hr hB hA + let H := inputHeight N + let L := (100 * (integerParameters N).M + 100000) * (coarseExponent (inputSmallLog N) + 1) + let S := H ^ L + let X := S ^ (K + 1) + have hH : 64 ≤ H := hell.trans (computed_smallLog_le_height N) + have hp : 0 < H := by omega + have hL : 3 ≤ L := by + have h := Nat.le_mul_of_pos_right (100 * (integerParameters N).M + 100000) + (by omega : 0 < coarseExponent (inputSmallLog N) + 1) + dsimp only [L] + omega + have hHS : H ≤ S := Nat.le_pow (by omega) + have hSX : S ≤ X := Nat.le_pow (by omega) + have h3S : H ^ 3 ≤ S := Nat.pow_le_pow_right hp hL + have hAX : A ≤ X := by + apply hA.trans + change H ^ (L * K) ≤ (H ^ L) ^ (K + 1) + rw [← pow_mul] + exact Nat.pow_le_pow_right hp (Nat.mul_le_mul_left L (Nat.le_succ K)) + have h := queryNormalization_fixedPower remaining A B X ((by omega : 2 ≤ H).trans (hHS.trans hSX)) + (hr.trans (hHS.trans hSX)) hAX (hB.trans (h3S.trans hSX)) + apply h.trans_eq + change ((H ^ L) ^ (K + 1)) ^ queryNormalizationBitDegree = H ^ (L * computedQueryNormalizationDegree K) + rw [← pow_mul, ← pow_mul] + congr 1 + +theorem computedQueryRawWidth_cap : + ∀ᶠ N : ℕ in atTop, + BinaryFraction.localWarmupWordBudget (integerParameters N).M (inputHeight N ^ 8) + + BinaryFraction.preparedKernelWordBudget (integerParameters N).M (inputHeight N ^ 8) ≤ + computedLocalKernelBudget queryRawWordDegree N := by + filter_upwards [inputSmallLog_tendsto.eventually (eventually_ge_atTop 64)] with N hell + let H := inputHeight N + let L := (100 * (integerParameters N).M + 100000) * (coarseExponent (inputSmallLog N) + 1) + let S := H ^ L + have hH : 64 ≤ H := hell.trans (computed_smallLog_le_height N) + have hL : 8 ≤ L := by + have h := Nat.le_mul_of_pos_right (100 * (integerParameters N).M + 100000) + (by omega : 0 < coarseExponent (inputSmallLog N) + 1) + dsimp only [L] + omega + have hHS : H ≤ S := Nat.le_pow (by omega) + have hM : (integerParameters N).M ≤ H := + Nat.pow_le_pow_right (by decide : 0 < (2 : ℕ)) (Nat.div_le_self _ _) + have h8 : H ^ 8 ≤ S := Nat.pow_le_pow_right (by omega) hL + have h := queryRawWord_fixedPower (integerParameters N).M (H ^ 8) S + ((by omega : 2 ≤ H).trans hHS) (hM.trans hHS) h8 + simpa only [S, L, computedLocalKernelBudget, localKernelPowerExponent, ← pow_mul] using h + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedQueryNumericZero.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedQueryNumericZero.lean new file mode 100644 index 0000000000000000000000000000000000000000..6f224a6765061f82fb933dbbca4cf54cee5540ac --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedQueryNumericZero.lean @@ -0,0 +1,29 @@ +import OAI.Combinatorics.EditApproximation.Refinement.ComputedPreparedInputBounds + +namespace OAI + +namespace EditApproximation +open Filter + +theorem computedQueryNumeric_zero : + ∀ᶠ N : ℕ in atTop, BinaryFraction.PreparedKernelNumericBounds (nx := 0) (ny := 0) + (M := (integerParameters N).M) N (integerParameters N).P (inputSmallLog N) + (40 * smallLogExponent N) (inputHeight N) (inputSmallLog N ^ 80) + (heightExponent N / 20) (smallLogExponent N) (inputHeight N ^ 8) (inputHeight N ^ 5) + (inputHeight N ^ ((100 * (integerParameters N).M + 100000) * (coarseExponent (inputSmallLog N) + 1))) + 0 BinaryFraction.zero BinaryFraction.zero BinaryFraction.zero BinaryFraction.zero BinaryFraction.zero + (fun _ _ => 0) := by + filter_upwards [computedPreparedNumericBounds, + inputSmallLog_tendsto.eventually (eventually_ge_atTop 64)] with N hn hell + have hH : 64 ≤ inputHeight N := hell.trans (computed_smallLog_le_height N) + have hz : BinaryFraction.zero.width ≤ inputHeight N ^ 8 := by + change 1 ≤ inputHeight N ^ 8 + exact one_le_pow₀ (by omega) + have hzv : BinaryFraction.zero.value = 0 := by + norm_num [BinaryFraction.value, BinaryFraction.zero, SignedBinary.value, signedMagnitude, bitWordValue] + exact hn 0 0 (by omega) 0 (by omega) _ _ _ _ _ hz hz hz hz hz + (by rw [hzv]; simp) (by rw [hzv]; norm_num) (fun _ _ => 0) (by intro b r; simp) + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedQueryOutput.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedQueryOutput.lean new file mode 100644 index 0000000000000000000000000000000000000000..8a99cebd45e0f13b3aedc2903b44134688fedebe --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedQueryOutput.lean @@ -0,0 +1,34 @@ +import OAI.Combinatorics.EditApproximation.Refinement.ComputedQueryAnswer + +namespace OAI + +namespace EditApproximation +attribute [local instance] queryArityNeZero queryRoundsNeZero + +/-- The binary evaluator returns exactly the answer used in the execution-law theorem. -/ +theorem computedQueryAnswerWithWork_execution (source target : List ℕ) (N : ℕ) + (epsilon : BinaryFraction) (hlarge : physicalLargeInput N epsilon) + (hsize : source.length + target.length ≤ N) + (occurrence : BinaryMemo PositionCounts) (symbolBits positionBits : ℕ) + (hs : ∀ z ∈ source, z < 2 ^ symbolBits) (ht : ∀ z ∈ target, z < 2 ^ symbolBits) + (hp : target.length ≤ 2 ^ positionBits) + (htable : occurrence = occurrenceBuild symbolBits positionBits target.zipIdx) + (execution : ComputedExecutionOutcome source target N) : + bitWordValue (computedQueryAnswerWithWork source target N occurrence symbolBits positionBits + (computedExecutionAccepted source target N execution)).1 = + computedFullAnswer source target N (.inr execution) := by + have hf : 3 ≤ smallLogExponent N := by + have h := (Nat.pow_le_pow_iff_right (by decide : 1 < (2 : ℕ))).mp hlarge.2.1.1 + omega + rw [computedQueryAnswerWithWork_value source target N occurrence symbolBits positionBits _ + (largeAccuracyInput_pos N epsilon.value hlarge.2.1) hlarge.2.1.1 hf hsize hlarge.2.2 hs ht hp htable] + change _ = physicalFamilyMemoAnswer source target N (integerParameters N).P (integerParameters N).T + (integerParameters N).S (inputHeight N) (Nat.two_pow_pos _) + (16384 * inputHeight N + 5) (computedFamilyMemoCode source target N (inputHeight N ^ 2)) + (finalTargetState target.length) (computedExecutionAccepted source target N execution) + simp only [physicalFamilyMemoAnswer, finalTargetState, substring, List.drop_zero, List.take_length, + computedFamilyResult] + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedQueryProgramWork.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedQueryProgramWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..bdac69d8fda6037c2bc7b49d4845a969b40f2002 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedQueryProgramWork.lean @@ -0,0 +1,85 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryProgramPolynomial +import OAI.Combinatorics.EditApproximation.Refinement.ComputedPreparedInputBounds +import OAI.Combinatorics.EditApproximation.Refinement.ComputedLocalKernelWork + +namespace OAI + +namespace EditApproximation +open Filter + +/-- Degree of the complete adaptive program when physical reads have degree `K`. -/ +def computedQueryProgramDegree (K : ℕ) : ℕ := (K + 1) * (16 * queryLocalProgramBitDegree) + +theorem computedQueryProgramBudget_cap (K : ℕ) : + ∀ᶠ N : ℕ in atTop, ∀ t W : ℕ, t ≤ inputHeight N ^ 2 → + W ≤ computedLocalKernelBudget K N → + BinaryFraction.queryLocalProgramBitBudget (integerParameters N).M N (integerParameters N).P + (inputSmallLog N) (40 * smallLogExponent N) (heightExponent N / 20) (smallLogExponent N) + (inputHeight N ^ 8) + (inputHeight N ^ ((100 * (integerParameters N).M + 100000) * + (coarseExponent (inputSmallLog N) + 1))) t W ≤ + computedLocalKernelBudget (computedQueryProgramDegree K) N := by + filter_upwards [computedPreparedNumericBounds, + inputSmallLog_tendsto.eventually (eventually_ge_atTop 64)] with N hn hell + intro t W ht hW + let H := inputHeight N + let M := (integerParameters N).M + let P := (integerParameters N).P + let p := coarseExponent (inputSmallLog N) + let L := (100 * M + 100000) * (p + 1) + let S := H ^ L + let X := S ^ (K + 1) + have hH : 64 ≤ H := hell.trans (computed_smallLog_le_height N) + have hp : 0 < H := by omega + have hL : 40 ≤ L := by + dsimp only [L] + nlinarith only [Nat.zero_le M, Nat.zero_le p, Nat.zero_le (M * p)] + have hHS : H ≤ S := Nat.le_pow (by omega) + have hSX : S ≤ X := Nat.le_pow (by omega) + have hX : 64 ≤ X := hH.trans (hHS.trans hSX) + have hz : BinaryFraction.zero.width ≤ H ^ 8 := by + change 1 ≤ H ^ 8 + exact one_le_pow₀ (by omega) + have hzv : BinaryFraction.zero.value = 0 := by + norm_num [BinaryFraction.value, BinaryFraction.zero, SignedBinary.value, signedMagnitude, bitWordValue] + have hnum := hn 0 0 (by omega) t ht BinaryFraction.zero BinaryFraction.zero + BinaryFraction.zero BinaryFraction.zero BinaryFraction.zero hz hz hz hz hz + (by rw [hzv]; simp) + (by rw [hzv]; norm_num) + (fun _ _ => 0) (by intro b r; simp) + change BinaryFraction.PreparedKernelNumericBounds (nx := 0) (ny := 0) (M := M) + N P (inputSmallLog N) (40 * smallLogExponent N) H (inputSmallLog N ^ 80) + (heightExponent N / 20) (smallLogExponent N) (H ^ 8) (H ^ 5) S t + BinaryFraction.zero BinaryFraction.zero BinaryFraction.zero BinaryFraction.zero BinaryFraction.zero + (fun _ _ => 0) at hnum + have hB : H ^ 8 ≤ S := by have := hnum.wordCap; omega + have he : 40 * smallLogExponent N ≤ S := by + have := hnum.thetaSize + omega + have heM : heightExponent N / 20 ≤ S := by have := hnum.scaleSizes; omega + have heF : smallLogExponent N ≤ S := by have := hnum.scaleSizes; omega + have hTheta : 2 ^ (40 * smallLogExponent N) ≤ S := by + calc + _ = inputSmallLog N ^ 40 := by unfold inputSmallLog; rw [← pow_mul]; congr 1; omega + _ ≤ H ^ 40 := Nat.pow_le_pow_left (computed_smallLog_le_height N) 40 + _ ≤ S := Nat.pow_le_pow_right hp hL + have hWX : W ≤ X := by + apply hW.trans + change H ^ (L * K) ≤ (H ^ L) ^ (K + 1) + rw [← pow_mul] + exact Nat.pow_le_pow_right hp (Nat.mul_le_mul_left L (Nat.le_succ K)) + have h := queryLocalProgramBitBudget_uniform_cap M N P (inputSmallLog N) + (40 * smallLogExponent N) (heightExponent N / 20) (smallLogExponent N) (H ^ 8) S t W X + hX hnum.inputSize (hnum.arityCap.trans hSX) (hnum.precisionCap.trans hSX) + ((computed_smallLog_le_height N).trans (hHS.trans hSX)) (he.trans hSX) (heM.trans hSX) + (heF.trans hSX) (hB.trans hSX) hSX (hnum.timeCap.trans hSX) hWX + (hTheta.trans hSX) (hnum.actionCap.trans hSX) (hnum.cartesianCap.trans hSX) + apply h.trans_eq + change ((H ^ L) ^ (K + 1)) ^ (16 * queryLocalProgramBitDegree) = + H ^ (L * computedQueryProgramDegree K) + rw [← pow_mul, ← pow_mul] + congr 1 + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedQueryRawWork.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedQueryRawWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..8628ba02e70f158c43d2045dbcaf026f178ff47b --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedQueryRawWork.lean @@ -0,0 +1,103 @@ +import OAI.Combinatorics.EditApproximation.Refinement.ComputedQueryTableWork +import OAI.Combinatorics.EditApproximation.Refinement.ComputedQueryNormalizationBudget +import OAI.Combinatorics.EditApproximation.Refinement.ComputedQueryExecution + +namespace OAI + +namespace EditApproximation +open Filter BinaryFraction +attribute [local instance] queryArityNeZero queryRoundsNeZero +attribute [local irreducible] queryChargedFamilyTable localRequestValue + +def computedQueryRawWorkDegree : ℕ := max 1 computedTableQueryDegree +def computedQueryRawWidthDegree : ℕ := max 1 queryRawWordDegree + +/-- Every raw body is charged on the actual, proved normalized-child oracle. -/ +theorem computedQueryMemoRaw_bounds : + ∀ᶠ N : ℕ in atTop, ∀ source target : List ℕ, source.length + target.length ≤ N → + ∀ (input : ComputedFamilyInput source target N) + (occurrence : BinaryMemo PositionCounts) (symbolBits positionBits : ℕ), + symbolBits ≤ inputHeight N ^ 3 → positionBits ≤ inputHeight N ^ 3 → + (∀ z ∈ source, z < 2 ^ symbolBits) → (∀ z ∈ target, z < 2 ^ symbolBits) → + target.length ≤ 2 ^ positionBits → occurrence = occurrenceBuild symbolBits positionBits target.zipIdx → + ∀ key : ComputedFamilyMemoKey source target N, + let oracle := fun child : {child : ComputedFamilyMemoKey source target N // + SourceRanked.rank ChargedPhysicalRequest.rank child < + SourceRanked.rank ChargedPhysicalRequest.rank key} => rankedBitProgramValue (SourceRanked.rank ChargedPhysicalRequest.rank) + (computedQueryMemoNormalized source target N occurrence symbolBits positionBits input) child.val + (computedQueryMemoRaw source target N occurrence symbolBits positionBits input key).work oracle (fun _ => 0) ≤ + computedLocalKernelBudget computedQueryRawWorkDegree N ∧ + ((computedQueryMemoRaw source target N occurrence symbolBits positionBits input key).value oracle).width ≤ + computedLocalKernelBudget computedQueryRawWidthDegree N := by + filter_upwards [computedQueryTable_work_width, computedQueryRawWidth_cap, computedQueryMass_word, + eventually_ge_atTop 1, inputSmallLog_tendsto.eventually (eventually_ge_atTop (2 ^ 1000))] + with N htable hraw hmass hN hell + intro source target hsize input occurrence symbolBits positionBits hsb hpb hs ht hp hoc key + dsimp only + have hsmall : 200 ≤ inputSmallLog N := two_hundred_le_two_pow_thousand.trans hell + have hH : 64 ≤ inputHeight N := (by omega : 64 ≤ inputSmallLog N).trans (computed_smallLog_le_height N) + have hf : 3 ≤ smallLogExponent N := by + have h := (Nat.pow_le_pow_iff_right (by decide : 1 < (2 : ℕ))).mp hell + omega + have hg := computed_kernel_guard_cost N hH + have hsmallBudget : inputHeight N + 3 ≤ computedLocalKernelBudget 1 N := by + have hpow : inputHeight N ≤ inputHeight N ^ 8 := Nat.le_pow (by decide) + omega + have hworkMono := computedLocalKernelBudget_mono N 1 computedQueryRawWorkDegree (Nat.le_max_left _ _) + have hwidthMono := computedLocalKernelBudget_mono N 1 computedQueryRawWidthDegree (Nat.le_max_left _ _) + have hrawMono := computedLocalKernelBudget_mono N queryRawWordDegree computedQueryRawWidthDegree + (Nat.le_max_right _ _) + have htableMono := computedLocalKernelBudget_mono N computedTableQueryDegree computedQueryRawWorkDegree + (Nat.le_max_right _ _) + cases key with + | inl key => + have hr := computedFamilyRange_bits_le source target N (inputHeight N ^ 2) hmass key + have hc : (input.2 key).val < 2 ^ inputHeight N := (input.2 key).isLt.trans_le + ((Nat.le_pow_clog (by decide : 1 < 2) _).trans + (Nat.pow_le_pow_right (by decide : 0 < 2) hr)) + have hb : Nat.size (input.2 key).val ≤ inputHeight N := Nat.size_le.mpr hc + change Nat.size (input.2 key).val + 3 ≤ _ ∧ (nat (input.2 key).val).width ≤ _ + exact ⟨(by omega : Nat.size (input.2 key).val + 3 ≤ computedLocalKernelBudget 1 N).trans hworkMono, + (nat_width_le _).trans ((by omega : Nat.size (input.2 key).val + 2 ≤ computedLocalKernelBudget 1 N).trans hwidthMono)⟩ + | inr key => + cases key with + | inl entry => + have hb : Nat.size (clampedSeedNat input.1 entry) ≤ inputHeight N := + (Nat.size_le_size (Nat.le_of_lt_succ (input.1 entry).isLt)).trans (computed_input_size_le_height N) + change 0 ≤ _ ∧ (nat (clampedSeedNat input.1 entry)).width ≤ _ + exact ⟨Nat.zero_le _, (nat_width_le _).trans + ((by omega : Nat.size (clampedSeedNat input.1 entry) + 2 ≤ computedLocalKernelBudget 1 N).trans hwidthMono)⟩ + | inr parent => + let oracle := fun child : {child : ComputedFamilyMemoKey source target N // + SourceRanked.rank ChargedPhysicalRequest.rank child < + SourceRanked.rank ChargedPhysicalRequest.rank (.inr (.inr parent) : ComputedFamilyMemoKey source target N)} => rankedBitProgramValue (SourceRanked.rank ChargedPhysicalRequest.rank) + (computedQueryMemoNormalized source target N occurrence symbolBits positionBits input) child.val + let tableOracle : ComputedQueryTableKey source target N parent → BinaryFraction := + fun child => oracle (SourceRanked.child ChargedPhysicalRequest.rank (.inr parent) child) + have hw (child) : (tableOracle child).width ≤ inputHeight N ^ 3 := + computedQueryMemoNormalized_width source target N occurrence symbolBits positionBits input hN hsmall hf + hsize hmass hs ht hp hoc _ + have hv (child) : (tableOracle (Sum.inr child)).value = computedFamilyTableValue source target N input child.val := + (computedQueryMemoNormalized_correct source target N occurrence symbolBits positionBits input hf hs ht hp hoc _).1 + have hb := htable source target hsize input occurrence symbolBits positionBits hsb hpb parent tableOracle hw hv + change (BitQuery.mapKeysWithWork (fun child => + (SourceRanked.child ChargedPhysicalRequest.rank (.inr parent) child, 1)) + (computedQueryTableProgram source target N occurrence symbolBits positionBits parent)).work oracle (fun _ => 0) ≤ _ ∧ + ((BitQuery.mapKeysWithWork (fun child => + (SourceRanked.child ChargedPhysicalRequest.rank (.inr parent) child, 1)) + (computedQueryTableProgram source target N occurrence symbolBits positionBits parent)).value oracle).width ≤ _ + constructor + · exact (BitQuery.mapKeysWithWork_work + (fun child : ComputedQueryTableKey source target N parent => + (SourceRanked.child ChargedPhysicalRequest.rank (.inr parent) child, 1)) + (computedQueryTableProgram source target N occurrence symbolBits positionBits parent) + oracle (fun _ => 0)).trans_le (hb.1.trans htableMono) + · exact (congrArg BinaryFraction.width (BitQuery.mapKeysWithWork_value + (fun child : ComputedQueryTableKey source target N parent => + (SourceRanked.child ChargedPhysicalRequest.rank (.inr parent) child, 1)) + (computedQueryTableProgram source target N occurrence symbolBits positionBits parent) + oracle)).trans_le (hb.2.trans (hraw.trans hrawMono)) + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedQueryReadBudget.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedQueryReadBudget.lean new file mode 100644 index 0000000000000000000000000000000000000000..5622abb7f980b4f91ed4d52d675729216dab1c98 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedQueryReadBudget.lean @@ -0,0 +1,57 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryCallbackPolynomial +import OAI.Combinatorics.EditApproximation.Refinement.ComputedLocalKernelWork + +namespace OAI + +namespace EditApproximation +open Filter + +/-- Degree contributed by guards, physical means, and scalar-source reads. -/ +def computedQueryReadDegree (K : ℕ) : ℕ := (K + 1) * queryCallbackShellDegree + +theorem computedQueryReadBudget_cap (K : ℕ) : + ∀ᶠ N : ℕ in atTop, ∀ T J B V C W : ℕ, + T ≤ inputHeight N ^ 2 → J ≤ inputHeight N → B ≤ inputHeight N ^ 8 → + V ≤ inputHeight N ^ 3 → C ≤ computedLocalKernelBudget K N → W ≤ computedLocalKernelBudget K N → + BinaryFraction.queryPhysicalDataBudget T J B V C (BinaryFraction.queryFamilySourceReadBudget J B W) ≤ + computedLocalKernelBudget (computedQueryReadDegree K) N := by + filter_upwards [inputSmallLog_tendsto.eventually (eventually_ge_atTop 64)] with N hell + intro T J B V C W hT hJ hB hV hC hW + let H := inputHeight N + let L := (100 * (integerParameters N).M + 100000) * (coarseExponent (inputSmallLog N) + 1) + let S := H ^ L + let X := S ^ (K + 1) + have hH : 64 ≤ H := hell.trans (computed_smallLog_le_height N) + have hp : 0 < H := by omega + have hL : 8 ≤ L := by + have h := Nat.le_mul_of_pos_right (100 * (integerParameters N).M + 100000) + (by omega : 0 < coarseExponent (inputSmallLog N) + 1) + dsimp only [L] + omega + have hSX : S ≤ X := Nat.le_pow (by omega) + have hHS : H ≤ S := Nat.le_pow (by omega) + have h8S : H ^ 8 ≤ S := Nat.pow_le_pow_right hp hL + have h2S : H ^ 2 ≤ S := Nat.pow_le_pow_right hp (by omega) + have h3S : H ^ 3 ≤ S := Nat.pow_le_pow_right hp (by omega) + have hcX : C ≤ X := by + apply hC.trans + change H ^ (L * K) ≤ (H ^ L) ^ (K + 1) + rw [← pow_mul] + exact Nat.pow_le_pow_right hp (Nat.mul_le_mul_left L (Nat.le_succ K)) + have hwX : W ≤ X := by + apply hW.trans + change H ^ (L * K) ≤ (H ^ L) ^ (K + 1) + rw [← pow_mul] + exact Nat.pow_le_pow_right hp (Nat.mul_le_mul_left L (Nat.le_succ K)) + have h := queryCallbackShell_fixedPower T J B V C W X + ((by omega : 2 ≤ H).trans (hHS.trans hSX)) + (hT.trans (h2S.trans hSX)) (hJ.trans (hHS.trans hSX)) (hB.trans (h8S.trans hSX)) + (hV.trans (h3S.trans hSX)) hcX hwX + apply h.trans_eq + change ((H ^ L) ^ (K + 1)) ^ queryCallbackShellDegree = H ^ (L * computedQueryReadDegree K) + rw [← pow_mul, ← pow_mul] + congr 1 + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedQueryRegisters.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedQueryRegisters.lean new file mode 100644 index 0000000000000000000000000000000000000000..06263854542d3bdec227d7fe7c2013751a1951e1 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedQueryRegisters.lean @@ -0,0 +1,121 @@ +import OAI.Combinatorics.EditApproximation.Refinement.ComputedQueryWidth +import OAI.Combinatorics.EditApproximation.Refinement.ComputedPreparedWords +import OAI.Combinatorics.EditApproximation.Refinement.ComputedQueryBudgetAlgebra + +namespace OAI + +namespace EditApproximation +open BinaryFraction + +/-- The remaining scalar premises of the concrete table dispatcher. -/ +structure ComputedQueryRegisters (N ny J : ℕ) + (request : PhysicalTableRequest (integerParameters N).M J ny) : Prop where + targetSuccessor : Nat.size (ny + 1) + 2 ≤ inputHeight N ^ 8 + initial : Nat.size ((32 * inputSmallLog N + 1) * N) + 3 ≤ inputHeight N ^ 8 + depth : Nat.size J ≤ inputHeight N ^ 8 + index : Nat.size request.index ≤ inputHeight N ^ 8 + warmup : Nat.size (integerParameters N).T ≤ inputHeight N ^ 8 + refinement : Nat.size (integerParameters N).S ≤ inputHeight N ^ 8 + rank : Nat.size (request.combinedRank (integerParameters N).T (integerParameters N).S) ≤ inputHeight N ^ 8 + pass : Nat.size request.pass ≤ inputHeight N ^ 8 + copy : Nat.size request.copy ≤ inputHeight N ^ 8 + passes : Nat.size (computedSeedPassCount N + 1) ≤ inputHeight N ^ 8 + copies : Nat.size (inputHeight N ^ 2 + 1) ≤ inputHeight N ^ 8 + multiplier : Nat.size (scheduledSeedMultiplier N (request.pass - 1)) + 2 ≤ inputHeight N ^ 8 + mean : warmupAverageWordBudget (integerParameters N).T (inputHeight N ^ 3) ≤ inputHeight N ^ 8 + +/-- None of these register bounds assumes a successful random draw. -/ +theorem computedQueryRegisters (N ny J : ℕ) (hN : 0 < N) + (hell : 2 ^ 1000 ≤ inputSmallLog N) (hny : ny ≤ N) (hJ : J ≤ inputHeight N) + (request : PhysicalTableRequest (integerParameters N).M J ny) + (hr : request.Bounded (computedSeedPassCount N + 1) (inputHeight N ^ 2) + (integerParameters N).T (integerParameters N).S) : ComputedQueryRegisters N ny J request := by + let H := inputHeight N + have hH : 64 ≤ H := (two_hundred_le_two_pow_thousand.trans hell |>.trans' (by decide : 64 ≤ 200)).trans + (computed_smallLog_le_height N) + have hp : 0 < H := by omega + have h1 : 1 ≤ H := by omega + have h28 : H ^ 2 ≤ H ^ 8 := Nat.pow_le_pow_right hp (by decide) + have h38 : H ^ 3 ≤ H ^ 8 := Nat.pow_le_pow_right hp (by decide) + have h48 : H ^ 4 ≤ H ^ 8 := Nat.pow_le_pow_right hp (by decide) + have hH8 : H ≤ H ^ 8 := Nat.le_pow (by decide) + have hhist : (integerParameters N).T + (integerParameters N).S + 1 ≤ H ^ 2 := + computed_history_budget_le_height_sq N (by omega) + have hT : (integerParameters N).T ≤ H ^ 2 := by omega + have hS : (integerParameters N).S ≤ H ^ 2 := by omega + have hindex : request.index ≤ H ^ 2 := hr.2.2.trans (by omega) + have hpasses : computedSeedPassCount N ≤ H := computedSeedPassCount_le_height N hN hell + have hpass : request.pass ≤ H := (Nat.le_of_lt_succ hr.1).trans hpasses + have hcopy : request.copy ≤ H ^ 2 := hr.2.1.le + have hsize : Nat.size N ≤ H := computed_input_size_le_height N + have hsmall : Nat.size (inputSmallLog N) ≤ H := + (Nat.size_le.mpr Nat.lt_two_pow_self).trans (computed_smallLog_le_height N) + have hinit : Nat.size ((32 * inputSmallLog N + 1) * N) + 3 ≤ H ^ 2 := by + have h1 := natural_product_bit_length 32 (inputSmallLog N) + have h2 := natural_sum_bit_length (32 * inputSmallLog N) 1 + have h3 := natural_product_bit_length (32 * inputSmallLog N + 1) N + have h32 : Nat.size 32 = 6 := by decide + simp only [h32, Nat.size_one] at h1 h2 + have hpoly : 2 * H + 11 ≤ H ^ 2 := by nlinarith only [hH] + omega + have htarget : Nat.size (ny + 1) + 2 ≤ H ^ 2 := by + have hs := natural_sum_bit_length ny 1 + have hn := (Nat.size_le_size hny).trans hsize + simp only [Nat.size_one] at hs + have hpoly : H + 4 ≤ H ^ 2 := by nlinarith only [hH] + omega + have hrank : request.combinedRank (integerParameters N).T (integerParameters N).S ≤ H ^ 4 := by + have hm := Nat.mul_le_mul hpass hhist + have hd : request.remainingDepth ≤ H := (Nat.sub_le _ _).trans hJ + have hc : H + H * H ^ 2 + H ^ 2 ≤ H ^ 4 := by + have h2 : 3 * H ≤ H ^ 2 := by nlinarith only [hH] + have h3 : H ≤ H ^ 2 := Nat.le_pow (by decide) + have h4 : H * H ^ 2 ≤ H ^ 4 := by + exact (Nat.mul_le_mul_right (H ^ 2) h3).trans_eq (by ring) + nlinarith only [hH, h2, h3, h4, sq_nonneg (H * (H - 2))] + unfold PhysicalTableRequest.combinedRank PhysicalTableRequest.rank + omega + have hmult : Nat.size (scheduledSeedMultiplier N (request.pass - 1)) + 2 ≤ H ^ 3 := by + unfold scheduledSeedMultiplier + rw [Nat.size_pow] + have hd : dyadicSeedExponent (smallLogExponent N) (computedSeedInitialExponent N) + (request.pass - 1) ≤ computedSeedInitialExponent N := Nat.sub_le _ _ + have hw := computed_window_le_height_cube N hN (by omega) (by omega) + change computedSeedInitialExponent N + 8 ≤ H ^ 3 at hw + omega + have hmean : warmupAverageWordBudget (integerParameters N).T (H ^ 3) ≤ H ^ 8 := by + have hts : Nat.size (integerParameters N).T ≤ H ^ 2 := + (Nat.size_le.mpr Nat.lt_two_pow_self).trans hT + have hm := Nat.mul_le_mul_right (H ^ 3 + 1) hT + have h5 : H ^ 2 * (H ^ 3 + 1) = H ^ 5 + H ^ 2 := by ring + rw [h5] at hm + have h25 : H ^ 2 ≤ H ^ 5 := Nat.pow_le_pow_right hp (by decide) + have h35 : H ^ 3 ≤ H ^ 5 := Nat.pow_le_pow_right hp (by decide) + have hu : 1 ≤ H ^ 5 := one_le_pow₀ h1 + have hcoeff : 50 ≤ H ^ 3 := (by omega : 50 ≤ H).trans (Nat.le_pow (by decide)) + have h58 : 50 * H ^ 5 ≤ H ^ 8 := + (Nat.mul_le_mul_right (H ^ 5) hcoeff).trans_eq (by ring) + unfold warmupAverageWordBudget bandMassTotalStorageBudget + nlinarith only [hts, hm, h25, h35, hu, h58] + refine ⟨htarget.trans h28, hinit.trans h28, + ((Nat.size_le.mpr Nat.lt_two_pow_self).trans hJ).trans hH8, + ((Nat.size_le.mpr Nat.lt_two_pow_self).trans hindex).trans h28, + ((Nat.size_le.mpr Nat.lt_two_pow_self).trans hT).trans h28, + ((Nat.size_le.mpr Nat.lt_two_pow_self).trans hS).trans h28, + ((Nat.size_le.mpr Nat.lt_two_pow_self).trans hrank).trans h48, + ((Nat.size_le.mpr Nat.lt_two_pow_self).trans hpass).trans hH8, + ((Nat.size_le.mpr Nat.lt_two_pow_self).trans hcopy).trans h28, + ?_, ?_, hmult.trans h38, hmean⟩ + · have hbound : computedSeedPassCount N + 1 ≤ H ^ 2 := by nlinarith only [hpasses, hH] + exact ((Nat.size_le.mpr Nat.lt_two_pow_self).trans hbound).trans h28 + · have hbound : H ^ 2 + 1 ≤ H ^ 3 := by + have hs := Nat.mul_le_mul_right (H ^ 2) (by omega : 2 ≤ H) + rw [← pow_succ'] at hs + change 2 * H ^ 2 ≤ H ^ 3 at hs + have hu : 1 ≤ H ^ 2 := one_le_pow₀ h1 + omega + exact ((Nat.size_le.mpr Nat.lt_two_pow_self).trans hbound).trans h38 + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedQuerySetup.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedQuerySetup.lean new file mode 100644 index 0000000000000000000000000000000000000000..b0354633d352ff96a38d7542c55c34c9dbd1d58c --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedQuerySetup.lean @@ -0,0 +1,87 @@ +import OAI.Combinatorics.EditApproximation.Refinement.ComputedQueryMemo +import OAI.Combinatorics.EditApproximation.Geometry.HeightPowerWork +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation +open Filter + +/- One materialized row of the shared pass-parameter array. -/ + + +/-- All pass constants and the normalization base are constructed before evaluation. -/ + + +theorem computedQuerySetupWithWork_pass (N : ℕ) (pass : Fin (computedSeedPassCount N + 1)) : + ((computedQuerySetupWithWork N).1.1.get pass) = + ((scheduledSeedWordWithWork N pass.val).1, computedQueryParameters N pass.val) := by + simp only [computedQuerySetupWithWork, vectorMapWithWork_value, computedQueryPassWithWork, + computedQueryParameters] + +theorem computedQuerySetupWithWork_base (N : ℕ) : + (computedQuerySetupWithWork N).1.2 = computedQueryBase N := by + simp only [computedQuerySetupWithWork, computedQueryBase] + +theorem computedQuerySetupWithWork_cost (N : ℕ) (hN : 0 < N) + (hell : 2 ^ 1000 ≤ inputSmallLog N) : + (computedQuerySetupWithWork N).2 ≤ inputHeight N ^ 12 := by + let H := inputHeight N + have hH : 64 ≤ H := (by have := two_hundred_le_two_pow_thousand.trans hell; omega : + 64 ≤ inputSmallLog N).trans (computed_smallLog_le_height N) + have hp : 0 < H := by omega + have hword : (inputSmallLog N).bits.length ≤ Nat.size (inputSmallLog N) := by + rw [← Nat.size_eq_bits_len] + have hwidth : (inputSmallLog N).bits.length ≤ H := hword.trans + ((Nat.size_le.mpr Nat.lt_two_pow_self).trans (computed_smallLog_le_height N)) + have hpass : computedSeedPassCount N + 1 ≤ H ^ 2 := by + have h := computedSeedPassCount_le_height N hN hell + change computedSeedPassCount N ≤ H at h + nlinarith only [h, hH] + have h3 : H ^ 3 ≤ H ^ 9 := Nat.pow_le_pow_right hp (by decide) + have hu : 1 ≤ H ^ 9 := one_le_pow₀ (by omega) + have hc (pass : Fin (computedSeedPassCount N + 1)) : + (computedQueryPassWithWork N pass.val).2 ≤ 4 * H ^ 9 := by + have hs := (scheduledSeedWordWithWork_bounds N pass.val hN (by omega) hH).2 + have hw := refinementParameterWordsWithWork_cost N pass.val (inputSmallLog N).bits + (by rw [bitWordValue_bits]; exact Nat.two_pow_pos _) hword hH + change _ ≤ H ^ 3 at hs + change _ ≤ H ^ 9 at hw + unfold computedQueryPassWithWork + dsimp only + omega + have hv := BinaryFraction.vectorMapWithWork_cost_le (computedSeedPassCount N + 1) + (fun i => computedQueryPassWithWork N i.val) (4 * H ^ 9) hc + have hvc : (vectorMapWithWork (computedSeedPassCount N + 1) + (fun i => computedQueryPassWithWork N i.val)).2 ≤ 5 * H ^ 11 := by + have hmul := Nat.mul_le_mul_right (4 * H ^ 9 + 6) hpass + have h2 : H ^ 2 ≤ H ^ 11 := Nat.pow_le_pow_right hp (by decide) + have hprod : H ^ 2 * (4 * H ^ 9 + 6) = 4 * H ^ 11 + 6 * H ^ 2 := by ring + have hH2 : H ^ 2 * 6 ≤ H ^ 11 := by + have hcoef : 6 ≤ H ^ 9 := (by omega : 6 ≤ H).trans (Nat.le_pow (by decide)) + exact (Nat.mul_le_mul_left (H ^ 2) hcoef).trans_eq (by ring) + rw [hprod] at hmul + omega + have hb := refinementBaseWithWork_cost (inputSmallLog N).bits H hwidth + have hbc : (refinementBaseWithWork (inputSmallLog N).bits).2 ≤ H ^ 8 := by + have hlinear : 11 * (H + 1) + 1 ≤ 12 * H := by omega + have hs := Nat.pow_le_pow_left hlinear 2 + have hpoly : bitPowerBitBudget 10 H + 200 * (H + 1) ≤ 400000 * H ^ 2 := by + unfold bitPowerBitBudget + nlinarith only [hs, hH] + have hcoef : 400000 ≤ H ^ 6 := + (by norm_num : 400000 ≤ (64 : ℕ) ^ 6).trans (Nat.pow_le_pow_left hH 6) + exact hb.trans (hpoly.trans ((Nat.mul_le_mul_right (H ^ 2) hcoef).trans_eq (by ring))) + have h811 : H ^ 8 ≤ H ^ 11 := Nat.pow_le_pow_right hp (by decide) + have hu11 : 1 ≤ H ^ 11 := one_le_pow₀ (by omega) + have hfinal : 11 * H ^ 11 ≤ H ^ 12 := + (Nat.mul_le_mul_right (H ^ 11) (by omega : 11 ≤ H)).trans_eq (by ring) + change (vectorMapWithWork (computedSeedPassCount N + 1) + (fun i => computedQueryPassWithWork N i.val)).2 + + (refinementBaseWithWork (inputSmallLog N).bits).2 + 5 ≤ H ^ 12 + omega + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedQuerySetupSpace.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedQuerySetupSpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..672fa6810897cc5c8ae33f51d74a2ed513c84b46 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedQuerySetupSpace.lean @@ -0,0 +1,93 @@ +import OAI.Combinatorics.EditApproximation.Refinement.ComputedQuerySetup +import OAI.Combinatorics.EditApproximation.Queries.QueryGroupSetupSpace +import OAI.Combinatorics.EditApproximation.Binary.BinaryOptimizerSpace +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation +open BinaryFraction + +namespace BinaryFraction + + + +theorem onlineParametersAllocation_le_work (word : List Bool) (hpos : 0 < bitWordValue word) : + onlineParametersAllocation word ≤ (onlineParametersWithWork word hpos).2 := by + have h5 := bitPowerAllocation_le_work word 5 + have h4 := bitPowerAllocation_le_work word 4 + unfold onlineParametersAllocation onlineParametersWithWork + dsimp only + omega + + + +theorem refinementDecrementAllocation_le_work (word : List Bool) (hpos : 0 < bitWordValue word) : + refinementDecrementAllocation word ≤ (refinementDecrementWithWork word hpos).2 := + Nat.add_le_add_right (bitPowerAllocation_le_work word 10) 1 + +end BinaryFraction + + + +theorem scheduledRefinementAllocation_le_work (N pass : ℕ) : + scheduledRefinementAllocation N pass ≤ (scheduledRefinementWordWithWork N pass).2 := by + unfold scheduledRefinementAllocation scheduledRefinementWordWithWork + split_ifs + · have h := signedPowerTwoAllocation_le_work + ((dyadicSeedExponent (smallLogExponent N) (computedSeedInitialExponent N) pass - smallLogExponent N : ℕ) : ℤ) + dsimp only + omega + · decide + + + +theorem refinementParameterAllocation_le_work (N pass : ℕ) (word : List Bool) + (hpos : 0 < bitWordValue word) : + refinementParameterAllocation N pass word ≤ (refinementParameterWordsWithWork N pass word hpos).2 := by + have ho := onlineParametersAllocation_le_work word hpos + have hf := scheduledRefinementAllocation_le_work N pass + have hd := refinementDecrementAllocation_le_work word hpos + unfold refinementParameterAllocation refinementParameterWordsWithWork + dsimp only + omega + + + +theorem refinementBaseAllocation_le_work (word : List Bool) : + refinementBaseAllocation word ≤ (refinementBaseWithWork word).2 := by + have hp := bitPowerAllocation_le_work word 10 + have hi := bitAddAllocation_le_work (bitPowerWithWork word 10).1 [true] false + have ht := trimBitWordAllocation_le_work (bitAddWithWork (bitPowerWithWork word 10).1 [true] false).1 + unfold refinementBaseAllocation refinementBaseWithWork + dsimp only + omega + + + +theorem computedQueryPassAllocation_le_work (N pass : ℕ) : + computedQueryPassAllocation N pass ≤ (computedQueryPassWithWork N pass).2 := by + have hs := signedPowerTwoAllocation_le_work + ((dyadicSeedExponent (smallLogExponent N) (computedSeedInitialExponent N) pass : ℕ) : ℤ) + have hp := refinementParameterAllocation_le_work N pass (inputSmallLog N).bits + (by rw [bitWordValue_bits]; exact Nat.two_pow_pos _) + unfold computedQueryPassAllocation computedQueryPassWithWork scheduledSeedWordWithWork + dsimp only + omega + + + +theorem computedQuerySetupAllocation_le_work (N : ℕ) : + computedQuerySetupAllocation N ≤ (computedQuerySetupWithWork N).2 := by + have hv := vectorMapAllocation_le_work (computedSeedPassCount N + 1) + (fun i => computedQueryPassWithWork N i.val) (fun i => computedQueryPassAllocation N i.val) + (fun i => computedQueryPassAllocation_le_work N i.val) + have hb := refinementBaseAllocation_le_work (inputSmallLog N).bits + unfold computedQuerySetupAllocation computedQuerySetupWithWork + dsimp only + omega + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedQueryStorage.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedQueryStorage.lean new file mode 100644 index 0000000000000000000000000000000000000000..60c7c283677fe1ed8ebfe2ebe96ea2f3faf1a083 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedQueryStorage.lean @@ -0,0 +1,92 @@ +import OAI.Combinatorics.EditApproximation.Refinement.ComputedQueryExecution +import OAI.Combinatorics.EditApproximation.Refinement.ComputedQueryWidth +import OAI.Combinatorics.EditApproximation.Binary.BitMemoStorage + +namespace OAI + +namespace EditApproximation +attribute [local instance] queryArityNeZero queryRoundsNeZero + +section Storage +variable (source target : List ℕ) (N : ℕ) + (occurrence : BinaryMemo PositionCounts) (symbolBits positionBits : ℕ) + (input : ComputedFamilyInput source target N) (hN : 0 < N) + (hell : 2 ^ 1000 ≤ inputSmallLog N) (hf : 3 ≤ smallLogExponent N) + (hsize : source.length + target.length ≤ N) + (hMass : Nat.size (localOnlineMassBound (integerParameters N).M (integerParameters N).P + (inputHeight N)) ≤ inputHeight N) + (hs : ∀ z ∈ source, z < 2 ^ symbolBits) (ht : ∀ z ∈ target, z < 2 ^ symbolBits) + (hp : target.length ≤ 2 ^ positionBits) + (htable : occurrence = occurrenceBuild symbolBits positionBits target.zipIdx) + +include hN hell hf hsize hMass hs ht hp htable in +theorem computedQueryMemoResult_width : + (computedQueryMemoResult source target N occurrence symbolBits positionBits input).value.width ≤ + inputHeight N ^ 3 := by + have h := (rankedBitMemoEvaluate_sound (SourceRanked.rank ChargedPhysicalRequest.rank) + (computedQueryMemoNormalized source target N occurrence symbolBits positionBits input) + (16384 * inputHeight N + 5) (computedFamilyMemoCode source target N (inputHeight N ^ 2)) + (computedFamilyMemoCode_injective source target N (inputHeight N ^ 2) hN + (two_hundred_le_two_pow_thousand.trans hell)) + (computedFamilyMemoCode_fits source target N (inputHeight N ^ 2) hN hell hsize le_rfl hMass) + (.inr (localFinalRootRequest target N (integerParameters N).T (integerParameters N).S + (inputHeight N) (Nat.two_pow_pos _) (finalTargetState target.length))) .empty + (bitMemoSound_empty _ _ _)).1 + change (computedQueryMemoResult source target N occurrence symbolBits positionBits input).value = _ at h + rw [h] + exact computedQueryMemoNormalized_width source target N occurrence symbolBits positionBits input + hN (two_hundred_le_two_pow_thousand.trans hell) hf hsize hMass hs ht hp htable _ + +include hN hell hf hsize hMass hs ht hp htable in +theorem computedQueryMemoResult_allWidths : + BinaryMemo.AllValues (fun word => word.width ≤ inputHeight N ^ 3) + (computedQueryMemoResult source target N occurrence symbolBits positionBits input).memory := by + apply rankedBitMemoEvaluate_widths + (SourceRanked.rank ChargedPhysicalRequest.rank) + (computedQueryMemoNormalized source target N occurrence symbolBits positionBits input) + (16384 * inputHeight N + 5) (computedFamilyMemoCode source target N (inputHeight N ^ 2)) + (computedFamilyMemoCode_injective source target N (inputHeight N ^ 2) hN + (two_hundred_le_two_pow_thousand.trans hell)) + (computedFamilyMemoCode_fits source target N (inputHeight N ^ 2) hN hell hsize le_rfl hMass) + (inputHeight N ^ 3) + · exact computedQueryMemoNormalized_width source target N occurrence symbolBits positionBits input + hN (two_hundred_le_two_pow_thousand.trans hell) hf hsize hMass hs ht hp htable + · exact bitMemoSound_empty _ _ _ + · intro key word h + simp only [BinaryMemo.lookup_empty, reduceCtorEq] at h + +include hN hell hf hsize hMass hs ht hp htable in +theorem computedQueryMemoResult_storage : + (computedQueryMemoResult source target N occurrence symbolBits positionBits input).memory.fractionStorage ≤ + (N + 2) ^ 65557 := by + have hw := computedQueryMemoResult_allWidths source target N occurrence symbolBits positionBits + input hN hell hf hsize hMass hs ht hp htable + have hs' := BinaryMemo.fractionStorage_le _ (inputHeight N ^ 3) hw + have hd := congrArg (fun result : RecursiveMemoResult (ComputedFamilyMemoKey source target N) => + result.memory.nodes) (computedQueryMemoResult_decode source target N occurrence symbolBits positionBits + input hN hell hf hsize hMass hs ht hp htable) + simp only [BitRecursiveMemoResult.decode, BinaryMemo.mapValues_nodes] at hd + have hn : (computedQueryMemoResult source target N occurrence symbolBits positionBits input).memory.nodes ≤ + (N + 2) ^ 65542 := by + rw [hd] + exact Nat.le_trans (Nat.le_succ _) (physicalFamilyMemo_nodes_polynomial source target N + (integerParameters N).P (integerParameters N).T (integerParameters N).S (inputHeight N) + (Nat.two_pow_pos _) (computedFamilyMemoCode source target N (inputHeight N ^ 2)) + (finalTargetState target.length) input) + have hh := Nat.pow_le_pow_left (computed_height_polynomial N) 3 + rw [← pow_mul] at hh + change inputHeight N ^ 3 ≤ (N + 2) ^ 12 at hh + have hu : 1 ≤ (N + 2) ^ 12 := Nat.one_le_pow _ _ (by omega) + have he : 8 ≤ (N + 2) ^ 3 := (by decide : 8 ≤ (2 : ℕ) ^ 3).trans + (Nat.pow_le_pow_left (by omega) 3) + have hc : 2 * inputHeight N ^ 3 + 4 ≤ (N + 2) ^ 15 := by + calc + _ ≤ 8 * (N + 2) ^ 12 := by omega + _ ≤ (N + 2) ^ 3 * (N + 2) ^ 12 := Nat.mul_le_mul_right _ he + _ = _ := by rw [← pow_add] + exact hs'.trans ((Nat.mul_le_mul hc hn).trans_eq (by rw [← pow_add])) + +end Storage +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedQueryTableBudget.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedQueryTableBudget.lean new file mode 100644 index 0000000000000000000000000000000000000000..dba65cc349ace20fbd798b95e99b7105f41d64a9 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedQueryTableBudget.lean @@ -0,0 +1,78 @@ +import OAI.Combinatorics.EditApproximation.Refinement.ComputedQueryReadBudget +import OAI.Combinatorics.EditApproximation.Refinement.ComputedQueryWarmupBudget +import OAI.Combinatorics.EditApproximation.Refinement.ComputedQueryBudgetAlgebra +import OAI.Combinatorics.EditApproximation.Queries.QueryChargedTableCost + +namespace OAI + +namespace EditApproximation +open Filter +attribute [local irreducible] queryLocalProgramBitDegree queryCallbackShellDegree queryInitialWarmupDegree + +def computedActiveQueryDegree : ℕ := computedQueryProgramDegree (computedQueryReadDegree 1) + +def computedActiveQueryBudget (N J t : ℕ) : ℕ := + BinaryFraction.queryLocalProgramBitBudget (integerParameters N).M N (integerParameters N).P + (inputSmallLog N) (40 * smallLogExponent N) (heightExponent N / 20) (smallLogExponent N) + (inputHeight N ^ 8) + (inputHeight N ^ ((100 * (integerParameters N).M + 100000) * + (coarseExponent (inputSmallLog N) + 1))) t + (BinaryFraction.queryPhysicalDataBudget (integerParameters N).T J (inputHeight N ^ 8) (inputHeight N ^ 3) + (50 * inputHeight N ^ 8 + 24) + (BinaryFraction.queryFamilySourceReadBudget J (inputHeight N ^ 8) (50 * inputHeight N ^ 8 + 25))) + +theorem computedActiveQueryBudget_cap : + ∀ᶠ N : ℕ in atTop, ∀ J t : ℕ, J ≤ inputHeight N → t ≤ inputHeight N ^ 2 → + computedActiveQueryBudget N J t ≤ computedLocalKernelBudget computedActiveQueryDegree N := by + filter_upwards [computedQueryReadBudget_cap 1, computedQueryProgramBudget_cap (computedQueryReadDegree 1), + inputSmallLog_tendsto.eventually (eventually_ge_atTop 64)] with N hread hprogram hell + intro J t hJ ht + have hH : 64 ≤ inputHeight N := hell.trans (computed_smallLog_le_height N) + have hg := computed_kernel_guard_cost N hH + have hT : (integerParameters N).T ≤ inputHeight N ^ 2 := by + have h := computed_history_budget_le_height_sq N (by omega) + omega + have hd := hread (integerParameters N).T J (inputHeight N ^ 8) (inputHeight N ^ 3) + (50 * inputHeight N ^ 8 + 24) (50 * inputHeight N ^ 8 + 25) hT hJ le_rfl le_rfl + (by omega) (by omega) + exact hprogram t _ ht hd + +def computedTableQueryDegree : ℕ := max 2 (max (computedQueryWarmupDegree 1) computedActiveQueryDegree) + 1 + +def computedTableQueryBudget (N Amax J symbolBits positionBits t : ℕ) : ℕ := + queryChargedTableBitBudget (integerParameters N).M (integerParameters N).P (inputSmallLog N) + Amax (inputHeight N ^ 2) J symbolBits positionBits (inputHeight N ^ 8) 1 + (computedActiveQueryBudget N J t) + +theorem computedTableQueryBudget_cap : + ∀ᶠ N : ℕ in atTop, ∀ Amax J symbolBits positionBits t : ℕ, + Amax ≤ computedLocalKernelBudget 1 N → J ≤ inputHeight N → + symbolBits ≤ inputHeight N ^ 3 → positionBits ≤ inputHeight N ^ 3 → t ≤ inputHeight N ^ 2 → + computedTableQueryBudget N Amax J symbolBits positionBits t ≤ + computedLocalKernelBudget computedTableQueryDegree N := by + filter_upwards [computedActiveQueryBudget_cap, computedQueryWarmupBudget_cap 1, + inputSmallLog_tendsto.eventually (eventually_ge_atTop 64)] with N hactive hwarm hell + intro Amax J symbolBits positionBits t hA hJ hs hp ht + have hH : 64 ≤ inputHeight N := hell.trans (computed_smallLog_le_height N) + have hg := computed_kernel_guard_cost N hH + have hw := hwarm Amax (inputHeight N ^ 2) J symbolBits positionBits 2 hA le_rfl hJ hs hp (by omega) + have ha := hactive J t hJ ht + let D := max 2 (max (computedQueryWarmupDegree 1) computedActiveQueryDegree) + have hover : 80 * (inputHeight N ^ 8 + 1) ≤ computedLocalKernelBudget 2 N := by + have hS : 2 ≤ computedLocalKernelBudget 1 N := by omega + have hsq : computedLocalKernelBudget 2 N = (computedLocalKernelBudget 1 N) ^ 2 := by + unfold computedLocalKernelBudget localKernelPowerExponent + simp only [Nat.mul_one, pow_mul] + rw [hsq] + nlinarith only [hg, hS] + have hbound := computedLocalKernelBudget_three N D _ _ _ (by omega) + (hover.trans (computedLocalKernelBudget_mono N 2 D (Nat.le_max_left _ _))) + (hw.trans (computedLocalKernelBudget_mono N (computedQueryWarmupDegree 1) D + ((Nat.le_max_left _ _).trans (Nat.le_max_right _ _)))) + (ha.trans (computedLocalKernelBudget_mono N computedActiveQueryDegree D + ((Nat.le_max_right _ _).trans (Nat.le_max_right _ _)))) + exact hbound + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedQueryTableWork.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedQueryTableWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..4c1db874d3a0a47e5537d20186bf4f5bc708ff31 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedQueryTableWork.lean @@ -0,0 +1,138 @@ +import OAI.Combinatorics.EditApproximation.Refinement.ComputedQueryRegisters +import OAI.Combinatorics.EditApproximation.Refinement.ComputedQueryConstants +import OAI.Combinatorics.EditApproximation.Refinement.ComputedQueryTableBudget +import OAI.Combinatorics.EditApproximation.Queries.QueryTableSemanticCost + +namespace OAI + +namespace EditApproximation +open Filter BinaryFraction +attribute [local instance] queryArityNeZero queryRoundsNeZero +attribute [local irreducible] queryChargedFamilyTable localRequestValue + +abbrev ComputedQueryTableParent (source target : List ℕ) (N : ℕ) := + {r : PhysicalTableRequest (integerParameters N).M + (intervalTreeDepth (integerParameters N).M source.length) target.length // + r.Bounded (computedSeedPassCount N + 1) (inputHeight N ^ 2) (integerParameters N).T (integerParameters N).S} + +abbrev ComputedQueryTableKey (source target : List ℕ) (N : ℕ) + (parent : ComputedQueryTableParent source target N) := + ChargedFamilyQueryKey (R := inputHeight N ^ 2) target N (integerParameters N).P + (inputSmallLog N) (40 * smallLogExponent N) (inputHeight N) (inputSmallLog N ^ 80) (.inr parent) + +def computedQueryTableProgram (source target : List ℕ) (N : ℕ) + (occurrence : BinaryMemo PositionCounts) (symbolBits positionBits : ℕ) + (parent : ComputedQueryTableParent source target N) := + queryChargedFamilyTable (R := inputHeight N ^ 2) source target N (integerParameters N).P + (inputSmallLog N) (40 * smallLogExponent N) (inputHeight N) (inputSmallLog N ^ 80) + (heightExponent N / 20) (smallLogExponent N) (computedParameterP_pos N) rfl rfl + (fun pass => (scheduledSeedWordWithWork N pass).1) (fun pass => (computedQueryParameters N pass).factor) + (computedQueryParameters N 0).tau (computedQueryParameters N 0).eta + (computedQueryParameters N 0).kappa (computedQueryParameters N 0).delta + (scheduledSeedMultiplier N) occurrence symbolBits positionBits parent + +/-- Complete dispatcher cost on any oracle storing the proved semantic values. -/ +theorem computedQueryTable_work_width : + ∀ᶠ N : ℕ in atTop, ∀ source target : List ℕ, source.length + target.length ≤ N → + ∀ (input : ComputedFamilyInput source target N) + (occurrence : BinaryMemo PositionCounts) (symbolBits positionBits : ℕ), + symbolBits ≤ inputHeight N ^ 3 → positionBits ≤ inputHeight N ^ 3 → + ∀ (parent : ComputedQueryTableParent source target N) + (oracle : ComputedQueryTableKey source target N parent → BinaryFraction), + (∀ key, (oracle key).width ≤ inputHeight N ^ 3) → + (∀ child, (oracle (Sum.inr child)).value = computedFamilyTableValue source target N input child.val) → + (computedQueryTableProgram source target N occurrence symbolBits positionBits parent).work + oracle (fun _ => 1) ≤ computedLocalKernelBudget computedTableQueryDegree N ∧ + ((computedQueryTableProgram source target N occurrence symbolBits positionBits parent).value oracle).width ≤ + localWarmupWordBudget (integerParameters N).M (inputHeight N ^ 8) + + preparedKernelWordBudget (integerParameters N).M (inputHeight N ^ 8) := by + filter_upwards [computedQueryParameters_numeric, computedTableQueryBudget_cap, computedQueryMass_word, + eventually_ge_atTop 1, inputSmallLog_tendsto.eventually (eventually_ge_atTop (2 ^ 1000))] + with N hnumeric hbudget hmass hN hell + intro source target hsize input occurrence symbolBits positionBits hsymbol hposition parent oracle hwidth hvalue + have hsmall : 200 ≤ inputSmallLog N := two_hundred_le_two_pow_thousand.trans hell + have hH : 64 ≤ inputHeight N := (by omega : 64 ≤ inputSmallLog N).trans (computed_smallLog_le_height N) + have hf : 3 ≤ smallLogExponent N := by + have h := (Nat.pow_le_pow_iff_right (by decide : 1 < (2 : ℕ))).mp hell + omega + have hJ : intervalTreeDepth (integerParameters N).M source.length ≤ inputHeight N := by + have h := computed_tree_depth_bound N source.length hN (by omega) hsmall + nlinarith only [h, hsmall] + have hregs := computedQueryRegisters N target.length _ hN hell (by omega) hJ parent.val parent.property + have hhist := computed_history_budget_le_height_sq N (by omega) + have ht : parent.val.index - (integerParameters N).T - 1 ≤ inputHeight N ^ 2 := + (Nat.sub_le _ _).trans ((Nat.sub_le _ _).trans (parent.property.2.2.trans (by omega))) + have hnum := hnumeric source.length target.length hsize _ ht parent.val.pass + have hv := computedQueryParameters_values N 0 hf (Nat.zero_le _) + have hdelta : 0 ≤ (computedQueryParameters N 0).delta.value := by + rw [hv.2.2.2.2] + change 0 ≤ 1 / (inputSmallLog N : ℚ) ^ 10 + positivity + have h38 : inputHeight N ^ 3 ≤ inputHeight N ^ 8 := Nat.pow_le_pow_right (by omega) (by decide) + have hA := scheduledSeedWordWithWork_range N parent.val.pass + have hAw := (scheduledSeedWordWithWork_bounds N parent.val.pass hN (by omega) hH).1.trans h38 + have hPd : ∃ j : ℕ, (integerParameters N).P = 2 ^ j := by + refine ⟨heightExponent N * (coarseExponent (inputSmallLog N) + 20), ?_⟩ + change (2 ^ heightExponent N) ^ (coarseExponent (inputSmallLog N) + 20) = _ + rw [← pow_mul] + let group := physicalFamilyGroup target N (integerParameters N).P (inputSmallLog N) + (40 * smallLogExponent N) (inputHeight N) (inputSmallLog N ^ 80) + (computedSeedPassCount N) (inputHeight N ^ 2) input.2 + let integer := physicalFamilyInteger source target N (integerParameters N).P (inputSmallLog N) + (40 * smallLogExponent N) (inputHeight N) (inputSmallLog N ^ 80) + (integerParameters N).T (integerParameters N).S (computedSeedPassCount N) (inputHeight N ^ 2) + (scheduledSeedFactor N) (scheduledSeedMultiplier N) (rationalParameters (inputSmallLog N)).tau + (rationalParameters (inputSmallLog N)).eta (rationalParameters (inputSmallLog N)).kappa + (rationalParameters (inputSmallLog N)).delta (computedParameterP_pos N) input.2 (clampedSeedNat input.1) + have hread (child : {r : ComputedQueryTableParent source target N // + r.val.combinedRank (integerParameters N).T (integerParameters N).S < + parent.val.combinedRank (integerParameters N).T (integerParameters N).S}) : + (oracle (Sum.inr ⟨Sum.inr child.val, ChargedPhysicalRequest.table_rank_lt parent child.val child.property⟩)).value = + localRequestValue source target N (integerParameters N).P (inputSmallLog N) + (40 * smallLogExponent N) (inputHeight N) (inputSmallLog N ^ 80) + (integerParameters N).T (integerParameters N).S (inputHeight N ^ 2) + (scheduledSeedFactor N) (scheduledSeedMultiplier N) (computedQueryParameters N 0).tau.value + (computedQueryParameters N 0).eta.value (computedQueryParameters N 0).kappa.value + (computedQueryParameters N 0).delta.value group integer (clampedSeedNat input.1) child.val.val := by + rw [hvalue] + simp only [computedFamilyTableValue, physicalFamilyRequestValue, chargedRequestValue, + hv.1, hv.2.2.1, hv.2.2.2.1, hv.2.2.2.2] + rfl + have hc := queryChargedFamilyTable_semantic_work_bound source target N (integerParameters N).P + (inputSmallLog N) (40 * smallLogExponent N) (inputHeight N) (inputSmallLog N ^ 80) + (heightExponent N / 20) (smallLogExponent N) (integerParameters N).initialFactor + (inputHeight N ^ 8) (inputHeight N ^ 5) + (inputHeight N ^ ((100 * (integerParameters N).M + 100000) * (coarseExponent (inputSmallLog N) + 1))) + (inputHeight N ^ 3) 1 (computedParameterP_pos N) rfl rfl + (fun pass => (scheduledSeedWordWithWork N pass).1) (fun pass => (computedQueryParameters N pass).factor) + (computedQueryParameters N 0).tau (computedQueryParameters N 0).eta + (computedQueryParameters N 0).kappa (computedQueryParameters N 0).delta + (scheduledSeedMultiplier N) occurrence symbolBits positionBits parent oracle (fun _ => 1) + (scheduledSeedFactor N) group integer (clampedSeedNat input.1) + hnum hPd (by exact (by omega : 2 ≤ inputHeight N).trans (Nat.le_pow (by decide))) h38 hregs.mean + hregs.targetSuccessor hregs.initial hregs.depth hregs.index hregs.warmup hregs.refinement hregs.rank + hAw hA.1 hA.2 hregs.pass hregs.copy hregs.passes hregs.copies hregs.multiplier + (hmass.trans (Nat.le_pow (by decide))) (fun key => hwidth _) (fun key => (hwidth _).trans h38) + (fun _ => le_rfl) hdelta hread + have hw := queryChargedFamilyTable_semantic_width source target N (integerParameters N).P + (inputSmallLog N) (40 * smallLogExponent N) (inputHeight N) (inputSmallLog N ^ 80) + (heightExponent N / 20) (smallLogExponent N) (inputHeight N ^ 8) + (inputHeight N ^ 5) + (inputHeight N ^ ((100 * (integerParameters N).M + 100000) * (coarseExponent (inputSmallLog N) + 1))) + (computedParameterP_pos N) rfl rfl + (fun pass => (scheduledSeedWordWithWork N pass).1) (fun pass => (computedQueryParameters N pass).factor) + (computedQueryParameters N 0).tau (computedQueryParameters N 0).eta + (computedQueryParameters N 0).kappa (computedQueryParameters N 0).delta + (scheduledSeedMultiplier N) occurrence symbolBits positionBits parent oracle + (scheduledSeedFactor N) group integer (clampedSeedNat input.1) hnum hregs.targetSuccessor hregs.initial + hregs.index (fun key => (hwidth _).trans h38) hdelta hread + refine ⟨?_, hw⟩ + apply hc.trans + convert hbudget (integerParameters N).initialFactor _ symbolBits positionBits + (parent.val.index - (integerParameters N).T) (computedQueryInitialFactor_cap N) hJ hsymbol hposition + ((Nat.sub_le _ _).trans (parent.property.2.2.trans (by omega))) using 1 + rfl + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedQueryTemporarySpace.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedQueryTemporarySpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..ed8a5a10df9b26bdde75aee91c8c9b435b74a787 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedQueryTemporarySpace.lean @@ -0,0 +1,123 @@ +import OAI.Combinatorics.EditApproximation.Binary.BitMemoHeap +import OAI.Combinatorics.EditApproximation.Refinement.ComputedQueryHeap +import OAI.Combinatorics.EditApproximation.Refinement.ComputedQueryStorage +import OAI.Combinatorics.EditApproximation.Refinement.ComputedBaseStorage +import OAI.Combinatorics.EditApproximation.Refinement.ComputedQueryWork +import OAI.Combinatorics.EditApproximation.Geometry.MemoCodeWork + +namespace OAI + +namespace EditApproximation +open Filter +attribute [local instance] queryArityNeZero queryRoundsNeZero + +/-- Cumulative concrete local allocations, address workspace, suspended +reads, dictionary paths and evaluator frames, over the actual cache trace. -/ +def computedQueryTemporaryCells (source target : List ℕ) (N : ℕ) + (occurrence : BinaryMemo PositionCounts) (symbolBits positionBits : ℕ) + (input : ComputedFamilyInput source target N) : ℕ := + rankedBitMemoCells (SourceRanked.rank ChargedPhysicalRequest.rank) + (computedQueryMemoNormalized source target N occurrence symbolBits positionBits input) + (computedQueryMemoHeap source target N occurrence symbolBits positionBits input) + (16384 * inputHeight N + 5) (computedFamilyMemoCode source target N (inputHeight N ^ 2)) + (fun key => (computedFamilyMemoCodeWithWork source target N (inputHeight N ^ 2) key).2) + (.inr (localFinalRootRequest target N (integerParameters N).T (integerParameters N).S + (inputHeight N) (Nat.two_pow_pos _) (finalTargetState target.length))) .empty + +theorem computedQueryTemporaryCells_bound (source target : List ℕ) (N : ℕ) + (occurrence : BinaryMemo PositionCounts) (symbolBits positionBits : ℕ) + (input : ComputedFamilyInput source target N) (hN : 0 < N) + (hell : 2 ^ 1000 ≤ inputSmallLog N) (hf : 3 ≤ smallLogExponent N) + (hsize : source.length + target.length ≤ N) + (hMass : Nat.size (localOnlineMassBound (integerParameters N).M (integerParameters N).P + (inputHeight N)) ≤ inputHeight N) + (hs : ∀ z ∈ source, z < 2 ^ symbolBits) (ht : ∀ z ∈ target, z < 2 ^ symbolBits) + (hp : target.length ≤ 2 ^ positionBits) + (htable : occurrence = occurrenceBuild symbolBits positionBits target.zipIdx) : + computedQueryTemporaryCells source target N occurrence symbolBits positionBits input ≤ + 3 * computedFamilyKernelWork source target N input + (computedQueryLocalWork source target N occurrence symbolBits positionBits input) + + (memoRequestCells (16384 * inputHeight N + 5) + (7 * intervalTreeDepth (integerParameters N).M source.length + 60) + 3) * + (computedFamilyResult source target N input).requests := by + have h := rankedBitMemoCells_le (SourceRanked.rank ChargedPhysicalRequest.rank) + (computedQueryMemoNormalized source target N occurrence symbolBits positionBits input) + (computedQueryMemoHeap source target N occurrence symbolBits positionBits input) + (16384 * inputHeight N + 5) (computedFamilyMemoCode source target N (inputHeight N ^ 2)) + (fun key => (computedFamilyMemoCodeWithWork source target N (inputHeight N ^ 2) key).2) + (7 * intervalTreeDepth (integerParameters N).M source.length + 60) + (computedFamilyMemoCodeWithWork_cost source target N (inputHeight N ^ 2)) + (.inr (localFinalRootRequest target N (integerParameters N).T (integerParameters N).S + (inputHeight N) (Nat.two_pow_pos _) (finalTargetState target.length))) .empty + change computedQueryTemporaryCells source target N occurrence symbolBits positionBits input + 3 ≤ + 3 * (computedQueryMemoResult source target N occurrence symbolBits positionBits input).localWork + + _ * (computedQueryMemoResult source target N occurrence symbolBits positionBits input).requests at h + rw [computedQueryMemoResult_localWork source target N occurrence symbolBits positionBits input + hN hell hf hsize hMass hs ht hp htable] at h + have hd := congrArg RecursiveMemoResult.requests + (computedQueryMemoResult_decode source target N occurrence symbolBits positionBits input + hN hell hf hsize hMass hs ht hp htable) + change (computedQueryMemoResult source target N occurrence symbolBits positionBits input).requests = _ at hd + rw [hd] at h + omega + +private theorem requestCells_factor (H J : ℕ) (hH : 100 ≤ H) (hJ : J ≤ H) : + memoRequestCells (16384 * H + 5) (7 * J + 60) + 3 ≤ H ^ 4 := by + have hcoef : 200000 ≤ H ^ 3 := + (by norm_num : 200000 ≤ (100 : ℕ) ^ 3).trans (Nat.pow_le_pow_left hH 3) + have hp : 200000 * H ≤ H ^ 4 := (Nat.mul_le_mul_right H hcoef).trans_eq (by ring) + unfold memoRequestCells + omega + +theorem computedQueryTemporaryCells_polynomial : + ∀ᶠ N : ℕ in atTop, ∀ source target : List ℕ, source.length + target.length ≤ N → + ∀ (input : ComputedFamilyInput source target N) + (occurrence : BinaryMemo PositionCounts) (symbolBits positionBits : ℕ), + symbolBits ≤ inputHeight N ^ 3 → positionBits ≤ inputHeight N ^ 3 → + (∀ z ∈ source, z < 2 ^ symbolBits) → (∀ z ∈ target, z < 2 ^ symbolBits) → + target.length ≤ 2 ^ positionBits → occurrence = occurrenceBuild symbolBits positionBits target.zipIdx → + computedQueryTemporaryCells source target N occurrence symbolBits positionBits input ≤ (N + 2) ^ 20 := by + filter_upwards [computedQueryLocalWork_cap, + computedFamilyKernelWork_polynomial computedQueryWorkDegree, + computedFamilyResult_requests_near_linear 1 (by norm_num), computedQueryMass_word, + eventually_ge_atTop 1, inputSmallLog_tendsto.eventually (eventually_ge_atTop (2 ^ 1000))] + with N hcap hwork hrequests hMass hN hell + intro source target hsize input occurrence symbolBits positionBits hsb hpb hs ht hp hoc + have hf : 3 ≤ smallLogExponent N := by + have h := (Nat.pow_le_pow_iff_right (by decide : 1 < (2 : ℕ))).mp hell + omega + have hl := hwork source target hsize input _ + (hcap source target hsize input occurrence symbolBits positionBits hsb hpb hs ht hp hoc) + have hr : (computedFamilyResult source target N input).requests ≤ (N + 2) ^ 2 := by + have h := hrequests source target hsize input + norm_num at h + exact_mod_cast h + have hH : 100 ≤ inputHeight N := + (by have := two_hundred_le_two_pow_thousand.trans hell; omega : 100 ≤ inputSmallLog N).trans + (computed_smallLog_le_height N) + have hd := computed_tree_depth_bound N source.length hN (by omega) + (two_hundred_le_two_pow_thousand.trans hell) + have hhundred : 100 ≤ inputSmallLog N := by + have := two_hundred_le_two_pow_thousand.trans hell + omega + have hm := Nat.mul_le_mul_left (intervalTreeDepth (integerParameters N).M source.length) hhundred + have hJ : intervalTreeDepth (integerParameters N).M source.length ≤ inputHeight N := by + nlinarith only [hd, hm] + have hc := requestCells_factor (inputHeight N) _ hH hJ + have hpoly : inputHeight N ^ 4 ≤ (N + 2) ^ 16 := + (Nat.pow_le_pow_left (computed_height_polynomial N) 4).trans_eq (by rw [← pow_mul]) + have hb := computedQueryTemporaryCells_bound source target N occurrence symbolBits positionBits + input hN hell hf hsize hMass hs ht hp hoc + have hprod := Nat.mul_le_mul (hc.trans hpoly) hr + have h2 : (N + 2) ^ 2 ≤ (N + 2) ^ 18 := Nat.pow_le_pow_right (by omega) (by decide) + have hfour : 4 * (N + 2) ^ 18 ≤ (N + 2) ^ 20 := by + calc + _ ≤ (N + 2) ^ 2 * (N + 2) ^ 18 := Nat.mul_le_mul_right _ (by nlinarith [Nat.zero_le N]) + _ = _ := by rw [← pow_add] + rw [← pow_add] at hprod + change _ ≤ (N + 2) ^ 18 at hprod + omega + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedQueryWarmupBudget.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedQueryWarmupBudget.lean new file mode 100644 index 0000000000000000000000000000000000000000..d8da60884315b3053248a384e66caab228ad6755 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedQueryWarmupBudget.lean @@ -0,0 +1,62 @@ +import OAI.Combinatorics.EditApproximation.Queries.QueryWarmupUniformCost +import OAI.Combinatorics.EditApproximation.Refinement.ComputedQueryProgramWork +import OAI.Combinatorics.EditApproximation.Refinement.ComputedQueryNumericZero + +namespace OAI + +namespace EditApproximation +open Filter +attribute [local irreducible] queryInitialWarmupDegree queryInitialWarmupPrimitiveDegree queryInitialWarmupBitDegree queryChargedWarmupBitBudget + +def computedQueryWarmupDegree (K : ℕ) : ℕ := (K + 1) * queryInitialWarmupDegree + +theorem computedQueryWarmupBudget_cap (K : ℕ) : + ∀ᶠ N : ℕ in atTop, ∀ Amax copies J symbolBits positionBits C : ℕ, + Amax ≤ computedLocalKernelBudget 1 N → copies ≤ inputHeight N ^ 2 → + J ≤ inputHeight N → symbolBits ≤ inputHeight N ^ 3 → positionBits ≤ inputHeight N ^ 3 → + C ≤ computedLocalKernelBudget K N → + queryChargedWarmupBitBudget (integerParameters N).M (integerParameters N).P (inputSmallLog N) + Amax copies J symbolBits positionBits (inputHeight N ^ 8) C ≤ + computedLocalKernelBudget (computedQueryWarmupDegree K) N := by + filter_upwards [computedQueryNumeric_zero, + inputSmallLog_tendsto.eventually (eventually_ge_atTop 64)] with N hnum hell + intro Amax copies J symbolBits positionBits C hA hc hJ hs hp hC + let H := inputHeight N + let M := (integerParameters N).M + let P := (integerParameters N).P + let L := (100 * M + 100000) * (coarseExponent (inputSmallLog N) + 1) + let S := H ^ L + let X := S ^ (K + 1) + have hH : 64 ≤ H := hell.trans (computed_smallLog_le_height N) + have hpos : 0 < H := lt_of_lt_of_le (by decide : 0 < 64) hH + have hL : 8 ≤ L := by + have h := Nat.le_mul_of_pos_right (100 * M + 100000) + (by omega : 0 < coarseExponent (inputSmallLog N) + 1) + dsimp only [L] + omega + have hHS : H ≤ S := Nat.le_pow ((by decide : 1 ≤ 8).trans hL) + have hSX : S ≤ X := Nat.le_pow (Nat.succ_le_succ (Nat.zero_le K)) + have h8S : H ^ 8 ≤ S := Nat.pow_le_pow_right hpos hL + have h2S : H ^ 2 ≤ S := Nat.pow_le_pow_right hpos ((by decide : 2 ≤ 8).trans hL) + have h3S : H ^ 3 ≤ S := Nat.pow_le_pow_right hpos ((by decide : 3 ≤ 8).trans hL) + have hCX : C ≤ X := by + apply hC.trans + change H ^ (L * K) ≤ (H ^ L) ^ (K + 1) + rw [← pow_mul] + exact Nat.pow_le_pow_right hpos (Nat.mul_le_mul_left L (Nat.le_succ K)) + have hAS : Amax ≤ S := by + simpa only [S, H, L, M, computedLocalKernelBudget, localKernelPowerExponent, Nat.mul_one] using hA + have hAX : Amax ≤ X := hAS.trans hSX + have h := queryChargedWarmupBitBudget_uniform_cap M P (inputSmallLog N) Amax copies J + symbolBits positionBits (H ^ 8) C X (hH.trans (hHS.trans hSX)) + (hnum.arityCap.trans hSX) (hnum.precisionCap.trans hSX) + ((computed_smallLog_le_height N).trans (hHS.trans hSX)) hAX + (hc.trans (h2S.trans hSX)) (hJ.trans (hHS.trans hSX)) + (hs.trans (h3S.trans hSX)) (hp.trans (h3S.trans hSX)) (h8S.trans hSX) hCX + (hnum.actionCap.trans hSX) (hnum.cartesianCap.trans hSX) + simpa only [X, S, H, L, computedLocalKernelBudget, localKernelPowerExponent, + computedQueryWarmupDegree, ← pow_mul, Nat.mul_assoc] using h + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedQueryWidth.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedQueryWidth.lean new file mode 100644 index 0000000000000000000000000000000000000000..f8ade543766bc9b5b39bc3c6deabf69398f4d0fd --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedQueryWidth.lean @@ -0,0 +1,98 @@ +import OAI.Combinatorics.EditApproximation.Refinement.ComputedQueryCorrect +import OAI.Combinatorics.EditApproximation.Queries.QueryHistorySemantic + +namespace OAI + +namespace EditApproximation +attribute [local instance] queryArityNeZero queryRoundsNeZero + +/-- Uniform magnitude bound for every table, independently of accuracy. -/ +theorem computedFamilyTableValue_abs_le (source target : List ℕ) (N : ℕ) + (hsize : source.length + target.length ≤ N) + (input : ComputedFamilyInput source target N) (key : ComputedFamilyTableKey source target N) : + |computedFamilyTableValue source target N input key| ≤ (((32 * inputSmallLog N + 1) * N : ℕ) : ℚ) := by + cases key with + | inl entry => + change |(clampedSeedNat input.1 entry : ℚ)| ≤ _ + rw [abs_of_nonneg (Nat.cast_nonneg _)] + exact_mod_cast (show clampedSeedNat input.1 entry ≤ (32 * inputSmallLog N + 1) * N from + (Nat.le_of_lt_succ (input.1 entry).isLt).trans (by nlinarith)) + | inr request => + unfold computedFamilyTableValue physicalFamilyRequestValue chargedRequestValue + have hb := localRequestValue_bounds (R := inputHeight N ^ 2) source target N (integerParameters N).P (inputSmallLog N) + (40 * smallLogExponent N) (inputHeight N) (inputSmallLog N ^ 80) + (integerParameters N).T (integerParameters N).S (inputHeight N ^ 2) + (scheduledSeedFactor N) (scheduledSeedMultiplier N) + (rationalParameters (inputSmallLog N)).tau (rationalParameters (inputSmallLog N)).eta + (rationalParameters (inputSmallLog N)).kappa (rationalParameters (inputSmallLog N)).delta + (physicalFamilyGroup target N (integerParameters N).P (inputSmallLog N) (40 * smallLogExponent N) + (inputHeight N) (inputSmallLog N ^ 80) (computedSeedPassCount N) (inputHeight N ^ 2) input.2) + (physicalFamilyInteger source target N (integerParameters N).P (inputSmallLog N) + (40 * smallLogExponent N) (inputHeight N) (inputSmallLog N ^ 80) (integerParameters N).T + (integerParameters N).S (computedSeedPassCount N) (inputHeight N ^ 2) + (scheduledSeedFactor N) (scheduledSeedMultiplier N) + (rationalParameters (inputSmallLog N)).tau (rationalParameters (inputSmallLog N)).eta + (rationalParameters (inputSmallLog N)).kappa (rationalParameters (inputSmallLog N)).delta + (computedParameterP_pos N) input.2 (clampedSeedNat input.1)) + (clampedSeedNat input.1) (by change 0 ≤ 1 / (inputSmallLog N : ℚ) ^ 10; positivity) request.val + rw [abs_of_nonneg hb.1] + exact hb.2.trans (by + simpa only [Nat.cast_mul, Nat.cast_add, Nat.cast_one, Nat.cast_ofNat] using + stageInitial_upper_all_seeds source target _ N (integerParameters N).P (inputSmallLog N) + (scheduledSeedFactor N request.val.pass) hsize (request.val.node, request.val.state)) + +theorem computedQueryMemoNormalized_width (source target : List ℕ) (N : ℕ) + (occurrence : BinaryMemo PositionCounts) (symbolBits positionBits : ℕ) + (input : ComputedFamilyInput source target N) + (hN : 0 < N) (hell : 200 ≤ inputSmallLog N) (hf : 3 ≤ smallLogExponent N) + (hsize : source.length + target.length ≤ N) + (hMass : Nat.size (localOnlineMassBound (integerParameters N).M (integerParameters N).P + (inputHeight N)) ≤ inputHeight N) + (hs : ∀ z ∈ source, z < 2 ^ symbolBits) (ht : ∀ z ∈ target, z < 2 ^ symbolBits) + (hp : target.length ≤ 2 ^ positionBits) + (htable : occurrence = occurrenceBuild symbolBits positionBits target.zipIdx) + (key : ComputedFamilyMemoKey source target N) : + (rankedBitProgramValue (SourceRanked.rank ChargedPhysicalRequest.rank) + (computedQueryMemoNormalized source target N occurrence symbolBits positionBits input) key).width ≤ + inputHeight N ^ 3 := by + have hH : 64 ≤ inputHeight N := (by omega : 64 ≤ inputSmallLog N).trans (computed_smallLog_le_height N) + have hbase := computed_refinementBase_length N (inputSmallLog N).bits (bitWordValue_bits _) + change (computedQueryBase N).length ≤ 10 * Nat.size (inputSmallLog N) + 3 at hbase + have hJ : intervalTreeDepth (integerParameters N).M source.length ≤ inputHeight N := by + have h := computed_tree_depth_bound N source.length hN (by omega) hell + nlinarith only [h, hell] + cases key with + | inl key => + have hr := computedFamilyRange_bits_le source target N (inputHeight N ^ 2) hMass key + have hc : (input.2 key).val < 2 ^ inputHeight N := (input.2 key).isLt.trans_le + ((Nat.le_pow_clog (by decide : 1 < 2) _).trans + (Nat.pow_le_pow_right (by decide : 0 < 2) hr)) + have hv : |computedFamilyExpectedValue source target N input (.inl key)| ≤ + ((2 ^ inputHeight N : ℕ) : ℚ) := by + change |((input.2 key).val : ℚ)| ≤ _ + rw [abs_of_nonneg (Nat.cast_nonneg _)] + exact_mod_cast hc.le + have hw := computedQueryMemoNormalized_width_bound source target N occurrence symbolBits positionBits + input hf hs ht hp htable (.inl key) (2 ^ inputHeight N) hv + simp only [queryFamilyMemoRemaining, Nat.zero_mul, Nat.zero_add, Nat.mul_one, + Nat.size_pow] at hw + have hsquare : inputHeight N + 4 ≤ inputHeight N ^ 2 := by nlinarith only [hH] + have hcub := hsquare.trans (Nat.pow_le_pow_right (by omega : 0 < inputHeight N) (by decide : 2 ≤ 3)) + omega + | inr key => + have hw := computedQueryMemoNormalized_width_bound source target N occurrence symbolBits positionBits + input hf hs ht hp htable (.inr key) ((32 * inputSmallLog N + 1) * N) + (computedFamilyTableValue_abs_le source target N hsize input key) + have hr : queryFamilyMemoRemaining (R := inputHeight N ^ 2) target N (integerParameters N).P (inputSmallLog N) + (40 * smallLogExponent N) (inputHeight N) (inputSmallLog N ^ 80) (.inr key) ≤ inputHeight N := by + cases key with + | inl entry => exact Nat.zero_le _ + | inr request => exact (Nat.sub_le _ _).trans hJ + have hm := Nat.mul_le_mul_right (computedQueryBase N).length hr + have hb := computed_cacheWordBudget_le_cube N (inputHeight N) (computedQueryBase N).length hH le_rfl hbase + simp only [Nat.mul_assoc] at hb + omega + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedQueryWork.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedQueryWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..6dee5a352339fac4fbe085149168995b66f65a09 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedQueryWork.lean @@ -0,0 +1,66 @@ +import OAI.Combinatorics.EditApproximation.Refinement.ComputedQueryRawWork +import OAI.Combinatorics.EditApproximation.Binary.BitQueryNormalizationCost + +namespace OAI + +namespace EditApproximation +open Filter BinaryFraction +attribute [local instance] queryArityNeZero queryRoundsNeZero +attribute [local irreducible] computedQueryRawWorkDegree computedQueryRawWidthDegree + +def computedQueryWorkDegree : ℕ := + max computedQueryRawWorkDegree (computedQueryNormalizationDegree computedQueryRawWidthDegree) + 1 + +/-- Complete local work, including binary denominator normalization. -/ +theorem computedQueryLocalWork_cap : + ∀ᶠ N : ℕ in atTop, ∀ source target : List ℕ, source.length + target.length ≤ N → + ∀ (input : ComputedFamilyInput source target N) + (occurrence : BinaryMemo PositionCounts) (symbolBits positionBits : ℕ), + symbolBits ≤ inputHeight N ^ 3 → positionBits ≤ inputHeight N ^ 3 → + (∀ z ∈ source, z < 2 ^ symbolBits) → (∀ z ∈ target, z < 2 ^ symbolBits) → + target.length ≤ 2 ^ positionBits → occurrence = occurrenceBuild symbolBits positionBits target.zipIdx → + ∀ key, computedQueryLocalWork source target N occurrence symbolBits positionBits input key ≤ + computedLocalKernelBudget computedQueryWorkDegree N := by + filter_upwards [computedQueryMemoRaw_bounds, computedQueryNormalizationBudget_cap computedQueryRawWidthDegree, + eventually_ge_atTop 1, inputSmallLog_tendsto.eventually (eventually_ge_atTop 200)] + with N hraw hnorm hN hell + intro source target hsize input occurrence symbolBits positionBits hsb hpb hs ht hp hoc key + have hH : 64 ≤ inputHeight N := (by omega : 64 ≤ inputSmallLog N).trans (computed_smallLog_le_height N) + have hJ : intervalTreeDepth (integerParameters N).M source.length ≤ inputHeight N := by + have h := computed_tree_depth_bound N source.length hN (by omega) hell + nlinarith only [h, hell] + have hr : queryFamilyMemoRemaining (R := inputHeight N ^ 2) target N (integerParameters N).P + (inputSmallLog N) (40 * smallLogExponent N) (inputHeight N) (inputSmallLog N ^ 80) key ≤ inputHeight N := by + cases key with + | inl key => exact Nat.zero_le _ + | inr key => + cases key with + | inl entry => exact Nat.zero_le _ + | inr request => exact (Nat.sub_le _ _).trans hJ + have hb : (computedQueryBase N).length ≤ inputHeight N ^ 3 := by + have h := computed_refinementBase_length N (inputSmallLog N).bits (bitWordValue_bits _) + have hs : Nat.size (inputSmallLog N) ≤ inputHeight N := + (Nat.size_le.mpr Nat.lt_two_pow_self).trans (computed_smallLog_le_height N) + have hp2 : 10 * inputHeight N + 3 ≤ inputHeight N ^ 2 := by nlinarith only [hH] + have hp3 := Nat.pow_le_pow_right (by omega : 0 < inputHeight N) (by decide : 2 ≤ 3) + exact h.trans ((show 10 * Nat.size (inputSmallLog N) + 3 ≤ inputHeight N ^ 2 by omega).trans hp3) + have hraw' := hraw source target hsize input occurrence symbolBits positionBits hsb hpb hs ht hp hoc key + have hlocal := rankedNormalizeBody_localWork_bound (SourceRanked.rank ChargedPhysicalRequest.rank) + (computedQueryMemoRaw source target N occurrence symbolBits positionBits input) + (computedQueryBase N) (computedQueryBase_pos N) + (queryFamilyMemoRemaining target N (integerParameters N).P (inputSmallLog N) + (40 * smallLogExponent N) (inputHeight N) (inputSmallLog N ^ 80)) + (fun _ => computedLocalKernelBudget computedQueryRawWidthDegree N) + (fun _ => computedLocalKernelBudget computedQueryRawWorkDegree N) + (inputHeight N ^ 3) hb key hraw'.2 hraw'.1 + have hn := hnorm _ _ _ hr le_rfl (Nat.le_refl (computedLocalKernelBudget computedQueryRawWidthDegree N)) + let D := max computedQueryRawWorkDegree (computedQueryNormalizationDegree computedQueryRawWidthDegree) + have hrawD := computedLocalKernelBudget_mono N computedQueryRawWorkDegree D (Nat.le_max_left _ _) + have hnormD := computedLocalKernelBudget_mono N (computedQueryNormalizationDegree computedQueryRawWidthDegree) D + (Nat.le_max_right _ _) + have hone : 1 ≤ computedLocalKernelBudget D N := one_le_pow₀ (by omega) + exact hlocal.trans (computedLocalKernelBudget_three N D _ _ _ (by omega) hrawD (hn.trans hnormD) hone) + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedRandomPhysicalCost.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedRandomPhysicalCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..b124e2a806d6585f5d84cb705d8e6d73be4bc991 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedRandomPhysicalCost.lean @@ -0,0 +1,116 @@ +import OAI.Combinatorics.EditApproximation.Refinement.ComputedRandomTableCost +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalRandomDataRequest + +namespace OAI + +namespace EditApproximation + +section Physical + +variable {σ α : Type*} (source target : List α) {M J : ℕ} [NeZero M] + (N P H : ℕ) (hN : 0 < N) (hell : 200 ≤ inputSmallLog N) + (hM : M = (integerParameters N).M) (hP : P = (integerParameters N).P) + (A tau eta kappa delta : ℚ) (hA : A ≤ ((integerParameters N).initialFactor : ℚ)) + (pass copy T S t : ℕ) (hT : T = (integerParameters N).T) + (ht : 0 < t) (htime : t ≤ (integerParameters N).S) + (node : PhysicalNode M J) (hbelow : node.1.val < J) + (readGroup : GroupScalarKey M (inputSmallLog N) (inputSmallLog N ^ 80) → FiniteQuery σ) + (readInteger : (ℕ × TargetInterval target.length) → ℕ → FiniteQuery σ) + (q : TargetInterval target.length) (sourceAnswer : σ → ℚ) + (answer : PhysicalTableRequest M J target.length → ℚ) + (hw : 0 ≤ answer (PhysicalTableRequest.warmup pass copy node 0 q)) + +include hN hell hM hP hA hT ht htime hw + + theorem computed_physicalRandom_current_reads : + (physicalRandomDataRequestQuery source target N P (inputSmallLog N) (40 * smallLogExponent N) + H (inputSmallLog N ^ 80) tau (refinementFactor A (inputSmallLog N)) eta kappa delta + pass copy T S t ht node hbelow readGroup readInteger q).cost + (Sum.elim sourceAnswer (fun key => answer key.val)) + (Sum.elim (fun _ => 0) (fun key => physicalCurrentReadWeight (T + t) key.val)) ≤ + 2 * M * inputSmallLog N ^ 256 := by + unfold physicalRandomDataRequestQuery + refine (computed_localRandomDataQuery_table_cost source target _ N P H T t hN hell hM hP hT + ht htime A tau eta kappa delta hA _ _ _ _ _ q _ _ _ _ 0 0 1 ?_ ?_ ?_ ?_ ?_ ?_ ?_ ?_).trans ?_ + · intro r + rw [FiniteQuery.mapKeys_cost] + exact (physicalRefinementWarmupRead_cost_current pass copy T S t ht node q node le_rfl + 0 (Nat.zero_le T) r _).le + · intro input + rw [FiniteQuery.mapKeys_cost] + simpa only [Nat.mul_zero, Function.comp_def, Sum.elim_inr] using + (physicalRefinementMassQuery_cost_current pass copy T S t ht node hbelow q input _).le + · intro input + rw [FiniteQuery.mapKeys_cost] + exact (physicalRefinementWarmupRead_cost_current pass copy T S t ht node q + (physicalChild node hbelow input.1) _ 0 (Nat.zero_le T) input.2 _).le + · intro key + rw [FiniteQuery.mapKeys_cost] + exact FiniteQuery.cost_zero _ _ + · intro key range + rw [FiniteQuery.mapKeys_cost] + exact FiniteQuery.cost_zero _ _ + · intro input + rw [FiniteQuery.mapKeys_cost] + exact (physicalRefinementEarlierQuery_cost_current pass copy T S t node hbelow q input _).le + · intro input + rw [FiniteQuery.mapKeys_cost] + exact (physicalRefinementCurrentQuery_cost_current pass copy T S t node hbelow q input _).le + · exact hw + · simp only [Nat.mul_zero, Nat.mul_one, Nat.zero_add] + exact le_rfl + + theorem computed_physicalRandom_earlier_reads : + (physicalRandomDataRequestQuery source target N P (inputSmallLog N) (40 * smallLogExponent N) + H (inputSmallLog N ^ 80) tau (refinementFactor A (inputSmallLog N)) eta kappa delta + pass copy T S t ht node hbelow readGroup readInteger q).cost + (Sum.elim sourceAnswer (fun key => answer key.val)) + (Sum.elim (fun _ => 0) (fun key => physicalEarlierReadWeight (T + t) key.val)) ≤ + inputHeight N ^ (257 * (coarseExponent (inputSmallLog N) + 1)) := by + unfold physicalRandomDataRequestQuery + refine (computed_localRandomDataQuery_table_cost source target _ N P H T t hN hell hM hP hT + ht htime A tau eta kappa delta hA _ _ _ _ _ q _ _ _ _ 1 1 0 ?_ ?_ ?_ ?_ ?_ ?_ ?_ ?_).trans ?_ + · intro r + rw [FiniteQuery.mapKeys_cost] + exact (physicalRefinementWarmupRead_cost_earlier pass copy T S t ht node q node le_rfl + 0 (Nat.zero_le T) r _).le + · intro input + rw [FiniteQuery.mapKeys_cost] + simpa only [Nat.mul_one, Function.comp_def, Sum.elim_inr] using + (physicalRefinementMassQuery_cost_earlier pass copy T S t ht node hbelow q input _).le + · intro input + rw [FiniteQuery.mapKeys_cost] + exact (physicalRefinementWarmupRead_cost_earlier pass copy T S t ht node q + (physicalChild node hbelow input.1) _ 0 (Nat.zero_le T) input.2 _).le + · intro key + rw [FiniteQuery.mapKeys_cost] + exact FiniteQuery.cost_zero _ _ + · intro key range + rw [FiniteQuery.mapKeys_cost] + exact FiniteQuery.cost_zero _ _ + · intro input + rw [FiniteQuery.mapKeys_cost] + exact physicalRefinementEarlierQuery_cost_earlier pass copy T S t node hbelow q input _ + · intro input + rw [FiniteQuery.mapKeys_cost] + exact (physicalRefinementCurrentQuery_cost_earlier pass copy T S t node hbelow q input _).le + · exact hw + · simp only [Nat.mul_one, Nat.mul_zero, Nat.add_zero] + let B := inputHeight N ^ (256 * (coarseExponent (inputSmallLog N) + 1)) + have hH : 64 ≤ inputHeight N := + (by omega : 64 ≤ inputSmallLog N).trans (computed_smallLog_le_height N) + have hB : 1 ≤ B := one_le_pow₀ (by omega) + change 2 + 2 * B + B ≤ _ + calc + _ ≤ 5 * B := by omega + _ ≤ inputHeight N * B := Nat.mul_le_mul_right B (by omega) + _ = inputHeight N ^ (1 + 256 * (coarseExponent (inputSmallLog N) + 1)) := by + dsimp only [B] + rw [pow_add, pow_one] + _ ≤ _ := pow_le_pow_right₀ (by omega) (by omega) + +end Physical + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedRandomTableCost.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedRandomTableCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..36a2a34d46b8e8358e54d765e6a128252c484ea3 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedRandomTableCost.lean @@ -0,0 +1,98 @@ +import OAI.Combinatorics.EditApproximation.Geometry.LocalRandomTableCost +import OAI.Combinatorics.EditApproximation.Refinement.ComputedRefinementReadBudget + +namespace OAI + +/-! The source-aware query satisfies the same table branching budgets. +Its group/online values may be arbitrary: only source-free table costs +and nonnegativity of the actual initial value are needed here. -/ + +namespace EditApproximation + + theorem computed_localRandomDataQuery_table_cost {ι α : Type*} (source target : List α) + {M : ℕ} [NeZero M] (parent : TargetInterval source.length) (N P H T t : ℕ) + (hN : 0 < N) (hell : 200 ≤ inputSmallLog N) (hM : M = (integerParameters N).M) + (hP : P = (integerParameters N).P) (hT : T = (integerParameters N).T) + (ht : 0 < t) (htime : t ≤ (integerParameters N).S) + (A tau eta kappa delta : ℚ) (hA : A ≤ ((integerParameters N).initialFactor : ℚ)) + (readParent : TargetInterval target.length → FiniteQuery ι) + (readMass readInitial : Fin M × TargetInterval target.length → FiniteQuery ι) + (readGroup : GroupScalarKey M (inputSmallLog N) (inputSmallLog N ^ 80) → FiniteQuery ι) + (readInteger : (ℕ × TargetInterval target.length) → ℕ → FiniteQuery ι) + (q : TargetInterval target.length) + (readEarlier : (Fin M × ℕ × TargetInterval target.length) → FiniteQuery ι) + (readCurrent : (Fin M × TargetInterval target.length) → FiniteQuery ι) + (oracle : ι → ℚ) (weight : ι → ℕ) (dataCost earlierCost currentCost : ℕ) + (hparent : ∀ r, (readParent r).cost oracle weight ≤ dataCost) + (hmass : ∀ key, (readMass key).cost oracle weight ≤ T * dataCost) + (hinitial : ∀ key, (readInitial key).cost oracle weight ≤ dataCost) + (hgroup : ∀ key, (readGroup key).cost oracle weight = 0) + (honline : ∀ key range, (readInteger key range).cost oracle weight = 0) + (hearlier : ∀ key, (readEarlier key).cost oracle weight ≤ earlierCost) + (hcurrent : ∀ key, (readCurrent key).cost oracle weight ≤ currentCost) + (hw : 0 ≤ (readParent q).value oracle) : + let B := inputHeight N ^ (256 * (coarseExponent (inputSmallLog N) + 1)) + (localRandomDataQuery source target parent N P (inputSmallLog N) (40 * smallLogExponent N) + H (inputSmallLog N ^ 80) tau (refinementFactor A (inputSmallLog N)) eta kappa delta t + readParent readMass readInitial readGroup readInteger q readEarlier readCurrent).cost oracle weight ≤ + (2 + 2 * B) * dataCost + B * earlierCost + + (2 * M * inputSmallLog N ^ 256) * currentCost := by + dsimp only + let B := inputHeight N ^ (256 * (coarseExponent (inputSmallLog N) + 1)) + let actual := fun r => (readParent r).value oracle + have hdata := computed_data_support_budget parent N P T hN hell hM hP hT A hA actual q hw + have hband (parentInitial : TargetInterval target.length → ℚ) (hq : parentInitial q = actual q) : + (refinementBandInputList (M := M) parent N P (inputSmallLog N) (40 * smallLogExponent N) + (refinementFactor A (inputSmallLog N)) parentInitial q).length * + (T * dataCost + dataCost) ≤ B * dataCost := by + have hb := (computed_data_support_budget parent N P T hN hell hM hP hT A hA + parentInitial q (by rw [hq]; exact hw)).2 + convert Nat.mul_le_mul_right dataCost hb using 1 + ring + have hstep (parentInitial : TargetInterval target.length → ℚ) (hq : parentInitial q = actual q) + (child initial : Fin M → TargetInterval target.length → ℚ) + (draw : CellGroupDraws M (inputSmallLog N) (inputSmallLog N ^ 80)) + (integer : ℕ → TargetInterval target.length → ℕ) : + (localRefinementStepQuery source target parent N P (inputSmallLog N) (40 * smallLogExponent N) + H (inputSmallLog N ^ 80) tau (refinementFactor A (inputSmallLog N)) eta kappa delta t + parentInitial child initial draw integer q readEarlier readCurrent).cost oracle weight ≤ + B * earlierCost + (2 * M * inputSmallLog N ^ 256) * currentCost := by + let earlier := fun i s r => (readEarlier (i, s, r)).value oracle + let current := fun i r => (readCurrent (i, r)).value oracle + have he := computed_queryEarlierHistory_card parent N P t hN hell hP (by omega) A hA + parentInitial q (by rw [hq]; exact hw) + rw [← hM] at he + have hc : (currentQueryInputCover source target parent N P (inputSmallLog N) + (40 * smallLogExponent N) (inputSmallLog N ^ 80) tau + (refinementFactor A (inputSmallLog N)) parentInitial child initial current draw q + (localOnlineCandidates source target parent N P (inputSmallLog N) (40 * smallLogExponent N) + H tau (refinementFactor A (inputSmallLog N)) eta kappa parentInitial child initial earlier + (t - 1) integer q)).card ≤ M * inputSmallLog N ^ 256 := by + subst M + exact computed_currentQueryInputCover_card source target N P hN hell parent A tau hA + parentInitial child initial current draw q (by rw [hq]; exact hw) _ + (localOnlineCandidates_length source target parent N P (inputSmallLog N) + (40 * smallLogExponent N) H tau (refinementFactor A (inputSmallLog N)) eta kappa + parentInitial child initial earlier (t - 1) integer q) + have hs := localRefinementStepQuery_cost_le source target parent N P (inputSmallLog N) + (40 * smallLogExponent N) H (inputSmallLog N ^ 80) tau + (refinementFactor A (inputSmallLog N)) eta kappa delta t parentInitial child initial draw integer q + readEarlier readCurrent oracle weight earlier current ht (fun _ => rfl) (fun _ => rfl) + earlierCost currentCost hearlier hcurrent + apply hs.trans + apply Nat.add_le_add (Nat.mul_le_mul_right earlierCost he) + convert Nat.mul_le_mul_right currentCost (Nat.mul_le_mul_left 2 hc) using 1 + ring + have h := localRandomDataQuery_table_cost_le source target parent N P (inputSmallLog N) + (40 * smallLogExponent N) H (inputSmallLog N ^ 80) tau + (refinementFactor A (inputSmallLog N)) eta kappa delta t readParent readMass readInitial + readGroup readInteger q readEarlier readCurrent oracle weight dataCost (T * dataCost) dataCost + (B * dataCost) (B * earlierCost + (2 * M * inputSmallLog N ^ 256) * currentCost) + hparent hmass hinitial hgroup honline hband hstep + have hi := Nat.mul_le_mul_right dataCost (Nat.add_le_add_left hdata.1 1) + dsimp only [B, actual] at h hi ⊢ + nlinarith only [h, hi] + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedReadChargedWork.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedReadChargedWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..5959ccb290bfb944bf15979d1baef1d407cbe018 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedReadChargedWork.lean @@ -0,0 +1,53 @@ +import OAI.Combinatorics.EditApproximation.Refinement.ComputedIndexedCoarseWork +import OAI.Combinatorics.EditApproximation.Refinement.ComputedCoarseSamplingWork +import OAI.Combinatorics.EditApproximation.Refinement.ComputedExecutionCosts +import OAI.Combinatorics.EditApproximation.Refinement.ComputedCoarsePreparation +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation +open Filter MeasureTheory + +/-- Execution budget including indexed coarse computation, consumed threshold +bits, rejection sampling, dictionary operations, address construction and unit charges. -/ + + +theorem computedExecutionReadChargedWork_integrable (source target : List ℕ) (N : ℕ) : + Integrable (computedExecutionReadChargedWork source target N) (computedExecutionLaw source target N) := + (((computedExecutionIndexedCoarseWork_integrable source target N).add + (computedExecutionCoarseSamplingWork_integrable source target N)).add + (computedExecutionNonlocalWork_integrable source target N)).add + (computedExecutionCoarsePreparationWork_integrable source target N) + +theorem computedExecutionReadChargedWork_expected_near_linear (epsilon : ℝ) (hepsilon : 0 < epsilon) : + ∀ᶠ N in atTop, ∀ source target : List ℕ, source.length + target.length ≤ N → + (∀ a ∈ source ++ target, Nat.size a ≤ inputHeight N ^ 3) → + (∫ execution, computedExecutionReadChargedWork source target N execution + ∂computedExecutionLaw source target N) ≤ (N + 2 : ℝ) ^ (1 + epsilon) := by + have hh : 0 < epsilon / 2 := half_pos hepsilon + filter_upwards [computedExecutionIndexedCoarseWork_expected_near_linear (epsilon / 2) hh, + computedExecutionCoarseSamplingWork_expected_near_linear (epsilon / 2) hh, + computedExecutionNonlocalWork_expected_near_linear (epsilon / 2) hh, + computedExecutionCoarsePreparationWork_expected_near_linear (epsilon / 2) hh, + constant_le_rpow_eventually 4 (epsilon / 2) hh] with N hc hs hn hp hfour + intro source target hsize hsymbol + have hiC := computedExecutionIndexedCoarseWork_integrable source target N + have hiS := computedExecutionCoarseSamplingWork_integrable source target N + have hiN := computedExecutionNonlocalWork_integrable source target N + have hiP := computedExecutionCoarsePreparationWork_integrable source target N + change integral (computedExecutionLaw source target N) + (((computedExecutionIndexedCoarseWork source target N + computedExecutionCoarseSamplingWork source target N) + + computedExecutionNonlocalWork source target N) + computedExecutionCoarsePreparationWork source target N) ≤ _ + rw [integral_add' ((hiC.add hiS).add hiN) hiP, integral_add' (hiC.add hiS) hiN, integral_add' hiC hiS] + calc + _ ≤ 4 * (N + 2 : ℝ) ^ (1 + epsilon / 2) := by + linarith only [hc source target hsize hsymbol, hs source target hsize, hn source target hsize, hp source target hsize hsymbol] + _ ≤ (N + 2 : ℝ) ^ (epsilon / 2) * (N + 2 : ℝ) ^ (1 + epsilon / 2) := + mul_le_mul_of_nonneg_right hfour (Real.rpow_nonneg (by positivity) _) + _ = _ := by rw [← Real.rpow_add (by positivity)]; congr 1; ring + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedRefinementReadBudget.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedRefinementReadBudget.lean new file mode 100644 index 0000000000000000000000000000000000000000..767b75d66029ed0d6bd9f41082bce58adbd832ef --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedRefinementReadBudget.lean @@ -0,0 +1,162 @@ +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalQueryProgress +import OAI.Combinatorics.EditApproximation.Geometry.RefinementSupportBudget +import OAI.Combinatorics.EditApproximation.Refinement.ComputedEarlierHistory + +namespace OAI + +/-! The actual refinement query, including the reads used to construct +its initial and mass data, satisfies the two dependency branching budgets. +Only nonnegativity of the actual initial query value is used. -/ + +namespace EditApproximation + +theorem computed_data_support_budget {nx ny M : ℕ} (parent : TargetInterval nx) + (N P T : ℕ) (hN : 0 < N) (hell : 200 ≤ inputSmallLog N) + (hM : M = (integerParameters N).M) (hP : P = (integerParameters N).P) + (hT : T = (integerParameters N).T) + (A : ℚ) (hA : A ≤ ((integerParameters N).initialFactor : ℚ)) + (initial : TargetInterval ny → ℚ) (q : TargetInterval ny) (hw : 0 ≤ initial q) : + (refinementInitialSupport N P (inputSmallLog N) (40 * smallLogExponent N) + (refinementFactor A (inputSmallLog N)) (initial q) q).length ≤ + 1 + inputHeight N ^ (256 * (coarseExponent (inputSmallLog N) + 1)) ∧ + (refinementBandInputList (M := M) parent N P (inputSmallLog N) (40 * smallLogExponent N) + (refinementFactor A (inputSmallLog N)) initial q).length * (T + 1) ≤ + inputHeight N ^ (256 * (coarseExponent (inputSmallLog N) + 1)) := by + let H := inputHeight N + let ell := inputSmallLog N + let W := (dyadicQueryWindow N (initial q) (refinementFactor A ell) ell).length + let C := ((32 * ell + 2) * 2 ^ (40 * smallLogExponent N) + 2) ^ 2 + let R := (64 * ell * P + 2) ^ 2 + C * (P + 1) ^ 2 + 1 + let history := (integerParameters N).T + (integerParameters N).S + 1 + let budget := localEarlierBudget W C M P ell history + have hF : ell ≤ H := computed_smallLog_le_height N + have hH : 64 ≤ H := (by omega : 64 ≤ ell).trans hF + have hPpos : 1 ≤ P := by rw [hP]; exact one_le_pow₀ Nat.one_le_two_pow + have hPpower : P ≤ H ^ (coarseExponent ell + 20) := by rw [hP]; exact le_rfl + have hMpos : 0 < M := by + rw [hM] + change 0 < 2 ^ _ + exact Nat.two_pow_pos _ + have hMbound : M ≤ H := by + rw [hM] + exact pow_le_pow_right₀ (by decide : (1 : ℕ) ≤ 2) (Nat.div_le_self _ _) + have hW : W ≤ H ^ 3 := + (computed_refinement_window N hN (by omega) A (initial q) hA).trans + (computed_window_le_height_cube N hN (by omega) (by omega)) + have hbudget : budget ≤ H ^ (256 * (coarseExponent ell + 1)) := + localEarlierBudget_poly H (coarseExponent ell) W C M P ell history hH hPpos hPpower hW + (computed_cell_budget_le_height_pow N hH) hMbound hF + (computed_history_budget_le_height_sq N (by omega)) + have hhistory : T + 1 ≤ history := by dsimp only [history]; omega + have hwide : 0 < (40 * P + 2) ^ 2 := by positivity + have hfactor : 0 < M * history * (40 * P + 2) ^ 2 := by positivity + have hraw : W * R ≤ budget := by + have h := Nat.le_mul_of_pos_right (W * R) hfactor + exact h.trans_eq (by dsimp only [budget, localEarlierBudget, R]; ring) + have hband : W * R * M * (40 * P + 2) ^ 2 * (T + 1) ≤ budget := by + apply (Nat.mul_le_mul_left (W * R * M * (40 * P + 2) ^ 2) hhistory).trans_eq + dsimp only [budget, localEarlierBudget, R] + ring + have hdyadic : ∃ e : ℕ, P = 2 ^ e := ⟨_, hP.trans (computed_P_dyadic N)⟩ + constructor + · exact (refinementInitialSupport_length N P ell (40 * smallLogExponent N) + (refinementFactor A ell) (initial q) q hdyadic (by omega) hw).trans + (Nat.add_le_add_left (hraw.trans hbudget) 1) + · exact (Nat.mul_le_mul_right (T + 1) + (refinementBandInputList_length parent N P ell (40 * smallLogExponent N) + (refinementFactor A ell) initial q hdyadic (by omega) hw)).trans (hband.trans hbudget) + +theorem computed_physicalRefinement_current_reads {α : Type*} (source target : List α) + {M J : ℕ} (N P H : ℕ) (hN : 0 < N) (hell : 200 ≤ inputSmallLog N) + (hM : M = (integerParameters N).M) + (A tau eta kappa delta : ℚ) (hA : A ≤ ((integerParameters N).initialFactor : ℚ)) + (pass copy T S t : ℕ) (ht : 0 < t) + (node : PhysicalNode M J) (hbelow : node.1.val < J) + (draw : CellGroupDraws M (inputSmallLog N) (inputSmallLog N ^ 80)) + (integer : ℕ → TargetInterval target.length → ℕ) + (q : TargetInterval target.length) (answer : PhysicalTableRequest M J target.length → ℚ) + (hw : 0 ≤ answer (PhysicalTableRequest.warmup pass copy node 0 q)) : + (physicalRefinementDataRequestQuery source target N P (inputSmallLog N) + (40 * smallLogExponent N) H (inputSmallLog N ^ 80) tau + (refinementFactor A (inputSmallLog N)) eta kappa delta pass copy T S t ht node hbelow + draw integer q).cost (fun request => answer request.val) + (fun request => physicalCurrentReadWeight (T + t) request.val) ≤ + 2 * M * inputSmallLog N ^ 256 := by + subst M + let initial := fun r => answer (PhysicalTableRequest.warmup pass copy node 0 r) + let mass := fun i r => (∑ j : Fin T, answer (PhysicalTableRequest.warmup pass copy + (physicalChild node hbelow i) j.val r)) / T + let childInitial := fun i r => answer (PhysicalTableRequest.warmup pass copy + (physicalChild node hbelow i) 0 r) + let current := fun i r => answer (PhysicalTableRequest.refinement pass copy + (physicalChild node hbelow i) T t r) + let children := fun i s r => if s < t then answer (PhysicalTableRequest.refinement pass copy + (physicalChild node hbelow i) T s r) else 0 + have hcard := computed_currentQueryInputCover_card source target N P hN hell + (physicalSourceInterval source.length node) A tau hA initial mass childInitial current draw q hw + (localOnlineCandidates source target (physicalSourceInterval source.length node) + N P (inputSmallLog N) (40 * smallLogExponent N) H tau (refinementFactor A (inputSmallLog N)) + eta kappa initial mass childInitial children (t - 1) integer q) + (localOnlineCandidates_length source target (physicalSourceInterval source.length node) + N P (inputSmallLog N) (40 * smallLogExponent N) H tau (refinementFactor A (inputSmallLog N)) + eta kappa initial mass childInitial children (t - 1) integer q) + have hread := physicalRefinementDataRequest_current_reads source target N P (inputSmallLog N) + (40 * smallLogExponent N) H (inputSmallLog N ^ 80) tau (refinementFactor A (inputSmallLog N)) + eta kappa delta pass copy T S t ht node hbelow draw integer q answer + apply hread.trans + convert Nat.mul_le_mul_left 2 hcard using 1 <;> first | rfl | exact Nat.mul_assoc _ _ _ + +theorem computed_physicalRefinement_earlier_reads {α : Type*} (source target : List α) + {M J : ℕ} (N P H : ℕ) (hN : 0 < N) (hell : 200 ≤ inputSmallLog N) + (hM : M = (integerParameters N).M) (hP : P = (integerParameters N).P) + (A tau eta kappa delta : ℚ) (hA : A ≤ ((integerParameters N).initialFactor : ℚ)) + (pass copy T S t : ℕ) (hT : T = (integerParameters N).T) + (ht : 0 < t) (htime : t ≤ (integerParameters N).S) + (node : PhysicalNode M J) (hbelow : node.1.val < J) + (draw : CellGroupDraws M (inputSmallLog N) (inputSmallLog N ^ 80)) + (integer : ℕ → TargetInterval target.length → ℕ) + (q : TargetInterval target.length) (answer : PhysicalTableRequest M J target.length → ℚ) + (hw : 0 ≤ answer (PhysicalTableRequest.warmup pass copy node 0 q)) : + (physicalRefinementDataRequestQuery source target N P (inputSmallLog N) + (40 * smallLogExponent N) H (inputSmallLog N ^ 80) tau + (refinementFactor A (inputSmallLog N)) eta kappa delta pass copy T S t ht node hbelow + draw integer q).cost (fun request => answer request.val) + (fun request => physicalEarlierReadWeight (T + t) request.val) ≤ + inputHeight N ^ (257 * (coarseExponent (inputSmallLog N) + 1)) := by + let initial := fun r => answer (PhysicalTableRequest.warmup pass copy node 0 r) + let B := inputHeight N ^ (256 * (coarseExponent (inputSmallLog N) + 1)) + have hdata := computed_data_support_budget (physicalSourceInterval source.length node) + N P T hN hell hM hP hT A hA initial q hw + have hcover : (queryEarlierInputCover (M := M) (physicalSourceInterval source.length node) + N P (inputSmallLog N) (40 * smallLogExponent N) t + (refinementFactor A (inputSmallLog N)) initial q).card ≤ B := by + subst M + exact computed_queryEarlierHistory_card (physicalSourceInterval source.length node) + N P t hN hell hP (by omega) A hA initial q hw + dsimp only [initial] at hdata hcover + have hread := physicalRefinementDataRequest_earlier_reads source target N P (inputSmallLog N) + (40 * smallLogExponent N) H (inputSmallLog N ^ 80) tau (refinementFactor A (inputSmallLog N)) + eta kappa delta pass copy T S t ht node hbelow draw integer q answer + dsimp only at hread + have hsum : (physicalRefinementDataRequestQuery source target N P (inputSmallLog N) + (40 * smallLogExponent N) H (inputSmallLog N ^ 80) tau + (refinementFactor A (inputSmallLog N)) eta kappa delta pass copy T S t ht node hbelow + draw integer q).cost (fun request => answer request.val) + (fun request => physicalEarlierReadWeight (T + t) request.val) ≤ 2 + 3 * B := by + omega + have hHeight : 64 ≤ inputHeight N := + (by omega : 64 ≤ inputSmallLog N).trans (computed_smallLog_le_height N) + have hB : 1 ≤ B := one_le_pow₀ (by omega) + have hfinal : 2 + 3 * B ≤ inputHeight N ^ (257 * (coarseExponent (inputSmallLog N) + 1)) := by + calc + _ ≤ 5 * B := by omega + _ ≤ inputHeight N * B := Nat.mul_le_mul_right B (by omega) + _ = inputHeight N ^ (1 + 256 * (coarseExponent (inputSmallLog N) + 1)) := by + dsimp only [B] + rw [pow_add, pow_one] + _ ≤ _ := pow_le_pow_right₀ (by omega) (by omega) + exact hsum.trans hfinal + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedRefinementWords.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedRefinementWords.lean new file mode 100644 index 0000000000000000000000000000000000000000..eebbd6ae4f31ffea7d3a61602370fe67684bee09 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedRefinementWords.lean @@ -0,0 +1,123 @@ +import OAI.Combinatorics.EditApproximation.Refinement.ComputedBinaryOnlineParameters +import OAI.Combinatorics.EditApproximation.Binary.BinaryRefinementParameters +import OAI.Combinatorics.EditApproximation.Binary.BinaryGroupSetup +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalSeedSchedule +import OAI.Combinatorics.EditApproximation.Geometry.ParameterLocalAsymptotics +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation + +/-- The scheduled integer refinement factor is materialized by its dyadic +exponent; the terminal pass materializes one. -/ + + +theorem scheduledRefinementWordWithWork_value (N pass : ℕ) + (hf : 3 ≤ smallLogExponent N) (hpass : pass ≤ computedSeedPassCount N) : + (scheduledRefinementWordWithWork N pass).1.value = + refinementFactor (scheduledSeedFactor N pass) (inputSmallLog N) := by + unfold scheduledRefinementWordWithWork + split_ifs with h + · simp only [BinaryFraction.signedPowerTwoWithWork_value, zpow_natCast] + rw [← scheduledSeedMultiplier_spec N pass hf h] + simp only [scheduledSeedMultiplier, Nat.cast_pow, Nat.cast_ofNat] + · have heq : pass = computedSeedPassCount N := by omega + rw [heq, scheduledSeedFactor_terminal_refinement N hf] + exact BinaryFraction.nat_value 1 + +theorem scheduledRefinementWordWithWork_bounds (N pass : ℕ) (hH : 64 ≤ inputHeight N) : + (scheduledRefinementWordWithWork N pass).1.width ≤ inputHeight N ^ 3 ∧ + (scheduledRefinementWordWithWork N pass).2 ≤ inputHeight N ^ 3 := by + let H := inputHeight N + change (scheduledRefinementWordWithWork N pass).1.width ≤ H ^ 3 ∧ + (scheduledRefinementWordWithWork N pass).2 ≤ H ^ 3 + have hp : coarseExponent (inputSmallLog N) ≤ H := + (coarseExponent_le_smallLog N).trans (computed_smallLog_le_height N) + have he : heightExponent N ≤ H := Nat.lt_two_pow_self.le + have hinitial : computedSeedInitialExponent N + 8 ≤ H ^ 3 := by + unfold computedSeedInitialExponent + have hm := Nat.mul_le_mul (Nat.add_le_add_right hp 4) he + change 64 ≤ H at hH + have hc : 3 * H ^ 2 ≤ H ^ 3 := by + calc + _ ≤ H * H ^ 2 := Nat.mul_le_mul_right (H ^ 2) (show 3 ≤ H by omega) + _ = _ := by ring + nlinarith only [hm, hH, hc] + unfold scheduledRefinementWordWithWork + split_ifs + · have he' : dyadicSeedExponent (smallLogExponent N) (computedSeedInitialExponent N) pass - + smallLogExponent N ≤ computedSeedInitialExponent N := + (Nat.sub_le _ _).trans (Nat.sub_le _ _) + have hw := BinaryFraction.signedPowerTwoWithWork_width + ((dyadicSeedExponent (smallLogExponent N) (computedSeedInitialExponent N) pass - smallLogExponent N : ℕ) : ℤ) + simp only [Int.natAbs_natCast] at hw + constructor + · exact hw.trans (by omega) + · simp only [BinaryFraction.signedPowerTwoWithWork, Int.natCast_nonneg, ite_true, Int.toNat_natCast] + omega + · have hw := BinaryFraction.nat_width_le 1 + have h3 : 3 ≤ H ^ 3 := (by omega : 3 ≤ H).trans (Nat.le_pow (by decide)) + exact ⟨hw.trans (by simpa only [Nat.size_one] using h3), h3⟩ + +/-- Width and range bounds for all five constructed scalar words. Tau and +kappa share the same reciprocal fourth-power word. -/ +theorem computedRefinementWords_bounds (N pass : ℕ) (word : List Bool) + (hvalue : bitWordValue word = inputSmallLog N) + (hwidth : word.length ≤ Nat.size (inputSmallLog N)) + (hH : 64 ≤ inputHeight N) (hpositive : 0 < bitWordValue word) : + let parameters := BinaryFraction.onlineParametersWithWork word hpositive + parameters.1.2.width ≤ inputHeight N ^ 8 ∧ + (scheduledRefinementWordWithWork N pass).1.width ≤ inputHeight N ^ 8 ∧ + parameters.1.1.width ≤ inputHeight N ^ 8 ∧ + (BinaryFraction.refinementDecrementWithWork word hpositive).1.width ≤ inputHeight N ^ 8 ∧ + |parameters.1.1.value| ≤ ((inputHeight N ^ 5 : ℕ) : ℚ) ∧ + 0 ≤ parameters.1.2.value ∧ parameters.1.2.value ≤ 1 := by + have hc := computedBinaryOnlineParameters_caps N word hvalue hwidth hH hpositive + have hword : word.length ≤ inputHeight N := hwidth.trans + ((Nat.size_le.mpr Nat.lt_two_pow_self).trans (computed_smallLog_le_height N)) + have hd := (BinaryFraction.refinementDecrementWithWork_cap word hpositive (inputHeight N) hH hword).1 + have ha := (scheduledRefinementWordWithWork_bounds N pass hH).1 + have h2 : inputHeight N ^ 2 ≤ inputHeight N ^ 8 := Nat.pow_le_pow_right (by omega) (by decide) + have h3 : inputHeight N ^ 3 ≤ inputHeight N ^ 8 := Nat.pow_le_pow_right (by omega) (by decide) + exact ⟨hc.2.1.trans h2, ha.trans h3, hc.1.trans h2, hd.trans h2, hc.2.2⟩ + + + +/-- Concrete construction of the scalar words consumed by the local kernel. -/ + + +theorem refinementParameterWordsWithWork_values (N pass : ℕ) (word : List Bool) + (hpositive : 0 < bitWordValue word) (hvalue : bitWordValue word = inputSmallLog N) + (hf : 3 ≤ smallLogExponent N) (hpass : pass ≤ computedSeedPassCount N) : + let values := (refinementParameterWordsWithWork N pass word hpositive).1 + values.tau.value = (rationalParameters (inputSmallLog N)).tau ∧ + values.factor.value = refinementFactor (scheduledSeedFactor N pass) (inputSmallLog N) ∧ + values.eta.value = (rationalParameters (inputSmallLog N)).eta ∧ + values.kappa.value = (rationalParameters (inputSmallLog N)).kappa ∧ + values.delta.value = (rationalParameters (inputSmallLog N)).delta := by + simp only [refinementParameterWordsWithWork, BinaryFraction.onlineParametersWithWork_kappa, + BinaryFraction.onlineParametersWithWork_eta, BinaryFraction.refinementDecrementWithWork_value, + scheduledRefinementWordWithWork_value N pass hf hpass, hvalue] + simp [rationalParameters] + +theorem refinementParameterWordsWithWork_cost (N pass : ℕ) (word : List Bool) + (hpositive : 0 < bitWordValue word) + (hwidth : word.length ≤ Nat.size (inputSmallLog N)) (hH : 64 ≤ inputHeight N) : + (refinementParameterWordsWithWork N pass word hpositive).2 ≤ inputHeight N ^ 9 := by + have ho := computedBinaryOnlineParameters_cost N word hwidth hH hpositive + have hf := (scheduledRefinementWordWithWork_bounds N pass hH).2 + have hw : word.length ≤ inputHeight N := hwidth.trans + ((Nat.size_le.mpr Nat.lt_two_pow_self).trans (computed_smallLog_le_height N)) + have hd := (BinaryFraction.refinementDecrementWithWork_cap word hpositive (inputHeight N) hH hw).2 + have hp : inputHeight N ^ 3 ≤ inputHeight N ^ 8 := Nat.pow_le_pow_right (by omega) (by decide) + have hunit : 1 ≤ inputHeight N ^ 8 := one_le_pow₀ (by omega) + have hmul := Nat.mul_le_mul_right (inputHeight N ^ 8) (show 8 ≤ inputHeight N by omega) + simp only [refinementParameterWordsWithWork] + rw [pow_succ] + nlinarith only [ho, hf, hd, hp, hunit, hmul] + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedRetainedValues.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedRetainedValues.lean new file mode 100644 index 0000000000000000000000000000000000000000..97c3809917a9f412b4d0b2c1ef34bae17881f5d4 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedRetainedValues.lean @@ -0,0 +1,124 @@ +import OAI.Combinatorics.EditApproximation.Refinement.ComputedPhysicalWork +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalLocalValueBits +import OAI.Combinatorics.EditApproximation.Refinement.ComputedCacheWords +import OAI.Combinatorics.EditApproximation.Geometry.RankedMemoStorage +import OAI.Combinatorics.EditApproximation.Numerics.RationalIntermediateBits + +namespace OAI + +namespace EditApproximation + +noncomputable def computedFamilyTableValue (source target : List ℕ) (N : ℕ) + (input : ComputedFamilyInput source target N) (key : ComputedFamilyTableKey source target N) : ℚ := + physicalFamilyRequestValue source target N (integerParameters N).P (inputSmallLog N) + (40 * smallLogExponent N) (inputHeight N) (inputSmallLog N ^ 80) (integerParameters N).T + (integerParameters N).S (computedSeedPassCount N) (inputHeight N ^ 2) + (scheduledSeedFactor N) (scheduledSeedMultiplier N) + (rationalParameters (inputSmallLog N)).tau (rationalParameters (inputSmallLog N)).eta + (rationalParameters (inputSmallLog N)).kappa (rationalParameters (inputSmallLog N)).delta + (clampedSeedNat input.1) (computedParameterP_pos N) input.2 key + +noncomputable def computedFamilyExpectedValue (source target : List ℕ) (N : ℕ) + (input : ComputedFamilyInput source target N) : + Sum (ComputedFamilyScalarKey source target N (inputHeight N ^ 2)) + (ComputedFamilyTableKey source target N) → ℚ := + Sum.elim (fun key => (input.2 key).val) (computedFamilyTableValue source target N input) + + theorem computedFamilyTableValue_bits (source target : List ℕ) (N : ℕ) + (hN : 0 < N) (hell : 200 ≤ inputSmallLog N) (hsize : source.length + target.length ≤ N) + (input : ComputedFamilyInput source target N) (key : ComputedFamilyTableKey source target N) : + rationalEncodingBits (computedFamilyTableValue source target N input key) ≤ inputHeight N ^ 3 := by + have hH : 64 ≤ inputHeight N := (by omega : 64 ≤ inputSmallLog N).trans + (computed_smallLog_le_height N) + have hJ : intervalTreeDepth (integerParameters N).M source.length ≤ inputHeight N := by + have h := computed_tree_depth_bound N source.length hN (by omega) hell + nlinarith only [h, hell] + apply (chargedRequestValue_encoding_bits source target N (integerParameters N).P + (inputSmallLog N) (40 * smallLogExponent N) (inputHeight N) (inputSmallLog N ^ 80) + (integerParameters N).T (integerParameters N).S (computedSeedPassCount N + 1) + (inputHeight N ^ 2) (inputSmallLog N) (scheduledSeedFactor N) (scheduledSeedMultiplier N) + _ _ _ _ _ _ (by omega) hsize (fun entry => Nat.le_of_lt_succ (input.1 entry).isLt) key).trans + exact computed_cacheWordBudget_le_cube N _ _ hH hJ (refinement_denominator_base_bits _) + + theorem computedFamilyExpectedValue_bits (source target : List ℕ) (N : ℕ) + (hN : 0 < N) (hell : 200 ≤ inputSmallLog N) (hsize : source.length + target.length ≤ N) + (hB : Nat.size (localOnlineMassBound (integerParameters N).M (integerParameters N).P + (inputHeight N)) ≤ inputHeight N) + (input : ComputedFamilyInput source target N) + (key : Sum (ComputedFamilyScalarKey source target N (inputHeight N ^ 2)) + (ComputedFamilyTableKey source target N)) : + rationalEncodingBits (computedFamilyExpectedValue source target N input key) ≤ inputHeight N ^ 3 := by + cases key with + | inl key => + change rationalEncodingBits ((input.2 key).val : ℚ) ≤ _ + rw [rationalEncodingBits_natCast] + have hr := computedFamilyRange_bits_le source target N (inputHeight N ^ 2) hB key + have hc : (input.2 key).val < 2 ^ inputHeight N := by + exact (input.2 key).isLt.trans_le + ((Nat.le_pow_clog (by decide : 1 < 2) _).trans + (Nat.pow_le_pow_right (by decide : 0 < 2) hr)) + have hs := Nat.size_le.mpr hc + have hH : 2 ≤ inputHeight N := (by omega : 2 ≤ inputSmallLog N).trans + (computed_smallLog_le_height N) + have hsquare : inputHeight N + 2 ≤ inputHeight N ^ 2 := by nlinarith only [hH] + have hh := hsquare.trans (pow_le_pow_right₀ (by omega : 1 ≤ inputHeight N) (by decide : 2 ≤ 3)) + omega + | inr key => exact computedFamilyTableValue_bits source target N hN hell hsize input key + + theorem computedFamilyResult_allValues (source target : List ℕ) (N : ℕ) + (hN : 0 < N) (hell : 2 ^ 1000 ≤ inputSmallLog N) (hsize : source.length + target.length ≤ N) + (hB : Nat.size (localOnlineMassBound (integerParameters N).M (integerParameters N).P + (inputHeight N)) ≤ inputHeight N) (input : ComputedFamilyInput source target N) : + BinaryMemo.AllValues (fun value => rationalEncodingBits value ≤ inputHeight N ^ 3) + (computedFamilyResult source target N input).memory := by + have hsmall : 200 ≤ inputSmallLog N := two_hundred_le_two_pow_thousand.trans hell + unfold computedFamilyResult physicalFamilyMemoResult chargedRandomMemoEvaluate + apply SourceRanked.memo_allValues (tableValue := computedFamilyTableValue source target N input) + · intro key + exact physicalFamilyProgram_value source target N (integerParameters N).P (inputSmallLog N) + (40 * smallLogExponent N) (inputHeight N) (inputSmallLog N ^ 80) + (integerParameters N).T (integerParameters N).S (computedSeedPassCount N) (inputHeight N ^ 2) + (scheduledSeedFactor N) (scheduledSeedMultiplier N) _ _ _ _ + (clampedSeedNat input.1) (computedParameterP_pos N) input.2 key + · exact computedFamilyMemoCode_injective source target N (inputHeight N ^ 2) hN hsmall + · exact computedFamilyMemoCode_fits source target N (inputHeight N ^ 2) hN hell hsize le_rfl hB + · exact computedFamilyExpectedValue_bits source target N hN hsmall hsize hB input + + theorem computed_height_polynomial (N : ℕ) : inputHeight N ≤ (N + 2) ^ 4 := by + have h4 : 4 ≤ (N + 2) ^ 2 := by nlinarith only [Nat.zero_le N] + calc + _ ≤ 2 ^ inputHeight N := Nat.lt_two_pow_self.le + _ ≤ 4 * (N + 2) ^ 2 := two_pow_inputHeight_le N + _ ≤ (N + 2) ^ 2 * (N + 2) ^ 2 := Nat.mul_le_mul_right _ h4 + _ = _ := by rw [← pow_add] + + theorem computedFamilyResult_retained_storage (source target : List ℕ) (N : ℕ) + (hN : 0 < N) (hell : 2 ^ 1000 ≤ inputSmallLog N) (hsize : source.length + target.length ≤ N) + (hB : Nat.size (localOnlineMassBound (integerParameters N).M (integerParameters N).P + (inputHeight N)) ≤ inputHeight N) (input : ComputedFamilyInput source target N) : + (computedFamilyResult source target N input).memory.rationalStorage ≤ (N + 2) ^ 65556 := by + have hvalues := computedFamilyResult_allValues source target N hN hell hsize hB input + have hs := BinaryMemo.rationalStorage_le _ (inputHeight N ^ 3) hvalues + have hn : (computedFamilyResult source target N input).memory.nodes ≤ (N + 2) ^ 65542 := + Nat.le_trans (Nat.le_succ _) (physicalFamilyMemo_nodes_polynomial source target N + (integerParameters N).P (integerParameters N).T (integerParameters N).S (inputHeight N) + (Nat.two_pow_pos _) (computedFamilyMemoCode source target N (inputHeight N ^ 2)) + (finalTargetState target.length) input) + have h4 : 4 ≤ (N + 2) ^ 2 := by nlinarith only [Nat.zero_le N] + have hh := Nat.pow_le_pow_left (computed_height_polynomial N) 3 + rw [← pow_mul] at hh + change inputHeight N ^ 3 ≤ (N + 2) ^ 12 at hh + have h12 : 1 ≤ (N + 2) ^ 12 := Nat.one_le_pow _ _ (by omega) + have hw : inputHeight N ^ 3 + 3 ≤ (N + 2) ^ 14 := by + calc + _ ≤ 4 * (N + 2) ^ 12 := by omega + _ ≤ (N + 2) ^ 2 * (N + 2) ^ 12 := Nat.mul_le_mul_right _ h4 + _ = _ := by rw [← pow_add] + calc + _ ≤ (inputHeight N ^ 3 + 3) * (computedFamilyResult source target N input).memory.nodes := hs + _ ≤ (N + 2) ^ 14 * (N + 2) ^ 65542 := Nat.mul_le_mul hw hn + _ = _ := by rw [← pow_add] + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedScalarCodeBits.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedScalarCodeBits.lean new file mode 100644 index 0000000000000000000000000000000000000000..42f2c9945557ca6d2d6abf629df1a80acca772e4 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedScalarCodeBits.lean @@ -0,0 +1,77 @@ +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalFamilyEncoding +import OAI.Combinatorics.EditApproximation.Refinement.ComputedSourceAddressBits +import OAI.Combinatorics.EditApproximation.Refinement.ComputedWarmupReadBudget +import OAI.Combinatorics.EditApproximation.Refinement.PhysicalRequestBits + +namespace OAI + +namespace EditApproximation + + theorem computed_physicalScalarCode_bound (N nx ny R : ℕ) + (hN : 0 < N) (hell : 200 ≤ inputSmallLog N) (hnx : nx ≤ N) (hny : ny ≤ N) + (hR : R ≤ inputHeight N ^ 2) + (hB : Nat.size (localOnlineMassBound (integerParameters N).M (integerParameters N).P + (inputHeight N)) ≤ inputHeight N) + (key : PhysicalScalarKey (integerParameters N).M + (intervalTreeDepth (integerParameters N).M nx) N ny (40 * smallLogExponent N) + (inputSmallLog N) (inputSmallLog N ^ 80) R + (localOnlineMassBound (integerParameters N).M (integerParameters N).P (inputHeight N))) : + physicalScalarCode key < 2 ^ (64 * (64 * inputHeight N) + 1) := by + let H := inputHeight N + let M := (integerParameters N).M + let J := intervalTreeDepth M nx + have hMH : M ≤ H := Nat.pow_le_pow_right (by decide) (Nat.div_le_self _ _) + have hMpos : 1 ≤ M := (by omega : 1 ≤ 2).trans (computed_branching_bounds N hN hell).1 + have hH : 64 ≤ H := (by omega : 64 ≤ inputSmallLog N).trans (computed_smallLog_le_height N) + have hlift (e : ℕ) (he : e ≤ 64 * H) : 2 ^ e ≤ 2 ^ (64 * H) := + Nat.pow_le_pow_right (by decide) he + have hHpow : H ^ 2 ≤ 2 ^ (2 * H) := by + calc + _ ≤ (2 ^ H) ^ 2 := Nat.pow_le_pow_left Nat.lt_two_pow_self.le 2 + _ = _ := by rw [← pow_mul]; congr 1; omega + have hentry : ∀ entry : PhysicalEntry M J ny, physicalEntryCode entry < 2 ^ (64 * H) := by + intro entry + exact ((physicalEntryCode_bound hMpos entry).trans_le + (computed_entryCapacity_bound N nx ny hN hell hnx hny)).trans_le (hlift (5 * H) (by omega)) + have hnode : ∀ node : PhysicalNode M J, physicalNodeCode node < 2 ^ (64 * H) := by + intro node + have hb : M ^ J * (J + 1) ≤ 2 ^ (5 * H) := by + simpa only [PhysicalTableRequest.entryCapacity, zero_add, one_pow, one_mul] using + computed_entryCapacity_bound N nx 0 hN hell hnx (Nat.zero_le N) + exact ((physicalNodeCode_bound hMpos node).trans_le hb).trans_le (hlift (5 * H) (by omega)) + have hsmall : smallLogExponent N ≤ H := + (Nat.lt_two_pow_self.le : smallLogExponent N ≤ 2 ^ smallLogExponent N).trans + (computed_smallLog_le_height N) + have hcell : ny * 2 ^ (40 * smallLogExponent N) + 1 ≤ 2 ^ (64 * H) := by + have hn : ny ≤ 2 ^ H := hny.trans ((Nat.le_add_right N 2).trans (inputHeight_covers_length N)) + have he : 2 ^ (40 * smallLogExponent N) ≤ 2 ^ (40 * H) := + Nat.pow_le_pow_right (by decide) (Nat.mul_le_mul_left 40 hsmall) + calc + _ ≤ 2 ^ H * 2 ^ (40 * H) + 1 := Nat.add_le_add_right (Nat.mul_le_mul hn he) 1 + _ = 2 ^ (41 * H) + 1 := by rw [← pow_add]; congr 2; omega + _ ≤ 2 ^ (41 * H) + 2 ^ (41 * H) := Nat.add_le_add_left Nat.one_le_two_pow _ + _ = 2 ^ (41 * H + 1) := by rw [pow_succ]; omega + _ ≤ _ := hlift _ (by omega) + apply physicalScalarCode_bound (64 * H) hnode hentry + · exact (computed_dyadicScales_length N (by omega)).trans (hHpow.trans (hlift _ (by omega))) + · exact hcell + · have hb := Nat.lt_size_self (localOnlineMassBound M (integerParameters N).P H) + exact (Nat.succ_le_of_lt hb).trans + ((Nat.pow_le_pow_right (by decide) hB).trans (hlift H (by omega))) + · exact hR.trans (hHpow.trans (hlift _ (by omega))) + · exact hMH.trans (Nat.lt_two_pow_self.le.trans (hlift H (by omega))) + · intro scale + have hs := List.get_mem (dyadicScales N) scale + obtain ⟨eb, _, heq⟩ := List.mem_map.mp hs + have hc : (groupDyadicScales M ((dyadicScales N).get scale) (inputSmallLog N)).length ≤ + 2 * inputSmallLog N := by + rw [← heq] + exact computed_group_scale_count N eb hN (by omega) + have htwo : 2 * inputSmallLog N ≤ 2 ^ (H + 1) := by + have hp := Nat.mul_le_mul_left 2 ((computed_smallLog_le_height N).trans Nat.lt_two_pow_self.le) + simpa only [pow_succ, Nat.mul_comm] using hp + exact hc.trans (htwo.trans (hlift _ (by omega))) + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedSeed.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedSeed.lean new file mode 100644 index 0000000000000000000000000000000000000000..0d05dfde0cc7545ff7c1715c3ab6d96b855964bc --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedSeed.lean @@ -0,0 +1,44 @@ +import OAI.Combinatorics.EditApproximation.Coarse.CoarseParameters + +namespace OAI + +/-! Initial-seed bounds with computed numerical parameters. -/ + +namespace EditApproximation + +open EditDistortion + +theorem computed_initialSeed_bounds {α : Type*} [DecidableEq α] + (N B D : ℕ) (x y : List α) + (hB : B = (integerParameters N).B) + (hD : D = computedCoarseDepth N (coarseEntryWidth x y)) + (hN : 0 < N) (hwidth : coarseEntryWidth x y ≤ N) + (hell : 200 ≤ inputSmallLog N) + (draws : CoarseGuessIndex (coarseEntryWidth x y) → CoarseThresholdDraws B D) + (hevent : CoarseInitialAccuracyEvent B D (initialThresholdQ N) (initialLambda N) x y draws) : + edit x y ≤ coarseInitialValue B D (initialThresholdQ N) (initialLambda N) N x y draws ∧ + coarseInitialValue B D (initialThresholdQ N) (initialLambda N) N x y draws ≤ + (integerParameters N).initialFactor * edit x y := by + have hH : (4 : ℚ) ≤ inputHeight N := by + exact_mod_cast (computed_coarse_branching N hN hell).1 + have hden : (0 : ℚ) < 64 * (inputHeight N : ℚ) := by linarith + have hlambda : initialLambda N < 1 := by + unfold initialLambda + exact (div_lt_one hden).2 (by linarith) + have hcapacity : coarseEntryWidth x y ≤ B ^ D := by + rw [hB, hD] + exact (computed_coarse_depth N _ hN hwidth hell).1 + have hfactor : coarseStructuralFactor (initialLambda N) D ≤ 2 := by + rw [hD] + exact computed_coarse_structuralFactor N _ hN hwidth hell + have hdistortion : 25 + 16 * B * D ≤ (integerParameters N).initialFactor := by + rw [hB, hD] + exact computed_coarse_distortion N _ hN hwidth hell + have hbounds := coarseInitialValue_bounds B D (initialThresholdQ N) (initialLambda N) + N x y draws hcapacity hwidth (pow_nonneg (Nat.cast_nonneg _) 4) + (div_nonneg zero_le_one hden.le) hlambda hfactor hevent + exact ⟨hbounds.1, hbounds.2.trans (Nat.mul_le_mul_right _ hdistortion)⟩ + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedSeedWords.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedSeedWords.lean new file mode 100644 index 0000000000000000000000000000000000000000..37b3674ec6d766cd472cc272422d250a4f681702 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedSeedWords.lean @@ -0,0 +1,44 @@ +import OAI.Combinatorics.EditApproximation.Refinement.ComputedRefinementWords +import OAI.Combinatorics.EditApproximation.Definitions + + +namespace OAI + +namespace EditApproximation + +/-- The actual dyadic incoming approximation factor used by a seed pass. -/ + + +theorem scheduledSeedWordWithWork_value (N pass : ℕ) : + (scheduledSeedWordWithWork N pass).1.value = scheduledSeedFactor N pass := by + simp only [scheduledSeedWordWithWork, BinaryFraction.signedPowerTwoWithWork_value, + zpow_natCast, scheduledSeedFactor] + +theorem scheduledSeedWordWithWork_bounds (N pass : ℕ) (hN : 0 < N) + (hell : 8 ≤ inputSmallLog N) (hH : 64 ≤ inputHeight N) : + (scheduledSeedWordWithWork N pass).1.width ≤ inputHeight N ^ 3 ∧ + (scheduledSeedWordWithWork N pass).2 ≤ inputHeight N ^ 3 := by + have he : dyadicSeedExponent (smallLogExponent N) (computedSeedInitialExponent N) pass ≤ + computedSeedInitialExponent N := Nat.sub_le _ _ + have hi := computed_window_le_height_cube N hN hell (by omega) + have hw := BinaryFraction.signedPowerTwoWithWork_width + ((dyadicSeedExponent (smallLogExponent N) (computedSeedInitialExponent N) pass : ℕ) : ℤ) + simp only [Int.natAbs_natCast] at hw + constructor + · exact hw.trans (by omega) + · simp only [scheduledSeedWordWithWork, BinaryFraction.signedPowerTwoWithWork, Int.natCast_nonneg, + ite_true, Int.toNat_natCast] + omega + +theorem scheduledSeedWordWithWork_range (N pass : ℕ) : + 1 ≤ (scheduledSeedWordWithWork N pass).1.value ∧ + (scheduledSeedWordWithWork N pass).1.value ≤ ((integerParameters N).initialFactor : ℚ) := by + rw [scheduledSeedWordWithWork_value] + constructor + · exact one_le_pow₀ (by norm_num : (1 : ℚ) ≤ 2) + · rw [← computedSeed_initial_factor] + exact pow_le_pow_right₀ (by norm_num : (1 : ℚ) ≤ 2) (Nat.sub_le _ _) + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedSourceAddressBits.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedSourceAddressBits.lean new file mode 100644 index 0000000000000000000000000000000000000000..2aec2b8be92d2aeda319bd3e451a812dd9040531 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedSourceAddressBits.lean @@ -0,0 +1,62 @@ +import OAI.Combinatorics.EditApproximation.Refinement.ComputedNumericalParameters +import OAI.Combinatorics.EditApproximation.Geometry.ParameterLocalAsymptotics + +namespace OAI + +/-! The actual uniform source-range address fits in one logarithmic input +word eventually. The coefficient can be any fixed natural number. -/ + +namespace EditApproximation + +open Filter +open scoped Topology + +theorem computed_sourceAddressBits_div_height_tendsto (C : ℕ) : + Tendsto (fun N => + ((C * (coarseExponent (inputSmallLog N) + 1) * Nat.size (inputHeight N) + 1 : ℕ) : ℝ) / + inputHeight N) atTop (𝓝 0) := by + have hupper := (smallLog_polynomial_div_height_tendsto 2).const_mul (4 * (C : ℝ) + 1) + simp only [mul_zero] at hupper + apply squeeze_zero' (Eventually.of_forall fun N => div_nonneg (Nat.cast_nonneg _) (Nat.cast_nonneg _)) _ hupper + filter_upwards [eventually_ge_atTop 1] with N hN + have he := (inputSmallLog_bounds N hN).1 + have hp := coarseExponent_le_smallLog N + have hell : 1 ≤ inputSmallLog N := Nat.one_le_two_pow + have hs : Nat.size (inputHeight N) = heightExponent N + 1 := by + simp only [inputHeight, Nat.size_pow] + have hsmall : (1 : ℝ) ≤ inputSmallLog N := by exact_mod_cast hell + have hpR : (coarseExponent (inputSmallLog N) : ℝ) + 1 ≤ 2 * inputSmallLog N := by + exact_mod_cast (show coarseExponent (inputSmallLog N) + 1 ≤ 2 * inputSmallLog N by omega) + have hsR : (Nat.size (inputHeight N) : ℝ) ≤ 2 * inputSmallLog N := by + exact_mod_cast (show Nat.size (inputHeight N) ≤ 2 * inputSmallLog N by omega) + have hproduct := mul_le_mul hpR hsR (Nat.cast_nonneg _) (by positivity : (0 : ℝ) ≤ 2 * inputSmallLog N) + have hscaled := mul_le_mul_of_nonneg_left hproduct (Nat.cast_nonneg C : (0 : ℝ) ≤ C) + have hnum : ((C * (coarseExponent (inputSmallLog N) + 1) * Nat.size (inputHeight N) + 1 : ℕ) : ℝ) ≤ + (4 * (C : ℝ) + 1) * (inputSmallLog N : ℝ) ^ 2 := by + push_cast + nlinarith only [hscaled, hsmall, sq_nonneg ((inputSmallLog N : ℝ) - 1)] + have h := div_le_div_of_nonneg_right hnum (Nat.cast_nonneg (inputHeight N) : (0 : ℝ) ≤ inputHeight N) + simpa only [mul_div_assoc] using h + +theorem computed_sourceAddressBits_le_height (C : ℕ) : + ∀ᶠ N in atTop, + C * (coarseExponent (inputSmallLog N) + 1) * Nat.size (inputHeight N) + 1 ≤ inputHeight N := by + filter_upwards [(computed_sourceAddressBits_div_height_tendsto C).eventually + (eventually_lt_nhds (by norm_num : (0 : ℝ) < 1))] with N h + have hH : (0 : ℝ) < inputHeight N := by + exact_mod_cast Nat.two_pow_pos (heightExponent N) + have hlt := (div_lt_one hH).mp h + exact_mod_cast hlt.le + +theorem computed_localOnlineMassBound_word : + ∀ᶠ N in atTop, + Nat.size (localOnlineMassBound (integerParameters N).M (integerParameters N).P (inputHeight N)) ≤ + inputHeight N := by + filter_upwards [computed_sourceAddressBits_le_height 8000, + inputHeight_real_tendsto.eventually (eventually_ge_atTop 64)] with N hbits hH + have hHnat : 64 ≤ inputHeight N := by exact_mod_cast hH + exact (computed_localOnlineMassBound_bits N hHnat).trans hbits + +end EditApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedSourceReadBudget.lean b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedSourceReadBudget.lean new file mode 100644 index 0000000000000000000000000000000000000000..87e0134dba994362537466ffcd2c70ce42fdba02 --- /dev/null +++ b/lean/OAI/Combinatorics/EditApproximation/Refinement/ComputedSourceReadBudget.lean @@ -0,0 +1,66 @@ +import OAI.Combinatorics.EditApproximation.Geometry.LocalRandomSourceQuery +import OAI.Combinatorics.EditApproximation.Refinement.ComputedEarlierInputBudget +import OAI.Combinatorics.EditApproximation.Refinement.ComputedGroupNumerical + +namespace OAI + +/-! Fixed-degree source-read bounds for a refinement entry. These hold on +all stored initial values, including outcomes outside accuracy events. -/ + +namespace EditApproximation + + theorem computed_source_key_budget {n M : ℕ} (N P : ℕ) + (hN : 0 < N) (hell : 200 ≤ inputSmallLog N) (hM : M = (integerParameters N).M) + (A : ℚ) (hA : A ≤ ((integerParameters N).initialFactor : ℚ)) + (initial : TargetInterval n → ℚ) (q : TargetInterval n) (hw : 0 ≤ initial q) : + (groupScalarKeys M (inputSmallLog N) (inputSmallLog N ^ 80) + (localGroupQueryKeys N (inputSmallLog N) (40 * smallLogExponent N) + (refinementFactor A (inputSmallLog N)) initial q)).length + + (localOnlineSourceKeys N P (inputSmallLog N) + (refinementFactor A (inputSmallLog N)) initial q).length ≤ inputHeight N ^ 91 := by + let H := inputHeight N + let ell := inputSmallLog N + have hF : ell ≤ H := computed_smallLog_le_height N + have hH : 64 ≤ H := (by omega : 64 ≤ ell).trans hF + have hMbound : M ≤ H := by + rw [hM] + exact pow_le_pow_right₀ (by decide : (1 : ℕ) ≤ 2) (Nat.div_le_self _ _) + have hW : (dyadicQueryWindow N (initial q) (refinementFactor A ell) ell).length ≤ H ^ 3 := + (computed_refinement_window N hN (by omega) A (initial q) hA).trans + (computed_window_le_height_cube N hN (by omega) (by omega)) + have hkeys : (localGroupQueryKeys N ell (40 * smallLogExponent N) + (refinementFactor A ell) initial q).length ≤ H ^ 87 := by + calc + _ ≤ (dyadicQueryWindow N (initial q) (refinementFactor A ell) ell).length * + ((32 * ell + 2) * 2 ^ (40 * smallLogExponent N) + 2) ^ 2 := + localGroupQueryKeys_length N ell (40 * smallLogExponent N) + (refinementFactor A ell) initial q (by omega) hw + _ ≤ H ^ 3 * H ^ 84 := Nat.mul_le_mul hW (computed_cell_budget_le_height_pow N hH) + _ = H ^ 87 := by rw [← pow_add] + have hlabels : ∀ key ∈ localGroupQueryKeys N ell (40 * smallLogExponent N) + (refinementFactor A ell) initial q, (groupDyadicScales M key.1 ell).length ≤ 2 * ell := by + intro key hk + have hb := localGroupQueryKeys_scale hk + obtain ⟨eb, _, heq⟩ := List.mem_map.mp hb + rw [hM, ← heq] + exact computed_group_scale_count N eb hN (by omega) + have hgroup : (groupScalarKeys M ell (ell ^ 80) (localGroupQueryKeys N ell + (40 * smallLogExponent N) (refinementFactor A ell) initial q)).length ≤ H ^ 90 := by + calc + _ ≤ (localGroupQueryKeys N ell (40 * smallLogExponent N) + (refinementFactor A ell) initial q).length * (2 * ell) * M := + groupScalarKeys_length_le M ell (ell ^ 80) (2 * ell) _ hlabels + _ ≤ H ^ 87 * (H * H) * H := Nat.mul_le_mul + (Nat.mul_le_mul hkeys (Nat.mul_le_mul (by omega) hF)) hMbound + _ = H ^ 90 := by ring + simp only [localOnlineSourceKeys, List.length_map] + have hsmall : H ^ 3 ≤ H ^ 90 := pow_le_pow_right₀ (by omega) (by omega) + calc + _ ≤ H ^ 90 + H ^ 90 := Nat.add_le_add hgroup (hW.trans hsmall) + _ = H ^ 90 * 2 := by omega + _ ≤ H ^ 90 * H := Nat.mul_le_mul_left _ (by omega) + _ = H ^ 91 := (pow_succ H 90).symm + +end EditApproximation + +end OAI